2.10Sampling: temperature, top-k, top-p
A language model only outputs probabilities. How you turn them into actual words, greedily, randomly or somewhere in between, changes everything about the text you get.
The model doesn’t choose words
At the end of the full Transformer walkthrough, the model produced 50,257 logitsLogitsRaw, unnormalized scores a model outputs, one per class or token. Softmax turns them into probabilities., and a softmaxSoftmaxA function that turns a vector of scores into probabilities by exponentiating each score and dividing by the total. turned them into a probability distributionProbability distributionAn assignment of probabilities to possible outcomes, summing to 1. over the vocabulary. That distribution is the model’s entire output. It doesn’t say “the next word is Paris”; it says “Paris: 62%, the: 8%, a: 5%, …” over every possible token.
Something outside the network has to turn that distribution into an actual token, append it, and run the model again. That something is the decoding strategy, or sampler. It has no learned parameters and costs almost nothing to run, yet it has a huge effect on output quality. The same model can sound robotic, creative, or completely unhinged depending on a few sampler settings.
There are two basic options, with everything else in between:
- Greedy decoding: always take the most probable token.
- Pure sampling: draw a token at random, with each token’s chance equal to its probability.
You’re at a restaurant with a long menu, and your friend has rated every dish. Greedy means you always order their #1 pick: reliable, but you eat the same thing every time. Pure sampling means you roll dice weighted by their ratings: usually something good, but now and then you end up with the 47th-ranked tripe surprise.
Temperature is how much you trust the ratings: low temperature exaggerates the gaps (the favorite dominates), high temperature evens them out (anything goes). Top-k says “only consider the top k dishes”. Top-p says “only consider the top dishes that together account for p of your friend’s enthusiasm”, so the shortlist is short when they have a clear favorite and long when they like many things equally. Min-p says “skip anything rated less than a fraction of the favorite”.
Temperature: one knob to sharpen or flatten
TemperatureTemperatureA sampling knob that divides logits before softmax. Low values make output more deterministic; high values make it more random. divides every logit before the softmax. Dividing by a small number (say ) stretches the gaps between logits, so the top token’s share grows and the tail shrinks. Dividing by a large number () shrinks the gaps and spreads probability more evenly. leaves the model’s distribution unchanged, and as the top token takes all the probability, which is just greedy decoding.
Crucially, temperature never changes the ranking of tokens, only how peaked the distribution is. A good way to measure peakedness is entropy, measured in bits: 0 bits means one certain outcome; bits means equally likely options. The demo shows entropy before and after your settings.
Cutting the tail: top-k, top-p and min-p
Even a well-trained model assigns small probabilities to thousands of bad continuations. Individually each is tiny, but there are so many that together they can add up to a meaningful chance per token. Over hundreds of tokens, pure sampling will eventually pick something absurd, and once a weird token is in the text, the model conditions on it and can spiral. Truncation methods fix this by zeroing the tail and renormalizing what remains.
- Top-kTop-k samplingSample only from the k most likely next tokens. keeps the most likely tokens. Simple, but is fixed: is too many when the model is confident (after “The capital of France is”, a few tokens make sense) and may be too few when it isn’t (the first word of a story).
- Top-pTop-p (nucleus) samplingSample from the smallest set of tokens whose probabilities add up to at least p. (nucleus sampling) keeps the smallest set of top tokens whose probabilities add up to at least , for example 0.9. When the model is confident, that might be 2 tokens; when it’s uncertain, 200. The cutoff adapts.
- Min-pMin-p samplingA truncation rule that keeps only tokens whose probability is at least a fraction p of the top token's probability, so the cutoff adapts to how confident the model is. keeps tokens whose probability is at least a fraction of the top token’s probability. With min-p = 0.1 and a top token at 60%, anything under 6% is dropped; if the top token is at only 8%, the bar falls to 0.8%. Its proponents argue it behaves better than top-p at high temperatures, and it’s widely available in open-source inference tools.
These 12 tokens stand in for the top of a ~100k-token vocabulary (the logits are illustrative). Order here: temperature, then top-k, top-p, min-p, then renormalize. Libraries differ in the exact order.
Things to try:
- Temperature 0.5, then 1.5. At 0.5, ” couch” jumps from 31% to about 51% and entropy drops from 2.78 to about 1.9 bits. At 1.5 the distribution flattens and ” moon” becomes a real possibility. Sample 20 times at each and compare the variety.
- Temperature 0 (greedy). One bar at 100%, zero entropy. Every sample is ” couch”. Deterministic, and in long open-ended text exactly this tends to produce loops.
- Top-p = 0.8. The 5 most likely tokens survive (they sum to about 84%). Now raise the temperature to 1.5: the nucleus widens, because the flatter distribution needs more tokens to reach 80%.
- Top-k = 3 vs min-p = 0.2. Both trim the list, but in different ways: top-k always keeps exactly 3, while min-p keeps everything within a factor of 5 of the leader. Change the temperature and see which one adapts.
- Combine high temperature with min-p. Temperature 1.8 plus min-p 0.2 keeps creative variety among plausible tokens while still refusing the absurd tail.
Greedy decoding and beam search
Greedy decodingGreedy decodingAlways picking the single most probable next token. Deterministic, equivalent to temperature 0, and prone to repetitive loops in open-ended text. is deterministic and cheap, and it’s a reasonable choice when there is one right answer and the answer is short: classification labels, extracting a field, short factual completions. For long open-ended generation it’s known to produce bland, repetitive text, often getting stuck repeating the same phrase. A 2019 study, “The Curious Case of Neural Text Degeneration”, documented this and introduced nucleus (top-p) sampling as the fix.
Greedy is also short-sighted: the most likely first token doesn’t always lead to the most likely sentence. Beam searchBeam searchA decoding method that keeps the k most probable partial sequences at each step and returns the best complete one. Common in translation; rarely used for chat models. addresses this by keeping the best partial sequences at each step (the “beam”), expanding each, and keeping the best again. It’s the classic choice for machine translation and speech recognition, where outputs are tightly constrained by the input. For chat and creative writing it’s rarely used: it is more expensive and, like greedy, tends toward generic, repetitive text.
Repetition penalties
A separate family of tweaks targets loops directly. A repetition penaltyRepetition penaltyA decoding-time adjustment that lowers the logits of tokens that already appeared in the text (as in frequency and presence penalties) to discourage loops. lowers the logits of tokens that already appear in the text. Variants include:
- Multiplicative repetition penalty (popularized by the CTRL paper in 2019): divide a previously seen token’s positive logit by a factor such as 1.2.
- Frequency penalty: subtract an amount proportional to how many times the token has appeared.
- Presence penalty: subtract a fixed amount if the token has appeared at all.
These help with loops but are blunt: they also penalize tokens that should repeat, such as variable names in code, a character’s name in a story, or “the”. Use them sparingly.
Choosing settings in practice
Common rules of thumb (not laws):
- Code, math, extraction, factual Q&A: low temperature (0 to 0.3), or greedy. You want the most likely answer.
- General chat: temperature around 0.7 to 1.0 with top-p around 0.9 to 0.95.
- Brainstorming and fiction: higher temperature (1.0 or a bit above) with a truncation method such as min-p to keep it coherent.
Reasoning models add a twist. Models trained to produce long chains of thought (see reasoning models) often come with specific recommended settings. At the time of writing, for example, the DeepSeek-R1 model card recommends a temperature around 0.6 (within 0.5–0.7), and Qwen3’s documentation recommends temperature 0.6 with top-p 0.95 and top-k 20 in its thinking mode, explicitly warning against greedy decoding. The stated reason is that greedy decoding over thousands of reasoning tokens tends to fall into endless repetition, while too high a temperature lets errors creep into long chains. Recommendations are model-specific and change between releases, so check each model’s card rather than treating any number as universal.
MATH CORNER · optionalTemperature, truncation and entropy, with numbers
Temperature. With logits and temperature :
As this tends to a one-hot vector on (greedy); as it tends to uniform.
Truncation. Sort tokens by probability, . Keep set :
- top-k:
- top-p: smallest with , then
- min-p:
then renormalize: for , and 0 otherwise.
Entropy (in bits): .
Worked example. Three tokens A, B, C with logits .
| setting | entropy | |||
|---|---|---|---|---|
| 0.665 | 0.245 | 0.090 | 1.20 bits | |
| (logits become 4, 2, 0) | 0.867 | 0.117 | 0.016 | 0.64 bits |
| (logits become 1, 0.5, 0) | 0.506 | 0.307 | 0.186 | 1.47 bits |
| , top-p = 0.9 | 0.731 | 0.269 | 0 | 0.84 bits |
| , min-p = 0.2 | 0.731 | 0.269 | 0 | 0.84 bits |
| , top-k = 1 (greedy) | 1 | 0 | 0 | 0 bits |
For top-p = 0.9: A alone has 0.665 < 0.9; A + B = 0.910 ≥ 0.9, so keep A and B and renormalize by 0.910. For min-p = 0.2: the threshold is 0.2 × 0.665 = 0.133, so B (0.245) stays and C (0.090) goes. Same result here, by different rules.
In code
A complete sampler for one step, in PyTorch:
import torch
def sample_next(logits, temperature=1.0, top_k=0, top_p=1.0, min_p=0.0):
"""logits: [vocab] for the last position. Returns one token id."""
if temperature == 0:
return int(torch.argmax(logits)) # greedy
probs = torch.softmax(logits / temperature, dim=-1)
sorted_p, idx = torch.sort(probs, descending=True)
keep = torch.ones_like(sorted_p, dtype=torch.bool)
if top_k > 0:
keep[top_k:] = False # top-k
if top_p < 1.0:
cum = torch.cumsum(sorted_p, dim=-1)
keep &= (cum - sorted_p) < top_p # top-p: keep until mass >= p
if min_p > 0:
keep &= sorted_p >= min_p * sorted_p[0] # min-p
sorted_p = torch.where(keep, sorted_p, torch.zeros_like(sorted_p))
choice = torch.multinomial(sorted_p / sorted_p.sum(), 1)
return int(idx[choice])
- “Temperature makes the model smarter or more creative.” Temperature only reshapes the distribution the model already produced. It can make outputs more varied or more conservative, but it adds no knowledge; high temperature mostly adds risk.
- “Temperature 0 gives the best answer.” It gives the single most likely next token at every step, which is not the same as the best overall response. For long or reasoning-heavy outputs, greedy decoding can loop or get stuck.
- “Top-p = 0.9 means the model is 90% confident.” It’s a cutoff on cumulative probability, used to decide which tokens to allow. It says nothing about whether the output is correct.
- “Sampling settings are part of the model.” They are chosen at inference time by whoever runs the model. The same weights can be decoded greedily in one app and at temperature 1.2 in another.
Check your understanding
Q1.You lower the temperature from 1.0 to 0.3. What happens to the next-token distribution?
Q2.The model is very confident (top token at 95%). With top-p = 0.9, how many tokens survive?
Q3.Why does pure sampling (T = 1, no truncation) sometimes derail long generations?
Q4.With min-p = 0.1, the top token has probability 0.5. Which tokens are kept?
Q5.Why do some reasoning models recommend temperature around 0.6 rather than greedy decoding?
Further reading
- paperThe Curious Case of Neural Text Degeneration — Holtzman et al. (2019): why greedy and beam search degenerate; introduces nucleus (top-p) sampling.
- paperHierarchical Neural Story Generation — Fan et al. (2018): popularized top-k sampling for story generation.
- paperTurning Up the Heat: Min-p Sampling for Creative and Coherent LLM Outputs — Nguyen et al. (2024): the min-p method and its evaluation.
- paperCTRL: A Conditional Transformer Language Model for Controllable Generation — Keskar et al. (2019): introduces the multiplicative repetition penalty.
- blogHow to generate text: using different decoding methods — Hugging Face's practical tour of greedy, beam search, top-k and top-p.
- docsDeepSeek-R1 model card — Includes the recommended sampling settings for the reasoning model.