TL;DR
Constrained decoding forces Large Language Models (LLMs) to strictly output valid structured formats (like JSON or domain-specific languages) via Context-Free Grammars (CFGs), but traditionally incurs massive runtime latency when checking large vocabularies against parsing stacks. XGrammar eliminates this bottleneck by precomputing the validity of context-independent tokens into an adaptive cache, pruning context-dependent checks through grammar expansion, and overlapping CPU mask generation with GPU inference. The result is up to a 100× per-token speedup over existing CFG decoders and near-zero latency overhead in end-to-end LLM serving.
What Problem Does This Paper Address?
When using LLMs for tool use, function calling, or code generation, downstream systems require strict syntactic adherence (e.g., valid JSON, SQL, or XML). While Context-Free Grammars (CFGs) offer the recursive expressiveness needed to define these formats, enforcing CFG constraints during auto-regressive generation is notoriously expensive:
- Massive Vocabularies: Modern tokenizers contain 32k to 128k+ tokens. Validating which tokens can legally follow at every decoding step creates huge computational overhead.
- Infinite Stack States: Unlike regular expressions handled by finite-state automata, CFGs rely on a pushdown stack to track nested rules, making exhaustive state precomputation impossible.
- Misaligned Token Boundaries: LLM tokens often span across arbitrary character boundaries, operators, or sub-UTF-8 byte sequences, triggering complex stack pushes and pops mid-token.
Prior tools either resorted to regex approximations (which fail on nested structures like arbitrary JSON), suffered large initialization costs, or evaluated every single token on the fly at runtime, creating severe bottlenecks during serving.
Methods
XGrammar models CFGs using a byte-level Pushdown Automaton (PDA) and applies several systems-level and algorithmic optimizations:
- Adaptive Token Mask Cache: XGrammar observes that token validation falls into three cases: entering a child rule, moving within the current rule, or completing a rule and returning to a parent. Only the third case depends on the deeper stack history. The paper designates the first two as context-independent tokens (the vast majority) and precomputes their validity keyed solely by the current automaton node. An adaptive storage scheme (storing sparse accepted arrays, sparse rejected arrays, or bitsets) reduces memory overhead by over 99%.
- Context Expansion: To minimize the remaining context-dependent tokens that must be checked dynamically at runtime, XGrammar statically inspects the parent rules via depth-first search to extract an expanded suffix automaton. If an uncompleted token's suffix cannot match what the parent rule legally accepts next, it is eliminated upfront during preprocessing.
- Persistent Execution Stack: Instead of copying parsing stacks when grammar ambiguities create multiple branches, XGrammar organizes parallel and historical stacks into a shared tree structure. This enables $O(1)$ state rollbacks and lets the engine process lexically sorted tokens by skipping shared prefixes.
- Automata Optimizations: Techniques adapted from compiler theory—specifically fragment rule inlining and node/epsilon-transition merging—minimize nondeterminism and reduce runtime stack proliferation.
- CPU-GPU Pipelining: Because token mask generation runs on the CPU and only requires the prior token, it is executed concurrently with the GPU forward pass (LLM prefill or decode), synchronizing only right before logits sampling.
Datasets
The authors evaluate XGrammar across several structured generation benchmarks:
json-mode-eval(NousResearch): Used for JSON Schema and unconstrained JSON benchmarks, evaluating structured extraction and function calling.- Synthetic XML Dataset: Testing nested XML code generation conforming to the XML 1.0 standard.
- Synthetic Python DSL Dataset: Adapted from the official Python grammar specification, covering basic control flow (
if,for,while) and standard primitive types.
Key Insights and Ideas
- Most tokens do not care about deep grammar history: More than 99% of vocabulary tokens in tasks like JSON parsing depend solely on the current grammar state, not the entire stack trace. Splitting the problem into context-independent (cached) and context-dependent (runtime-checked) tokens radically trims redundant computations.
- Context information can travel backwards: By looking ahead into parent rules during compilation (Context Expansion), the system can statically identify that strings valid in isolation are guaranteed to fail in the parent context, cutting remaining runtime checks by 90%.
- Grammar parsing hides in GPU latency: For typical batch sizes, computing masks on the host CPU takes less wall-clock time than running the transformer forward pass on the GPU. Overlapping them masks the cost of grammar enforcement almost entirely.
Key Results
- Per-Token Mask Latency: Under 40 µs/token for JSON Schema and unconstrained JSON, and under 200 µs/token for XML and Python DSL (evaluated on Llama-3.1-8B-Instruct). This represents up to a 3× speedup on regex/JSON Schema and over 100× speedup on general CFGs compared to baselines like Outlines and
llama.cpp. - End-to-End Serving Throughput: When integrated into SGLang and MLC-LLM on an NVIDIA H100 GPU, XGrammar achieved up to an 80× improvement in output token generation rate compared to competing solutions under high batch sizes.
- Zero-Overhead Serving: In MLC-LLM, running with structured constraints introduced virtually no latency penalty over unconstrained decoding (e.g., 6.2 ms vs. 6.3 ms Time Per Output Token).
- Correctness: Achieved 100% syntactic correctness on function calling and XML generation tasks, compared to 62% and 80% without grammar enforcement.
- Edge Deployment: Successfully compiled via WebAssembly for client-side execution in WebLLM, adding near-zero overhead on an Apple M3 Max and an iPhone 14 Pro Max.
Limitations and Future Work
- Bounded DFS in Context Expansion: To prevent infinite loops caused by recursive grammar definitions, the context expansion algorithm avoids following rule-referencing edges when extracting expanded suffixes. While fragment rule inlining mitigates this, some deep contextual pruning opportunities remain unexploited.
- Ambiguous Grammars: If a CFG exhibits high structural ambiguity, maintaining multiple branches in the persistent stack still consumes CPU cycles during runtime resolution.
- Future Directions: Expanding integrations across additional serving engines (e.g., TensorRT-LLM, vLLM) and exploring more intricate agentic DSLs and multi-modal structured outputs.
Summary updated