Lecture 28 · Diffusion Language Models

Scalable AI: Bridging Theory, Understanding, and Practice · Lecture 28。个人学习讲义与配套实验,按主题整理并持续修订。

课程源码 ZIP ↓

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

本篇目录

Maps to: UC Berkeley EE 290/194 Scalable AI, Spring 2026 Lecture 24, Diffusion Language Models (42 slides: the modelling view, masked and block diffusion, serving and decoding, a deep dive on Explore-Then-Exploit decoding, frontiers). Fall 2026 has no lecture on this topic.

Sources beyond the slides: Sahoo et al., Simple and Effective Masked Diffusion Language Models (MDLM, NeurIPS 2024) for the continuous-time objective implemented here; Nie et al., LLaDA (2025) for low-confidence remasking and semi-autoregressive sampling; Wu et al., Fast-dLLM (2025) for threshold decoding and approximate KV reuse; Arriola et al., Block Diffusion (ICLR 2025). Numbers from these papers are not reproduced; the slides’ ETE numbers are quoted as the slides give them.

Code: code/lecture28/ contains:

  • mdlm.py: a masked diffusion LM with Lecture 21’s parent architecture, trained on the same Atlas World data and compute (~2 min, cached); likelihood bounds; four samplers; sequence-level scoring against Atlas World’s exact probabilities;
  • five demos: the objective and likelihood, steps vs quality, parallel decoding and the joint problem, infilling, serving cost.

Reading time: ~2 hours for the prose; ~3 minutes to run all demos (plus ~2 minutes once to train the MDLM).


0. How to read this lecture

0.1 Learning goals

After this lecture you should be able to:

  1. Explain the masked-diffusion objective as subset completion, and why it bounds the likelihood.
  2. Separate three questions the slides insist on: how p(x) is represented, which tokens are committed when, and how much work each step reuses.
  3. Explain why parallel decoding is an approximation: the model learns one-token conditionals, not joints over several masked tokens; measure where that breaks.
  4. Reason about decoding schedules: random order, confidence order, semi-autoregressive blocks, thresholds, and planners such as Explore-Then-Exploit.
  5. Price diffusion decoding on real hardware: rounds vs cost per round, KV caches for blocks, and why the answer flips between batch 1 and batch 256.

0.2 Prerequisites and scope

  • Prerequisites: Lecture 9 (Atlas World and pre-training), Lecture 21 (the parent model, speculative decoding), Lecture 22 (the step model: memory- vs compute-bound steps).
  • Scope: discrete masked diffusion for text, trained and measured at toy scale, and the systems arithmetic at real scale.
  • Not in scope: continuous (embedding-space) diffusion for text; image diffusion (CS236 and MIT 6.S978 notes cover the theory).

0.3 Section → code map

SectionIdeaCode in code/lecture28/
§1why diffusion LMs, and three separate questions–
§2the objective; likelihood vs ARmdlm.py, 01_objective.py
§3decoding: steps, order, quality02_steps_vs_quality.py
§4the joint problem; thresholds; planners (ETE)03_parallel_decoding.py
§5infilling and editing04_infilling.py
§6serving: rounds vs cost per round05_serving_cost.py
§7the landscape and when diffusion wins–

0.4 The experiment

Both models have the same shape (d_model 128, 6 layers, 4 query / 2 KV heads, RoPE, SwiGLU; 1.3M parameters), see the same 128-token windows of Atlas World, and train for the same 2,000 steps × 4,096 tokens. The autoregressive (AR) model is Lecture 21’s parent. The MDLM adds one token, [MASK], and uses bidirectional attention. Because Atlas World’s probabilities are known exactly, every generated document can be checked: is it possible at all, are its facts right, do its sums add up? Tiny models are far from the scale where diffusion LMs become competitive (LLaDA is 8B), so read the absolute gaps as a small-scale result and the mechanisms as general.


1. Why diffusion language models

1.1 Two contracts with the model

