AI ENGINEERING · LLM FOUNDATIONS · FOUNDATIONS · 4 OF 35

Temperature, Top-p and Sampling in LLMs, Explained

How a model's raw scores become one chosen token: softmax worked over four candidates, greedy decoding, temperature reshaping the distribution (computed at 0.2, 1.0 and 1.5), top-k and top-p cutting the tail, seeds and why temperature 0 is still not fully deterministic, max tokens and stop sequences, and which settings to use for extraction, code and creative writing.

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17
  18. 18
  19. 19
  20. 20
  21. 21
  22. 22
  23. 23
  24. 24
  25. 25
  26. 26
  27. 27
  28. 28
  29. 29
  30. 30
  31. 31
  32. 32
  33. 33
  34. 34
  35. 35
1 / 19

Press play to hear the narration, or step through at your own pace.

Key takeaways

  • Softmax → odds
  • T reshapes them
  • top-k/top-p cut the tail
  • seeds help reruns
  • cap tokens, check why it stopped

Notes

The idea

Here is the idea. On each step the model does one forward pass and returns a raw score, called a logit, for every token in its vocabulary. Turning those scores into one chosen token is done by a small piece of code called the sampler. Temperature, top p, top k, the seed, max tokens and stop sequences are all sampler settings. They change how you pick, not what the model knows.

Two separate jobs
  • the model: one forward pass → a score (logit) for every token in the vocabulary
  • the sampler: small code that turns scores into ONE token
  • temperature, top-p, top-k, seed, max tokens, stop: all are sampler settings

Softmax

Our running example. The prompt is, my neighbour has a pet, and we keep four candidates. The logits are dog three, cat two point six, fox one point four, and pizza zero. Softmax raises e to each logit, giving about twenty, thirteen and a half, four, and one. Divide each by the total, thirty eight point six, and dog gets fifty two percent, cat thirty five, fox ten, and pizza three. Only the gaps between logits matter.

Four candidates, T = 1
token     logit   e^logit   prob
" dog"      3.0     20.1     52%
" cat"      2.6     13.5     35%
" fox"      1.4      4.1     10%
" pizza"    0.0      1.0      3%
                sum 38.6

prob = e^logit / sum of e^logit
only gaps matter: add 5 to every
logit and nothing changes

Greedy decoding

The simplest strategy is greedy decoding. Always take the most likely token, so here, always dog. It is repeatable and works well when there is one right answer, like pulling a date out of an invoice. But long greedy text tends to be flat, and it can fall into loops, repeating the same phrase. And the best token at each step does not guarantee the best sentence overall.

Greedy decoding
  • pick the highest token, always
  • + repeatable, no randomness
  • + good for short, factual, one-right-answer tasks
  • flat, predictable prose
  • can get stuck repeating the same phrase
  • best token per step is not always the best sentence

Sampling and the tail

The alternative is sampling. Draw a token at random, weighted by probability. Dog about half the time, cat a third, fox one in ten, pizza one in thirty. That gives variety, with a catch. A real vocabulary has around a hundred thousand tokens. Each nonsense token may be tiny, but together they can hold half a percent per step. Over a five hundred token answer, the chance of drawing at least one bad token is about ninety two percent.

The long tail
vocabulary        ~100,000 tokens
each junk token   ~0.0005%
all junk, summed  ~0.5% per step

over a 500-token answer:
  P(no junk) = 0.995^500 ≈ 8%
  P(at least one) ≈ 92%

fix: reshape and trim the
distribution before drawing

Temperature

Temperature is the main dial. Before softmax, divide every logit by a number T. With T below one, the gaps between logits get bigger, so the favourite becomes even more likely. At T equals one, you get the model's distribution as trained. Above one, the gaps shrink, the distribution flattens, and rare tokens get a bigger share. As T approaches zero, the top token takes everything, so temperature zero is treated as greedy decoding.

Temperature T
  • divide every logit by T, then apply softmax
  • T below 1: gaps grow, the top token wins more T = 1: the model as trained
  • T above 1: gaps shrink, rare tokens rise
  • T near 0: same as greedy

Temperature in numbers

Now with numbers. At temperature zero point two, the logits become fifteen, thirteen, seven and zero. Dog jumps to eighty eight percent, cat drops to twelve, and fox and pizza fall below a tenth of a percent. At one, we are back to fifty two, thirty five, ten and three. At one point five, the logits shrink to two, one point seven, zero point nine and zero. Dog falls to forty five percent, fox rises to fifteen, and pizza doubles to six.

Same logits, three temperatures
token     T=0.2   T=1.0   T=1.5
" dog"      88%     52%     45%
" cat"      12%     35%     34%
" fox"      ~0%     10%     15%
" pizza"    ~0%      3%      6%

