Lecture 11 · Diffusion Models I: Denoising, Sampling and Guidance

Deep Unsupervised Learning · Lecture 11。个人学习讲义与配套实验,按主题整理并持续修订。

课程源码 ZIP ↓

个人整理的学习笔记,非官方讲义;课程来源与整理说明见课程介绍。配套示例未逐一运行验证。

本篇目录

Maps to: UC Berkeley CS294-158 Deep Unsupervised Learning (Spring 2024), Lecture 6 · Thu 2/22/2024 · Diffusion Models, first part (slides 1–40 and 68–95): motivation (DALL·E 2, Sora, UniSim), the state of the field in 2020, denoising diffusion probabilistic models (forward and reverse process, the variational bound, the simplified loss), the DDPM architecture, the key inspirations (nonequilibrium thermodynamics; score matching and annealed Langevin dynamics), “diffusion models beat GANs” (learned variance, architecture improvements, classifier guidance), classifier-free guidance (training, sampling, the FID / IS trade-off), the DDIM sampler, prediction targets (xx, ϵ\epsilon, vv), the problem with common noise schedules (zero terminal SNR), and the U-Net and its conditioning. Homework 4, Questions 1–2. Basis: The slides give the algorithms and results. These notes derive the forward marginals, the posterior of a reverse step, the variational bound and how it becomes “predict the noise”, Tweedie’s formula, DDIM, the probability-flow ODE and the guidance rules. Then they check everything against exact optimal denoisers: for a 2-D mixture of 402 Gaussians and for ShapeWorld itself, E[x0∣xt]E[x_0 \mid x_t] can be computed in closed form — so every trained network, every sampler and every guidance rule is compared with the best possible one. Code: code/lecture11/ (4 scripts + diffusion.py; PyTorch (CPU); scripts 01–02 take 1–2 minutes, 03–04 ~45–60 minutes the first time (U-Nets cached)) Reading time: 4 hours including running the code


0. How to read this lecture

0.1 Learning goals

After this lecture you should be able to:

  1. Write the forward process of a diffusion model, its closed-form marginals q(xt∣x0)q(x_t \mid x_0), and the signal-to-noise ratio of a schedule.
  2. Derive the posterior q(xt−1∣xt,x0)q(x_{t-1} \mid x_t, x_0), the variational bound, and why it reduces to a (re-weighted) noise-prediction loss.
  3. Explain why the reverse step can be modelled as a Gaussian only when steps are small — and measure it.
  4. State Tweedie’s formula: the optimal noise predictor is the scaled score −σt∇log⁡pt-\sigma_t \nabla \log p_t, and the optimal denoiser the posterior mean.
  5. Implement DDPM and DDIM sampling and the probability-flow ODE, and say what each trades.
  6. Compare the ϵ\epsilon-, x0x_0- and vv-parameterizations and explain zero terminal SNR.
  7. Derive classifier guidance and classifier-free guidance, and explain their fidelity / diversity trade-off.
  8. Distinguish a diffusion model that generalizes from one that memorizes its training set.

0.2 Prerequisites and scope

AssumedIntroduced hereDeveloped later
VAEs and the ELBO (Lectures 7–8)forward / reverse processes, DDPM, the simple losslatent diffusion, Diffusion Transformers, text-to-image (Lecture 12)
continuous flows and the change of variables (Lecture 6)DDIM, the probability-flow ODEfast sampling: distillation, adversarial diffusion (Lecture 12)
GANs, FID and precision / recall (Lectures 9–10)score functions, Tweedie’s formula, guidancevideo diffusion (Lecture 17)

0.3 Map

§1  why diffusion? the state of the field in 2020
§2  the forward process and noise schedules                                       ← code 01, Part 1
§3  the reverse process: Gaussian steps, the ELBO, "predict the noise"             ← code 01, Part 2
§4  scores and the optimal denoiser (Tweedie); the inspirations
§5  sampling: DDPM, DDIM, the probability-flow ODE                                ← code 01, Parts 3-4
§6  training a denoiser: homework 4 Q1                                             ← code 02, Parts 1-3
§7  what to predict: ε, x_0 or v -- and zero terminal SNR                          ← code 02, Part 4
§8  the U-Net, and pixel diffusion on ShapeWorld: generalizing vs memorizing       ← code 03
§9  guidance: classifier guidance, classifier-free guidance                        ← code 04
§10 summary   §11 pitfalls   §12 exercises   §13 further reading   §14 next lecture

0.4 Notation

SymbolMeaning
x0x_0; xtx_tdata; the noised version at time tt
αt\alpha_t, σt\sigma_tsignal and noise scales, xt=αtx0+σtϵx_t = \alpha_t x_0 + \sigma_t \epsilon; homework 4: αt=cos⁡(πt/2)\alpha_t = \cos(\pi t/2), σt=sin⁡(πt/2)\sigma_t = \sin(\pi t/2), t∈[0,1]t \in [0, 1]
βi\beta_i, αˉi\bar\alpha_iDDPM’s discrete schedule: αˉi=∏j≤i(1−βj)\bar\alpha_i = \prod_{j \le i}(1 - \beta_j), so α=αˉ\alpha = \sqrt{\bar\alpha}, σ=1−αˉ\sigma = \sqrt{1 - \bar\alpha}
SNR(t)=αt2/σt2\mathrm{SNR}(t) = \alpha_t^2/\sigma_t^2signal-to-noise ratio; λ=log⁡SNR\lambda = \log \mathrm{SNR}
ϵ^\hat\epsilon, x^0\hat x_0, v^\hat va network’s predictions; v=αtϵ−σtx0v = \alpha_t \epsilon - \sigma_t x_0
ϵ∗\epsilon^*, x0∗x_0^*the optimal predictions E[ϵ∣xt]E[\epsilon \mid x_t], E[x0∣xt]E[x_0 \mid x_t]
η\etasampler noise: 1 = DDPM, 0 = DDIM
wwguidance scale

0.5 How the experiments are run

  • 2-D data with an exact denoiser. Lecture 5’s smiley drawn as a mixture of 402 small Gaussians (standard deviation 0.1). Every noised version is again a Gaussian mixture, so ptp_t, E[x0∣xt]E[x_0 \mid x_t] and even the exact reverse step q(xs∣xt)q(x_s \mid x_t) are closed-form (diffusion.GMM2D).
  • ShapeWorld with an exact denoiser. Every panel is one of 960 known images and the two panels are coupled only through the shape kinds, so E[x0∣xt]E[x_0 \mid x_t] under the true distribution is a sum over 960 × 8 terms per panel (diffusion.ShapeWorldDenoiser); under the training set it is a softmax over 10,000 images (EmpiricalDenoiser).
  • Homework 4’s continuous-time setup: cosine schedule, t∼U(0,1)t \sim U(0, 1), the DDPM sampler from t=1−10−4t = 1 - 10^{-4} to 10−410^{-4}, Adam 10−310^{-3} with 100 warmup steps and cosine decay. Images live in {−1,+1}\{-1, +1\}; samples are thresholded at 0 and judged with Lecture 9’s exact yardsticks and scores.
  • Everything is seeded and single-threaded; reruns print identical numbers.

1. Why diffusion?

The slides take stock of the course in 2020. Autoregressive models and flows gave exact likelihoods; latent variable models gave approximate ones and representations; GANs gave the most realistic images “but have lots of bells and whistles and struggle with truly covering what’s in the data distribution” — Lectures 9–10 measured both halves of that sentence: the ring’s dropped modes, the oscillating games, the sharp but never-valid ShapeWorld samples.

