Search

Search papers and lessons

Variational Autoencoder

Level 4 · 18 min read

A variational autoencoder learns a smooth latent space by encoding each input as a distribution, not a point, and training with a reconstruction term plus a KL penalty toward a simple prior.

On this page

  • Colour = topic mix
  • Probability
  • Calculus
  • Discrete math
  • Generative models
  • Inference
  • Information theory
  • Sign in to see your progress

TL;DR

A variational autoencoder, or VAE, is a generative model that learns to compress data into a short hidden code and rebuild it from that code. Unlike a plain autoencoder, the encoder outputs a distribution over codes, not a single point. Training balances two things: rebuilding the input well, and keeping every code distribution close to a simple prior, usually a standard Gaussian.

That balance makes the hidden space smooth. Nearby codes decode to similar images, so you can sample a fresh code from the prior and decode it into something new.

Where you'll see it: in generative models of faces and molecules, in the image autoencoders that compress latent diffusion models, and in any setting where a learned, smooth latent space is more useful than a sharp reconstruction.

Intuition

A map with no holes

A plain autoencoder maps each input to one point in a code space. Suppose you train it on handwritten digits. The points for the digit 3 and the digit 8 may sit far apart, and the empty space between them decodes to nonsense. If you pick a random point there, you get a blurred or meaningless image.

A VAE fixes this by making the encoder output a small cloud instead of a point: a mean and a spread for each code dimension. Training then does two jobs. The reconstruction term asks that a sample from the cloud decode back to the input. The KL term asks that every cloud sit close to the same simple region, the prior. Because the clouds overlap and fill the region, the gaps between digits get filled in. Moving slightly in code space changes the image slightly, and the decoder never sees an unfamiliar region during training that it has to guess about.

This is the same latent variable idea that explains data through a hidden cause. The VAE is one way to fit such a model when the hidden cause is continuous and the posterior is too hard to compute exactly.

Why the sampling step needs a trick

Sampling is a random step, and gradient descent cannot pass through a random draw. The fix is the reparameterization trick: write the sample as a fixed noise draw passed through a smooth function of the encoder outputs. Then the randomness sits in the noise, and the gradients flow through the mean and spread.

flowchart LR
  X[Input x] --> E[Encoder] --> M[Mean mu and spread sigma]
  M --> S[Sample z = mu + sigma times eps]
  N[Noise eps from N 0 1] --> S
  S --> D[Decoder] --> R[Reconstruction of x]
  M --> K[KL penalty toward N 0 1]

The math

Setup

Let xx be an observed data point and zz a hidden code with prior p(z)=N(0,I)p(z) = \mathcal{N}(0, I). The decoder defines a likelihood pθ(x∣z)p_\theta(x \mid z), a distribution over data given a code. The encoder is a learned approximation qϕ(z∣x)q_\phi(z \mid x) to the true posterior pθ(z∣x)p_\theta(z \mid x), which is intractable. Both networks are neural networks. θ\theta and ϕ\phi are their parameters.

The objective

The evidence lower bound for one data point is

L(θ,ϕ;x)=Eqϕ(z∣x)[log⁡pθ(x∣z)]−DKL(qϕ(z∣x) ∥ p(z)).\mathcal{L}(\theta, \phi; x) = \mathbb{E}_{q_\phi(z \mid x)}\big[\log p_\theta(x \mid z)\big] - D_{\mathrm{KL}}\big(q_\phi(z \mid x)\,\|\,p(z)\big).

Training maximises L\mathcal{L} over both networks at once. Equivalently, we minimise the loss −L-\mathcal{L}. The first term is the expected log likelihood of the data under the decoder, which is minus the reconstruction error. The second term is the KL divergence between the encoder's distribution and the prior. It is zero only when the encoder output matches the prior exactly.

The closed-form KL for Gaussians

Take the encoder to output a diagonal Gaussian, qϕ(z∣x)=N(μ,diag(σ2))q_\phi(z \mid x) = \mathcal{N}(\boldsymbol{\mu}, \mathrm{diag}(\boldsymbol{\sigma}^2)), with JJ latent dimensions. The KL term to a standard Gaussian has a closed form:

DKL=12∑j=1J(μj2+σj2−1−log⁡σj2).D_{\mathrm{KL}} = \frac{1}{2} \sum_{j=1}^{J} \left(\mu_j^2 + \sigma_j^2 - 1 - \log \sigma_j^2\right).

