Coding assistants · Research feature

LLM Code Generation Often Overconfident About Incorrect Programs

The findings are limited to 7–8B parameter models, single-generation synthesis, and Python-based benchmarks, with no evaluation of larger models, repository-scale workflows, or other programming languages.

Adapted from research by Ravishka Rathnasuriya, Wei Yang.

arXiv preprint revision · 2026-10-08 · Attribution & reuse
In this article
Editorial illustration of developer workstation.

Editor’s introduction

The study examines overconfidence in four open-source code models, measuring whether model-derived uncertainty correlates with execution correctness across three Python benchmarks. Instruction tuning increases confidence on failing generations without consistently improving the ability to distinguish correct from incorrect code. Common mitigation strategies enhance specific aspects of reliability but fail to reliably reduce overconfident failures. The research suggests that hidden model representations may contain correctness signals not reflected in confidence outputs. The findings are limited to 7–8B parameter models, single-generation synthesis, and Python-based benchmarks, with no evaluation of larger models, repository-scale workflows, or other programming languages.

Introduction

Large language models (LLMs) have become increasingly effective at code generation, synthesizing implementations from natural-language specifications, programming tasks, and partial code contexts. They are now integrated into software development workflows to assist with implementation, debugging, testing, and repair. However, generated code is not self-validating. A program may be syntactically valid, idiomatic, and plausible while still violating the intended specification, especially on edge cases revealed only through execution. Thus, a central reliability challenge for LLM-based software engineering is not only whether a model can generate code, but whether a system can determine when generated code should be trusted.

Existing validation approaches primarily rely on execution-based evaluation or program analysis. These techniques are essential, but they do not fully solve the deployment-time reliability problem. Execution requires tests, input generators, or behavioral oracles, which may be incomplete, expensive, or unavailable for each generated candidate. Program analysis can identify specific defect classes, but it is often conservative, property-specific, and does not generally estimate whether an arbitrary generated program satisfies its specification. Moreover, both execution and analysis are typically applied after generation. This limits their ability to provide lightweight, model-intrinsic reliability signals during interactive code generation.

A natural alternative is an uncertainty-aware code-generation system. In an ideal setting, the system would know whether a generated program generalizes to unseen tests or real user inputs. Such a generalizability oracle is unavailable in practice, because functional correctness can only be established through validation against a specification, tests, or downstream behavior. Therefore practical systems must rely on proxies. The broader machine-learning literature operationalizes this proxy through uncertainty metrics derived from predictive distributions, confidence scores, entropy, margins, calibration methods, and related quantities. Such metrics have been extensively studied in classification tasks and more recently in natural language generation (NLG), where they are used as proxies for output correctness, factuality, or risk. These estimates also support selective abstention, where high-risk outputs are withheld or routed to additional validation.

However, uncertainty is less directly related to correctness in code generation than in classification or open-ended NLG. In classification, uncertainty is defined over the label distribution, and evaluation is performed on the predicted label. In open-ended NLG, uncertainty is commonly estimated over the generated response and evaluated against response-level properties such as correctness or factuality. In code generation, model probabilities are assigned during token generation, whereas correctness is determined by the execution behavior of the completed program. Therefore, a generated program can have high token likelihood and still fail to satisfy its specification. Thus, token- and sequence-level uncertainty are only proxies for execution correctness.

Using token- and sequence-level uncertainty as proxies for execution correctness creates a dilemma of overconfidence in code generation. A generated program may receive high model confidence and still fail execution-based evaluation. This mismatch is consistent with how code LLMs are trained and evaluated. First, autoregressive training optimizes next-token prediction rather than whether model confidence reflects execution correctness. Second, standard code-generation evaluation measures generation success rather than the reliability of model confidence. Pass@1 and pass@k measure whether generated programs pass the evaluation tests, whereas binary grading gives no credit to abstention. Therefore, such evaluation does not assess whether failing generations receive lower confidence than passing ones. Testing and program analysis provide evidence more directly tied to execution correctness, but they require external validation and may be costly or incomplete. Therefore, model-derived uncertainty remains attractive as an early reliability signal, despite the possibility of overconfident failures.

Reliability of Standard Uncertainty Signals for Failure Detection

We evaluate each score using AUC, with fail as the positive class, and orient the scores so that larger values indicate greater estimated failure risk. An AUC of 0.5 corresponds to random ranking. We focus on HumanEval+ and MBPP+ because both passing and failing generations are sufficiently represented across the studied models. We exclude BigCodeBench because its substantially lower pass rates leave few passing generations for several models, making pass-fail discrimination estimates less stable. Full metric definitions and implementation details are available on the project website.

Prefill uncertainty shows the same limitation. The highest AUC is 0.70 for CodeLlama on HumanEval+, whereas most model–benchmark settings fall between 0.52 and 0.62. Several scores are close to random ranking, particularly on MBPP+, and no prefill metric is consistently strongest across models.

Implication. The results do not support a model- and task-independent mapping from standard uncertainty scores to code correctness. Furthermore, an uncertainty signal that is useful in one setting cannot be assumed to provide the same failure evidence in another.

Uncertainty-Based Selective Generation