T=0.2: logits 15, 13, 7, 0
T=1.5: logits 2, 1.7, 0.9, 0

low T: two-horse race
high T: pizza chance doubles

Top-k

Temperature reshapes the tail but never removes it. Truncation does. Top k keeps only the k most likely tokens and throws the rest away. With k equals two, dog and cat survive, fox and pizza are cut, and renormalising gives dog sixty, cat forty. The weakness is that k is fixed. When the model is sure, even two is too generous. When it is unsure, with twenty good options, two is far too tight.

Top-k, k = 2, T = 1
  • keep the k best tokens dog 52%, cat 35%: kept fox, pizza: cut
  • renormalise to sum to 100%: dog 60%, cat 40%
  • weakness: k is fixed. sure step: k too generous unsure step: k too tight

Top-p (nucleus)

Top p, also called nucleus sampling, fixes that. Sort the tokens by probability and keep adding them until the running total reaches p. With p equals zero point nine: dog brings us to fifty two percent, cat to eighty seven, still short, fox to ninety seven, done. Pizza is cut, and the three survivors are renormalised. The set adapts. When the model is confident, one or two tokens survive. When it is unsure, dozens do.

Top-p = 0.9, T = 1
sorted   prob   running total
dog       52%    52%
cat       35%    87%   still < 90%
fox       10%    97%   reached: stop
pizza      3%    cut

renormalise: dog 53, cat 36, fox 11

confident step: 1-2 tokens kept
unsure step: dozens kept

The full pipeline

One full step: get the logits, divide by temperature, apply softmax, apply top k if it is set, apply top p, renormalise, and draw one token. The exact order varies a little between servers. Some open source servers also offer min p, which keeps any token at least a set fraction as likely as the top one. Most providers advise tuning temperature or top p, not both, so you can tell which one changed the result.

One step, a common order
1 logits from the model
2 divide by temperature
3 softmax → probabilities
4 top-k: keep k best (if set)
5 top-p: keep the nucleus
6 renormalise, draw one token

min-p: keep tokens at least
  p × the top token's prob
tip: tune temperature OR top-p

Seeds

The random draw comes from a random number generator, and a seed fixes where that generator starts. With the same prompt, settings, seed and model build, a rerun usually makes the same choices and gives the same text. Usually is the honest word. Many APIs describe seeds as best effort, and some do not offer one at all. Always log the seed, the settings and the exact model version with each request, so you can reproduce a bad output.

Seeds
  • the draw uses a random number
  • generator; a seed fixes it
  • same prompt + settings + seed + same model build → usually the same output
  • many APIs: "best effort" only some do not offer a seed
  • log seed, settings, model id

Why T = 0 still varies

An interview favourite. Temperature zero is greedy, so why can two runs still differ? Because GPU arithmetic is not exact. Adding numbers in a different order rounds differently, and servers batch your request with other people's, so batch size changes the order of operations. When two tokens are almost tied, a tiny rounding change can swap them, and every token after that differs. Treat temperature zero as nearly repeatable, never guaranteed.

Why T = 0 can still differ
  • float maths: (a+b)+c and a+(b+c) round differently
  • batching: your request shares a batch with others, and batch size changes the maths order
  • near ties: two logits a hair apart can swap places
  • one swap changes every token after it
  • the model behind a name moves

Max tokens

Two settings decide when generation ends. First, max tokens, a hard cap on output tokens. If the model hits it, the text is simply cut off, often mid sentence, and the response says the finish reason was length rather than a natural stop. Always check that reason. A truncated JSON object will not parse. With reasoning models, the hidden thinking tokens usually count against the same budget, so set the cap with room to spare.

Max tokens
  • a hard cap on OUTPUT tokens
  • hit the cap: text cut mid- sentence, reason "length"
  • natural end: reason "stop"
  • always check the reason: cut-off JSON will not parse
  • thinking tokens of reasoning
  • models usually count too

Stop sequences

Second, stop sequences. You give a few strings, and generation ends the moment the model writes one of them. Say the stop sequence is a new line followed by Q colon. The model answers, then starts to invent the next question, and the server stops right there. The stop text is usually left out. Stop sequences keep output to one answer or one item, and save output tokens.

Stop sequences
stop = ["\nQ:", "</answer>"]

model writes: "A: 42.\nQ: Next"
you receive:  "A: 42."
  (stop text usually left out)

uses: one answer, one list item,
  one SQL query, end of a tag

saves output tokens and time

Settings by task

