SWE-smith

SWE-smith breaks working code on purpose and keeps only the breaks that fail a test. That made 50,137 tasks for $1,360 and trained an agent that solves 40.2% of SWE-bench Verified.

Learn how to manufacture training tasks for software agents: break a repository, check the break with its own tests, and turn the result into data.

Tap a way of breaking code below. Each square is one candidate bug. A pink square breaks at least one test, so it becomes a task. Watch how many of 100 survive. Then we build, piece by piece, the environment, the filter, the bug makers, the issue text, the trajectories and the training.

You need a feel for what a unit test is (a small program that passes or fails) and a little Python for the code. We build the rest from zero.

Based on SWE-smith: Scaling Data for Software Engineering Agents (arXiv 2504.21798, NeurIPS 2025 Datasets and Benchmarks) by John Yang, Kilian Lieret, Carlos E. Jimenez, Alexander Wettig, Kabir Khandpur, Yanzhe Zhang, Binyuan Hui, Ofir Press, Ludwig Schmidt and Diyi Yang. Every idea is re-taught here in our own words and devices. It is a reading for CS 329Z, Data for Agents.

Keep the bugs that fail tests

Yield rates and per-candidate costs are the paper’s (Table 1; the crawl rate is 2,294 of 93,139 pull requests, Appendix C.1). Cost per kept task is our division of cost by yield. Which squares are pink is illustrative: the grid shows how many, not which.

Chapter 0

The Data Was the Bottleneck

See why open models for software work lacked practice problems, and the one idea that fixes it

Imagine you want to teach a student to fix broken programs. You need practice problems. Each one needs a broken program, a description of the fault, and a way to check the fix. You have a few hundred. The student needs tens of thousands.

That was the state of open research on software engineering agents in early 2025. An agent here is a language model wrapped in a loop. It reads a code repository, runs commands, edits files and tries to fix a reported problem. The best ones ran on closed models. The paper says open models lagged because of one gap: not enough training data, the examples a model learns from.

What one practice problem looks like

A repository is a folder of code under version control. A unit test is a small program that calls a piece of that code and passes or fails. Together they make a safety net: change the code wrongly and a test turns red.

A task instance is one practice problem. It holds a repository, a written problem (an issue, like a bug report), and the tests that decide whether a fix works. The benchmark SWE-bench uses 2,294 such instances from 12 real Python projects. Agents score by the share of instances they fix.

Why the old recipes do not scale

The paper names two recipes. The first crawls pull requests (a pull request is a proposed code change) and issues from GitHub. That gives plenty of text, but no way to run anything. Without tests you cannot tell a right fix from a wrong one. The model can only learn what code looks like.

The second recipe copies SWE-bench. It keeps only pull requests that fix a linked issue and also change tests. Few pass that filter. Then someone must build a working environment for each survivor, so the code runs at the commit where the change was made. The paper says this step needs a lot of human work and the environments fill terabytes.

The device below shows the result. Each bar is a dataset from the paper’s Table 2. Switch between task count, repository count and storage.

Compare the datasets

Pick what to compare. The teal-ringed bar is SWE-smith. Notice that no other dataset is both large and light.

All values are the paper’s Table 2. Storage is blank in the paper for datasets that ship no environments (SWE-fixer, SWE-bench-train) or do not list a size (SWE-bench-extra); those bars show none.

SWE-fixer has more tasks, but it ships no environments, so nothing in it can run. SWE-gym has real tests but only 2,400 tasks from 11 repositories and 6 terabytes of images. SWE-smith has 50,000 tasks from 128 repositories in 295 gigabytes.

The inversion

Here is the paper’s core move. SWE-bench starts with a task and then hunts for an environment that runs it. SWE-smith flips the order. It builds an environment for a repository whose tests already pass. Then it makes tasks inside that environment.

How do you make a task from working code? You break it. Change a function so that it is wrong, run the tests, and see if any turn red. A red test is proof that the change matters, and it is also the check a future fix must satisfy. The paper puts the insight in one line: running code can validate a proposed fix, and it can also find bug candidates that cause real breakage.

The rest of the pipeline follows. A model writes an issue that describes the symptom. A strong expert model tries to fix the bug, and its recorded steps, called a trajectory, become training data. A smaller model is then fine-tuned on them, which means its weights are trained further on those examples.

The headline numbers: 50,137 task instances from 128 repositories, 5,016 expert trajectories, and a 32B model called SWE-agent-LM-32B that resolves 40.2% of SWE-bench Verified in a single attempt. Creating the dataset took one author about 20 hours of human labor, and the model calls cost $1,360.

The road

  1. A task instance, and what SWE-bench costs: the parts of a task and the human funnel.
  2. Environment first: one container per repository, and the storage it saves.
  3. Break it, then check it: the filter that keeps only bugs that fail tests.
  4. Breaking code with models and with syntax trees: three bug makers and their yields.
  5. Mirroring pull requests and combining bugs: real changes undone, small bugs stacked.
  6. Writing the issue: what a model sees, and why leaking the test hurts.
  7. From tasks to trajectories to a model: rejection sampling fine-tuning.
  8. The results: Table 3 and how data size moves the score.
  9. What makes the data useful: strategies, difficulty, repositories, specialists.
  10. How the agent fails, and the limits: loops, time limits and honest caveats.
  11. Field guide: numbers, a checklist, the core loop as code.
What is the key change SWE-smith makes to how task instances are collected?

Chapter 1

A Task Instance, and What SWE-bench Costs

Open one task instance, learn its two kinds of tests, and count the human hours the old method needs

A user of a small web library writes a bug report. “When I pass a path object, the function crashes.” A maintainer reads it, finds the fault, and fixes it. She also adds a test, so the bug cannot come back. Later, someone saves that whole episode as a practice problem for an AI. That is a task instance.

The parts

A SWE-smith task instance has the same shape as one from SWE-bench, with a few fields removed. Here is what it carries, as the paper’s Appendix A.1 lists it.

# field names from Appendix A.1; the values are illustrative
task = {
  "repo":              "pallets/flask",               # which project
  "instance_id":       "flask.lm_modify.a1b2c3",      # repo.bugtype.hash
  "base_commit":       "bc09840-with-bug",            # the code WITH the bug applied
  "patch":             "<diff that causes the bug>",   # undoing it is the solution
  "problem_statement": "Passing a Path crashes ...",  # the issue text the agent reads
  "FAIL_TO_PASS":      ["tests/test_helpers.py::test_path"],
  "PASS_TO_PASS":      ["tests/test_app.py::test_ok", ...],
}

