Skip to content
LearnAI
PART 8 · IMAGE & VIDEO GENERATION/ Foundations of generation

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.

⏱ 13 minIntermediate

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.

ANALOGY· Describing a face over the phone

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:

Without a constraint, the network could just copy the input. The bottleneck prevents that: zz has far fewer dimensions than xx, 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 zz, 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.

INTERACTIVE2D latent space explorer
Latent space
AB1σ2σ
cheerfulgrumpysurprisedsleepy
z = (0.20, 0.10)
training signal at z
none
no signal → junk
recon. error
0.011
lower = sharper
KL to N(0, I)
6.82
not penalized
prior sample
Interpolating from A to B in latent space:
A
17%
33%
50%
67%
83%
B

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.

Each dot is a training face encoded into a 2D latent space. Drag on the plane to decode any point. Compare the plain autoencoder with the VAE, sample z from N(0, I), and watch the interpolation strip between A and B. In VAE mode, try β from 0.1 to 4.

Things to try:

  1. 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.
  2. 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.
  3. VAE, interpolate. The strip now morphs smoothly: cheerful → something in between → sleepy. Latent arithmetic like this is why people describe latent spaces as “meaningful”.
  4. 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 μ(x)\mu(x) and a standard deviation σ(x)\sigma(x) for each latent dimension. During training we sample zz from N(μ,σ2)\mathcal{N}(\mu, \sigma^2) and decode that. Since the decoder must reconstruct xx from any zz in a small cloud around μ\mu, 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 σ\sigma 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 N(μ,σ2)\mathcal{N}(\mu, \sigma^2) is from the prior N(0,I)\mathcal{N}(0, I). It pulls means toward the origin and pushes σ\sigma toward 1. The result: the encodings tile the region where N(0,I)\mathcal{N}(0, I) puts its mass, so sampling z∼N(0,I)z \sim \mathcal{N}(0, I) 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 zz from a distribution” isn’t a differentiable operation with respect to μ\mu and σ\sigma. 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 ε∼N(0,1)\varepsilon \sim \mathcal{N}(0, 1) from outside the network and compute

z=μ+σ⋅ε.z = \mu + \sigma \cdot \varepsilon .

Now zz is an ordinary differentiable function of μ\mu and σ\sigma, and the randomness is just an input. Gradients flow straight through to the encoder. (Keep this formula in mind: diffusion’s xt=αˉt x0+1−αˉt εx_t = \sqrt{\bar\alpha_t}\, x_0 + \sqrt{1-\bar\alpha_t}\, \varepsilon is the same move.)

The β trade-off

Higgins et al.’s β-VAE (2017) multiplies the KL term by a weight β\beta. With β>1\beta > 1, the latent space is smoother and its dimensions tend to capture separate, interpretable factors (“disentanglement”), but reconstructions get blurrier. With β\beta small, reconstructions are sharp but the space develops gaps. Push β\beta very high and the encoder gives up: every input maps to roughly N(0,I)\mathcal{N}(0, I) 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 xx, the encoder gives q(z∣x)=N(μ,diag⁡σ2)q(z \mid x) = \mathcal{N}(\mu, \operatorname{diag}\sigma^2), the decoder gives p(x∣z)p(x \mid z), and the prior is p(z)=N(0,I)p(z) = \mathcal{N}(0, I). The ELBO is

log⁡p(x) ≥ Ez∼q(z∣x)[log⁡p(x∣z)]⏟reconstruction  −  β KL(q(z∣x) ∥ p(z))⏟keep codes near N(0,I)\log p(x) \ \ge\ \underbrace{\mathbb{E}_{z \sim q(z\mid x)}\big[\log p(x \mid z)\big]}_{\text{reconstruction}} \;-\; \beta\, \underbrace{\mathrm{KL}\big(q(z\mid x)\ \|\ p(z)\big)}_{\text{keep codes near } \mathcal{N}(0,I)}

with β=1\beta = 1 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 dd:

KL=12∑d(μd2+σd2−1−ln⁡σd2).\mathrm{KL} = \tfrac12 \sum_d \left( \mu_d^2 + \sigma_d^2 - 1 - \ln \sigma_d^2 \right).

Worked example (one latent dimension).

encodingμ\muσ\sigmaμ2+σ2−1−ln⁡σ2\mu^2 + \sigma^2 - 1 - \ln\sigma^2KL
exactly the prior010 + 1 − 1 − 0 = 00
typical VAE code0.50.80.25 + 0.64 − 1 + 0.446 = 0.3360.168
autoencoder-like point, far out2.00.14 + 0.01 − 1 + 4.605 = 7.6153.808

The far-out, needle-thin code costs over 20× more. The −ln⁡σ2-\ln\sigma^2 term explodes as σ→0\sigma \to 0, which is what stops a VAE from collapsing back into a plain autoencoder.

Reparameterized sample for the typical code with ε=−0.5\varepsilon = -0.5: z=0.5+0.8⋅(−0.5)=0.1z = 0.5 + 0.8 \cdot (-0.5) = 0.1. Its gradients are ∂z/∂μ=1\partial z / \partial \mu = 1 and ∂z/∂σ=ε=−0.5\partial z / \partial \sigma = \varepsilon = -0.5.

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).

COMMON MISCONCEPTIONS
  • “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

0/5 answered
  1. Q1.Why do random latent codes often decode to garbage in a plain autoencoder?

  2. Q2.What does the reparameterization trick z = μ + σ·ε achieve?

  3. Q3.An encoding has μ = 2.0 and σ = 0.1. Compared with μ = 0, σ = 1, its KL penalty is…

  4. Q4.You train a β-VAE with a very large β. What is the most likely result?

  5. Q5.In Stable Diffusion 1.x, what does the VAE do?

Further reading

Progress is saved in this browser only.
Type to search across all lessons and glossary terms.