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 code09_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 fromcode/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:
- State the two decoding objectives — optimization (find the mode) and sampling (draw from the distribution) — and when each is used.
- Run greedy decoding and beam search, and explain why neither guarantees the most likely output (search errors).
- Explain the pitfalls of MAP decoding: repetition traps, short outputs, atypicality, and probability spread over paraphrases — and their remedies (length normalization, sampling, MBR).
- Explain why ancestral sampling degrades (the heavy tail, compounding error ), and what temperature, top-k, top-p and min-p change.
- 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
| Section | Idea | Demo in code/lecture09/ |
|---|---|---|
| §2.2–2.4 | greedy vs beam vs exact MAP; search errors | 01_map_decoding.py Parts A–B (+ decoders.py) |
| §2.5 | MAP pitfalls: atypical and short outputs, length normalization, repetition traps | 01_map_decoding.py Parts C–D |
| §2.6 | probability spread across paraphrases; minimum Bayes risk | 03_mbr.py |
| §3 | ancestral sampling, the heavy tail, temperature / top-k / top-p / min-p | 02_sampling.py |
| §4 | KV cache; memory-bound decoding; speculative decoding | 04_fast_decoding.py (+ fast_decoding.py) |
0.4 Notation
| Symbol | Meaning |
|---|---|
| the input (prompt); the output | |
| the autoregressive model | |
| , | vocabulary; the set of all outputs |
| beam width; for top-k, for top-p, the temperature | |
| probability mass a model puts on “bad” next tokens | |
| , | draft 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
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
This is called mode-seeking (it finds a mode of the distribution), or maximum a posteriori (MAP) decoding: given evidence , find the mode of the posterior . The key challenge is that is huge, sequences, so we cannot enumerate it.
2.3 Greedy decoding and beam search
Greedy decoding chooses the most likely token at each step:
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 most likely partial outputs, expands each by its best next tokens, and keeps the best again:
- is greedy.
- would be exact MAP; for GPT-2’s vocabulary and 128 tokens that is .
- In practice 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:
| decoder | output | log 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, 8 | for painting class , which met on monday and on tuesday and on … , she wanted to buy her own brush . | −11.107 |
| beam 16 … 128 | she 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 (). 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):
| decoder | search errors | mean log p gap | worst gap |
|---|---|---|---|
| greedy | 40.0% | 1.565 | 3.912 |
| beam 2 | 40.0% | 1.565 | 3.912 |
| beam 4 | 40.0% | 1.565 | 3.912 |
| beam 16 | 0.0% | 0.000 | 0.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 .
Measured (Part C, exact search over completions of 100 prompts, by enumeration):
| completions | mean length (words) |
|---|---|
| exact MAP | 4.95 |
| exact MAP, length-normalized, | 5.27 |
| exact MAP, length-normalized, | 10.24 |
| greedy (search errors included) | 9.63 |
| samples (20 per prompt) | 6.84 |
The exact mode is shorter than a typical completion. Full normalization () 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:
| outcome | log p of one such sequence | P(number of heads = k) |
|---|---|---|
| all heads (the mode) | −51.1 | |
| exactly 60 heads | −67.3 | 0.081 |
| 50–70 heads | 0.968 |
The single all-heads sequence is times more likely than any particular 60-heads sequence. But there are 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,
estimated with samples. With = “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:
| decoder | spread people | concentrated people |
|---|---|---|
| greedy | 2.0% | 100.0% |
| beam 4 | 4.0% | 100.0% |
| one sample | 55.0% | 57.0% |
| MBR, 5 samples (utility: same city) | 76.0% | 75.0% |
| MBR, 20 samples | 91.0% | 93.0% |
MBR’s price: 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:
This is equivalent to drawing a whole sequence (Lecture 3). Each step is a draw from a categorical distribution over items: draw 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 , a length- output contains no bad token with probability :
- , : 0.276
- , : 0.0014
- , : 0.000034
Measured (demo 02 Part A). Because Errand World’s truth is known, is measurable: the model’s probability on next tokens that are impossible given the prefix.
| model | (mass on impossible next tokens) | tokens per sentence | predicted valid | measured valid |
|---|---|---|---|---|
| well-trained (4,000 sentences, 12 epochs) | 0.0040 | 11.2 | 95.7% | 96.0% |
| partly trained (2,000 sentences, 4 epochs) | 0.0661 | 10.9 | 47.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 most probable tokens, renormalize: if top-, else 0.
- Top-p (nucleus) (Holtzman et al., 2020): keep the smallest set of most probable tokens whose total mass is at least . 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:
makes the distribution more peaked, flatter, and 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.
| sampler | valid | quality | distinct of 1,000 | coverage |
|---|---|---|---|---|
| the true distribution (reference) | 100.0% | −8.32 | 792 | 38.3% |
| ancestral (τ = 1) | 46.2% | −7.31 | 874 | 27.8% |
| temperature 0.7 | 51.5% | −7.43 | 824 | 26.8% |
| temperature 1.3 | 22.6% | −7.34 | 956 | 16.1% |
| top-k 2 | 66.7% | −8.54 | 316 | 2.5% |
| top-k 10 | 58.0% | −7.21 | 785 | 31.3% |
| top-p 0.5 | 41.9% | −8.13 | 495 | 3.5% |
| top-p 0.9 | 60.2% | −7.42 | 797 | 30.2% |
| min-p 0.05 | 63.9% | −7.30 | 770 | 32.7% |
| min-p 0.2 | 52.5% | −7.37 | 780 | 23.8% |
| greedy (τ = 0) | 100.0% | −10.52 | 1 | 0.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 attends to positions , and needs the keys and values of all of them. Recomputing those keys and values at every step redoes work over a generation:
- step 1:
- step 2:
- step 3:
- …
KV caching stores them instead. For one layer and one head at step :
- compute , , (each );
- append to the cached and to ;
- attend: .
Without the cache, we recompute and 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 , 4 layers): greedy decoding with and without the cache produces identical tokens, with logits differing by at most (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:
The first term dominates for compute-bound operations, the second for memory-bound ones.
- Matrix–matrix : FLOPs for bytes — lots of work per byte, compute-bound.
- Matrix–vector : FLOPs for 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):
| FLOPs | bytes of weights read | time if compute-bound | time if memory-bound | bound by | |
|---|---|---|---|---|---|
| one token, batch 1 | 45 µs | 7.0 ms | memory (156×) | ||
| one token each, batch 16 | 0.72 ms | 7.0 ms | memory | ||
| one token each, batch 160 | 7.18 ms | 7.0 ms | compute |
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):
| goal | strategy | examples |
|---|---|---|
| reduce memory traffic (shrink the data to move) | quantization, distillation, GQA / MQA | GPTQ, AWQ (Lecture 19); Lecture 8; Lecture 5 |
| increase FLOP/s | optimize how operations run on the hardware | FlashAttention (Lecture 22), torch.compile, kernel fusion |
| reduce FLOPs | architectural changes | mixture of experts (Lecture 21), Mamba (Lecture 22) |
| parallelize over time | draft cheaply, verify in parallel | speculative decoding |
| parallelize over time | generate several tokens at once | non-autoregressive / diffusion models (Lecture 15) |
| many sequences | share prefixes; batch better; optimize the program | PagedAttention, 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:
- A small draft model generates tokens ahead, cheaply.
- The large target model scores all of them in one forward pass. That costs about the same as one decoding step, because decoding is memory-bound.
- Each drafted token is accepted with probability .
- At the first rejection, a replacement is drawn from the normalized residual , and the remaining drafts are discarded. If every draft is accepted, one bonus token is drawn from .
This accept/resample rule makes the output distributed exactly as samples from (exercise 7). The draft affects only how many target passes are needed. With an acceptance rate per checked token, each target pass yields on average tokens.
Measured (demo 04 Part C, Errand World; target 115k parameters, draft 7k, 16× smaller):
| draft | acceptance | tokens per target call | theory | valid sentences | |
|---|---|---|---|---|---|
| trained draft | 1 | 78.7% | 1.75 | 1.79 | 95.0% |
| trained draft | 2 | 77.0% | 2.19 | 2.36 | 95.7% |
| trained draft | 4 | 77.0% | 2.73 | 3.17 | 95.1% |
| trained draft | 8 | 77.3% | 3.11 | 3.98 | 94.0% |
| untrained draft | 4 | 2.5% | 1.02 | 1.03 | 95.3% |
| direct sampling from the target | 1 | 94.2% |
- The acceptance rate is constant in , as the theory assumes.
- Tokens per call fall below the formula at larger because an Errand World sentence is only ~12 tokens long. Rounds near the end are cut short; at , 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
- Two objectives: optimization (MAP, mode-seeking) and sampling. Greedy is beam search with ; neither guarantees the most likely output.
- 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.
- 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; overshoots.
- Atypicality: all-heads, .
- Probability spread across paraphrases: greedy 2% vs MBR-20 91% when the truth is said four ways.
- Ancestral sampling suffers from the heavy tail. predicted validity within a few tenths of a percent (47.3% vs 47.2%).
- 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.
- Efficient inference:
- The KV cache is exact and turns recomputation into .
- 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 , 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
-
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.
Answer
First 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. -
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?
Answer
After 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. -
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 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}$. -
Top-p by hand. Next-token probabilities are (0.5, 0.2, 0.15, 0.1, 0.05). Which tokens do top-p with , top-k with , and min-p 0.25 keep, and what are the renormalized probabilities?
Answer
Top-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.) -
Temperature. Show that as temperature sampling becomes greedy, and as 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$. -
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?
Answer
Most 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). -
Speculative sampling is exact. For one token with draft and target , show that the accept/resample rule outputs token with probability .
Answer
P(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)$. -
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?
Answer
Per 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).
Related assignment (concepts only)
- 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.pyandfast_decoding.pyhere 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 | 接受率 / 残差分布 |