Lecture 9 · Decoding Algorithms

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

课程源码 ZIP ↓

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

本篇目录

Maps to: CMU 11-711 Spring 2026, Lecture 9 (02/10), slides anlp-s2026-09-decoding.pdf (adapted from Matthew Finlayson’s NeurIPS 2024 tutorial and Amanda Bertsch’s Spring 2025 guest lecture); course demo code 09_decoding/ (categorical.ipynb: sampling from a categorical distribution; decoding.ipynb: greedy, beam, sampling with SmolLM2; kv_cache.ipynb: a KV cache by hand). Reading: S. Welleck, A. Bertsch, M. Finlayson, H. Schoelkopf, A. Xie, G. Neubig, I. Kulikov, Z. Harchaoui, From Decoding to Meta-Generation: Inference-time Algorithms for Large Language Models (2024), Sections 1–3. Sources: the public slides, the reading, and the papers cited in each section. Every number labelled “measured” comes from code/lecture09/, run on the author’s machine (Apple M4 Pro, Python 3.13, PyTorch 2.14, one CPU thread). Code: code/lecture09/ — every demo runs in under 40 seconds. Reading time: ~100 minutes for the prose; ~25 more for the demos.


0. How to read this lecture

0.1 Learning goals

After this lecture you should be able to:

  1. State the two decoding objectives — optimization (find the mode) and sampling (draw from the distribution) — and when each is used.
  2. Run greedy decoding and beam search, and explain why neither guarantees the most likely output (search errors).
  3. Explain the pitfalls of MAP decoding: repetition traps, short outputs, atypicality, and probability spread over paraphrases — and their remedies (length normalization, sampling, MBR).
  4. Explain why ancestral sampling degrades (the heavy tail, compounding error (1−ϵ)T(1-\epsilon)^T), and what temperature, top-k, top-p and min-p change.
  5. Explain the KV cache, why decoding is memory-bound, latency vs throughput, and how speculative decoding speeds up generation without changing its distribution.

0.2 Prerequisites and scope

  • Prerequisites: Lecture 3 (autoregressive models, sampling, Errand World), Lecture 5 (attention, KV cache sizes), Lectures 7–8 (prompting, sequence-level distillation, verifiers).
  • Scope: token-level generation algorithms and the basics of efficient inference.
  • Not in scope: meta-generation — best-of-N, self-consistency, tree search, refinement (Lecture 23); quantization (Lecture 19); FlashAttention and state-space models (Lecture 22); serving systems such as PagedAttention and continuous batching (not in the Spring 2026 slides; Lecture 23’s Further reading has pointers).

0.3 Section → code map

SectionIdeaDemo in code/lecture09/
§2.2–2.4greedy vs beam vs exact MAP; search errors01_map_decoding.py Parts A–B (+ decoders.py)
§2.5MAP pitfalls: atypical and short outputs, length normalization, repetition traps01_map_decoding.py Parts C–D
§2.6probability spread across paraphrases; minimum Bayes risk03_mbr.py
§3ancestral sampling, the heavy tail, temperature / top-k / top-p / min-p02_sampling.py
§4KV cache; memory-bound decoding; speculative decoding04_fast_decoding.py (+ fast_decoding.py)

0.4 Notation

SymbolMeaning
xxthe input (prompt); y=y1:Ty = y_{1:T} the output
pθ(y∣x)=∏tpθ(yt∣y<t,x)p_\theta(y \mid x) = \prod_t p_\theta(y_t \mid y_{<t}, x)the autoregressive model
V\mathcal{V}, Y\mathcal{Y}vocabulary; the set of all outputs
BBbeam width; kk for top-k, pp for top-p, τ\tau the temperature
ϵ\epsilonprobability mass a model puts on “bad” next tokens
qq, ppdraft and target models in speculative decoding

1. Where decoding sits

The course so far, in the recipe of Lecture 1:

  • Modeling / parameterization: classification or generation? Autoregressive? Which architecture? (Lectures 1–5.)
  • Learning: maximum likelihood or something else? Pretrain first? What data or supervision? (Lectures 3, 6–8.)
  • Inference (today): using a model after learning.

Given “The weather today is”, an autoregressive LM supplies a distribution over the next token. Decoding is everything that turns those distributions into an output such as “cloudy with a chance of …”.


2. Decoding as optimization

2.1 Basic setup

An autoregressive model factorizes