Two fields need care. FAIL_TO_PASS (F2P) lists the tests that fail on the broken code and should pass after a correct fix. They are the proof the bug is real. PASS_TO_PASS (P2P) lists every other test. They pass before and must still pass after. They catch a fix that breaks something else.

An agent’s attempt counts as resolved when every test in both lists passes. One failure is enough to reject it.

resolved
One if the attempt counts as a fix, zero if not.
∧
“And”: every test must pass.
j ∈ F2P ∪ P2P
All the tests in the task: the ones that were broken, plus the ones that must stay green.
testj
One check. It runs the code and returns pass or fail.
repo + fix
The repository after the agent’s edit. Only this final state is tested.

Notice what is missing. SWE-bench keeps a hidden test_patch, so the agent never sees the tests that grade it. SWE-smith has no such field. Its failing tests already live in the repository, visible to the agent. This is fine for training, and it is why the paper says the tasks are not meant for evaluation.

How SWE-bench makes one

SWE-bench collection starts from real pull requests. Keep a pull request only if it edits code, links an issue, and edits tests. Then check out the repository as it was just before the change. Then work out how to install that old version, which can differ from commit to commit. Then run the tests before and after to confirm the F2P list.

The paper measured this on one project, pallets/flask. SWE-bench started from 2,434 pull requests. Only 107 passed the filter, and only 11 became task instances once an environment could be built. That is 0.45%. The authors estimate those 11 took about 38 hours of human work.

SWE-smith ran on the same project for comparison. The function-rewrite strategy (LM Rewrite, Chapter 4) produced 402 candidates, and 267 broke a test. Setting up the environment took 10 minutes. Making the bugs took 23 minutes and $2.47. Checking them took 14 minutes. Try the two methods side by side.

Collect tasks from one repository

Pick a method, then set how many tasks you want. The bars show the funnel on a log scale. The read-out scales the paper’s per-task time and cost.

100

Funnel counts, minutes and dollars are the paper’s flask case study (Appendix C.2). Scaling them linearly to your slider value is our illustration; real costs vary by repository.

Why is the install step so costly? Software changes over time. A pull request from 2022 needs the libraries of 2022. A later one may need different versions. So SWE-bench needs install instructions for many past versions of each project, and a person must work them out. The paper calls this the most costly step of SWE-bench collection.

SWE-smith avoids it by working only on the latest commit. It needs one set of install instructions for each repository. Every bug it makes is a small edit to that one version, so the environment never has to travel back in time.

The time per task is simple division. For SWE-bench, 38 hours is 2,280 minutes, and 2,280 divided by 11 tasks is 207.27 minutes each. For SWE-smith, the three steps total 47 minutes, and 47 divided by 267 is 0.176 minutes, about 10.6 seconds.

The symptom, the measure, the fix. The symptom: training data is scarce. The measure: 11 usable tasks from 2,434 pull requests, 207 minutes of human time each. The fix: stop hunting for tasks that exist and make the ones you need.
An agent edits a repository to fix a task. Which tests must pass for the attempt to count as resolved?

Chapter 2

Environment First

Build one working lab for each repository, and see why sharing it saves a factor of about 450 in storage

A chemistry teacher wants to run 400 experiments. She can build a new lab for each experiment, with its own benches and gas taps. Or she can build one good lab and run all 400 inside it. SWE-smith takes the second path. Its first step is the lab, not the experiment.

Choosing the repositories

Which projects get a lab? The authors start with the 5,000 most downloaded packages on PyPI, the public index of Python packages, as of 18 November 2024. They sort by GitHub stars and drop any package with fewer than 1,000 stars. They also drop all 12 repositories that SWE-bench uses for testing, so no exam material leaks into training. They check each license allows this use.

Why Python only? A Python package follows habits. It installs from a standard file, and it usually tests with pytest, a common Python test runner. These habits let one install recipe work for many projects. The paper lists other languages as future work.

Letting an agent install it

Installing a project is itself a software job, so the authors give it to an agent. They run SWE-agent on the repository’s latest commit for at most 100 steps. The prompt tells it to install the code and run the test suite. A person then reads the agent’s record and checks the install steps. One rule decides if a repository stays: more than 80% of the existing tests must pass. On average, one install run took 17 steps and $0.72.

That rule matters. The tests are the safety net that will catch each synthetic bug. If most tests already fail, a new failure tells you nothing. Only a repository that is mostly green can show that a change broke something.

Once a repository passes, the authors write a Dockerfile, a short recipe that rebuilds the same machine from scratch. A Docker image is the built result: operating system, libraries and code, frozen. A container is a running copy of that image, thrown away after use.

The human work is small. Reading the agent’s trajectory to extract the install steps takes about 7 minutes per repository. Writing the parser that reads test output takes about 1 minute, and parsers are reused across repositories that use pytest. Building the whole dataset took one author about 20 hours.

One image, many tasks

Here is the storage idea. SWE-bench builds a Docker image for every task instance, because each one sits at a different old commit. SWE-smith makes every bug at the same commit, so all bugs from a repository share one image. Apply a bug as a patch, run, then undo it.

Count the cost. Let N be the number of tasks and s the size of one image.

Sper-task
Disk space if every task has its own image, as in SWE-bench.
Sshared
Disk space if tasks from one repository share an image, as in SWE-smith.
N
How many tasks you want.
k
Tasks per repository. The paper averages 381.
s
Size of one image. SWE-gym averages 2.6 GB. SWE-smith’s 125 images average about 2.3 GB (290.54 GB in total).

Take N = 50,000. The per-task way needs 50,000 times 2.6 GB, which is 130,000 GB or 130 TB. The shared way is capped by the number of repositories, so it stores 125 images, 290.54 GB. The ratio is about 450. The paper states a range of 50 to 150 TB for the per-task way, and a 500 times difference. Move the slider to see where each line goes.

Share the lab

Drag the number of tasks. The yellow bar is one image per task. The warm bar is one image per repository. Bars use a log scale.

12,000

