8.1Autoencoders, VAEs & latent space
Squeeze images through a bottleneck and you get a compressed "latent space". Make that space smooth and you can sample new images from it, which is why every Stable Diffusion run starts and ends with a VAE.
Why compress before you create?
Welcome to Part 8, where models stop reading images and start making them. Before we get to the famous generators, we need the idea that sits underneath nearly all of them: the latent spaceLatent spaceA compressed internal representation space learned by a model, where nearby points represent similar things..
A 256×256 color photo is 196,608 numbers. But photos of faces don’t use that space freely. Change pixels at random and you get noise, not another face. Real faces occupy a thin, structured region of pixel space, and the factors that actually vary are few: pose, lighting, expression, age, hair. If a model could find coordinates for those factors, generating a new face would mean picking a new set of coordinates, and editing a face would mean nudging one.
An autoencoderAutoencoderA network trained to reproduce its input after squeezing it through a narrow bottleneck: an encoder compresses, a decoder reconstructs. is the simplest machine for finding such coordinates. And the variational autoencoder, its probabilistic upgrade, is still doing quiet but essential work inside today’s image and video generators.
Imagine you have to describe a face to a sketch artist over a bad phone line, using only two numbers. Through practice, the two of you agree on a code: the first number means “how cheerful”, the second “how round”. You are the encoder, the two numbers are the latent code, and the artist is the decoder. The narrow phone line is the bottleneck, and how close the sketch is to the real face is the reconstruction loss.
Now someone hands the artist two numbers you never used together. If your code was sloppy, with “cheerful” faces all crammed around 7 and “grumpy” ones around −9 and nothing in between, the artist has no idea what (0, 0) means and draws nonsense. A VAE is the rule that forces you to use the codes evenly and smoothly, so every pair of numbers means some sensible face.
Encoder, bottleneck, decoder
An autoencoder is two networks trained together:
- The encoder maps an input (say, an image) to a short vector , the latent code.
- The decoder maps the code back to an image .
- The training loss is just reconstruction error, for example the mean squared difference , minimized with ordinary gradient descentGradient descentRepeatedly nudging the parameters a small step opposite the gradient, so the loss goes downhill..
Without a constraint, the network could just copy the input. The bottleneck prevents that: has far fewer dimensions than , so the encoder must keep what matters and throw away what’s predictable. A linear autoencoder with squared error learns the same subspace as principal component analysis; deep, nonlinear ones can learn curved, much more efficient coordinates. Hinton and Salakhutdinov’s 2006 Science paper showed deep autoencoders compressing images far better than PCA.
This makes autoencoders excellent at compression and representation. But try to use the decoder as a generator (pick a random , decode it) and things go wrong.
The hole problem
Nothing in the reconstruction loss cares about the parts of latent space that no training example maps to. The encoder is free to put cheerful faces at one corner and grumpy faces at another, with wide empty gulfs between. Points in those gulfs were never decoded during training, so the decoder’s output there is unconstrained, and usually garbage. Random sampling lands in a gulf most of the time.
The decoder here is a hand-built stand-in: it averages the training faces whose encodings could have produced z. In the plain autoencoder, where no encoding ever landed, it has nothing to go on, so we show the arbitrary output a real decoder tends to produce there.
Things to try:
- Plain autoencoder, drag through the middle. Near a cluster you get a clean face of that type. In the empty center, the decoder produces junk. The interpolation strip from A to B passes through the gulf, so its middle frames are broken.
- Press “z ~ N(0, I)” a few times. In the autoencoder, random samples land in holes. Switch to VAE and repeat: every sample is a plausible face.
- VAE, interpolate. The strip now morphs smoothly: cheerful → something in between → sleepy. Latent arithmetic like this is why people describe latent spaces as “meaningful”.
- Raise β. The shaded circles (each encoding’s uncertainty) grow, the clusters squeeze toward the origin, the KL readout falls, and the reconstruction error rises: faces get more average. Lower β and the gaps start to reopen. That is the β trade-off.
The decoder in this demo is a hand-built stand-in (a weighted average of training faces), not a trained network, and its junk faces are a cartoon. But the geometry is faithful: training signal only reaches latent points that encodings can produce, and the VAE’s job is to spread that signal everywhere.
The variational autoencoder
Kingma and Welling’s Auto-Encoding Variational Bayes (2013), and independently Rezende, Mohamed and Wierstra (2014), fixed the hole problem with two changes.
Change 1: encode to a distribution, not a point. The encoder outputs a mean and a standard deviation for each latent dimension. During training we sample from and decode that. Since the decoder must reconstruct from any in a small cloud around , its training covers regions, not just points. Neighboring clouds overlap, and the decoder learns to blend smoothly between them.
Change 2: keep the clouds near a standard Gaussian. Without a penalty, the encoder would shrink to zero (back to points) and spread the means far apart. So the loss adds a KL divergenceKL divergenceA measure of how different one probability distribution is from another. Zero when they are identical; not symmetric. term measuring how far each is from the prior . It pulls means toward the origin and pushes toward 1. The result: the encodings tile the region where puts its mass, so sampling and decoding gives realistic outputs.
The total loss, reconstruction plus KL, is the negative of the evidence lower bound (ELBO)Evidence lower bound (ELBO)The VAE training objective: reconstruction quality minus a KL penalty. It is a lower bound on the log-likelihood of the data., a lower bound on the log-probability the model assigns to the data. Maximizing it is a principled way to train a generative model with a latent variable.
The reparameterization trick
There’s a snag. Backpropagation needs gradients, and “sample from a distribution” isn’t a differentiable operation with respect to and . The fix is the reparameterization trickReparameterization trickWriting a random sample as z = μ + σ·ε with ε ~ N(0, 1), so gradients can flow through μ and σ while the randomness lives in ε.: draw noise from outside the network and compute
Now is an ordinary differentiable function of and , and the randomness is just an input. Gradients flow straight through to the encoder. (Keep this formula in mind: diffusion’s is the same move.)
The β trade-off
Higgins et al.’s β-VAE (2017) multiplies the KL term by a weight . With , the latent space is smoother and its dimensions tend to capture separate, interpretable factors (“disentanglement”), but reconstructions get blurrier. With small, reconstructions are sharp but the space develops gaps. Push very high and the encoder gives up: every input maps to roughly and the decoder outputs one average image, a failure called posterior collapse. The demo’s β slider walks along exactly this trade-off.
VAEs famously produce blurry samples. Part of the reason is the squared-error reconstruction loss: when the decoder is unsure, the loss-minimizing output is an average of the possibilities, and averages of sharp images are blurry. This blurriness was one motivation for GANs and, later, diffusion.
MATH CORNER · optionalThe VAE loss, and the KL term with small numbers
For an input , the encoder gives , the decoder gives , and the prior is . The ELBO is
with for the standard VAE. With a Gaussian decoder, the reconstruction term becomes squared error. For Gaussians, the KL has a closed form, summed over latent dimensions :
Worked example (one latent dimension).
| encoding | KL | |||
|---|---|---|---|---|
| exactly the prior | 0 | 1 | 0 + 1 − 1 − 0 = 0 | 0 |
| typical VAE code | 0.5 | 0.8 | 0.25 + 0.64 − 1 + 0.446 = 0.336 | 0.168 |
| autoencoder-like point, far out | 2.0 | 0.1 | 4 + 0.01 − 1 + 4.605 = 7.615 | 3.808 |
The far-out, needle-thin code costs over 20× more. The term explodes as , which is what stops a VAE from collapsing back into a plain autoencoder.
Reparameterized sample for the typical code with : . Its gradients are and .
In code
A minimal VAE in PyTorch. The two lines that make it a VAE rather than an autoencoder are the reparameterized sample and the KL term.
import torch, torch.nn as nn, torch.nn.functional as F
class VAE(nn.Module):
def __init__(self, d_in=784, d_hidden=400, d_z=2):
super().__init__()
self.enc = nn.Sequential(nn.Linear(d_in, d_hidden), nn.ReLU())
self.mu, self.logvar = nn.Linear(d_hidden, d_z), nn.Linear(d_hidden, d_z)
self.dec = nn.Sequential(nn.Linear(d_z, d_hidden), nn.ReLU(),
nn.Linear(d_hidden, d_in), nn.Sigmoid())
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) # reparameterization
return self.dec(z), mu, logvar
def vae_loss(x, x_hat, mu, logvar, beta=1.0):
rec = F.binary_cross_entropy(x_hat, x, reduction="sum")
kl = 0.5 * torch.sum(mu.pow(2) + logvar.exp() - 1 - logvar)
return rec + beta * kl
# Generate: decode samples from the prior
# new_images = model.dec(torch.randn(16, 2))
The VAE’s second career: compressor for diffusion
VAE samples lost the image-quality race to GANs and then diffusion. But VAEs found a second, crucial role. Latent diffusion (Rombach et al., 2021), the design behind Stable Diffusion, first trains an autoencoder that maps a 512×512×3 image to a 64×64×4 latent (8× smaller in height and width, 4 channels) and back. The diffusion model then works entirely in that small latent space, which is about 48 times cheaper per step.
That autoencoder is a VAE with a twist. Its KL weight is tiny, just enough to keep the latents well-behaved, because here the goal is faithful reconstruction, not sampling from the prior. To avoid VAE blur, it is trained with a perceptual loss and an adversarial (GAN-style) loss on top of pixel error. Newer image models such as SD3 and FLUX use 16 latent channels instead of 4 to keep more detail, and video models extend the same idea to compress time as well as space (see Video generation basics).
- “A good autoencoder is automatically a good generator.” Reconstruction loss says nothing about latent points no training example maps to. Without a regularizer like the VAE’s KL term, random latents often decode to garbage.
- “The VAE’s randomness is just noise that hurts quality.” The sampling during training is the point: it forces the decoder to handle whole neighborhoods, which makes the space continuous and samplable.
- “Bigger β is always better because the space is smoother.” Smoothness costs reconstruction quality. Too much β gives blurry, average outputs and eventually posterior collapse.
- “Stable Diffusion’s VAE generates the image.” The diffusion model generates a latent; the VAE decoder only translates that latent to pixels. Its KL weight is tiny and it’s never sampled from its prior.
Check your understanding
Q1.Why do random latent codes often decode to garbage in a plain autoencoder?
Q2.What does the reparameterization trick z = μ + σ·ε achieve?
Q3.An encoding has μ = 2.0 and σ = 0.1. Compared with μ = 0, σ = 1, its KL penalty is…
Q4.You train a β-VAE with a very large β. What is the most likely result?
Q5.In Stable Diffusion 1.x, what does the VAE do?
Further reading
- paperAuto-Encoding Variational Bayes (Kingma & Welling, 2013) — The original VAE paper and the reparameterization trick.
- paperTutorial on Variational Autoencoders (Doersch, 2016) — A gentle, intuition-first derivation of the VAE objective.
- paperβ-VAE: Learning Basic Visual Concepts with a Constrained Variational Framework (Higgins et al., 2017) — The β trade-off and disentanglement.
- paperNeural Discrete Representation Learning (van den Oord et al., 2017) — VQ-VAE: discrete latent codes.
- paperHigh-Resolution Image Synthesis with Latent Diffusion Models (Rombach et al., 2021) — How a VAE-style autoencoder became the compressor for Stable Diffusion.