A model only scores every token in its vocabulary; a separate rule, the decoder, edits those scores, reshapes them, cuts the unlikely tail and picks one token, and which tokens survive that rule decides whether the same model writes loops, sensible prose, noise or valid JSON.
Fig. 1 is one real next-token distribution through the decoder, 151,936 scores in and one token out: Qwen2.5-0.5B-Instruct writing the opening of a lighthouse story, second token (after "The") measured here (src/reading_numbers.mjs).
You need: logits and softmax (assumed), and what a token is (Tokenizers), which matters for constrained decoding. Where the sampler runs inside a serving engine's step is on vLLM: inside the default engine.
Numbers are published, with the source linked, unless marked derived (formula shown), measured here (computed offline on a small open model, scripts in the page source) or unconfirmed. Training draws from the same stack for RL rollouts and rejection sampling (Topic: llm-training-and-post-training).
The formula behind steps 1 to 3: one forward pass ends in a vector of logits z, one per vocabulary entry (151,936 for Qwen2.5-0.5B-Instruct, 50,257 for GPT-2), and the softmax with temperature turns them into probabilities:
Decoders fall into two families: search is deterministic and looks for a high-probability sequence (greedy, beam); sampling draws at random from a reshaped distribution. Constraints sit before either, as a logit processor.
Greedy decoding takes the argmax token at every step: what temperature 0 means. It is locally optimal and, for open-ended text, repetitive and dull. Beam search keeps the B highest-probability partial sequences: each is extended by its best next tokens, all candidates are scored by total log-probability, and the top B survive. Beam search is the standard for machine translation and summarisation, where outputs are short and closed-ended; chat LLMs essentially do not use it, and greedy is fine only for short factual answers.
In Fig. 2 both run on GPT-2 small continuing a sentence from Jerome K. Jerome's Three Men in a Boat (1889); every score is the model's own log-probability measured here. Each column is one step; a box's height is its sequence's total log-probability (taller is more probable), and faded boxes are hypotheses the decoder dropped.
Try: step to 4 in beam mode. Greedy's "was very" is still a candidate but scores below three other branches, so beam search drops it. After six tokens the best beam is 6.7 times more probable than greedy's text measured here (exp(−7.54 + 9.44); recompute.py).
More probable is not better. Run both for 80 tokens on the same prompt measured here: both searches fall into a loop the model rates as highly probable; the sample wanders but does not repeat.
Holtzman et al. named this: "using likelihood as a decoding objective leads to text that is bland and strangely repetitive", and natural text's per-token probability is "on average, much lower than text generated by beam search" (§4.3). On 5,000 WebText continuations with GPT-2 Large (762M) they measured perplexity 12.38 for human text against 1.50 for greedy and 1.48 for beam search with 16 beams, and 73.66% of greedy texts repeating (Table 1, Holtzman et al., 2019). Section 3 reruns that comparison on twelve decoders.
The top 12 of 151,936 tokens are drawn; the last row is every other token together. Grey bar: probability before the cut; blue bar: after. Counts include the tail, computed from a binned summary of all 151,936 logits and checked against the exact count in recompute.py (6,102 against an exact 6,099 kept tokens at T 1.5) measured here.
Pure sampling at T = 1 lets the long tail in, and a few bad draws derail the text (Holtzman et al. measured perplexity 22.73 for pure sampling against 12.38 for human text). So the stack reshapes first: temperature, then truncation, then renormalise, then sample.
The before/after runs the same real distribution through top-p, the method min-p was proposed to replace, and through min-p: an uncertain step (the lighthouse story of the hero, top token 22%) and a confident one (after "The capital of Australia is", "Canberra" 96%).
Try: the uncertain step at T 2: top-p keeps about 35,700 tokens and min-p 46. That is the whole argument for min-p, on a real distribution.
Hugging Face transformers applies its warpers as temperature, top-k, top-p, min-p, typical; vLLM as penalties, temperature, min-p, then top-k and top-p. llama.cpp applies temperature last by default (penalties, DRY, top-n-sigma, top-k, typical, top-p, min-p, XTC, temperature), so its truncation sees the T = 1 distribution. With llama.cpp's defaults (top-k 40, top-p 0.95, min-p 0.05) at T 1.5, the uncertain step keeps 14 tokens with temperature last and 34 with temperature first measured here. The Sampler lab has the switch, every knob on this page and 32 real distributions.
| Sampler | Rule | Source |
|---|---|---|
| Typical sampling | Keep the tokens whose surprisal −log p is closest to the distribution's entropy, until their mass reaches typical_p ("entropy-relative"). At 0.5 it drops the single most likely token on four of the five uncertain steps tried in the lab (Lighthouse 1 and 2, Kitten 1 and 3), because its surprisal is far below the entropy measured here. | Meister et al., 2022; in the lab |
| Mirostat | Adjust a top-k-like cut on the fly so that the text's surprise stays near a target (τ = 5 by default in llama.cpp) | Basu et al., 2020 |
| Top-a | Keep tokens above a threshold proportional to the square of the top probability | local-model community; origin unconfirmed |
| XTC (exclude top choices) | With some probability, remove every token above a threshold except the least likely of them: cuts the most likely tokens, not the least, to break clichés | p-e-w, text-generation-webui PR 6335 (2024) |
| DRY (don't repeat yourself) | Penalise a token that would extend a sequence already in the context, by multiplier × base(length − allowed length) (base 1.75, allowed length 2 in llama.cpp) | llama.cpp common.h |
Most are niche, from the local-model community. Mirostat and DRY act on a generated sequence rather than one distribution, so the lab leaves them out.
Every truncation trades diversity for staying in the model's high-probability region, and human text sits in between. GPT-2 small (124M) is given the first 48 tokens of four paragraphs of Three Men in a Boat and writes 48 more, 16 times per decoder; the book's real next 48 tokens are the human reference measured here.
Defaults reproduce the ordering of Holtzman et al.'s Table 1 independently (GPT-2 small and 4 passages here; GPT-2 Large and 5,000 WebText passages there): search far below human perplexity (greedy 2.26, beam 2.37 against 31.0; theirs 1.50 and 1.48 against 12.38), pure sampling above it (47.2; theirs 22.73) and top-p 0.95 closest (31.6; theirs 13.13). The absolute values do not compare across the two studies: a smaller model is more surprised by everything. Perplexity near human is a necessary condition for human-like text, not a measure of quality.
Perplexity: exp of minus the mean log-probability per token under GPT-2 small at T = 1 (human text is the target, not the minimum). Diversity: distinct-2 over the 16 samples of a passage (greedy and beam give one text 16 times, so their figure is divided by 16). Hover a dot for its decoder; the table in the closed block below has every value.
Repetition: share of a text's 4-grams that repeat an earlier 4-gram.
Every sampled decoder starts from the same random seed, so pure sampling and top-p 0.95 often write the same words until the first draw that top-p's cut removes. Texts are GPT-2's, unedited except that newlines are shown as ↵ and any em-dash the model wrote is shown as "--". Three samples per passage are shown, skipping any that match a short list of slurs, sexual and violent words (GPT-2 at high temperature produces them); the measures use all 16. Em-dashes in Jerome's text were replaced by commas before tokenising. Script: src/make_data.py degen; numbers: src/recompute.py.
Step 2 of Fig. 1 is one interface in every framework: a logit processor takes the tokens so far and the logits, and returns edited logits. In transformers it is LogitsProcessor.__call__(input_ids, scores), and the repetition penalty, no-repeat n-gram, minimum length (suppress the end token) and token bans are all processors applied before the warpers. OpenAI-style APIs and open servers expose the simplest one as logit bias: a value from −100 to 100 added to a token's logit before sampling, where −100 effectively bans it (OpenAI API reference; vLLM's logit_bias and allowed_token_ids in sampling_params.py). A grammar mask (section 5) is a processor that adds −∞.
The repetition controls are processors that use counts of what is already in the context:
no_repeat_ngram_size).Qwen2.5-0.5B-Instruct continuing the pattern "red, blue, red, blue, red," at position 7 of its reply ("red, blue, red,"): the right next token " blue" is already in the context three times (the prompt counts) and was generated once. Repetition penalty 1.3 divides its logit 25.72 by 1.3, so the runner-up " and" (17.59) gains, and " blue" falls from 99.9% to 73.6%; a frequency penalty of 1 subtracts 1 per generated occurrence and barely moves it (99.7%) measured here. Penalties are blunt instruments, needed less as models improved and still useful for small models.
Constrained (or structured) decoding guarantees that the output matches a format, a JSON schema, a regular expression or a context-free grammar, by masking every token that would break it at every step: an engine compiles the constraint to an automaton over the tokenizer's vocabulary, tracks the automaton's state as tokens are emitted, and before the sampler runs sets every disallowed logit to −∞. The running example: Qwen2.5-0.5B-Instruct, greedy, asked to extract {"name": string, "age": integer} from one sentence. Its favourite first token is a Markdown fence, which no JSON parser accepts.
``` (56.9%), then {↵ (35.4%); the other 151,657 tokens hold 1.3% together.{↵ goes from 35.4% to 99.5%, {" from 0.16% to 0.44%.{↵, the model's second choice. The grammar's state moves on, and the next step gets a new mask (Fig. 4 counts them).The model's real probabilities at the first step measured here; the formula, in the same names:
The mask changes size at every step, and that is what makes it expensive or cheap. Inside a string almost anything is allowed; at a structural position only a handful of tokens are.
The constrained run's 19 steps, picked token under each bar. Inside the name about 76,660 of 151,665 tokens are allowed; at structural positions 1 to 17. Orange bars are steps where the allowed tokens held under 5% of the model's probability, so the grammar overruled it: step 2 (0.0004%) and step 10 (2.5%), both whitespace, explained below. At step 13 the model gave 22.6% to a quote, which would have made the age a string; the integer type masked it measured here.
The whole run, without and with the mask, is a widget you step through (24 tokens unconstrained, 19 constrained): the token list shows the model's top 8 at each step with its own probabilities, a tick marking those the grammar allows; in the constrained mode the masked ones are struck out and the picked token is ringed. Same weights, same greedy rule: the unconstrained run writes its fences and fails to parse, the constrained one parses.
Try: step 0 in both modes: the model puts 57% on ```; the constrained run starts with {. Then step 2 of the constrained run: the model wants two spaces of indentation, the toy grammar's whitespace cap forbids the second, and it is forced onto a token it gave 0.0004%. The output is still valid JSON, with one-space indentation.
The request is illustrative (a made-up person); everything else is the model's real output measured here. A tick marks tokens the grammar allows.
The grammar is a regular expression, with whitespace capped at two characters between JSON tokens:
\{[ \n]{0,2}"name"[ \n]{0,2}:[ \n]{0,2}"[A-Za-z .\-]{1,40}"[ \n]{0,2},[ \n]{0,2}"age"[ \n]{0,2}:[ \n]{0,2}(0|[1-9][0-9]{0,2})[ \n]{0,2}\}
At every step each of the 151,665 tokenizer strings was checked with the regex package's partial matching: a token is allowed when the text so far plus the token can still complete a match (src/make_data.py json). That is a brute-force check of the whole vocabulary at every step; the engines below exist to avoid it.
| Engine | Grammar and method | Mask cost and where it runs |
|---|---|---|
| Outlines | Regular expression or JSON schema compiled to a finite-state machine over tokens, with an index of which tokens are allowed in every state: "transitions between the states of a finite-state machine" (Willard and Louf, 2023). The approach that popularised near-zero-overhead structured output. | a lookup per step once the index is built |
| XGrammar | Full context-free grammars with a pushdown automaton. Tokens are split into context-independent ones, whose validity depends only on the automaton's position and is precomputed, and context-dependent ones, checked at runtime against a persistent stack: for Llama-3.1 and a JSON grammar the context-dependent tokens are "less than 1% (1134 out of 128k)", cut to 120 by context expansion (Dong et al.). | under 40 µs per token for JSON schema, overlapped with the GPU's forward pass. Default backend in vLLM (the "auto" backend tries XGrammar first and falls back to llguidance: sampling_params.py), SGLang (serving_hook.py), TensorRT-LLM and MLC-LLM (README); where SGLang calls it in its scheduler, and the jump-forward decoding SGLang removed in v0.4.4, are on SGLang, section 6 |
| llguidance (behind Guidance) | An Earley parser on top of a lexer built from regular-expression derivatives; masks computed lazily by walking a trie of the vocabulary. | about 50 µs per token for a 128k tokenizer. "LLGuidance shipped in OpenAI for JSON Schema"; in llama.cpp, vLLM (from 0.8.2), SGLang (from 0.4.4) and Chromium (README) |
Provider "structured outputs" and strict function calling are this mechanism plus training. OpenAI's Structured Outputs works "by constraining OpenAI models to match developer-supplied schemas and by training our models to better understand complicated schemas"; the schema is converted to a context-free grammar; gpt-4o-2024-08-06 scored 100% on its complex-schema eval against under 40% for gpt-4-0613 (OpenAI, 6 August 2024, archived). JSON mode guarantees valid JSON; only Structured Outputs guarantees schema adherence (docs). Grammar-constrained tool-call parsing is standard in serving stacks.
": closes a key and starts the colon), whitespace rules decide which tokenisations are reachable (steps 2 and 10 above), and an unbounded whitespace rule lets a model emit spaces forever.| Use | Typical setting | Where it comes from |
|---|---|---|
| Chat | T about 0.7 with top-p 0.9 to 0.95, or min-p 0.05 | Rule of thumb from the original page unconfirmed as a standard; close to published defaults: llama.cpp T 0.8, top-k 40, top-p 0.95, min-p 0.05 (common.h); Qwen3 non-thinking T 0.7, top-p 0.8, top-k 20 (card) |
| Reasoning models | T 0.6, top-p 0.95; never greedy | Qwen3 thinking mode: T 0.6, top-p 0.95, top-k 20, min-p 0, "DO NOT use greedy decoding" (endless repetitions, card). DeepSeek-R1: T 0.5 to 0.7, 0.6 recommended, "to prevent endless repetitions or incoherent outputs" (card) |
| Code and maths, one answer | Greedy or near it, T 0 to 0.3 | Codex found the best temperature for pass@1 is 0.2 and for pass@100 is 0.8 (Chen et al., 2021) |
| Evaluations | Fix seeds and settings, or sample k answers and report pass@k or majority vote | DeepSeek-R1 reports pass@1 as the mean over 64 samples at T 0.6, top-p 0.95 (card); majority vote is self-consistency (Wang et al., 2022) |
2023-06-01 any non-default temperature, top_p or top_k "returns a 400 error" (Anthropic, Opus 5.5 migration guide), and API version 2026-10-21 (21 October 2026) removes the three parameters altogether: sending one returns 400 "even at the parameter's default value", and a request samples at the defaults, temperature 1.0. On an older model that still honoured a lowered temperature, such as Sonnet 4.6, the new version loses that effect and "No other setting replaces it"; such a request has to stay on 2023-06-01 (migration guide). OpenAI's reasoning models other than GPT-6 Astra do not support temperature, top_p, presence_penalty, frequency_penalty, logprobs or logit_bias; GPT-6 Astra supports temperature and top_p (Azure OpenAI reasoning docs, 21 September 2026). What stays in the caller's hands on those APIs is the output's shape (structured outputs, section 5) and how much it thinks, not the sampler.Text watermarking is the one technique built on sampling that this page owns. The sampler's random draw is replaced by a choice that a secret key and the preceding tokens decide, so each pick is still drawn from the model's distribution and the text reads the same, but many such picks together carry a statistical signal a key holder can test for. Google DeepMind's SynthID-Text does this with tournament sampling (Dathathri et al., Nature 2024); Claude's watermark, announced 14 August 2026, "is a version of the SynthID-Text approach" and "only changes the source of the randomness used to pick among words" (Anthropic). Its limits follow from the mechanism: few acceptable word choices (code, tightly constrained or factual text) leave little signal, short samples detect poorly, and a complete rewrite removes it; detection is a key holder's API in private preview, not a public detector.
Every sampler from the Reading tab (sections 2 and 4), applied to 32 real next-token distributions: four prompts to Qwen2.5-0.5B-Instruct, eight positions each along the model's own greedy reply. Pick a prompt and a position, move the controls, and see which tokens survive and how likely each becomes. "Draw 200" samples from the result.
Data: Qwen2.5-0.5B-Instruct (Apache 2.0), float32 on CPU, chat template with the default system prompt; logits saved by src/make_data.py. Sampler rules follow transformers (temperature first) and llama.cpp (temperature last). Presets from llama.cpp, Qwen3 and DeepSeek-R1; "Chat rule of thumb" is the original page's.
Rows are the most probable tokens at T = 1, before any penalty (␣ is a space, ↵ a newline). Grey: probability after penalties and temperature, before truncation; blue: final probability; the label names the filter that cut a token; an orange border marks a token already in the context. Penalties use the counts the frameworks use: the repetition penalty counts every token in the context including the chat template and system prompt (as transformers does); presence and frequency count only tokens generated so far (as the OpenAI formula does). Tokens beyond the top 60 are grouped in 0.1-logit bins; counts that include them match the exact full-vocabulary result within 1% (recompute.py --exact). Penalties are not applied to tokens beyond the top 60.
Links open in a new tab, with reading times.
Temperature, top-k, top-p, min-p, typical and the three repetition penalties on 32 real distributions, in either sampler order.
The parent: one request through a serving engine, then a thousand; the sampler is the last step of each forward pass it follows. Reading: 34 min, plus 3 in closed details
Sibling: the acceptance rule that preserves this page's distributions, every kind of drafter, and the batch size where it stops paying. Reading: 36 min, plus 8 in closed details
Sibling: the shared batch that makes temperature 0 unrepeatable on a server. Reading: 37 min, plus 21 in closed details
Sibling: where the sampler and the structured-output mask run in the engine's step. Reading: 41 min, plus 15 in closed details
Where sampling feeds training: RL rollouts, rejection sampling and distillation draw from this stack. Reading: 26 min, plus 22 in closed details
Owns pass@k, majority voting and best-of-n (sections 2 and 3), with a sampling lab. Reading: 35 min, plus 8 in closed details
Best-of-n as an amplifier of reward-model errors. Reading: 33 min, plus 12 in closed details
How sampling feeds training: rollouts for RL, rejection sampling for SFT. Reading: 33 min, plus 4 in closed details
Why token boundaries make grammar masks hard. Reading: 46 min, plus 15 in closed details
Speculative decoding calculator with Gemma 4's drafter; reproduces Leviathan et al.'s Table 4. (calculator 30 min)
The week's DiffusionGemma story: about 1,500 tokens a second on one H100 from 256-token blocks refined in parallel. (animation 21 min)
Decoding a block of tokens in parallel by denoising instead of left to right. (24 min)
The paper's beam search (beam 4, length penalty 0.6) on its translation task. (20 min)
Clear, practical treatment of the standard knobs. (35 min)
The strongest recent addition to the sampler toolbox, by its authors' account. (45 min)
The re-analysis that disputes min-p's evaluation; read with the paper. (30 min)
Holtzman et al. 2019, the nucleus-sampling paper: why likelihood-maximising decoding fails for open-ended text. (45 min)
How modern constrained decoding works and why it is near-zero overhead. (45 min + 25 min)
The finite-state-machine index behind Outlines. (25 min)
Why temperature 0 is not reproducible on a server, and batch-invariant kernels. (30 min)
Leviathan et al.: the acceptance rule and the expected speed-up. (40 min)
technical_knowledge_base/systems_and_performance/topic_inference_and_serving/sampling_and_decoding/src/ in the knowledge base repository, including the scripts that computed every distribution and sample (make_data.py) and checked every number (recompute.py).