Each dimension contributes a penalty for shifting its mean away from zero and for changing its spread away from one. The σj2−log⁡σj2\sigma_j^2 - \log \sigma_j^2 part is smallest at σj=1\sigma_j = 1, where it equals 1, and grows without bound as σj\sigma_j goes to zero or to infinity. So the penalty pushes the encoder toward a blurry cloud, and the reconstruction term pushes back toward a sharp one.

The reparameterised estimate

The expectation in L\mathcal{L} is estimated by sampling. With ϵ∼N(0,I)\boldsymbol{\epsilon} \sim \mathcal{N}(0, I), set z=μ+σ⊙ϵ\mathbf{z} = \boldsymbol{\mu} + \boldsymbol{\sigma} \odot \boldsymbol{\epsilon}, where ⊙\odot is the element-wise product. One sample gives an unbiased estimate of the reconstruction term, and it is differentiable in μ\boldsymbol{\mu} and σ\boldsymbol{\sigma}. In practice a single sample per data point is enough, which keeps the cost the same as a plain autoencoder.

0.511.5200.511.522.5sigmaKL (nats)
  • KL for mu = 0, as a function of sigma
With mu = 0, the KL penalty is zero at sigma = 1, the prior itself, and rises steeply for very sharp encodings (small sigma).

Worked examples

Example
One latent dimension, from encoder output to loss

An encoder reads one input and outputs μ=0.8\mu = 0.8 and σ=0.5\sigma = 0.5.

  1. Sample noise: ϵ=−0.4\epsilon = -0.4.
  2. Form the latent code: z=0.8+0.5×(−0.4)=0.6z = 0.8 + 0.5 \times (-0.4) = 0.6.
  3. Compute the KL term: σ2=0.25\sigma^2 = 0.25, μ2=0.64\mu^2 = 0.64, and log⁡σ2=log⁡0.25≈−1.3863\log \sigma^2 = \log 0.25 \approx -1.3863.
  4. Plug into the formula: 12(0.64+0.25−1+1.3863)=12(1.2763)≈0.638\frac{1}{2}\left(0.64 + 0.25 - 1 + 1.3863\right) = \frac{1}{2}(1.2763) \approx 0.638 nats.
  5. Suppose the decoder gives the true pixel probability 0.90.9, so the reconstruction term is −log⁡0.9≈0.105-\log 0.9 \approx 0.105.
  6. Add the two terms: 0.105+0.638≈0.7430.105 + 0.638 \approx 0.743 nats for this example.

Interpretation: most of the loss here is the KL penalty. The encoder moved its mean away from zero and narrowed its spread, and the prior pays for both. Training would trade that cost against better reconstructions. The sampled z=0.6z = 0.6 is what the decoder sees, and it is a little off from the mean 0.80.8 because of the noise draw.

Example
Sharp encodings cost more

Keep μ=0\mu = 0 and compare two encoders that differ only in their spread.

  1. Encoder A has σ=1\sigma = 1. Then σ2=1\sigma^2 = 1 and log⁡σ2=0\log \sigma^2 = 0. The KL is 12(0+1−1−0)=0\frac{1}{2}(0 + 1 - 1 - 0) = 0.
  2. Encoder B has σ=0.1\sigma = 0.1. Then σ2=0.01\sigma^2 = 0.01 and log⁡σ2=log⁡0.01≈−4.6052\log \sigma^2 = \log 0.01 \approx -4.6052. The KL is 12(0+0.01−1+4.6052)=12(3.6152)≈1.808\frac{1}{2}(0 + 0.01 - 1 + 4.6052) = \frac{1}{2}(3.6152) \approx 1.808 nats.

Interpretation: encoder B is more precise about where the input lies, so it can reconstruct better. It pays about 1.8 nats of KL for that precision. Whether that trade is worth it depends on how much the decoder gains. A VAE is always choosing this balance, for every latent dimension at once.

Example
Posterior collapse, numerically

Suppose the decoder becomes powerful enough to reconstruct the data without using zz. Then nothing rewards the encoder for carrying information, and the KL term is free to fall.

  1. The encoder outputs μ=0\mu = 0 and σ=1\sigma = 1 for every input.
  2. The KL term is 12(0+1−1−0)=0\frac{1}{2}(0 + 1 - 1 - 0) = 0.
  3. The code zz is pure noise from the prior, carrying no information about xx.