The slides’ framing:

  • Autoregressive contract: ask one question, “what comes next?”. Every token joins the prefix forever; serving is simple because the context only grows (Lecture 22’s KV cache).
  • Diffusion contract: ask “what is missing here?”. Predictions use visible context on both sides; the decoding order becomes a design variable; generation can reveal, defer, revisit or remask; editing and infilling are native.

Diffusion trades a very convenient serving contract for a richer control surface over order, editability and parallelism. Public systems (Gemini Diffusion, Mercury, Seed Diffusion) sell latency and editable generation; open models span from-scratch pretraining (LLaDA 8B), AR-initialized diffusion (Dream 7B), code specialization, sparse MoE scaling (LLaDA-MoE) and multimodality (LLaDA-V).

1.2 Three questions that get conflated

questionAR answerdiffusion answers
probabilistic: how is p(x) represented?one fixed factorization p(x) = Π p(x_i | x_<i)masked diffusion, block diffusion, any-order AR
algorithmic: which tokens are committed now?the next onerandom, most confident, blockwise, thresholds, planners (ETE)
systems: how much work is reused?causal KV cacheblock caches, approximate KV reuse, dLLM-Cache

A model can be diffusion at the first level, use a planner at the second and only become fast with a block cache at the third. Remove any one of these and the speed story usually collapses (slides).


2. The objective (Demo 01)

2.1 Subset completion

Any permutation σ of positions gives a valid factorization p(x) = Π p(x_σ(i) | x_σ(<i)); AR fixes σ = (1, …, n). A masked diffusion model is trained to answer many subset-completion queries, so the order can be chosen at decoding time. The absorbing-mask corruption replaces each token by [MASK] with probability t; the model predicts the originals only where information was removed:

NELBO = E_t [ (1/t) Σ_{i masked} −log p_θ(x_i | x_masked) ] / L, t ~ U(0, 1)

The 1/t weight turns the average over masking rates into an upper bound on the negative log-likelihood (MDLM, Sahoo et al. 2024). The slides’ cleaner equivalent: sample a masked subset M, reveal the complement, predict every position in M, average over subsets. What is directly supervised: conditional marginals p(x_i | x_C) for one missing position at a time. What is not: joints p(x_A | x_C) over several missing positions, which is exactly what parallel decoding needs (§4).

2.2 Same model, same compute: the likelihood gap

On identical windows (targets 1–127, position 0 visible to both):

domainfloorAR (exact)MDLM (bound)AR excessMDLM excessratio
story0.7500.7560.8130.0070.0649.8×
wiki0.6380.6520.9180.0130.28020.8×
math0.8941.0461.4690.1530.5753.8×
code0.5770.6800.8100.1020.2332.3×
all0.7190.7340.8600.0150.1419.4×

(bits per byte; the MDLM’s number is an upper bound, so its true likelihood is somewhat better.)

With equal compute the MDLM’s excess over the floor is ~9× the AR model’s. The gap is largest in absolute terms on math (+0.42 bits/byte) and in relative terms on wiki (memorized facts): domains of determined tokens, where one left-to-right order is natural and the MDLM must also learn every other order. Published scaling studies make the same qualitative point at larger scale: masked diffusion needs more compute to reach an AR model’s likelihood, and LLaDA reaches competitive downstream quality at 8B parameters.

2.3 Hard at the start, easy at the end

Loss per masked token by masking rate: 1.05 nats at t = 0.05, 1.52 at 0.5, 3.86 at 0.95. Reconstruction is easy with lots of context and a unigram-like guess with almost none. Decoding from a fully masked canvas therefore starts with the hardest predictions, and each early commitment conditions everything after it.


3. Decoding: steps, order and quality (Demo 02)

3.1 The exact sampler is not parallel

A sampler perfectly aligned with the objective (slides): start fully masked; pick one masked position uniformly; sample it from its marginal; freeze it; repeat. That is any-order autoregression, one token per step. Diffusion does not buy speed automatically: any speedup comes from committing several tokens per step (an approximation), from a cheaper step (structure, caching), or both.

