Temperature, Top-p and Top-k Sampling in LLMs Explained
By LatestLLM Editorial · Published · Facts verified · 8 min read
Also called: temperature, top-p, nucleus sampling, top-k, greedy decoding, decoding strategies, creativity setting
Before this: Next-token prediction
In one line
Sampling is how a language model picks the next token from its probabilities, and temperature, top-k and top-p are the dials that make the choice safer or more adventurous.
Sampling and temperature, simply and technically
In plain English
After a model works out how likely each possible next word is, something has to choose one. Always picking the top word gives answers that are repeatable but can be bland and repetitive. Rolling a weighted die, so likelier words come up more often, gives variety but sometimes picks a strange word. A few settings let you decide how adventurous the roll should be.
Temperature is the best known: low makes the model stick to its favourites, high lets it wander. Top-k and top-p cut off the long tail of unlikely words before the roll. That is why the same prompt can give different answers each time, and why tools for writing and tools for code often use different settings.
Think of it like this: Choosing the next word is like picking a restaurant from a ranked list. With temperature at zero you always go to number one. Turn the temperature up and you are more willing to try number five. Top-k says “only consider the top three places”, and top-p says “only consider enough places to cover 90% of my usual choices”. The analogy holds for the mechanics, but a model's list has thousands of entries and the ranking changes with every word it writes.
Everyday example: The same prompt twice
A user asks for a name for a bakery, twice, with a high temperature the first time and a low one the second.
Input:
Suggest a name for a bakery
Output:
High temperature: different names each run. Low temperature: nearly the same name
What it shows: With a high temperature the answers vary a lot: “Crumb & Co.”, “The Golden Whisk”, “Flour Power”. With a low temperature the model returns almost the same name each time, the one it finds most likely. Neither is more correct; they are different trade-offs between variety and reliability.
Technically
A decoder produces logits z over the vocabulary. Temperature T divides them before the softmax: p_i = exp(z_i / T) / Σ_j exp(z_j / T). As T falls toward 0 the distribution approaches one-hot on the top token (greedy decoding); T = 1 leaves it unchanged; T > 1 flattens it. Top-k keeps only the k highest-probability tokens and renormalises. Top-p, or nucleus sampling (Holtzman et al. 2019), keeps the smallest set of tokens whose cumulative probability reaches p, so the number kept adapts to how confident the model is. Holtzman et al. observed that using likelihood as a decoding objective leads to bland, repetitive text, and that decoding choices alone strongly affect quality.
The order of operations matters, and libraries differ. A common pipeline applies temperature, then top-k, then top-p, then draws from what remains. Top-k sampling for open-ended generation was explored by Fan et al. (2018). Settings are exposed in APIs with different ranges and defaults, so a temperature of 1 is a neutral sample from the model's own distribution rather than an absolute measure of creativity. Even at temperature 0, outputs can differ slightly between runs because of floating-point differences on parallel hardware.
Technical example: Sampling settings on a real distribution
The eight most likely next tokens after “The capital of France is” in GPT-2 small. Temperature, top-k and top-p are applied in that order over these eight tokens, and the resulting probabilities are shown.
Code (python):
import math
top = [(" the", .0846), (" now", .0479), (" a", .0462), (" France", .0324),
(" Paris", .0322), (" in", .0266), (" also", .0264), (" not", .0238)]
def sample_dist(T=1.0, k=8, p=1.0):
z = [math.log(q) / T for _, q in top]
e = [math.exp(v - max(z)) for v in z]
probs = [v / sum(e) for v in e]
order = sorted(range(len(top)), key=lambda i: -probs[i])[:k]
mass, kept, cum = sum(probs[i] for i in order), [], 0.0
for i in order:
kept.append(i)
cum += probs[i] / mass
if cum >= p:
break
total = sum(probs[i] for i in kept)
return {top[i][0].strip(): round(probs[i] / total, 3) for i in kept}
for label, args in [("T=1.0", {}), ("T=0.5", {"T": 0.5}), ("T=1.5", {"T": 1.5}),
("top-k 3", {"k": 3}), ("top-p 0.5", {"p": 0.5})]:
print(f"{label:10s}", sample_dist(**args))
Output:
T=1.0 {'the': 0.264, 'now': 0.15, 'a': 0.144, 'France': 0.101, 'Paris': 0.101, 'in': 0.083, 'also': 0.082, 'not': 0.074}
T=0.5 {'the': 0.458, 'now': 0.147, 'a': 0.136, 'France': 0.067, 'Paris': 0.066, 'in': 0.045, 'also': 0.045, 'not': 0.036}
T=1.5 {'the': 0.21, 'now': 0.144, 'a': 0.14, 'France': 0.111, 'Paris': 0.11, 'in': 0.097, 'also': 0.097, 'not': 0.09}
top-k 3 {'the': 0.473, 'now': 0.268, 'a': 0.259}
top-p 0.5 {'the': 0.473, 'now': 0.268, 'a': 0.259}
What it shows: Lowering the temperature to 0.5 concentrates probability on “the” (it rises from 0.264 to 0.458) and raising it to 1.5 spreads probability to the unlikely tokens. Top-k 3 and top-p 0.5 both remove the tail outright and, here, keep the same three tokens. The probabilities are renormalised over GPT-2's eight most likely tokens, which hold 32% of its full distribution; real samplers work on all 50,257.
Temperature
In plain English: Temperature is a dial between cautious and adventurous. Turned down, the model almost always picks its top choice. Turned up, unlikely choices come up more often. At very high settings the text becomes erratic.
Technically:
Dividing logits by T before softmax multiplies every logit gap by 1/T. For two tokens with logit gap Δ, the probability ratio is exp(Δ / T): halving the temperature squares the ratio. In the GPT-2 example the ratio between “the” and “Paris” is 2.63 at T = 1 and about 6.9 at T = 0.5.
Temperature 0 is treated as greedy decoding in most APIs. Temperature does not change which token is most likely, only how much more likely it is than the others, so ordering is preserved; its effect depends on how confident the model already was.
What is greedy decoding?
Always taking the single highest-probability token. It corresponds to a temperature of zero.
Does temperature change the model?
No. It changes only how the output probabilities are used to choose a token.
Top-k and top-p
In plain English: Even with a moderate temperature, the long tail of improbable words has real weight when added up, and one unlucky draw can derail a sentence. Top-k and top-p cut that tail off before the draw, so the choice is only among sensible words.
Technically:
Top-k keeps a fixed number of candidates, which is too many when the model is certain and too few when many words are plausible. Top-p keeps the smallest set whose cumulative probability reaches p, so a confident model keeps one or two tokens and an uncertain one keeps dozens. Holtzman et al. introduced nucleus sampling for this reason after showing that pure likelihood decoding yields degenerate text.
A related rule, min-p, keeps tokens whose probability is at least a fraction of the top token's. Repetition and frequency penalties lower the scores of tokens already used. All of them reshape the same distribution before one draw.
Everyday example: A confident and an unsure model
Top-p is set to 0.9 for both cases.
What it shows: After “2 + 2 =” one token already holds 99%, so the nucleus is a single token. After “Once upon a” the model is unsure, so the nucleus may hold fifty tokens. The same setting adapts to each situation.
Greedy, beam search and sampling
In plain English: There are three broad ways to pick words. Greedy takes the best word each time. Beam search keeps several partial sentences alive and picks the best whole sentence. Sampling rolls the weighted die. Chat models mostly sample.
Technically:
Greedy decoding is deterministic and fast but can repeat itself and miss paths where a lower-probability token leads to a better sentence. Beam search maximises total sequence probability and was common in translation, but for open-ended text it favours bland, repetitive output, the degeneration problem Holtzman et al. describe.
Human-written text is not the highest-probability text. People pick surprising words some of the time, which is why sampling with moderate settings reads as more natural than always choosing the likeliest word.
Choosing settings in practice
In plain English: There is no single best setting. If you need a fact or a piece of code that works, you want the model to stay close to its most likely answer. If you want ideas, you want more variety and can afford some duds.
Technically:
Providers set their own defaults and ranges, so values do not transfer between APIs. A typical approach is to adjust either temperature or top-p, not both, since they overlap in effect. Deterministic tasks such as extraction, classification and code usually benefit from low temperature; brainstorming and creative writing from higher.
Sampling interacts with other behaviour. Some reasoning models' model cards recommend particular sampling settings, and evaluating a model with different sampling settings can change benchmark scores, so reported results should say how they were generated.
Common misconceptions
Myth: Temperature measures how creative or intelligent the model is.
Reality: It only controls how closely the draw follows the model's own probabilities. The underlying knowledge and ranking of tokens are unchanged.
Myth: Temperature 0 guarantees the identical answer every time.
Reality: It makes the choice greedy, which is nearly deterministic, but floating-point differences on parallel hardware can still cause small variations.
Myth: Higher temperature makes the model more accurate or more truthful.
Reality: Higher temperature makes unlikely tokens more probable, which usually raises the error rate on factual and reasoning tasks.
Where you'll see this
- gpt-oss architecture: gpt-oss produces its next-token scores over 201,088 tokens, which the serving stack then samples with the user's settings.
- Gemma 4 architecture: Gemma 4 soft-caps logits at 30 before they reach the sampler, which bounds how extreme a distribution can get.
- DeepSeek-V3 architecture: DeepSeek-V3's multi-token-prediction module can act as the draft in speculative decoding, which has to preserve the sampling distribution.
Key takeaways
- Sampling is the rule for picking the next token from the model's probabilities; the same prompt can give different answers because the pick is random.
- Temperature rescales the logits: low values sharpen the distribution toward the top token, high values flatten it.
- Top-k keeps the k likeliest tokens; top-p (nucleus) keeps the smallest set whose probabilities add up to p, adapting to the model's confidence.
- Tasks with one right answer, such as code or extraction, usually favour low randomness; open-ended writing tolerates more.
Frequently asked questions
What does temperature do in an LLM?
It divides the logits before softmax. Low temperature makes the model favour its top choices; high temperature makes the distribution flatter and the output more varied.
What is top-p sampling?
Nucleus sampling: only the smallest group of tokens whose probabilities add up to p is kept, and the next token is drawn from that group.
What is the difference between top-k and top-p?
Top-k keeps a fixed number of tokens; top-p keeps a variable number, depending on how concentrated the distribution is.
Why does ChatGPT give different answers to the same question?
Because it samples from probabilities. Unless randomness is turned off, each run can draw different tokens.
What temperature should I use?
Low for code, extraction and factual answers; higher for brainstorming and creative writing. Check the provider's defaults, since ranges differ.
Sources
Facts last verified November 23, 2026.