Denoising diffusion probabilistic models (Ho, Jain & Abbeel, 2020) combined the strengths: trained by a likelihood bound (stable, no game, mode-covering), with sample quality that soon passed GANs (Dhariwal & Nichol, 2021). By 2024 they drive text-to-image (DALL·E 2/3, Imagen, Stable Diffusion), video (Sora: a cat waking its owner for breakfast, from a paragraph of text) and even world models for robots (UniSim: imagining the results of actions).

The idea in one sentence: destroy data gradually with noise, and learn to undo one small step of destruction at a time. Each small undo is easy (§3 shows how easy, exactly); chaining a thousand of them turns noise into data.


2. The forward process

2.1 Adding noise in many small steps

DDPM defines a Markov chain that adds a little Gaussian noise at each of T=1000T = 1000 steps:

q(xi∣xi−1)=N(1−βi xi−1,  βiI),q(x_i \mid x_{i-1}) = N\big(\sqrt{1 - \beta_i}\, x_{i-1},\; \beta_i I\big),

with a variance schedule β1=10−4,…,βT=0.02\beta_1 = 10^{-4}, \ldots, \beta_T = 0.02 (linear). The 1−βi\sqrt{1 - \beta_i} shrinks the signal so that the total variance stays bounded (“variance preserving”). Because Gaussians compose, any step can be reached in one shot (Exercise 1):

q(xi∣x0)=N(αˉi x0,  (1−αˉi)I),αˉi=∏j≤i(1−βj),q(x_i \mid x_0) = N\big(\sqrt{\bar\alpha_i}\, x_0,\; (1 - \bar\alpha_i) I\big), \qquad \bar\alpha_i = \prod_{j \le i}(1 - \beta_j),

i.e. xi=αx0+σϵx_i = \alpha x_0 + \sigma\epsilon with α=αˉi\alpha = \sqrt{\bar\alpha_i}, σ=1−αˉi\sigma = \sqrt{1 - \bar\alpha_i}. This is what makes training cheap: no need to simulate the chain — pick a time, noise the data directly.

2.2 Schedules in continuous time

Homework 4 uses continuous time t∈[0,1]t \in [0, 1] and specifies αt,σt\alpha_t, \sigma_t directly, here the cosine schedule αt=cos⁡(πt/2)\alpha_t = \cos(\pi t/2), σt=sin⁡(πt/2)\sigma_t = \sin(\pi t/2) (α2+σ2=1\alpha^2 + \sigma^2 = 1). What matters about a schedule is how the signal-to-noise ratio SNR=α2/σ2\mathrm{SNR} = \alpha^2/\sigma^2 falls with tt — how much of the network’s capacity is spent on each noise level — and where it ends.

Experiment (script 01, Part 1). The smiley under the cosine schedule, with the exact KL from ptp_t to N(0,I)N(0, I):

ttαt\alpha_tlog SNR (cosine)log SNR (DDPM linear, i=1000ti = 1000t)KL(pt∥N(0,I)p_t \Vert N(0, I))
0.10.988+3.7+2.20.695
0.20.951+2.2+0.70.185
0.40.809+0.6−1.40.033
0.60.588−0.6−3.60.006
0.80.309−2.2−6.5≈ 0
1.00−∞−10.1≈ 0

The smiley is unrecognizable (KL < 0.04 nats) by t=0.4t = 0.4. DDPM’s linear schedule is noisier at every intermediate tt — and does not end at pure noise: αˉT=4×10−5\bar\alpha_T = 4 \times 10^{-5}, i.e. αT=0.0064\alpha_T = 0.0064 of the signal survives (log SNR −10.1). §7.2 explains why that matters.


3. The reverse process

3.1 The posterior of one step is Gaussian

Going backwards, q(xi−1∣xi)q(x_{i-1} \mid x_i) is intractable (it depends on the whole data distribution), but conditioned on x0x_0 it is a Gaussian (Exercise 2):

q(xi−1∣xi,x0)=N(μ~i(xi,x0),  β~iI),μ~i=αˉi−1 βi1−αˉi x0+1−βi (1−αˉi−1)1−αˉi xi,β~i=1−αˉi−11−αˉi βi.q(x_{i-1} \mid x_i, x_0) = N\big(\tilde\mu_i(x_i, x_0),\; \tilde\beta_i I\big), \quad \tilde\mu_i = \frac{\sqrt{\bar\alpha_{i-1}}\,\beta_i}{1 - \bar\alpha_i}\,x_0 + \frac{\sqrt{1 - \beta_i}\,(1 - \bar\alpha_{i-1})}{1 - \bar\alpha_i}\,x_i, \quad \tilde\beta_i = \frac{1 - \bar\alpha_{i-1}}{1 - \bar\alpha_i}\,\beta_i.

DDPM models the reverse step as a Gaussian too, pθ(xi−1∣xi)=N(μθ(xi,i),σi2I)p_\theta(x_{i-1} \mid x_i) = N(\mu_\theta(x_i, i), \sigma_i^2 I), with a fixed variance (βi\beta_i or β~i\tilde\beta_i). The slides call the full reverse model “conceptually helpful; but we never explicitly represent pθp_\theta”: what is learned is a denoiser.

3.2 Why may the reverse step be Gaussian?

The true q(xi−1∣xi)=∫q(xi−1∣xi,x0) q(x0∣xi) dx0q(x_{i-1} \mid x_i) = \int q(x_{i-1} \mid x_i, x_0)\, q(x_0 \mid x_i)\, dx_0 is a mixture of the Gaussians above, weighted by how likely each x0x_0 is given xix_i. If the step is small, xi−1x_{i-1} is pinned close to xix_i whatever x0x_0 is, and the mixture is nearly Gaussian; for big steps it can have many modes. (Feller’s classic result: the reverse of a diffusion with small enough steps has the same functional form.)

Experiment (script 01, Part 2). For the smiley the exact reverse step q(xs∣xt)q(x_s \mid x_t) is computable. KL in nats between it and the best single Gaussian (moment-matched), averaged over xtx_t:

ttstep Δ=0.001\Delta = 0.0010.010.050.10.2jump to the data
0.30.00000.00000.00400.04080.45071.143
0.60.00000.00000.00010.00050.00631.377
0.90.00000.00000.00000.00000.00021.428

With DDPM’s step size (Δ=0.001\Delta = 0.001) the Gaussian assumption is exact to four decimals. Near the data (small tt) larger steps quickly become non-Gaussian; at high noise even Δ=0.2\Delta = 0.2 is fine. This is why sampling needs many steps — and why later methods replace large Gaussian steps by GANs or distilled models (Lecture 12).

3.3 The variational bound, and “predict the noise”

A diffusion model is a latent variable model (Lecture 7) whose latents are x1,…,xTx_1, \ldots, x_T and whose “encoder” is the fixed forward process. Its ELBO splits into one term per step (Exercise 3):

−log⁡pθ(x0)≤KL(q(xT∣x0)∥p(xT))⏟≈0+∑i>1Eq KL(q(xi−1∣xi,x0) ∥ pθ(xi−1∣xi))⏟two Gaussians−Eqlog⁡pθ(x0∣x1).-\log p_\theta(x_0) \le \underbrace{\mathrm{KL}(q(x_T \mid x_0) \Vert p(x_T))}_{\approx 0} + \sum_{i > 1} E_q\,\underbrace{\mathrm{KL}\big(q(x_{i-1} \mid x_i, x_0) \,\Vert\, p_\theta(x_{i-1} \mid x_i)\big)}_{\text{two Gaussians}} - E_q \log p_\theta(x_0 \mid x_1).

