Diffusion Models
Learning to undo noise, one small step at a time.
Destroying an image takes no skill: add a little Gaussian noise, then a little more, a thousand times over. A diffusion model is trained to undo one of those small steps and nothing else. Chain a thousand undone steps and pure noise turns into a new image, and the single regression loss that trains the network turns out to estimate the gradient of the log-density at every noise level.
What you’ll learn
- Derive the forward-process marginal from the single steps, and read a noise schedule through and the signal-to-noise ratio.
- Implement the noise-prediction loss and prove that its minimizer is the scaled score .
- Write the DDPM sampling loop, explain why it takes many small steps, and show how DDIM and the probability-flow ODE sample deterministically in far fewer.
- Explain how class labels and text enter the denoiser, what classifier-free guidance and latent diffusion change, and how U-Net and transformer backbones are built.
The forward process: noise on a schedule
Start with data , say images with pixel values scaled to . A diffusion model fixes a noise schedule and corrupts the data with a Markov chain, the forward process:
Throughout this lesson counts discrete steps and is the number of steps, not a sequence length. Each step shrinks the current image slightly and adds a little fresh Gaussian noise. The shrinking keeps the scale under control: if every coordinate of has unit variance, then has variance as well, which is why this chain is called variance preserving. Nothing in it is learned.
Give each step its own fresh noise and introduce the shorthand and its running product . The claim to prove is for a single standard normal ; at it is the definition.
Assume the claim at step , with its own noise , and substitute. Two independent zero-mean Gaussian noise terms appear:
Variances of independent Gaussians add, and . The noise is one Gaussian of variance , which completes the induction:
Training never has to simulate the chain: draw and , and form in one line. As the data are forgotten and , the distribution that sampling starts from.
A schedule is easiest to read through , the fraction of the data's variance still present at step , or through the signal-to-noise ratio , which falls monotonically from very large to nearly zero. DDPM (Ho, Jain & Abbeel, 2020) used steps with rising linearly from to . That gives , and Ho et al. measured the mismatch at about bits per dimension: the end of the chain is, for all practical purposes, pure noise.
With DDPM's linear schedule (, from to ), at which step does first fall below , so that noise carries more than half of the variance?
Show the answer
260 step
, which reaches near ; the exact product first drops below at . A quarter of the way through the chain, half of the signal is gone, and from on less than 1% remains: the last third of the chain is nearly pure noise. That imbalance is one reason later work replaced the linear schedule (The Design Space of Diffusion Models).
What the network is trained to predict
The forward process destroys information; the reverse process must restore it. The network that does so is surprisingly simple to train: show it a noisy together with its step , and ask for the noise that was added. Ho et al.'s simplified objective is plain regression:
Where does this loss come from? Viewed as a hierarchical VAE whose encoder is the fixed forward chain, a DDPM has an ELBO that splits into one Gaussian KL term per step, each a weighted noise-prediction error; the Emergence lesson Very Deep Hierarchical VAEs writes it out. drops the weights, which shifts emphasis toward the noisier, harder steps, and it gave better samples: a state-of-the-art unconditional CIFAR-10 FID of 3.17 at the time. Training is then a few lines:
import torch
import torch.nn.functional as F
T = 1000
betas = torch.linspace(1e-4, 0.02, T) # DDPM's linear schedule
alpha_bar = torch.cumprod(1 - betas, dim=0) # alpha_bar[t-1] is the text's alpha-bar_t
def diffusion_loss(model, x0):
t = torch.randint(0, T, (x0.shape[0],)) # one random step per example (0-based)
eps = torch.randn_like(x0)
ab = alpha_bar[t].view(-1, *[1] * (x0.dim() - 1))
xt = ab.sqrt() * x0 + (1 - ab).sqrt() * eps # jump straight to step t
return F.mse_loss(model(xt, t), eps) # regress the noise
for x0 in loader: # e.g. images scaled to [-1, 1]
loss = diffusion_loss(model, x0)
opt.zero_grad(); loss.backward(); opt.step()model is any network that maps to an array shaped like . Each time an example is seen it is reused at a fresh random step with fresh noise, so the data are effectively augmented without limit.
A squared error is minimized pointwise by a conditional mean. Each has its own term, so for an unrestricted function the weighting over is irrelevant:
The noised marginal is a mixture of Gaussians, one per clean image: . Differentiate under the integral and divide by : the score of a mixture is the posterior average of its components' scores.
Each component's score is explicit, and at a training pair it is the noise in disguise:
Combining, , the first claim. Writing and taking gives the second.
So a noise predictor is a score estimator in disguise, and training it is denoising score matching (Vincent, 2011) at every noise level at once; the Emergence lesson Energy-Based Models derives score matching from scratch. Two consequences shape everything that follows.
- No normalizing constant. The score ignores any constant factor in , so the network never has to compute a probability.
- Many noise levels. At low noise the score can be learned only near the training points; between them, where a sampler starting from noise would begin, there is almost no training signal. Heavy noise spreads every training point over the whole space and makes the score learnable everywhere, and a decreasing ladder of noise levels leads samples from there back to the data (Song & Ermon, 2019).
A well-trained network receives at a step where , and its implied clean image is close to the best possible estimate . What does look like?
- A sharp, realistic image from the data distribution
- The training image that was noised to produce
- Close to the average of the training data: a featureless blur
- Pure noise, since is almost pure noise
Show the answer
C. Close to the average of the training data: a featureless blur
At , carries almost no information about , so the posterior over clean images is nearly the data distribution itself, and its mean is nearly the dataset average. This is why a single denoising step from pure noise cannot generate: sampling needs many steps, each committing to a little more detail as the noise level falls.
Running the chain backward
To sample you need the reverse transitions , which depend on the unknown data distribution. Two facts make a learned approximation work. First, if the clean image were known, the reverse step would be an exact Gaussian, by Gaussian conditioning on the forward process:
Second, when is small the true reverse step is itself close to Gaussian (Sohl-Dickstein et al., 2015), so a Gaussian with a learned mean loses little. DDPM plugs the network's into . Written with the predicted noise the mean simplifies, and written with the implied score it is a step uphill on the log-density of the current noise level, followed by a slight rescaling:
@torch.no_grad()
def sample(model, shape):
x = torch.randn(shape) # x_T ~ N(0, I)
for t in reversed(range(T)): # 0-based: T-1, ..., 0
eps = model(x, torch.full((shape[0],), t))
ab = alpha_bar[t]
x = (x - betas[t] / (1 - ab).sqrt() * eps) / (1 - betas[t]).sqrt() # the mean
if t > 0: # no noise on the last step
var = betas[t] * (1 - alpha_bar[t - 1]) / (1 - ab) # tilde-beta_t
x = x + var.sqrt() * torch.randn_like(x)
return xOne network evaluation per step, in all: the price of DDPM sampling. Generation is inherently sequential, because each step needs the previous step's output.
Deterministic sampling: DDIM and the probability-flow ODE
A thousand evaluations per sample is expensive, and skipping steps of the DDPM chain makes each Gaussian step too crude. DDIM (Song, Meng & Ermon, 2021) starts from an observation about the loss: it involves only the marginals , never the step-to-step transitions. Every forward process with the same marginals, Markov or not, has the same training objective, so one trained network can be sampled by any of them. The deterministic member gives the update
With no fresh noise, the output is a deterministic function of the starting noise , and running the map in reverse encodes a real image into noise, which makes interpolation and editing possible. The continuous-time picture explains why this works. Song et al. (2021) showed that as the steps shrink, the DDPM chain becomes, in continuous time , a stochastic differential equation , and that the probability-flow ODE
transports a cloud of points so that it has exactly the SDE's marginal at every time. Integrated backward from noise with the learned score, it generates data with no randomness after the first draw. Deterministic DDIM is a first-order discretization of this ODE, and higher-order solvers need fewer steps still (The Design Space of Diffusion Models). Its close relative, flow matching, trains the velocity field of such an ODE directly, by regression onto the velocities of straight lines drawn between noise samples and data samples (Continuous Flows & Flow Matching).
Why can a network trained with the DDPM loss be sampled with DDIM, whose forward process is different and not even Markov, without retraining?
- DDIM fine-tunes the network's last layer on the fly
- The loss depends only on the marginals , which DDIM's processes share with DDPM's, so the same network is optimal for all of them
- DDIM and DDPM have identical step-to-step transitions
- With fewer steps, the network's errors cancel out
Show the answer
B. The loss depends only on the marginals , which DDIM's processes share with DDPM's, so the same network is optimal for all of them
samples directly from and never touches . Any family with those marginals defines the same training problem, and DDIM picks the member whose reverse process is deterministic and can skip steps.
Backbones, conditioning and latents
Backbones. The denoiser maps an image-shaped input to an image-shaped output, and the standard choice since DDPM has been a U-Net (Ronneberger, Fischer & Brox, 2015): downsampling and upsampling paths joined by skip connections at every resolution, so the output keeps fine detail while the deepest layers see the whole image. DDPM's version stacked residual blocks with group normalization, used self-attention at , and added a sinusoidal embedding of inside every residual block. Diffusion transformers (DiT; Peebles & Xie, 2023) replace the U-Net with a vision transformer over small patches of a latent image, injecting and the class through adaptive layer normalization; their quality improved steadily with compute per forward pass (The Design Space of Diffusion Models).
Conditioning. For a class label, add a learned class embedding to the step embedding, so every block sees both. For text, an encoder (a CLIP or T5 transformer, frozen or trained) turns the prompt into token vectors , and cross-attention layers inside the U-Net let every spatial position read from them (Rombach et al., 2022):
Latent diffusion. Pixels are expensive: a RGB image has 786,432 values, and the network processes all of them at every step. Latent diffusion (Rombach et al., 2022) first trains an autoencoder that shrinks the image 4- to 16-fold along each side (8-fold in Stable Diffusion) into a small latent grid, runs the whole diffusion process on the latents, and decodes once at the end (Latent Spaces for Generative Models designs that autoencoder).
Three systems of 2022 brought text-to-image diffusion into wide use: DALL·E 2 (Ramesh et al.), which generates a CLIP image embedding from the caption and then decodes it to pixels with a diffusion model; Imagen (Saharia et al.), a frozen T5 text encoder driving a pixel-space diffusion model and two diffusion super-resolution stages up to ; and Stable Diffusion, latent diffusion with publicly released weights.
| Sampler | Network evaluations per sample | Where |
|---|---|---|
| DDPM ancestral sampling | 1,000, one per training step | Ho et al. (2020) |
| DDIM on a subsequence of steps | 20–100 for quality comparable to 1,000 DDPM steps | Song, Meng & Ermon (2021) |
| Heun's second-order ODE solver (EDM) | 35 on CIFAR-10 | The Design Space of Diffusion Models |
| DPM-Solver (exponential integrator) | 10–20 | The Design Space of Diffusion Models |
| Distilled students: progressive distillation, consistency models, adversarial distillation | 1–4 | Few-Step Generation |
Key takeaways
- The forward process has the closed-form marginal , so training samples any step in one draw; a schedule is read through or .
- The network regresses the added noise, ; its optimum is , so denoising at many noise levels is score estimation at many noise levels.
- DDPM samples with small Gaussian reverse steps, accurate only because each step is small; DDIM reuses the same network on a deterministic, step-skipping process that discretizes the probability-flow ODE.
- Class labels join the step embedding, text enters through cross-attention, and classifier-free guidance extrapolates from the unconditional prediction toward the conditional one at two evaluations per step.
- Latent diffusion runs the whole process in an autoencoder's latent space; U-Nets and diffusion transformers are the two standard backbones.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
At some step . What is the distribution of given ?
Show the answer
B.
, so the mean is and the covariance is . The noise's standard deviation is .
Over all functions, what does the noise-prediction loss's minimizer equal?
- The exact noise that was added to
- , where is the distribution of noised data at step
Show the answer
D. , where is the distribution of noised data at step
The minimizer is , and the score of the noised marginal is the posterior average of . The noise points away from the data, so predicting it means pointing down the density: hence the minus sign.
You train with the same loss but a schedule of only large steps, and sample with DDPM's Gaussian reverse steps. What goes wrong?
- Training fails, because the loss is undefined for large
- Each true reverse transition is now broad and often multimodal, so a single Gaussian step with a learned mean approximates it badly and samples land between modes
- Nothing: ten steps give the same samples ten to a hundred times faster
- can no longer approach zero, so sampling cannot start from noise
Show the answer
B. Each true reverse transition is now broad and often multimodal, so a single Gaussian step with a learned mean approximates it badly and samples land between modes
Gaussian reverse steps are accurate only when each forward step adds a little noise. With big steps the true reverse conditional must choose among very different cleaner images, which a Gaussian centered at their average cannot represent.
In a text-conditioned U-Net's cross-attention layer, where do the queries, keys and values come from?
- Queries from the text tokens; keys and values from the image features
- Queries, keys and values all from the image features
- Queries from the image features; keys and values from the text encoder's token vectors
- Queries, keys and values all from the text tokens
Show the answer
C. Queries from the image features; keys and values from the text encoder's token vectors
Each spatial position of the feature map asks a question (its query) and reads from the prompt's tokens (their keys and values), so the output at every position is a mixture of word information relevant to it, and it keeps the image's shape.
Go deeper
- Guidance & Conditioning · Classifier and classifier-free guidance, autoguidance and steering generation with text and images.
- The Design Space of Diffusion Models · Noise schedules, preconditioning, samplers and diffusion transformers.
- Few-Step Generation · Progressive distillation, consistency models and adversarial distillation.
Further reading
- J. Ho, A. Jain & P. Abbeel, "Denoising diffusion probabilistic models," NeurIPS (2020).
- Y. Song, J. Sohl-Dickstein, D. P. Kingma, A. Kumar, S. Ermon & B. Poole, "Score-based generative modeling through stochastic differential equations," ICLR (2021).
- R. Rombach, A. Blattmann, D. Lorenz, P. Esser & B. Ommer, "High-resolution image synthesis with latent diffusion models," CVPR (2022).
- S. J. D. Prince, Understanding Deep Learning, ch. 18 "Diffusion models" (MIT Press, 2023).