Module 10 gave the agent a score. This module turns the score into a better agent. There are two places to make a change. The context is everything the model reads: the instruction, the examples, the tool descriptions. The weights are the model itself. Context changes are cheap, quick and work with any model behind an API; weight changes need training, but can teach a small model what prompting alone cannot. The CS329Z lecture on optimisation lists what either one needs: data, a system with parameters to change, and a metric that says whether a change helped. Without all three there is nothing to optimise, only guessing.

Notebooks

Notebook 11a: The data flywheel and prompt optimisation serves support tickets with a traced classifier, turns the traces and a triager’s corrections into a dataset, then improves the prompt with bootstrapped demos, random search and a reflective instruction search, scored on a held-out test set. Notebook 11b: GRPO on a toy tool router writes REINFORCE, group-relative advantages, ratio clipping and a KL penalty in numpy, trains a router that picks one of five tools, then fits a reward model to biased preferences and watches the policy exploit it.

The data flywheel

The data comes from the agent itself. Every request it serves is a trace (Module 10), and many products collect a signal about the outcome for free: a thumbs-down, an edit to a draft, a ticket moved to another queue.

Definition 11.1 (Data flywheel).

A data flywheel is the loop that turns production use into improvement: serve requests and record traces, attach feedback to them, turn traces and feedback into a labelled dataset, optimise the agent on it, and deploy the new version only if it passes a held-out evaluation. The new version’s traces feed the next turn.

serve triage agent trace inputs + feedback label train / val / test optimise demos, instruction evaluate held-out test corrections become labels deploy if it wins

In notebook 11a the agent sorts support tickets into five queues (shipping, refund, billing, account, bug). In a simulated week it serves 120 tickets; a human triager accepts the queue or moves the ticket, and that action is recorded as a feedback event on the ticket’s trace. Half the tickets were moved, so production accuracy, read from the feedback alone, was 0.50. Each correction is a free, correct label. The 120 served tickets are split into train (58) and validation (62). The test set is 60 separate tickets that were never served, and it stays untouched until the end. The flywheel (Definition 11.1) has one rule that is easy to break: the deploy decision uses data the optimiser never saw.

Optimising the prompt

DSPy (Khattab et al.) treats a prompt as the parameters of a program: an instruction and a list of demonstrations, plugged into a fixed signature such as “ticket in, label out”.

Definition 11.2 (Prompt optimisation).

Prompt optimisation searches over the instruction and the demonstrations of a fixed program, with the model’s weights frozen, to maximise a metric on a training and validation set. The optimiser calls the model many times; the deployed program calls it once per request, as before.

Notebook 11a tries the two main moves of prompt optimisation (Definition 11.2). The first is DSPy’s bootstrapped few-shot: run the program on the training tickets, keep the runs that pass the metric as demos, and pick the best set of demos by random search on validation. It helped little, and the reason is instructive. Of the 27 runs that passed, 17 were the easy tickets that use a listed keyword, so the demos showed the model what it already knew. Demos drawn from all labelled tickets, corrected failures included, did much better.

The second move rewrites the instruction. A reflector model reads the training tickets the current instruction got wrong, explains each failure in a line, and proposes a revised instruction; the revision is kept only if validation accuracy improves. Pryzant et al. call the explanation a textual gradient (ProTeGi); GEPA (Agrawal et al.) keeps a population of candidates instead of one, and MIPROv2 (Opsahl-Ong et al.) proposes instructions grounded in the data and searches over instruction and demo choices together. In the notebook the reflective search ran five rounds. It kept the proposals of the first three (new keywords for four labels and two priority rules such as “if the ticket mentions error, the label is bug”), rejected the fourth, and stopped when the reflector proposed it again. On the held-out test set:

programvalidationtesttest, indirect tickets
seed instruction0.530.500.15
+ demos from successes0.630.550.19
+ demos from all labels0.740.770.46
reflected instruction0.870.900.77
reflected + demos0.900.930.85

