Decoding: greedy, beam search, temperature, top-k, top-p
The model only gives you a probability distribution; the decoding strategy decides which token you actually get. Learn what every generation knob does and how to choose settings for code, chat and creative writing.
At every step an LLM outputs Logits — one score per vocabulary token — which Softmax converts to probabilities. Decoding is the rule that turns this distribution into an actual token. The same model can sound robotic, natural, or completely unhinged depending only on a few numbers: Temperature, Top-k sampling, Top-p (nucleus) sampling and friends. These are the knobs you will touch most often when using any LLM API.
Deterministic decoding: greedy and beam search
Greedy decoding picks the arg-max token every step. It is fast and reproducible, but locally best choices can lead to globally poor text, and it easily falls into repetition loops. Beam search keeps the B most probable partial sequences (beams) and expands each one, finally returning the highest-scoring complete sequence. It works well where there is one “correct” short output — translation, summarization, speech recognition — but for open-ended generation, maximizing likelihood produces bland, repetitive text. Holtzman et al. called this *neural text degeneration*: human text is not the most probable text[1].
- score(y)
- the beam-search ranking score of candidate output y
- |y|^α
- the length of y (in tokens) raised to the power α
- α
- length-penalty exponent, typically 0.6–1.0
- Σ_t
- sum over the tokens of y
- log P(y_t | y_<t, x)
- log-probability of token t given the earlier output tokens and the input x (always ≤ 0)
▸Worked example
Sampling with temperature
- p_i(T)
- probability of token i at temperature T
- z_i
- logit (raw score) of token i
- T
- Temperature, > 0 (typical 0.2–1.2)
- exp
- exponential e^(·)
- Σ_j
- sum over all vocabulary tokens j
▸Worked example
| Token | T = 0.5 | T = 1.0 | T = 1.5 |
|---|---|---|---|
| kopi (coffee) | 65.7% | 47.0% | 39.0% |
| teh (tea) | 24.2% | 28.5% | 28.0% |
| air (water) | 8.9% | 17.3% | 20.0% |
| susu (milk) | 1.2% | 6.4% | 10.3% |
| bensin (petrol!) | 0.02% | 0.9% | 2.7% |
Notice the absurd token “bensin”: at T = 1.5 it is sampled almost 3 times in 100. Over a 500-token answer, many such low-probability picks accumulate, and one bad token can derail everything after it. That is why sampling is almost always combined with truncation of the unreliable tail.
Truncation: top-k and top-p (nucleus)
- Top-k (Fan et al.[2]): keep only the k most probable tokens, renormalize, sample. With k = 2 above → kopi 62%, teh 38%. Weakness: a fixed k is too many when the model is confident (keeps junk) and too few when many continuations are valid.
- Top-p / nucleus (Holtzman et al.[1]): keep the smallest set of tokens whose cumulative probability reaches p. With p = 0.9 at T = 1: 47.0 + 28.5 + 17.3 = 92.8% ≥ 90% → keep kopi, teh, air; bensin is gone. The set shrinks automatically when the model is confident and grows when it is unsure.
- Order of operations in common libraries: logits → repetition penalty → temperature → top-k → top-p → softmax → random draw.
- V⁽ᵖ⁾
- the nucleus: the set of tokens kept by Top-p (nucleus) sampling sampling
- V
- the whole Vocabulary
- V′ ⊆ V
- a candidate subset V′ of the vocabulary (⊆ = “is a subset of”)
- Σ_{x ∈ V′}
- sum over the tokens x in V′
- P(x | x_<t)
- model probability of token x as the next token
- p
- the threshold, e.g. 0.9
▸Worked example
Try this
- Set temperature to 0 and press “Sample ×20”: all 20 samples are the same token (greedy). Entropy is 0.
- Raise temperature to 2 with top-k = 12 and top-p = 1: the bars flatten, entropy rises, and silly tokens start appearing in the samples.
- Keep temperature at 2 but lower top-p to 0.8: the greyed-out tail disappears and samples become sensible again — truncation rescues high temperature.
- Compare prompts: with a peaked distribution top-p keeps only 1–2 tokens, with a flat one it keeps many. Top-k keeps the same count in both — that is the difference.
- What it is
- Divides the logits before softmax, controlling how peaked or flat the next-token distribution is.
- ↑ If you increase it
- Flatter distribution → more diverse, surprising, “creative” text; above ~1.2 errors and incoherence grow quickly, especially without top-p.
- ↓ If you decrease it
- Sharper distribution → focused, consistent, repeatable output; at 0 it is greedy, which can repeat itself and sound flat.
- Typical values
- 0–0.3 for extraction, classification, code; 0.7–1.0 for chat and writing.
- What it is
- Keep only the k highest-probability tokens before sampling.
- ↑ If you increase it
- More candidates survive → more diversity, but also more chance of picking junk from the tail. k = vocabulary size disables it.
- ↓ If you decrease it
- Safer, more predictable text; k = 1 is exactly greedy decoding.
- Typical values
- 40–50 (Hugging Face
generatedefaults to 50 when sampling); often left off when using top-p.
- What it is
- Nucleus sampling: keep the smallest set of top tokens whose probabilities add up to at least p.
- ↑ If you increase it
- Toward 1.0 → the full tail is allowed (no truncation); more diversity and more risk.
- ↓ If you decrease it
- Fewer candidates → more conservative; very low p (≈0.1) behaves almost like greedy.
- Typical values
- 0.9–0.95. Providers usually recommend tuning temperature *or* top-p, not both at once.
- What it is
- Number of partial sequences kept in beam search (1 = greedy).
- ↑ If you increase it
- Finds higher-likelihood sequences; better for translation/summaries, but slower (≈ B× compute) and blander for open-ended text.
- ↓ If you decrease it
- Faster; at 1 you are back to greedy decoding.
- Typical values
- 4–5 for translation/summarization; 1 (with sampling) for chat.
- What it is
- Lowers the logits of tokens that already appeared (multiplicative in Hugging Face, additive per occurrence in OpenAI-style APIs).
- ↑ If you increase it
- Breaks repetition loops; too high and the model avoids necessary words (names, “the”, code keywords) and becomes odd.
- ↓ If you decrease it
- No penalty: natural word reuse, but greedy/low-temperature decoding may loop.
- Typical values
- 1.0–1.2 (Hugging Face); 0–0.5 (frequency_penalty in OpenAI-style APIs).
- What it is
- Hard cap on how many tokens are generated.
- ↑ If you increase it
- Allows long answers; worst-case cost and latency grow linearly.
- ↓ If you decrease it
- Cheaper and faster, but answers (or JSON!) can be cut mid-sentence — check the finish reason.
- Typical values
- Set from the expected output size plus margin, e.g. 256 for short answers, 1–4k for long ones.
| Task | Suggested settings |
|---|---|
| Code, SQL, data extraction, classification | temperature 0–0.2, top-p 1 |
| Assistant chat, Q&A | temperature 0.5–0.8, top-p 0.9–0.95 |
| Brainstorming, fiction, marketing copy | temperature 0.9–1.1, top-p 0.95 |
| Translation / summarization with seq2seq models | beam search (4 beams) or greedy, no sampling |
import numpy as np
def sample(logits, temperature=1.0, top_k=0, top_p=1.0, rng=np.random.default_rng(0)):
if temperature == 0: # greedy
return int(np.argmax(logits))
z = np.asarray(logits, dtype=float) / temperature
if top_k > 0: # keep k largest logits
kth = np.sort(z)[-top_k]
z = np.where(z < kth, -np.inf, z)
p = np.exp(z - z.max()); p /= p.sum() # stable softmax
if top_p < 1.0: # nucleus
order = np.argsort(-p)
cum = np.cumsum(p[order])
keep = order[: np.searchsorted(cum, top_p) + 1]
mask = np.zeros_like(p); mask[keep] = 1
p = p * mask; p /= p.sum()
return int(rng.choice(len(p), p=p))
logits = [3.0, 2.5, 2.0, 1.0, -1.0] # kopi, teh, air, susu, bensin
print([sample(logits, 1.0, top_p=0.9) for _ in range(10)])from transformers import AutoTokenizer, AutoModelForCausalLM
tok = AutoTokenizer.from_pretrained("gpt2")
model = AutoModelForCausalLM.from_pretrained("gpt2")
inputs = tok("Once upon a time", return_tensors="pt")
creative = model.generate(**inputs, do_sample=True, temperature=0.9, top_p=0.95,
top_k=0, max_new_tokens=60, repetition_penalty=1.1)
beam = model.generate(**inputs, do_sample=False, num_beams=4,
no_repeat_ngram_size=3, max_new_tokens=60)
print(tok.decode(creative[0], skip_special_tokens=True))
print(tok.decode(beam[0], skip_special_tokens=True))generate.▸Go deeper: entropy and why likelihood is not quality
- H(p)
- entropy of the Probability distribution p
- −Σ_i
- minus the sum over all tokens i
- p_i
- probability of token i
- log
- logarithm: natural log gives nats, log₂ gives bits
▸Worked example
Holtzman et al. showed that human-written text keeps a fairly high, fluctuating per-token surprise, whereas beam search produces text whose probability is unnaturally high — and repetitive[1]. Pure sampling has the opposite problem: the long tail of thousands of individually unlikely tokens has substantial total mass. Truncation methods (top-k, top-p, and newer ones like min-p) aim to sample from the “reliable head”. The Hugging Face blog post and generation docs show all strategies side by side with runnable code[3][4].
Quiz
References
- [1]The Curious Case of Neural Text DegenerationPaperHoltzman et al.2020arxiv.orgIntroduces nucleus (top-p) sampling.
- [2]
- [3]How to generate text: using different decoding methods for language generation with TransformersArticlevon Platen2020huggingface.co
- [4]Transformers documentation — Generation strategiesDocsHugging Facehuggingface.co