pθ(y1:T∣x)=∏t=1Tpθ(yt∣y<t,x),p_\theta(y_{1:T} \mid x) = \prod_{t=1}^T p_\theta(y_t \mid y_{<t}, x),

and each factor is a distribution over next tokens. We choose a next token, add it to the context, get a new distribution, and repeat until an end token. Every step requires a choice. Decoding asks two things:

  • What is the objective?
  • How do local choices achieve it?

2.2 The objective: the most likely output

y^=arg⁡max⁡y∈Ypθ(y∣x).\hat y = \arg\max_{y \in \mathcal{Y}} p_\theta(y \mid x).

This is called mode-seeking (it finds a mode of the distribution), or maximum a posteriori (MAP) decoding: given evidence xx, find the mode of the posterior pθ(y∣x)p_\theta(y \mid x). The key challenge is that Y\mathcal{Y} is huge, ∣V∣T\lvert\mathcal{V}\rvert^T sequences, so we cannot enumerate it.

Greedy decoding chooses the most likely token at each step:

y^t=arg⁡max⁡y∈Vpθ(y∣y^<t,x).\hat y_t = \arg\max_{y \in \mathcal{V}} p_\theta(y \mid \hat y_{<t}, x).

It does not guarantee the most likely sequence. A likely first token can lead into a region where every continuation is unlikely.

Beam search is a width-limited breadth-first search. It keeps the BB most likely partial outputs, expands each by its best next tokens, and keeps the best BB again:

  • B=1B = 1 is greedy.
  • B=∣V∣TB = \lvert\mathcal{V}\rvert^T would be exact MAP; for GPT-2’s vocabulary and 128 tokens that is 50,00012850{,}000^{128}.
  • In practice BB is a small hyperparameter, e.g. 4–16.

In HuggingFace: model.generate(do_sample=False, num_beams=1) for greedy, num_beams=b for beam search.

MAP decoding has traditionally been used for closed-ended tasks such as translation and summarization.

2.4 Measured: search errors on a language with known probabilities

Errand World’s 34,320 sentences and their exact probabilities can be enumerated (Lecture 3), so we can compare a decoder’s output with the true most likely sentence. decoders.TableLM exposes the true distribution through the same interface as a trained model.

Measured (demo 01 Part A), the most likely sentence of the whole language:

decoderoutputlog p
greedy (beam 1)for music class , which met on monday and on tuesday and on friday , he wanted to buy his own guitar .−11.107
beam 2, 4, 8for painting class , which met on monday and on tuesday and on … , she wanted to buy her own brush .−11.107
beam 16 … 128she bought a car yesterday .−5.866
exact MAP (enumeration)she bought a car yesterday .−5.866

Greedy’s sentence is about 190 times less likely than the true mode (e11.107−5.866e^{11.107 - 5.866}). Sentences starting with “for” (40% of the language) look best for the first token, then split into many continuations: eight activities, optional clauses, days, subjects. Each of them is individually unlikely. “she” (35% of a 30% sentence type) looks worse at first, but leads into a short sentence with few choices. Beams of width ≤ 8 are filled entirely with “for …” prefixes after two steps; it takes 16 beams to keep the winner alive.

Measured (Part B): completing 300 prompts (the first three words of random sentences):

decodersearch errorsmean log p gapworst gap
greedy40.0%1.5653.912
beam 240.0%1.5653.912
beam 440.0%1.5653.912
beam 160.0%0.0000.000

2.5 Pitfalls of MAP decoding

Even when we can find the mode, it is often not what we want. The slides list two kinds of pitfall: degeneracy (repetition traps, short sequences, atypicality), and the question of whether the highest-probability output is the “best”.

Repetition traps. Greedy decoding with real models falls into loops. The slides show SmolLM2-135M repeating a sentence, and Holtzman et al. (2020) documented the same for GPT-2. Models assign high probability to repetitive loops: once a phrase has appeared, repeating it becomes likely. Mitigations include a repetition penalty at decoding time, or changing the training loss (unlikelihood training).

Measured (demo 01 Part D). Errand World “diaries”: sentences drawn independently, and after each one the diary continues with probability 0.8 or ends with 0.2.

  • Greedy on the true diary distribution writes the same sentence 5 times, until the 120-token limit.
  • The exact most likely diary is a single sentence (log p −7.48), while greedy’s 120-token prefix has log p −60.34. At each sentence boundary, “continue” (0.8) beats “stop” (0.2) one step at a time, though every continuation costs far more than 0.8.
  • A Transformer trained on diaries loops the same way (5 sentences, 1 distinct).
  • Its samples do not loop: 5.4 sentences on average (true mean 5.0), with 0.3% repeated sentences.

