Many code-generation systems now work in a loop. The model writes a program, a compiler or test suite reports what failed, and the model revises. Loops like this raise success rates a great deal, but they have no principled way to decide when to quit. Sometimes success comes on the next round. Sometimes the model is thrashing, cycling through broken variants and paying compiler and decoding time for nothing. We propose a stopping rule for these loops. It reads the model's own token-level uncertainty on each revision, meaning how spread out its next-token probabilities are, and it comes with a statistical guarantee: across tasks, it rarely stops a loop that would have gone on to succeed. The signal is essentially free because it comes from logits the model already computes. The guarantee comes from calibrating the stopping threshold on held-out tasks, so the user chooses the acceptable rate of lost successes in advance.
The key design choice is the question we ask entropy to answer. Earlier attempts used uncertainty to decide whether the current draft is wrong and should be regenerated, and that failed badly. We use it only to predict whether more rounds are likely to help, while the verifier stays in the loop and judges correctness. In short, the compiler says whether the program works, and the model's uncertainty over its recent revisions says whether it is still making progress or going in circles.
Core Claim
In a verifier-driven refinement loop, the trajectory of token entropy and varentropy across successive revisions carries information about future success that the verifier's own feedback does not. Varentropy is the variance of per-token surprisal, and it signals competition between a few alternatives rather than diffuse confusion. Combining the two sources and calibrating with conformal risk control should cut the expected number of refinement rounds, and the wall-clock time, well below the best fixed round budget, while holding the fraction of lost eventual successes below a chosen level $\alpha$.
Where This Sits
The motivating evidence comes from two places. VERINA benchmarks Lean 4 code, specification, and proof generation. Its authors found that allowing up to 64 compiler-feedback rounds lifted proof success from 4.9% pass@1 (OpenAI o3) to about 20%, but inference cost grew steeply and models often thrashed. So the long tail is valuable yet expensive, and a stopping rule has something real to save. RepoCoder, which iterates between retrieval and generation for repository-level completion, and Extrapolative Controlled Sequence Generation via Iterative Refinement both name the lack of stopping criteria as an open problem.
The work that constrains our design most is When Uncertainty Isn't Enough. It tested mean token entropy, verbalized confidence, P(True), entropy ensembles, and semantic entropy probes as triggers for regenerating code without running tests. Pass@1 dropped in 5 of 6 configurations, by nearly 10 points for Llama-3.2-3B on HumanEval, because noisy uncertainty caused correct programs to be overwritten. The same study reports that execution-based correction lifted DeepSeek-Coder-1.3B on HumanEval from 0.61 to 0.87, and it suggests that uncertainty might instead serve as a gate for deciding when to pay for verification. We take that suggestion in a specific direction. Uncertainty never overrides the verifier in our method; it only decides whether to buy another verified round. A wrong decision therefore costs a missed success, which is exactly the quantity we control, and it can never corrupt a passing program.
The statistical machinery comes from Statistical Early Stopping for Reasoning Models. That work stops long reasoning traces on ill-posed questions by modeling verbalized doubt keywords as a point process, and it uses a maxwise conformal rule that bounds premature stops below $\alpha$. The authors report saving 38–70% of reasoning tokens. We differ in three ways. Our signal is logit entropy, not surface keywords, which addresses the "silent failure" blind spot that paper admits. Our unit is a verified refinement round, not a 250-token bin inside a single trace. And our target is future verifier success, not whether a question is ill-posed. The same paper also finds that length is a red herring, since fixed length thresholds do not transfer across domains. That finding motivates our cross-benchmark transfer test.
The entropy features themselves come from LogitScope, which computes entropy, varentropy, and skewness of the next-token distribution from logits alone. Useful Confidence Measures: Beyond the Max Score supports using the full distribution rather than the top probability. It shows entropy cutting adaptive calibration error from 10.71 to 2.70 on WILDS Amazon under shift.
Two other methods use entropy inside generation but answer different questions. Latent Phase-Shift Rollback combines hidden-state direction changes with high entropy to trigger one-token rollbacks during math reasoning. TSPD with Confidence Extrapolation trains an LSTM controller that uses per-token entropy trajectories to freeze converged tokens in diffusion language models. Both act within a single generation. Neither decides when a multi-round, externally verified loop should end, and neither offers a guarantee on lost successes.
Research Program
Logging refinement runs. We first build a corpus of logged refinement trajectories. For each task we run the loop to a generous budget $B$: 64 rounds on VERINA via sunblaze-ucb/verina, and 10 rounds on HumanEval, BigCodeBench, and LiveCodeBench, run through an execution harness such as amazon-science/mxeval where applicable. Every round records the verifier outcome, and the logits come for free. Because every trajectory runs to $B$, we know the first successful round $T^*_i$ for every task, so any stopping rule can be scored offline without rerunning the model.
Features. At round $r$, the features come from two sources. The model-side features are the mean and upper quantiles of per-token entropy and varentropy over the revised program. We also compute these over the diff span only, meaning the tokens that changed since round $r-1$, and track the change in each across rounds. The verifier-side features are the number of tests passed, whether the error message repeated, and the edit distance between successive revisions.
Stopping score. A small hazard model, logistic regression or gradient-boosted trees, estimates the probability $s_r$ that success will occur in some later round given everything seen so far. The loop stops when $s_r$ falls below a threshold $\lambda$.
Calibration. Let $\tau_\lambda(i)$ be the stopping round for task $i$ under threshold $\lambda$. The risk we control is the missed-success rate:
$$R(\lambda) = \Pr\big[\tau_\lambda(i) < T^*_i \le B\big],$$
which is the probability of quitting a task that would have succeeded within the budget. $R(\lambda)$ can only grow as $\lambda$ grows, because a higher threshold stops loops earlier. On $n$ held-out calibration tasks with empirical risk $\hat R(\lambda)$, we therefore select
$$\hat\lambda = \max\{\lambda : (n\hat R(\lambda)+1)/(n+1) \le \alpha\},$$
the standard split-conformal correction. This bounds expected missed-success risk at $\alpha$ when calibration and test tasks are exchangeable. We borrow the maxwise variant of Statistical Early Stopping to handle monitoring at every round.
Analysis. The analytic question is what the entropy trajectory encodes. Our hypothesis is that thrashing shows up as revisions that stay low-entropy while still failing: the model confidently repeats the same mistake. Productive search should instead show high varentropy concentrated in the edited span, reflecting a live choice among a few alternatives. We will test this hypothesis directly, not assume it.
Baselines
The naive reference point is running every loop to the full budget $B$. It gives the maximum achievable success and the maximum cost, and every other method is scored by how much of that cost it saves and how much of that success it keeps. For VERINA the relevant ceiling reported in the file is roughly 20% proof success after 64 rounds (VERINA). We found no reported result on Lacuna for any adaptive stopping rule on VERINA or on execution-feedback HumanEval loops, so all stopping comparisons are new measurements on shared logs.
The first strong competitor is the best fixed round budget $K$. We choose $K$ on the same calibration split as the smallest budget whose missed-success rate is at most $\alpha$. This baseline is simple and hard to beat on a single benchmark. Beating it means lower mean rounds, lower wall-clock time, or both, at the same realized missed-success rate, measured on the same test tasks.
The second is a verifier-only no-progress heuristic that stops after $m$ consecutive rounds with an unchanged error or no gain in tests passed. We tune $m$ on the calibration split. It is the rule most practitioners would write first.
The third is the same hazard model and conformal calibration using only verifier-side features. This is the key ablation. It uses identical data, model class, hyperparameter search budget, and $\alpha$, and differs from our method only by excluding the entropy and varentropy features. If it matches the full model, the entropy signal adds nothing and our core claim is false.
The strongest existing method is an adaptation of Statistical Early Stopping to this setting. It applies their doubt-keyword counting and maxwise conformal rule to the natural-language reasoning the model emits alongside each revision. That paper reports recovering 82–85% of oracle detection power on ill-posed reasoning. We will report our method's gap to the oracle stopper, which halts exactly at $T^*_i$ or immediately when $T^*_i > B$, in the same terms.
We also run a mean-token-entropy-only stopper, as in DebUnc and the code self-correction study. It tests whether varentropy and diff-localized features matter beyond the crude average.
Finally, we compare against compute-matched restarts. Here the budget saved by early stopping is spent on fresh independent samples, and the comparison asks whether the combined policy beats best-of-$N$ at equal total rounds.
Why not just…?
Why not just use a fixed iteration budget? On any one benchmark, a tuned $K$ may be nearly as good, and that is a real threat. The argument for adaptivity rests on heavy-tailed success times. On VERINA, most gains beyond pass@1 arrive over dozens of rounds, and Statistical Early Stopping shows that fixed length budgets fail to transfer across domains. We settle this empirically in two ways. First, we compare cost at matched $\alpha$ within each benchmark. Second, we calibrate $K$ and $\hat\lambda$ on HumanEval and test on BigCodeBench and LiveCodeBench, measuring how badly each violates its nominal $\alpha$. If fixed $K$ matches us in both settings, we will say so.
Why not just stop when the compiler says you are stuck? Repeated errors and flat test counts are informative and free, and they may capture most of the signal. That is exactly why the verifier-only hazard model is our central ablation and not a strawman. Two gaps motivate the entropy features. Binary test outcomes cannot tell a near-miss from broken code, as ReLoc notes for unit-test search. And Lean compiler errors on proofs often change on the surface without any real progress. The experiment decides the question.
Why not just let the model's uncertainty decide when to regenerate, skipping the verifier? When Uncertainty Isn't Enough shows that this corrupts correct code, and Latent Phase-Shift Rollback reports that prompted self-verification cost 9 points on math. Our method never removes the verifier. It can only decline to buy another round, so its failure mode is bounded and measured.
Why not just prompt the model for its confidence? The code self-correction study found verbalized confidence only weakly related to correctness. Asking for confidence also adds decoding tokens to every round, which works against the goal of reducing latency. We include it as a feature-set variant to confirm it adds nothing beyond the logits.
Proposed Experiments
The primary experiment runs open-weight models on VERINA, HumanEval, BigCodeBench, and LiveCodeBench. Open weights are required because the method needs logits. The small coders from the code self-correction study, DeepSeek-Coder-1.3B, Qwen2.5-Coder-3B, and Llama-3.2-3B, let us compare directly with that paper, and a larger open coder tests whether entropy becomes more informative at scale, which that study left open. We use a 50/50 calibration/test split, repeated over 20 random splits, with $\alpha \in \{0.02, 0.05, 0.1\}$.
We report the following metrics:
- realized missed-success rate against $\alpha$;
- final success rate;
- mean and 90th-percentile rounds per task;
- wall-clock time including compiler calls;
- area under the success-versus-compute curve.
The decisive checks are three.
- Entropy adds information. At equal $\alpha$, the full model must use significantly fewer rounds than the verifier-only hazard model, judged by paired comparison over splits. If it does not, the entropy signal is not worth adding.
- The guarantee holds out of domain. Calibrating on one benchmark and testing on another must keep the missed-success rate near $\alpha$ better than a fixed $K$ does.
- Early stopping beats restarting. In the compute-matched comparison, early stopping must beat best-of-$N$ restarts on the success-versus-compute curve.
A secondary analysis tests the thrashing hypothesis. It plots diff-span varentropy and mean entropy for loops that eventually succeed against loops that never do. If the entropy-based stopper wins, this analysis shows why. If the hypothesis fails, it explains why the ablation came out the way it did.
References
- VERINA: Benchmarking Verifiable Code Generation
- RepoCoder: Repository-Level Code Completion Through Iterative Retrieval and Generation
- Extrapolative Controlled Sequence Generation via Iterative Refinement
- When Uncertainty Isn't Enough: An Empirical Study of Self-Correction in Code Generation
- Statistical Early Stopping for Reasoning Models
- LogitScope: A Framework for Analyzing LLM Uncertainty Through Information Metrics
- Useful Confidence Measures: Beyond the Max Score
- Latent Phase-Shift Rollback: Inference-Time Error Correction via Residual Stream Monitoring and KV-Cache Steering
- Efficient Diffusion LLMs via Temporal-Spatial Parallel Decoding and Confidence Extrapolation
- DebUnc: Improving Large Language Model Agent Communication With Uncertainty Metrics
- Let's Revise Step-by-Step: A Unified Local Search Framework for Code Generation with LLMs