Sampling, Temperature and Determinism
How the model turns probabilities into text, and how temperature and related knobs trade creativity for consistency.
Beginner · about 3 hours · difficulty 2/5
Learn first: Transformers and Attention, Intuitively
At each step the model outputs a probability for every token in its vocabulary. Decoding is how you choose one.
The main knobs
- Temperature: scales the distribution. Low values (near 0) make the most likely token win almost every time, good for extraction and classification. Higher values spread probability out, good for brainstorming and creative writing.
- Top-p (nucleus sampling): only sample from the smallest set of tokens whose probabilities sum to p.
- Top-k: only sample from the k most likely tokens.
- Max tokens: a hard cap on output length. If a response stops mid-sentence, check the stop reason; it probably hit this limit.
- Stop sequences: strings that end generation early.
Determinism is not guaranteed
Even at temperature 0, hosted models are not perfectly deterministic because of batching and floating point effects on the provider side. Design your system to tolerate variation: validate outputs, and evaluate on many samples instead of one.
Practical defaults
Change one knob at a time, usually temperature. Some reasoning models fix or ignore sampling parameters, so check the provider docs before tuning. Never use temperature as a fix for a bad prompt.
Good enough to move on
You can explain what temperature does to the distribution, pick sensible settings for extraction versus creative tasks, and read the stop reason of a response.
Key concepts
- Temperature
- Top-p and top-k
- Max tokens and stop reasons
- Stop sequences
- Greedy vs sampling vs beam search
- Logprobs: Useful for confidence signals
Mini project
Generate 10 completions of the same prompt at three temperatures, measure how many distinct answers you get, and chart the results.
Check yourself
Your classification pipeline returns different labels for the same input across runs. Name two causes and two mitigations.
Free resources
- How to generate text: decoding methods (Hugging Face)
- Anthropic documentation (Anthropic)