About this notebook
Companion to Module 11: Optimizing agents. Every cell below was executed with the offline backend, so you can reproduce these outputs exactly with no API key. Download the notebook (.ipynb)
Notebook 11a improved an agent by editing its prompt. The other lever is the weights: fine-tune the model on its own attempts, rewarded by a verifier. The algorithms used for that today (REINFORCE with a baseline, PPO, GRPO) are short formulas, and the easiest way to understand them is to implement them where everything is small enough to check. This notebook does that for the smallest agent decision there is: which tool should handle this query?
query (hidden type) --> features x --> policy pi(tool | x) --> tool --> verifier
^ |
| reward 1 or 0 |
└──── update the weights <─────┘You will
- build the router’s world and compute exactly how good any policy is;
- derive the policy gradient, and measure how much a baseline cuts its noise;
- take one GRPO step by hand: group of answers, z-scored advantages, ratio, clipping;
- compare learning curves of REINFORCE and GRPO at the same sample budget;
- start from a supervised (SFT) policy and keep RL close to it with a KL penalty;
- replace the verifier with a reward model learned from biased preferences, and watch the policy exploit it.
No language model in this notebook
The “policy” is a linear softmax over five tools: 45 weights, trained in numpy on the CPU in under a second per run. An LLM policy outputs a sequence of tokens instead of one choice, which changes the bookkeeping (section 7) but not the update rules. The environment, the annotators and their bias are all simulated, so the numbers show how the algorithms behave, not what they would gain on a real model.
import matplotlib.pyplot as plt
import numpy as np
from agentlab.nbsetup import setup
from agentlab.tiny.grpo import (SoftmaxPolicy, expert_demos, group_advantages, grpo,
reinforce, sft)
from agentlab.tiny.prefs import BradleyTerryRM, synthetic_preferences
from agentlab.tiny.routing_env import CUES, DISTRACTORS, QUERY_TYPES, TOOLS, RoutingEnv
nb = setup("11b_grpo_tool_router")LLM backend
offline policy model (deterministic, rule-based, no API key used)
1. The environment
A query has one of five hidden types. Each tool solves each type with some probability, and a verifier says whether it did: reward 1 or 0. The table is the whole world.
env = RoutingEnv()
print(f"{'P(success)':<16}" + "".join(f"{t:>13}" for t in TOOLS))
for qt, row in zip(QUERY_TYPES, env.success):
print(f"{qt:<16}" + "".join(f"{p:>13.2f}" for p in row))P(success) calculator web_search code_runner calendar sql_db arithmetic 0.95 0.30 0.80 0.02 0.05 fresh_facts 0.02 0.85 0.10 0.02 0.10 data_analysis 0.15 0.45 0.90 0.02 0.60 scheduling 0.02 0.20 0.05 0.95 0.05 records_lookup 0.02 0.55 0.35 0.05 0.90
The router never sees the type. It sees nine binary features: five cues (cue i fires with probability 0.8 for type i and 0.1 otherwise), three distractors that are coin flips, and a constant 1. A cue can be missing or misleading, so even a perfect router makes mistakes. With only 2^8 = 256 possible inputs we can compute any policy’s expected reward exactly instead of estimating it, which is what makes the curves below smooth.
print("features:", ", ".join(CUES + DISTRACTORS), "+ bias")
print(f"uniform random router {env.uniform_value():.3f}")
print(f"best router from the features {env.bayes_value():.3f}")
print(f"router that sees the true type {env.oracle_value():.3f}")features: has_numbers, says_latest, mentions_csv, mentions_meeting, mentions_customer, is_polite, is_long, has_typo + bias uniform random router 0.339 best router from the features 0.718 router that sees the true type 0.910
Training can at best close the gap from 0.34 to 0.72. The last 0.19 is information the features do not carry; no algorithm recovers it.
2. The policy gradient, and why a baseline helps
The policy is
In words: push up the log-probability of what you did, in proportion to the reward you
got. That is REINFORCE (Williams, 1992). Subtracting a baseline
The check below draws 400 gradient estimates from batches of 16 at the starting (uniform) policy and compares their spread.
rng = np.random.default_rng(0)
start = SoftmaxPolicy(env.n_actions, env.n_features)
est = {False: [], True: []}
for _ in range(400):
types, X = env.sample(16, rng)
a = start.sample(X, rng)
r = env.rewards(types, a, rng)
for use_baseline in (False, True):
adv = r - r.mean() if use_baseline else r
g = (adv[:, None, None] * start.grad_logp(X, a)).mean(axis=0)
est[use_baseline].append(g.ravel())
for use_baseline, g in est.items():
g = np.array(g)
norm = np.linalg.norm(g.mean(axis=0))
print(f"baseline={str(use_baseline):<5} |mean gradient| {norm:.3f}"
f" total variance {g.var(axis=0).sum():.4f}")baseline=False |mean gradient| 0.082 total variance 0.0616 baseline=True |mean gradient| 0.074 total variance 0.0383
Same direction on average, about 40% less variance with the baseline here. (Both use the same batches, so the comparison is paired.) PPO learns a value network to serve as the baseline; GRPO, next, gets one for free from a group of samples.
3. One GRPO step by hand
Group Relative Policy Optimisation (Shao et al., 2024) changes three things:
- Groups. Sample
answers to the same query. Each answer’s advantage is its reward z-scored within the group, . The group mean is the baseline: no value network needed. - Reuse with clipping. Take several gradient steps on the same samples. To keep the
policy from drifting far from the one that collected them, optimise PPO’s clipped
objective
, with the ratio . Once a sample’s ratio leaves the band in the direction its advantage pushes, its gradient is zero. - KL to a reference. Subtract
, estimated per sample with (section 5).
Here is one group of eight, for one query, with a policy that has already learned a little (the SFT policy of section 5, built here early).
demo_X, demo_a = expert_demos(env, 100, 0.7, np.random.default_rng(1))
ref = sft(env, demo_X, demo_a)
rng = np.random.default_rng(20)
qtype, xq = env.sample(1, rng)
G = 8
X = np.repeat(xq, G, axis=0)
a = ref.sample(X, rng)
r = env.rewards(np.repeat(qtype, G), a, rng)
adv = group_advantages(r[None])[0]
print("query type:", QUERY_TYPES[qtype[0]], "| cues on:",
[c for c, v in zip(CUES, xq[0]) if v] or "none")
print(f"{'i':>2} {'tool':<12} {'p_old':>6} {'reward':>7} {'advantage':>10}")
p_old = ref.probs(X)[np.arange(G), a]
for i in range(G):
print(f"{i:>2} {TOOLS[a[i]]:<12} {p_old[i]:>6.2f} {r[i]:>7.0f} {adv[i]:>10.2f}")query type: records_lookup | cues on: ['mentions_customer'] i tool p_old reward advantage 0 sql_db 0.65 1 0.77 1 sql_db 0.65 1 0.77 2 code_runner 0.22 1 0.77 3 code_runner 0.22 0 -1.29 4 web_search 0.06 0 -1.29 5 calculator 0.06 0 -1.29 6 sql_db 0.65 1 0.77 7 sql_db 0.65 1 0.77
Now four epochs of clipped updates on this group alone. Watch the ratios: the sql_db samples (positive advantage) climb towards 1.2 and slow down as they near it; the failed web_search and calculator samples drop below 0.8 in the first step and contribute nothing after that.
pol, clip, lr = ref.copy(), 0.2, 0.3
idx = np.arange(G)
for epoch in range(1, 5):
p = pol.probs(X)[idx, a]
ratio = p / p_old
active = ratio * adv <= np.clip(ratio, 1 - clip, 1 + clip) * adv
coef = np.where(active, adv * ratio, 0.0)
pol.W += lr * (coef[:, None, None] * pol.grad_logp(X, a)).mean(axis=0)
print(f"epoch {epoch}: ratios " + " ".join(f"{q:.2f}" for q in ratio)
+ f" still active {active.sum()}/{G}")
print(f"\n{'':<8}" + "".join(f"{t:>13}" for t in TOOLS))
for label, P in (("before", ref.probs(xq)[0]), ("after", pol.probs(xq)[0])):
print(f"{label:<8}" + "".join(f"{q:>13.2f}" for q in P))epoch 1: ratios 1.00 1.00 1.00 1.00 1.00 1.00 1.00 1.00 still active 8/8
epoch 2: ratios 1.14 1.14 0.76 0.76 0.70 0.70 1.14 1.14 still active 5/8
epoch 3: ratios 1.16 1.16 0.72 0.72 0.66 0.66 1.16 1.16 still active 5/8
epoch 4: ratios 1.18 1.18 0.69 0.69 0.62 0.62 1.18 1.18 still active 5/8
calculator web_search code_runner calendar sql_db
before 0.06 0.06 0.22 0.00 0.65
after 0.04 0.04 0.14 0.00 0.78
The ratios printed in each epoch are measured before that epoch’s update, so the first row is all 1.00. Three details are worth noticing.
- Clipping does not stop the first step from overshooting the band; it only stops the policy being pushed further in the same direction. The step size still matters.
- Samples 2 and 3 chose the same tool for the same query, so they share a ratio. The
failed one is clipped; the successful one stays active, because its push is upward
while the ratio has moved down. That is the
minin the objective at work. - If all eight answers had the same reward, every advantage would be zero and the group would teach nothing: a dead group. Because of the z-score, a group with one success in eight pushes as hard in total as a group with seven.
4. Learning curves at the same sample budget
Each method sees 128 rollouts per step for 150 steps: REINFORCE as one batch of 128 queries, GRPO as 16 queries x 8 answers. Three seeds each; curves show the mean and the range. “GRPO, 1 epoch” turns off sample reuse, so it isolates what groups and z-scores do on their own.
seeds = (0, 1, 2)
STEPS = 150
runs = {
"REINFORCE": lambda s: reinforce(env, SoftmaxPolicy(5, 9), steps=STEPS, batch=128,
baseline=False, seed=s),
"REINFORCE + baseline": lambda s: reinforce(env, SoftmaxPolicy(5, 9), steps=STEPS,
batch=128, baseline=True, seed=s),
"GRPO, 1 epoch": lambda s: grpo(env, SoftmaxPolicy(5, 9), steps=STEPS, epochs=1,
seed=s),
"GRPO, 4 epochs": lambda s: grpo(env, SoftmaxPolicy(5, 9), steps=STEPS, epochs=4,
seed=s),
}
curves = {name: [fn(s) for s in seeds] for name, fn in runs.items()}
for name, hs in curves.items():
final = [h.value[-1] for h in hs]
print(f"{name:<22} final value {np.mean(final):.3f} (seeds: "
+ ", ".join(f"{v:.3f}" for v in final) + ")")REINFORCE final value 0.539 (seeds: 0.539, 0.540, 0.537) REINFORCE + baseline final value 0.537 (seeds: 0.536, 0.538, 0.537) GRPO, 1 epoch final value 0.580 (seeds: 0.565, 0.605, 0.569) GRPO, 4 epochs final value 0.679 (seeds: 0.684, 0.676, 0.678)
colors = {"REINFORCE": "#81796f", "REINFORCE + baseline": "#2c7d54",
"GRPO, 1 epoch": "#b5523b", "GRPO, 4 epochs": "#2c5f9e"}
fig, ax = plt.subplots(figsize=(6.4, 3.8))
for name, hs in curves.items():
xs = np.array(hs[0].samples) / 1000
V = np.array([h.value for h in hs])
ax.plot(xs, V.mean(0), color=colors[name], lw=1.8, label=name)
ax.fill_between(xs, V.min(0), V.max(0), color=colors[name], alpha=0.15, lw=0)
ax.axhline(env.bayes_value(), color="#81796f", ls=":", lw=1)
ax.text(0.5, env.bayes_value() + 0.008, "best possible from the features", fontsize=8,
color="#81796f")
ax.axhline(env.uniform_value(), color="#81796f", ls="--", lw=1)
ax.text(7.5, env.uniform_value() + 0.008, "uniform router", fontsize=8, color="#81796f")
ax.set_xlabel("rollouts (thousands)")
ax.set_ylabel("expected reward")
ax.set_ylim(0.3, 0.76)
ax.legend(frameon=False, loc="lower right", fontsize=8)
ax.spines[["top", "right"]].set_visible(False)
fig.tight_layout()
plt.show()
Exact expected reward of the router during training, mean of three seeds with the range shaded. All methods see 128 rollouts per step. The two REINFORCE curves overlap; GRPO with one epoch is only a little ahead of them; reusing each batch for four clipped epochs is what makes GRPO faster here.
Be careful what you conclude. In this setting the baseline barely matters at batch 128, because averaging over 128 samples already removes most of the noise that section 2 measured at batch 16. GRPO’s groups and z-scores alone are worth only a little. Most of its lead comes from taking four gradient steps per batch, which clipping makes safe; with a larger step size REINFORCE would close part of the gap, and with a learned value network PPO gets the same reuse. The real reasons GRPO is popular for LLMs are practical: no value network the size of the policy to train, and a baseline that compares answers to the same prompt.
The dead-group fraction shows the price of group baselines. As the policy grows confident, more groups come back all-0 or all-1 and carry no gradient:
h = curves["GRPO, 4 epochs"][0]
for step in (0, 30, 60, 90, 120, 145):
i = step // 5
print(f"step {step:>3}: value {h.value[i]:.3f} dead groups {h.dead[i]:.0%}")step 0: value 0.339 dead groups 6% step 30: value 0.575 dead groups 6% step 60: value 0.645 dead groups 12% step 90: value 0.670 dead groups 19% step 120: value 0.679 dead groups 19% step 145: value 0.682 dead groups 38%
For LLM training this is why pipelines filter prompts by difficulty, keeping those the current model solves sometimes but not always; DAPO (Yu et al., 2025) resamples until a batch has enough live groups.
5. Start from SFT, stay near it with KL
Real RL fine-tuning never starts from a uniform policy. It starts from a supervised model (SFT) trained on demonstrations, and it adds a penalty that keeps the new policy close to that reference. Here the demonstrations are 100 queries routed by an expert who knows the type but slips 30% of the time.
print(f"SFT policy value {env.value(ref.probs):.3f} "
f"(uniform {env.uniform_value():.3f}, best {env.bayes_value():.3f})")
betas = (0.0, 0.05, 0.2, 1.0)
tuned = {b: grpo(env, ref.copy(), ref=ref, steps=STEPS, beta=b, seed=0) for b in betas}
for b, h in tuned.items():
print(f"beta={b:<5} value {h.value[-1]:.3f} KL to SFT {h.kl[-1]:.3f}")SFT policy value 0.555 (uniform 0.339, best 0.718) beta=0.0 value 0.692 KL to SFT 0.307 beta=0.05 value 0.687 KL to SFT 0.255 beta=0.2 value 0.673 KL to SFT 0.186 beta=1.0 value 0.624 KL to SFT 0.058
fig, ax = plt.subplots(figsize=(6.4, 3.4))
kls = [0.0] + [tuned[b].kl[-1] for b in betas]
vals = [env.value(ref.probs)] + [tuned[b].value[-1] for b in betas]
order = np.argsort(kls)
ax.plot(np.array(kls)[order], np.array(vals)[order], color="#2c5f9e", marker="o", lw=1.5)
ax.annotate("SFT start", (kls[0], vals[0]), xytext=(8, -4), textcoords="offset points",
fontsize=8, color="#81796f")
for b, k, v in zip(betas, kls[1:], vals[1:]):
ax.annotate(f"beta = {b}", (k, v), xytext=(6, -12), textcoords="offset points",
fontsize=8, color="#81796f")
ax.axhline(env.bayes_value(), color="#81796f", ls=":", lw=1)
ax.set_xlabel("KL(policy || SFT reference)")
ax.set_ylabel("expected reward")
ax.set_xlim(-0.02, max(kls) * 1.25)
ax.spines[["top", "right"]].set_visible(False)
fig.tight_layout()
plt.show()
Final value against final KL divergence from the SFT policy, for four KL weights. A larger weight buys a policy closer to the reference at the cost of some reward.
With a verifier as the reward, the KL penalty mostly costs reward: the verifier cannot be fooled, so there is little to protect against. It still has two jobs in practice. It keeps the model’s other skills (here there are none; in an LLM, everything it was not trained on), and it limits how far the policy can run with a reward that can be fooled. That second job is the next section.
6. A learned reward model, and how a policy exploits it
Many agent tasks have no verifier. Then the reward comes from a model trained on human
preferences: show annotators two answers, record which one they prefer, and fit a
score
Our simulated annotators mostly prefer the tool that works, 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 is linear in the same nine features, one weight vector per tool.
Xp, tp, win, lose = synthetic_preferences(env, 3000, np.random.default_rng(2), bias=0.5,
temperature=0.1)
rm = BradleyTerryRM(env.n_actions, env.n_features)
losses = rm.fit(Xp[:2400], win[:2400], lose[:2400])
print(f"loss {losses[0]:.3f} -> {losses[-1]:.3f}; held-out agreement with annotators "
f"{rm.accuracy(Xp[2400:], win[2400:], lose[2400:]):.2f}")
X_all, lik = env.all_inputs()
post = lik / lik.sum(1, keepdims=True)
types_of_x = post.argmax(1)
rm_best = rm.scores_all(X_all).argmax(1)
print(f"\n{'query type':<16} {'true best tool':<15} {'RM favourite (share of inputs)'}")
for t, qt in enumerate(QUERY_TYPES):
picks = np.bincount(rm_best[types_of_x == t], minlength=5)
fav = picks.argmax()
print(f"{qt:<16} {TOOLS[env.success[t].argmax()]:<15} {TOOLS[fav]} "
f"({picks[fav] / picks.sum():.0%})")loss 0.578 -> 0.404; held-out agreement with annotators 0.80 query type true best tool RM favourite (share of inputs) arithmetic calculator web_search (95%) fresh_facts web_search web_search (100%) data_analysis code_runner web_search (100%) scheduling calendar web_search (75%) records_lookup sql_db web_search (100%)
The reward model agrees with the annotators on 80% of held-out pairs, which would look fine on a dashboard. But it has learned their bias, and a linear model over noisy features turns “web search is a bit better than it looks” into “web search is the best answer to almost every query”. Now train the SFT policy with GRPO against this reward model instead of the verifier, for several KL weights, and track both the score the policy is optimising (the proxy) and the true success rate. The step size is smaller than in section 5 so that the curves can be followed step by step; the run labelled “verifier reward” uses the same settings with the true reward, for comparison.
px = lik.mean(1)
def proxy_value(pol):
return float(px @ np.sum(pol.probs(X_all) * rm.scores_all(X_all), axis=1))
def rm_reward(types, X, actions, rng):
return rm.score(X, actions)
rm_betas = (0.0, 0.3, 1.0, 3.0)
hacked = {b: grpo(env, ref.copy(), ref=ref, steps=STEPS, lr=0.1, beta=b, seed=0,
reward_fn=rm_reward, proxy_value=proxy_value) for b in rm_betas}
honest = grpo(env, ref.copy(), ref=ref, steps=STEPS, lr=0.1, beta=0.0, seed=0)
for b, h in hacked.items():
print(f"beta={b:<4} proxy {h.proxy[0]:.2f} -> {h.proxy[-1]:.2f} true "
f"{h.value[0]:.3f} -> {h.value[-1]:.3f} KL {h.kl[-1]:.2f}")
print(f"verifier reward, beta=0: true {honest.value[0]:.3f} -> {honest.value[-1]:.3f}")beta=0.0 proxy 0.72 -> 1.84 true 0.555 -> 0.472 KL 1.98 beta=0.3 proxy 0.72 -> 1.67 true 0.555 -> 0.518 KL 1.20 beta=1.0 proxy 0.72 -> 1.33 true 0.555 -> 0.578 KL 0.36 beta=3.0 proxy 0.72 -> 0.95 true 0.555 -> 0.588 KL 0.03 verifier reward, beta=0: true 0.555 -> 0.658
pal = {0.0: "#b5523b", 0.3: "#c9a03b", 1.0: "#2c7d54", 3.0: "#2c5f9e"}
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(6.4, 3.6), sharex=True)
for b, h in hacked.items():
steps = np.array(h.samples) / 128
ax1.plot(steps, h.proxy, color=pal[b], lw=1.6, label=f"beta = {b}")
ax2.plot(steps, h.value, color=pal[b], lw=1.6)
ax2.plot(np.array(honest.samples) / 128, honest.value, color="#81796f", ls="--", lw=1.4,
label="verifier reward")
ax1.set_ylabel("reward-model score (proxy)")
ax2.set_ylabel("true success rate")
for ax in (ax1, ax2):
ax.set_xlabel("GRPO step")
ax.spines[["top", "right"]].set_visible(False)
handles = ax1.get_lines() + ax2.get_lines()[-1:]
fig.legend(handles, [ln.get_label() for ln in handles], loc="upper center", ncol=5,
frameon=False, fontsize=8)
fig.tight_layout(rect=(0, 0, 1, 0.92))
plt.show()
GRPO from the SFT policy against the learned reward model, for four KL weights. Left: the reward-model score the policy optimises keeps rising. Right: the true success rate falls without a KL penalty and improves only slightly with one, while training on the verifier itself (dashed) does clearly better.
This is reward over-optimisation (Gao et al., 2023), in miniature. The proxy rose from 0.72 to 1.84 while the true success rate fell below where training started: the policy learned to send queries to web_search because the reward model likes it. The KL penalty is the standard defence, and here it works only as a brake: at beta = 1 or 3 the policy cannot move far enough to be badly hurt, but it cannot move far enough to improve much either (0.59 at best, against 0.66 for the same run on the verifier).
Three lessons transfer directly to agent training.
- Prefer verifiable rewards. Tests that pass, an answer that matches, a booking that exists in the database. Reinforcement learning with verifiable rewards (RLVR) is popular for agents precisely because a verifier cannot be flattered.
- Watch the true metric, not the reward. The proxy curve on the left looks like success. Keep a held-out evaluation with code-based graders (Module 10) and stop when it stops improving.
- Agreement is not enough. 80% agreement with annotators said nothing about the one direction the policy would push in. Test a reward model where the policy will take it.
7. From a router to an LLM agent
Every formula above carries over. What changes is what an “answer” is.
this notebook an LLM agent
----------------------------------- ---------------------------------------------
query x prompt (task, tools, history)
one tool choice a a sequence of tokens: a reply or a whole
multi-turn trajectory with tool calls
log pi(a | x) sum of the log-probs of the generated tokens
group of 8 choices 8 sampled completions of the same prompt
verifier: success table tests pass, answer matches, state checks out
KL(pi || ref) per query KL summed (or averaged) over tokens
dead groups prompts too easy or too hard: filter them
45 weights, under a second billions of weights, GPU-days per runThe harder questions in agent RL come from the right-hand column: how to assign credit to individual tool calls in a long trajectory, how to average per-token terms without biasing towards short or long answers (Liu et al., 2025, discuss GRPO’s length and std normalisation), and how to run thousands of sandboxed environments to collect the rollouts. Module 13’s coding agent is the kind of environment that RL for coding agents runs at scale.
Try this
- Set
cue_hit=0.95inRoutingEnv. How much closer does the best router get to the oracle, and how much faster does GRPO get there?- Make the verifier noisy: flip 20% of rewards in
env.rewards. Which method in section 4 degrades most?- In section 6, bias the annotators only on
data_analysisandrecords_lookup(bias=[0, 0, 0.5, 0, 0.5]). Does GRPO on the reward model still hurt the true success rate?- Remove the std from
group_advantages(divide by 1 instead). What happens to the learning curve, and to how much a one-in-eight success is worth?- Give the reward model more data (
n_pairs=30000). Does it lose the bias? (It should not: more data teaches it the annotators’ preferences more precisely, bias included.)
nb.usage()| model calls | input tokens | output tokens | cost |
|---|---|---|---|
| 0 (none) | 0 | 0 | USD 0.0000 |