Level 3 In-Depth AI · Generative AI
Variational Autoencoders
A variational autoencoder (VAE) is an autoencoder whose encoder outputs a small cloud of possible codes instead of a single point, and which keeps all those clouds close to a standard bell curve. The latent space becomes smooth, so you can sample a random code and decode it into a new example.
- Level
- ●●●●● Intermediate
- Reading
- 13 min
- To learn it well
- 1 hour to read, an hour to practise
- Builds on
- 18 concepts →
- Quiz
- 5 questions ↓
This leads to
Latent Diffusion and Stable DiffusionThe full path from zero — 18 concepts before this one
- What Is AI?
- Vectors
- Derivatives and Slopes
- Probability Basics
- How Machines Learn
- Partial Derivatives and Gradients
- Matrices and Matrix Multiplication
- Probability Distributions
- Supervised, Unsupervised and Reinforcement Learning
- Gradient Descent
- Entropy, Cross-Entropy and KL Divergence
- Supervised Learning
- Linear Regression
- The Perceptron
- Logistic Regression
- Neural Networks
- Autoencoders
- What Generative Models Do
- Variational Autoencoders
Read them roughly in this order. See it on the concept map →
Why it matters
The Autoencoders chapter ended with a problem. An ordinary autoencoder compresses data into codes very well, but you can't generate with it. Its codes sit in scattered clumps, and a random code usually decodes to nonsense.
The variational autoencoder (VAE) fixes this with two small changes. The result is a real generative model: draw a random code from a standard bell curve, decode it, and you get a new, plausible example. You also get a smooth latent space, where walking from one code to another morphs one example gradually into the other.
VAEs matter today for three reasons:
- They are inside most image and video generators. Stable Diffusion, FLUX, Sora-style video models and many others first compress images with a VAE-style autoencoder and then run diffusion on the compressed codes. See Latent Diffusion and Stable Diffusion.
- Their mathematics, the ELBO, recurs everywhere. Diffusion models are trained with a version of the same bound (Diffusion Models).
- They are a clean, fast model for structured data such as molecules, for anomaly detection, and for learning compact representations.
The intuition
Go back to the two players who invent a short code to describe drawings. In a plain autoencoder, the describer gives one exact code, say , for each drawing. The drawer learns to handle exactly those codes and nothing else. The space between them is unexplored territory.
A VAE changes the rules in two ways.
- Fuzzy codes. The describer doesn't give an exact point. It gives a small region: "somewhere around , give or take 0.2". During training, a random point is picked from that region and passed to the drawer. The drawer must therefore draw well for every code near the centre, not just the centre itself. Nearby codes now have to mean similar things.
- Everyone stays near the middle. A penalty pulls every region towards a fixed reference cloud, the standard bell curve centred at zero. The describer can't hide codes in far corners or leave big empty gaps. The regions of all the training examples pack together and overlap to fill the reference cloud.
After training, the whole reference cloud is covered with codes the drawer understands. So to generate, you pick a random point from the bell curve, hand it to the drawer, and get a plausible new drawing.
Key idea A VAE's encoder outputs a distribution (a mean and a spread) instead of a single code, and a KL penalty keeps those distributions close to a standard Gaussian. The latent space becomes smooth and gap-free, so sampling a random Gaussian code and decoding it generates new data.
How it works
The three pieces
A VAE has three ingredients. Each is a probability distribution.
- The prior . This is the reference cloud: a standard Gaussian in dimensions, mean zero and spread one in every direction. is the identity matrix, which here means the dimensions are independent. "Prior" means what we assume about codes before seeing any data.
- The encoder . A neural network with weights ("phi") reads an input and outputs two vectors of length : a centre ("mu") and a spread ("sigma"). Together they describe the fuzzy region of codes for that input.
- The decoder . A network with weights turns a code back into an example. In practice it outputs pixel values, and "probability of given " just means how well those values match the real ones.
The loss: reconstruction plus KL
The VAE loss has two terms, matching the two rules in the intuition.
The reconstruction term asks: if I sample a code from the encoder's region and decode it, how well do I get the input back? It is the same reconstruction error as in a plain autoencoder (squared error or binary cross-entropy), averaged over the random choice of code.
The KL term measures how far the encoder's cloud is from the prior. It uses the KL divergence, a measure of how different two distributions are. It is zero when they are identical and grows as they differ. The Entropy, Cross-Entropy and KL Divergence chapter defines it. For a Gaussian encoder and a standard Gaussian prior it has a simple closed form, summed over the latent dimensions:
Read it term by term for one dimension :
- penalises a centre far from zero, which keeps codes near the middle.
- is zero when and positive otherwise. It penalises clouds that are too tight (tiny means a near-exact code, as in a plain autoencoder) and clouds that are too wide.
Worked example. Suppose the encoder gives and in one dimension. Then , and , so the KL is . With and , the cloud is the prior, and the KL is .
The two terms pull in opposite directions. Reconstruction wants each input to have its own sharp, distinct code. KL wants every code to look like the same bell curve. The balance between them is what produces a latent space that is both informative and smooth.
Where the loss comes from: the ELBO
Why these two terms? A VAE is meant to be a likelihood-based model. We would like to maximise , the log-probability of each training example. That would require averaging the decoder over every possible code, which can't be computed exactly. Kingma and Welling showed that the two-term quantity is a lower bound on it:
The right-hand side is the ELBO, the evidence lower bound ("evidence" is an old name for ). means "the average over codes drawn from the encoder's cloud". Raising the ELBO pushes up the true log-likelihood, because the ELBO sits underneath it. The VAE loss is the negative ELBO: reconstruction error plus KL. The gap between the two sides is exactly how far the encoder's cloud is from the true best cloud for that input. A better encoder gives a tighter bound.
The word "variational" comes from variational inference, the statistical method of approximating an intractable distribution with a simpler one (here, a Gaussian) and optimising the fit.
The reparameterisation trick
One technical obstacle remains. Training needs gradients, and the code is sampled at random. You can't backpropagate through a coin flip: how does the loss change if you nudge , when is a random draw?
The reparameterisation trick moves the randomness out of the way. Instead of "draw from ", write:
Here ("epsilon") is plain standard noise, drawn fresh each time, and means element-by-element multiplication. Both forms give exactly the same distribution of . But now is an ordinary differentiable function of and , with treated as a fixed input. Backpropagation goes straight through. Networks usually output (the "log-variance") rather than , because it can be any real number, while must be positive.
Generating
After training, throw away the encoder. Draw from and decode it. Because the KL term packed the training codes into that cloud, most random draws land somewhere the decoder knows.
Real numbers from the code below
A VAE with a 2-number latent space, trained on all 1,797 digits for 2,000 steps, reports per image:
| Step | Reconstruction | KL | Loss (negative ELBO) |
|---|---|---|---|
| 0 | 45.87 | 0.02 | 45.90 |
| 500 | 23.15 | 1.97 | 25.12 |
| 2000 | 21.43 | 2.68 | 24.11 |
At the start the encoder outputs roughly the prior, so the KL is near zero and reconstruction is terrible. As training goes on, the encoder "spends" about 2.7 units of KL to carry information about each digit, and the reconstruction error halves. The average spread the encoder learns is and in the two dimensions. Each digit gets a small cloud, much tighter than the prior's spread of 1, but not a single point. Class centres come out at, for instance, for zeros and for sevens, as in the picture.
In code
The full VAE in PyTorch, trained on scikit-learn's 8×8 digits. It runs in about 10 seconds on a laptop CPU.
import torch, torch.nn as nn, torch.nn.functional as F
from sklearn.datasets import load_digits
torch.manual_seed(0)
digits = load_digits()
X = torch.tensor(digits.data, dtype=torch.float32) / 16.0 # 1797 x 64, values in [0, 1]
class VAE(nn.Module):
def __init__(self, latent_dim=2):
super().__init__()
self.enc = nn.Sequential(nn.Linear(64, 128), nn.ReLU())
self.mu, self.logvar = nn.Linear(128, latent_dim), nn.Linear(128, latent_dim)
self.dec = nn.Sequential(nn.Linear(latent_dim, 128), nn.ReLU(), nn.Linear(128, 64))
def forward(self, x):
h = self.enc(x)
mu, logvar = self.mu(h), self.logvar(h)
z = mu + torch.exp(0.5 * logvar) * torch.randn_like(mu) # reparameterisation trick
return self.dec(z), mu, logvar # decoder outputs logits
model = VAE()
opt = torch.optim.Adam(model.parameters(), lr=1e-3)
for epoch in range(2001):
logits, mu, logvar = model(X)
recon = F.binary_cross_entropy_with_logits(logits, X, reduction="sum") / len(X)
kl = -0.5 * torch.sum(1 + logvar - mu**2 - logvar.exp()) / len(X)
loss = recon + kl # negative ELBO
opt.zero_grad(); loss.backward(); opt.step()
if epoch % 500 == 0:
print(f"epoch {epoch:4d} recon {recon.item():6.2f} KL {kl.item():5.2f} loss {loss.item():6.2f}")
with torch.no_grad(): # generate: decode random z ~ N(0, I)
samples = torch.sigmoid(model.dec(torch.randn(3, 2)))
print((samples[0].reshape(8, 8) * 16).round().int())
# epoch 0 recon 45.87 KL 0.02 loss 45.90
# epoch 500 recon 23.15 KL 1.97 loss 25.12
# epoch 1000 recon 22.30 KL 2.31 loss 24.62
# epoch 1500 recon 21.92 KL 2.44 loss 24.36
# epoch 2000 recon 21.43 KL 2.68 loss 24.11
# tensor([[ 0, 0, 6, 13, 13, 7, 1, 0], <- a brand-new "8", drawn from
# [ 0, 2, 12, 12, 12, 11, 2, 0], a random code
# [ 0, 3, 10, 7, 9, 9, 1, 0],
# [ 0, 2, 8, 12, 14, 6, 0, 0],
# [ 0, 1, 6, 13, 13, 6, 0, 0],
# [ 0, 1, 7, 7, 9, 10, 1, 0],
# [ 0, 1, 9, 9, 11, 11, 2, 0],
# [ 0, 0, 6, 13, 13, 6, 1, 0]], dtype=torch.int32)
The KL line is the closed-form formula above, rewritten with : . Compared with the plain autoencoder, only three things changed: two output heads (mu and logvar), the sampling line, and the KL term.
Common pitfalls
- Blurry samples. VAE samples of natural images are noticeably blurry. The Gaussian decoder and the averaging over fuzzy codes both reward "safe" average outputs. That is why VAEs are now used mostly as compressors, with a diffusion model or a GAN-style loss on top for sharpness.
- Posterior collapse. With a powerful decoder, such as an autoregressive one that can model the data by itself, the model may ignore the code entirely. It sets every to 0 and to 1, the KL drops to zero, and the latent space carries no information. Watch the KL term. If it sits near zero, the code is unused. Common remedies are KL annealing (start with KL weight 0 and ramp it up) and weaker decoders.
- Wrong loss scale. If you average the reconstruction over pixels but sum the KL over dimensions, or the reverse, the balance silently changes. Be consistent, as the code above is: both are summed per image, then averaged over images.
- Predicting directly. A network output can be negative. Predict and exponentiate.
Watch out Don't read the VAE loss as a measure of image quality. A lower negative ELBO means a better likelihood bound, which doesn't always mean sharper or more realistic samples. Always look at samples too.
Where it leads
- β-VAE multiplies the KL term by a weight . With , the latent dimensions tend to separate into independent factors, such as slant and thickness. This is called "disentanglement". With much less than 1, the model behaves more like a plain autoencoder.
- VQ-VAE replaces the Gaussian codes with discrete entries from a learned codebook. That gives sequences of tokens that a Transformer can model. Image tokenizers and neural audio codecs descend from it (Music and Voice Generation).
- The Stable Diffusion autoencoder is a convolutional VAE with a very small KL weight, trained with extra perceptual and adversarial losses for sharpness. It turns a 512×512×3 image into a 64×64×4 latent. Diffusion then generates in that latent space (Latent Diffusion and Stable Diffusion).
- Hierarchical VAEs (NVAE, VDVAE) stack many latent layers and produce much sharper images.
- The ELBO comes back in Diffusion Models. A diffusion model can be seen as a very deep hierarchical VAE whose "encoder" is fixed noise addition.
A bit of history
Diederik Kingma and Max Welling posted "Auto-Encoding Variational Bayes" in December 2013. Rezende, Mohamed and Wierstra at DeepMind independently published the same idea a few weeks later, in early 2014, under the name "stochastic backpropagation". The reparameterisation trick was the key that made variational inference trainable with ordinary gradient descent on large neural networks. Variational inference itself had been developed in the 1990s, by Jordan, Ghahramani, Jaakkola and others.
VAEs were soon overshadowed in image quality by Generative Adversarial Networks, and later by Diffusion Models. But they never went away. β-VAE (2017) launched the study of disentangled representations, and VQ-VAE (2017) became the basis of discrete tokenizers. The 2021 latent diffusion paper put a VAE at the front of Stable Diffusion. In 2019, Kingma and Welling wrote a long tutorial, An Introduction to Variational Autoencoders, that remains the best deep dive.
Try it
- Set the KL weight to 0 (
loss = recon) and retrain. Decode a grid of codes as in the picture. What happens to the regions between digit classes, and why?- Set the KL weight to 5 (
loss = recon + 5 * kl). What happens to the KL value, the reconstruction error and the samples?- Encode one "0" and one "1", take their means and , and decode 6 evenly spaced points on the line between them. Print each as an 8×8 grid.
Hint for 2: a large KL weight squeezes all clouds onto the prior. Watch for signs of posterior collapse.
Learn more
Hand-picked courses, books, videos and tutorials for going deeper. See all resources →
From Autoencoder to Beta-VAE
A clear tour of autoencoders, denoising and sparse autoencoders, VAEs, beta-VAE and VQ-VAE, with the derivations.
An Introduction to Variational Autoencoders
A long, readable tutorial on VAEs by their inventors, from the ELBO to modern extensions.
Understanding Deep Learning
A modern, beautifully illustrated textbook covering everything from basics to Transformers and diffusion, with notebooks.
CS236: Deep Generative Models (course notes)
Stanford's course on generative models: autoregressive models, VAEs, normalizing flows, GANs and energy-based models, with free lecture notes.
Auto-Encoding Variational Bayes
Introduced the variational autoencoder and the reparameterisation trick.
Neural Discrete Representation Learning (VQ-VAE)
An autoencoder whose latent codes are entries from a learned codebook: the root of image and audio tokenizers.
Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/generative/vae.md