Topic 27 of 62 · Generating and serving
Temperature, top-k, and top-p
EasyHow do temperature, top-k, and nucleus (top-p) sampling reshape the next-token distribution?
1 · Start with the intuition
At each decode step, the model outputs a vector of raw logits z over the vocabulary V. Sampling strategies control the trade-off between coherence and diversity when drawing the next token: temperature T rescales the logits (z / T) before softmax to sharpen (T < 1) or flatten (T > 1) the distribution, while top-k and top-p (nucleus) truncate the long tail of low-probability tokens and renormalize the survivors so a million tiny probabilities cannot add up to a nonsensical word choice.
2 · How the mechanism works
Mechanism step 1 of 3 · no question to answer
Scale logits by temperature T
Compute z′ = z / T (for T > 0); as T → 0⁺, softmax approaches greedy argmax.
Next, we will look at: Truncate the tail (top-k / top-p). Move on when this operation makes sense.
Visualizing the behavior
Logits [2, 1, 0, −1] at three temperatures
DerivedT = 0.5 (sharper)
T = 1.0 (model distribution)
T = 2.0 (flatter)
Top-p = 0.8 on [0.60, 0.25, 0.10, 0.05]
DerivedOriginal distribution
Smallest set reaching 0.8, renormalized
3 · The governing equation
pᵢ(T) = exp(zᵢ / T) / Σⱼ exp(zⱼ / T), T > 0
Top-k set: K_k = { indices of the k largest probabilities }
Top-p set: smallest prefix S_p (sorted p₁ ≥ p₂ ≥ …) such that Σ_{i ∈ S_p} pᵢ ≥ pNotation: Setting T = 0 in an API is a convention for deterministic greedy decoding (argmaxᵢ zᵢ), since dividing by 0 is undefined.
Why prefer top-p over top-k? Because the shape of the next-token distribution changes dramatically from token to token. When the model is almost certain (e.g., completing “San ___” → “Francisco” with p = 0.96), top-k = 50 still forces 49 unlikely tokens into the pool, whereas top-p = 0.90 keeps only “Francisco.” When the model is choosing the opening word of a creative story and 100 words are all plausible, top-k = 5 cuts off 95 good options, whereas top-p = 0.90 automatically expands to include them. Note that when temperature, top-k, and top-p are combined, their exact order of application changes the resulting distribution.
4 · Put concrete numbers on it
Worked numbers (from stated assumptions)5 · Common misconception to avoid
Saying “setting temperature = 0 makes the model factual and eliminates hallucinations,” or thinking that temperature = 0 guarantees bit-identical outputs across different batch sizes on a GPU (where non-associative floating-point reductions in batched kernels can flip close logit ties).
In practice · implementation & engineering rule of thumb
For deterministic evals, use explicit argmax (do_sample=False) rather than small positive temperatures, and keep batch size and tensor-parallel degree fixed when comparing outputs.
def sample_top_p(logits, temp=0.7, top_p=0.9):
probs = F.softmax(logits / temp, dim=-1)
sorted_probs, sorted_idx = torch.sort(probs, descending=True, dim=-1)
cum_probs = torch.cumsum(sorted_probs, dim=-1)
# Remove tokens whose cumulative mass BEFORE including them already reached top_p:
sorted_probs[(cum_probs - sorted_probs) >= top_p] = 0.0
sorted_probs /= sorted_probs.sum(dim=-1, keepdim=True)
next_tok = torch.multinomial(sorted_probs, num_samples=1)
return sorted_idx.gather(-1, next_tok)Go one level deeper
Follow-ups that often come after a correct first answer.
- min-p sampling
- Keep tokens whose probability is at least min_p × p_max. When the model is confident, few tokens survive; when it is uncertain, many do. Hugging Face supports it as min_p, with typical values around 0.01–0.2.
- Why not just beam search
- Beam search approximately maximizes sequence likelihood, which suits constrained tasks such as translation. For open-ended text, high-likelihood search tends to produce bland, repetitive output. Holtzman et al. documented this and introduced nucleus (top-p) sampling in response.
6 · Self-check & interview synthesis
Explain it in your own words first
Before revealing the reference answer, try answering the opening question aloud in four beats: what it is → how the math works → what trade-off it makes → a concrete number or failure mode.
Follow-up question interviewers often ask next
MediumDoes changing the temperature from T = 1.0 to T = 0.2 change which token greedy (argmax) decoding picks?
Show follow-up reasoning
No. Dividing all logits by any positive constant T > 0 is a strictly monotonic transformation, so it preserves the exact ranking of the logits—the maximum logit before scaling is still the maximum logit after scaling.