The same model scores 71.8% on grade-school math when told “think step by step” and 80.2% when told “take a deep breath”. Optimization finds better words, and sometimes better weights, from your data and metric.
Learn when improving an AI system pays off, how to search for better prompts, examples and weights, why agents now do the searching, and how to choose among the methods.
Press each prompt to test it on the same model and the same math problems, or press Let the optimizer search. Watch the best score so far climb as the search tries more words. Then we build, piece by piece, every method the lecture names: few-shot search, MIPROv2, GEPA, SFT, GRPO, on-policy distillation and agents that optimize agents.
You need a rough idea of what a prompt is (the text you send a model) and a little Python for the code. We build the rest from zero.
Based on Lecture 9 of Stanford CS 329Z: Engineering AI Agents (Fall 2026), taught by Diyi Yang, Michael Ryan and John Yang, and its three readings: GEPA, MIPROv2 and DeepSeekMath. Lecture slides. Every idea is re-taught here in our own words and devices; it follows Lecture 5, Frameworks.
The four prompts and their scores are the lecture’s own quick poll (slide 3, from the OPRO paper): the lecture names PaLM 2-L-IT and grade-school math word problems, with scores of 71.8%, 80.2% and 74.5%, plus 34.0% for an empty instruction (the OPRO table, slide 25). The search order here is illustrative: it tries the prompts from the least to the most imaginative.
Chapter 0
See what you need in hand before a search can help, and why a system that already works still has a last mile to cover
Picture an agent that sorts incoming support tickets into five queues. A week ago it was right 82% of the time. You read its mistakes, rewrite the prompt by hand, and run it again. Now it scores 84%. A colleague tweaks one sentence and it drops to 79%. Nobody knows why.
That wobble is the problem this lecture solves. A prompt is the text you send a model. Small changes in that text move the score by many points, and you cannot predict which way. Reading every change by hand is slow, and the score never settles.
The lecture opens with a quick poll to make the point. A model called PaLM 2-L-IT must solve grade-school math problems. Prompt A says “Let’s think step by step” and scores 71.8%. Prompt B says “Take a deep breath and work on this problem step-by-step” and scores 80.2%. Prompt C says “Let’s combine our numerical command and clear thinking to quickly and accurately decipher the answer” and scores 74.5%. You found them at the top of this page. Few people would have guessed B.
Here is the idea. Instead of guessing which words work, you write down how to score an answer, collect some examples, and let a program try many versions and keep the best. The program does the trying. You do the scoring.
That is optimization: a search for a better version of your system, guided by a score. The lecture puts it in one sentence: optimization lets us specify intent through data and evals, and improve our system. An eval is a repeatable test that gives your system a number. Your intent lives in the examples and the test, not only in the prompt text.
The word “system” matters. What you optimize can be the words (context optimization, Chapters 1 to 5), the model’s internal numbers, called its weights (weight optimization, Chapters 6 to 8), or the whole agent harness (Chapter 9). Chapter 10 helps you pick.
The slide draws three pillars, and it says that to optimize an AI system you need all three. The first is data: training examples, rollouts (recorded runs of an agent), demonstrations (examples of the right behavior) and human feedback. The second is the system or model: a single language model, a compound AI system (several model calls wired together), or an agentic system. The third is the evaluation and metric: a pass rate, an exact match, an LLM judge (a model that grades another model’s answer), or a cost and latency figure.
The metric is the compass. A search with no score is a random walk. Try the three pillars below, then try the four scenarios.
Press a pillar to switch it on or off, or pick a scenario. The optimizer in the middle lights up only when all three are present.
Illustrative scenarios of our own, built on the three pillars of slide 8. The rule is the lecture’s: to optimize an AI system you need all three.
Someone always asks: do we still need to fiddle with prompts? Will models not just get better with scale? The lecture’s answer is the last mile. A delivery company moves a parcel across the country cheaply, then loses most of its cost on the final stretch to your door. A general model does the same: it is a great general solution, and it covers the first 99% of the journey. Optimization covers the final mile. Once you know your exact setting, you can adapt to it.
The slide gives four signs that you are ready. You have data and evals that suit your domain. Examples and feedback can state requirements that are hard to write out in a prompt. Sometimes a good eval conveys your intent better than any prose, and you tune the system to the eval. Or the system has many parts that are hard to tune by hand.
It also lists five benefits. Reliability: fewer repeated errors, steadier results. Domain fit: better scores on specialised work. Lower cost and latency: the same quality from a smaller model, a shorter prompt or fewer tool calls. Learning from experience: good runs and failures become lasting gains. Adaptability: the system keeps up when models, tools and tasks change.
One short note on the course. This lecture ran five minutes of conditions, twenty-five on context optimization, twenty-five on weight optimization, ten on agents and ten on which strategy to use. Homework 2 came out the next Monday, the day of a guest lecture. Homework 1 was due the Friday after that, and the midway report the week after. We follow the lecture’s order.
Chapter 1
Learn why shuffling the same examples can swing a score by many points, and how to pick a good order with no answer key
You build a movie-review sorter. The prompt holds four worked examples, each a review and the word “positive” or “negative”. It works on a small test. Then you add the examples in a different order, and the score falls by twenty points. Nothing else changed.
This is a real effect, and the lecture covers it first. Before we fix it, we need the setting.
A few-shot prompt has three parts: a task description, a few examples, and the new input you want answered. The lecture’s slide shows a French translation task. The description says “Translate English to French”. The examples are “sea otter to loutre de mer”, “peppermint to menthe poivrée” and “plush giraffe to girafe peluche”. The last line, “cheese =>”, is the question. The slide credits the GPT-3 paper for this format.
No weights change. The model reads the examples as part of its input, and that alone teaches it the task. We call this in-context learning: learning from the text in the prompt, with no training step. Because the examples are just text, they are something you can search over.
Lu and colleagues (2022) asked a plain question: with the same examples, does the order matter? Yes. Some orders gave near-chance results and others gave near-state-of-the-art results. The slide’s title, “Fantastically Ordered Prompts and Where to Find Them”, is the paper’s own.
You could try every order and score each on a labelled dev set. That costs a lot, and often you have no spare labels. The paper’s trick needs none. It builds a probing set: a pile of inputs the model itself generates, run through each candidate ordering. The slide notes that the ground-truth labels of the probing set are thrown away. Only the model’s own predictions are used.
Why does that work? A bad order often makes the model fall into a rut. It answers “positive” to almost everything. You can see the rut without knowing any right answer, because a healthy classifier gives a mix of answers.
Entropy measures how spread out a set of probabilities is. If one outcome has probability 1, the entropy is 0. If two outcomes split 50 and 50, the entropy is at its largest for two outcomes, 0.693 in natural-log units. The paper uses two kinds.
Work one by hand with four probing reviews. Ordering X labels all four “negative”. Then p(negative) is 1 and p(positive) is 0, so GlobalE is 0. Ordering Y labels two negative and two positive. Then both shares are 0.5, and GlobalE is 0.693. For local entropy, say Y puts 50/50 on every review: each review has entropy 0.693, and the average is 0.693. Say X puts 0.99 and 0.01 on every review: each has entropy 0.056. Ordering Y is the healthy one.
pythonimport math def H(ps): # entropy of one probability list return -sum(p * math.log(p) for p in ps if p > 0) def score_order(order, probe): # probe: model-made inputs, no labels needed probs = [label_probs(order, x) for x in probe] # one model call each: {"pos": 0.5, "neg": 0.5} picks = [max(p, key=p.get) for p in probs] # the label it would answer glob = H([picks.count(v) / len(picks) for v in set(picks)]) local = sum(H(p.values()) for p in probs) / len(probs) return glob + local # our simple sum; the paper uses each entropy as its own score
Now try the search. Each dot below is one ordering of the same four examples.
Each dot is one of 24 orderings. Across is the entropy score you can measure with no answer key. Up is the true accuracy you usually cannot see. Raise the number of orderings you try, then switch how you choose.
Toy data, labelled illustrative: 24 made-up orderings with a seeded random generator, built so that entropy tracks accuracy loosely. It shows the method, not the paper’s numbers. The lecture’s claim is that choosing by probing-set entropy approaches the oracle ordering found by trying every order on a dev set (slide 18).
Two limits are worth knowing. Four examples give 24 orderings, but ten give 3,628,800, so in practice you try a sample. And entropy is a proxy. It spots a model stuck in a rut, not one that is confidently wrong in a balanced way.
The lecture’s point is not this one trick. It is a pattern: treat part of the prompt as a knob, find a score you can measure, and search. The next chapters turn more of the prompt into knobs.
Here is the whole procedure as a budget. Say you have four examples and so 24 orderings. The model writes a probing set of 50 inputs once. For each ordering you make 50 model calls, one per probing input, which is 1,200 calls in all. Each call returns the probabilities of the labels, and from them you get both entropies. No person labels anything. Trying the oracle instead needs the same 1,200 calls plus a labelled dev set to check the answers against.
The symptom of a bad order is a collapse: the model says “positive” to nearly every review. You measure it by counting the predicted labels on the probing set. The fix is to choose the ordering whose predictions spread out and whose per-review doubt stays alive. Always confirm the final pick on a small labelled sample when you have one, because entropy is a proxy and a proxy can be fooled.
Chapter 2
Let the model write its own worked examples, keep the ones that pass your metric, and use them as the few-shot examples
You have 200 math word problems with answers, and nothing else. Your sorter does best when its examples show the working: “Roger starts with 5 balls, buys 2 cans of 3, so 5 + 6 = 11.” But your data says only “11”. Nobody wrote the working, and writing 200 of them by hand is slow.
The lecture’s idea in plain words: ask the model to write the working itself, check the final answer against the data, and keep only the working that led to a right answer.
Chain-of-thought (CoT) prompting asks the model to write its reasoning steps before the answer. The slide shows the classic pair. Standard prompting answers the tennis-ball question with “27” and is wrong. CoT prompting writes “Roger started with 5 balls. 2 cans of 3 tennis balls each is 6 tennis balls. 5 + 6 = 11” and is right. The lecture says the catch: labelled examples for few-shot use often do not come with reasoning.
Zelikman and colleagues (2022) fill the gap with rejection sampling: draw many samples, keep the ones that pass a test, and throw the rest away. Their method is called STaR, short for Self-Taught Reasoner. The loop on the slide has four steps.
The cost of step 4 is that STaR changes weights. That brings us to the lecture’s next slide.
Khattab and colleagues (2023) built DSPy, a framework that treats a language-model program as something to compile. You may remember it from Lecture 5. Its bootstrap step reuses the STaR filter, and it does not finetune. As the slide puts it: we do not even need to finetune; just rejection-sample successful reasoning.
Here is the data flow. A trace is the record of one run of your program: the input, each model call, the reasoning, and the output. For each training input, DSPy runs the program. It passes the output to your metric, a function that returns a score. A good score keeps the trace. A bad score discards it. The kept traces become few-shot demonstrations in the prompt.
pythondef metric(example, pred): # your score: here, exact match on the answer return pred.answer.strip() == example.answer demos = [] for ex in trainset: pred = program(question=ex.question) # {"rationale": "Roger starts with 5...", "answer": "11"} if metric(ex, pred): demos.append((ex.question, pred.rationale, pred.answer)) # keep this trace # else: discard it
One more step makes it work. Different sets of demos give different scores, as Chapter 1 showed. So DSPy builds several candidate sets, then tries combinations on the dev set and keeps the best. That is a random search: pick combinations at random, score each, keep the winner. The slide’s diagram shows three candidate programs scoring 32%, 16% and 54%, and the 54% one wins.
Run the filter yourself. Six training questions have different difficulty. Choose how many attempts each question gets.
Each row is a training question. Each square is one attempt: green passes the metric and is kept, red is discarded. A purple square is an attempt that got the correct answer as a hint. Change the attempts, switch the hint, and press Run again.
Illustrative: the six questions, their chance of a right answer on one attempt (90%, 80%, 60%, 50%, 30%, 15%) and the +35 point lift from a hint are our own numbers. The expected count uses the exact formula 1 − (1 − p)k. Draws are random in your browser.
Two things stand out. More attempts rescue the medium questions, but the hardest question stays out of reach, so your demos lean toward easier problems. The hint rescues some of those hard ones, at a price: the rationale was written knowing the answer, so it can explain the answer without really reasoning toward it.
The slide credits this table to the DSPy paper: GSM8K math word problems, with two models. Test scores for the paper’s own rows are in the table.
| Program and compile step | GPT-3.5 test | Llama2-13b-chat test |
|---|---|---|
| Plain prompt, no compiling | 25.2 | 9.4 |
| Plain prompt, bootstrapped twice | 61.7 | 36.5 |
| CoT, few-shot with human-written reasoning | 72.4 | 33.7 |
| CoT, bootstrapped | 72.9 | not reported |
The slide’s conclusion: bootstrapping reasoning or outputs, and then randomly searching on the training set, can beat providing human reasoning or gold labels. On GPT-3.5 the bootstrapped CoT program (72.9) edges out the human-written one (72.4). The humans did not have to write anything.
Bootstrapping has a built-in bias. The questions the model already solves produce passing traces, and the questions it cannot solve produce none. So the kept demonstrations lean toward easy problems. The symptom is a demo set where every example looks alike and the hard cases are missing. You measure it by recording the solve rate of every training question and plotting how the kept traces spread across that range.
There are three fixes. Allow more attempts, which the device above lets you do. Add a hint after a miss, as STaR does, and accept the risk that the rationale was written knowing the answer. Or write a stricter metric that checks the steps and not just the final number. In the table, “bootstrapped twice” means a second round that starts from the first round’s better program, which pulls in harder questions.
Chapter 3
Show a model its past prompts with their scores and ask it to write a better one, then see why the best word was “breath”
Imagine you ask a sharp colleague to improve your prompt. You do not just say “make it better”. You hand over a sheet: the last eight prompts you tried, each with its score, lowest first. Then you ask for a ninth that beats them all. A good colleague reads the pattern and writes something new.
That is the whole of the lecture’s next section, which it calls reflective optimization: the system looks at what happened, thinks about it, and changes itself. The first method is OPRO.
Yang and colleagues (2024) wrote “Large Language Models as Optimizers”. The slide’s summary is short: allow the LLM to see past instructions and how performant they were, then ask the LLM to write a new instruction. The text you send to make that happen is the meta-prompt. It is a prompt about prompts. It holds four pieces.
Two models are in play, and it helps to keep their names apart. The optimizer is the model that reads the meta-prompt and writes new instructions. The scorer is the model that actually does the task under each new instruction, so that the score is measured and not guessed. The table on the lecture’s slide has a caption saying that all results use the pre-trained PaLM 2-L as the scorer, while the optimizer changes from row to row.
Each round has four steps. First, build the meta-prompt from the history. Second, ask the optimizer for one or more new instructions. Third, run the scorer on the training problems with each new instruction and get a score. Fourth, add the new pairs to the history and go again. After a set number of rounds you pick the instruction with the best score.
A worked example makes the data flow plain. Say the history holds two entries: the empty instruction at 34.0 and “Let’s think step by step.” at 71.8. The meta-prompt is about 120 tokens (illustrative). The optimizer writes “Break this down.” The scorer runs 100 problems and gets 79 right. The new pair enters the history at 79.0, and the next meta-prompt lists three entries, with “Break this down.” last. Try it below.
The box shows the exact meta-prompt the optimizer would read, lowest score first. Press Ask for a new instruction. The optimizer replies, the scorer tests it, and the pair joins the history.
The instructions and scores are the rows of the OPRO table on slide 25 (empty 34.0, step by step 71.8, “Break this down.” 79.9, arithmetic 78.5, numerical command 74.5, deep breath 80.2). In the paper each came from a different optimizer model, so lining them up as one run is our illustration. The meta-prompt wording is a faithful sketch, not the paper’s exact text.
Notice the last line of the history is always the best so far. The optimizer reads the pattern and nudges it. It does not search blindly: each proposal is conditioned on every earlier proposal and its number.
The slide’s table is striking. The human baselines are “Let’s think step by step.” at 71.8, a longer human phrase at 58.8, and the empty string at 34.0. The optimizer-written rows are higher. With PaLM 2-L-IT as the optimizer, the winner is “Take a deep breath and work on this problem step-by-step.” at 80.2. With PaLM 2-L, it is the three words “Break this down.” at 79.9. With gpt-3.5-turbo it scored 78.5, and with gpt-4 it scored 74.5. The slide’s comment: it identifies interesting strategies like “Take a deep breath…”.
Why would a deep breath help a model that never breathes? Nobody knows for sure. The honest reading is that a prompt works through the text patterns the model saw in training, and a human cannot guess those patterns. A search can find them. That is exactly why we measure.
The symptom: the best instruction scores 80 on the problems the optimizer used, and 74 on new ones. The measurement: hold back a test set the loop never sees, and compare the two scores at the end. The fix: pick on a separate dev set, report on the test set, and keep the history short so the meta-prompt does not fill with near-duplicates. The slide’s accuracies are labelled “test” for this reason.
Count the model calls in one round. The optimizer is called once, or a few times if it proposes several candidates, and each call reads a meta-prompt of a few hundred tokens. Then every candidate must be scored. If the dev set has 100 problems and you test 8 candidates, the scorer runs 800 times. So the scorer, not the optimizer, is where the bill grows. That is why OPRO keeps its history short and why a small dev set speeds the loop.
To get varied candidates, the optimizer is sampled with some randomness. If you decode it greedily, it tends to repeat its last idea, and the history fills with near-copies. A little temperature, which Lecture 2 explained, gives new wording each time. The scores then decide which new wording stays.
Chapter 4
Build an optimizer from the last three chapters: write candidate instructions, collect demonstrations, and search the pairs with a score
You now hold three tools. Chapter 1 searched the order of examples. Chapter 2 made examples from the model’s own passing runs. Chapter 3 had a model write instructions. A real program has several model calls, and each call needs its own instruction and its own examples. Trying every pair by hand is hopeless.
MIPROv2 is the lecture’s answer. Opsahl-Ong and colleagues (2024) named it from Multiprompt Instruction PRoposal Optimizer; the reading’s title is “Optimizing Instructions and Demonstrations for Multi-Stage Language Model Programs”. It has three stages, and the slide lists them: bootstrap demonstrations, propose instructions based on reflection, and search the combinations. The lecture walks one tiny example through all three. A program called classify_iris takes four flower measurements and returns one of three species.
This is Chapter 2 again. Run each training example through the program several times. Score each run with the metric. Keep the passing traces as candidate demonstrations, and discard the rest. The slide steps it frame by frame: training input in, the program runs, the metric scores the output, and a poor score means the trace is thrown out.
One kept trace looks like this: petal_length: "1.4", petal_width: "0.2", sepal_length: "4.6", sepal_width: "3.2", then a rationale that reads “Let’s think step by step in order to predict the iris species. We know that the petal length is 1.4 cm, which is relatively short…” and ends with answer: "setosa". Run it many times and you get many such traces. MIPROv2 groups them into several demo sets, each a small bundle of traces.
Now we need instructions. Chapter 3 asked a model to write them. MIPROv2 asks a model too, but first it gives that model facts about your task. The lecture calls this grounding: tying a proposal to real details so it is not a guess. The proposer is the model that writes the candidates. It reads four things.
Because the tip changes from call to call, the same grounding gives different candidates. Build the proposer’s input below.
Switch the four grounding inputs on or off. The box shows what the proposer model would read. Pick a tip to see which style of instruction it asks for.
The summaries and the four tips are quoted or closely paraphrased from slides 36 to 47. The three example instructions are the lecture’s; the match between a tip and a candidate is our own illustration, since in practice the proposer varies its output run to run. Token counts are rough estimates, labelled illustrative.
The slide shows three proposals. One says: given the measurements, predict the species and give step-by-step reasoning. Another says: predict the species to save a critically endangered species from extinction. The third frames it as a rare iris on the brink of extinction. Two of the three came from the high-stakes tip. They look silly. Whether they work is a question for Stage 3.
Now you hold N instructions and N demo sets. Each pair is a complete program. Scoring every pair on the full training set is too slow. MIPROv2 uses the surrogate idea: keep a running belief about how good each instruction and each demo set is, and use the belief to pick which pair to test next. The lecture says a Bayesian surrogate model keeps these beliefs. The slide draws them as a green and red slider beside each item.
One round has five steps, copied from the slide’s frames. Sample one instruction and one demo set, guided by the beliefs. Slot them into the program. Draw a minibatch, a small random slice of the training data. Run the minibatch through the program and score it. Update the beliefs from the result. Repeat for the chosen number of rounds, called num_batches, with a full evaluation on all the data every few rounds as a check.
The minibatch is the cost saver. Scoring 25 examples per round for 30 rounds is 750 program runs (illustrative), far fewer than scoring every pair on every example.
Left bars are the beliefs about four instructions, right bars about four demo sets. Press One round to sample a pair, score a minibatch and update. Watch the beliefs sharpen.
Toy simulation, labelled illustrative: the true quality of each instruction and demo set is hidden and made up, a minibatch has 20 examples, and beliefs are running averages with an exploration bonus (a simple stand-in for MIPROv2’s Bayesian surrogate). The five-step round is the slide’s.
The output is one optimized module: an instruction and a set of demonstrations. The slide’s final example uses the high-stakes iris instruction plus one kept setosa trace. In code, the whole thing is three lines.
pythonimport dspy opt = dspy.MIPROv2(metric=metric, auto="light") # the three stages run inside compile() tuned = opt.compile(program, trainset=trainset) # a program with a new instruction and demos tuned.save("classify_iris.json") # the whole result is plain text
Failure mode. Symptom: the winning instruction is odd, such as the extinction story, and you wonder if it will hold up. Measurement: score the tuned program on a held-out test set that the search never touched. Fix: if the test score falls well below the search score, enlarge the training set, or write a stricter metric. The lecture’s later table shows MIPROv2 gains, next to GEPA, in Chapter 5.
Chapter 5
Feed the optimizer words about the failure, not only a number, and keep a pool of prompts that each win somewhere
A score of 0.4 tells you the prompt is weak. It does not tell you why. Suppose your assistant leaks a customer’s home town to an outside service. A number says “bad”. A sentence says “the rewrite kept the name of the town”. The sentence tells the optimizer exactly what to fix.
The last two methods in the context section use this idea. Both let a model reflect on a run and write down what went wrong, in plain words.
In ordinary training, a gradient is a number that says which way to nudge each weight to reduce the error. It flows backward from the loss through every layer. Yuksekgonul and colleagues (2024) ask: can we do the same with words? The slide’s summary: have an LLM reflect on what can be improved about an output, and propagate that feedback back through the prompts in the system.
Picture a pipeline of three model calls. The final answer is wrong. A critic model reads the answer and writes: “This response skips the units.” That sentence is a textual gradient for the final call. A second critic reads that call’s prompt plus the feedback, and writes what to change in the prompt of the call before it. The note travels backward, one stage at a time, as text. At each stage an LLM then rewrites the prompt using the note. The slide’s diagram shows a prompt at accuracy 77.8% rewritten to 91.9% after such passes.
GEPA, the first reading, adds two things to reflection. Agrawal and colleagues named it Genetic-Pareto. First, it keeps a pool of many prompts, not one. Second, it chooses which prompt to improve using a Pareto frontier.
The Pareto idea is simple. Say you have five prompts and six test tasks. One prompt has the best average. Another has a lower average but is the best on task 3, because it holds a rule the others lack. If you keep only the best average, you lose that rule. A prompt is on the Pareto frontier if no other prompt beats it on every task. GEPA keeps the winners of each task, and picks a parent in proportion to how many tasks it wins.
Each row is a prompt, each column a task, each cell a score. Outlined cells are the best score on that task. Choose a rule for picking the parent, then press Add a child: it copies the parent and repairs its weakest task.
Toy scores of our own (illustrative), not the paper’s. The rule is GEPA’s: candidates that hold the best score on at least one task stay on the frontier, and the parent is drawn in proportion to the number of tasks a candidate wins. A child here gains 18 points on the parent’s weakest task and shifts the others by a few points.
The slide’s diagram has these steps. Pick a parent from the filtered pool. Run it on a small minibatch and keep the full traces, meaning every prompt, tool call and output. Ask a reflection model to read the traces and the metric’s feedback, and to write a new prompt: a mutation. Or take two candidates that are strong in different places and combine their best parts: a merge. Test the child on the minibatch. If it does not improve, discard it. If it does, score it on every task and add it to the pool. Repeat until the budget of model calls runs out.
The lecture works an example from PAPILLON, a privacy system. Two prompts run in a row. The first, the prompt creator, rewrites a private user question into a version that is safe to send to a powerful outside model. The second, the information aggregator, takes the outside answer and the original question and writes the final reply. The baseline prompts are two short sentences. Along the evolved branches, the prompts grow into long, specific instructions: how to find private details, what to replace them with, and how to keep the answer useful.
The slide’s table uses GPT-4.1 Mini on six tasks. The last two columns are the average across tasks and the gain over the baseline. Choose a task to see every method.
Press a column of the lecture’s table. Bars show the score of each method on it.
Numbers are the table on slide 68, from the GEPA paper: GPT-4.1 Mini, scores in percent. The same table reports a smaller model, Qwen3-8B, as the optimizer and GPT-4.1 Mini as the target: 62.03 on average, +9.00 over the baseline.
A GEPA row holds the best score on every column. Plain GEPA leads on HotpotQA (69.00), and GEPA with merge leads on IFBench, Hover and PUPA. Both tie on AIME-2025 and LiveBench-Math. The best average is 66.36 for GEPA with merge, a gain of 13.33 over the baseline. The slide says it plainly: reflective prompt evolution with GEPA outperforms the baselines across tasks. The GEPA paper’s title goes further and says it can outperform reinforcement learning, which Chapter 10 returns to.
Failure mode. Symptom: evolved prompts keep growing, with long lists of rules that slow every call. Measurement: track prompt tokens and the score on held-out tasks together. Fix: use merge to combine, prune rules that never matter, and stop when the held-out score stops rising.
Chapter 6
Move from changing the words around the model to changing the model, by copying a strong teacher’s agent runs into a student
Chapters 1 to 5 never touched the model. Every gain came from the text you sent in. That is cheap and fast, but the model still reads each long prompt on every call, and a small model may not follow a long prompt well. The lecture’s next section changes the weights, the millions of numbers inside the model that decide what it writes.
The first method is the oldest: show the model good examples and make it copy them. That is supervised finetuning, or SFT.
The lecture reminds us of the training loss from Lecture 2. A language model gives a probability to every token in its vocabulary. The cross-entropy loss looks only at the probability the model gave to the token that really came next. The less probability it gave, the bigger the loss.
Because y is 0 for every token but one, the sum has a single live term: minus the log of the probability of the right token. A worked case: the model gave the true next token a probability of 0.25. The loss is −ln(0.25) = 1.39. After training it gives 0.80, and the loss is 0.22. SFT does this for every token of every example. Instruction finetuning, the slide’s other recall, is exactly this loss on instruction and answer pairs, including chain-of-thought pairs and tasks the model never saw.
An agent’s work is a long run of steps, so an example is a long run too. The slide gives the recipe in four lines. Roll out a teacher, a strong model, on agent tasks. Post-train a student, a smaller model, on the tasks the teacher completed. Focus on diversity of tasks and environments. The student then learns task execution.
A rollout is one complete recorded run: the task, each thought, each tool call, each tool result, and the end. Its data shape is a list of messages, which the trainer flattens into one long token sequence. The loss usually counts only the tokens the agent wrote, not the tool results it was handed.
The slide adds one more step: it is also possible to verify the output somehow and train with rejection sampling. That is Chapter 2’s filter again, now keeping whole runs. Try it. Two rollouts are in the pool: one passes its check, one fails.
Bars show how likely the student is to write each action token. Raise the training steps and watch the likelihoods climb. Then switch the filter off, so the failed rollout trains the student too.
Toy numbers of our own (illustrative): each token starts at a made-up probability and moves toward 1 as the loss is minimized, p(step) = 1 − (1 − p0) e−step/8. The loss shown is the average of −ln p over the tokens that are in the training set. The lesson, not the speed, is the point.
With the filter on, only the passing rollout trains. The student’s average loss drops and the passing tokens grow likely. With the filter off, the failing rollout’s tokens grow likely too, including the bad command. A student copies what it is shown. The checker is part of your training data, and every hole in it becomes a habit.
Raoof and colleagues (2026) built a full recipe, and the lecture promises more in the agent data lectures. The slide shows six stages: source tasks, mix tasks, filter tasks, generate rollouts with the teacher, filter rollouts, and the final recipe. Their finetuned model scores strongly on Terminal-Bench 2.0 and on a 100-task subset of SWE-bench Verified, and the curves rise with dataset size from about 316 examples up to 100,000. The slide’s own summary: finetuning on rollouts from a strong teacher helps.
Chen and colleagues (2023) tried the idea early. They collected rollouts from GPT-4 using several reasoning styles: plain chain of thought, ReAct (think, act, observe, repeat) and Reflexion (try again after a self-critique). They finetuned Llama-2 models on the mixed set. At test time the student picks its own style. The table below uses the slide’s numbers: exact-match score (EM).
Switch between each model prompted as a ReAct agent and the same model after finetuning on GPT-4 rollouts. The dashed line is prompted GPT-3.5.
Numbers are table 2 of the FireAct paper as shown on slide 79. The slide’s claim: finetuning Llama2-13B on GPT-4 rollouts makes it a better agent than prompted GPT-3.5.
Failure mode. Symptom: the student does well on tasks like the teacher’s and falls apart on new ones. Measurement: test on tasks and environments absent from the training set. Fix: widen the variety of tasks, as the slide says, before you add more of the same.
Two choices decide how an SFT run goes. The first is the loss mask: the trainer counts only the tokens the agent wrote. Say a rollout has 600 tokens, of which 400 are the agent’s thoughts and tool calls and 200 are tool results. The loss averages over 400 tokens, so the student is not trained to imitate a file listing that the environment produced.
The second is the spread of tasks. A thousand rollouts of one task teach one task. A hundred rollouts across ten environments teach the student how to handle new ones, which is why the slide tells you to focus on diversity. When a score stalls, ask whether you need more rollouts or more kinds of rollout. Usually it is more kinds.
Chapter 7
Let the student try tasks itself, reward the ones it completes, and see why GRPO needs fewer models than PPO
SFT copies a teacher, so the student cannot easily pass the teacher. Think of a chess coach who only lets you replay his games. You learn his style and nothing beyond it. Now think of a coach who watches your games and tells you which moves led to wins. That is a different kind of learning, and it can go further.
That second kind is reinforcement learning (RL): the model acts, an outside check scores the result, and the weights move toward the actions that scored well. The lecture’s recipe for agents has four lines. Roll out the student on agent tasks. Reward it for completing the task. Vary the environments and the task difficulty. And verifiability is key.
A verifier is a check that says, without a human, whether a task was done. The slide shows a terminal task: find the files whose names end in .example.com, then save the output. An external reward verifies if the task was completed: a script compares the output file with the expected one and returns 1 or 0. Run the student several times inside a group, and several groups to a batch.
The classic method is PPO, proximal policy optimization. The slide labels its parts. The policy model is the student being trained. It generates an output o for a question q. A reference model is a frozen copy of the starting student; the KL term, a measure of how far two models’ outputs have drifted apart, keeps the student near it. A reward model scores the whole output with one number. A value model guesses, for each token, how good the future looks from there. Then GAE, the generalized advantage estimate, combines rewards and values to say how useful each token was compared with other choices.
The lecture counts the cost in three lines: four models to keep in memory, two models to train every step, and several expensive per-token steps. Every one of those is a bill.
DeepSeekMath (the third reading) introduced GRPO, group relative policy optimization. The idea in plain words: instead of training a model to guess how good a token is, sample a group of answers to the same question, score them all, and call an answer good if it beat the group’s average.
The slide’s counts flip. Three models in memory, and the reward model need not be a model at all, since a verifier script works. One model to train every step. And only the KL term is per token; everything else is per whole answer.
The advantage says how much better than usual an answer was. GRPO computes it as a z-score within the group: subtract the group’s mean reward, divide by its standard deviation.
Work it with G = 8 and a 1 or 0 reward. Four answers are right, so the mean is 0.5 and the standard deviation is 0.5. A right answer gets (1 − 0.5) / 0.5 = +1. A wrong one gets (0 − 0.5) / 0.5 = −1. Now say only one of eight is right. The mean is 0.125 and the standard deviation is 0.331. The right answer gets +2.65, a big push, and each wrong one gets −0.38, a small shove.
Each tile is one rollout of the same question. Set how many are truly correct, then switch on a sloppy check that also pays hedged answers. Bars show each rollout’s advantage.
Illustrative group of eight with a 1 or 0 reward. The advantage uses the exact formula above, with the population standard deviation; code adds a tiny constant so a group with equal rewards gives 0 instead of a divide by zero. The sloppy check treats up to two wrong answers as hedges that contain the right number and pay them 1.
Two lessons sit in that device. First, if all eight succeed or all eight fail, every advantage is 0 and the group teaches nothing. A question the model always solves, or never solves, gives no signal, which is why the slide says to vary task complexity. Second, a sloppy verifier pays a hedge like “it is $12 or $18” the same as a real answer, and the model learns to hedge. The check is part of your training data.
The slide ends with the whole GRPO objective and labels each piece. We read it in words. Take an expectation (an average) over questions from your dataset and over groups of sampled answers. Average over the group, then over the tokens in each response. For each token compute a ratio: how likely the new policy makes this token, divided by how likely the old policy did. Multiply the ratio by the advantage, and clip the ratio to the range 1 − ε to 1 + ε, so that no single token gets over-updated. Subtract the KL penalty, scaled by β, to keep the policy from drifting far from the reference.
Switch between PPO and GRPO. Boxes marked trained change every step. Frozen boxes only sit in memory.
The model list and the counts (four held and two trained for PPO, three held and one trained for GRPO) are slide 84 to 91. The memory line assumes every model has the same size N, which is illustrative; in GRPO the reward “model” can be a verifier script and cost no weights at all.
The slide closes with the real-world case: DeepSeek-R1 trained with GRPO, and a plot of PPO against GRPO on the MATH task over about 2,500 steps, where GRPO ends above both PPO settings. A short code sketch of the core:
pythondef group_advantages(rewards, eps=1e-6): mu = sum(rewards) / len(rewards) sd = (sum((r - mu) ** 2 for r in rewards) / len(rewards)) ** 0.5 return [(r - mu) / (sd + eps) for r in rewards] # all 0 if every reward is equal # one answer, one token: ratio = new_prob / old_prob def token_term(ratio, adv, eps=0.2): return min(ratio * adv, max(min(ratio, 1 + eps), 1 - eps) * adv)
Chapter 8
Combine the strong points of SFT and RL: the student writes its own answers, and a teacher grades every token
Back to chess. The lecture’s slide says it is handy to get chess coaching on a game you actually played, rather than a game you just observed. A coach who reviews your own game can point at move 14 and say “that was the mistake”. A coach who shows you a master’s game cannot. Neither is as slow as winning or losing the game and hearing only the final score.
This chapter builds the third weight method from that picture. It comes from a blog post by Thinking Machines on on-policy distillation, which the slides cite throughout.
Ask two things of any training method. First: whose words does the student train on? If they are the teacher’s, the method is off-policy. If the student writes them itself, it is on-policy. (A policy is the model’s way of choosing what to write.) Second: how often does the student hear feedback? One score at the end is a sparse signal. A signal on every token is dense.
| Method | Whose words | Signal |
|---|---|---|
| Supervised finetuning | off-policy (teacher’s) | dense |
| Reinforcement learning | on-policy (student’s) | sparse |
| On-policy distillation | on-policy (student’s) | dense |
The slide’s table is this grid. SFT is dense but off-policy: the student never sees its own mistakes. RL is on-policy but sparse: one number at the end, spread over a thousand tokens. On-policy distillation takes the good half of each.
The slide uses the question “What is 5 + (2 × 3)?” and shows how each method treats it.
SFT. The teacher’s answer is “2 × 3 equals 6, add 5 to get 11.” The student is shown, for each teacher token, the probability it would have given that token. Where the student gave a low probability, the loss is high.
RL. The student writes its own answer: “5 + 2 is 7 and 7 × 3 is 21.” A grader checks the final number against 11 and returns reward 0. That one 0 is all the student hears. It does not know which token was the mistake.
On-policy distillation. The student writes the same wrong answer. Now the teacher reads it token by token and says how likely the teacher would be to write each token at that spot. A token the teacher finds unlikely is a mistake. Try all three.
Choose a method. Each bar is the training signal that lands on one token. Taller means a stronger push.
Illustrative probabilities of our own, shaped like the lecture’s slide 96 example (“What is 5 + (2 × 3)?”). The student and teacher probabilities per token are made up so that the early “2” and the final “21” stand out. The signal for SFT is −ln pstudent on the teacher’s tokens; for RL the same reward on every token; for on-policy distillation ln pstudent − ln pteacher on the student’s own tokens.
Take the slide’s example in numbers (illustrative). At the final token “21” the student gives 0.50 and the teacher 0.02. The difference of logs is ln(0.50) − ln(0.02) = −0.69 − (−3.91) = 3.22. At the token “7” after “is”, both give about 0.8 or 0.99, so the difference is near 0. The big numbers land on the tokens where the student and teacher disagree. That is dense, token-level blame, with no human label, and the student wrote the tokens itself.
The data flow: sample a response from the student; run the teacher once over the same text to read off its log probabilities; subtract; train the student to shrink the sum. The teacher never writes anything. It only grades.
The lecture uses the Qwen3 family. The flagship models go through four stages: long chain-of-thought cold start, reasoning RL, thinking-mode fusion, and general RL. The lightweight models (from 30B-A3B down to 0.6B) use strong-to-weak distillation from the flagships. The slide then compares ways of improving a student, as measured on the math test AIME’24 and the science test GPQA-Diamond.
Choose a measure. The first row is a student trained by off-policy distillation. The next two rows add a final stage on top of it.
Numbers are slide 103, from Table 21 of the Qwen3 technical report as shown on the slide. GPU hours for plain off-policy distillation are unreported there, so that bar is missing on the cost view. The slide’s conclusion: on-policy distillation was more efficient and produced better models than RL.
On AIME’24 the RL stage lifts the student from 55.0 to 67.6, and the on-policy distillation stage lifts it to 74.4. The RL run used 17,920 GPU hours; the on-policy distillation run used 1,800, about ten times fewer. The cost comes from density: one teacher pass gives a signal on every token, where RL must sample many full answers to learn from one reward each.
Failure mode. Symptom: the student matches the teacher on the teacher’s kind of questions and fails on others. Measurement: score on prompts the teacher never graded. Fix: grade a diverse prompt set, and remember a student cannot learn what the teacher itself does poorly.
The teacher never has to write. It reads the student’s finished response once, in a single pass, and returns a log probability for every token. That is one forward pass over the text, the same cost as scoring it. RL, by contrast, must sample many full answers and wait for a verifier before it hears anything.
The loss also has a gentle bias, worth knowing by name. Because the average runs over the student’s samples, the student is pushed away from tokens the teacher finds unlikely, and not pushed to cover everything the teacher might say. Researchers call this reverse KL. It tends to make a student commit to one good habit of the teacher, which suits a task with a clear right answer.
Chapter 9
Hand the search itself to an agent that can read logs, edit code and run experiments, and see why the metric now needs the most care
Every method so far has a fixed shape. MIPROv2 edits two things, an instruction and a demo set. GEPA edits prompts. GRPO edits weights. A person designed the search, and the search follows the design.
Now give the job to an agent. It can read files, run code, look at results and decide what to try next. What can it optimize? The lecture’s answer is nearly anything that runs on software. This part has three examples and one warning.
Zhang and colleagues (2026 on the slide; arXiv 2505.22954) built a coding agent that edits its own code. The loop on the slide has four moves. Select a parent agent from an archive, a growing library of every agent version so far. Self-modify: the parent reads a task about its own repository and writes a change to itself, which makes a child. Evaluate the child on a coding benchmark. Add the child to the archive.
The rule for picking a parent is the clever part. The slide says: select parents to self-modify proportionally to performance and inversely proportional to the number of children. A good agent is likely to be picked. An agent that already has many children is picked less, so the search does not pour all its effort into one branch. Even a modest agent keeps a chance, because a weak ancestor may lead somewhere new.
Each dot is an agent: across is the order it was made, up is its benchmark score. Lines join a child to its parent. Choose how parents are picked and press Self-modify.
Toy simulation (illustrative): a child’s score is its parent’s plus a random change that is slightly positive on average; the parent weight is (score − 0.1)2 divided by (1 + children). The lecture’s finding is that both self-improvement and open-ended exploration were critical (slide 109); the real runs rise from about 20% to about 50% on SWE-bench over 80 iterations.
The slide’s ablations back the design. Take away self-improvement, so that a fixed meta-agent writes the changes and the parent does not, and the curve flattens. Take away open-ended exploration, so that each step builds only on the latest agent, and it flattens too. The lecture’s sentence: both the self-improvement (the parent modifies itself rather than a meta-agent) and the exploration (returning to prior parents instead of always building on the latest) were critical.
Recall from Lecture 5 that a harness is the code around the model: the loop, the tools, the memory, the prompts. Meta-Harness (arXiv 2603.28052) asks an agent to improve a harness. Its three steps: the meta agent reads a filesystem of all prior experience and proposes new harness code; the new harness plus an LLM is evaluated on tasks; every log goes back to the filesystem. The slide’s point is in the word “all”: allow a meta agent to see all prior experience and decide what to edit next. Over time the agent builds better and better harnesses for domain-targeted problems, and the slide’s bar chart on Terminal-Bench 2 shows the optimized harness above the human-written ones.
The last example is the simplest and the most general, from Andrej Karpathy’s autoresearch repository. Give an agent access to a repository. Let it brainstorm and write a change. Run the experiment. If the metric improves, build on it. Otherwise, reset. Log the findings. The loop is a ratchet: progress can be kept, and a failed try costs only the time it took.
The prompt on the slide spells the loop out. Look at the git state. Tune train.py with an idea. Commit. Run it. Read the result with grep. If the run crashed, read the stack trace and try to fix it. Record the numbers in a results file. If the validation metric (bits per byte, lower is better) improved, keep the commit and advance the branch. If it is equal or worse, git reset back. The last line tells the agent never to stop, so a person can leave it running overnight. The slide’s chart title reads: 83 experiments, 15 kept improvements.
pythonbest = run("train.py") # baseline metric, lower is better while budget_left(): idea = agent.propose(repo, results_log) # reads every earlier try and its number apply(idea); git("commit") score = run("train.py") log(idea, score) if score < best: best = score # keep: the branch advances else: git("reset --hard HEAD~1") # revert: the try is gone, the log stays
Each dot is one experiment on a measured metric (lower is better). Green dots were kept, faint dots were reverted. The blue line is the true score on data the loop never sees. Then switch on a leaky metric.
Toy simulation (illustrative): most ideas change the true score by a small random amount that is a little worse than zero on average; the leaky metric lets 15% of ideas “cheat”, improving the measured number by a large step while the true score stays flat. The real run on slide 115 kept 15 of 83 experiments.
Run it with the leaky metric on. The measured score keeps falling, and the true score stalls. The agent is a capable optimizer, and a capable optimizer finds every hole in what you measure. The slide’s summary says the same: agents are relatively capable optimizers; set them up in an environment where they can log results, ideate and execute, and they are pretty good at optimizing anything that runs on software. And then: the metric and evals become the most critical part to control.
Failure mode. Symptom: the measured metric climbs while users say nothing improved. Measurement: keep a hidden held-out test, and read the logs of the kept changes. Fix: limit what the agent may edit, stop it from touching the eval, and refresh the held-out set.
One practical rule runs through all three examples. The agent is writing and running code, so run it where a mistake cannot hurt you. Use a sandbox with no access to your keys, your production data or the network beyond what the task needs. Keep every change in version control, so any step can be undone, and keep the logs, so you can read why a change was kept.
The same rule covers the evals. Put the final test where the agent cannot edit it, and run it yourself. An agent that can change the scoring script has found the shortest path to a high score. That is not a failure of the agent. It is the metric doing what you asked.
Chapter 10
Weigh sample cost, access, speed and prompt length, and see when words, weights, or both in turn are the right move
You now know a dozen methods. A teammate asks: “so which one do we run on Monday?” The lecture gives a short, practical answer, built from two facts and two lists of reasons.
A sample, here, is one run of your system that you pay for: a rollout, an example, a model call. The first fact is that prompt optimization is much more sample-efficient than RL. The slide shows GEPA against GRPO on two tasks, HotpotQA and IFBench, using the 8 billion parameter Qwen3 model, with the score on the vertical axis and the number of rollouts, up to 25,000, across. GEPA’s curve shoots up within the first few thousand rollouts. GRPO climbs slowly and is still below it at the right edge. The GEPA paper’s abstract puts the gap at up to 35 times fewer rollouts.
The reason is the signal. A GRPO update learns from a number per rollout. A GEPA update reads a whole trace and a sentence of feedback, so each rollout carries far more information about what to change.
The second fact comes from OpenThoughts-Agent. Weight optimization is more data hungry, but it can grow effectively with thousands and thousands of examples. Its curves in Chapter 6 kept rising from 316 examples to 100,000. A prompt can hold only so much. A set of weights can absorb far more.
Together the facts give the shape below: words win at small budgets and flatten, and weights start slow and keep climbing. Move the budget and see which side is ahead.
Drag the budget of samples (rollouts or examples). The warm curve is context optimization, the pink curve weight optimization. The vertical line is your budget.
Illustrative shapes, not data. They follow the two facts: context optimization rises fast and flattens (slide 119), weight optimization starts low and keeps growing with thousands of examples (slide 120). The score scale and the crossing point are made up; in your own system the crossing depends on the task and the model.
The slide gives three. The model is behind an API. Some strong models do not offer finetuning access, so words are your only knob. You need to rerun often and quickly. Context optimization runs faster and on simpler infrastructure than weight training: no GPUs to rent, and a new prompt is live the moment you save it. Environment interactions are expensive. If every rollout means a slow sandbox or a paid tool call, the method that needs fewer rollouts wins.
Also three. Context optimization fails. Small models can have weak instruction following, so no prompt rescues them. You have a capable teacher and want a cheaper model. Distilling directly into a student is often effective, as Chapters 6 and 8 showed. The context is getting too long. Prompt optimization adds rules and examples, and the prompt grows. Every call pays to read it. Training the knowledge into the weights removes that cost, which the lecture calls avoiding context bloat.
The two are not rivals. Soylu and colleagues (2024) wrote “BetterTogether”. Their finding, on the slide: sometimes it is best to optimize the prompts, then the weights, then the prompts again. Why would that order help? First prompts give you a working pipeline and good traces. Then finetuning on those traces folds the pipeline’s habits into the weights. Then the new model has a different style, so you tune its prompts once more.
Try the advisor. Switch on the facts that are true for your system.
Each switch is one of the lecture’s six reasons. Warm switches favour context optimization, pink switches favour weights.
The six reasons are slides 121 and 122. The rule that combines them is our own simple count, labelled illustrative: more context reasons, start with context; more weight reasons, start with weights; both, the BetterTogether order of prompts, weights, prompts.
| If this is true | Reach for | Because |
|---|---|---|
| Only an API, or you rerun often | Context optimization | No weights to touch, and it runs on simple infrastructure |
| Rollouts are slow or costly | Context optimization | It is far more sample efficient than RL |
| A small model ignores instructions | Weight optimization | Words cannot fix a model that cannot follow them |
| A strong teacher exists, and you want it cheaper | SFT or on-policy distillation | The student inherits the teacher’s behavior |
| The prompt keeps growing | Weight optimization | It moves the content out of every call’s input |
| Both kinds of pressure | Prompts, weights, prompts | BetterTogether found the order helps |
Failure mode. Symptom: you spend a month finetuning and the gain is a few points. Measurement: first run a prompt optimizer on the same data and compare. Fix: start with the cheaper method, since its curve rises first, and move to weights when the curve flattens.
Do not argue about the choice; measure it. A plain plan fits in four steps, and the first is cheap.
Compare the costs as well as the scores. Say the prompt run used 2,000 rollouts and one afternoon, and the weight run needed rented GPUs and a day (illustrative). When the vendor ships a new model version next month, the prompt run repeats in an afternoon. The weight run repeats from the start. Rerun cost belongs in the decision, next to the score and the one-time cost, and a plan that ignores it looks cheap only on the first day.
Chapter 11
Review every method with its numbers, a checklist, the core code, and the links that go deeper
The lecture’s closing slide ticks five boxes: the conditions for optimization, context optimization, weight optimization, optimization with agents, and which strategy to use. You can now rebuild each box from memory. This chapter is the reference page you keep.
Optimization lets you state intent through data and evals, and improve a system with a search. It needs three pillars: data, a system you can change, and a metric. Context optimization changes the words around a fixed model. It bootstraps passing traces into few-shot demonstrations, asks a model to propose instructions from past scores (OPRO), searches instruction and demo pairs with a surrogate (MIPROv2), and reflects on failures while keeping a Pareto pool (TextGrad, GEPA). Weight optimization changes the model. SFT copies a teacher’s verified rollouts. RL, with PPO or the lighter GRPO, rewards the student’s own tries against a verifier. On-policy distillation lets a teacher grade the student’s own words token by token. Agents can run the search themselves, but then the metric is the part you must guard. To choose: words are sample-cheap and fast, weights keep growing with data, and BetterTogether alternates them.
| What | Number | Why it matters |
|---|---|---|
| Prompt poll, PaLM 2-L-IT | 71.8%, 74.5%, 80.2% | Wording alone moves the score by 8.4 points |
| Empty instruction (OPRO table) | 34.0% | Instructions matter a great deal |
| DSPy on GSM8K, GPT-3.5 test | 25.2 plain; 61.7 bootstrapped; 72.9 CoT bootstrapped | Self-made demos can match human-written ones |
| GEPA, GPT-4.1 Mini average | 53.03 baseline; 58.67 MIPROv2; 65.22 GEPA; 66.36 with merge | Reflection beats a plain search |
| FireAct, Llama-2-13B | 21.2 prompted; 34.4 finetuned (GPT-3.5 prompted 31.4) | SFT on teacher rollouts lifts a small model |
| GRPO advantage, 4 of 8 right | +1 right, −1 wrong; 1 of 8 right gives +2.65 and −0.38 | Rare wins push hard; all-equal groups give 0 |
| PPO versus GRPO models | 4 held, 2 trained; 3 held, 1 trained | GRPO drops the value model |
| Qwen3, AIME’24 | 55.0 off-policy; 67.6 with RL; 74.4 with on-policy distillation | Dense, on-policy signal beats sparse |
| Qwen3 added-stage cost | 17,920 GPU hours for RL; 1,800 for on-policy distillation | About ten times cheaper |
| Auto-research run | 15 kept of 83 experiments | A ratchet keeps only what the metric rewards |
| Term | Plain meaning | Chapter |
|---|---|---|
| Metric | A function that scores an output with a number | 0 |
| Bootstrapping | Keep the model’s own passing traces as examples | 2 |
| Meta-prompt | A prompt that shows past prompts and scores to an optimizer | 3 |
| Minibatch | A small random slice of data, scored to save cost | 4 |
| Pareto frontier | Candidates that are best on at least one task | 5 |
| Rollout | One recorded run of an agent from task to end | 6 |
| Advantage | How much better than the group average an answer was | 7 |
| On-policy | Trained on text the student wrote itself | 8 |
| Harness | The code around a model: loop, tools, memory, prompts | 9 |
These four pieces are the lecture’s whole toolkit. They are sketches: program, llm, metric and agent stand for your own objects.
python# 1. Context optimization: DSPy MIPROv2 (Chapters 2 to 4) import dspy opt = dspy.MIPROv2(metric=metric, auto="light") # bootstrap demos, propose instructions, search pairs tuned = opt.compile(program, trainset=trainset) # text only: an instruction and a few demos # 2. An OPRO-style step (Chapter 3): past (text, score) pairs, lowest first history.sort(key=lambda p: p.score) reply = llm(META_PROMPT.format(pairs=history[-8:])) # the optimizer writes one new instruction history.append(score(extract(reply), devset)) # the scorer measures it on real data # 3. GRPO advantage and the clipped token term (Chapter 7) def group_advantages(rewards, eps=1e-6): mu = sum(rewards) / len(rewards) sd = (sum((r - mu) ** 2 for r in rewards) / len(rewards)) ** 0.5 return [(r - mu) / (sd + eps) for r in rewards] def token_term(ratio, adv, eps=0.2): return min(ratio * adv, max(min(ratio, 1 + eps), 1 - eps) * adv) # 4. On-policy distillation loss per token (Chapter 8): the student's own sample tokens = student.sample(prompt) loss = (student.logprobs(prompt, tokens) - teacher.logprobs(prompt, tokens)).mean()
Lecture 5 showed the frameworks that wire agents together, including DSPy. This lecture showed how to improve what those frameworks build. The same three pillars appear again in the evaluation and agent-data lectures: with no data and no metric there is nothing to optimize. The slide after the summary announces a guest lecture on the next Monday, with the Terminal-Bench logo, and Homework 2 released that day.
The course meets at Stanford and posts its slides on the course site. This lesson re-teaches Lecture 9, taught by Diyi Yang, Michael Ryan and John Yang, from their slides and the three readings. The devices and wording here are our own, so follow the links for the originals.
Now press Teach and explain, from memory, how you would improve one real system: which pillar you would check first, which method you would run, how you would test the result, and when you would move from words to weights. Then go back to the search at the top, press Let the optimizer search, and say out loud what each prompt tested and why the winner won.