AILearn AI
LearnGlossarySources
ID/EN
Learn AI — open material for learning AIEvery lesson cites its original sources.
✎Large Language Models
  1. Tokenization: how text becomes numbers
  2. How LLMs work: next-token prediction at scale
  3. Decoding: greedy, beam search, temperature, top-k, top-p
  4. Scaling laws: parameters, data and compute
  5. Fine-tuning & alignment: SFT, RLHF, DPO, LoRA/QLoRA
  6. Prompting: zero-shot, few-shot, chain-of-thought, structured output
  7. Retrieval-Augmented Generation (RAG)
  8. Agents & tool use: ReAct, function calling, MCP
Modules
  1. ◎ AI Foundations
  2. ∿ Classical Machine Learning
  3. ⌬ Neural Networks
  4. ↘ Training Results & Evaluation
  5. ▦ Deep Learning Architectures
  6. ✎ Large Language Models
  7. ◐ Image Generation
  8. ♪ Audio & Speech AI
  9. ◈ Multimodal, Video & 3D
  10. ↻ Reinforcement Learning
  11. ⚙ ML Development & MLOps
  12. ★ Advanced & Frontier Topics
Learn/Large Language Models

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.

Intermediate~20 min·4 references
Key terms
LogitsTemperatureTop-k samplingTop-p (nucleus) samplingSoftmax

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.

≈
Analogy: ordering at a warung
The menu shows how often each dish is ordered. Greedy always orders the best-seller. Temperature is your mood: low = stick to favourites, high = feel adventurous, very high = order randomly. Top-k says “only consider the k most popular dishes”. Top-p says “only consider the most popular dishes that together make up p% of all orders” — a short list when there is one obvious favourite, a long list when tastes are spread out.

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) = (1 / |y|^α) · Σ_t log P(y_t | y_<t, x)
Beam-search score with a length penalty α (α > 0 counteracts the bias toward short outputs).
In words: A candidate's score is the sum of its token log-probabilities, which only gets more negative as the output grows — so raw scores favour short answers. Dividing by length^α offsets that: α = 0 means no correction, α = 1 means average log-probability per token.
Symbols(hover a symbol in the formula)
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
Short candidate: 3 tokens, Σ log P = −3.0. Long candidate: 6 tokens, Σ log P = −4.8 α = 0: −3.0 vs −4.8 → short wins α = 0.6: −3.0 / 3^0.6 = −1.552 vs −4.8 / 6^0.6 = −1.638 → short still wins, narrowly α = 1: −3.0 / 3 = −1.0 vs −4.8 / 6 = −0.8 → long wins

Sampling with temperature

