concept / diffusion-models
Next task →
University/Generative AI/Generative models/Denoising Diffusion Probabilistic Models
Generative AI and LLMs · Generative models · Diffusion processes

Denoising Diffusion Probabilistic Models

DDPMs generate data by learning to reverse a gradual Gaussian noising process: a fixed forward process destroys structure over T steps, and a trained network predicts the added noise so the chain can be run backwards from pure noise. The variational bound reduces to a denoising squared-error loss, noise schedules and parameterizations control quality, and DDIM/latent diffusion make sampling practical.

39 sectionsresearch260 minhand-authored · structural 79/100
Take assessment →
Mastery requires: derivation reproduced, from-scratch implementation committed, failure case explained, and assessment score ≥ 80%. Current state: not_started.

1. Concept overview

A denoising diffusion probabilistic model is a latent-variable generative model with a fixed TT-step forward (diffusion) process that gradually corrupts data x0∼qdatax_0\sim q_{\text{data}} with Gaussian noise, and a learned reverse process that denoises step by step:

q(xt∣xt−1)=N(αt xt−1, βtI),pθ(xt−1∣xt)=N(μθ(xt,t), σt2I).q(x_t\mid x_{t-1})=\mathcal{N}\bigl(\sqrt{\alpha_t}\,x_{t-1},\,\beta_t I\bigr),\qquad p_\theta(x_{t-1}\mid x_t)=\mathcal{N}\bigl(\mu_\theta(x_t,t),\,\sigma_t^2 I\bigr).

With αt=1−βt\alpha_t=1-\beta_t and αˉt=∏s=1tαs\bar\alpha_t=\prod_{s=1}^t\alpha_s, a crucial closed form holds:

xt=αˉt x0+1−αˉt ε,ε∼N(0,I).x_t=\sqrt{\bar\alpha_t}\,x_0+\sqrt{1-\bar\alpha_t}\,\varepsilon,\qquad \varepsilon\sim\mathcal{N}(0,I).

Ho et al. (2020) parameterize μθ\mu_\theta through a noise predictor εθ(xt,t)\varepsilon_\theta(x_t,t) and train with the strikingly simple objective

Lsimple(θ)=Et,x0,ε∥ε−εθ(xt,t)∥2.L_{\text{simple}}(\theta)=\mathbb{E}_{t,x_0,\varepsilon}\bigl\lVert\varepsilon-\varepsilon_\theta(x_t,t)\bigr\rVert^2 .

Sampling starts from xT∼N(0,I)x_T\sim\mathcal{N}(0,I) and iterates TT learned denoising steps. DDPMs combine the sharpness of GAN-like adversarial training with a stable, supervised-style regression loss, at the cost of slow, sequential sampling.

2. Why this concept exists

Generative models face a trilemma: sample quality, training stability, and likelihood/compositional flexibility. GANs produce sharp samples but train via a minimax game prone to mode collapse and instability; autoregressive models give exact likelihoods but generate pixel-by-pixel (slow, no global coherence); VAEs are fast and likelihood-based but produce blurry samples due to the KL regularization and simple decoders.

Diffusion models avoid adversarial training entirely: the forward process is fixed and the learning problem is "predict the noise you added" — a denoising regression with a well-defined target at every step. This yields:

  • stable training with a simple MSE loss and no discriminator;
  • high-quality, diverse samples (state of the art on ImageNet at high resolution);
  • conditional generation via cross-attention or guidance without retraining the generator;
  • tractable likelihoods via the variational lower bound.

Earlier ideas: Sohl-Dickstein et al. (2015) framed diffusion as a variational Markov chain; Song & Ermon (2019/2020) developed score matching with Langevin dynamics; Ho et al. (2020) connected and simplified these into DDPM, making high-quality image generation practical.

3. Historical background

Sohl-Dickstein, Weiss, Maheswaranathan & Ganguli (2015) introduced the framework of using a sequence of small Gaussian perturbations and learning the reverse Markov chain by variational inference.

Song & Ermon (2019, 2020) developed noise-conditional score networks and Langevin sampling, showing that estimating ∇xlog⁡qt(x)\nabla_x\log q_t(x) (the score) gives a generative process; their 2020 SDE paper unified score-based and diffusion models.

Ho, Jain & Abbeel (2020) introduced DDPM: reparameterized the reverse mean in terms of εθ\varepsilon_\theta, derived the simplified loss, used a cosine-friendly linear noise schedule, and achieved strong unconditional image samples with a U-Net.

Nichol & Dhariwal (2021) improved DDPM with learned reverse variances, a cosine schedule, and better conditioning, achieving likelihoods competitive with autoregressive models. Dhariwal & Nichol (2021) showed diffusion classifiers/guidance beating BigGAN. Song et al. (2020) introduced DDIM for fast deterministic sampling. Rombach et al. (2022) moved diffusion into a compressed VAE latent space (Latent Diffusion Models), enabling high-resolution text-to-image generation at feasible cost (Stable Diffusion). Ho & Salimans (2022) formalized classifier-free guidance; Karras et al. (2022) distilled sampling to few steps via EDM.

4. Fundamental problem

Learn a distribution pθ(x0)p_\theta(x_0) close to the data distribution qdata(x0)q_{\text{data}}(x_0) such that:

  1. we can compute a tractable training objective (no adversarial game, no exhaustive normalization constants);
  2. sampling is possible by a finite procedure from xT∼N(0,I)x_T\sim\mathcal{N}(0,I);
  3. the model can be conditioned on text, class labels, or images;
  4. the same machinery scales to high-dimensional data (512×512×3512\times512\times3 images or billions of language-model parameters).

The key observation is that while pθ(x0)p_\theta(x_0) itself is intractable, each reverse conditional is a small Gaussian whose mean can be learned by a denoiser. The variational upper bound on −log⁡pθ(x0)-\log p_\theta(x_0) decomposes into per-step KL terms, each of which is a denoising regression.

5. First-principles explanation

Fact 1 — repeated small Gaussian perturbations converge to standard normal. With αˉt=∏s≤t(1−βs)→0\bar\alpha_t=\prod_{s\le t}(1-\beta_s)\to0, the closed form xt=αˉtx0+1−αˉtεx_t=\sqrt{\bar\alpha_t}x_0+\sqrt{1-\bar\alpha_t}\varepsilon implies q(xT)≈N(0,I)q(x_T)\approx\mathcal{N}(0,I) independent of x0x_0. Thus noise provides a simple, known prior.

Fact 2 — the posterior is Gaussian and computable given x0x_0. Bayes' rule gives

q(xt−1∣xt,x0)=N(μ~t(xt,x0),β~tI),q(x_{t-1}\mid x_t,x_0)=\mathcal{N}(\tilde\mu_t(x_t,x_0),\tilde\beta_t I),

