Sampling and Temperature

How a language model chooses each next token, what temperature, top-k and top-p change, and which settings suit which tasks.

13 minLesson 5 of 6
On this page
  1. How the next token is chosen
  2. Temperature
  3. Top-k and top-p
  4. Pitfalls
  5. Choosing settings in practice
  6. What to practise next

A language model does not produce text directly. For every position it produces a probability for each possible next token, and a separate step called sampling decides which token is actually used. Temperature, top-k and top-p are settings for that step. They control how predictable or how varied the output is, which is why the same prompt can give different answers on different runs.

If the model always took the single most likely token, it would give the same answer every time, and open-ended writing would often be flat or get stuck repeating a phrase. If it picked too freely, unlikely tokens would eventually break sentences and structured formats such as JSON. The sampling settings let you choose a point between those two failures.

How the next token is chosen

At each step the model assigns a raw score to every token in its vocabulary. The softmax function turns these scores into probabilities that add up to 1, as described in the attention lesson. The sampler then picks one token from those probabilities and appends it to the text, and the process repeats for the next position. The simplest sampler, greedy decoding, always takes the token with the highest probability.

The alternative is to pick at random, weighted by probability, so a token with probability 0.46 is chosen about 46% of the time. In code, you draw a random number r between 0 and 1 and add up the probabilities in order. The first token at which the running total passes r is the one chosen. Each token effectively owns a slice of the range from 0 to 1, and the width of the slice is its probability.

The tracer below follows one choice. A model is completing "My favourite fruit is" and has five candidates. It also shows what temperature does to the probabilities, which the next section explains.

Temperature and sampling for one tokenUse the arrows or ← → keys
scaled = each score / temperaturechances = softmax(scaled)r = random number in [0, 1)running = 0for each token: running += chance  if r < running: pick this token
  1. word
    0apple
    1mango
    2banana
    3kiwi
    4durian
    score
    02
    11.5
    21
    30
    4-1
    chance
    00.46
    10.28
    20.17
    30.06
    40.02
    temperature
    1

    1These are the raw scores. At temperature 1 they are used unchanged, and softmax gives the probabilities shown (rounded).

  2. word
    0apple
    1mango
    2banana
    3kiwi
    4durian
    running
    00.46
    10.74
    20.91
    30.98
    41
    r
    0.62
    running
    0.46

    2The random number drawn is r = 0.62. After apple the running total is 0.46, and 0.62 is not below it, so the loop continues.

  3. word
    0apple
    1mango
    2banana
    3kiwi
    4durian
    running
    00.46
    10.74
    20.91
    30.98
    41
    r
    0.62
    running
    0.74
    pick
    mango

    3After mango the running total is 0.74, and 0.62 is below it, so the pick is mango, even though apple was more likely. Greedy decoding would have returned apple every time.

  4. word
    0apple
    1mango
    2banana
    3kiwi
    4durian
    scaled
    04
    13
    22
    30
    4-2
    chance
    00.66
    10.24
    20.09
    30.01
    40
    temperature
    0.5

    4At temperature 0.5 every score is doubled to 4, 3, 2, 0 and -2. The gaps double as well, so apple rises from 0.46 to 0.66 and durian almost disappears.

  5. word
    0apple
    1mango
    2banana
    3kiwi
    4durian
    scaled
    01
    10.75
    20.5
    30
    4-0.5
    chance
    00.34
    10.26
    20.2
    30.12
    40.07
    temperature
    2

    5At temperature 2 every score is halved to 1, 0.75, 0.5, 0 and -0.5. The probabilities become more even, and durian is now chosen about once in 13 draws.

  6. T = 0.5
    00.66
    10.24
    20.09
    30.01
    40
    T = 1
    00.46
    10.28
    20.17
    30.06
    40.02
    T = 2
    00.34
    10.26
    20.2
    30.12
    40.07

    6The ranking is the same at all three temperatures. Only the size of apple's lead changes, and with it how much variety you see.

1 / 6

Temperature

Temperature changes the probabilities before the pick. The sampler divides every score by the temperature and then applies softmax. A temperature below 1 widens the gaps between scores, so the top tokens become even more likely and the output is more predictable. A temperature of exactly 1 leaves the model's probabilities as they are. A temperature above 1 narrows the gaps, so unlikely tokens gain a larger share and the output is more varied and more likely to go wrong.

