What you will build
blog-coding-tutorials/c12-agent-rlA complete agent-RL system: an environment with injected tool failures, a behaviour-cloned policy, a GRPO trainer with trajectory-level and action-level credit, reward shaping with a deliberate hack, a curriculum, and a pipeline with a trajectory store and an independent verifier.
- Theory first
- Time
- About three hours, with the runs
- Hardware
- Any CPU. No GPU needed. The CPU numbers below came from an AMD EPYC 7R13 with 8 threads. The GPU numbers came from an NVIDIA H100 80GB HBM3, torch 2.15.0+cu132.
- You need
- The loss mask from C6 and the agent loop from C10. Python 3.10+, PyTorch 2.x, pytest. Transformers and PEFT for the last step.
- Package
agentrl
Final repo tree c12-agent-rl/
c12-agent-rl/ ├── README.md # what, how to run, results table ├── agentrl/ │ ├── tasks.py # step 1: the five levels │ ├── env.py # step 1: reset, observe, step, reward, done │ ├── expert.py # step 1: scripted demonstrator │ ├── trajectory.py # step 2: text view and tensor view │ ├── codec.py # step 2: word tokenizer, encode_trajectory │ ├── policy.py # step 3: tiny transformer + value head │ ├── batching.py # step 4: padded tensors and masks │ ├── bc.py # step 4: behaviour cloning │ ├── shift.py # step 5: perturbations, signatures │ ├── sampling.py # step 6: shared rollout pieces │ ├── rollout_naive.py # step 6: the reference │ ├── rollout.py # step 6: batched generation │ ├── advantages.py # steps 7, 9: group-relative, GAE │ ├── grpo.py # step 8: clipped surrogate, update │ ├── online.py # steps 8, 11, 12: loop, sampler, curriculum │ ├── rewards.py # step 10: outcome, activity, potential │ ├── failures.py # step 13: failure injection │ ├── offline.py # step 14: offline GRPO, filtered BC │ ├── system.py # step 15: store, verifier, workers, resume │ ├── hf_policy.py # step 16: Llama and SmolLM2 adapters │ └── evaluate.py # the four evaluation suites ├── scripts/ │ ├── demo_env.py │ ├── train_bc.py │ ├── distribution_shift.py │ ├── experiments.py # main, credit, shaping, curriculum, ... │ ├── recovery_demo.py │ ├── export_figures.py │ └── train_system.py ├── benchmarks/ │ ├── bench_rollout.py │ └── bench_policy.py ├── results/ # measured outputs, as text and JSON ├── tests/ │ ├── test_env.py │ ├── test_policy_rollout.py │ ├── test_advantages_grpo.py │ └── test_system_hf.py └── conftest.py
The plan
Can an agent that imitates successful runs be taught to handle what those runs never showed it? We build the system that answers this, and measure the answer.
Here is the answer, so you can read the rest with it in mind. Cloning works on the expert's path and breaks one step off it. Plain GRPO with an outcome reward did not fix that in our runs. Over 120 iterations, clean success went from 78% to 80%, perturbed from 13% to 3%, and failures from 21% to 19%. A likely cause: the clone rarely succeeds on the hardest levels, so most groups have no reward variance and there is little to reinforce. We have a probe that fits this, but it is unsaved, and one run below argues against it as the whole story. Two other runs did lift perturbed success: a variant with one on-policy step per iteration on a larger batch, which also changed the learning rate, minibatch and run length (13% to 31%) and filtered BC on the policy's own successes (27%). Every learning result here is a single seed, so read them as leads. The code is the main deliverable, and the runs show how to read it.
The task is small. An agent must find the right config file, change one value, and submit. Five tools are available: list, read, search, edit, submit. The reward is 1 if the final files are correct, and 0 otherwise.
This toy has the same shape as real agent training. There is a task, a stateful world, tool output the model cannot predict, and a verifier. Because it is small, a policy can be trained and scored end to end on a CPU. So we can measure each idea instead of sketching what should happen.
We go from imitating demonstrations to learning from consequences. The derivations live in the theory posts. Here we implement each idea and look at what it does.
The theory of this postReinforcement learning for agents, from first principlesClone the repo once. Every command below runs from its root.
$ git clone https://github.com/srini-anirudh/blog-coding-tutorials.git
$ cd blog-coding-tutorials
$ python -m venv .venv && .venv/bin/pip install -e ".[dev]"
Build the filesystem environment
Goal A small world with state, five tools and an exact reward, driven entirely by text.
Start with what a task is. A task has some config files, a sentence that says what to change, and the files that a correct agent leaves behind. Each file holds three key = value lines.
class Subtask:
"""One required edit. ``kind`` says how much the agent must discover before it can make it."""
kind: str # "direct" | "search" | "dependent" | "stale"
key: str # key to change
path: str # file that really holds ``key``
value: str # value it must end up with
source_key: str | None = None # dependent: the key whose value must be copied
source_path: str | None = None # dependent: the file that holds ``source_key``
stale_path: str | None = None # stale: the wrong path written in the task text
def text(self) -> str:
if self.kind == "direct":
return f"set {self.key} in {self.path} to {self.value}"
if self.kind == "stale":
return f"set {self.key} in {self.stale_path} to {self.value}"
if self.kind == "search":
return f"set {self.key} to {self.value}"
return f"set {self.key} in {self.path} to value of {self.source_key}"
def optimal_calls(self) -> int:
return {"direct": 1, "search": 2, "dependent": 3, "stale": 3}[self.kind]
The kind field is the difficulty. A direct task names the file. A search task names only the key, so the agent must find the file. A dependent task also hides the value: the agent must look up one key to learn what to write into another.
Now the environment. It has the five methods every RL environment has. Notice the types: strings go in and strings come out. A tiny word-level policy and a pretrained language model can both drive this, with no adapter inside the environment.
class FileSystemEnv:
def __init__(self, task: Task, max_steps: int | None = None, seed: int | None = None):
self.task = task
self.max_steps = max_steps or task.optimal_steps + 6
self.seed = task.seed if seed is None else seed
# -- the environment API -------------------------------------------------------------------------------
def reset(self) -> str:
self.files: Files = copy.deepcopy(self.task.files)
self.rng = random.Random(self.seed) # drives failure injection only
self.history: list[Step] = []
self.revealed: set[tuple[str, str]] = set() # milestones the agent has observed
self.submitted = False
self._obs = self.task.text
return self._obs
def observe(self) -> str:
return self._obs
def step(self, action: str) -> tuple[str, float, bool]:
"""Run one tool call. Returns (observation, reward, done)."""
assert not self.done(), "episode is over; call reset()"
parsed = parse_action(action)
if parsed is None:
obs = INVALID
else:
command, args = parsed
obs = inject(self.task.failures, command, self.rng) or self._run(command, args)
self._obs = obs
step = Step(action, obs, error=obs.startswith("error"))
self.history.append(step) # appended first: done() counts the history
step.reward = self.reward() if self.done() else 0.0
step.progress = self.progress()
return obs, step.reward, self.done()
def reward(self) -> float:
"""Outcome reward: 1 if the agent submitted and the files equal the target, else 0."""
return 1.0 if self.submitted and self.files == self.task.target() else 0.0
def done(self) -> bool:
return self.submitted or len(self.history) >= self.max_steps
Three details matter. reset deep-copies the files, so no episode can leak into the next. step never raises on a bad action: a malformed call becomes the observation error invalid input, because the model has to read that message and react. And reward is a pure function of the final files.
Here are the tools. Only edit and submit change anything.
def _run(self, command: str, args: list[str]) -> str:
if command == "list":
hits = sorted(p for p in self.files if p.split("/")[0] == args[0])
return " ".join(hits) if hits else "error no such dir"
if command == "read":
path = args[0]
if path not in self.files:
return MISSING
for key in self.files[path]:
self.revealed.add((path, key))
return " ; ".join(f"{k} = {v}" for k, v in self.files[path].items())
if command == "search":
hits = sorted(p for p, kv in self.files.items() if args[0] in kv)
for p in hits:
self.revealed.add((p, "*"))
return "found " + " ".join(hits) if hits else "found none"
if command == "edit":
path, key, value = args
if path not in self.files:
return MISSING
if key not in self.files[path]:
return "error no such key"
if value not in VALUES:
return INVALID
self.files[path][key] = value
return "ok"
self.submitted = True # submit
return "submitted"
revealed set records what the agent has observed. Shaped rewards use it later.Before any model exists, we need something that can solve every task. Otherwise a low score could mean the task is impossible. So we write a scripted expert. It is a generator: it yields an action and receives the tool's answer.
def call(action: str) -> Plan:
"""Issue one tool call; retry while the error is transient. The step budget bounds the retries."""
obs = yield action
while obs in TRANSIENT:
obs = yield action
return obs
def locate(key: str) -> Plan:
obs = yield from call(f"search {key}")
return obs.split()[1] # "found db/main" -> "db/main"
def lookup_value(key: str) -> Plan:
path = yield from locate(key)
obs = yield from call(f"read {path}")
return dict(kv.split(" = ") for kv in obs.split(" ; "))[key]
def solve(task_text: str) -> Plan:
for sub in parse_task(task_text):
value = sub["value"] or (yield from lookup_value(sub["src"]))
path = sub["path"] or (yield from locate(sub["key"]))
obs = yield from call(f"edit {path} {sub['key']} {value}")
if obs == MISSING: # stale path in the task text: find where the key really lives
path = yield from locate(sub["key"])
yield from call(f"edit {path} {sub['key']} {value}")
yield "submit"
return "done"
yield from keeps each plan readable. It parses only the task text and the tool output, the same inputs the policy gets.Run it across the five curriculum levels.
$ .venv/bin/python c12-agent-rl/scripts/demo_env.py
task [1]: set workers in db/base to 67
0: edit db/base workers 67 -> ok
1: submit -> submitted
success=True submitted=True truncated=False
task [2]: set ttl to 0
0: search ttl -> found jobs/main
1: edit jobs/main ttl 0 -> ok
2: submit -> submitted
success=True submitted=True truncated=False
task [3]: set ttl in web/base to value of host
0: search host -> found jobs/main
1: read jobs/main -> mode = 84 ; timeout = 84 ; host = 43
2: edit web/base ttl 43 -> ok
3: submit -> submitted
success=True submitted=True truncated=False
task [4]: set timeout in app/main to 17
0: edit app/main timeout 17 -> error no such file
1: search timeout -> error timeout
2: search timeout -> error timeout
3: search timeout -> found auth/base
4: edit auth/base timeout 17 -> ok
5: submit -> submitted
success=True submitted=True truncated=False
task [5]: set limit in web/main to value of timeout and set ttl to 8
0: search timeout -> found db/prod
1: read db/prod -> timeout = 54 ; depth = 97 ; rate = 50
2: edit web/main limit 54 -> ok
3: search ttl -> error timeout
4: search ttl -> found web/base
5: edit web/base ttl 8 -> ok
6: submit -> submitted
success=True submitted=True truncated=False
Record the trajectory as text and as tokens
Goal One sequence that holds the whole episode, with a mask that says which tokens the policy produced.
A trajectory is τ = (s0, a0, r0, ..., sT). We store it two ways. The text view is for reading and for the verifier. The tensor view is for training.
class Step:
action: str # what the agent emitted, e.g. "search port"
observation: str # what the tool returned, e.g. "found db/main"
reward: float = 0.0 # outcome reward arrives on the last step only
forced: bool = False # True for injected mistakes (perturbed starts); never trained on
error: bool = False # the tool returned an error
progress: float = 0.0 # potential Phi(s_{t+1}) in [0, 1]: fraction of task milestones reached
@dataclass
class Trajectory:
task_text: str
level: int
seed: int
steps: list[Step] = field(default_factory=list)
success: bool = False
submitted: bool = False
truncated: bool = False # ran out of steps or context
# tensor view, filled by the rollout or by ``codec.encode_trajectory``
tokens: list[int] = field(default_factory=list)
action_mask: list[int] = field(default_factory=list)
logprobs: list[float] = field(default_factory=list) # log pi_old(token) on action tokens, 0 elsewhere
step_of_token: list[int] = field(default_factory=list) # step index for action tokens, -1 elsewhere
state_positions: list[int] = field(default_factory=list) # index of the <act> token before each step
group: int = -1 # GRPO group id: trajectories of the same task share it
policy_version: int = 0
meta: dict = field(default_factory=dict)
The tensor layout is one line. Task, then action, then tool output, then the next action. This is one multi-turn conversation.
def encode_trajectory(traj: Trajectory, codec: Codec) -> Trajectory:
"""Fill the tensor view of a text trajectory (used for expert demos and for offline data).
Layout: <bos> task <act> a_0 <eos> <obs> o_0 <act> a_1 <eos> <obs> o_1 ... ; mask = 1 on a_t and its <eos>.
"""
tokens = prompt_ids(codec, traj.task_text)
mask, step_of, states = [0] * len(tokens), [-1] * len(tokens), []
for t, step in enumerate(traj.steps):
states.append(len(tokens) - 1)
action = codec.encode(step.action) + [codec.eos]
tokens += action
mask += [0 if step.forced else 1] * len(action)
step_of += [-1 if step.forced else t] * len(action)
if t < len(traj.steps) - 1:
obs = observation_ids(codec, step.observation)
tokens += obs
mask += [0] * len(obs)
step_of += [-1] * len(obs)
traj.tokens, traj.action_mask, traj.step_of_token, traj.state_positions = tokens, mask, step_of, states
traj.logprobs = [0.0] * len(tokens)
return traj
Look inside the tensors for one level 2 episode.
token id mask step
<bos> 1 0 -1
set 11 0 -1
ttl 69 0 -1
to 13 0 -1
0 74 0 -1
<act> 2 0 -1
search 8 1 0
ttl 69 1 0
<eos> 3 1 0
<obs> 4 0 -1
found 17 0 -1
jobs/main 58 0 -1
<act> 2 0 -1
edit 9 1 1
jobs/main 58 1 1
ttl 69 1 1
0 74 1 1
<eos> 3 1 1
<obs> 4 0 -1
ok 19 0 -1
<act> 2 0 -1
submit 10 1 2
<eos> 3 1 2
tokens torch.Size([1, 23]) action_mask torch.Size([1, 23]) actions tokens 10
state positions (the <act> tokens): [5, 12, 20]
| Tensor | Shape | Meaning |
|---|---|---|
| tokens | (B, T) | The whole episode, right-padded with <pad>. |
| action_mask | (B, T) | 1 on tokens the policy sampled. |
| old_logprobs | (B, T) | log πold of each sampled token, 0 elsewhere. |
| step_of_token | (B, T) | Which step each action token belongs to, −1 elsewhere. |
| logits | (B, T, V) | V = 174. The next-token distribution at each position. |
| values | (B, T) | The critic's estimate of the final reward at each position. |
Choose a policy that can learn on this machine
Goal A language-model-shaped policy that is fast enough to train and score many times on a CPU, with an interface a larger LM can fill.
The obvious choice is a pretrained LM with LoRA, as in C6 and C9. So we measure it first. The benchmark runs one GRPO iteration through each candidate: 16 episodes, then one update.
$ .venv/bin/python c12-agent-rl/benchmarks/bench_policy.py --tasks 4 --G 4 --hardware "AMD EPYC 7R13"
one GRPO iteration: 4 tasks x G=4 = 16 episodes, untrained policies, AMD EPYC 7R13, 8 CPU threads
policy device params trainable rollout s update s total s
TinyPolicy d=128 L=3 cpu 686,465 686,465 0.37 0.06 0.43
LlamaForCausalLM d=128 L=3 cpu 832,001 832,001 0.60 0.06 0.66
SmolLM2-135M + LoRA r=16 cpu 136,358,785 1,843,777 29.77 2.92 32.69
This settles it. One iteration through SmolLM2-135M with LoRA took 33 seconds on the AMD EPYC 7R13 CPU, 8 threads. The tiny policy took 0.43 seconds, about 76 times faster. Our main run has 120 iterations at 12 times this batch size. At the SmolLM2 rate that one run would take about 13 hours, and this post has eight experiments with many runs. So learning curves on a CPU have to come from a small model, and that is what we use. Nothing about the algorithm depends on the size. These timings ran once on a shared machine, so read the ratio, not the absolute numbers.
The policy is a small decoder-only transformer: 686,465 parameters. It reads one token sequence and predicts the next token. It generates an action token by token until <eos>. So everything that follows is the code that would also train a larger LM. Step 16 checks that by swapping one in.
class Block(nn.Module):
def __init__(self, cfg: PolicyConfig):
super().__init__()
self.n_heads = cfg.n_heads
self.norm1 = nn.RMSNorm(cfg.d_model)
self.qkv = nn.Linear(cfg.d_model, 3 * cfg.d_model, bias=False)
self.proj = nn.Linear(cfg.d_model, cfg.d_model, bias=False)
self.norm2 = nn.RMSNorm(cfg.d_model)
self.mlp = nn.Sequential(nn.Linear(cfg.d_model, 4 * cfg.d_model), nn.GELU(),
nn.Linear(4 * cfg.d_model, cfg.d_model))
def forward(self, x: torch.Tensor) -> torch.Tensor:
B, T, D = x.shape
q, k, v = self.qkv(self.norm1(x)).view(B, T, 3, self.n_heads, D // self.n_heads).unbind(2)
att = F.scaled_dot_product_attention(q.transpose(1, 2), k.transpose(1, 2), v.transpose(1, 2),
is_causal=True) # (B, H, T, d_h)
x = x + self.proj(att.transpose(1, 2).reshape(B, T, D))
return x + self.mlp(self.norm2(x))
class TinyPolicy(nn.Module):
"""Right-padded batches need no attention mask: with causal attention, position t never sees the padding
that comes after the sequence ends, so the logits at real positions are exact."""
def __init__(self, cfg: PolicyConfig):
super().__init__()
self.cfg = cfg
self.tok = nn.Embedding(cfg.vocab_size, cfg.d_model)
self.pos = nn.Embedding(cfg.max_len, cfg.d_model)
self.blocks = nn.ModuleList(Block(cfg) for _ in range(cfg.n_layers))
self.norm = nn.RMSNorm(cfg.d_model)
self.lm_head = nn.Linear(cfg.d_model, cfg.vocab_size, bias=False)
self.value_head = nn.Linear(cfg.d_model, 1)
self.apply(self._init)
@staticmethod
def _init(m: nn.Module) -> None:
if isinstance(m, (nn.Linear, nn.Embedding)):
nn.init.normal_(m.weight, std=0.02)
if isinstance(m, nn.Linear) and m.bias is not None:
nn.init.zeros_(m.bias)
def forward(self, input_ids: torch.Tensor) -> PolicyOutput:
"""input_ids: (B, T) -> logits (B, T, V), values (B, T)."""
T = input_ids.shape[1]
x = self.tok(input_ids) + self.pos(torch.arange(T, device=input_ids.device))
for block in self.blocks:
x = block(x)
h = self.norm(x)
return PolicyOutput(self.lm_head(h), self.value_head(h).squeeze(-1))
One log-probability helper does the alignment that causes most bugs in this kind of code. out[:, t] scores tokens[:, t], computed from the logits at position t - 1.
def token_logprobs(logits: torch.Tensor, tokens: torch.Tensor, temperature: float = 1.0) -> torch.Tensor:
"""log pi(tokens[:, t] | tokens[:, :t]) for t >= 1, aligned so out[:, t] scores tokens[:, t]; out[:, 0] = 0.
logits: (B, T, V) from a forward over ``tokens`` (B, T). Returns (B, T).
Dividing by the sampling temperature keeps the training distribution equal to the one we sampled from.
"""
logp = F.log_softmax(logits[:, :-1].float() / temperature, dim=-1)
picked = logp.gather(-1, tokens[:, 1:].unsqueeze(-1)).squeeze(-1) # (B, T-1)
return F.pad(picked, (1, 0))
| Tensor | Shape | Meaning |
|---|---|---|
| input_ids | (B, T) | Token ids of whole episodes, right-padded. |
| x | (B, T, 128) | Token embedding plus position embedding. |
| q, k, v | (B, T, 4, 32) | One projection split into 3 tensors and 4 heads, before the transpose. |
| att | (B, 4, T, 32) | Output of causal scaled dot-product attention. |
| logits | (B, T, V) | Next-token scores at every position. |
| values | (B, T) | One critic number per position. It is read at the <act> tokens. |
| token_logprobs | (B, T) | out[:, t] scores tokens[:, t], and out[:, 0] is 0. |
Clone the expert
Goal Teach the action syntax and the procedure from clean demonstrations, then measure how far that gets.
Behaviour cloning minimises L = −∑t log π(a*t | st). In code, this is cross-entropy with a loss mask. If you did C6, you have written this already. The only change is that the assistant turn is now many turns.
def expert_demos(n: int, levels: tuple[int, ...], codec: Codec, seed: int = 0) -> list[Trajectory]:
"""Clean expert episodes. Seeds start at 10**6 so they never collide with evaluation seeds."""
rng = random.Random(seed)
demos = []
for k in range(n):
task = sample_task(rng.choice(levels), seed=10**6 + seed * n + k)
demos.append(encode_trajectory(run_episode(FileSystemEnv(task), ScriptedExpert(task.text)), codec))
return demos
def bc_loss(policy, batch: Batch) -> torch.Tensor:
logp = token_logprobs(policy(batch.tokens).logits, batch.tokens) # (B, T)
return -(logp * batch.action_mask).sum() / batch.action_mask.sum()
$ .venv/bin/python c12-agent-rl/scripts/train_bc.py --demos 30000 --steps 3000 --layers 3
device=cpu threads=8 vocab=174 params=686,465 demos=30000
step 1 loss 5.2665
step 200 loss 0.1486
step 400 loss 0.0771
step 600 loss 0.0655
step 800 loss 0.0444
step 1000 loss 0.0666
step 1200 loss 0.0293
step 1400 loss 0.0426
step 1600 loss 0.0415
step 1800 loss 0.0335
step 2000 loss 0.0345
step 2200 loss 0.0277
step 2400 loss 0.0251
step 2600 loss 0.0321
step 2800 loss 0.0263
step 3000 loss 0.0436
trained in 155s
success (greedy, 300 unseen tasks per suite): {'clean': 0.797, 'perturbed': 0.143, 'failures': 0.2, 'long': 0.0}
Read the last line carefully. On 300 fresh tasks per suite, the policy succeeds 80% of the time. From perturbed starts it succeeds 14%. With failures injected it succeeds 20%. On long tasks it succeeds 0%. It never saw an error message or an and in a task, and it shows.
This is the cloned policy that the rest of the post starts from. A strong start is not the aim. It knows the action syntax and the procedure, which gives RL something to work with.
Break the clone with one small mistake
Goal Put the policy one harmless step off the expert's path, and measure what happens.
A cloned policy has seen only the expert's states. The expert never errs. So the moment the policy makes any mistake, or the world behaves differently, it is somewhere it has never been. This is the compounding-error argument from the DAgger paper. We can measure it directly.
Derivation inWhy cloning is not enoughA perturbed start plays k wrong actions before the policy takes over: a search for an unrelated key, a read of a missing file, a malformed call. Each is harmless. The files do not change, and the budget still leaves room to finish. To make "a state no demonstration contains" a number, we abstract each state into its history of action types and outcome types.
def random_mistake(task: Task, rng: random.Random) -> str:
needed = {s.key for s in task.subtasks} | {s.source_key for s in task.subtasks}
kind = rng.choice(["search", "read", "list", "malformed", "missing"])
if kind == "search":
return f"search {rng.choice([k for k in KEYS if k not in needed])}"
if kind == "read":
return f"read {rng.choice(sorted(task.files))}"
if kind == "list":
return f"list {rng.choice(DIRS)}"
if kind == "malformed":
return rng.choice(["edit", "search", "read port", f"edit {rng.choice(sorted(task.files))}"])
return f"read {rng.choice([p for p in PATHS if p not in task.files])}"
def signature(traj: Trajectory, t: int) -> tuple[str, ...]:
"""Abstract state before step t: the task level plus the (action type, outcome type) pairs so far."""
hist = tuple(f"{s.action.split()[0] if s.action.split() else '?'}:{_outcome(s.observation)}"
for s in traj.steps[:t])
return (f"L{traj.level}",) + hist
def seen_signatures(demos: list[Trajectory]) -> set[tuple[str, ...]]:
return {signature(d, t) for d in demos for t in range(len(d.steps))}
def unseen_rate(trajs: list[Trajectory], seen: set[tuple[str, ...]]) -> float:
"""Fraction of the policy's own decisions (forced steps excluded) taken in a state absent from the demos."""
states = [signature(tr, t) for tr in trajs for t, s in enumerate(tr.steps) if not s.forced]
return sum(s not in seen for s in states) / max(len(states), 1)
$ .venv/bin/python c12-agent-rl/scripts/distribution_shift.py --ckpt c12-agent-rl/runs/bc.pt
9 distinct abstract states in 5000 demonstrations
mistakes success expert unseen-state rate submitted
0 0.797 1.000 0.000 1.000
1 0.173 1.000 0.946 0.963
2 0.087 1.000 0.992 0.933
3 0.043 1.000 1.000 0.737
task [2]: set ttl to 0
0: read jobs/main -> workers = 48 ; host = 76 ; ttl = 87 (forced)
1: edit edit db/dev ttl 30 -> error invalid input
2: edit 0 ttl 0 -> error no such file
3: submit -> submitted
success=False submitted=True truncated=False
step 0: state seen in demos = True
step 1: state seen in demos = False
step 2: state seen in demos = False
step 3: state seen in demos = False
task [3]: set depth in cache/base to value of timeout
0: search host -> found jobs/dev (forced)
1: read jobs/dev -> mode = 42 ; host = 80 ; level = 63
2: edit cache/base depth 42 -> ok
3: submit -> submitted
success=False submitted=True truncated=False
step 0: state seen in demos = True
step 1: state seen in demos = True
step 2: state seen in demos = True
step 3: state seen in demos = True
One harmless step takes success from 80% to 17%. Three steps take it to 4%. The expert stays at 100% from the same starts, so the task never became harder. Look at the first trajectory. After one correct-looking read, the policy emits edit edit db/dev ttl 30. No demonstration contains that action. It is what a next-token model does outside its data.
Let the policy act in the environment
Goal Generate whole episodes with the current policy, write a slow version first, then make it fast and prove the two agree.
DAgger would ask an expert to label the new states. For agents, that expert rarely exists. So the policy learns from its own consequences instead, and that starts with letting it act. Here is the naive rollout. It handles one episode and one token at a time.
@torch.no_grad()
def rollout_one(policy, codec: Codec, env: FileSystemEnv, *, temperature: float = 1.0,
forced: list[str] | None = None, max_action_tokens: int = 6, max_len: int = 384,
device: str = "cpu") -> Trajectory:
tr = new_trajectory(env, prompt_ids(codec, env.reset()))
forced = list(forced or [])
while not env.done():
step = len(env.history)
tr.state_positions.append(len(tr.tokens) - 1) # the <act> token: the state the action is taken in
is_forced = bool(forced)
if is_forced: # an injected mistake: played, never trained on
text = forced.pop(0)
append(tr, codec.encode(text) + [codec.eos], None, step)
else:
ids, lps = [], []
while len(ids) < max_action_tokens:
x = torch.tensor([tr.tokens + ids], device=device) # (1, T)
tok, lp = sample_token(policy(x).logits[:, -1], temperature) # next-token logits (1, V)
ids.append(int(tok))
lps.append(float(lp))
if ids[-1] == codec.eos:
break
append(tr, ids, lps, step)
text = codec.decode([i for i in ids if i != codec.eos])
obs, _, done = env.step(text)
env.history[-1].forced = is_forced
if done:
break
if len(tr.tokens) + max_action_tokens + OBS_BUDGET > max_len: # out of context: end the episode unsubmitted
break
append(tr, observation_ids(codec, obs), None, step)
return finish(tr, env)
It works. It is also slow, so we profile it.
$ .venv/bin/python c12-agent-rl/benchmarks/bench_rollout.py --hardware "AMD EPYC 7R13"
episodes=64, levels 1-5, greedy decoding, AMD EPYC 7R13, 8 CPU threads
rollout device batch seconds episodes/s forwards
naive cpu 1 1.17 54.6 777
batched cpu 8 0.52 122.4 197
batched cpu 64 0.26 248.8 43
batched cpu 256 0.90 285.3 53
time inside policy forward: naive 94%, batched 91%
slow tools: every call sleeps as if it ran a command (batched rollout, batch 64)
tool latency workers seconds episodes/s
0 ms 0 0.26 247.2
0 ms 8 0.22 291.2
0 ms 32 0.29 221.0
20 ms 0 5.09 12.6
20 ms 8 1.01 63.1
20 ms 32 0.55 117.3
The naive rollout runs 54.6 episodes per second with 777 forward passes. Batching 64 episodes runs 248.8 per second with 43 forwards. The policy forward takes 94% of the naive run and 91% of the batched run. So the model is the bottleneck, and batching is the fix.
Slow tools change this. At 20 ms per call, 64 episodes take 5.1 seconds with no workers and 0.6 seconds with 32 workers. Real tools can take far longer than 20 ms, in which case a real system spends its time waiting on them.
A GPU only pays off at a large batch for a policy this small. On an NVIDIA H100 80GB HBM3, torch 2.15.0+cu132, batch 64 ran at 147.9 episodes per second, against 223.6 on the CPU rows of the same file, and the GPU figure includes the first CUDA call. At batch 256 the GPU ran at 822.7 episodes per second, against 277.7 on the CPU. Both are single runs from results/bench_rollout_gpu.txt.
@torch.no_grad()
def sample_actions(policy, prefixes: list[list[int]], codec: Codec, temperature: float,
max_tokens: int, device: str) -> list[tuple[list[int], list[float]]]:
"""Generate one action for each prefix. Returns (token ids, log-probs) per row; ids end in <eos> if it fired."""
B = len(prefixes)
lens = torch.tensor([len(p) for p in prefixes], device=device) # (B,)
buf = torch.full((B, int(lens.max()) + max_tokens), codec.pad, dtype=torch.long, device=device)
for i, p in enumerate(prefixes):
buf[i, : len(p)] = torch.tensor(p, device=device)
out_tok = torch.full((B, max_tokens), -1, dtype=torch.long, device=device) # -1 = not generated
out_lp = torch.zeros(B, max_tokens, device=device)
alive = torch.arange(B, device=device) # rows still generating
for k in range(max_tokens):
L = int(lens[alive].max())
logits = policy(buf[alive, :L]).logits # (b, L, V)
tok, lp = sample_token(logits[torch.arange(len(alive), device=device), lens[alive] - 1], temperature)
buf[alive, lens[alive]] = tok
lens[alive] += 1
out_tok[alive, k], out_lp[alive, k] = tok, lp
alive = alive[tok != codec.eos]
if len(alive) == 0:
break
out_tok, out_lp = out_tok.tolist(), out_lp.tolist()
result = []
for ids, lps in zip(out_tok, out_lp):
n = sum(i >= 0 for i in ids)
result.append((ids[:n], lps[:n]))
return result
def test_rollout_logprobs_match_a_training_forward():
"""pi_old from sampling == pi_theta recomputed on the whole sequence: the GRPO ratio starts at exactly 1."""
pol = tiny(1)
torch.manual_seed(0)
trajs = rollout_batch(pol, codec, [FileSystemEnv(sample_task(2, i)) for i in range(8)], temperature=1.0)
batch = collate(trajs, codec.pad)
logp = token_logprobs(pol(batch.tokens).logits, batch.tokens)
torch.testing.assert_close(logp * batch.action_mask, batch.old_logprobs, atol=1e-5, rtol=0)
| Tensor | Shape | Meaning |
|---|---|---|
| lens | (B,) | Current length of each row. It marks where the next token goes. |
| buf | (B, Lmax + K) | Prefixes, right-padded, with room for K new tokens. |
| alive | (b,) | Row indices still generating. It shrinks as rows emit <eos>. |
| logits | (b, L, V) | One forward over the rows still alive, cut to the longest of them. |
| out_tok, out_lp | (B, K) | Sampled ids and their log-probabilities. -1 marks a token that was not generated. |
Outcome reward and group-relative advantages
Goal Turn one bit of feedback per episode into a signed signal, with no critic.
We start with the honest reward: 1 if the files are right, 0 otherwise. It cannot be gamed by looking busy. It also says nothing about which action helped. To get a gradient from it, GRPO samples G trajectories for the same task and compares them with each other.
Derivation inGRPO from first principlesdef group_relative(rewards: torch.Tensor, groups: torch.Tensor, scale: bool = True,
eps: float = 1e-4) -> torch.Tensor:
"""rewards (N,), groups (N,) integer group ids -> advantages (N,).
``std`` is the unbiased sample std, as in TRL's GRPOTrainer. ``scale=False`` keeps only the mean baseline
(the Dr. GRPO variant), which stops low-variance groups from being amplified.
"""
adv = torch.zeros_like(rewards)
for g in groups.unique():
m = groups == g
r = rewards[m]
adv[m] = (r - r.mean()) / (r.std() + eps) if scale else r - r.mean()
return adv
Try it. Click a trajectory to change its reward. Notice what happens when every reward is the same.
| Rewards | A for each winner | A for each loser | Without the std |
|---|---|---|---|
| 1 winner, 7 losers | +2.474 | −0.353 | +0.875 and −0.125 |
| 4 winners, 4 losers | +0.935 | −0.935 | +0.5 and −0.5 |
| 7 winners, 1 loser | +0.353 | −2.474 | +0.125 and −0.875 |
| All fail or all win | 0 | 0 | 0 |
| Tensor | Shape | Meaning |
|---|---|---|
| rewards | (N,) | One return per trajectory. N = tasks × G. |
| groups | (N,) | Integer group id. Members of a group share one task. |
| adv | (N,) | One advantage per trajectory. It sums to about 0 within each group. |
Write the GRPO update and train
Goal A clipped surrogate over action tokens of whole episodes, and a first RL run that we read honestly.
The update is the same as in C6, applied to multi-turn sequences. Environment tokens stay out of the loss because of the mask. Everything else is PPO's clip and an optional KL to a reference policy.
def grpo_loss(policy, batch, adv_tok: torch.Tensor, cfg: GRPOConfig, ref_policy=None,
value_targets: torch.Tensor | None = None, value_mask: torch.Tensor | None = None):
out = policy(batch.tokens)
logp = token_logprobs(out.logits, batch.tokens, cfg.temperature) # (B, T)
mask = batch.action_mask
n = mask.sum().clamp(min=1)
ratio = (logp - batch.old_logprobs).exp()
surr = torch.min(ratio * adv_tok, ratio.clamp(1 - cfg.clip, 1 + cfg.clip) * adv_tok)
loss = -(surr * mask).sum() / n
stats = {"clip_frac": (((ratio - 1).abs() > cfg.clip).float() * mask).sum().item() / n.item()}
if ref_policy is not None and cfg.kl_beta > 0:
with torch.no_grad():
ref = token_logprobs(ref_policy(batch.tokens).logits, batch.tokens, cfg.temperature)
kl = (ref - logp).exp() - (ref - logp) - 1 # k3, >= 0
loss = loss + cfg.kl_beta * (kl * mask).sum() / n
stats["kl"] = ((kl * mask).sum() / n).item()
if value_targets is not None:
v_loss = (((out.values - value_targets) ** 2) * value_mask).sum() / value_mask.sum().clamp(min=1)
loss = loss + cfg.value_coef * v_loss
stats["value_loss"] = v_loss.item()
return loss, stats
The online loop is short. It samples tasks, rolls out G episodes per task, and updates.
def group_rollouts(policy, codec: Codec, episodes: list[Episode], G: int, cfg: GRPOConfig, device: str,
version: int = 0, group_offset: int = 0) -> list[Trajectory]:
"""G trajectories per task. Members share the task and the start; their tool-failure seeds differ."""
envs, forced, groups = [], [], []
for g, ep in enumerate(episodes):
task = sample_task(ep.task_level, ep.seed)
for j in range(G):
envs.append(FileSystemEnv(task, seed=ep.seed * 31 + j))
forced.append(ep.forced)
groups.append(group_offset + g)
trajs = rollout_batch(policy, codec, envs, forced=forced, temperature=cfg.temperature, device=device,
version=version)
for t, g in zip(trajs, groups):
t.group = g
return trajs
def train_online(policy, codec: Codec, sampler, cfg: GRPOConfig, *, iterations: int, tasks_per_iter: int = 32,
G: int = 8, device: str = "cpu", ref_policy=None, curriculum: Curriculum | None = None,
eval_fn=None, eval_every: int = 10, log=print) -> list[dict]:
opt = torch.optim.AdamW(policy.parameters(), lr=cfg.lr, weight_decay=0.0)
ref_policy = ref_policy or (copy.deepcopy(policy).eval() if cfg.kl_beta > 0 else None)
history = []
for it in range(1, iterations + 1):
t0 = time.time()
if curriculum is not None:
sampler.mix = curriculum.mix
trajs = group_rollouts(policy, codec, sampler.sample(tasks_per_iter), G, cfg, device, version=it)
t1 = time.time()
stats = update(policy, opt, trajs, cfg, pad=codec.pad, device=device, ref_policy=ref_policy, seed=it)
row = {"iter": it, **group_stats(trajs, cfg.reward), **stats,
"t_rollout": t1 - t0, "t_update": time.time() - t1}
if curriculum is not None:
row["stage"] = curriculum.stage
curriculum.record(row["success"])
if eval_fn is not None and (it % eval_every == 0 or it == iterations):
row["eval"] = eval_fn(policy)
history.append(row)
log(_fmt(row))
return history
| Quantity | Shape or size | Meaning |
|---|---|---|
| tasks per iteration | 24 | Sampled from levels 1 to 5, half of level 1 to 3 starts perturbed. |
| G | 8 | Rollouts per task, so 192 episodes per iteration. |
| minibatch tokens | (64, T) | T is the longest episode in the minibatch. |
| adv_tok | (64, T) | Per-token advantage, zero off the action mask. |
| ratio | (64, T) | exp(log πθ − log πold), exactly 1 before the first step. |
$ .venv/bin/python c12-agent-rl/scripts/experiments.py main
--- grpo
it 1 success 0.29 return 0.29 zero-var 0.75 steps 4.3 clip 0.142 0.9s+1.1s
it 20 success 0.29 return 0.29 zero-var 0.83 steps 4.1 clip 0.095 0.6s+0.7s eval clean=0.80 perturbed=0.00 failures=0.20 long=0.00
it 40 success 0.23 return 0.23 zero-var 0.71 steps 5.6 clip 0.246 1.3s+0.8s eval clean=0.79 perturbed=0.03 failures=0.23 long=0.00
it 60 success 0.17 return 0.17 zero-var 0.54 steps 7.2 clip 0.107 2.5s+1.0s eval clean=0.79 perturbed=0.01 failures=0.19 long=0.00
it 80 success 0.11 return 0.11 zero-var 0.92 steps 8.5 clip 0.014 3.0s+1.0s eval clean=0.81 perturbed=0.02 failures=0.20 long=0.00
it 100 success 0.15 return 0.15 zero-var 0.83 steps 8.5 clip 0.019 3.5s+1.2s eval clean=0.81 perturbed=0.02 failures=0.21 long=0.00
it 120 success 0.10 return 0.10 zero-var 0.88 steps 8.6 clip 0.067 3.7s+1.3s eval clean=0.80 perturbed=0.03 failures=0.19 long=0.00
Read the eval columns first. Over 120 iterations and 8 minutes, greedy success went clean from 78% to 80%, perturbed from 13% to 3%, failures from 21% to 19%, long from 0% to 0%. So this run did not improve the policy, and perturbed success ended lower. These RL runs evaluate on 150 tasks per suite, so their starting values differ slightly from the 300-task numbers in step 4. The run is a single seed.
The sampled columns tell the same story. Sampled success averaged 0.21 over the first 10 iterations and 0.20 over the last 10, so it did not move. What did move is the shape of the episodes. The share that submitted fell from 0.93 to 0.35 (the same two means), and episodes grew from 4.5 to 7.9 steps. Greedy decoding still picks the cloned behaviour, so the eval columns hide most of this drift.
Why so little learning? We have a likely cause, and a probe that supports part of it. We sampled the cloned policy at temperature 1, as training does, on 800 training seeds at each of the two hardest levels.
policy bc.pt, temperature 1.0, 800 sampled episodes per level, seeds 10**6 + i
level success hit an error succeeded after an error submitted
4 159 586 9 778
5 0 782 0 797
On level 4, 159 of 800 episodes succeeded (20%), 586 hit an error, and only 9 of those succeeded. On level 5, 0 of 800 succeeded. A group of eight is flat whenever all its members fail or all succeed, and a flat group gives no gradient. The zero-var column averaged 0.80 over the first 10 iterations and 0.80 over the last 10. Levels 1 and 2, which the clone already solves, add flat groups of the all-win kind, so the probe covers only part of the flat share. The probe is a scratch script and is not saved in results/. A second run of it with another seed, also unsaved, gave 563 errors and 13 recoveries on level 4. Read these counts as roughly 570 and 10. Short 30-iteration checks with a lower learning rate, a KL penalty, the mean-only advantage and temperature 0.7 looked the same, and those are unsaved too.
One variant gave a gain on one suite. The default update reuses each batch for two epochs of minibatch steps. After the first step the ratios move away from 1, and the main run had 0.00 to 0.33 of its action tokens per iteration outside the clip range of 0.8 to 1.2. The variant below takes one gradient step per iteration on a batch four times larger, so every update is exactly on-policy. It also changes the learning rate (3e-4 instead of 2e-4), the minibatch size (768 instead of 64) and the length of the run (60 iterations instead of 120). It sees 46,080 episodes in total, against 23,040.
def onpolicy() -> None:
"""The main run with one on-policy gradient step per iteration on a 4x larger batch (96 tasks x G=8)."""
cfg = GRPOConfig(lr=3e-4, epochs=1, minibatch=768)
dump("onpolicy", run("grpo on-policy", FULL_MIX, cfg, iterations=ARGS.iters or 60, tasks=96, G=8, eval_every=20))
GRPOConfig defaults stay.$ .venv/bin/python c12-agent-rl/scripts/experiments.py onpolicy--- grpo on-policy
it 1 success 0.27 return 0.27 zero-var 0.75 steps 4.4 clip 0.000 4.5s+4.6s
it 20 success 0.25 return 0.25 zero-var 0.67 steps 7.0 clip 0.000 12.2s+4.1s eval clean=0.77 perturbed=0.15 failures=0.21 long=0.00
it 40 success 0.27 return 0.27 zero-var 0.74 steps 4.3 clip 0.000 2.1s+1.3s eval clean=0.78 perturbed=0.27 failures=0.22 long=0.00
it 60 success 0.22 return 0.22 zero-var 0.79 steps 7.2 clip 0.000 10.5s+3.8s eval clean=0.79 perturbed=0.31 failures=0.22 long=0.00
The perturbed suite rose from 13% to 31%. Failures went from 21% to 22%, and clean stayed at 79%. Long stayed at 0%. Perturbed success rose at every evaluation: 15%, 27%, 31%. The clip fraction is 0 on every iteration, as it must be when the old and new policy are the same at the only step. This run took 13 minutes. Sampled success averaged 0.24 over its first 10 iterations and 0.27 over its last 10, with 7.2 steps per episode at the end, so the gain shows only in the greedy perturbed suite. With 150 tasks the standard error of one score is about 3 to 4 points. It is one seed, so treat it as a lead, not a result.
Trajectory-level or action-level credit
Goal Compare one advantage per episode against one advantage per action, on the long-horizon tasks.
Trajectory-level credit gives every action of an episode the same advantage. A winning episode with a pointless retry rewards the retry. Over many episodes the noise averages out, but it costs samples. The horizon makes this worse.
The alternative is a critic. The value head estimates V(st), the expected final reward from a state. The difference V(st+1) − V(st) then says whether one action helped. GAE blends these one-step differences.
Derivation inCredit over fifty stepsdef gae(rewards: list[float], values: list[float], gamma: float = 1.0, lam: float = 0.95) -> list[float]:
"""Per-step advantages for one episode. ``values[t]`` = V(s_t); the episode ends after the last step."""
adv, running = [0.0] * len(rewards), 0.0
for t in reversed(range(len(rewards))):
next_v = values[t + 1] if t + 1 < len(values) else 0.0
delta = rewards[t] + gamma * next_v - values[t]
running = delta + gamma * lam * running
adv[t] = running
return adv
def step_advantages(trajs: list[Trajectory], cfg: GRPOConfig,
values: list[list[float]] | None = None) -> tuple[list[list[float]], list[list[float]]]:
"""Per-step advantages and value targets for each trajectory."""
rewards = [REWARDS[cfg.reward](t) for t in trajs]
if cfg.credit == "trajectory":
R = torch.tensor([sum(r) for r in rewards])
A = group_relative(R, torch.tensor([t.group for t in trajs]), scale=cfg.scale_std)
return [[float(a)] * t.n_steps for a, t in zip(A, trajs)], [[] for _ in trajs]
assert values is not None, "action-level credit needs V(s_t) from the value head"
adv = [gae(r, v, cfg.gamma, cfg.lam) for r, v in zip(rewards, values)]
targets = [[a + v for a, v in zip(ad, vs)] for ad, vs in zip(adv, values)]
flat = torch.tensor([a for ad in adv for a in ad])
mu, sd = flat.mean(), flat.std() + 1e-4 # whiten over the batch, as PPO does
return [[(a - mu.item()) / sd.item() for a in ad] for ad in adv], targets
to_tokens then scatters them onto action tokens.| Tensor | Shape | Meaning |
|---|---|---|
| values | (B, T) | The value head's output at every position. We read it only at the <act> tokens. |
| V(st) | nsteps per episode | A Python list per trajectory. Episodes have different lengths. |
| adv_tok | (B, T) | Each step's advantage copied onto that step's action tokens, 0 elsewhere. |
| value_targets | (B, T) | GAE plus V(st), placed at the <act> positions. |
| value_mask | (B, T) | 1 at the <act> positions, so the critic trains only there. |
$ .venv/bin/python c12-agent-rl/scripts/experiments.py credit
(10-iteration means, first -> last)
run failures long success submit zero-var steps
trajectory 22% 0% 0.04->0.06 1.00->0.14 0.87->0.84 3.1->10.3
action 21% 0% 0.06->0.05 1.00->1.00 0.84->0.90 4.0->3.9
action+potential 23% 0% 0.05->0.05 0.99->0.97 0.86->0.87 4.3->4.9
Replay real episodes from a trained policy. Choose a group, a member and a credit mode. Find a wasted step and see what each mode says about it.
On the evaluation suites the three runs are the same. Failures ended at 22%, 21% and 23%, against 21% at the start, and long stayed at 0% in each. Sampled success stayed low (0.04 to 0.06, 0.06 to 0.05 and 0.05 to 0.05 as 10-iteration means), and 0.84 to 0.90 of the groups were flat at the end. There was little signal for any credit scheme to divide up.
One difference did show up in the sampled episodes. Under trajectory credit, the share that submitted fell from 1.00 to 0.14 and episodes grew from 3.1 to 10.3 steps. Under action credit they stayed at 3.9 steps with 1.00 submitted. That is one seed, and the greedy suites do not show it. The comparison is also not clean: action credit adds a critic, and it whitens advantages over the whole batch instead of within each group, so it can give a gradient on a group where every reward is equal. Treat the difference as a lead, not as evidence about credit alone.
The figure below shows what the two kinds of credit do with a signal when there is one. Only level 4 had groups with a win.
Shape the reward, then hack it on purpose
Goal Add intermediate rewards, see what a reasonable-looking one pays for, and fix it with a form that cannot be farmed.
Outcome rewards are sparse. Step 8 showed how sparse: most groups were flat. So people add milestones. Here are two ways, in the same file.
def activity(traj: Trajectory, bonus: float = 0.2) -> list[float]:
r = [bonus if (not s.error and s.action != "submit") else 0.0 for s in traj.steps]
if r:
r[-1] += traj.outcome
return r
Think about what the highest-scoring behaviour is. Solving a level 2 task gives 0.2 + 0.2 + 1 = 1.4. Looping read until the step budget ends gives 0.2 per call, for nine calls: 1.8. The reward prefers not solving the task. We wrote it that way on purpose, in one line.
Check that claim against the real reward functions. These episodes were played in the real environment. Choose a behaviour and a reward.
rewards.py on scripted episodes of one level 2 task. No policy and no training are involved, so these numbers are exact on any machine.$ .venv/bin/python c12-agent-rl/scripts/experiments.py shaping
(10-iteration means, first -> last)
reward clean start->final success return submit steps
outcome 78%->81% 0.68->0.64 0.68->0.64 1.00->0.96 3.5->3.8
activity 78%->73% 0.68->0.61 1.18->1.16 1.00->0.89 3.5->4.2
potential 78%->81% 0.68->0.64 0.68->0.64 1.00->0.96 3.5->3.8
The result is consistent with a hack, and one seed cannot separate it from noise. Averaged over 10 iterations, the activity run's return went from 1.18 to 1.16, so the trainer saw no gain. Its sampled success went from 0.68 to 0.61, and the outcome run's from 0.68 to 0.64. Single iterations swing between 0.44 and 0.82, so these two are not clearly different. The submit share fell from 1.00 to 0.89 and episodes grew from 3.5 to 4.2 steps, against 0.96 and 3.8 under the outcome reward. Clean greedy success ended at 73%, against 81% with the outcome reward and 78% at the start. That gap is about 1.6 standard errors.
The figure's box shows one trace. It is the sampled episode with the most steps, picked by us, so it is the clearest case and not a typical one. Before training, the policy copied a wrong value and submitted. After training, on the same task, it read the same file again and again until the budget ran out. That earns more under this reward than an honest failure, so it is the behaviour a hack would produce. One trace does not show that the reward caused it.
The potential run ended at exactly the outcome run's numbers: 81% clean and 0.64 sampled success over the last 10 iterations. That is what the Insight below predicts.
The fix is potential-based shaping (Ng, Harada and Russell, 1999). Define Φ(s), the fraction of milestones reached. Pay Φ(st+1) − Φ(st) on each step. Credit arrives early, but losing progress costs what gaining it paid.
def potential(traj: Trajectory, gamma: float = 1.0) -> list[float]:
r = outcome(traj)
phi_prev = 0.0 # Phi(s_0) = 0: nothing found or edited yet
for t, s in enumerate(traj.steps):
phi_next = s.progress # the env sets Phi = 0 once the episode is over
if t == traj.n_steps - 1 and not s.reward and not traj.submitted:
phi_next = 0.0 # context-truncated episodes end too
r[t] += gamma * phi_next - phi_prev
phi_prev = phi_next
return r
Exploration: temperature, group size, diverse starts
Goal Measure what controls how much signal each batch of rollouts carries.
GRPO learns only from groups that disagree. So exploration has a concrete meaning here: it is whatever makes a group's outcomes differ. We measure the fraction of zero-variance groups, because each one is a batch of rollouts that taught nothing.
Three levers are in the code, and we measure two of them. Sampling temperature changes how often a group tries something else. Group size G changes how likely one member is to get lucky. The task sampler supplies diverse tasks and diverse starts, which we did not vary here. The temperature must also enter the training log-probabilities, otherwise the ratio no longer describes the sampling distribution. token_logprobs takes it as an argument for that reason.
class TaskSampler:
"""Diverse tasks and diverse initial states. Training seeds start at 10**6, away from the eval seeds."""
def __init__(self, mix: TaskMix, seed: int = 0):
self.mix, self.rng, self.next_seed = mix, random.Random(seed), 10**6 + 10**5 * seed
def sample(self, n: int) -> list[Episode]:
levels, weights = zip(*self.mix.levels.items())
out = []
for _ in range(n):
level, seed = self.rng.choices(levels, weights)[0], self.next_seed
self.next_seed += 1
k = self.rng.choice([1, 2]) if level <= 3 and self.rng.random() < self.mix.p_perturb else 0
out.append(Episode(level, seed, perturbations(sample_task(level, seed), k, seed) if k else []))
return out
$ .venv/bin/python c12-agent-rl/scripts/experiments.py exploration
$ .venv/bin/python c12-agent-rl/scripts/experiments.py groupsize
run zero-var(mean) success(last10) submit(last10) perturbed failures long
T=0.5 0.82 0.21 0.32 1% 21% 0%
T=1.0 0.78 0.20 0.55 1% 19% 0%
T=1.5 0.70 0.16 0.59 3% 19% 0%
G=2 0.90 0.22 0.45 0% 21% 0%
G=4 0.84 0.20 0.77 5% 20% 0%
G=8 0.78 0.20 0.55 1% 19% 0%
G=16 0.68 0.24 0.61 19% 21% 0%
Averaged over each run, the share of flat groups was 0.82 at T=0.5, 0.78 at T=1.0, 0.70 at T=1.5. Temperature changed that share a little and changed nothing that mattered. Every temperature ended with perturbed success at 1% to 3%, down from 13%, and failures at 19% to 21%. A likely reason is that almost no sampled episode on the hard levels succeeds, so wider sampling finds nothing new to reinforce. We did not test that. We also did not vary the starts: every run here uses the same task sampler, with half of the level 1 to 3 starts perturbed.
Group size shows one exception. At 192 rollouts per iteration, the flat share averaged 0.90 at G=2, 0.84 at G=4, 0.78 at G=8, 0.68 at G=16. G = 2, 4 and 8 ended with perturbed success at 0%, 5% and 1%. G = 16, with only 12 tasks per iteration, ended at 19%. It is one seed on 150 tasks, and the other three runs went the opposite way, so we do not read it as a result. The G = 8 row is the same run as the T = 1.0 row, so it appears twice.
Curriculum: from one tool to long horizons
Goal Raise the difficulty only when the policy is ready, and compare that against starting at the hardest level.
The chance that a sampled episode solves a long task shrinks with its length. Below some point, whole groups fail and the update has nothing to work on. A curriculum keeps the policy where it sometimes succeeds. The ladder has five rungs.
class Curriculum:
"""Move to the next stage when the rolling training success on the current stage passes ``threshold``."""
stages: list[TaskMix]
threshold: float = 0.7
window: int = 5
stage: int = 0
recent: list[float] = field(default_factory=list)
@property
def mix(self) -> TaskMix:
return self.stages[self.stage]
def record(self, success: float) -> bool:
self.recent = (self.recent + [success])[-self.window:]
ready = len(self.recent) == self.window and sum(self.recent) / self.window >= self.threshold
if ready and self.stage < len(self.stages) - 1:
self.stage, self.recent = self.stage + 1, []
return True
return False
$ .venv/bin/python c12-agent-rl/scripts/experiments.py curriculum
run clean perturbed failures long stage(0=1st) success(10-it means) submit(10-it means)
hardest first 78% 13% 21% 0% - 0.00->0.00 1.00->1.00
final mix 47% 1% 21% 0% - 0.13->0.12 0.62->0.22
staged 74% 1% 21% 0% 0 0.22->0.16 0.91->0.78
None of the three schedules improved anything. On the long suite they ended at 0%, 0% and 0%.
- Hardest first trained on level 5 only. Not one group ever had a win (the flat share was 1.00 over the last 10 iterations), so the policy never changed. Every suite stayed at its start value.
- The final mix is levels 2 to 5 at weights 1, 1, 2 and 4, so half of the tasks are level 5. It lowered clean success from 78% to 47%. Its submit share fell from 0.62 to 0.22 and episodes grew to 9.3 steps. That is the same mix the staged run was meant to reach, and a heavy level 5 share gives the update mostly failed episodes.
- The staged curriculum never left stage 1 of 3. Its first stage is level 3 with half the starts perturbed, and its sampled success averaged 0.16 over the last 10 iterations, far below the 0.75 threshold. So it trained on that one mix for 100 iterations, and the promotion rule never fired.
So this run does not test whether a curriculum helps. It shows that the ladder only works if the first rung can be climbed. Here the cloned policy fails half-perturbed level 3 starts too often to get past the threshold. A lower threshold, or a first stage with clean starts only, would be the next thing to try.
Failure recovery: timeouts, bad input, missing files
Goal Inject the ways tools really fail, reward finishing anyway, and look at the behaviour that appears.
Real tools can hang, crash, reject arguments and point at files that have moved. Demonstrations from clean runs show none of this. So we inject the failures in the environment, seeded per episode. A failed call costs a step, so a policy that panics runs out of budget.
TIMEOUT = "error timeout"
TOOL_ERROR = "error internal"
INVALID = "error invalid input"
MISSING = "error no such file"
TRANSIENT = (TIMEOUT, TOOL_ERROR, INVALID)
@dataclass(frozen=True)
class FailureConfig:
p_timeout: float = 0.0
p_tool_error: float = 0.0
p_invalid: float = 0.0
@property
def enabled(self) -> bool:
return self.p_timeout + self.p_tool_error + self.p_invalid > 0
def inject(cfg: FailureConfig, command: str, rng: random.Random) -> str | None:
"""Return an error message to replace the tool's real output, or None to let the call through."""
if command == "submit":
return None
if command in ("search", "read") and rng.random() < cfg.p_timeout:
return TIMEOUT
if rng.random() < cfg.p_tool_error:
return TOOL_ERROR
if command == "edit" and rng.random() < cfg.p_invalid:
return INVALID
return None
error no such file.No recovery bonus is in the reward. The outcome reward already pays only the episodes that finish. So the question is whether GRPO learns recovery from that signal alone. Here is the failure suite for the cloned policy and for the policy from the main run.
bc success 0.200 recovered 5/218 episodes with an error
error internal 1/87
error invalid input 4/217
error no such file 0/133
error timeout 0/63
grpo success 0.177 recovered 0/221 episodes with an error
error internal 0/68
error invalid input 0/221
error no such file 0/118
error timeout 0/63
GRPO did not learn recovery from the outcome reward alone. The cloned policy recovered in 5 of 218 episodes that hit an error. The policy from the main run recovered in 0 of 221. Look at the rows. The clone's few recoveries all came after error invalid input or error internal. It never recovered from a timeout (0 of 63) or a no such file error (0 of 133). Two cautions on the rows. The no such file row includes stale paths from the task and also files that the policy mistyped itself, and an episode with several errors is counted in several rows. The scripted expert recovers from all four, because it retries and searches. The clone never saw it do so, since the demonstrations come from clean levels.
Offline against online
Goal Give offline and online training the same data budget and the same gradient steps, and compare.
Online rollouts cost environment time. Offline training reuses a stored dataset for free. So the question is what the free data can teach. We collect one buffer from the cloned policy, with as many trajectories as the online run will generate. Then we train two offline methods on it.
def offline_grpo(policy, codec: Codec, buffer: list[Trajectory], cfg: GRPOConfig, *, iterations: int,
tasks_per_iter: int, device: str = "cpu", eval_fn=None, eval_every: int = 10, seed: int = 0,
log=print) -> list[dict]:
"""Each iteration samples ``tasks_per_iter`` stored groups, so one iteration costs what an online one does."""
opt = torch.optim.AdamW(policy.parameters(), lr=cfg.lr, weight_decay=0.0)
rng = random.Random(seed)
groups: dict[int, list[Trajectory]] = {}
for t in buffer:
groups.setdefault(t.group, []).append(t)
keys = sorted(groups)
history = []
for it in range(1, iterations + 1):
batch = [t for g in rng.sample(keys, min(tasks_per_iter, len(keys))) for t in groups[g]]
row = {"iter": it, **update(policy, opt, batch, cfg, pad=codec.pad, device=device, seed=it)}
if eval_fn is not None and (it % eval_every == 0 or it == iterations):
row["eval"] = eval_fn(policy)
log(f"it {it:3d} clip {row['clip_frac']:.3f} eval {row['eval']}")
history.append(row)
return history
$ .venv/bin/python c12-agent-rl/scripts/experiments.py offline
buffer: 15360 trajectories from the cloned policy, sampled success 0.247, 480 gradient steps
method clean perturbed failures long
online 81% 2% 20% 0%
offline GRPO 77% 5% 21% 0%
filtered BC 80% 27% 25% 0%
The simplest method scored highest. Filtered BC trains only on the 25% of stored episodes that succeeded, and it took perturbed from 13% to 27% and failures from 21% to 25%. With 150 tasks per suite one score has a standard error of about 3 to 4 points, and this is one seed. Online GRPO with the default update ended at 2% perturbed, and offline GRPO at 5%.
The clip fraction shows why offline GRPO struggles. Online it stayed between 0.01 and 0.33. Offline it climbed from 0.17 to about 0.45: the clip fraction counts tokens whose ratio is more than 0.2 away from 1, so nearly half the tokens are far from the stored policy. Tokens past the bound in the direction their advantage favours stop giving gradient, which is some of them and not all. The stored log-probabilities describe the cloned policy, and the policy has moved away from it.
The full agent-RL system
Goal Separate the loop into the components a production trainer has, each timed and each testable.
The loop in step 8 mixes everything together. A real system separates it, because each part scales and fails differently. Task sampler, env workers, rollouts, trajectory store, verifier, batches, update, new policy.
class Verifier:
"""Re-run the recorded actions on a fresh copy of the task and decide success from the final files.
The reward never comes from what the agent or the rollout worker claims. A disagreement means a bug or a
tampered record, so the verifier's answer wins and the mismatch is counted.
"""
def __init__(self) -> None:
self.checked = 0
self.mismatches = 0
def verify(self, traj: Trajectory) -> Trajectory:
env = FileSystemEnv(sample_task(traj.level, traj.seed), seed=traj.meta.get("env_seed"))
env.reset()
for step in traj.steps:
if env.done():
break
env.step(step.action)
verdict = env.reward() == 1.0
self.checked += 1
self.mismatches += int(verdict != traj.success)
traj.success = verdict
if traj.steps: # outcome reward lives on the last step
traj.steps[-1].reward = float(verdict)
return traj
def iteration(self) -> dict:
clock = {}
t = time.perf_counter()
def lap(name: str) -> None:
nonlocal t
now = time.perf_counter()
clock[name] = now - t
t = now
episodes = self.sampler.sample(self.sys.tasks_per_iter)
lap("sample")
trajs = self.rollouts(episodes)
lap("rollout")
self.store.append(trajs)
lap("store")
trajs = [self.verifier.verify(tr) for tr in trajs]
lap("verify")
batch = make_batches(trajs, self.version, self.sys.max_lag)
lap("batch")
stats = update(self.policy, self.opt, batch, self.cfg, pad=self.codec.pad, device=self.device,
seed=self.version)
lap("update")
self.version += 1
return {"version": self.version, **group_stats(trajs, self.cfg.reward), **stats, "clock": clock}
$ .venv/bin/python c12-agent-rl/scripts/train_system.py --iters 10
store: 1920 trajectories, 5.87 MB; verifier: 1920 checked, 0 mismatches
v1 success 0.28 zero-var 0.79 sample 0.00s rollout 1.30s store 0.02s verify 0.03s batch 0.00s update 0.52s
v2 success 0.27 zero-var 0.83 sample 0.00s rollout 3.46s store 0.02s verify 0.02s batch 0.00s update 0.93s
v3 success 0.23 zero-var 0.67 sample 0.00s rollout 3.70s store 0.02s verify 0.02s batch 0.00s update 1.11s
v4 success 0.23 zero-var 0.83 sample 0.00s rollout 4.36s store 0.02s verify 0.02s batch 0.00s update 1.22s
v5 success 0.42 zero-var 0.67 sample 0.00s rollout 1.85s store 0.02s verify 0.02s batch 0.00s update 1.06s
v6 success 0.14 zero-var 0.96 sample 0.00s rollout 2.63s store 0.02s verify 0.02s batch 0.00s update 1.09s
v7 success 0.20 zero-var 0.83 sample 0.00s rollout 3.46s store 0.03s verify 0.02s batch 0.00s update 1.00s
v8 success 0.12 zero-var 0.71 sample 0.00s rollout 3.84s store 0.02s verify 0.02s batch 0.00s update 1.06s
v9 success 0.14 zero-var 0.79 sample 0.00s rollout 4.53s store 0.03s verify 0.02s batch 0.00s update 1.16s
v10 success 0.12 zero-var 0.92 sample 0.00s rollout 5.13s store 0.03s verify 0.02s batch 0.00s update 1.06s
workers=32 latency=20ms total 44.9s sample 0.0% rollout 76.3% store 0.5% verify 0.4% batch 0.0% update 22.7%
store: 1920 trajectories, 5.87 MB; verifier: 1920 checked, 0 mismatches
The output above is the last of three runs, each 10 iterations. This tests the pipeline and its timings, not training: the policy did not improve over these iterations either. Sampled success went from 0.28 to 0.12, and after the run the evaluation read 78% clean and 1% perturbed. With instant tools the whole run took 40 seconds. With 20 ms per tool call and no workers it took 318 seconds. With 32 workers it took 45 seconds. The verifier checked 1920 trajectories in each run and found 0 mismatches. The store holds 5.9 MB for 1920 episodes.
Drop in a Hugging Face model
Goal Prove the interfaces hold: the same rollout and update code runs a trusted Llama and SmolLM2 with LoRA.
All of this claims to be LM-shaped. Here is the check. An adapter gives any causal LM the same PolicyOutput, and nothing in rollout.py, grpo.py or online.py changes.
class HFPolicy(nn.Module):
def __init__(self, model, vocab_size: int | None = None):
super().__init__()
if vocab_size is not None and vocab_size != model.get_input_embeddings().num_embeddings:
model.resize_token_embeddings(vocab_size)
self.model = model
self.value_head = nn.Linear(model.config.hidden_size, 1)
nn.init.zeros_(self.value_head.weight)
nn.init.zeros_(self.value_head.bias)
def forward(self, input_ids: torch.Tensor) -> PolicyOutput:
"""Right-padded input needs no attention mask here either: causal attention never looks ahead."""
out = self.model(input_ids=input_ids, output_hidden_states=True)
h = out.hidden_states[-1] # (B, T, D)
return PolicyOutput(out.logits, self.value_head(h.to(self.value_head.weight.dtype)).squeeze(-1))
def tiny_llama_policy(vocab_size: int, hidden: int = 128, layers: int = 2, heads: int = 4) -> HFPolicy:
"""A randomly initialised LlamaForCausalLM the size of TinyPolicy: the trusted-implementation check."""
from transformers import LlamaConfig, LlamaForCausalLM
cfg = LlamaConfig(vocab_size=vocab_size, hidden_size=hidden, intermediate_size=4 * hidden,
num_hidden_layers=layers, num_attention_heads=heads, num_key_value_heads=heads,
max_position_embeddings=512, tie_word_embeddings=False)
return HFPolicy(LlamaForCausalLM(cfg))
def test_tiny_llama_drops_in_for_rollout_and_update():
"""The trusted HF Llama architecture runs the same rollout and the same update, with no code change."""
torch.manual_seed(0)
pol = tiny_llama_policy(codec.vocab_size, hidden=32, layers=1, heads=2).eval()
trajs = rollout_batch(pol, codec, [FileSystemEnv(sample_task(1, i)) for i in range(4)], temperature=1.0)
for i, t in enumerate(trajs):
t.group = i // 2
b = collate(trajs, codec.pad)
logp = token_logprobs(pol(b.tokens).logits, b.tokens)
torch.testing.assert_close(logp * b.action_mask, b.old_logprobs, atol=1e-5, rtol=0)
trajs[0].success = True
trajs[0].steps[-1].reward = 1.0
before = copy.deepcopy(pol.state_dict())
update(pol, torch.optim.AdamW(pol.parameters(), lr=1e-3), trajs, GRPOConfig(minibatch=4, epochs=1),
pad=codec.pad, device="cpu")
assert any((before[k] != v).any() for k, v in pol.state_dict().items())
$ .venv/bin/python -m pytest c12-agent-rl/tests/test_system_hf.py -k llama
2 passed, 9 deselected in 18.73s
Both tests pass with no change to rollout.py, grpo.py or online.py. The benchmark in step 3 used the same adapter: a 832,001-parameter Llama took 0.66 seconds per iteration, against 0.43 seconds for our 686,465-parameter policy. SmolLM2 with LoRA has 1,843,777 trainable parameters out of 136,358,785. It ran one iteration in that benchmark.
The test that loads SmolLM2-135M-Instruct with LoRA and plays one episode needs the model in your cache. Run with -m network, it gave: 1 passed (AMD EPYC 7R13 CPU, 8 threads).
We did not train SmolLM2 here. On a CPU the experiments in this post would take days, as step 3 showed. So this step shows that the interfaces hold. It says nothing about how well a real LM learns this task. Exercise 5 is that experiment.
One GPU number puts this in scale. On an NVIDIA H100 80GB HBM3, torch 2.15.0+cu132, the same SmolLM2 iteration from step 3 took 3.5 seconds, against 33 seconds on the CPU. That is results/bench_policy_gpu.txt, measured once. Training SmolLM2 on this task on a GPU has not been measured.
The methods compared
Rows are the training methods we ran. Columns are what the post measured. Read a column to see which method moved that suite. All numbers are greedy success on fresh tasks, from one seed. All rows ran on an AMD EPYC 7R13 CPU, 8 threads, and every row is scored on the same 150 tasks per suite, so the first row shows the starting values of the RL runs. Differences of a few points on a single seed are not meaningful.
| Method | Needs | New env steps | Clean | Perturbed | Failures | Long | Main risk |
|---|---|---|---|---|---|---|---|
| Behaviour cloning | An expert | None | 78% | 13% | 21% | 0% | Breaks off the expert's path |
| Filtered BC | A stored buffer | None after collection | 80% | 27% | 25% | 0% | Learns only what the buffer already does |
| Offline GRPO | A stored buffer with log-probs | None after collection | 77% | 5% | 21% | 0% | Stale log-probabilities, heavy clipping |
| GRPO, 2 epochs per batch | An environment and a verifier | 192 episodes per iteration | 80% | 3% | 19% | 0% | No gain. Flat groups, drift to long episodes |
| GRPO, on-policy variant | The same | 768 episodes per iteration | 79% | 31% | 22% | 0% | Five settings differ from the main run, so the cause of the gain is untested |
| GRPO, action credit | The same, plus a critic | 192 episodes per iteration | not run | not run | 21% | 0% | No gain on the suites it evaluated |
| GRPO, curriculum | The same, plus a stage schedule | 192 episodes per iteration | 74% | 1% | 21% | 0% | Never left stage 1 of 3 |
| GRPO, activity reward | A reward that pays for calls | 192 episodes per iteration | 73% | not run | not run | not run | Reward hacking |
Compare every row with the first one. The default GRPO rows, with action credit, the curriculum or the activity reward, did not improve any suite, and the default run lowered Perturbed from 13% to 3%. Two rows lifted Perturbed: filtered BC (27%) and the on-policy GRPO variant (31%), which changed five settings at once. Both are single seeds on 150 tasks, with a standard error of about 3 to 4 points. No method moved Long. In our probe the clone solved none of 800 sampled level 5 episodes. Rows marked not run used a narrower evaluation set: the credit runs evaluated only failures and long, and the shaping runs only clean.
Run everything
The final folder, and every command that produced a number in this post. Checkpoints go to runs/, which git ignores. Measured outputs are in results/. On a machine with a CUDA GPU the two benchmark commands add a CUDA row on their own. Some outputs in this post come from our own runs and are not in results/: the probe in step 8, the Break-it boxes, and the test snippets. The summary tables in steps 9 to 14 are computed from the JSON files in results/, and no script prints them.
c12-agent-rl/ final tree
c12-agent-rl/ ├── README.md # what, how to run, results table ├── agentrl/ │ ├── tasks.py # step 1: the five levels │ ├── env.py # step 1: reset, observe, step, reward, done │ ├── expert.py # step 1: scripted demonstrator │ ├── trajectory.py # step 2: text view and tensor view │ ├── codec.py # step 2: word tokenizer, encode_trajectory │ ├── policy.py # step 3: tiny transformer + value head │ ├── batching.py # step 4: padded tensors and masks │ ├── bc.py # step 4: behaviour cloning │ ├── shift.py # step 5: perturbations, signatures │ ├── sampling.py # step 6: shared rollout pieces │ ├── rollout_naive.py # step 6: the reference │ ├── rollout.py # step 6: batched generation │ ├── advantages.py # steps 7, 9: group-relative, GAE │ ├── grpo.py # step 8: clipped surrogate, update │ ├── online.py # steps 8, 11, 12: loop, sampler, curriculum │ ├── rewards.py # step 10: outcome, activity, potential │ ├── failures.py # step 13: failure injection │ ├── offline.py # step 14: offline GRPO, filtered BC │ ├── system.py # step 15: store, verifier, workers, resume │ ├── hf_policy.py # step 16: Llama and SmolLM2 adapters │ └── evaluate.py # the four evaluation suites ├── scripts/ │ ├── demo_env.py │ ├── train_bc.py │ ├── distribution_shift.py │ ├── experiments.py # main, credit, shaping, curriculum, ... │ ├── recovery_demo.py │ ├── export_figures.py │ └── train_system.py ├── benchmarks/ │ ├── bench_rollout.py │ └── bench_policy.py ├── results/ # measured outputs, as text and JSON ├── tests/ │ ├── test_env.py │ ├── test_policy_rollout.py │ ├── test_advantages_grpo.py │ └── test_system_hf.py └── conftest.py
$ .venv/bin/python -m pytest c12-agent-rl -m "not slow and not gpu and not network"
$ .venv/bin/python c12-agent-rl/scripts/demo_env.py
$ .venv/bin/python c12-agent-rl/scripts/train_bc.py --demos 30000 --steps 3000 --layers 3
$ .venv/bin/python c12-agent-rl/scripts/distribution_shift.py
$ .venv/bin/python c12-agent-rl/benchmarks/bench_rollout.py --hardware "your CPU name"
$ .venv/bin/python c12-agent-rl/benchmarks/bench_policy.py --tasks 4 --G 4 --hardware "your CPU name"
$ .venv/bin/python c12-agent-rl/scripts/experiments.py main
$ .venv/bin/python c12-agent-rl/scripts/experiments.py onpolicy
$ .venv/bin/python c12-agent-rl/scripts/experiments.py credit
$ .venv/bin/python c12-agent-rl/scripts/experiments.py shaping
$ .venv/bin/python c12-agent-rl/scripts/experiments.py exploration
$ .venv/bin/python c12-agent-rl/scripts/experiments.py groupsize
$ .venv/bin/python c12-agent-rl/scripts/experiments.py curriculum
$ .venv/bin/python c12-agent-rl/scripts/experiments.py offline
$ .venv/bin/python c12-agent-rl/scripts/recovery_demo.py
$ .venv/bin/python c12-agent-rl/scripts/export_figures.py
$ .venv/bin/python c12-agent-rl/scripts/train_system.py --iters 10
$ .venv/bin/python -m pytest c12-agent-rl -m "not slow and not gpu and not network"
50 passed, 1 deselected in 20.31s
$ .venv/bin/python -m pytest c12-agent-rl -m network
1 passed, 50 deselected in 35.43s
$ .venv/bin/python -m pytest c12-agent-rl -m "slow or gpu"
51 deselected in 0.17s
Key insights and nuances
- One harmless mistake takes the cloned policy from 80% to 17%, while the expert stays at 100%. A clean evaluation hides this completely. Step 5.
- If the recorded log-probabilities do not equal a training forward over the same tokens, the GRPO ratio does not start at 1. An off-by-one here does not crash. Only the test catches it. Step 6.
- Dividing by the group std makes a lone winner +2.47 and a lone loser −2.47, against ±0.35 for the majority. A flat group gives exactly 0, so log how many groups are flat. Step 7.
- Outcome-only GRPO with the default update did not improve held-out success here. A likely cause is that most groups were flat: the clone recovered in 9 of 586 sampled level 4 episodes that hit an error and solved 0 of 800 on level 5. The probe is unsaved, flat groups also come from all-win groups, and the on-policy run had the same flat share and still gained, so the cause is not established. Step 8.
- Greedy evaluation can hide drift. Sampled episodes got longer and submitted less often while the greedy suites barely moved. Log the submit share and the episode length as well as success. Step 8.
- A variant with one on-policy step per iteration on a larger batch (and a higher learning rate, a larger minibatch and half the iterations) lifted perturbed success from 13% to 31% on one seed. We did not separate the changes. Step 8.
- With under 10% sampled success and 84 to 90% of groups flat, trajectory and action credit scored the same on the suites. The comparison also changes normalisation and adds a critic, so it says little about credit alone. Step 9.
- The activity run is consistent with a hack but not separated from noise. Its submit share fell to 0.89 and clean success ended at 73%, against 81% with the outcome reward, about 1.6 standard errors apart. One seed. Step 10.
- Potential-based shaping cancels over an episode, so under trajectory-level GRPO it changes nothing. Our potential run matched the outcome run exactly. Step 10.
- A curriculum only helps if its first rung can be climbed. Ours never left stage 1, so it tested nothing. Log which stage the run is in. Step 12.
- Filtered BC on the clone's own successes (27% perturbed) ended within a few points of the on-policy run (31%) and above every other GRPO variant, with far less machinery and no new rollouts. Both are single seeds, and the two runs differ in several settings. It is a cheap baseline to run early. Step 14.
- The verifier replays recorded actions on a fresh copy of the task and decides the reward from the files. The rollout worker's claim never counts. Step 15.
Exercises
- Add DAggerMedium The scripted expert plans from the task text, so it can label any state. Roll out the cloned policy, ask the expert for the right action at each state it visits, add those to the demos and retrain. Compare the perturbed suite with step 5.
Hint
Replay the actions so far through a fresh
ScriptedExpertplan to get the next expert action. Forced steps stay masked. - Try anchor-state groupsHard Trajectory groups compare whole episodes. Group-in-Group Policy Optimization compares actions taken from the same abstract state. Use
signaturefromshift.pyas the anchor, and compare againstgroup_relativeon the long suite.Hint
Compute one advantage per step: the step's return minus the mean return of all steps with the same signature in the batch.
- Add demotion and an automatic curriculumMedium Give
Curriculuma demotion rule, then replace the fixed stages with sampling weights set by each level's zero-variance rate. Does it beat the fixed ladder? - Break the verifierEasy Change
FileSystemEnv.rewardso it checks only the first subtask. Find which suite and which log line reveals the change first, and how long the policy takes to exploit it on level 5. - Train the real LMHard Use
smollm_policyand the sametrain_online. First do SFT on the expert demos with LoRA, then GRPO. On a CUDA GPU, measure how many iterations per hour you get, and note what you had to change. Keep a small G at first.
What the series built
This is the last post in the series. Here is what you have now built, each piece from the one before it.
- Raw PyTorch training loopC1: tensors, autograd, optimizers, written by hand
- The Hugging Face stackC2: Transformers, Datasets, Trainer and Accelerate, opened up
- Attention libraryC3: MHA, GQA, MLA and fused kernels, with equivalence tests
- Modern LLMC4: RoPE, GQA, KV cache and generation
- Distributed LLM trainerC5: data pipeline, mixed precision, DDP and resume
- SFT, DPO and GRPO pipelineC6: post-training a real pretrained model
- Vision-language modelC7: encoder, connector and image-token splicing
- Multimodal training systemC8: stages, mixtures and evaluation
- Multimodal RL systemC9: preferences, hallucination and vision rewards
- Coding-agent harnessC10: tools, the loop, permissions and event logs
- Agent memory systemC11: context engineering and stored memory
- Agent RL environmentC12: this post, from a toy filesystem to a full training system
You should now be able to read the code at each layer of a small agent-training stack, from a tensor operation up to a training system. The GRPO loss in this post is a log_softmax and a gather from C1. It runs over a model from C4, with a loss mask from C6, in a loop whose environment has the shape of the harness from C10. The last step adds no new kind of machinery.
The toy here is small on purpose. To scale it, swap the environment for a sandboxed repository, swap the policy for a real LM, and put the rollouts on an inference server. The theory posts cover what changes then.
Continue reading
- Reinforcement learning for agents, from first principles: the theory behind every step of this post, including echo traps and environment scaling, which we did not build.
- Reinforcement learning from first principles: returns, policy gradients and baselines, derived.
- How reinforcement learning teaches models to reason: GRPO, RLVR and what the reward really buys in reasoning models.
- The agent evaluation playbook: how to grade agents once the suite is bigger than four rows.
- Inside an AI agent harness: the production shape of the environment we built here.
- Add Memory and Context Engineering to the Agent: the previous tutorial, and the context policy this one's long episodes would need at scale.
References
Grouped by topic. Every entry links to its primary source.
Imitation and distribution shift
- A Reduction of Imitation Learning and Structured Prediction to No-Regret Online Learning · Ross, Gordon and Bagnell, 2011 (DAgger)
- Agent Learning via Early Experience · Zhang et al., 2025
Policy optimisation and credit
- Proximal Policy Optimization Algorithms · Schulman et al., 2017
- High-Dimensional Continuous Control Using Generalized Advantage Estimation · Schulman et al., 2015
- DeepSeekMath: Pushing the Limits of Mathematical Reasoning in Open Language Models · Shao et al., 2024 (GRPO)
- Understanding R1-Zero-Like Training: A Critical Perspective · Liu et al., 2025 (Dr. GRPO)
- DAPO: An Open-Source LLM Reinforcement Learning System at Scale · Yu et al., 2025 (token-level loss normalisation)
- Group-in-Group Policy Optimization for LLM Agent Training · Feng et al., 2025
Multi-turn agent RL
- The Landscape of Agentic Reinforcement Learning for LLMs: A Survey · Zhang et al., 2025
- A Practitioner's Guide to Multi-turn Agentic Reinforcement Learning · Wang et al., 2025
- Search-R1: Training LLMs to Reason and Leverage Search Engines with Reinforcement Learning · Jin et al., 2025
- RAGEN: Understanding Self-Evolution in LLM Agents via Multi-Turn Reinforcement Learning · Wang et al., 2025
- AgentGym-RL: Training LLM Agents for Long-Horizon Decision Making through Multi-Turn Reinforcement Learning · Xi et al., 2025
Rewards and reward hacking
- Policy Invariance Under Reward Transformations: Theory and Application to Reward Shaping · Ng, Harada and Russell, 1999
- Reward Hacking in Reinforcement Learning · Weng, 2024
- LLMs Gaming Verifiers: RLVR can Lead to Reward Hacking · Helff et al., 2026
- SpecBench: Measuring Reward Hacking in Long-Horizon Coding Agents · Zhao et al., 2026
Models and code used
- blog-coding-tutorials: c12-agent-rl · the code for this tutorial
- SmolLM2-135M-Instruct · Hugging Face
- PEFT · Hugging Face