基于语言模型的类型约束代码生成
Type-constrained code generation with language models

原始链接: https://arxiv.org/abs/2504.09246

本文介绍了一种基于类型约束的解码方法,以提高大型语言模型 (LLMs) 生成的代码的准确性和可靠性。 文章指出,LLMs 经常由于超出语法约束的类型错误而生成不可编译的代码,因此利用类型系统来指导代码生成。该方法包括开发新颖的前缀自动机和可居住类型搜索策略,以确保生成的代码符合类型系统规则。该方法在一个基础语言上进行了形式化,并扩展到 TypeScript 以证明其实用性。在 HumanEval 和 MBPP 数据集上的评估结果表明,编译错误显著减少(超过一半),并且各种代码生成任务(合成、翻译和修复)的功能正确性大幅提高。这些改进在不同大小和系列的 LLMs 上都观察到了,包括具有超过 300 亿参数的最新开放权重模型,突显了类型约束解码的通用性和有效性。

这篇 Hacker News 讨论帖关注一篇关于利用语言模型 (LLM) 进行类型约束代码生成的论文。其核心思想是利用类型信息来指导 LLM 生成更准确、更可靠的代码。 讨论的一个重点是将 TypeScript 编译器 (tsc) 重写为 Go 的决定。Anders Hejlsberg(TypeScript 的创建者)认为 Go 更快的编译速度可以与 LLM 建立更紧密的反馈循环,从而更快地识别类型错误。尽管 TypeScript 本身就是类型化的,但 Go 的类型系统更简单,类型检查速度更快。 讨论扩展到比较 Go 和 Rust 在编译速度和适用性方面的差异。虽然高度优化的 Rust 版本*可能*更快,但 TypeScript 团队选择将代码近乎 1:1 地移植到 Go,以保留现有编译器的结构,而这在 Rust 中会更难实现。 该讨论帖还提到了其他方法,例如 MultiLSPy(一种用于语言服务器协议的 Python 包装器)、在抽象语法树 (AST) 而不是标记上训练 LLM,以及利用文档来改进代码生成。一些用户分享了他们使用 Devin 等工具的经验,这些工具使用代码执行和测试来改进代码。其他人指出,目前的 LLM 难以处理复杂的 TypeScript 类型错误。LLM 代码生成的回溯技术也被提及。
相关文章
  • (评论) 2024-06-30
  • 大型语言模型理解空值 2025-04-07
  • Typed Lisp 导引 2025-05-04
  • (评论) 2024-08-09
  • (评论) 2024-06-13

  • 原文

    View a PDF of the paper titled Type-Constrained Code Generation with Language Models, by Niels M\"undler and Jingxuan He and Hao Wang and Koushik Sen and Dawn Song and Martin Vechev

    View PDF
    Abstract: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.
    From: Niels Mündler [view email]
    [v1] Sat, 12 Apr 2025 15:03:00 UTC (2,798 KB)
    [v2] Thu, 8 May 2025 09:33:40 UTC (2,667 KB)
    联系我们 contact @ memedata.com