Illustrative model built from the paper’s numbers: 2.6 GB per image (SWE-gym average), 381 tasks per repository (Section 2.2), at most 125 shared images of about 2.32 GB (Appendix C.1). The paper’s own estimate for 50k tasks the old way is 50 to 150 TB.

Small N shows the other side. With 500 tasks you need only 2 repositories, so the shared way stores a few gigabytes. The gap grows with every task you add, because the shared way stops growing once all repositories are built.

def build_environment(repo):
    agent_log = swe_agent(repo.latest_commit,
                          task="install it and run the tests",
                          max_steps=100)
    spec = parse_install_steps(agent_log)          # a person checks this, about 7 min
    if pass_rate(run_tests(repo, spec)) <= 0.80:   # the tests must mostly pass
        return None
    return docker_build(repo, spec)                # one image, reused for every bug
Why can SWE-smith use one Docker image for hundreds of tasks from a repository?

Chapter 3

Break It, Then Check It

Learn the one filter that turns random edits into real tasks, and measure how many bugs it keeps

A fire marshal wants to know if a building’s smoke alarms work. She lights a small fire and listens. If an alarm rings, the alarm is real. If nothing rings, she learns something else: that corner of the building has no alarm.

SWE-smith tests a repository the same way. Its tests are the alarms. A synthetic bug is the small fire. If a test goes red, the bug is real and visible. If every test stays green, no alarm covers that code, and the candidate is useless as a task.

The filter, step by step

Every bug maker in the next two chapters hands this chapter the same thing: a candidate, written as a diff. A diff is a list of the lines a change removes and adds. The filter then runs the same four steps on every candidate.

  1. Apply the diff to the clean repository inside its Docker container.
  2. Run the whole test suite, with a clock running.
  3. If more than two minutes pass, discard the candidate.
  4. If at least one test that used to pass now fails, keep the candidate. Record the failing tests as FAIL_TO_PASS and the rest as PASS_TO_PASS.

We can write the keep rule as one line.

keep(c)
True if candidate c becomes a task, false if it is thrown away.
∃ j ∈ P : …
“There is some test in P, the set of tests that passed on the clean repository, that now fails.” One is enough.
time(c) ≤ 120 s
Running the suite with the bug must finish within two minutes. This caps the cost of every later check.

Why a time limit? A bug can send a loop into endless repetition, so the suite never ends. Every later run, by the expert and by anyone who trains on the task, would pay that delay. Dropping slow candidates is cheap protection.

Try the filter on eight invented candidates. Each bar is how long the test suite ran. Slide the limit and watch which candidates stay.

Run the filter

Pink bars broke at least one test and finished in time: kept. Grey bars broke nothing. Yellow bars ran past the limit. Drag the time limit.

120 s

Illustrative: the eight candidates, their failing-test counts and their run times are invented. The rule (at least one passing test must fail; at most two minutes) is the paper’s (Section 2.1).

Take the third bar, a dropped loop. It breaks 12 tests, but its run takes 150 seconds. At the paper’s 120-second limit it is discarded. Raise the limit to 160 and it joins the kept set. The second and fifth bars break nothing at any limit, so no limit rescues them.

How many survive?

The yield of a bug maker is the share of its candidates that survive the filter. In the paper, yield is kept divided by tried. LM Modify tried 31,950 candidates and kept 17,887, a yield of 55.98%. Across all strategies in Table 1 the average is 50.1%.

Yield sets the real price of a task. A bug maker that costs 5 cents per candidate and keeps one in three really costs about 15 cents per task. The hero at the top showed this division for each strategy.

Why most tests are never broken

Run the filter long enough and a pattern appears. Take flask again. The SWE-bench version has 207 tests across its 11 instances, and the instances together break only 15 of them. That is a bug coverage of 7.25%. The SWE-smith version has 474 tests across 267 instances, and together they break 422 of them: 89.03%.

The paper explains the gap. Most tests are written alongside working code to keep correct behavior correct. Well-run projects rarely merge a change that turns them red. So real history almost never breaks them. Synthetic bugs can break any of them on demand.

For training this matters. A model that learns only from real regressions sees a narrow slice of the test suite. Synthetic bugs spread the lesson across almost all of it.

def validate(repo, candidate_diff, limit_s=120):
    apply_patch(repo, candidate_diff)
    result = run_tests(repo, timeout=limit_s)       # {test_name: "pass" | "fail"}
    if result.timed_out:
        return None                                  # too slow, discard
    f2p = [t for t in result.tests if result[t] == "fail" and clean_result[t] == "pass"]
    if not f2p:
        return None                                  # no alarm rang, discard
    p2p = [t for t in result.tests if t not in f2p]  # everything else
    return {"FAIL_TO_PASS": f2p, "PASS_TO_PASS": p2p}
The symptom, the measure, the fix. The symptom: most random edits are useless. The measure: yield, between 34% and 97% depending on the maker. The fix: let the tests decide, and keep only the edits they notice.
A candidate bug is applied and every test still passes. What does SWE-smith do?

Chapter 4

Breaking Code with Models and Syntax Trees

Meet three bug makers, one that asks a model, one that asks a model to start over, and one that needs no model at all

You have a working function and a safety net of tests. How do you break the function in a way that matters? The paper tries several answers. This chapter covers the three that work on one function at a time. The next covers the two that work on more.

First, how all of them start. The pipeline lists every function and class in the repository. Each one is a candidate site. A bug maker takes one site and returns a diff. The filter from Chapter 3 judges the diff.

LM Modify: ask a model to plant a bug

The simplest idea is to ask. The model gets a function and a role: a developer doing “chaos monkey testing.” Chaos monkey is the practice of breaking things on purpose to see what notices. The prompt asks for a logical bug that will break existing unit tests.

To get variety, the prompt lists nine kinds of bug, such as off-by-one errors, flipped conditions, wrong default values and swallowed exceptions. Each call shows only three of the nine, picked at random. The rules say the bug must not cause a syntax error, must not change the function signature, and must carry no comment that gives it away.

This works well by yield: 17,887 of 31,950 candidates break a test, 55.98%, at 0.38 cents each. But there is a catch. Spot checks showed that most of these bugs are simple variable mix-ups, like swapping a = a; b = b into a = b; b = a. An open request does not give a wide range of mistakes. The difficulty model rated LM Modify tasks the easiest of all strategies.

