Sampling and Temperature
How a language model picks each next token from its predicted probabilities. Temperature, top-k and top-p trade predictability for creativity.
Also decoding · temperature · top-k · top-p · nucleus sampling · greedy decoding
The model has a bag of possible next words, with many marbles for likely words and few for unlikely ones. Temperature shakes the bag: low temperature means you almost always grab the most common marble, high temperature gives rare marbles a real chance.
Where it fits
+All relationships as a list
Is a kind of / part of
Siblings
- AI Agents and Tool Use
- BERT
- Direct Preference Optimization
- Embedding
- Fine-Tuning
- Google Translate
- GPT
- Hallucination
- In-Context Learning
- Keyboard Autocomplete
- Large Language Model
- LLM Evaluation and Benchmarks
- Perplexity
- Pretraining
- Prompting
- Retrieval-Augmented Generation
- RLHF
- Scaling Laws
- Tokenization
- Vector Database
- word2vec
Uses / built on
Applies to
Try it
How it works
At every step, a language model outputs a score for each token in its vocabulary. A softmax turns those scores into probabilities. Something then has to choose:
- Greedy: always take the most likely token. Deterministic, but tends to loop and repeat.
- Sampling: draw a token at random according to the probabilities. More natural, but occasionally picks something absurd from the long tail.
The knobs that shape the draw:
- Temperature divides the scores before the softmax. Below 1 sharpens the distribution toward the top choices; above 1 flattens it so unlikely tokens gain probability.
- Top-k keeps only the k most likely tokens and samples among them.
- Top-p (nucleus) keeps the smallest group of top tokens whose probabilities add up to p. When the model is confident, that group is small; when it is unsure, it widens.
So the same model can sound like a careful encyclopedia or a playful storyteller, depending only on how you sample.
The math
With logits and temperature :
As this approaches greedy (argmax); as it approaches uniform.
Everyday use cases
- Case 01
Factual answers and code
Low temperature makes output focused and repeatable.
- Case 02
Brainstorming and fiction
Higher temperature produces more varied, surprising text.
Strengths, weaknesses and when to use it
Strengths
- Lets one model behave conservatively or creatively without retraining.
Weaknesses
- Too high and the text becomes incoherent; too low and it gets repetitive.
When to use itTune it per task. Most APIs expose temperature and top-p.
Check yourself
- Q01
What does temperature 0 (or near 0) do?
Show answer
A: Always picks the most likely token
- Q02
What does top-p = 0.9 keep?
Show answer
B: The smallest set of most likely tokens whose probabilities add up to at least 90%