Concept notebookChecking saved investigationReading browser-local route memory before showing a continuation.

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.

published · difficulty 4/5 · 22 min read

01

01

Intuition

Build the mental picture first so the rest of the page has something to attach to.

PredictName the object in plain language, then predict what should change.Leave with one reusable mental picture before notation appears.

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.

Section prompt

Copy-only prompts — each action copies a page-grounded prompt to your clipboard. Nothing is sent by this site.

02

02

Math

Translate the story into symbols, assumptions, and a derivation you can inspect.

InspectTrack the same object through the notation and check each symbol.Leave with the invariant the equations preserve.

Let V\mathcal VV be a fixed finite token vocabulary, including an end token <eos>\texttt{<eos>}<eos>.

Represent the schema as a deterministic finite automaton

A=(Q,V,δ,q0,F),δ:Q×VQ.A=(Q,\mathcal V,\delta,q_0,F),\qquad \delta:Q\times\mathcal V\rightharpoonup Q.A=(Q,V,δ,q0,F),δ:Q×VQ.

For a prefix y1:ty_{1:t}y1:t, the schema state is qt=δ\*(q0,y1:t)q_t=\delta^\*(q_0,y_{1:t})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)\ell_t(v)t(v) and temperature τ\tauτ, constrained decoding uses

M(qt)={vV:δ(qt,v) is defined and can reach F},pA(vy1:t)=exp(t(v)/τ)1[vM(qt)]uM(qt)exp(t(u)/τ).M(q_t)= \{v\in\mathcal V:\delta(q_t,v)\ \mathrm{is\ defined\ and\ can\ reach}\ F\}, \qquad p_A(v\mid y_{1:t})= \frac{\exp(\ell_t(v)/\tau)\mathbf 1[v\in M(q_t)]} {\sum_{u\in M(q_t)}\exp(\ell_t(u)/\tau)}.M(qt)={vV:δ(qt,v) is defined and can reach F},pA(vy1:t)=uM(qt)exp(t(u)/τ)exp(t(v)/τ)1[vM(qt)].

Then a decoder selects or samples yt+1y_{t+1}yt+1 from pAp_ApA and updates

qt+1=δ(qt,yt+1).q_{t+1}=\delta(q_t,y_{t+1}).qt+1=δ(qt,yt+1).

Stopping is accepted only when qt+1Fq_{t+1}\in Fqt+1F, usually after an explicit <eos>\texttt{<eos>}<eos> token.

If top-ppp is used, the hard schema mask should be applied first, then top-ppp truncates and renormalizes inside the valid set. Applying top-ppp 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)M(q_t)M(qt) and the run stops in FFF, then the token sequence is in L(A)L(A)L(A). Nothing follows about whether the content is true, useful, task-correct, or semantically correct; safety is likewise outside a formal syntax guarantee.

Section prompt

Copy-only prompts — each action copies a page-grounded prompt to your clipboard. Nothing is sent by this site.

03

03

Code

Keep the implementation aligned with the notation so the algorithm is legible.

TraceMatch variables to symbols before reading the implementation.Leave with a runnable witness for the math.

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"
Section prompt

Copy-only prompts — each action copies a page-grounded prompt to your clipboard. Nothing is sent by this site.

04

04

Interactive Demo

Use direct manipulation to connect the explanation to a moving system.

ManipulateChange one control and predict the visible response before reveal.Leave with the observed invariant or a repaired model.

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.

difficulty 4/5undergraduatecode-aligned
Demo inquiry checkpoint

Manipulate one control and predict the visible change.

01Choose lensTrace a quantity
02ObserveDemo state pending
03GroundName the equation, invariant, or control that explains it.
04CarryNext: Retrieval-Augmented Generation: External Memory for Generation

Choose what to inspect in Structured Decoding: Token Masks From Schema Automata. This shared fallback is an observation guide, not evidence of learning.

Loading interactive demo...

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.

Section prompt

Copy-only prompts — each action copies a page-grounded prompt to your clipboard. Nothing is sent by this site.

4/4 sections ready

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?

BeforeDecoding & Sampling: Temperature, Top-p & Inference-Time ControlNow4/4 sections readyTryManipulate one control and predict the visible change.NextRetrieval-Augmented Generation: External Memory for Generation
Object contextLLM Systems
ConceptLearner lens

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?

Mode questionCan I say the mechanism back in one sentence before I reveal anything?

Start with the prediction checkpoint, then compare the reveal to the mental model.

Take this move

Study modes

Keep the object fixed; change the lens.

Route back through the notebook

Carry the same object through intuition, math, code, and demo.

4/4 sections ready
Carry inDecoding & Sampling: Temperature, Top-p & Inference-Time Control

Bring the mental model from Decoding & Sampling: Temperature, Top-p & Inference-Time Control; this page will reuse it instead of restarting from zero.

Work hereStructured 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.

Carry outRetrieval-Augmented Generation: External Memory for Generation

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.
ConceptStructured Decoding: Token Masks From Schema AutomataLLM Systems

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.

Demo notes open01 / Intuition
Editorial systems illustration of an automaton gating valid token paths.
Prediction lens

Start with the picture, metaphor, or geometric mechanism.

Commit first

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.

4/4 stages readyDemo notes connected
Prediction

Which visible object should carry the first intuition?

Commit first

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.

Object - ConceptStructured Decoding: Token Masks From Schema AutomataQuestion

What is the smallest example that makes Structured Decoding: Token Masks From Schema Automata click without losing the math?

