Bring the mental model from Decoding & Sampling: Temperature, Top-p & Inference-Time Control; this page will reuse it instead of restarting from zero.
LLM Systems
Structured Decoding: Token Masks From Schema Automata
How a schema automaton or parser state turns next-token logits into constraint-valid generation by masking invalid continuations, while leaving truth and task success outside the formal guarantee.

Concept Structure
Structured Decoding: Token Masks From Schema Automata
Start with the picture, metaphor, or geometric mechanism.
Make the objects explicit and connect them with notation.
Mirror the equations with runnable implementation details.
Manipulate the mechanism and watch the idea respond.
Learning map
Structured Decoding: Token Masks From Schema AutomataConceptual Bridge
What should feel connected as you move through this page.
How a schema automaton or parser state turns next-token logits into constraint-valid generation by masking invalid continuations, while leaving truth and task success outside the formal guarantee.
The next edge should feel earned: use the demo prediction here before following Retrieval-Augmented Generation: External Memory for Generation.
01
Intuition
Build the mental picture first so the rest of the page has something to attach to.
Canonical sources: Scholak et al., "PICARD", Beurer-Kellner et al., "LMQL", the JSON Schema object reference, the Outlines constrained-generation docs, OpenAI's Structured Outputs guide, Louf and Willard et al., "DOMINO", Dong et al., "XGrammar", and the vLLM structured outputs docs.
Decoding and sampling turn next-token logits into text. Structured decoding adds one more object to the loop: a tiny parser or automaton state.
At each step, the model still proposes ordinary logits over tokens. The schema state asks a stricter question: which next tokens can still lead to a valid completion? Invalid tokens are masked to probability zero. The remaining tokens are renormalized, then greedy decoding, sampling, beam search, or tree search can choose among them.
The guarantee is narrow but useful. If the automaton is correct, every emitted token follows its mask, and decoding stops in an accepting state, then the output belongs to the formal language. That does not mean the source is true, the tool should be called, the answer is safe, or the selected enum is semantically right.
This page studies that finite mechanism, not product JSON mode, tool calling, retries, validators after generation, or full JSON Schema.
The demo is deliberately over toy tokens: real tokenizers can split or merge pieces like "tool" or {, so production masks are built over actual token IDs. The schema here is exact-order and finite-enum; real JSON Schema can admit many equivalent serializations. The naive and cached check counts in the demo illustrate carried decode-time mask work, not a universal latency model.
02
Math
Translate the story into symbols, assumptions, and a derivation you can inspect.
Let be a fixed finite token vocabulary, including an end token .
Represent the schema as a deterministic finite automaton
For a prefix , the schema state is when every transition is defined.
That "can reach" clause matters. A local transition that enters a dead end should not remain allowed.
The allowed-token mask should include only tokens that can still reach acceptance. Given model logits and temperature , constrained decoding uses
Then a decoder selects or samples from and updates
Stopping is accepted only when , usually after an explicit token.
If top- is used, the hard schema mask should be applied first, then top- truncates and renormalizes inside the valid set. Applying top- first can throw away every valid token when the raw model strongly prefers invalid ones.
The modest theorem is:
If every emitted token is sampled from and the run stops in , then the token sequence is in . Nothing follows about whether the content is true, useful, task-correct, or semantically correct; safety is likewise outside a formal syntax guarantee.
03
Code
Keep the implementation aligned with the notation so the algorithm is legible.
This witness implements the same finite object as the demo: a token-level automaton for a tiny ordered retrieval-call schema. The unconstrained decoder can choose an invalid token immediately. The constrained decoder is schema-valid. A semantic-mismatch profile stays schema-valid while choosing the wrong source for the hidden task.
from collections import defaultdict
from math import exp
V = [
"{", "}", ":", ",",
'"tool"', '"source"', '"k"',
'"retrieve"', '"lookup"', '"docs"', '"tickets"',
"1", "2",
'"DROP"', '"extra"', "true", "<eos>",
]
D = {
0: {"{": 1},
1: {'"tool"': 2},
2: {":": 3},
3: {'"retrieve"': 4, '"lookup"': 4},
4: {",": 5},
5: {'"source"': 6},
6: {":": 7},
7: {'"docs"': 8, '"tickets"': 8},
8: {",": 9},
9: {'"k"': 10},
10: {":": 11},
11: {"1": 12, "2": 12},
12: {"}": 13},
13: {"<eos>": 14},
}
ACCEPT = {14}
VALID_PROFILES = {"schema-friendly", "format-confused", "semantic-mismatch"}
def good_states():
rev = defaultdict(set)
for q, arcs in D.items():
for tok, r in arcs.items():
rev[r].add(q)
good = set(ACCEPT)
stack = list(ACCEPT)
while stack:
r = stack.pop()
for q in rev[r]:
if q not in good:
good.add(q)
stack.append(q)
return good
GOOD = good_states()
def allowed(q):
return [tok for tok in V if D.get(q, {}).get(tok) in GOOD]
def step(q, tok):
return D.get(q, {}).get(tok)
def base_logits(q, profile):
if profile not in VALID_PROFILES:
raise ValueError(f"unknown profile: {profile}")
z = {tok: -2.0 for tok in V}
for tok in allowed(q):
z[tok] = 1.0
preferred = {3: '"retrieve"', 7: '"docs"', 11: "2"}
if q in preferred:
z[preferred[q]] = 2.0
if profile == "format-confused":
z['"DROP"'] = 5.0
z['"extra"'] = 4.0
if profile == "semantic-mismatch" and q == 7:
z['"tickets"'] = 5.0
z['"docs"'] = 1.0
return z
def softmax(z, toks):
m = max(z[t] for t in toks)
weights = {t: exp(z[t] - m) for t in toks}
total = sum(weights.values())
return {t: weights.get(t, 0.0) / total for t in V}
def masked_probs(z, q):
return softmax(z, allowed(q))
def rejection_mass(z, q):
raw = softmax(z, V)
return 1.0 - sum(raw[t] for t in allowed(q))
def decode(profile="format-confused", constrained=True, max_steps=32):
q = 0
toks = []
states = [q]
for _ in range(max_steps):
z = base_logits(q, profile)
p = masked_probs(z, q) if constrained else softmax(z, V)
tok = max(V, key=lambda t: (p[t], -V.index(t)))
toks.append(tok)
q_next = step(q, tok)
if q_next is None:
return {"tokens": toks, "states": states, "accepted": False}
q = q_next
states.append(q)
if q in ACCEPT:
return {"tokens": toks, "states": states, "accepted": True}
return {"tokens": toks, "states": states, "accepted": False}
def parse_source(tokens):
i = tokens.index('"source"')
return tokens[i + 2].strip('"')
assert allowed(0) == ["{"]
assert set(allowed(3)) == {'"retrieve"', '"lookup"'}
assert allowed(13) == ["<eos>"]
bad = decode("format-confused", constrained=False)
assert bad["accepted"] is False
assert bad["tokens"][0] == '"DROP"'
good = decode("format-confused", constrained=True)
assert good["accepted"] is True
assert good["tokens"] == [
"{", '"tool"', ":", '"retrieve"', ",",
'"source"', ":", '"docs"', ",",
'"k"', ":", "2", "}", "<eos>",
]
z = base_logits(3, "format-confused")
p = masked_probs(z, 3)
assert p['"DROP"'] == 0.0
assert rejection_mass(z, 3) > 0.90
sem = decode("semantic-mismatch", constrained=True)
assert sem["accepted"] is True
assert parse_source(sem["tokens"]) == "tickets"
04
Interactive Demo
Use direct manipulation to connect the explanation to a moving system.
Use the Schema Mask Explorer as a prediction check. At the current automaton state, inspect the raw logits and predict whether the raw highest-logit token survives the schema mask, gets replaced by the highest valid token, or has no valid continuation.
After reveal, compare raw probability mass with the masked-and-renormalized distribution. Then turn the mask off to see a high-logit invalid token break the prefix, or use the semantic-mismatch profile to see the key limitation: schema-valid output can still choose the wrong source for the task.
Live Concept Demo
Explore Structured Decoding: Token Masks From Schema Automata
The stage is code-native and interactive. Use it to test the explanation against the mechanism.
Manipulate one control and predict the visible change.
Commit to what Structured Decoding: Token Masks From Schema Automata should make visible before reading the result.
After The First Pass
Turn the concept into an inspected object.
Once the invariant is visible in the intuition, math, code, and demo, use these panels to inspect the mechanism visually, check source support, practice the idea, and attach a grounded research question.
Mechanism Storyboard
See the idea move before the page explains it
How a schema automaton or parser state turns next-token logits into constraint-valid generation by masking invalid continuations, while leaving truth and task success outside the formal guarantee.

Start with the picture, metaphor, or geometric mechanism.
Before reading further, choose the kind of change Structured Decoding: Token Masks From Schema Automata should make visible.
Visual Inquiry
Make the image answer a mathematical question
How a schema automaton or parser state turns next-token logits into constraint-valid generation by masking invalid continuations, while leaving truth and task success outside the formal guarantee.
Which visible object should carry the first intuition?
Pick the cue that should make Structured Decoding: Token Masks From Schema Automata easier to reason about before the page gives the answer.
Source Grounding
Canonical references for the mechanism on this page.
Grounds guided generation as token-logit masking from finite-state or parser state, with vocabulary indexing for efficient valid-token lookup.
Open sourceGrounds the distinction between schema compliance, coverage, efficiency, and downstream output quality.
Open sourceClaim Review
How a schema automaton or parser state turns next-token logits into constraint-valid generation by masking invalid continuations, while leaving truth and task success outside the formal guarantee.
Claims without a substantive review badge still need exact source-support review.
willard-2023-guided-generation, geng-2025-jsonschemabench
Use equation, code, and demo objects to check whether the source support is operational.
Willard and Louf support FSM/parser state plus token-logit masks that zero invalid vocabulary continuations. Geng et al. support constrained decoding as invalid-token masking from constraints and prefix tokens, and evaluate schema compliance separately from coverage, efficiency, and output quality.
Sources: Efficient Guided Generation for Large Language Models, JSONSchemaBench: A Rigorous Benchmark of Structured Outputs for Language ModelsChecks the formal constraint mechanism, not semantic correctness. Real JSON Schema guarantees depend on tokenizer handling, schema-feature coverage, implementation details, and validation semantics. Top-p-after-mask is a local implementation warning.A bounded review summary is present; still check caveats and exact source scope.Willard and Louf support the mask mechanism: guided generation uses FSM/parser state to compute valid vocabulary continuations and zero invalid-token probability. Geng et al. support structured-output framing and the separation between schema compliance, coverage, efficiency, and output quality. Page math/code/demo are toy token-level witnesses; validity is formal, not truth/task success.
Reviewer: codex+oracle; reviewed 2026-05-07Source support candidates
paper 2023Efficient Guided Generation for Large Language ModelsGrounds guided generation as token-logit masking from finite-state or parser state, with vocabulary indexing for efficient valid-token lookup.
paper 2025JSONSchemaBench: A Rigorous Benchmark of Structured Outputs for Language ModelsGrounds the distinction between schema compliance, coverage, efficiency, and downstream output quality.
Practice Loop
Try the idea before it explains itself
How a schema automaton or parser state turns next-token logits into constraint-valid generation by masking invalid continuations, while leaving truth and task success outside the formal guarantee.
Before touching the demo, predict one visible change that should happen in Structured Decoding: Token Masks From Schema Automata.
Reveal when your model needs a nudge.
Reveal when your model needs a nudge.
Reveal when your model needs a nudge.
A concrete answer is on the canvas.
The answer names why the claim should hold.
It touches the page context or a neighboring idea.
Research Room
Attach the question to an exact object
Pick the concept, equation, source, code witness, claim, misconception, or demo state before asking for help. The handoff stays grounded to that object.Open the draft below to save one note and next action in this browser.
Structured Decoding: Token Masks From Schema Automata
What is the smallest example that makes Structured Decoding: Token Masks From Schema Automata click without losing the math?
Local action draftNo local draft saved yetExpand only when ready to capture one local next action
This draft stays locally in this browser for concept:llm-systems/structured-decoding.
- Source ids to inspect: willard-2023-guided-generation, geng-2025-jsonschemabench
- Definition, prerequisite, and contrast concept links
- The equation or code witness that makes the concept operational
- One demo state that shows the invariant instead of a slogan
- The learner can state the mechanism in their own words
- The learner can name the prerequisite that would repair confusion
- The learner can predict how the mechanism changes under one perturbation
I am working in Continuous Function's research reading room. Object: concept - Structured Decoding: Token Masks From Schema Automata Object key: concept:llm-systems/structured-decoding Context: LLM Systems Anchor id: concept/concept-notebook/llm-systems/structured-decoding Open question: What is the smallest example that makes Structured Decoding: Token Masks From Schema Automata click without losing the math? Evidence to inspect: - Source ids to inspect: willard-2023-guided-generation, geng-2025-jsonschemabench - Definition, prerequisite, and contrast concept links - The equation or code witness that makes the concept operational - One demo state that shows the invariant instead of a slogan What would resolve this: - The learner can state the mechanism in their own words - The learner can name the prerequisite that would repair confusion - The learner can predict how the mechanism changes under one perturbation Answer as a careful research tutor: stay source-grounded, separate verified evidence from assumptions, name the relevant math objects, and end with one next action.
concept/concept-notebook/llm-systems/structured-decoding
concept:llm-systems/structured-decoding