Unit 4 · Inference and Interaction
Lesson 13 · Available to read
How Generation Works: Sampling, Temperature and Decoding
The generation loop in detail: logits, greedy decoding, temperature, top-k and top-p sampling.
At every step an LLM outputs logits — one raw score per vocabulary token — which softmax turns into probabilities (Lesson 4). But a distribution isn't text. Something has to choose a token, append it, and run the model again. That something is the decoding strategy, and its settings — temperature, top-p and friends — are the knobs you see in every LLM API.
Greedy decoding
The simplest strategy: always pick the single most probable token (the argmax).
- Pros: deterministic, fast, good for short factual answers or classification.
- Cons: it can get stuck in repetitive loops ("I think that I think that…"), and the locally best token isn't always part of the best overall answer. Text tends to be bland.
Beam search
Beam search keeps the k most probable partial sequences ("beams") at each step and extends each one, finally returning the sequence with the highest total probability. It works well when there is one right answer, like machine translation. For open-ended writing it tends to produce generic, repetitive text — high-probability text is not the same as interesting or human-like text — so chat models mostly use sampling instead.
Sampling
Sampling draws the next token at random according to its probability: a token with probability 0.3 is chosen 30% of the time. This produces varied, natural text — but sampling from the full distribution occasionally picks something from the long tail of unlikely tokens, and one bad token can derail everything after it. The following controls tame that.
Temperature
Temperature T divides the logits before softmax:
p = softmax(z / T)
- T < 1 sharpens the distribution: likely tokens become even likelier.
- T = 1 leaves it unchanged.
- T > 1 flattens it: unlikely tokens get more chance.
- T → 0 approaches greedy decoding.
Example with logits (2, 1, 0):
- T = 0.5 → logits (4, 2, 0) → probabilities ≈ (0.87, 0.12, 0.02)
- T = 1 → ≈ (0.67, 0.24, 0.09)
- T = 2 → logits (1, 0.5, 0) → ≈ (0.51, 0.31, 0.19)
Top-k and top-p (nucleus) sampling
These methods cut off the tail before sampling, then renormalise what's left:
- Top-k keeps only the k most likely tokens (e.g. k = 40). Simple, but a fixed k is too many when the model is confident and too few when many continuations are reasonable.
- Top-p, also called nucleus sampling, keeps the smallest set of tokens whose probabilities add up to at least p (e.g. p = 0.9). When the model is confident, the nucleus might be one or two tokens; when it's uncertain, it widens automatically.
Worked example: sorted probabilities (0.5, 0.2, 0.15, 0.1, 0.05) with p = 0.8. Cumulative sums: 0.5, 0.7, 0.85 — so we keep the first three tokens. Renormalising by 0.85 gives (0.59, 0.24, 0.18), and we sample from those.
Variants such as min-p (keep tokens with at least some fraction of the top token's probability) follow the same idea. Temperature and top-p are often combined; many providers recommend adjusting one rather than both.
Other controls
- Max tokens — a hard cap on output length.
- Stop sequences — strings that end generation when produced (for example, the start of a new user turn).
- End-of-sequence token — the model itself signals it's done.
- Repetition, frequency and presence penalties — lower the logits of tokens that have already appeared, to reduce loops.
- Constrained / structured decoding — mask the logits of any token that would break a required format, such as a JSON schema or a grammar, so the output is guaranteed to parse.
- Seeds — fix the random number generator for reproducibility. Even then, results may differ slightly across hardware or when requests are batched differently, so don't rely on bit-for-bit determinism.
Choosing settings
- Factual Q&A, extraction, code: low temperature (0–0.3) for consistency.
- General chat: moderate settings (around T = 0.7, top-p = 0.9 is a common default).
- Brainstorming and fiction: higher temperature for variety — but too high and the text becomes incoherent.
- Self-consistency: for reasoning problems, sample several answers at moderate temperature and take the majority vote — diversity can improve accuracy.
Remember that decoding can only choose among what the model considers plausible. It can make outputs safer, more varied or more consistent, but it can't add knowledge the model doesn't have.
The takeaway
The model only produces a distribution; the decoding strategy chooses the token. Greedy is deterministic but dull, temperature sharpens or flattens the distribution, top-k/top-p trim the unreliable tail, and stop rules, penalties and constraints shape the final output.
Practice
0 of 7 attempted
- 1Calculate
Logits for three tokens are (1, 0, −1). Compute the probabilities at temperature T = 1 and T = 0.5.
Saved in this browser
- 2Calculate
Sorted token probabilities are (0.35, 0.25, 0.15, 0.10, 0.08, 0.07). Which tokens does top-p sampling keep with p = 0.7, and what are their renormalised probabilities?
Saved in this browser
- 3Explain in your own words
Why does top-p adapt better than top-k to how confident the model is?
Saved in this browser
- 4Multiple choice
What happens as temperature approaches 0?
- 5Explain in your own words
Why do chat models usually use sampling rather than beam search?
Saved in this browser
- 6Apply
Choose decoding settings (temperature, top-p, other controls) for each case and justify briefly: (a) extracting invoice fields to JSON, (b) a customer-support chatbot, (c) generating 20 diverse product-name ideas.
Saved in this browser
- 7Recall
List four ways generation can stop.
Saved in this browser