Temperature & Sampling
Turning probabilities into choices
Sampling settings shape the probability distribution — temperature flattens or sharpens it, top-p and top-k cut the tail. Deterministic tasks want low variance; creative tasks want room to roam.
What you will learn
- Explain temperature and top-p/top-k behavior
- Choose settings per task type
- Implement basic sampling in a few lines
What is this?
After the model outputs a probability distribution over tokens, sampling converts it into a concrete token. Temperature scales logits (higher = flatter/random, lower = sharper/deterministic); top-p keeps the minimal set of tokens covering probability p; top-k keeps the k highest. All three tune the same dial from 'safest' to 'wildest'.
Why do you need it?
- Factual/code tasks collapse at high temperature — plausible-but-wrong takes over.
- Creative writing and brainstorming collapse at zero temperature — endless repeats.
- Top-p prunes absurd tails while keeping some freedom (vs naked temperature).
- Determinism is expensive; when you need reproducibility, control sampling explicitly.
Mental model
A dimmer switch on the imagination
Sampling settings
Lowest dim = press the most-probable word every time (flat, safe prose). Highest dim = every word from a fevered turn (chaos). Top-p is a 'reasonable word filter' that keeps dimming meaningful but refuses nonsense.
How it works
- Temperature: divide logits by T, then softmax. T=0 → argmax (greedy); T>1 → increasingly uniform.
- Top-p: sort tokens by probability descending; keep the set whose cumulative probability reaches p; renormalize.
- Top-k: keep only the k highest-probability tokens; renormalize.
- T0 + top-p combined = quality-focused but not brittle.
- Defaults from most platforms are the sweet spot until a task tells you otherwise.
Sampling choices on one distribution.
Examples
Temperature math in plain Python
import math, random logits = [0.1, 2.0, 0.9, 0.4] def softmax(v): e = [math.exp(x - max(v)) for x in v] s = sum(e) return [x/s for x in e] print('T=0.5 (sharp) :', softmax([x/0.5 for x in logits]))print('T=1.0 (normal):', softmax([x/1.0 for x in logits]))print('T=2.0 (flat) :', softmax([x/2.0 for x in logits]))Higher temperature compresses differences until the bag equals chance; lower temperature sharpens the leader.
In production
- Code generation uses low temperature (near 0) — determinism beats creativity.
- Summarization prefers low temperature for consistency of facts.
- Naming/product brainstorming runs high temperature + top-p tail filtering.
- A/B loggers capture parameters so sample behavior isn't mysterious later.
Best practices
- Pick settings per request type, not globally.
- Never tune blindly; run the same prompts at a couple of settings on a small eval set.
- Document parameters in production logs.
- For reproducibility, seed + low temperature, and acknowledge residual variance.
Common mistakes
- Zero temperature as 'guaranteed determinism' for all tasks — it still varies by batch/knightess and platform.
- Temperature-only with no top-p invites rare nonsensical tokens.
- Set high temperature on accounting-style writing and paying for it later.
Common issues
Repetitive degenerate output at low temperatureGreedy decoding circling on a local pattern
Slight temperature (0.3) + top-p, add repetition penalty if available.
Same prompt, two answers not matchingSampling implies variance; no seed used
Use seed/reproducible params for tests; log params; accept variance in prod.
Debugging tips
- Creative tasks output bland repeats → raise temperature/top-p with discrimination.
- Factual tasks invent creative-look info → drop temperature toward 0..0.2.
- Outputs vary wildly at the same parameters across platforms → log the effective model + params.
Interview checkpoint
Hands-on lab
- Implement softmax with a temperature parameter
- Show that lower temperature sharpens and higher flattens
- Compare greedy picks and probability mass across temperatures
Temperature Shapes the Sampling Distribution
25 min · intermediate
Quick quiz
Which setting is the closest thing to deterministic decoding?
Top-p caps the cumulative probability mass of candidate tokens.