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.

status: publishedimportance: importantdifficulty 4/5math: undergraduateread: 22mlive demo
Editorial systems illustration of an automaton gating valid token paths.

Concept Structure

Structured Decoding: Token Masks From Schema Automata

01Intuition

Start with the picture, metaphor, or geometric mechanism.

02Math

Make the objects explicit and connect them with notation.

03Code

Mirror the equations with runnable implementation details.

04Interactive Demo

Manipulate the mechanism and watch the idea respond.

2prerequisites
1next concepts
3related links

Learning map

Structured Decoding: Token Masks From Schema Automata
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 flow

4/4 sections readyAsk about thisResearch room
ConceptStructured Decoding: Token Masks From Schema AutomataLLM Systems
2 sources attachedLocal snapshot ready
concept:llm-systems/structured-decoding

Conceptual Bridge

What should feel connected as you move through this page.

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.

Test the linkManipulate one control and predict the visible change.Then continue to Retrieval-Augmented Generation: External Memory for Generation
01

01

Intuition

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

Section prompt

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

02

Math

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

Section prompt

Let V\mathcal V be a fixed finite token vocabulary, including an end token <eos>\texttt{<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.

For a prefix y1:ty_{1:t}, the schema state is qt=δ\*(q0,y1:t)q_t=\delta^\*(q_0,y_{1: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) 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)}.

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

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

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

If top-pp is used, the hard schema mask should be applied first, then top-pp truncates and renormalizes inside the valid set. Applying top-pp 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) and the run stops in FF, then the token sequence is in 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.

03

03

Code

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

Section prompt

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

04

Interactive Demo

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

Section prompt

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.

difficulty 4/5undergraduatecode-aligned
Demo Prediction Checkpoint

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.

Prediction 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 readyLive demo 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.

paper · 2023Efficient Guided Generation for Large Language ModelsWillard and Louf

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

Open source
paper · 2025JSONSchemaBench: A Rigorous Benchmark of Structured Outputs for Language ModelsGeng et al.

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

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.

Status1 substantive review recorded

Claims without a substantive review badge still need exact source-support review.

Sources2 references

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

Witnesses4 local objects

Use equation, code, and demo objects to check whether the source support is operational.

Substantively reviewedStructured 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.Claim metadata: source checked

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

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.

Readiness0/3 checks ready
Predict

Before touching the demo, predict one visible change that should happen in Structured Decoding: Token Masks From Schema Automata.

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.

Object research drawerClose
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?

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

Open source object
concept/concept-notebook/llm-systems/structured-decoding concept:llm-systems/structured-decoding