Interpretation: the loss is now only the reconstruction term, which the decoder minimises without help from zz. This is posterior collapse. Common fixes include annealing the KL weight up from zero during early training, or weakening the decoder, as described under tradeoffs below. See the variational lower bound for where the KL term comes from.

Tradeoffs and failure modes

SituationProblemBetter choice
You need sharp, high-fidelity samplesVAE reconstructions and samples are often blurryA GAN, or a diffusion model, or a VAE used only as a compressor
The latent space must be smooth and sampleableA plain autoencoder has holes in its code spaceVAE with the KL term
The decoder is very powerfulPosterior collapse, the latent code is ignoredKL annealing, a weaker decoder, or a more structured latent
The data is discrete, such as tokensGaussian latents and Gaussian decoders fit poorlyA discrete latent such as a vector-quantised VAE
Many latent dimensionsSome dimensions collapse to the prior (KL near 0) and carry no information, so the nominal latent size overstates the real oneCheck per-dimension KL, and shrink the latent or use a hierarchical one

The most common practical surprise is that a VAE reconstructs well but generates blurry samples. The reconstruction term rewards averages over plausible images when the decoder cannot tell which one is correct, and the Gaussian likelihood does not punish blur strongly. The objective is doing what it was asked to do.

History

Diederik Kingma and Max Welling introduced the VAE in the paper Auto-Encoding Variational Bayes, posted in December 2013. Their goal was to make variational inference scale to large datasets. Inference in latent variable models usually needs an expensive per-data-point optimisation. They replaced it with an encoder network that amortises the cost, and they used the reparameterisation trick to train the whole thing with stochastic gradient descent.

Danilo Rezende, Shakir Mohamed and Daan Wierstra published closely related work in 2014, and the two papers together made the approach standard. The VAE caught on for three reasons. It was simple to implement from ordinary autoencoder code. It gave a principled probabilistic model rather than a heuristic one. And its latent space supported interpolation and sampling in ways that plain autoencoders did not. Later work, such as the image autoencoders used in latent diffusion, kept the VAE idea and used it as a learned compressor.

Check yourself

QuestionRecall: what are the two terms in the VAE objective, and what does each one do?Show answer

The first term is the expected log likelihood of the data under the decoder, averaged over samples from the encoder. It rewards codes that reconstruct the input well. The second term is the KL divergence between the encoder distribution and the prior. It penalises encodings that stray from the prior, which keeps the latent space smooth and sampleable. Training maximises the first term and minimises the second, and the balance between them sets how much detail the latent space keeps.

QuestionComputation: an encoder outputs mu = 0.5 and sigma = 1 for one latent dimension. What is the KL penalty for that dimension?Show answer

Here σ2=1\sigma^2 = 1 and log⁡σ2=0\log \sigma^2 = 0. The formula gives 12(μ2+σ2−1−log⁡σ2)=12(0.25+1−1−0)=0.125\frac{1}{2}(\mu^2 + \sigma^2 - 1 - \log \sigma^2) = \frac{1}{2}(0.25 + 1 - 1 - 0) = 0.125 nats. The shift in the mean is the only cost, since the spread already matches the prior.

QuestionWhy: why does the VAE encode each input as a distribution rather than a point, if a point would be simpler?Show answer

A point encoder can place each training input at an isolated location, so the space between training codes is never trained and decodes to nonsense. A distribution forces neighbouring encodings to overlap and cover the prior's region. The KL term pulls every distribution toward the same prior, so the overlap is systematic. The result is a latent space where most points, including ones sampled from the prior, decode to plausible outputs.

QuestionApplied: you train a VAE and find that its KL term falls to nearly zero within the first epoch, and the reconstructions look like the average of the training set. Name the likely cause and a fix you would try first.Show answer

This is posterior collapse. The decoder has learned to produce average-looking outputs that ignore zz, so the encoder has no incentive to carry information, and the KL term goes to zero. A reasonable first fix is KL annealing: start the KL weight at zero and raise it gradually over the first several thousand steps, so the encoder learns to use the latent code before the penalty bites. If that fails, weaken the decoder or check that the reconstruction loss is not overwhelmingly strong relative to the KL term.

Sources