You ask a model to choose a tool, and your code is ready to run the result. It needs a JSON record with the tool's name and arguments, but the model replies with a helpful sentence. Your parser cannot use that response to run the next step. Structured output from LLMs matters whenever another piece of software has to act on the response, because readable prose alone is not enough to keep that exchange working.
Restricting the next token can make malformed records unreachable under the supported grammar. OpenAI's 2024 evaluation reported 100% schema compliance with Structured Outputs, against under 40% for prompted gpt-4-0613. We build the mask on a small model and check formatting separately from correct field values.
This post builds it from scratch on GPT-2 small, which runs on a laptop CPU with no API key. You will write a character automaton for one schema, lift it onto GPT-2's 50,257-token vocabulary, and watch it turn a model that produces valid records 4% of the time into one that produces them 100% of the time. You will also measure the cost of masking. On this task a differently written grammar for the same schema drops field accuracy from 50% to 29%.
Let's Build It
Open this in Google Colab and run it top to bottom. The model download is 500MB and everything after it is CPU seconds.
Here is one record being decoded under the mask. The left panel is the output so far. The right panel is the model's eight highest-scoring tokens at that step, with the ones the grammar rejects marked -inf.

At step one the model's eight favourite continuations are all illegal, and exactly two tokens in the whole vocabulary are not. By step nine we are inside a free-text name and nearly everything passes. At the final step a single token is legal, and it is the closing brace.
The whole sampler is a standard greedy loop with two extra lines.
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
model = AutoModelForCausalLM.from_pretrained("gpt2").eval()
tokenizer = AutoTokenizer.from_pretrained("gpt2")
grammar = Grammar() # the schema as an automaton
masker = TokenMask(vocab_strings(tokenizer), grammar, tokenizer.eos_token_id)
state = grammar.start()
ids = tokenizer(prompt, return_tensors="pt").input_ids
past, emitted = None, []
while state != ACCEPT:
with torch.no_grad():
step = model(ids, past_key_values=past, use_cache=True)
past = step.past_key_values
mask, moves = masker.for_state(state) # which tokens fit here
logits = step.logits[0, -1].masked_fill(~mask, float("-inf"))
token = int(logits.argmax())
state, ids = moves[token], torch.tensor([[token]])
emitted.append(token)
print(tokenizer.decode(emitted))
{"name": "Aida Lovelace", "age": 36, "verified": true}
That output parses, matches the schema and has the wrong first name, which is what a 124M-parameter model gives you. Nothing in the loop retried, validated or repaired anything. The record came out valid because no other record could have.
What Just Happened?
The schema as a character automaton
A general JSON parser is more machinery than this needs. One schema with fixed keys is a chain of fixed text with holes in it, and a chain is a small automaton.

