Decoding and sampling
From a probability distribution to the next token — every knob explained
A language model outputs a distribution over the vocabulary; decoding decides what to do with it. The same model can be repetitive or creative, deterministic or diverse, valid JSON or a mess, purely because of temperature, top-p and constraints. These settings are the last thing between the model and the user, they interact with prompting (8.4 Prompting as programming) and inference cost (7.10 Efficient inference: KV cache, GQA, FlashAttention, speculative decoding, quantization), and constrained decoding is what makes structured outputs and tool calls reliable (9.6 Generation side: context assembly, citations, structured outputs and tool calling, 10.2 Tool use and function calling).
You'll be able to
- Write the softmax-with-temperature formula and compute how temperature reshapes a distribution
- Explain greedy, beam, top-k, top-p and min-p sampling and when each is appropriate
- Describe repetition penalties, stop sequences, logit bias and grammar-constrained decoding
- Choose decoding settings for code, chat, extraction and creative tasks
- Explain why 'temperature 0' is not perfectly deterministic in practice
Key ideas
- Decoding chooses a token from softmax(z/T); temperature rescales sharpness without changing the ranking.
- Greedy and beam search favor probable sequences and loop or go bland in open-ended text; beam suits translation-like tasks.
- Top-k keeps k tokens; top-p keeps the smallest set with cumulative probability ≥ p and adapts to confidence; min-p scales with the top probability.
Show 4 more key ideas
- Repetition/frequency/presence penalties, no-repeat n-grams, stop sequences and logit bias give fine control — strong penalties break code.
- Grammar-constrained decoding masks invalid tokens each step, guaranteeing schema-valid JSON — the basis of structured outputs and tool calling.
- Temperature 0 is only approximately deterministic on batched GPU hardware; reasoning models prefer default sampling plus a thinking budget.
- Speculative decoding speeds generation without changing the output distribution.
Suggested path through this lesson
Logits → probabilities → one token
At each step the model produces logits over the vocabulary. Softmax turns them into probabilities, we pick a token, append it, and run the next forward pass (cheaply, thanks to the KV cache — 7.10 Efficient inference: KV cache, GQA, FlashAttention, speculative decoding, quantization) until an end-of-sequence token or a length limit. Decoding strategies differ only in how we pick.
Greedy and beam search
Greedy decoding takes every step. It is fast and fine for short, factual outputs and classification, but for open-ended text it produces loops ("I think that I think that…") and bland phrasing — the most probable next token repeatedly is not the most probable sequence, and not what humans write. Beam search keeps the best partial sequences by cumulative log-probability (with length normalization so short outputs are not favored). It shines in encoder–decoder tasks with a narrow correct answer — translation, speech recognition (7.7 Encoder–decoder: T5, BART and choosing an architecture) — and is rarely used for chat, where it amplifies repetition and genericness.
Temperature
Divide the logits by a temperature before the softmax:
recovers greedy decoding; samples from the model's own distribution; flattens it, raising the entropy (1.9 Information theory: entropy, cross-entropy and KL divergence) and the chance of unlikely tokens. Temperature never reorders tokens — it only changes how peaked the distribution is.
Math check. Three logits . At : , sum , so . At the logits become : . At they become : . Same ranking, very different sharpness.
Truncation: top-k, top-p, min-p
Sampling from the full distribution occasionally picks a token from the long, low-probability tail — the source of many nonsense outputs. Truncation methods cut the tail, then renormalize:
- Top-k keeps the most probable tokens. Simple, but a fixed is too many when the model is confident and too few when it is not.
- Top-p (nucleus) keeps the smallest set of tokens whose cumulative probability reaches (e.g. 0.9). The set adapts: one token when the model is sure, dozens when it is uncertain.
- Min-p keeps tokens with , scaling the cutoff with the model's confidence; it behaves well at high temperatures.
Implementations usually apply temperature first, then top-k, then top-p. Typical chat settings are with top-p –; for extraction or code, .
Penalties, stops and biases
- Repetition penalty: divide the logits of already-generated tokens by (or subtract a constant); frequency/presence penalties subtract and . Mild values reduce loops; strong values forbid legitimate repeats (code!).
- No-repeat n-gram blocking: ban any -gram that already occurred.
- Stop sequences end generation when a string appears (e.g. a closing tag); max tokens caps length.
- Logit bias: add a constant to chosen tokens' logits to encourage or forbid them (e.g. force a yes/no answer).
Constrained (grammar-guided) decoding
To guarantee valid JSON matching a schema, compute at each step the set of tokens that keep the output consistent with a grammar or finite-state machine compiled from the schema, and mask everything else (set their logits to ) before sampling. Libraries such as Outlines, llguidance and the guided-decoding modes of vLLM implement this; provider APIs expose it as structured outputs. The model still chooses content; the grammar guarantees form. This is the backbone of reliable tool calling (10.2 Tool use and function calling) and structured extraction (9.6 Generation side: context assembly, citations, structured outputs and tool calling).
Determinism, seeds and reasoning models
Sampling with a fixed seed is reproducible in principle, but batched GPU kernels are not bit-exact across batch compositions and hardware, so even can produce different outputs across calls — "temperature 0" means mostly deterministic. Providers of reasoning models (8.6 Reasoning models and test-time compute) generally recommend leaving sampling at defaults (, no top-p tweaks): the reasoning trace needs diversity, and the final answer is already filtered by the model's own verification.
Choosing settings
| task | temperature | truncation | other |
|---|---|---|---|
| classification / extraction / code | 0–0.3 | top-p 1.0 or small top-k | constrained decoding, stop sequences |
| assistant chat | 0.7 | top-p 0.9–0.95 | mild repetition penalty if loops appear |
| creative writing, brainstorming | 0.9–1.2 | top-p 0.95 or min-p 0.05 | sample several candidates |
| self-consistency voting (8.4 Prompting as programming) | 0.7–1.0 | top-p 0.95 | k samples, majority vote |
| reasoning models | provider default | default | control the thinking budget instead |
Speed tricks such as speculative decoding (7.10 Efficient inference: KV cache, GQA, FlashAttention, speculative decoding, quantization) draft tokens with a small model and verify them with the large one without changing the sampling distribution — decoding settings and inference optimization are separate concerns.
import torch
def sample_next(logits, temperature=1.0, top_k=0, top_p=1.0):
if temperature <= 0:
return int(torch.argmax(logits))
logits = logits / temperature
if top_k > 0:
kth = torch.topk(logits, top_k).values[-1]
logits = torch.where(logits < kth, torch.full_like(logits, -float("inf")), logits)
probs = torch.softmax(logits, dim=-1)
if top_p < 1.0:
sorted_p, idx = torch.sort(probs, descending=True)
cum = torch.cumsum(sorted_p, dim=-1)
cut = cum - sorted_p > top_p # tokens after the nucleus
sorted_p[cut] = 0.0
probs = torch.zeros_like(probs).scatter(0, idx, sorted_p)
probs = probs / probs.sum()
return int(torch.multinomial(probs, 1))
Where this shows up later
- Constrained decoding underlies structured outputs and tool calls — 9.6 Generation side: context assembly, citations, structured outputs and tool calling, 10.2 Tool use and function calling.
- Reasoning models shift control from sampling knobs to thinking budgets — 8.6 Reasoning models and test-time compute.
- Decoding is where inference cost is paid token by token — 7.10 Efficient inference: KV cache, GQA, FlashAttention, speculative decoding, quantization; evaluation must fix decoding settings to be reproducible — 8.7 Evaluating LLMs.
Common pitfalls (4)
- Setting a strong repetition penalty for code generation, which punishes necessary repeated identifiers and brackets.
- Using top-k = 1 or temperature 0 for creative tasks and reporting that the model is 'boring'.
- Expecting bit-identical outputs at temperature 0 across API calls.
- Parsing free-form text for JSON instead of using structured outputs or constrained decoding.
Recap: all 7 key points
- Decoding chooses a token from softmax(z/T); temperature rescales sharpness without changing the ranking.
- Greedy and beam search favor probable sequences and loop or go bland in open-ended text; beam suits translation-like tasks.
- Top-k keeps k tokens; top-p keeps the smallest set with cumulative probability ≥ p and adapts to confidence; min-p scales with the top probability.
- Repetition/frequency/presence penalties, no-repeat n-grams, stop sequences and logit bias give fine control — strong penalties break code.
- Grammar-constrained decoding masks invalid tokens each step, guaranteeing schema-valid JSON — the basis of structured outputs and tool calling.
- Temperature 0 is only approximately deterministic on batched GPU hardware; reasoning models prefer default sampling plus a thinking budget.
- Speculative decoding speeds generation without changing the output distribution.
Watch
The last section visualizes softmax with temperature on real next-token distributions.
Read
Try it live
Interactive demo
runs in your browserExercises
- Temperature by hand
For logits compute the softmax at and the entropy of each distribution in bits. Expected: entropy increases monotonically with and approaches bits.
- Implement the sampler
Implement
sample_nextas in the notes plus min-p. Feed it a fixed toy distribution 10,000 times for each setting and plot the empirical token frequencies. Expected: top-p removes exactly the tail tokens beyond the nucleus; min-p's cutoff moves with temperature. - Degeneration experiment
With a small open model, generate 200 tokens from the same prompt using greedy, beam (B=4), and nucleus sampling (, ). Measure the fraction of repeated 4-grams. Expected: greedy and beam repeat far more than nucleus sampling.
- Constrained JSON
Define a JSON schema for a product record and use a provider's structured-output mode or Outlines to generate 50 records from noisy descriptions. Count schema violations. Expected: zero violations with constraints versus several without.
Quiz
Flashcards
These cards are now in your spaced-repetition queue. Review all due cards →