XGrammar让大模型生成结构化输出快100倍,几乎无额外开销。
XGrammar: Flexible and Efficient Structured Generation Engine for Large Language Models
- 分词预检+动态栈机制,加速语法解析
- 实测比现有方案快100倍,端到端近乎零延迟
- 适合需要高效结构化输出的智能体应用
大型语言模型智能体的应用日益复杂多样,对可解析为代码、结构化函数调用和具身智能体指令的结构化输出需求激增。上下文无关文法是通过约束解码实现结构化生成的灵活方法,但运行时需遍历所有词汇表中的标记并维护多个栈状态,带来显著开销。本文提出XGrammar,一种高效且灵活的结构化生成引擎。该方法将词汇表划分为可预先检查的上下文无关标记与运行时需动态解释的上下文相关标记,并通过语法扩展减少前者数量。同时构建高效的持久化栈加速上下文相关标记检查。最后,将语法引擎与LLM推理引擎协同设计,使语法计算与GPU执行重叠。实验表明,XGrammar相比现有方案最高提速100倍。结合LLM推理引擎后,可在端到端低延迟服务中实现近乎零开销的结构化生成。
原文摘要 · Abstract (English)
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.
Thank you to arXiv for use of its open access interoperability. PaperDance 不是 arXiv 官方产品;中文卡片由大模型生成,请以原文为准。