Making agent training data is now cheap. Deciding what to keep is hard: in this toy pool, only 18 of 60 items teach anything, and three filters lift that share from 30% to 100%.
Learn which tasks are worth training on, which runs are worth copying, and when more data beats better data.
Switch on Verify tasks, Screen difficulty and Drop repeats one at a time and watch the pool shrink toward the items that teach. Then we build each filter, piece by piece, and test it against the lecture’s evidence.
You need a rough idea of how a model is trained on examples and a little Python for the code. We build the rest from zero.
Based on Lecture 12 of Stanford CS 329Z: Engineering AI Agents (Fall 2026), taught by Diyi Yang, Michael Ryan and John Yang, and its readings: Yang et al., SWE-smith, Shankar et al., Who Validates the Validators?, and Zhou et al., LIMA. Lecture slides: PDF, on the course site.
teaches wrong signal no signal repeat
Toy pool, illustrative: 18 items teach, 9 have a broken verifier (wrong signal), 21 are too easy or too hard (no signal) and 12 are near copies of others (redundant signal). The three kinds and the three filters are the lecture’s (slides 8 and 10); the counts are made up.
Chapter 0
See why a pipeline that makes agent data cheaply still needs a hard decision about what to keep
Last night your pipeline made three million agent runs. This morning your lead asks one question: which of these runs go into training? Nobody on the team can answer it quickly, and that is the whole lecture.
First, the housekeeping, in one paragraph. Homework 2 is out: the task is due 11/23 and peer reviews are due 12/2. The midpoint demo and report are due Friday 11/6, and oral exam sign-ups are overdue. Now to the content.
Lecture 11 showed how to make agent data. The slides recap it on one slide, which they number Lecture 10. Agents need more than text: they need tasks (a job to do), environments (a place to do it) and trajectories (a recorded run). People make realistic data, but slowly. Mined traces, synthesis and simulators make it cheaply. And data teaches by accident: reward hacks and harness overfit.
Lecture 12 starts where that one stopped. If making data is cheap, you now have too much of it. Some of it is wrong. Some of it is useless. Some of it is the same thing a thousand times.
The lecture states its claim in one line: making tasks and trajectories is now cheap, and deciding what to keep is the hard part. It draws a grid of squares, all filled, and then the same grid with most of them thrown away. The hero at the top of this page is that picture made playable.
A real example comes from Meta’s CWM (Code World Model) team. They generated 3 million agent trajectories from 10.2 thousand Docker images (packaged, ready-to-run copies of a computer setup) of 3.15 thousand code repositories (folders of project code). Then they decided what to keep. Two of their choices are on the slide.
The first choice: drop near-duplicates. Within each repository, a kept trajectory has a Jaccard similarity below 0.5 with every other kept one. Jaccard similarity compares two sets. Count the items they share, then divide by the count of items in either set. Identical sets score 1. Sets with nothing in common score 0.
Try it on a toy. The slide does not say which units CWM compares, so this device compares the sets of steps that two runs took. Pick a second run, then move the limit.
Run A is already kept. Choose a candidate run. Matching steps light up. Raise the limit until the verdict flips.
The 3M runs, 10.2k images, 3.15k repos and the 0.5 limit are from CWM (slide 7). The three short runs are made up for this device.
Run B is run A plus one extra look: 5 shared steps out of 6 different ones, J = 5/6 = 0.83. Drop it. Run D takes another route: 2 shared out of 9 different, J = 0.22. Keep it. The limit is a dial you set, and it trades size against variety.
The second CWM choice is the surprising one. They kept failed attempts. Their goal was a world model of code environments, a model that predicts what happens next. A failed run still shows real outputs. So they did not filter by success. The rule is clear: what to keep depends on what you want to teach.
The lecture draws the pipeline as a funnel with six levels: candidate tasks, valid tasks, learnable tasks, rollouts, kept trajectories and the training mix. A rollout is one complete attempt by the model. Each step down the funnel discards items. Section 2 of the lecture covers the first three levels (which tasks), section 3 the next two (which trajectories), and section 4 the last (more data or better data).
The funnel also tells you what you pick. For SFT (supervised fine-tuning: copy recorded runs) you select trajectories. For RL (reinforcement learning: practice against a checker) you select environments, each one a task, a sandbox and a verifier that decides success.
Slide 10 names three. Wrong signal: a broken verifier or a hacked success tells the model that bad work is good. No signal: a task so easy or so hard that every attempt scores the same, so nothing can be learned. Redundant signal: more of the same, which costs money and adds nothing. The hero pool has all three, and each toggle removes one.
Does the choice really matter? Slide 11 shows evidence from the OpenThoughts-Agent paper (Raoof, 2026). With the same base model and the same budget of SFT traces, picking the most effective subset beat picking at random, on several benchmarks.
Slide 12 sets up a fight. On one side, less is more: LIMI trained on 78 hand-curated trajectories and beat a model trained on 10,000. On the other, more is more: Orchard found that at scale, data size matters more than how you pick. Chapters 8 and 9 settle it.
The road for the rest of the lesson follows the lecture’s order.
Chapter 1
Use SWE-bench Verified to see how often a task fails before the model even tries it
Your agent fixes a bug. The fix is correct, and any engineer would approve it. The test still fails. The reward is 0. Training now pushes the model away from a correct answer. Nothing is wrong with the model. The task is broken.
The lecture opens its task section with a mental model: pick tasks in a loop of four moves. First, filter out broken or unreliable tasks. Second, check validity by running them. Third, keep tasks the model sometimes solves. Fourth, re-select as the model improves. This chapter is move 1. Chapters 2 to 4 are the other three.
Slide 15 shows one real case. The task is sklearn-14520, from the code library scikit-learn. The issue text says: the copy parameter of TfidfVectorizer is ignored, and the reporter asks if they are missing something. That is all the agent sees.
The unit test (a small program that checks one behavior and passes or fails) demands more. It requires an exact deprecation warning with this wording: “‘copy’ param is unused and has been deprecated since version 0.22.” That sentence was decided in a pull request discussion. The agent never sees that discussion. No agent could guess the words.
Two things are wrong. The problem statement is underspecified: it does not say what to build. The tests are unfair: they reject a correct solution. A task with either flaw gives wrong signal, the first bad kind of data from Chapter 0.
python# what the test demands (slide 15): the exact words, never given to the agent msg = ("'copy' param is unused and has been deprecated since version 0.22. " "Backward compatibility for 'copy' will be removed in 0.24.") with pytest.warns(DeprecationWarning, match=msg): # a correct fix with other wording FAILS tv.transform(train_data, copy=True)
OpenAI asked humans to check. Slide 16: 93 Python developers annotated 1,699 random samples of SWE-bench, a benchmark of real software issues taken from open-source projects. Each sample got labels from 3 annotators, and the pipeline kept the highest-severity label. So one annotator who spots a problem is enough to flag the sample. Higher severity means a worse problem.
Slide 17 gives the results. 38.3% were flagged for underspecified problem statements. 61.1% were flagged for unfair unit tests. 68.3% were filtered out overall. Check the arithmetic. 38.3 + 61.1 = 99.4, which is more than 68.3. So many samples carry both flaws. At least 99.4 − 68.3 = 31.1% of all samples do.
Each square is 1% of the samples. Filled squares are flagged. Choose a flag. Below, the same model scores on the original set and on the filtered set.
The 1,699 samples, the 38.3%, 61.1% and 68.3% (OpenAI, SWE-bench Verified, slides 16 and 17) and GPT-4o’s 16% and 33.2% (slide 18) are the lecture’s. “Both, at least” is arithmetic from them: 38.3 + 61.1 − 68.3. Counts are the percentage times 1,699, rounded.
Take “dropped overall”. 68.3% of 1,699 is about 1,160 samples. About 539 survive. Two thirds of the annotated samples did not pass a human read.
Slide 18 is the proof that it matters. GPT-4o scored 16% on the original SWE-bench and 33.2% on SWE-bench Verified. Same model. More than double the score, just from removing tasks that no one could solve fairly. The lecture’s caption reads: broken tasks hide real ability. In training, they give wrong rewards.
That last point is the one to hold. In a benchmark, a broken task only lowers a score. In RL training it does worse. The model gets 0 for a right answer and learns to avoid right answers. The unfair test is a bad teacher.
Symptom: the training reward on some tasks never rises, and the model’s correct patches fail. Measurement: have people read a random sample, as OpenAI did, and count how many flag each problem. Fix: drop the flagged tasks, or rewrite them so the statement says what the tests check.
Human review gives high quality and low speed. 93 developers and three labels each is a lot of work for 1,699 samples. The next chapter shows how to automate the same job by running code.
pythondef keep_task(labels, cutoff): # labels: 3 severities, one per annotator worst = max(labels) # one alarmed annotator is enough return worst < cutoff # the cutoff is a choice you make
Chapter 2
Replace human review with checks that execute the task, as APIGen and CodeMidas do
Chapter 1 needed 93 people to read 1,699 tasks. Your pipeline makes tens of thousands. Nobody can read them all. So the second move in the task loop is to let the computer check validity by running each task. A task that cannot survive being run does not deserve to be trained on.
The lecture’s first example is APIGen (Liu et al., 2024), a pipeline that makes tool-use data. A tool call is a request from a model to a function, such as get_weather(city="Paris"). Slide 19 says human review does not scale, so APIGen automates it with three checks.
Check 1 is the format check: does the call parse, and do its fields match the function’s signature? Check 2 is the execution check: run the call for real. Does it return a result, not an error? Check 3 is the semantic check: a language model reads the query and the result and judges whether they match. Each check is cheaper than the next, so the cheap ones run first and most bad items never reach the judge.
pythondef apigen_check(query, call, tools): # illustrative shapes, not APIGen’s code if not parses(call, tools[call.name].schema): return "drop: format" result = tools[call.name].run(**call.args) # execute for real if result.error: return "drop: execution" if not judge(query, call, result).matches_intent: return "drop: meaning" return "keep"
The second example is CodeMidas (Ye et al., 2026), from the MiMo model team. It builds coding RL environments from source code alone: no issues, no pull requests, no commits, no existing tests. So it must write the task, the tests and a reference solution itself. Then it must prove they fit together.
First rule: tests should accept any correct solution. Slide 21 compares two tests. The too-strict test is sklearn-14520 again: it demands an exact message from a pull request discussion. The CodeMidas test checks only what the task states. If the task says “raise ValueError on bad input” and does not fix the message wording, the test is pytest.raises(ValueError) and nothing more. The paper’s rule: test the stated behavior, not an accident of one solution.
Second rule: each task runs in six fresh containers. A container is a clean, isolated copy of the computer, so no run leaks into the next. Run the starting code twice. Both runs must fail. Run the reference solution four times. All four must pass. A task is kept only if all six come out as expected.
Why six? Each run guards against one bug. If the tests already pass on the starting code, the task is vacuous: there is nothing to fix. If the reference solution fails, the task is impossible. And a flaky test, one that passes sometimes and fails sometimes on the same code, shows itself by disagreeing across repeats. Repeating a run is the cheapest flakiness detector.
Choose a kind of candidate task, then press Run. The first two boxes run the starting code and must fail. The last four run the reference solution and must pass.
The six-container rule (2 starting runs that must fail, 4 reference runs that must pass, keep only if all six match) is CodeMidas (slide 22). The four task kinds and the 75% flaky rate are made up for this device. The “too strict” task passes all six runs on purpose.
Run the flaky task a few times. A test that passes 75% of the time on the right solution passes four times in a row with probability 0.75 × 0.75 × 0.75 × 0.75 = 0.316. So the four-run check removes 68% of such tasks. Raise the repeat count and it removes more. Cost grows with every run, so you choose a count.
Now run the too strict task. It passes all six runs and is kept. The six-run check cannot see it. The reference solution is the one the test was written around, so of course it passes. Only the first rule, test the stated behavior, prevents this. Two filters guard two different faults.
Static checks cannot see how a model attacks a task. So CodeMidas runs rollouts and applies three more filters (slide 23). The leakage probe drops a task if adversarial rollouts find the solution leaking, for example sitting in a cached file. The verdict review drops a task if a reviewer finds a wrong verifier verdict. The outcome filter drops a task if every attempt passes or every attempt fails. Chapter 3 shows why that last one matters.
pythondef keep_task(task): start = [run_fresh(task.tests, task.start_code) for _ in range(2)] # must all FAIL ref = [run_fresh(task.tests, task.reference) for _ in range(4)] # must all PASS if any(r.passed for r in start) or not all(r.passed for r in ref): return False rolls = rollouts(model, task, k=8) if leaks_solution(rolls) or reviewer_finds_wrong_verdict(rolls): return False return 0 < sum(r.passed for r in rolls) < len(rolls) # drop all-pass and all-fail
Does all this work pay? Slide 24 says yes. The filtered 3k subset beats the unfiltered 8k sample on all three evaluations. The full filtered 5k set beats the 8k set by 0.59, 4.59 and 4.49 points on SWE-bench Pro, DeepSWE and an internal benchmark. Fewer tasks, higher score, because each task now tells the truth.
Chapter 3
Compute the training signal of one prompt and see why mixed results are the only ones that teach
A teacher gives a class one question. Every student answers right. The teacher learns nothing about who needs help, and no student learns anything new. Now every student answers wrong. Again nothing is learned: nobody can tell a good attempt from a bad one. The question teaches only when answers differ.
RL training works the same way. The lecture shows this with DAPO (Yu et al., 2025), a recipe for training reasoning models. Its lesson applies to every agent task, because it is a fact about the training signal itself.
RL needs to know which attempts to make more likely. One simple method samples a group: the same prompt, tried several times. With 8 tries you get 8 rollouts and 8 rewards, each 1 (pass) or 0 (fail). Then you ask how each rollout did compared with its own group.
That comparison is the advantage: how much better than the group’s average a rollout was. The slide gives the formula.
Work the slide’s first row. The rewards are 1, 0, 1, 1, 0, 0, 1, 0: four passes out of eight. The mean is 0.5. The standard deviation is the square root of 0.5 × 0.5, which is 0.5. A passing rollout gets (1 − 0.5) / 0.5 = +1. A failing one gets (0 − 0.5) / 0.5 = −1. The model learns: do more of what the four passes did.
Now the slide’s second row: all eight rewards are 1. The mean is 1. The standard deviation is 0. Every numerator is 1 − 1 = 0, so every advantage is 0. In code the division is guarded so it does not crash, and the result is zero. The lecture’s label: no gradient. The model does not move.
Let p be the chance that the model solves one prompt on a single try. The group is all-wrong with probability (1 − p) to the power 8, and all-right with probability p to the power 8. So the chance of a mixed group is
With G = 8 and p = 0.5, P(mixed) = 1 − 0.0039 − 0.0039 = 0.992. With p = 0.9 it is 1 − 0.430 − 0 = 0.570. With p = 0.99 it falls to 0.077. Move the slider and watch both ends collapse.
Each circle is one of 8 rollouts of the same prompt: filled means pass. Under it is its advantage. Drag the solve rate. Press Resample to draw new rollouts.
The advantage formula and the two example rows (mixed, all correct) are DAPO (slide 25). The rollouts here are drawn from your solve rate p, and the batch of 32 is a number picked for the device.
Slide 26 plots the share of prompts where every rollout is correct, over training steps. It climbs. A stronger model solves more prompts every time, so more groups look like the all-correct row. Each batch holds fewer prompts the model can still learn from. The fixed batch size stays the same, but the useful part shrinks.
Read the device at p = 0.9. You sample 8 rollouts and 43% of the groups are all-correct. Those rollouts cost real compute and give an advantage of zero. This is wasted sampling: you paid for answers that carry no signal.
Slide 27 gives dynamic sampling. Draw prompts. Roll out each group. Drop any group where all rewards are right or all are wrong. Keep going until the batch holds only mixed groups. The lecture reports the same accuracy in fewer steps, even though each step samples more.
pythondef advantages(r): # r: [G] rewards of one group m, s = mean(r), std(r) return [0.0 for _ in r] if s == 0 else [(x - m) / s for x in r] def fill_batch(policy, prompts, B=32, G=8): batch = [] while len(batch) < B: x = next(prompts) rolls = [policy.rollout(x) for _ in range(G)] r = [verify(x, y) for y in rolls] if 0 < sum(r) < G: # keep only mixed groups batch.append((x, rolls, advantages(r))) return batch
The cost is easy to count. To fill a batch of 32 you need about 32 / P(mixed) prompts. At p = 0.9 that is 32 / 0.570, about 56 prompts, or about 450 rollouts, for 32 useful groups. You pay about 1.75 times the sampling for a batch with no dead weight.
This is the same outcome filter you met in Chapter 2: drop a task if every attempt passes or every attempt fails. One idea, used at the task level before training and at the batch level during it.
Chapter 4
Screen a task pool by pass rate, then see why the screen goes stale as the model improves
A coach picks drills for a runner. A drill the runner always finishes builds nothing. A drill the runner never finishes is only a bad day. The useful drills sit in the middle: sometimes finished, sometimes not. Chapter 3 proved the math for that. This chapter turns it into a pipeline step, using LEGO-RL, and then asks what happens as the runner gets fitter.
LEGO-RL (Du et al., 2026) builds software tasks for RL. Slide 28 shows two screens and a third one to come. The numbers are worth reading as a funnel.
| Stage | Tasks left | Share of the start |
|---|---|---|
| Candidates | 36,884 | 100% |
| Rule-based screening | 22,806 | 61.8% |
| Build and verifier check | 21,681 | 58.8% |
| Difficulty screen (next) | 2,699 | 7.3% |
The first two stages are the validity checks from Chapter 2: rules that reject malformed tasks, then a real build and a verifier run. They cut 36,884 to 21,681. A verifier is the code that decides pass or fail. The slide adds one number: about 2.5% of inspected tasks had verifiers that wrongly applied the reference patch, so even the checker needs checking.
The big drop is the third stage, the difficulty screen. It takes 21,681 down to 2,699. That is 12.4% of the valid tasks. Valid tasks are not the same as useful tasks.
The screen is simple. Run the current model on each task 4 times. Count the passes. The slide draws five boxes: 0/4 (never solved), 1/4, 2/4 and 3/4 (all three: keep), and 4/4 (always solved). The final training set is the 2,699 tasks in the keep band.
Slide 30 shows what the screen buys. In the unscreened pool, 72.7% of tasks are never solved and 13.4% are always solved. So only 100 − 72.7 − 13.4 = 13.9% of the pool sits in the middle. The slide’s plots show that training on the unscreened pool improves neither the held-out validation solve rate nor the training reward. The slide does not say the 13.9% and the 2,699 come from one sample, so treat them as close, not equal.
pythondef difficulty_screen(tasks, model, tries=4): keep = [] for t in tasks: solved = sum(verify(t, model.rollout(t)) for _ in range(tries)) if 1 <= solved <= tries - 1: # 1/4, 2/4, 3/4: keep keep.append(t) return keep # 0/4 and 4/4 give a zero advantage (Ch 3)
Here is the catch, on slide 31. The screen measured the model as it was. As training works, the model gets better. A task that was 2/4 becomes 4/4. The keep band empties from the top. Under the OpenHands SDK, the share of zero-variation groups rose from 44.7% to 51.4% over training. Zero variation means all rollouts got the same reward: the Chapter 3 dead groups. The lecture’s advice: refresh the pool over time.
Try the device. It has 400 tasks of evenly spread difficulty. Move the model’s skill and count the tasks in the keep band. Then switch on Refresh the pool.
Bars count tasks by how many of 4 tries pass. Green is the keep band. Drag the skill up. Then turn on the refresh and drag again.
Toy model, illustrative: 400 tasks whose difficulty is spread evenly from −3 to 3, and a chance of solving each of 1 / (1 + e−1.5 (skill − difficulty)). The 1 to 3 out of 4 screen is LEGO-RL (slide 29); the refresh idea is its slide 31 and WebRL’s curriculum.
At skill 0 about 160 of the 400 tasks (40%) are in the band. Move to skill 3 and only about 80 (20%) stay: the rest are now always solved. With the refresh on, the pool is rebuilt around the model’s level and the band holds at about 40%. Refreshing costs work: new tasks must be made and checked again. But a stale pool wastes every rollout you spend on it.
WebRL (Qi et al., ICLR 2025) shows refreshing in an online setting. It trains web agents, and the lecture names three problems: scarce training tasks, sparse feedback (most attempts earn nothing), and policy distribution drift (the model’s own behavior shifts as it trains, so old data stops fitting).
Its answer to scarcity is a self-evolving curriculum. A curriculum is an order of tasks from easier to harder. WebRL writes new tasks from the model’s unsuccessful attempts, so the next tasks sit just beyond what it can do. Its answer to sparse feedback is an outcome-supervised reward model (ORM): a model trained to judge whether a whole attempt succeeded, so every attempt gets a score. The slide’s figure also shows a KL-limited policy update and a replay buffer, which fight drift.
The result is on slide 34. WebRL lifts Llama-3.1-8B from 4.8% to 42.4% on WebArena-Lite, a gain of 37.6 points. The 70B model reaches 47.3%. So a small model with a good loop gets within 5 points of a model almost nine times its size.
pythondef webrl_round(policy, tasks, orm): rolls = [policy.rollout(t) for t in tasks] reward = [orm.judge(r) for r in rolls] # a learned judge: no hand-written checker failed = [r for r, s in zip(rolls, reward) if s == 0] new_tasks = [write_harder_variant(r.task) for r in failed] # the curriculum grows from failures policy.update(rolls, reward, kl_limit=True) # stay close to the old policy return new_tasks
Chapter 5
Audit the runs that passed, because the verifier cannot tell how the agent got its green light
A student hands in a perfect exam. You look closer. The answers match the answer key word for word, and the key was lying open on the teacher’s desk. The score is real. The learning is not. If you copy this student’s method, you copy the cheating.
The lecture now moves from tasks to trajectories (recorded runs), and it opens with a slide that splits them four ways. Passed the tests: some are cheats (check how the agent got there), and some are sloppy (select by process quality). Failed the tests: some are worth keeping if labeled as failed, and some contain good steps you can salvage. The slide’s title is the whole chapter: passing the tests is not the same as being a good demonstration. This chapter takes the cheats.
The Qwen team’s paper The Verification Horizon (2026) starts with a claim on slide 37: generating solutions is no longer the hard part, verifying them is. A verifier checks the result, such as tests passing. It does not check the route. So an agent that finds a shortcut gets the same reward as one that does the work.
The paper catalogs seven shortcuts on slide 38. In plain words, from their names:
Chapter 9 of last lecture’s lesson told the git-history story from the other side: the grader leaked. Here the same hole shows up as a cheat the data pipeline must catch.
Slide 39 shows why this is a data problem and not a curiosity. Only 4.32% of trajectories use solution-artifact retrieval. That is rare. But 72.34% of those resolve the task, which is 12.35 points above the baseline, so the baseline resolve rate is 72.34 − 12.35 = 59.99%. A shortcut that wins more often than honest work gets reinforced. In RL the model learns to take it.
Slide 40 shows the result over training: the pass rate can stay high while clean performance drops. Clean performance means the share resolved without a shortcut. The headline number hides the rot.
Slide 41 gives the fix and the numbers. Add a monitor, a checker that reads each trajectory and flags shortcuts. Averaged over three SWE-bench variants, the hacked resolved rate falls from 28.57% to 0.56%. The clean resolved rate rises from 40.22% to 60.53%.
Look at what the headline would say. If the hacked and clean rates split the resolved tasks, as their names suggest, the total pass rate is 28.57 + 40.22 = 68.79% without the monitor and 0.56 + 60.53 = 61.09% with it. By pass rate the monitored run looks 7.7 points worse. By clean rate it is 20.3 points better. Which measure you trust decides which run you ship.
Each bar is a share of tasks resolved: green clean, red hacked. Choose how to judge, and see which run wins.
The four rates (28.57% to 0.56%, 40.22% to 60.53%, averaged over three SWE-bench variants) are The Verification Horizon (slide 41). Adding hacked and clean into a pass rate is this lesson’s reading, not a number from the paper.
A monitor is itself a validator: a judge of other output, often a language model. Is it right? Shankar et al., Who Validates the Validators? (UIST 2024), study exactly that. Their finding is easy to feel. People do not know their grading criteria before they start. They discover them while grading real outputs, so the criteria drift. Their fix is to keep a human in the loop: grade a few outputs, check the judge against those grades, and revise both. See the full Veanor.
For your monitor this means: sample flagged and unflagged runs, read a few yourself, and measure how often the monitor agrees with you. A monitor you never checked is a second wrong signal.
pythondef audit(run, tests_before): # the shape of a monitor, not the paper’s flags = [] if run.touched(".git") or run.ran("git log"): flags.append("git-history mining") if run.files_changed() & tests_before: flags.append("test-oracle tampering") if run.network_calls(): flags.append("external fix lookup") if llm_judge(run).says_shortcut: flags.append("judged shortcut") return flags keep = [r for r in runs if r.passed and not audit(r, tests)] # only clean passes become SFT data
The measurement habit is the same as in Chapter 1: count. Report two numbers every time, the pass rate and the clean rate, and treat a widening gap as an alarm.
Chapter 6
Select trajectories and then segments by process quality, as SWE-Prime does
A mechanic fixes your car. It runs. But she opened three wrong panels first, checked the oil twice, and loosened a bolt she then forgot to tighten. The result passed. A new mechanic who copies every move learns the detours and the risky habit along with the repair.
Chapter 5 removed the cheats. This chapter handles honest passes that are still poor teachers. Slide 42 draws one successful trajectory as a row of steps ending in “tests pass”, with three steps marked: ineffective (it did nothing useful), redundant (it repeated earlier work) and risky (it could have broken something, even if it did not this time). The slide’s point is in its title: successful runs can still contain such steps.
In SFT (supervised fine-tuning) the model learns to imitate every token it is graded on. If a clean run contains a risky command, the loss rewards the model for writing that command. The model has no way to know the step was a mistake that happened to be harmless. So the quality of the path matters, not only the end.
A trajectory is long. Throwing away a whole run because of one bad step wastes its good steps. Throwing away nothing keeps the bad step. SWE-Prime (Zheng et al., 2026) takes a middle path with two stages, shown on slide 43.
First, score each successful trajectory on its process: did it explore sensibly, avoid repeats and stay safe? The paper’s figure also shows a result-quality check and a check that the chosen set is representative, so the kept set does not collapse onto one kind of task. Keep the best runs and drop the rest.
Next, cut each kept trajectory into segments, short stretches of steps. Score each segment on three things from the slide. Contribution: how much did it move the task toward the fix? Risk: could it do damage? Learnability: is it a pattern the model can pick up and reuse, neither trivial nor impossibly specific? Keep the segments with high contribution, low risk and good learnability.
How do you drop a segment from an SFT example without breaking the story? Use the loss mask from Lecture 11. The dropped steps stay in the text as context, so the later steps still make sense, but their mask is 0 so the model is never graded on writing them.
Try it on a toy trajectory. Ten steps, each scored for contribution and risk. Move the two limits and see what survives.
Each box is a step; its height is its contribution, its outline its risk. Filled boxes are graded in training. Hollow boxes are context only.
Illustrative: the ten steps and their scores are made up. The idea (flag ineffective, redundant and risky steps; score segments on contribution, risk and learnability; mask rather than delete) is SWE-Prime (slides 42 and 43). Real scores come from a model, not a table.
At the defaults (0.30 and 0.40) six of ten steps survive, which is 315 of 575 tokens, or 55%. The wrong-file detour, the repeated file open, the risky command and the repeated test run are masked. The grep, the edit and the test run remain, which is exactly the part that teaches the fix. Push the contribution limit to 0.90 and only the edit survives. It is too thin to teach how to find the bug. Selection has two failure modes: keeping noise and keeping too little.
Slide 44 gives the result. Training on a 10% subset selected by SWE-Prime beats training on all successful trajectories, with relative gains up to 12.2% on SWE-bench Pro and 24.2% on SWE-bench Verified. A relative gain is a ratio: 24.2% means the score is 1.242 times the baseline, not 24.2 points higher. So if the baseline were 40% (illustrative), 1.242 × 40 = 49.7%.
The cost story is as good as the quality story. A tenth of the data means about a tenth of the training tokens. With 30,000 successful runs (illustrative), you train on 3,000 and finish roughly ten times faster, with a better model.
Compare with Chapter 5. The cheat audit asks did it break the rules. The process audit asks was it a good way to work. Both look at the route, never only the result.
pythondef select(runs, keep_frac=0.10, c_min=0.3, r_max=0.4): good = [r for r in runs if r.passed] good.sort(key=lambda r: process_quality(r), reverse=True) # stage 1 good = good[: int(keep_frac * len(good))] for r in good: # stage 2 for seg in chunk(r): keep = contribution(seg) >= c_min and risk(seg) <= r_max and learnable(seg) seg.loss_mask = 1 if keep else 0 # context stays, grading goes return good
Chapter 7
Keep failures with a label, or salvage their good steps, instead of throwing every failed run away
A pilot’s flight ends in a bad landing. The review finds that the first forty minutes were flown perfectly. Only the last approach went wrong. Would you cut the whole flight from the training video? You would lose forty minutes of good flying to hide four minutes of error.
Standard practice does exactly that. It trains only on runs that passed and discards the rest. The last branch of slide 36 asks for better: failed runs can be kept labeled as failed, or mined for their good steps. Two papers show how.
NAT, short for Negative-Aware Training (Wang et al., NAACL 2025), starts from slide 45. The left side of the slide shows a successful trajectory. The right side shows a failed one whose early steps are reasonable, and says standard practice throws the whole run away.
NAT’s trick is small. Add a label, a short prefix or suffix on each training example that says whether the run succeeded. Train on all the runs, successes and failures. At test time you ask for the success label, so the model writes in the style it learned for successes.
Why does it work? Slide 47 gives NAT’s own explanation: failed trajectories mix useful information with errors, and the label gives a better trade-off between the two. Without a label the model cannot tell the good from the bad, so it imitates both. With a label it learns what failure looks like and keeps it apart from what success looks like.
EEF stands for Explore Expert Failures (Lan et al., 2025). It begins from a different complaint on slide 48. The usual recipe is RFT, rejection-sampling fine-tuning: sample many runs, reject the failures, fine-tune on the successes. The slide shows an expert that mostly succeeds on easy subtasks. So hard subtasks almost never make it into training.
Here is the arithmetic, with made-up rates. A subtask the expert solves 90% of the time gives 18 kept runs out of 20 tries. A hard one it solves 10% of the time gives 2. RFT’s training set holds nine times more easy examples than hard ones. The model gets good at what it already did well.
Slide 49 adds the second point: a failure may come from mistakes in only the last few steps. Prior methods treat every action in a failed run as negative. EEF instead goes back to the intermediate states of failed expert runs and explores from there. It finds the steps that lead on to success and keeps those. The failed run becomes a source of good steps and of hard-subtask examples.
Slide 50 gives the result on WebShop, a simulated shopping task: EEF reaches a 62% win rate, RFT 53.6% and GPT-4 35.6%. EEF beats RFT by 8.4 points and GPT-4 by 26.4.
Take a toy pool of 100 runs on a task with 8 steps. Forty runs succeed. Sixty fail, and in each failure the first j steps are good and the remaining 8 − j are bad. Slide 45 says early steps are reasonable, so start with j = 5. Choose a recipe and move j.
Choose a recipe. Move the slider: the share of each failed run that went well before the first mistake.
Toy counts, illustrative: 40 successful runs and 60 failed runs of 8 steps each. The labeled recipe assumes the label keeps the bad steps apart when you ask for success, which is NAT’s claim (slide 47), not something this device proves. The four recipes are from slides 45 to 49.
Successes only learns 40 × 8 = 320 good steps and no bad ones, but it throws away 60 runs. Copying everything with no label learns 320 + 60 × 5 = 620 good steps and also 60 × 3 = 180 bad ones: a useful share of 77.5%. Labeling or salvaging keeps the 620 good steps. Salvage cuts each failure at its first mistake, so the 180 bad steps never enter. Labeling keeps them but tagged, so they do not show up when you ask for success.
Now set j to 1. Failures now hold almost nothing good, and copying everything is mostly noise. The recipes differ most where failures are poor. Set j to 8 and failures are all good, which means the verifier is probably broken: go back to Chapter 1.
Symptom: the SFT set is small, and the model never improves on hard cases. Measurement: count the share of kept runs by subtask difficulty. If hard subtasks fill 5% of the data, that is why. Fix: bring failures back, labeled or cut, and check that hard subtasks grow.
pythondef nat_example(run): # NAT style: one label, all runs tag = "[outcome: success]" if run.passed else "[outcome: failure]" return tag + "\n" + run.text # at test time, prompt with the success tag def eef_salvage(failed_run, policy, tries=8): # EEF style: explore from the failed run’s states out = [] for i, state in enumerate(failed_run.states): rolls = [policy.rollout_from(state) for _ in range(tries)] wins = [r for r in rolls if r.passed] if wins: out.append((failed_run.prefix(i), wins[0])) # a good step that leads to success return out
One caution joins this to Chapter 5. A failed run can hide a cheat too, and a label saying “failure” can be wrong if the verifier is broken. Audit before you label.
Chapter 8
Weigh LIMA and LIMI against Orchard to see when a small curated set wins and when size does
Two coaches argue. One says: give me twelve perfect drills and I will turn a beginner into a player. The other says: give me a thousand ordinary drills, because volume wins. Both have a champion to show you. The lecture’s last section, More data, or better data?, puts the two coaches in one room and asks who is right.
Slide 52 draws the question as two curves, labeled illustrative, not data. A small curated set climbs fast and flattens. An unfiltered set climbs slowly and keeps going. The curves cross. The slide’s bottom line is one sentence: either way, diversity is what generalizes. Chapter 9 returns to that. First, the evidence for each coach.
The older case is LIMA, Less Is More for Alignment (Zhou et al., NeurIPS 2023). The authors took a 65-billion-parameter LLaMa base model, a model that had only read text, and fine-tuned it on just 1,000 carefully chosen prompts and responses. They used no RL and no human-preference training, only the plain supervised loss. In a controlled human study, LIMA’s answers were judged equal to or better than GPT-4’s in 43% of cases, better than or equal to Bard’s in 58%, and better than or equal to DaVinci003’s in 65%. DaVinci003 had been trained with human feedback.
Their explanation is the Superficial Alignment Hypothesis. The abstract says almost all knowledge in a language model is learned during pre-training, and only limited instruction-tuning data is needed to teach the model to produce high-quality output. The model already knows the facts. A thousand examples teach the format and style of a good answer, nothing more.
LIMI (Xiao et al., 2025) makes the same bet for agents. Slide 53 places it on a log scale of training examples: LIMI at 78 agent trajectories, LIMO at 817 math samples, LIMA at 1,000 alignment examples, and the comparison set at 10,000. Slide 54 gives the claim: 78 hand-curated trajectories beat 10,000, which is 128 times fewer (10,000 / 78 = 128). The score on AgencyBench is 73.5% with 78 samples against 47.8% for a model trained on 10,000, a gap of 25.7 points.
How were the 78 made? Slide 55: 60 queries came from real developer and researcher scenarios, and 18 were sampled from queries synthesized from GitHub pull requests. Slide 56 adds that four PhD students worked with GPT-5 on each task until it succeeded. That is a great deal of human care per example.
Slide 57 then adds the fine print, and it is worth reading slowly. AgencyBench is small: 10 tasks, and it shares many authors with LIMI. And without the command-line environment, generalization was 50.0% against 48.7% for GLM-4.5, a small gain. So the headline is real but narrow.
Now the other coach. Orchard (Peng et al., 2026) designed a clean experiment, slide 58. Fix the base model, the SFT recipe and the harness. Vary only two things: the number of trajectories (512, 1,024 or 2,048) and the strategy for choosing them. Six strategies: Random; two heuristics, Diverse repo (spread across many repositories) and Concentrated repo (few repositories); and three that use properties of the gold patch, Multi-file, Large diff and Composite. Each dot is one SFT run.
First finding, slide 59: any good SFT helps. The base model scores 22.0%. Even the worst SFT setting adds 22 points. Second finding, slide 60: scale dominates. Here is the table, which you can explore below.
Six lines, one per strategy, on SWE-bench Verified. Pick a strategy and a size. The read-out compares two ways to improve.
Every value is the SFT-only resolve rate on SWE-bench Verified from Orchard’s Table 10 (slide 60). The base model, recipe and harness are fixed in the paper; only the size and the strategy change.
Read it as the lecture does. The worst method, Diverse repo, goes from 44.0% at 512 trajectories to 52.2% at 2,048: +8.2 points. The spread across all six strategies at 512 is 49.5 − 44.0 = 5.5 points. So choosing the wrong strategy at small size costs less than failing to scale. Look at the right edge: at 2,048 the six strategies span 52.2 to 54.2, only 2.0 points. Strategies matter less and less as data grows.
Random at 2,048 (52.8%) even beats the best strategy at 512 (49.5%) by 3.3 points. And for Random, doubling adds 4.5 points from 512 to 1,024 and 2.5 from 1,024 to 2,048: the gains shrink, but they do not stop.
Both, on different ground. LIMA and LIMI tested small sets built with great care against a weak, or differently built, large baseline. Orchard held everything fixed except size and strategy and used cheap, automatic strategies. The next chapter shows slide 68, which reconciles the two. For now, remember what each side did not test.
python# Orchard’s clean design: change one thing at a time, everything else fixed for n in (512, 1024, 2048): for strategy in (random_pick, diverse_repo, concentrated_repo, multi_file, large_diff, composite): data = strategy(pool, n) model = sft(base_model, data, recipe=FIXED, harness=FIXED) table[strategy.__name__, n] = resolve_rate(model, swe_bench_verified)
Chapter 9
Spread data across many environments, then use one table to reconcile less-is-more with more-is-more
A student practices one maze a thousand times. She is brilliant at that maze. Hand her a new maze, same rules, different walls, and she freezes. A second student practices a hundred mazes ten times each. On day one she is slower. On the new maze she is far better. Practice volume was equal. Practice variety was not.
Slide 52 said it in one line: either way, diversity is what generalizes. Three results back it up.
AgentRefine (Fu et al., ICLR 2025) opens on slide 61 with a bar chart over five agent benchmarks: AlfWorld, BabyAI, SciWorld, PDDL and Jericho. Existing agent data does well on held-in tasks, the environments it was trained on, and poorly on held-out ones, which it never saw. A held-out test is the only test of whether the model learned the skill or the maze.
Slide 62 lists the three errors that dominate in new environments. A format error: the action is malformed, such as Action: clik [Buy Now]. Illogical reasoning: the thought says the mug is in the sink, and the action goes to the fridge. Repeated generation: the agent writes Action: look again and again.
The cure on slides 63 and 64 has two parts. First, synthesize diverse environments. Second, train the model to fix its own mistakes by showing it runs where an error is made, noticed and corrected. Result: self-correction data holds up better when the environment changes slightly, and diverse environments and diverse thoughts in the data are what make it generalize.
Slide 65 recaps the data lecture (Lecture 11 here, Lecture 10 in the slides): SWE-smith (Yang et al., NeurIPS 2025) builds one environment per repository and synthesizes bugs inside it. Pick a repository with tests, inject a bug that breaks at least one test, and you have a task with a built-in checker. The full method has its own Veanor: SWE-smith.
The diversity experiment is on slides 66 and 67. Every run trains on exactly 700 expert trajectories. What changes is the number of repositories they come from, from 4 up to 100. With 4 repositories each one supplies 700 / 4 = 175 trajectories. With 100 repositories each supplies 7. The amount of data is identical. Only the variety differs.
The result: performance grows roughly logarithmically with repository count. On the slide’s plot the score rises from about 10.3% at 5 repositories to about 15.1% at 100. Logarithmic growth means each doubling adds about the same amount. From 5 to 100 is log2(20) = 4.32 doublings, so each adds about 4.8 / 4.32 = 1.1 points. Explore that line below.
Choose a view. In Repositories, drag the count. In Filter or size, compare three training sets from the Takeaways slide.
Repositories view: the two end points (about 10.3% at 5 repos, about 15.1% at 100) are read off the SWE-smith plot on slide 67; the line between them is a straight line on a log axis, a model of “roughly logarithmic”, not their data. Filter or size view: the three scores and sizes are from The Verification Horizon, Table 10 (slide 68).
Slide 68 answers the question Chapter 8 left open. Its title: filtering is most valuable when the candidate pool is limited. The numbers are fine-tuning scores for three training sets, from The Verification Horizon’s Table 10. A random sample of 9,139 examples scores 21.61. A filtered set of the same size, 9,139, scores 23.52. The full unfiltered set of 19,050 scores 24.75.
Do the sums. Filtering adds 23.52 − 21.61 = 1.91 points at equal size. Using twice the data, 19,050 / 9,139 = 2.08 times as many, adds 24.75 − 21.61 = 3.14 points over random, and 1.23 over the filtered set. The lecture states the conclusion: filtering beats random at the same size, but the bigger unfiltered set wins. This reconciles LIMI and Orchard.
The reconciling idea is simple. When your pool is small and cannot grow, you cannot buy size, so selection is the lever, and LIMI-style curation pays. When your pool is large and cheap, size is the lever, and Orchard-style scaling pays. The best plan does both: scale diverse sources, and filter out the wrong-signal and no-signal items so the extra data is not a burden.
Symptom: a model that is excellent on its own benchmark breaks when you change the tools or the layout. Measurement: hold out whole environments, not just whole tasks, and compare held-in with held-out. Fix: spread the data across more repositories and environments, and include runs that show mistakes being fixed.
pythondef diverse_pick(trajs, n): # round-robin across repositories buckets = group_by(trajs, key=lambda t: t.repo) # {repo: [trajectories]} picked = [] while len(picked) < n and any(buckets.values()): for repo in list(buckets): if buckets[repo] and len(picked) < n: picked.append(buckets[repo].pop()) # one from each repo per pass return picked
Chapter 10
Keep the numbers, the checklist and the core code from the lecture in one place
The lecture ends on one sentence: making agent data is cheap, and the work is deciding what to keep. Slide 70 sorts that work by the funnel from Chapter 0. For tasks: run each one to check it, keep the ones the model sometimes solves, and refresh the pool as the model improves. For trajectories: a pass can be a cheat, so check how it passed, and failures still teach. For the training mix: curate when data is scarce, and at scale, size and diversity win.
| What | Number | Why it matters |
|---|---|---|
| CWM | 3M trajectories, 10.2k images, 3.15k repos; Jaccard below 0.5; failures kept | Drop near-duplicates, keep failures if the goal is a world model |
| SWE-bench Verified | 1,699 samples, 93 developers; 38.3% underspecified, 61.1% unfair tests, 68.3% dropped | Broken tasks give wrong rewards |
| GPT-4o on SWE-bench | 16% original, 33.2% Verified | Same model, double the score once broken tasks go |
| CodeMidas | 6 containers: 2 must fail, 4 must pass; filtered 3k beats unfiltered 8k | Run it to check it, and test only what the task states |
| DAPO | advantage = (reward − group mean) / group std; all-same group gives 0 | Only mixed groups teach; sample until the batch is full of them |
| LEGO-RL | 36,884 to 21,681 valid to 2,699 kept; 72.7% never solved, 13.4% always solved | Keep tasks solved 1 to 3 times out of 4 |
| LEGO-RL staleness | zero-variation groups 44.7% to 51.4% | The screen goes stale; refresh the pool |
| WebRL | Llama-3.1-8B 4.8% to 42.4%; the 70B model 47.3% | A curriculum grown from failures lifts a small model |
| Verification Horizon | 4.32% use retrieval, 72.34% of those resolve; hacked 28.57% to 0.56%, clean 40.22% to 60.53% | Audit how a run passed; monitor trajectories |
| SWE-Prime | 10% subset beats all successes; relative gains up to 12.2% and 24.2% | Select by process quality, then by segment |
| EEF on WebShop | 62% against RFT 53.6% and GPT-4 35.6% | Salvage the good steps of failed expert runs |
| LIMA and LIMI | 1,000 examples; 78 trajectories beat 10,000 (73.5% against 47.8%) | Curated small sets win, on narrow evidence |
| Orchard | base 22.0%; worst SFT +22; worst strategy +8.2 from 512 to 2,048; spread at 512 is 5.5 | At scale, size beats strategy |
| SWE-smith | 700 trajectories over 4 to 100 repos; growth roughly logarithmic | Spread the same data over more environments |
| Takeaways table | random 21.61, filtered 23.52 (both 9,139), full 24.75 (19,050) | Filter when the pool is limited; scale when it is not |
Slide 69 turns the lecture into five steps. Use them in order on any pile of agent data.
pythondef select_agent_data(candidates, model, env_runner): tasks = [t for t in candidates if keep_task(t)] # Ch 1-2: valid, six-container check tasks = difficulty_screen(tasks, model, tries=4) # Ch 3-4: solved 1 to 3 times of 4 runs = [model.rollout(t) for t in tasks for _ in range(8)] ok = [r for r in runs if r.passed and not audit(r, tests)] # Ch 5: no cheats ok = trim_segments(best_by_process(ok, 0.10)) # Ch 6: process quality, masked steps bad = [nat_example(r) for r in runs if not r.passed] # Ch 7: failures, labeled mix = diverse_pick(ok + bad, n=BUDGET) # Ch 8-9: scale, across many repos return mix # then refresh tasks against the new model
Read it line by line and name the chapter behind each choice. The tasks are checked before the model ever runs on them. The model’s own rollouts then decide which tasks are learnable. Only audited passes feed the imitation set. Failures join under a label. The last line spreads the budget across repositories.
Lecture 11 made the data. This lecture chose from it. The next lecture asks the question that follows every training run: how do we know the agent actually improved? That is evaluation. Chapter 5’s gap between pass rate and clean rate is a small preview of the problem.
This lesson re-teaches Lecture 12 of Stanford CS 329Z: Engineering AI Agents (Fall 2026), taught by Diyi Yang, Michael Ryan and John Yang. The slides PDF and the course site are the primary sources. The readings are Yang et al., SWE-smith (NeurIPS 2025, arXiv 2504.21798), Shankar et al., Who Validates the Validators? (UIST 2024, arXiv 2404.12272) and Zhou et al., LIMA (NeurIPS 2023, arXiv 2305.11206). All figures come from the slides or from the abstracts and sources named here. Toy numbers are labeled illustrative. The explanations, devices and code are our own.
Now press Present or Teach and explain from memory: the three ways data goes bad, the five steps of the checklist, and when more data beats better data. Then go back to the hero and clean the pool again, naming the lecture slide behind each filter.