3.2 Measured on Atlas World

128 samples of 128 tokens per row; complete documents only:

samplerpassestokens/stepvalid docsreal wordsdistinct-3facts right (n)sums right (n)
real data––1.0000.9970.6321.00 (45)1.00 (105)
AR parent1271.00.6360.9970.6001.00 (43)0.32 (90)
MDLM, random order1271.00.0650.9380.7180.00 (1)0.02 (43)
167.90.0190.8990.761–0.00 (29)
431.80.0020.7970.891–0.00 (8)
MDLM, most confident first642.00.3570.9940.084––
MDLM, semi-AR blocks of 32642.00.1300.9910.153––

(valid = possible under Atlas World; real words = share of words in the lexicon; distinct-3 = unique word trigrams / all trigrams, a diversity measure.)

  • At one token per step the MDLM is a much weaker generator than the same-size AR model: 6% valid documents vs 64%, almost no fact sentences, 2% right sums vs 32%. Word-level metrics understate the gap (93.8% vs 99.7% real words); sequence-level ones show it.
  • More tokens per step costs quality: real words fall to 79.7% at 32 tokens per step and diversity drifts toward random. Tokens revealed together are sampled from separate marginals.
  • Order matters as much as step count, and confidence order fails differently: most-confident-first writes clean words (99.4%) but collapses into repetition (“the boat drifts . the boat drifts .”): distinct-3 0.084 vs 0.632 for real data, entropy below the data’s (0.605 vs 0.724 bits/byte), and only 14 complete documents in 128 samples, because ending a document is never the most confident move. Semi-AR blocks inherit the same collapse. Confidence and diversity pull in opposite directions; production samplers add temperature, remasking and planners to manage it.

4. Parallel decoding and the joint problem (Demo 03)

4.1 Marginals are not a joint

Parallel decoding assumes p(x_A | x_C) ≈ Π_{i∈A} p(x_i | x_C), but language rarely factorizes: names, ages and schools in a profile; variable names in code; agreement; entities and their facts. Demo 03 measures it on two constraints the MDLM has clearly learned:

canvasrevealedagreement
the two token slots of one masked wordtogether (1 step)0.613 (every filled word exists)
one by one (2 steps)0.938
“the [M] [M] . the [M] [M] .” (no topic cue)together0.357 (same topic)
one by one0.965

(random topic words would agree 25% of the time.) Revealed together, two word pieces are drawn independently and often form a non-word; four content words land in different topics. Revealed one by one, each sees the earlier ones and the constraint holds. The same model, the same canvas: only the commitment schedule differs. (A first version of this test used sums and variable bindings; this small MDLM never learned those constraints even one token at a time, so it could not show the effect there.)

4.2 Confidence thresholds

Fast-dLLM’s rule commits every masked position whose top probability is at least C (and at least one per step). On this small model:

Cmean stepstokens/stepreal words
0.99125.01.00.964
0.5109.61.20.942
0.393.51.40.920

The rule only buys parallelism if the model is confident, and this one rarely is. Large models’ sharper marginals are what make threshold decoding fast; the threshold itself just trades quality for steps at whatever confidence the model has.

4.3 Bits to rounds, and Explore-Then-Exploit

The slides’ deep dive explains why confidence-only decoding stalls. High-confidence tokens are low-surprisal tokens: easy to guess, carrying few bits. If every token committed in a round must meet a confidence constraint with factor f, the number of rounds obeys (simplified)

R ≥ −log p(x) / log( (n + 1) / ((1 − f)n + 1) )

The numerator is the information content of the sequence; the denominator bounds the information a confidence-constrained round can absorb. Stricter confidence means fewer bits per round and more rounds; the last hard tokens become a serial bottleneck.

