WGRAMMAR: Leverage Prior Knowledge to Accelerate Structured Decoding

Ran Wang, Xiaoxuan Liu, Hao Ren, Gang Chen, Fanchao Qi, Maosong SunarXiv 2025

TL;DR

WGrammar is a lightweight structured decoding engine that accelerates constrained LLM generation (like JSON or HTML) by up to 250× for Time-to-First-Token (TTFT) compared to state-of-the-art systems. It achieves this by decomposing constraints into static, offline-precompiled templates and dynamic, runtime arguments, replacing slow pushdown automata with fast, context-free finite state machines.

What Problem Does This Paper Address?

As Large Language Models (LLMs) are increasingly integrated into complex workflows, function calling, and agentic pipelines, ensuring their outputs strictly adhere to specific formats (like JSON schemas or HTML structures) is critical. This process, known as structured decoding, typically relies on Context-Free Grammars (CFGs) enforced via token-level logit masking.

However, existing state-of-the-art libraries (such as Outlines and XGrammar) suffer from severe latency bottlenecks. They parse full CFGs from scratch using Pushdown Automata (PDAs) for every single request. This introduces massive overhead across three stages: grammar compilation, real-time state tracking, and logit mask creation. For complex production tasks, this overhead can add seconds to the Time-to-First-Token (TTFT), severely bottlenecking real-time applications.

Methods

WGrammar introduces a paradigm shift by leveraging the inherent prior knowledge of production workloads. Instead of treating every incoming request as an entirely new, arbitrary grammar, it proposes three key techniques:

  1. Constraint Decomposition: It splits constraints into static components (e.g., fixed HTML tags or JSON keys) and dynamic components (e.g., user arguments). The static structures are precompiled offline using the Earley algorithm to create a reusable "structure factory," while dynamic arguments are quickly injected online using a linear-time LALR(1) parser.
  2. Operator-Based FSM Tracking: Because most real-world structured generation tasks lack deeply nested, recursive grammar, WGrammar replaces heavy PDAs with Finite State Machines (FSMs). It introduces a compositional set of context-free operators—such as Wait, Write, IfElse, Sequence, and DoWhile—to track states in constant time.
  3. Global Mask Caching: Unlike PDAs, whose states are highly context-dependent, WGrammar’s operators are context-free. This allows the engine to globally cache generated logit masks across different requests and decoding steps, turning expensive runtime tensor operations into simple cache lookups.
The collaborative parsing workflow of WGrammar, separating offline template compilation from online argument instantiation.

Datasets

The authors evaluated WGrammar against state-of-the-art baselines using three distinct datasets reflecting production and standard benchmarks:

  • Outline-Generation: A complex task where an LLM generates an abstract summary of a document while strictly preserving its original hierarchical HTML section structure.
  • Reference-Lookup: A task requiring the LLM to identify relevant paragraphs for a given topic and return them in a flat JSON array mapping topics to section IDs.
  • JSON-mode-eval: A standard public benchmark that tests an LLM's ability to strictly follow a provided JSON schema.

Key Insights and Ideas

  • Production Structures are Predictable: The core insight is that production workloads rarely require arbitrary CFG flexibility. The structural skeleton is usually fixed, meaning compiling the entire grammar per request is redundant.
  • Algorithmic Simplicity Beats Low-Level Optimization: Despite being implemented in Python, WGrammar's state tracking stage outperformed XGrammar’s highly optimized C++ implementation by 7× to 8×. This demonstrates that reducing complexity from a PDA stack to an FSM provides a much larger efficiency gain than language-level optimization alone.
  • Context-Free Independence Unlocks Caching: By avoiding the contextual history inherent in pushdown automata, the engine ensures that identical local states yield identical token masks, making global caching highly effective.

Key Results

  • Massive TTFT Acceleration: WGrammar reduces structured decoding TTFT overhead by over 250× compared to XGrammar. On the structurally complex Outline-Generation dataset, XGrammar introduced 2,747.83 ms of TTFT overhead, whereas WGrammar reduced it to just 10.93 ms.
  • Throughput Improvements: WGrammar reduced Time Per Output Token (TPOT) overhead by up to 2.33× compared to XGrammar.
  • Stage-by-Stage Breakdown: Fine-grained analysis on the Outline-Generation task showed a 175× speedup in grammar compilation and a 2× speedup in mask creation due to global caching.
Execution overhead breakdown across grammar compilation, state tracking, and mask creation stages.

Limitations and Future Work

  • Manual Template Design: To achieve optimal performance, developers must manually design the offline templates using WGrammar's backend Domain-Specific Language (DSL), which can introduce friction for users unfamiliar with writing grammars.
  • Non-Greedy Regex Matching: WGrammar utilizes non-greedy matching for regular expressions, which differs from the standard greedy matching behavior common in text processing. Users must be aware of this semantic difference when defining constraints.

Summary updated

BibTeX
@misc{wang2025wgrammar,
  author = {Ran Wang and Xiaoxuan Liu and Hao Ren and Gang Chen and Fanchao Qi and Maosong Sun},
  title = {{WGRAMMAR: Leverage Prior Knowledge to Accelerate Structured Decoding}},
  year = {2025},
  eprint = {2507.16768},
  archivePrefix = {arXiv},
  url = {https://arxiv.org/abs/2507.16768},
}
Figure