LeepCast
Subscribe
All posts
AI & ML

LLM Sampling Explained: Temperature, Top-k, Top-p, and Min-p

A language model does not output text; it outputs a probability for every token in its vocabulary. This guide walks through how temperature, top-k, top-p, and min-p turn those probabilities into a choice, with runnable code and a worked example.

LeepCast7 min read

Every time a large language model produces a token, it does not pick a word directly. It produces a score, called a logit, for every token in its vocabulary, and those scores are turned into a probability distribution. The decoding strategy is the rule that turns that distribution into one concrete token. Temperature, top-k, top-p, and min-p are the four knobs most inference stacks expose for that rule, and they interact in ways that are easy to get wrong.

This explainer covers what each knob does mathematically, why each one was introduced, how they combine, and how to pick sensible values for different kinds of work. It ends with a small, dependency-free Python implementation you can run to see the numbers for yourself.

From logits to probabilities

The model's final layer emits one logit per vocabulary entry. A softmax converts them into probabilities that are all positive and sum to one. The simplest decoding rule, greedy decoding, always takes the most probable token. Beam search extends that idea by tracking several high-probability sequences at once. Both are maximization strategies, and the paper that introduced nucleus sampling (Holtzman et al. , ICLR 2020) showed that maximization tends to produce degenerate text for open-ended generation: bland, generic phrasing and repetitive loops, even with strong models.

Sampling avoids that by drawing the next token at random in proportion to its probability. Pure sampling has the opposite problem: the vocabulary has tens of thousands of entries, and the long tail of individually unlikely tokens adds up to a meaningful amount of probability mass. Draw from it often enough and the output eventually picks a token that makes no sense, after which the rest of the text has to build on that mistake. Every knob below is a way of controlling that trade-off between repetition and incoherence.

Temperature: reshaping the whole distribution

Temperature divides every logit by a number T before the softmax. With T below 1, the gaps between logits grow, so the top tokens gain probability and the tail shrinks. With T above 1, the gaps shrink and the distribution flattens. As T approaches 0 the result converges on greedy decoding, which is why many servers treat a temperature of zero as a request for greedy output; vLLM, for example, documents that zero means greedy sampling.

Temperature never removes a token. It only changes how likely each one is. That is the key limitation: raising the temperature to get more varied wording also raises the probability of every nonsense token in the tail. The truncation methods exist to cut that tail off.

Top-k: keep a fixed number of candidates

Top-k sampling keeps only the k most probable tokens, sets the rest to zero, renormalizes, and samples. It is simple and cheap. Hugging Face Transformers uses a default of 50 when a model's generation config does not set one, while vLLM defaults to 0, meaning no top-k limit at all.

The weakness is that k is fixed while the shape of the distribution changes at every step. Holtzman et al. point out both failure directions. When the model is uncertain and probability is spread across many reasonable tokens, a small k discards good options and pushes the text toward generic choices. When the model is confident and nearly all probability sits on one or two tokens, a large k lets poor candidates back in, and renormalization inflates their share.

Top-p (nucleus sampling): keep a fixed amount of probability

Top-p replaces a fixed count with a fixed probability budget. Sort tokens from most to least likely, then keep the smallest prefix whose cumulative probability reaches p. That set is called the nucleus. Everything else is dropped, and the nucleus is renormalized. With p set to 0.9, a confident step might keep two tokens and an uncertain step might keep dozens, which is exactly the adaptivity top-k lacks.

Top-p has its own blind spot, and it shows up at high temperature. Because the cutoff is defined by cumulative mass, a flattened distribution needs many more tokens to reach the budget, so low-probability tokens slip into the nucleus. The min-p paper reports this directly: on the GPQA benchmark with Mistral 7B at temperature 3.0, top-p accuracy fell to 0.46 percent, while min-p held at 24.55 percent.

Min-p: a threshold that scales with confidence

Min-p (Nguyen et al. , ICLR 2025) sets a threshold relative to the most likely token. Given a base value, the threshold is the base multiplied by the top token's probability, and any token below it is removed before renormalizing. If the top token has probability 0.8 and the base is 0.1, only tokens at or above 0.08 survive. If the top token has only 0.2, the bar drops to 0.02 and many more options remain.

The effect is that the filter tightens when the model is sure and loosens when it is not, using the shape of the distribution rather than a count or a cumulative sum. The authors report a base of 0.05 to 0.1 working well across tasks and models, and suggest much higher values, around 0.5 to 0.7, when deliberately sampling at very high temperatures. Hugging Face describes typical min-p values of 0.01 to 0.2 as roughly as selective as top-p values of 0.99 to 0.8, which is a useful mental conversion: a larger min-p is stricter, the opposite direction from top-p.

Order of operations matters

These settings are applied as a chain, and the order changes the result. In the min-p paper's method, temperature is applied first and the threshold is computed on the temperature-scaled probabilities. Libraries generally follow the same pattern of scaling the logits and then truncating, but the exact order of every processor is an implementation detail of each library, so check the source of the stack you deploy rather than assuming.

Stacking several truncation methods is legal but often redundant. Each one removes tokens, so the effective filter is whichever is strictest at that step. A common source of confusion is a configuration that sets top-k to 50, top-p to 0.95, and min-p to 0.05 at once, and then attributes behavior to the wrong knob. When tuning, change one parameter at a time and leave the others at their disabled values: top-k 0, top-p 1.0, and min-p 0 in vLLM's conventions.

A worked example in plain Python

