On the Robustness of LLMs' Internal Representation of Code Correctness
This study systematically analyzes the robustness of internal code correctness signals in LLMs, comparing extraction methods and data variations, with accuracy ranging 41-63%.
Key Findings
Methodology
Using linear probing, the study contrasts hidden states of correct and incorrect programs to construct a correctness direction. Variations include extraction location, prompt framing, and model type. Experiments on four instruction-tuned models (Mistral-7B-Instruct, Qwen-2.5-Coder, OpenCoder-8B, CodeLlama-7B) and two benchmarks (HumanEval, BigCodeBench) in in- and out-of-distribution settings. Control mutants and behavior-preserving refactors evaluate data impact.
Key Results
- Different configurations lead to significant performance variation; no single best setup. Mean-difference method shows better generalization. Extraction position and framing greatly influence results, with models performing worse out-of-distribution. Data augmentation via mutants/refactors does not significantly improve signals, indicating data limitations. Max accuracy reaches 63%, but overall signals remain unstable.
- Model internal representations exhibit limited robustness across configurations and datasets. Performance drops notably in out-of-distribution scenarios, highlighting generalization challenges. The findings suggest the need for more stable extraction strategies and richer data for improved internal signals.
Significance
This research highlights the potential and limitations of internal signals for code correctness assessment, offering insights into model interpretability and guiding future robustness improvements. It impacts automated code review, program verification, and model explainability, fostering advances in AI-driven software engineering.
Technical Contribution
The paper systematically compares PCA and mean-difference methods across models and datasets, introduces control mutants and refactors to assess data impact, and provides a comprehensive experimental pipeline. It emphasizes multi-configuration analysis, deepening understanding of internal representations and their stability, and offers a foundation for future robustness enhancements.
Novelty
First comprehensive comparison of multiple extraction methods (PCA vs. mean-diff) across diverse models and datasets. Introduces controlled mutation and refactor techniques to evaluate data effects on signals. Establishes a multi-configuration framework for analyzing internal representation robustness, advancing interpretability research.
Limitations
- Despite extensive analysis, the maximum accuracy remains around 63%, indicating limited reliability of internal signals for correctness. Configuration sensitivity and data limitations hinder generalization, especially out-of-distribution. The current methods do not fully address the instability of internal representations, necessitating further research into more robust extraction techniques and richer training data.
Future Work
Future directions include integrating multi-modal signals, developing adaptive extraction methods, and scaling to larger models and languages. Exploring multi-task learning and interpretability techniques could enhance internal signal stability. Broader evaluation across diverse tasks and datasets will be essential to validate and improve robustness, ultimately enabling more reliable AI-based code verification tools.
AI Executive Summary
As large language models (LLMs) increasingly generate code, assessing the correctness of their outputs becomes vital. Traditional metrics like confidence scores and test execution are limited by calibration issues and computational costs. Recent research explores internal representations—hidden states—as an alternative. This study systematically examines how different extraction configurations—such as position, prompt framing, and construction method—affect the robustness of code correctness signals across four instruction-tuned models and two benchmarks.
The core approach involves contrasting hidden states of correct and incorrect programs to derive a correctness direction via linear probing. Variations in extraction location (last token vs. response average), prompt framing (neutral, concept, function), and construction method (PCA vs. mean-difference) were tested. Results show no single configuration dominates; performance varies significantly with setup, and out-of-distribution scenarios are particularly challenging. The highest accuracy achieved was 63%, indicating limited stability.
Further, introducing controlled mutants and behavior-preserving refactors revealed that data variation has minimal impact on improving signal quality. These findings underscore the complexity of internal representations and their sensitivity to configuration and data. The research emphasizes the need for more robust extraction strategies and richer datasets to enhance model interpretability and reliability.
Overall, this work advances understanding of internal signals in LLMs, providing a foundation for future efforts to develop more stable, generalizable internal correctness indicators. Such progress is crucial for deploying AI in safety-critical software development, automated verification, and beyond, ultimately fostering more trustworthy AI systems.
Deep Analysis
Background
The evolution of transformer-based LLMs like GPT, BERT, and subsequent instruction-tuned models such as Codex, CodeLlama, and Qwen has significantly advanced automatic code generation. These models excel at completing code snippets, generating functions, and even entire modules, transforming software development workflows. However, their outputs often lack reliable correctness signals, as traditional metrics like confidence scores and test executions are either poorly calibrated or computationally expensive. Recent studies, including Ribeiro et al. (2022), demonstrated that internal hidden states encode high-level semantic properties, including truthfulness and code correctness. These insights suggest that internal representations could serve as proxies for correctness assessment, offering a faster, test-free evaluation method. Nonetheless, the robustness and generalizability of such internal signals remain underexplored, especially across different models, datasets, and configurations.
Core Problem
Despite promising initial results, the internal correctness signals extracted via linear probing are sensitive to multiple factors—extraction location, prompt framing, and construction method—leading to inconsistent performance across models and datasets. The signals tend to degrade in out-of-distribution scenarios, limiting practical deployment. Furthermore, the data used to build these signals, often generated from model failures or canonical solutions, may not fully capture the complexity of real-world errors. This variability hampers the development of reliable, model-agnostic internal correctness indicators, constraining their utility in automated verification, debugging, and safety-critical applications.
Innovation
This paper introduces a comprehensive, systematic framework for analyzing how different configurations—construction methods (PCA vs. mean-difference), prompt framings (neutral, concept, function), and extraction locations (last token vs. response average)—affect the robustness of internal correctness signals. It innovates by integrating controlled mutation and refactoring techniques to generate diverse, behavior-preserving error samples, enabling rigorous testing of data impact. The study evaluates four instruction-tuned models across multiple datasets, providing a detailed variance analysis and revealing configuration sensitivities. This multi-faceted approach advances understanding of internal representation stability and guides the design of more robust extraction strategies.
Methodology
- �� Use linear probing to contrast hidden states of correct and incorrect programs, constructing correctness directions. • Vary extraction location (last token vs. response average) and prompt framing (neutral, concept, function). • Implement PCA and mean-difference methods for direction construction, comparing their performance. • Generate controlled error pairs via mutation operators (arithmetic, variable, control flow) and validate with test suites. • Apply behavior-preserving refactors to produce confounded variants, testing data impact. • Conduct experiments on four models (Mistral, Qwen, OpenCoder, CodeLlama) and two benchmarks (HumanEval, BigCodeBench), using cross-validation to select optimal layers and configurations. • Measure performance via pairwise and selection accuracy, analyzing variance contributions.
Experiments
- �� Datasets include HumanEval and BigCodeBench, covering diverse programming tasks and external library calls. • Use 10-fold cross-validation, ensuring robustness. • Compare configurations across extraction methods, prompt framings, and locations. • Generate error pairs through 20 mutation operators, validate failures with test suites, and create confounded variants via refactoring. • Evaluate performance metrics—pairwise accuracy and selection accuracy—across models and datasets, analyzing configuration effects and robustness. • Conduct ablation studies to assess the impact of data augmentation and configuration choices.
Results
- �� No single configuration consistently outperforms others; performance varies with setup. • Mean-difference construction exhibits better generalization across models and datasets. • Extraction location and prompt framing significantly influence accuracy, with models performing worse out-of-distribution. • Data augmentation via mutants and refactors does not substantially improve signals, indicating data limitations. • The highest observed accuracy is 63%, highlighting the challenge of stable internal correctness signals. These results suggest that internal representations are sensitive and require more robust extraction strategies for practical use.
Applications
- �� Automated code review: internal signals can supplement traditional testing for quick error detection. • Candidate ranking: internal correctness scores can prioritize promising solutions. • Rapid verification: test-free assessment accelerates development cycles. • Educational tools: internal signals help visualize correctness reasoning, aiding learning and debugging.
Limitations & Outlook
- �� Current signals are insufficiently accurate for critical applications, with maximum around 63%. • Configuration sensitivity and dataset limitations hinder robustness, especially out-of-distribution. • Data augmentation strategies showed limited improvements, indicating the need for richer, more diverse data. • Model internal representations remain fragile, necessitating further research into more stable extraction methods and larger, more varied training datasets. Future work should explore multi-modal signals, adaptive extraction techniques, and larger-scale models to address these challenges.
Plain Language Accessible to non-experts
想象你在一个工厂里,工人们每天都在生产各种商品。工厂的管理者想知道哪些工人做得好,哪些出了差错。于是,他们偷偷观察工人的动作、表情,试图找到一些隐藏的线索。通过分析这些线索,管理者可以判断工人是否在按标准操作。这个过程就像模型内部的隐藏状态,里面藏着很多信息。研究人员用特殊的方法,把这些隐藏的线索提取出来,试图判断代码是否正确。不同的提取方法和观察位置会影响判断的准确性。就像管理者用不同的观察角度,判断工人是否出错一样。这个研究告诉我们,要让工厂(模型)更聪明,不能只看表面,还要深入内部观察,找到真正的“秘密”。
ELI14 Explained like you're 14
想象你在学校里,有个老师想知道你的作业是不是做对了,但老师不能每次都检查答案。于是,他偷偷观察你写作业时的动作和表情,试图判断你是否写错了。这个方法很聪明,但也有难点:不同的观察角度和方法会影响判断的准确性。有时候,老师观察到的细节(比如写字的速度或用的笔)可能和作业是否正确没有关系。研究人员用类似的方法,从模型内部的“隐藏状态”中提取线索,试图判断代码是否正确。他们发现,不同的提取方法和观察位置会影响判断的效果。有时候,即使用最好的方法,也只能正确判断一部分代码。这提醒我们,要让模型更聪明,不仅要看表面,还要深入内部,找到真正的“秘密”。
Abstract
Code generated by modern language models often reads naturally. Yet, it also often fails to implement what was asked. This should be no surprise, as research shows the models' own confidence signals are poorly calibrated with actual correctness. A promising way to assess correctness looks inside the model: by contrasting the hidden states of correct and incorrect programs, recent work captured an internal signal of code correctness that is able to judge candidate solutions better than the model's token-level or stated confidence, with no test execution. However, this signal was captured under one particular way, leaving open an important question: whether it reflects a robust property of the model or an artifact of that choice. We study this question systematically, varying how the signal is extracted from the model internals. Besides this, we also ask if the signal's quality is limited by the data used to extract it, by constructing program pairs that differ only in the fault that makes them incorrect. Our results show that no single configuration is best, and that isolating the fault does not help.