◆ AI All-in-One

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
↗ Plan a path here

Read first

AutoencodersEntropy, Cross-Entropy and KL DivergenceWhat Generative Models Do

This leads to

Latent Diffusion and Stable Diffusion
The full path from zero — 18 concepts before this one
  1. What Is AI?
  2. Vectors
  3. Derivatives and Slopes
  4. Probability Basics
  5. How Machines Learn
  6. Partial Derivatives and Gradients
  7. Matrices and Matrix Multiplication
  8. Probability Distributions
  9. Supervised, Unsupervised and Reinforcement Learning
  10. Gradient Descent
  11. Entropy, Cross-Entropy and KL Divergence
  12. Supervised Learning
  13. Linear Regression
  14. The Perceptron
  15. Logistic Regression
  16. Neural Networks
  17. Autoencoders
  18. What Generative Models Do
  19. 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 (0.31,−1.72)(0.31, -1.72), 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.

  1. Fuzzy codes. The describer doesn't give an exact point. It gives a small region: "somewhere around (0.3,−1.7)(0.3, -1.7), 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.
  2. 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.

0 1 2 3 4 5 6 7 8 9 Where the encoder puts each digit mean μ of the code for 900 digits; big numeral = class centre What the decoder draws decode a 6×6 grid of codes from z = (−2, −2) to (2, 2) z₁ → z₂ ↑ dashed circles: 1 and 2 standard deviations of the prior N(0, I) every code decodes to something digit-like, and neighbouring codes give similar digits
Fig. 1 The 2-D latent space of a VAE trained on handwritten digits (the code below). Left: where the encoder places 900 digits. Each digit class forms its own region, and the regions pack together inside the standard bell curve. Right: decoding a regular grid of codes. Every code becomes a digit-like image, and digits morph smoothly into their neighbours. The 4s at the top left and the 0s at the bottom left match where those classes sit in the left panel.

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.

  1. The prior p(z)=N(0,I)p(\mathbf{z}) = \mathcal{N}(\mathbf{0}, \mathbf{I}). This is the reference cloud: a standard Gaussian in kk dimensions, mean zero and spread one in every direction. I\mathbf{I} is the identity matrix, which here means the dimensions are independent. "Prior" means what we assume about codes before seeing any data.
  2. The encoder qϕ(z∣x)=N ⁣(μ,diag⁡(σ2))q_\phi(\mathbf{z} \mid \mathbf{x}) = \mathcal{N}\!\left(\boldsymbol{\mu}, \operatorname{diag}(\boldsymbol{\sigma}^2)\right). A neural network with weights ϕ\phi ("phi") reads an input x\mathbf{x} and outputs two vectors of length kk: a centre μ\boldsymbol{\mu} ("mu") and a spread σ\boldsymbol{\sigma} ("sigma"). Together they describe the fuzzy region of codes for that input.
  3. The decoder pθ(x∣z)p_\theta(\mathbf{x} \mid \mathbf{z}). A network with weights θ\theta turns a code back into an example. In practice it outputs pixel values, and "probability of x\mathbf{x} given z\mathbf{z}" just means how well those values match the real ones.