LM Rewrite: ask a model to start over

The second idea gives the model less. It sees only the function’s header (its name and arguments) and its docstring (the short description). It must write the body again. Nobody asks it for a bug. Its own mistakes become the bugs.

This yields fewer tasks, 35.04%, and costs more, 3.93 cents per candidate, but the tasks are harder. A rewrite differs from the original in many small ways at once. Median edit size is 24 lines, against 3 for LM Modify (Table 1).

Procedural modification: edit the tree

The third idea needs no model. Python can read its own code into a tree. An abstract syntax tree (AST) shows the structure of a program: a function contains an if, the if contains a comparison, the comparison has a left side, an operator and a right side. A procedural modification is a small program that takes one tree and returns an edited tree. It may remove a loop, invert an if, change an operator or shuffle statements.

The paper uses 13 such transformations. Each picks a random matching spot, edits it, and writes the tree back as code. It costs nothing in model calls. The yield depends on the edit: inverting an if breaks a test 49.44% of the time, but shuffling the functions in a class breaks one only 1.88% of the time.

Now work through one. The function below gives a bulk discount. Four tests describe it. Pick an edit and see which tests notice.

Mutate the tree

Choose an edit. The code box shows the edited function. The test list shows which of the four tests now fail, and whether the filter keeps the bug.

Toy example written for this lesson, run live in your browser. The function, the four tests and the six edits are illustrative. The edit kinds are among the paper’s procedural transformations (Table 8, Table 10).

Look at the last edit. Renaming a variable changes the text but not the behavior, so no test fails and the filter discards it. Inverting the if breaks three of four tests. Changing >= to > breaks only the boundary test, with qty = 10. That one-test failure is a sharp, precise task. It teaches the agent to read an edge case.

import ast

class InvertIf(ast.NodeTransformer):
    def visit_If(self, node):
        self.generic_visit(node)                 # walk the children first
        node.test = ast.UnaryOp(op=ast.Not(), operand=node.test)   # if x  becomes  if not x
        return node

tree = ast.parse(source_of_function)
bugged = ast.unparse(ast.fix_missing_locations(InvertIf().visit(tree)))
The symptom, the measure, the fix. The symptom: asking a model for bugs gives a narrow kind of bug. The measure: LM Modify tasks rate easiest, and training on them scores lowest (Chapter 9). The fix: use several makers with different habits, and mix their output.
Which bug maker needs no language model call at all?

Chapter 5

Mirroring Pull Requests and Combining Bugs

Undo a real change to get a realistic bug, then stack small bugs to get a bigger one

A garage keeps a record of every repair it ever made. Today a customer brings in a car that runs well. The mechanic reads an old repair order: “replaced a worn belt.” He puts the old worn belt back. Now he has a car with a real, known fault, and he knows exactly what fixes it.

That is PR mirroring. The paper also calls it inverting pull requests. Each merged pull request is a record of a repair. Undo it in today’s code and the old fault returns.

Why a model must undo the change

The obvious tool is git apply --reverse, which runs a patch backwards. The authors tried it first. For the large majority of patches it fails. They read 100 pull request patches from the sqlfluff project and found two facts. Most of the changes still exist in the code today, so undoing them is possible. But the exact lines have moved because of later edits, so a mechanical reverse cannot find them.

So a language model does the undo. It receives the diff and the current source of each file the diff touched. It returns a full rewrite of the file with the diff’s changes reverted. The paper found reasoning models, such as o3-mini, especially good at this. The pipeline gathers the rewrites into one patch and sends it to the filter.

Two design choices matter. First, the model works on the repository’s latest commit, not on the commit that existed when the pull request landed. The install recipe from Chapter 2 only fits the latest code, so going back in time would break it. Second, the pipeline skips pull requests that edit more than 8 files. No SWE-bench instance that edits more than 6 files had ever been solved, so such tasks would waste the expert’s time.

Does the mirror match the original?

The authors checked with a test. They took 100 SWE-bench task instances from django and tried to rebuild each from its pull request. They recovered 92 of 100. Of those 92, 84 broke exactly the same F2P tests as the original. The other 8 broke a subset, because some tests were removed from the project over time.

PR mirroring also relaxes SWE-bench’s rules. A pull request no longer needs a linked issue, because a model can write the issue text (Chapter 6). It no longer needs to edit a test file, because the filter finds the failing tests itself. Of 2,345 mirrored tasks in SWE-smith, only 708 (30.19%) had a real issue to use.

The price is the cost: 5.53 cents per candidate, because the model rewrites whole files. The yield is 33.8%. And there is one weakness. The rest of the repository is newer than the pull request, so line numbers in a real issue may be a little off.

Combining bugs

Chapter 4’s bug makers edit one function. Real fixes often touch several places. SWE-smith builds bigger tasks by combining bugs. It takes bugs that already passed the filter, picks several from the same file or the same module, and applies their patches one after another. If all of them apply cleanly, the pipeline saves the result as a single patch.

The yield is 96.9%, the highest of any strategy. That makes sense: each part was already known to break something. A combined task also fails more tests, with a median of 15, against 3 to 7 for the other strategies, and its median edit is 11 lines. The difficulty model scored it highest, 5.72.

Roughly, the failing tests of a combined bug are the union of its parts’ failing tests.

F2P(a + b)
Tests that fail when both bug a and bug b are applied.
F2P(a)
Tests that fail with bug a alone.
F2P(b)
Tests that fail with bug b alone. A test in both sets is counted once.

Why only “about”? One bug can hide another. The real pipeline does not guess: it runs the suite again on the combined patch. The device below uses the plain union, so treat it as a toy.

Stack the bugs

Each dot is one of twelve tests in a file. Switch bugs on and off. Pink dots fail. Notice that two bugs that share a test fail fewer tests than the sum.

Illustrative: the three bugs, their failing tests and the twelve-test file are invented. The paper’s combined tasks have a median of 15 failing tests and 11 edited lines (Table 1). Real combination re-runs the suite instead of assuming a union.

Turn on A and B. A fails tests 1, 2 and 3. B fails tests 3 and 4. Test 3 is in both, so together they fail 4 tests, not 5. Add C, which fails 6 to 9, and the file shows 8 failing tests. The task now asks the agent to repair three separate faults.

