Repository navigation
Module 20
⬅️ Module 19 · 🗺️ Curriculum · 🏠 Home · Module 21 ➡️
Level: Advanced · Prerequisites: Modules 03, 11, 14, 18 · Time: about 10–12 hours
On this page: Overview and learning goals · Beginner: the big picture · Core concepts and derivations · Worked example · Implementation · Advanced topics · Pitfalls and best practices · Conceptual questions and answers · Sources and further reading
Diffusion models generate data by learning to reverse a gradual noising process. A fixed forward process turns data into pure Gaussian noise over many small steps; a neural network learns to undo each step. Training is a simple regression ("predict the noise"), is stable and covers modes well, and the same framework (with latent spaces, guidance and fast samplers) underlies today's leading image, video and audio generators.
After this module you should be able to:
- define the forward process and derive its closed form
$\mathbf{x}_t=\sqrt{\bar\alpha_t}\mathbf{x}_0+\sqrt{1-\bar\alpha_t}\mathbf{\varepsilon}$ ; - derive the reverse-process posterior and the simplified noise-prediction loss;
- write DDPM sampling, and explain DDIM, classifier-free guidance and latent diffusion;
- relate diffusion to score matching, VAEs and flow matching.
Drop ink into water: the picture slowly dissolves into uniform cloudiness. Reversing it looks impossible — but if we know how the ink spreads locally, one tiny step at a time, we can learn to un-spread it step by step, starting from cloudy water and ending with a picture. A diffusion model is a network that, given a noisy image and the noise level, estimates the noise so that a little of it can be removed.