p_i(T) = exp(z_i / T) / Σ_j exp(z_j / T)
T < 1 sharpens the distribution, T > 1 flattens it, T → 0 becomes greedy.
In words: Divide every logit by the temperature, then apply the usual softmax. T < 1 stretches the gaps between logits (sharper, more predictable); T > 1 shrinks them (flatter, more random). T = 1 leaves the model's distribution unchanged.
Symbols(hover a symbol in the formula)
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
Logits z = [2, 1, 0] T = 1: e^[2, 1, 0] = [7.389, 2.718, 1] → p = [0.665, 0.245, 0.090] T = 0.5: z/T = [4, 2, 0] → [54.598, 7.389, 1] → p = [0.867, 0.117, 0.016] (sharper) T = 2: z/T = [1, 0.5, 0] → [2.718, 1.649, 1] → p = [0.506, 0.307, 0.186] (flatter)
TokenT = 0.5T = 1.0T = 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%
Example: next token after “Pagi ini saya minum segelas …” (“This morning I drank a glass of …”) with logits 3.0, 2.5, 2.0, 1.0, −1.0.

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⁽ᵖ⁾ = smallest V′ ⊆ V such that Σ_{x ∈ V′} P(x | x_<t) ≥ p
The nucleus: tokens outside it get probability 0, the rest are rescaled to sum to 1.
In words: Sort tokens from most to least likely and keep adding them until their probabilities add up to at least p. Sample only from that “nucleus” (after renormalizing). When the model is confident the nucleus is tiny; when it is unsure it grows.
Symbols(hover a symbol in the formula)
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
Sorted probabilities: 0.50, 0.20, 0.15, 0.10, 0.05; p = 0.9 Cumulative: 0.50 → 0.70 → 0.85 (< 0.9) → 0.95 (≥ 0.9) → keep the top 4 Renormalize: [0.50, 0.20, 0.15, 0.10] / 0.95 = [0.526, 0.211, 0.158, 0.105] The 5% tail token can never be sampled.
Loading interactive…
Hand-made logits for a few prompts; the sampling itself is real.

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.
knobtemperature
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.
knobtop_k
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 generate defaults to 50 when sampling); often left off when using top-p.
knobtop_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.
knobnum_beams
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.
knobrepetition_penalty / frequency_penalty
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).
knobmax_new_tokens / max_tokens
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.
TaskSuggested settings
Code, SQL, data extraction, classificationtemperature 0–0.2, top-p 1
Assistant chat, Q&Atemperature 0.5–0.8, top-p 0.9–0.95
Brainstorming, fiction, marketing copytemperature 0.9–1.1, top-p 0.95
Translation / summarization with seq2seq modelsbeam search (4 beams) or greedy, no sampling
Starting recipes — always validate on your own task.
python
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)])
Temperature + top-k + top-p sampling from scratch (NumPy).
python
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))
The same knobs in Hugging Face generate.
!
Pitfalls
(1) Temperature 0 is not a guarantee of determinism on hosted APIs: floating-point and batching effects can still change outputs; use a seed parameter if offered and test. (2) Low temperature does not make answers *true*, only more consistent — a confident wrong answer stays wrong. (3) Changing temperature and top-p aggressively at the same time makes behaviour hard to reason about. (4) Some reasoning-focused models fix or ignore sampling parameters; read the provider docs. (5) For evaluation runs, fix decoding settings, otherwise you are comparing noise.
▸Go deeper: entropy and why likelihood is not quality
H(p) = −Σ_i p_i log p_i
Entropy of the next-token distribution (shown in the widget). Temperature ↑ ⇒ entropy ↑.
In words: Entropy measures how spread out a distribution is: the average “surprise” −log p_i, weighted by how likely each outcome is. 0 means one token is certain; the maximum, log V, means all V tokens are equally likely.
Symbols(hover a symbol in the formula)
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
Uniform over 4 tokens: −4 · 0.25 · ln 0.25 = ln 4 = 1.386 nats (= 2 bits) Skewed [0.7, 0.1, 0.1, 0.1]: −(0.7 ln 0.7 + 3 · 0.1 ln 0.1) = 0.2497 + 0.6908 = 0.9404 nats (1.357 bits) Certain [1, 0, 0, 0]: 0 nats

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

1.
What happens to the next-token distribution when you raise the temperature from 0.7 to 1.5?
2.
Probabilities are 0.50, 0.30, 0.15, 0.05. With top-p = 0.8, which tokens remain?
3.
Why does top-p often work better than a fixed top-k?
4.
You need an LLM to extract invoice fields into JSON reliably. Which settings are the best starting point?
5.
Beam search with 5 beams on an open-ended story prompt most likely produces…
Score: 0/5

References

  1. [1]
    The Curious Case of Neural Text Degeneration
    PaperHoltzman et al.2020arxiv.org
    Introduces nucleus (top-p) sampling.
  2. [2]
    Hierarchical Neural Story Generation
    PaperFan et al.2018arxiv.org
    Popularized top-k sampling.
  3. [3]
    How to generate text: using different decoding methods for language generation with Transformers
    Articlevon Platen2020huggingface.co
  4. [4]
    Transformers documentation — Generation strategies
    DocsHugging Facehuggingface.co
← Previous
How LLMs work: next-token prediction at scale
Next →
Scaling laws: parameters, data and compute