Short sequences. Every extra token multiplies in a probability below 1, so MAP favors short outputs. Stahlberg & Byrne (2019) found that for many neural translation models the single most likely output is the empty sequence. Beam search works in practice partly because it fails to find it. The remedy is length normalization: rank finished hypotheses by log⁡p/∣y∣α\log p / \lvert y\rvert^\alpha.

Measured (Part C, exact search over completions of 100 prompts, by enumeration):

completionsmean length (words)
exact MAP4.95
exact MAP, length-normalized, α=0.5\alpha = 0.55.27
exact MAP, length-normalized, α=1\alpha = 110.24
greedy (search errors included)9.63
samples (20 per prompt)6.84

The exact mode is shorter than a typical completion. Full normalization (α=1\alpha = 1) overshoots to the longest options. Greedy’s search errors happen to go the long way here: ”,” → a relative clause looks best one step at a time.

Atypicality. Take a biased coin with P(heads) = 0.6 and flip it 100 times. The most likely outcome is all heads, and it is wildly atypical:

outcomelog p of one such sequenceP(number of heads = k)
all heads (the mode)−51.16.5×10−236.5 \times 10^{-23}
exactly 60 heads−67.30.081
50–70 heads0.968

The single all-heads sequence is e16e^{16} times more likely than any particular 60-heads sequence. But there are (10060)\binom{100}{60} of the latter, so a typical outcome has about 60 heads. Errand World’s MAP sentence appears in only 0.10% of samples, is 6 words long against an average of 10.0, and has log p −5.87 against a typical −8.30 (minus the entropy per sentence, 8.31). The most likely generation can be atypical in the same way (Meister et al., 2022). One remedy is sampling.

2.6 Is the highest-probability output the best?

Outputs with low probability tend to be worse than those with high probability. Among the top outputs, though, the relation is less clear. One reason: when there are many ways to say the same thing, probability is spread across them. A meaning expressed in four phrasings at 0.15 each has total probability 0.6, yet each of its strings loses to a different meaning stated one way at 0.3. MAP compares strings; what we usually care about is meanings. We often want outputs that are likely, but not necessarily maximally likely.

Minimum Bayes risk (MBR) decoding makes this precise. Pick the candidate with the highest expected utility under the model’s own distribution,

