CodeMirage: Hallucinations in Code Generated by Large Language Models

Vibhor Agarwal, Yulong Pei, Salwa Alamir, Xiaomo LiuarXiv 2024 · DOI

Abstract

While Large Language Models (LLMs) are increasingly used for "no-code" automation, they frequently produce "code hallucinations"—snippets that look correct but contain logical, structural, or security flaws. This paper introduces CodeMirage, the first comprehensive benchmark and taxonomy for code hallucinations, revealing that even state-of-the-art models like GPT-4 struggle to reliably detect these subtle errors.

The Problem: Beyond Textual Hallucinations

In natural language, a hallucination is text that is fluent but factually incorrect. In the world of software engineering, the stakes are higher: a "hallucinated" code snippet might pass a visual inspection but fail on an edge case, leak memory, or open a security backdoor.

The authors identify a significant gap in current research: while text hallucinations are well-documented, there has been no formal framework for defining, categorizing, or benchmarking hallucinations specifically in code. This makes it difficult for developers to trust LLM-generated code in production environments without exhaustive manual review.

Methodology

The researchers approached the problem in three phases:

  1. Taxonomy Development: They defined five distinct categories of code hallucinations: dead/unreachable code, syntactic incorrectness, logical errors, robustness issues, and security vulnerabilities.
  2. Dataset Generation: Using GPT-3.5, they intentionally generated 1,137 hallucinated Python snippets based on problems from the well-known HumanEval and MBPP datasets. They used "type-specific" prompts to force the model to create specific kinds of errors.
  3. Detection Experiments: They tested how well various models could act as a "code judge," comparing one-shot prompting of LLMs (GPT-4, GPT-3.5, and CodeLLaMA-7B) against a fine-tuned baseline using CodeBERT.
  4. Structural Analysis: They used McCabe’s cyclomatic complexity to measure the logical "density" of the code, comparing correct snippets against hallucinated ones.

The CodeMirage Dataset

The paper introduces CodeMirage, a new benchmark dataset containing 1,137 hallucinated Python snippets. The dataset was validated by five human experts, achieving a Cohen’s kappa score of 0.76, indicating strong agreement on the error types.

Distribution of hallucination types in the CodeMirage dataset.

Key Insights: The Complexity Signal

Interestingly, hallucinated code—particularly those with "dead code"—tends to have higher cyclomatic complexity than correct code. This suggests that LLMs often "over-engineer" their mistakes, adding unnecessary logical paths when they lose track of the solution.

Conversely, code with "robustness issues" (like missing exception handling) often has lower complexity relative to other hallucination types. These are "hallucinations of omission" where the model fails to account for the messy reality of file systems or network states. The authors emphasize that these snippets are dangerous because they are "plausible"; they follow Python syntax and look like something a human might write.

Detection Results

Even for GPT-4, detecting these errors is a challenging task. The macro-F1 scores remain relatively low across the board, suggesting that simple prompting isn't enough to ensure code safety.

Performance comparison of LLMs and fine-tuned CodeBERT in detecting code hallucinations.
  • GPT-4 vs. The Field: GPT-4 was the top performer among LLMs for detection. On the HumanEval subset, it achieved a macro-F1 score of 0.5512, outperforming the fine-tuned CodeBERT baseline (0.4897).
  • CodeBERT's Edge: On the larger MBPP dataset, the fine-tuned CodeBERT model performed best (F1 of 0.6344), suggesting that specialized, smaller models still have a role to play in code verification.
  • Open Source Struggles: Smaller open-source models like CodeLLaMA-7B struggled significantly in the one-shot detection task, yielding very low F1 scores (around 0.04 on HumanEval), indicating they lack the reasoning depth required to spot subtle logical flaws without extensive fine-tuning.

Limitations and Future Work

The authors acknowledge that the current study is limited to Python and hallucinations generated by GPT-3.5. Future work should expand to languages like C++, Java, or Go. The next logical step is mitigation—developing techniques like Retrieval-Augmented Generation (RAG) or iterative self-correction to prevent these hallucinations. Additionally, the authors suggest integrating software engineering tools (like compilers and AST parsers) into the LLM pipeline to provide "ground truth" feedback during code generation.

Summary updated

BibTeX
@misc{agarwal2024codemirage,
  author = {Vibhor Agarwal and Yulong Pei and Salwa Alamir and Xiaomo Liu},
  title = {{CodeMirage: Hallucinations in Code Generated by Large Language Models}},
  year = {2024},
  eprint = {2408.08333},
  archivePrefix = {arXiv},
  url = {https://arxiv.org/abs/2408.08333},
}
Figure