Temperature, Top-p and Top-k Explained: How an LLM Picks the Next Token
Every time a language model writes a word, it is making a choice. The model does not output a single answer. It produces a score for every token in its vocabulary, and a separate step called sampling decides which token actually gets used. Temperature, top-p and top-k are the dials that control that step.
Most people tune these settings by feel: "temperature up for creative, down for code." That rule of thumb is fine, but it hides why it works and when it fails. This guide shows the math behind each setting with a small worked example, so you can set them on purpose.
From logits to probabilities
A model's final layer produces one raw score, called a logit, for each token in the vocabulary. Logits can be any real number, so they are not probabilities yet. To turn them into probabilities, the model applies the softmax function:
p(token i) = exp(logit_i) / sum over all j of exp(logit_j)
Softmax makes every probability positive and makes them sum to 1. Larger logits get larger probabilities, and because of the exponential, a small gap in logits can become a big gap in probability.
To keep numbers readable, imagine a toy vocabulary of four candidate tokens for the next word, with these logits:
| Token | Logit |
|---|---|
| A | 2.0 |
| B | 1.0 |
| C | 0.5 |
| D | 0.0 |
Applying softmax at the default settings gives:
| Token | exp(logit) | Probability |
|---|---|---|
| A | 7.389 | 0.579 |
| B | 2.718 | 0.213 |
| C | 1.649 | 0.129 |
| D | 1.000 | 0.078 |
The sum of the exponentials is 12.756, so A gets 7.389 ÷ 12.756, or about 58%. That distribution is what the model "believes" before any sampling tricks are applied. If you want to see where logits come from, our and stages walk through the pipeline.
Temperature: sharpening or flattening the distribution
Temperature divides every logit before softmax:
p(token i) = exp(logit_i / T) / sum over all j of exp(logit_j / T)
- T below 1 makes the distribution sharper. The top token gets even more probability.
- T equal to 1 leaves the model's own distribution unchanged.
- T above 1 flattens the distribution. Unlikely tokens get a bigger share.
Here is the same toy example at three temperatures:
| Token | T = 0.5 | T = 1.0 | T = 2.0 |
|---|---|---|---|
| A | 0.831 | 0.579 | 0.409 |
| B | 0.112 | 0.213 | 0.248 |
| C | 0.041 | 0.129 | 0.193 |
| D | 0.015 | 0.078 | 0.150 |
At T = 0.5, token A wins about 83% of the time. At T = 2.0, even token D, the weakest candidate, is chosen 15% of the time. Nothing about the model's knowledge changed. Only the randomness did.
As temperature approaches zero, sampling becomes greedy decoding: always pick the highest-probability token. Most APIs treat a temperature of 0 as exactly that. Be careful with the word "deterministic," though. Even at zero, outputs can differ between runs because of batching, floating-point arithmetic and hardware differences. Low temperature makes answers more repeatable, not guaranteed identical.
Top-k: cut the list to the best k tokens
Temperature reshapes the whole distribution. Top-k instead removes candidates. You keep only the k most likely tokens, renormalize their probabilities so they sum to 1, and sample from that short list.
With k = 2 on our toy example at T = 1, only A and B survive:
- A: 0.579 ÷ (0.579 + 0.213) = about 0.731
- B: 0.213 ÷ (0.579 + 0.213) = about 0.269
C and D can never be chosen. This blocks the long tail of strange tokens, which is useful when the vocabulary has tens of thousands of entries and most of them are nonsense in context.
The weakness of top-k is that k is fixed. Sometimes the model is nearly certain and one token holds 95% of the probability, so keeping 40 candidates just adds noise. Other times the model is genuinely uncertain and 40 candidates are all reasonable, so cutting to five throws away good options. A fixed number cannot adapt to how confident the model is.
Top-p (nucleus sampling): cut by probability, not by count
Top-p, also called nucleus sampling, solves that problem. Instead of keeping a fixed number of tokens, it sorts tokens from most to least likely and keeps the smallest set whose cumulative probability reaches p.
With p = 0.8 on the toy example at T = 1:
- A alone covers 0.579, which is below 0.8.
- A plus B covers 0.792, which is still below 0.8.
- A plus B plus C covers 0.921, which reaches 0.8, so the set is {A, B, C}.
Renormalize the survivors (the sum of their exponentials is 11.756):
| Token | Probability after top-p = 0.8 |
|---|---|
| A | 0.629 |
| B | 0.231 |
| C | 0.140 |
| D | 0 |
When the model is confident, the nucleus is tiny, maybe one or two tokens. When it is uncertain, the nucleus grows. That adaptivity is why top-p is the more common choice in modern APIs.
How the settings combine
In most implementations the order is: apply temperature to the logits, convert to probabilities with softmax, apply top-k and/or top-p to prune, renormalize, then sample. Because these settings interact, a few practical rules help:
- Change one at a time. Many providers advise adjusting temperature or top-p, not both, because the effects overlap and become hard to reason about.
- Temperature changes the shape, top-p and top-k change the cutoff. If outputs feel too random, lowering temperature is the broad fix. If you only see occasional bizarre tokens, a modest top-p trims the tail.
- Some models restrict or ignore these parameters. Certain reasoning models, for example, fix or reject sampling settings. Check your provider's documentation rather than assuming the dials work everywhere.
Here is a minimal implementation that makes the pipeline concrete:
import math
import random
def sample(logits, temperature=1.0, top_k=None, top_p=None):
if temperature == 0:
return max(range(len(logits)), key=lambda i: logits[i]) # greedy
scaled = [x / temperature for x in logits]
m = max(scaled) # for numerical stability
exps = [math.exp(x - m) for x in scaled]
total = sum(exps)
probs = [e / total for e in exps]
ranked = sorted(range(len(probs)), key=lambda i: probs[i], reverse=True)
if top_k:
ranked = ranked[:top_k]
if top_p:
kept, cum = [], 0.0
for i in ranked:
kept.append(i)
cum += probs[i]
if cum >= top_p:
break
ranked = kept
weights = [probs[i] for i in ranked] # random.choices renormalizes
return random.choices(ranked, weights=weights)[0]
print(sample([2.0, 1.0, 0.5, 0.0], temperature=0.7, top_p=0.9))
Run it a few hundred times with different settings and count how often each token appears. The counts will match the tables above, which is a good way to build intuition.
Practical starting points
There is no universal best setting, because the right value depends on the model and the task. These are starting points to test, not rules:
Then test on your own prompts. The best approach is to run a small set of real tasks at two or three settings and compare, using the method in our guide to .
Common misconceptions
- "Low temperature makes the model more accurate." It makes the model more consistent. If the most likely answer is wrong, a low temperature will repeat the wrong answer reliably.
- "High temperature makes the model smarter or more creative." It makes it more random. Creativity comes from the model and the prompt, and randomness just changes which path is taken.
- "Temperature 0 means identical outputs every time." Usually close, but not guaranteed.
- "Top-p and top-k do the same thing." Both prune the tail, but top-k uses a fixed count and top-p uses a probability mass, so they behave differently when the model's confidence changes.
- "Sampling settings fix hallucinations." They can reduce wild guesses, but they do not give the model facts it lacks. For that, look at retrieval and grounding.
Other knobs you may meet
Some APIs expose extra controls built on the same idea. Frequency and presence penalties push down tokens that already appeared to reduce repetition. A min-p setting keeps tokens whose probability is above a fraction of the top token's probability. Repetition penalties are common in local runtimes. They all modify or prune the distribution before the final draw, so the mental model you just learned still applies.
Sampling and cost
Sampling settings do not change the price per token, but they can change how many tokens you use. Higher randomness can lead to longer, wandering answers, and retries after a bad output cost more. If you are working with an API, keep an eye on output length with the , and see for the budgeting side.
FAQ
What temperature should I use? Start low (around 0 to 0.3) for tasks that need consistency, and moderate to higher for open-ended writing. Test on your own prompts.
Should I change temperature and top-p together? Usually change one. Their effects overlap, and changing both makes it hard to know what caused a difference.
Why does the same prompt give different answers? Because sampling is random by design, and even at low temperature small numerical differences can change which token wins.
Does temperature affect the model's knowledge? No. It only changes how the model's existing probabilities are used when picking each token.
The takeaway
An LLM does not "decide" a word. It scores every token, softmax turns scores into probabilities, and sampling picks one. Temperature reshapes the probabilities, top-k keeps a fixed number of candidates and top-p keeps a probability mass. Once you can compute the toy example by hand, you can set these dials on purpose instead of by feel.