Skip to content
LearnAI

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.

⏱ 13 minBeginner

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.
ANALOGY· Ordering at a restaurant

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. TT divides every logit before the softmax. Dividing by a small number (say T=0.5T = 0.5) stretches the gaps between logits, so the top token’s share grows and the tail shrinks. Dividing by a large number (T=1.5T = 1.5) shrinks the gaps and spreads probability more evenly. T=1T = 1 leaves the model’s distribution unchanged, and as T→0T \to 0 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; log⁡2n\log_2 n bits means nn 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.

INTERACTIVESampling playground
Prompt: After a long day, the cat curled up on the ▁
Presets:
original (T = 1, no filters)after your settingscut (greyed)
␣couch4.1
31→31.0%
␣bed3.8
23→23.0%
␣sofa3.3
14→13.9%
␣rug2.9
9→9.3%
␣windowsill2.6
7→6.9%
␣floor2.4
6→5.7%
␣pillow2.0
4→3.8%
␣mat1.7
3→2.8%
␣keyboard1.2
2→1.7%
␣radiator0.8
1→1.1%
␣roof0.1
1→0.6%
␣moon-1.2
0→0.2%
entropy, original
2.78 bits
entropy, after
2.78 bits
tokens still allowed
12 of 12
top token probability
31.0%

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.

Twelve candidate next tokens with fixed logits. Move the sliders and watch the distribution reshape: outlined bars are the original probabilities, filled bars are after your settings, and greyed tokens are cut. Then press 'Sample 20 times'.

Things to try:

  1. 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.
  2. 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.
  3. 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%.
  4. 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.
  5. 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 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 bb best partial sequences at each step (the “beam”), expanding each, and keeping the best bb 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 ziz_i and temperature T>0T > 0:

pi(T)=ezi/T∑jezj/T.p_i(T) = \frac{e^{z_i / T}}{\sum_j e^{z_j / T}} .

As T→0T \to 0 this tends to a one-hot vector on arg⁡max⁡izi\arg\max_i z_i (greedy); as T→∞T \to \infty it tends to uniform.

Truncation. Sort tokens by probability, p(1)≥p(2)≥⋯p_{(1)} \ge p_{(2)} \ge \cdots. Keep set SS:

  • top-k: S={(1),…,(k)}S = \lbrace (1), \ldots, (k) \rbrace
  • top-p: smallest mm with ∑r=1mp(r)≥p\sum_{r=1}^{m} p_{(r)} \ge p, then S={(1),…,(m)}S = \lbrace (1), \ldots, (m) \rbrace
  • min-p: S={i:pi≥pmin⋅p(1)}S = \lbrace i : p_i \ge p_\text{min} \cdot p_{(1)} \rbrace

then renormalize: p~i=pi/∑j∈Spj\tilde p_i = p_i / \sum_{j \in S} p_j for i∈Si \in S, and 0 otherwise.

Entropy (in bits): H=−∑ipilog⁡2piH = -\sum_i p_i \log_2 p_i.

Worked example. Three tokens A, B, C with logits (2,1,0)(2, 1, 0).

settingpAp_ApBp_BpCp_Centropy
T=1T = 10.6650.2450.0901.20 bits
T=0.5T = 0.5 (logits become 4, 2, 0)0.8670.1170.0160.64 bits
T=2T = 2 (logits become 1, 0.5, 0)0.5060.3070.1861.47 bits
T=1T = 1, top-p = 0.90.7310.26900.84 bits
T=1T = 1, min-p = 0.20.7310.26900.84 bits
T=1T = 1, top-k = 1 (greedy)1000 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])
COMMON MISCONCEPTIONS
  • “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

0/5 answered
  1. Q1.You lower the temperature from 1.0 to 0.3. What happens to the next-token distribution?

  2. Q2.The model is very confident (top token at 95%). With top-p = 0.9, how many tokens survive?

  3. Q3.Why does pure sampling (T = 1, no truncation) sometimes derail long generations?

  4. Q4.With min-p = 0.1, the top token has probability 0.5. Which tokens are kept?

  5. Q5.Why do some reasoning models recommend temperature around 0.6 rather than greedy decoding?

Further reading

Progress is saved in this browser only.
Type to search across all lessons and glossary terms.