Each KL between Gaussians with equal variance is a squared distance between means: 12σi2∥μ~i−μθ∥2\frac{1}{2\sigma_i^2}\lVert\tilde\mu_i - \mu_\theta\rVert^2. Ho et al. parameterize the mean through a noise prediction: since x0=(xi−1−αˉi ϵ)/αˉix_0 = (x_i - \sqrt{1 - \bar\alpha_i}\,\epsilon)/\sqrt{\bar\alpha_i},

μθ(xi,i)=11−βi(xi−βi1−αˉi ϵθ(xi,i)),KL term=βi22σi2(1−βi)(1−αˉi) ∥ϵ−ϵθ(xi,i)∥2.\mu_\theta(x_i, i) = \frac{1}{\sqrt{1 - \beta_i}}\Big(x_i - \frac{\beta_i}{\sqrt{1 - \bar\alpha_i}}\,\epsilon_\theta(x_i, i)\Big), \qquad \text{KL term} = \frac{\beta_i^2}{2\sigma_i^2 (1 - \beta_i)(1 - \bar\alpha_i)}\,\lVert \epsilon - \epsilon_\theta(x_i, i)\rVert^2 .

Dropping the weights gives the simple loss the slides call the variance-reduction version:

Lsimple=Et, x0, ϵ∥ϵ−ϵθ(αtx0+σtϵ, t)∥2.L_{\text{simple}} = E_{t,\, x_0,\, \epsilon}\big\lVert \epsilon - \epsilon_\theta(\alpha_t x_0 + \sigma_t \epsilon,\, t)\big\rVert^2 .

Training: pick an image, a time and a noise; noise the image; regress the noise. No game, no encoder, no posterior collapse. The re-weighting de-emphasizes the low-noise steps, which dominate the bound but matter little for sample quality; it makes the likelihood worse and the samples better (Ho et al. report both).


4. Scores, the optimal denoiser, and the inspirations

What does a perfectly trained network output? The loss is a squared error, so the minimizer is the conditional expectation:

ϵ∗(xt,t)=E[ϵ∣xt],x0∗(xt,t)=E[x0∣xt]=xt−σt ϵ∗αt.\epsilon^*(x_t, t) = E[\epsilon \mid x_t], \qquad x_0^*(x_t, t) = E[x_0 \mid x_t] = \frac{x_t - \sigma_t\,\epsilon^*}{\alpha_t}.

Tweedie’s formula connects it with the score of the noised distribution (Exercise 4):

∇xlog⁡pt(xt)=−ϵ∗(xt,t)σt,E[x0∣xt]=xt+σt2 ∇log⁡pt(xt)αt.\nabla_x \log p_t(x_t) = -\frac{\epsilon^*(x_t, t)}{\sigma_t}, \qquad E[x_0 \mid x_t] = \frac{x_t + \sigma_t^2\, \nabla \log p_t(x_t)}{\alpha_t}.

A noise predictor is a score estimator. That links DDPM to its two inspirations on the slides:

  • Nonequilibrium thermodynamics (Sohl-Dickstein et al., 2015) introduced diffusion models: a forward diffusion that slowly destroys structure and a learned reverse diffusion, trained with the same variational bound.
  • Score matching and annealed Langevin dynamics (Song & Ermon, 2019; NCSN): learn ∇log⁡pσ\nabla \log p_\sigma for a ladder of noise levels by denoising score matching (which is exactly the loss above), then sample with Langevin dynamics, x←x+δ2∇log⁡pσ(x)+δ zx \leftarrow x + \frac{\delta}{2}\nabla\log p_\sigma(x) + \sqrt{\delta}\,z, from high noise down to low. “Very promising sample generation” — and the score view leads to the SDE / ODE formulation used in §5.3.

For ShapeWorld and for the 402-Gaussian smiley, E[x0∣xt]E[x_0 \mid x_t] is a finite sum, so these scripts can sample with the optimal denoiser and compare it with every trained one.


5. Sampling

5.1 DDPM: ancestral sampling

Start from xT∼N(0,I)x_T \sim N(0, I) and repeatedly draw xi−1∼pθ(xi−1∣xi)x_{i-1} \sim p_\theta(x_{i-1} \mid x_i): predict the noise, form the mean, add fresh Gaussian noise. One network evaluation per step, 1,000 steps for the original DDPM.

5.2 DDIM: the same marginals, fewer and deterministic steps

Song, Meng & Ermon (2021) noticed that the training loss only involves the marginals q(xt∣x0)q(x_t \mid x_0), and many processes share them. Writing the predicted clean image x^0=(xt−σtϵ^)/αt\hat x_0 = (x_t - \sigma_t\hat\epsilon)/\alpha_t, a whole family of updates is consistent with the same marginals (Exercise 5):