The script below implements all four methods with only the standard library. It uses a toy six-token vocabulary for a prompt like 'The capital of France is', with logits chosen so that one answer dominates, two filler words are plausible, one wrong answer is possible, and two tokens are nonsense.

python
import math
import random

def softmax(logits, temperature=1.0):
    scaled = [x / temperature for x in logits]
    m = max(scaled)                       # subtract max for numerical stability
    exps = [math.exp(x - m) for x in scaled]
    total = sum(exps)
    return [e / total for e in exps]

def top_k(probs, k):
    ranked = sorted(range(len(probs)), key=lambda i: probs[i], reverse=True)
    return set(ranked[:k])

def top_p(probs, p):
    ranked = sorted(range(len(probs)), key=lambda i: probs[i], reverse=True)
    kept, cumulative = set(), 0.0
    for i in ranked:                      # smallest prefix whose mass reaches p
        kept.add(i)
        cumulative += probs[i]
        if cumulative >= p:
            break
    return kept

def min_p(probs, base):
    threshold = base * max(probs)         # scaled by the top token's probability
    return {i for i, q in enumerate(probs) if q >= threshold}

def renormalize(probs, kept):
    total = sum(probs[i] for i in kept)
    return [probs[i] / total if i in kept else 0.0 for i in range(len(probs))]

tokens = ["Paris", "the", "a", "London", "banana", "purple"]
logits = [6.0, 4.5, 4.0, 3.0, 0.5, 0.0]

for t in (0.7, 1.0, 1.5):
    probs = softmax(logits, t)
    print(f"T={t}: " + "  ".join(f"{w}={q:.3f}" for w, q in zip(tokens, probs)))

probs = softmax(logits, 1.5)
for name, kept in [("top_k=3", top_k(probs, 3)),
                   ("top_p=0.9", top_p(probs, 0.9)),
                   ("min_p=0.1", min_p(probs, 0.1))]:
    print(f"{name}: kept {[tokens[i] for i in sorted(kept)]}")

final = renormalize(probs, min_p(probs, 0.1))
random.seed(0)
print("sampled:", random.choices(tokens, weights=final)[0])

Running it with Python 3 prints the following:

text
T=0.7: Paris=0.841  the=0.099  a=0.048  London=0.012  banana=0.000  purple=0.000
T=1.0: Paris=0.707  the=0.158  a=0.096  London=0.035  banana=0.003  purple=0.002
T=1.5: Paris=0.552  the=0.203  a=0.146  London=0.075  banana=0.014  purple=0.010
top_k=3: kept ['Paris', 'the', 'a']
top_p=0.9: kept ['Paris', 'the', 'a']
min_p=0.1: kept ['Paris', 'the', 'a', 'London']
sampled: a

Three things are visible. First, temperature alone moved the nonsense tokens from effectively zero at 0.7 to a combined 2.4 percent at 1.5; across a long generation, that adds up to frequent derailments. Second, every truncation method removed both nonsense tokens at T=1.5. Third, min-p kept 'London', because 0.075 is above its threshold of 0.1 times 0.552. That is the method working as designed, keeping a plausible alternative, but it is also a reminder that no sampler checks facts. If the next token must be correct rather than merely plausible, sampling is the wrong tool.

Pushing the same toy example to T=3.0 makes the limits concrete. The top token falls to about 0.36 and the min-p threshold at a base of 0.1 drops to about 0.036, so both nonsense tokens, at roughly 0.057 and 0.049, pass. This matches the paper's advice to raise the base substantially when sampling at very high temperatures.

Choosing settings in practice

  • Extraction, classification, code, and tool calls: use greedy decoding or a low temperature, and leave the truncation knobs disabled. Variety is a defect here.
  • General assistant chat: keep temperature near 1.0 and use one truncation method, such as top-p around 0.9 to 0.95 or min-p around 0.05 to 0.1.
  • Creative writing and brainstorming: raise temperature for variety, and prefer min-p, which the ICLR 2025 results show holding coherence at higher temperatures better than top-p.
  • Generating multiple candidates for later ranking or voting: sampling is the point, so use moderate temperature with min-p and a fixed seed per run when reproducibility matters for debugging.
  • Evaluations: record every sampling parameter alongside the scores, because a result measured at temperature 0 and one measured at temperature 1 are not comparable.

Common mistakes

  1. Assuming a provider's defaults match another provider's. Transformers falls back to top-k 50 when a model's config does not set it; vLLM falls back to no top-k. The same model can therefore behave differently across two stacks with no visible config change.
  2. Reading min-p like top-p. A higher top-p is looser; a higher min-p is stricter.
  3. Raising temperature to fix repetitive output without adding any truncation, which trades loops for occasional nonsense.
  4. Tuning several knobs at once and then being unable to say which one helped.
  5. Using sampling for answers that have exactly one correct form, then blaming the model for inconsistency.

Summary

Temperature reshapes the distribution but never removes tokens. Top-k removes all but a fixed count, which ignores how confident the model is. Top-p removes all but a fixed probability budget, which adapts to the distribution but admits tail tokens when the distribution is flat. Min-p removes everything below a fraction of the top token's probability, which adapts to confidence directly and has shown better coherence at high temperatures in published benchmarks. Pick one truncation method, set temperature for the task, change one variable at a time, and log the settings with every result.

Share

Enjoyed this?

Get the next deep dive in your inbox. No spam — just the stories worth reading.

Subscribe to the newsletter

Comments