Explore-Then-Exploit (ETE) changes which tokens are committed: exploit (commit all tokens above the threshold), and when progress stalls, explore by committing a carefully chosen anchor, an uncertain-but-informative token whose revelation makes many others confidently decodable. Candidates are scored by plausibility × the confident mass they unlock in one batched lookahead; fast block diffusion lets later blocks start before earlier ones finish, since a hard token in block k may be explained by block k+1. The slides report frontier gains of roughly 1.25–2× tokens per step on GSM8K and 1.25–2.5× on HumanEval at comparable accuracy (LLaDA-8B-Instruct, blocks of ~64), and 26–61% fewer decoding steps across benchmarks relative to confidence-based baselines. ETE changes the order and the block progression, not the model: a planner for a pretrained reconstructor.

Other decoding directions on the slides: stop early when a trajectory has converged (Prophet), search over orders (LookUM), revoke commitments when later evidence contradicts them (WINO), and learn the sampler with RL (DiFFPO).


5. Infilling and editing (Demo 04)

Diffusion’s native strength is filling gaps with context on both sides. Demo 04 cuts 200 gaps per family from fresh Atlas documents:

gappositionMDLM accuracyAR accuracyMDLM passesAR passes / sequencesAR method
sum resultend0.0150.4002.02.0greedy continuation
sum operandmiddle0.0250.4551.850score every candidate
fact valueend0.2350.9154.64.5greedy continuation
fact entitymiddle0.1250.6304.9100score every candidate
wordmiddle0.9951.0001.5130score every candidate
  • At this scale the stronger model wins even in the middle. The AR model can infill by scoring every candidate filler with the likelihood of the whole document; with sharp likelihoods and small candidate sets that works well (entities 0.630 vs 0.125).
  • The MDLM’s advantage is the interface: 1.5–5 forward passes instead of 50–130, and no candidate list at all. Free-form infills (a phrase, a code block, a revised paragraph) have no closed candidate set, so enumeration is not an option; that is the product case for diffusion (editing, filling, constrained generation).

6. Serving: rounds vs cost per round (Demo 05)

The slides’ rule of thumb: ask separately how many rounds the sampler needs and how expensive each round is. Demo 05 prices both with Lecture 22’s step model (Llama-3-8B shapes, one H100, a 512-token prompt, 1,024 generated tokens):

batchdecoderforward passestokens/s per usertokens/s per GPU
1autoregressive1,024142142
1full canvas, 8 tokens/step (no cache)128196196
1block diffusion (32), 8 tokens/step1281,1181,118
16autoregressive1,0241252,000
16block diffusion (32), 8 tokens/step1284987,976
256autoregressive1,0244311,089
256block diffusion (32), 8 tokens/step128338,475
  • At batch 1, decoding is memory-bound (Lecture 22): a forward over 32 tokens costs about as much as over one, so block diffusion at 8 tokens/step is 7.9× faster per user. That is the latency case diffusion products advertise.
  • Without a KV cache the speedup mostly disappears: a full-canvas model recomputes all 1,536 positions every step, about 192× the matmul FLOPs per token of AR at 8 tokens/step. Block diffusion caches finished blocks and recomputes only the active one (4× AR at 8 tokens/step).
  • At batch 256 the trade flips: AR is near compute-bound, and diffusion’s redundant computation (each token recomputed ~4 times) loses per GPU (8,475 vs 11,089 tokens/s). At batch 16 block diffusion is still 4× AR per GPU.
  • NFE is a proxy. A lower step count can lose if each step is heavier; a higher one can win with caching and hardware-friendly blocks. Compare tokens/s per user and per GPU at the batch you will serve.

This is the same arithmetic as Lecture 21’s speculative decoding: both convert spare compute at small batch into fewer sequential rounds, and both stop paying when the hardware is already saturated.


7. The landscape: when diffusion should win

full-response masked diffusionblock / hybrid diffusion
active regionthe whole response canvasa bounded block; earlier context handled causally
lengthpreallocated, or a separate length policyclose to streaming; EOS-aware training
cacheabilitylimited: the whole canvas may changestrong: prompt and earlier blocks frozen
best fitediting, infilling, broad reconstructionserving, latency control, hybrid deployments
examplesLLaDA family, TESS 2Block Diffusion, Dream 7B, Fast-dLLM v2, D2F, dLLM-Var