with μ~t=αt(1−αˉt−1)1−αˉtxt+αˉt−1βt1−αˉtx0\tilde\mu_t=\frac{\sqrt{\alpha_t}(1-\bar\alpha_{t-1})}{1-\bar\alpha_t}x_t+\frac{\sqrt{\bar\alpha}_{t-1}\beta_t}{1-\bar\alpha_t}x_0 and β~t=1−αˉt−11−αˉtβt\tilde\beta_t=\frac{1-\bar\alpha_{t-1}}{1-\bar\alpha_t}\beta_t. This is the target for the reverse step.

Fact 3 — the network only needs to predict noise. If εθ\varepsilon_\theta estimates ε\varepsilon, we can recover x0x_0 via x^0=(xt−1−αˉtεθ)/αˉt\hat x_0=(x_t-\sqrt{1-\bar\alpha_t}\varepsilon_\theta)/\sqrt{\bar\alpha_t} and plug it into μ~t\tilde\mu_t. Algebraically this gives

μθ(xt,t)=1αt(xt−βt1−αˉtεθ(xt,t)),\mu_\theta(x_t,t)=\frac{1}{\sqrt{\alpha_t}}\Bigl(x_t-\frac{\beta_t}{\sqrt{1-\bar\alpha_t}}\varepsilon_\theta(x_t,t)\Bigr),

which is why the loss becomes noise-prediction MSE.

Fact 4 — variational bound. Since each forward and reverse step is Gaussian, all KL divergences are analytic; maximizing the VLB is equivalent to minimizing a weighted sum of denoising errors, which Ho et al. simplified to uniform weights over tt.

6. Prerequisite concepts

You need: (a) multivariate Gaussian distributions, covariance matrices, and the reparameterization trick (sampling \arαx+1−\arα\ arepsilon\sqrt{\ar\alpha}x+\sqrt{1-\ar\alpha}\ arepsilon); (b) KL divergence and the variational lower bound as used in VAEs; (c) Markov chains, Bayes' rule, and completing the square to get a Gaussian posterior; (d) denoising score matching and the connection  ablaxlog⁡qt(x)≈−\ arepsilon heta/1−\arαt\ abla_x\log q_t(x)\approx-\ arepsilon_\ heta/\sqrt{1-\ar\alpha_t}; (e) U-Net architectures with residual blocks, group normalization, and attention; (f) PyTorch tensor broadcasting, torch.cumprod, and autograd. Familiarity with FID and sample-quality evaluation helps when interpreting benchmark claims.

7. Complete mathematical formulation

Forward process. q(x1:T∣x0)=∏t=1Tq(xt∣xt−1)q(x_{1:T}\mid x_0)=\prod_{t=1}^Tq(x_t\mid x_{t-1}), q(xt∣xt−1)=N(1−βtxt−1,βtI)q(x_t\mid x_{t-1})=\mathcal{N}(\sqrt{1-\beta_t}x_{t-1},\beta_t I), with βt\beta_t a fixed variance schedule (linear: β1=10−4,βT=0.02\beta_1=10^{-4},\beta_T=0.02, T=1000T=1000; cosine schedule as an alternative).

Closed form. q(xt∣x0)=N(αˉtx0,(1−αˉt)I)q(x_t\mid x_0)=\mathcal{N}(\sqrt{\bar\alpha_t}x_0,(1-\bar\alpha_t)I).

Reverse process. pθ(x0:T)=p(xT)∏t=1Tpθ(xt−1∣xt)p_\theta(x_{0:T})=p(x_T)\prod_{t=1}^Tp_\theta(x_{t-1}\mid x_t), p(xT)=N(0,I)p(x_T)=\mathcal{N}(0,I).

Variational lower bound.

log⁡pθ(x0)≥−KL(q(xT∣x0)∥p(xT))+∑t=2T−KL(q(xt−1∣xt,x0)∥pθ(xt−1∣xt))+Eq(x1∣x0)[log⁡pθ(x0∣x1)].\log p_\theta(x_0)\ge -\mathrm{KL}(q(x_T\mid x_0)\|p(x_T))+\sum_{t=2}^T-\mathrm{KL}(q(x_{t-1}\mid x_t,x_0)\|p_\theta(x_{t-1}\mid x_t))+\mathbb{E}_{q(x_1\mid x_0)}[\log p_\theta(x_0\mid x_1)].

With σt2=β~t\sigma_t^2=\tilde\beta_t, the tt-th KL becomes 12σt2∥μ~t−μθ∥2+C\frac{1}{2\sigma_t^2}\lVert\tilde\mu_t-\mu_\theta\rVert^2+C, and substituting the ε\varepsilon-parameterization gives a weight βt22σt2αt(1−αˉt)E∥ε−εθ∥2\frac{\beta_t^2}{2\sigma_t^2\alpha_t(1-\bar\alpha_t)}\mathbb{E}\lVert\varepsilon-\varepsilon_\theta\rVert^2.

Simplified loss (DDPM).

Lsimple=Et∼Unif{1,…,T}, x0,ε∥εθ(xt,t)−ε∥2.L_{\text{simple}}=\mathbb{E}_{t\sim\mathrm{Unif}\{1,\dots,T\},\,x_0,\varepsilon}\lVert\varepsilon_\theta(x_t,t)-\varepsilon\rVert^2 .

Sampler (DDPM). xt−1=μθ(xt,t)+β~t zx_{t-1}=\mu_\theta(x_t,t)+\sqrt{\tilde\beta_t}\,z, z∼N(0,I)z\sim\mathcal{N}(0,I), t=T,…,1t=T,\dots,1 (DDPM often uses σt2=βt\sigma_t^2=\beta_t for the last steps).

DDIM (deterministic, η=0\eta=0). xt−1=αˉt−1x^0+1−αˉt−1εθ(xt,t)x_{t-1}=\sqrt{\bar\alpha}_{t-1}\hat x_0+\sqrt{1-\bar\alpha}_{t-1}\varepsilon_\theta(x_t,t), allowing a subsequence of ∼20\sim20–50 steps.

Classifier-free guidance. ε^=εθ(xt,t,∅)+w(εθ(xt,t,c)−εθ(xt,t,∅))\hat\varepsilon=\varepsilon_\theta(x_t,t,\varnothing)+w\bigl(\varepsilon_\theta(x_t,t,c)-\varepsilon_\theta(x_t,t,\varnothing)\bigr), with ww the guidance scale.

8. Notation dictionary