Some starting points. Extraction, JSON and classification: temperature zero to zero point two, because there is one right answer. Code: zero to zero point three, or sample several candidates at a higher temperature and keep the one that passes the tests. Chat and question answering: around zero point five to zero point eight. Creative writing: about zero point eight to one point two, with top p near zero point nine. Then measure on your own examples.

Starting points
task             temperature  top-p
extraction, JSON  0 - 0.2      1
classification    0            1
code              0 - 0.3      1
chat, Q&A         0.5 - 0.8    1
creative writing  0.8 - 1.2    0.9-0.95
brainstorming     ~1, several samples

plus: schema for JSON, tight
max tokens, stop sequences

Common mistakes

Common mistakes. Setting temperature to zero to stop made up facts. It only makes the model consistent, so a wrong answer becomes the same wrong answer every time. Tests that expect identical text. Using a high temperature for JSON and getting broken brackets. Tuning temperature and top p together. Ignoring the finish reason. And assuming every model honours these settings. Some reasoning models fix their own sampling.

Mistakes to avoid
  • T = 0 to stop wrong facts: it makes them consistent, not correct
  • tests that expect identical text on every run
  • high T for JSON output
  • tuning T and top-p together
  • ignoring the finish reason
  • assuming every model obeys: some fix or ignore settings

Numbers worth knowing

Numbers worth knowing. Temperature usually runs from zero to about two, with a default near one. Top p is typically zero point nine to zero point nine five, and one means off. Top k, where offered, is usually about twenty to a hundred. Vocabularies run from about fifty thousand to a quarter of a million tokens. Sampling itself costs almost nothing next to the forward pass. And output tokens cost roughly three to five times input tokens.

Ballpark numbers
temperature range   0 to ~2
common default      ~1
top-p typical       0.9 to 0.95
top-p = 1           no truncation
top-k typical       ~20 to 100
vocabulary          ~50k to 250k
sampling cost       tiny vs forward pass
output tokens       ~3-5x input price

T = 0 repeatability: high, not 100%

Say it like this

How to say it. The model produces logits. We divide by the temperature, apply softmax, cut the unlikely tail with top p, and draw one token, repeating until a stop sequence or the token limit. For extraction we use temperature zero, a JSON schema, a tight max tokens and a check on the finish reason. Temperature zero is not fully deterministic because of batching and floating point, so our tests check fields, not exact text.

In the interview
  • "The model gives logits; we divide by temperature, apply softmax, cut the tail with top-p, and draw. For this extraction job: temperature 0, a JSON schema, tight max tokens, and we check the finish reason. T = 0 is not fully deterministic, so tests check fields, not exact text."

Interview questions

Q1How does an LLM turn its output into a chosen token?

The model outputs a logit for every vocabulary token. The sampler optionally divides the logits by a temperature, applies softmax to get probabilities, optionally truncates the tail with top-k or top-p, renormalises, and either takes the top token (greedy) or draws one at random.

Q2What does temperature do, mathematically?

It divides every logit by T before softmax. T below 1 widens the gaps so the top tokens get more probability; T above 1 narrows them so the distribution flattens; T approaching 0 is equivalent to greedy decoding.

Q3What is the difference between top-k and top-p sampling?

Top-k keeps a fixed number of the most likely tokens. Top-p keeps the smallest set whose cumulative probability reaches p, so it keeps few tokens when the model is confident and many when it is unsure. Both renormalise the survivors before drawing.

Q4Why is temperature 0 not perfectly deterministic?

GPU floating-point arithmetic is not associative, and servers batch requests together, so the order of operations can change between runs. When two tokens are nearly tied, a tiny rounding difference can flip the top choice, and every later token changes. Model updates behind an alias add more variation.

Q5Does a low temperature reduce hallucinations?

Not really. It makes the model pick its most likely continuation consistently, so a wrong belief is repeated reliably. Grounding the model in sources, constraining output and verifying results are what reduce made-up facts.

Q6Why do providers suggest changing temperature or top-p, but not both?

They interact: temperature reshapes the distribution and top-p then cuts it, so changing both makes the effect hard to reason about or attribute. Fix one at its default and tune the other against an evaluation set.

Q7What happens when generation hits max tokens?

The output is cut off wherever it is, possibly mid-sentence or mid-JSON, and the finish reason reports length instead of a natural stop. Applications should check the finish reason and retry with a larger budget or a shorter task.

Q8What sampling settings would you use for data extraction versus creative writing?

Extraction: temperature 0 to 0.2, a JSON schema or forced tool call, a tight max-tokens limit and a finish-reason check. Creative writing: temperature around 0.8 to 1.2 with top-p near 0.9 to 0.95, possibly generating several drafts to choose from.