Diffusion Models
A diffusion model learns to undo noise one step at a time. The forward process, the training target, and why sampling takes hundreds of network calls.
Jump to a section
Destroying an image on a schedule
DDPM, the 2020 paper that made diffusion models competitive for images, corrupts each training image over 1,000 steps. At step it scales the image down slightly and mixes in Gaussian noise of variance , with rising linearly from to . By the last step the image keeps 0.64% of its original amplitude, and what remains is, for practical purposes, pure noise.
Generation runs the other way: start from pure noise and remove it, one step at a time, until an image is left. Adding the noise was trivial. Removing it requires a network that has learned, from the training data, what noise is likely to be hiding in an input it has never seen. That learned prediction is the whole model.
The forward process never needs to be simulated step by step. Because each step adds independent Gaussian noise, the noisy sample at any step can be drawn directly from the clean one:
is the fraction of signal variance that survives to step . The two coefficients' squares sum to 1, so if the data has unit variance, so does every : this is the variance-preserving process. Under DDPM's schedule, is 0.90 at step 100, 0.079 at step 500 and at step 1,000.
Recovering the signal from a noise guess
Suppose a network looks at and returns a noise estimate . Rearranging the forward equation gives a direct estimate of the clean signal:
If the guess is exactly right, . If it is off by , so that , the clean estimate is off by
The gain depends only on how much signal is left. At it is 1. At it is 2, so a noise error of moves the clean estimate by . At it is 7, and at DDPM's last step it is about 157. A small mistake in predicting the noise becomes a large mistake in the implied image exactly when there is least signal to go on.
Separate noising from knowing how to denoise
Mix a known signal with fixed Gaussian noise, then inspect how an error in the noise estimate changes the recovered signal.
Reduced motion is on. Use Previous and Next to inspect each state.
x̂₀ = (xₜ − √(1−ᾱ) ε̂) / √ᾱ
Start with a known signal
This 8 × 8 signal and seeded noise are available to us. A trained denoiser would not be given the true noise.
Explore the inputs and calculations
Read the two calculations
xₜ = √ᾱ x₀ + √(1−ᾱ) ε
x̂₀ = (xₜ − √(1−ᾱ) ε̂) / √ᾱ
The estimate is ε̂ᵢ = εᵢ + error × sin(i + 1). At each setting the Gaussian draw stays fixed. Color intensity clamps at |value| = 2; the MSE uses the full, unclipped values.
Why does the same noise-prediction error hurt more when little signal remains?
Reconstructing x₀ divides by √ᾱ. Its error is −√((1−ᾱ)/ᾱ) times the noise-prediction error. That amplification grows as ᾱ becomes small.
The worked example keeps the true signal and noise in hand, which a real sampler never has. It uses a fixed synthetic signal and seeded noise, lets you set directly rather than through a timestep schedule, and adds an error of your choosing to the noise estimate. It checks the algebra; it does not train a network or generate an image.
The identity also explains why direct estimates look blurry at high noise. A network trained with squared error learns the conditional mean of the noise given , and so the implied is the average of every clean image that could plausibly have produced . Near pure noise, that set is enormous and its average is a smear.
Training in a few lines
Training never runs the full chain. Pick a real example, a random step and fresh noise , form in one shot, and ask the network to recover . DDPM's simplified objective is plain mean squared error:
The noise is the target and never an input. Predicting the noise is one choice; networks can equally be trained to predict or a velocity that mixes the two, and given , each converts to the others by a linear formula.
1import torch
2import torch.nn.functional as F
3
4T = 1000
5betas = torch.linspace(1e-4, 0.02, T) # DDPM's linear schedule
6alpha_bar = torch.cumprod(1 - betas, dim=0)
7
8
9def training_loss(model, x0):
10 t = torch.randint(0, T, (x0.shape[0],), device=x0.device)
11 eps = torch.randn_like(x0)
12 a = alpha_bar.to(x0.device)[t].view(-1, *([1] * (x0.dim() - 1)))
13 xt = a.sqrt() * x0 + (1 - a).sqrt() * eps
14 return F.mse_loss(model(xt, t), eps) # the model sees xt and t, never epsThe arithmetic above can be checked without a network. This version uses known noise, so every expected answer is visible:
1from math import prod, sqrt
2
3
4def corrupt(clean, noise, alpha_bar):
5 return [sqrt(alpha_bar) * x + sqrt(1 - alpha_bar) * e
6 for x, e in zip(clean, noise)]
7
8
9def estimate_clean(noisy, predicted_noise, alpha_bar):
10 if not 0 < alpha_bar <= 1:
11 raise ValueError("alpha_bar must be in (0, 1]")
12 return [(z - sqrt(1 - alpha_bar) * e) / sqrt(alpha_bar)
13 for z, e in zip(noisy, predicted_noise)]
14
15
16clean, noise = [1.0, -1.0], [0.25, -0.5]
17noisy = corrupt(clean, noise, 0.5)
18recovered = estimate_clean(noisy, noise, 0.5)
19assert all(abs(a - b) < 1e-12 for a, b in zip(clean, recovered))
20
21# A noise error of 0.1 moves the clean estimate by -gain * 0.1.
22for alpha_bar, gain in [(0.5, 1), (0.2, 2), (0.02, 7)]:
23 wrong = [e + 0.1 for e in noise]
24 error = estimate_clean(corrupt(clean, noise, alpha_bar), wrong, alpha_bar)[0] - clean[0]
25 assert abs(error + gain * 0.1) < 1e-9
26
27# DDPM's schedule leaves 0.64% of the amplitude after 1,000 steps.
28betas = [1e-4 + (0.02 - 1e-4) * i / 999 for i in range(1000)]
29alpha_bar_T = prod(1 - b for b in betas)
30assert 0.0063 < sqrt(alpha_bar_T) < 0.0064
31assert 157 < sqrt((1 - alpha_bar_T) / alpha_bar_T) < 158Sampling runs the network hundreds of times
The identity is not a sampler. Jumping from pure noise to in one step gives the blurry average described above. DDPM instead takes one small step back at a time, using schedule-dependent coefficients and fresh noise:
with as one of the two variances the paper tested. Each step removes a little of the predicted noise and adds back a smaller amount of new noise. With this sampler DDPM reached an FID of 3.17 on unconditional CIFAR-10, but every sample costs 1,000 network evaluations.
Most later work attacks that cost. DDIM uses the same trained network with a deterministic update that runs on a subsequence of the timesteps, such as 50 of the 1,000. Step count alone does not fix quality or cost, though: the network, the noise schedule, the numerical method, guidance and hardware all interact. Compare samplers at matched settings rather than trusting a universal quality-versus-steps curve.
Working in a latent space, steering with guidance
Running a U-Net over every pixel at every step is expensive, so latent diffusion moves the process into a learned compressed representation. An autoencoder is trained first; diffusion then runs on its latents, and the decoder turns the final latent into an image. Stable Diffusion uses a downsampling factor of 8: a 512 × 512 RGB image (786,432 values) becomes a 64 × 64 × 4 latent (16,384 values), 48 times fewer. The price is that no sample can contain detail the decoder cannot reconstruct.
Conditioning on text or a class changes the predicted noise, and classifier-free guidance exaggerates that change. The same network is trained with the condition sometimes dropped, and at sampling time its two predictions are combined:
Larger pushes samples harder towards the condition, at the cost of diversity and, past a point, of visible artifacts. It also doubles the work per step, since both predictions are needed.
Where it goes wrong
Leaking the target. The noise is the training label. A pipeline that passes into the model, directly or through a cached tensor, trains a network that predicts perfectly and generates nothing.
Mismatched parameterizations. A network trained to predict and sampled as if it predicted or velocity still runs, and produces garbage. The same applies to sampling with a different schedule from the one used in training.
Reading too much into . An intermediate clean estimate is a quantity inside the sampler, not the output. Its blur at high noise is expected behaviour, not a bug.
Assuming the forward process solves generation. Knowing exactly how noise was added does not reveal the noise in a new sample. No algebra recovers a unique original from arbitrary noise; the network supplies a learned guess, and the sampler turns many guesses into a sample.
Sources and further reading
- Ho et al., Denoising Diffusion Probabilistic Models: forward process, training objective, and reverse sampler.
- Rombach et al., High-Resolution Image Synthesis with Latent Diffusion Models: diffusion in a learned latent representation.
- Song et al., Denoising Diffusion Implicit Models (2020): a deterministic sampler that skips steps.
- Ho and Salimans, Classifier-Free Diffusion Guidance (2022): guidance without a separate classifier.