def mirror(pr_diff, repo):
    files = files_touched(pr_diff)
    if len(files) > 8: return None                       # too big for an expert to solve
    rewrites = {f: llm_revert(read(repo, f), pr_diff) for f in files}   # whole-file rewrite
    return make_diff(repo, rewrites)                     # then: the Chapter 3 filter

def combine(valid_bugs, same_file):
    patch = repo_clean
    for bug in sample(valid_bugs, k=num_bugs):      # bugs from one file or module
        patch = apply(patch, bug.diff) or fail()         # all must apply cleanly
    return patch                                         # then: re-run the filter
The symptom, the measure, the fix. The symptom: reversing a patch with git fails. The measure: the large majority of 100 sqlfluff patches would not reverse. The fix: let a model rewrite each file with the change undone.
Why does SWE-smith use a language model to undo a pull request instead of running git in reverse?

Chapter 6

Writing the Issue

See what text the agent reads, compare four ways to write it, and learn why showing the failing test backfires

You run a small project. Two messages arrive on the same morning. One says: “broken.” The other says: “When I pass a path object to load() it crashes with a TypeError. Here are five lines that show it. I expected a string back.” Which would you rather fix?

The agent in SWE-smith faces the same choice. It does not see the patch or the tests. It sees only a problem statement, text written like a GitHub issue. The paper notes that this text can change how hard and how solvable a task is. A clear “expected versus observed” or a few lines of reproduction code help the agent find the bug and check its fix.

Synthetic bugs have no reporter. So SWE-smith must write the text. The authors compared four ways.

Four ways to write it

  1. Fixed templates. A set of fill-in-the-blank messages. They name the bug type, files, functions or failing tests, chosen at random. The one that gives all four kinds of information gets the highest chance (0.15), so more tasks are well specified.
  2. Failing test code. Show the source of one failing test and its log. If a task has several failing tests, show only one.
  3. Model-written (LM). The model gets a real SWE-bench Verified issue as a style example, the bug patch, the list of failing tests, one failing test’s source, and the test output. It writes a new issue in that style, with reproduction code. Its rules: do not explain the fix, do not mention pytest or the test name, and copy the example’s level of polish, even when that means being messy.
  4. Original text. Use the real issue from the pull request. This works only for PR Mirror tasks that had one: 708 of 2,345.

The final recipe is the model-written one. It costs 2.54 cents per issue on average, and $200 for 10,000 bugs.

The experiment

To compare them, the authors sampled 600 PR Mirror tasks. For each, they made the issue four ways, ran the expert agent, and trained a 7B student on the successful trajectories. To be fair they capped each run at the smallest count, 259 trajectories. They scored the student on SWE-bench Verified. Look at the four options below.

Pick the issue style

Choose a style. The box shows an example of the text the agent would read. The bars show the student’s score after training on that style.

The four texts in the box are invented examples written for this lesson. The scores are the paper’s Table 5 (7B student, 600 PR Mirror tasks, SWE-bench Verified); the differences between the last three sit inside the error bars.

The last three styles score within noise of each other: 7.3, 7.7 and 7.8 percent. The model-written issues match the real ones. Fixed templates score lowest, 6.4 percent, and give the fewest successful trajectories, 259. They also give a narrow set of behaviors: the expert used 379 unique actions on template issues and 550 on model-written ones, which is 31 percent fewer.

The surprise: showing the test hurts

The failing-test style gives the most successful trajectories, 390. Seeing the test makes the bug easy to find. But the student trained this way scores only 7.3 percent, below the model-written text. The paper traces the cause to one habit.

A good agent first writes a short script that reproduces the bug. That habit lets it confirm the failure and later confirm the fix. If the issue already hands over the test, the expert skips the script, and the student learns to skip it too. On the 500 Verified tasks, the model trained on model-written issues tried to reproduce the bug in 379 runs. The test-trained model did so in 127.

drop
The share of reproduction attempts lost by training on test-style issues.
127
Runs out of 500 in which the test-trained student tried to reproduce the bug.
379
The same count for the student trained on model-written issues.

So 127 divided by 379 is 0.335, and the drop is 66.5 percent, which the paper reports as 66. The lesson is general. Data that makes the training task easier can teach a worse habit. Leaking the answer to the expert leaks it out of the student’s skills.

def make_issue(patch, f2p_tests, test_log, demo_issue):
    prompt = f"""Write a realistic GitHub issue. Mimic the style of the demo.
    Do NOT explain the fix. Do NOT mention pytest or the test name.
    Include a short script that reproduces the problem.
    <demo>{demo_issue}</demo> <patch>{patch}</patch>
    <test source>{one_of(f2p_tests).source}</test source> <output>{test_log}</output>"""
    return llm(prompt)        # what the agent will read; it never sees the patch
The symptom, the measure, the fix. The symptom: a student that never reproduces bugs. The measure: 127 reproduction runs against 379. The fix: write issues that describe the symptom, not the test.
Why did training on issues that included the failing test code give a weaker student?

Chapter 7

From Tasks to Trajectories to a Model

Watch an expert attempt the tasks, keep the successful attempts, and train a smaller model on them

A young carpenter learns from a master. She watches the master fix many broken doors. But she only studies the jobs that ended with a door that closed. Jobs that went wrong teach her the wrong moves, so she skips them.

SWE-smith trains a model the same way. A strong expert model attempts the tasks. The tests grade each attempt. Only the passing attempts become training examples for a smaller student model. The paper calls this rejection sampling fine-tuning: sample many attempts, reject the failures, fine-tune on the rest.

What the expert runs inside

The expert works through SWE-agent, an agent system that gives a model an agent computer interface (ACI): a small, well-designed set of tools. There are three. bash runs a shell command. str_replace_editor views, creates and edits files. submit ends the task.

The agent works in turns. Each turn the model writes a thought and an action, in the style called ReAct. The tool runs the action and returns an observation. The loop repeats. The whole record is a trajectory. The expert is mostly Claude 3.7 Sonnet (a minority of trajectories came from Claude 3.5 Sonnet and GPT-4o), with a limit of 75 steps and $2.00 per run. The student base models are Qwen 2.5 Coder Instruct, 7B and 32B.

Why limit the steps and the money? A stuck agent can loop for ever. The limits stop a run when it reaches 75 steps, spends $2.00, or fills the expert’s context window. The paper says the great majority of automatic stops come from the 75-step limit. A stopped run is a failed run, so it never enters the training set.