concept:llm-systems/structured-decoding
Boundary

sources: willard-2023-guided-generation, geng-2025-jsonschemabench

Check

Open the closest source note before trusting the local explanation.

Evidence

2 selected-object sources shown first; 2 references total.

Next move

Audit the claim boundary, then ask from the same selected object.

selected object source · paper · 2023Efficient Guided Generation for Large Language ModelsWillard and Louf
Located CF editorial boundary

Grounds guided generation as token-logit masking from finite-state or parser state, with vocabulary indexing for efficient valid-token lookup.

Used here as

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...

Caveat

Checks the formal constraint mechanism, not semantic correctness. Real JSON Schema guarantees depend on tokenizer handling, schema-feature coverage, implementation details, and validation...

Open source
selected object source · paper · 2025JSONSchemaBench: A Rigorous Benchmark of Structured Outputs for Language ModelsGeng et al.
Located CF editorial boundary

Grounds the distinction between schema compliance, coverage, efficiency, and downstream output quality.

Used here as

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...

Caveat

Checks the formal constraint mechanism, not semantic correctness. Real JSON Schema guarantees depend on tokenizer handling, schema-feature coverage, implementation details, and validation...

Open source

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.

Object - ConceptStructured Decoding: Token Masks From Schema AutomataQuestion

What is the smallest example that makes Structured Decoding: Token Masks From Schema Automata click without losing the math?

concept:llm-systems/structured-decoding
Boundary

sources: willard-2023-guided-generation, geng-2025-jsonschemabench

Check

Treat every claim as provisional until source support and a local witness agree.

Evidence

1 structured claim check on this concept.

Next move

Run the prediction or practice transfer before asking for a grounded review.

1 CF editorial source-scope review recorded

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.

Structured decoding can turn a schema or grammar state into an allowed-token mask, forcing generation to stay inside the formal constraint while leaving semantic truth and task success outside the guarantee.
Used here as

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...

Local witness
Equation 1
A=(Q,V,δ,q0,F),δ:Q×VQ.A=(Q,\mathcal V,\delta,q_0,F),\qquad \delta:Q\times\mathcal V\rightharpoonup Q.
Equation 2
M(qt)={vV:δ(qt,v) is defined and can reach F},pA(vy1:t)=exp(t(v)/τ)1[vM(qt)]uM(qt)exp(t(u)/τ).M(q_t)= \{v\in\mathcal V:\delta(q_t,v)\ \mathrm{is\ defined\ and\ can\ reach}\ F\}, \qquad p_A(v\mid y_{1:t})= \frac{\exp(\ell_t(v)/\tau)\mathbf 1[v\in M(q_t)]} {\sum_{u\in M(q_t)}\exp(\ell_t(u)/\tau)}.
Caveat

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...

Review stateCF editorial source-scope reviewClaim metadata: source checkedPublisher-side editorial review only; not independent replication. 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-07

Practice 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.

AttemptNo learning claim inferred
Object - ConceptStructured Decoding: Token Masks From Schema AutomataQuestion

What is the smallest example that makes Structured Decoding: Token Masks From Schema Automata click without losing the math?

concept:llm-systems/structured-decoding
Boundary

sources: willard-2023-guided-generation, geng-2025-jsonschemabench

Check

Use one state from Structured Decoding: Token Masks From Schema Automata to explain what changes, why it changes, and which assumption the explanation needs.

Evidence

No learner move yet; no learning state is inferred.

Next move

Write first, use only the help you need, then try a new case without it.

Explain

Use one state from Structured Decoding: Token Masks From Schema Automata to explain what changes, why it changes, and which assumption the explanation needs.

Hint 1

Reveal when your model needs a nudge.

Hint 2

Reveal when your model needs a nudge.

Hint 3

Reveal when your model needs a nudge.

Grounded object roomClose
Selected object routeAsk from this object; carry one invariant back.sources: willard-2023-guided-generation, geng-2025-jsonschemabench
  1. ObjectConceptStructured Decoding: Token Masks From Schema Automata
  2. PredictBefore revealStructured Decoding: Token Masks From Schema Automata prediction
  3. WitnessCompare codeStructured Decoding: Token Masks From Schema Automata code witness 1
  4. RoomAsk groundedChecking local snapshot
ConceptStructured Decoding: Token Masks From Schema AutomataLLM Systems

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.
Next local actionNo local draft saved yet

Open the draft below to save one note and next action in this browser.

conceptLLM Systems

Structured Decoding: Token Masks From Schema Automata

Anchored question

What is the smallest example that makes Structured Decoding: Token Masks From Schema Automata click without losing the math?

Source boundaryInspect source ids: willard-2023-guided-generation, geng-2025-jsonschemabenchStable content-object key attached
Role lenses for this object

These are fixed, deterministic perspectives derived from the selected object. They do not represent people, community contributions, or independent review.

Learner evidence requestAsk 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.

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.

Next action

The learner can state the mechanism in their own words

Evidence4 checks
PredictionChecking carried observation
ActionReady for one action
AILearner handoff ready
Open source object
01PredictionChecking browser-local route memory
02EvidenceChecking for a carried observation
03BoundaryInspect source ids: willard-2023-guided-generation, geng-2025-jsonschemabench
04Next moveSave one next action
Local action draftNo local draft saved yetExpand only when ready to capture one local next action
Local action draft

This draft stays locally in this browser for concept:llm-systems/structured-decoding.

No local draft saved.
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
Object-attached AI handoff

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