🧬 Deterministic Schemas • XGrammar • Outlines • vLLM Guided Decoding
Structured Outputs: Constrained Decoding & FSM Grammars
How modern inference engines compile Pydantic v2 and JSON Schemas into Finite State Machines (FSMs) and pushdown automata to mask invalid logits at the sampler level—guaranteeing 100% schema compliance with zero retry loops.
⚡ 30-Second Grammar Engine Benchmark
| Engine | Grammar Automaton | Per-Token Mask Latency | Jump-Forward / Fast-Forward Tokens |
|---|---|---|---|
| XGrammar (vLLM / SGLang Default) | Byte-level Pushdown Automaton + Adaptive Token Mask Cache | < 40 µs / token | Yes: Auto-inserts deterministic JSON boilerplate keys without GPU forward passes. |
| Outlines (dottxt) | Regex-compiled Finite State Machine (FSM) index | ~100 µs / token | Yes: Zero-overhead deterministic transitions on single-path states. |
| Prompt-Only JSON Mode (Legacy) | None (Validation + LLM Retry Loop) | +600–1,800 ms on retry | No: Wastes full GPU forward pass for every syntax bracket and key name. |
01 How FSM Logit Masking & Fast-Forwarding Work in Python
import math
from typing import Dict, List
class FSMLogitProcessor:
"""
Demonstrates how Outlines / XGrammar constrain LLM token sampling at 0 retry cost.
transitions[state_id] = {token_id: next_state_id}
"""
def __init__(self, transitions: Dict[int, Dict[int, int]]):
self.transitions = transitions
self.state = 0
def mask_logits(self, raw_logits: List[float]) -> List[float]:
allowed_tokens = self.transitions.get(self.state, {})
return [
logit if tok_id in allowed_tokens else -math.inf
for tok_id, logit in enumerate(raw_logits)
]
def can_jump_forward(self) -> int | None:
# If current FSM state has exactly 1 valid outgoing token (e.g. '{"action": "'),
# emit it directly on CPU without running a GPU Transformer forward pass!
allowed = self.transitions.get(self.state, {})
if len(allowed) == 1:
tok_id, next_state = next(iter(allowed.items()))
self.state = next_state
return tok_id
return None