Therefore, selective generation trades coverage for accuracy. If uncertainty reflects functional correctness, removing uncertain generations should increase the accuracy of the accepted subset relative to the model’s original accuracy. If high-certainty failures remain, reducing coverage may provide little improvement or even reduce accuracy.

BigCodeBench shows that this behavior does not persist across benchmarks. DeepSeekCoder and OpenCoder achieve modest accuracy improvements after uncertainty-based filtering. In contrast, the 10% most certain generations from CodeLlama and QwenCoder contain no passing solutions under either confidence or entropy where their original accuracies are 6.5% and 8.2%, respectively. For CodeLlama, no generation in the top 25% by confidence passes either. In these cases, uncertainty-based filtering reduces accuracy rather than improving it.

The comparison further separates uncertainty-ranking quality from generation accuracy. OpenCoder has the highest original accuracy on MBPP+ but receives little accuracy improvement from selective generation. Conversely, models with lower original accuracy can obtain substantially more accurate retained subsets.

Finding. Overconfident failures can occupy the high-certainty region of the uncertainty ranking. As a result, decreasing coverage does not consistently improve execution accuracy and can reduce it when uncertainty is misaligned with functional correctness. This misalignment is model- and benchmark-dependent and does not follow the model’s original generation accuracy.

Implications of Overconfidence Characterization

Our characterization separates three properties of reliability-aware code generation: functional accuracy, uncertainty-based correctness discrimination, and its stability after post-training. Pass/fail evaluation measures only the first and the latter two determine whether model uncertainty remains informative for reliability decisions.

Reliability evaluation should measure correctness discrimination separately from task accuracy. A model can achieve higher Pass@1 without becoming better at identifying which of its generations are correct. Therefore, evaluation should report whether uncertainty separates passing from failing programs in addition to reporting functional accuracy. Coverage-accuracy analysis provides a corresponding view by showing whether uncertainty ranking yields more accurate accepted subsets.

Post-training objectives for correctness do not necessarily improve self-assessment. Our base-instruction comparison shows that model certainty and correctness discrimination can change independently after instruction tuning. Therefore, improving generation quality does not impose a corresponding constraint on confidence assigned to remaining failures. Reliability oriented post-training should treat generation correctness and uncertainty-based self-assessment as separate optimization targets.

Uncertainty behavior should be re-evaluated after model updates. Post-training can alter both the magnitude and the ordering of uncertainty scores. An uncertainty-based selection mechanism validated for one model version may no longer exhibit the same correctness discrimination after the model is updated. Model evolution should include regression evaluation of both functional accuracy and uncertainty-correctness alignment.

Calibration Improves Probability Alignment but Provides Limited Predictive Skill

Evaluation Setup. We examine to what extent post-hoc calibration mitigates overconfidence by mapping uncertainty scores to estimated probabilities of execution correctness. For confidence, we use average token confidence and bottom-10% token confidence. For entropy, we use average token entropy and top-10% token entropy. We calibrate each score using Platt scaling (PS) which fits a logistic mapping from each original uncertainty score to an estimated probability of correctness and isotonic regression which fits a monotonic non-parametric mapping from uncertainty scores to empirical correctness.

On BigCodeBench, calibration produces large reductions in BS while BSS remains near zero across models. For CodeLlama, PS reduces the BS of average token confidence from 0.856 to 0.061, but the corresponding BSS is approximately 0.001. Therefore, the calibrated BS is nearly equivalent to the error of the base-rate predictor. The remaining models exhibit the same pattern, with calibrated BSS values generally close to zero and the largest values reaching only about 0.01–0.02.

The BS and BSS results show that calibration primarily corrects the scale of the uncertainty scores rather than providing substantial predictive information about individual generations. This interpretation is consistent with our selective-accuracy analysis, where passing and failing generations remain overlapping in the uncertainty space. Post-hoc calibration can remap these scores to better-aligned probabilities, but it cannot remove the underlying overlap between correct and incorrect generations.

Finding. Post-hoc calibration corrects the magnitude of overconfidence but does not resolve overconfident failures. Although calibration substantially improves probability alignment, the calibrated scores provide little skill beyond the benchmark pass rate and remain unable to reliably distinguish passing from failing generations.

Discussion

This direction requires execution-grounded training data. Each training example should connect a task and generated candidate to an execution outcome, so that high-confidence failures can be identified explicitly. Matched passing and failing candidates for the same task are particularly useful because they control for differences in task difficulty. Such data can support objectives that penalize confident failures and reward appropriate deferral. Our latent-space analysis provides an additional opportunity where passing and failing generations exhibit different internal representations even when output confidence overlaps, suggesting that these internal signals may support learned failure prediction rather than relying only on token probabilities.

At inference time, the system should determine what additional evidence is needed before accepting generated code. We distinguish three such cases. First, when the task specification is incomplete or ambiguous, the system should seek clarification from the developer. Second, when correctness depends on missing external information, the system should retrieve or verify that information. Third, when the risk lies in the generated implementation, the system should obtain program-level evidence through testing, analysis, or an independent evaluator. Repeated generation can support this process, but our results show that sampling alone does not resolve candidate selection and eventually reaches persistent failures. Therefore, an inference-time controller should choose among clarification, validation, regeneration, and deferral according to the expected reliability improvement and its cost.

