Bring the mental model from Decoding & Sampling: Temperature, Top-p & Inference-Time Control; this page will reuse it instead of restarting from zero.
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.
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.
Copy-only prompts — each action copies a page-grounded prompt to your clipboard. Nothing is sent by this site.
02
Math
Translate the story into symbols, assumptions, and a derivation you can inspect.
Let V be a fixed finite token vocabulary, including an end token <eos>.
Represent the schema as a deterministic finite automaton
For a prefix y1:t, the schema state is qt=δ\*(q0,y1:t) 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 ℓt(v) and temperature τ, constrained decoding uses
Then a decoder selects or samples yt+1 from pA and updates
Stopping is accepted only when qt+1∈F, usually after an explicit <eos> token.
If top-p is used, the hard schema mask should be applied first, then top-p truncates and renormalizes inside the valid set. Applying top-p 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 M(qt) and the run stops in F, then the token sequence is in L(A). Nothing follows about whether the content is true, useful, task-correct, or semantically correct; safety is likewise outside a formal syntax guarantee.
Copy-only prompts — each action copies a page-grounded prompt to your clipboard. Nothing is sent by this site.
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"
Copy-only prompts — each action copies a page-grounded prompt to your clipboard. Nothing is sent by this site.
04
Interactive Demo
Use direct manipulation to connect the explanation to a moving system.
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.
Choose what to inspect in Structured Decoding: Token Masks From Schema Automata. This shared fallback is an observation guide, not evidence of learning.
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.
Copy-only prompts — each action copies a page-grounded prompt to your clipboard. Nothing is sent by this site.
Concept: 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?
Object contextLLM Systems
concept:llm-systems/structured-decodingStructured 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?
Start with the prediction checkpoint, then compare the reveal to the mental model.
Take this moveStudy modes
Keep the object fixed; change the lens.Route back through the notebook
Carry the same object through intuition, math, code, and demo.
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.
After The First Pass
Turn the concept into an inspected object.
The lower panels are one second act: keep the object fixed, inspect it visually, check source boundaries, practice transfer, then attach the 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.
What is the smallest example that makes Structured Decoding: Token Masks From Schema Automata click without losing the math?
concept:llm-systems/structured-decodingsources: willard-2023-guided-generation, geng-2025-jsonschemabench
Open the closest source note before trusting the local explanation.
2 selected-object sources shown first; 2 references total.
Audit the claim boundary, then ask from the same selected object.
Grounds guided generation as token-logit masking from finite-state or parser state, with vocabulary indexing for efficient valid-token lookup.
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 constra...
Checks the formal constraint mechanism, not semantic correctness. Real JSON Schema guarantees depend on tokenizer handling, schema-feature coverage, implementation details, and validation...
Grounds the distinction between schema compliance, coverage, efficiency, and downstream output quality.
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 constra...
Checks the formal constraint mechanism, not semantic correctness. Real JSON Schema guarantees depend on tokenizer handling, schema-feature coverage, implementation details, and validation...
Claim 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.
What is the smallest example that makes Structured Decoding: Token Masks From Schema Automata click without losing the math?
concept:llm-systems/structured-decodingsources: willard-2023-guided-generation, geng-2025-jsonschemabench
Treat every claim as provisional until source support and a local witness agree.
1 structured claim check on this concept.
Run the prediction or practice transfer before asking for a grounded review.
Publisher-side editorial review is not independent replication. Claims without it still need exact source-support review. 2 references and 3 local witnesses are available for inspection.
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 toke...
Checks 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-af...
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-07Practice notebook
Use the idea, then test it somewhere new
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.
What is the smallest example that makes Structured Decoding: Token Masks From Schema Automata click without losing the math?
concept:llm-systems/structured-decodingsources: willard-2023-guided-generation, geng-2025-jsonschemabench
Use one state from Structured Decoding: Token Masks From Schema Automata to explain what changes, why it changes, and which assumption the explanation needs.
No learner move yet; no learning state is inferred.
Write first, use only the help you need, then try a new case without it.
Use one state from Structured Decoding: Token Masks From Schema Automata to explain what changes, why it changes, and which assumption the explanation needs.
Reveal when your model needs a nudge.
Reveal when your model needs a nudge.
Reveal when your model needs a nudge.
Write an attempt before asking the companion.
0 of 3 progressive hints opened.
This draft and any AI response do not establish mastery; a later unassisted case can.
- ObjectConceptStructured Decoding: Token Masks From Schema Automata
- PredictBefore revealStructured Decoding: Token Masks From Schema Automata prediction
- WitnessCompare codeStructured Decoding: Token Masks From Schema Automata code witness 1
- RoomAsk groundedChecking local snapshot
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?
These are fixed, deterministic perspectives derived from the selected object. They do not represent people, community contributions, or independent review.
Source ids willard-2023-guided-generation, geng-2025-jsonschemabench must support the exact object, not just the surrounding topic.
Treat this as a mechanism object: connect the definition to one equation, code witness, or demo before broadening the discussion.
Ask the learner to perturb one representation, then check whether the same invariant survives in math, code, and demo.
The learner can state the mechanism in their own words
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 Deterministic role lenses for this object: - Boundary: fixed perspectives, not people, community contributions, or independent review - Source-checking summary: Treat this as a mechanism object: connect the definition to one equation, code witness, or demo before broadening the discussion. - Proposed experiment: Ask the learner to perturb one representation, then check whether the same invariant survives in math, code, and demo. - Teach/transfer move: Turn the mechanism into one sentence that predicts a neighboring concept. - Assumptions: - Source ids willard-2023-guided-generation, geng-2025-jsonschemabench must support the exact object, not just the surrounding topic. - The stable content-object key lets local drafts, prompts, and route memory attach without changing the source page. - The concept explanation is local atlas prose until checked against its math, code, and source support. - Prerequisite gaps should become a repair route, not a reason to leave the object vague. - Role-lens requests: - Learner: ask for "Ask what would make "Structured Decoding: Token Masks From Schema Automata" feel predictable rather than familiar." | assumption: Source ids willard-2023-guided-generation, geng-2025-jsonschemabench must support the exact object, not just the surrounding topic. | next action: The learner can state the mechanism in their own words - Researcher: ask for "Source ids to inspect: willard-2023-guided-generation, geng-2025-jsonschemabench" | assumption: The stable content-object key lets local drafts, prompts, and route memory attach without changing the source page. | next action: The learner can name the prerequisite that would repair confusion - Experimenter: ask for "Choose one variable or condition to perturb before asking for an explanation." | assumption: The concept explanation is local atlas prose until checked against its math, code, and source support. | next action: The learner can predict how the mechanism changes under one perturbation - Professor: ask for "Find the smallest transferable rule a learner could reuse without the AI." | assumption: Prerequisite gaps should become a repair route, not a reason to leave the object vague. | next action: Teach or transfer: Turn the mechanism into one sentence that predicts a neighboring concept. 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. Current deterministic role lens for this object: - Role lens: Learner - Evidence request: Ask what would make "Structured Decoding: Token Masks From Schema Automata" feel predictable rather than familiar. - Assumption to keep visible: Source ids willard-2023-guided-generation, geng-2025-jsonschemabench must support the exact object, not just the surrounding topic. - Proposed experiment: Ask the learner to perturb one representation, then check whether the same invariant survives in math, code, and demo. - Next action: The learner can state the mechanism in their own words
concept/concept-notebook/llm-systems/structured-decoding
concept:llm-systems/structured-decoding