Decoding & sampling (temperature, top-p)

In one sentence

The model scores every token; decoding picks one. Use low temperature for facts, code and tool calls, higher temperature with top-p or min-p for variety. Even temperature 0 isn't bit-for-bit reproducible.

Analogy: A radio DJ picking the next song: greedy always plays the #1 hit, temperature sets how often a deep cut sneaks in, and top-p only allows the songs that together make up 90% of requests.

Every generated token goes through this loop; sampling settings only reshape the distribution before the pick.

How it works

  • Softmax turns the logits into probabilities over the whole vocabulary (~128k tokens for Llama 3).
  • Temperature divides logits by T: below 1 sharpens the distribution, above 1 flattens it, near 0 becomes greedy.
  • Top-p keeps the smallest set summing to p, so the pool shrinks when the model is confident.
  • Min-p keeps tokens with at least min_p × the top token's probability, staying coherent at high temperature.
  • Batch size changes kernel reduction order, so T=0 logits depend on who else shares the batch.

Check yourself

Answer to mark it learned; your answers aren't scored.

An invoice-extraction pipeline runs at the API's default temperature 1 and a few percent of outputs are broken JSON. A teammate wants to switch to a bigger model. What do you do first?

Go deeper

Sampling playground Interactive lab
Full explanation

Decoding is how a model turns its output into text, one token at a time. At each step the model emits a logit (raw score) for every token in its vocabulary (~128k for Llama 3); softmax turns them into probabilities, and a decoding strategy picks one.

  • Greedy: always take the top token. Deterministic in theory, repetitive on open-ended text.
  • Temperature divides the logits by T before softmax. T < 1 sharpens the distribution, T > 1 flattens it; T → 0 becomes greedy.
  • Top-k keeps only the k most likely tokens.
  • Top-p (nucleus) keeps the smallest set whose probabilities sum to p (e.g. 0.9), so the pool shrinks when the model is confident and widens when it isn't.
  • Min-p keeps tokens with at least min_p × p(top token); it stays coherent at high temperatures.

Temperature 0 is not fully deterministic. Floating-point addition isn't associative, and inference kernels change their reduction order with batch size, so your logits depend on who else is in the batch. MoE routing can depend on the batch too, and near-ties flip the argmax. Treat outputs as a distribution and design for Non-determinism: pass@k & variance.

Code What temperature, top-p and min-p do to a softmax
pythonWhat temperature, top-p and min-p do to a softmax
import numpy as np

logits = np.array([4.0, 3.0, 2.0, 0.5])  # raw scores for 4 candidate tokens

def softmax(x, T=1.0):
    z = x / T                    # temperature rescales the logits
    p = np.exp(z - z.max())      # subtract max for numerical stability
    return p / p.sum()

for T in (0.2, 0.7, 1.0, 1.5):
    print(T, softmax(logits, T).round(3))
# 0.2 [0.993 0.007 0.    0.   ]   <- practically greedy
# 0.7 [0.767 0.184 0.044 0.005]
# 1.0 [0.652 0.24  0.088 0.02 ]   <- the model's own distribution
# 1.5 [0.534 0.274 0.141 0.052]   <- the tail gains mass

def nucleus(p, top_p=0.9):       # smallest set with mass >= top_p
    order = np.argsort(p)[::-1]
    keep = order[: np.searchsorted(np.cumsum(p[order]), top_p) + 1]
    q = np.zeros_like(p)
    q[keep] = p[keep]
    return q / q.sum()

def min_p_filter(p, min_p=0.1):  # cutoff scales with the top token's prob
    q = np.where(p >= min_p * p.max(), p, 0.0)
    return q / q.sum()

rng = np.random.default_rng(42)  # seeded: reproducible on one machine
p = nucleus(softmax(logits, T=0.7))
token = rng.choice(len(p), p=p)  # sample from the truncated distribution
greedy = int(np.argmax(logits))  # what "temperature 0" means in practice
Real example

Logits [4.0, 3.0, 2.0, 0.5]: at T=1 the top token gets 65%; at T=0.2 it gets 99.3% (practically greedy); at T=1.5 it drops to 53% and the weakest token climbs from 2% to 5%. In one product that becomes three settings:

  • Ticket classifier and JSON extraction: T=0 plus Structured outputs & JSON mode; you want the same label every run.
  • Marketing-copy brainstorm: T≈0.9, top_p=0.95; you want five different drafts.
  • Self-consistency & best-of-N vote on a math question: 5 samples at T≈0.7, then majority; diversity is the point.
Trade-offs +3 · −3

+ You gain

  • One knob trades consistency for diversity, with no retraining.
  • Truncation (top-p, min-p) cuts the low-probability tail where nonsense tokens live.
  • Sampling several times at T>0 enables self-consistency, best-of-n and diverse synthetic data.

− You pay

  • Higher temperature raises the odds of off-path tokens: broken formats and made-up details.
  • Greedy or T=0 on open-ended text tends to loop and repeat itself.
  • Settings don't transfer: T=0.7 means different things across models, and some reasoning APIs don't let you set it.

Use it when

Low (0–0.3): extraction, classification, code, tool calls, evals. Higher (0.7–1.0) with top-p 0.9–0.95 or min-p ~0.05–0.1: brainstorming, creative writing, diverse samples for voting or synthetic data.

Avoid it when

Don't raise temperature to fix bland answers; fix the prompt. Don't rely on T=0 for reproducibility, audits or cache keys; store the outputs. Don't tune temperature and top-p at the same time.

Numbers to know 4
  • OpenAI API temperature 0–2 (default 1). Anthropic: 0–1 on older Claude models; Opus 4.7/4.8, Sonnet 5 and Haiku 5.5 reject non-default temperature, top_p and top_k with a 400 (release notes, May–Oct 2026).
  • Common truncation settings: top_p 0.9–0.95; min_p 0.05–0.1.
  • Thinking Machines: 1,000 runs of one prompt at T=0 on Qwen3-235B gave 80 distinct completions; batch-invariant kernels made them identical.
  • Vocabulary scored at every step: ~128k tokens (Llama 3) to ~200k (OpenAI o200k).
Common pitfalls 4
  • Assuming T=0 means identical outputs, then building caching, tests or audits on that.
  • Tuning temperature and top_p together; providers recommend changing one, not both.
  • Running JSON or code generation at T≈1 and blaming the model for broken syntax.
  • Comparing models in an eval at different sampling settings and reading the gap as model quality.
Interview questions 2

Answer out loud first, then reveal.

Why can the same prompt at temperature 0 give different answers?Show answer

Because temperature 0 only means argmax; the logits themselves aren't bit-stable. Floating-point addition isn't associative, and servers choose kernels and reduction orders by batch size, so my request's numbers depend on what else is batched with it. When two tokens are nearly tied, a tiny difference flips the pick and the rest of the text diverges. MoE routing and silent model updates add more. So I store outputs I must reproduce, evaluate over several runs, and pay for batch-invariant kernels only if bitwise determinism is a real requirement.

What sampling settings would you pick for a tool-calling agent versus a copywriting feature?Show answer

For tool calls and extraction I want the mode of the distribution: temperature 0–0.2, plus structured outputs or constrained decoding so the format can't break; variety there is just risk. For copywriting I want diversity without the junk tail: temperature ~0.8–1.0 with top-p 0.95 or min-p 0.05, generating several candidates and ranking them. In both cases I pin the settings per feature in config, version them with the prompt, and run evals with exactly the production settings.