Temperature, Top-k & Top-p Sampling
Temperature reshapes the next-token distribution without reordering it. How it differs from top-k and top-p, and what decoding cannot fix.
Jump to a section
Two ways to decode badly
At every step GPT-2 assigns a probability to each of its 50,257 tokens, and something has to turn that distribution into one token. Always taking the most likely token sounds safe, but Holtzman et al. showed that maximization makes GPT-2 Large fall into loops: once "I don't know." repeats, each repetition makes the next more probable. Sampling from the full distribution fails the other way. Thousands of individually unlikely tokens add up to real probability mass, and sooner or later one of them derails the text.
Decoding sits between those failures, and it is three separate operations. Temperature reshapes the distribution. Truncation (top-k or top-p) decides which tokens stay eligible. Sampling draws one token from what is left, after renormalizing. A temperature of zero is not part of this pipeline: it is the usual convention for switching to greedy decoding.
Temperature reshapes without reordering
Given logits , temperature divides them before the softmax:
leaves the model's distribution as it is. As , mass concentrates on the largest logit, and a unique maximum gives the greedy limit. As grows past 1, the distribution flattens towards uniform.
Another way to see it: is proportional to . Temperature 0.5 squares every probability and renormalizes; temperature 2 takes square roots. Either way the ranking never changes. Temperature cannot make the model prefer a token it did not already rank higher; it only changes how much more.
Take four tokens with probabilities 0.5, 0.3, 0.15 and 0.05 at :
| Temperature | A | B | C | D | Kept by top-p 0.9 |
|---|---|---|---|---|---|
| 0.5 | 0.685 | 0.247 | 0.062 | 0.007 | 2 tokens |
| 1 | 0.500 | 0.300 | 0.150 | 0.050 | 3 tokens |
| 2 | 0.379 | 0.294 | 0.208 | 0.120 | all 4 |
At the least likely token goes from a 1-in-20 chance to better than 1 in 9. That is the whole effect: lower-probability tokens get chosen more often.
Truncation keeps the token that crosses the line
Top-k keeps the highest-probability tokens, zeros the rest and renormalizes. Top-p, or nucleus sampling, keeps the smallest set of top tokens whose mass reaches the threshold,
then renormalizes and samples from it. The difference is what adapts. Top-k keeps the same number of candidates whether the model is confident or not. Top-p keeps few when the model is sure and many when it is uncertain, which is why Holtzman et al. proposed it.
The threshold is cumulative, not per token. At in the table, A and B sum to only 0.8, short of 0.9, so C must also stay even though its own probability is 0.15. The retained mass is 0.95, and renormalizing gives about 0.526, 0.316 and 0.158, with D excluded.
Because temperature runs first, it changes both the probabilities and the size of the nucleus. The table shows it: at the same top-p of 0.9, the cooler distribution keeps two tokens and the warmer one keeps all four. The choice of words is still bounded by the model's fixed logits; temperature only redistributes mass among them.
Greedy and beam search are search, not sampling
Greedy decoding takes the argmax at every step. Beam search keeps the highest-scoring partial sequences among all one-token expansions of the current beam, usually with a length normalization so that short outputs are not favoured just for having fewer factors below 1. It is an approximate search: nothing guarantees it finds the most probable complete sequence.
Both are deterministic given identical logits and tie-breaking. A full serving system can still vary from run to run, because batching and numerical kernels change floating-point results, and because the model behind an API can change. Setting temperature to 0 in an API is a request for greedy decoding, not a reproducibility guarantee.
Search suits tasks where one high-scoring output is the goal, such as some translation and summarization setups, though even there many outputs can be valid and the highest-scoring one is not necessarily the best. For open-ended text, high total probability favours safe, generic continuations and the repetition loops above. Holtzman et al.'s point was that human text is rarely the most probable text.
In code
For one finite logit vector, apply temperature, then top-k, then nucleus truncation. The nucleus must include the token that first reaches or crosses the requested mass.
1import torch
2import torch.nn.functional as F
3
4def sampling_probs(logits: torch.Tensor, temperature=1.0, top_k=0, top_p=1.0):
5 if logits.ndim != 1 or not torch.isfinite(logits).all():
6 raise ValueError("Expected one finite logit vector")
7 if temperature <= 0 or not 0 < top_p <= 1 or not 0 <= top_k <= logits.numel():
8 raise ValueError("Use positive temperature, 0 < top_p <= 1, and a valid top_k")
9 scaled = logits / temperature
10 if top_k > 0:
11 keep = torch.topk(scaled, top_k).indices
12 filtered = torch.full_like(scaled, float("-inf"))
13 filtered[keep] = scaled[keep]
14 scaled = filtered
15 probs = F.softmax(scaled, dim=-1)
16 if top_p < 1.0:
17 sorted_probs, idx = torch.sort(probs, descending=True)
18 # Remove a token only if the mass BEFORE it already reaches p.
19 mass_before = torch.cat([sorted_probs.new_zeros(1), sorted_probs.cumsum(0)[:-1]])
20 sorted_probs[mass_before >= top_p] = 0.0
21 probs = torch.zeros_like(probs).scatter(0, idx, sorted_probs)
22 probs = probs / probs.sum()
23 return probs
24
25
26def sample(logits: torch.Tensor, temperature=1.0, top_k=0, top_p=1.0) -> int:
27 if temperature == 0: # explicit greedy convention
28 return logits.argmax().item()
29 probs = sampling_probs(logits, temperature, top_k, top_p)
30 return torch.multinomial(probs, 1).item()
31
32logits = torch.randn(50000)
33token = sample(logits, temperature=0.8, top_p=0.9)The table above can be checked with the standard library alone:
1def with_temperature(probs, t):
2 powered = [p ** (1 / t) for p in probs] # p(T) is proportional to p(1) ** (1/T)
3 return [p / sum(powered) for p in powered]
4
5
6def nucleus(probs, top_p):
7 kept, mass = [], 0.0
8 for p in sorted(probs, reverse=True):
9 if mass >= top_p: # stop only once the mass BEFORE a token reaches p
10 break
11 kept.append(p)
12 mass += p
13 return [p / mass for p in kept]
14
15
16probs = [0.5, 0.3, 0.15, 0.05]
17assert [round(p, 3) for p in nucleus(probs, 0.9)] == [0.526, 0.316, 0.158]
18assert [len(nucleus(with_temperature(probs, t), 0.9)) for t in (0.5, 1, 2)] == [2, 3, 4]What decoding cannot fix
Knowledge. Neither temperature nor truncation adds information the model lacks. A confident distribution can be confidently wrong, and a diverse sample can be accurate. A lower temperature is not a truthfulness setting.
Order of operations. Not every implementation applies temperature before truncation, and some let you reorder the steps. The table shows why it matters: the same top-p keeps a different number of tokens depending on the temperature it sees. When comparing settings across systems, check the order rather than assuming it.
Flat distributions under top-k. With a fixed , a model that is unsure over hundreds of plausible tokens is cut to the same as one that is nearly certain. That is the case top-p was designed for.
One setting for every task. Code completion, factual answers and fiction want different trade-offs between consistency and variety. Evaluate a decoding policy on the task it will serve, at matched settings, rather than carrying one default everywhere.
Sources and further reading
- Holtzman et al., The Curious Case of Neural Text Degeneration: nucleus sampling and comparisons with maximization-based decoding.
Keep going
Ask your own question about Temperature, Top-k & Top-p Sampling, or start a guided session on it: six short pages, from the big picture to code you can run.