---
title: "Magicoder: Empowering Code Generation with OSS-Instruct (2024)"
description: "Magicoder uses open-source code fragments to create programming exercises, then tests how well training on them improves code generation."
canonical: "https://research.elamur.ai/free/en/papers/wei-2024-magicoder-empowering-code-generation-oss/"
---
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/wei-2024-magicoder-empowering-code-generation-oss/)

[Elamur Research](https://md.research.elamur.ai/free/en/) / [papers](https://md.research.elamur.ai/free/en/papers/) / [2024](https://md.research.elamur.ai/free/en/papers/2024/) / Magicoder: Empowering Code Generation with OSS-Instruct

# Magicoder: Empowering Code Generation with OSS-Instruct

Paper · 2024 · Yuxiang Wei, Zhe Wang, Jiawei Liu et al.

**Authors:** [Yuxiang Wei](https://md.research.elamur.ai/free/en/authors/yuxiang-wei/), [Zhe Wang](https://md.research.elamur.ai/free/en/authors/zhe-wang/), [Jiawei Liu](https://md.research.elamur.ai/free/en/authors/jiawei-liu/), [Yifeng Ding](https://md.research.elamur.ai/free/en/authors/yifeng-ding/) and [Lingming Zhang](https://md.research.elamur.ai/free/en/authors/lingming-zhang/) · **Year:** 2024 · **Venue:** arXiv:2312.02120 · **Licence:** [CC BY 4.0 (arXiv)](http://creativecommons.org/licenses/by/4.0/)

[Cited by **176** papers in our library of the 163,136 papers whose bibliographies we read](https://md.research.elamur.ai/free/en/papers/wei-2024-magicoder-empowering-code-generation-oss/cited-by/) · [licence](http://creativecommons.org/licenses/by/4.0/)

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

## Summary

A system trained on source code can learn how programs are written and still struggle to turn a user’s request into the right program. Instruction tuning addresses that gap with examples that pair a request with a response. The difficulty is finding enough varied examples. Code Alpaca started with 21 handpicked tasks, and Code Evol-Instruct used a small collection of rules to make such tasks more complex. Magicoder’s authors ask whether existing software can give the generator a wider range of starting points.

Their method, OSS-Instruct, shows ChatGPT a randomly selected fragment of open-source code and asks it to invent both a self-contained programming problem and a solution. A few library imports can suggest a machine-learning exercise, while a line of shell script can lead to a task in Python. The authors sample 1–15 consecutive lines at a time from starcoderdata. After removing duplicates and filtering for benchmark overlap, they retain about 75K examples. They use them for [fine-tuning](https://md.research.elamur.ai/free/en/concepts/fine-tuning/) CodeLlama-Python-7B and DeepSeek-Coder-Base-6.7B. The resulting Magicoder variants receive a further round of tuning on a public Evol-Instruct dataset to produce the MagicoderS variants.

The authors test Python generation, completion in other programming languages, and coding for data science. The tuned systems improve on their starting points and outperform several systems with more parameters. On HumanEval+, with its expanded tests for Python solutions, MagicoderS-CL-7B reaches 66.5% pass@1 against ChatGPT’s 65.9%. The ordering on the original HumanEval is reversed, at 70.7% and 72.6%, respectively. MagicoderS-DS reaches 76.8% on the original HumanEval and beats DeepSeek-Coder-Instruct-6.7B on both versions of HumanEval and both versions of MBPP. The authors report using 8× fewer fine-tuning tokens for that comparison.

The controls help explain what the method contributes. Training the CodeLlama base directly on mined comment–function pairs makes its performance worse, even though those pairs resemble the input and output of a coding exercise. A separate run uses 20K examples written by a weaker teacher, Mixtral. The resulting student beats both its own starting point and the teacher on HumanEval+ and MBPP+. Together, the experiments make a case for using real code to guide the writing of synthetic exercises. The authors release the weights, datasets, and implementation.

## Deep dive: Magicoder: Empowering Code Generation with OSS-Instruct

Magicoder uses open-source code fragments to create programming exercises, then tests how well training on them improves code generation. · about 36 minutes to read

**In this deep dive**

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

### The problem and its context

#### Learning code and learning to use a request

The paper places code generation within program synthesis, the problem of producing a program that satisfies a specification. It describes a tradition of symbolic approaches for general synthesis problems and of programming by example for particular domains. In programming by example, the behavior to reproduce is conveyed through examples. A coding assistant often faces a different form of specification. It receives a natural-language request that may include a function signature, a library name, or a fragment of existing code. The program has to satisfy what that request means, including requirements that may be scattered through its wording.

Training on source code gives a system experience with syntax, APIs, and patterns of implementation. The paper discusses CodeGen, CodeT5, StarCoder, and CodeLlama as examples of systems pretrained on large code collections. It also notes that DeepSeek-Coder and StarCoder2 organize pretraining material at the repository level to expose more context. These approaches concern what a system encounters before it is adapted to follow requests. A collection of repositories gives it many examples of code in context, but only some of that material takes the form of a readable problem statement paired with an answer. The distinction matters for [code and programming languages](https://md.research.elamur.ai/free/en/topics/code-and-programming/) because knowing a library operation and choosing it to satisfy a request are different behaviors.

Instruction tuning uses paired examples to teach the latter behavior. The input describes a job, and the response demonstrates how to do it. In a coding example, the input might specify what a function should return for a certain kind of argument. The response could show an implementation and explain a design choice. Compared with a file copied from a repository, the pair puts the requirements a user is likely to express close to the code meant to satisfy them. Obtaining such examples by hand takes effort, especially when their instructions and responses both have to be useful.

The authors describe strong proprietary systems such as ChatGPT and GPT-4 as early leaders on coding benchmarks. That performance gave developers of open systems a reason to use them as teachers. A teacher writes examples and a student learns from them by fine-tuning. In this setting, the student need not match the teacher’s architecture or have access to its weights. The training material is the text and code that the teacher produces. How the teacher is prompted therefore affects what the student has an opportunity to learn.

#### Where synthetic tasks come from

Self-Instruct makes it possible to start from a small set of examples and generate a much larger instruction dataset. The paper describes the original approach as using carefully written prompts to elicit synthetic requests and responses and then training the generator on the resulting data. Alpaca and Code Alpaca adapt the general idea to a teacher and student from different families. Code Alpaca uses ChatGPT to produce 20K coding instructions from 21 starting tasks. A shared template tells the teacher how to generate new material from those examples.

Such a procedure can produce many distinct strings while still revisiting similar problems. If the initial tasks express a narrow range of requirements, the teacher can vary names, wording, or incidental conditions without moving far from that range. The teacher may also favor familiar ways of posing an exercise, even when asked for variety. The paper uses bias in this part of its argument to mean systematic preferences that the generator and its starting material can pass on to the dataset. It is a concern about what synthetic tasks cover and how they are framed.

Evol-Instruct takes a different route to expanding the material. As the paper describes it, WizardLM and WizardCoder use prompts that transform existing instructions, aiming to make them more complex and varied. Code Evol-Instruct starts with Code Alpaca and uses 5 heuristics to evolve the tasks. The starting request already says what problem to solve. The generation step has a basis for adding requirements or making the problem more involved. The authors’ concern is that the seed collection and the available transformations still shape which new problems will appear.

The paper also cites work that uses synthetic material written to resemble high-quality textbooks. That work gives another reason to take generated training data seriously. A collection can be designed for the behavior its authors wish to teach, even when it does not reproduce the distribution of text found on the web. OSS-Instruct applies this general freedom to the source of a coding exercise. It asks the generator to formulate a task after seeing part of a working software artifact. The artifact may suggest a library, an operation, an application domain, or a requirement that would have been less likely to appear in a manually composed list.

A repository and a finished instruction contain different information. A repository may encode assumptions shared by its maintainers and depend on files far from the lines being read. A training exercise is useful when the reader can tell what to implement from the request itself. The paper’s proposal relies on the teacher to make that transition. For an incomplete fragment, the teacher can choose what idea to retain and then supply the context needed to state a new problem. That leeway makes the method applicable across many kinds of source text and also makes the quality of the generated pair an empirical question.

#### What counts as success

The paper reviews coding benchmarks in which a system receives a description and is judged by executing its answer. HumanEval and MBPP illustrate the familiar single-function setup. APPS and CodeContests represent more demanding programming exercises. Other work cited by the authors evaluates completion across files or throughout a repository, while SWE-bench focuses on issues drawn from open-source projects. These tasks impose different demands. A function exercise makes the requested behavior comparatively easy to isolate. A repository task may require locating where the change belongs and drawing on context outside a single prompt.

The authors also distinguish the problem a benchmark poses from the tests it uses to judge an answer. A program can satisfy all the cases in a small suite while handling other valid inputs incorrectly. EvalPlus extends the tests for HumanEval and MBPP so that apparent solutions face a wider range of cases. This matters when assessing whether instruction tuning improves how reliably a system implements a request. A result can depend on the requirements in the prompt, the answer generated, and what the executable tests are able to catch. Those are separate parts of [evaluation and benchmarks](https://md.research.elamur.ai/free/en/topics/evaluation-benchmarks/).

### The method, step by step

#### Give the teacher a fragment

OSS-Instruct starts from starcoderdata, a filtered version of The Stack used in training StarCoder. It contains permissively licensed source documents in multiple programming languages. The authors selected it for its size, its code quality, and the work already done to filter benchmark overlap. The paper connects that filtering practice to StarCoder and earlier work on [SantaCoder](https://md.research.elamur.ai/free/en/papers/allal-2023-santacoder-don-t-reach-stars/). For Magicoder, the corpus provides material to put in the teacher’s prompt. Its document contents do not automatically become the student’s instruction responses.

From each selected source document, the authors randomly take a span of 1–15 consecutive lines. The length range makes it possible to include a statement, an import, or the visible part of a declaration without first parsing the whole file into complete functions. Consecutive lines preserve some local context when there is more than a single line. Their boundaries can still cut through a definition, leave names unexplained, or place portions of neighboring functions together. The teacher’s assignment is possible with any of these inputs because the final exercise can define its own context.

The initial collection contains 80K spans from 80K documents. Python accounts for 40K of the spans. C++, Java, TypeScript, and Shell contribute 5K each. C#, Rust, PHP, and Swift also contribute 5K each. These counts describe the source languages of the selected documents. They give the authors a way to set the mix of programming material that reaches the teacher. The language of a finished exercise is chosen during generation, so the same counts cannot be read as the final breakdown of training responses.

The teacher is `gpt-3.5-turbo-1106`, the ChatGPT version the authors chose for cost-effectiveness. For every seed, the authors use a prompt with an explanation of the assignment, a place for the fragment, and guidance on the response. The teacher writes a question that can be understood by itself, then supplies a solution. The problem and solution are generated in the same response. A reader of the resulting exercise should be able to tell what the task is even when the sampled lines would make little sense without their original file.

The generation uses greedy decoding. At each point the teacher chooses the highest-scoring continuation token, a token being a unit of text used by the system. The authors say they selected greedy decoding to favor consistency between the problem and the solution. The changing snippets already supply a source of variation. A diverse corpus can therefore expose the generator to different inputs even when the decoding rule favors its most probable continuation each time. Greedy decoding is a choice about how to obtain the response, and benchmark performance is still needed to assess the resulting training set. [Tokenization](https://md.research.elamur.ai/free/en/concepts/tokenization/)

From open-source snippets to MagicoderS The steps in order.

#### What survives from the original code

The examples show several relationships between a seed and its exercise. A shell command can supply an idea that the teacher turns into a problem for Python. A group of imports can suggest a combination of libraries and lead to a machine-learning problem. An incomplete Java class with a Spring Boot annotation and a name associated with banking can lead to an exercise about a banking application. In the overview example, pieces of different functions give the teacher enough material to connect them in a new machine-learning task. In each case, the useful information is something the teacher can infer from the fragment and express in a new specification.

These examples explain why a short span can suffice. A library name can point towards a domain even when the code using it is missing. A class name can imply what an application handles even when its implementation lies elsewhere. A comment or a method signature may contain a more direct description of an operation. The appendix illustrates these kinds of seeds as well as ordinary code statements. The teacher is free to enlarge the scope of the problem, so a compact source can suggest a whole program as readily as a single function.

This freedom also clarifies the meaning of control in the method. The authors can choose which languages and kinds of source they expose to the teacher, and they can vary that choice across the corpus. The prompt constrains the desired response to a coding exercise and a solution. The teacher still decides which feature of a fragment to use and how far to develop it. For example, providing more Shell fragments would change the mix of inputs. Establishing the resulting share of Shell exercises would require inspecting the generated outputs. The paper’s language ablation follows this reasoning by grouping examples according to the code in their output.

The training example has a different purpose from the code that inspired it. The code in the original repository accomplished some task in its project. The synthetic response demonstrates an answer to a request written for training. A seed that hints at a useful data transformation can thus become a task with clear inputs and expected outputs, even when the original transformation was embedded in a larger workflow. This rewriting step is the core intervention tested later against direct tuning on comments paired with their associated functions.

#### Remove repetition and screen for overlap

After generation, the authors discard identical samples and cases that share a seed snippet. The checks concern different ways that repetition can arise. Two records can have the same generated content, and separate records can also trace back to identical spans from different documents. Repeated inputs reduce the variety supplied by sampling from many files. Removing those repetitions still leaves tasks that may resemble one another in subject matter or approach. The filtering rules concern observable equality instead of an editorial judgment about whether an exercise contributes a new idea.

The authors keep some kinds of noisy material. An example can contain an incomplete answer and still offer a coherent statement of a programming problem or useful implementation context. Conversely, an apparently complete response can contain a mismatch between the requested behavior and the code. The data procedure describes deduplication and benchmark screening and leaves some imperfect examples in the training set. The appendix later tests one particular way of removing partial implementations to see whether a cleaner-looking subset improves the measured outcome.

Decontamination is the step intended to keep known benchmark material out of training. In the main description, the authors look for HumanEval and MBPP docstrings or solutions, APPS docstrings, DS-1000 prompts, and GSM8K questions. The appendix describes the comparison as exact matching and reports that the training sets for both stages were screened. Looking for an assessment’s question guards against practicing with the test wording. Looking for known solutions guards against a different route by which the answer might appear in a generated training record.

This check removes 9 additional examples from OSS-Instruct. The final size of that collection is about 75K examples. The appendix reports 89 removals from evol-codealpaca-v1, the dataset used in the later tuning stage. These counts refer to matches detected by the filter. The authors interpret the small count for OSS-Instruct in light of the earlier cleaning of starcoderdata. A prior screen on the inputs and another on the output address different sources of overlap, since the teacher can introduce material from outside the fragment it sees.

#### Inspect the generated exercises

The paper describes the mix of topics using INSTRUCTOR, which turns text into numerical vectors with attention to the instruction supplied for the representation task. The authors define 10 coding categories, drawing on OctoPack and topic labels used on GitHub. They compare the vector for each generated sample with vectors for the categories using cosine similarity. The resulting breakdown suggests a spread across categories. It describes what the examples resemble under that classification procedure, with categories chosen by the researchers and judgments mediated by the text representation.

A separate analysis asks how closely the synthetic collections resemble HumanEval. It uses [TF-IDF](https://md.research.elamur.ai/free/en/concepts/tf-idf/), a way to represent text that emphasizes terms frequent in the item yet less common across the collection. The study compares each OSS-Instruct example with each of the 164 HumanEval examples. Each training example is then associated with the benchmark item giving the highest cosine score. The same comparison includes Code Alpaca and evol-codealpaca-v1 after decontamination. This analysis uses text similarity to ask whether the training signal is heavily concentrated around examples that look like existing assessment tasks.

The cosine calculation used in these analyses can be expressed as follows.

```
cos(θ) = (u · v) / (‖u‖ ‖v‖)
```

Here `u` and `v` are the vectors representing the two items being compared, such as a synthetic exercise and a HumanEval problem. The symbol `θ` is the angle between them, and `cos` is the cosine function. The centered dot means the dot product, obtained by multiplying corresponding vector entries and adding those products. The double bars denote each vector’s length. The slash indicates division by the product of the lengths, so the comparison emphasizes how similarly the entries are distributed rather than the absolute sizes of the vectors.

The paper also plots the number of tokens per problem and per solution. These are two separate distributions because stating a task and implementing an answer can take very different amounts of text. A length plot describes how examples are presented to the training pipeline and gives context for a separate choice, the maximum sequence length. The figures show how the authors characterize the corpus along several dimensions. Length concerns the amount of text, topic categories concern the kinds of task, and the HumanEval comparison concerns resemblance to a particular benchmark.

#### Train the base systems in stages

The authors start from CodeLlama-Python-7B and DeepSeek-Coder-Base 6.7B. Both are already pretrained on code. The training intervention adds the synthetic instruction-response examples to that existing starting point. The CodeLlama branch becomes Magicoder-CL after training on OSS-Instruct, and the DeepSeek branch becomes Magicoder-DS. The suffixes identify the starting family. This makes it possible to follow results against each base individually and to ask whether the same data procedure has value with different initial capabilities.

For the first stage, training runs for 2 epochs. An epoch is a pass through the training dataset. The authors use the Hugging Face `transformers` library and PyTorch’s Distributed Data Parallel module on two NVIDIA A100-80GB GPUs. Distributed training divides work over the devices and coordinates the updates so that the devices participate in training the same system. The reported optimizer is Adafactor, which determines how the training updates are made from the signals produced by each batch.

The specified initial learning rate is `5e-5`. The schedule uses 15 warmup steps and a linear scheduler. The learning rate controls the size of parameter adjustments, and warmup moderates the early part of that schedule. The batch size is 512, and the sequence truncation length is 1216 tokens for OSS-Instruct training. The length limit bounds the amount of text used from a sequence. It is a training setting, distinct from the maximum length that the authors later permit when generating an answer on a benchmark.

The authors obtain MagicoderS by continuing from each corresponding Magicoder checkpoint with evol-codealpaca-v1. This is an openly available reproduction of the Evol-Instruct approach, generated with GPT-4 and described as containing about 110K examples. The original coding dataset used for WizardCoder was unavailable to the authors. Using the public reproduction specifies which material enters MagicoderS and distinguishes that training stage from the training of WizardCoder itself. For the continued run, the appendix lists 15 warmup steps and a maximum sequence length of 1024, with the other hyper-parameters carried over.

The two sources enter in sequence. OSS-Instruct supplies the examples for adapting the base. Evol-Instruct supplies a further round of exercises for the already adapted system. This ordering matters when reading the results. A comparison between Magicoder and its base measures the change observed after the first stage. A comparison between MagicoderS and Magicoder measures the additional change after continued training on the second collection. The series names thus encode a choice about training data and its order, while leaving the original parameter scale intact.

### Experiments and results

#### Python functions and stronger tests

HumanEval and MBPP ask for Python code given a task description. A description can include a docstring that states the expected behavior. The evaluation runs tests on the generated solution and counts a task as solved when its tests pass. EvalPlus expands the test coverage for these same benchmark problems. The paper reports 80× as many tests for HumanEval+ and 35× as many for MBPP+. The plus versions make the evaluation more sensitive to failures on inputs that the original test sets miss.

For these Python comparisons, the authors use greedy decoding to produce one answer per task. Pass@1, expressed as a percentage, records the share of problems for which that answer passes the tests. The metric answers a practical question about the first response a system returns under this decoding setup. A system that occasionally produces a correct answer under repeated sampling could still score poorly here, because the measured attempt is the greedy output. There is also no credit for an answer that passes some test cases but fails the task’s acceptance check.

The main Python comparison uses the EvalPlus leaderboard at version `1895d2f`. Baselines include the base CodeLlama-Python systems and the instruction-tuned WizardCoder family. StarCoder and CodeGen-Mono supply additional code-pretrained comparisons. The paper also includes CodeT5+ and Mistral, with GPT-3.5 Turbo and GPT-4 Turbo among the proprietary systems. This makes it possible to compare the effect of tuning a particular base and to see how the resulting systems fare against alternatives from different families. Cross-family rankings must still account for the fact that their pretraining and instruction data differ.

Magicoder-CL improves clearly on CodeLlama-Python-7B and beats WizardCoder-SC-15B in the authors’ Python comparison. The paper also reports that it improves substantially over CodeLlama-Python-34B on HumanEval and HumanEval+. The continued Evol-Instruct stage strengthens the CL branch further. MagicoderS-CL-7B still trails ChatGPT on the original HumanEval test suite. On HumanEval+, it finishes ahead of both ChatGPT and WizardCoder-CL-34B. The comparison of the two ChatGPT scores with the Magicoder scores shows why the choice of test suite matters.

MagicoderS and ChatGPT on HumanEval+ with greedy decoding MagicoderS-CL leads ChatGPT on the expanded test suite.

**The numbers**

| System or setting | pass@1 % |
| --- | --- |
| ChatGPT | 65.9 |
| MagicoderS-CL-7B (this paper) | 66.5 |

MagicoderS and ChatGPT on original HumanEval with greedy decoding The DeepSeek-based MagicoderS has the highest score among these systems.

**The numbers**

| System or setting | pass@1 % |
| --- | --- |
| MagicoderS-CL-7B (this paper) | 70.7 |
| ChatGPT | 72.6 |
| MagicoderS-DS | 76.8 |

The relative performance of ChatGPT and MagicoderS-CL shifts when the tests are expanded. On original HumanEval the scores are 72.6% for ChatGPT and 70.7% for MagicoderS-CL. On HumanEval+ they are 65.9% and 66.5%, respectively. The authors interpret the ordering on the expanded suite as evidence that the CL variant can produce more robust solutions in this comparison. Here robustness refers to success under more test cases for the benchmark tasks. The experiment also demonstrates how accepting a solution on the original tests and accepting it under a stronger suite can lead to different conclusions about relative performance.

The DeepSeek comparison uses the same Python benchmark families and greedy decoding, with DeepSeek-Coder baseline results from EvalPlus. Magicoder-DS improves on the 6.7B base after OSS-Instruct. MagicoderS-DS reaches 76.8% pass@1 on original HumanEval. The paper reports that this enhanced variant beats DeepSeek-Coder-Instruct-6.7B on HumanEval, HumanEval+, MBPP, and MBPP+. It also closely matches DeepSeek-Coder-Instruct-33B across these evaluations. The comparison with the instruction-tuned 6.7B version is reported at 8× fewer fine-tuning tokens. That figure measures the amount of text used in the tuning comparison, while the outcome is measured separately through benchmark success.

#### Completion in other programming languages

MultiPL-E tests whether the improvements extend beyond Python. The paper evaluates Java, JavaScript, and C++, as well as PHP, Swift, and Rust. Each is assessed as code completion. The prompt format supplies a context for continuing code, which differs from the instructional exchange used to train Magicoder. A gain here is evidence that the outcome of tuning can survive a change in how the problem is presented.

The main MultiPL-E comparison follows the settings in the WizardCoder paper. The temperature is `0.2`, the top-p value is `0.95`, the maximum generation length is `512`, and the sample count is `50`. Temperature influences how sharply generation favors high-scoring choices. Top-p sampling limits the next-token candidates to a group whose cumulative probability reaches the chosen threshold. The length setting caps the output, while the sample count gives the evaluation multiple generated completions for estimating pass@1 under sampling. On MultiPL-E the reported metric thus concerns success on a sampled attempt, whereas the main HumanEval and MBPP comparison uses a single greedy answer.

The authors use the BigCode evaluation harness for their runs at the 7B scale and draw other results from WizardCoder. ChatGPT and GPT-4 are omitted because the harness did not support them. WizardCoder-CL-7B is also absent from this analysis because its inference was too slow in the authors’ environment. These conditions define the set of systems against which the multilingual claims are made. The comparison with ChatGPT on HumanEval+ belongs to the Python text-to-code evaluation.

Magicoder-CL improves on CodeLlama-Python-7B in each of the evaluated languages. It also beats WizardCoder-SC-15B in half of them. MagicoderS-CL then improves over Magicoder-CL across the full language set and achieves performance the authors describe as comparable to WizardCoder-CL-34B. This result matters for the CL branch in particular. Its base is specialized for Python, yet the training procedure also improves completion in other languages. The authors take the improvement under the harness’s completion format as evidence that tuning teaches something useful beyond the format of an instruction-response exchange.

#### Data-science code and insertion

DS-1000 contains 1K programming problems covering 7 Python data-science libraries. These are practical coding issues assessed with unit tests. They broaden the comparison beyond writing a standalone function to a short general prompt. An answer can depend on using operations from a library in the right combination or performing a transformation consistent with the surrounding code. DS-1000 evaluates both completion, where the answer follows a prefix, and insertion, where the missing content has to fit between a prefix and a suffix.

The main CL evaluation uses completion because the CodeLlama-Python base does not support the insertion format. For completion, the paper reports temperature `0.2`, top-p `0.5`, a maximum generation length of `1024`, and `40` samples. The authors use the preferred prompt formats for the systems they evaluate at the 7B scale and take other results from WizardCoder. The baselines include InCoder and CodeGen alongside StarCoder and Code-Cushman-001. CodeLlama-Python and WizardCoder give comparisons to the relevant base and to another instruction-tuned family.

Magicoder-CL-7B leads the baselines included in this completion experiment, among them WizardCoder-CL-7B and WizardCoder-SC-15B. MagicoderS-CL-7B extends that lead. Compared with WizardCoder-SC-15B, the paper reports an absolute gain of 8.3 percentage points in DS-1000 completion pass@1. This is a comparison of the resulting systems under the completion protocol. It shows that the training sequence can help on tasks where library use is part of the requirement, in addition to ordinary Python function exercises.

The appendix evaluates insertion with the DeepSeek branch. The setting is also called fill-in-the-middle, since the system must generate code that fits between parts of an existing context. The evaluation again uses temperature `0.2`, top-p `0.5`, a maximum generation length of `1024`, and `40` samples. The authors report that Magicoder performs well against the evaluated insertion baselines. The experiment supports the usefulness of OSS-Instruct in a setting with both left and right context, for a base capable of operating in that format. It measures a separate behavior from completion in the CL branch.

#### Competitive problems and longer responses

The paper includes an additional evaluation on 300 selected problems from the APPS test set. APPS gives the authors a competitive programming setting in which the tasks can require more elaborate algorithmic solutions. The evaluation is zero-shot, meaning the test prompt provides the problem without worked demonstrations, and uses greedy decoding. In this comparison, Magicoder-CL improves over its base and WizardCoder-CL. MagicoderS-CL-7B surpasses WizardCoder-SC-15B. MagicoderS-DS leads the evaluated systems, including the instruction-tuned DeepSeek-Coder baseline at 6.7B. These are results for the selected subset under the specified decoding procedure.

The authors complement benchmark scores with examples that make changes in behavior visible. They compare the DeepSeek base with Magicoder-DS and supply the base with a prefix intended to elicit a plausible response format. In one case, a Python function must validate its argument before checking whether an integer is a cube. The tuned output explicitly checks the argument’s type. That observation identifies a particular requirement the response addresses and leaves the correctness of the entire function to a fuller assessment.

A Scala example asks for a string transformation that preserves the ends and reverses the interior. The tuned response handles inputs of length at most 2 explicitly, returning them unchanged. The base output accesses the endpoints directly, which leaves a problem for an empty string. The authors describe Scala as outside the OSS-Instruct dataset. The example illustrates how a response can apply an edge-case pattern in a language beyond the reported training collection, although its evidential weight comes from the particular behavior shown.

Another demonstration asks for an easy Python programming exercise. The base outputs a simple function, while Magicoder-DS supplies a task, a solution, and a usage example. The task being requested is exercise design, one level removed from solving a given exercise. The paper says this request type is absent from the OSS-Instruct collection. The response illustrates how the treatment can change the interpretation of an instruction as well as the implementation selected for it.

The longer MagicoderS-DS outputs include an interactive Python game, a console board game in Java, an image application using Gradio, and a PyTorch workflow for handwritten-digit classification. They demonstrate that a single response can assemble components such as input handling, state updates, or training and evaluation loops. The paper presents them as cases rather than as a scored benchmark. They give the reader material to inspect alongside the automatic results, whose pass@1 figures refer to defined task sets and executable tests.

### What the ablations show

#### The language of the generated answers matters

The language ablation changes which OSS-Instruct examples reach CodeLlama-Python-7B. The researchers classify the roughly 75K examples by whether the generated text includes the opening marker for a Python code fence. The resulting groups contain approximately 43K examples labeled Python-only and 32K labeled non-Python. They use the generated text because the language of the seed can differ from that of the answer. The shell-to-Python example illustrates exactly why a split based on the source file would answer a different question.

The label is operational. It describes the test the authors can apply consistently across a large dataset. A Python code fence reveals that an example includes code identified as Python. It is weaker evidence that the full example uses Python exclusively. Conversely, an untagged answer could contain Python code. These possibilities matter when interpreting transfer between the groups. The comparison is between subsets created by a textual criterion, which gives a tractable estimate of the relationship between the languages emphasized during training and performance at evaluation.

The variants are trained for 2 epochs with the same setup and evaluated by greedy decoding. The Python outcome is HumanEval+ pass@1. The multilingual outcome is average pass@1 across the MultiPL-E languages in the main comparison. The greedy protocol here differs from the sampled main MultiPL-E run. It supplies common assessment conditions for the ablation, so the informative comparison is among the variants evaluated within this experiment.

Training on the Python subset improves the Python result, and the non-Python subset improves the multilingual result. The second subset also improves HumanEval+ by 10.4 percentage points over the base. That is the most direct evidence in the ablation for a benefit across the language groups. Both tuned variants begin with the same CodeLlama-Python pretraining. The gain therefore concerns what changes after additional instruction training, with Python ability already present in the starting system. It is consistent with learning general patterns of specifying and solving a task, which can be expressed in different languages.

Combining both subsets yields a stronger improvement on the Python evaluation. The average multilingual score is slightly below the variant trained on the non-Python subset alone. The authors attribute the latter observation to the approximately 57% share of Python examples in the combined training material. Under equal epoch counts the full mixture also exposes the system to more examples per pass than either subset. The comparison establishes an outcome for the authors’ particular mixture. It leaves room for the size of the subsets, their tasks, and the relative frequency of examples from each group to influence the scores.

#### A function and its comment make a demanding control

The direct-tuning control tests a plausible alternative use of the source corpus. Following the approach of CodeSearchNet, the authors mine functions accompanied by semantically related comments. They use the signature and comment as the input and the function body as the target. This creates examples with a format close to a benchmark exercise in which a brief natural-language description and a signature precede the implementation. The procedure can draw on existing repository artifacts without paying a teacher to write each example.

The authors first prioritize pairs that overlap their original seed fragments and obtain about 11K examples. They collect the remaining 64K from the broader seed document corpus, producing 75K comment–function pairs. This matches the number of OSS-Instruct examples and keeps the two collections tied to the same source pool. It also indicates how closely the examples can be aligned. Many of the paired functions come from the wider documents because only some seed spans overlap with suitable comment–function pairs.

The two training options use CodeLlama-Python-7B as the starting point, and the control is trained for 2 epochs with the same setup. Tuning on the mined pairs lowers performance relative to the base, while tuning on OSS-Instruct raises it. The result matters because the mined material has a superficially appropriate exercise format and a provenance shared with the generated material. Those characteristics are insufficient to reproduce the gain. How well the comment specifies the work done by the function becomes an important part of the comparison.

The authors suggest that intrinsic noise and inconsistency in the mined pairs may explain the drop. A comment can accurately describe the role of a function to a repository maintainer while leaving out conditions necessary for someone implementing it from scratch. The function body can also encode assumptions about other parts of the codebase. A synthetic exercise written together with its response gives the teacher a chance to make those assumptions explicit or choose a more self-contained task. The experiment changes several properties together, including the origin of the target code and the relationship between input and answer. It supports the full OSS-Instruct procedure over this direct baseline, with improved semantic correspondence as the authors’ account of why.

#### The student can beat the teacher on the benchmark

The Mixtral experiment varies the teacher. The authors use Mixtral-8x7B-Instruct-v0.1 to generate 20K OSS-Instruct examples, then train CodeLlama-Python-7B for 2 epochs. They compare the tuned system, Magicoder-CL-Mixtral-7B, with both its CodeLlama base and the teacher. Its pass@1 exceeds both comparison systems on HumanEval+ and MBPP+. The tests thus show that the method can provide a useful signal even when the teacher itself performs worse than the resulting student on the tasks used to measure the outcome.

The teacher has different information in its generation assignment from what it sees in the benchmark. To create a training example, it has a seed snippet and can choose a task suited to the idea it draws from that snippet. To answer HumanEval+ or MBPP+, it receives a problem chosen by the benchmark. It is possible for a system to write useful practice problems in the first setting while sometimes failing to solve assigned problems in the second. The student also brings its own code pretraining, so its performance reflects how the new examples work with that preparation.

The authors propose two explanations. They suggest that instruction tuning helps the pretrained student use capabilities it already has, and that the seed gives the teacher useful context for writing a problem and a consistent solution. The experiment provides evidence that a teacher’s benchmark score is an incomplete predictor of its value as a data generator. Isolating the contribution of the snippets with this teacher would require a matched comparison using the same teacher to write training examples without snippets. The observed ranking supports the combined setup and leaves the relative importance of the proposed explanations open.

#### Removing incomplete solutions did not help in this test

The appendix compares the retained OSS-Instruct collection with a version filtered for signs of unfinished implementations. In particular, the authors remove examples with partial Python code marked by `pass` or `NotImplemented`. They train CodeLlama-Python-7B for 2 epochs and compare HumanEval+ pass@1. The version that retains these examples performs slightly better. This is the evidence behind the decision to leave certain imperfect outputs in the corpus.

Even when a solution is incomplete, its description of the task, the code it already contains, or the context it provides about libraries can be useful. The markers used by the filter indicate a type of structural incompleteness. A marker can also be meaningful in a correct code example. Removing all cases that meet the criterion changes both the amount and the composition of the training material. The ablation therefore evaluates this filtering decision as a whole. It gives no separate score for how valuable an incorrect answer is relative to a verified answer for the very same problem.

There is a distinction between this result and the poor performance of mined comment–function data. In the noisy-data experiment, both versions are drawn from examples written as tasks and answers. In the direct-tuning experiment, the alternative comes from existing comments and implementations used to create training pairs. A partially implemented answer within a clearly framed task brings a different kind of imperfection from a complete function whose comment describes only part of its behavior. The paper’s controls put those circumstances into different comparisons, so a general ranking of all forms of noise would require further evidence.

#### Textual resemblance to HumanEval is an incomplete explanation

The HumanEval similarity comparison addresses the possibility that a strong coding score comes from generating practice material close in wording to the benchmark. After screening the datasets, the authors measure the closest HumanEval match for each synthetic example using the TF-IDF and cosine procedure. OSS-Instruct has the lowest average similarity among the collections considered, while Code Alpaca, which follows Self-Instruct, has the highest. The finding makes high lexical similarity an unlikely general explanation for OSS-Instruct’s benchmark gains.

The result is a dataset analysis, since computing similarity leaves the trained systems unchanged. It complements the ablations by addressing a question they cannot answer directly. It also has a narrower scope than an examination of whether training and test problems require the same concepts. An exercise with unfamiliar wording can call for the same algorithm as one in HumanEval. An exercise with shared terminology can demand different behavior. The comparison shows that the dataset need not be especially close to HumanEval under this representation to yield strong test performance.

### Limitations

#### Limits the authors identify

The paper applies the method to bases with at most 7B parameters because of resource constraints. Comparisons against bigger systems establish how the tuned variants rank on particular tasks. Estimating the effect of the same data on a larger base would require training such a base and comparing its performance before and after the intervention. The authors identify that experiment as future work. They also propose designing the distribution of seed snippets more deliberately and using a stronger teacher such as GPT-4 to generate higher-quality exercises.

The authors say that the prompting assignment can be difficult for weak teachers. A useful response must interpret enough of the fragment to choose a task, state that task independently of the source file, and provide a solution consistent with it. The Mixtral comparison verifies a second working teacher under a particular setup. The lower end of teacher capability at which these steps remain reliable is unknown. The possibility of self-training at different capacities is raised as a question for future study.

The impact statement discusses possible use where domain-specific training material is scarce or private and recognizes that stronger code generators can be misused to produce deliberately vulnerable software. The evaluation concerns coding performance under the stated benchmarks and contains no measurement of the frequency of vulnerable outputs. The paper also gives limited details about the training comparison with DeepSeek-Coder-Instruct because the relevant data and instruction-tuning procedure were undisclosed at the time. Its reported token comparison consequently has a narrower interpretation than a complete accounting of how each system was produced.

#### Limits visible in the experimental design

The main experiments support the practical value of OSS-Instruct on the examined bases and benchmarks. Its motivating claim about diversity has several kinds of evidence, including varied qualitative examples and categories based on text embeddings. These describe properties of the generated collection under the authors’ chosen representations. Estimating how thoroughly the corpus covers real programming work would require a definition of that population and a measure of its coverage. For instance, an application-style exercise can have realistic vocabulary while omitting the integration constraints that matter in an existing project.

The seed-language counts are known because the authors choose them. The generated-language proportions are available only through the classification the paper uses in its ablation. The effect of deliberately choosing certain snippet types or application domains is likewise open. The method offers a clear point of control at the input, while the mapping from input choices to measured output coverage depends on the teacher. With greedy decoding, the teacher’s preferences are still present in how it interprets a snippet and writes an answer.

The decontamination evidence has a similar scope. Removing exact matches for known benchmark text addresses direct textual overlap. The similarity analysis assesses closeness using a representation of terms and their frequencies. Semantic overlap can survive both procedures, such as when an exercise restates a familiar problem or implements a shared algorithm with different identifiers. The available results establish the number of matches removed by the stated check and the relative average resemblance under TF-IDF. They leave the total amount of related material in pretraining and teacher training unmeasured.

The controlled comparisons also leave some causal questions open. In the multilingual ablation, group membership depends on a code-fence marker and the groups differ in size. In the direct-tuning comparison, both training sets have 75K entries, but their token lengths and the nature of their inputs and outputs can differ. In the incomplete-code experiment, removing samples reduces the available data at the same time that it changes the type of material used. The controls answer whether particular datasets and filtering choices worked better in practice. Attributing each outcome to a single property would require matching the other properties more closely.

The comparison between Magicoder and MagicoderS establishes the benefit of adding the public Evol-Instruct stage in the reported sequence. There is room to ask how much of that benefit comes from the characteristics of Evol-Instruct and how much from additional continued training. Equal-budget comparisons with other follow-on datasets, and a reverse ordering of the two stages, would answer different questions about the combination. The evidence here is for using OSS-Instruct to adapt the base and then continuing with evol-codealpaca-v1.

A difference in pass@1 has meaning within a specified evaluation protocol. On HumanEval and MBPP, the greedy choice is the response being tested. MultiPL-E and DS-1000 use sampled answers in the main experiments, and the language ablation has its own greedy evaluation. The plus suites catch behaviors missed by their original tests, but their judgments still depend on finite sets of cases. They provide evidence of functional correctness on those cases. More demanding requirements such as integration with a larger codebase, maintainability, and predictable behavior after a change are outside what those scores directly measure.

Finally, the examples of complex programs show a range of output forms and also illustrate why demonstrations carry a different evidential weight. The console Othello prompt calls for the game to finish once neither player has a legal move. The displayed program checks for game termination before switching the current player, so that check does not establish that both players lack moves. The Gradio demonstration includes an introductory sentence referring to a snake game even though the code that follows is for image rotation. These are observable discrepancies within the paper’s examples. A convincing program structure or accompanying explanation can coexist with an implementation or response that misses part of the user’s request.

### What came after

#### More ways to construct coding data

[SelfCodeAlign](https://md.research.elamur.ai/free/en/papers/wei-2024-selfcodealign-self-alignment-code-generation/) takes up self-alignment for code generation. It relates to a question opened by the Mixtral experiment and raised in Magicoder’s discussion of future work. A pretrained coding system can benefit from tasks created with the help of code. Self-alignment asks how much of the work of creating and learning from that material a system can do for itself. The citation places OSS-Instruct in that line of inquiry. The stated focus of SelfCodeAlign is who supplies the alignment signal, whereas Magicoder’s defining choice is what contextual material to show a teacher.

[OpenCoder](https://md.research.elamur.ai/free/en/papers/huang-2025-opencoder-open-cookbook-top-tier/) cites Magicoder in a work framed as an open recipe for developing coding systems. Magicoder contributes an example of a recipe in which the source of instructions, the construction of responses, and the order of tuning can all be specified. OpenCoder’s stated scope covers building a strong coding system more broadly. The connection is relevant to reproducibility because a reader comparing training approaches needs to know which datasets and stages each recipe describes.

[KodCode](https://md.research.elamur.ai/free/en/papers/xu-2025-kodcode-diverse-challenging-verifiable-synthetic/) centers its synthetic coding dataset on variety, difficulty, and verifiability. This brings the standard of evidence for the generated answers into view. Magicoder investigates whether examples written from source fragments improve a student and tests a filter for some incomplete responses. A dataset framed around verifiability asks an additional question about how to determine whether a proposed answer satisfies the individual generated problem. The citation connects the common interest in producing a varied supply of exercises with a research direction that emphasizes judging the exercises and answers themselves.

[OpenCodeReasoning](https://md.research.elamur.ai/free/en/papers/ahmad-2025-opencodereasoning-advancing-data-distillation-competitive/) studies data distillation for competitive coding. Magicoder uses a synthetic problem–solution pair as the unit of instruction and includes competitive programming through its APPS evaluation. OpenCodeReasoning’s stated focus puts the competitive setting at the center of the distillation problem. It is a related question with a more specific task domain. Problems in that domain can make it especially important to examine what the training examples teach about choosing and implementing an algorithm, as well as whether the resulting program passes.

[On LLMs-Driven Synthetic Data Generation, Curation, and Evaluation](https://md.research.elamur.ai/free/en/papers/long-2024-llms-driven-synthetic-data-generation/) places the citation in a wider survey of synthetic data. Magicoder is a case where the generator receives an external artifact, the outputs undergo cleaning, and the authors judge the collection in part by what a student learns from it. Those are distinct choices in a synthetic-data pipeline. A survey with that wider remit puts the source of examples alongside decisions about which examples to keep and how to evaluate their contribution.

#### Execution, coverage, and fresh problems

[OpenCodeInterpreter](https://md.research.elamur.ai/free/en/papers/zheng-2024-opencodeinterpreter-integrating-code-generation-execution/) cites Magicoder in work that combines writing code with running and refining it. Magicoder uses execution to score generated answers during evaluation, with its main Python results based on the first greedy response. An approach that incorporates execution and refinement puts feedback into the generation process as well. This changes the question being studied from how frequently the initial answer works to how code generation can benefit from observing and responding to execution.

[LiveCodeBench](https://md.research.elamur.ai/free/en/papers/jain-2024-livecodebench-holistic-contamination-free-evaluation/) addresses benchmark contamination through fresh coding problems, as the Magicoder paper itself describes. The connection is direct. Magicoder checks generated training material for overlap with established tasks, while LiveCodeBench changes the evaluation material used to measure performance. Fresh problems help address the possibility that older benchmark content has entered any of the data contributing to a coding system. That approach to evaluation is especially relevant when a synthetic-data pipeline draws on both a large source corpus and a pretrained teacher.

[BigCodeBench](https://md.research.elamur.ai/free/en/papers/zhuo-2024-bigcodebench-benchmarking-code-generation-diverse/) broadens the evaluation question through diverse function calls and complex instructions. Its stated scope connects to Magicoder’s library-based examples and its evaluation on Python data-science problems. In each case, generating code can require more than implementing an algorithm from a short specification. A system may have to select library operations and combine them in a way that satisfies multiple requirements. The citation situates Magicoder as a point of comparison in this broader assessment of code generation.

The details of these connections differ in what the later works establish. The Magicoder paper describes LiveCodeBench’s use of fresh problems, and the other citations identify research on topics such as self-alignment, data verification, and execution-assisted writing. Citation alone leaves open whether a later project reused Magicoder’s data, weights, or prompt. The documented relationships trace the questions that persisted after OSS-Instruct: how to source diverse tasks, how to judge synthetic answers, and how to evaluate a coding system when it encounters a problem it has never seen.

## Cite

Cite as Yuxiang Wei, Zhe Wang, Jiawei Liu, Yifeng Ding and Lingming Zhang. 2024. Magicoder: Empowering Code Generation with OSS-Instruct. arXiv:2312.02120.

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

```bibtex
@misc{wei2024magicoder,
  title = {{Magicoder: Empowering Code Generation with OSS-Instruct}},
  author = {Yuxiang Wei, Zhe Wang, Jiawei Liu, Yifeng Ding and Lingming Zhang},
  year = {2024},
  doi = {10.48550/arxiv.2312.02120},
  eprint = {2312.02120},
  archivePrefix = {arXiv},
  url = {https://doi.org/10.48550/arxiv.2312.02120}
}
```

> 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)