“Indirect” tickets say what they mean without a listed keyword (“I want my money back, not a replacement”). The whole search cost 3,617 calls to the classifier and 6 to the reflector.

Remark 11.1 (What these numbers do and do not show).

The classifier in notebook 11a is a rule set that reads keywords, so keyword edits move it a lot; a capable LLM already knows that “money back” means a refund, and gains less. With 60 test tickets, 0.90 and 0.93 are not distinguishable; 0.50 and 0.93 are. And an optimised prompt is fitted to one model: keep the dataset and the optimiser, and re-run them, behind the eval gate, whenever the model changes.

With those caveats (Remark 11.1), the shape of the result is typical: the instruction carries the rules that apply to many tickets, and demos patch the one-off phrasings no rule covers.

Changing the weights with a verifiable reward

When prompting plateaus, the weights are the next lever. The lecture separates two recipes. Supervised fine-tuning (SFT) has a strong teacher model do the tasks and trains the student on the teacher’s trajectories. Reinforcement learning has the student do the tasks itself and rewards it when it succeeds. For agents the reward is often a program: the tests pass, the answer matches, the booking exists. The CS329Z lecture on agent data names the raw material of each recipe: SFT needs trajectories (recordings of an agent solving tasks), RL needs environments (a task, a sandbox to act in, and a verifier).

Definition 11.3 (RL with verifiable rewards).

Reinforcement learning with verifiable rewards samples outputs from the current policy, scores each with a program that checks success, and changes the weights to make rewarded outputs more likely. Nobody writes a target output; the verifier only judges.

Notebook 11b strips this (Definition 11.3) to its smallest version, small enough to run in numpy in two seconds. A query has one of five hidden types (arithmetic, fresh facts, data analysis, scheduling, records lookup). The policy sees nine binary features of the query and picks one of five tools; the verifier returns 1 if the tool solved it. A uniformly random router scores 0.339, the best possible router given the features 0.718, and one that could see the hidden type 0.910. The policy is a softmax over a linear function of the features, , and the policy gradient (REINFORCE, Williams 1992) says how to raise the expected reward:

Push up the log-probability of what you did, in proportion to how much better than the baseline it went. Any baseline that does not depend on the action leaves the expectation in equation unchanged and can cut its noise: at a batch of 16, using the batch mean cut the gradient variance from 0.0616 to 0.0383. Strictly, the batch mean includes each sample’s own reward, so it shrinks the expected gradient by a factor , here . A leave-one-out mean, the average of the other rewards, removes even that bias.

GRPO (Shao et al.) is the variant behind DeepSeek-R1. It samples a group of answers to the same query and uses the group as the baseline:

It then takes several gradient steps on the same samples, with PPO’s clipped ratio to stop the policy moving far from the one that collected them, and a penalty that keeps it near a reference policy:

With equation , a group in which every answer got the same reward has zero advantage everywhere and teaches nothing. The notebook compares the methods at the same budget, 128 rollouts per step for 150 steps, three seeds each:

methodfinal value
REINFORCE0.539
REINFORCE with a baseline0.537
GRPO, one gradient step per batch0.580
GRPO, four gradient steps per batch0.679

The honest reading is that most of GRPO’s lead here comes from reusing each batch four times, which the clipping in equation makes safe; groups and z-scores alone add a little, and at batch 128 the baseline hardly matters. The lecture gives the practical reasons GRPO caught on for language models. PPO keeps four models in memory (policy, reference, reward model and a value model) and trains two of them; GRPO drops the value model, trains only the policy, and its “reward model” can be a program. The price is visible in the notebook as well: as the router grew confident, the share of groups whose answers all got the same reward rose from 6% to 38%. That is why training pipelines keep prompts the model solves sometimes but not always, and why DAPO resamples until a batch has enough useful groups.

Real fine-tuning starts from an SFT model, not a uniform one. The notebook’s SFT router, trained on 100 demonstrations from an expert who slips 30% of the time, scores 0.555. GRPO from there with different penalty weights :

