Lecture 15 · Diffusion and Flows (Multimodal III)

Advanced Natural Language Processing · Lecture 15。个人学习讲义与配套实验,按主题整理并持续修订。

课程源码 ZIP ↓

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

本篇目录

Maps to: CMU 11-711 Spring 2026, Lecture 15 (03/10), “Modeling IV: Diffusion and Flows”; slides anlp-s2026-15-multimodal-iii.pdf (titled “Multimodal Modeling III”); course code 15_diffusion/ddpm_colab.ipynb. Readings: J. Ho, A. Jain, P. Abbeel, Denoising Diffusion Probabilistic Models (NeurIPS 2020); Y. Lipman et al., Flow Matching for Generative Modeling (ICLR 2023). From Fall 2025’s guest lecture on diffusion language models: S. Sahoo et al., Simple and Effective Masked Diffusion Language Models (NeurIPS 2024); S. Gong et al., Scaling Diffusion Language Models via Adaptation from Autoregressive Models (2024). Sources: the public slides and notebook, the readings, and the papers cited in each section. Every number labelled “measured” comes from code/lecture15/, run on the author’s machine (Apple M4 Pro, Python 3.13, PyTorch 2.14, one CPU thread). Code: code/lecture15/ — six demos, each under two minutes. Reading time: ~110 minutes for the prose; ~30 more for the demos.


0. How to read this lecture

0.1 Learning goals

After this lecture you should be able to:

  1. Describe diffusion as two processes: a fixed forward process that destroys data with noise, and a learned reverse process that removes it. Derive the closed form q(xt∣x0)q(x_t \mid x_0) and explain what a noise schedule must satisfy.
  2. Explain how the ELBO turns into the simple noise-prediction loss, why that loss has a nonzero floor, and how predicting noise, data or vv changes the weighting.
  3. State Tweedie’s formula and use it to explain why a noise predictor is a score estimator.
  4. Explain the continuous-time view: the reverse SDE, the probability-flow ODE, DDIM as Euler’s method on it, and why the number and placement of steps matters.
  5. Derive classifier guidance and classifier-free guidance from Bayes’ rule, and say what the guidance weight buys and costs.
  6. Explain flow matching: velocity fields, the conditional loss with straight paths, why it has the same minimizer as the intractable marginal loss, and how it relates to diffusion.
  7. Explain masked diffusion for text: the masking forward process, the ELBO as an any-order autoregressive loss, parallel decoding and its errors. Say when a diffusion LM beats an autoregressive one.

0.2 Prerequisites and scope

  • Prerequisites:
    • Lecture 12: generative paradigms, the VAE and its ELBO (importance sampling + Jensen), the reparameterization trick, image tokens and their information loss.
    • Lecture 3: language models as ∏tp(xt∣x<t)\prod_t p(x_t \mid x_{<t}); Errand World and its exact sentence probabilities.
    • Lecture 9: decoding (sampling, temperature, the cost of one token per forward pass).
    • Basic probability: Gaussians, conditional expectation, Bayes’ rule.
  • Scope: the slides’ three parts (diffusion basics, extensions, flow matching), plus discrete diffusion for text, which Fall 2025 covered in a guest lecture.
  • Not in scope:
    • Score-matching objectives other than denoising (sliced score matching, etc.).
    • SDE theory beyond the facts used.
    • Architectures (U-Net, DiT) beyond a paragraph.
    • Video and audio diffusion.

0.3 Section → code map

SectionIdeaDemo in code/lecture15/
§1.2Ring World: a data distribution with exact scoresring_world.py
§2.1the forward process, schedule, closed form01_ddpm.py Part A
§2.3the loss and its exact floor01_ddpm.py Part B
§2.4Tweedie: the network learns the score01_ddpm.py Part C
§2.5sampling01_ddpm.py Part D
§2.6ε vs x₀ vs v prediction01_ddpm.py Part E
§3SDE vs ODE, steps, solvers, time grids, inversion02_samplers.py
§4classifier and classifier-free guidance03_guidance.py
§5flow matching, diffusion ≡ flow, reflow, likelihood04_flow_matching.py
§6.2–6.4masked diffusion LM vs AR05_masked_diffusion_lm.py
§6.5data-constrained training06_data_constrained.py

0.4 Notation

SymbolMeaning
x0x_0a data point; xtx_t its noisy version at step t=1,…,Tt = 1, \dots, T (T=1000T = 1000)
βt\beta_t, αt=1−βt\alpha_t = 1 - \beta_t, αˉt=∏i≤tαi\bar\alpha_t = \prod_{i \le t} \alpha_ithe noise schedule
at=αˉta_t = \sqrt{\bar\alpha_t}, σt=1−αˉt\sigma_t = \sqrt{1 - \bar\alpha_t}signal and noise scales: xt=atx0+σtεx_t = a_t x_0 + \sigma_t \varepsilon
ε∼N(0,I)\varepsilon \sim \mathcal N(0, I)the noise; εθ(xt,t)\varepsilon_\theta(x_t, t) the network’s prediction of it
∇xlog⁡pt(x)\nabla_x \log p_t(x)the score of the noisy marginal ptp_t
cca condition (a class here; a text prompt in practice); ww the guidance weight
s∈[0,1]s \in [0, 1]flow time (s=0s = 0 noise, s=1s = 1 data); Xs=(1−s)X0+s x1X_s = (1-s)X_0 + s\,x_1; v(x,s)v(x, s) a velocity field
NFEnumber of function (network) evaluations: the cost of sampling
[M]the mask token of discrete diffusion

1. Generation by iterative denoising

1.1 Where we are, and the idea

The slides frame this lecture as multi-to-image: text (and images) in, images out. Lecture 12 did that autoregressively. A VQ tokenizer turns an image into a few hundred discrete tokens, and a Transformer predicts them one at a time. Lecture 12 also measured the price:

  • the tokenizer loses information (our ceiling was 81% exact reconstructions);
  • generation takes one network call per token;
  • errors compound left to right.

Diffusion takes a different route. There are no discrete tokens, and the image is not generated in raster order. All pixels (or all latent dimensions) are refined together, over a few dozen steps, from pure noise to an image.

The slides’ core idea is two processes:

x0  →  q    x1  →  q    ⋯  →  q    xTandxT  →  pθ    xT−1  →  pθ    ⋯  →  pθ    x0.x_0 \;\xrightarrow{\;q\;}\; x_1 \;\xrightarrow{\;q\;}\; \cdots \;\xrightarrow{\;q\;}\; x_T \qquad\text{and}\qquad x_T \;\xrightarrow{\;p_\theta\;}\; x_{T-1} \;\xrightarrow{\;p_\theta\;}\; \cdots \;\xrightarrow{\;p_\theta\;}\; x_0 .

  • The forward process qq is fixed and requires no learning. It adds a little Gaussian noise at each step, until after TT steps the data is indistinguishable from noise.
  • The reverse process pθp_\theta is learned. Each step removes a little noise.

Why should this be easier than generating an image in one shot (a GAN, a VAE decoder)? Each reverse step only has to undo a small corruption, and a small step of Gaussian noise is undone, to a good approximation, by a Gaussian step. The hard problem, sampling a complicated distribution, is cut into TT easy problems, each of them a regression: predict the noise that was added. We know the noise during training because we added it. There is no adversary and no posterior to approximate.

1.2 Ring World: a laboratory with exact answers

The course notebook trains on MNIST, where we can only look at samples. To measure what a diffusion model learns, these notes use a 2-D distribution (ring_world.py):

  • eight round Gaussian blobs (std S=0.15S = 0.15) on a circle of radius 2;
  • four classes (“red”, “green”, “blue”, “gold”), each owning a major blob (70% of the class) and a minor one (30%).
             -*%#*-                    one blob per 45 degrees; each class owns
     .:-+=:  :=#@@*=:   .:-==-:.       a major blob and the minor blob next to it
     .-+#*=:             .:+#*+-       (the picture is 5,000 samples)
  -+%@#=:                     ..=#%%+:
  .-+%@*=:                      .-*@%+-

The point of a Gaussian mixture: noising keeps it a Gaussian mixture. If x0∼N(μk,S2I)x_0 \sim \mathcal N(\mu_k, S^2 I), then xt=atx0+σtε∼N(atμk,(at2S2+σt2)I)x_t = a_t x_0 + \sigma_t \varepsilon \sim \mathcal N(a_t \mu_k, (a_t^2 S^2 + \sigma_t^2) I). So everything a diffusion model tries to learn has a closed form:

  • the noisy density ptp_t and its score;
  • the optimal denoiser;
  • the noisy classifier p(c∣xt)p(c \mid x_t);
  • the optimal flow velocity.

The demos compare every network with these exact answers, and run every sampler with the exact model too. With the exact model, any remaining error is the sampler’s alone.

Sample quality is scored automatically (ring_world.quality):

  • off: the share of samples farther than 4S4S from every blob (true data: 0.03%);
  • spread: blob width relative to the truth (1 = right; < 1 too concentrated; > 1 smeared);
  • tv: whether the blobs get the right proportions;
  • minor: the minor blob’s share within its class (true 0.30), a measure of diversity.

2. Denoising diffusion probabilistic models (DDPM)

2.1 The forward process

Each forward step shrinks the current point a little and adds a little noise:

