Skip to content
mlmentorship

Decoding strategies: greedy, beam, top-k, top-p, temperature

Calculate eligible tokens, normalized probabilities and sequence scores under a declared decoding pipeline.

Published · 14 min read ·Role-specific ·Advanced
Reading depth

Summary

Decoding turns next-token scores into eligible outputs using a declared selection or search policy. Temperature changes probabilities; truncation removes tokens before the retained distribution is normalized. Neither high model probability nor low temperature establishes factual correctness.

Specify vocabulary, allowed-token mask, processor order, tie policy, and EOS or budget stopping. Our default calculation uses temperature , then truncation, renormalization, and sampling. An empty allowed set is an error requiring an explicit recovery policy, not an arbitrary token.

The strategies

Greedy

Pick at every step.

Declare tie-breaking among allowed maxima. Local argmax need not maximize complete-sequence probability or task quality.

Retain a declared number of prefixes, expanding them by cumulative score . Finite beams prune possibilities and need not find the global optimum. Specify completed-EOS handling, length normalization, and stopping together; these can change the selected sequence.

Temperature sampling

Sample from where is the logit vector and is the temperature.

Require . Lower values sharpen relative probabilities; concentrates on maximizers, with ties requiring a policy. Large approaches uniform over finite allowed logits, not masked tokens.

Top-k sampling

Retain exactly highest-probability allowed tokens, resolving cutoff ties by a declared order (Fan et al., 2018). Renormalize their probabilities; a fixed count does not fix retained mass.

Top-p (nucleus) sampling

Retain the smallest sorted prefix whose mass reaches at least threshold , including the crossing token. Choose a threshold in ; declare cutoff ties and renormalize (Holtzman et al., 2020).

Learning objective

Top-k fixes a count; top-p changes the count to reach a probability mass

A probability threshold chooses a count only after seeing the distributionTop-k with k=2 keeps mass 0.70 here. Top-p with p=0.8 needs the third token too, reaching mass 0.85.Keep token identities; change theselection ruleTop-k two stops after the secondtokenRetained mass 0.7; 2 tokensTop-p 0.8 needs the third tokenRetained mass 0.85; 3 tokens
Derivation
Candidate supports for a confident distribution Seven sorted token probabilities are 72, 12, 6, 4, 3, 2, and 1 percent. Top-k with k equals 3 always keeps tokens A through C and captures 90 percent mass. Top-p with p equals 0.80 keeps only A and B, the smallest prefix reaching at least 80 percent, and captures 84 percent mass. CONFIDENT NEXT TOKEN 72%A 12%B 6%C 4%D 3%E 2%F 1%G top-k = 3 · 3 tokens · 90% mass top-p = .80 · 2 tokens · 84% mass
Candidate supports for an uncertain distribution Seven sorted token probabilities are 24, 20, 17, 14, 11, 8, and 6 percent. Top-k with k equals 3 still keeps tokens A through C but now captures only 61 percent mass. Top-p with p equals 0.80 expands through token E, the smallest prefix reaching at least 80 percent, and captures 86 percent mass. UNCERTAIN NEXT TOKEN 24%A 20%B 17%C 14%D 11%E 8%F 6%G top-k = 3 · 3 tokens · 61% mass top-p = .80 · 5 tokens · 86% mass
both panels use the same vertical probability scale. Solid top-k brackets retain three tokens with masses 0.90 and 0.61. Dashed top-p brackets retain two and five tokens, reaching at least 0.80 with masses 0.84 and 0.86. Divide by the retained mass before sampling; do not sample from the original probabilities without renormalizing.
Check: Why does the uncertain distribution need five tokens rather than four to reach 80% mass?
Read it this way: Top-k with k=2 keeps mass 0.70 here. Top-p with p=0.8 needs the third token too, reaching mass 0.85.
Why must the 0.8 cutoff include a third token?

Confident top-k becomes ; confident top-p becomes . Uncertain top-k becomes ; uncertain top-p becomes .

Change processor order

New task: use and top-p on probabilities .

Picture and change: temperature transforms probabilities proportionally to their square roots.

Check: temperature first gives approximately , requiring all three tokens. Truncation first retains mass , then temperature gives .

Use when: reproducing a serving pipeline; processor order is part of the distribution.

Search complete sequences

New task: maximize a two-token sequence’s probability, then stop.

Picture and change: first-token probabilities are . Their best continuation probabilities are and .

Check: greedy follows A, obtaining joint probability . A width-two search can retain B and its completion.

Use when: sequence-score search, rather than a single-step sample, matches the actual objective.

Min-p sampling

Retain and renormalize. This compares individual probabilities with the maximum, not cumulative mass.

Repetition penalty and other modifiers

Real systems layer modifications on top of the base sampler:

  • Repetition penalty: one sign-aware convention divides positive repeated-token logits by and multiplies negative ones by .
  • Frequency / presence penalty: linear adjustment based on how often a token has appeared.
  • No-repeat n-gram: forbid repeating any n-gram already in the output.
  • Logit bias: add token-specific offsets; use an explicit hard mask to forbid tokens.

Dividing a negative logit alone is wrong: increases its score, while decreases it. Grammar constraints restrict allowed tokens but do not establish semantic or factual correctness.

Choosing per task

TaskPolicy to evaluate
Translation, QA, summarizationCompare search/sampling against task metrics, not likelihood alone
CodeDeclare sampling and stopping; evaluate generated programs
Open chatEvaluate quality and diversity under fixed settings
Creative writingChoose support and temperature against a declared objective
Structured outputEnforce grammar, then validate the completed result

Common pitfalls

Compare models under declared policies, random states, masks, and stop rules. An EOS mask can make a budget endpoint differ from a naturally completed sequence. Zero temperature is an implementation’s argmax policy, not a division operation.

What does min-p retain from the uncertain seven-token fixture?

Answer

All seven: the threshold is , below the smallest probability . Neither top-k’s count nor top-p’s cumulative threshold describes that support.