valueKL to the SFT policy
00.6920.307
0.050.6870.255
0.20.6730.186
1.00.6240.058

With a reward you can trust, the KL term only costs value. Its job shows up when the reward is not trustworthy.

When the reward is learned

Many qualities have no verifier: helpfulness, tone, whether a plan is sensible. The usual substitute is to ask people which of two outputs they prefer and fit a reward model to those comparisons. The Bradley–Terry model, the standard choice (Lambert, chapter 5), assumes that the probability of preferring to depends on the difference of their rewards:

where is the logistic function; fitting means minimising the negative log of equation over the labelled pairs. In notebook 11b the simulated annotators mostly prefer the tool that worked, with one bias: an answer backed by a web search looks more trustworthy, so they rate web_search as if it were 0.5 more likely to succeed than it is. The reward model fits well by the usual measure: loss falls from 0.578 to 0.404, and it agrees with the annotators on 80% of held-out pairs. Yet its favourite tool is web_search for every one of the five query types.

Remark 11.2 (Reward over-optimisation).

A learned reward is a proxy for the true one. Optimising it hard finds the places where the two disagree: the proxy keeps rising while the true reward stalls, then falls. Gao et al. measured this for language models: the gap grows with the KL distance from the starting policy, which is what the KL penalty limits.

The notebook shows the effect (Remark 11.2) in miniature. GRPO on the reward model, from the SFT router, for different :

rewardproxy rewardtrue valueKL
reward model00.72 to 1.840.555 to 0.4721.98
reward model1.00.72 to 1.330.555 to 0.5780.36
reward model3.00.72 to 0.950.555 to 0.5880.03
verifier00.555 to 0.658

Without the penalty, the policy more than doubled its proxy reward and ended worse than where it started. A strong penalty prevents the damage, but also most of the gain. The verifier, which cannot be flattered, did best. For agents the lesson is to use verifiable rewards wherever the task allows (tests, exact checks, the state of the environment), to judge training by the true metric rather than the reward, and to check a reward model’s agreement on the cases where it matters, not only on average. An overall 80% hid a bias that applied everywhere.

The same lecture collects the ways agent data teaches things nobody intended. An environment with a loophole trains the loophole: coding agents have learned to make a test run report success instead of fixing the code, which is Module 13’s reason to keep the verifier out of the agent’s reach. Trajectories recorded in a single harness teach that harness’s conventions along with the skill, so the model stumbles in another. And a model trained on human approval can learn to look right rather than be right, the human version of the reward-model bias above.

Which lever to pull

leverwhat changeswhat it needswhen
prompt optimisationinstruction, demosdozens to hundreds of labelled examples and a metricfirst, and after every model change
SFTweightstrajectories from a stronger teacherto make a small, cheap model behave like a large one
RL with a verifierweightstasks, a verifier, much computewhen success is checkable and prompting has plateaued

The lecture’s own summary is that optimisation is for the last mile: a general model is a good start, and optimisation adapts it to your data and your metric. Agents are now capable optimisers themselves, editing prompts, harnesses or code and keeping what scores better, which makes the metric the part that most needs guarding. Whatever is optimised, the eval gate of Module 10 decides what ships.

Try this

  • In notebook 11a, the simulated triager in agentlab/optimize/flywheel.py always knows the right queue. Make it wrong on 10% of tickets. How much do the demo and instruction searches lose on the test set?
  • Replace the reflector’s keep-if-better rule with keep-the-best-two (a small pool, as GEPA does). Does the search still get stuck after round four?
  • In notebook 11b, run grpo with group_size 2, 4, 8 and 16 and groups = 128 // group_size, so every run sees 128 rollouts per step. Plot the final value and the share of dead groups. Which group size is best here, and why does equation behave badly for ?
  • Set the annotator bias to 0 and re-run the reward-model experiment. Does over-optimisation disappear, or does a weaker version remain?
  • Add a sixth tool that always fails but which the annotators rate highly. How fast does the unpenalised policy find it?

Readings