Diffusion Models
Learning to reverse a noising process.
A diffusion model is trained by a one-line regression: predict the noise. Behind it sit a variational bound, denoising score matching, a stochastic and an ordinary differential equation that share every marginal, and a family of samplers that trade steps for error. This lesson derives them, and uses a sampler with the exact score to separate sampling error from learning error.
What you’ll learn
- Derive the DDPM bound as a sum of Gaussian KL terms and prove that noise prediction is weighted denoising score matching.
- Prove that an exact-score DDPM step has exactly the right mean, and locate its error in the step's variance.
- Derive the probability-flow ODE from the Fokker–Planck equation, and show that deterministic DDIM is Euler's method on it.
- Express classifier-free guidance as a tilted density, compute latent diffusion's savings, and state a convergence guarantee for score-based sampling.
DDPM as a hierarchical VAE
It is a hierarchical VAE whose encoder, the forward chain, is fixed. Because that encoder is Gaussian, so is its posterior given , by standard Gaussian conditioning:
Take the ELBO with the forward chain as encoder. Rewriting each with Bayes' rule as makes the marginals telescope:
has no parameters. Each is a KL between Gaussians with fixed covariances and , so only the means matter:
Substitute into , and give the same form with a predicted noise:
The difference is proportional to . Ho et al.'s drops the weight, which relative to the bound emphasizes the noisier steps, and gave better samples. In continuous time the bound depends on the schedule only through the SNR at its two endpoints (Kingma et al., 2021).
The conditional score is explicit, and it is the noise up to scale:
Expand both squares. The terms agree, and so do the cross terms, because averaging the conditional density's gradient over gives the marginal's gradient:
The remaining terms do not involve . Read as a statement about , this is Tweedie's formula, proved in Autoencoders & Latent Spaces:
Suppose could be any function of . How does replacing the bound's weights by 's uniform weights change the optimal ?
- It shifts the optimum toward accuracy at the noisiest steps
- It turns into a predictor of
- It changes the optimum only at
- Not at all: each has its own term, minimized by for any positive weight
Show the answer
D. Not at all: each has its own term, minimized by for any positive weight
With unlimited capacity the objective decouples across , and a positive weight does not move a term's minimizer. Weights matter only because one finite network is shared across all and trained by SGD: they decide where its errors go.
What a sampler gets wrong
A sampler's output carries two errors: the network's score error and the error of taking finitely many steps. The widget below has no network. Its data are a mixture of 320 small Gaussians (standard deviation 0.045) along a shape, so every noised marginal is a known mixture and its score is computed exactly. Whatever is wrong with its samples is the sampler's doing, and a lemma says where to look.
Given , with affine in . The tower property gives:
Insert Tweedie's formula and simplify with and :
The law of total covariance adds the spread of the posterior mean to the posterior covariance.
Away from , is proportional to , so the deficit per step is , negligible for fine steps. With few, large steps every step is too narrow, and the cloud of samples contracts toward the data's center of mass. At the last step makes and : the sampler outputs the posterior mean itself, missing all of . Learned variances (Nichol & Dhariwal, 2021) and analytically optimal ones (Bao et al., 2022) target exactly this deficit.
Score SDEs, the probability-flow ODE and DDIM
Let with . The DDPM chain becomes the variance-preserving SDE on , whose marginals have (Song et al., 2021). The widget's schedule is exactly this SDE with rising linearly from 0.1 to 20, the continuum limit of DDPM's 1,000-step linear schedule. In general, take with marginals .
The SDE's marginals obey the Fokker–Planck equation:
Use to fold the diffusion term into the drift:
This is the continuity equation of the velocity field , so particles moving by have marginals (given uniqueness for the continuity equation). The flow is invertible, so the instantaneous change of variables gives exact likelihoods, with the divergence estimated by Hutchinson's trace estimator:
DDIM (Song, Meng & Ermon, 2021) starts from the observation that the DDPM loss involves only the marginals , so every process with the same marginals can reuse the trained network. A family of non-Markovian forward processes indexed by yields the update
Why tolerates large steps: in the variables and , the probability-flow ODE of the VP-SDE reads , and deterministic DDIM is exactly Euler's method on it:
Euler's global error is . Higher-order solvers that exploit the ODE's semilinear structure (Karras et al., 2022; Lu et al., 2022) reach good samples in tens of evaluations.
Distillation removes most of the rest: progressive distillation halves the step count repeatedly (Salimans & Ho, 2022), consistency models learn to map any point of an ODE trajectory to its endpoint (Song et al., 2023), and adversarial distillation adds a GAN loss (Generative Adversarial Networks). Flow matching and rectified flows (Lipman et al., 2023; Liu, Gong & Liu, 2023) skip the SDE and regress a velocity field along straight paths ; as of the mid-2020s they are a common choice for large image and video generators.
You sample a model trained as a 1,000-step DDPM with DDIM at , using 20 of its timesteps, twice from the same . What happens?
- Two different images, because each step injects fresh noise
- Two identical images: the map from to is deterministic, and approximately invertible
- An error: DDIM requires a network retrained for 20 steps
- Samples from a different target distribution, because DDIM's forward process differs from DDPM's
Show the answer
B. Two identical images: the map from to is deterministic, and approximately invertible
With , and each step is a deterministic function of . It discretizes the probability-flow ODE, so running it backward encodes a real image into an , which is used for editing and interpolation.
Guidance, latent diffusion and the frontier
Conditioning needs . Classifier guidance (Dhariwal & Nichol, 2021) trains a classifier on noisy inputs and adds times its gradient. Classifier-free guidance (Ho & Salimans, 2022) trains a single network in which the condition is replaced by a null token for a random 10–20% of examples, then extrapolates from the unconditional prediction toward the conditional one:
Pixel-space diffusion spends much of its capacity on imperceptible detail. Latent diffusion (Rombach et al., 2022) first trains an autoencoder, with perceptual and patch-adversarial losses and light KL or VQ regularization (Variational Autoencoders & the ELBO), that downsamples by a factor , then runs diffusion on the latents. Text enters through cross-attention to a text encoder's outputs. Stable Diffusion, released in 2022, used with 4 latent channels. Diffusion Transformers (Peebles & Xie, 2023) replaced the U-Net with a transformer over latent patches.
Stable Diffusion's autoencoder maps a RGB image to a latent. By what factor does this cut the number of values the diffusion model must process?
Show the answer
48
values versus : a factor of . Attention costs grow faster than linearly in the number of positions, and spatial positions fall by , so the compute saving per step is larger still.
Key takeaways
- DDPM's bound is a sum of Gaussian KL terms. With the mean parameterized like the posterior mean, each term is a weighted , and drops the weights, which leaves a perfect model unchanged.
- Noise prediction is weighted denoising score matching, with optimum ; in continuous time the bound depends on the schedule only through its endpoints.
- With the exact score, a DDPM step's mean is exactly , and its error is the missing covariance . That deficit contracts samples when steps are few and makes the last step output . Given an accurate score, steps reach TV error .
- The reverse SDE and the probability-flow ODE, with drift , share every marginal. Deterministic DDIM is Euler's method on that ODE, and higher-order solvers, distillation and flow matching cut the number of steps further.
- Classifier-free guidance follows the score of , trading diversity for fidelity; latent diffusion runs the whole process in an autoencoder's latent space, 48 times smaller for Stable Diffusion.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
A DDPM sampler with the exact score uses 5 steps, and its samples are too tightly clustered toward the middle of the data. Which part of each step is at fault?
- The step's variance: the Gaussian step uses and omits
- The step's mean, which is biased toward the data's center of mass
- Tweedie's formula, which fails for large steps
- The score is evaluated at the wrong noise level
Show the answer
A. The step's variance: the Gaussian step uses and omits
With the exact score, for any step size. The true conditional also has covariance beyond , which is large when steps are large, so every step is too narrow and the cloud contracts.
What does the probability-flow ODE share with the reverse-time SDE?
- The same sample paths
- It is the reverse SDE with its noise term deleted
- The same marginal distribution at every time
- Nothing: it targets a different distribution, with exact likelihoods as compensation
Show the answer
C. The same marginal distribution at every time
Both have the marginals of the forward SDE, as the Fokker–Planck computation shows. The ODE's drift is , half the score term of the reverse SDE's .
With guidance weight , the classifier-free guided score at noise level is the score of which (unnormalized) density?
Show the answer
D.
, and by Bayes' rule.
A noise predictor is trained to optimality with . What is ?
- The noise that was actually added to produce
Show the answer
C.
Squared error is minimized by , and denoising score matching (equivalently Tweedie's formula) gives .
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).
- J. Ho & T. Salimans, "Classifier-free diffusion guidance," arXiv:2207.12598 (2022).
- R. Rombach, A. Blattmann, D. Lorenz, P. Esser & B. Ommer, "High-resolution image synthesis with latent diffusion models," CVPR (2022).
- K. P. Murphy, Probabilistic Machine Learning: Advanced Topics, ch. "Diffusion models" (MIT Press, 2023).