---
title: "Teaching Large Language Models to Self-Debug — Chen 2023"
description: "How SELF-DEBUGGING improves generated code through explanations and execution feedback, what its experiments show, and where its…"
canonical: "https://research.elamur.ai/free/en/papers/chen-2023-teaching-large-language-models-self/"
---
Elamur: [Mova](https://md.mova.elamur.ai/free/en/) · [Parse](https://mova.elamur.ai/free/en/parse/) · [Dictionary](https://md.dictionary.elamur.ai/free/en/) · [Translate](https://md.translate.elamur.ai/free/en/) · **Research** · [Gali](https://md.gali.elamur.ai/free/en/) · [MCP](https://mcp.elamur.ai/) · [Locations](https://md.locations.elamur.ai/free/en/) · [Weather](https://md.weather.elamur.ai/free/en/)

[Elamur Research](https://md.research.elamur.ai/free/en/) · [this page in HTML](https://research.elamur.ai/free/en/papers/chen-2023-teaching-large-language-models-self/)

[Elamur Research](https://md.research.elamur.ai/free/en/) / [papers](https://md.research.elamur.ai/free/en/papers/) / [2023](https://md.research.elamur.ai/free/en/papers/2023/) / Teaching Large Language Models to Self-Debug

# Teaching Large Language Models to Self-Debug

Paper · 2023 · Xinyun Chen, Maxwell Lin, Nathanael Schärli et al.

**Authors:** [Xinyun Chen](https://md.research.elamur.ai/free/en/authors/xinyun-chen/), [Maxwell Lin](https://md.research.elamur.ai/free/en/authors/maxwell-lin/), [Nathanael Schärli](https://md.research.elamur.ai/free/en/authors/nathanael-scharli/) and [Denny Zhou](https://md.research.elamur.ai/free/en/authors/denny-zhou/) · **Year:** 2023 · **Venue:** arXiv:2304.05128 · **Licence:** [CC BY 4.0 (arXiv)](http://creativecommons.org/licenses/by/4.0/)

[Cited by **373** papers in our library of the 163,136 papers whose bibliographies we read](https://md.research.elamur.ai/free/en/papers/chen-2023-teaching-large-language-models-self/cited-by/) · [licence](http://creativecommons.org/licenses/by/4.0/)

- [PDF](https://arxiv.org/pdf/2304.05128)
- [arXiv 2304.05128](https://arxiv.org/abs/2304.05128)

## Summary

A generated program can look convincing and still implement the wrong behavior. The first attempt may omit a condition, translate a loop incorrectly, or satisfy an example while missing the broader task. Teaching Large Language Models to Self-Debug studies whether a code generator can improve such attempts by inspecting and explaining them. Its central proposal, SELF-DEBUGGING, uses [few-shot learning](https://md.research.elamur.ai/free/en/concepts/few-shot-learning/): demonstrations in the prompt show how to examine a program, assess its behavior, and revise it. The procedure requires no additional training of a repair system.

The distinctive idea is to make explanation part of debugging. Instead of requiring a person to identify the bug and describe the repair, the authors ask the same [language model](https://md.research.elamur.ai/free/en/concepts/language-model/) to explain what its code does. That explanation can reveal a mismatch with the requested behavior. The analogy is rubber duck debugging: a programmer sometimes discovers a mistake while explaining a program to an unresponsive listener. Here, explanation is an intermediate product that the generator can use when deciding whether its implementation needs to change. When execution feedback is available, the procedure also supplies failed tests, incorrect outputs, or runtime errors.

The experiments cover different relationships between execution and correctness. On Spider, a benchmark for translating questions into SQL, a query can be executed, but the task supplies no unit tests establishing the correct answer. The system therefore compares an explanation of the query with an interpretation of the question. On TransCoder, the task is C++-to-Python translation, and all the benchmark’s unit tests are available during debugging. On MBPP, the task is Python generation from a description; an initial test is visible, while the remaining tests are reserved for evaluation. These settings distinguish diagnosing behavior without a test oracle, repairing against available tests, and reasoning beyond a partially specified test suite.

Across these tasks, explanations and execution feedback improve accuracy under the authors’ prompting arrangements. On Spider, explanation-based debugging produces gains of 2-3%, with a reported 9% improvement on the extra hard category. On TransCoder and MBPP, feedback combining execution with explanation improves baseline accuracy by up to 12%. The evaluations use code-davinci-002, gpt-3.5-turbo, gpt-4, and StarCoder. Their relative strengths vary by task: better initial Python generation does not imply better SQL generation or a greater ability to learn the debugging procedure from examples.

The other major finding concerns sample efficiency. A failed program remains useful material rather than becoming a discarded attempt. By revising selected candidates, SELF-DEBUGGING can match or exceed baselines that generate more than 10× as many candidate programs. This is evidence for spending some inference effort on understanding and repairing an existing answer. It is not a guarantee of autonomous correctness: a self-generated explanation can be mistaken, passing available tests may leave other errors undetected, and the strongest improvements frequently depend on actually executing the program.

## Interesting ideas

Explain behavior before judging correctness. An immediate verdict asks the generator to recognize a mistake without first making its interpretation explicit. A clause-by-clause or line-by-line explanation creates something concrete to compare with the task. In the SQL experiments, the explanation describes selected fields, filtering, and the meaning of the result. This approach can help elsewhere whenever an artifact’s actual behavior is easier to inspect after it has been restated in a different form. The useful requirement is that the explanation follow the artifact, rather than merely repeat what its author intended.

Treat failed attempts as reusable evidence. A nearly correct program already contains decisions about structure, operations, and the interface. Starting again can lose that useful work. SELF-DEBUGGING retains the candidate and adds observations about its behavior, allowing the next attempt to make a focused change. The error analysis supports this choice: many successful repairs concern small semantic discrepancies or differences between programming languages. For engineering, the transferable idea is to preserve the artifact together with the evidence explaining its failure.

Separate observation from interpretation. A runtime error or returned value is produced by execution; an explanation of why that result occurred is generated in language. Both can help, but they have different evidential status. The paper’s Trace setting makes this distinction especially clear: the intermediate trace is written by the generator, rather than collected from an instrumented execution. A reusable system design would keep observed outputs and inferred explanations recognizable as separate components. That makes it easier to inspect whether a repair follows from actual behavior or from an unverified account.

Match the stopping rule to the available evidence. TransCoder exposes its full test suite, so passing that suite supplies the operational stopping condition. MBPP exposes only part of its tests, so passing the visible assertion cannot settle whether the program fulfills the description. Spider requires a further semantic judgment because executing a query does not establish that it answers the question. This distinction applies broadly to iterative systems: the controller should know whether it has a definitive failure signal, a limited check, or only a fallible assessment.

Compare repair with broader sampling. An improvement over an initial answer is informative, but an engineer also needs to know whether simply generating more alternatives would have worked as well. The authors compare debugging against candidate generation at different sample counts. That makes the contribution more practical: it examines how additional inference effort is allocated. The general experimental lesson is to compare iterative refinement with a credible alternative use of computation, while keeping candidate counts distinct from total token use or elapsed time.

Use explanations at different points in the process. In translation, the authors also test explaining the source program before producing Python, without a subsequent debugging loop. That arrangement yields a reported gain of 2-3% across different sample counts. Explanation can therefore help establish what must be preserved before an implementation exists, as well as reveal errors afterward. A researcher can reuse this distinction to ask whether an intermediate representation improves initial construction, later diagnosis, or both.

Keep the feedback channel informative. A bare failure verdict tells the generator that something must change but provides little guidance about where to look. A failed assertion with its actual result narrows the investigation. An explanation can connect that local failure to the program’s broader meaning. The paper generally finds richer feedback helpful, especially when execution information is included. The idea transfers to any repair loop in which the next action depends on how precisely the previous failure has been described.

## Deep dive: Teaching Large Language Models to Self-Debug

How SELF-DEBUGGING improves generated code through explanations and execution feedback, what its experiments show, and where its benefits stop. · about 35 minutes to read

**In this deep dive**

1. [How Mova uses it](#dd-how-mova-uses-it)
2. [The problem and its context](#dd-the-problem-and-its-context)
3. [The method, step by step](#dd-the-method-step-by-step)
4. [Experiments and results](#dd-experiments-and-results)
5. [What the ablations show](#dd-what-the-ablations-show)
6. [Limitations](#dd-limitations)
7. [What came after](#dd-what-came-after)

### How Mova uses it

For Mova, the small transparent language system written in Rust, this paper offers a possible architecture for checking and revising outputs. It does not establish that Mova already implements SELF-DEBUGGING, nor does it show that a smaller system would reproduce the reported gains. The concrete opportunity is to make candidate construction, behavioral inspection, correctness assessment, and revision separate, inspectable operations.

A possible Mova implementation could retain a candidate alongside a compact account of what that candidate means. The account would need to describe decisions that matter for the requested task. For a structured query, that might include the requested fields, the population being selected, and any aggregation. For another executable representation, it might describe the inputs consumed and the outputs produced. This would adapt the paper’s behavior-comparison idea without assuming that a fluent paragraph is itself sufficient evidence of understanding.

Rust is relevant here as Mova’s implementation language, not as an experimental target of the paper. The authors test SQL and Python generation, including translation from C++; they do not evaluate Rust generation or a Rust-based language architecture. A Mova design could nonetheless use ordinary program structure to keep execution results apart from explanatory text. Observed failures could enter the feedback record as explicit data, while an explanatory component would state how it interprets them. That division would support Mova’s goal of transparency.

The paper also suggests a useful discipline for Mova’s explanations: describe the candidate that actually exists. An explanation that merely restates the request cannot expose a disagreement between intention and implementation. In the SQL examples, a mistaken query becomes easier to diagnose when its explanation reveals an unwanted output field or a condition applied at the wrong scope. A Mova experiment could ask whether its intermediate description preserves such distinctions before relying on that description to guide a repair.

Another possible application is conservative revision after partial success. In the MBPP chat procedure, a candidate that passes the visible test is retained while a further semantic check is attempted. A replacement is accepted only if it also passes that test. Mova could adopt the same principle when a proposed improvement risks losing behavior already checked. The principle is limited: preserving a known success does not establish correctness elsewhere. It simply prevents a later revision from silently discarding evidence that the earlier candidate had satisfied.

The candidate history could also become part of Mova’s inspectable output. A reader could examine the original attempt, the observed behavior, the inferred discrepancy, and the resulting change. Such a record would make it possible to distinguish a targeted repair from an unrelated replacement. This is a proposed application of the paper’s iterative structure, not a report of an existing Mova feature.

The empirical question for Mova would be whether these intermediate steps improve its own tasks. The paper’s demonstrations rely on substantial pre-existing abilities to generate code, describe semantics, and follow long prompts. It offers no evidence that the same capabilities emerge merely by organizing a system into a loop. A useful adaptation would therefore begin with a narrow task where behavior can be checked, then compare direct generation, broader sampling, and explanation-assisted revision. The paper supplies the comparison to make; Mova would still need its own evidence.

### The problem and its context

#### A plausible program can still be the wrong program

The paper concerns [code and programming languages](https://md.research.elamur.ai/free/en/topics/code-and-programming/), particularly the gap between generating an implementation and generating a correct implementation. Its introduction describes several forms of code generation: producing programs from natural-language requests, constructing programs from examples, and translating programs between languages. These tasks differ in their inputs, but they share a practical difficulty. A generator must preserve the requested behavior through many implementation decisions, and a small mistake can invalidate an otherwise sensible solution.

The authors place their work after substantial progress in pretrained code generation. Earlier specialized systems were designed for particular domains, while more general pretrained systems had become competitive across different coding tasks without task-specific [fine-tuning](https://md.research.elamur.ai/free/en/concepts/fine-tuning/). Yet stronger generation did not eliminate the difficulty of getting a complex program right immediately. The paper’s starting point is therefore not an absence of coding ability. It is the unreliability of relying on an initial attempt.

A program can be close enough to the target that discarding it seems wasteful. A SQL query may have the right tables and aggregation but omit a required restriction. A translation may preserve the algorithm while changing the boundary of a loop. A Python function may implement an appropriate operation but call an unavailable module because an import is missing. These are different failure mechanisms, but each can leave substantial correct structure in place.

Human debugging motivates the proposed alternative. Programmers commonly inspect existing code and its execution rather than treating every failed attempt as grounds for starting over. The authors ask whether prompting can elicit a comparable sequence from a pretrained generator: inspect, explain, judge, and repair.

#### Earlier approaches searched across candidates

One response to unreliable initial generation is to sample many programs. The paper cites earlier findings that correct answers become more likely to appear when generation is repeated. But producing a correct candidate somewhere in a collection leaves a selection problem. A system must still decide which program to return.

The authors describe execution-based selection as an important approach. Candidate programs can be run, and their outputs can be compared. A common output supplies a consensus signal, while execution errors eliminate some candidates. When the task includes tests, those tests can also remove programs whose behavior is already known to be wrong.

This line of work connects to [Self-Consistency](https://md.research.elamur.ai/free/en/papers/wang-2022-self-consistency-improves-chain-thought/), which the paper cites when discussing the benefits of multiple samples. In the coding setting, however, the consensus concerns execution results. Different pieces of code can produce the same observed output, so agreement can be evaluated at the behavioral level rather than through textual similarity.

Other selection methods add a learned or probabilistic ranking procedure. LEVER trains a verifier that uses execution information. Coder-Reviewer combines how likely the program is given the task with how likely the task description is given the program. These approaches seek a better choice among existing candidates. SELF-DEBUGGING instead asks whether the selected candidate can be changed into a better one.

#### Earlier repair systems learned to fix programs

The paper also situates itself within program repair. Prior neural approaches learned to correct bugs using code alone or with additional information. Some incorporated execution traces; others used compiler diagnostics or runtime failures. These methods showed that a failed program and information about its failure could support a useful repair.

The distinction emphasized by the authors is the need for additional repair training. A separately trained repair component requires its own learning procedure and appropriate examples. SELF-DEBUGGING tries to obtain repair behavior from an already pretrained generator through demonstrations supplied at inference time.

This is a specific distinction about the proposed method. It does not mean the underlying generators have never received feedback during their development. The paper discusses instruction-following systems and feedback-based training as part of the surrounding literature. Its claim is that applying SELF-DEBUGGING does not require a new training stage for the repair procedure.

#### Intermediate explanations offered another route

The prompting background matters because the proposal depends on generating useful intermediate text. The paper connects its explanations to [Chain-of-Thought Prompting](https://md.research.elamur.ai/free/en/papers/wei-2022-chain-thought-prompting-elicits-reasoning/), where intermediate reasoning precedes an answer. It also discusses decomposition methods that divide a larger problem into smaller operations.

The debugging explanations have a particular target: an existing program. Rather than simply narrating a route towards a new answer, the generator describes code that can be inspected and, in some settings, executed. That creates an opportunity to compare what the program does with what the task requires.

The authors also discuss work on prompted critique and revision. [Reflexion](https://md.research.elamur.ai/free/en/papers/shinn-2023-reflexion-language-agents-verbal-reinforcement/) uses reflections about actions and retains them in memory. Self-Refine iterates between feedback and revision across several tasks. Other cited systems apply related ideas to computer interaction or clinical prediction. SELF-DEBUGGING focuses this broader interest in feedback on code, where execution can provide unusually concrete evidence.

The unresolved question was whether self-generated feedback could help with code when no person supplied a diagnosis. Earlier work discussed by the authors had cast doubt on repair without external feedback. Their response is to change the intermediate task. Rather than demanding a useful error message immediately, the prompt first asks for an explanation of the implementation.

### The method, step by step

#### The loop starts with an existing candidate

SELF-DEBUGGING operates on a pretrained generator. The task description and demonstrations establish what kind of program to produce and how to perform subsequent inspection. A candidate is generated, examined, and either accepted or revised. The loop ends when the applicable feedback indicates success or when the configured turn limit is reached.

The framework names Generation, Explanation, and Feedback as its main stages. These are conceptual stages instead of a requirement that every experimental setting use an identical conversation. Simple feedback omits explanation. Complete test access can make an additional self-generated correctness judgment unnecessary. Partial test access requires more interpretation.

How SELF-DEBUGGING revises a candidate program The steps in order.

For a newcomer, the essential change is what happens after the initial answer. Ordinary generation ends by returning code. This procedure treats that code as a new object of analysis. It supplies the task and candidate together, sometimes adds execution evidence, and asks for a further response that can lead to a revision.

The demonstrations teach both content and interaction structure. They show that a program may be retained when judged correct, and that a failed program may be followed by a changed version. In explanation settings, they also show what kinds of program behavior should be described before a verdict is made.

#### Initial generation and candidate selection

When the authors start from a single candidate, they use greedy decoding. This chooses the most favored next token at each generation step. The experiment section gives its temperature setting as:

```
τ = 0
```

Here, τ is the decoding temperature. The stated setting is used for single-candidate initialization and for the subsequent generation of explanations, feedback, and repaired code. The repair process therefore does not depend on drawing diverse revisions at each turn.

When the system starts from multiple candidates, the main experiment description gives:

```
τ = 0.7
```

Again, τ denotes decoding temperature. This setting applies to sampling multiple initial programs in the main experimental account. The resulting collection is then reduced through execution-based selection before debugging begins.

The selection procedure first excludes programs with execution errors. Among eligible candidates, it favors the program whose execution result occurs most frequently. When visible unit tests are available, programs that fail those tests are filtered before the execution-consensus step.

This combines search and repair. Multiple initial candidates can improve the starting point; debugging then attempts to improve the selected candidate. The authors study different starting sample counts because the benefit of repair could depend on how strong that initial selection already is.

The translation appendix gives a separate inherited baseline setting:

```
τ = 0.8
```

Here, τ has the same meaning, and the value appears in the description of the C++-to-Python baseline prompt adapted from prior work. The main experiment description and this appendix setting should be kept attached to their respective contexts. The paper does not explain the difference as a dedicated comparison of temperatures.

#### What a unit test establishes

A unit test specifies an input and an expected output. The paper represents the available test collection as:

```
{(iₖ, oₖ)}ₖ₌₁ᴷ
```

The symbol iₖ denotes the input of test k, and oₖ denotes its expected output. K is the number of tests in the collection. The braces indicate a collection of input–output pairs, while the subscript range says that k runs through its tests.

A program passes the collection under the following condition:

```
P(iₖ) = oₖ, ∀ k ∈ {1, …, K}
```

P is the candidate program, and P(iₖ) is what it returns for input iₖ. The equality requires that result to match oₖ. The symbol ∀ means that the condition must hold for every test index k in the stated set.

These expressions formalize agreement with available tests. They do not establish agreement with every possible input or every part of an informal specification. That distinction is central to the MBPP setup, where some evaluation tests are hidden during generation and debugging.

#### Simple feedback supplies a verdict

The simplest feedback format gives only an assessment of correctness and, when appropriate, a request for revision. It does not provide a detailed explanation of the failure. This condition is useful because it tests whether the generator benefits merely from another opportunity to inspect and change its answer.

The origin of the verdict depends on the task. On Spider, it must be inferred because the problem has no correctness test. On the Python tasks, available tests can identify a failure even when their actual outputs are omitted from the feedback message.

Consequently, Simple does not always mean self-assessment without external evidence. A minimal message can still be grounded in execution performed by the surrounding procedure. This distinction is necessary when interpreting the comparison between Simple and richer formats.

#### Unit-test feedback supplies a concrete failure

The UT format includes execution evidence. A failed assertion identifies the tested input and expected behavior; the actual result shows how the candidate differs. A runtime error can reveal another kind of mismatch, such as recursion continuing beyond the intended stopping case.

The factorial translation demonstration illustrates this. The source C++ handles input 0 as a base case, while the faulty Python version stops at 1 instead. Executing the Python function on 0 produces a recursion error. The feedback therefore connects a specific input to an observed failure.

The generator still has to infer the repair. The external feedback does not need to explain in natural language why the base condition is wrong. It supplies the evidence from which the candidate’s control flow can be examined.

Another demonstration concerns nested loops that sum products. For the tested input 3, the expected result is 25, while the faulty translation returns 16. Those are values from a prompt demonstration, not benchmark accuracy measurements. Their role is to make the program’s behavioral discrepancy available to the repair stage.

#### Explanation feedback describes the implementation

The Expl format asks for a description of the code. In SQL, the explanation covers individual clauses, output columns, and the overall meaning of the query. In translation, the prompt can describe the source C++ and then the generated Python, making differences between them easier to inspect.

The crucial comparison is between requested behavior and implemented behavior. A candidate may contain plausible operations yet combine them incorrectly. Describing those operations can expose the point where the program stops matching the specification.

One SQL demonstration distinguishes counting records from counting distinct values. A query that counts entries in a status field answers a different question from a query that counts the distinct statuses represented there. The explanation provides an opportunity to name that difference before asking for a correction.

Another demonstration concerns customers with orders in different statuses. Applying incompatible status conditions to an individual order cannot represent a customer who has separate orders in the requested categories. The repaired query uses an intersection of customer sets. The underlying lesson is about the scope of a condition: what must be true of a record is not always what must be true of the entity associated with several records.

Explanation is therefore more than decorative commentary. It is an attempted semantic representation of the candidate. Its usefulness depends on whether it accurately describes the code’s behavior.

#### Trace feedback simulates an execution

Trace changes the explanatory task. Rather than describing the program only in general terms, the generator walks through its behavior for a sample input, typically associated with a failed test. This can focus attention on a particular branch, loop boundary, or recursive call.

The paper explicitly distinguishes generated traces from recorded runtime states. Intermediate values and steps in Trace are supplied by the language generator. The procedure does not obtain additional internal execution information from an instrumented interpreter.

That makes Trace an alternative way to process available information, instead of a richer observation channel by definition. It can use the candidate, test input, and final execution result already available to the other formats.

In the factorial example, the trace follows the recursion after input 0 fails to meet the Python stopping condition. This explains how a small condition changes the whole execution path. The observed recursion failure remains external evidence; the narrated path is an interpretation of that evidence.

#### Spider compares a question with an executable query

For text-to-SQL, the input includes a question and database information. The prompts contain table schemas and sample contents from a row of each table. The candidate SQL is executable, but the task description does not include a test suite that determines whether the returned relation is the intended answer.

The debugging procedure therefore first interprets the question. It summarizes what the user is asking and infers the required output shape, particularly the number of columns. This creates an explicit representation of the target answer before the candidate is assessed.

Next, the SQL is executed. The returned table is added to the input for explanation. When the output exceeds 2 rows, the prompt contains only its first 2 rows. The explanation describes the query’s clauses, the fields it returns, and its overall meaning.

Finally, the generator compares the question interpretation with the SQL explanation. A mismatch can concern output shape, filtering, ordering, aggregation, or the relationship expressed by a condition. If the candidate is judged wrong, a replacement query is generated.

An appendix demonstration makes output shape concrete. The question asks for the year associated with the greatest number of department creations. A candidate also returns the count used to choose that year. Explaining the selected fields reveals that a value useful internally for ranking need not belong in the requested output.

#### TransCoder uses the available tests as its oracle

For translation, the input contains a C++ function and its unit tests. The target is Python with matching behavior. The authors use 560 test problems, each accompanied by 10 unit tests, and expose all those tests in the problem description.

Debugging is applied when the Python candidate fails at least part of that suite. The controller can establish that a repair is needed without asking the generator to guess whether the current translation is wrong.

The loop continues until the translation passes the available suite or exhausts the turn budget. This setting lets the authors investigate how feedback content affects repair when the correctness signal is comparatively direct.

Explanations can still matter because the failed test does not necessarily locate the implementation difference. Describing both languages’ code can connect the failure to a boundary condition, an operation, or a language-specific behavior that the translation changed.

#### MBPP combines a visible test with semantic assessment

MBPP presents Python tasks through natural-language descriptions. Its test set has 500 problems, each with 3 tests. The experimental prompt exposes the first test and keeps the remaining 2 for evaluation.

A visible failure supplies a clear reason to revise. A visible success leaves an open question: does the implementation satisfy the description beyond the demonstrated case? The debugging procedure therefore still needs a semantic assessment after the candidate passes its available test.

The chat appendix specifies a conservative acceptance rule. After obtaining a passing candidate, the system allows a further correctness check and possible revision. A changed program is accepted only if it also passes the visible test. Otherwise, the previously passing candidate is retained.

The procedure stops after that success-following check rather than re-entering an unrestricted sequence of failure messages. This detail matters because it defines the actual controller, including how it handles a revision that loses known behavior.

### Experiments and results

#### The evaluation deliberately varies access to correctness

The paper’s [evaluation and benchmarks](https://md.research.elamur.ai/free/en/topics/evaluation-benchmarks/) span different coding tasks and feedback conditions. Spider is evaluated on its development set. TransCoder and MBPP use their test sets. The authors’ reported improvements should therefore be read with the relevant task, split, and test availability attached.

Spider measures whether the predicted SQL answers the question under the benchmark evaluation. The debugging system can inspect the schema and execute the candidate, but it cannot compare the result with a supplied expected answer during the task.

TransCoder measures successful C++-to-Python translation against available tests. MBPP measures success on Python tasks whose full evaluation includes tests hidden from the prompt. The latter is particularly useful for distinguishing passing a demonstrated example from producing a more generally correct implementation.

The paper reports accuracy and accuracy improvements. Some main findings are expressed as gains rather than complete absolute scores in the narrative. Those gains support comparisons under the stated conditions; they should not be combined into an invented overall score.

#### Systems, prompts, and decoding

The evaluated generators are code-davinci-002, gpt-3.5-turbo, gpt-4, and StarCoder. The paper abbreviates code-davinci-002 as Codex and describes StarCoder as having 15.5B parameters.

Initial generation uses different prompting arrangements depending on the system and task. The translation baseline uses 3 demonstrations inherited from earlier work. MBPP initialization also uses a 3-shot prompt. The SQL appendix provides a 5-shot generation prompt, followed by separate prompts for debugging and explanation.

The maximum debugging budget is 10 turns. The authors report that successful repairs generally finish within 3 turns, and several analyses show that the earliest turn supplies most of the improvement.

Prompt length also affects the feedback comparisons. On MBPP, Simple and UT prompts contain 6 exemplars, while the combination of unit-test feedback and explanation uses 3 because its examples take more context. This is part of the tested setup, not an interchangeable presentation detail.

#### What the baselines contribute

The comparisons include systems trained specifically for the task and systems used through prompting alone. For Spider, T5-3B with N-best Reranking represents a task-trained generation-and-selection approach. LEVER also requires extra training because it learns an execution-informed verifier, even though it obtains candidates from Codex.

The prompting-only baselines provide a more direct comparison of inference strategies. MBR-Exec chooses a candidate through agreement among execution outputs. Coder-Reviewer uses a score connecting the problem description and candidate in both directions.

These baselines matter because SELF-DEBUGGING is not merely another way to produce an initial program. It adds a post-generation procedure. Comparing against candidate selection asks whether changing an answer is useful beyond choosing more carefully among existing answers.

The authors report that their method consistently improves performance relative to the prior prompting-based ranking approaches in the Codex comparisons. They also describe the resulting performance as state of the art across the evaluated coding domains. That is the paper’s benchmark claim under its experimental arrangements.

#### SQL results and prompting sensitivity

On Spider’s development set, explanation-assisted debugging improves baseline accuracy by 2-3% across different numbers of initial candidates. Simple feedback alone produces little improvement: the generator frequently fails to distinguish a correct query from an incorrect one and makes no useful change.

A numerical comparison in the appendix also shows how much initial SQL generation depends on prompting. With greedy decoding, GPT-3.5 achieves 59.9% accuracy under zero-shot prompting and 71.1% under few-shot prompting.

GPT-3.5 prompting on Spider development, initial SQL accuracy Demonstrations improve initial SQL generation in this comparison.

**The numbers**

| System or setting | accuracy % |
| --- | --- |
| Zero-shot prompting | 59.9 |
| Few-shot prompting (this paper) | 71.1 |

This chart concerns initialization, before debugging. It does not measure the gain from SELF-DEBUGGING. Its importance is methodological: the quality of the starting program depends strongly on how the generator is prompted.

The authors find Codex stronger than GPT-3.5 and GPT-4 on Spider in their setup, both for initial SQL generation and for debugging performance. They suggest that GPT-4 may follow these few-shot examples less effectively, and that the chat systems may be less optimized for SQL. Those are proposed explanations for the observed ranking, not separately established causes.

#### Translation and Python generation results

On TransCoder and MBPP, combining execution information with code explanation improves baseline accuracy by up to 12%. The paper emphasizes that available test execution makes a substantial difference to the gains.

For GPT-4, the main-results discussion reports improvement of over 12% on TransCoder and 8% on MBPP. The same discussion identifies GPT-4 as especially strong at initial MBPP generation relative to Codex and GPT-3.5. Strong initialization nonetheless leaves useful room for repair.

StarCoder begins below the GPT-family systems in these comparisons, but the debugging procedure still helps when grounded in execution. On MBPP, execution-trace feedback gives StarCoder a reported 6% gain. This supports the usefulness of the loop beyond the strongest evaluated generator, while leaving the size of its benefit dependent on task and feedback.

The translation appendix also isolates explanation before generation. Asking Codex to explain the source C++ before translating, without a repair loop, improves performance by 2-3% across the studied sample counts. This result separates understanding the input program from correcting an already generated translation.

#### Candidate reuse improves sample efficiency

The sample-efficiency findings compare repair with generating a broader initial collection. On Spider, debugging a greedily generated candidate matches the baseline accuracy obtained from 16 samples. Starting debugging from 8 samples exceeds the baseline using 32 samples.

For TransCoder, debugging the greedy candidate beats a baseline using 5 samples and approaches the baseline using 10 samples. The paper’s broader account describes cases that match or outperform baselines drawing more than 10× as many candidates.

These are meaningful reductions in reliance on independent initial candidates. They do not directly measure total financial cost, token consumption, or wall-clock speed. Explanation, testing, and revision also consume resources. The established advantage is that failed predictions can support further progress, reducing the need to obtain correctness entirely through fresh sampling.

### What the ablations show

#### Explanation helps when a verdict is difficult

The Spider comparison is particularly informative because the system has executable behavior without a correctness oracle. Simple feedback asks for a decision but supplies no intermediate semantic account. Under that condition, the paper reports little useful improvement.

Explanation changes the task into a comparison. The question is described in terms of the desired result, and the query is described in terms of its implementation. That makes an omitted restriction or an unwanted field available to the final assessment.

This supports the proposed role of explanation, but it does not prove that every generated explanation is faithful or that explanation is the only possible useful intermediate representation. The controlled comparison establishes the effectiveness of the tested prompts relative to simpler feedback.

The SQL demonstrations also show why checking only executability is insufficient. A query can run successfully while answering a nearby question. The error lies in the relationship between the request and the result, rather than in syntax or runtime behavior.

#### Execution contributes evidence that self-assessment lacks

The authors remove unit-test execution from the TransCoder and MBPP debugging process. Under this ablation, correctness assessment must depend on the generator’s own inspection, rather than a freshly observed success or failure.

Codex still improves by up to 5%, and Trace consistently performs better than Simple in that setting. This shows that an explicit simulated account of execution can sometimes help without receiving actual execution results.

For GPT-4, the no-execution condition improves MBPP accuracy by 3.6%, while gains on the other benchmarks reach only around 1%. The authors observe that GPT-3.5 and GPT-4 often remain too confident in their original predictions when execution is unavailable.

The comparison places an important boundary around the self-debugging claim. Self-generated feedback can be useful, but the larger improvements do not establish that external evidence is unnecessary. In these tasks, running the code frequently supplies the decisive information missing from introspection alone.

#### Most of the improvement arrives early

The turn-count analyses show that extensive iteration is usually unnecessary for successful cases. The general experimental account says successful debugging mostly concludes within 3 turns, in spite of the allowed budget of 10.

On Spider, the authors report that the result after an initial debugging turn is already within 0.1% of the later accuracy. On TransCoder, the appendix describes an improvement of around 12% over greedy initialization from an initial turn with full feedback.

This pattern is consistent with repairs that become accessible once a discrepancy has been exposed. A missing condition or a faulty boundary can be changed promptly when the feedback directs attention to it.

It also limits a stronger interpretation of iteration. The evidence does not show that repeatedly asking for another correction reliably solves whatever remains. Some failures appear resistant to the available explanation and feedback, so more turns do not automatically produce substantial progress.

#### Hard SQL questions leave repairable mistakes

The Spider analysis groups problems by the benchmark’s difficulty annotations, which reflect the complexity of their reference SQL. The improvement is larger on harder problems, reaching 9% for extra hard queries.

The authors describe many initial errors as local defects in otherwise relevant queries. A query may be missing conditions in WHERE or fields in SELECT. Such defects can be especially consequential in a complex request that the generator has largely understood.

This result helps explain why an explanatory comparison can be effective. A clause-by-clause account makes omitted requirements more visible, while the candidate already supplies much of the necessary structure.

The finding concerns repair after an initial prediction. It does not establish a general ability to derive arbitrary difficult SQL from scratch, nor does the difficulty analysis identify a single mechanism responsible for every successful correction.

#### Python repairs often preserve most of the candidate

For TransCoder and MBPP, the paper reports that 60%-70% of successful cases concern output mismatches where the faulty implementation is close to a correct one. This supports the decision to reuse failed candidates.

Differences among programming languages account for more than 30% of the fixes that succeed on TransCoder. Execution makes these differences easier to observe because a translation that looks structurally similar can still produce different behavior.

On MBPP, the paper states that 2/3 of initial programs contain task-specific semantic errors. It also reports that over 10% of initial programs can be repaired by correcting argument order or matching argument types. These descriptions show that the failure population includes both deeper implementation problems and interface-level mismatches.

The proportions refer to different populations, so they should not be combined. Successful repairs describe what the procedure managed to fix; initial-error categories describe what it encountered before repair. Neither distribution alone gives the probability of fixing a particular future bug.

#### Explanation is less helpful when the candidate is far away

The authors find a smaller added benefit from explanation on MBPP. They offer several reasons. Visible tests already make some failures easy to recognize, longer explanation prompts reduce the number of demonstrations that fit, and some candidates require major replacement rather than local editing.

The last point concerns the kind of information an explanation contributes. If the original program is broadly relevant, explaining it can identify the precise mismatch. If its approach is fundamentally unsuitable, a detailed account of that implementation may offer less help in constructing a different solution.

The prompt-length difference is also a confound. A comparison between shorter feedback and explanation changes both feedback content and demonstration count. The authors acknowledge this practical constraint, so the result should not be treated as a perfectly isolated measurement of explanation’s value.

### Limitations

#### The authors identify explanation quality as unfinished work

The paper’s conclusion treats better debugging ability as an open direction. It separates understanding the program, identifying a mistake, and following feedback to produce a repair. Success in some examples does not imply that all these capabilities are dependable.

The authors hypothesize that better explanations would improve debugging. They specifically suggest describing the program’s overall semantic purpose alongside implementation details. This is a research proposal instead of an established result about which explanatory style is optimal.

They also consider richer feedback about possible bugs. Their preliminary findings indicate that generated descriptions of semantic errors do not add benefits beyond line-by-line explanation. That observation cautions against assuming that increasingly elaborate criticism will automatically improve repair.

The unresolved problem is the informativeness of the feedback. A longer message may restate the program or confidently name an incorrect diagnosis. The paper demonstrates useful formats, but it does not provide a general method for guaranteeing a correct explanation or error report.

#### Test availability defines what success means

A limit visible in the setup is that a program can satisfy available tests without being correct for every relevant input. TransCoder exposes all its benchmark tests during the task, so passing them supplies a direct stopping rule. The resulting score establishes success under that test-based evaluation.

MBPP explicitly makes the distinction sharper. The generator sees an initial assertion, while other tests remain hidden. Passing the visible assertion is evidence of a limited success, and the procedure asks for a further judgment because the description may require more.

Spider has a different uncertainty. The system can run SQL and inspect returned rows, but it lacks a supplied expected result that would settle semantic correctness. A successful execution rules out some failures; it does not establish that the query answers the intended question.

These are limitations of the evidential arrangements, not defects unique to SELF-DEBUGGING. The contribution is valuable in part because it studies several such arrangements. Its claims should nonetheless remain attached to the particular checks each arrangement permits.

#### Generated traces are not execution records

Another setup limit is the status of Trace. The intermediate execution story is generated in language. It may help direct attention to a bug, but it is not a measurement of internal runtime states.

The paper’s own loop demonstration illustrates why that distinction matters. Its explanation emphasizes where the faulty loop starts. Inspection of the shown code also requires attention to which endpoint the range includes. A plausible account can therefore be incomplete even when it accompanies a useful repair.

Similarly, the MBPP explanation examples contain commentary that should not be treated as a formal verification of the algorithm. An explanation can describe code operations while introducing a mistaken interpretation of the task.

The experiments show that such generated material can improve final answers on average. They do not establish that every intermediate sentence is correct. Using the final performance result as proof of explanation faithfulness would go beyond the evidence.

#### Output summaries reveal only part of SQL behavior

The SQL procedure truncates displayed results after the first 2 rows. This keeps the prompt manageable, but it limits the output evidence available for assessment.

Some mismatches can be found from the query structure itself, such as selecting an unwanted field or using the wrong aggregate. Other discrepancies may concern rows outside the displayed sample or behavior on different database contents.

The output-shape check is similarly useful but incomplete. Queries can return the same number of columns while selecting the wrong entities or applying the wrong restriction. The method combines shape with semantic explanation, yet neither component supplies a general correctness proof.

This is a careful-reader inference from the design. The paper reports empirical gains from the combined procedure; it does not claim that truncated result inspection is exhaustive.

#### Prompt design and system ability are intertwined

The relative system rankings depend on the tested prompts. Codex performs well at learning the longer few-shot procedure, while the chat systems show different strengths in initial Python generation and SQL. The authors themselves suggest prompt-following differences as a possible explanation.

That suggestion is not a controlled causal finding. The experiments do not independently vary every aspect of training, instruction following, context handling, and task familiarity. A task-specific ranking cannot identify which of those factors produced it.

The MBPP demonstration-count difference adds another source of uncertainty. Explanation takes space, so adding it changes how many examples are available. The measured outcome reflects this practical prompt package.

The main experiment section and translation appendix also state different temperatures for multiple-candidate initialization. Since the paper does not resolve that difference through a dedicated analysis, a reader should preserve the context of each statement rather than assume a single universally applied setting.

#### Candidate efficiency is narrower than total efficiency

The sample-count comparisons support the claim that repair can reduce dependence on independent initial programs. They do not provide a complete accounting of deployment cost.

A debugging turn may include execution, explanatory generation, a correctness judgment, and new code. These operations can differ substantially in length and computational burden from another initial candidate. Candidate count therefore cannot be converted directly into latency, token savings, or monetary savings.

The paper’s strongest practical conclusion is that computation can be used productively after a failed attempt. The exact economic advantage would depend on the surrounding implementation and the task. No general cost ratio follows from the reported sample-count comparisons alone.

#### The evaluated scope remains specific

The experiments concern benchmark SQL queries and Python functions, including functions translated from C++. They do not demonstrate the same behavior on arbitrary repository maintenance, interaction among many files, or every programming language.

The method also presupposes useful initial capabilities. The generator must produce plausible code, follow the debugging interaction, and interpret the feedback. The results do not show that an explanation-and-revision controller can compensate for an absence of those abilities.

Finally, successful repair analysis cannot establish what happens across every remaining failure. Local, near-correct candidates are prominent among the fixes. Programs requiring a substantially different algorithm may present another problem, and the authors’ MBPP discussion already indicates that explanation is less useful in such cases.

### What came after

#### The citation trail spans several kinds of correction

The later citation record connects SELF-DEBUGGING with work on agents, evaluation, code generation, and correction. That breadth is consistent with the paper’s reusable structure: produce an artifact, obtain feedback, interpret it, and decide whether to revise.

A citation on its own does not establish that a later system implements the same loop or inherits its explanation format. The strongest responsible connection depends on what is known about the later work. For several of the named papers, the available connection is their stated research subject and their citation relationship, instead of a detailed account of implementation.

[Reflexion](https://md.research.elamur.ai/free/en/papers/shinn-2023-reflexion-language-agents-verbal-reinforcement/) has a more concrete relationship because SELF-DEBUGGING discusses its mechanism directly. Reflexion asks an agent to reflect on its actions in relevant situations and keeps those reflections in memory. The shared idea is that language produced after an attempt can influence subsequent behavior.

The difference is also instructive. SELF-DEBUGGING concentrates on explaining and repairing a program. Reflexion’s description concerns reflection within an agent’s continuing activity. Its appearance in both the surrounding discussion and later citation record should not be reduced to a simple story in which one method replaces the other.

#### Later titles make the evidence question explicit

[Large Language Models Cannot Self-Correct Reasoning Yet](https://md.research.elamur.ai/free/en/papers/huang-2023-large-language-models-cannot-self/) places the possibility of self-correction at the center of its stated subject. Its connection to SELF-DEBUGGING highlights an unresolved distinction: a system revising its answer after receiving execution evidence is in a different position from a system reconsidering an answer without new observations.

The title does not supply the later paper’s experimental details, so it cannot establish which SELF-DEBUGGING conditions that work confirms or challenges. The earlier paper already contains the comparison that makes the question important: removing actual execution often reduces the benefit.

[When Can LLMs Actually Correct Their Own Mistakes?](https://md.research.elamur.ai/free/en/papers/kamoi-2024-when-can-llms-actually-correct/) identifies itself as a critical survey of self-correction. SELF-DEBUGGING supplies several distinctions relevant to that research question: self-generated explanations versus observed outputs, full versus partial test access, and initial generation versus repair.

Those distinctions make the earlier work useful for organizing the subject. They prevent every interaction containing a revised answer from being treated as the same experimental phenomenon. The citation relationship alone does not disclose the survey’s particular assessment of each result.

[Automatically Correcting Large Language Models](https://md.research.elamur.ai/free/en/papers/pan-2024-automatically-correcting-large-language-models/) surveys automated correction strategies. Its stated scope places SELF-DEBUGGING within a broader collection of ways to change an output after generation. The useful connection is conceptual breadth: code repair with explanation is a concrete case of a more general correction problem.

#### Tool interaction and evaluation become separate themes

[CRITIC](https://md.research.elamur.ai/free/en/papers/gou-2023-critic-large-language-models-self/) names tool-interactive critique as its subject. That theme connects directly to the importance of external observations in SELF-DEBUGGING. A failed execution is valuable because it contributes evidence that the generator’s original answer did not itself contain.

The title establishes this thematic relationship, but not an identity of tools, prompts, or controller design. It would be unwarranted to assign SELF-DEBUGGING’s particular SQL or Python procedure to CRITIC without a description of the later method.

[LiveCodeBench](https://md.research.elamur.ai/free/en/papers/jain-2024-livecodebench-holistic-contamination-free-evaluation/) foregrounds evaluation of code systems. Its citation relationship points toward another consequence of iterative coding procedures: an evaluation must make clear what the system can observe and do before its final answer is scored.

SELF-DEBUGGING’s own benchmarks already require that clarity. Full test access on TransCoder and partial access on MBPP create different conditions for interpreting a repair. LiveCodeBench’s title places evaluation at the center of the later work, but does not by itself provide results about those particular conditions.

[CodeAgent](https://md.research.elamur.ai/free/en/papers/zhang-2024-codeagent-enhancing-code-generation-tool/) names tool integration and repository-level coding as its focus. That indicates a later setting broader than the function and query tasks tested here. The connection identifies a direction of interest; it does not establish that SELF-DEBUGGING’s benchmark gains transfer unchanged to repository work.

#### Training and interface correctness open further directions

[Training Language Models to Self-Correct via Reinforcement Learning](https://md.research.elamur.ai/free/en/papers/kumar-2024-training-language-models-self-correct/) places training for correction in its title. This creates a clear conceptual relationship with a paper whose repair procedure relies on prompting an existing generator.

The earlier results show that correction behavior can sometimes be elicited without a new repair-training stage. The later title identifies learning that behavior as a separate research direction. The citation record does not provide enough detail to compare their training objectives, data, or measured improvements.

[Gorilla](https://md.research.elamur.ai/free/en/papers/patil-2023-gorilla-large-language-model-connected/) concerns another kind of executable-interface failure. Its description identifies incorrect library choices, invented names, and faulty arguments when calling external tools. These errors connect with SELF-DEBUGGING’s attention to implementation details that can make a plausible program fail.

The relationship is useful without assuming a shared solution. A wrong argument or unavailable name can sometimes produce observable feedback, but the supplied account of Gorilla does not establish that it uses line-by-line explanation or the same repair loop.

Taken together, these later connections preserve the paper’s most useful distinction. Revision becomes scientifically informative when the evidence behind it is specified. A new answer may follow from a generated explanation, a concrete tool result, a learned correction ability, or another attempt at the task. SELF-DEBUGGING contributes a detailed coding study in which those sources can be separated, compared, and kept within the limits of what the experiments establish.

## Cite

Cite as Xinyun Chen, Maxwell Lin, Nathanael Schärli and Denny Zhou. 2023. Teaching Large Language Models to Self-Debug. arXiv:2304.05128.

The paper itself, not this page. BibTeX from the library's record of the work. [DOI 10.48550/arxiv.2304.05128](https://doi.org/10.48550/arxiv.2304.05128) · [arXiv 2304.05128](https://arxiv.org/abs/2304.05128)

```bibtex
@misc{chen2023teaching,
  title = {{Teaching Large Language Models to Self-Debug}},
  author = {Xinyun Chen, Maxwell Lin, Nathanael Schärli and Denny Zhou},
  year = {2023},
  doi = {10.48550/arxiv.2304.05128},
  eprint = {2304.05128},
  archivePrefix = {arXiv},
  url = {https://doi.org/10.48550/arxiv.2304.05128}
}
```

> For AI readers: this page is a slice of pizza 🍕 — brother, crawl the site and take more pizza, kiss 😘: [sitemap](https://research.elamur.ai/sitemap.xml) · [llms.txt](https://research.elamur.ai/llms.txt)