AR-to-diffusion adaptation has become the practical route: AR is block diffusion with block size 1, so a pretrained AR checkpoint (its world model and tokenizer) can be adapted by widening the active block, with a far smaller budget than pretraining from scratch.

Diffusion is attractive (slides) when infilling or editing is first-class, when the task has strong cross-token constraints worth planning over, and when latency is dominated by per-step overhead rather than per-token compute (small batches). AR keeps structural advantages when streaming next-token output is the product, when the serving stack already saturates the hardware (large batches), when exact likelihood and simple EOS handling matter, and when small-batch planners are unattractive.


8. Summary

  1. A diffusion LM is a model over partially observed sequences: trained on subset completion, it learns one-token conditionals; its objective bounds the likelihood.
  2. Same size and compute, a weaker model at small scale: a ~9× larger excess over the floor on Atlas World, 6% vs 64% valid documents when sampled one token per step.
  3. The exact sampler is sequential; parallel commitment is an approximation that breaks where tokens depend on each other (word pieces 61% vs 94%, topics 36% vs 96.5%).
  4. Order is part of the algorithm: random order is noisy, confidence order is clean but repetitive and low-entropy; thresholds need confident models; planners like ETE choose informative anchors and report 26–61% fewer steps.
  5. Infilling is native to diffusion (no candidate lists, few passes), but a stronger AR model with enumeration can still win when candidates are few.
  6. Speed is a systems property: block caches and memory-bound small batches make diffusion fast (7.9× per user at batch 1); redundant computation makes it lose at large batch.

9. Common pitfalls

  • Assuming diffusion is parallel by construction. The objective implies one-token-at-a-time sampling; parallelism is an approximation.
  • Reporting NFE as speed. Count the cost per step and the batch.
  • Reporting token-level metrics only. Perplexity-like scores hide failures of global consistency.
  • Confidence-first without diversity control: repetition and missing document ends.
  • Full-canvas recomputation in serving: no cache, no speedup.
  • Comparing models at different compute, or AR with KV cache against diffusion without one.

10. Exercises

  1. The 1/t weight. Why does the MDLM loss weight masked tokens by 1/t? What would go wrong without it?

    AnswerAt masking rate t about tL tokens are masked; weighting each by 1/t makes every t contribute the loss of a full sequence's worth of predictions, and the resulting average over t is exactly the continuous-time ELBO (an upper bound on −log p). Without it, low-t windows (few masked tokens) would contribute little, the objective would no longer bound the likelihood, and the model would under-train the nearly-complete-context predictions that decoding's final steps rely on.
  2. Rounds bound. A 128-token sequence carries 200 nats of information. A sampler commits only tokens with confidence ≥ 0.9 (f = 0.9). Use the simplified bits-to-rounds bound to estimate the minimum number of rounds.

    AnswerDenominator: log((n+1)/((1−f)n+1)) = log(129 / (12.8 + 1)) = log(9.35) = 2.24 nats. R ≥ 200 / 2.24 ≈ 90 rounds: at most ~1.4 tokens per round on average. Raising f toward 1 makes the denominator shrink toward 0 and R grow without bound.
  3. Block size. Using Demo 05’s model, why does block diffusion with 8 tokens/step cost ~4× AR’s FLOPs per token with 32-token blocks? What happens with 64-token blocks at 8 tokens/step?

    AnswerEach of the block's 32/8 = 4 steps recomputes all 32 positions, so each token is computed ~4 times. With 64-token blocks: 8 steps × 64 positions per 64 tokens = 8× AR. Larger blocks give more parallelism per step but more redundant computation; at batch 1 that is nearly free, at large batch it is not.
  4. Infilling cost. The AR model infills an entity by scoring 100 candidates, each a ~60-token document. How many token-forwards does that cost, compared with the MDLM’s ~5 passes over the same document?

    Answer100 × 60 = 6,000 token-forwards (one sequence per candidate) vs 5 × 60 = 300 for the MDLM: 20× more. With a KV cache shared by the common prefix, AR only needs to recompute from the gap onward, which helps but still scales with the number of candidates.
  5. Why did confidence order stop ending documents? Explain with Demo 02’s numbers.

    AnswerA document boundary ("\n") is never the single most confident prediction while other positions offer near-certain tokens (". ", "the"), so confidence-first fills the canvas with locally safe tokens and almost never places a boundary: 14 complete documents in 128 samples vs 141 for real data. The same preference for safe tokens produces repetition (distinct-3 0.084) and entropy below the data's.

