XGrammar: Flexible and Efficient Structured Generation Engine for Large Language Models

Yixin Dong, Charlie F. Ruan, Yaxing Cai, Ruihang Lai, Ziyi Xu +2 more
11/22/2024
cs.CLcs.AIcs.PL

No official code found. Best implementation: mlc-ai/xgrammar (1,792 stars, Apache-2.0, last commit 2026-05-01).

Abstract

The applications of LLM Agents are becoming increasingly complex and diverse, leading to a high demand for structured outputs that can be parsed into code, structured function calls, and embodied agent commands. These developments bring significant demands for structured generation in LLM inference. Context-free grammar is a flexible approach to enable structured generation via constrained decoding. However, executing context-free grammar requires going through several stack states over all tokens in vocabulary during runtime, bringing non-negligible overhead for structured generation. In this paper, we propose XGrammar, a flexible and efficient structure generation engine for large language models. XGrammar accelerates context-free grammar execution by dividing the vocabulary into context-independent tokens that can be prechecked and context-dependent tokens that need to be interpreted during runtime. We further build transformations to expand the grammar context and reduce the number of context-independent tokens. Additionally, we build an efficient persistent stack to accelerate the context-dependent token checks. Finally, we co-design the grammar engine with LLM inference engine to overlap grammar computation with GPU executions. Evaluation results show that XGrammar can achieve up to 100x speedup over existing solutions. Combined with an LLM inference engine, it can generate near-zero overhead structure generation in end-to-end low-LLM serving.

View on arXivView PDF

Code Implementations(1)

mlc-ai/xgrammarCommunity72%
Apache-2.0

Fast, Flexible and Portable Structured Generation

1,792175C, C++Jun 28, 20245 months agoApache-2.0
large-language-modelsstructured-generation

Similar Papers

Cite this paper

@article{dong2024xgrammar,
  title  = {XGrammar: Flexible and Efficient Structured Generation Engine for Large Language Models},
  author = {Yixin Dong and Charlie F. Ruan and Yaxing Cai and Ruihang Lai and Ziyi Xu and Yilong Zhao and Tianqi Chen},
  year   = {2024},
  eprint = {2411.15100},
  archivePrefix = {arXiv},
  url    = {http://arxiv.org/abs/2411.15100v3}
}

Add a badge to your README

Shows whether official code is linked for this paper.

Code of Paper badge
[![Code of Paper](https://codeofpaper.com/badge/2411.15100.svg)](https://codeofpaper.com/paper/2411.15100)

Discussion