q(xt∣xt−1)=N ⁣(xt; αt xt−1, (1−αt)I),αt=1−βt.q(x_t \mid x_{t-1}) = \mathcal N\!\left(x_t;\ \sqrt{\alpha_t}\, x_{t-1},\ (1 - \alpha_t) I\right), \qquad \alpha_t = 1 - \beta_t .

The shrinking is what keeps the variance from growing. If xt−1x_{t-1} has unit variance, so does xtx_t, since αt⋅1+(1−αt)=1\alpha_t \cdot 1 + (1 - \alpha_t) = 1.

The key property: jump to any tt directly. Compose two steps, xt=αt(αt−1xt−2+1−αt−1 ε′)+1−αt εx_t = \sqrt{\alpha_t}(\sqrt{\alpha_{t-1}} x_{t-2} + \sqrt{1-\alpha_{t-1}}\,\varepsilon') + \sqrt{1-\alpha_t}\,\varepsilon. The two noise terms are independent Gaussians, with total variance αt(1−αt−1)+(1−αt)=1−αtαt−1\alpha_t(1 - \alpha_{t-1}) + (1 - \alpha_t) = 1 - \alpha_t\alpha_{t-1}. By induction,

q(xt∣x0)=N ⁣(xt; αˉt x0, (1−αˉt)I),xt=atx0+σt ε,  ε∼N(0,I).q(x_t \mid x_0) = \mathcal N\!\left(x_t;\ \sqrt{\bar\alpha_t}\, x_0,\ (1 - \bar\alpha_t) I\right), \qquad x_t = a_t x_0 + \sigma_t\, \varepsilon,\ \ \varepsilon \sim \mathcal N(0, I).

This reparameterization is what makes training cheap. To get a training example at step 500, we do not run 500 noising steps; we draw one ε\varepsilon and compute x500x_{500} in one line.

The schedule. αˉt\bar\alpha_t must:

  • start at 1 (data);
  • end near 0 (noise);
  • decrease monotonically.

Ho et al. use a linear schedule, βt\beta_t from 10−410^{-4} to 0.020.02 over T=1000T = 1000 steps. Measured on Ring World (demo 01, Part A):

ttαˉt\bar\alpha_tata_t (signal)σt\sigma_t (noise)SNR at2/σt2a_t^2/\sigma_t^2class readable by the exact Bayes classifier
10.999900.99990.010010⁴100.0%
1000.897020.94710.32098.7198.4%
2500.524090.72390.68991.178.0%
5000.078590.28030.95990.08541.8%
10000.000040.00641.00004·10⁻⁵25.7% (chance 25%)

The last column is a direct measure of information: how well the best possible classifier can still tell which class a noisy point came from.

  • Most of the destruction happens between t=100t = 100 and t=500t = 500. After t≈750t \approx 750 almost nothing is left. This is why later work moved to schedules that waste fewer steps at either end (the cosine schedule of Nichol & Dhariwal, 2021, is in diffusion.Schedule).
  • The closed form is right. Running the 1,000-step chain 20,000 times from x0=(2,0)x_0 = (2, 0) gives mean 0.0001 and std 0.9990 at t=1000t = 1000. The closed form says 0.0127 and 1.0000; the Monte Carlo standard error of the mean is 0.007.

2.2 The reverse process and the ELBO

The reverse process starts from the prior p(xT)=N(0,I)p(x_T) = \mathcal N(0, I) and applies learned Gaussian steps:

pθ(x0:T)=p(xT)∏t=1Tpθ(xt−1∣xt),pθ(xt−1∣xt)=N ⁣(xt−1; μθ(xt,t), σq2(t)I).p_\theta(x_{0:T}) = p(x_T) \prod_{t=1}^{T} p_\theta(x_{t-1} \mid x_t), \qquad p_\theta(x_{t-1} \mid x_t) = \mathcal N\!\left(x_{t-1};\ \mu_\theta(x_t, t),\ \sigma_q^2(t) I\right).

Training goal: maximum likelihood, log⁡pθ(x0)=log⁡∫pθ(x0:T) dx1:T\log p_\theta(x_0) = \log \int p_\theta(x_{0:T})\, dx_{1:T}. The integral over all the intermediate x1:Tx_{1:T} is intractable. It is the latent-variable situation of Lecture 12, with x1:Tx_{1:T} as latents, and the same two moves give a bound. First, importance sampling with the forward process q(x1:T∣x0)q(x_{1:T} \mid x_0) as the proposal. Then Jensen’s inequality:

log⁡pθ(x0)=log⁡Eq ⁣[pθ(x0:T)q(x1:T∣x0)] ≥ Eq ⁣[log⁡pθ(x0:T)q(x1:T∣x0)]=ELBO.\log p_\theta(x_0) = \log \mathbb E_{q}\!\left[\frac{p_\theta(x_{0:T})}{q(x_{1:T} \mid x_0)}\right] \ \ge\ \mathbb E_q\!\left[\log \frac{p_\theta(x_{0:T})}{q(x_{1:T} \mid x_0)}\right] = \text{ELBO}.

The difference from a VAE: the “encoder” qq is fixed, not learned, so only the decoder side is trained. Expanding and regrouping (Ho et al., App. A), the negative ELBO splits into three terms:

−ELBO=DKL ⁣(q(xT∣x0) ∥ p(xT))⏟LT: prior matching+∑t=2TEq DKL ⁣(q(xt−1∣xt,x0) ∥ pθ(xt−1∣xt))⏟Lt−1: denoising − Eqlog⁡pθ(x0∣x1)⏟L0: reconstruction.-\text{ELBO} = \underbrace{D_{\mathrm{KL}}\!\big(q(x_T \mid x_0)\,\|\,p(x_T)\big)}_{L_T:\ \text{prior matching}} + \sum_{t=2}^{T} \underbrace{\mathbb E_q\, D_{\mathrm{KL}}\!\big(q(x_{t-1} \mid x_t, x_0)\,\|\,p_\theta(x_{t-1} \mid x_t)\big)}_{L_{t-1}:\ \text{denoising}} \ \underbrace{-\ \mathbb E_q \log p_\theta(x_0 \mid x_1)}_{L_0:\ \text{reconstruction}} .

  • LTL_T has no parameters: with αˉT≈0\bar\alpha_T \approx 0 it is ≈ 0.
  • The work is in Lt−1L_{t-1}: make each learned reverse step match the posterior of the forward process, q(xt−1∣xt,x0)q(x_{t-1} \mid x_t, x_0), the distribution of the previous point if we knew the clean data.

That posterior is Gaussian (a product of Gaussians), with

μq(xt,x0)=αˉt−1 (1−αt)1−αˉt x0+αt (1−αˉt−1)1−αˉt xt,σq2(t)=(1−αt)(1−αˉt−1)1−αˉt.\mu_q(x_t, x_0) = \frac{\sqrt{\bar\alpha_{t-1}}\,(1 - \alpha_t)}{1 - \bar\alpha_t}\, x_0 + \frac{\sqrt{\alpha_t}\,(1 - \bar\alpha_{t-1})}{1 - \bar\alpha_t}\, x_t, \qquad \sigma_q^2(t) = \frac{(1 - \alpha_t)(1 - \bar\alpha_{t-1})}{1 - \bar\alpha_t}.

The KL between two Gaussians with the same variance is a scaled squared distance between their means, so Lt−1∝∥μq(xt,x0)−μθ(xt,t)∥2L_{t-1} \propto \|\mu_q(x_t, x_0) - \mu_\theta(x_t, t)\|^2.

Three ways to parameterize the same thing. μq\mu_q depends on the unknown x0x_0. The network must supply the missing piece, and there are three equivalent choices:

  • predict the data: x^0=xθ(xt,t)\hat x_0 = x_\theta(x_t, t) and plug it into μq\mu_q. The loss is ∥xθ−x0∥2\|x_\theta - x_0\|^2 (with tt-dependent weights).
  • predict the noise: since x0=(xt−σtε)/atx_0 = (x_t - \sigma_t \varepsilon)/a_t, μq\mu_q can be rewritten in terms of ε\varepsilon: μq=1αt(xt−1−αt1−αˉt ε),\mu_q = \frac{1}{\sqrt{\alpha_t}}\Big(x_t - \frac{1 - \alpha_t}{\sqrt{1 - \bar\alpha_t}}\,\varepsilon\Big), and the network predicts εθ(xt,t)\varepsilon_\theta(x_t, t). The loss is ∥εθ−ε∥2\|\varepsilon_\theta - \varepsilon\|^2, again with tt-dependent weights.
  • predict v=atε−σtx0v = a_t \varepsilon - \sigma_t x_0 (Salimans & Ho, 2022), a mixture of the two.

Ho et al.’s empirical finding: dropping the ELBO’s weights and using the noise-prediction loss gives the best samples:

Lsimple(θ)=Et∼U{1..T}, x0, ε ∥ε−εθ(atx0+σtε, t)∥2.L_{\text{simple}}(\theta) = \mathbb E_{t \sim U\{1..T\},\ x_0,\ \varepsilon}\ \big\|\varepsilon - \varepsilon_\theta(a_t x_0 + \sigma_t \varepsilon,\ t)\big\|^2 .

The slides’ “what training boils down to”: sample a data point, a step, and a noise; add the noise; train the network to tell you what noise you added.

2.3 Training, and why the loss never reaches zero

Demo 01 trains a small MLP (3 hidden layers of 128 units, 37,762 parameters, sinusoidal time features) for 20,000 steps of 256 examples. On one CPU thread this takes ~12 s.

After training the loss is about 0.46, and it will not go lower. Is the network bad? Ring World lets us answer exactly.

The minimizer of a squared loss is the conditional mean. So the best possible εθ(xt,t)\varepsilon_\theta(x_t, t) is E[ε∣xt]\mathbb E[\varepsilon \mid x_t], and the loss of the best possible predictor is the floor:

L⋆=E ∥ε−E[ε∣xt]∥2=E tr Var(ε∣xt)>0.L^\star = \mathbb E\, \big\|\varepsilon - \mathbb E[\varepsilon \mid x_t]\big\|^2 = \mathbb E\, \mathrm{tr}\,\mathrm{Var}(\varepsilon \mid x_t) > 0 .

The floor is positive because many different (x0,ε)(x_0, \varepsilon) pairs produce the same xtx_t. Measured (demo 01, Part B, 200,000 fresh triples):

noise steps ttfloornetwork’s lossexcess (distance to the optimum)
1–101.89101.93130.0287
10–501.38851.39820.0068
50–1000.67480.69130.0145
100–2500.98340.98690.0033
250–5000.73270.73330.0005
500–10000.05280.05300.0002
all0.46200.46430.0020
  • The network is within 0.5% of optimal. A loss of 0.464 against a floor of 0.462 means there is almost nothing left to learn. On real data the floor is unknown, which is why diffusion losses are notoriously uninformative: the training loss is dominated by an irreducible term. Lecture 13’s lesson that loss is not the metric applies with force.
  • The floor depends on tt in an instructive way.
    • At the smallest tt, xt≈x0x_t \approx x_0 plus a tiny noise. The noise is essentially unpredictable, so the floor is ≈ 2 (the dimension).
    • At the largest tt, xt≈εx_t \approx \varepsilon, so the noise is almost fully predictable (floor ≈ 0).
    • In between the floor is not monotone. The bump at tt = 100–250 is where the noise is as large as the gaps between blobs, so which blob a point came from becomes uncertain.

2.4 From noise to gradients: Tweedie’s formula

What exactly has the network learned? The slides’ answer is the score, ∇xlog⁡pt(x)\nabla_x \log p_t(x): the direction in which the noisy density increases fastest.

Tweedie’s formula. Let z=a x0+σ εz = a\, x_0 + \sigma\, \varepsilon with x0∼px_0 \sim p. Then pt(z)=∫p(x0) N(z;ax0,σ2I) dx0p_t(z) = \int p(x_0)\, \mathcal N(z; a x_0, \sigma^2 I)\, dx_0. Differentiate under the integral; the Gaussian’s gradient is N(⋅) (ax0−z)/σ2\mathcal N(\cdot)\,(a x_0 - z)/\sigma^2:

∇zlog⁡pt(z)=∫p(x0) N(z;ax0,σ2I) (ax0−z)/σ2 dx0pt(z)=E ⁣[ax0−zσ2 | z]=−E[ε∣z]σ,\nabla_z \log p_t(z) = \frac{\int p(x_0)\,\mathcal N(z; a x_0, \sigma^2 I)\,(a x_0 - z)/\sigma^2\, dx_0}{p_t(z)} = \mathbb E\!\left[\frac{a x_0 - z}{\sigma^2}\,\middle|\, z\right] = -\frac{\mathbb E[\varepsilon \mid z]}{\sigma},

because z−ax0=σεz - a x_0 = \sigma\varepsilon. So the optimal noise predictor and the score are the same object up to a scale:

εθ(xt,t)≈E[ε∣xt]=−σt ∇xlog⁡pt(xt).\varepsilon_\theta(x_t, t) \approx \mathbb E[\varepsilon \mid x_t] = -\sigma_t\, \nabla_x \log p_t(x_t).

Intuition. To predict which noise was added, you must know which way the data lies. Removing the predicted noise moves the point toward higher probability. The diffusion network is a learned compass, one for every noise level.

Measured (demo 01, Part C). We compare −εθ/σt-\varepsilon_\theta/\sigma_t with the exact Ring World score. The median cosine similarity is 0.994–1.000 across noise levels. The median relative error is 1–8% for t≥10t \ge 10, but 63.5% for t<10t < 10. That is not a failure: there the optimal prediction itself is tiny (∣E[ε∣xt]∣≈0.18|\mathbb E[\varepsilon \mid x_t]| \approx 0.18, since almost none of the noise is predictable), so small absolute errors are large relative ones.

The ring_world.py self-test checks Tweedie’s formula directly. It averages (z−ax0)/σ(z - a x_0)/\sigma over 400,000 data points, weighted by how likely each would produce zz, and the result matches −σ×-\sigma \times score to two decimals.

2.5 Sampling

The learned reverse step is N(μθ,σq2I)\mathcal N(\mu_\theta, \sigma_q^2 I), with

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

Ancestral sampling (the slides’ and the notebook’s algorithm):

  1. Draw xT∼N(0,I)x_T \sim \mathcal N(0, I).
  2. For t=T,…,1t = T, \dots, 1: compute μθ\mu_\theta, then draw xt−1∼N(μθ,σq2(t)I)x_{t-1} \sim \mathcal N(\mu_\theta, \sigma_q^2(t) I) (no noise at the last step).

Measured with 1,000 steps (demo 01, Part D; 4,000 samples each):

samplesofftvspreadminor
true data0.02%0.0211.0060.300
exact denoiser E[ε∣xt]\mathbb E[\varepsilon \mid x_t]0.02%0.0200.9820.299
learned network0.30%0.0220.9640.298
  • With the exact denoiser, the sampler reproduces the data. At 1,000 steps the algorithm itself is essentially exact.
  • The learned network is close: 0.30% of samples land between blobs, and proportions and diversity are right. The pictures (printed by the demo) are hard to tell apart.

2.6 Predict the noise, the data, or v?

Section 2.2 said the three parameterizations are equivalent. As unweighted losses they are not, and demo 01 (Part E) shows how much that matters:

network predictsoffspreadnoise-prediction error at t<10t < 10
ε\varepsilon0.30%0.9640.0287
x0x_00.02%0.27429.3
vv0.32%0.9850.0149

The x₀-predictor’s samples collapse onto the blob centers (spread 0.27). Its “off” rate looks perfect only because collapsed samples sit at the centers. Why?

  • ∥x0−x^0∥2=(σt/at)2 ∥ε−ε^∥2\|x_0 - \hat x_0\|^2 = (\sigma_t / a_t)^2\, \|\varepsilon - \hat\varepsilon\|^2.
  • At t=1t = 1, (σt/at)2=10−4(\sigma_t/a_t)^2 = 10^{-4}. The x₀ loss hardly cares about the network’s errors at small tt, where it outputs something close to the blob center rather than to xtx_t itself.
  • The sampler converts those x₀ predictions back into noise predictions, dividing by σt\sigma_t. That multiplies small x₀ errors into huge noise errors (29.3).

So the choice of target is a choice of loss weighting over noise levels. Ho et al.’s finding that LsimpleL_{\text{simple}} works best is an empirical statement about weighting. Much later work (Kingma & Gao, 2023; Esser et al., 2024) is about choosing that weighting deliberately.


3. The continuous-time view and faster sampling

3.1 From steps to differential equations

1,000 network calls per sample is expensive. The notebook’s MNIST sampler takes ~10 s on an A100 for 64 images. To sample faster we need to understand what the 1,000 steps approximate.

The SDE. As T→∞T \to \infty the forward chain becomes a stochastic differential equation (Song et al., 2021):

dz=f(t) z dt+g(t) dw,dz = f(t)\, z\, dt + g(t)\, dw,

drift toward zero plus Brownian noise. A classical result (Anderson, 1982) says it can be run backwards in time:

dz=[f(t) z−g(t)2 ∇zlog⁡pt(z)] dt+g(t) dwˉ.dz = \big[f(t)\, z - g(t)^2\, \nabla_z \log p_t(z)\big]\, dt + g(t)\, d\bar w .

The only unknown is the score, and §2.4 says the noise predictor supplies it: ∇zlog⁡pt≈−εθ/σt\nabla_z \log p_t \approx -\varepsilon_\theta / \sigma_t. DDPM’s ancestral sampler is one discretization of this reverse SDE.

The probability-flow ODE. For every such SDE there is a deterministic ordinary differential equation whose solutions have the same marginals ptp_t at every time:

dz=[f(t) z−12 g(t)2 ∇zlog⁡pt(z)] dt.dz = \Big[f(t)\, z - \tfrac{1}{2}\, g(t)^2\, \nabla_z \log p_t(z)\Big]\, dt .

It has no noise term, so each starting point zTz_T follows one fixed path to one fixed sample. This opens the door to the numerical analyst’s toolbox: ODE solvers, step-size control, higher-order methods. It also raises the slides’ question: if all we need is an ODE that carries noise to data, why derive it from a noising process at all? That question leads to flow matching (§5).

3.2 DDIM: Euler on the ODE

DDIM (Song, Meng & Ermon, 2021) predicts the clean point, then re-noises it to the next level with the same predicted noise:

x^0=xt−σt εθ(xt,t)at,xt′=at′ x^0+σt′ εθ(xt,t).\hat x_0 = \frac{x_t - \sigma_t\, \varepsilon_\theta(x_t, t)}{a_t}, \qquad x_{t'} = a_{t'}\, \hat x_0 + \sigma_{t'}\, \varepsilon_\theta(x_t, t).

Divide by at′a_{t'} and write xˉ=x/a\bar x = x/a, σˉ=σ/a\bar\sigma = \sigma/a: the update becomes xˉt′=xˉt+(σˉt′−σˉt) εθ(xt,t)\bar x_{t'} = \bar x_t + (\bar\sigma_{t'} - \bar\sigma_t)\, \varepsilon_\theta(x_t, t). That is exactly Euler’s method for the ODE dxˉ/dσˉ=ε(x)d\bar x / d\bar\sigma = \varepsilon(x), the probability-flow ODE in these variables (Karras et al., 2022). DDIM needs no retraining: any noise-prediction network can be sampled with it, at any subset of steps.

A deterministic map (demo 02, Part D). From the same starting noise:

  • two DDIM runs land in the same blob 100.0% of the time;
  • two DDPM runs only 13.2% of the time (two unrelated samples: 14.5%).

The noise is a latent code for the sample, and the map can be inverted. Running DDIM backwards (“DDIM inversion”) finds the noise that generates a given data point:

  • with 1,000 steps and the exact denoiser, data → noise → data reconstructs points to 0.012 blob widths (learned network: 0.011);
  • with 20 steps, to 0.50.

Inversion is how diffusion models edit real images: invert a photo, then regenerate it with a changed prompt.

3.3 How many steps, which solver, which time grid?

Demo 02 measures sample quality against the budget of network calls. The table below uses the exact denoiser, so every error is discretization error, the sampler’s alone (cells: off-data share / spread):

NFEDDPM (SDE)DDIM (Euler, ODE)Heun (2nd order)
10000.0% / 0.980.0% / 0.990.0% / 1.00
1000.0% / 0.870.1% / 0.950.1% / 1.02
500.1% / 0.810.1% / 0.920.2% / 1.08
201.2% / 0.751.3% / 0.846.0% / 1.41
108.2% / 1.088.5% / 1.0668.7% / 1.99
631.5% / 1.7428.2% / 1.6699.1% / 1.97

Three lessons:

  • Few steps fail even with a perfect model. Each big step jumps to the average of the plausible clean points. First the samples become too concentrated (DDPM spread 0.75 at 20 calls), then they scatter between blobs.
  • The ODE tolerates fewer steps than the SDE. DDIM keeps the spread closer to 1 at every budget.
  • A higher-order solver is not automatically better. Heun’s method (one extra network call per step to correct the slope) helps only when the steps are already small. With big steps the corrector evaluates the slope at a badly predicted point, and it diverges (68.7% off at 10 calls). Its error bound assumes the slope changes little within a step.

Where the steps go matters more than the solver. The table above spends its steps evenly in DDPM’s tt. Demo 02 (Part C) compares three time grids that start and end at the same noise levels:

time grid (Euler / DDIM)exact denoiser, 10 callslearned network, 10 calls
evenly spaced DDPM steps tt8.5% off7.9% off
EDM grid (Karras et al., ρ=7\rho = 7)6.7%11.5%
evenly spaced flow time ss (§5.4)0.6%2.9%

The linear schedule spends most of its steps where nothing is happening (t>750t > 750, §2.1). A grid that spends them where the class is being decided cuts the error by more than 10×. Keep this result in mind for §5.4.

3.4 Other extensions (the slides’ table)

problemsolutionkey ideareference
pixel space is expensivelatent diffusiondiffuse in an autoencoder’s latent space (Lecture 12’s tokenizer, but continuous)Rombach et al. 2022
architectureDiffusion Transformer (DiT)a Transformer on latent patches replaces the U-NetPeebles & Xie 2022
stochastic samplingdeterministic paths, ODE solvers§3.2–3.3Song et al. 2021
slow samplingdistillationtrain a student to match the teacher in fewer stepsSalimans & Ho 2022

Latent diffusion is why text-to-image models are affordable. A 512×512 image becomes a 64×64×4 latent, 48× fewer numbers, and the expensive network runs only there. Unlike Lecture 12’s VQ tokens, the latent is continuous: no codebook ceiling.


4. Conditional generation: guidance

4.1 Classifier guidance

We want samples of p(x∣c)p(x \mid c), e.g. “dog”. Bayes’ rule for the noisy marginals, pt(x∣c)∝pt(x) p(c∣xt=x)p_t(x \mid c) \propto p_t(x)\, p(c \mid x_t = x), becomes, after taking ∇xlog⁡\nabla_x \log:

∇xlog⁡pt(x∣c)=∇xlog⁡pt(x)+∇xlog⁡pt(c∣x).\nabla_x \log p_t(x \mid c) = \nabla_x \log p_t(x) + \nabla_x \log p_t(c \mid x).

The normalizer p(c)p(c) does not depend on xx, so it drops out of the gradient. Multiply by −σt-\sigma_t to get noise predictions. Dhariwal & Nichol (2021) train a noisy classifier pϕ(c∣xt)p_\phi(c \mid x_t) and sample with

ε~(xt,c)=εθ(xt)−w σt ∇xlog⁡pϕ(c∣xt).\tilde\varepsilon(x_t, c) = \varepsilon_\theta(x_t) - w\, \sigma_t\, \nabla_x \log p_\phi(c \mid x_t).

w=1w = 1 is the conditional distribution. w>1w > 1 exaggerates the class, which Dhariwal & Nichol found makes samples better looking.

The catch is that the classifier must work on noisy inputs at every noise level, so a pretrained image classifier will not do. A separate model has to be trained for this one purpose.

4.2 Classifier-free guidance (CFG)

Ho & Salimans (2022) remove the classifier:

  • Training: train one network on both tasks. With some probability (here 15%) the condition is replaced by a “no condition” token, so the same network learns εθ(xt,c)\varepsilon_\theta(x_t, c) and εθ(xt)\varepsilon_\theta(x_t).
  • Sampling: ε~(xt,c)=(1+w) εθ(xt,c)−w εθ(xt).\tilde\varepsilon(x_t, c) = (1 + w)\, \varepsilon_\theta(x_t, c) - w\, \varepsilon_\theta(x_t).

The slides note that this is classifier guidance with an implicit classifier. By Bayes, ∇log⁡pt(c∣x)=∇log⁡pt(x∣c)−∇log⁡pt(x)=−1σt [ε⋆(x,c)−ε⋆(x)]\nabla \log p_t(c \mid x) = \nabla \log p_t(x \mid c) - \nabla \log p_t(x) = -\frac{1}{\sigma_t}\,[\varepsilon^\star(x, c) - \varepsilon^\star(x)]. Substitute:

(1+w) ε(x,c)−w ε(x)=ε(x)−(1+w) σt ∇xlog⁡pt(c∣x).(1 + w)\,\varepsilon(x, c) - w\,\varepsilon(x) = \varepsilon(x) - (1 + w)\,\sigma_t\, \nabla_x \log p_t(c \mid x).

So CFG with weight ww is classifier guidance with weight 1+w1 + w.

Measured exactly (demo 03, Part A). Ring World provides the exact unconditional and conditional scores and the exact noisy classifier. Starting from the same noise, the two guided samplers produce the same samples to 3×10−143 \times 10^{-14} for every weight tested. w=−1w = -1 gives the unconditional model (25.6% in the right class), and w=0w = 0 the conditional one (100%).

4.3 What the guidance weight buys and costs

With exact scores (no learning error at all; demo 03, Part B), as ww goes from 0 to 8:

  • samples stay on the data (off ≤ 0.03% at every ww) and in the right class;
  • the minor blob’s share falls from 0.302 to 0.163. Guidance sharpens the distribution toward where the noisy classifier is surest.

Look at the exact p(green∣xt)p(\text{green} \mid x_t) at t=300t = 300: it is 0.766 at the major blob’s noisy center and 0.616 at the minor one’s. The minor blob neighbors blue’s major blob, so it is more confusable. With w>0w > 0 we are not sampling p(x∣c)p(x \mid c) but a tilted version of it, ∝p(x∣c) p(c∣x)w\propto p(x \mid c)\, p(c \mid x)^{w} at each noise level: more typical, less diverse.

With learned networks (demo 03, Part C):

networkwwright classminor (true 0.30)off
under-trained (1,000 steps)099.3%0.25125.7%
2100.0%0.01311.0%
8100.0%0.0001.0%
well-trained (20,000 steps)0100.0%0.3010.2%
2100.0%0.2030.1%
8100.0%0.18613.3%
  • For a weak model, guidance is a quality knob. It removes the smear between blobs (25.7% → 1.0% off), which is the slides’ “no guidance vs w=3w = 3” picture. The price is that diversity collapses: the minor blob vanishes.
  • For a strong model, large ww breaks samples. At w=8w = 8, 13.3% are off the data, against 0.0% with exact scores. The formula amplifies the difference between two imperfect predictions by ww, and with it their errors. This is why practitioners keep ww moderate: Stable Diffusion’s default guidance scale, 7.5, is 1+w1 + w in this notation.

CFG is now standard in text-to-image systems, with cc a text encoding (CLIP, T5) instead of a class label. The same “contrast with the unconditional model” trick has been carried back to language models as CFG for LMs and contrastive decoding (Sanchez et al., 2023; Li et al., 2023).


5. Flow matching

5.1 Flows: transport noise to data along a velocity field

The ODE view of §3 suggests a more direct design (Lipman et al., 2022; Albergo & Vanden-Eijnden, 2022; Liu et al., 2022): learn a velocity field that carries noise to data, without any noising process.

  • A velocity field vs:Rd→Rdv_s: \mathbb R^d \to \mathbb R^d for s∈[0,1]s \in [0, 1].
  • A flow ϕs\phi_s defined by the ODE ddsϕs(x)=vs(ϕs(x))\frac{d}{ds}\phi_s(x) = v_s(\phi_s(x)), with ϕ0(x)=x\phi_0(x) = x.
  • Start from X0∼p0X_0 \sim p_0 (noise) and integrate to s=1s = 1. If vv is right, X1=ϕ1(X0)∼p1=pdataX_1 = \phi_1(X_0) \sim p_1 = p_{\text{data}}.

Generation is integrating an ODE; training is learning vv.

5.2 The flow-matching loss, and the conditional trick

The natural loss regresses the network on the true velocity:

LFM=Es,Xs ∥vθ(Xs,s)−vs(Xs)∥2.L_{\text{FM}} = \mathbb E_{s, X_s}\, \|v_\theta(X_s, s) - v_s(X_s)\|^2 .

But we do not know vsv_s, or even the intermediate distributions it should produce.

The conditional trick. Choose the path per data point. For one data point x1x_1 and one noise sample X0X_0, use the straight line

Xs=(1−s) X0+s x1,ddsXs=x1−X0,X_s = (1 - s)\, X_0 + s\, x_1, \qquad \frac{d}{ds} X_s = x_1 - X_0,

and regress on that known, constant velocity:

LCFM=Es, x1, X0 ∥vθ(Xs,s)−(x1−X0)∥2.L_{\text{CFM}} = \mathbb E_{s,\ x_1,\ X_0}\, \big\|v_\theta(X_s, s) - (x_1 - X_0)\big\|^2 .

Why this gives the right answer. Many pairs (X0,x1)(X_0, x_1) pass through the same point XsX_s. The marginal velocity there is their average, vs(x)=E[x1−X0∣Xs=x]v_s(x) = \mathbb E[x_1 - X_0 \mid X_s = x], and it carries the marginal distribution correctly. Expand the square around that conditional mean; the cross term vanishes:

LCFM=E ∥vθ(Xs,s)−vs(Xs)∥2⏟LFM+E ∥vs(Xs)−(x1−X0)∥2⏟a constant: the floor.L_{\text{CFM}} = \underbrace{\mathbb E\,\|v_\theta(X_s, s) - v_s(X_s)\|^2}_{L_{\text{FM}}} + \underbrace{\mathbb E\,\|v_s(X_s) - (x_1 - X_0)\|^2}_{\text{a constant: the floor}} .

The two losses differ by a constant that does not depend on θ\theta, so they have the same gradients and the same minimizer. This is the slides’ key result, and the same argument that made LsimpleL_{\text{simple}} learn E[ε∣xt]\mathbb E[\varepsilon \mid x_t] in §2.3.

Measured (demo 04, Part A). Ring World’s exact marginal velocity is v(x,s)=(E[x1∣Xs=x]−x)/(1−s)v(x, s) = (\mathbb E[x_1 \mid X_s = x] - x)/(1 - s):

  • The trained network’s CFM loss is 3.704, against a floor of 3.700.
  • Its distance to the exact marginal velocity, which it never saw, is only 0.0046 (mean squared, against a typical ∥v∥2\|v\|^2 of 2.36).

5.3 Sampling with few steps

To sample, integrate dX/ds=vθ(X,s)dX/ds = v_\theta(X, s) from noise with Euler steps. Demo 04 (Part B) compares the flow network with demo 01’s DDPM network sampled by DDIM on evenly spaced steps (off-data share / spread):

NFEflow networkexact velocityDDPM network + DDIMexact ε + DDIM
259.3% / 2.0364.6% / 2.0984.7% / 1.98100% / –
49.6% / 1.118.1% / 1.1157.9% / 2.0674.5% / 2.15
83.3% / 0.971.2% / 0.9512.6% / 1.2813.7% / 1.32
321.2% / 0.960.1% / 0.972.0% / 0.900.4% / 0.89

The flow needs far fewer steps: at 8 calls 3.3% off against 12.6%. The slides’ explanation is that flow matching “learns an ODE with straight paths that are easier to integrate”. The next two sections test both halves of that sentence.

5.4 Two sides of the same coin

The straight-path interpolation Xs=s x1+(1−s) X0X_s = s\, x_1 + (1 - s)\, X_0 is a Gaussian path, just like diffusion’s atx0+σtεa_t x_0 + \sigma_t \varepsilon. It is the data scaled by ss plus Gaussian noise scaled by 1−s1 - s. Match the signal-to-noise ratio, at/σt=s/(1−s)a_t/\sigma_t = s/(1-s), and the two describe the same noisy point up to a rescaling: Xs=s2+(1−s)2  ztX_s = \sqrt{s^2 + (1-s)^2}\; z_t. So:

  • the marginal ODEs are the same family of curves;
  • a noise predictor and a velocity predictor carry the same information (§2.2’s parameterizations, one more time).

A few lines of algebra show that one Euler step of the flow, X′=X+h (X−ε^)/sX' = X + h\,(X - \hat\varepsilon)/s, is exactly one DDIM step between the matched noise levels.

Measured (demo 04, Part C):

  • With exact models, flow-matching Euler and DDIM run on the flow’s time grid agree to 7×10−137 \times 10^{-13}: they are the same algorithm.
  • With the learned networks on the same grid, the DDPM network puts 4.1% of samples off the data at 8 calls, against the flow network’s 3.2% (and 12.6% on evenly spaced tt).

Most of the flow’s advantage was its time grid: evenly spaced flow time spends steps where the sample is being decided (§3.3). What genuinely differs between “diffusion” and “flow matching” is a set of design choices:

  • the time grid;
  • the parameterization (noise vs velocity);
  • the loss weighting over noise levels;
  • straight vs variance-preserving interpolation.

These are exactly the knobs Stable Diffusion 3 tuned (§5.7). Gao et al. (2024) put it as “two sides of the same coin”.

5.5 Are the paths straight? Reflow

The conditional paths are straight by construction. The paths the sampler follows are the marginal ones, which average over all conditional paths crossing at each point, and averages of crossing lines are curved. Liu et al.’s (2022) straightness measure is S=∫01E ∥(X1−X0)−v(Xs,s)∥2 dsS = \int_0^1 \mathbb E\, \|(X_1 - X_0) - v(X_s, s)\|^2\, ds. It is 0 exactly when every path is a straight line traversed at constant speed, the case in which a single Euler step is exact.

Rectified flow / reflow (Liu et al., 2022):

  1. Generate pairs (X0,X1=ϕ1(X0))(X_0, X_1 = \phi_1(X_0)) with the trained flow.
  2. Train a new flow on these coupled pairs instead of independent ones. The new conditional paths no longer cross, so the new marginal paths are straight.

Measured (demo 04, Part D):

velocity fieldstraightness SSchord / path length1 Euler step: off / spread2 steps
exact marginal velocity1.47850.6664100%64.6% / 2.09
flow network1.45570.6702100%59.3% / 2.03
reflow network0.00020.99984.2% / 1.014.6% / 1.02

So “flow matching learns straight paths” needs a qualification: the paths are straight only after reflow, which makes one-step generation work. Reflow’s price is that it copies its teacher’s mistakes: its samples inherit the first flow’s errors, and its likelihood is slightly worse (next section). This idea, distilling a curved sampler into a straight or few-step one, is behind today’s one- and few-step image generators.

5.6 A flow has an exact likelihood

A flow is an invertible map, so its density follows from the instantaneous change of variables (Chen et al., 2018): along a path, ddslog⁡ps(Xs)=−∇⋅v(Xs,s)\frac{d}{ds}\log p_s(X_s) = -\nabla \cdot v(X_s, s). Integrating from a data point back to the noise,

log⁡p1(x1)=log⁡N(X0;0,I)−∫01∇⋅v(Xs,s) ds.\log p_1(x_1) = \log \mathcal N(X_0; 0, I) - \int_0^1 \nabla \cdot v(X_s, s)\, ds .

In 2-D the divergence is the trace of a 2×2 Jacobian, two autograd calls.

Euler’s method is too crude here: near s=1s = 1 every blob contracts at rate ~1/(1−s)1/(1-s). The demo uses 4th-order Runge–Kutta; with the exact velocity it recovers log⁡pdata\log p_{\text{data}} to within 5×10−35 \times 10^{-3} on every one of 500 points.

Measured on 2,000 test points (demo 04, Part E):

  • the flow network’s NLL is 1.075 nats per point, against 1.052 under the true density;
  • that is a KL of 0.023 nats (Lecture 3’s identity: cross-entropy = entropy + KL);
  • reflow: 0.055.

Diffusion models get likelihoods the same way, through their probability-flow ODE. The likelihood comparisons in the diffusion literature are computed like this.

5.7 Case study: Stable Diffusion 3

Esser et al. (2024) put the pieces together:

  • Rectified flow (straight paths, velocity prediction), with intermediate times sampled more often during training (a logit-normal distribution over ss). This reweights the loss toward the noise levels where the image is decided: §2.6 and §5.4’s loss-weighting knob, chosen deliberately.
  • Latent space of a pretrained autoencoder (§3.4).
  • Text conditioning from two CLIP text encoders and T5 (Lecture 11), fed to a Transformer (MM-DiT) that attends jointly over text and image tokens, plus classifier-free guidance.

6. Diffusion for text

6.1 Why text is different

Gaussian noise needs a continuous space, and text is discrete. There are two main ways to proceed:

  • Diffuse in embedding space (Diffusion-LM, Li et al., 2022). Add Gaussian noise to word embeddings and round back to words at the end. The rounding step is fragile.
  • Diffuse with discrete corruption (D3PM, Austin et al., 2021). The forward process changes tokens, either into random other tokens (“uniform”) or into a special [M] mask token (“absorbing state”). The masked version works best and has the simplest theory (Sahoo et al., 2024; Shi et al., 2024; Ou et al., 2024). It is what current diffusion LMs use.

6.2 Masked diffusion

Forward process. At time t∈[0,1]t \in [0, 1], each token is independently replaced by [M] with probability tt (the linear schedule). At t=0t = 0 we have the sentence; at t=1t = 1, all masks:

t = 0.0   for tennis class , she wanted to buy her own racquet .
t = 0.5   for [M] class , [M] wanted [M] buy [M] own racquet [M]
t = 1.0   [M] [M] [M] [M] [M] [M] [M] [M] [M] [M] [M] [M]

Reverse model. A Transformer without the causal mask (BERT-like) reads a partly masked sentence and predicts a distribution for every masked position. Once unmasked, a token stays fixed. The model is a denoiser for masked text, as the diffusion network was a denoiser for noisy points.

The ELBO. The same two moves as §2.2 (a forward process as the proposal, then Jensen) give, for this forward process,

−log⁡pθ(x) ≤ ∫011t Ezt[∑i: zti=[M]−log⁡pθ(xi∣zt)] dt.-\log p_\theta(x) \ \le\ \int_0^1 \frac{1}{t}\ \mathbb E_{z_t}\Big[\sum_{i:\ z_t^i = [M]} -\log p_\theta(x^i \mid z_t)\Big]\, dt .

This is a masked-LM loss weighted by 1/t1/t. When few tokens are masked (small tt), each prediction counts more.

The any-order view. Condition on exactly kk of the LL positions being masked. The probability of a particular set of kk masks at time tt is tk(1−t)L−kt^k (1-t)^{L-k}, and summed over all sets (Lk)\binom{L}{k} of them. The time integral then gives

∫011t(Lk)tk(1−t)L−k dt=(Lk)B(k,L−k+1)=1k.\int_0^1 \frac{1}{t}\binom{L}{k} t^k (1-t)^{L-k}\, dt = \binom{L}{k} B(k, L - k + 1) = \frac{1}{k}.

So the bound equals

∑k=1L EM: ∣M∣=k[1k∑i∈M−log⁡pθ(xi∣x∉M)]:\sum_{k=1}^{L}\ \mathbb E_{M:\ |M| = k}\Big[\tfrac{1}{k}\sum_{i \in M} -\log p_\theta(x^i \mid x_{\notin M})\Big]:

the average loss of an autoregressive model that generates the positions in a random order, revealing one random masked position at a time. A masked diffusion LM is an any-order autoregressive model (Hoogeboom et al., 2022; Ou et al., 2024). With the true conditionals, any order gives exactly −log⁡p(x)-\log p(x) by the chain rule. The model’s handicap is learning: it must get the conditionals right for every order, not just left to right.

6.3 Measured: likelihood on Errand World

Demos 05–06 use Lecture 3’s Errand World, a toy language of 34,320 sentences whose probabilities are known exactly. Its entropy is 8.309 nats per sentence. Sentences are padded to 25 positions (<s>, words, </s>, padding).

The two models have the same size:

  • an AR Transformer (Lecture 5’s, d=64d = 64, 2 layers);
  • a masked-diffusion LM (the same Transformer without the causal mask).

Like Gong et al. (2024), the diffusion model reads its prediction for position jj at position j−1j - 1. This “shift” lines it up with the AR model’s next-token outputs.

Measured on 2,000 test sentences (demo 05, Part A):

modelnats / sentencegap to the truth
true language, these sentences8.3210
AR Transformer, exact −log⁡p-\log p (2,500 steps)8.3440.022
masked diffusion, ELBO bound (5,000 steps)8.7090.388

With twice the training steps, the diffusion model is still 0.39 nats per sentence above the truth, against the AR model’s 0.02. Sahoo et al. (2024) narrowed this gap at scale but did not close it. Larger studies (Nie et al., 2024) find masked diffusion needs substantially more compute for the same likelihood.

Part of the gap is that the bound is a bound. Part is the harder task, visible in the any-order decomposition. The mean loss per masked token is 0.110 nats when 1 of 25 positions is masked, 0.239 at 10, and 1.324 when all are masked: the model must guess the first token of a random order with no context.

6.4 Generation: parallel decoding and its errors

Sampling runs the reverse process. Start with all masks; at each of NN steps, reveal a share of the remaining masks, drawing each revealed token from the model’s distribution. The selling point is that one forward pass can reveal many tokens. An AR model needs one pass per token (~11 per Errand World sentence with a KV cache); a diffusion LM with N<LN < L steps needs only NN.

The catch is conditional independence. Tokens revealed in the same step are sampled independently: p(xi∣z) p(xj∣z)p(x^i \mid z)\, p(x^j \mid z) instead of p(xi,xj∣z)p(x^i, x^j \mid z). If the subject and the possessive are revealed together, the model may well choose “he” and “their”, each plausible on its own.

Measured with 500 samples per row (demo 05, Part B):

samplernetwork callsvalid sentencesagreement errorsdistinct (exact draws: 435)
AR, left to right~1198.2%0.0%429
diffusion10.0%–0
diffusion48.2%41.9%39
diffusion829.8%20.0%141
diffusion2559.2%7.0%259
diffusion20080.8%1.2%346
  • Few steps produce word salad. One step means 25 independent guesses (0% valid). One sample from 4 steps reads “for painting class he wanted to buy their own goggles .” The errors are exactly the ones independence predicts: agreement fails (41.9% at 4 steps) between positions decided together.
  • What remains at 200 steps is the model, not the sampler. Agreement errors are down to 1.2%, yet 19.2% of samples are invalid. Only 28.5% of the valid ones are long purchase sentences (true share 40%): the model is weaker on long-range structure. Its likelihood gap (0.39 nats) says the same.

Confidence-ordered unmasking (MaskGIT, Chang et al., 2022; LLaDA, Nie et al., 2025) reveals the tokens the model is surest of first, instead of random positions (Part C):

16 stepsvalidmean true log p (exact sampler: −8.31)distinct of 500purchase sentences (true 40%)
random order50.4%−7.7922425.4%
confidence order99.4%−6.641420.0%

Confidence ordering makes almost every sample grammatical, but the samples are too typical:

  • they are far more probable than real sentences;
  • they are much less diverse;
  • not a single one is a long purchase sentence.

The sampler commits early to what is easiest to be sure of, which here means short, frequent sentence types. It is a form of low-temperature decoding (Lecture 9) and inherits its trade-off.

6.5 Where diffusion LMs shine

Bidirectional context (demo 05, Part D). We blank one random word in each of 300 test sentences and ask for its distribution given both sides. The exact answer comes from the language itself:

  • the diffusion LM answers in one forward pass, at KL 0.0144 nats from the exact conditional;
  • the AR model must score all 128 candidate sentences (128 passes) to do as well (KL 0.0013).

Generation shows the gap more starkly. To fill in the subject of ”… ___ wanted to buy his own racquet .”, the diffusion LM gets it right 99.3% of the time in one pass. An AR model sampling left to right reaches the blank before it has seen “his”, and agrees only 18.7% of the time. Infilling, editing and constraints on the end of a text are natural for diffusion LMs, as the reversal curse (Lecture 7) is for AR ones.

Scarce data (demo 06). Both models are trained on the same 2,000 sentences, seen ~80 (AR) and ~160 (diffusion) times:

best test NLLfinal test NLLfinal train NLL (true: 8.401)samples copying a training sentence
AR8.719 (after 6.4 epochs)10.4747.14492.8%
masked diffusion8.5188.5188.41855.8%
exact sampler of the language———52.0%
  • The AR model overfits within a few epochs. Its training NLL ends below the true NLL of those sentences: it memorizes them. 92.8% of its samples are verbatim training sentences, against 52.0% expected from the language.
  • The diffusion model keeps improving and ends ahead of the AR model’s best, reversing the ranking of §6.3. The reason is that it never sees the same input twice in the same way: in 319,488 training draws it saw 268,070 different masked inputs, where the AR model saw the same 1,357. Masking is built-in data augmentation, and an any-order task cannot be solved by memorizing one path.

This reproduces in miniature Prabhudesai et al.’s (2025) “diffusion beats autoregression in data-constrained settings”. With web text running out (Lecture 6), the point is not academic.

6.6 Diffusion vs autoregression for text

autoregressivemasked diffusion
likelihoodexact; best per unit of computean upper bound; needs more compute for the same value
generation costone pass per token (KV cache)one pass per step; many tokens per step
quality vs speedfixedtunable by the number of steps; few steps → independence errors
contextleft onlyboth sides: infilling, editing
repeated dataoverfits earlykeeps improving (masking as augmentation)
toolingmature (KV caches, speculative decoding)young: caching is harder without a causal mask

Large masked-diffusion LMs exist: LLaDA (8B, trained from scratch; Nie et al., 2025), and models adapted from AR checkpoints by Gong et al.’s recipe (continued training while annealing the attention mask from causal to full). Commercial diffusion LMs advertise speed: many tokens per forward pass. Whether they can match AR quality at equal compute is an open research question, and the measurements above show why it is a real trade-off rather than a free lunch.


7. Summary

  1. Diffusion = a fixed forward process that adds Gaussian noise (xt=atx0+σtεx_t = a_t x_0 + \sigma_t\varepsilon, sampled in one step) + a learned reverse process. Its ELBO reduces to regressing the added noise (LsimpleL_{\text{simple}}).
    • Measured: the loss has an exact floor (0.462), and the network is within 0.002 of it.
  2. The noise predictor is a score estimator (Tweedie): εθ≈−σt∇log⁡pt\varepsilon_\theta \approx -\sigma_t \nabla \log p_t.
    • Measured: cosine 0.994–1.000 with the exact score.
    • The target (noise / data / v) is a loss weighting over noise levels: unweighted x₀-prediction collapses samples (spread 0.27).
  3. Continuous time: the reverse SDE and the probability-flow ODE share marginals. DDIM is Euler on the ODE: deterministic and invertible.
    • Few steps fail even with a perfect model.
    • A 2nd-order solver needs small steps.
    • The time grid matters most: 8.5% → 0.6% off at 10 calls.
  4. Guidance: classifier guidance adds ∇log⁡p(c∣xt)\nabla \log p(c \mid x_t); CFG with weight ww is classifier guidance with weight 1+w1+w and an implicit classifier.
    • Measured identical to 3×10−143 \times 10^{-14}.
    • Guidance trades diversity for typicality: it cleans weak models and breaks strong ones at large ww.
  5. Flow matching regresses straight conditional velocities, with the same minimizer as the marginal loss.
    • Measured: CFM floor 3.700, network 0.0046 from the true velocity.
    • With matched time grids, flow Euler and DDIM are the same algorithm (7×10−137 \times 10^{-13}).
    • Marginal paths are curved until reflow straightens them (one step: 4.2% off).
    • Flows give exact likelihoods (KL 0.023 nats).
  6. Masked diffusion for text: masking as the forward process; the ELBO is a 1/t1/t-weighted masked-LM loss, equal to an any-order AR loss. Measured:
    • The diffusion LM trails AR in likelihood (gap 0.39 vs 0.02).
    • It degrades with few steps (parallel tokens are independent) and with confidence ordering (too typical).
    • It wins at infilling (99.3% vs 18.7%) and on scarce, repeated data (8.518 vs 8.719).

Common pitfalls

  • Judging a diffusion loss against zero. It has a large irreducible floor; compare checkpoints by sample metrics or likelihoods, not raw loss.
  • Switching the prediction target without the matching weighting. x₀- and ε-prediction are only equivalent with the right weights.
  • Blaming the network for sampler error. Before tuning the model, run the sampler with as many steps as you can afford: if quality improves, the steps were the problem.
  • Assuming higher-order solvers always help. With big steps they can diverge; the time grid matters at least as much.
  • Cranking the guidance weight. It amplifies model errors and kills diversity; report diversity next to quality.
  • Saying “flow matching paths are straight”. The conditional paths are; the marginal ones are not, without reflow.
  • Comparing a diffusion LM’s ELBO with an AR model’s exact NLL as if both were exact. One is an upper bound.
  • Few-step diffusion LM decoding without checking dependencies. Tokens revealed together are independent; agreement and other long-range constraints break first.
  • Reporting confidence-ordered samples’ validity without their diversity. It can be 99% valid and miss a whole sentence type.

Exercises

  1. The closed form. Show by induction that q(xt∣x0)=N(αˉt x0,(1−αˉt)I)q(x_t \mid x_0) = \mathcal N(\sqrt{\bar\alpha_t}\,x_0, (1 - \bar\alpha_t) I). With the linear schedule, why is αˉ1000≈4×10−5\bar\alpha_{1000} \approx 4 \times 10^{-5} “close enough to 0”? What would go wrong if αˉT\bar\alpha_T were 0.1?

    AnswerIf $x_{t-1} = \sqrt{\bar\alpha_{t-1}}x_0 + \sqrt{1-\bar\alpha_{t-1}}\varepsilon'$, then $x_t = \sqrt{\alpha_t}x_{t-1} + \sqrt{1-\alpha_t}\varepsilon = \sqrt{\bar\alpha_t}x_0 + [\sqrt{\alpha_t(1-\bar\alpha_{t-1})}\varepsilon' + \sqrt{1-\alpha_t}\varepsilon]$; the bracket is Gaussian with variance $\alpha_t - \bar\alpha_t + 1 - \alpha_t = 1 - \bar\alpha_t$. With $a_T = 0.0064$ the signal in $x_T$ is 0.6% of the data's scale, so $q(x_T \mid x_0) \approx \mathcal N(0, I)$ = the prior and $L_T \approx 0$; demo 01 measures 25.7% Bayes accuracy (chance 25%). With $\bar\alpha_T = 0.1$, $x_T$ still carries a third of the signal; sampling from $\mathcal N(0, I)$ would start from the wrong distribution (a train/test mismatch at the first step), and samples would be biased toward the data mean.
  2. The loss floor. Explain why the floor of LsimpleL_{\text{simple}} is ≈ dd (the dimension) at the smallest tt and ≈ 0 at the largest. Why is the floor not monotone in between on Ring World?

    AnswerSmall $t$: $x_t \approx x_0 + \sigma_t\varepsilon$ with $\sigma_t \ll S$, so $\varepsilon$'s effect is buried in the much larger uncertainty about $x_0$ within its blob; $\mathbb E[\varepsilon \mid x_t] \approx$ a small shrinkage, and nearly all of $\mathbb E\|\varepsilon\|^2 = d$ remains. Large $t$: $x_t \approx \varepsilon$, so $\varepsilon \approx x_t$ is almost perfectly predictable. In between, the floor tracks how uncertain $x_0$ is given $x_t$. When the noise scale reaches the distance between blobs ($t \approx$ 100–250), the blob identity becomes ambiguous and the uncertainty jumps (measured: 0.67 at $t$ = 50–100, 0.98 at 100–250), before the shrinking signal makes $x_0$ irrelevant.
  3. Tweedie. Using ∇zlog⁡pt(z)=−E[ε∣z]/σ\nabla_z \log p_t(z) = -\mathbb E[\varepsilon \mid z]/\sigma, show that the optimal one-step denoiser is E[x0∣z]=(z+σ2∇zlog⁡pt(z))/a\mathbb E[x_0 \mid z] = (z + \sigma^2 \nabla_z \log p_t(z))/a. For a single Gaussian x0∼N(μ,S2)x_0 \sim \mathcal N(\mu, S^2), compute it and interpret.

    Answer$\mathbb E[x_0 \mid z] = (z - \sigma\,\mathbb E[\varepsilon \mid z])/a = (z + \sigma^2\nabla\log p_t(z))/a$. For one Gaussian, $p_t = \mathcal N(a\mu, a^2S^2 + \sigma^2)$, score $= (a\mu - z)/(a^2S^2+\sigma^2)$, so $\mathbb E[x_0\mid z] = \mu + \frac{aS^2}{a^2S^2 + \sigma^2}(z - a\mu)$: a shrinkage of the rescaled observation toward the prior mean, with weight set by the signal-to-noise ratio (the Wiener filter). `ring_world.noised` computes exactly this per blob and averages with the responsibilities.
  4. CFG algebra. Starting from Bayes’ rule, show that (1+w)ε(x,c)−w ε(x)=ε(x)−(1+w)σt∇log⁡pt(c∣x)(1+w)\varepsilon(x,c) - w\,\varepsilon(x) = \varepsilon(x) - (1+w)\sigma_t\nabla\log p_t(c \mid x). What distribution would exact CFG sample at a single noise level, and why is that not the same as what the full sampler produces?

    Answer$\varepsilon(x, c) = -\sigma_t\nabla\log p_t(x\mid c) = -\sigma_t[\nabla\log p_t(x) + \nabla\log p_t(c\mid x)] = \varepsilon(x) - \sigma_t\nabla\log p_t(c \mid x)$; substitute and collect. At one level the guided score is that of $p_t(x)\,p_t(c\mid x)^{1+w} \propto p_t(x\mid c)\,p_t(c\mid x)^{w}$. But the sampler uses a *different* tilt at every noise level, and the tilted marginals at different levels are not the noisy versions of one distribution. The end result is not $p(x\mid c)p(c\mid x)^w$ for any single $w$ (Chidambaram et al., 2024). Demo 03 shows the net effect: sharpening toward the confidently-classified major blob.
  5. CFM = FM + constant. Prove that the cross term vanishes in E∥vθ−(x1−X0)∥2=E∥vθ−v∥2+E∥v−(x1−X0)∥2\mathbb E\|v_\theta - (x_1 - X_0)\|^2 = \mathbb E\|v_\theta - v\|^2 + \mathbb E\|v - (x_1 - X_0)\|^2, where v(x,s)=E[x1−X0∣Xs=x]v(x, s) = \mathbb E[x_1 - X_0 \mid X_s = x].

    AnswerThe cross term is $2\,\mathbb E[(v_\theta(X_s) - v(X_s))^\top (v(X_s) - (x_1 - X_0))]$. Condition on $X_s$: the first factor is fixed and the second has conditional mean $v(X_s) - \mathbb E[x_1 - X_0 \mid X_s] = 0$. The same argument (the conditional mean minimizes squared error, and the residual is orthogonal to any function of the conditioning variable) gives the DDPM loss floor of §2.3.
  6. Masked diffusion’s weights. Verify ∫011t(Lk)tk(1−t)L−kdt=1k\int_0^1 \frac{1}{t}\binom{L}{k}t^k(1-t)^{L-k}dt = \frac{1}{k} and use it to write the ELBO as a sum over kk. Why does the k=Lk = L term (everything masked) cost so much more than the others (1.324 vs 0.110–0.385 nats per token in demo 05)?

    Answer$\binom{L}{k}B(k, L-k+1) = \frac{L!}{k!(L-k)!}\cdot\frac{(k-1)!(L-k)!}{L!} = \frac{1}{k}$. So $-\text{ELBO} = \sum_k \mathbb E_{|M|=k}[\frac1k\sum_{i\in M}\ell_i]$, the expected loss of the $(L-k+1)$-th prediction of a random-order AR model. With everything masked, each position must be predicted from no context at all: its marginal distribution. Position 5 of a random sentence could be almost any word, so its entropy is high. With at least one token visible, the sentence type and much else are known, and the per-token loss drops sharply.
  7. Parallel decoding. In Errand World, the possessive is determined by the subject. Suppose a diffusion LM reveals the subject and the possessive in the same step, and its marginals are exactly right: P(he)=P(she)=0.25P(\text{he}) = P(\text{she}) = 0.25, P(they)=P(i)=0.2P(\text{they}) = P(\text{i}) = 0.2, P(we)=0.1P(\text{we}) = 0.1, and the possessive’s marginal matches. What is the probability of an agreement error? How does the measured 41.9% at 4 steps compare, and why is it lower?

    AnswerAgreement holds when both independent draws pick the matching pair: $\sum p_i^2 = 0.0625 + 0.0625 + 0.04 + 0.04 + 0.01 = 0.215$, so the error rate is 78.5%. The measured 41.9% at 4 steps is lower because the two positions are revealed in the same step only part of the time. When one is revealed earlier, the other is predicted *conditioned* on it, which removes the error. More steps make simultaneous reveals rarer (20.0% at 8, 1.2% at 200).
  • Assignment 3 (literature review, proposal, baseline reproduction) is released. Diffusion LMs and flow-matching samplers are active areas where a reproduction is feasible on modest compute. §5.4 and §6.3 show the two analyses a careful reproduction needs: compare samplers at matched time grids and NFE, and never compare a bound with an exact likelihood without saying so. These notes do not provide assignment code.

Further reading

  • J. Ho, A. Jain, P. Abbeel, “Denoising Diffusion Probabilistic Models”, NeurIPS 2020 (course reading); J. Sohl-Dickstein et al., “Deep Unsupervised Learning using Nonequilibrium Thermodynamics”, ICML 2015.
  • Y. Song et al., “Score-Based Generative Modeling through Stochastic Differential Equations”, ICLR 2021; J. Song, C. Meng, S. Ermon, “Denoising Diffusion Implicit Models”, ICLR 2021; T. Karras et al., “Elucidating the Design Space of Diffusion-Based Generative Models”, NeurIPS 2022.
  • A. Nichol, P. Dhariwal, “Improved Denoising Diffusion Probabilistic Models”, ICML 2021; T. Salimans, J. Ho, “Progressive Distillation for Fast Sampling of Diffusion Models”, ICLR 2022; D. Kingma, R. Gao, “Understanding Diffusion Objectives as the ELBO with Simple Data Augmentation”, NeurIPS 2023.
  • P. Dhariwal, A. Nichol, “Diffusion Models Beat GANs on Image Synthesis”, NeurIPS 2021; J. Ho, T. Salimans, “Classifier-Free Diffusion Guidance”, 2022.
  • Y. Lipman et al., “Flow Matching for Generative Modeling”, ICLR 2023 (course reading), and “Flow Matching Guide and Code”, 2024; X. Liu, C. Gong, Q. Liu, “Flow Straight and Fast: Learning to Generate and Transfer Data with Rectified Flow”, ICLR 2023; M. Albergo, E. Vanden-Eijnden, “Building Normalizing Flows with Stochastic Interpolants”, ICLR 2023; R. Gao et al., “Diffusion Meets Flow Matching: Two Sides of the Same Coin”, 2024 (blog).
  • R. Rombach et al., “High-Resolution Image Synthesis with Latent Diffusion Models”, CVPR 2022; W. Peebles, S. Xie, “Scalable Diffusion Models with Transformers”, ICCV 2023; P. Esser et al., “Scaling Rectified Flow Transformers for High-Resolution Image Synthesis” (Stable Diffusion 3), ICML 2024.
  • J. Austin et al., “Structured Denoising Diffusion Models in Discrete State-Spaces”, NeurIPS 2021; X. Li et al., “Diffusion-LM Improves Controllable Text Generation”, NeurIPS 2022; S. Sahoo et al., “Simple and Effective Masked Diffusion Language Models”, NeurIPS 2024 (Fall 2025 reading); J. Shi et al., “Simplified and Generalized Masked Diffusion for Discrete Data”, NeurIPS 2024; J. Ou et al., “Your Absorbing Discrete Diffusion Secretly Models the Conditional Distributions of Clean Data”, 2024.
  • S. Gong et al., “Scaling Diffusion Language Models via Adaptation from Autoregressive Models”, 2024 (Fall 2025 reading); S. Nie et al., “Scaling up Masked Diffusion Models on Text”, ICLR 2025, and “Large Language Diffusion Models” (LLaDA), 2025; M. Prabhudesai et al., “Diffusion Beats Autoregressive in Data-Constrained Settings”, 2025.

Preview of Lecture 16 — Reinforcement learning I

So far every model has been trained to imitate data, whether by maximum likelihood, denoising or flow matching. The next block changes the supervision. A model generates, a reward says how good the result was, and the model is updated to make good outputs more likely. Lecture 16 builds the foundations:

  • MDPs, returns and policies;
  • the policy gradient (Lecture 1’s REINFORCE, now derived properly);
  • baselines and advantages, GAE;
  • PPO’s clipped objective.

They are measured on the course’s CartPole example and on a small text environment where the exact gradient is known. Diffusion connects too. The score-function estimator behind REINFORCE is the one Lecture 12 compared with reparameterization, and “fine-tune a diffusion model with a reward” is an RL problem of exactly this kind.


术语表 (Glossary, English → 中文)

English中文
diffusion model / denoising diffusion probabilistic model (DDPM)扩散模型 / 去噪扩散概率模型
forward process / reverse process前向过程 / 反向过程
noise schedule / linear / cosine schedule噪声调度 / 线性 / 余弦调度
signal-to-noise ratio (SNR)信噪比
reparameterization重参数化
evidence lower bound (ELBO) / prior matching / denoising / reconstruction term证据下界 / 先验匹配项 / 去噪项 / 重建项
posterior q(x_{t-1} | x_t, x_0)前向过程后验
noise prediction / data prediction / v-prediction噪声预测 / 数据预测 / v 预测
loss floor (irreducible loss)损失下界(不可约损失)
score / score function / Tweedie’s formula分数 / 分数函数 / Tweedie 公式
ancestral sampling祖先采样
stochastic / ordinary differential equation (SDE / ODE)随机 / 常微分方程
probability-flow ODE概率流常微分方程
DDIM / inversion去噪扩散隐式模型 / 反演
number of function evaluations (NFE)函数评估次数
discretization error / Euler / Heun / Runge–Kutta method离散化误差 / 欧拉法 / 休恩法 / 龙格-库塔法
time grid / step schedule时间网格 / 步长安排
latent diffusion / Diffusion Transformer (DiT) / distillation潜空间扩散 / 扩散 Transformer / 蒸馏
conditional generation条件生成
classifier guidance / classifier-free guidance (CFG) / guidance weight分类器引导 / 无分类器引导 / 引导权重
implicit classifier / condition dropout隐式分类器 / 条件丢弃
diversity / fidelity / typicality多样性 / 保真度 / 典型性
flow / velocity field / flow matching流 / 速度场 / 流匹配
conditional flow matching (CFM) / conditional vs marginal velocity条件流匹配 / 条件速度与边缘速度
straight path / Gaussian path直线路径 / 高斯路径
rectified flow / reflow / straightness / coupling整流流 / 再整流 / 直线度 / 耦合
change of variables / divergence变量替换 / 散度
discrete diffusion / absorbing state / mask token离散扩散 / 吸收态 / 掩码词元
masked diffusion language model (MDLM)掩码扩散语言模型
any-order autoregression任意顺序自回归
parallel decoding / conditional independence并行解码 / 条件独立
confidence-ordered unmasking置信度优先揭示
infilling / bidirectional context填空 / 双向上下文
data-constrained regime / memorization / data augmentation数据受限情形 / 记忆 / 数据增强
← 返回课程目录