A reliability benchmark should evaluate an end-to-end policy that can accept generated code, obtain additional validation, retry generation, or defer. The evaluation should vary the cost of accepting incorrect code and the available validation budget. The central outcome is whether the system reduces false acceptance without relying on indiscriminate deferral or unlimited validation. Such evaluation would measure whether a code-generation system uses reliability evidence appropriately under deployment constraints, rather than only whether it produces a calibrated score.

These three directions target different causes of overconfident failure. Training determines whether the model identifies likely failures, inference-time control determines how the system responds to uncertain evidence, and evaluation determines whether those responses reduce false acceptance. Ultimately, an intervention addresses overconfidence only to the extent that it reduces failing programs that remain eligible for acceptance, without relying on indiscriminate deferral or unbounded validation.

Threats to Validity

This section discusses potential threats to validity in our study, organized into four standard categories: internal, external, construct, and conclusion validity. These categories address risks pertaining to our experimental design and methodology, as well as the generalizability of our findings.

Internal validity. Our results depend on the correct implementation of uncertainty metrics, calibration methods, sampling procedures, and execution-based evaluation. We mitigate this threat by following standard definitions from prior work, reusing established implementations when available, and applying the same evaluation pipeline across models and benchmarks. For stochastic procedures, such as sampling-based uncertainty and repeated generation, we use fixed decoding settings within each experiment and compare trends across multiple models. Nevertheless, implementation details such as token filtering, sequence truncation, and score orientation may affect individual metric values.

External validity. We evaluate four open-source code LLMs on HumanEval+, MBPP+, and BigCodeBench analyses. These benchmarks provide executable correctness labels and allow controlled comparison of uncertainty signals, but they do not cover all software-engineering settings. Our findings may not fully generalize to larger proprietary models, project-level development tasks, other programming languages, or agentic workflows with tool use and iterative repair. Metrics requiring token probabilities or hidden states also assume white-box model access, which may not be available for API-only models. Extending this analysis to closed models and repository-scale tasks remains future work.

Construct validity. We operationalize correctness using benchmark test suites. Although HumanEval+ and MBPP+ strengthen the original tests, execution outcomes may still miss untested behaviors. Thus, our labels approximate functional correctness rather than prove semantic equivalence. We also treat token confidence, entropy, calibration scores, sampling behavior, abstention, and latent effective rank as proxies for reliability-related evidence. These constructs do not directly measure program correctness; they measure whether model-derived signals align with execution outcomes. This distinction is central to our study, but it limits claims about absolute correctness.

Conclusion validity. Our conclusions are based on trends observed across multiple models, benchmarks, uncertainty families, and mitigation strategies. The main findings do not depend on a single metric: weak failure detection, high-confidence failures, limited local-token separation, bounded sampling gains, and unreliable prompt-level abstention appear across settings. However, exact effect sizes may vary with decoding parameters, calibration splits, thresholds, and benchmark composition. We therefore avoid claiming that uncertainty is useless. Our conclusion is more specific: the evaluated model-derived signals are insufficient as standalone reliability mechanisms for deciding that generated code is likely to pass execution-based validation.

Uncertainty estimation in ML and NLG. Uncertainty estimation has been widely studied in classification, using confidence scores, entropy, Bayesian approximations, ensembles, and calibration methods to identify unreliable predictions. Recent work extends these ideas to natural-language generation through token uncertainty, sequence likelihood, sample diversity, semantic uncertainty, and judge-based estimates. Code generation differs because correctness is determined by executable program behavior rather than textual plausibility or subjective quality. Our work studies whether these uncertainty signals remain useful under execution-based correctness.

Uncertainty and calibration for code models. Prior work has studied uncertainty, calibration, and reliability signals for code models. These studies show that code models can be miscalibrated and that post-hoc methods can improve confidence alignment. Our focus is different: we study whether model-derived uncertainty can support reliability decisions for generated code, such as identifying likely failures, abstaining, or deciding when additional validation is needed. This setting is distinct from uncertainty in non-generative SE tasks such as defect prediction or vulnerability detection, where predictions are labels over existing artifacts rather than generated programs whose correctness is observed only after execution.

Code-generation evaluation and mitigation. Code-generation research commonly evaluates models with pass@1, pass@k, execution feedback, repair, and prompting strategies. These methods measure or improve the ability to produce correct code, but they do not fully address whether a model can recognize when its own output is likely to fail. Sampling can increase the chance that a correct candidate exists, but does not identify which candidate should be trusted. Prompt-level abstention can expose a deferral option, but does not guarantee safe generate-or-defer behavior. We evaluate these techniques as responses to overconfident failure rather than as general performance-improvement methods.

Summary. Our work provides a rigorous characterization of the dilemma of overconfidence in code LLMs: model-derived uncertainty is available during generation, but it does not reliably identify generated programs that fail execution-based evaluation. The results position overconfident failure as a deployment-facing SE reliability problem and motivate future mechanisms that connect model self-assessment to execution-grounded correctness.