Skip to content

Module 20

Anurag Prasad edited this page Nov 8, 2026 · 9 revisions

Module 20 — Diffusion Models and Denoising Diffusion Probabilistic Models

⬅️ 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


Overview and learning goals

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}\boldsymbol\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.

Beginner: the big picture

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.

Forward diffusion on a 2-D dataset with linear and cosine schedules

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
Loading

Core concepts and derivations

Forward diffusion process

With a variance schedule $\beta_1,\dots,\beta_T\in(0,1)$, $\alpha_t=1-\beta_t$:

$$ q(\mathbf{x}_t\mid\mathbf{x}_{t-1})=\mathcal{N}\bigl(\sqrt{1-\beta_t},\mathbf{x}_{t-1},\ \beta_t I\bigr). $$

Each step shrinks the signal slightly and adds noise, preserving unit variance if the data have it. Typical: $T=1000$, $\beta$ linear from $10^{-4}$ to $0.02$ (Ho et al. 2020), or the cosine schedule (Nichol & Dhariwal 2021) that destroys information more gently at the ends.

Closed form at any step

With $\bar\alpha_t=\prod_{s=1}^t\alpha_s$, composing Gaussians (sum of independent Gaussians is Gaussian) gives

$$ q(\mathbf{x}_t\mid\mathbf{x}_0)=\mathcal{N}\bigl(\sqrt{\bar\alpha_t}\mathbf{x}_0,\ (1-\bar\alpha_t)I\bigr)\ \Longleftrightarrow\ \mathbf{x}_t=\sqrt{\bar\alpha_t},\mathbf{x}_0+\sqrt{1-\bar\alpha_t},\boldsymbol\varepsilon,\ \ \boldsymbol\varepsilon\sim\mathcal{N}(0,I). $$

Induction: $\mathbf{x}t=\sqrt{\alpha_t}\mathbf{x}{t-1}+\sqrt{1-\alpha_t}\boldsymbol\varepsilon_t=\sqrt{\alpha_t\bar\alpha_{t-1}}\mathbf{x}0+\sqrt{\alpha_t(1-\bar\alpha{t-1})}\boldsymbol\varepsilon_{t-1}'+\sqrt{1-\alpha_t}\boldsymbol\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}$: $\mathbf{x}_T$ is essentially pure noise.

Reverse process and the true posterior