Dividing by zero is impossible, so a temperature of 0 is handled as a special case that means greedy decoding. Dividing every score by the same positive number never changes their order, so temperature changes how much the leader is favoured but never which token is the leader.

function chancesAt(scores, temperature) {
  if (temperature === 0) { // greedy: all the probability on the top score
    const top = scores.indexOf(Math.max(...scores));
    return scores.map((_, i) => (i === top ? 1 : 0));
  }
  const scaled = scores.map((s) => s / temperature); // the only change
  const biggest = Math.max(...scaled);
  const exps = scaled.map((s) => Math.exp(s - biggest));
  const total = exps.reduce((a, b) => a + b, 0);
  return exps.map((e) => e / total);
}
 
// r is a random number in [0, 1).
function sample(chances, r) {
  let running = 0;
  for (let i = 0; i < chances.length; i++) {
    running += chances[i];
    if (r < running) return i;
  }
  return chances.length - 1; // guard against rounding
}
 
const words = ["apple", "mango", "banana", "kiwi", "durian"];
const chances = chancesAt([2, 1.5, 1, 0, -1], 1);
words[sample(chances, 0.62)]; // "mango"
import math
 
def chances_at(scores, temperature):
    if temperature == 0:  # greedy: all the probability on the top score
        top = scores.index(max(scores))
        return [1.0 if i == top else 0.0 for i in range(len(scores))]
    scaled = [s / temperature for s in scores]  # the only change
    biggest = max(scaled)
    exps = [math.exp(s - biggest) for s in scaled]
    total = sum(exps)
    return [e / total for e in exps]
 
# r is a random number in [0, 1).
def sample(chances, r):
    running = 0.0
    for i, c in enumerate(chances):
        running += c
        if r < running:
            return i
    return len(chances) - 1  # guard against rounding
 
words = ["apple", "mango", "banana", "kiwi", "durian"]
chances = chances_at([2, 1.5, 1, 0, -1], 1)
words[sample(chances, 0.62)]  # "mango"

The random number is passed in as r so that the example is repeatable. In real use you would pass Math.random() or random.random().

Top-k and top-p

A real vocabulary has tens of thousands of tokens. Most of them have tiny probabilities, but together this long tail can hold a noticeable share, so an occasional pick from it can derail a sentence. Top-k and top-p remove the tail before the pick. Neither one changes the probabilities of the tokens that remain, other than rescaling them so they add up to 1 again.

Top-k

Top-k keeps only the k most likely tokens, for example the top 40, and discards the rest. It is easy to understand, but the right value of k depends on the situation. When the model is nearly certain, for instance when it is finishing a word, a single token deserves almost all the probability, and keeping 40 candidates lets in 39 poor ones. When many continuations are reasonable, as at the start of a story, 40 candidates may cut off good ones.

Top-p

Top-p, also called nucleus sampling, adapts to this. It sorts the tokens by probability and keeps the smallest group whose probabilities add up to at least p, then rescales that group to sum to 1. With the fruit example at temperature 1 and p = 0.9, apple (0.46) and mango (0.28) reach only 0.74, so banana is added and the total becomes 0.91, which passes 0.9. Kiwi and durian are dropped, and the three survivors are rescaled to about 0.51, 0.31 and 0.19. When the model is sure, top-p keeps only one or two tokens, and when it is unsure, it keeps many.

Top-p filter
function topP(chances, p) {
  const order = chances.map((_, i) => i).sort((a, b) => chances[b] - chances[a]);
  const kept = new Set();
  let running = 0;
  for (const i of order) { // keep the likeliest until they cover p
    kept.add(i);
    running += chances[i];
    if (running >= p) break;
  }
  return chances.map((c, i) => (kept.has(i) ? c / running : 0));
}
def top_p(chances, p):
    order = sorted(range(len(chances)), key=lambda i: -chances[i])
    kept, running = set(), 0.0
    for i in order:  # keep the likeliest until they cover p
        kept.add(i)
        running += chances[i]
        if running >= p:
            break
    return [c / running if i in kept else 0.0 for i, c in enumerate(chances)]