Figure 20.1 — Left: $\bar\alpha_t$ for the linear ($\beta:10^{-4}\to0.02$) and cosine schedules over $T=1000$. Right: a two-moons dataset at $t=0,100,300,999$ under the linear schedule — structure is progressively destroyed until it is indistinguishable from $\mathcal{N}(0,I)$. Original figure (figures/make_figs_2.py).
flowchart LR
X0["x0 (data)"] -- "q: add noise" --> X1["x1"] --> XD["..."] --> XT["xT ~ N(0,I)"]
XT -- "p_theta: denoise" --> XD2["..."] --> X1b["x1"] --> X0b["x0 (sample)"]
UNET["Network eps_theta(x_t, t)"] -.-> XD2
With a variance schedule
Each step shrinks the signal slightly and adds noise, preserving unit variance if the data have it. Typical:
With
Induction: $\mathbf{x}t=\sqrt{\alpha_t}\mathbf{x}{t-1}+\sqrt{1-\alpha_t}\mathbf{\varepsilon}t=\sqrt{\alpha_t\bar\alpha{t-1}}\mathbf{x}0+\sqrt{\alpha_t(1-\bar\alpha{t-1})}\mathbf{\varepsilon}_{t-1}'+\sqrt{1-\alpha_t}\mathbf{\varepsilon}t$ and the two noise terms combine to variance $\alpha_t(1-\bar\alpha{t-1})+1-\alpha_t=1-\bar\alpha_t$. So we can noise any $\mathbf{x}0$ to any level in one shot — essential for efficient training. With the linear schedule, $\bar\alpha{1000}\approx4\times10^{-5}$:
We learn $p_\theta(\mathbf{x}_{t-1}\mid\mathbf{x}t)=\mathcal{N}(\mathbf{\mu}\theta(\mathbf{x}_t,t),\sigma_t^2I)$. Conditioned on
Substituting
Like a VAE with a fixed encoder (Module 18), the ELBO decomposes into $\sum_tD_{KL}\bigl(q(\mathbf{x}_{t-1}\mid\mathbf{x}t,\mathbf{x}0)\Vert p\theta(\mathbf{x}{t-1}\mid\mathbf{x}t)\bigr)$ plus end terms. Each KL between Gaussians with equal variance is a weighted squared difference of means. Parameterising $\mathbf{\mu}\theta=\frac1{\sqrt{\alpha_t}}\bigl(\mathbf{x}t-\frac{\beta_t}{\sqrt{1-\bar\alpha_t}}\mathbf{\varepsilon}\theta(\mathbf{x}_t,t)\bigr)$ and dropping the weights (Ho et al. 2020):
Training: sample
Start from
$\mathbf{\varepsilon}\theta$ is a rescaled score: $\nabla{\mathbf{x}_t}\ln q(\mathbf{x}_t\mid\mathbf{x}_0)=-\mathbf{\varepsilon}/\sqrt{1-\bar\alpha_t}$, so predicting noise = estimating
DDIM (Song et al. 2021) defines a non-Markovian family with the same marginals; with
Classifier-free guidance (Ho & Salimans 2022): train one network with the condition
The denoiser is usually a U-Net (Ronneberger et al. 2015) with residual conv blocks, self-attention at low resolution, skip connections between matching resolutions, and the timestep
Schedule numbers (linear,
import torch
T = 1000
beta = torch.linspace(1e-4, 0.02, T); alpha = 1 - beta; abar = torch.cumprod(alpha, 0)
def q_sample(x0, t, eps): # closed-form forward process
a = abar[t].view(-1, *[1] * (x0.dim() - 1))
return a.sqrt() * x0 + (1 - a).sqrt() * eps
def train_step(model, x0, opt):
t = torch.randint(0, T, (x0.size(0),)); eps = torch.randn_like(x0)
loss = ((eps - model(q_sample(x0, t, eps), t)) ** 2).mean()
opt.zero_grad(); loss.backward(); opt.step(); return loss.item()
@torch.no_grad()
def ddpm_sample(model, shape):
x = torch.randn(shape)
for t in reversed(range(T)):
eps = model(x, torch.full((shape[0],), t))
x = (x - (1 - alpha[t]) / (1 - abar[t]).sqrt() * eps) / alpha[t].sqrt()
if t > 0: x = x + beta[t].sqrt() * torch.randn_like(x)
return x-
Noise schedules and loss weighting: signal-to-noise ratio
$\mathrm{SNR}(t)=\bar\alpha_t/(1-\bar\alpha_t)$ unifies parameterisations; EDM (Karras et al. 2022) systematically designs preconditioning, schedules and samplers. - Likelihood evaluation via the ELBO or probability-flow ODE; discrete diffusion for text/graphs.
- Control: ControlNet, inpainting, image editing (SDEdit), inversion, LoRA fine-tuning (Module 22).
- Video/audio/3-D diffusion, diffusion for robotics policies and molecules.
- Distillation: consistency models, adversarial/score distillation for few-step generation.
- Memorisation & safety: training-data regurgitation, watermarking and misuse (Module 24).
- Indexing errors in
$\bar\alpha_t$ ($t$ from 0 vs 1). - Not normalising data to
$[-1,1]$ (the prior assumes roughly unit variance). - Using uniform
$t$ without checking loss variance across noise levels. - Sampling with the training network instead of the EMA copy.
- Using too few steps with an ancestral sampler (use DDIM/DPM-Solver instead).
- Forgetting that guidance scale
$w$ interacts with step count and schedule.
Q1. Derive $q(\mathbf{x}_t\mid\mathbf{x}_0)$.
Unrolling $\mathbf{x}t=\sqrt{\alpha_t}\mathbf{x}{t-1}+\sqrt{1-\alpha_t}\mathbf{\varepsilon}_t$ and merging independent Gaussian noises gives mean
Q2. Why is the training objective just noise prediction?
The ELBO's per-step KL reduces to a (weighted) squared error between true and predicted reverse means; with the mean parameterised via $\mathbf{\varepsilon}\theta$ it becomes $\lVert\mathbf{\varepsilon}-\mathbf{\varepsilon}\theta\rVert^2$, and dropping weights works better empirically.
Q3. How is the noise predictor related to the score function?
$\nabla_{\mathbf{x}_t}\ln q(\mathbf{x}_t\mid\mathbf{x}0)=-\mathbf{\varepsilon}/\sqrt{1-\bar\alpha_t}$, so $\mathbf{\varepsilon}\theta$ estimates
Q4. Why is DDPM sampling slow and how does DDIM help?
DDPM needs ~1000 sequential network evaluations because each step is a tiny stochastic reversal. DDIM uses a deterministic non-Markovian process with the same marginals, allowing large time-step skips.
Q5. Explain classifier-free guidance.
Jointly train conditional and unconditional denoisers; at sampling extrapolate from the unconditional toward the conditional prediction with scale
Q6. Why do diffusion models cover modes better than GANs?
They optimise a likelihood-based (ELBO) regression objective for all noise levels, penalising missing modes; there is no adversarial game that can collapse.
Q7. Why is the cosine schedule useful?
The linear schedule destroys signal too quickly near the end, wasting steps on nearly pure noise; cosine keeps
Q8. What is the advantage of latent diffusion?
Running diffusion in a lower-dimensional autoencoder latent space cuts memory and compute by large factors while a decoder restores perceptual detail.
Q9. How does flow matching differ from DDPM?
It regresses a deterministic velocity field along simple paths from noise to data (ODE-based), avoiding the noise-schedule machinery and often needing fewer sampling steps.
- Sohl-Dickstein, J., et al. (2015). Deep unsupervised learning using nonequilibrium thermodynamics. ICML. arXiv:1503.03585.
- Ho, J., Jain, A., & Abbeel, P. (2020). Denoising diffusion probabilistic models. NeurIPS. arXiv:2006.11239.
- Nichol, A., & Dhariwal, P. (2021). Improved denoising diffusion probabilistic models. ICML. arXiv:2102.09672.
- Song, J., Meng, C., & Ermon, S. (2021). Denoising diffusion implicit models. ICLR. arXiv:2010.02502.
- Song, Y., et al. (2021). Score-based generative modeling through stochastic differential equations. ICLR. arXiv:2011.13456.
- Dhariwal, P., & Nichol, A. (2021). Diffusion models beat GANs on image synthesis. NeurIPS. arXiv:2105.05233.
- Ho, J., & Salimans, T. (2022). Classifier-free diffusion guidance. arXiv:2207.12598.
- Rombach, R., et al. (2022). High-resolution image synthesis with latent diffusion models. CVPR. arXiv:2112.10752.
- Karras, T., et al. (2022). Elucidating the design space of diffusion-based generative models. NeurIPS. arXiv:2206.00364.
- Salimans, T., & Ho, J. (2022). Progressive distillation for fast sampling of diffusion models. ICLR.
- Lipman, Y., et al. (2023). Flow matching for generative modeling. ICLR. arXiv:2210.02747.
- Peebles, W., & Xie, S. (2023). Scalable diffusion models with Transformers. ICCV. arXiv:2212.09748.
- Ronneberger, O., Fischer, P., & Brox, T. (2015). U-Net. MICCAI. arXiv:1505.04597.
- Vincent, P. (2011). A connection between score matching and denoising autoencoders. Neural Computation, 23(7).
⬅️ Module 19 · 🗺️ Curriculum · 🏠 Home · Module 21 ➡️
🏠 Home · 🗺️ Curriculum · 🧭 Learning paths · ❓ Question bank · 📖 Glossary · 📚 References · ✏️ Contributing
🏠 Home · 🗺️ Curriculum · 🧭 Learning paths
❓ Question bank · 📖 Glossary · 📚 References
Jump to module:
01 02 03 04 05 06 07 08 09 10 11 12
13 14 15 16 17 18 19 20 21 22 23 24