Blue segments match one character at a time against text the schema fixes. Amber segments are the holes the model fills: a string that loops on any safe character until a quote closes it, one to three digits, or the literal true or false. Cap the string at 24 characters and the number at three digits and the automaton has a finite number of states, so every path through it terminates.
The state is a triple: which segment we are in, how many characters of that segment have matched, and (for the boolean, which is an alternation between two literals) which branch was taken.
def advance(self, state, ch):
"""Consume one character. Returns the next state, or None if ch is illegal."""
seg_idx, pos, branch = state
kind, param = self.segments[seg_idx]
if kind == "lit": # fixed text: exactly one legal character
text = str(param)
if ch != text[pos]:
return None
pos += 1
return self._enter(seg_idx + 1) if pos == len(text) else (seg_idx, pos, 0)
if kind == "str": # a hole the model fills
if ch == '"': # the closing quote ends the segment
return self._enter(seg_idx + 1)
if pos >= int(param) or ch not in STRING_CHARS:
return None
return (seg_idx, pos + 1, 0)
...
Nothing here knows about a language model. These sixty lines answer one question, which is which characters may come next given what has been written.
Masking the logits
The bridge from characters to tokens is one loop over the vocabulary. A token is legal in a state when every character in it is legal in turn, and the state it leaves behind is where the automaton lands after consuming the whole token.
def for_state(self, state):
"""Boolean mask over the vocabulary, plus the state each legal token lands in."""
if state in self._cache:
return self._cache[state]
mask = torch.zeros(len(self.vocab), dtype=torch.bool)
moves = {}
for token_id, text in enumerate(self.vocab):
landed = self.grammar.consume(state, text) # walk every character
if landed is not None:
mask[token_id] = True
moves[token_id] = landed
self._cache[state] = (mask, moves)
return mask, moves
Scanning 50,257 tokens per step would be slow, so the result is cached against the automaton state. A decode visits around 50 distinct states, pays for each once, and reuses the mask everywhere it recurs. Willard and Louf (2023) formalise the same trick as an index built ahead of time, which is how the production libraries stay fast.
Applying the mask is logits.masked_fill(~mask, float("-inf")). Negative infinity survives the softmax as exactly zero probability, so an illegal token cannot be sampled at any temperature. Every guarantee in this post rests on that one line.
Token boundaries
A tokeniser is not a parser and knows nothing about the grammar. GPT-2 encodes the opening brace and the first quote as a single token {", because that pair is common in its training data, while the grammar sees two characters belonging to two different places in the schema.

Three of the six internal grammar boundaries fall inside a token. The mask therefore has to be built by walking each candidate token's characters through the automaton. A character-level check applied character by character would arrive too late, since by the time you see the second character of {" the token is already committed.
The bottom panel shows what the mask does to the search space. At structural positions the model chooses between 1 and 12 tokens out of 50,257. Inside the name it chooses between roughly 48,600. Across the whole prompt set the median step has 4 legal tokens and the mean has 12,067, and the gap between those two numbers shows the shape of the task, since a record is mostly skeleton with a little freedom in the middle.
The steps where the grammar overrules the model
Rejection is only interesting when the model wanted the rejected thing.

At step one every one of the model's eight favourites is illegal: after the few-shot examples it wants to write a newline, a run of zeros or a byte fragment. At step two the legal quote sits at rank five, so the mask reaches past four preferred tokens to find it. Averaged over the whole prompt set the mask keeps 89.5% of the model's probability mass and overrides its top choice on 8.5% of steps. Nine steps in ten, the grammar and the model agree and the mask changes nothing.
Going Deeper
The three strategies, measured
The comparison uses one prompt set: 16 sentences of the form "Ada Lovelace is 36 and her account is verified", a three-shot prompt, and the schema {"name": str, "age": int, "verified": bool}. Four strategies run against it. Ask nicely samples once and calls json.loads. Retry samples up to five times and keeps the first output that parses and matches the schema. Retry with feedback does the same but pastes the rejected output back into the prompt with a correction line. Validate and repair samples once, then cuts to the first brace, closes open strings and braces, and wraps a bare fragment that looks like key-value pairs. Constrained applies the mask.

At temperature 0 a good few-shot prompt gets most of the way there. GPT-2 returns a schema-conforming record for 13 of the 16 sentences, an 81% success rate, and every non-constrained strategy lands on the same 81% because they all start from the same deterministic sample. Retry fires a second attempt on the failures and gets the identical output back, which is worth remembering before adding a retry loop around a temperature-0 call.
81% looks survivable until it is chained. An agent that makes five tool calls in a row at that rate completes 0.81 to the fifth, which is 35% of runs. Constrained decoding returns 16 of 16 at both temperatures, and by construction it would return 160 of 160.
Turn the temperature up to 0.8, which is where anything wanting varied output lives, and the prompted strategies collapse. Asking nicely conforms on 4% of prompts. The failures are the ones any practitioner recognises: a missing opening brace, square brackets instead of curly, a preamble before the object, a run of asterisks, a sentence in Japanese. Repair recovers some of those and reaches 8%. Retry, given five attempts, reaches 23% and spends 4.48 calls per record to do it.
Retry with feedback lands at 4%, no better than a single attempt. The trick assumes the model can read "that was not valid JSON, try again" and change its behaviour, and a 124M-parameter model cannot. It treats the correction as more context to continue. Feedback loops earn their place at frontier scale, and this measurement says nothing about that case. It does say the loop is not free, and that a small model is one place where paying for it buys nothing.
The cost of retrying
Success rate alone understates the difference, because a failed attempt still pays for the whole prompt.

Divide each strategy's token spend by its success rate and you get what one usable record costs. Constrained decoding spends 165 tokens. Retry spends 3,166, a factor of 19. Retry with feedback spends 24,518, because each attempt carries every failed attempt before it, so the prompt grows while the odds do not improve.
The blue portion of each bar is prompt tokens, and it dominates everywhere. This is the same arithmetic as the ReAct agent's scratchpad, where the token bill grows faster than the step count because every step re-sends everything before it. Retrying is that pattern with nothing to show for the extra context. If you want to put your own numbers against it, the LLM cost calculator takes prompt and completion tokens per call.
Sub-word misalignment
The mask has a cost that does not show up in any success rate. Take the 16 constrained outputs and re-encode each one with GPT-2's own tokeniser. None of the 16 tokenise to the tokens we emitted, and the difference is exactly one token every time.
emitted = ['{', '"', 'name', '":', ' "', 'A', 'ida', ...]
canonical = ['{"', 'name', '":', ' "', 'A', 'ida', ...]
At step one, two tokens are legal: { and {". The model scores the bare brace higher, the mask has no opinion between them, and the decode commits to a token sequence GPT-2 would never produce for that string. Everything after step one is conditioned on a prefix that is off the distribution the model was trained on.
Beurer-Kellner et al. (2024) named this and showed it matters:
not only do such methods incur performance overhead during generation, but many of them also significantly impair task accuracy, if they do not correctly align the underlying LLM sub-word vocabularies with external constraints.
Their fix, DOMINO, keeps a set of candidate tokenisations alive instead of committing to the first legal token, and reports near-zero overhead against unconstrained decoding. The masker in this post takes the naive route. That suits a post about the mechanism and would not survive production.
The grammar as a hyperparameter
Sub-word misalignment predicts something testable. If the constraint's exact spelling changes which tokenisations are reachable, then two grammars that accept the same set of JSON documents should not score the same. Three grammars, same schema, same 16 prompts, same three seeds.

All three return valid JSON matching the schema on 16 of 16 prompts. The guarantee is untouched. Field accuracy moves from 50% to 35% when the keys are reordered so verified comes first, and to 29% when the space after each colon is removed. Deleting one character per field costs 21 points of accuracy.
The probability-mass column explains it. The canonical grammar, whose spelling matches the three-shot examples in the prompt, keeps 89% of the model's mass at the average step. Reordering the keys keeps 70%. A mask that discards three tenths of the model's mass at the average step is steering hard, and a steered model gets fewer answers right.
Practical version: write the grammar the way the model has seen the format written. Match the spacing in your few-shot examples, keep the key order stable, and treat a schema rewrite as a change that needs re-evaluating.
The limits of the guarantee
Constrained decoding guarantees a parser will accept the output. It says nothing about whether the output is correct. In the sampled runs the mask took schema conformance from 4% to 100% and field accuracy to 50%, and that ceiling comes from GPT-2 small misreading "Ada" as "Aida" while the method itself imposes no such limit. Among the outputs that did parse, accuracy was 46% unconstrained and 44% constrained at temperature 0, so on this task the mask neither helped nor hurt the content it wrapped.
A schema can also make things worse by demanding a field the evidence does not support. "verified": bool has no null, so a sentence that says nothing about verification forces a guess, and the guess arrives looking exactly as confident as a fact. Where the answer may be unknown, put that in the schema as an option and let the model take it.
The decision rule
Constrained decoding needs access to logits. If you control decoding, locally or through an API that accepts a schema or grammar, use it, since the guarantee is free of charge and the cost arithmetic favours it heavily. If you are calling an endpoint that returns finished text, validate and repair is the pragmatic floor, and retrying a temperature-0 call is not a strategy.
Reach for a mask when the output feeds a parser, a database write or another program: extraction, tool calls, classification into a fixed label set. Leave it off when the output is prose for a person, when the model needs room to reason in the open before answering, or when your schema is deep enough that the automaton becomes its own maintenance problem. A common middle path lets the model think freely and constrains only the final block, which keeps the reasoning tokens and the guarantee at once.
Where This Comes From
Grammar-constrained decoding predates the current interest in it by decades in parsing, and the modern line starts with two 2023 papers.

Geng et al. (2023), "Grammar-Constrained Decoding for Structured NLP Tasks without Finetuning" (EMNLP 2023), made the case that the format problem is a decoding problem. They apply formal grammars to information extraction, entity disambiguation and constituency parsing, and report that grammar-constrained models "substantially outperform unconstrained LMs or even beat task-specific finetuned models", which is the argument for trying a grammar before a training run.
Willard and Louf (2023), "Efficient Guided Generation for Large Language Models", supplied the engineering that made it practical and became the Outlines library. Their reformulation is the one this post implements:
In this article we show how the problem of neural text generation can be constructively reformulated in terms of transitions between the states of a finite-state machine. This framework leads to an efficient approach to guiding text generation with regular expressions and context-free grammars by allowing the construction of an index over a language model's vocabulary.
The index is the part worth studying. Our for_state scans the whole vocabulary the first time it sees a state and caches the answer, which is the same idea discovered lazily. Willard and Louf build the map from automaton states to permitted token sets ahead of time, so the per-token cost stops scaling with vocabulary size, and report that the approach "adds little overhead to the token sequence generation process".
Beurer-Kellner et al. (2024), "Guiding LLMs The Right Way: Fast, Non-Invasive Constrained Generation", is the corrective. Their DOMINO algorithm tracks several candidate tokenisations through the constraint and uses speculative decoding to stay cheap, reporting "virtually no overhead and in some cases even almost 2x speedup over unconstrained decoding". The one-extra-token result measured above is a small instance of the problem they characterise.
The commercial timeline is short. llama.cpp merged GBNF grammar support in July 2023, OpenAI shipped Structured Outputs in August 2024 with the comparison quoted at the top of this post, and every serving stack now carries an implementation, usually XGrammar or Outlines underneath. That same masking step can make a grammar-constrained request slower on a busy server, because it interacts with the batching machinery described in how LLM serving works once different requests in a batch sit at different automaton states.
Further reading
- The original paper: Willard and Louf (2023), sections 3 and 4 for the FSM formulation and the index construction
- The corrective: Beurer-Kellner et al. (2024), section 3 on sub-word misalignment, which is the failure this post reproduces
- The library: Outlines, the reference implementation of the index approach
- Next topic: retrieval, which is the other half of a working agent and the subject of the next post in this series
Interactive Tools
- LLM Cost Calculator: put your own token prices against the retry-versus-constrain arithmetic in this post
- KV Cache Calculator: size the cache that makes each masked decoding step cheap enough to matter
Related Posts
- Building a ReAct Agent in Python: the loop that consumes these records, and where a failed parse costs a whole step
- KV Cache: The Memory Behind Fast LLM Inference: why the incremental decoding loop above is cheap after the first forward pass
- How LLM Serving Works: what happens when many constrained requests share one batch
- Parallel Token Generation: an alternative to strictly left-to-right decoding, and what it does to guarantees like this one
- GRPO from Scratch: the post-training method that teaches format compliance instead of enforcing it
- Prompt Injection Against Tool-Using Agents: a grammar fixes the shape of a tool call and says nothing about who chose it