Temperature and a cutoff do different jobs, and many systems let you set both. Temperature controls how strongly the leaders are favoured, and top-k or top-p controls how far down the list the sampler is allowed to reach. Providers usually advise changing one of them and leaving the other at its default, because adjusting both at once makes it hard to tell which one caused a change in the output. When both are applied, the usual order is temperature first, then the top-k or top-p cutoff on the reshaped probabilities, so a higher temperature makes a top-p cutoff keep more tokens. Setting top-k to 1 is the same as greedy decoding.

Many APIs also offer repetition controls, usually called frequency or presence penalties. They lower the score of tokens that have already appeared in the output, which pushes the model away from repeating itself without making the rest of the text more random. They are the better tool when the problem is repetition, because raising the temperature to fix repetition also raises the chance of errors elsewhere.

SettingWhat it changesTypical use
Greedy (temperature 0)Always takes the most likely token.Extraction, classification, structured output.
TemperatureHow strongly the most likely tokens are favoured.The main control for predictable versus varied text.
Top-kKeeps a fixed number of candidates.A simple cap on the tail.
Top-pKeeps as many candidates as it takes to cover probability p.A cap on the tail that adapts to how sure the model is.

Pitfalls

Temperature 0 is not always repeatable

Greedy decoding removes the random draw, so the output is usually the same on every run. It is not guaranteed, because the scores are computed with floating-point arithmetic, and small differences in how the work is split across hardware can change a score slightly. If two tokens were nearly tied, that can flip the choice, and the text diverges from that point on. If your application needs an exact repeat, store the first output instead of regenerating it, and check whether your provider offers a seed option, remembering that even a seed is usually documented as best effort.

Raising temperature does not make the model more creative or smarter

Temperature adds no knowledge or ability. It only gives less likely tokens a larger share, and past a moderate value most of those tokens are simply worse choices. If you want varied ideas, ask for them directly, for example "give me ten options that differ in tone", and keep the temperature moderate. A single response at high temperature tends to be one odd answer, not a set of good ones.

Lowering temperature does not fix wrong answers

If the model's most likely token is wrong, greedy decoding picks that wrong token every time. A low temperature removes random slips, but it cannot supply facts the model does not have. Why Models Hallucinate covers what helps with that.

Low temperature can cause repetition

When the most likely continuation of a phrase is the phrase itself, greedy and very low-temperature decoding can repeat it again and again. A little randomness usually breaks the loop. If you see repetition in long outputs, raise the temperature slightly or use a repetition penalty before changing anything else.

The same number does not mean the same thing everywhere

Providers differ in the allowed range, the default value, and whether top-k or top-p is available at all. A temperature of 0.7 on one service is not guaranteed to behave like 0.7 on another, so read the documentation of the service you use and test with your own prompts.

Choosing settings in practice

Start from what the task needs. When there is one correct output, such as extracting fields from a document, classifying a message or generating JSON that a program will parse, use a low temperature, because randomness can only add errors. When you want several different good answers, such as names, taglines or story openings, use a moderate temperature of roughly 0.7 to 1 and generate several candidates, since each extra sample costs little. A very high temperature rarely helps.

Many chat products set these values for you and do not show them. In an API, change one setting at a time and compare outputs on a fixed set of test prompts, so you can see what each change did. For machine-readable output, also use the structured-output features described in Structured Output, because a low temperature reduces format errors but does not rule them out.

Try it: Pick the settings

For each task, choose a low temperature (near 0) or a moderate one (around 0.7 to 1), and give a one-sentence reason.

Show a sample answer
  1. Low. Each invoice has one correct answer, so randomness can only add errors.
  2. Moderate. You want variety, and near 0 many of the names would be small variations of the most likely one.
  3. Low. The format is strict, and one unlikely token can break the JSON.
  4. Moderate. Different openings are the goal, and you can also run the request several times to get more options.

The rule of thumb is to go low when there is one correct output, and to go moderate and generate several candidates when you want options to choose from.

Quick check

The probabilities are [0.5, 0.3, 0.2] and the random number is r = 0.85. Which token is picked?

What happens to the probabilities when the temperature goes from 1 to 2?

With top-p = 0.8 and probabilities [0.6, 0.25, 0.1, 0.05], which tokens are kept?

A pipeline sets temperature to 0 and still sometimes gets different outputs for the same prompt. What is the most likely reason?

What to practise next

Write the temperature step yourself in Storyteller Word Odds. Then read Why Models Hallucinate to see why a model can be fluent and wrong at the same time.