Autoencoders & Variational Autoencoders
Compressing to a latent code, and making that code a distribution you can sample.
An autoencoder learns to squeeze data through a narrow code and rebuild it. That makes a compressor, not a generator: nobody knows which codes are valid. The variational autoencoder turns the code into a probability distribution, and one inequality, the evidence lower bound, turns training it into ordinary gradient descent.
What you’ll learn
- Build an autoencoder, explain why a linear one with squared error learns the principal subspace, and why a plain autoencoder's code space cannot be sampled.
- Derive the evidence lower bound and identify its gap.
- Derive the Gaussian KL term in closed form and implement a VAE training step with the reparameterization trick.
- Explain why VAE samples blur, how trades reconstruction against the KL term, and how conditional VAEs model .
Autoencoders: learning by copying
An autoencoder has two parts: an encoder that maps an input to a code , and a decoder that maps it back. In this lesson always denotes a latent variable, not a pre-activation. Both networks are trained together to minimize a reconstruction loss, usually the squared error:
Copying is trivial if the code is as large as the input, so the architecture blocks it. An undercomplete autoencoder makes , a bottleneck; others keep large and penalize the code instead (sparse or contractive autoencoders).
Two caveats keep this honest. The subspace is determined but the coordinates are not: replacing by and by for any invertible matrix leaves unchanged, so the code units are generally mixtures of the principal components, not the components themselves. And with nonlinear encoders and decoders the autoencoder can learn curved low-dimensional structure that no linear projection captures; that is the point of making them deep.
Denoising autoencoders (Vincent et al., 2008) corrupt the input, for example by adding noise or zeroing random pixels, and train the network to output the clean version. The network can no longer copy, so even a wide code must capture structure. The idea returns in force later: for Gaussian noise, the optimal denoiser moves a noisy point along the gradient of the log-density of the noise-blurred data, so learning to denoise is learning that gradient (Vincent, 2011). Diffusion models are built on exactly this.
None of this yields a generator. The encoder maps the training set to some cloud of codes whose shape nobody specified. Decode a code from outside that cloud and the output is meaningless, and there is no rule for drawing codes from inside it.
A latent-variable model and its lower bound
The variational autoencoder (Kingma & Welling, 2014; Rezende, Mohamed & Wierstra, 2014) starts from the generative side. Fix a simple prior over codes, , and let the decoder define a distribution over data given a code, : a Gaussian centered at , or independent Bernoulli pixels with probabilities . Sampling is then trivial: draw , then . Training by maximum likelihood needs the marginal
The fix is amortized variational inference: train an encoder to propose codes that explain , and use it to bound the likelihood from below.
Multiply and divide inside the integral by , which turns the integral into an expectation under the encoder:
The logarithm is concave, so by Jensen's inequality the log of an expectation is at least the expectation of the log:
Group the last two terms into a KL divergence. The result is the evidence lower bound: a reconstruction term minus a regularizer that keeps each input's code distribution close to the prior.
To see exactly what was lost, write , which holds for any , and add and subtract :
The gap is the KL divergence from the encoder to the true posterior, which is never negative. Maximizing over pulls the encoder toward the posterior and tightens the bound; maximizing over raises the likelihood itself (or makes the posterior easier to match).
For one training example, when does the ELBO equal exactly?
- When the encoder's distribution matches the prior,
- When the reconstruction is perfect
- When the encoder's distribution equals the true posterior,
- Never: Jensen's inequality is always strict
Show the answer
C. When the encoder's distribution equals the true posterior,
The gap is , which is zero exactly when the two distributions agree. A diagonal Gaussian encoder usually cannot match a neural decoder's posterior exactly, so in practice a gap remains.
The KL term in closed form
With a diagonal Gaussian encoder and a standard normal prior, the regularizer needs no sampling at all. Both distributions factor over the latent dimensions, so the KL is a sum of one-dimensional terms. Derive one of them:
Write the KL as an expectation under of the log-ratio of the two densities. The terms cancel:
Under , and :
Collect the terms and sum over the dimensions:
Each term is zero only at , . The part pulls codes toward the origin; , minimized at , stops the encoder from shrinking its noise to zero, which would turn the VAE back into a plain autoencoder with isolated points in code space.
One latent dimension has encoder mean and standard deviation . What is its KL divergence from , in nats?
Show the answer
0.82 nats
nats. Most of it comes from the narrow spread: . The same dimension with would cost only .
The KL term has an information-theoretic reading: averaged over the data, it upper-bounds how many nats of information the code carries about the input. Every nat the encoder spends to make a code more specific is charged against the bound, and it pays only if the decoder's reconstruction improves by more. That bargain explains both the strengths and the failures you will meet next.
The reparameterization trick and a training step
The reconstruction term has no closed form, so it is estimated by sampling, usually with a single per example. But a sample drawn from is not a differentiable function of : how should the gradient reach the encoder? The reparameterization trick moves the randomness into a parameter-free variable:
The decoder's likelihood decides the reconstruction loss. Independent Bernoulli pixels give the binary cross-entropy. A Gaussian with fixed variance gives : squared error, with setting its exchange rate against the KL term. Here is a complete training step for binarized digits:
import torch
import torch.nn as nn
import torch.nn.functional as F
class VAE(nn.Module):
def __init__(self, d=784, h=400, k=20):
super().__init__()
self.enc = nn.Sequential(nn.Linear(d, h), nn.ReLU(), nn.Linear(h, 2 * k))
self.dec = nn.Sequential(nn.Linear(k, h), nn.ReLU(), nn.Linear(h, d))
def forward(self, x):
mu, logvar = self.enc(x).chunk(2, dim=-1)
z = mu + torch.exp(0.5 * logvar) * torch.randn_like(mu) # reparameterization
return self.dec(z), mu, logvar # decoder outputs logits
def neg_elbo(x, logits, mu, logvar):
rec = F.binary_cross_entropy_with_logits(logits, x, reduction='sum') # -log p(x|z)
kl = 0.5 * (mu.pow(2) + logvar.exp() - logvar - 1).sum() # closed form
return (rec + kl) / x.shape[0]
model = VAE()
opt = torch.optim.Adam(model.parameters(), lr=1e-3)
for x in loader: # x: (B, 784) binarized pixels in {0, 1}
loss = neg_elbo(x, *model(x))
opt.zero_grad(); loss.backward(); opt.step()The encoder predicts rather than , so any real output is a valid variance. To generate, skip the encoder: torch.sigmoid(model.dec(torch.randn(16, 20))) gives 16 grids of pixel probabilities.
Think first The loss above uses one sample of per example. Is the gradient biased?
No. For each fixed the gradient of is exact, and averaging over gives the true gradient, so one sample is an unbiased, if noisy, estimate. The mini-batch already averages over many examples, which is why one sample per example is enough in practice.
Blur, β and conditions
Why samples blur. With a Gaussian decoder, the reconstruction term is a squared error, which is minimized by the conditional mean: the decoder outputs the average of all images consistent with a code. Because the encoder is noisy, nearby codes from many slightly different images get mixed, and their average is soft. Two further effects add to it. Sampling uses the prior , but the decoder was trained on codes from the aggregate posterior , which never matches the prior exactly, so some prior samples land in regions the decoder rarely saw. And the per-pixel noise of is usually dropped when sampling, since it would only add static.
The β trade-off. Weighting the regularizer by gives the objective . Larger squeezes the information in the code, giving blurrier reconstructions but codes closer to the prior; smaller gives sharper reconstructions and a less regular code space. With a Gaussian decoder, is equivalent to rescaling the fixed decoder variance . The β-VAE (Higgins et al., 2017) chose and found that on simple images varying in a few independent factors (position, scale, rotation), individual code units tended to align with single factors: "disentanglement". Locatello et al. (2019) later proved that without inductive biases or some supervision, such disentanglement is not identifiable from the data alone.
Conditional VAEs. To model , for a class or for a whole input image when the target is, say, its segmentation, give to every part of the model: an encoder , a decoder and possibly a learned prior . The same derivation bounds by . Sohn, Lee & Yan (2015) used this for structured prediction: different samples of give different plausible outputs for one input, where a deterministic network would average them.
You raise from to in a VAE trained on faces. What do you expect?
- Sharper reconstructions, because the regularizer is stronger
- Codes that carry less information about each face, blurrier reconstructions, and per-input code distributions closer to the prior
- No change, because only rescales the loss
- Posterior collapse is now impossible
Show the answer
B. Codes that carry less information about each face, blurrier reconstructions, and per-input code distributions closer to the prior
A larger weight on the KL makes every nat of information in the code more expensive, so the encoder keeps less detail and the decoder reconstructs a blurrier average. The flip side is a code space that matches the prior more closely.
Key takeaways
- An autoencoder compresses to a code and reconstructs it; with linear maps and squared error it learns the principal subspace (Baldi & Hornik, 1989). Its code space has no distribution, so it cannot generate.
- A VAE defines and maximizes the ELBO , whose gap is .
- For diagonal Gaussians the regularizer is , and the reparameterization makes the reconstruction term differentiable.
- Gaussian decoders output conditional means, so samples blur; trades reconstruction against the KL term, and expressive decoders can make ignoring optimal (posterior collapse).
- Conditional VAEs bound with an encoder, decoder and prior that all see , giving several plausible outputs for one input.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
You train the same linear autoencoder, with a 3-unit code and squared error, twice from different random initializations. The data are centered and their covariance has distinct positive eigenvalues, and both runs reach the global minimum. How do the two runs' codes and compare?
- They are identical, because the global minimum is unique
- They span the same principal subspace, and one is an invertible linear function of the other:
- They span unrelated three-dimensional subspaces, one per initialization
- They agree up to reordering the code units and flipping their signs
Show the answer
B. They span the same principal subspace, and one is an invertible linear function of the other:
Both runs have equal to the projection onto the top-3 principal subspace, so each for an orthonormal basis of that subspace and some invertible . Then : the same information, in a basis that depends on the run.
Which identity holds for any encoder ?
Show the answer
D.
The likelihood exceeds the ELBO by the KL from the encoder to the true posterior. Because a KL is never negative, is a lower bound, tight exactly when is the posterior.
Why do VAEs write with instead of sampling directly?
- So that the randomness no longer depends on , and backpropagation can carry the reconstruction gradient through and to the encoder
- To make the KL term computable in closed form
- To make sampling faster at test time
- To make the code discrete
Show the answer
A. So that the randomness no longer depends on , and backpropagation can carry the reconstruction gradient through and to the encoder
A sample drawn from is not a differentiable function of . Moving the randomness into makes a deterministic, differentiable function of and , giving low-variance gradient estimates of the reconstruction term.
A VAE with a Gaussian decoder of fixed variance produces blurry samples. Which explanation is the main one?
- Adam's gradient noise smears the decoder's weights
- The prior is too narrow to hold many images
- The latent space has too many dimensions
- The squared-error reconstruction term is minimized by the conditional mean, so the decoder outputs an average of the images consistent with a noisy code
Show the answer
D. The squared-error reconstruction term is minimized by the conditional mean, so the decoder outputs an average of the images consistent with a noisy code
Under a Gaussian likelihood the best prediction is the mean, and the mean of several slightly different images is soft. Sharper models change the likelihood or the decoder (autoregressive or adversarial decoders, perceptual losses) or add latent structure.
Go deeper
- Learned Tokenizers for Images & Audio · VQ-VAE, VQGAN, residual and finite scalar quantization.
- Very Deep Hierarchical VAEs · Latent hierarchies, NVAE and why very deep VAEs rival autoregressive models.
- Latent Spaces for Generative Models · Autoencoders built for diffusion: compression, the reconstruction–generation trade-off and semantic latents.
Further reading
- D. P. Kingma & M. Welling, "Auto-encoding variational Bayes," ICLR (2014).
- D. J. Rezende, S. Mohamed & D. Wierstra, "Stochastic backpropagation and approximate inference in deep generative models," ICML (2014).
- D. P. Kingma & M. Welling, "An introduction to variational autoencoders," Foundations and Trends in Machine Learning (2019).
- S. J. D. Prince, Understanding Deep Learning, ch. 17 "Variational autoencoders" (MIT Press, 2023).