Skip to content

6.2 Variational autoencoders

ready≈ 11.5 hoursNeeds: 6.1, 1.5Unlocks: 6.3, 6.5
  1. 1 Learn
  2. 2 Bridge & derive
  3. 3 Explore (ELBO decomposition)
  4. 4 Do
  5. 5 Check

A model you can sample. A VAE says how the data could have been made: draw a code z from a fixed prior p(z) = N(0, I), then draw x from a decoder p(x | z). To generate, do exactly that. Training should maximise log p(x) = log ∫ p(x | z) p(z) dz, but the integral over every code has no closed form (Prince, sections 17.1–17.3).

The bound. An encoder q(z | x) = N(μ(x), diag σ(x)²) guesses which codes could have made x. Jensen’s inequality then gives the evidence lower bound, log p(x) ≥ Eq[log p(x | z)] − KL(q(z | x) ‖ p(z)), which is tight when q equals the true posterior p(z | x). The first term is the 6.1 reconstruction loss; the second keeps every code distribution near the prior, so prior samples land where the decoder was trained (Kingma and Welling 2013, sections 2.2–2.3).

Two Gaussians, one formula. Both q and p are Gaussian, so the KL has a closed form, derived below and in appendix B of Kingma and Welling. Only the reconstruction term needs a sample of z.

Reparameterisation. Sampling z ~ q is not differentiable in μ and σ, but z = μ + σ ε with ε ~ N(0, I) is: the randomness moves into an input, and gradients flow through μ and σ (Kingma and Welling, section 2.4). The alternative, the score-function estimator of 5.10, is unbiased too but far noisier; the task measures both.

β and the bound’s gap. Weighting the KL by β trades reconstruction against how tightly the codes fill the prior (Higgins et al. 2017); only β = 1 is the ELBO. To check how loose the bound is, average K importance-weighted samples inside the log: the estimate rises towards log p(x) as K grows (Burda et al. 2015).

The ELBO, and the KL between two Gaussiansstep 1 of 6
  1. log⁡p(x)=log⁡Eq(z∣x)[p(x∣z) p(z)q(z∣x)]\log p(x) = \log \mathbb{E}_{q(z|x)}\Big[\frac{p(x|z)\,p(z)}{q(z|x)}\Big]

ELBO decomposition

Reconstruction vs KL trade-off

Static view on small screens. Open this page on a laptop to interact.

circles: 1 and 2 standard deviations of the prior N(0, I)
0123456789

decoded at evenly spaced quantiles of the prior (each row and column holds 1/8 of its mass)

random codes z ~ N(0, I), decoded

β = 0.25150.5 + 9.15 = 159.7 (−log p(x) ≈ 157.9)β = 1152.4 + 5.56 = 157.9 (−log p(x) ≈ 155.9)β = 4158.9 + 3.37 = 162.3 (−log p(x) ≈ 157.8)test nats per image: reconstruction + KL = −ELBO (at β = 1)
average σ of a code: 0.10 (the prior's is 1) posterior means within 2 prior σ: 70% (a sample from the prior: 86%)

The KL term in one dimension

dashed: prior N(0, 1); solid: one code's q(z | x) = N(1.00, 0.50²), on the same scale
KL = ½μ² + ½(σ² − 1 − ln σ²) = 0.500 + 0.318 = 0.818 nats

Each dot is the mean of one test image's code distribution q(z | x); the ellipses show its spread. The KL term pulls every code distribution towards the prior: the ½μ² part pulls the means to the origin, the other part pushes each σ towards 1. A small β mostly ignores it, so the means spread beyond the prior's disc and the σ shrink; a large β packs the codes into the prior's disc and reconstructions get blurrier. Read the bars for the trade: at β = 1 the loss is exactly the negative ELBO, a bound on −log p(x).

A slider picks one of three small VAEs trained on MNIST with a 2D latent space and β = 0.25, 1 or 4. A scatter plot shows the posterior means of 600 test images, coloured by digit, with optional ellipses for each code’s spread and dashed circles at 1 and 2 standard deviations of the prior. Beside it, an 8 × 8 grid decodes evenly spaced quantiles of the prior, and a row decodes eight random prior samples, with a button for new ones. Bars give each model’s test reconstruction term and KL, their sum (the negative ELBO) and an importance-sampled −log p(x). Below, two sliders set the mean and spread of one code distribution in one dimension, plotted against the prior, with the KL split into its two terms. Keyboard: Tab to the sliders and buttons.

Variational autoencoders: edit exercises/stubs/m6_2_vae.py on your own machine. This task needs PyTorch, which the in-page runner does not have.

pip install torch   # CPU build is enough for the tests
mlc check 6.2
Hints · gaussian_kl 0/3 revealed
Hints · vae_loss 0/3 revealed
Hints · log_likelihood_estimate 0/3 revealed

Then train on MNIST. Open notebooks/6.2-vae.ipynb on Kaggle (a CPU is enough) and paste in your 6.2 file. It compares the two gradient estimators, trains VAEs with a 2D and a 32D code at several β, plots the latent space and samples next to your 6.1 autoencoder’s, and estimates log p(x) with your importance sampler for K from 1 to 1,000.

1. Why can a VAE generate new images when the 6.1 autoencoder could not?
2. When is the ELBO equal to log p(x)?
3. What does the reparameterisation z = μ + σ ε buy?
4. You raise β from 1 to 4. What happens?
  • not yet: All tests pass (0/?)
  • not yet: Checkpoint quiz ≥ 80%
Finish the items above first.
Learner log: time spent and points of confusion

Every confusion you note becomes a fix before the module is marked stable. Export it from the progress page and attach it to an issue.