How grammar-guided logit masking guarantees valid syntax
At every decode step, a language model outputs a vector of raw scores (logits) over its entire vocabulary V. Unconstrained sampling converts all V logits into probabilities, giving nonzero mass to tokens that violate your target schema. Constrained decoding tracks parser state alongside sequence generation and sets disallowed token logits to -∞ before softmax.
| Approach | Syntax guarantee | Latency and token cost |
|---|---|---|
| Prompt instructions + parser retry | None on first pass; retries multiply tail latency | Wastes prefill and decode tokens whenever validation fails |
| Regex / FSM constrained decoding | Exact match for regular languages and flat/bounded JSON schemas | Near-zero per-step overhead with precomputed token bitmasks; supports jump-forward |
| Pushdown / CFG decoding (XGrammar, llguidance) | Exact match for recursive schemas, SQL, and DSLs | Sub-millisecond CPU stack + bitmask generation overlapped with GPU execution |
Naively testing 128,000 BPE strings against a regex on every decode step would bottleneck the CPU. Outlines solved this for regular expressions and JSON schemas by indexing the tokenizer vocabulary against deterministic finite-state machine (FSM) states offline, storing a compact allowed-token bitmask per state. XGrammar extended low-overhead masking to full context-free grammars by separating context-independent token masks from tiny dynamic stack checks.
Trace FSM logit masking and jump-forward in Python
Notice two wins when a schema compiles into a token-level FSM: first, chatty preambles (" sure") receive -inf and can never be sampled; second, whenever an FSM state allows only one valid token (such as "{" or '"status":'), the engine can append those deterministic tokens without running a full GPU decode step per character—a technique SGLang calls compressed finite-state jump-forward decoding.
vocab = ["{", '"status":', ' "ok"', ' "error"', "}", " sure", " ```"]
# FSM transitions for {"status": "ok"|"error"}: state -> {token_id: next_state}
fsm = {
0: {0: 1}, # deterministic: must emit "{"
1: {1: 2}, # deterministic: must emit '"status":'
2: {2: 3, 3: 3}, # model chooses between ' "ok"' and ' "error"'
3: {4: 4}, # deterministic: must emit "}"
}
raw_logits_at_choice = [0.4, 0.2, 2.1, 1.3, 0.1, 4.8, 3.9] # model prefers " sure"!
state, output, model_calls = 0, [], 0
while state != 4:
allowed = fsm[state]
if len(allowed) == 1: # jump-forward deterministic boilerplate
tok_id, state = next(iter(allowed.items()))
output.append(vocab[tok_id])
else:
model_calls += 1
masked = [score if i in allowed else float("-inf")
for i, score in enumerate(raw_logits_at_choice)]
tok_id = max(range(len(vocab)), key=masked.__getitem__)
output.append(vocab[tok_id])
state = allowed[tok_id]
print("Generated:", "".join(output))
print(f"Decision steps requiring model logits: {model_calls} (out of {len(output)} tokens)")Generated: {"status": "ok"}
Decision steps requiring model logits: 1 (out of 4 tokens)Even though " sure" (4.8) and " `" (3.9) had higher raw logits than valid JSON values, masking guaranteed {"status": "ok"} on the first pass. When compressed tokens are appended via jump-forward, the engine runs a single multi-token prefill/extension pass over the inserted boilerplate so the KV cache stays exact before the next branching decision. Implement full FSM masking yourself in Finite-State Constrained Decoding.
Jump-forward boilerplate, then mask invalid logits at branch points
- "ok" ✓
- "error" ✓
- sure ×
- ``` ×
Disallowed tokens receive −∞ so chatty prose or markdown fences cannot be sampled.
- {
- "status":
- "ok"
- }
Single-transition states insert deterministic syntax directly; the model chooses among valid schema branches.
Four failure modes to guard against in production
- Syntax validity is not semantic accuracy. Forcing JSON without mentioning the schema in the system prompt makes the model discover field names blindly via logit masks, degrading answer quality. Always include concise field descriptions in the prompt AND attach
response_formatortools. - Unbounded whitespace or optional loops. Loose regexes or schemas that permit infinite spaces/newlines allow a confused model to spin until
max_tokenstruncates the JSON mid-object. Bound array lengths (maxItems) and string patterns where practical. - First-schema compilation cold start. Compiling a large recursive JSON Schema for the first time can take tens or hundreds of milliseconds on CPU. Reuse canonical schema definitions across requests so vLLM structured outputs and SGLang structured outputs hit their in-memory grammar caches.
- Reasoning traces plus JSON. Reasoning models need unconstrained
<think>...</think>tokens before schema enforcement begins; configure reasoning parsers alongside tool-call parsers in our vLLM & SGLang command builder.
Structured outputs and constrained decoding FAQ
Does constrained decoding slow down every decode step?
Modern backends such as XGrammar and compressed FSMs compute bitmasks on the CPU in microseconds and overlap mask transfer with GPU execution, often matching—or with jump-forward, beating—unconstrained latency.
Why did my constrained JSON response still fail json.loads()?
Almost always because generation hit max_tokens before reaching a terminal FSM state; check finish_reason == "length" before parsing.
What is the difference between response_format (json_schema) and tools function calling?
json_schema constrains the entire assistant message to one schema, whereas tools lets the model choose whether to reply in natural language or emit one or more structured tool calls parsed via --tool-call-parser.
Sources and further reading
Primary documentation and research behind this guide.
- Efficient Guided Generation for Large Language Models (Outlines, 2023)
- XGrammar: Flexible and Efficient Structured Generation Engine for Large Language Models (2024)
- LMSYS Org: Fast JSON Decoding for Local LLMs with Compressed Finite State Machine
- vLLM v0.30.0: Structured outputs
- SGLang: Structured outputs and jump-forward decoding