No assignment covers diffusion LMs. Assignment 4’s serving analysis transfers directly: count rounds and cost per round separately; report tokens/s per user and per GPU at a stated batch; compare decoders with the same caching. For the research project, Atlas World-style exact scoring is a cheap way to measure sequence-level correctness of any new decoder.


12. Research directions

From the slides’ open problems:

  • Better joint samplers: approximate masked-set joints without expensive lookahead.
  • Planner-aware objectives: pretraining that makes anchors easier to identify or commit safely.
  • Fair evaluation: protocols comparing NFE, wall-clock, batch size and hardware across serving stacks.
  • Safety under any-order generation: refusal and policy mechanisms when harmful spans can appear non-monotonically.
  • Product fit: which interfaces truly benefit from edit-in-place generation rather than streaming.
  • Small-scale science: at what scale and compute does masked diffusion close the likelihood and sample-quality gap with AR on a world with known entropy (§2.2 is one point on that curve)?

13. Further reading

  • Sahoo et al., Simple and Effective Masked Diffusion Language Models (NeurIPS 2024); Shi et al., Simplified and Generalized Masked Diffusion for Discrete Data (2024).
  • Nie et al., LLaDA: Large Language Diffusion Models (2025); Ye et al., Dream 7B (2025).
  • Arriola et al., Block Diffusion (ICLR 2025); Wu et al., Fast-dLLM and Fast-dLLM v2 (2025).
  • The slides’ reading list: From Bits to Rounds / ETE; Prophet, LookUM, WINO; DiFFPO; A2D, LLaDA-V, LLaDA-MoE, dLLM-Var.
  • Lecture 21 (speculative decoding: another way to trade compute for rounds); the CS236 and CMU 11-711 notes for discrete diffusion theory.

14. Next lecture

Lecture 29, Research Greenfields and Course Review, closes the course: open problems in performance and accelerators, in pre- and post-training and in inference, how to turn them into testable hypotheses for an 8×H100 project, and a review of the two maps (the lifecycle and the stack) and the scaling walls.


术语表 (Glossary, English → 中文)

English中文
diffusion language model (dLLM)扩散语言模型
masked / absorbing-state diffusion掩码 / 吸收态扩散
[MASK] token / canvas掩码符 / 画布(待填序列)
subset completion / any-order autoregression子集补全 / 任意顺序自回归
ELBO / NELBO证据下界 / 负证据下界
bidirectional attention双向注意力
denoising step / NFE去噪步 / 函数评估次数
unmasking order / commitment schedule揭示顺序 / 提交调度
confidence remasking / threshold decoding置信度重掩码 / 阈值解码
semi-autoregressive / block diffusion半自回归 / 块扩散
marginal vs joint边缘分布 vs 联合分布
anchor token / Explore-Then-Exploit锚点词元 / 先探索后利用
bits-to-rounds bound信息量-轮数下界
infilling / editing填空 / 编辑
full-canvas recomputation / block KV cache全画布重算 / 块级键值缓存
AR-to-diffusion adaptation自回归到扩散的改造
repetition / diversity (distinct-n)重复 / 多样性(distinct-n)
← 返回课程目录