Decode-Time Grammars: Constrained LLM Generation over a Refinement Order of Grammar Fragments

Shuoming Zhang, Ruiyuan Xu, Haofeng Li, Qiuchu Yu, Yangyu Zhang, Chunwei Xia, Xiaobing Feng, Chenxi Wang, Huimin Cui, Jiacheng ZhaoarXiv 2026

TL;DR

While grammar-constrained decoding ensures that LLM-generated code is syntactically correct, it cannot prevent semantic hallucinations like referencing undefined variables or missing database columns. This paper introduces decode-time grammars, a method that dynamically updates the token mask based on the evolving runtime environment to eliminate these "ghost references" by construction. Across SQL, P4, and tensor DSLs, this approach achieves perfect reference safety with only a minor impact on generation throughput.

What Problem Does This Paper Address?

When LLMs generate code for domain-specific languages (DSLs), custom APIs, or command-line tools, they frequently hallucinate identifiers. They might reference a buffer that was never allocated, a database column that doesn't exist, or an unsupported CLI flag. The authors term these environment-invalid errors ghost references.

Standard grammar-constrained decoding fails to solve this problem. A fixed context-free grammar (CFG) can easily enforce that an operand must be an identifier, but it cannot ensure that the identifier matches a previously declared variable. Because declaration-before-use consistency is fundamentally non-context-free, the constraint must dynamically adapt to the code that has already been generated.

Fig. 1. Motivation and design insight. Long-tail programming surfaces can produce syntax-valid but environment-invalid ghost references. Partial, property-specific grammar fragments constrain only environment- bound references, while leaving open-ended program choices to the model.

Methods

The authors propose a framework called gproj that shifts grammar constraints from fixed, static rules to dynamic, environment-indexed fragments. The core components include:

  • Decode-Time Grammars & The Tightening Operator ($\tau_\Gamma$): As the LLM generates code, the system tracks the live runtime environment ($\Gamma$), such as declared variables or database schemas. When the model hits a reference position (a "hole"), the tightening operator replaces generic identifier rules with a specific slot containing only the valid candidates currently available in $\Gamma$.
  • Refinement Order ($\sqsubseteq$): Grammars are organized hierarchically from loose (base CFG) to tight (fully pinned values). A per-region policy ($\pi$) decides how strictly to constrain a hole, allowing the system to gracefully fall back to looser constraints if a strict match isn't available.
  • TemplateInductor: To avoid writing these grammar fragments by hand, the authors designed an offline tool that uses anti-unification to automatically learn grammar templates from a small corpus of example programs, validating them through an agentic loop against a strict parser gate.
Fig. 2. Decode-time grammars, end to end. Left: the offline inductor (§§ 4.3) lowers a TileLang corpus into a ladder of grammar fragments ordered by refinement (§§ 4.2); colored slots mark the operand holes they came from, and 𝜏Γ is the edge where the no-ghost guarantee switches on. Right: at decode time the policy 𝜋picks a rung, and 𝜏Γ tightens its open reference positions into slots instantiated from the runtime environment Γ — only Buffer-sort names survive into the token mask; ghost names are not sampleable (Theorem 1).

Datasets

The approach was evaluated across several distinct programming surfaces:

  • TileLang: A low-resource tensor-kernel DSL used for high-performance GPU programming.
  • SQL: Evaluated using database schemas from the standard Spider dataset benchmark.
  • P4: A data-plane programming language for network packet processing (tested on basic.p4 and l2fwd.p4 structures).
  • CLI & APIs: Evaluated using live tool states for Git commands, FFmpeg filter complexes, and AVX-512 compiler headers.

Key Insights and Ideas

  • The "Division of Labor": The authors argue that code generation should split mechanical correctness from open-ended algorithmic choices. The grammar mask handles the mechanical task of ensuring identifiers exist, freeing the LLM to focus entirely on high-level logic, structure, and intent.
  • Dynamic Support is Mathematically Necessary: The paper formally proves that no finite family of precompiled, static grammars can be both ghost-free and non-blocking over an unbounded identifier space. The token mask must be synthesized dynamically from the prefix at runtime.
  • Immunity to Model Size: Because the constraints are enforced at the token-mask level, the "no-ghost" guarantee holds true regardless of whether you are using a lightweight 0.6B parameter model or a massive 236B frontier model. Stronger models simply provide better high-level sketches, while the reference layer remains perfectly secure.

Key Results

  • Zero Ghost References: Across all tested models (Qwen3-0.6B, GPT-OSS-20B, DeepSeek-V4-Flash) and programming languages, gproj eliminated ghost references entirely by construction.
  • Perfect Execution Match: On a difficult subset of Spider SQL tasks, restricting the LLM to the valid schema columns boosted the execution match rate from 76% (unconstrained) to 100% in a single pass, outperforming traditional prompting and retry strategies.
  • Low Serving Overhead: Compared to standard unconstrained decoding, gproj introduces an average throughput reduction of only 17.3%. When compared against standard static masking (XGrammar), the incremental cost of the dynamic runtime specialization is in the low teens (10.6%–17.8%), making it highly practical for production deployment.

Limitations and Future Work

While gproj guarantees that every reference is valid within the environment, it does not guarantee functional correctness. For example, in SQL, the model is prevented from inventing a column, but it can still select the wrong valid column and produce an incorrect query result.

Additionally, the current implementation faces engineering limitations: the Times repetition combinator does not yet support nested grammar calls, and cross-boundary type agreement requires a manual mapping between host and embedded vocabularies. The authors suggest that extending this runtime decode-loop interface to handle richer, stateful semantic monitors and learned switching policies is the next logical step.

Summary updated

BibTeX
@misc{zhang2026decode,
  author = {Shuoming Zhang and Ruiyuan Xu and Haofeng Li and Qiuchu Yu and Yangyu Zhang and Chunwei Xia and Xiaobing Feng and Chenxi Wang and Huimin Cui and Jiacheng Zhao},
  title = {{Decode-Time Grammars: Constrained LLM Generation over a Refinement Order of Grammar Fragments}},
  year = {2026},
  eprint = {2607.18357},
  archivePrefix = {arXiv},
  url = {https://arxiv.org/abs/2607.18357},
}
Figure