Latent diffusion
Diffusion in the latent space of a frozen autoencoder, conditioning on text, classifier-free guidance and sampling in fewer steps.
The bill for pixels
The topic Continuous-time diffusion and flow matching finished the theory of diffusion: noise prediction, scores, the SDE and the probability-flow ODE describe one model, and good solvers cut sampling from 1000 steps to tens. It ended with the bill: every one of those steps is still a full pass of a large network over the whole image.
Here is that bill in full. One colour image has
numbers, and a pixel-space sampler pushes all of them through at each of the steps, with in the original DDPM. Training is no cheaper, since every gradient step denoises full-resolution images. Rombach et al. (2022) quote 150–1000 V100-days to train the strongest pixel-space models, and about five days on one A100 to draw 50,000 samples.
Attention makes it worse. A self-attention layer compares every position with every other one, so its cost grows with the square of the number of positions, and a image has of them. That is why pixel-space U-Nets attend only at coarse resolutions.
Now suppose an encoder could turn the image into a grid with 4 channels per cell, and a decoder could turn the grid back into the image with no visible loss. Diffusion in that grid would touch far fewer numbers at every step. This topic builds that encoder and runs the whole DDPM machinery inside it.
Two kinds of compression
Most of the bits in a photo describe things nobody notices: the exact texture of grass, sensor noise, the precise edge of every hair. Rombach et al. (2022) split what a generative model has to learn into two kinds of compression.
- Perceptual compression removes high-frequency detail. It accounts for most of the bits and almost none of the meaning.
- Semantic compression is the actual content: which objects, where, in what pose and light.
A pixel-space diffusion model does both jobs with one network. Its simplified loss already puts little weight on imperceptible detail, but the network still runs over every pixel, at every step, for every sample.
Latent diffusion gives each job its own model. An autoencoder does the perceptual compression once. It is trained first and then reused, unchanged, by any diffusion model built on top of it. The diffusion model does the semantic part in the autoencoder's latent space, where imperceptible detail has already been stripped out. At the very end the decoder puts plausible detail back.
The autoencoder returns
So the autoencoder from the topic Autoencoders returns, this time as a compressor rather than a generator. Following Rombach et al., write the encoder as and the decoder as . An image becomes a latent grid
where is the downsampling factor and the number of latent channels. Stable Diffusion uses , . The paper compares from 1 to 32: is pixel space again, loses too much detail, and between 4 and 16 balances speed and fidelity. In this topic is always such an autoencoder latent, not the prior noise of a VAE.
The topic The reparameterization trick ended with blurry VAE samples. This autoencoder is sharp because its loss is more than squared error. A perceptual loss compares features of a pretrained network instead of raw pixels, and a patch discriminator (PatchGAN) adds an adversarial loss, the GAN from GANs as a two-player game doing what it is good at: local realism.
The latent is also regularized, lightly, in one of two ways.
- KL-regularized: the encoder outputs a Gaussian, as in a VAE, with a KL penalty toward weighted by about . In the language of β-VAE and VQ-VAE, that is a tiny : the code may keep almost everything about , and the KL only stops its scale from drifting.
- VQ-regularized: a vector-quantization layer as in VQ-VAE, folded into the decoder.
Why regularize at all? The forward process assumes data on a scale of about one, so that really ends near . Stable Diffusion also multiplies its latents by a fixed to bring their variance to one.
DDPM in latent space
The recipe has two stages. First train the autoencoder and freeze it. Then encode every training image, , and run DDPM on these latents exactly as before. The forward process from DDPM: the forward process becomes
and the loss from DDPM: reverse process and objective becomes
Nothing in the DDPM derivation cared what meant, so nothing changes. The network is still a U-Net, now on a grid. Sampling draws , runs the reverse chain in latent space and hands the final latent to the decoder: .
The loop closes with β-VAE and VQ-VAE. The VQ-VAE also trained an autoencoder first and fitted a prior over its codes afterwards, with an autoregressive PixelCNN. Latent diffusion keeps the two stages and puts a diffusion model in the prior's place.
Conditioning on a prompt
A sampler that draws random images is only half useful; we want the image for a given class label or text prompt . The network simply takes the condition as one more input:
and the loss is the same, averaged over pairs . A class label can enter as a learned embedding added to the time embedding. Text needs more. A text encoder turns the prompt into a sequence of token vectors; in Stable Diffusion 1.x these are 77 vectors of 768 numbers from a frozen CLIP text encoder.
The U-Net reads that sequence through cross-attention layers at several resolutions. With the U-Net's features at each latent position,
Each latent position asks which words are relevant to it and mixes in their vectors. The region that will become a dog can attend to "dog"; the sky can attend to "sunset".
Guidance from the score
A conditional model trained this way follows its prompt, but loosely: samples often look only vaguely like . The score view from Score matching shows how to push harder. By Bayes' rule , so the conditional score splits into two parts:
The second term pulls toward latents that a classifier would confidently call . Classifier guidance (Dhariwal and Nichol, 2021) trains such a classifier on noisy inputs and scales its gradient up. Classifier-free guidance (Ho and Salimans, 2022) needs no classifier: rearranged, the same identity says the classifier term is a difference of two scores,
Give that term the weight with . The guided score is
the score of . At it is the plain conditional score; a larger sharpens the distribution toward latents where is high. Recall from Score matching that a noise prediction is a scaled score, .
Classifier-free guidance in practice
In noise predictions the guided score becomes the formula used in practice:
Both predictions come from one network. During training the condition is replaced by a null token , an empty prompt, in a fraction of steps, typically 10–20%. This condition dropout teaches the same to predict noise with and without the prompt. At sampling time each step runs the network twice, usually as one batch of two.
This course uses the convention of Ho and Salimans: is plain conditional sampling. Many libraries instead write with a guidance scale ; Stable Diffusion's default is .
Guidance trades diversity for fidelity. As grows, samples follow the prompt more closely and look more alike, and very large gives oversaturated colours and harsh contrast. One caution: is not exactly the noise prediction of any single noised distribution, so guidance is a well-motivated heuristic rather than exact sampling from . It works remarkably well.
Fewer steps, and what comes next
Even in latent space, 1000 steps with two network calls each is slow. DDIM (Song, Meng and Ermon, 2021) reuses the same trained and samples on a short subsequence of the steps, often 50. From the current latent it first estimates the clean latent, then jumps to an earlier step deterministically; this is a discretization of the probability-flow ODE from the previous topic:
Why is this a step of that ODE? Divide the latent by its signal coefficient and measure time by the noise-to-signal ratio:
Along the noising path , so the noise enters linearly in . Substitute the probability-flow ODE and : the terms in cancel, comes out as times , and is that same factor. So the ODE is simply . One Euler step holds at its value at : . Since and , multiplying by gives exactly the update above.
No fresh noise enters, so the same always gives the same image, and running the update the other way maps an image approximately back to its noise. With guidance, simply replaces . Higher-order solvers such as DPM-Solver++ get good images in 15–20 steps. Distillation cuts further by changing the network: progressive distillation (Salimans and Ho, 2022) trains a student to do two teacher steps in one, round after round, down to about 4 steps, and a consistency model (Song et al., 2023) maps any point of an ODE trajectory straight to its clean end, in one step.
So the course now has a working text-to-image model: a frozen autoencoder, DDPM in its latent, cross-attention for the prompt, classifier-free guidance and a fast sampler. Each of its steps denoises the whole latent at once. The oldest family with an exact likelihood works the opposite way: it generates one value at a time, each conditioned on all the values before it. The next topic, Autoregressive models, builds that family.
Check your understanding
The same questions as in Pulse. Answers are shared between modes.
Answers are saved on the server and tied to this browser until you sign in.