Autoencoders and VAEs¶
An autoencoder squeezes data through a bottleneck and learns to rebuild it. A variational autoencoder turns that into a real generative model: a prior over a latent code, a decoder that turns a code into data, and an encoder that learns to guess which code produced a given input. All three are trained together by maximising one quantity, the evidence lower bound (ELBO). If you understand the ELBO, you understand VAEs, half of diffusion and much of modern probabilistic deep learning.
10,000 ft
Generative modelling asks for a model \(p_\theta(\mathbf{x})\) that you can sample from and that puts probability where the data is (the track overview). Latent-variable models explain each data point with an unobserved cause \(\mathbf{z}\), as in Gaussian mixtures and EM. The variational autoencoder (Kingma and Welling; Rezende, Mohamed and Wierstra, both 2013–14) made such models deep: a neural decoder, a neural inference network as encoder, and the reparameterisation trick so that backpropagation can train both. The VAE's ideas outlived its samples. Its ELBO is the objective that diffusion models optimise; its autoencoder is the compressor inside every latent diffusion system; its discrete cousin, the VQ-VAE, turns images and audio into tokens that transformers can model; and its sparse relatives are the main tool of interpretability.
2,000 ft
A VAE is an autoencoder whose code is a distribution, regularised to look like a fixed prior.
- The encoder maps \(\mathbf{x}\) to the mean and variance of a Gaussian over codes.
- A code is sampled as \(\mathbf{z} = \boldsymbol\mu + \boldsymbol\sigma\odot\boldsymbol\epsilon\), so gradients flow through \(\boldsymbol\mu\) and \(\boldsymbol\sigma\).
- The decoder maps \(\mathbf{z}\) back to a distribution over \(\mathbf{x}\).
- The loss is reconstruction error plus a KL penalty that keeps each code distribution close to \(\mathcal N(\mathbf 0, I)\).
- That sum is exactly the negative ELBO, a lower bound on \(\log p_\theta(\mathbf{x})\).
- To generate, drop the encoder: sample \(\mathbf{z}\sim\mathcal N(\mathbf 0, I)\) and decode.
Ground level¶
Autoencoders: compression as a training signal¶
An autoencoder is two networks trained as one. The encoder \(f_\phi\) maps an input \(\mathbf{x}\in\mathbb R^D\) to a code \(\mathbf{z}\in\mathbb R^K\); the decoder \(g_\theta\) maps the code back; the loss is the reconstruction error \(\lVert \mathbf{x} - g_\theta(f_\phi(\mathbf{x}))\rVert^2\). Nobody labels anything. The supervision is the input itself, so this is the oldest form of what is now called self-supervised learning.
The trick is that the network must not be allowed to learn the identity. The classic way is a bottleneck, \(K \ll D\): to rebuild a 784-pixel digit from 16 numbers, the code has to capture what varies between digits (which digit, slant, stroke width) and the decoder has to know everything that does not (that digits are strokes on a blank background).
Three facts place autoencoders on the map:
- A linear autoencoder is PCA. With linear encoder and decoder and squared error, the optimum spans the same subspace as the top \(K\) principal components (Baldi and Hornik, 1989), though not necessarily with orthogonal axes. Depth and nonlinearity let an autoencoder find curved low-dimensional structure that PCA flattens; see PCA, t-SNE and UMAP.
- Other ways to stop the identity. A denoising autoencoder (Vincent et al., 2008) corrupts the input and asks for the clean version, so it must learn which directions are "data" and which are "noise". Hold on to that: a denoiser implicitly learns the gradient of the log-density, the insight behind score matching and diffusion. A sparse autoencoder uses a wide code (\(K > D\)) but penalises how many units are active; this is the workhorse of mechanistic interpretability, where it splits a model's activations into interpretable features.
- Deep autoencoders work. Hinton and Salakhutdinov's 2006 Science paper showed that deep autoencoders, pre-trained layer by layer, compress images and documents far better than PCA. That result was one of the sparks of the deep learning reset.
Why a plain autoencoder is not a generative model¶
Train an autoencoder with a 2-D code on MNIST and plot the codes of the training set. You get a scatter of clusters with irregular shapes, at arbitrary scales, with gaps between them. Now try to generate: pick a random point in the plane and decode it. Most points fall in regions no training code ever visited, and the decoder, which was never trained there, produces smudges.
The autoencoder learned a good map from data to codes. It did not learn a distribution over codes, so it has no idea where to sample. Two repairs are needed:
- Decide in advance what the distribution of codes should be (a prior, say \(\mathcal N(\mathbf 0, I)\)), and train the encoder to fill it.
- Make the decoder robust to the whole neighbourhood of each code, not one point, so that the space between training codes decodes to something sensible.
The VAE does both, and it does them not as ad hoc regularisers but as the consequence of a single principle: maximum likelihood in a latent-variable model.
The generative story¶
Write down how you would like the data to have been made:
The decoder network computes the parameters of \(p_\theta(\mathbf{x}\mid\mathbf{z})\): for real-valued data, a Gaussian mean \(g_\theta(\mathbf{z})\) (with some variance); for binarised pixels, one Bernoulli probability per pixel. The model's density over data is the evidence (or marginal likelihood)
This is a continuous mixture: infinitely many components, one per \(\mathbf{z}\), each a simple distribution whose centre is placed by a neural network. A Gaussian mixture with \(K\) components is the discrete version, and you fitted it with EM. Simple pieces, mixed through a flexible map, can represent very complicated densities.
Training by maximum likelihood (MLE) means maximising \(\sum_i \log p_\theta(\mathbf{x}_i)\). The obstacle is the integral. For a neural decoder it has no closed form, and naive Monte Carlo, \(\frac1S\sum_s p_\theta(\mathbf{x}\mid\mathbf{z}_s)\) with \(\mathbf{z}_s\sim p(\mathbf{z})\), is hopeless: almost every \(\mathbf{z}\) from the prior decodes to something that is not \(\mathbf{x}\), so the average is dominated by rare lucky draws. EM would need the posterior \(p_\theta(\mathbf{z}\mid\mathbf{x}) = p_\theta(\mathbf{x}\mid\mathbf{z})p(\mathbf{z})/p_\theta(\mathbf{x})\), which contains the same integral.
The ELBO: a bound you can optimise¶
The way out is to bring in a second distribution \(q_\phi(\mathbf{z}\mid\mathbf{x})\), a guess at which codes could have produced \(\mathbf{x}\), and use it for importance sampling:
The inequality is Jensen's (\(\log\) is concave). \(\mathcal L\) is the evidence lower bound. Two rearrangements make it readable.
As a training loss. Split \(p_\theta(\mathbf{x},\mathbf{z}) = p_\theta(\mathbf{x}\mid\mathbf{z})p(\mathbf{z})\):
The first term says: codes drawn from the encoder's distribution must decode back to \(\mathbf{x}\). The second says: the encoder's distribution for each \(\mathbf{x}\) must stay close to the prior. These are precisely the two repairs from above, and neither was invented: both fell out of the bound.
As a statement about the gap. Instead of Jensen, write \(p_\theta(\mathbf{x},\mathbf{z}) = p_\theta(\mathbf{z}\mid\mathbf{x})\,p_\theta(\mathbf{x})\):
This is an identity, not an inequality. The gap between the evidence and the bound is exactly how far the encoder's guess is from the true posterior, measured by KL divergence. So maximising \(\mathcal L\) over \(\phi\) (with \(\theta\) fixed) cannot change \(\log p_\theta(\mathbf{x})\); it can only shrink the gap, which makes the encoder a better approximate posterior. Maximising over \(\theta\) pushes the evidence up (or the gap down). Doing both at once is variational inference and learning in one gradient step.
The picture to keep
The evidence \(\log p_\theta(\mathbf{x})\) is a ceiling you cannot see. The ELBO is a floor you can measure. The encoder raises the floor toward the ceiling; the decoder raises the ceiling and the floor together. Training pushes the floor up; whenever the floor rises, the ceiling is at least that high.
You can check the identity on a model where everything is computable. In the Build it section a one-dimensional linear-Gaussian model has \(\log p(x) = -2.3659\) at \(x=3\); an encoder guess \(q = \mathcal N(1.00, 0.50^2)\) gives an ELBO of \(-2.658\), and the gap, \(0.292\), matches \(\mathrm{KL}(q\,\|\,\text{posterior}) = 0.290\) to Monte Carlo precision. At the exact posterior \(\mathcal N(1.114, 0.330^2)\) the gap is zero, and every single Monte Carlo sample of the bound equals \(\log p(x)\) exactly.
Amortised inference: why there is an encoder at all¶
Classical variational inference fits a separate \(q\) for each data point by running an optimiser. With a million images that is a million optimisations, repeated whenever \(\theta\) changes. The VAE instead trains one network, \(q_\phi(\mathbf{z}\mid\mathbf{x}) = \mathcal N\big(\boldsymbol\mu_\phi(\mathbf{x}),\operatorname{diag}\boldsymbol\sigma^2_\phi(\mathbf{x})\big)\), that outputs the variational parameters for any input in one forward pass. This is amortised inference: the cost of inference is paid once, during training, and spread over every future query.
It has a price. The best diagonal Gaussian for each \(\mathbf{x}\) may still be far from the true posterior (the approximation gap), and the encoder may not even find that best Gaussian (the amortisation gap). Cremer, Li and Duvenaud (2018) measured both and found that the amortisation gap is often the larger one. More flexible posteriors (normalising flows in the encoder, as in inverse autoregressive flow) attack the first; bigger encoders or a few refinement steps attack the second.
The reparameterisation trick¶
The reconstruction term is an expectation over \(\mathbf{z}\sim q_\phi\), and we need its gradient with respect to \(\phi\), the parameters of the distribution we are sampling from. You cannot backpropagate through "draw a random number".
The trick is to move the randomness out of the way. A Gaussian sample can be written as a deterministic function of the parameters and parameter-free noise:
Now \(\mathbb E_{q_\phi}[h(\mathbf{z})] = \mathbb E_{\boldsymbol\epsilon}[h(\boldsymbol\mu + \boldsymbol\sigma\odot\boldsymbol\epsilon)]\), the distribution being averaged over no longer depends on \(\phi\), and the gradient moves inside: \(\nabla_\phi\,\mathbb E_{\boldsymbol\epsilon}[h(\cdot)] = \mathbb E_{\boldsymbol\epsilon}[\nabla_\phi h(\boldsymbol\mu+\boldsymbol\sigma\odot\boldsymbol\epsilon)]\). One sample of \(\boldsymbol\epsilon\) per data point gives an unbiased gradient estimate, and autodiff computes it like any other.
The alternative that works for any distribution is the score-function (REINFORCE) estimator, \(\nabla_\phi \mathbb E_{q_\phi}[h] = \mathbb E_{q_\phi}[h(\mathbf{z})\,\nabla_\phi \log q_\phi(\mathbf{z})]\), the same estimator that trains policy gradients. It is unbiased too, but it only uses the value of \(h\), not its slope, and its variance is far higher. For the toy problem \(\nabla_\mu\,\mathbb E_{z\sim\mathcal N(\mu,1)}[z^2] = 2\mu\) at \(\mu=1\), the reparameterised estimator has variance about 4 and the score-function estimator about 30 (code below): you would need roughly eight times as many samples for the same precision, and the ratio grows with dimension.
Discrete latents break the trick
\(\mathbf{z} = \boldsymbol\mu + \boldsymbol\sigma\odot\boldsymbol\epsilon\) needs a continuous, differentiable path from parameters to sample. For categorical latents there is none. The options are the score-function estimator with variance reduction, a continuous relaxation (Gumbel-softmax), or the straight-through estimator used by the VQ-VAE below.
Reading the loss: reconstruction against rate¶
For a diagonal Gaussian encoder and standard normal prior the KL term has a closed form (derived in The maths):
Worked example. An encoder outputs \(\boldsymbol\mu = (1.0,\,-0.5)\) and \(\log\boldsymbol\sigma^2 = (-1.386,\,0)\), so \(\boldsymbol\sigma^2 = (0.25,\,1)\). Dimension 1 contributes \(0.25 + 1 - 1 + 1.386 = 1.636\); dimension 2 contributes \(1 + 0.25 - 1 - 0 = 0.25\). The KL is \(\tfrac12(1.886) = 0.943\) nats, or 1.36 bits. Dimension 2 has the prior's variance and costs only for its offset mean. Dimension 1 pays for both its offset and its precision: saying "\(z_1\) is \(1.0 \pm 0.5\)" carries information.
That last sentence is the right way to read the KL term. It is the rate: the number of nats of information about \(\mathbf{x}\) that the code carries, averaged over the encoder's noise. The reconstruction term is the distortion. A VAE is a learned lossy compressor that trades rate against distortion (Alemi et al., 2018, "Fixing a broken ELBO"), and the ELBO weights the two equally. A dimension that carries no information has \(\mu_j = 0\), \(\sigma_j = 1\) for every input and costs nothing; the encoder will happily switch dimensions off if they don't pay for themselves.
Two knobs change the trade:
- The decoder variance. With \(p_\theta(\mathbf{x}\mid\mathbf{z}) = \mathcal N(g_\theta(\mathbf{z}), s^2 I)\), the reconstruction term is \(-\frac{1}{2s^2}\lVert\mathbf{x}-g_\theta(\mathbf{z})\rVert^2\) plus a constant. Small \(s\) makes reconstruction errors expensive relative to rate, so the model uses more latent information and reconstructs sharply; large \(s\) lets it get away with blur. Many implementations write "MSE + KL" and silently set \(s^2 = \tfrac12\); the implied choice of \(s\) is a real hyperparameter.
- \(\beta\)-VAE. Higgins et al. (2017) multiplied the KL by \(\beta > 1\). Rate becomes expensive, the model keeps only the most useful factors of variation, and on simple datasets those factors often align with individual latent dimensions (disentanglement). Locatello et al. (2019) later showed that, without inductive biases or supervision, disentanglement is not identifiable, so treat it as a useful tendency on curated data, not a guarantee.
What the latent space looks like¶
The union of all the encoder's blobs, \(q_\phi(\mathbf{z}) = \frac1N\sum_i q_\phi(\mathbf{z}\mid\mathbf{x}_i)\), is called the aggregate posterior. Generation samples from the prior \(p(\mathbf{z})\), but the decoder was trained on samples from \(q_\phi(\mathbf{z})\). When the two differ, prior samples land in "holes" and decode badly. Hoffman and Johnson's "ELBO surgery" analysis shows the average KL term splits into the mutual information between \(\mathbf{x}\) and \(\mathbf{z}\) plus \(\mathrm{KL}(q_\phi(\mathbf{z})\,\|\,p(\mathbf{z}))\): the ELBO penalises the mismatch, but it also penalises information, so the two goals pull against each other. Learned priors (VampPrior, or a second-stage model fitted to the codes, as in VQ-VAE and latent diffusion) close the holes by fitting the prior to the aggregate posterior instead.
Because neighbouring codes decode to similar outputs, the latent space supports interpolation (decode points on a line between two codes and watch one face morph into another) and latent arithmetic (average the codes of smiling faces minus non-smiling ones to get a "smile vector"). The same geometry appears in word embeddings.
Why VAE samples are blurry¶
Train a VAE on faces with a Gaussian decoder and the samples look like soft-focus photographs. This is not a bug in the code; it is the objective. A Gaussian decoder with fixed variance scores reconstructions by squared error, and when several plausible images are consistent with one code, the squared-error-optimal output is their average. Averages of sharp images with slightly different edge positions are blurry. The encoder's noise makes it worse: each code must decode well for a whole blob of nearby \(\mathbf{z}\).
There are three ways out, and modern systems use all of them:
- Better likelihoods. An autoregressive decoder (PixelCNN-style) models pixel dependencies and does not average. But see posterior collapse, next.
- Hierarchies. NVAE (Vahdat and Kautz, 2020) and Very Deep VAEs (Child, 2020) stack dozens of latent layers, coarse to fine, and produce sharp faces at 256×256 and above; Child showed a deep enough VAE matches autoregressive likelihoods on images.
- Perceptual and adversarial losses. Replace pixel MSE with a feature-space loss (LPIPS) and add a GAN discriminator. This is how the autoencoders inside VQGAN and Stable Diffusion are trained: they reconstruct sharply because a discriminator punishes blur.
Posterior collapse¶
Give a VAE a very powerful decoder, such as an LSTM language model over sentences (Bowman et al., 2015) or a PixelCNN over images, and something unexpected happens: the KL term goes to zero, every \(q_\phi(\mathbf{z}\mid\mathbf{x})\) equals the prior, and the decoder ignores \(\mathbf{z}\) entirely. The model has become a plain autoregressive model with an unused latent.
The reason is the rate–distortion trade. Encoding information in \(\mathbf{z}\) costs rate. If the decoder can model the data well without that information, using its own autoregressive context, then the cheapest solution is to send nothing. Chen et al. (2016, "Variational lossy autoencoder") gave the information-theoretic argument: information that the decoder can model locally will never be routed through the latent.
Collapse is not only a powerful-decoder phenomenon. In a linear VAE, which is probabilistic PCA, Lucas et al. (2019) showed that a latent direction collapses exactly when its data variance is below the decoder's noise variance \(s^2\): the signal in that direction is not worth its rate. The Build it section reproduces this. With data eigenvalues \((4, 2, 0.5, 0.1, 0.1)\) and \(s^2 = 1\), a 3-D linear VAE learns decoder columns of length \(\sqrt{\lambda_j - s^2} = (1.732, 1, 0)\): two active latents and one collapsed, with KL of \(\tfrac12\log(\lambda_j/s^2) = (0.693, 0.347, 0)\) nats per dimension.
Practical defences:
- KL annealing: multiply the KL by a weight that ramps from 0 to 1 over the first part of training, so the encoder learns to carry information before it is charged for it (Bowman et al.).
- Free bits: don't charge for the first \(\lambda\) nats of KL per dimension or group, \(\sum_j \max(\lambda, \mathrm{KL}_j)\) (Kingma et al., 2016).
- Weaken the decoder: limit its receptive field or drop its inputs (word dropout), so the latent is the only route for global information.
- Choose \(s\) honestly: an inflated decoder variance invites collapse, as the linear case shows.
Discrete latents: the VQ-VAE¶
The VQ-VAE (van den Oord, Vinyals and Kavukcuoglu, 2017) replaces the Gaussian code with a grid of discrete tokens. The encoder outputs a vector \(\mathbf{z}_e(\mathbf{x})\) at each spatial position; each vector is snapped to its nearest entry in a learned codebook \(\{\mathbf{e}_1,\dots,\mathbf{e}_M\}\); the decoder sees the snapped vectors \(\mathbf{z}_q\). An image becomes, say, a 32×32 grid of integers from a vocabulary of 512.
Snapping has no gradient, so the VQ-VAE copies the decoder's gradient with respect to \(\mathbf{z}_q\) straight onto \(\mathbf{z}_e\) (the straight-through estimator). The loss has three parts:
where \(\operatorname{sg}\) is stop-gradient: the second term moves codebook vectors toward the encoder outputs assigned to them (in practice often replaced by an exponential moving average, which is k-means run online), and the third, the commitment loss with \(\beta = 0.25\) in the paper, keeps the encoder from wandering away from its codes. With a uniform prior over codes, the KL term is a constant (\(\log M\) per position) and drops out.
Training happens in two stages. First the VQ-VAE learns to compress. Then a separate autoregressive model (PixelCNN in the original; transformers since) learns the prior over token grids. Sampling generates tokens with the prior and decodes them. This two-stage pattern, a compressor plus a powerful generative model in its latent space, is the template for nearly everything that followed: VQ-VAE-2, VQGAN plus a transformer (Esser et al., 2020), the image tokenisers inside multimodal LLMs (vision-language models), the neural audio codecs that turn speech into tokens (speech and audio), and, with a continuous latent and diffusion instead of a transformer, latent diffusion.
Codebook collapse
Only a fraction of the codebook gets used: entries that are never nearest to any encoder output never move. Remedies include initialising codes from encoder outputs (k-means), resetting dead codes to random encoder outputs, lower-dimensional or normalised codes, and replacing the codebook with fixed scalar quantisation of each dimension (finite scalar quantisation).
Where VAEs sit today¶
As stand-alone image generators, VAEs were overtaken first by GANs on sharpness and then by diffusion models on everything. Their ideas did not lose:
- Every latent diffusion model contains a VAE-style autoencoder. Stable Diffusion's compresses a 512×512×3 image to a 64×64×4 latent (a factor of 8 per side) with a lightly KL-regularised encoder and a GAN-trained decoder, and the diffusion model works only in that latent space (latent diffusion). Video models do the same with spatio-temporal autoencoders (video and world models).
- Diffusion models are hierarchical VAEs with a fixed encoder (the noising process) and one latent per step; their loss is an ELBO (diffusion).
- Tokenisers for images and audio are VQ-VAE descendants.
- World models in reinforcement learning (Dreamer) learn a VAE-style latent state and plan in it (model-based RL).
- Sparse autoencoders decompose LLM activations into features (interpretability).
History¶
Who found it
Autoencoders go back to the 1980s connectionists (Rumelhart, Hinton and Williams's 1986 work used them; Baldi and Hornik proved the PCA connection in 1989). The wake–sleep algorithm (Hinton, Dayan, Frey and Neal, 1995) and the Helmholtz machine (Dayan et al., 1995) already paired a generative network with a recognition network that guessed latent causes, trained by alternating phases. What was missing was a single objective with low-variance gradients. Diederik Kingma and Max Welling posted Auto-Encoding Variational Bayes in December 2013 (ICLR 2014), and Danilo Rezende, Shakir Mohamed and Daan Wierstra independently posted Stochastic Backpropagation and Approximate Inference in Deep Generative Models in January 2014 (ICML 2014). Both contributed the reparameterisation gradient and the amortised encoder. The ideas then branched: semi-supervised VAEs (Kingma et al., 2014), importance-weighted bounds (Burda et al., 2015), normalising-flow posteriors (Rezende and Mohamed, 2015; Kingma et al., 2016), β-VAE (2017), VQ-VAE (2017) and VQ-VAE-2 (2019), NVAE and VDVAE (2020). Kingma and Welling's VAE paper received the first ICLR Test of Time award in 2024.
First principles¶
Why does the VAE look the way it does? Start from three commitments and each piece is forced.
1. We want maximum likelihood. Maximising \(\frac1N\sum_i\log p_\theta(\mathbf{x}_i)\) is the same as minimising \(\mathrm{KL}(p_{\text{data}}\,\|\,p_\theta)\), the forward KL, which punishes the model for assigning low probability to anything in the data. That is why VAEs (like all likelihood models) cover all the modes of the data and are rarely accused of mode collapse, and also why they spread mass into implausible in-between regions: forward KL is "mass-covering".
2. We want a latent-variable model. Low-dimensional causes, decoded by a network, give a model that can represent curved, multimodal data with simple components. The price is that the likelihood is an integral we cannot compute.
3. We refuse to compute that integral. Any tractable surrogate must be a bound or an estimate. The family of bounds \(\mathbb E_q[\log p(\mathbf{x},\mathbf{z}) - \log q(\mathbf{z})]\) is the natural one because its slack is a KL divergence to the posterior, which is zero for the right \(q\). Nothing else gives you an objective that is simultaneously (a) a valid lower bound, (b) tight at an achievable optimum and © an expectation under a distribution you choose, which is what makes Monte Carlo gradients possible.
From there: amortisation is forced by data-set size, the reparameterisation trick by the need for low-variance gradients through samples, the Gaussian encoder by the need for a closed-form KL and a reparameterisable sample, and the standard-normal prior by convenience (any fixed distribution works; the decoder can warp \(\mathcal N(\mathbf 0, I)\) into anything).
What breaks if you change things? Use the reverse direction of KL in the bound and you lose the lower-bound property. Drop the KL term and you have a stochastic autoencoder with no reason for codes to fill the prior. Make the encoder deterministic and the KL to a continuous prior is infinite. Make the bound tighter with more samples (next section) and, interestingly, the encoder can get worse: Rainforth et al. (2018) showed the signal-to-noise ratio of the encoder's gradient decreases as the IWAE bound tightens.
The maths¶
Setup. Data \(\mathbf{x}\in\mathbb R^D\); latent \(\mathbf{z}\in\mathbb R^K\); prior \(p(\mathbf{z}) = \mathcal N(\mathbf 0, I_K)\); decoder \(p_\theta(\mathbf{x}\mid\mathbf{z})\); encoder \(q_\phi(\mathbf{z}\mid\mathbf{x}) = \mathcal N(\boldsymbol\mu,\operatorname{diag}\boldsymbol\sigma^2)\) with \((\boldsymbol\mu, \log\boldsymbol\sigma^2) = \text{enc}_\phi(\mathbf{x})\), both in \(\mathbb R^K\). A mini-batch has shape \((B, D)\); the encoder output has shape \((B, 2K)\); \(\boldsymbol\epsilon\) and \(\mathbf{z}\) have shape \((B, K)\); the decoder output has shape \((B, D)\).
Derivation: the ELBO identity
For any \(q\) with \(q(\mathbf{z}) > 0\) wherever \(p_\theta(\mathbf{z}\mid\mathbf{x}) > 0\):
The first line holds because \(\log p_\theta(\mathbf{x})\) does not depend on \(\mathbf{z}\); the second is Bayes' rule; the third multiplies and divides by \(q\). Since KL is non-negative, \(\mathcal L\le\log p_\theta(\mathbf{x})\) with equality iff \(q = p_\theta(\cdot\mid\mathbf{x})\). Corollary: if \(q\) is the exact posterior, \(\log p_\theta(\mathbf{x},\mathbf{z}) - \log q(\mathbf{z}) = \log p_\theta(\mathbf{x})\) for every \(\mathbf{z}\), so a single-sample estimate of the bound has zero variance. The code below shows exactly that.
Derivation: KL between a diagonal Gaussian and N(0, I)
The KL factorises over dimensions, so take one: \(q = \mathcal N(\mu,\sigma^2)\), \(p = \mathcal N(0,1)\).
Take the expectation under \(q\), using \(\mathbb E_q[(z-\mu)^2] = \sigma^2\) and \(\mathbb E_q[z^2] = \sigma^2 + \mu^2\):
It is zero iff \(\mu=0,\sigma=1\). Its gradients, \(\partial/\partial\mu = \mu\) and \(\partial/\partial\log\sigma^2 = \tfrac12(\sigma^2-1)\), are what the encoder's KL branch backpropagates. Parameterising \(\log\sigma^2\) rather than \(\sigma\) keeps the variance positive without constraints. The general form for \(q=\mathcal N(\boldsymbol\mu_1,\Sigma_1)\), \(p=\mathcal N(\boldsymbol\mu_2,\Sigma_2)\) is \(\tfrac12\big[\operatorname{tr}(\Sigma_2^{-1}\Sigma_1) + (\boldsymbol\mu_2-\boldsymbol\mu_1)^\top\Sigma_2^{-1}(\boldsymbol\mu_2-\boldsymbol\mu_1) - K + \log\frac{\det\Sigma_2}{\det\Sigma_1}\big]\).
The reconstruction term. For a Gaussian decoder \(\mathcal N(\hat{\mathbf{x}}, s^2 I)\) with \(\hat{\mathbf{x}} = g_\theta(\mathbf{z})\):
For a Bernoulli decoder over binary pixels with probabilities \(\hat{\mathbf{x}}\in(0,1)^D\):
the negative of binary cross-entropy summed (not averaged) over pixels. Averaging over pixels instead of summing silently divides the reconstruction term by \(D\) and is equivalent to \(\beta = D\): a common bug that produces a collapsed, blurry VAE.
The training objective. With one sample \(\boldsymbol\epsilon_i\) per example,
an unbiased estimate of the average ELBO whose gradient with respect to both \(\theta\) and \(\phi\) is unbiased too. Maximise it with Adam.
Derivation: the reparameterisation gradient and why its variance is lower
For \(z = \mu + \sigma\epsilon\), \(\nabla_\mu\mathbb E_\epsilon[h(z)] = \mathbb E_\epsilon[h'(z)]\) and \(\nabla_\sigma\mathbb E_\epsilon[h(z)] = \mathbb E_\epsilon[h'(z)\,\epsilon]\). The score-function estimator uses \(\nabla_\mu\log q(z) = (z-\mu)/\sigma^2\), giving \(\mathbb E_q[h(z)(z-\mu)/\sigma^2]\). Integration by parts (Stein's lemma, \(\mathbb E[h(z)(z-\mu)] = \sigma^2\mathbb E[h'(z)]\)) shows the two have the same mean. The variances differ: for \(h(z) = z^2\), \(\mu=1\), \(\sigma=1\), the reparameterised sample \(2z\) has variance \(4\sigma^2 = 4\), while \(z^2(z-\mu)\) has variance \(\mathbb E[z^4(z-1)^2] - 4 = 34 - 4 = 30\). The reparameterised estimator uses the derivative of \(h\), which carries information about which direction improves \(h\); the score-function estimator must discover that direction by correlating values of \(h\) with the noise.
Tighter bounds. The importance-weighted autoencoder (Burda, Grosse and Salakhutdinov, 2015) uses \(S\) samples inside the log:
with \(\mathcal L_S\to\log p_\theta(\mathbf{x})\) as \(S\to\infty\). \(\mathcal L_{5000}\) is the standard way to report a VAE's test log-likelihood, since the ELBO alone understates it.
Linear VAE (used in Build it). With \(p(\mathbf{x}\mid\mathbf{z}) = \mathcal N(W\mathbf{z}, s^2 I)\), \(q(\mathbf{z}\mid\mathbf{x}) = \mathcal N(A\mathbf{x}, \operatorname{diag}\mathbf{v})\) and zero-mean data with covariance \(C\), every expectation is closed-form:
Its maximum is probabilistic PCA (Tipping and Bishop, 1999) with fixed noise: column \(j\) of \(W\) has length \(\sqrt{\max(\lambda_j - s^2, 0)}\) along the \(j\)-th eigenvector of \(C\), and the optimal KL in that direction is \(\tfrac12\log(\lambda_j/s^2)\) for \(\lambda_j > s^2\) and zero otherwise. That is posterior collapse in closed form.
Build it¶
1. The ELBO identity, checked exactly (NumPy). A model small enough that \(\log p(x)\) and the true posterior are known, so the gap can be compared with \(\mathrm{KL}(q\,\|\,\text{posterior})\):
import numpy as np
rng = np.random.default_rng(0)
# A latent-variable model where everything is exact:
# z ~ N(0, 1), x | z ~ N(w z + b, s^2)
w, b, s = 2.0, 0.5, 0.7
x = 3.0 # one observed data point
# Exact evidence: x ~ N(b, w^2 + s^2)
var_x = w**2 + s**2
log_px = -0.5 * np.log(2*np.pi*var_x) - 0.5 * (x - b)**2 / var_x
# Exact posterior p(z | x) is Gaussian (conjugacy)
post_var = 1.0 / (1.0 + w**2 / s**2)
post_mu = post_var * w * (x - b) / s**2
def log_normal(v, m, sd):
return -0.5*np.log(2*np.pi*sd**2) - 0.5*(v - m)**2 / sd**2
def elbo(mu, sigma, n=100_000):
"""Monte Carlo ELBO: E_q[log p(x|z) + log p(z) - log q(z)], z = mu + sigma*eps."""
z = mu + sigma * rng.standard_normal(n)
terms = log_normal(x, w*z + b, s) + log_normal(z, 0, 1) - log_normal(z, mu, sigma)
return terms.mean(), terms.std()
def kl_gauss(m1, s1, m2, s2):
return np.log(s2/s1) + (s1**2 + (m1-m2)**2) / (2*s2**2) - 0.5
print(f"log p(x) = {log_px:.4f}")
print(f"true posterior = N({post_mu:.4f}, {np.sqrt(post_var):.4f}^2)")
for mu, sig in [(0.0, 1.0), (1.0, 0.5), (post_mu, 1.0), (post_mu, np.sqrt(post_var))]:
e, sd = elbo(mu, sig)
gap = kl_gauss(mu, sig, post_mu, np.sqrt(post_var))
print(f"q=N({mu:.2f},{sig:.2f}^2) ELBO={e:8.4f} gap={log_px-e:.4f} "
f"KL(q||post)={gap:.4f} per-sample std={sd:.3f}")
log p(x) = -2.3659
true posterior = N(1.1136, 0.3304^2)
q=N(0.00,1.00^2) ELBO=-11.0318 gap=8.6659 KL(q||post)=8.6556 per-sample std=11.766
q=N(1.00,0.50^2) ELBO= -2.6582 gap=0.2924 KL(q||post)=0.2901 per-sample std=1.053
q=N(1.11,1.00^2) ELBO= -5.3476 gap=2.9817 KL(q||post)=2.9740 per-sample std=5.787
q=N(1.11,0.33^2) ELBO= -2.3659 gap=0.0000 KL(q||post)=0.0000 per-sample std=0.000
The prior as a guess (\(q = \mathcal N(0,1)\)) gives a bound 8.7 nats below the truth: this is why sampling \(\mathbf{z}\) from the prior to estimate the likelihood fails. Getting the mean right but the width wrong (row 3) still costs 3 nats. At the true posterior the bound is tight and every sample agrees.
2. Reparameterisation against REINFORCE (NumPy):
import numpy as np
rng = np.random.default_rng(1)
# Two unbiased estimators of d/dmu E_{z~N(mu,1)}[z^2] (true value: 2*mu)
mu, n = 1.0, 100_000
eps = rng.standard_normal(n)
z = mu + eps
reparam = 2 * z # d/dmu f(mu + eps) = f'(z)
score_fn = z**2 * (z - mu) # f(z) * d/dmu log N(z; mu, 1) (REINFORCE)
for name, g in [("reparameterisation", reparam), ("score function", score_fn)]:
print(f"{name:19s} mean={g.mean():.3f} variance={g.var():.2f}")
3. Posterior collapse in a linear VAE (NumPy). Gradient ascent on the closed-form expected ELBO from The maths:
import numpy as np
rng = np.random.default_rng(0)
# 5-D Gaussian data whose covariance has eigenvalues 4, 2, 0.5, 0.1, 0.1
D, K, s2 = 5, 3, 1.0 # data dim, latent dim, decoder noise variance
lam = np.array([4.0, 2.0, 0.5, 0.1, 0.1])
Q, _ = np.linalg.qr(rng.standard_normal((D, D)))
C = Q @ np.diag(lam) @ Q.T # data covariance (data mean is zero)
W = 0.1 * rng.standard_normal((D, K)) # decoder p(x|z) = N(W z, s2 I)
A = 0.1 * rng.standard_normal((K, D)) # encoder q(z|x) = N(A x, diag(v))
logv = np.zeros(K)
def expected_elbo(W, A, logv):
"""E_data[ELBO] in closed form (constants dropped): linear-Gaussian, no sampling."""
v, R = np.exp(logv), np.eye(D) - W @ A
recon = np.trace(R @ C @ R.T) + np.sum(v * np.sum(W**2, 0))
kl = 0.5 * (np.sum(v) + np.trace(A @ C @ A.T) - K - np.sum(logv))
return -recon / (2 * s2) - kl
lr = 0.05
for step in range(4001):
v, R = np.exp(logv), np.eye(D) - W @ A
gW = (R @ C @ A.T - W * v) / s2
gA = W.T @ R @ C / s2 - A @ C
glogv = v * (-np.sum(W**2, 0) / (2 * s2) - 0.5 + 0.5 / v)
W, A, logv = W + lr * gW, A + lr * gA, logv + lr * glogv
if step % 1000 == 0:
print(f"step {step:4d} E[ELBO] = {expected_elbo(W, A, logv):.4f}")
norms = np.sort(np.linalg.norm(W, axis=0))[::-1]
print("decoder column norms :", np.round(norms, 3))
print("pPCA theory sqrt(lam-s2):", np.round(np.sqrt(np.maximum(lam[:K] - s2, 0)), 3))
kl_per_dim = 0.5 * (np.exp(logv) + np.diag(A @ C @ A.T) - 1 - logv)
print("KL per latent dim (nats):", np.round(np.sort(kl_per_dim)[::-1], 4))
step 0 E[ELBO] = -3.4672
step 1000 E[ELBO] = -2.3909
step 2000 E[ELBO] = -2.3897
step 3000 E[ELBO] = -2.3897
step 4000 E[ELBO] = -2.3897
decoder column norms : [1.732 1. 0. ]
pPCA theory sqrt(lam-s2): [1.732 1. 0. ]
KL per latent dim (nats): [0.6931 0.3466 0. ]
The third latent is collapsed: its decoder column is zero and its KL is zero, because the 0.5
variance it could explain is less than the noise variance \(s^2 = 1\) the decoder assumes. Set
s2 = 0.3 and it comes back to life.
4. A convolution-free VAE on MNIST (PyTorch; standard code, not run here):
import torch, torch.nn as nn, torch.nn.functional as F
class VAE(nn.Module):
def __init__(self, D=784, H=400, K=16):
super().__init__()
self.enc = nn.Sequential(nn.Linear(D, H), nn.ReLU(), nn.Linear(H, 2 * K))
self.dec = nn.Sequential(nn.Linear(K, H), nn.ReLU(), nn.Linear(H, D))
def forward(self, x): # x: (B, 784) in [0, 1]
mu, logvar = self.enc(x).chunk(2, dim=-1) # (B, K) each
z = mu + torch.exp(0.5 * logvar) * torch.randn_like(mu) # reparameterise
logits = self.dec(z) # (B, 784)
rec = F.binary_cross_entropy_with_logits(logits, x, reduction="none").sum(-1)
kl = 0.5 * (logvar.exp() + mu**2 - 1 - logvar).sum(-1)
return (rec + kl).mean() # negative ELBO, nats per image
model = VAE()
opt = torch.optim.Adam(model.parameters(), lr=1e-3)
# for x, _ in loader: loss = model(x.view(-1, 784)); opt.zero_grad(); loss.backward(); opt.step()
# generate: torch.sigmoid(model.dec(torch.randn(64, 16)))
Things to try
- In snippet 1, use \(q=\mathcal N(\mu_\text{post}, 0.2^2)\) (too narrow). The gap is again the KL, but now the per-sample spread is large in the other direction: an over-confident \(q\) misses posterior mass.
- In snippet 3, sweep
s2from 0.05 to 5 and plot how many latents stay active. You have just drawn a rate–distortion curve. - In the PyTorch VAE, set
K=2, train, and decode a 20×20 grid of \(\mathbf{z}\) values in \([-3,3]^2\). Then do the same for a plain autoencoder (drop the KL and the noise) and see the holes. - Replace
.sum(-1)in the reconstruction with.mean(-1)and watch the KL win: the samples turn into one blurry average digit. - Add \(\beta\) to the KL term and measure how the number of active dimensions (those with average KL above 0.01 nats) changes.
Common misconceptions¶
\"The KL term is just a regulariser you can tune away.\"
It is half of a bound on the log-likelihood. Re-weighting it gives a different, valid objective (rate–distortion), but then the number you report is no longer a likelihood bound, and samples from the prior get worse as the aggregate posterior drifts from it.
\"VAEs are blurry because the latent is too small.\"
Mostly they are blurry because of the decoder likelihood: a factorised Gaussian scores sharp detail as noise and predicts its mean. Hierarchical latents, autoregressive or adversarially trained decoders fix the blur with the same latent size.
\"The encoder is part of the generative model.\"
It is part of the training machinery: an approximate posterior. Generation needs only the prior and the decoder. The encoder is what you keep when you want representations or compression.
Check yourself¶
Why can't you train a latent-variable model by sampling z from the prior and averaging p(x|z)?
Because the estimator's variance is enormous: for a given \(\mathbf{x}\), almost all prior samples decode to something else, so \(p_\theta(\mathbf{x}\mid\mathbf{z})\) is negligible except on a tiny region of \(\mathbf{z}\)-space you almost never hit. Snippet 1 quantifies the loss: using the prior as the proposal costs 8.7 nats in the bound. The encoder is a learned proposal that looks in the right place.
Write log p(x) as the ELBO plus something. What is the something, and what does maximising the ELBO over the encoder do to it?
\(\log p_\theta(\mathbf{x}) = \mathcal L + \mathrm{KL}(q_\phi(\mathbf{z}\mid\mathbf{x})\,\|\,p_\theta(\mathbf{z}\mid\mathbf{x}))\). Over \(\phi\) the left side is constant, so increasing \(\mathcal L\) decreases the KL: the encoder becomes a better approximation of the true posterior.
An encoder outputs μ = (0, 2) and σ² = (1, 0.5). Compute the KL to N(0, I).
Dimension 1: \(1 + 0 - 1 - 0 = 0\). Dimension 2: \(0.5 + 4 - 1 - \log 0.5 = 3.5 + 0.693 = 4.193\). KL \(= \tfrac12(4.193) = 2.10\) nats.
Why does the reparameterisation trick need the noise distribution not to depend on φ?
So that the expectation is over a fixed distribution and the gradient can move inside it: \(\nabla_\phi\mathbb E_{p(\epsilon)}[h(g_\phi(\epsilon))] = \mathbb E_{p(\epsilon)}[\nabla_\phi h(g_\phi(\epsilon))]\). If the sampling distribution depended on \(\phi\), differentiating it would bring back a \(\nabla_\phi\log p\) term, which is the high-variance score-function estimator.
Your text VAE with an LSTM decoder has KL ≈ 0 for every input. What happened, and name three fixes.
Posterior collapse: the autoregressive decoder models the text well without the latent, so the optimum sends zero information through \(\mathbf{z}\). Fixes: KL annealing, free bits, word dropout or a weaker decoder (limited context), or an objective that explicitly rewards mutual information. Check also that the reconstruction is summed over tokens, not averaged.
In a linear VAE with decoder noise variance s², which latent directions collapse, and why does that make sense from a rate–distortion view?
Directions whose data variance \(\lambda_j \le s^2\). Encoding such a direction would cost rate \(\tfrac12\log(\lambda_j/s^2)\), which is non-positive: the decoder already attributes that much variation to noise, so there is nothing to gain in distortion. Only directions with signal above the assumed noise floor are worth paying for.
The VQ-VAE has no KL term in its loss. Where did it go?
With a deterministic one-hot posterior over \(M\) codes per position and a uniform prior, the KL is \(\log M\) per position, a constant, so it does not affect training. The real prior is fitted afterwards by a separate autoregressive model over the codes.
Hard: why might making the bound tighter (IWAE with large S) make the encoder worse?
As \(S\) grows, the IWAE bound depends less and less on the quality of \(q\) (any proposal with the right support works with infinitely many samples), so the gradient signal for \(\phi\) shrinks relative to its noise. Rainforth et al. (2018) showed the encoder gradient's signal-to-noise ratio decays like \(1/\sqrt S\), while the decoder's improves. Remedies use different bounds for the two networks.
Go deeper¶
Papers
- Auto-Encoding Variational Bayes — Kingma and Welling, 2013. The VAE paper. Sections 2.3–2.4 (the estimator and reparameterisation) and Appendix B (the Gaussian KL) are the core.
- Stochastic Backpropagation and Approximate Inference in Deep Generative Models — Rezende, Mohamed and Wierstra, 2014. The independent co-discovery, with a cleaner treatment of gradients through Gaussian samples.
- An Introduction to Variational Autoencoders — Kingma and Welling, 2019. The authors' own 80-page monograph: the best single reference, including flows and hierarchical models.
- Importance Weighted Autoencoders — Burda, Grosse and Salakhutdinov, 2015. Tighter bounds, and how VAE likelihoods are reported.
- Generating Sentences from a Continuous Space — Bowman et al., 2015. Where posterior collapse was named and KL annealing introduced.
- Fixing a Broken ELBO — Alemi et al., 2017. The rate–distortion reading of the ELBO.
- β-VAE: Learning Basic Visual Concepts with a Constrained Variational Framework — Higgins et al., ICLR 2017. Disentanglement by upweighting the KL; read with Locatello et al. for the caveat.
- Don't Blame the ELBO! A Linear VAE Perspective on Posterior Collapse — Lucas et al., 2019. The closed-form collapse reproduced in Build it.
- Neural Discrete Representation Learning (VQ-VAE) — van den Oord, Vinyals and Kavukcuoglu, 2017. Discrete codes, the straight-through estimator and the two-stage recipe.
- NVAE: A Deep Hierarchical Variational Autoencoder — Vahdat and Kautz, 2020. How far a carefully engineered hierarchical VAE can go on images.
Videos and lectures
- Stanford CS236: Deep Generative Models (2023) — Stefano Ermon. The latent-variable and VAE lectures are the clearest university treatment; course site at deepgenerativemodels.github.io.
Articles and blog posts
- From Autoencoder to Beta-VAE — Lilian Weng, 2018. A compact tour of the whole autoencoder family with consistent notation.
- Tutorial on Variational Autoencoders — Carl Doersch, 2016. Gentle, intuition-first; good if the ELBO still feels abstract.
Courses and books
- Understanding Deep Learning — Simon J. D. Prince, 2023. Chapter 17 (variational autoencoders) has the best figures of the ELBO and the posterior gap.
Code
- AntixK/PyTorch-VAE — Many VAE variants (β-VAE, VQ-VAE, IWAE and more) in one consistent codebase, useful for comparing losses side by side.
Where this leads¶
- Generative adversarial networks: the opposite bet, sharp samples with no likelihood and no encoder.
- Diffusion models: a VAE with a fixed encoder and a thousand latent layers, trained on the same ELBO.
- Latent diffusion and guidance: a VAE compresses, diffusion generates in its latent space.
- Score matching and flow matching: what the denoising autoencoder was secretly learning.
- Vision-language models: VQ-style tokenisers that let one transformer read and write images.