xt′=αt′ x^0+σt′2−ηt2  ϵ^+ηt z,ηt=η σt′σt1−αt2αt′2,t′<t.x_{t'} = \alpha_{t'}\,\hat x_0 + \sqrt{\sigma_{t'}^2 - \eta_t^2}\;\hat\epsilon + \eta_t\, z, \qquad \eta_t = \eta\,\frac{\sigma_{t'}}{\sigma_t}\sqrt{1 - \frac{\alpha_t^2}{\alpha_{t'}^2}}, \quad t' < t.

η=1\eta = 1 gives DDPM’s ancestral step (this is homework 4’s formula); η=0\eta = 0 gives DDIM: deterministic — “move x^0\hat x_0 to the next noise level and add back the predicted noise”. Two consequences from the slides: the step size at inference can differ from training (most models give good samples with ~50 steps), and since noise xTx_T maps deterministically to an image, images can be inverted to noise (used for editing in Lecture 12).

5.3 The probability-flow ODE: a diffusion model is a flow

As the number of DDIM steps grows, the updates become an ordinary differential equation that carries pdatap_{\text{data}} to N(0,I)N(0, I) (Song et al., 2021). With the angle ϕ=πt/2\phi = \pi t/2 of the cosine schedule (x=cos⁡ϕ x0+sin⁡ϕ ϵx = \cos\phi\,x_0 + \sin\phi\,\epsilon) it is remarkably simple: dxdϕ=cos⁡ϕ ϵ^−sin⁡ϕ x^0=v^\frac{dx}{d\phi} = \cos\phi\,\hat\epsilon - \sin\phi\,\hat x_0 = \hat v. This is a continuous normalizing flow (Lecture 6): its log-likelihood is the prior’s plus the integrated divergence of the velocity field, computed exactly in 2-D with automatic differentiation.

5.4 Experiments (script 01, Parts 3–4): sampling with the optimal denoiser

No learning at all — the exact E[x0∣xt]E[x_0 \mid x_t] of the smiley — and different numbers of steps. “−log⁡pdata-\log p_{\text{data}}(sample)” is the true negative log-density of the generated points (for perfect samples it equals the entropy, 1.580); “off” counts samples in regions where real data are rare (1% for real samples):

stepssampler−log⁡pdata-\log p_{\text{data}}off the drawingsliced W1W_1
2DDPM / DDIM9.76 / 10.2058% / 60%0.43 / 0.43
5DDPM / DDIM3.19 / 3.2920% / 20%0.23 / 0.18
10DDPM / DDIM1.43 / 1.394.1% / 3.1%0.13 / 0.10
20DDPM / DDIM1.18 / 1.360.5% / 0.9%0.097 / 0.065
50DDPM / DDIM1.29 / 1.490.1% / 0.9%0.046 / 0.047
200DDPM / DDIM1.49 / 1.550.5% / 0.7%0.054 / 0.042
—real data1.5801.0%0.049

Sampling with the exact denoiser: 5 and 200 steps

  • Even a perfect denoiser needs steps. With 2–5 steps samples are smeared between the strokes (the figure); from 20–50 steps on they match the data (sliced W1W_1 at the real-vs-real floor). This error is pure discretization — the large-step non-Gaussianity of §3.2.
  • DDIM is better at few steps (sliced W1W_1 0.065 vs 0.097 at 20 steps): it adds no fresh noise that later steps must remove.
  • DDPM with few steps is under-dispersed: its samples have lower −log⁡pdata-\log p_{\text{data}} than real data (1.18 at 20 steps vs 1.58) — they crowd the centers of the strokes. The fixed variance of each step ignores the uncertainty about x0x_0; Improved DDPM (Nichol & Dhariwal, 2021) learns the variance for this reason (“learned variance” on the slides). With 200 steps the effect fades.

The ODE likelihood of the exact model, 200 test points: 1.6631 nats with 200 RK4 steps vs the exact 1.6631 (largest per-point difference 0.0008; 0.013 with 50 steps, 2.3 with 10). A diffusion model has an exact likelihood — through its ODE.


6. Training a denoiser (homework 4 Q1)

Setup (script 02). An MLP with 4 hidden layers of 64 units on cat(x,t)\mathrm{cat}(x, t), trained on 100,000 points of the smiley with batch 1,024 for 6,000 steps (homework 4’s recipe). Because the exact ϵ∗\epsilon^* is known, the loss can be split into the irreducible part (the optimal denoiser’s error) and the network’s excess error:

ttoptimal E∥ϵ∗−ϵ∥2E\lVert\epsilon^* - \epsilon\rVert^2network E∥ϵ^−ϵ∥2E\lVert\hat\epsilon - \epsilon\rVert^2excess
0.021.8881.995+0.107
0.051.5281.949+0.421
0.101.1491.863+0.715
0.201.3861.709+0.323
0.401.2971.307+0.009
0.600.7510.755+0.004
0.950.0140.015+0.001

Most of the loss is irreducible: even the optimal denoiser cannot tell which nearby point of the drawing produced a noisy observation. The network is near-optimal at high noise and far from it at low noise (tt = 0.05–0.2), where the strokes (0.1 wide) must be resolved — invisible in the training curve, which averages over tt.

Samples (Part 2): with the same samplers, the network is much worse than the optimal denoiser — about half of its samples fall off the drawing even with 200 DDPM steps, and DDIM with few steps explodes (−log⁡p-\log p in the thousands). §7 finds the cause.

Likelihood through the ODE (Part 3, 300 test points; exact: 1.509 nats): the ϵ\epsilon-network 2.773 (+1.26), the vv-network 1.671 (+0.16), the x0x_0-network 607 — useless (§7).

Samples of the trained networks


7. What to predict, and where the schedule ends

7.1 ϵ\epsilon, x0x_0 or vv

Any one of ϵ\epsilon, x0x_0 or v=αtϵ−σtx0v = \alpha_t\epsilon - \sigma_t x_0 determines the others given xtx_t (with α2+σ2=1\alpha^2 + \sigma^2 = 1: ϵ=αv+σxt\epsilon = \alpha v + \sigma x_t, x0=αxt−σvx_0 = \alpha x_t - \sigma v). They differ in conditioning. The slides motivate vv geometrically: (αt,σt)(\alpha_t, \sigma_t) is a point on the unit circle, xtx_t rotates from x0x_0 to ϵ\epsilon as the angle grows, and vv is the velocity of that rotation, dxt/dϕdx_t/d\phi. Progressive distillation (Salimans & Ho, 2022) introduced it because the others break at one end:

  • ϵ\epsilon-prediction at high noise: x^0=(xt−σtϵ^)/αt\hat x_0 = (x_t - \sigma_t\hat\epsilon)/\alpha_t divides by αt→0\alpha_t \to 0;
  • x0x_0-prediction at low noise: ϵ^=(xt−αtx^0)/σt\hat\epsilon = (x_t - \alpha_t\hat x_0)/\sigma_t divides by σt→0\sigma_t \to 0;
  • vv-prediction is a rotation of (x0,ϵ)(x_0, \epsilon) — bounded at both ends.

Experiment (script 02, Part 4). The same MLP, trained on each target; errors against the optimal denoiser after converting to ϵ^\hat\epsilon and x^0\hat x_0:

predictiont=0.001t = 0.001: ϵ^\hat\epsilon err / x^0\hat x_0 errt=0.05t = 0.05t=0.5t = 0.5t=0.95t = 0.95t=1−10−4t = 1 - 10^{-4}
ϵ\epsilon0.028 / 7e-80.42 / 0.00260.0055 / 0.00550.0012 / 0.190.0013 / 51,000
x0x_0390 / 0.00100.51 / 0.00320.0006 / 0.00065e-6 / 0.00087e-11 / 0.0027
vv0.29 / 7e-70.027 / 0.00020.0010 / 0.00102e-6 / 0.00042e-11 / 0.0009
predictionDDIM 50 steps: −log⁡pdata-\log p_{\text{data}} / off / sliced W1W_1DDPM 200 steps
ϵ\epsilon607 / 92% / 1.847.14 / 51% / 0.097
x0x_07.18 / 51% / 0.0996.47 / 44% / 0.109
vv2.15 / 8.6% / 0.0331.84 / 4.6% / 0.047

The ϵ\epsilon-network’s error near t=1t = 1 is tiny (0.0013), but the sampler’s first step from t=1−10−4t = 1 - 10^{-4} turns it into an x^0\hat x_0 error of 51,000 (1/α2=4×1071/\alpha^2 = 4 \times 10^7). The x0x_0-network’s ϵ^\hat\epsilon explodes near t=0t = 0 (which ruins its ODE likelihood). The vv-network is well-behaved at both ends and — same architecture, same budget — gives samples at the real-data noise floor. For images, homework 4’s remedy for ϵ\epsilon-prediction is to clip x^0\hat x_0 to the data range [−1,1][-1, 1] at every step, which removes the explosion (script 03 does so).

7.2 Zero terminal SNR

Lin et al. (2024): most schedules do not reach pure noise at t=Tt = T — Stable Diffusion’s ends at αˉT≈0.0047\bar\alpha_T \approx 0.0047; DDPM’s linear one at 4×10−54 \times 10^{-5} (§2). Two problems follow. During training the “noisiest” inputs still leak global information about x0x_0 (e.g. its mean brightness), and the network learns to use it; at sampling time we start from pure N(0,I)N(0, I), where there is no such signal, and the model reads signal into noise — Stable Diffusion could not make very dark or very bright images. The fix: rescale the schedule so that αT=0\alpha_T = 0 exactly. But at αT=0\alpha_T = 0 the ϵ\epsilon-target is trivial (xT=ϵx_T = \epsilon, the network learns the identity) and x^0\hat x_0 is undefined — the ϵ\epsilon row of the table above taken to its limit. vv-prediction to the rescue: at t=Tt = T, v=−x0v = -x_0, a meaningful target (“predict the mean image”). The slides’ recipe: rescale the schedule to zero terminal SNR and fine-tune with the vv-loss. Homework 4’s cosine schedule already ends at α=0\alpha = 0.


8. The U-Net, and pixel diffusion on ShapeWorld

8.1 Architecture

DDPM’s backbone is PixelCNN++‘s U-Net (a Wide ResNet): residual blocks at several resolutions (32×32 down to 4×4 for CIFAR), downsampling and upsampling paths connected by skip connections, group normalization, self-attention at 16×16, and the time tt injected into every residual block through a sinusoidal embedding (as for Transformer positions) and a small MLP. Two ways to inject a conditioning vector (time, class, later text): add it to the feature map (homework 4’s U-Net), or use it to produce a per-channel scale and shift (adaptive group norm / FiLM), which works better (Dhariwal & Nichol). The CIFAR-10 model had 35.7 million parameters; the LSUN / CelebA-HQ models 114–256 million. Dhariwal & Nichol’s architecture improvements: more attention heads and resolutions, BigGAN-style residual up/downsampling, adaptive group norm.

8.2 Experiment: between the truth and the training set (script 03)

Setup. Homework 4 Q2’s U-Net, small: channels (16, 32) at 12×24 and 6×12, one residual block per resolution, time embedding added in every block — 160,000 parameters; ϵ\epsilon-prediction, batch 64, 10,000 steps (~45 minutes on one CPU thread). Sampling: DDPM, 100 steps, x^0\hat x_0 clipped to [−1,1][-1, 1]. The two exact denoisers are used with the same sampler.

Part 1 — samples (2,000 each):

denoiservalidnovel validflipscopy rateISFIDprecisionrecall
exact, for the true pdatap_{\text{data}}100%87.5%0.000.577.884060.950.95
exact, for the training set100%0.0%0.000.577.893640.950.93
U-Net (160k parameters)30.4%28.6%6.20.237.571,8630.900.94

(real data: 100% valid, 87% novel, copy rate 0.5625, FID between two real sets 323–437.)

Samples of the three denoisers

  • The optimal denoiser for the true distribution generates the true distribution: every sample valid, 87.5% new (real data: 87%), the copy rule right (0.57).
  • The optimal denoiser for the training set reproduces the training set: every sample valid and none new — and the better FID of the two (364): FID cannot tell (Lecture 9). Minimizing the training loss perfectly is memorization.
  • The U-Net sits in between, on the right side: 30% of its samples are valid ShapeWorld images, nearly all of them new; 6 flips on average. By FID (1,863) and precision / recall (0.90 / 0.94: no mode-seeking) it beats every GAN (Lectures 9–10: FID ≥ 14,893, recall ≤ 0.37) and the VAE, and it beats the 18-token VQ-VAE + Transformer of Lecture 8 in validity (26%). Like Lecture 3’s convolutional models it misses the long-range copy rule (0.23 vs 0.56).

Part 2 — between the two optima. For 300 noised test images, the squared distance (per image, pixels in {−1,+1}\{-1, +1\}) between the U-Net’s x^0\hat x_0 and each optimal denoiser:

ttU-Net vs truth’s optimumU-Net vs training set’s optimumtraining set’s vs truth’s optimum
0.10.0362.262.1
0.30.2461.561.6
0.53.059.861.4
0.728.051.945.7
0.911.211.80.6

On test images the memorizing optimum snaps to the nearest training image (distance ~62 from the truth at low noise), while the U-Net agrees with the true optimum almost exactly at low noise (0.03 at t=0.1t = 0.1): it has learned to denoise shapes, not to recall images — it generalizes. Its error is concentrated at mid noise (tt ≈ 0.7), the level where the image’s identity (which shapes, where) is decided; mistakes made there are what the low-noise steps later render as crisp but invalid shapes.

Part 3 — sampling steps (500 samples):

steps102050100200
DDPM: valid / flips16.4% / 7.326.2% / 6.429.6% / 6.231.8% / 6.132.0% / 6.5
DDIM: valid / flips6.4% / 11.17.6% / 10.89.0% / 10.59.0% / 10.012.2% / 8.9

With the exact denoiser DDIM was the better sampler at few steps (§5.4); with an imperfect network it is much worse here (9% vs 30% valid at 50–100 steps). The fresh noise of each DDPM step lets later steps correct an earlier mistake; DDIM’s deterministic path commits to it. (Karras et al., 2022, make the same observation and add controlled “churn” noise to deterministic samplers.)

Plan vs reality. The first version of this experiment trained the U-Net for 4,000 steps, and it gave 1.8% valid samples (FID 3,577; DDIM 0.6%). Training 2.5× longer — the same model, recipe and seed — raised validity to 30%. The loss had looked converged (0.0245 at both 3,200 and 4,000 steps, but the cosine learning-rate schedule was already near 0); the samples were not. Undertrained diffusion models look almost right; a pixel-exact criterion makes the difference visible.


9. Guidance

9.1 Classifier guidance

Dhariwal & Nichol (“Diffusion models beat GANs on image synthesis”, 2021) added a term to the sampler that steers each step towards a class yy. By Bayes’ rule, ∇log⁡p(xt∣y)=∇log⁡p(xt)+∇log⁡p(y∣xt)\nabla \log p(x_t \mid y) = \nabla\log p(x_t) + \nabla\log p(y \mid x_t), so with a classifier trained on noisy images pϕ(y∣xt)p_\phi(y \mid x_t):

ϵ~=ϵ^(xt)−w σt ∇xtlog⁡pϕ(y∣xt).\tilde\epsilon = \hat\epsilon(x_t) - w\,\sigma_t\,\nabla_{x_t}\log p_\phi(y \mid x_t).

w=1w = 1 samples p(x∣y)p(x \mid y); w>1w > 1 samples ∝p(x) p(y∣x)w\propto p(x)\,p(y \mid x)^w — a sharper, “lower temperature” distribution that favours images the classifier is sure about. With w≈1w \approx 1–10, guided ImageNet models matched BigGAN’s image quality with better diversity (higher recall).

9.2 Classifier-free guidance

Ho & Salimans (2022): can we get the sharpening without training a separate noisy classifier? Bayes again: ∇log⁡p(y∣xt)=∇log⁡p(xt∣y)−∇log⁡p(xt)\nabla\log p(y \mid x_t) = \nabla\log p(x_t \mid y) - \nabla\log p(x_t), and both terms are diffusion models. Train one network on both: replace the label by a “null” token 10–20% of the time (“a one-line change of code during training”). At sampling time mix the two predictions:

ϵ~=ϵ^(xt,∅)+w (ϵ^(xt,y)−ϵ^(xt,∅))\tilde\epsilon = \hat\epsilon(x_t, \varnothing) + w\,\big(\hat\epsilon(x_t, y) - \hat\epsilon(x_t, \varnothing)\big)

(w=0w = 0: unconditional, w=1w = 1: conditional, w>1w > 1: guided; the slides write the same thing as (1+w′)ϵ^(x,y)−w′ϵ^(x,∅)(1 + w')\hat\epsilon(x, y) - w'\hat\epsilon(x, \varnothing)). The slides’ plot of FID and IS against ww: IS keeps improving (each sample a more “realistic member of its class”), FID improves briefly and then gets worse (diversity is lost). GLIDE, DALL·E 2, Imagen and Stable Diffusion all use it (Lecture 12).

9.3 Experiment (script 04)

Class = the kind of the left shape. 100 samples per class (800), DDPM 50 steps. “Requested shape” and “right = requested” are read exactly from valid samples; in the true conditional distribution p(x∣y)p(x \mid y) they are 100% and 0.5625.

Part 1 — classifier guidance with the exact model. The exact unconditional denoiser plus the exact noisy classifier p(y∣xt)p(y \mid x_t) (both from ShapeWorld’s tables): ϵ~=ϵ∗−w σt∇log⁡p(y∣xt)\tilde\epsilon = \epsilon^* - w\,\sigma_t\nabla\log p(y \mid x_t).

scale wwvalidrequested shaperight = requestednovel validdistinctFIDprecisionrecall
0 (unconditional)100%13.6%0.1389.8%7969730.940.94
1100%100%0.5688.2%7956650.950.93
2100%100%0.7080.1%7802,5080.960.93
4100%100%0.8066.1%7289,0260.970.88

At w=1w = 1, Bayes’ rule on the score is exact: the samples are p(x∣y)p(x \mid y) — the requested shape every time, the right panel copying it at exactly the data’s rate, novelty unchanged. Above 1, every sample is still valid and of the right class, yet the distribution is distorted: guidance favours images that are “most clearly class yy”, and in ShapeWorld the clearest evidence for the left shape is the right panel showing it too (copy rate 0.56 → 0.80). Novelty falls and FID rises tenfold. Here the trade-off is not “quality vs diversity” — quality is perfect throughout — it is typicality vs faithfulness to the distribution.

Part 2 — classifier-free guidance with a U-Net. Lecture 11’s U-Net with a class embedding added to the time embedding, trained 10,000 steps with the class dropped 10% of the time; ϵ~=ϵ^(x,∅)+w(ϵ^(x,y)−ϵ^(x,∅))\tilde\epsilon = \hat\epsilon(x, \varnothing) + w(\hat\epsilon(x, y) - \hat\epsilon(x, \varnothing)):

scale wwvalidrequested shaperight = requestednovel validFIDprecisionrecall
0 (unconditional)23.9%11.5%0.1522.8%3,4530.900.92
1 (conditional)25.9%88.9%0.6023.2%1,7960.920.91
227.0%98.1%0.9022.2%2,0000.950.85
326.9%99.1%0.9421.4%4,4540.930.82
521.9%100%0.9814.6%9,1500.920.73
720.0%100%0.9712.5%12,3960.910.69

Exact classifier guidance and classifier-free guidance (columns: requested class)

  • The slides’ FID curve, measured: from w=0w = 0 to 1, FID improves (3,453 → 1,796 — the conditional model is simply the better model) and the requested shape goes from chance to 89%. Beyond, class adherence saturates at 100% while FID worsens (12,396 at w=7w = 7) and recall falls (0.91 → 0.69): diversity is traded for class-typicality.
  • The conditional model learned the copy rule (0.60 at w=1w = 1, vs 0.15 unconditionally — and vs 0.23 for Lecture 11’s unconditional U-Net): telling the network the left shape makes the long-range dependency easy. Guidance then overshoots it (0.90 at w=2w = 2, 0.98 at w=5w = 5), more than exact guidance does (0.70, 0.80): the learned conditional over-weights the class for the right panel too.
  • Validity barely depends on guidance (20–27%): guidance makes samples more class-typical, not more correct. Pixel-level errors are the network’s, and no sampling trick removes them.

10. Summary

  1. A diffusion model destroys data with noise in closed form (xt=αtx0+σtϵx_t = \alpha_t x_0 + \sigma_t\epsilon) and learns to undo one small step at a time; training is regression of the noise, a re-weighted variational bound.
  2. The true reverse step is Gaussian for small steps and multimodal for large ones (KL to the best Gaussian: 0.0000 at Δ=0.01\Delta = 0.01, 0.45 at Δ=0.2\Delta = 0.2 near the data) — why sampling needs many steps.
  3. The optimal noise prediction is the scaled score, ϵ∗=−σ∇log⁡pt\epsilon^* = -\sigma\nabla\log p_t (Tweedie); the optimal denoiser is the posterior mean — computable exactly for a Gaussian mixture and for ShapeWorld.
  4. Even the optimal denoiser needs ~20+ steps; DDIM beats DDPM at few steps with the exact model; DDPM with few steps under-disperses (learned variances, Improved DDPM). The probability-flow ODE is a flow whose likelihood matched the exact density to 0.0008 nats.
  5. A trained network is near-optimal at high noise and far off at low noise in 2-D; its error is invisible in the average loss.
  6. ϵ\epsilon-prediction explodes near t=1t = 1 (x^0\hat x_0 divides by α\alpha: error 51,000), x0x_0-prediction near t=0t = 0; vv-prediction is well-conditioned at both ends and gave samples at the noise floor. Schedules should reach zero terminal SNR.
  7. On ShapeWorld the exact denoiser for the truth generates the truth (100% valid, 87.5% new); the exact denoiser for the training set reproduces it (100% valid, 0% new, better FID). A 160k-parameter U-Net (10,000 steps) sits in between on the side of the truth: 30% valid, nearly all new, FID 1,863, precision / recall 0.90 / 0.94 — better than every GAN and the VAE — and agrees with the true optimum on test images at low noise. Its errors live at mid noise. A 4,000-step version gave only 1.8% valid samples.
  8. For an imperfect network DDPM beats DDIM (32% vs 9% valid): fresh noise lets later steps correct mistakes.
  9. Guidance: exact classifier guidance at scale 1 samples p(x∣y)p(x \mid y) exactly; larger scales keep samples valid but distort the distribution (copy rate 0.56 → 0.80, novelty 88% → 66%). Classifier-free guidance improves FID from ww = 0 to 1 (3,453 → 1,796), then trades diversity for class-typicality (recall 0.91 → 0.69 at w=7w = 7) without making samples more valid.

11. Common pitfalls

  1. Reading the training loss as sample quality. Most of a diffusion loss is irreducible (the optimal denoiser’s error is 1.9 at small tt in script 02), and it averages over tt: a network can be near-optimal at high noise and far off at low noise without the curve showing it.
  2. Starting the sampler at t=1t = 1 exactly with the cosine schedule: α=0\alpha = 0 and x^0=(x−σϵ^)/α\hat x_0 = (x - \sigma\hat\epsilon)/\alpha is undefined. Start at 1−10−41 - 10^{-4} — and know that an ϵ\epsilon-network’s tiny error is then multiplied by 1/α1/\alpha (clip x^0\hat x_0, or predict vv).
  3. Few DDPM steps. Ancestral sampling with a fixed variance under-disperses (and eventually smears) when steps are large; use DDIM or many steps — or distillation (Lecture 12).
  4. Forgetting that guidance changes the distribution. w>1w > 1 samples ∝p(x)p(y∣x)w\propto p(x)p(y \mid x)^w, not p(x∣y)p(x \mid y): more typical, less diverse, and — script 04 — joint statistics such as “the right shape copies the left one” drift.
  5. Using the same noise for training and evaluation of the loss across noise levels, or comparing losses of ϵ\epsilon-, x0x_0- and vv-models directly: they weight noise levels differently; convert predictions to the same quantity first (script 02, Part 4).
  6. Confusing “valid” with “novel”. The training set’s own optimal denoiser gives 100% valid samples — all copies. Check samples against the training set.
  7. A schedule that does not reach pure noise (DDPM’s linear one ends at α=0.0064\alpha = 0.0064): the model learns to rely on leaked signal it will not get at sampling time.
  8. Forgetting x̂_0 clipping for images with ϵ\epsilon-prediction (homework 4’s tip): without it the first steps can push samples far outside [−1,1][-1, 1].

12. Exercises

Exercise 1 (one-shot noising — derivation). From q(xi∣xi−1)=N(1−βi xi−1,βiI)q(x_i \mid x_{i-1}) = N(\sqrt{1 - \beta_i}\,x_{i-1}, \beta_i I), show q(xi∣x0)=N(αˉi x0,(1−αˉi)I)q(x_i \mid x_0) = N(\sqrt{\bar\alpha_i}\,x_0, (1 - \bar\alpha_i)I).

Answer

Induction. If xi−1=αˉi−1x0+1−αˉi−1 ϵ1x_{i-1} = \sqrt{\bar\alpha_{i-1}}x_0 + \sqrt{1 - \bar\alpha_{i-1}}\,\epsilon_1, then xi=1−βi xi−1+βi ϵ2=αˉi x0+[(1−βi)(1−αˉi−1) ϵ1+βi ϵ2]x_i = \sqrt{1 - \beta_i}\,x_{i-1} + \sqrt{\beta_i}\,\epsilon_2 = \sqrt{\bar\alpha_i}\,x_0 + \big[\sqrt{(1 - \beta_i)(1 - \bar\alpha_{i-1})}\,\epsilon_1 + \sqrt{\beta_i}\,\epsilon_2\big]. The bracket is Gaussian with variance (1−βi)(1−αˉi−1)+βi=1−(1−βi)αˉi−1=1−αˉi(1 - \beta_i)(1 - \bar\alpha_{i-1}) + \beta_i = 1 - (1 - \beta_i)\bar\alpha_{i-1} = 1 - \bar\alpha_i.

Exercise 2 (the posterior of a step — derivation). Derive q(xi−1∣xi,x0)q(x_{i-1} \mid x_i, x_0) (mean μ~i\tilde\mu_i, variance β~i\tilde\beta_i of §3.1).

Answer

Bayes: q(xi−1∣xi,x0)∝q(xi∣xi−1) q(xi−1∣x0)q(x_{i-1} \mid x_i, x_0) \propto q(x_i \mid x_{i-1})\,q(x_{i-1} \mid x_0), both Gaussian in xi−1x_{i-1}. The precisions add: 1−βiβi+11−αˉi−1=1−αˉiβi(1−αˉi−1)\frac{1 - \beta_i}{\beta_i} + \frac{1}{1 - \bar\alpha_{i-1}} = \frac{1 - \bar\alpha_i}{\beta_i(1 - \bar\alpha_{i-1})}, so β~i=1−αˉi−11−αˉiβi\tilde\beta_i = \frac{1 - \bar\alpha_{i-1}}{1 - \bar\alpha_i}\beta_i. The mean is β~i\tilde\beta_i times the precision-weighted sum 1−βiβixi+αˉi−11−αˉi−1x0\frac{\sqrt{1 - \beta_i}}{\beta_i}x_i + \frac{\sqrt{\bar\alpha_{i-1}}}{1 - \bar\alpha_{i-1}}x_0, which gives the two coefficients of §3.1.

Exercise 3 (the variational bound — derivation). Starting from log⁡pθ(x0)≥Eq[log⁡pθ(x0:T)−log⁡q(x1:T∣x0)]\log p_\theta(x_0) \ge E_q[\log p_\theta(x_{0:T}) - \log q(x_{1:T} \mid x_0)], show that the bound splits into the prior term, one KL per step between q(xi−1∣xi,x0)q(x_{i-1} \mid x_i, x_0) and pθ(xi−1∣xi)p_\theta(x_{i-1} \mid x_i), and a reconstruction term.

Answer

Write q(x1:T∣x0)=q(xT∣x0)∏i>1q(xi−1∣xi,x0)q(x_{1:T} \mid x_0) = q(x_T \mid x_0)\prod_{i > 1} q(x_{i-1} \mid x_i, x_0) (Bayes on each step of the Markov chain, conditioned on x0x_0) and pθ(x0:T)=p(xT)∏i≥1pθ(xi−1∣xi)p_\theta(x_{0:T}) = p(x_T)\prod_{i \ge 1}p_\theta(x_{i-1} \mid x_i). The log-ratio becomes log⁡p(xT)q(xT∣x0)+∑i>1log⁡pθ(xi−1∣xi)q(xi−1∣xi,x0)+log⁡pθ(x0∣x1)\log\frac{p(x_T)}{q(x_T \mid x_0)} + \sum_{i > 1}\log\frac{p_\theta(x_{i-1} \mid x_i)}{q(x_{i-1} \mid x_i, x_0)} + \log p_\theta(x_0 \mid x_1); taking expectations turns the first two kinds of terms into minus KL divergences.

Exercise 4 (Tweedie’s formula — derivation). For xt=αx0+σϵx_t = \alpha x_0 + \sigma\epsilon, show ∇xtlog⁡pt(xt)=−E[ϵ∣xt]/σ\nabla_{x_t}\log p_t(x_t) = -E[\epsilon \mid x_t]/\sigma and hence E[x0∣xt]=(xt+σ2∇log⁡pt(xt))/αE[x_0 \mid x_t] = (x_t + \sigma^2\nabla\log p_t(x_t))/\alpha.

Answer

pt(xt)=∫p(x0) N(xt;αx0,σ2I) dx0p_t(x_t) = \int p(x_0)\,N(x_t; \alpha x_0, \sigma^2 I)\,dx_0. Differentiate under the integral: ∇pt=∫p(x0)N(⋅) (−(xt−αx0)/σ2) dx0\nabla p_t = \int p(x_0) N(\cdot)\,\big(-(x_t - \alpha x_0)/\sigma^2\big)\,dx_0. Divide by ptp_t: ∇log⁡pt=−E[(xt−αx0)/σ2∣xt]=−E[ϵ∣xt]/σ\nabla\log p_t = -E[(x_t - \alpha x_0)/\sigma^2 \mid x_t] = -E[\epsilon \mid x_t]/\sigma. Substituting ϵ=(xt−αx0)/σ\epsilon = (x_t - \alpha x_0)/\sigma and solving for E[x0∣xt]E[x_0 \mid x_t] gives the second form.

Exercise 5 (DDIM). Show that the update xt′=αt′x^0+σt′2−ηt2 ϵ^+ηtzx_{t'} = \alpha_{t'}\hat x_0 + \sqrt{\sigma_{t'}^2 - \eta_t^2}\,\hat\epsilon + \eta_t z maps xt∼q(xt∣x0)x_t \sim q(x_t \mid x_0) to xt′∼q(xt′∣x0)x_{t'} \sim q(x_{t'} \mid x_0) when x^0=x0\hat x_0 = x_0 and ϵ^=ϵ\hat\epsilon = \epsilon are exact, for any ηt≤σt′\eta_t \le \sigma_{t'}.

Answer

With exact predictions, xt′=αt′x0+σt′2−ηt2 ϵ+ηtzx_{t'} = \alpha_{t'}x_0 + \sqrt{\sigma_{t'}^2 - \eta_t^2}\,\epsilon + \eta_t z, where ϵ\epsilon and zz are independent standard normals. The noise part has variance σt′2−ηt2+ηt2=σt′2\sigma_{t'}^2 - \eta_t^2 + \eta_t^2 = \sigma_{t'}^2, so xt′=αt′x0+σt′ϵ′x_{t'} = \alpha_{t'}x_0 + \sigma_{t'}\epsilon': the right marginal for every ηt\eta_t. Training never sees how xtx_t and xt′x_{t'} are jointly distributed, only the marginals — which is why one network supports the whole family. ηt\eta_t as in homework 4 reproduces DDPM’s posterior variance; η=0\eta = 0 is deterministic.

Exercise 6 (ϵ\epsilon-loss vs x0x_0-loss vs vv-loss). Show ∥ϵ^−ϵ∥2=SNR(t) ∥x^0−x0∥2\lVert\hat\epsilon - \epsilon\rVert^2 = \mathrm{SNR}(t)\,\lVert\hat x_0 - x_0\rVert^2 and ∥v^−v∥2=(1+SNR(t)) ∥x^0−x0∥2\lVert\hat v - v\rVert^2 = (1 + \mathrm{SNR}(t))\,\lVert\hat x_0 - x_0\rVert^2 (with α2+σ2=1\alpha^2 + \sigma^2 = 1). Which noise levels does each loss emphasize?

Answer

ϵ^−ϵ=(x−αx^0)/σ−(x−αx0)/σ=−(α/σ)(x^0−x0)\hat\epsilon - \epsilon = (x - \alpha\hat x_0)/\sigma - (x - \alpha x_0)/\sigma = -(\alpha/\sigma)(\hat x_0 - x_0): squared, SNR=α2/σ2\mathrm{SNR} = \alpha^2/\sigma^2. For vv: v=αϵ−σx0v = \alpha\epsilon - \sigma x_0 and ϵ=(x−αx0)/σ\epsilon = (x - \alpha x_0)/\sigma, so v=(αx−x0)/σv = (\alpha x - x_0)/\sigma and v^−v=−(x^0−x0)/σ\hat v - v = -(\hat x_0 - x_0)/\sigma: squared, 1/σ2=1+SNR1/\sigma^2 = 1 + \mathrm{SNR}. So ϵ\epsilon-loss weights x0x_0-errors by SNR (huge at low noise, zero at pure noise); vv-loss by 1+SNR1 + \mathrm{SNR} (never zero: high-noise levels still count); x0x_0-loss weights all equally.

Exercise 7 (classifier-free guidance as a distribution — derivation). Show that ϵ~=ϵ^(x,∅)+w(ϵ^(x,y)−ϵ^(x,∅))\tilde\epsilon = \hat\epsilon(x, \varnothing) + w(\hat\epsilon(x, y) - \hat\epsilon(x, \varnothing)) corresponds to the score of p~t(x)∝pt(x)1−w pt(x∣y)w∝pt(x) pt(y∣x)w\tilde p_t(x) \propto p_t(x)^{1 - w}\,p_t(x \mid y)^w \propto p_t(x)\,p_t(y \mid x)^w.

Answer

ϵ^=−σ∇log⁡p\hat\epsilon = -\sigma\nabla\log p, so ϵ~=−σ[(1−w)∇log⁡pt(x)+w∇log⁡pt(x∣y)]=−σ∇log⁡(pt(x)1−wpt(x∣y)w)\tilde\epsilon = -\sigma[(1 - w)\nabla\log p_t(x) + w\nabla\log p_t(x \mid y)] = -\sigma\nabla\log\big(p_t(x)^{1 - w}p_t(x \mid y)^w\big). With Bayes, pt(x∣y)=pt(y∣x)pt(x)/p(y)p_t(x \mid y) = p_t(y \mid x)p_t(x)/p(y), and the product is ∝pt(x) pt(y∣x)w\propto p_t(x)\,p_t(y \mid x)^w. (Strictly, the noised versions of this tilted distribution are not the tilted noised distributions, so guided sampling is a heuristic for w≠0,1w \ne 0, 1 — one reason guidance distorts statistics.)

Exercise 8 (memorization). Show that the optimal denoiser for a training set {x(i)}\{x^{(i)}\} is E[x0∣xt]=∑isoftmaxi(−∥xt−αx(i)∥2/2σ2) x(i)E[x_0 \mid x_t] = \sum_i \mathrm{softmax}_i\big(-\lVert x_t - \alpha x^{(i)}\rVert^2/2\sigma^2\big)\,x^{(i)}, and argue that sampling with it (many small steps) returns a training image.

Answer

The data distribution is uniform over the NN training images; given xtx_t, the posterior over which image was noised is proportional to N(xt;αx(i),σ2I)N(x_t; \alpha x^{(i)}, \sigma^2 I); the posterior mean is the weighted average. As t→0t \to 0 the softmax sharpens onto the nearest training image, and the reverse dynamics are attracted to it: the sampler’s endpoint is one of the x(i)x^{(i)}. A network that generalizes must therefore fail to minimize the training loss perfectly — script 03 measures where it sits between the two optima.

Exercise 9 (coding). In script 02, train the ϵ\epsilon-network twice as long (12,000 steps) and check whether its low-noise excess error and its samples improve. Then sample it with x^0\hat x_0 clipped to [−3,3][-3, 3].

Answer

(Run it.) Expect the excess error at tt = 0.05–0.2 to shrink but not vanish (capacity), the DDIM explosion to remain without clipping (it is a conditioning problem near t=1t = 1, not a training problem), and clipping to remove the explosion while leaving the low-noise blur.


13. Further reading

From the slides

  • J. Ho, A. Jain, P. Abbeel. Denoising Diffusion Probabilistic Models, NeurIPS 2020.
  • J. Sohl-Dickstein et al. Deep Unsupervised Learning using Nonequilibrium Thermodynamics, ICML 2015; Y. Song, S. Ermon. Generative Modeling by Estimating Gradients of the Data Distribution (NCSN), NeurIPS 2019.
  • P. Dhariwal, A. Nichol. Diffusion Models Beat GANs on Image Synthesis, NeurIPS 2021; A. Nichol, P. Dhariwal. Improved Denoising Diffusion Probabilistic Models, ICML 2021.
  • J. Ho, T. Salimans. Classifier-Free Diffusion Guidance, 2022.
  • J. Song, C. Meng, S. Ermon. Denoising Diffusion Implicit Models, ICLR 2021.
  • T. Salimans, J. Ho. Progressive Distillation for Fast Sampling of Diffusion Models (vv-parameterization), ICLR 2022.
  • S. Lin et al. Common Diffusion Noise Schedules and Sample Steps are Flawed, WACV 2024.
  • O. Ronneberger, P. Fischer, T. Brox. U-Net, MICCAI 2015.
  • Tutorials linked from the slides: L. Weng’s blog post on diffusion models; the CVPR 2022 diffusion tutorial; C. Luo, Understanding Diffusion Models: A Unified Perspective, 2022; Y. Song’s blog on score-based models; and, for what the lecture skipped, Y. Song et al., Score-Based Generative Modeling through SDEs (ICLR 2021) and T. Karras et al., Elucidating the Design Space of Diffusion-Based Generative Models (NeurIPS 2022).

Added by these notes

  • B. Efron. Tweedie’s Formula and Selection Bias, JASA 2011 — the posterior-mean / score identity of §4.
  • Z. Kadkhodaie, F. Guth, E. Simoncelli, S. Mallat. Generalization in Diffusion Models Arises from Geometry-Adaptive Harmonic Representations, ICLR 2024 — when diffusion models memorize vs generalize (§8).
  • N. Carlini et al. Extracting Training Data from Diffusion Models, USENIX Security 2023.
  • D. Kingma, T. Salimans, B. Poole, J. Ho. Variational Diffusion Models, NeurIPS 2021 — the ELBO in terms of the SNR, and how loss weightings relate.

14. Next lecture

Lecture 11 built diffusion models from first principles on pixels. Lecture 12 follows them into the systems on the slides: text-to-image (GLIDE, DALL·E 2, Imagen, DALL·E 3), latent diffusion and the Diffusion Transformer (homework 4 Q3, on a ShapeWorld latent), cascades and video models, editing a pretrained model (SDEdit, inpainting — judged with the exact denoiser of this lecture), ControlNet, score distillation through a renderer, fast sampling by distillation (can a 1-step student beat the optimal denoiser’s 1-step sampler?), diffusion models as classifiers — and a side-by-side comparison of every model family of the course.

← 返回课程目录