We learn $p_\theta(\mathbf{x}_{t-1}\mid\mathbf{x}t)=\mathcal{N}(\boldsymbol\mu\theta(\mathbf{x}_t,t),\sigma_t^2I)$. Conditioned on $\mathbf{x}_0$ the true reverse step is tractable (Bayes' rule on Gaussians):

$$ q(\mathbf{x}_{t-1}\mid\mathbf{x}_t,\mathbf{x}_0)=\mathcal{N}\bigl(\tilde{\boldsymbol\mu}_t(\mathbf{x}_t,\mathbf{x}_0),\tilde\beta_tI\bigr),\quad \tilde{\boldsymbol\mu}_t=\frac{\sqrt{\bar\alpha_{t-1}}\beta_t}{1-\bar\alpha_t}\mathbf{x}_0+\frac{\sqrt{\alpha_t}(1-\bar\alpha_{t-1})}{1-\bar\alpha_t}\mathbf{x}_t,\quad\tilde\beta_t=\frac{1-\bar\alpha_{t-1}}{1-\bar\alpha_t}\beta_t . $$

Substituting $\mathbf{x}_0=(\mathbf{x}_t-\sqrt{1-\bar\alpha_t}\boldsymbol\varepsilon)/\sqrt{\bar\alpha_t}$ simplifies the mean to

$$ \tilde{\boldsymbol\mu}_t=\frac1{\sqrt{\alpha_t}}\Bigl(\mathbf{x}_t-\frac{\beta_t}{\sqrt{1-\bar\alpha_t}}\boldsymbol\varepsilon\Bigr). $$

Variational bound and the simplified loss

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 $\boldsymbol\mu\theta=\frac1{\sqrt{\alpha_t}}\bigl(\mathbf{x}t-\frac{\beta_t}{\sqrt{1-\bar\alpha_t}}\boldsymbol\varepsilon\theta(\mathbf{x}_t,t)\bigr)$ and dropping the weights (Ho et al. 2020):

$$ L_{\text{simple}}=\mathbb{E}_{t\sim\mathcal{U}{1..T},\ \mathbf{x}_0,\ \boldsymbol\varepsilon}\Bigl[\lVert\boldsymbol\varepsilon-\boldsymbol\varepsilon_\theta(\sqrt{\bar\alpha_t}\mathbf{x}_0+\sqrt{1-\bar\alpha_t}\boldsymbol\varepsilon,\ t)\rVert^2\Bigr]. $$

Training: sample $\mathbf{x}_0$, $t$, $\boldsymbol\varepsilon$; form $\mathbf{x}_t$; regress the noise. Equivalent parameterisations: predict $\mathbf{x}_0$ or the $v$-prediction $v=\sqrt{\bar\alpha_t}\boldsymbol\varepsilon-\sqrt{1-\bar\alpha_t}\mathbf{x}_0$ (Salimans & Ho 2022).

Sampling (DDPM)

Start from $\mathbf{x}_T\sim\mathcal{N}(0,I)$ and iterate for $t=T,\dots,1$:

$$ \mathbf{x}_{t-1}=\frac1{\sqrt{\alpha_t}}\Bigl(\mathbf{x}_t-\frac{1-\alpha_t}{\sqrt{1-\bar\alpha_t}}\boldsymbol\varepsilon_\theta(\mathbf{x}_t,t)\Bigr)+\sigma_t\mathbf{z},\quad\mathbf{z}\sim\mathcal{N}(0,I)\ (\mathbf{z}=0\text{ at }t=1),\ \ \sigma_t^2\in{\beta_t,\tilde\beta_t}. $$

Score matching and the SDE view

$\boldsymbol\varepsilon_\theta$ is a rescaled score: $\nabla_{\mathbf{x}_t}\ln q(\mathbf{x}_t\mid\mathbf{x}_0)=-\boldsymbol\varepsilon/\sqrt{1-\bar\alpha_t}$, so predicting noise = estimating $\nabla\ln p_t$ (denoising score matching; Vincent 2011, Module 16). In the continuous limit, forward noising is an SDE $d\mathbf{x}=f(\mathbf{x},t)dt+g(t)d\mathbf{w}$ and sampling reverses it using the score (Song et al. 2021); the same marginals are produced by a deterministic probability-flow ODE. Flow matching / rectified flows (Lipman et al. 2023) regress a velocity field along (nearly) straight paths between noise and data, giving simpler training and fewer sampling steps.

Fast sampling: DDIM

DDIM (Song et al. 2021) defines a non-Markovian family with the same marginals; with $\sigma_t=0$ sampling is deterministic and can skip steps: $\mathbf{x}{t-1}=\sqrt{\bar\alpha{t-1}},\hat{\mathbf{x}}0+\sqrt{1-\bar\alpha{t-1}},\boldsymbol\varepsilon_\theta$, with $\hat{\mathbf{x}}_0=\frac{\mathbf{x}t-\sqrt{1-\bar\alpha_t}\boldsymbol\varepsilon\theta}{\sqrt{\bar\alpha_t}}$, using 20–50 steps instead of 1000. Higher-order ODE solvers (DPM-Solver), distillation (progressive, consistency models) push toward 1–4 steps.

Conditioning, classifier-free guidance and latent diffusion

Classifier-free guidance (Ho & Salimans 2022): train one network with the condition $c$ randomly dropped; at sampling use $\tilde{\boldsymbol\varepsilon}=\boldsymbol\varepsilon_\theta(\mathbf{x}t,\varnothing)+w\bigl(\boldsymbol\varepsilon\theta(\mathbf{x}t,c)-\boldsymbol\varepsilon\theta(\mathbf{x}_t,\varnothing)\bigr)$; $w>1$ trades diversity for fidelity. Latent diffusion (Rombach et al. 2022) runs diffusion in the compressed latent space of a pretrained autoencoder (Modules 16, 18), greatly cutting cost; text conditioning enters through cross-attention (Module 14).

Network architecture

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 $t$ injected through sinusoidal embeddings (Module 15) and adaptive normalisation. Recent models use Transformer backbones (DiT, Peebles & Xie 2023). Keep an EMA of weights for sampling.

Worked example

$\bar\alpha_t=0.64$, $x_0=1$, $\varepsilon=0.5$: $x_t=0.8\cdot1+0.6\cdot0.5=1.1$ (since $\sqrt{0.64}=0.8$, $\sqrt{0.36}=0.6$). A perfect noise predictor returns $\hat\varepsilon=0.5$, recovering $\hat x_0=(1.1-0.6\cdot0.5)/0.8=1.0$ ✓.

Schedule numbers (linear, $T=1000$): $\bar\alpha_1=0.9999$, $\bar\alpha_{100}=0.897$, $\bar\alpha_{500}=0.079$, $\bar\alpha_{1000}=4.0\times10^{-5}$. At $t=100$ the signal coefficient is $\sqrt{0.897}=0.947$ and the noise coefficient $0.321$.

Implementation

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

Advanced topics

  • 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).

Pitfalls and best practices

  • 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.

Conceptual questions and answers

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}\boldsymbol\varepsilon_t$ and merging independent Gaussian noises gives mean $\sqrt{\bar\alpha_t}\mathbf{x}_0$ and variance $1-\bar\alpha_t$.

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 $\boldsymbol\varepsilon_\theta$ it becomes $\lVert\boldsymbol\varepsilon-\boldsymbol\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)=-\boldsymbol\varepsilon/\sqrt{1-\bar\alpha_t}$, so $\boldsymbol\varepsilon\theta$ estimates $-\sqrt{1-\bar\alpha_t},\nabla\ln p_t$.

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 $w$, increasing adherence to the condition at the cost of diversity.

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 $\bar\alpha_t$ decaying more smoothly.

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.

Sources and further reading

  • 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 ➡️

🎓 Deep Learning Hub

🏠 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

Part 1 · Mathematical foundations
Part 2 · Neural network fundamentals
Part 3 · Training deep networks
Part 4 · Core architectures
Part 5 · Representation and generative learning
Part 6 · Specialised, modern and responsible deep learning
Reference and meta

Clone this wiki locally