arXivDaily arXiv每日学术速递 周一至周五更新
感恩节,周五至周末无更新,大家顺遂。周一再来吧
arXiv 2504.09246cs.LGcs.PL
收藏

基于类型约束的语言模型代码生成

Type-Constrained Code Generation with Language Models

ETH Zurich(苏黎世联邦理工学院)

Niels Mündler, Jingxuan He, Hao Wang, Koushik Sen, Dawn Song, Martin Vechev

AI总结:

本文提出一种类型约束解码方法,通过前缀自动机和可居留类型搜索强制LLM生成类型正确的代码,在HumanEval和MBPP上将编译错误减少一半以上并显著提升功能正确性。

摘要:

大型语言模型(LLMs)在代码生成方面取得了显著成功。然而,由于它们的下一token推理过程并未对代码的形式化方面进行建模,它们仍然经常生成无法编译的输出。尽管约束解码是缓解这一问题的一种有前景的方法,但它目前仅被应用于处理领域特定语言或通用编程语言的语法特征。然而,LLMs经常生成带有类型错误的代码,这类错误超出了语法范畴,并且通常难以被充分约束。为了解决这一挑战,我们引入了一种类型约束解码方法,利用类型系统来引导代码生成。为此,我们开发了新颖的前缀自动机以及一种对可居留类型的搜索方法,形成了一种可靠的方法来强制LLM生成的代码具有良好的类型正确性。我们在一个基础简单类型语言上将我们的方法形式化,并将其扩展到TypeScript以证明其实用性。我们在HumanEval和MBPP数据集上的评估表明,我们的方法将编译错误减少了一半以上,并在代码合成、翻译和修复任务中显著提高了功能正确性,涵盖了不同规模和模型家族的LLMs,包括参数超过30B的最先进开放权重模型。结果证明了我们的方法在利用类型系统的形式化规则约束LLM代码生成方面的通用性和有效性。

英文摘要:

Large language models (LLMs) have achieved notable success in code generation. However, they still frequently produce uncompilable output because their next-token inference procedure does not model formal aspects of code. Although constrained decoding is a promising approach to alleviate this issue, it has only been applied to handle either domain-specific languages or syntactic features of general-purpose programming languages. However, LLMs frequently generate code with typing errors, which are beyond the domain of syntax and generally hard to adequately constrain. To address this challenge, we introduce a type-constrained decoding approach that leverages type systems to guide code generation. For this purpose, we develop novel prefix automata and a search over inhabitable types, forming a sound approach to enforce well-typedness on LLM-generated code. We formalize our approach on a foundational simply-typed language and extend it to TypeScript to demonstrate practicality. Our evaluation on the HumanEval and MBPP datasets shows that our approach reduces compilation errors by more than half and significantly increases functional correctness in code synthesis, translation, and repair tasks across LLMs of various sizes and model families, including state-of-the-art open-weight models with more than 30B parameters. The results demonstrate the generality and effectiveness of our approach in constraining LLM code generation with formal rules of type systems.

机构、总结、中文摘要均由AI分析而来,可能存在错误,请以论文正文为准。

↑