<thought>The issue says load() fails on Path. Let me find where load is defined.</thought>
<action>bash: grep -rn "def load" src/</action>
OBSERVATION: src/loader.py:41:def load(path):

<thought>I will write a script that reproduces the crash first.</thought>
<action>str_replace_editor create reproduce.py ...</action>
OBSERVATION: File created.
...                                   # about 58 messages per kept trajectory, on average

That sample is our own sketch of the format, not a real trajectory. One detail in the paper is real and important. The expert models call tools through function calling, a structured format. The student is asked to write its thought and action inside XML tags instead. So the pipeline must convert each expert trajectory into the XML style before training. The paper says that fine-tuning on the function-calling format directly does not work.

From 50,137 tasks to 5,016 examples

The expert does not attempt all 50,137 tasks. It attempts 8,686 of them, 17.3 percent. The authors first ran the expert for their ablations, which gave 5,105 trajectories. Then, because PR Mirror and LM Rewrite tasks gave the most useful data (Chapter 9), they ran the expert on every task of those two kinds. The pool grew to 6,457 successful trajectories out of 17,906 attempts: a 36 percent success rate.

One more step. Some tasks are easy and the expert solves them again and again. Repeated easy solutions crowd out hard ones, and an earlier study found they hurt the student. So the paper caps each task at 3 trajectories. That leaves 5,016 training examples. They span 123 repositories, with at least 10 examples from 91 of them. A typical trajectory is 58 messages long, which is 29 actions.

D
The training set: a list of full trajectories, ready to be trained on.
τi
One expert attempt at one task: every thought, action and observation, in order.
resolved(τi)
True if the F2P and P2P tests all pass on the attempt’s final code. This is the rejection step.
≤ 3
The cap per task. It keeps easy tasks from dominating.

Step through the funnel.

Build the training set

Press Step to run the next stage. Each bar uses a square-root scale so the small stages stay visible.

Counts are from Sections 3 and 4 and Appendix F.3: 50,137 tasks; 8,686 attempted (17.3%); 17,906 attempts; 6,457 resolved (36%); 5,016 after the cap of 3 per task.

The training itself

Training is ordinary next-token learning. The student reads each trajectory and learns to predict the expert’s next thought and action. The paper uses full-parameter fine-tuning with the torchtune library, learning rate 5e-5, at most 3 epochs, and a context length of 32,768 tokens, on 2 to 8 H100 GPUs. At test time the student runs with temperature 0 and sees only its 5 most recent tool outputs, to save context.

Does rejecting failures matter? The paper tested it. It trained the 32B model on random trajectories with no filtering, at several sizes, and compared with the filtered sets. Training on only the resolved trajectories was better.

In rejection sampling fine-tuning, which expert attempts become training data?

Chapter 8

The Results

Read Table 3 line by line and see what 5,016 trajectories bought on SWE-bench

After a season of practice, a student sits the exam. The exam here is SWE-bench. The student is SWE-agent-LM-32B, which is Qwen 2.5 Coder Instruct 32B fine-tuned on 5,016 SWE-smith trajectories. How did it do?

What the number means

The paper reports Pass@1, the share of tasks an agent resolves in a single attempt, with no voting and no second tries. It tests on two SWE-bench subsets. Lite has 300 instances chosen to be easier and cheaper to run. Verified has 500 instances that people checked for clear problem statements and fair tests.

Pass@1
The score in Table 3, written as a percent.
1 / |T|
One over the number of tasks. For Verified, |T| is 500.
t ∈ T
Each task in the test set, taken once.
resolvedt
One if the first attempt on task t passes all its tests, zero if not. The paper ran the 32B model six times and averaged, so this is a mean over runs.

A worked case: 40.2 percent of 500 tasks is 201 tasks resolved on average. Each task counts the same, so an easy task and a hard one move the score equally.

Table 3, in one picture

The device plots the paper’s Table 3 for open-weight models, plus Claude 3.7 Sonnet, the expert that made the trajectories. Switch between Verified and Lite.

Read Table 3

Pick a benchmark. The warm bar is SWE-agent-LM-32B. Notice that it sits above models trained on far more data, and well below its expert.

All values are the paper’s Table 3 (Pass@1; each model with the agent system the table lists). A dash in the paper’s Lite column means the original source did not report it, shown here as none. Models with verifiers or many attempts are excluded by the paper.

Read the table with three questions.

How does the student compare with other open models? On Verified it scores 40.2, ahead of Qwen3-235B-A22B (34.4), R2E-Gym-32B (34.4) and SWE-fixer-72B (32.8). SWE-fixer used 110,000 training instances. The 32B model used about 5,000. The paper says this is a new best among open-weight models. The 7B version, trained on 2,000 trajectories, reaches 15.2.

How does it compare with closed models? It is not at the top. Claude 3.7 Sonnet with the same SWE-agent scores 58.2 on Verified. A 32B student reaches about 69 percent of its teacher (40.2 divided by 58.2). It beats GPT-4o with SWE-agent (23.0) and with Agentless (38.8). Only Llama3-SWE-RL-70B, trained on 11 million instances, is just ahead at 41.0.

How much did the data size matter? Figure 1 shows the score rising as trajectories grow from 100 to 5,000. At about 500 trajectories, a fair comparison with earlier work, the 32B model reached 28.2 on Verified. The paper reports a gain of 8.2% over SWE-gym and 0.7% over R2E-Gym at that size. The score then climbs from 28.2 to 40.2 as the data grows tenfold, so more data drives much of the gain.

The system around the model matters

Table 3 hides a trap. A score belongs to a pair: a model and the agent system around it. Claude 3.5 Sonnet scores 33.6 on Verified inside SWE-agent, 46.2 inside AutoCodeRover, 50.8 inside Agentless and 53.0 inside OpenHands. The model did not change. The loop, the tools and the prompts did.

So the authors fix the system. They use SWE-agent for both the expert and the student, because SWE-agent with Claude 3.7 Sonnet was the top open-source solution on SWE-bench at the time. This also means the student learned to work with SWE-agent’s three tools. Its 40.2 is a score for that pairing. A different scaffold could shift the number up or down, and the paper does not test one.

One attempt is a floor, not a ceiling

