Chapter 2 · Decoding Strategies¶
2.1 How do greedy decoding and beam search differ, and why is beam search rarely used for open-ended generation? ★★¶
One-sentence answer
Greedy decoding picks the most probable token at every step; it is simple, deterministic and the cheapest, but it only looks at the current step, so the result is not necessarily the most probable sequence overall. Beam search keeps the \(k\) candidate paths with the highest cumulative log-probability at every step, searching more thoroughly and getting closer to the most probable sequence. It is rarely used for open-ended generation because "the most probable text" is not good text in the first place: it tends to be bland, repetitive and short, and beam search also has low diversity, high cost and no streaming. Beam search remains a good fit for tasks such as translation and speech recognition, where the answer is nearly unique and tightly constrained by the input.
I will address three aspects: how each method works, why open-ended generation avoids beam search, and where beam search still fits.
(1) Greedy decoding takes only the best choice at the current step, whereas beam search keeps several candidate paths at once.
At each step the model outputs a probability distribution over the whole vocabulary for the next token, and the decoding strategy decides how to pick a token from it. Greedy decoding simply takes the most probable token at every step, so it is deterministic and has the lowest cost. Its problem is that it is short-sighted: being locally optimal at every step does not yield the most probable sequence overall. For example, picking a word with probability 0.4 at the start might force an awkward continuation, while another word with probability 0.3 might lead to a very smooth path. Beam search is designed to ease this short-sightedness: at each step it keeps the \(k\) partial sequences (called beams) with the highest cumulative log-probability, extends each beam by one token, and picks the new top \(k\) from all candidates, until these sequences finish; it then outputs the highest-scoring complete sequence. With \(k=1\) it reduces to greedy decoding. Since every token's log-probability is negative, longer sequences accumulate lower scores, so beam search naturally favors short outputs and usually needs length normalization (see "Going deeper" below).
(2) Beam search is rarely used for open-ended generation, fundamentally because the objective of "maximizing probability" is itself wrong.
- The most probable text is not good text: Holtzman et al. (2019) found that human-written text is not what the model considers most probable; people regularly use surprising but highly informative words. Searching specifically for the most probable sequence tends to produce empty, generic and repetitive text. Beam search searches more thoroughly than greedy decoding, so the problem actually gets worse: the larger the beam, the shorter and blander the output tends to be.
- Low diversity: The \(k\) beams usually differ by only a few words and are essentially the same answer, so they do not help when you want several different candidates.
- High cost and no streaming: It must maintain \(k\) sequences and their KV caches at once, and which beam wins is not known until the end, so output cannot be shown to the user as it is generated.
- Little gain for aligned chat models: After RLHF the model's output distribution is already sharp, so beam search adds little. If you really want to trade more compute for quality, sampling \(N\) complete responses and choosing among them with a verifier or reward model works better (see 4.2 in Chapter 4).
(3) Beam search still fits tasks whose answer is nearly unique and tightly constrained by the input.
In machine translation, speech recognition and very short structured outputs, the correct answer is largely determined by the input and the model's distribution is already concentrated; here "finding the most probable sequence" and "finding the correct answer" largely coincide, and beam search reliably reduces greedy decoding's search errors. In addition, when a task needs an ordered top-\(k\) list of candidates, beam search is natural, because at the end it yields exactly the \(k\) highest-scoring sequences. For example, generative retrieval and generative recommendation represent documents or items as sequences of discrete IDs and use beam search to decode the \(k\) highest-scoring IDs in one pass as the retrieved candidates (TIGER, Rajput et al. 2023).
In summary: beam search solves the search problem of "finding the most probable sequence"; but the trouble with open-ended generation is not the search, it is that the most probable sequence is not what we want in the first place.
Going deeper: formulas, length normalization, and a comparison of three decoding methods
(1) The objectives of greedy decoding and beam search.
Here \(x\) is the input, \(y\) the generated sequence, \(y_t\) its \(t\)-th token, \(y_{<t}\) the tokens before it, \(w\) ranges over the whole vocabulary, \(|y|\) is the sequence length, and \(\alpha\) controls the strength of length normalization (usually 0.6–1.0): \(\alpha = 0\) means no normalization and \(\alpha = 1\) means ranking by average log-probability. (GNMT uses a length penalty of the form \(\big((5+|y|)/6\big)^{\alpha}\), with the same idea.)
(2) Exact search exposes the problem even more starkly.
Stahlberg & Byrne (2019) ran exact search (finding the globally highest-scoring translation without pruning) on a Transformer translation model and found that, for more than half of the sentences, the output the model scored highest was the empty translation. Part of the reason beam search still works is precisely that its search is not thorough. This shows that the problem lies in the model's probabilities themselves (a preference for short outputs), not only in the search algorithm.
(3) Comparing three decoding methods.
| Greedy | Beam search | Sampling | |
|---|---|---|---|
| What it does at each step | Takes the most probable token | Keeps the \(k\) paths with the highest cumulative score | Draws at random from the (reshaped) distribution |
| Deterministic | Yes | Yes | No |
| Objective | Locally maximal probability | Approximately maximal sequence probability | Text that "looks like the model's distribution" |
| Compute and memory cost | Lowest | About \(k\) times | Similar to greedy |
| Diversity | None | Very low | High |
| Supports streaming | Yes | No | Yes |
| Typical use | Extraction, classification, short answers | Translation, speech recognition, generative retrieval | Chat, writing, reasoning models |
Follow-up questions
Follow-up 1: Why does beam search need length normalization?
Because log-probabilities are negative, longer sequences accumulate lower scores, and without normalization beam search systematically favors short sequences. Every additional token adds a negative number to the score, so a short sequence that emits EOS (the end-of-sequence token) too early can easily beat a complete, longer one. Normalizing by length amounts to comparing "the average log-probability per token", so candidates of different lengths can be compared fairly; an \(\alpha\) between 0 and 1 is a compromise between no normalization and a full average.
Follow-up 2: Why does greedy decoding easily fall into repetition loops in open-ended generation?
Because repetition is self-reinforcing, and greedy decoding always picks the most probable token. Xu et al. (2022) found that the more times a sentence has already been repeated in the context, the more likely the model is to repeat it again. Once greedy decoding enters a repeated fragment, the probability of the next repetition is pushed higher, and greedy decoding is certain to take it, so the more it repeats, the more certain it becomes, and a loop forms. Sampling can escape the loop with some probability, which is one reason both open-ended generation and reasoning models advise against greedy decoding (see 2.2).
Follow-up 3: Both beam search and best-of-N "generate several candidates and pick one". How do they differ?
They differ in the selection criterion and in how diverse the candidates are. Beam search prunes step by step according to the model's own cumulative probability, and in the end it also picks the sequence the model finds most probable, so the candidates are highly similar; best-of-N samples \(N\) complete responses independently and then picks with an external verifier or reward model, so the candidates are more diverse and the criterion is closer to the quality we actually care about. That is why, on open-ended and reasoning tasks, methods such as best-of-N are usually more effective than beam search (see Chapter 4).
Common mistakes
- Do not say that beam search finds the globally optimal sequence: It prunes at every step and is only an approximate search; exact search is exponential in both vocabulary size and length.
- Do not say that a larger beam always gives better output: In open-ended generation, larger beams tend to give shorter and blander outputs.
- Do not say that greedy decoding yields the most probable sequence overall: A local optimum is not a global one.
- Do not treat beam search as a sampling method: It is a deterministic search; for a given input the output is unique.
2.2 How do temperature, top-k and top-p work? ★★¶
One-sentence answer
All three reshape the next-token distribution before sampling: temperature divides the logits by \(T\) to control how sharp the distribution is, without removing any token; top-k keeps only the \(k\) most probable tokens; top-p keeps the smallest set whose cumulative probability reaches \(p\), so the size of the candidate set adapts to the shape of the distribution. Common implementations apply repetition penalties first, then divide by the temperature, then apply top-k and top-p truncation, and finally renormalize and sample. The selection principle is: the more a task has a single correct answer, the less randomness; the more diversity it needs, the higher the temperature.
I will address three aspects: why these methods are needed, how each works and the order in which they are applied, and how to choose among them in different settings.
(1) Sampling directly from the full distribution is dragged down by the long tail, and all three methods exist to control that tail.
Sampling means drawing a token at random according to the probability distribution, which makes outputs more natural and more varied than greedy decoding. But sampling directly from the full distribution has a problem: the vocabulary has over a hundred thousand tokens, most with tiny probabilities, yet this "long tail" adds up to a sizable total. For example, if each step has a 2% chance of landing in the tail, then over 200 tokens the probability of landing there at least once is about \(1-0.98^{200}\approx 98\%\). And once an absurd token is drawn, the model treats it as fact and keeps writing, so everything after it drifts off. We therefore want to keep the diversity that sampling brings while avoiding being led astray by the tail, and all three methods address this.
(2) The three methods act on different aspects of the distribution: temperature changes its shape, while top-k and top-p cut off its tail.
- Temperature: Before the softmax, each token's logit \(z_i\) is divided by the temperature \(T\), i.e. \(p_i = \exp(z_i/T)/\sum_j \exp(z_j/T)\). With \(T<1\) the gaps between logits are amplified and the distribution sharpens, so output is more conservative; as \(T\to 0\) it reduces to greedy decoding. With \(T>1\) the distribution flattens and low-probability tokens get more chances, so output is more varied and more error-prone; as \(T\to\infty\) it approaches uniform sampling over the vocabulary. Temperature only changes the shape of the distribution; it never sets any token's probability to 0.
- Top-k (Fan et al. 2018): Keep only the \(k\) most probable tokens, renormalize and sample, cutting off the long tail directly. Its problem is that \(k\) is fixed and does not adapt to the shape of the distribution: when there are many reasonable next words (say, "Today I feel like eating _"), a small \(k\) cuts off reasonable choices; when the next word is nearly certain (say, "The United States of _"), most of the \(k\) candidates are words that should not appear.
- Top-p (nucleus sampling, Holtzman et al. 2019): Sort tokens from most to least probable, keep the smallest set whose cumulative probability reaches \(p\) (e.g. 0.9 or 0.95), and sample from it. When the distribution is flat, many tokens are needed to reach \(p\), so the candidate set grows on its own; when it is sharp, one or two tokens may suffice, so the set shrinks on its own. This adaptivity is exactly what makes it better than top-k.
The three are usually combined, and the order affects the result. Common implementations (e.g. Hugging Face transformers) first apply repetition penalties to the logits (see 2.3), then divide by the temperature, then apply truncations such as top-k and top-p in turn, and finally renormalize and sample. Because the temperature comes before truncation, raising the temperature flattens the distribution and enlarges the top-p candidate set as well, so \(T\) and \(p\) are not two independent knobs; some frameworks allow the temperature to be applied after truncation, in which case the candidate set is determined by the original distribution alone and the temperature only redistributes probability within it. In addition, \(T=0\) is usually special-cased in implementations as taking the argmax directly, since dividing by 0 is undefined.
(3) The selection principle: the more a task has a single correct answer, the less randomness; the more diversity it needs, the higher the temperature.
- Deterministic tasks: Extraction, classification and short factual answers have one correct answer, so use greedy decoding or a temperature near 0, which also makes results reproducible.
- Open-ended generation: General chat commonly uses \(T\approx 0.7\) with top-p \(\approx 0.9\), balancing natural variety against drifting off; creative writing and brainstorming can raise the temperature to around 1.
- Reasoning models and multi-sample methods: The official advice for both DeepSeek-R1 and Qwen3 is a temperature around 0.6 with top-p 0.95, and both explicitly advise against greedy decoding, because over a long chain of thought of thousands of tokens greedy decoding easily falls into endless repetition; settings that need several candidates (best-of-N, self-consistency) must use a fairly high temperature, otherwise the \(N\) samples are nearly identical and voting or reranking becomes pointless (see 4.2 in Chapter 4).
In practice one usually tunes mainly one of temperature and top-p, rather than pushing both aggressively at the same time, because their effects compound.
In summary: temperature decides how sharp the distribution is, while top-k and top-p decide which tokens are eligible to be chosen; the three are used together and set according to how much determinism and diversity the task needs.
Going deeper: formulas, a numerical example and common settings
(1) Definitions of the three methods.
Here \(z_i\) is token \(i\)'s logit, \(T\) the temperature, and \(p_i\) the adjusted probability; \(V_k\) is the top-k candidate set; \(V_p\) is the top-p candidate set, i.e. the smallest set obtained by taking tokens from most to least probable until the cumulative probability is at least \(p\). After truncation, probabilities inside the candidate set are renormalized to sum to 1, and those outside are set to 0.
(2) A numerical example: how temperature changes the shape of the distribution.
Take three tokens with logits \((2, 1, 0)\): at \(T=1\) the probabilities are about \((0.665, 0.245, 0.090)\); at \(T=0.5\) they become \((0.867, 0.117, 0.016)\), clearly sharper; at \(T=2\) they become \((0.506, 0.307, 0.186)\), clearly flatter. The ranking of the three tokens never changes; only the gaps do.
(3) Common settings.
| Setting | Typical configuration | Why |
|---|---|---|
| Extraction, classification, short factual answers | Greedy or \(T \approx 0\) | One correct answer; reproducible |
| Code or math with a standard model | Low \(T\) (0–0.3), optional top-p | Precision first; a little randomness helps escape loops |
| General chat assistant | \(T \approx 0.7\), top-p \(\approx 0.9\) | Natural and varied, with the tail cut off |
| Creative writing, brainstorming | \(T \approx 1\), top-p \(\approx 0.95\) | Diversity is needed |
| Reasoning models with long CoT | \(T \approx 0.6\), top-p 0.95, no greedy (official advice for DeepSeek-R1, Qwen3) | Greedy decoding easily loops over thousands of tokens |
| Best-of-N, self-consistency | \(T \approx\) 0.7–1.0 | Samples must differ enough for voting and reranking to help |
| Translation, speech recognition | Beam search | The correct output is nearly unique and tightly constrained by the input |
(For thinking mode, Qwen3 also recommends top-k 20 and min-p 0; for non-thinking mode it recommends \(T=0.7\) and top-p 0.8.)
Follow-up questions
Follow-up 1: Is the output always fully deterministic at temperature 0?
Not necessarily. In theory \(T=0\) is greedy decoding and should be deterministic. But in a real serving system, the same request is batched with different other requests each time, and with different batch sizes the order of floating-point sums inside GPU kernels can differ; floating-point addition is not associative, so the results differ slightly. When two tokens have very close logits, that tiny difference can flip the argmax, and the rest of the generation diverges completely. Thinking Machines Lab (2025) pointed out that the main source of this nondeterminism is that kernels are not batch-invariant, and implemented kernels whose results do not depend on batch size to eliminate it, at some cost in speed. The same numerical differences also cause the probability mismatch between the training engine and the inference engine in RL training (see the LLM Training Pipeline direction, Chapter 8).
Follow-up 2: Why is greedy decoding discouraged for reasoning models?
Because long chains of thought amplify greedy decoding's repetition problem, and the recommended usage and evaluation of these models are based on sampling anyway. A reasoning model generates thousands or even tens of thousands of tokens at a time, and once greedy decoding enters a repeated fragment somewhere, it is likely to keep circling until it hits the length limit. That is why both DeepSeek-R1 and Qwen3 explicitly recommend sampling at a temperature around 0.6; when the DeepSeek-R1 paper reports pass@1, it also samples each problem several times at temperature 0.6 and top-p 0.95 and averages the accuracy, rather than using a single greedy run.
Follow-up 3: Why is top-p better than top-k, and what problem does it still have?
Top-p's candidate set adapts to the shape of the distribution, but at high temperature or with a flat distribution it still lets in too many tokens that should not appear. When the temperature is high, the distribution is flattened, so a large number of tokens is needed to reach a cumulative probability of \(p\), and junk tokens from the long tail enter the candidate set too, making the output prone to incoherence. This is exactly the problem methods such as min-p address: they set the truncation threshold to a fraction of the top probability, so that the candidate set adjusts with the model's confidence rather than with cumulative probability (see 2.3).
Common mistakes
- Do not say that temperature removes low-probability tokens: It only changes the shape of the distribution; removing tokens is the job of truncation methods such as top-k and top-p.
- Do not describe top-p as "keeping only tokens whose probability exceeds \(p\)": \(p\) is a threshold on cumulative probability, not on any single token's probability.
- Do not say that \(T=0\) means dividing by 0 inside the softmax: Implementations special-case it as taking the argmax directly.
- Do not push both temperature and top-p aggressively at the same time: Their effects compound; tuning mainly one of them is usually enough.
2.3 What problems do repetition penalties and samplers such as min-p solve? ★¶
One-sentence answer
They target two different failures of standard sampling. Repetition penalties target the degeneration of "getting more and more repetitive" by lowering the scores of tokens that have already appeared, in the common forms of the CTRL-style multiplicative repetition penalty and the count-based frequency and presence penalties, at the cost of also penalizing necessary repetition such as code identifiers and names; min-p targets top-p's tendency to let in too many junk tokens at high temperature or with a flat distribution, by setting the truncation threshold to a fraction of the top probability so that the candidate set adapts to the model's confidence. Both are heuristic patches and should be used lightly.
I will address three aspects: the repetition problem and repetition penalties, the truncation problem and min-p, and the limitations of these methods.
(1) Repetition penalties target self-reinforcing repetition loops by directly lowering the scores of tokens that have already appeared.
As noted earlier, repetition is self-reinforcing: the more a passage has been repeated, the more likely the model is to repeat it again (Xu et al. 2022). The most direct countermeasure is to modify the logits before sampling, making tokens that have already appeared harder to pick again. There are two common forms:
- The multiplicative repetition penalty: CTRL (Keskar et al. 2019) proposed that, for tokens that have already appeared, positive logits are divided by \(\theta\) and negative logits are multiplied by \(\theta\), with \(\theta>1\) (commonly 1.1–1.3). Positive and negative logits must be handled separately because dividing a negative logit by \(\theta\) would make it larger (closer to 0), which has the opposite effect.
- The additive frequency and presence penalties: This is the form used in the OpenAI API. The frequency penalty subtracts in proportion to how many times a token has already appeared, so the more often it appears, the larger the penalty, and it mainly suppresses verbatim loops; the presence penalty subtracts a fixed amount once a token has appeared at all, and it mainly nudges the model toward new content.
(2) Min-p targets the problem that fixed truncation rules cannot adjust to the model's confidence.
Top-p truncates by cumulative probability, so with a flat distribution it lets a large number of tail tokens into the candidate set; yet people want precisely to raise the temperature in creative writing to increase diversity, and once the temperature is high, the distribution flattens, many words that should not appear enter the candidate set, and the output becomes incoherent. Min-p (Nguyen et al. 2024) takes a different approach: it keeps only tokens whose probability is at least \(p_{\text{base}} \cdot p_{\max}\), where \(p_{\max}\) is the current top token probability and \(p_{\text{base}}\) is usually 0.05–0.1. The threshold therefore adjusts automatically with the model's confidence: when the model is confident, e.g. \(p_{\max}=0.9\) and \(p_{\text{base}}=0.1\), the threshold is 0.09 and the candidate set is very small; when the model is uncertain, e.g. \(p_{\max}=0.2\), the threshold drops to 0.02 and many more options are kept. This allows sampling at higher temperatures while staying coherent (the Hugging Face implementation applies it after the temperature).
(3) These methods are heuristic patches, and each has a cost.
- Repetition penalties also hit necessary repetition: Variable names in code, people's names, formatting symbols, the brackets and quotes of JSON, and common function words are all supposed to recur. A heavy penalty breaks code, makes structured output invalid and makes prose awkward. Frameworks also differ in what they penalize; some also penalize tokens that appeared in the prompt, which is especially harmful for tasks that restate or rewrite the input.
- Min-p's advantage is not consistent: A later independent evaluation (Schaeffer et al. 2025) argued that min-p does not consistently outperform top-p and other methods across settings, and that its gains depend on the task and hyperparameters.
- The root cause of repetition often lies in the model itself: Severe repetition often reflects problems in training or quantization, and penalties at decoding time only relieve the symptom. For modern chat and reasoning models, a light presence penalty is usually added only when loops appear (this is Qwen3's official advice).
In summary: repetition penalties adjust which tokens' scores should be pushed down, while min-p adjusts how the truncation threshold should be set; both are patches on standard sampling and should be applied lightly to specific problems.
Going deeper: formulas and a comparison of truncation methods
(1) The two forms of repetition penalty.
Here \(z_i\) is token \(i\)'s logit; the left formula is CTRL's repetition penalty, where \(\theta > 1\) is the penalty strength and it applies only to tokens that have already appeared; the right formula is the frequency and presence penalties, where \(c_i\) is the number of times token \(i\) has appeared, \(\alpha\) is the frequency-penalty coefficient, \(\beta\) is the presence-penalty coefficient, and \(\mathbb{1}[\cdot]\) is the indicator function (1 if the condition holds, 0 otherwise). (A harder alternative bans any repeated n-gram of a given length, i.e. no_repeat_ngram_size, but it also hits necessary repetition.)
(2) Min-p's truncation rule.
Here \(p_i\) is token \(i\)'s probability and \(p_{\text{base}}\) the relative threshold. By contrast, epsilon sampling uses a fixed absolute threshold \(p_i \ge \varepsilon\), which does not change with the model's confidence.
(3) Comparing truncation methods.
| Method | Truncation rule | Size of the candidate set | Main problem |
|---|---|---|---|
| Top-k | Keep the \(k\) most probable tokens | Fixed | Does not change with the shape of the distribution |
| Top-p | Keep the smallest set whose cumulative probability reaches \(p\) | Changes with the shape of the distribution | Lets in many tail tokens when the distribution is flat |
| Min-p | Keep tokens with probability at least \(p_{\text{base}} \cdot p_{\max}\) | Changes with the model's confidence | Gains are inconsistent across tasks |
| Epsilon sampling | Keep tokens with probability at least a fixed \(\varepsilon\) | Changes with the distribution, but the threshold is fixed | The threshold does not adjust to confidence |
Follow-up questions
Follow-up 1: Why does the repetition penalty treat positive and negative logits differently?
Because the same division pushes positive and negative logits in opposite directions. The goal of the penalty is to make the logit smaller. Dividing a positive logit by \(\theta>1\) makes it smaller, as intended; but dividing a negative logit by \(\theta\) brings it closer to 0, i.e. makes it larger, which actually raises the token's probability. Negative logits are therefore multiplied by \(\theta\) instead, making them more negative.
Follow-up 2: How do the frequency penalty and the presence penalty differ, and when is each used?
The former accumulates with the number of occurrences, while the latter only distinguishes "has appeared" from "has not appeared". The frequency penalty subtracts a little more each time a token appears again, which suits suppressing loops that repeat the same phrase verbatim; the presence penalty subtracts a fixed amount from any token that has appeared, regardless of how many times, which suits encouraging the model to bring in new topics and vocabulary. Neither should be too large, or the model will be forced to avoid words it should reuse.
Follow-up 3: When do min-p and top-p differ the most?
In the two extremes: when the model is very confident, and when the distribution has been flattened. When the model is very confident (say the top probability is 0.9), top-p at 0.95 still has to include several low-probability tokens to reach the cumulative probability, whereas min-p's threshold is 0.09 and keeps essentially only the most likely token. When the temperature is high and the distribution is flattened, top-p has to include a large number of tail tokens, whereas min-p's threshold falls with the top probability but still proportionally excludes tokens far below it. When the distribution has a moderate shape, the two give similar results.
Common mistakes
- Do not apply a heavy repetition penalty to code or JSON output: Variable names, brackets and quotes are supposed to repeat, and a heavy penalty produces broken output.
- Do not say that repetition penalties cure repetition: They only relieve the symptom; severe repetition often comes from the model itself.
- Do not describe min-p's threshold as a fixed absolute probability: It is a fraction of the top probability; the fixed threshold belongs to epsilon sampling.
- Do not say that min-p beats top-p on every task: Independent evaluation shows its advantage is not consistent.
2.4 How is structured output (constrained decoding) implemented? ★¶
One-sentence answer
Before sampling at each step, constrained decoding uses a grammar (a regular expression, or a context-free grammar converted from a JSON schema) to compute which tokens keep the output a valid prefix, sets the logits of all other tokens to \(-\infty\), and then samples or takes the argmax as usual, which guarantees that the output conforms to the format. The engineering difficulty is computing this mask quickly over a vocabulary of over a hundred thousand tokens at every step: Outlines precomputes an index over a finite-state machine, and XGrammar uses a pushdown automaton and caches the context-independent tokens. At the model level, step-by-step truncation distorts the distribution, and an overly strict format can hurt reasoning, so the model is often allowed to reason freely first and fill in the format afterwards.
I will address three aspects: the basic mechanism, how to compute the mask efficiently, and its limitations.
(1) The basic mechanism: at each step, mask the logits so that only tokens keeping the output a valid prefix are allowed.
Constrained decoding first expresses the format requirement as a formal grammar: simple formats can be written as regular expressions, and a JSON schema can be converted into a context-free grammar. During generation, a parser state is maintained that records where the text generated so far sits in the grammar. At each step, for every token in the vocabulary, we check whether appending its characters to the current text still gives a prefix of some valid string; invalid tokens have their logits set to \(-\infty\), i.e. probability 0. Sampling then proceeds as usual over the remaining tokens, and the sampled token advances the parser state; the end-of-sequence token is allowed only when the parser is in a state where the text already forms a complete valid string. For example, after generating {"age":, if the schema says age is an integer, only tokens beginning with a digit or a minus sign are allowed. As long as generation ends normally, the output is therefore guaranteed to conform to the format, whereas prompting alone, or retrying after malformed output, only makes a correct format more likely.
(2) The key to computing the mask efficiently is to precompute as much of the work as possible.
The difficulty is that tokens are not aligned with grammar symbols: a single token can span several grammar symbols (e.g. "}, contains a quote, a closing brace and a comma at once), so at every step the strings of over a hundred thousand tokens must each be checked against the automaton, which is very slow if done directly. The mainstream approaches all rely on precomputation.
- Finite-state machines with a precomputed index: Outlines (Willard & Louf 2023) compiles a regular expression into a finite-state machine and precomputes, for each state, "which tokens are accepted and which state each leads to", so each step at runtime is just a table lookup. Its limitations are that a finite-state machine cannot express arbitrarily deep nesting, and that compiling complex schemas takes a long time.
- Pushdown automata with a cache by token class: JSON allows arbitrary nesting, which requires a pushdown automaton with a stack to represent a context-free grammar. XGrammar (Dong et al. 2024) observed that, for the vast majority of tokens, validity depends only on the current grammar position (the top of the stack) and not on deeper stack contents, so it can be precomputed and cached for each position; only the few tokens that depend on the whole stack need to be checked at runtime. This cuts the per-token constraint overhead by up to about 100 times compared with earlier methods, and it has been integrated into inference frameworks such as vLLM and SGLang.
- Overlapping with model computation and skipping the determined parts: The mask can be computed on the CPU while the GPU runs the forward pass for that step, so the two proceed in parallel; when the grammar dictates that only a fixed string can come next (e.g. a key name in the schema), those tokens can be appended directly without decoding them one at a time (SGLang's jump-forward decoding, Zheng et al. 2023).
(3) Limitations: constrained decoding guarantees only syntactic correctness, and its intervention in the distribution can affect quality.
- Step-by-step truncation distorts the distribution: Removing invalid tokens at each step and renormalizing does not account for "how many valid continuations remain after choosing this token". The resulting distribution therefore differs from the true conditional distribution (the model's distribution restricted to valid strings), and it can push the model onto a low-probability valid path (Park et al. 2024).
- An overly strict format can hurt reasoning: Tam et al. (2024) found that requiring the model to answer directly in a strict format such as JSON lowers accuracy on reasoning tasks such as math, while having little effect on, or even helping, classification tasks. A common mitigation is to let the model reason in natural language first and output the structured result afterwards, or to place a reasoning field before the answer field in the schema, because generation proceeds left to right and the answer field should be generated only after the reasoning.
- Syntactic correctness is not content correctness: Constrained decoding guarantees valid JSON that conforms to the schema, but whether the field values are correct, or fabricated, still depends on the model itself.
In summary: constrained decoding turns "a correct format" from a probabilistic guarantee into a deterministic one; the costs are the per-step mask computation and the intervention in the distribution, with precomputation reducing the overhead in engineering and "reason first, then fill in the format" reducing the impact on quality in practice.
Going deeper: the form of the mask, an example of distribution distortion, and a comparison of approaches
(1) The distribution after masking.
Here \(\mathcal{L}\) is the set of valid strings defined by the grammar, \(\mathrm{Prefix}(\mathcal{L})\) is the set of all their prefixes, \(y_{<t}\, y_t\) denotes appending token \(y_t\) to the text generated so far, and \(v\) ranges over the vocabulary. In implementation this is equivalent to setting the logits of invalid tokens to \(-\infty\) before the softmax.
(2) An example of distribution distortion.
The true conditional distribution is \(p(y \mid y \in \mathcal{L}) \propto p(y)\,\mathbb{1}[y \in \mathcal{L}]\), which reweights by the probability of the whole sequence. Suppose the opening token has two valid choices, A and B, with model probabilities 0.9 and 0.1; only 1% of the continuations after A are valid, while all continuations after B are valid. The true conditional distribution should choose B with probability about 92% (\(0.1 / (0.9\times 0.01 + 0.1)\)), but step-by-step masking still chooses A with probability 0.9 and is then forced into that 1% of valid continuations. Grammar-aligned decoding (Park et al. 2024) corrects this bias by estimating, for each prefix, "the probability that the future will be valid".
(3) Approaches to guaranteeing the format.
| Approach | Guarantees the format | Guarantees schema conformance | Cost |
|---|---|---|---|
| Prompting only | No | No | None |
| Retrying on failure | No (only lowers the failure rate) | No | Several generations |
| JSON mode | Guarantees valid JSON | No | Small |
| Constrained decoding (finite-state machine) | Yes | Yes (limited nesting depth) | Slow precompilation, table lookup at runtime |
| Constrained decoding (pushdown automaton) | Yes | Yes | A few runtime checks per step |
(4) A published number.
When OpenAI launched Structured Outputs in 2024, it reported that on its complex JSON schema evaluation, gpt-4o-2024-08-06 with strict mode scored 100%, while gpt-4-0613 scored under 40%; targeted training alone reached 93%, and the remaining gap was closed by constrained generation, for which the schema is converted into a context-free grammar. This shows that training can raise format compliance substantially, but reaching 100% still requires constrained decoding.
Follow-up questions
Follow-up 1: How do JSON mode and Structured Outputs differ?
JSON mode only guarantees that the output is valid JSON, while Structured Outputs guarantees that it conforms to a given schema. JSON mode constrains a generic JSON grammar, so the model can still omit required fields, use the wrong types or add extra fields; Structured Outputs compiles the specific schema into a grammar, so field names, types, required fields and enum values are all constrained. Function-calling arguments can be constrained in the same way.
Follow-up 2: Why can constrained decoding make reasoning worse, and how can this be mitigated?
Because the format constraint takes over the generation the model would otherwise use for reasoning, and it may force the model to commit to an answer before reasoning. When the output is required to be {"answer": ...} directly, the model has no chance to write out reasoning steps first, which amounts to switching off chain of thought; a strict format can also push the model toward forms of expression it is unfamiliar with. There are three mitigations: put a reasoning field before the answer field in the schema; work in two passes, generating freely first and then converting the result into the structured format; and, for reasoning models, constrain only the final output that comes after the thinking ends.
Follow-up 3: Does constrained decoding slow generation down?
It adds overhead, but precomputation and overlap can largely hide it, and sometimes it is even faster. Computing the mask at each step is extra CPU work, and if implemented poorly it becomes a bottleneck, especially when the batch is large and each request has a different schema. Precomputed indexes, caching by token class, and overlapping with the GPU forward pass can keep this overhead very small; and for fixed content such as key names in the schema, appending several tokens directly skips several decoding steps, which can actually shorten the total time.
Common mistakes
- Do not say that constrained decoding guarantees correct content: It guarantees only the syntax and the schema, not that the field values are right.
- Do not say that constrained decoding leaves the model's distribution unchanged: Step-by-step truncation differs from the true conditional distribution.
- Do not put the answer field before the reasoning field in a schema: Generation proceeds left to right, so this amounts to giving the answer first and finding reasons afterwards.
- Do not say that prompting or JSON mode guarantees schema conformance: Only constrained decoding that compiles the schema into a grammar gives a deterministic guarantee.