Decoding: greedy, beam, temperature, top-k, top-p¶
A language model does not produce text; it produces a probability distribution over the next token. Decoding is the algorithm that turns that distribution into text, one token at a time, and the same model can be dull, brilliant or broken depending on it. This page derives each method, shows exactly what it does to one distribution, and explains why the most probable text is usually not the text you want.
10,000 ft
Training gives a model of \(p(x_t\mid x_{<t})\) (the language-modelling objective). Everything a user sees comes through a decoder that chooses from it. Decoding is where you trade reliability against variety (extraction wants determinism, brainstorming wants diversity), where you enforce formats (structured outputs), where reasoning models spend extra compute by sampling many answers (test-time compute), and where serving systems win speed without changing the output distribution (speculative decoding). It costs nothing to change and is the first thing to check when generations look wrong.
2,000 ft
Generation is a loop: run the model on the text so far, get logits for the next token, transform them, choose a token, append it, repeat until an end token or a length limit. The methods differ only in the transform and the choice. Search methods (greedy, beam) try to find high-probability text. Sampling methods draw from the distribution after reshaping it: temperature sharpens or flattens it; top-k, top-p and min-p cut off the unreliable tail.
- Greedy: always take the arg max. Deterministic, prone to loops.
- Beam search: keep the \(b\) best partial sequences. Good for short, tightly constrained outputs.
- Temperature \(T\): divide logits by \(T\); \(T<1\) sharpens, \(T>1\) flattens.
- Top-k / top-p / min-p: keep only the \(k\) most likely tokens, the smallest set with mass \(p\), or tokens within a factor of the best; renormalise; sample.
Ground level¶
The loop, and what it costs¶
Generation is autoregressive: token \(t+1\) cannot be chosen until token \(t\) exists. Processing the prompt (the prefill) is one parallel forward pass; each generated token (the decode steps) needs another forward pass over one new position, reusing cached keys and values for the rest (KV cache). The decoding algorithm adds almost nothing to that cost: sorting \(V\) logits is trivial next to a forward pass. Beam search is the exception, since it runs \(b\) sequences in parallel.
At every step the model gives logits \(\mathbf{z}\in\mathbb{R}^V\) and \(p_i = \operatorname{softmax}(\mathbf{z})_i\). Throughout this page we use one concrete distribution, the model's next-token beliefs after "The cat sat on the":
| token | mat | floor | sofa | bed | roof | chair | table | keyboard | moon | banana |
|---|---|---|---|---|---|---|---|---|---|---|
| logit | 3.2 | 2.9 | 2.4 | 2.2 | 1.6 | 1.5 | 1.0 | 0.3 | −1.0 | −2.0 |
| \(p\) | 0.320 | 0.237 | 0.144 | 0.118 | 0.065 | 0.058 | 0.035 | 0.018 | 0.005 | 0.002 |
Its entropy is 1.805 nats: genuinely uncertain, as it should be.
Search: greedy and beam¶
Greedy decoding picks \(\arg\max_i p_i\) at every step ("mat"). It is deterministic, which is useful for extraction, classification and tests. It is also myopic: the best first token need not start the best sequence.
Beam search keeps the \(b\) highest-scoring partial sequences. At each step it extends every beam by every token, scores the candidates by total log-probability, and keeps the top \(b\). With \(b=1\) it is greedy; with \(b=\infty\) it is exact search. A toy model in Build it shows the classic failure of greedy:
| method | output | probability |
|---|---|---|
| greedy (beam 1) | The dog ⟨/s⟩ | 0.132 |
| beam 2 or 3 | A dog ⟨/s⟩ | 0.257 |
| exact mode | A dog ⟨/s⟩ | 0.257 |
| beam 3, length-normalised | The cat sat ⟨/s⟩ | 0.173 |
Greedy took "The" (0.55 against 0.45) and committed to a worse path; a beam of 2 kept "A" alive long enough to find that "A dog" is far more likely. The last row shows the other famous property of search: it prefers short outputs. Every token multiplies in a probability below 1, so longer sequences score lower. Translation systems counter this with length normalisation; GNMT divided the log-probability by \(\text{lp}(Y) = (5+|Y|)^\alpha/(5+1)^\alpha\), with \(\alpha\) tuned on development data (Wu et al., 2016). In the toy, plain averaging per token switches the answer to a longer sentence.
The short-output bias can be extreme. Stahlberg and Byrne (2019) ran exact search on a Transformer translation model and found that for more than half of the WMT15 English–German test sentences, the single most probable output was the empty translation. Beam search only worked because it failed to find the true mode.
Why maximisation fails for open-ended text¶
For translation or speech recognition, the output is tightly determined by the input, and beam search is still a strong default. For open-ended generation it is not. Holtzman et al. (2019) compared decoders on GPT-2 Large continuations of WebText (Table 1 of the paper):
| method | perplexity of generated text | repetition % |
|---|---|---|
| human text | 12.38 | 0.28 |
| greedy | 1.50 | 73.66 |
| beam, \(b=16\) | 1.48 | 28.94 |
| pure sampling | 22.73 | 0.22 |
| sampling, \(T=0.9\) | 10.25 | 0.66 |
| top-\(k=40\) | 6.88 | 0.78 |
| nucleus, \(p=0.95\) | 13.13 | 0.36 |
Human text has perplexity about 12 under the model: people do not write the most predictable next word. Greedy and beam output is far more probable than anything a human writes (perplexity 1.5) and degenerates into repetition in nearly three-quarters of cases. Pure sampling has the opposite problem: perplexity 22.7, too surprising, because it occasionally draws from the long tail of low-probability tokens and derails. Nucleus sampling lands closest to human statistics on both columns.
Two mechanisms explain the greedy failure:
- Repetition reinforces itself. Holtzman et al. show the probability of repeating a phrase rises with each repetition: once a loop starts, the context full of copies makes another copy the most likely continuation. Transformers are very good at copying from context, and argmax never escapes.
- The mode is atypical. In a long sequence the single most probable outcome looks nothing like a typical sample (derived in First principles). Human text lives in the "typical set", at about the entropy of the distribution, not at its peak.
Greedy is not 'the model's real answer'
People often treat temperature 0 as the model's true opinion and sampling as noise. For a question with one correct short answer, greedy is usually right. For anything long or open-ended, greedy is a particular, biased search procedure with its own failure modes (loops, blandness, truncation). Neither is "the model"; the model is the distribution.
Temperature¶
Temperature divides the logits before the softmax:
\(T=1\) is the model's own distribution. \(T\to 0\) approaches greedy. \(T>1\) flattens towards uniform. On our example, \(T=0.5\) lifts "mat" from 0.320 to 0.506 and pushes "banana" to effectively zero; \(T=1.5\) lowers "mat" to 0.247 and raises "banana" fourfold to 0.008. Temperature reshapes the whole distribution, but it never removes a token: at any \(T>0\) the tail still gets mass, and over hundreds of tokens the tail gets many chances.
Truncation: top-k, top-p and min-p¶
Truncation methods zero out the tail, renormalise what is left, and sample. They differ in how they decide where the tail starts.
- Top-k keeps the \(k\) most probable tokens (Fan et al., 2018, used \(k=10\) for story generation; GPT-2's published samples used \(k=40\)). The weakness: a fixed \(k\) is too many when the model is confident (after "The capital of France is", only one token is reasonable) and too few when it is not (after "My favourite word is").
- Top-p (nucleus) sampling keeps the smallest set of tokens whose cumulative probability reaches \(p\) (Holtzman et al., 2019). The set adapts: one or two tokens when the model is sure, dozens when it is not.
- Min-p keeps tokens whose probability is at least \(p_\text{base}\) times the top token's probability: \(p_i \ge p_\text{base}\cdot\max_j p_j\) (Nguyen et al., 2024, ICLR 2025, who recommend \(p_\text{base}\) between 0.05 and 0.1). The threshold scales with the model's confidence, so it stays tight when the top token is dominant and loosens when the distribution is flat, which makes high temperatures usable.
On our example (code in Build it):
| method | tokens kept | p(mat) after renormalising | p(banana) |
|---|---|---|---|
| plain sampling, \(T=1\) | 10 | 0.320 | 0.002 |
| top-\(k=3\) | mat, floor, sofa | 0.457 | 0 |
| top-\(p=0.9\) | first 6 (cumulative 0.942) | 0.340 | 0 |
| min-\(p=0.1\) (threshold 0.032) | first 7 | 0.328 | 0 |
Order matters in implementations: most libraries apply penalties, then temperature, then truncation, then sample. Min-p in particular is defined on the temperature-scaled distribution in the min-p paper, so "high temperature plus min-p" behaves very differently from "high temperature alone".
Other controls you will meet¶
- Repetition penalty (CTRL, Keskar et al., 2019): for tokens already generated, divide the logit by \(\theta\) (they suggest \(\theta\approx1.2\)). Dividing a negative logit by \(\theta>1\) would raise its probability, so Hugging Face's implementation multiplies negative logits by \(\theta\) instead (source).
- Frequency and presence penalties: subtract \(\lambda_\text{freq}\cdot\text{count}_i + \lambda_\text{pres}\cdot\mathbb{1}[\text{count}_i>0]\) from logit \(i\), where the count is over generated tokens. This is exactly what vLLM applies, and it is the form exposed by OpenAI-compatible APIs.
- Typical sampling (Meister et al., 2022): keep the tokens whose surprisal \(-\log p_i\) is closest to the current entropy \(H\), until mass \(\tau\) is covered. It targets the typical set directly, sometimes excluding the single most likely token.
- Contrastive search (Su et al., 2022): choose among the top-\(k\) by model confidence minus a penalty for similarity to earlier hidden states; deterministic and repetition-resistant.
- Logit bias and grammar masks: add constants to particular logits, or set every token that would violate a JSON schema or grammar to \(-\infty\). Constrained decoding guarantees a valid format; see Structured outputs and function calling.
- Stop sequences and length limits: decoding ends at an end-of-sequence token, a stop string or a token budget. A response that ends mid-sentence usually hit the budget.
Decoding in practice¶
- Extraction, classification, code edits, evals that need reproducibility: greedy or low \(T\) (0 to 0.3). Note that "temperature 0" is often not bit-for-bit deterministic in production serving: batching and parallel floating-point reductions can change logits slightly between runs.
- Chat and writing: \(T\) around 0.7 to 1.0 with top-\(p\) 0.9 to 0.95 or min-\(p\) 0.05 to 0.1 are common starting points. Many model cards publish the settings the developers tuned for; use those first.
- Many samples, then choose: self-consistency samples several chains of reasoning and takes the majority answer (Wang et al., 2022); best-of-\(n\) samples and picks with a verifier or reward model. These need diverse samples, so they use \(T\approx 0.7\)–1, not greedy. This is the simplest form of test-time compute.
- Translation, speech recognition, short constrained outputs: beam search with length normalisation is still standard.
- Speed without changing the distribution: speculative decoding lets a small draft model propose several tokens and the large model verify them in one pass; a rejection rule makes the output distribution exactly the large model's (Leviathan et al., 2022; Chen et al., 2023). The rule is derived in The maths; the systems side is in Serving LLMs.
Decoding in Jarvis
In an assistant that explains financial-plan numbers computed by code, the numbers must never come from sampling. The pattern is: deterministic code computes; the model routes and explains at low temperature, with constrained decoding for tool calls. Sampling variety is a feature in prose and a bug in figures. See Case study: how Jarvis is built.
First principles¶
Search finds the mode; sampling finds typical text¶
Consider 100 flips of a coin with \(P(\text{heads})=0.6\). The single most probable sequence is all heads, with probability \(0.6^{100}\approx 6.5\times10^{-23}\). A particular sequence with 60 heads has probability \(0.6^{60}0.4^{40}\approx 5.9\times10^{-30}\), ten million times smaller. Yet there are \(\binom{100}{60}\approx1.37\times10^{28}\) such sequences, and together they carry probability 0.081, while "100 heads" as an outcome carries \(6.5\times10^{-23}\). A sampler produces about 60 heads; an optimiser produces 100. Note also that \(0.6^{60}0.4^{40} = 2^{-100H}\) exactly, with \(H=0.971\) bits: typical sequences have probability about \(2^{-nH}\). This is the asymptotic equipartition property.
Text behaves the same way. The highest-probability continuation is a degenerate, maximally predictable string ("the the the", or the empty output); real text sits in the typical set, at a per-token surprisal near the entropy. That is why human text has perplexity around 12 under GPT-2 while greedy output has 1.5, and why the goal for open-ended generation is sampling from a cleaned-up distribution, not finding the best sequence.
Why the tail must be cut¶
If sampling is right, why not sample at \(T=1\) with no truncation? Because the model's tail is unreliable. Maximum likelihood minimises \(D_\text{KL}(p_\text{data}\,\|\,p_\theta)\), which harshly punishes the model for giving near-zero probability to anything real and barely punishes it for spreading small probability over junk (the language-modelling objective). So each of thousands of bad tokens gets a little mass. Individually negligible, collectively they are not: over a 500-token generation the chance of hitting at least one tail token can be large, and one bad token can derail everything after it. Truncation is a cheap correction for the model's mass-covering bias: it trusts the head of the distribution and discards the tail.
The quality–diversity frontier¶
Every method has one knob that moves along the same frontier: low temperature, small \(k\), small \(p\), large \(p_\text{base}\) all buy coherence and lose diversity. The methods differ in how efficiently they trade. Fixed top-\(k\) wastes the knob because it ignores confidence; top-\(p\) and min-\(p\) adapt per step. No setting is best for every task, which is why the knob is exposed to users.
The maths¶
Temperature as tempering¶
Let \(\beta = 1/T\) and \(p^{(\beta)}_i = e^{\beta z_i}/Z(\beta)\) with \(Z(\beta)=\sum_j e^{\beta z_j}\). Then \(p^{(\beta)}_i \propto p_i^{\beta}\), a "tempered" distribution in the sense of statistical physics (\(z\) plays the role of negative energy).
Derivation: entropy falls monotonically as temperature falls
Write \(A(\beta) = \log Z(\beta)\). Then \(\log p^{(\beta)}_i = \beta z_i - A(\beta)\) and \(A'(\beta) = \sum_i p^{(\beta)}_i z_i = \mathbb{E}_\beta[z]\). The entropy is
Differentiate, using \(\frac{d}{d\beta}\mathbb{E}_\beta[z] = \operatorname{Var}_\beta[z]\) (a standard exponential-family identity):
So raising \(\beta\) (lowering \(T\)) never increases entropy, and strictly decreases it unless all logits are equal. Limits: \(\beta\to 0\) gives the uniform distribution (\(H=\log V\)); \(\beta\to\infty\) puts all mass on the arg max (\(H=0\)). Ranking is preserved for every \(T>0\), because \(z_i/T\) is a monotone transform of \(z_i\).
Truncation sets¶
With tokens sorted so that \(p_{(1)}\ge p_{(2)}\ge\dots\):
and the sampling distribution is \(q_i = p_i\,\mathbb{1}[i\in S] / \sum_{j\in S}p_j\). In logit space, min-\(p\) is a fixed margin below the top logit: \(z_i \ge z_{(1)} + \ln p_\text{base}\) (for \(p_\text{base}=0.1\), within 2.30 nats of the best). Top-\(p\) has no such fixed margin; it depends on the whole shape of the distribution.
Sampling by arg max: the Gumbel-max trick¶
If \(g_1,\dots,g_V\) are independent standard Gumbel variables, \(g_i = -\log(-\log u_i)\) with \(u_i\sim\text{Uniform}(0,1)\), then
Derivation: why adding Gumbel noise and taking the arg max samples the softmax
The Gumbel CDF is \(F(x)=\exp(-e^{-x})\) and its density \(f(x) = e^{-x}\exp(-e^{-x})\). Let \(Y_i = z_i + g_i\). Then \(P(Y_j < y) = \exp(-e^{-(y-z_j)})\). The probability that \(Y_i\) is the largest, conditioning on its value \(y\):
Substitute \(s = e^{-y}\), \(ds = -e^{-y}dy\):
Consequences: sampling is "perturb, then argmax", so greedy is sampling with the noise switched off, and temperature is \(\arg\max(z_i/T + g_i)\), equivalently \(\arg\max(z_i + T g_i)\): temperature scales the noise. Taking the top \(k\) of the perturbed logits gives \(k\) samples without replacement (the Gumbel-top-\(k\) trick of Kool et al., 2019), which turns beam search into a stochastic beam search. Relaxing the arg max to a softmax gives the Gumbel-softmax estimator (Jang et al., 2016).
Beam search objective¶
Beam search approximately solves \(\hat{\mathbf{y}} = \arg\max_{\mathbf{y}} \sum_{t}\log p(y_t\mid y_{<t},\mathbf{x})\), or with length normalisation \(\arg\max_{\mathbf{y}} \frac{1}{\text{lp}(|\mathbf{y}|)}\sum_t\log p(y_t\mid y_{<t},\mathbf{x})\). Without normalisation the objective is a sum of negative terms, so it decreases with every added token; that is the short-output bias in one line.
Speculative sampling keeps the distribution exact¶
A draft model proposes token \(x\sim q\); the target model's distribution is \(p\). Accept \(x\) with probability \(\min(1, p(x)/q(x))\); if rejected, sample from the residual \(r(x) = \max(0, p(x)-q(x))/Z\).
Derivation: the output is distributed exactly as p
The probability of accepting the proposal and outputting \(x\) is \(q(x)\min(1, p(x)/q(x)) = \min(q(x), p(x))\). The total acceptance probability is \(\alpha = \sum_x \min(p(x), q(x))\), so rejection happens with probability \(1-\alpha\). Since \(\sum_x \max(0, p(x)-q(x)) = \sum_x\left(p(x)-\min(p(x),q(x))\right) = 1-\alpha\), the residual's normaliser is \(Z = 1-\alpha\). Therefore
The speed-up comes from verifying several drafted tokens with one forward pass of the large model; the better the draft matches \(p\) (the larger \(\alpha\)), the more tokens are accepted per pass.
Build it¶
1. Every transform on one distribution.
import numpy as np
words = ["mat", "floor", "sofa", "bed", "roof", "chair", "table", "keyboard", "moon", "banana"]
logits = np.array([3.2, 2.9, 2.4, 2.2, 1.6, 1.5, 1.0, 0.3, -1.0, -2.0]) # "The cat sat on the ..."
def softmax(z, T=1.0):
z = z / T; z = z - z.max(); p = np.exp(z); return p / p.sum()
def top_k(p, k):
keep = np.zeros_like(p, bool); keep[np.argsort(p)[::-1][:k]] = True; return keep
def top_p(p, thr): # smallest set whose mass reaches thr
order = np.argsort(p)[::-1]; cum = np.cumsum(p[order])
keep = np.zeros_like(p, bool); keep[order[:np.searchsorted(cum, thr) + 1]] = True; return keep
def min_p(p, base): # keep tokens with p >= base * max(p)
return p >= base * p.max()
def renorm(p, keep):
q = np.where(keep, p, 0.0); return q / q.sum()
p = softmax(logits)
H = -(p * np.log(p)).sum()
print(f"entropy {H:.3f} nats; greedy picks '{words[p.argmax()]}'")
rows = {"T=1.0": p, "T=0.5": softmax(logits, 0.5), "T=1.5": softmax(logits, 1.5),
"top-k=3": renorm(p, top_k(p, 3)), "top-p=0.9": renorm(p, top_p(p, 0.9)),
"min-p=0.1": renorm(p, min_p(p, 0.1))}
print(" " + " ".join(f"{w[:6]:>6s}" for w in words))
for name, q in rows.items():
print(f"{name:10s} " + " ".join(f"{x:6.3f}" for x in q) + f" kept {int((q > 0).sum()):2d}")
entropy 1.805 nats; greedy picks 'mat'
mat floor sofa bed roof chair table keyboa moon banana
T=1.0 0.320 0.237 0.144 0.118 0.065 0.058 0.035 0.018 0.005 0.002 kept 10
T=0.5 0.506 0.278 0.102 0.068 0.021 0.017 0.006 0.002 0.000 0.000 kept 10
T=1.5 0.247 0.202 0.145 0.127 0.085 0.079 0.057 0.036 0.015 0.008 kept 10
top-k=3 0.457 0.338 0.205 0.000 0.000 0.000 0.000 0.000 0.000 0.000 kept 3
top-p=0.9 0.340 0.252 0.153 0.125 0.069 0.062 0.000 0.000 0.000 0.000 kept 6
min-p=0.1 0.328 0.243 0.147 0.120 0.066 0.060 0.036 0.000 0.000 0.000 kept 7
2. Greedy versus beam versus exact search on a toy model whose next-token probabilities depend only on the previous token.
import numpy as np
# A toy language model: next-token probabilities depend only on the last token.
P = {"<s>": {"The": 0.55, "A": 0.45},
"The": {"dog": 0.40, "cat": 0.35, "</s>": 0.25},
"A": {"dog": 0.95, "</s>": 0.05},
"dog": {"barked": 0.40, "</s>": 0.60},
"cat": {"sat": 0.90, "</s>": 0.10},
"barked": {"</s>": 1.0}, "sat": {"</s>": 1.0}}
def beam_search(width, alpha=0.0, max_len=6):
beams = [(0.0, ["<s>"])] # (log-prob, tokens)
done = []
for _ in range(max_len):
cand = [(lp + np.log(p), seq + [t]) for lp, seq in beams for t, p in P[seq[-1]].items()]
cand.sort(key=lambda c: c[0], reverse=True)
beams = []
for lp, seq in cand[:width]:
(done if seq[-1] == "</s>" else beams).append((lp, seq))
if not beams: break
score = lambda c: c[0] / (len(c[1]) - 1) ** alpha # length normalisation when alpha > 0
return max(done, key=score)
def all_sequences(seq=("<s>",), lp=0.0):
if seq[-1] == "</s>": yield lp, list(seq); return
for t, p in P[seq[-1]].items(): yield from all_sequences(seq + (t,), lp + np.log(p))
for w in [1, 2, 3]:
lp, seq = beam_search(w)
print(f"beam width {w}: {' '.join(seq[1:]):24s} p = {np.exp(lp):.3f}")
lp, seq = max(all_sequences())
print(f"exact mode: {' '.join(seq[1:]):24s} p = {np.exp(lp):.3f}")
lp, seq = beam_search(3, alpha=1.0)
print(f"beam 3, length-normalised: {' '.join(seq[1:])} (p = {np.exp(lp):.3f})")
beam width 1: The dog </s> p = 0.132
beam width 2: A dog </s> p = 0.257
beam width 3: A dog </s> p = 0.257
exact mode: A dog </s> p = 0.257
beam 3, length-normalised: The cat sat </s> (p = 0.173)
3. The Gumbel-max trick, checked empirically.
import numpy as np
rng = np.random.default_rng(0)
logits = np.array([3.2, 2.9, 2.4, 2.2, 1.6, 1.5, 1.0, 0.3, -1.0, -2.0])
p = np.exp(logits - logits.max()); p /= p.sum()
n = 200_000
g = -np.log(-np.log(rng.random((n, logits.size)))) # standard Gumbel noise
gumbel_max = np.bincount((logits + g).argmax(1), minlength=logits.size) / n
inverse_cdf = np.bincount(np.searchsorted(np.cumsum(p), rng.random(n)), minlength=logits.size) / n
print("softmax ", np.round(p, 4))
print("Gumbel-max ", np.round(gumbel_max, 4))
print("inverse CDF ", np.round(inverse_cdf, 4))
print(f"max |Gumbel-max - softmax| = {np.abs(gumbel_max - p).max():.4f} "
f"(sampling s.d. ~ {np.sqrt(p.max() * (1 - p.max()) / n):.4f})")
top3 = np.argsort(-(logits + g[:5]), axis=1)[:, :3] # Gumbel-top-k: k distinct samples
print("Gumbel-top-3 (5 draws, without replacement):", top3.tolist())
softmax [0.3196 0.2368 0.1436 0.1176 0.0645 0.0584 0.0354 0.0176 0.0048 0.0018]
Gumbel-max [0.3208 0.2369 0.1435 0.1164 0.0651 0.058 0.0354 0.0176 0.0046 0.0017]
inverse CDF [0.3191 0.237 0.1448 0.1168 0.0636 0.0587 0.0357 0.0179 0.0047 0.0018]
max |Gumbel-max - softmax| = 0.0012 (sampling s.d. ~ 0.0010)
Gumbel-top-3 (5 draws, without replacement): [[0, 5, 4], [0, 2, 6], [6, 7, 2], [0, 3, 1], [0, 5, 2]]
4. The same experiment on a real model. This uses the 354,336-parameter character-level GPT
trained in Build a GPT from scratch (its engine.py, model.py and
saved weights gpt_np.npz). Each strategy writes 400 characters after "ROMEO:"; we report the
perplexity of the generated text under the model's own \(T=1\) distribution and the share of repeated
10-character windows. For reference, the model's perplexity on real held-out Shakespeare is
\(e^{1.601}\approx 4.96\).
import numpy as np
from engine import T
from model import gpt # the NumPy GPT from "Build a GPT from scratch"
text = open("input.txt").read(); chars = sorted(set(text)); stoi = {c: i for i, c in enumerate(chars)}
P = {k: T(v) for k, v in np.load("gpt_np.npz").items()} # weights saved by that page's training run
ctx, L, H = 64, 3, 4
def generate(prompt, n, temp=1.0, top_p=1.0, min_p=0.0, seed=0):
rng, idx, nll = np.random.default_rng(seed), [stoi[c] for c in prompt], []
for _ in range(n):
z = gpt(np.array([idx[-ctx:]]), P, L, H).data[0, -1].astype(np.float64)
p1 = np.exp(z - z.max()); p1 /= p1.sum() # model's own distribution (for scoring)
if temp == 0: nxt = int(p1.argmax())
else:
q = np.exp((z - z.max()) / temp); q /= q.sum()
order = np.argsort(q)[::-1]; keep = np.zeros_like(q, bool)
keep[order[:np.searchsorted(np.cumsum(q[order]), top_p) + 1]] = True
keep &= q >= min_p * q.max()
q = np.where(keep, q, 0); nxt = int(rng.choice(len(q), p=q / q.sum()))
nll.append(-np.log(p1[nxt])); idx.append(nxt)
out = "".join(chars[i] for i in idx[len(prompt):])
grams = [out[i:i + 10] for i in range(len(out) - 9)]
rep = 1 - len(set(grams)) / len(grams) # share of repeated 10-char windows
return out, np.exp(np.mean(nll)), rep
prompt = "ROMEO:\n"
for name, kw in [("greedy", dict(temp=0)), ("T=0.7", dict(temp=0.7)), ("T=1.0", dict(temp=1.0)),
("T=1.0, top-p 0.9", dict(top_p=0.9)), ("T=1.6", dict(temp=1.6)),
("T=1.6, min-p 0.1", dict(temp=1.6, min_p=0.1))]:
out, ppl, rep = generate(prompt, 400, **kw)
print(f"{name:17s} ppl {ppl:5.2f} repeated 10-grams {rep:5.1%} | {out[:48]!r}")
greedy ppl 2.09 repeated 10-grams 84.1% | 'What thou hast thou the prince of the strange,\nA'
T=0.7 ppl 2.94 repeated 10-grams 0.0% | "Since, sir,\nWe'll it conters the recious for the"
T=1.0 ppl 3.83 repeated 10-grams 0.0% | "Peace; sittan thou hadst lutter'd not. Hear is o"
T=1.0, top-p 0.9 ppl 3.19 repeated 10-grams 1.0% | 'O a sulless\nWas the best itself and my grantal o'
T=1.6 ppl 11.63 repeated 10-grams 0.0% | "O,\n'Worthy,\nWas the Diplloys, on snapty! O, gran"
T=1.6, min-p 0.1 ppl 4.86 repeated 10-grams 0.0% | 'O F tritors\nWas the Larments, plate myself-blood'
This is Holtzman et al.'s table in miniature. Greedy decoding is far more "probable" than real text (perplexity 2.09 against 4.96) and collapses into a loop; its output continues "And the prince of the prince of the prince,\nAnd the prince of the prince of the prince,\n…" until the budget runs out. Pure sampling at \(T=1\) avoids loops; its perplexity (3.83) is below that of real text because the model's own samples measure its entropy \(H(p_\theta)\), while real text also pays the KL gap. At \(T=1.6\) the tail takes over (perplexity 11.6, invented words). Adding min-\(p\) 0.1 to the same temperature cuts the tail and brings the statistics back to 4.86, almost exactly those of real text, while keeping the extra variety.
Things to try
- In program 1, set the logits to
[5, 1, 1, 1, 1, 1, 1, 1, 1, 1](confident) and to all zeros (clueless). How many tokens do top-\(k=3\), top-\(p=0.9\) and min-\(p=0.1\) keep in each case? Which method adapts and which does not? - Apply min-\(p\) after \(T=2\) and before it. Show the kept sets differ, and explain why order matters.
- In program 2, add a length penalty in GNMT's form \((5+|Y|)^\alpha/6^\alpha\) and find the \(\alpha\) at which the output switches from "A dog" to a three-word sentence.
- Implement speculative sampling with \(p\) = the \(T=1\) distribution and \(q\) = the \(T=1.5\) distribution from program 1. Draw 200,000 tokens and check the output histogram matches \(p\). What is the acceptance rate \(\sum_x\min(p,q)\)?
- Implement a repetition penalty both ways (CTRL's divide-by-\(\theta\) and the sign-aware version) on a logit vector with negative entries. Which tokens become more likely under the naive rule?
Check yourself¶
What does temperature do to the ranking of tokens, and to the entropy?
Nothing to the ranking (\(z_i/T\) is monotone in \(z_i\) for \(T>0\)). Entropy decreases monotonically as \(T\) decreases: \(dH/d\beta = -\beta\operatorname{Var}_\beta[z]\le 0\) with \(\beta = 1/T\).
Why does beam search produce short outputs without length normalisation?
It maximises a sum of log-probabilities, each negative, so every added token lowers the score. Sequences that end early avoid those extra negative terms. In the extreme, exact search can find the empty output to be the mode, as Stahlberg and Byrne showed for translation.
When would you prefer top-p to top-k? When min-p to top-p?
Top-\(p\) over top-\(k\) when the model's confidence varies a lot from step to step: it keeps few tokens when confident and many when not. Min-\(p\) over top-\(p\) at higher temperatures: top-\(p\) on a flattened distribution admits many junk tokens to reach the mass \(p\), whereas min-\(p\)'s threshold is relative to the top token, so it stays strict.
Greedy output has perplexity 1.5 and human text 12.4 under GPT-2. Why is the more probable text worse?
Because the most probable sequence is atypical: real text sits in the typical set with per-token surprisal near the entropy. Maximisation finds degenerate, highly predictable strings, especially repetition loops that reinforce themselves as the context fills with copies.
Prove that arg max(z + g) with Gumbel noise g samples from softmax(z).
See the derivation above: condition on the winner's perturbed value \(y\), multiply the Gumbel CDFs of the others, substitute \(s=e^{-y}\), and the integral evaluates to \(e^{z_i}/\sum_j e^{z_j}\).
Hard: speculative decoding uses a cheaper model's samples. Why is the final output not biased towards the cheap model?
Proposals are accepted with probability \(\min(1, p/q)\) and rejections are resampled from the normalised residual \(\max(0,p-q)\). The output probability is \(\min(p,q) + \max(0,p-q) = p\). The draft affects only speed (the acceptance rate), never the distribution.
Hard: you run self-consistency with 16 samples at T = 0 and get no gain. Why?
At \(T=0\) all 16 samples are (nearly) identical greedy decodes, so the majority vote is a vote of one. Self-consistency needs diversity among reasoning paths; it works because different paths make different errors while correct paths agree.
Go deeper¶
Papers
- The Curious Case of Neural Text Degeneration — Holtzman et al., 2019. Nucleus sampling and the evidence against maximisation. Read sections 3–4 and Table 1.
- Hierarchical Neural Story Generation — Fan et al., 2018. Where top-k sampling became standard.
- Turning Up the Heat: Min-p Sampling — Nguyen et al., 2024 (ICLR 2025). Confidence-scaled truncation; section 3 defines it in three lines.
- Locally Typical Sampling — Meister et al., 2022. The information-theoretic view of why human text is not the mode.
- If beam search is the answer, what was the question? — Meister, Vieira, Cotterell, 2020. Why beam search's errors are a feature: an implicit uniform-information-density bias.
- On NMT Search Errors and Model Errors: Cat Got Your Tongue? — Stahlberg and Byrne, 2019. Exact search finds the empty translation.
- Google's Neural Machine Translation System — Wu et al., 2016. Section 7: beam search with length normalisation and coverage penalty.
- Fast Inference from Transformers via Speculative Decoding — Leviathan, Kalman, Matias, 2022. The exact-distribution acceptance rule; read with Chen et al., 2023.
- Stochastic Beams and Where to Find Them — Kool, van Hoof, Welling, 2019. The Gumbel-top-k trick and sampling without replacement.
- Self-Consistency Improves Chain of Thought Reasoning — Wang et al., 2022. Sampling as a reasoning strategy.
Articles and docs
- How to generate text — Patrick von Platen, Hugging Face. Greedy, beam, top-k and top-p with runnable examples and pictures.
- Generation strategies — Hugging Face Transformers docs. Every knob as a library parameter, including contrastive search and assisted (speculative) decoding.
Videos and code
- Let's build GPT: from scratch, in code, spelled out — Andrej Karpathy. Ends with the simplest possible sampling loop; useful to see it in context.
- vLLM — A production serving engine;
sampling_params.pydocuments every decoding parameter real APIs expose.
Where this leads¶
- Build a GPT from scratch — train the model whose distribution you then decode.
- KV cache, FlashAttention, MQA/GQA/MLA — what makes each decoding step cheap.
- Serving LLMs: batching, PagedAttention, speculative decoding — decoding at production scale.
- Structured outputs and function calling — grammar-constrained decoding.
- Reasoning models and test-time compute — sampling many paths, and models trained to think longer.