Variational autoencoders: reparameterization, posterior collapse, β-VAE and VQ-VAE
Before this lesson: lesson 01 (the ELBO, its gap and amortized inference). Gradient estimators in detail: calculus, lesson 12. The rate–distortion view: information theory, lesson 10. The multivariate Gaussian density (the probability and statistics track) and backpropagation (deep learning, lesson 03). Time: about 95 minutes, plus the notebook.
Why this matters #
A VAE is the latent variable model of lesson 01 with a neural network in each direction, trained by stochastic gradient descent on the ELBO. Three choices make it work: the reparameterization trick (low-variance gradients through a random sample), the closed-form Gaussian KL, and the decoder likelihood, which sets the balance between the two loss terms. A wrong balance gives the classic failures: blurry samples and posterior collapse.
Today VAEs are used mostly as the first stage of larger generators. Stable Diffusion runs diffusion in the latent space of a KL-regularized autoencoder (lesson 13). VQGAN and neural audio codecs turn images and sound into discrete tokens for transformers. In science, LDCast (Leinonen et al., 2023) runs precipitation nowcasting in an autoencoder's latent space, and latent diffusion models of seismic ground motion do the same. A rule to remember: the second stage can only generate what the first-stage decoder can produce, so check the autoencoder first.
1. Predict first #
2. The picture #
The parts of a VAE #
- Encoder : a network with parameters maps to two vectors, the mean and the log-variance , for a latent .
- Decoder : a network with parameters maps to the parameters of a distribution over , for example a mean .
- Prior .
The loss for one data point is minus the ELBO of lesson 01, written as two terms:
The blobs tile the prior. Each data point gets a Gaussian blob in latent space. The rate pulls every blob toward : mean to 0, width to 1. The distortion pushes blobs apart and makes them narrow, so that identifies . At the balance, the blobs tile the prior. If the rate wins completely, every blob equals the prior and says nothing about : posterior collapse.
The figure shows this balance exactly, for a VAE whose encoder and decoder are linear. For this model section 3 derives the optimum in closed form, so there is no training and no noise.
Move β (or press the "Try" buttons) and watch the blobs. Right: the data (blue), a 2D Gaussian cloud with variances and along two directions, and eight chosen points (yellow). Left: the latent space with the prior (aqua circles at 1 and 2 standard deviations) and the encoder blob of each chosen point (orange). At both latent directions are used. At the threshold exceeds : the second direction collapses, every blob becomes as wide as the prior in , and the model (orange dashed) keeps only the first direction. At both collapse.
The reparameterization trick #
The loss contains , an average over a random sample whose distribution depends on . We cannot backpropagate through "draw a random number". The trick moves the randomness to a fixed input:
where is the elementwise product. Now is a deterministic, differentiable function of and , and the noise does not depend on . So the gradient flows from the decoder through into the encoder. The result is the pathwise gradient estimator. The older alternative, the score-function (REINFORCE) estimator, uses only values of the loss. The figure compares them on a 1D problem: estimate .
Compare the two histograms, then change . Each histogram shows 500 independent gradient estimates; each estimate averages samples. The pathwise estimator averages ; the score-function estimator averages . Both are centred on the exact gradient (dark line). For at the per-sample variances are 4 and 87. For the order flips. For the step function the pathwise estimate is always 0 and wrong: has no useful slope.
An encoder outputs and for a 1D latent. What is ?
In 1D, . Equal variances remove only the variance part; the mean still costs .
3. Definitions and main results #
The Gaussian VAE objective #
For one data point , with noise samples and :
It is an unbiased estimate of the ELBO, and its gradient is an unbiased estimate of the ELBO's gradient in both and . is standard; the minibatch averages the noise. The encoder outputs , an unconstrained number, and is positive by construction. The KL is computed exactly (Theorem 1), not by sampling, which removes one source of noise.
Theorem 1: the KL divergence between two Gaussians #
Simplest case. In 1D, .
General case. For Gaussians on ,
For the VAE (, , , ): .
Proof of Theorem 1
- .
- Write for the expectation under . Then .
- Trace trick. For with mean and covariance , any matrix and vector : write . The cross term has mean 0, and . So .
- With , : the last expectation in step 2 is . With , : the middle one is .
- Collect the terms: this is the general formula.
- VAE case: , the quadratic term is , and .
Each dimension costs . Since , with equality only at , a dimension is free only when and . A variance above 1 costs nats too, not only a variance below 1.
Pathwise and score-function gradients #
We need , with . Two unbiased estimators exist:
- Score function (REINFORCE, also called the likelihood-ratio estimator): . It needs only samples of , values of , and .
- Pathwise (reparameterized): with , for example , . It needs to be differentiable in and a differentiable sampling path.
Why both are unbiased
- Score function: , because . The last integral is .
- Pathwise: , and the distribution of does not depend on . So the gradient can move inside the expectation (for smooth enough ), and the chain rule gives .
Why pathwise is usually better. The pathwise estimator uses the slope of . The score-function estimator uses only values of , multiplied by a random factor with mean 0. Add a constant to : the mean of the score-function estimator does not change (because ), but its variance grows like times the Fisher information. The noise also grows with the dimension of . A VAE's is a sum over thousands of pixels with a large magnitude, so the score-function estimate would be very noisy. Example (the figure): for and , the gradient in is 4, and the per-sample variance is 4 (pathwise) against 87 (score function). "Usually", not always: for a fast-changing such as , the pathwise variance grows like , and the score function can win (variance about 4.5 against 0.5 for ).
When the pathwise estimator is not available.
- Discrete : there is no differentiable path from noise to a sample. Use the score function with a baseline, a continuous relaxation (Gumbel-softmax, biased), or the straight-through estimator (biased; VQ-VAE below).
- not differentiable in , for example a step function or a black-box simulator. Then almost everywhere and the "pathwise" average is wrong, as in the figure.
- Distributions without a simple sampling path (Gamma, Beta, Dirichlet): these need implicit reparameterization.
Your model has a Bernoulli latent variable with . Which gradient estimator gives an unbiased estimate of ?
The score-function estimator needs only samples, values of and , so it is unbiased for discrete (a baseline reduces its variance). The map is a step: its derivative in is 0 almost everywhere, so the "pathwise" gradient is always 0 and biased. Straight-through is a useful but biased approximation.
The decoder variance and "MSE + β·KL" #
Take a Gaussian decoder for ( pixels or features):
Proposition 2 (a fixed variance is a weight). Multiply by : . So minimizing "summed squared error " is the same as maximizing the ELBO of a Gaussian decoder with
The weight says how noisy the model believes the data are. A large makes it cheap to give up reconstruction (toward collapse). A small makes reconstruction dominate (toward a plain autoencoder with an irregular latent space).
Proposition 3 (a learned variance). If one scalar is learned with the rest, its optimum is the mean squared error per dimension, . Proof. Set the derivative in to zero: . At the optimum the distortion is : logarithmic in the MSE. In effect , which shrinks as the reconstructions improve. A decoder that outputs a variance per pixel does the same per dimension.
Blurriness. For squared error, the best decoder mean at is the average of all inputs that the encoder maps near . An average of several images is blurry. Papers usually show the decoder mean ; adding the decoder noise (noise) would give grainy images instead.
A paper trains a VAE with "summed squared error over pixels ". Which Gaussian decoder does this loss assume?
By Proposition 2, "sum of squared errors " is times minus the ELBO (plus a constant) when . With : . A weight on the KL is the same as a fixed decoder variance.
Posterior collapse #
Definition. Posterior collapse: for every , in some or all latent dimensions. The decoder ignores those dimensions, and their KL is about 0.
Proposition 4 (collapse can be optimal). Suppose some decoder ignores and still fits the data: for every . Then gives a global maximum of the expected ELBO.
Proof of Proposition 4
- The decoder ignores , so and are independent under the model, and the true posterior equals the prior.
- So has zero gap (lesson 01, Theorem 1), and .
- For any model, ; the second inequality is Gibbs' inequality. Step 2 reaches this ceiling.
Information in costs rate; the model pays it only when the reconstruction gain is larger. Autoregressive decoders (PixelCNN, LSTM or transformer text decoders) can model alone, so they often collapse (Bowman et al., 2016, for text).
A linear example: collapse without a powerful decoder (Lucas, Tucker, Grosse and Norouzi, Don't Blame the ELBO!, 2019). Data in 1D; decoder with a fixed ; prior ; encoder . Train with weight on the KL ( is the ELBO). Then the optimum is
So the direction is active iff . If , collapse is the global optimum: the decoder noise already explains all the data variance, and there is no powerful decoder at all.
Derivation of the linear optimum
- Expected distortion: , so .
- Expected rate (Theorem 1): .
- The objective is . Write . Setting gives ; setting gives .
- Put these back, with : .
- : positive for , negative after. So if , else .
- At an active optimum, and , so the rate is .
In more dimensions (probabilistic PCA with data variances along the principal directions), each direction is treated separately: direction is active iff . This is the figure in section 2. So partial collapse is not always a bug: it can be the model choosing its latent dimension.
When collapse happens. (i) Strong decoders that model without . (ii) A large , or a large fixed decoder variance (as in the linear example, and in question 1 of section 1). (iii) Early training: while the decoder is weak, is an attractive state, and the encoder lags behind (He et al., 2019).
How to detect it. Log the KL per latent dimension, ; a value near 0 marks a collapsed dimension. Count active units: dimension is active if (Burda et al., 2016). Check that decoded outputs change when you change . Report rate and distortion separately, not only their sum.
Fixes. KL annealing: raise the KL weight from 0 to 1 during training (also cyclical schedules). Free bits (Kingma et al., 2016): replace by , with averaged over the minibatch, so the first nats per dimension are free. Learn the decoder variance, so that can drop below the data variance. Weaken the decoder, or add skip connections from to every decoder layer. More encoder updates per decoder update (He et al., 2019) help only when the encoder lags behind (cause iii), not when collapse is the optimum.
The β-VAE: the rate–distortion view #
Average over the data: distortion and rate . Then . The β-VAE (Higgins et al., 2017) minimizes
- : lower rate, more distortion; more compressed and often more factorized codes, blurrier reconstructions. Since , : still a bound, but looser.
- : more information in , sharper reconstructions, a weaker match between the codes and the prior. is in general not a bound on .
- The rate bounds the information that carries about : (information theory, lesson 10).
Predicting the choice. Each trained model is a point . The objective picks the point that a line of slope touches first when it moves up from below. So the winner always lies on the lower convex hull of the points. Two models , with tie at ; above the lower-rate model wins.
Move β, or press "Sweep β". The magenta curve is the set of optimal (rate, distortion) points of the linear VAE of section 2, one for each β. The orange point is the optimum for the current β, and the dashed line through it has slope : the line $D + \beta R = $ const touches the curve there. The yellow ring is , the ordinary ELBO. Large β slides the point to rate 0: both directions collapse (at , here 2 and 6).
You raise β from 1 to 4 in a β-VAE and retrain. What happens to the rate and the distortion at the new optimum?
β is the price of one nat of rate. A higher price moves the optimum along the rate–distortion curve to lower rate and higher distortion; in the linear VAE, directions with collapse. β is not a global rescaling: it changes the relative weight of the two terms. And with is a looser bound, not a tighter one.
VQ-VAE #
A VQ-VAE (vector-quantized VAE; van den Oord, Vinyals and Kavukcuoglu, 2017) uses a discrete latent: a list of vectors instead of a Gaussian blob.
- Codebook. vectors . The encoder outputs (one per spatial position in practice).
- Quantization. and : the nearest code. So is one-hot. With a uniform prior over the codes, the KL term is the constant and is dropped.
- Loss (with = stop-gradient: the identity in the forward pass, zero gradient in the backward pass):
with in the paper (results were similar for to ). This is not the β of the β-VAE.
- Straight-through gradient. In the forward pass, the decoder sees . In the backward pass, is copied unchanged to , as if quantization were the identity. In code: .
- Who trains what. The decoder: the reconstruction term. The encoder: reconstruction (through the straight-through copy) and the commitment term, which keeps close to its code so that encoder outputs do not drift or grow. The codebook: only the codebook term, which moves toward the encoder outputs assigned to it (often replaced by moving averages: an online k-means).
- Generation. The prior is uniform during training. Afterwards, an autoregressive model (PixelCNN, a transformer; lesson 03) is fitted on the code indices, sampled, and decoded.
- Codebook collapse. Often only a few codes are used. An unused code is never the argmin, so it gets no gradient and stays dead. The usage (the fraction of positions that pick code ) gives the perplexity , the effective number of codes. Fixes: initialize codes from encoder outputs (k-means), moving-average updates, reset dead codes to recent encoder outputs, low-dimensional -normalized codes, or finite scalar quantization (FSQ; Mentzer et al., 2023), which rounds a few dimensions to a fixed grid and has no learned codebook to collapse.
Press "Codebook step" a few times, then "Reset dead codes". The blue points are encoder outputs (the track's 8-Gaussians data); the orange dots are the codes, and the thin lines are the Voronoi cells: every is replaced by the code of its cell. From the bad start in the corner, one code wins every point; the others (magenta) get no gradient and never move. Resetting dead codes to random encoder outputs brings them back. Then try "codes from data": every code is used, but two codes can share one cluster. The violet arrows are the commitment pull on .
In the VQ-VAE loss, which term changes the codebook vectors ?
The straight-through copy sends the reconstruction gradient to , not to . The commitment term has on , so it trains only the encoder. Only the codebook term has a gradient in : , which moves the code toward its encoder outputs. A code that is never the argmin gets no gradient at all.
Why autoencoders are the first stage. An autoencoder trained with reconstruction, perceptual and adversarial losses (VQGAN; Esser et al., 2021) removes detail that the eye does not see and keeps a small, dense latent. In the Stable Diffusion autoencoder, a image (196,608 numbers) becomes a latent (4,096 numbers, 48 times fewer), and the KL weight is only about (lesson 13). The diffusion model or the transformer then spends its capacity on content, and the cost of attention falls with the number of tokens. Discrete codes serve token models (VQGAN + transformer, residual VQ in audio codecs); continuous, weakly regularized latents serve diffusion.
Answers to section 1. (1) Several hundred. Multiply the loss by : it becomes summed squared error . So and, by Proposition 2, ( for pixels in ). The model believes that the pixels are almost pure noise, so ignoring is cheap: collapse and a blurry average image. Fix: sum the squared error over pixels () or learn . (2) Straight-through: the encoder receives as if quantization were the identity, plus the gradient of the commitment term.
4. Worked example #
(a) Gaussian KL. The encoder outputs and , so .
- Dimension 1: .
- Dimension 2: .
- Total: nats. Dimension 1 pays for its mean, dimension 2 for a variance below 1.
(b) One reparameterized sample. With : . The local derivatives are and, since , . Backpropagation multiplies by these numbers.
(c) The decoder variance.
- Summed squared error KL: , so .
- Summed squared error KL: ().
- Mean squared error over pixels KL: , .
- A learned scalar variance with a per-pixel MSE of : .
(d) Collapse in the linear VAE. Data variance , .
- : , so ; rate nats. The encoder family contains the exact posterior, so the ELBO equals the log-likelihood of : .
- : , so and the rate is 0 (collapse). The model is , and ELBO log-likelihood .
(e) Which model does the β-VAE prefer? Three trained models, in nats:
| model | |||||
|---|---|---|---|---|---|
| A | 2 | 60 | 60.4 | 62 | 64 |
| B | 10 | 50 | 52.0 | 60 | 70 |
| C | 25 | 44 | 49.0 | 69 | 94 |
Ties: A and B at ; B and C at . So C wins for , B for (this includes the ELBO, ), and A for .
(f) One VQ step. Codebook , , ; encoder output .
- Squared distances: , , . So and .
- Codebook term: (summed over the 2 entries); commitment term: .
- Gradients: the codebook term gives , so a descent step moves toward . The commitment term gives , which pulls toward . The reconstruction gradient at is added to unchanged. and get no gradient.
5. In code #
NumPy and SciPy check the numbers of section 4 by other routes: Monte Carlo for the KL, per-sample gradient estimates, a numerical optimizer for the linear VAE, and SciPy's vector quantizer.
import numpy as np
from scipy.stats import norm
from scipy.optimize import minimize
from scipy.cluster.vq import vq
# (a) Closed-form KL(N(mu, diag s^2) || N(0, I)) vs a Monte Carlo estimate
mu, s = np.array([2.0, 0.0]), np.array([1.0, 0.5])
kl = 0.5 * (mu**2 + s**2 - 1 - np.log(s**2))
rng = np.random.default_rng(0)
z = mu + s * rng.normal(size=(1_000_000, 2)) # reparameterized samples
mc = (norm.logpdf(z, mu, s) - norm.logpdf(z, 0, 1)).mean(0)
print(kl.round(4), kl.sum().round(4), mc.round(3))
# [2. 0.3181] 2.3181 [2.004 0.318]
# (b) Two unbiased per-sample estimates of d/dmu E[z^2], z ~ N(2, 1); the true value is 4
eps = rng.normal(size=1_000_000)
pathwise = 2 * (2.0 + eps) # f'(mu + eps)
score = (2.0 + eps) ** 2 * eps # f(z) * d/dmu log q(z) = f(z) (z - mu)
print(f"{pathwise.mean():.2f} {pathwise.var():.1f} | {score.mean():.2f} {score.var():.0f}")
# 4.00 4.0 | 3.99 86 (exact variances: 4 and 87)
# (c) Linear VAE: x ~ N(0, lam), decoder N(w z, s2) with s2 fixed, encoder N(a x, v).
# The expected ELBO in closed form, maximized over (w, a, log v).
def elbo_and_rate(params, lam, s2):
w, a, logv = params
v = np.exp(logv)
recon = -0.5 * np.log(2 * np.pi * s2) - (lam * (1 - w * a) ** 2 + w**2 * v) / (2 * s2)
rate = 0.5 * (a**2 * lam + v - 1 - logv)
return recon - rate, rate
lam = 1.0
for s2 in (0.25, 1.5):
res = minimize(lambda p: -elbo_and_rate(p, lam, s2)[0], x0=[0.5, 0.5, 0.0])
elbo, rate = elbo_and_rate(res.x, lam, s2)
var_x = res.x[0] ** 2 + s2 # model marginal: x ~ N(0, w^2 + s2)
loglik = -0.5 * np.log(2 * np.pi * var_x) - lam / (2 * var_x)
print(s2, f"|w| = {abs(res.x[0]):.3f} rate = {rate:.3f} ELBO = {elbo:.4f} log-lik = {loglik:.4f}")
# 0.25 |w| = 0.866 rate = 0.693 ELBO = -1.4189 log-lik = -1.4189
# 1.5 |w| = 0.000 rate = 0.000 ELBO = -1.4550 log-lik = -1.4550 (collapse is optimal)
# (d) Which (rate, distortion) model does D + beta R prefer?
R = np.array([2.0, 10.0, 25.0]); D = np.array([60.0, 50.0, 44.0])
for beta in (0.2, 1.0, 2.0):
print(beta, D + beta * R, "ABC"[np.argmin(D + beta * R)])
# 0.2 [60.4 52. 49. ] C | 1.0 [62. 60. 69.] B | 2.0 [64. 70. 94.] A
# (e) Nearest code of the VQ example (SciPy's vector quantization)
codebook = np.array([[0.0, 0.0], [2.0, 0.0], [0.0, 2.0]])
print(vq(np.array([[1.5, 0.4]]), codebook))
# (array([1], dtype=int32), array([0.64031242])): index 1 is e_2 (0-based), distance^2 = 0.41
The score-function variance is itself a noisy estimate with heavy tails: with samples it lands
near 87, not exactly on it. In PyTorch, torch.distributions.Normal(mu, sigma).rsample() gives the
reparameterized sample and .sample() gives a sample with no gradient path.
6. Where it shows up #
- Latent diffusion (lesson 13). The Stable Diffusion autoencoder adds perceptual (LPIPS) and patch-adversarial losses to a very small KL term. In LDCast (precipitation) and in latent models of seismic ground motion, check that the autoencoder reconstructs the quantities you will evaluate (extremes, spectra, peak values) before you train the diffusion stage.
- Token-based generators. VQGAN codes plus a transformer or a masked model; DALL·E 1 used a discrete VAE trained with a Gumbel-softmax relaxation; audio codecs (SoundStream, EnCodec) use residual VQ under speech and music language models.
- Representation learning. β-VAE and its variants are used to learn more factorized ("disentangled") codes; the linear analysis shows that β also decides how many directions survive.
- Training logs. Plot rate, distortion, per-dimension KL and active units. A rate near 0 with a good-looking loss is collapse, not success.
7. Common mistakes #
- Mean-reduced reconstruction with a summed KL. This is a silent , the number of pixels; see question 1 of section 1.
- An encoder that outputs with no positivity constraint. Output (and clamp it in practice) to avoid NaNs.
- Binary cross-entropy on non-binary pixels. For it is not a normalized likelihood, so the "ELBO" is not a bound on a real and cannot be compared with other models.
- Reading a small KL as good regularization. Check the active units first.
- Wrong stop-gradients in VQ. Writing gives the encoder no reconstruction gradient; dropping in the codebook term lets it train the encoder too.
- Reporting a objective as a likelihood bound. Only guarantees a bound.
- Using the pathwise gradient through a discrete or non-differentiable step. The gradient is 0 almost everywhere, so the estimate is silently wrong.
8. Check yourself #
- The encoder outputs and . Compute the KL to .
Answer
Dimension 1: 0. Dimension 2: . Dimension 3: . Total nats. - A paper minimizes (summed) . Which decoder does this assume?
Answer
A Gaussian decoder with fixed variance (), by Proposition 2. - Why can the reparameterization trick not be used for a categorical latent? Name two alternatives.
Answer
There is no differentiable map from fixed noise to a discrete sample: the sample changes in jumps, and its derivative with respect to the class probabilities is 0 almost everywhere. Alternatives: the score-function estimator with a baseline; a Gumbel-softmax relaxation; the straight-through estimator. - Linear VAE with data variance , fixed decoder variance and : give
and the rate. What changes for ?
Answer
, ; rate nats. For : and the rate is 0; posterior collapse is the optimum. - Models P (, ) and Q (, ). Which wins for , for , and
where do they tie?
Answer
: P gives 34, Q gives 36, so P. : P gives 32, Q gives 30, so Q. Tie at . - A VQ-VAE has 512 codes; after training, 40 codes are used, about equally often. What is the
effective number of bits per position, why do the other 472 codes not recover, and what would you do?
Answer
About bits instead of . A dead code is never the nearest code, so the codebook term never updates it. Reset dead codes to recent encoder outputs, initialize with k-means, use moving-average updates or normalized low-dimensional codes, or switch to FSQ.
Give in 1D.
. It is 0 only for , .
Write the reparameterization trick for a diagonal Gaussian encoder.
, . The noise no longer depends on , so gradients flow through .
Write the score-function (REINFORCE) gradient estimator.
.
Why does the pathwise estimator usually have lower variance than the score-function estimator?
It uses the slope ; the score-function estimator multiplies values of by a zero-mean random factor, so its noise grows with (and with the dimension).
Which decoder variance does "summed squared error KL" assume?
A Gaussian decoder with fixed .
Define rate and distortion of a VAE.
Rate ; distortion ; .
What is posterior collapse, and how do you detect it?
for all , so carries no information. Signs: per-dimension KL near 0 and no active units ().
In a linear VAE with fixed decoder variance , when is a latent direction with data variance active?
When ; then and the rate is .
What is the straight-through estimator in VQ-VAE?
Forward: the decoder sees the nearest code . Backward: the gradient at is copied to unchanged; in code .
Name the three loss terms of VQ-VAE.
Reconstruction , codebook , and commitment .
9. Interview angle #
- "Write the VAE loss." — Summed reconstruction NLL plus , with . Watch the reductions (sum vs mean).
- "Why does reparameterization reduce variance?" — It uses ; the score-function estimator uses only values of times a zero-mean factor, so its noise scales with .
- "Is posterior collapse an optimization bug?" — Not always: with a decoder that can model alone, or a decoder variance above the data variance, it is the optimum of the ELBO.
- "What does β do in a β-VAE? Is the objective still a bound?" — It trades distortion for rate along the rate–distortion curve; it is a bound only for .
- "How do gradients pass the argmin in VQ-VAE? What is the commitment loss for?" — A straight-through copy; the commitment loss keeps encoder outputs close to their codes.
- "Why are VAE samples blurry and diffusion samples sharp?" — A Gaussian decoder mean averages over what does not determine. A diffusion sampler builds the output in many small denoising steps, so the final output is a sample, not an average over the remaining uncertainty.
10. Practice #
The notebook for this lesson runs in Colab. It has five exercises, each with a check cell and a folded solution, and an optional PyTorch demo:
- The Gaussian KL in closed form vs Monte Carlo, in 1D and in the general (full-covariance) case.
- The variance of pathwise and score-function gradients for three test functions.
- A linear VAE in 2D: optimize it numerically and find the β at which each latent direction collapses; compare with .
- Nearest-code quantization and the straight-through gradient: check which gradient reaches the encoder and the codebook.
- Choose between trained models with and find the tie values of β.
- (Optional, PyTorch) a tiny VAE on two moons: the 2D latent space, samples, and active units.
11. Watch and read #
- Diederik P. Kingma and Max Welling, An Introduction to Variational Autoencoders (2019): §2.3–2.4 (gradients and the reparameterization trick), §2.5 (the factorized Gaussian encoder), §2.8 (KL annealing, free bits and blurriness).
- Aaron van den Oord, Oriol Vinyals and Koray Kavukcuoglu, Neural Discrete Representation Learning (VQ-VAE, 2017): §3.1–3.3 (the loss, , the prior fitted afterwards).
- James Lucas, George Tucker, Roger Grosse and Mohammad Norouzi, Don't Blame the ELBO! A Linear VAE Perspective on Posterior Collapse (2019): the linear analysis behind the figures of this lesson.
- Irina Higgins et al., β-VAE: Learning Basic Visual Concepts with a Constrained Variational Framework (ICLR 2017).
- Lilian Weng, From Autoencoder to Beta-VAE: a compact overview with the reparameterization trick, β-VAE and VQ-VAE.
- Kevin Murphy, Probabilistic Machine Learning: Advanced Topics (free PDF): ch. 21 (VAEs), including §21.4 (posterior collapse) and §21.6 (VQ-VAE).
Runs in your browser with nothing to install. The notebook repeats the key demos and has exercises with checks; solutions are inside, folded.
No Google account needed: Python runs inside your browser. The first start downloads about 40 MB; your changes are saved in this browser only.