y^MBR=arg⁡max⁡y∈C Ey′∼pθ(⋅∣x)[U(y,y′)]≈arg⁡max⁡y∈C 1N∑j=1NU(y,yj′),\hat y_{\text{MBR}} = \arg\max_{y \in \mathcal{C}}\ \mathbb{E}_{y' \sim p_\theta(\cdot \mid x)}\big[U(y, y')\big] \approx \arg\max_{y \in \mathcal{C}}\ \frac{1}{N}\sum_{j=1}^N U(y, y'_j),

estimated with NN samples. With UU = “same answer”, MBR returns the answer with the most probability mass, a majority vote over meanings. This is exactly self-consistency for chain-of-thought (Lecture 23).

Measured (demo 03, Answer World):

  • 200 people, each asked “where does X live ?”.
  • For the spread half, the true city comes in four phrasings (“lima .” / “in lima .” / “she lives in lima .” / “the city of lima .”, 0.15 each), and a wrong city in one (“in dakar .”, 0.30).
  • For the concentrated half, the true city has one phrasing (0.60).

Under the true distribution, the most likely string is wrong for every spread person and right for every concentrated one. The most likely answer is right for all of them. A model trained on Answer World behaves the same:

decoderspread peopleconcentrated people
greedy2.0%100.0%
beam 44.0%100.0%
one sample55.0%57.0%
MBR, 5 samples (utility: same city)76.0%75.0%
MBR, 20 samples91.0%93.0%

MBR’s price: NN model samples instead of one search. And it needs a utility that captures what “the same” means: exact match for answers, BLEU or a learned metric for translations.


3. Decoding as sampling

3.1 Ancestral sampling

Modern LLM APIs expose sampling settings. The basic algorithm, ancestral sampling, samples from the model’s next-token distribution at each step:

y^t∼pθ(⋅∣y^<t,x),t=1,…,end.\hat y_t \sim p_\theta(\cdot \mid \hat y_{<t}, x), \quad t = 1, \dots, \text{end}.

This is equivalent to drawing a whole sequence y1:T∼pθ(y1:T∣x)y_{1:T} \sim p_\theta(y_{1:T} \mid x) (Lecture 3). Each step is a draw from a categorical distribution over ∣V∣\lvert\mathcal{V}\rvert items: draw u∼U(0,1)u \sim U(0,1) and find where it falls in the cumulative probabilities. PyTorch implements it as torch.multinomial.

3.2 What goes wrong: the heavy tail and compounding error

With a poorly trained model, ancestral sampling produces incoherent text, and even with good models it often does. The reason is the heavy tail. There are many choices for the next token (50,000). Even if each “bad” token has a tiny probability, their sum is not tiny.

Compounding error. If the total probability of sampling a bad token at a step is ϵ\epsilon, a length-TT output contains no bad token with probability (1−ϵ)T(1-\epsilon)^T:

  • ϵ=0.01\epsilon = 0.01, T=128T = 128: 0.276
  • ϵ=0.05\epsilon = 0.05, T=128T = 128: 0.0014
  • ϵ=0.01\epsilon = 0.01, T=1024T = 1024: 0.000034

Measured (demo 02 Part A). Because Errand World’s truth is known, ϵ\epsilon is measurable: the model’s probability on next tokens that are impossible given the prefix.

modelϵ\epsilon (mass on impossible next tokens)tokens per sentence TTpredicted valid (1−ϵ)T(1-\epsilon)^Tmeasured valid
well-trained (4,000 sentences, 12 epochs)0.004011.295.7%96.0%
partly trained (2,000 sentences, 4 epochs)0.066110.947.3%47.2%

The formula predicts the measured validity to within a few tenths of a percent. Even a model with only 0.4% of its mass in the tail ruins one sentence in 25. At the length of an essay, ruin is certain.

3.3 Truncate the tail, or reshape it

Truncation samples only from the reliable head of each distribution:

  • Top-k (Fan et al., 2018): keep the kk most probable tokens, renormalize: y^t∼pθ(yt∣y<t,x)/Z\hat y_t \sim p_\theta(y_t \mid y_{<t}, x) / Z if yt∈y_t \in top-kk, else 0.
  • Top-p (nucleus) (Holtzman et al., 2020): keep the smallest set of most probable tokens whose total mass is at least pp. The set adapts: a few tokens when the model is sure, many when it is not.
  • Many more strategies:
    • min-p: keep tokens with probability ≥ min-p × that of the most likely token;
    • ε / η sampling (Hewitt et al., 2022): drop tokens below an absolute or entropy-dependent threshold;
    • typical sampling (Meister et al., 2023): keep tokens whose surprisal is close to the entropy.

Temperature reshapes instead of truncating:

softmax(z/τ)i=exp⁡(zi/τ)∑jexp⁡(zj/τ).\mathrm{softmax}(z / \tau)_i = \frac{\exp(z_i / \tau)}{\sum_j \exp(z_j / \tau)}.

τ<1\tau < 1 makes the distribution more peaked, τ>1\tau > 1 flatter, and τ→0\tau \to 0 is greedy. In HuggingFace: do_sample=True, with top_k=20, top_p=0.9, temperature=….

Measured (demo 02 Part C): 1,000 samples per setting from the partly trained model, scored against the truth. “Quality” is the mean true log p of the valid samples; “coverage” is the true probability mass of the distinct valid sentences found.

samplervalidqualitydistinct of 1,000coverage
the true distribution (reference)100.0%−8.3279238.3%
ancestral (τ = 1)46.2%−7.3187427.8%
temperature 0.751.5%−7.4382426.8%
temperature 1.322.6%−7.3495616.1%
top-k 266.7%−8.543162.5%
top-k 1058.0%−7.2178531.3%
top-p 0.541.9%−8.134953.5%
top-p 0.960.2%−7.4279730.2%
min-p 0.0563.9%−7.3077032.7%
min-p 0.252.5%−7.3778023.8%
greedy (τ = 0)100.0%−10.5210.0%

How to read it:

  • Moderate truncation helps. Top-p 0.9 and min-p 0.05 raise validity from 46% to 60–64% and raise coverage, because fewer samples are wasted on impossible sentences.
  • Aggressive truncation collapses diversity. Top-k 2: 316 distinct sentences covering 2.5% of the mass. Greedy is the limit: one sentence, valid, with log p −10.52. That is demo 01’s long “for … class , which met on …” sentence, far less likely than a typical one.
  • Quality is not “higher is better”. The true distribution’s own samples score −8.32, minus the entropy. The model’s valid ancestral samples score higher (−7.31) only because it under-samples rare sentences (coverage 27.8% vs 38.3%). Read validity, diversity and coverage together.

4. Speeding up decoding

4.1 The KV cache

During decoding, the token at step tt attends to positions ≤t\le t, and needs the keys and values of all of them. Recomputing those keys and values at every step redoes O(T2)O(T^2) work over a generation:

  • step 1: k1,v1k_1, v_1
  • step 2: k1,v1,k2,v2k_1, v_1, k_2, v_2
  • step 3: k1,v1,k2,v2,k3,v3k_1, v_1, k_2, v_2, k_3, v_3
  • …

KV caching stores them instead. For one layer and one head at step tt:

  • compute qt=htWqq_t = h_t W_q, kt=htWKk_t = h_t W_K, vt=htWVv_t = h_t W_V (each 1×dk1 \times d_k);
  • append ktk_t to the cached K1:t−1K_{1:t-1} and vtv_t to V1:t−1V_{1:t-1};
  • attend: zt=softmax(qtK1:t⊤/dk) V1:tz_t = \mathrm{softmax}(q_t K_{1:t}^\top / \sqrt{d_k})\, V_{1:t}.

Without the cache, we recompute K1:t=[h1;… ;ht]WKK_{1:t} = [h_1; \dots; h_t] W_K and V1:tV_{1:t} every step. Because the causal mask hides the future, the earlier keys and values never change: caching is exactly equivalent to recomputing. The first pass over the prompt, which fills the cache for all prompt tokens at once, is called prefill.

Measured (demo 04 Part A, fast_decoding.forward_cached on a LLaMA-style model with d=128d = 128, 4 layers): greedy decoding with and without the cache produces identical tokens, with logits differing by at most 1.3×10−61.3 \times 10^{-6} (floating-point rounding). For 512 new tokens the cached loop was about 10× faster on this CPU (timing varies). Lecture 5 computed what the cache costs in memory at real sizes: 10.7 GB for a 70B-like model at 4,096 tokens, and 8× less with grouped-query attention.

4.2 Why is decoding slow?

An operation takes time for two reasons: moving data (weights, activations) and computing. A simple model:

time≈max⁡(FLOPsdevice FLOP/s, bytes movedmemory bandwidth).\text{time} \approx \max\left(\frac{\text{FLOPs}}{\text{device FLOP/s}},\ \frac{\text{bytes moved}}{\text{memory bandwidth}}\right).

The first term dominates for compute-bound operations, the second for memory-bound ones.

  • Matrix–matrix A=BCA = BC: O(mkn)O(mkn) FLOPs for O(mk+kn)O(mk + kn) bytes — lots of work per byte, compute-bound.
  • Matrix–vector a=Bxa = Bx: O(mk)O(mk) FLOPs for O(mk)O(mk) bytes — about one multiply-add per weight read, memory-bound.

Decoding one token is matrix–vector work: every weight is read once to process a single token.

Measured (demo 04 Part B, arithmetic for a 7B model in fp16 on an A100-like GPU with 312 TFLOP/s and 2.0 TB/s):

FLOPsbytes of weights readtime if compute-boundtime if memory-boundbound by
one token, batch 11.4×10101.4\times10^{10}1.4×10101.4\times10^{10}45 µs7.0 msmemory (156×)
one token each, batch 162.2×10112.2\times10^{11}1.4×10101.4\times10^{10}0.72 ms7.0 msmemory
one token each, batch 1602.2×10122.2\times10^{12}1.4×10101.4\times10^{10}7.18 ms7.0 mscompute

A single sequence uses less than 1% of the GPU’s arithmetic. Batching ~156 sequences shares each weight read among them. That is why serving systems batch aggressively (Lecture 23). The same effect is visible on a CPU: one 16 MB matrix times 512 vectors cost about 20× less per vector than times one vector (timing varies).

What does “speeding up” mean?

  • Latency: how long a user waits: time to first token, time per request.
  • Throughput: how much the system completes: tokens or requests per second.

Batching raises throughput; speculative decoding lowers latency.

A quick tour of strategies (slides):

goalstrategyexamples
reduce memory traffic (shrink the data to move)quantization, distillation, GQA / MQAGPTQ, AWQ (Lecture 19); Lecture 8; Lecture 5
increase FLOP/soptimize how operations run on the hardwareFlashAttention (Lecture 22), torch.compile, kernel fusion
reduce FLOPsarchitectural changesmixture of experts (Lecture 21), Mamba (Lecture 22)
parallelize over timedraft cheaply, verify in parallelspeculative decoding
parallelize over timegenerate several tokens at oncenon-autoregressive / diffusion models (Lecture 15)
many sequencesshare prefixes; batch better; optimize the programPagedAttention, RadixAttention (SGLang), continuous batching, DSPy (not in the slides; pointers in Lecture 23’s Further reading)

4.3 Speculative decoding

Some tokens are easier to predict than others: in “The cow jumped over the moon .”, most tokens are predictable. Speculative decoding (Leviathan et al., 2023; Chen et al., 2023) works like this:

  1. A small draft model qq generates γ\gamma tokens ahead, cheaply.
  2. The large target model pp scores all of them in one forward pass. That costs about the same as one decoding step, because decoding is memory-bound.
  3. Each drafted token is accepted with probability αi=min⁡(1,p(token∣… )q(token∣… ))\alpha_i = \min\left(1, \frac{p(\text{token} \mid \dots)}{q(\text{token} \mid \dots)}\right).
  4. At the first rejection, a replacement is drawn from the normalized residual max⁡(0,p−q)\max(0, p - q), and the remaining drafts are discarded. If every draft is accepted, one bonus token is drawn from pp.

This accept/resample rule makes the output distributed exactly as samples from pp (exercise 7). The draft affects only how many target passes are needed. With an acceptance rate α\alpha per checked token, each target pass yields on average (1−αγ+1)/(1−α)(1 - \alpha^{\gamma+1})/(1 - \alpha) tokens.

Measured (demo 04 Part C, Errand World; target 115k parameters, draft 7k, 16× smaller):

draftγ\gammaacceptancetokens per target calltheoryvalid sentences
trained draft178.7%1.751.7995.0%
trained draft277.0%2.192.3695.7%
trained draft477.0%2.733.1795.1%
trained draft877.3%3.113.9894.0%
untrained draft42.5%1.021.0395.3%
direct sampling from the target194.2%
  • The acceptance rate is constant in γ\gamma, as the theory assumes.
  • Tokens per call fall below the formula at larger γ\gamma because an Errand World sentence is only ~12 tokens long. Rounds near the end are cut short; at γ=1\gamma = 1, measured and theory agree (1.75 vs 1.79).
  • Correctness does not depend on the draft. An untrained draft is almost never accepted, giving no speed-up, yet the samples are just as valid (95.3%). The first-token distribution of 1,500 speculative samples is as close to the target’s exact distribution (total variation 0.032) as 1,500 direct samples (0.019), both within sampling noise.

5. Summary

  1. Two objectives: optimization (MAP, mode-seeking) and sampling. Greedy is beam search with B=1B = 1; neither guarantees the most likely output.
  2. On Errand World, greedy’s sentence was ~190× less likely than the true mode, and beams up to 8 made the same error: early-likely prefixes that branch widely crowd every beam. Greedy erred on 40% of prompts; beam 16 on none.
  3. MAP pitfalls:
    • Repetition traps: greedy repeats a diary sentence 5× while the true mode is one sentence.
    • Short outputs: exact MAP completions average 4.95 words vs 6.84 for samples. Length normalization helps; α=1\alpha = 1 overshoots.
    • Atypicality: all-heads, 6.5×10−236.5\times10^{-23}.
    • Probability spread across paraphrases: greedy 2% vs MBR-20 91% when the truth is said four ways.
  4. Ancestral sampling suffers from the heavy tail. (1−ϵ)T(1-\epsilon)^T predicted validity within a few tenths of a percent (47.3% vs 47.2%).
  5. Truncation (top-k, top-p, min-p) and temperature trade validity against diversity and coverage. Moderate settings (top-p 0.9, min-p 0.05) improved both validity and coverage; aggressive ones collapse diversity.
  6. Efficient inference:
    • The KV cache is exact and turns O(T2)O(T^2) recomputation into O(T)O(T).
    • Decoding is memory-bound (156× for a 7B model at batch 1), so batching raises throughput.
    • Speculative decoding gives ~2.7 tokens per target pass with an exact output distribution.

Common pitfalls

  • Assuming greedy or a small beam returns the most likely output. On Errand World it missed by a factor of ~190.
  • Treating the most likely output as the best. It can be short, repetitive, atypical, or the most likely string of a less likely meaning.
  • Sampling with no truncation from an imperfect model. At ϵ=0.01\epsilon = 0.01, long outputs are almost surely corrupted.
  • Truncating so hard that diversity collapses (top-k 2: 2.5% coverage), and then calling the higher log-probability “better quality”.
  • Comparing samplers by mean log-probability alone. The truth’s own samples are not the highest-scoring ones.
  • Implementing a KV cache with wrong positions. With RoPE, the new token must be rotated by its absolute position, not by 0.
  • Expecting speculative decoding to change outputs. It never changes the distribution; a bad draft only costs speed.
  • Reasoning about decoding speed in FLOPs. At batch 1 the bytes moved, not the arithmetic, set the time.

Exercises

  1. Greedy can be arbitrarily bad. Construct a two-step distribution in which greedy returns an output whose probability is less than half that of the mode.

    AnswerFirst token: A with 0.6, B with 0.4. After A: 6 tokens of 0.1 each, then end. After B: one token with 1.0, then end. Greedy picks A (0.6) then any of the six: probability 0.06. The mode is B then its token: 0.4 — 6.7× more likely. Errand World's "for …" prefix is this pattern at scale.
  2. Beam width. Why did beams of width 2, 4 and 8 all return the same −11.107 sentence in demo 01, and what had to be true for width 16 to find the mode?

    AnswerAfter two steps the eight "for " prefixes (0.05 each) beat every alternative ("she bought" 0.0315 …), so any beam of width ≤ 8 holds only "for …" prefixes and can never reach a T3 sentence. With 16 beams, "she bought" (and other T3/T2 prefixes) survive the second step; once the "for …" hypotheses split into clauses and days, their probabilities fall below the short T3 sentence, which finishes first with the highest score.
  3. Compounding error. A model puts 0.2% of its mass on bad tokens at each step. What fraction of 500-token answers contain no bad token? How small must ϵ\epsilon be for 90% of 2,000-token answers to be clean?

    Answer$0.998^{500} = e^{500 \ln 0.998} \approx e^{-1.0} \approx 0.37$. For $(1-\epsilon)^{2000} \ge 0.9$: $\epsilon \le 1 - 0.9^{1/2000} \approx 5.3\times10^{-5}$.
  4. Top-p by hand. Next-token probabilities are (0.5, 0.2, 0.15, 0.1, 0.05). Which tokens do top-p with p=0.6p = 0.6, top-k with k=2k = 2, and min-p 0.25 keep, and what are the renormalized probabilities?

    AnswerTop-p 0.6: the smallest prefix with mass ≥ 0.6 is (0.5, 0.2) → (5/7, 2/7). Top-k 2: the same. Min-p 0.25: threshold 0.25 × 0.5 = 0.125 → (0.5, 0.2, 0.15) → (0.588, 0.235, 0.176). (`decoders.py`'s self-test checks these three.)
  5. Temperature. Show that as τ→0\tau \to 0 temperature sampling becomes greedy, and as τ→∞\tau \to \infty it becomes uniform over the vocabulary.

    Answer$\mathrm{softmax}(z/\tau)_i = 1 / \sum_j \exp((z_j - z_i)/\tau)$. For the maximal $z_i$, every other term has $z_j - z_i < 0$, so it vanishes as $\tau \to 0$ and the probability → 1 (ties aside); for others some term → ∞ and the probability → 0. As $\tau \to \infty$ every exponent → 0, all terms → 1, and each probability → $1/\lvert\mathcal{V}\rvert$.
  6. MBR. Samples of answers are: “in lima” ×3, “lima” ×2, “she lives in lima” ×1, “in dakar” ×4. Which output do greedy-on-strings (most frequent string) and MBR with utility “same city” choose?

    AnswerMost frequent string: "in dakar" (4 of 10). MBR: the expected utility of any lima string is 6/10, of "in dakar" 4/10 — MBR chooses a lima answer (any of them; ties broken by order).
  7. Speculative sampling is exact. For one token with draft qq and target pp, show that the accept/resample rule outputs token xx with probability p(x)p(x).

    AnswerP(output $x$) = P(draft $x$ and accept) + P(reject) · P(resample $x$) $= q(x)\min(1, p(x)/q(x)) + \big(1 - \sum_y \min(q(y), p(y))\big) \frac{\max(0, p(x)-q(x))}{\sum_y \max(0, p(y) - q(y))}$. The first term is $\min(q(x), p(x))$. Since $\sum_y \min(p, q) = 1 - \sum_y \max(0, p - q)$, the second is $\max(0, p(x) - q(x))$. Sum: $\min(q, p) + \max(0, p - q) = p(x)$.
  8. KV-cache memory. A model has 32 layers, 8 K/V heads of size 128, fp16. How much cache does one sequence of 8,192 tokens need, and how many such sequences fit next to 16 GB of weights on an 80 GB GPU?

    AnswerPer token: $2 \times 32 \times 8 \times 128 \times 2$ B = 131,072 B = 128 KiB; × 8,192 tokens = 1 GiB per sequence. (80 − 16) GB ≈ 59.6 GiB → about 59 sequences (minus activations and fragmentation — what PagedAttention addresses).
  • Assignment 2 is released on 02/12 (two days after this lecture). Decoding choices — greedy vs sampling, temperature, top-p — and a KV cache are the standard building blocks of any generation pipeline it may involve. decoders.py and fast_decoding.py here are teaching implementations on toy models. These notes do not provide assignment code.

Further reading

  • S. Welleck et al., “From Decoding to Meta-Generation: Inference-time Algorithms for Large Language Models”, TMLR 2024 (course reading, §1–3).
  • A. Holtzman et al., “The Curious Case of Neural Text Degeneration”, ICLR 2020 (top-p); A. Fan, M. Lewis, Y. Dauphin, “Hierarchical Neural Story Generation”, ACL 2018 (top-k); J. Hewitt, C. Manning, P. Liang, “Truncation Sampling as Language Model Desmoothing”, Findings of EMNLP 2022; M. Nguyen et al., “Min-p sampling”, 2024.
  • F. Stahlberg, B. Byrne, “On NMT Search Errors and Model Errors: Cat Got Your Tongue?”, EMNLP 2019; C. Meister, R. Cotterell, T. Vieira, “If Beam Search is the Answer, What was the Question?”, EMNLP 2020; C. Meister et al., “Locally Typical Sampling”, TACL 2023.
  • S. Kumar, W. Byrne, “Minimum Bayes-Risk Decoding for Statistical Machine Translation”, NAACL 2004; B. Eikema, W. Aziz, “Is MAP Decoding All You Need?”, COLING 2020.
  • Y. Leviathan, M. Kalman, Y. Matias, “Fast Inference from Transformers via Speculative Decoding”, ICML 2023; C. Chen et al., “Accelerating Large Language Model Decoding with Speculative Sampling”, 2023.
  • R. Pope et al., “Efficiently Scaling Transformer Inference”, MLSys 2023.

Preview of Lecture 10 — Retrieval and RAG

Every model so far could only use what was stored in its parameters, and Lecture 7 showed that this storage follows a long tail: popular facts are learned, rare ones are not. Lecture 10, a guest lecture by Akari Asai, gives the model a library. Its parts:

  • Datastores: what to store and how to chunk it.
  • Retrievers: TF-IDF and BM25; dense dual encoders trained contrastively; approximate nearest-neighbor search; rerankers.
  • Using retrieval: retrieval-augmented generation, RETRO, kNN-LM.
  • When retrieval helps and hurts: the long tail, unhelpful documents, and adaptive retrieval as in Self-RAG.

术语表 (Glossary, English → 中文)

English中文
decoding / inference解码 / 推理
decoding objective解码目标
mode-seeking / maximum a posteriori (MAP)求众数 / 最大后验
greedy decoding贪心解码
beam search / beam width束搜索 / 束宽
search error / model error搜索误差 / 模型误差
degeneracy / repetition trap退化 / 重复陷阱
length normalization长度归一化
atypical / typical set非典型 / 典型集
probability spread / paraphrase概率分散 / 同义表述
minimum Bayes risk (MBR) / expected utility最小贝叶斯风险 / 期望效用
self-consistency / majority vote自洽性 / 多数投票
ancestral sampling祖先采样
categorical distribution类别分布
heavy tail / compounding error重尾 / 误差累积
truncation sampling: top-k / top-p (nucleus) / min-p截断采样:top-k / top-p(核采样)/ min-p
temperature温度
validity / diversity / coverage有效性 / 多样性 / 覆盖率
KV cache / prefill键值缓存 / 预填充
memory-bound / compute-bound访存受限 / 计算受限
memory bandwidth / arithmetic intensity内存带宽 / 算术强度
latency / throughput延迟 / 吞吐量
batching / continuous batching批处理 / 连续批处理
speculative decoding / draft model / target model投机解码 / 草稿模型 / 目标模型
acceptance rate / residual distribution接受率 / 残差分布
← 返回课程目录