| Symbol | Meaning | Type / shape | |---|---|---| | x0x_0 | clean data sample | e.g. image (3,H,W)(3,H,W) in [−1,1][-1,1] | | xtx_t | noised sample at step tt | same shape as x0x_0 | | ε\varepsilon | Gaussian noise added by forward process | N(0,I)\mathcal{N}(0,I), same shape | | βt\beta_t | forward variance at step tt | scalar schedule | | αt=1−βt\alpha_t=1-\beta_t | retained-signal factor | scalar | | αˉt\bar\alpha_t | cumulative product ∏s≤tαs\prod_{s\le t}\alpha_s | scalar | | TT | number of diffusion steps | integer, e.g. 1000 | | q,pθq,p_\theta | forward / learned reverse process | Markov chains | | εθ(xt,t)\varepsilon_\theta(x_t,t) | neural noise predictor | same shape as xtx_t | | μ~t,β~t\tilde\mu_t,\tilde\beta_t | true posterior mean / variance | scalar–vector | | μθ,σt\mu_\theta,\sigma_t | reverse mean / std | vector / scalar | | x^0\hat x_0 | predicted clean sample | same shape as x0x_0 | | ww | classifier-free guidance scale | scalar | | LVLB,LsimpleL_{\text{VLB}},L_{\text{simple}} | variational / simplified loss | scalar | | τ\tau | DDIM sampling subsequence | list of timesteps |

9. Step-by-step derivation

Step 1 — forward marginal. Because Gaussians add and xt=αtxt−1+βtεtx_t=\sqrt{\alpha_t}x_{t-1}+\sqrt{\beta_t}\varepsilon_t, unrolling gives xt=αˉtx0+1−αˉtεx_t=\sqrt{\bar\alpha_t}x_0+\sqrt{1-\bar\alpha_t}\varepsilon (variances add as ∏αs\prod\alpha_s weighted sums; verify by induction: 1−αˉt=(1−αˉt−1)+αˉt−1βt1-\bar\alpha_t=(1-\bar\alpha_{t-1})+\bar\alpha_{t-1}\beta_t).

Step 2 — posterior via Bayes. ∝q(xt∣xt−1)q(xt−1∣x0)\propto q(x_t\mid x_{t-1})q(x_{t-1}\mid x_0); completing the square in xt−1x_{t-1} gives μ~t\tilde\mu_t and β~t\tilde\beta_t as in section 8.

Step 3 — variational bound. Use log⁡pθ(x0)≥Eq[log⁡pθ(x0:T)/q(x1:T∣x0)]\log p_\theta(x_0)\ge\mathbb{E}_q[\log p_\theta(x_{0:T})/q(x_{1:T}\mid x_0)] and the Markov factorization; most terms cancel, leaving KLs between Gaussians.

Step 4 — parameterize the mean. Substitute x^0=(xt−1−αˉtεθ)/αˉt\hat x_0=(x_t-\sqrt{1-\bar\alpha_t}\varepsilon_\theta)/\sqrt{\bar\alpha_t} into μ~t\tilde\mu_t and simplify coefficients:

μθ=αt(1−αˉt−1)1−αˉtxt+αˉt−1βt1−αˉtx^0=1αt(xt−βt1−αˉtεθ).\mu_\theta=\frac{\sqrt{\alpha_t}(1-\bar\alpha_{t-1})}{1-\bar\alpha_t}x_t+\frac{\sqrt{\bar\alpha}_{t-1}\beta_t}{1-\bar\alpha_t}\hat x_0 =\frac{1}{\sqrt{\alpha_t}}\Bigl(x_t-\frac{\beta_t}{\sqrt{1-\bar\alpha_t}}\varepsilon_\theta\Bigr).

The identity uses αˉt=αtαˉt−1\bar\alpha_t=\alpha_t\bar\alpha_{t-1} and 1−αˉt=(1−αˉt−1)+αtαˉt−1βt1-\bar\alpha_t=(1-\bar\alpha_{t-1})+\alpha_t\bar\alpha_{t-1}\beta_t.

Step 5 — simplify the loss. ∥μ~t−μθ∥2=βt2αt(1−αˉt)∥ε−εθ∥2\lVert\tilde\mu_t-\mu_\theta\rVert^2=\frac{\beta_t^2}{\alpha_t(1-\bar\alpha_t)}\lVert\varepsilon-\varepsilon_\theta\rVert^2. Ho et al. observed that dropping the time-dependent coefficient wt=βt22σt2αt(1−αˉt)w_t=\frac{\beta_t^2}{2\sigma_t^2\alpha_t(1-\bar\alpha_t)} (i.e. using uniform weights) improves perceptual sample quality, giving LsimpleL_{\text{simple}}; learned/rebalanced weights recover better likelihoods (Nichol & Dhariwal 2021).

Step 6 — sampling. Iterating pθp_\theta from xT∼N(0,I)x_T\sim\mathcal{N}(0,I) implements the reverse chain. DDIM observes that the same trained εθ\varepsilon_\theta defines a family of reverse processes indexed by η∈[0,1]\eta\in[0,1]; η=0\eta=0 is deterministic and consistent for a subsequence of steps, enabling fast sampling.

10. Proofs and proof intuition