xinput x̂reconstruction Encoder Decoder μσ z = μ + σ · ε ε ~ N(0, I)fresh random noise KL losskeep N(μ, σ²)close to N(0, I) Reconstruction loss how badly x̂ misses x Total loss = reconstruction + KL (the negative ELBO). The randomness enters only through ε, so gradients can flow back through μ and σ into the encoder: the reparameterisation trick.
Fig. 2 A VAE. The encoder produces a mean μ and spread σ. A code is formed as z = μ + σ·ε, using fresh random noise ε, then decoded. Two losses train it: reconstruction (does x̂ match x?) and KL (is the encoder's cloud close to the standard Gaussian?).

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 kk latent dimensions:

DKL(qϕ(z∣x) ∥ p(z))=12∑j=1k(μj2+σj2−1−log⁡σj2)D_{\mathrm{KL}}\big(q_\phi(\mathbf{z}\mid\mathbf{x}) \,\|\, p(\mathbf{z})\big) = \frac{1}{2} \sum_{j=1}^{k} \left( \mu_j^2 + \sigma_j^2 - 1 - \log \sigma_j^2 \right)

Read it term by term for one dimension jj:

  • μj2\mu_j^2 penalises a centre far from zero, which keeps codes near the middle.
  • σj2−1−log⁡σj2\sigma_j^2 - 1 - \log \sigma_j^2 is zero when σj=1\sigma_j = 1 and positive otherwise. It penalises clouds that are too tight (tiny σ\sigma means a near-exact code, as in a plain autoencoder) and clouds that are too wide.

Worked example. Suppose the encoder gives μ=1\mu = 1 and σ=0.5\sigma = 0.5 in one dimension. Then μ2=1\mu^2 = 1, σ2=0.25\sigma^2 = 0.25 and log⁡0.25=−1.386\log 0.25 = -1.386, so the KL is 12(1+0.25−1+1.386)=0.818\tfrac{1}{2}(1 + 0.25 - 1 + 1.386) = 0.818. With μ=0\mu = 0 and σ=1\sigma = 1, the cloud is the prior, and the KL is 12(0+1−1−0)=0\tfrac{1}{2}(0 + 1 - 1 - 0) = 0.

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 log⁡pθ(x)\log p_\theta(\mathbf{x}), 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:

log⁡pθ(x)  ≥  Ez∼qϕ(z∣x)[log⁡pθ(x∣z)]⏟reconstruction  −  DKL(qϕ(z∣x) ∥ p(z))⏟KL\log p_\theta(\mathbf{x}) \;\ge\; \underbrace{\mathbb{E}_{\mathbf{z} \sim q_\phi(\mathbf{z}\mid\mathbf{x})}\big[\log p_\theta(\mathbf{x} \mid \mathbf{z})\big]}_{\text{reconstruction}} \;-\; \underbrace{D_{\mathrm{KL}}\big(q_\phi(\mathbf{z}\mid\mathbf{x}) \,\|\, p(\mathbf{z})\big)}_{\text{KL}}

The right-hand side is the ELBO, the evidence lower bound ("evidence" is an old name for log⁡p(x)\log p(\mathbf{x})). Ez∼q[⋯ ]\mathbb{E}_{\mathbf{z} \sim q}[\cdots] 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 μ\mu, when z\mathbf{z} is a random draw?

The reparameterisation trick moves the randomness out of the way. Instead of "draw z\mathbf{z} from N(μ,σ2)\mathcal{N}(\boldsymbol{\mu}, \boldsymbol{\sigma}^2)", write:

z=μ+σ⊙ϵ,ϵ∼N(0,I)\mathbf{z} = \boldsymbol{\mu} + \boldsymbol{\sigma} \odot \boldsymbol{\epsilon}, \qquad \boldsymbol{\epsilon} \sim \mathcal{N}(\mathbf{0}, \mathbf{I})

Here ϵ\boldsymbol{\epsilon} ("epsilon") is plain standard noise, drawn fresh each time, and ⊙\odot means element-by-element multiplication. Both forms give exactly the same distribution of z\mathbf{z}. But now z\mathbf{z} is an ordinary differentiable function of μ\boldsymbol{\mu} and σ\boldsymbol{\sigma}, with ϵ\boldsymbol{\epsilon} treated as a fixed input. Backpropagation goes straight through. Networks usually output log⁡σ2\log \sigma^2 (the "log-variance") rather than σ\sigma, because it can be any real number, while σ\sigma must be positive.

Generating

After training, throw away the encoder. Draw z\mathbf{z} from N(0,I)\mathcal{N}(\mathbf{0}, \mathbf{I}) 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 σ≈0.27\sigma \approx 0.27 and 0.300.30 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, (−1.67,−0.57)(-1.67, -0.57) for zeros and (0.95,1.44)(0.95, 1.44) 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 log⁡σ2\log\sigma^2: −12∑(1+log⁡σ2−μ2−σ2)-\tfrac{1}{2}\sum(1 + \log\sigma^2 - \mu^2 - \sigma^2). 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 μ\boldsymbol{\mu} to 0 and σ\boldsymbol{\sigma} 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 σ\sigma directly. A network output can be negative. Predict log⁡σ2\log\sigma^2 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 β\beta. With β>1\beta > 1, the latent dimensions tend to separate into independent factors, such as slant and thickness. This is called "disentanglement". With β\beta 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

  1. 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?
  2. Set the KL weight to 5 (loss = recon + 5 * kl). What happens to the KL value, the reconstruction error and the samples?
  3. Encode one "0" and one "1", take their means μ0\boldsymbol{\mu}_0 and μ1\boldsymbol{\mu}_1, 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.

Check your understanding

5 quick questions. Pick an answer to see whether you were right and why. Your best score is saved on this device.

  1. In one latent dimension a VAE's encoder outputs μ = 0 and σ = 1. What is the KL term for that dimension?

  2. During training you notice the KL term stays near zero while reconstruction stays poor. What is the most likely problem?

  3. Why does a VAE write z = μ + σ·ε instead of drawing z directly from N(μ, σ²)?

  4. You set the KL weight to 0 and retrain a VAE, then decode a grid of codes. What do you expect?

  5. Your VAE's loss (negative ELBO) dropped a lot, but samples still look blurry. How should you read this?

Finished this chapter?

Learn more

Hand-picked courses, books, videos and tutorials for going deeper. See all resources →

Article

From Autoencoder to Beta-VAE

Lilian Weng · 2018 · Intermediate · Free

A clear tour of autoencoders, denoising and sparse autoencoders, VAEs, beta-VAE and VQ-VAE, with the derivations.

Book

Understanding Deep Learning

Simon J. D. Prince · 2023 · Intermediate · Free

A modern, beautifully illustrated textbook covering everything from basics to Transformers and diffusion, with notebooks.

Course

CS236: Deep Generative Models (course notes)

Stefano Ermon & Aditya Grover (Stanford) · Intermediate · Free

Stanford's course on generative models: autoregressive models, VAEs, normalizing flows, GANs and energy-based models, with free lecture notes.

Paper

Auto-Encoding Variational Bayes

Kingma & Welling · 2013 · Advanced · Free

Introduced the variational autoencoder and the reparameterisation trick.

Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/generative/vae.md