All Table 3 numbers are single attempts. The paper also ran the 32B model six times and measured Pass@k, the share of tasks solved by at least one of k tries. It rises from 40.2 at k = 1 to 54.8 at k = 6. The authors did not train a verifier to pick the best attempt, but they release their trajectories so others can. The model is compatible with that approach.

How does SWE-agent-LM-32B (40.2 on Verified) compare with SWE-fixer-72B (32.8)?

Chapter 9

What Makes the Data Useful

Run the ablations: which bug makers, which difficulty, how many repositories, and when a specialist beats a generalist

You bought a large crate of practice problems. Some are great. Some are dull. Before you train on all of them, you want to know which kind to use. The paper answers with a set of small, careful experiments. Each one trains a 7B student on a chosen slice and scores it on SWE-bench Verified.

Which bug maker?

The authors sampled 1,000 tasks from each strategy, made model-written issues, and ran the expert on them. To compare fairly, they trained each student on the same number of trajectories, 507, the fewest that any strategy produced.

PR Mirror leads with 9.2 percent. That is expected, because real pull requests look most like SWE-bench. The surprise is how close LM Rewrite (8.8) and Procedural (8.6) come. LM Modify trails at 5.7, a steep fall. Chapter 4 explained why: most LM Modify bugs are the same easy kind of variable mix-up, so the expert’s trajectories on them are alike and shallow.

Which difficulty?

To measure difficulty at scale, the authors trained a model. They took 1,699 SWE-bench instances that people had rated, while building SWE-bench Verified, by how long a fix would take: under 15 minutes (easy), 15 minutes to an hour (medium), and over an hour (hard). They fine-tuned Qwen 2.5 32B to predict the rating from the issue and the fix. It reaches 75.3 percent accuracy on held-out tasks, and every wrong guess is off by one level.

A dataset gets one number, its difficulty score. Each easy task counts as 1, medium as 5 and hard as 9. The score is the average.

score
The dataset’s average difficulty, from 1 (all easy) to 9 (all hard).
neasy
Tasks the model rates easy. The weights 1, 5, 9 stand for the three labels.
nmed
Tasks rated medium.
nhard
Tasks rated hard.
N
All tasks in the sample. It equals the three counts added up.

Work through PR Mirror. Of 1,000 sampled tasks, 206 are easy, 619 medium and 175 hard. The sum is 206 plus 3,095 plus 1,575, which is 4,876. Divide by 1,000 and the score is 4.876. SWE-bench itself scores 5.01.

Dataset (1,000 tasks each for SWE-smith)EasyMediumHardScore
SWE-smith LM Modify441542173.30
SWE-smith Procedural374603233.60
SWE-smith PR Mirror2066191754.88
SWE-smith LM Rewrite687961365.27
SWE-smith Combine527162325.72
SWE-bench (2,294)4381,4084465.01
SWE-gym (2,438)2881,4566645.62

Now the useful finding. Harder tasks are harder to solve: the expert resolves 58.6 percent of easy, 41.0 of medium and 17.0 of hard. But harder tasks do not teach better. The authors built four 500-trajectory training sets with difficulty scores 2, 4, 6 and 8, and the students scored 12.4, 10.8, 13.6 and 12.2. There is no clear trend. Difficulty predicts whether the expert succeeds. It does not predict whether the trajectory teaches.

Which repositories, and how many?

Another run trained on 700 trajectories from procedural bugs, drawn from 4, 25, 50 or 100 repositories. More repositories gave better scores, roughly in proportion to the logarithm of the count. Breadth helps even when the number of examples stays fixed.

The last test went the other way. Make a specialist. The authors made 1,276 procedural tasks from one project, SymPy, and trained on 700 trajectories. They scored on 22 SymPy tasks from SWE-bench Verified that were created after 1 January 2022. A 7B model trained on SymPy only scores 21.2, against 13.6 for the 7B model trained on 100 repositories. A further SymPy stage lifts the 32B model from 33.3 to 42.4. The paper says general performance dropped only slightly.

Run the ablations

Pick an experiment. Each bar is a student trained on that slice of data and scored on SWE-bench Verified (or on SymPy tasks for the last one).

Values are the paper’s Table 4 (bug makers), Section 4.1 text (difficulty and specialists) and the labels of Figure 5 (repositories, read from the figure). All use SWE-agent; the last view scores 22 SymPy tasks, so one task is worth 4.5 points.

Put the four findings together. A good mix has several bug makers, a spread of repositories, and issue text that does not leak the test. Difficulty is a weak guide. And if you care about one project, a small specialist set can pay off a lot.

What did the paper find about task difficulty and training value?

Chapter 10

How the Agent Fails, and the Limits

Watch what the trained student does when it gets stuck, and list what the paper does not claim

An apprentice is good, quick, and sometimes strange. Halfway through a job she opens the same cabinet twelve times, reading a different shelf each time, until the foreman calls time. She was not wrong. She was stuck. The paper studies SWE-agent-LM-32B on SWE-bench Verified to find out how it behaves, next to its expert.

The good news: it is efficient

On tasks it resolves, the student takes fewer steps on average than Claude 3.7 Sonnet: 24.9 against 29.1. That gap partly reflects which tasks each solves. On the tasks both solve, the numbers are 24.8 and 25.6, nearly equal. It also keeps its focus on long runs, with 31 instances resolved after 40 steps or more. When it decides to submit, it is right about as often as the expert: 60 percent against 63 percent of the time.

The bad news: loops

The student often repeats itself. The paper counts the longest block of identical commands in a run. More than 25 percent of student runs contain a block of 10 or more, against under 4 percent for Claude. A block of 10 goes with an 89 percent chance of failure. Most of the longest blocks, 73 percent, are the file viewer, showing different pieces of one file instead of searching.

The cause is the run limits. A looping agent keeps issuing similar commands until the 75-step or $2.00 limit ends the run. The paper links 53 percent of the student’s failures to such limits, against a small share for Claude. Often the agent is still searching or reproducing the bug and has not edited any code. The dominant failure is localization: it cannot find where the fault is. The authors tried simple scaffold fixes that break loops. They cut the repetition but did not improve resolve rates.

How to measure a loop