Lemma 1 (forward marginal). xt=αˉtx0+1−αˉtεx_t=\sqrt{\bar\alpha_t}x_0+\sqrt{1-\bar\alpha_t}\varepsilon. Proof by induction. For t=1t=1 true. If true at t−1t-1, then xt=αt(αˉt−1x0+1−αˉt−1ε′)+βtε′′x_t=\sqrt{\alpha_t}(\sqrt{\bar\alpha}_{t-1}x_0+\sqrt{1-\bar\alpha}_{t-1}\varepsilon')+\sqrt{\beta_t}\varepsilon''. The noise has variance αt(1−αˉt−1)+βt=1−αˉt\alpha_t(1-\bar\alpha_{t-1})+\beta_t=1-\bar\alpha_t (using αˉt=αtαˉt−1\bar\alpha_t=\alpha_t\bar\alpha_{t-1}), and independent Gaussians add. □\square

Lemma 2 (posterior Gaussian). q(xt−1∣xt,x0)=N(μ~t,β~tI)q(x_{t-1}\mid x_t,x_0)=\mathcal{N}(\tilde\mu_t,\tilde\beta_tI) with the formulas in section 8. Proof. log⁡q(xt−1∣xt,x0)=−12βt∥xt−1−αtxt−1∥2−12αˉt−1∥xt−αtxt−1∥2\log q(x_{t-1}\mid x_t,x_0)=-\frac{1}{2\beta_t}\|x_{t-1}-\sqrt{\alpha_tx_{t-1}}\|^2-\frac{1}{2\bar\alpha_{t-1}}\|x_t-\sqrt{\alpha_t}x_{t-1}\|^2 up to constants (using the marginal for xtx_t given x0x_0); complete the square in xt−1x_{t-1}. □\square

Lemma 3 (mean error equals noise error up to a factor). With σt2=β~t\sigma_t^2=\tilde\beta_t, μ~t−μθ=βtαt1−αˉt(ε−εθ)\tilde\mu_t-\mu_\theta=\frac{\beta_t}{\sqrt{\alpha_t}\sqrt{1-\bar\alpha_t}}(\varepsilon-\varepsilon_\theta). Proof. Substitute x^0\hat x_0 into μ~t\tilde\mu_t and collect coefficients; the xtx_t coefficient is common and cancels. □\square

Lemma 4 (DDIM consistency). For η=0\eta=0, deterministic steps xt−1=αˉt−1x^0+1−αˉt−1εθx_{t-1}=\sqrt{\bar\alpha}_{t-1}\hat x_0+\sqrt{1-\bar\alpha}_{t-1}\varepsilon_\theta leave the training objective's marginals q(xt∣x0)q(x_t\mid x_0) unchanged for any increasing subsequence. Proof sketch. Under the model's x^0\hat x_0 constant along the chain, substituting xt=αˉtx^0+1−αˉtεθx_t=\sqrt{\bar\alpha_t}\hat x_0+\sqrt{1-\bar\alpha_t}\varepsilon_\theta gives the same form at t−1t-1; hence skipping steps is consistent (Song et al. 2020). □\square

Proof intuition. Every reverse step is a least-squares denoising problem: knowing x0x_0 would make the posterior mean exact; the network estimates the missing information through the noise. The VLB is just the sum of Gaussian KLs, which reduce to squared errors.

11. Geometric interpretation

The forward process traces a straight line in signal–noise space: at time tt, xtx_t is a convex combination (in quadrature) of the data point and Gaussian noise, with signal-to-noise ratio SNR(t)=αˉt/(1−αˉt)\mathrm{SNR}(t)=\bar\alpha_t/(1-\bar\alpha_t) decreasing monotonically from large to ~0. Geometrically, noising shrinks the data manifold toward the origin while inflating it with isotropic noise until it is indistinguishable from the prior Gaussian ball.

The reverse process learns a vector field on noisy images: at each (xt,t)(x_t,t), εθ\varepsilon_\theta points roughly from xtx_t toward the nearest high-density region of the data manifold. Iterating small steps follows this field back to the manifold — analogous to gradient descent on an energy landscape where the score ∇xlog⁡qt(x)≈−εθ/1−αˉt\nabla_x\log q_t(x)\approx-\varepsilon_\theta/\sqrt{1-\bar\alpha_t}.

In distribution space, diffusion transports a simple Gaussian to a complex multimodal data distribution through a smooth chain of intermediate densities; unlike GANs, the chain is not a single mapping but a sequence of small, learnable Gaussian transitions, which is why training is stable. Classifier-free guidance effectively extrapolates the score away from the unconditional density, sharpening modes at the cost of diversity.

12. Visual explanation

Draw a horizontal chain of boxes x0→x1→⋯→xTx_0\to x_1\to\dots\to x_T: the forward arrows are fixed Gaussians (blue, labelled αt,βt\sqrt{\alpha_t},\beta_t), the reverse arrows are learned (orange, labelled μθ,σt\mu_\theta,\sigma_t). Show a sample image progressively turning into static, then the chain running backwards from static to a new image.

A second visual plots αˉt\bar\alpha_t and SNR(t)\mathrm{SNR}(t) versus tt for the linear and cosine schedules: linear keeps SNR high early and collapses near TT; cosine decays more gradually, improving sample quality. Show the 1-D toy trajectory from section 13: x0=2x_0=2 drifting toward 0 with variance 1−αˉt1-\bar\alpha_t.

Third visual: the U-Net architecture — a "U" with downsampling (32→64→128 channels), a bottleneck with attention at 16×16, and upsampling with skip connections; a time-embedding vector enters each residual block via an MLP and feature-wise affine transformation (AdaGN).

The Interactive Diffusion Playground in Practical Labs lets you drag tt, see xtx_t and the network's εθ\varepsilon_\theta, and toggle classifier-free guidance to watch samples sharpen.

13. Numerical worked example

Use a tiny 1-D "dataset" with x0=2x_0=2, T=4T=4, β=(0.1,0.2,0.3,0.4)\beta=(0.1,0.2,0.3,0.4), hence α=(0.9,0.8,0.7,0.6)\alpha=(0.9,0.8,0.7,0.6) and αˉ=(0.9,0.72,0.504,0.3024)\bar\alpha=(0.9,0.72,0.504,0.3024). Draw a single noise realization ε=1\varepsilon=1.

Forward samples xt=αˉtx0+1−αˉtεx_t=\sqrt{\bar\alpha_t}x_0+\sqrt{1-\bar\alpha_t}\varepsilon:

  • t=1t=1: 0.9487(2)+0.3162(1)=2.21360.9487(2)+0.3162(1)=2.2136.
  • t=2t=2: 0.8485(2)+0.5292(1)=2.22620.8485(2)+0.5292(1)=2.2262.
  • t=3t=3: 0.7100(2)+0.7043(1)=2.12410.7100(2)+0.7043(1)=2.1241.
  • t=4t=4: 0.5499(2)+0.8352(1)=1.93500.5499(2)+0.8352(1)=1.9350, and q(x4)≈N(0,1)q(x_4)\approx\mathcal{N}(0,1) for large TT.

True posterior at t=2t=2 given x2=2.2262x_2=2.2262 and x0=2x_0=2:

μ~2=0.8(1−0.9)1−0.72(2.2262)+0.9(0.2)1−0.72(2)=0.7111+1.3553=2.0664,\tilde\mu_2=\frac{\sqrt{0.8}(1-0.9)}{1-0.72}(2.2262)+\frac{\sqrt{0.9}(0.2)}{1-0.72}(2)=0.7111+1.3553=2.0664, β~2=1−0.91−0.72(0.2)=0.07143,σ~2=0.2673.\tilde\beta_2=\frac{1-0.9}{1-0.72}(0.2)=0.07143,\qquad \tilde\sigma_2=0.2673.

If the network predicts the true εθ=1\varepsilon_\theta=1, then

μθ=10.8(2.2262−0.20.28)=2.2262−0.37800.8944=2.0664=μ~2,\mu_\theta=\frac{1}{\sqrt{0.8}}\Bigl(2.2262-\frac{0.2}{\sqrt{0.28}}\Bigr)=\frac{2.2262-0.3780}{0.8944}=2.0664=\tilde\mu_2,

confirming the parameterization identity. A reverse sample is x1=2.0664+0.2673zx_1=2.0664+0.2673 z; one draw with z=0z=0 lands exactly at the posterior mean.

SNR at t=4t=4 is 0.3024/0.6976=0.43350.3024/0.6976=0.4335; at t=1000t=1000 with the linear schedule it is ∼10−4\sim10^{-4} — the signal is essentially gone.

14. Real-world analogy

Imagine restoring a photograph that has been degraded by adding a little grain 1000 times. The forward process is easy: add a fresh dusting of grain each time. The restoration network is trained by being shown a photo at a random stage of degradation and asked "how much grain did I add?" — a concrete supervised question. Since it learns to recognize grain at every noise level, you can start with pure static and repeatedly ask it to remove a little grain, nudging the image back toward a plausible photograph each step. Classifier-free guidance is like telling the restorer "make it more like a sunset" and amplifying the difference between that instruction and an unconditioned restoration.

15. Algorithm pseudocode

algorithm DDPM_Train(denoiser eps_theta, data q_data, T, schedule beta_t):
    precompute alpha_t = 1-beta_t ; alpha_bar_t = prod_{s<=t} alpha_s
    repeat:
        x0 ~ q_data
        t ~ Uniform{1,...,T}
        eps ~ N(0,I)
        x_t <- sqrt(alpha_bar_t)*x0 + sqrt(1-alpha_bar_t)*eps   # forward
        loss <- ||eps_theta(x_t, t) - eps||^2                  # denoising MSE
        gradient step on loss

algorithm DDPM_Sample(eps_theta, T, beta_t):
    x_T ~ N(0,I)
    for t = T down to 1:
        eps_hat <- eps_theta(x_t, t)
        mu <- (1/sqrt(alpha_t)) * (x_t - beta_t/sqrt(1-alpha_bar_t)*eps_hat)
        z ~ N(0,I) if t > 1 else 0
        x_{t-1} <- mu + sqrt(beta_t)*z     # or sqrt(beta_tilde_t)
    return x_0

algorithm DDIM_Sample(eps_theta, subsequence tau of length S):
    x_T ~ N(0,I)
    for i = S down to 1:
        t <- tau[i] ; t_prev <- tau[i-1]
        eps_hat <- eps_theta(x_t, t)
        x0_hat <- (x_t - sqrt(1-alpha_bar_t)*eps_hat)/sqrt(alpha_bar_t)
        x_{t_prev} <- sqrt(alpha_bar_{t_prev})*x0_hat
                      + sqrt(1-alpha_bar_{t_prev})*eps_hat   # eta=0, deterministic
    return x_0

16. Implementation from scratch

import numpy as np

betas = np.array([0.1, 0.2, 0.3, 0.4])
alphas = 1 - betas
abar = np.cumprod(alphas)
T = len(betas)

def q_sample(x0, t, eps):
    """Closed-form forward sample at 1-based timestep t."""
    a = abar[t-1]
    return np.sqrt(a)*x0 + np.sqrt(1-a)*eps

x0, eps = 2.0, 1.0
xt = np.array([q_sample(x0, t, eps) for t in range(1, T+1)])
print("abar:", np.round(abar, 4))
print("x_t:", np.round(xt, 4))       # [2.2136, 2.2262, 2.1241, 1.9350]

def posterior(t, x_t, x0):
    """True q(x_{t-1}|x_t,x0) mean and variance, 1-based t."""
    a_t, ab_t = alphas[t-1], abar[t-1]
    ab_prev = abar[t-2] if t > 1 else 1.0
    b_t = betas[t-1]
    mean = (np.sqrt(a_t)*(1-ab_prev)/(1-ab_t))*x_t \
         + (np.sqrt(ab_prev)*b_t/(1-ab_t))*x0
    var = (1-ab_prev)/(1-ab_t)*b_t
    return mean, var

mu_true, var_true = posterior(2, xt[1], x0)
mu_pred = (xt[1] - betas[1]/np.sqrt(1-abar[1])*eps)/np.sqrt(alphas[1])
print(mu_true, var_true, mu_pred)    # 2.066397 0.071428... 2.066397
assert abs(mu_true - mu_pred) < 1e-10

# One reverse step with a perfect denoiser and zero noise.
sample = mu_true
assert abs(sample - 2.0664) < 1e-3

17. Professional library implementation

import math
import torch
import torch.nn as nn
import torch.nn.functional as F
from torchvision import datasets, transforms

def time_embedding(t, dim=64):
    """Sinusoidal timestep embedding; t: (b,) -> (b, dim), dim even."""
    half = dim // 2
    freq = torch.exp(torch.arange(half, device=t.device) * (-math.log(10000)/half))
    ang = t[:, None].float() * freq[None, :]
    return torch.cat([torch.sin(ang), torch.cos(ang)], dim=-1)

class ResBlock(nn.Module):
    def __init__(self, c, tdim=64):
        super().__init__()
        self.n1, self.c1 = nn.GroupNorm(8, c), nn.Conv2d(c, c, 3, padding=1)
        self.n2, self.c2 = nn.GroupNorm(8, c), nn.Conv2d(c, c, 3, padding=1)
        self.tproj = nn.Linear(tdim, c)
    def forward(self, x, temb):
        h = self.c1(F.silu(self.n1(x)))
        h = h + self.tproj(F.silu(temb))[:, :, None, None]  # AdaGN-style conditioning
        return x + self.c2(F.silu(self.n2(h)))

class TinyUNet(nn.Module):
    """Predicts noise: (b,1,28,28) + timestep -> (b,1,28,28)."""
    def __init__(self, in_ch=1, base=32, tdim=64):
        super().__init__()
        self.tmlp = nn.Sequential(nn.Linear(tdim, tdim), nn.SiLU(), nn.Linear(tdim, tdim))
        self.in_conv = nn.Conv2d(in_ch, base, 3, padding=1)
        self.down = ResBlock(base, tdim)
        self.pool = nn.AvgPool2d(2)               # 28x28 -> 14x14
        self.mid = ResBlock(base, tdim)
        self.up = nn.Upsample(scale_factor=2, mode="nearest")
        self.merge = nn.Conv2d(2*base, base, 3, padding=1)
        self.out_block = ResBlock(base, tdim)
        self.out_conv = nn.Conv2d(base, in_ch, 3, padding=1)
    def forward(self, x, t):
        temb = self.tmlp(time_embedding(t))        # (b,64)
        h0 = self.in_conv(x)                       # (b,32,28,28)
        h1 = self.down(h0, temb)                   # skip connection
        h = self.pool(h1)                          # (b,32,14,14)
        h = self.mid(h, temb)
        h = self.merge(torch.cat([self.up(h), h1], dim=1))
        return self.out_conv(self.out_block(h, temb))

T = 1000
beta = torch.linspace(1e-4, 0.02, T)
alpha = 1 - beta
abar = torch.cumprod(alpha, dim=0)
ab_prev = torch.cat([torch.ones(1), abar[:-1]])
model = TinyUNet()
opt = torch.optim.AdamW(model.parameters(), lr=2e-4)

def q_sample(x0, t, eps):
    a = abar[t][:, None, None, None]
    return torch.sqrt(a)*x0 + torch.sqrt(1-a)*eps

dataset = datasets.MNIST("./data", train=True, download=True,
                         transform=transforms.ToTensor())
loader = torch.utils.data.DataLoader(dataset, batch_size=128, shuffle=True)
for epoch in range(10):
    for x0, _ in loader:
        x0 = x0*2 - 1                              # scale to [-1,1]
        t = torch.randint(0, T, (x0.shape[0],))
        eps = torch.randn_like(x0)
        loss = F.mse_loss(model(q_sample(x0, t, eps), t), eps)
        opt.zero_grad(set_to_none=True); loss.backward(); opt.step()

@torch.no_grad()
def sample(n=16):
    x = torch.randn(n, 1, 28, 28)
    for i in reversed(range(T)):
        ti = torch.full((n,), i, dtype=torch.long)
        eps_hat = model(x, ti)
        a, ap, b = abar[i], ab_prev[i], beta[i]
        x0_hat = (x - torch.sqrt(1-a)*eps_hat)/torch.sqrt(a)
        mean = (torch.sqrt(alpha[i])*(1-ap)/(1-a))*x \
             + (torch.sqrt(ap)*b/(1-a))*x0_hat
        x = mean + math.sqrt(b)*torch.randn_like(x) if i > 0 else mean
    return x.clamp(-1, 1)

images = sample()

Classifier-free guidance: during training randomly replace the condition with a learned null token ∅\varnothing (~10% of the time); at sampling compute two noise predictions and use ε^=εθ(xt,t,∅)+w(εθ(xt,t,c)−εθ(xt,t,∅))\hat\varepsilon=\varepsilon_\theta(x_t,t,\varnothing)+w(\varepsilon_\theta(x_t,t,c)-\varepsilon_\theta(x_t,t,\varnothing)).

18. Code walkthrough

Forward sample. q_sample uses the closed form, so the training loop never simulates tt sequential noise additions; this is what makes training parallel over timesteps — sample a random tt per example and jump directly to xtx_t. The broadcasting [:,None,None,None] turns the per-sample αˉt\bar\alpha_t into a spatial multiplier.

Network. TinyUNet maps a noisy image and a timestep to a noise tensor of identical shape — the key design constraint for ε\varepsilon-prediction. time_embedding uses sinusoidal features of tt (as in transformers); tproj(...)[:,:,None,None] broadcasts a channelwise affine shift into every spatial position, telling the network which noise level it is denoising. Skip connections preserve fine spatial detail.

Training. F.mse_loss(pred, eps) is exactly LsimpleL_{\text{simple}}: no VLB weights, no discriminator. The target ε\varepsilon is known because we added it. The schedule buffers alpha, abar, ab_prev are precomputed once; ab_prev[0]=1 handles t=1t=1 where αˉ0=1\bar\alpha_0=1.

Sampling. The reverse loop uses the exact posterior mean with x^0\hat x_0 from the network, i.e. μθ\mu_\theta; adding βtz\sqrt{\beta_t}z reproduces DDPM's stochastic chain. For DDIM, replace that line with the deterministic update using the ab_prev value of a skipped timestep. This loop is sequential by nature — TT network evaluations — which is the main practical bottleneck.

Numerical check. The scratch code verifies μθ=μ~2\mu_\theta=\tilde\mu_2 to 10−1010^{-10} on the 1-D example, a cheap unit test for any reparameterization change.

19. Tensor and memory analysis

Training memory for the tiny MNIST model, batch b=128b=128, images (1,28,28)(1,28,28), base=32:

  • input/noise/target tensors: 3×128×7843\times128\times784 floats ≈ 1.2 MB;
  • U-Net activations: down path (128,32,28,28)(128,32,28,28) ≈ 12.8 MB, bottleneck (128,32,14,14)(128,32,14,14) ≈ 3.2 MB, up path with concatenation ≈ 12.8 MB; total activations ~30 MB; gradients of similar size; Adam states 2×2\times params (~0.8M parameters ≈ 3 MB ×3) — training fits easily in a few hundred MB.

Scaling to latent diffusion (Stable Diffusion): a 512×512 RGB image in pixel space would be (3,512,512)(3,512,512) ≈ 3 MB per sample; the VAE encoder maps it to (4,64,64)(4,64,64) ≈ 64 KB, an 8× spatial compression. A batch of 8 latents is 0.5 MB; the U-Net (≈860M parameters in SD 1.5, ~3.4 GB fp32) dominates memory, plus activations of order gigabytes at attention layers. Mixed precision (fp16) halves weights and activations.

During sampling, only the current xtx_t, the noise prediction, and a few scratch tensors are needed — memory is small, but the T=1000T=1000 sequential forward passes cost time. Caching αˉ\bar\alpha schedules and using torch.no_grad() avoids autograd graph storage.

20. Time complexity

Training: each step samples a random tt and performs one U-Net forward/backward on a batch, costing O(b⋅cost(U-Net))O(b\cdot\mathrm{cost}(\text{U-Net})) — independent of TT (the schedule is just a lookup). This is a major practical advantage: training cost is the same as a supervised denoiser.

Sampling: TT sequential denoising evaluations, O(T⋅b⋅cost(U-Net))O(T\cdot b\cdot\mathrm{cost}(\text{U-Net})); with T=1000T=1000 and a large U-Net this can take minutes per image on a GPU. DDIM with a subsequence of S=20S=20–50 steps reduces this by T/ST/S (20–50×); distillation (consistency models, progressive distillation) can reach 1–4 steps.

Complexity of the U-Net itself is dominated by convolutions (O(HWCinCoutk2)O(HWC_{\text{in}}C_{\text{out}}k^2)) and self-attention at resolution RR (O(b R2d)O(b\,R^2 d) in memory and compute for R2R^2 tokens). In latent space, R=64R=64 gives 4096 tokens instead of 5122=262144512^2=262144 — a 64× attention saving.

21. Space complexity

Model storage: O(d)O(d) parameters (tiny MNIST net ~0.8M; Stable Diffusion U-Net ~860M ≈ 3.4 GB fp32, 1.7 GB fp16). Optimizer states add 2d2d for Adam. Training activations scale as O(b×feature map sizes)O(b\times\text{feature map sizes}) and can be cut by checkpointing at ~30% extra compute.

Sampling needs O(b×dim⁡x)O(b\times\dim x) for the state plus one denoiser forward's activations (no backward graph under no_grad). Storing the whole reverse trajectory for visualization costs O(Tbdim⁡x)O(Tb\dim x), e.g. 1000×16×7841000\times16\times784 floats ≈ 50 MB for MNIST — manageable, but for high-resolution latents it is avoided.

Variance schedules and αˉ\bar\alpha buffers are O(T)O(T) — negligible. Classifier-free guidance doubles (or triples, with text conditioning) the denoiser evaluations per sampling step unless batched.

22. Experimental demonstration

  1. Verify the forward closed form numerically: generate xtx_t by applying tt single-step noisings iteratively and compare with q(xt∣x0)q(x_t\mid x_0); assert equality in distribution and (with fixed noise decomposition) exact sample equality.
  2. Verify μθ=μ~t\mu_\theta=\tilde\mu_t when εθ=ε\varepsilon_\theta=\varepsilon on the 1-D example at several tt; this catches schedule indexing errors.
  3. Train the tiny MNIST DDPM for 5–10 epochs and sample 16 digits; inspect progression at t=1000,750,500,250,1t=1000,750,500,250,1 to see structure emerge progressively.
  4. Compare samplers: DDPM T=1000T=1000 vs. DDIM with S=50S=50 and S=20S=20 from the same trained model; record wall-clock time per image and qualitative quality; compute FID if feasible.
  5. Ablate the schedule: replace linear β\beta with cosine; compare sample sharpness and training loss curves at the same number of steps.
  6. Classifier-free guidance sweep w∈{1,3,5,8}w\in\{1,3,5,8\} on a class-conditional model: compute inception score / FID and record the diversity–fidelity tradeoff (higher ww: sharper, less diverse).

23. Benchmark results

Ho et al. (2020) reported DDPM FID scores on unconditional CIFAR-10 of 3.17 with the simplified loss (and 3.21 with the full VLB loss), outperforming contemporary GANs' ~5–10 range, and strong Inception scores on ImageNet 128×128 conditional generation.

Dhariwal & Nichol (2021) reached FID 2.14 on ImageNet 128×128 with improved architectures/guidance, and a diffusion classifier achieved 78.9% top-1 accuracy, beating BigGAN-deep on some metrics. Nichol & Dhariwal (2021) obtained likelihoods around 3.72 bits/dim on CIFAR-10 with learned variances and cosine schedules, rivaling autoregressive models.

Latent diffusion (Rombach et al. 2022) reported FID 3.60 on ImageNet 256×256 and competitive MS-COCO text-to-image results at a fraction of pixel-space compute; SD 1.5 (a later derivative) became the de-facto open baseline.

These numbers depend heavily on evaluation protocol (number of samples, FID implementation, guidance scale, sampler steps, classifier-free vs. classifier guidance). Always report sampler, steps, guidance scale, and sample count; compare within one protocol only.

24. Limitations

  • Sampling is slow: hundreds to thousands of sequential network evaluations (DDIM/distillation mitigate but trade quality/Training complexity).
  • Training may be stable but is expensive: large U-Nets and long schedules need substantial compute; high-resolution pixel-space diffusion is memory-hungry.
  • The simplified loss ignores VLB weights, giving worse likelihoods even when samples are better; likelihood and perceptual quality disagree.
  • Mode coverage can still be imperfect; classifier-free guidance with large ww reduces diversity and can saturate images.
  • The forward process assumes a fixed Gaussian noise schedule; mismatched schedules/parameterizations cause instability or poor samples.
  • Conditional generation requires extra machinery (cross-attention, guidance, classifiers).
  • Evaluation is tricky: FID is sensitive to sample count and preprocessing; no single number captures fidelity and diversity.

25. Failure scenarios

  1. Samples are pure noise: the reverse mean is miscomputed (wrong αˉ\bar\alpha indexing), or the model was trained at a different schedule than sampling; unit-test μθ=μ~\mu_\theta=\tilde\mu.
  2. Samples are oversaturated / burned with high guidance: reduce ww; monitor per-channel clipping rate.
  3. Training loss plateaus: learning rate too small/large, or the network cannot see tt (missing time embedding); log loss per timestep bucket.
  4. Off-by-one in αˉ\bar\alpha: using abar[t] instead of abar[t-1] for 1-based tt; verify with the 1-D example and with t=1 where αˉ0=1\bar\alpha_0=1.
  5. NaN in sampling near t=0t=0: division by 1−αˉt\sqrt{1-\bar\alpha_t} when αˉt≈1\bar\alpha_t\approx1; clamp αˉt<1−10−6\bar\alpha_t<1-10^{-6} or skip the noise-adding step at t=1t=1.
  6. DDIM produces blurred samples after skipping steps: the subsequence is too coarse or the model was trained with a different schedule; use 20–50 steps and verify consistency.
  7. Memory explosion at high resolution: pixel-space attention at 512² is quadratic; use latent diffusion or local attention.

26. Common misconceptions

  • "The forward process is learned." It is fixed; only the reverse denoiser is trained.
  • "The network predicts the clean image." DDPM predicts the noise ε\varepsilon; x^0\hat x_0 is derived (prediction of x0x_0 is an equivalent parameterization used by some variants).
  • "The simplified loss is the VLB." It drops time-dependent weights; it optimizes sample quality better but gives worse likelihood.
  • "More diffusion steps always mean better samples." Quality saturates; T=1000T=1000 is often more than needed, especially with DDIM.
  • "DDIM is a different trained model." It reuses the same εθ\varepsilon_\theta with a different (deterministic) reverse process.
  • "Classifier-free guidance needs a classifier." It needs only a conditional and an unconditional denoiser (null-condition dropout during training).
  • "Diffusion models are autoregressive." They generate all pixels in parallel per step but sequentially across tt; the factorization is over noise levels, not pixels.

27. Alternative approaches

  • GANs (StyleGAN, BigGAN): single forward pass, sharp samples, but unstable training and mode collapse.
  • VAEs: fast, likelihood-based, but often blurry samples; expressive priors partly close the gap.
  • Autoregressive models (PixelCNN, GPT-style image models): exact likelihood, slow sequential pixel/token generation.
  • Score-based SDEs / flow matching: continuous-time generalization; probability-flow ODEs enabling adaptive solvers and few-step sampling.
  • Consistency models / progressive distillation: distill the TT-step chain to 1–4 steps.
  • Normalizing flows: invertible, exact likelihood, architectural constraints.
  • Latent diffusion: the same DDPM machinery in a compressed autoencoder space for efficiency.

29. Research applications

  • Text-to-image / video: Stable Diffusion, Imagen, DALL·E 2/3, Sora-style video diffusion with spatiotemporal U-Nets or diffusion transformers.
  • Image-to-image / editing: inpainting, super-resolution, style transfer via conditional diffusion and guidance.
  • Scientific domains: molecular conformation generation, protein design (diffusion on 3D coordinates), weather forecasting, medical image synthesis.
  • Audio / speech: waveform diffusion (WaveNet-style), vocoders, music generation.
  • Reinforcement learning: diffusion policies for robotic action sequences; generative modeling of trajectories.
  • Theory: score-based SDE frameworks, optimal transport connections, sampling acceleration, and understanding guidance biases.

30. Important research papers

  • Sohl-Dickstein J., Weiss E. A., Maheswaranathan N., Ganguli S. (2015), Deep Unsupervised Learning using Nonequilibrium Thermodynamics, ICML — original diffusion framework.
  • Song Y., Ermon S. (2019/2020), Generative Modeling by Estimating Gradients of the Data Distribution / Score-Based Generative Modeling through Stochastic Differential Equations, NeurIPS/ICLR.
  • Ho J., Jain A., Abbeel P. (2020), Denoising Diffusion Probabilistic Models, NeurIPS — DDPM and the simplified loss.
  • Song J., Meng C., Ermon S. (2020), Denoising Diffusion Implicit Models, ICLR — DDIM.
  • Nichol A. Q., Dhariwal P. (2021), Improved Denoising Diffusion Probabilistic Models, ICML — cosine schedule, learned variance.
  • Dhariwal P., Nichol A. (2021), Diffusion Models Beat GANs on Image Synthesis, NeurIPS.
  • Ho J., Salimans T. (2022), Classifier-Free Diffusion Guidance, NeurIPS workshop.
  • Rombach R. et al. (2022), High-Resolution Image Synthesis with Latent Diffusion Models, CVPR.

31. Further reading

  • Ho et al. (2020) — the paper's derivations and pseudocode are compact enough to reproduce in a weekend.
  • Song et al. (2020) DDIM for the deterministic-sampling family.
  • Nichol & Dhariwal (2021) for schedules and learned variances.
  • Rombach et al. (2022) for latent diffusion and cross-attention conditioning.
  • Hugging Face "Diffusion Models" course and the diffusers library docs.
  • Karras et al. (2022), Elucidating the Design Space of Diffusion-Based Generative Models, for modern sampler design.

32. Practical exercises

  1. Implement the forward closed form and the posterior mean/variance in NumPy; verify the 1-D numbers in section 13 to 4 decimals.
  2. Prove μθ=μ~t\mu_\theta=\tilde\mu_t when εθ=ε\varepsilon_\theta=\varepsilon symbolically, then verify numerically for 5 timesteps.
  3. Implement the tiny MNIST DDPM from memory; train for 3 epochs and sample digits; show the denoising trajectory at 5 timesteps.
  4. Derive the VLB weights and implement both LVLBL_{\text{VLB}} and LsimpleL_{\text{simple}}; compare likelihood proxy and sample quality.
  5. Implement DDIM sampling on the same trained model and compare times/quality for S∈{10,20,50,100}S\in\{10,20,50,100\}.
  6. Add classifier-free guidance: train with null-condition dropout, sample with w∈{1,3,5}w\in\{1,3,5\}, and quantify the diversity–fidelity tradeoff (FID vs. feature diversity).

33. Debugging challenges

  • Sampled images look like static: check the schedule indexing (abar[t-1]), that the model output shape matches xtx_t, and that sampling uses the same TT/schedule as training.
  • NaN losses early in training: scale inputs to [−1,1][-1,1], check t dtype (long), and clamp schedules at t=1t=1.
  • Loss decreases but samples are blurry: schedule too aggressive or network too small; try cosine β\beta and more capacity.
  • Guidance saturates images: reduce ww and check that the null-condition branch is actually being used during training.
  • DDIM with few steps gives artefacts: use more steps or a schedule-matched subsequence; verify x^0\hat x_0 is computed with the correct αˉt\bar\alpha_t.
  • Out of memory during training: enable mixed precision, reduce batch, or move to latent space.
  • t=1 sampling divides by zero: use σ1=0\sigma_1=0 and set ab_prev[0]=1 explicitly.

34. Advanced exercises

  1. Derive the continuous-time limit of DDPM as an SDE (Song et al. 2020) and show the reverse-time SDE uses the score ∇log⁡qt\nabla\log q_t.
  2. Derive the DDIM family from the non-Markovian forward process and prove that different η\eta values give the same training marginals.
  3. Prove that optimizing LsimpleL_{\text{simple}} corresponds to a reweighted score-matching objective; identify the weighting and its effect on low/high-noise regimes.
  4. Implement learned reverse variance (Nichol & Dhariwal) by predicting a mixture parameter over βt,β~t\beta_t,\tilde\beta_t; compare VLB scores.
  5. Implement a diffusion transformer (DiT) patchifying latents instead of using a U-Net; compare FLOPs at the same sample quality.
  6. Derive classifier-free guidance from a classifier-guided score and analyze how large ww distorts the implied distribution.

35. Interview questions

  • State the forward process and derive q(xt∣x0)q(x_t\mid x_0) in closed form.
  • Derive μ~t\tilde\mu_t and show that predicting ε\varepsilon suffices to parameterize the reverse mean.
  • Why do Ho et al. drop the VLB weights? What is gained and lost?
  • Compare DDPM sampling with DDIM sampling; why can DDIM skip steps?
  • Explain classifier-free guidance and the effect of the scale ww.
  • Why is training cost independent of TT but sampling cost proportional to TT?
  • What is the role of the noise schedule, and how do linear and cosine schedules differ?
  • Why do latent diffusion models use a VAE encoder/decoder?

36. Research questions

  • Can we design noise schedules and loss weightings that simultaneously optimize likelihood and perceptual quality?
  • What is the minimal number of sampling steps achievable without distillation while preserving fidelity for a given model capacity?
  • How does classifier-free guidance bias the generated distribution, and can we correct it while keeping sharpness?
  • Can diffusion models be trained with single-step consistency objectives from scratch at scale?
  • How do diffusion-generated data affect downstream model training (data quality, memorization, and distribution collapse)?

37. Mastery assessment

To pass: (1) derive the forward marginal and posterior mean without notes; (2) prove the \ arepsilon\ arepsilon-parameterization identity and derive L extsimpleL_{\ ext{simple}} from the VLB; (3) reproduce the 1-D numerical example; (4) implement DDPM training and sampling for MNIST plus DDIM sampling; (5) explain schedules, U-Net conditioning, and guidance; (6) diagnose static/blurry/saturated samples; (7) answer the interview questions. Complete the linked assessment; reading alone is not mastery.

38. Implementation submission

Push a repository containing ddpm_numpy.py (forward, posterior, parameterization check), ddpm_torch.py (TinyUNet, schedule, training loop, samplers DDPM/DDIM, CFG hook), experiments.ipynb (1-D verification, MNIST samples with denoising trajectory, sampler-step sweep, guidance sweep), a README.md with derivations and measured timings, and tests asserting μ heta= ildeμt\mu_\ heta=\ ilde\mu_t and shape/dtype correctness. Submit the repository URL and exact reproduction command.

39. Completion criteria

All of: every section read; forward and reverse derivations reproduced on paper; NumPy and PyTorch implementations passing tests; at least three experiments with recorded numbers and plots; assessment score ≥80%\ge80\%; one failure case (noise-only samples, schedule off-by-one, or guidance saturation) reproduced and explained; one research question answered in a one-page note citing a paper. Only then mark the concept mastered.`

Research papers linked to this concept

sohldickstein2015 · citation recorded, library entry pending
ho2020 · citation recorded, library entry pending
song2020ddim · citation recorded, library entry pending
nichol2021 · citation recorded, library entry pending
rombach2022 · citation recorded, library entry pending