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 be an observed data point and a hidden code with prior . The decoder defines a likelihood , a distribution over data given a code. The encoder is a learned approximation to the true posterior , which is intractable. Both networks are neural networks. and are their parameters.
The objective
The evidence lower bound for one data point is
Training maximises over both networks at once. Equivalently, we minimise the loss . 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, , with latent dimensions. The KL term to a standard Gaussian has a closed form:
Each dimension contributes a penalty for shifting its mean away from zero and for changing its spread away from one. The part is smallest at , where it equals 1, and grows without bound as 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 is estimated by sampling. With , set , where is the element-wise product. One sample gives an unbiased estimate of the reconstruction term, and it is differentiable in and . In practice a single sample per data point is enough, which keeps the cost the same as a plain autoencoder.
- KL for mu = 0, as a function of sigma
Worked examples
An encoder reads one input and outputs and .
- Sample noise: .
- Form the latent code: .
- Compute the KL term: , , and .
- Plug into the formula: nats.
- Suppose the decoder gives the true pixel probability , so the reconstruction term is .
- Add the two terms: 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 is what the decoder sees, and it is a little off from the mean because of the noise draw.
Keep and compare two encoders that differ only in their spread.
- Encoder A has . Then and . The KL is .
- Encoder B has . Then and . The KL is 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.
Suppose the decoder becomes powerful enough to reconstruct the data without using . Then nothing rewards the encoder for carrying information, and the KL term is free to fall.
- The encoder outputs and for every input.
- The KL term is .
- The code is pure noise from the prior, carrying no information about .
Interpretation: the loss is now only the reconstruction term, which the decoder minimises without help from . 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
| Situation | Problem | Better choice |
|---|---|---|
| You need sharp, high-fidelity samples | VAE reconstructions and samples are often blurry | A GAN, or a diffusion model, or a VAE used only as a compressor |
| The latent space must be smooth and sampleable | A plain autoencoder has holes in its code space | VAE with the KL term |
| The decoder is very powerful | Posterior collapse, the latent code is ignored | KL annealing, a weaker decoder, or a more structured latent |
| The data is discrete, such as tokens | Gaussian latents and Gaussian decoders fit poorly | A discrete latent such as a vector-quantised VAE |
| Many latent dimensions | Some dimensions collapse to the prior (KL near 0) and carry no information, so the nominal latent size overstates the real one | Check 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 and . The formula gives 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 , 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
- Kingma, Welling (2013), Auto-Encoding Variational Bayes: arxiv.org/abs/1312.6114
- Doersch (2016), Tutorial on Variational Autoencoders: arxiv.org/abs/1606.05908
- Variational autoencoder (Wikipedia)