Commands vary in their arguments, so the authors reduce each action to a base command. Strip any environment variable at the start. If commands are chained with && or semicolons, keep the last one. Remove the arguments. Keep two words for tools with subcommands, such as git checkout. Then the repetition length is the longest block of equal base commands.

L
The repetition length of one trajectory.
i
Each block of consecutive actions that share one base command.
runi
How many actions are in block i. L is the largest of these.

Try it on two invented runs. The first behaves well. The second views one file again and again. Notice that the arguments differ on every line of the second run, yet its base command never changes.

Find the loop

Pick a run. Each line shows the raw command and its base command. The longest block of equal base commands is marked.

Both runs are invented for this lesson. The reduction rules are the paper’s (Appendix F.5.2). The 89% failure rate at a block of 10 and the shares of 25% and 4% are the paper’s (Section 4.2, Figure 7).

What the paper does not claim

The authors list the limits plainly, and the appendix adds more.

Why do long repeated sequences of commands matter so much for the student?

Chapter 11

Field Guide

Keep the numbers, the terms, a build checklist and the whole pipeline as code

Here is the paper in one paragraph. Software agents lacked training data because the SWE-bench recipe needed a person to build an environment for each task. SWE-smith inverts the order. It builds one environment per repository, breaks the code in five ways, keeps only the breaks that fail a test, and has a model write the issue. An expert agent attempts the tasks, and only its passing attempts train a 32B student, which reaches 40.2 percent on SWE-bench Verified.

The numbers

MeasurementValueSource
Dataset size50,137 tasks from 128 Python repositories; 381 per repository on averageTable 1, Section 2.2
Cost to build$1,360 ($1,000 bugs, $160 installs, $200 issues for 10k bugs); about 20 hours of one author’s timeSection 2.1, 2.2
Yield by strategyCombine 96.9%, LM Modify 56.0%, Procedural 40.2%, LM Rewrite 35.0%, PR Mirror 33.8%Table 1
Cost per candidate0.00¢ (Combine, Procedural), 0.38¢ (LM Modify), 3.93¢ (LM Rewrite), 5.53¢ (PR Mirror)Table 1
Issue text2.54¢ per issue; 30.19% of mirrored tasks had an original issueSection 2.2, Appendix D
Storage295 GB for 50k tasks; 50 to 150 TB the old way; about 500 times lessTable 2, Section 2.2
Flask, per task207.27 min of human time against 0.176 min and $0.00613; bug coverage 7.25% against 89.03%Appendix C.2
Training set5,016 trajectories from 6,457 resolved of 17,906 attempts; cap of 3 per task; 123 repositoriesSection 4, Appendix F.3
Main result40.2% Verified and 30.7% Lite (32B); 15.2% and 11.7% (7B)Table 3
AblationsPR Mirror 9.2, LM Rewrite 8.8, Procedural 8.6, LM Modify 5.7; leaked-test issues cut reproduction runs by 66%Tables 4 and 5, Section 4.1
Behavior24.9 steps against 29.1; over 25% of runs have a block of 10 repeats (89% fail); 53% of failures hit a limitSection 4.2

The terms

TermPlain meaning
Task instanceA repository with a bug, an issue text, and the tests that grade a fix
FAIL_TO_PASS, PASS_TO_PASSTests the bug breaks, and tests that must stay green
YieldShare of candidates that survive the filter
PR MirrorUndo a real pull request, with a model, in today’s code
TrajectoryThe full record of an agent’s thoughts, actions and observations on one task
Rejection sampling fine-tuningTrain only on attempts that passed the tests
Pass@1Share of tasks solved on a single attempt

The core as code

def swe_smith(repos, expert, student):
    tasks = []
    for repo in repos:
        env = build_environment(repo)                    # Chapter 2: one image per repository
        for cand in (lm_modify(repo) + lm_rewrite(repo) + procedural(repo)
                     + pr_mirror(repo)):                 # Chapters 4 and 5
            r = validate(env, cand)                      # Chapter 3: keep if a passing test fails
            if r: tasks.append({**r, "patch": cand, "problem_statement": make_issue(r, cand)})  # Chapter 6
        tasks += combine(tasks_of(repo))                 # Chapter 5
    data = []
    for t in tasks_to_try(tasks):
        traj = run_agent(expert, t, max_steps=75, max_usd=2.0)       # Chapter 7
        if resolved(traj, t) and count(data, t) < 3:
            data.append(to_xml_format(traj))
    return fine_tune(student, data)                      # lr 5e-5, up to 3 epochs, 32k context

A build checklist

Tick what you would need to run SWE-smith on your own project. The read-out counts what is left.

Plan your own run

Tick each piece you already have. The read-out names the next one to build.

The list is our summary of the pipeline in Chapters 2 to 7, not a list from the paper. The 80% rule, the limits and the cap are the paper’s.

Where it sits

SWE-smith joins a line of work on data for agents. Our CS 329Z lecture on data for agents sets out why trajectories, environments and rewards are the raw material. The data selection lecture then asks which of those examples to keep. The lesson on supervised fine-tuning an agent on traces shows the training step in code. Terminal-Bench is a benchmark whose tasks were written and audited by people, a useful contrast with synthetic ones. For scoring agents, read agent evaluation and benchmark auditing. For learning from test rewards, which SWE-smith leaves out, see SPICE and self-play software agents. The course begins with what agentic systems are.

Credit and sources

SWE-smith: Scaling Data for Software Engineering Agents was written by John Yang, Kilian Lieret, Carlos E. Jimenez, Alexander Wettig, Kabir Khandpur, Yanzhe Zhang, Binyuan Hui, Ofir Press, Ludwig Schmidt and Diyi Yang, from Stanford University, Princeton University, Alibaba Qwen and independent work. It appeared at NeurIPS 2025 (Datasets and Benchmarks) and as arXiv 2504.21798. Read the original at arxiv.org/abs/2504.21798. The authors release the collection code, task instances, trajectories and models at swesmith.com. Every number in this lesson comes from that paper, except where a device says it is illustrative or a line says it is our division.

Let the tests choose the tasks. The paper’s best idea is small. Do not search for problems that happen to exist. Make problems from working code, and let the repository’s own tests say which ones are real.
Go back to the hero and tap each bug maker again. Now you know what sits behind each pink square: an edit, a test run, a filter, and an issue a model will write.
Which statement matches the paper?
SWE-smith
Read the paper · Back to Veanors