π VAE: Auto-Encoding Variational Bayes
VAE: Auto-Encoding Variational Bayes (Kingma & Welling, 2013)
A plain autoencoder compresses data through a bottleneck, but its codes are scattered wherever training put them. Pick a random point in its latent space, decode it, and you usually get garbage. It is a compressor, not a generative model.
The variational autoencoder makes the latent space a probability distribution you can sample from. It does that with two ideas from this paper:
- The evidence lower bound (ELBO): a trainable objective that bounds the likelihood $\log p(x)$, which cannot be computed directly.
- The reparameterisation trick: rewrite sampling so gradients can flow through it, and the whole thing trains with ordinary backpropagation.
This page verifies the ELBO identity exactly on a model where $\log p(x)$ is known, measures why the reparameterisation trick matters, and trains a VAE on handwritten digits, then walks through its latent space.
helpers ready
1. The ELBO, and why it is a bound
A latent-variable model says: draw a code $z \sim p(z) = \mathcal{N}(0, I)$, then draw data from a decoder $p_\theta(x \mid z)$. Training should maximise
$$\log p_\theta(x) = \log \int p_\theta(x \mid z)\, p(z)\, dz,$$
but that integral over every possible $z$ is intractable for a neural decoder. The VAE introduces an encoder $q_\phi(z \mid x)$ that guesses which codes could have produced $x$. Then, exactly:
$$\log p_\theta(x) = \underbrace{\mathbb{E}_{q}\big[\log p_\theta(x\mid z)\big] - \mathrm{KL}\big(q_\phi(z\mid x)\,\|\,p(z)\big)}_{\text{ELBO}} \;+\; \mathrm{KL}\big(q_\phi(z\mid x)\,\|\,p_\theta(z\mid x)\big)$$
The last KL is never negative, so the ELBO is a lower bound on $\log p(x)$. The gap is exactly how far the encoder is from the true posterior. Maximising the ELBO therefore does two jobs at once: it fits the decoder and it pulls the encoder toward the posterior.
The two ELBO terms read naturally: reconstruct $x$ well, and keep the codes close to the prior so that sampling from $\mathcal{N}(0, I)$ lands somewhere the decoder understands.
Checking it where everything is computable
Use a 1-D linear-Gaussian model: $z \sim \mathcal{N}(0,1)$ and $x \mid z \sim \mathcal{N}(wz, s^2)$. Then $p(x) = \mathcal{N}(0, w^2+s^2)$ and the true posterior is Gaussian too, so every term above has a closed form.
==============================================================================
THE ELBO IDENTITY, CHECKED EXACTLY
==============================================================================
model: z ~ N(0,1), x|z ~ N(2.0 z, 0.5); observed x = 1.5
log p(x) = log N(1.5; 0, 4.5) = -1.920977
true posterior p(z|x) = N(0.6667, 0.1111)
Several encoders q(z|x) = N(m, v)
------------------------------------------------------------------------------
m v | recon KL(q||prior) ELBO | gap KL(q||post)
0.000 1.000 | -6.8224 0.0000 -6.8224 | 4.90139 4.90139
0.300 0.500 | -3.3824 0.1416 -3.5239 | 1.60296 1.60296
0.900 0.200 | -1.4624 0.8097 -2.2721 | 0.35111 0.35111
0.667 0.111 | -1.0446 0.8764 -1.9210 | 0.00000 0.00000
[PASS] log p(x) - ELBO == KL(q || true posterior) for every q (to 1e-12)
[PASS] the bound is tight (gap 0) exactly when q is the true posterior
Monte Carlo check of the reconstruction term for q = N(0.3, 0.5): -3.3875 vs closed form -3.3824
Training the encoder means moving $q$ toward the posterior. As it moves, the ELBO rises to meet $\log p(x)$, and the gap, the KL to the posterior, closes.
2. The reparameterisation trick
The ELBO contains $\mathbb{E}_{z \sim q_\phi}[\cdot]$, and the encoder parameters $\phi$ sit inside the distribution being sampled. You cannot backpropagate through "draw a random number".
The trick is to move the randomness outside:
$$z = \mu_\phi(x) + \sigma_\phi(x)\odot\varepsilon, \qquad \varepsilon \sim \mathcal{N}(0, I)$$
Now $z$ is a deterministic, differentiable function of $\mu$ and $\sigma$, and $\varepsilon$ is just an input. Gradients flow through $\mu$ and $\sigma$ as through any layer.
The alternative, the score-function (REINFORCE) estimator, is also unbiased. The cell below measures what that costs in variance on a simple case: $\frac{\partial}{\partial\mu}\mathbb{E}_{z\sim\mathcal{N}(\mu,\sigma^2)}[z^2] = 2\mu$.
============================================================================== TWO UNBIASED GRADIENT ESTIMATORS, VERY DIFFERENT NOISE ============================================================================== true gradient: 2 * mu = 2.000 reparameterisation: mean 2.0009 variance 3.992 score function: mean 1.9994 variance 30.037 variance ratio: 7.5x [PASS] both are unbiased (means within 0.02 of 2.0) [PASS] reparameterisation has at least 5x lower variance
3. A VAE on handwritten digits
The encoder maps each 8Γ8 digit to $(\mu, \log\sigma^2)$ in a 2-dimensional latent space, small enough to draw. The decoder maps $z$ back to 64 pixel intensities. The loss is the negative ELBO: binary cross-entropy for reconstruction, plus the closed-form KL between $\mathcal{N}(\mu, \sigma^2)$ and $\mathcal{N}(0, 1)$:
$$\mathrm{KL} = -\tfrac{1}{2}\sum_j \big(1 + \log\sigma_j^2 - \mu_j^2 - \sigma_j^2\big)$$
============================================================================== TRAINING A 2-D VAE ON 1,797 DIGITS ============================================================================== step 1: reconstruction 44.34 KL 0.01 -ELBO 44.35 nats step 500: reconstruction 22.18 KL 2.29 -ELBO 24.47 nats step 2000: reconstruction 20.15 KL 3.26 -ELBO 23.41 nats step 6000: reconstruction 19.39 KL 3.45 -ELBO 22.84 nats KL term: closed form vs Monte Carlo, on the trained encoder ------------------------------------------------------------------------------ mean KL over 200 digits: closed form 3.4551 Monte Carlo 3.4551 [PASS] closed-form KL matches a 20,000-sample estimate (within 1%)
Two things to notice. The digits form clusters even though the VAE never saw a label: it organised the latent space by visual similarity on its own. And the decoded grid is smooth. Every point in the prior's range decodes to something digit-like, with gradual transitions between classes. That is the KL term at work. It packs the codes together near the origin, with no empty gaps where the decoder has never been trained.
A walk through the latent space, decoded at every step:
4. Strengths, weaknesses, and descendants
Sampling is trivial: draw $z \sim \mathcal{N}(0, I)$ and decode. Encoding is a single forward pass, and the latent space is smooth and meaningful.
The weakness is blur. A Gaussian or Bernoulli likelihood per pixel rewards predicting the average of the plausible outputs, which looks soft. GANs, on the next page, were partly a reaction to this.
Descendants carry the ideas into nearly every modern generator:
- Ξ²-VAE weights the KL term by Ξ² > 1 to encourage disentangled latent factors.
- VQ-VAE replaces the Gaussian latent with a learned discrete codebook.
- Latent diffusion (Stable Diffusion) uses a VAE-style autoencoder to compress 512Γ512 images into a 64Γ64Γ4 latent grid, then runs diffusion in that small space. See the diffusion page.
Summary
- $\log p(x) = \text{ELBO} + \mathrm{KL}(q \,\|\, \text{posterior})$. Verified exactly: the gap equals the KL to the true posterior for every $q$, and vanishes when $q$ is that posterior.
- ELBO = reconstruction β KL to the prior: decode well, and keep codes where the prior will sample.
- Reparameterisation writes $z = \mu + \sigma\varepsilon$. It is unbiased like the score-function estimator, with far lower variance, measured here.
- A 2-D VAE on digits clusters them without labels, and decodes every point of the prior's range into something digit-like.