揭示大模型代码生成幻觉现象与成因,提出有效缓解方法
LLM Hallucinations in Practical Code Generation: Phenomena, Mechanism, and Mitigation
- 构建代码生成幻觉分类体系,分析六款主流模型表现
- 发现幻觉在复杂上下文场景中更易出现,影响代码正确性
- 提出基于RAG的缓解方案,在所有模型上均有效
代码生成旨在从需求描述自动生成代码,显著提升开发效率。近年来基于大语言模型(LLMs)的方法展现出良好效果,彻底革新了代码生成任务。尽管性能优异,大模型在生成代码时常产生幻觉,尤其在需要处理实际开发中复杂上下文依赖的场景下更为明显。以往研究主要聚焦于独立函数生成中的幻觉问题,本研究开展实证分析,深入探讨在更贴近实际、更复杂的仓库级代码生成场景中,大模型幻觉的现象、机制与缓解策略。首先,我们人工审查六款主流大模型的生成结果,建立代码生成幻觉的分类体系;其次,系统分析幻觉现象及其在不同模型间的分布特征;进一步探究幻觉成因,识别出四个潜在影响因素;最后,提出一种基于RAG的缓解方法,在所有被研究的大模型中均表现出一致有效性。复现资源已公开于https://github.com/DeepSoftwareAnalytics/LLMCodingHallucination。
原文摘要 · Abstract (English)
Code generation aims to automatically generate code from input requirements, significantly enhancing development efficiency. Recent large language models (LLMs) based approaches have shown promising results and revolutionized code generation task. Despite the promising performance, LLMs often generate contents with hallucinations, especially for the code generation scenario requiring the handling of complex contextual dependencies in practical development process. Although previous study has analyzed hallucinations in LLM-powered code generation, the study is limited to standalone function generation. In this paper, we conduct an empirical study to study the phenomena, mechanism, and mitigation of LLM hallucinations within more practical and complex development contexts in repository-level generation scenario. First, we manually examine the code generation results from six mainstream LLMs to establish a hallucination taxonomy of LLM-generated code. Next, we elaborate on the phenomenon of hallucinations, analyze their distribution across different models. We then analyze causes of hallucinations and identify four potential factors contributing to hallucinations. Finally, we propose an RAG-based mitigation method, which demonstrates consistent effectiveness in all studied LLMs. The replication package including code, data, and experimental results is available at https://github.com/DeepSoftwareAnalytics/LLMCodingHallucination
Thank you to arXiv for use of its open access interoperability. PaperDance 不是 arXiv 官方产品;中文卡片由大模型生成,请以原文为准。