Exact global maximization is intractable: Over our 1,027-token BPE vocabulary and a 50-token horizon, 1027^{50} > 10^{150} continuations exist—no decoder can enumerate the search tree.
The maximization vs. sampling dilemma: Greedy argmax rapidly traps the generator in deterministic repetition loops, whereas unpruned sampling draws low-probability tail tokens that derail the rollout.
Two Families of Decoders: Maximization vs. Sampling
Task-Driven Decoder Selection
Whether we should search for a high-probability sequence or sample stochastically depends fundamentally on the entropy of the target task:
Maximization Decoders (Greedy & Beam Search): Approximate \operatorname*{argmax}_{x_{1:T}} P(x_{1:T}). Best for constrained, low-entropy tasks (speech recognition, machine translation, OCR) where the input admits only a narrow band of correct outputs.
Truncated Sampling Decoders (Temperature, Top-k, Top-p, Min-p): Reshape or prune the unreliable low-probability tail of P(x_t \mid x_{<t}) and draw stochastically. Standard for open-ended generation (dialogue, creative writing) where a well-calibrated model spreads mass across many valid continuations.
A Model-Agnostic Next-Token Logit Interface
Unified Decoder Boundary
Every decoding algorithm in this section interacts with our trained RNN language model (RNNLM,d = 512, h = 128, validation perplexity \approx 60) solely through a black-box function step_fn(ids) -> logits returning a 1D NumPy vector of length |\mathcal{V}| = 1{,}027:
model.eval() # Dropout offdef seq_logits(ids): # Token ids in, NumPy logits at every position outwith torch.inference_mode(): logits = model(d2l.tensor([ids], device=d2l.try_gpu()))return d2l.numpy(logits)[0]def step_fn(ids): # Token ids in, NumPy logits for the next token outreturn seq_logits(ids)[-1]
Architecture and framework invariance: Because step_fn takes a list of integer token IDs and returns next-token logits as a NumPy array, the exact same decoder code drives an RNN, a state space model, or a Transformer in any framework.
One model call per token: Deterministic and fast, committing irreversibly to the top token at each step.
Why local argmax is myopic: Committing to A at step 1 (0.50 > 0.40) leads to a diffuse step 2 (0.50 \times 0.30 = 0.15), pruning branch B whose confident continuation yields 0.40 \times 0.90 = 0.36(2.4\times higher).
Neural Text Degeneration: Deterministic Limit Cycles
Why Greedy Rollouts Loop
Running greedy decoding for 50 tokens after 'The Time Traveller' and 'It seemed to me that' exposes its second, even more severe failure mode—repetitive looping:
"The Time Traveller.\n\n'I had\nfrom the\nsidea.\n\n'I had\nfrom
the\nsidea.\n\n'I had\nfrom the\nsidea.\n\n'I had\nf"
"It seemed to me that\ntheir.\n\n'I had\nfrom the\nsidea.\n\n'I had\nfrom
the\nsidea.\n\n'I had\nfrom the\nsidea.\n\n'I"
Deterministic state-space attractors: In an autoregressive RNN under greedy decoding, both \mathbf{H}_t = g(\mathbf{H}_{t-1}, x_t) and x_t = \operatorname*{argmax} \mathbf{O}_{t-1} are deterministic mappings. Once the trajectory lands near a hidden state it visited a few tokens earlier, it is mathematically locked into a periodic limit cycle forever.
Not just a small-RNN artifact: Holtzman et al. (2020) proved that the exact same neural text degeneration afflicts 1.5B-parameter GPT-2 Transformers whenever open-ended text is decoded by likelihood maximization.
Beam Search: Retaining the Top-w Partial Hypotheses
Maximization Family II: Beam Search
Beam search mitigates greedy myopia by maintaining a beam of the w highest-scoring partial prefixes at every step (where beam widthw = 1 recovers greedy search and w \to \infty approaches exhaustive search):
Expand-and-prune loop (width w = 2, |\mathcal{V}| = 5):
Step 1: Keep the w = 2 most probable first tokens (A and C).
Step 2: Expand each active beam across all |\mathcal{V}| tokens (w|\mathcal{V}| = 10 candidates), score by cumulative log-probability \log P(x_1) + \log P(x_2 \mid x_1), and prune back to the top w = 2(AB and CE).
Step T: Total evaluations scale linearly as O(w|\mathcal{V}|T)(5 + 10 + 10 = 25 instead of |\mathcal{V}|^3 = 125).
Why raw log-likelihood (\beta = 0) biases short: Every term \log P \le 0 is non-positive, so adding tokens monotonically lowers cumulative log-probability and favors premature <eos>.
Interpolating exponent \beta \in [0, 1] (Wu et al., 2016):\beta \approx 0.75 balances cumulative likelihood against per-token average (\beta = 1).
Implementing Length-Normalized Beam Search
From-Scratch Implementation & Evaluation
At most w extensions per beam can survive, so each beam keeps only its top w tokens:
def beam_search(step_fn, prefix, num_tokens, beam_size=4, alpha=0.75, eos_id=None):"""Length-normalized beam search (score = log P / len^alpha). Returns candidates sorted best-first; [0][1] is the argmax sequence."""def log_softmax(logits): logits = [float(l) for l in logits] m =max(logits) lse = m + math.log(sum(math.exp(l - m) for l in logits))return [l - lse for l in logits] score =lambda logp, ids: logp /max(1, len(ids) -len(prefix))**alpha beams = [(0.0, list(prefix), False)] # (log-prob, sequence, finished)for _ inrange(num_tokens):ifall(done for _, _, done in beams):break candidates = [b for b in beams if b[2]] # Finished pass throughfor logp, ids, _ in (b for b in beams ifnot b[2]): logprobs = log_softmax(step_fn(ids)) best =sorted(range(len(logprobs)), key=lambda i: -logprobs[i])[:beam_size] candidates += [(logp + logprobs[i], ids + [i], i == eos_id)for i in best] beams =sorted(candidates, key=lambda b: score(b[0], b[1]), reverse=True)[:beam_size]returnsorted([(score(logp, ids), ids) for logp, ids, _ in beams], reverse=True)
w=1, score -4.13: "The Time Traveller.\n\n'I had\nfrom the\nsidea.\n\n'I
had\nfrom the\nsidea.\n"
w=4, score -3.43: "The Time Traveller.\n\n'Then I had\ndeliculture.\n\n'Then
I had\ndeliculture.\n"
w=1, score -4.21: "It seemed to me that\ntheir.\n\n'I had\nfrom
the\nsidea.\n\n'I had\nfrom the\nside"
w=4, score -3.60: "It seemed to me that it was a\npossibly.\n\n'As I saw
a\npossibly.\n\n'As"
Higher model likelihood, persistent repetition: Widening the beam from w = 1 \to 4 finds continuations with higher log-probability scores (less negative length-normalized scores), yet open-ended prose still collapses into repetitive clauses.
Ancestral Sampling and the Unreliable Tail Problem
Sampling Family: Motivation
x_t \sim P(x_t \mid x_{<t})
Why pure sampling derails (Holtzman et al., 2020): Softmax assigns positive probability to all |\mathcal{V}| = 1{,}027 tokens. After 'The Time Traveller', the 140–174 most probable tokens hold 90\% of the mass; the other \sim 850–890 implausible tail tokens share up to 10\% at every step.
50-step compounding failure: At a tail-draw rate of 10\% per step, only (1 - 0.1)^{50} \approx 0.005 of 50-token rollouts avoid drawing a tail token that derails subsequent context.
Temperature Scaling: Reshaping Softmax Entropy
Sampling Control I: Temperature
Temperature scaling divides the logit vector \mathbf{o} \in \mathbb{R}^{|\mathcal{V}|} by \tau > 0 before applying the softmax:
tau=0.5: "The Time Traveller pale of the\ndelight of\nthe lamp and\npresent
bushes.\n\n'I had\npresently\nmetinessed\nof a time. I felt\nwhich\n"
tau=1.0: "The Time Traveller.'\n\n'From the powersing solack, and silent it
would by vanished! I came gave me to me.\n\n'I took with me up of
them?ly dancing ru"
tau=2.0: 'The Time Traveller went co tsprockated d�ir can� stoelt-lice slow
against\nich�ined to hished theirsentantworld in dararact disItvesj�
perllow\nWild5ise?3 seemed'
Three regimes:\tau \to 0^+ converges to deterministic greedy argmax; \tau = 1 recovers unaltered ancestral sampling; \tau > 1 flattens the distribution toward uniform (at \tau = 2.0, tail bytes break English and even valid UTF-8).
Why temperature alone is a blunt instrument: Lowering \tau (e.g., \tau = 0.5) suppresses the unreliable tail only by simultaneously crushing diversity among the top 3–5 plausible head tokens.
Three Tail-Truncation Rules: Top-k, Top-p, and Min-p
Sampling Control II: Tail Truncation
Rather than distorting the head of the distribution, truncated samplers sort tokens in descending order P(x_{(1)}) \ge P(x_{(2)}) \ge \cdots \ge P(x_{(|\mathcal{V}|)}), zero out everything beyond a cutoff rank K, renormalize the surviving head, and sample:
Truncation Rule
Surviving Support Set \mathcal{S}
Toy Distribution (0.45, 0.25, 0.15, 0.10, 0.05)
Adaptation to Model Entropy
Top-k (Fan et al., 2018)
Fixed rank count: \{x_{(1)}, \ldots, x_{(k)}\}
k = 2 \implies \{0, 1\} (mass 0.70)
None (rigid): Keeps k tokens whether entropy is near 0 or high
Top-p / Nucleus (Holtzman et al., 2020)
Smallest head with \sum_{i=1}^K P(x_{(i)}) \ge p
p = 0.80 \implies \{0, 1, 2\} (cum. mass 0.85 \ge 0.80)
Cumulative mass: Shrinks when peaked, widens when flat
Each rule reduces to choosing how many sorted head tokens keep survive renormalization:
def sample_next(logits, temperature=1.0, k=None, p=None, min_p=None, rng=None):"""Draw a token id from 1-D NumPy logits; temperature 0 is greedy. Top-k, top-p, and min-p truncate the temperature-scaled distribution.""" logits = np.asarray(logits, dtype=np.float64)if temperature ==0:returnint(logits.argmax()) probs = np.exp((logits - logits.max()) / temperature) order = np.argsort(-probs) # token ids, most probable first probs = probs[order] / probs.sum() keep =len(probs)if k isnotNone: # top-k: a fixed count keep =min(keep, k)if p isnotNone: # top-p: smallest head of mass p keep =min(keep, int(np.searchsorted(probs.cumsum(), p)) +1)if min_p isnotNone: # min-p: a fraction of the top keep =min(keep, int((probs >= min_p * probs[0]).sum())) rng = np.random.default_rng() if rng isNoneelse rngreturnint(order[rng.choice(keep, p=probs[:keep] / probs[:keep].sum())])
A Unified Composable Sampler in Fifteen Lines (cont.)
From-Scratch Implementation
def generate(step_fn, prefix, num_tokens, eos_id=None, **strategy):"""Extend prefix by up to num_tokens ids, each chosen by sample_next from step_fn(ids), the next-token logits; stop early at eos_id.""" ids =list(prefix)for _ inrange(num_tokens): ids.append(sample_next(step_fn(ids), **strategy))if eos_id isnotNoneand ids[-1] == eos_id:breakreturn ids
Geometric View of Cutoffs on a Trained Model
Visualizing Truncation on Log–Log Axes
Plotting our trained RNN’s sorted next-token probabilities after 'The Time Traveller' on log–log axes gives each truncation rule a clear geometric meaning:
Head vs. tail structure: Probabilities decay gently across ranks 1\text{--}50(0.15 \to 10^{-3}) before plunging into a 900-token noise tail.
Vertical vs. horizontal cutoffs:
Top-k(k = 20, orange): Fixed vertical wall at rank 20.
Top-p(p = 0.9, green): Vertical wall placed dynamically where cumulative area reaches 90\%.
Min-p(p_{\min} = 0.05, red): Horizontal floor at 5\% of the rank-1 peak (0.05\,P(x_{(1)})); everything below the bar is pruned.
How Adaptive Cutoffs Respond to Model Confidence
Peaked vs. Uncertain Contexts
Comparing the uncertain prefix 'The Time Traveller' against the highly predictable prefix 'The Time' (which is followed by ' Traveller' in 11 of 13 occurrences in the novella) highlights how the three cutoffs behave across entropy regimes:
'The Time Traveller': top probability 0.10; kept: top-k 20, top-p 140, min-p 31
'The Time': top probability 0.69; kept: top-k 20, top-p 6, min-p 2
When the model is confident ('The Time', high P_{\max}): Top-k = 20 foolishly admits 19 unlikely tokens, whereas both top-p and min-p contract sharply to just a few candidates.
When the model is uncertain ('The Time Traveller', flat head): To accumulate 90\% of the probability mass, top-p = 0.9 must keep roughly 140–175 tokens, reaching deep into the tail, whereas min-p = 0.05 keeps only tokens within 20\times of the leader (between about 10 and 30 plausible choices).
Head-to-Head Generation Across Decoding Strategies
Qualitative Rollout Comparison
Generating 50-token continuations from 'The Time Traveller' under greedy decoding, pure sampling (\tau = 1), and our three truncated samplers demonstrates the qualitative improvement immediately:
greedy: "The Time Traveller.\n\n'I had\nfrom the\nsidea.\n\n'I had\nfrom
the\nsidea.\n\n'I had\nfrom the\nsidea.\n\n'I had\nf"
tau=1: 'The Time Traveller, and sgat; so like a sttyj dayshindting,
posserent and buth on that Gecting it leve against\nbut7 Sa crying\ndark
weight at first'
top-k=20: "The Time Traveller looked round in these gone. His animals
had\nsoon.\n\n'I wood to see some\nthe Psychologist in\nmank, and I
directive, and my hand. I was in"
top-p=0.9: 'The Time Traveller rarements. Then I thought "As of trift his
ownisterse of the Palace of Gallen Proburned this white.\n\n\'Chen my an
exton.\n'
min-p=0.05: "The Time Traveller came to pates of\nbit\nmels. Then\n'Then.
As\nbefore a bigroud of these chambuge steading\ninsmination. I"
Breaking the cycle without tail gibberish: Greedy decoding locks into a deterministic loop, pure \tau = 1 sampling occasionally stumbles into implausible subword splices, and top-k=20, top-p=0.9, and min-p=0.05 all generate diverse, non-looping continuations.
Quantifying Likelihood vs. Diversity (Distinct-3)
Systematic Benchmark Across 20 Prompts
To quantify the trade-off between model likelihood (mean log-probability per generated token) and lexical diversity, we measure \textrm{distinct-}3 (the ratio of unique 3-grams to total 3-grams, where 1.00 means zero repetition) across 20 random 100-token rollouts:
greedy: log-prob per token -1.89, distinct-3 0.15
beam, w=4: log-prob per token -1.46, distinct-3 0.19
tau=1: log-prob per token -3.93, distinct-3 0.99
top-k=20: log-prob per token -2.83, distinct-3 0.99
top-p=0.9: log-prob per token -3.38, distinct-3 0.99
min-p=0.05: log-prob per token -2.78, distinct-3 0.98
The maximization collapse: Greedy and beam search (w = 4) achieve the highest per-token log-probability (\approx -1.4 to -1.6 nats), yet their distinct-3 scores collapse (\approx 0.15\text{--}0.30) because over 70\% of their output consists of repeated 3-grams.
The truncated sampling sweet spot: Pure sampling (\tau = 1) reaches distinct-3\approx 0.99 but suffers low likelihood (\approx -4.0 nats); top-k=20 and min-p=0.05 preserve nearly identical diversity (distinct-3\approx 0.97\text{--}0.99) while boosting per-token log-probability by a full nat (\approx -2.9 nats).
Why Perplexity Evaluates Models, Not Decoders
Separating Model Quality from Decoder Choice
A common pitfall in language modeling is attempting to use perplexity (or model log-likelihood of generated text) to rank decoding algorithms:
Perplexity scores the model on human text:\textrm{PPL} = \exp(-\frac{1}{T}\sum_t \log P(x_t \mid x_{<t})) evaluates how much probability mass the model’s distributions assign to held-out ground-truth passages—before any decoder is invoked.
Why model likelihood of generated text is tautological: Scoring generated outputs by \frac{1}{T}\sum_t \log P(\hat{x}_t \mid \hat{x}_{<t}) will always crown greedy or beam search the “winner,” even when the resulting text is a degenerate loop ("and the time traveller and the time traveller...").
Proper decoder evaluation: Use surface diagnostics (distinct-n, repetition rate) to catch degeneration, reference metrics (BLEU, COMET, WER) on constrained tasks, and blind human preference (or calibrated judge evaluations) on open-ended generation.
Inference Complexity: Stateless O(T²) vs. Cached O(T)
Systems Cost of Autoregressive Generation
Stateless prefix re-evaluation (step_fn(ids)): Re-running the network over x_{1:t} at step t performs \sum_{t=1}^T t = O(T^2) cell updates.
Stateful recurrent carry (predict): Passing \mathbf{H}_{t-1} \in \mathbb{R}^h forward costs 1 cell update per token(O(T) total) and a fixed 512-byte state at any sequence length.
Next horizon (Chapters 10–12): Upgrade \mathbf{H}_t with gates/SSMs so gradients survive in O(1) space (§12), or retain all past token K/V vectors via self-attention at O(T) memory cost (§10–11).
Concept Check: Beam Search, Cutoffs & Complexity
Check Your Understanding
Test your mastery of decoding algorithms and their computational properties:
Beam Search Function Evaluations: With vocabulary size |\mathcal{V}| = 1{,}027, generation length T = 50, and beam width w = 4 (assuming no early <eos>), how many times does beam_search call step_fn across the 50 steps, compared to exhaustive search over all |\mathcal{V}|^T sequences?
Top-p vs. Min-p on a Peaked Distribution: Suppose at step t, the top token has probability P(x_{(1)}) = 0.95, the runner-up has P(x_{(2)}) = 0.04, and the remaining 1,025 tokens share 0.01. Which exact token(s) survive under (a) top-p with p = 0.90 versus (b) min-p with p_{\min} = 0.05?
Temperature Invariance of Cutoffs:sample_next applies top-k, top-p, and min-pafter temperature scaling P_\tau(x) \propto P(x)^{1/\tau}. Which of the three rules keeps the exact same support set of tokens at every temperature \tau > 0?
beam_search makes 1 + 49 \times 4 = 197 calls to step_fn (1 call on the initial prompt at step 1, then w = 4 calls per step for steps 2, \ldots, 50, scoring 1027 + 49 \times 4 \times 1027 = 202{,}319 candidate extensions), versus > 10^{150} sequences in exhaustive search.
(a) Top-p(p = 0.90) keeps only 1 token (x_{(1)}) because 0.95 \ge 0.90 already exceeds the threshold, acting purely greedily and excluding the 4\% runner-up. (b) Min-p(p_{\min} = 0.05) keeps 1 token (x_{(1)}) since the cutoff is 0.05 \times 0.95 = 0.0475 > 0.04 (or keeps x_{(2)} as well whenever P(x_{(2)}) \ge 0.0475).
Top-k is invariant to \tau > 0: Because p \mapsto p^{1/\tau} is strictly increasing for all \tau > 0, it preserves the rank ordering of all tokens, so the top k tokens never change (whereas top-p and min-p change their support size as \tau flattens or sharpens the distribution).
Summary: Decoding Strategies Compared
Section Takeaways
Strategy
Selection / Truncation Rule
Key Hyperparameter
Adaptivity to Distribution Shape
Per-Step Model Calls
Primary Use Case & Failure Mode
Greedy Decoding
x_t = \operatorname*{argmax}_{x} P(x \mid x_{<t})
None (\tau = 0)
Deterministic single peak
1
Fast baseline; myopic and locks into deterministic repetition loops
Beam Search
Keep top-w prefixes by \frac{1}{T^\beta}\sum \log P
Width w, length exp. \beta \approx 0.75
Tracks w paths in parallel
w
Standard for constrained tasks (MT, ASR); still loops on open-ended text
Temperature Sampling
Sample P_\tau(x) \propto \exp(o_x / \tau)
Temperature \tau > 0
Uniformly sharpens (\tau < 1) or flattens (\tau > 1)
1
Reshapes entropy globally; cooling tail also kills head diversity
Summary: Decoding Strategies Compared (cont.)
Section Takeaways
Strategy
Selection / Truncation Rule
Key Hyperparameter
Adaptivity to Distribution Shape
Per-Step Model Calls
Primary Use Case & Failure Mode
Top-k Sampling
Sample from top k ranks of P_\tau
Count k \in \{1, \ldots, \lvert\mathcal{V}\rvert\}
Fixed size k regardless of model confidence
1
Cuts tail beyond rank k; admits k-1 bad tokens when distribution is peaked
Top-p (Nucleus)
Smallest head with \sum_{i=1}^K P_\tau(x_{(i)}) \ge p
Cumulative mass p \in (0, 1) (e.g. 0.9)
Mass-adaptive (shrinks when peaked, widens when flat)
1
Adapts to entropy; can reach hundreds of tokens into a flat tail at high \tau