Coding tutorial · Build it from scratch

Train an Agent With Reinforcement Learning

We build a small filesystem environment, clone a scripted expert, watch one small mistake break the clone, and then train the agent online with GRPO and measure what it learns. Everything runs on a CPU, and every number names the machine that produced it.

Agent RLGRPOEnvironments

A 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.

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 principles

Clone 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]"
Step 01

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]
Listing 1One required edit. The kind says how much the agent must discover before it can make the edit.

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
Listing 2The API. The reward is computed from the files, not reported by the agent.

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"
Listing 3The five tools, about 25 lines. The revealed set records what the agent has observed. Shaped rewards use it later.

Figure 1One real level 3 episode from the task generator. The output of each tool becomes an argument of the next one.

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"
Listing 4The expert. 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

Checkpoint

  • demo_env.py prints a successful episode for each level.
  • The expert's step count equals optimal_steps on the clean levels.
Step 02

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)
Listing 5The record. Highlighted: the tensor view. It stores the token ids the policy actually sampled.

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
Listing 6Text into tensors. Only action tokens get mask 1, and injected mistakes get 0.

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]
The tensors of one training batch (B episodes, longest T tokens)
TensorShapeMeaning
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.

Figure 2One real episode as tokens. Each row is a tensor. The camera follows how the update reads them.

Checkpoint

  • Every position in state_positions holds the <act> token.
  • A trajectory round-trips through JSON unchanged (test_trajectory_json_roundtrip).
Step 03

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))
Listing 7The policy. The block is a trimmed version of C4. The value head is one linear layer. Only the action-level update uses it.

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))
Listing 8The shift by one is here and nowhere else.
Inside one forward pass (d_model = 128, 4 heads, V = 174)
TensorShapeMeaning
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.

Checkpoint

  • Changing a future token leaves earlier logits unchanged (test_causality_future_tokens_do_not_change_past_logits).
  • The checkpoint saves and loads with equal outputs.
Step 04

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()
Listing 9The whole of behaviour cloning. Demonstrations come from clean environments at levels 1 to 3.
$ .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.

Checkpoint

  • Loss falls below about 0.05, and the clean suite is well above the other three on unseen tasks.
  • test_bc_loss_drops_and_save_load_roundtrip passes.
Step 05

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 enough

A 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])}"
Listing 10The injected mistakes. None of them changes a file.
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)
Listing 11The measure. Forced steps are excluded: we only count decisions the policy took itself.
$ .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

Figure 3Top left: the abstract states a level 3 demonstration visits. Bottom left: the states after one forced mistake. Right: the measured cost on AMD EPYC 7R13 CPU, 8 threads, against the expert from the same starts.

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.

Checkpoint

  • The expert stays at or near 100% at every k. The drop belongs to the policy.
  • The unseen-state rate rises as success falls.
Step 06

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)
Listing 12The reference rollout. The highlighted loop generates one action. Each token needs a forward pass over the whole history.

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
Listing 13Batched generation. One forward serves every episode that is waiting for an action. Each row reads its logits at its own last position.
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)
Listing 14If this test fails, every later number is wrong. Check it first when an RL run behaves strangely.
Inside sample_actions, for B waiting episodes and at most K action tokens
TensorShapeMeaning
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.

Checkpoint

  • test_naive_and_batched_rollouts_agree_greedy passes.
  • test_rollout_logprobs_match_a_training_forward passes at tolerance 1e-5.
Step 07

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 principles
def 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
Listing 15The whole baseline. Mean and std of a small group of rollouts replace a learned critic.

Try it. Click a trajectory to change its reward. Notice what happens when every reward is the same.

Group mean0
Group std0
Largest A0
Policy gradientnone

Figure 4Group-relative advantages. Click a trajectory to cycle its reward through 0, 1 and 0.5. Blue bars push the trajectory's actions up. Orange bars push them down. A flat group gives no gradient at all.
What group_relative returns for one group of G = 8
RewardsA for each winnerA for each loserWithout 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 win000
The tensors of this step
TensorShapeMeaning
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.

Checkpoint

  • test_group_relative_matches_numpy_reference and test_group_relative_properties pass.
  • test_zero_variance_batch_produces_zero_policy_gradient passes.
Step 08

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
Listing 16The loss. Highlighted: the ratio, the clip, and the mean over action tokens.

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
Listing 17Group members share the task and the start. Their failure seeds differ, so one member may hit a timeout that another does not.
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
Listing 18The online RL loop. A fresh policy version generates every batch.
One iteration of the main run
QuantityShape or sizeMeaning
tasks per iteration24Sampled from levels 1 to 5, half of level 1 to 3 starts perturbed.
G8Rollouts 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

Figure 5Every learning curve in this post, from real runs on AMD EPYC 7R13 CPU, 8 threads. Each point is greedy success on fresh tasks. Choose the experiment and the suite. Every run is a single seed. Some runs shared a busy host, so the post compares scores and not wall-clock times.

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))
Listing 19Five changes from the main run: learning rate 3e-4 instead of 2e-4, one epoch instead of two, minibatch 768 instead of 64, 96 tasks per iteration instead of 24, and 60 iterations instead of 120. The other 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.

Checkpoint

  • Compare every greedy suite with its cloned value before you believe a run. Also watch the sampled success and steps columns, because greedy evaluation can hide drift.
  • Read the zero-var column. If it is near 1, the update has no signal. In our main run it averaged 0.78.
Step 09

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 steps
def 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
Listing 20GAE in one short loop. With λ = 1 this is the final reward minus the baseline. With λ = 0 it is the one-step difference. The test checks both limits.
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
Listing 21Both kinds of credit return per-step advantages, so the loss does not change. The two differ in more than credit: trajectory credit normalises within each group, while action credit adds a critic and whitens over the whole batch. to_tokens then scatters them onto action tokens.
Action-level credit, per minibatch of B episodes
TensorShapeMeaning
values(B, T)The value head's output at every position. We read it only at the <act> tokens.
V(st)nsteps per episodeA 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.

Figure 6Real rollouts of the policy trained with action-level credit, on level 4. Level 5 produced no group with a win, so it has nothing to show. The advantages come from the same functions the update calls. Blue is positive, orange is negative.

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.

Checkpoint

  • test_gae_matches_explicit_sum_and_special_cases passes.
  • test_to_tokens_puts_step_advantage_on_its_action_tokens_only passes.
Step 10

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
Listing 22The hackable reward. It pays for activity.

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.

Figure 7Per-step rewards from 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

Figure 8The activity reward, real run. Left: the shaped return the trainer sees. Right: true success of the sampled episodes, with the outcome-reward run in grey for reference. The box shows one task sampled before training, then the same task after.
(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
Listing 23Potential-based shaping. The environment defines Φ = 0 at the start and at the end.

Checkpoint

  • test_activity_reward_pays_more_for_looping_than_for_solving passes.
  • Always log true success beside the training reward. The gap between them is your reward-hack alarm.
Step 11

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
Listing 24Diverse tasks and diverse initial states. The perturbed starts from step 5 are now training data.
$ .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.

Checkpoint

  • Your training log reports zero-variance groups on every iteration.
Step 12

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.

Figure 9The curriculum. Each rung adds one difficulty. The right side shows what the cloned policy scores before any RL.
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
Listing 25Promotion on a rolling success rate. There is no demotion. An exercise asks you to add it.
$ .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%.

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.

Checkpoint

  • test_curriculum_advances_on_threshold_only passes.
Step 13

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
Listing 26Four failure types. The stale path comes from the task generator: the task names a file that no longer exists, so the first edit returns 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.

Checkpoint

  • test_failure_injection_is_seeded_and_recoverable passes.
  • Count recoveries per failure type, not only overall success. Our run shows why: the totals hide which errors never get fixed.
Step 14

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
Listing 27Offline GRPO reuses the stored groups and the stored log-probabilities. As the policy moves away from the behaviour policy, ratios leave the clip range.
$ .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.

Checkpoint

  • Offline GRPO's clip_frac climbs through the run. Online stays lower, because its old log-probs refresh every iteration.
Step 15

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
Listing 28The verifier replays recorded actions on a fresh copy of the task and decides the reward from the files. The agent's claim and the rollout's claim do not count.
Why grade the state, not the claimThe agent evaluation playbook
    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}
Listing 29One pass through the pipeline, with a timer on each box.
$ .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

Figure 10The system, with the time each box took in a real run with instant tools.

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.

Checkpoint

  • Verifier mismatches stay at 0 on a healthy run. Any other value means a bug or a tampered record.
  • test_system_iteration_runs_all_stages and the resume test pass.
Step 16

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))
Listing 30The adapter, and a Llama the same size as our policy. This is the trusted implementation we compare against.
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())
Listing 31The comparison test. The same rollout, the same log-probability identity, the same update, on HF Llama.
$ .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.

Checkpoint

  • test_tiny_llama_drops_in_for_rollout_and_update passes offline.
  • test_smollm_lora_runs_one_episode passes with the model in your cache (marked network).

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.

Agent training methods in this tutorial
MethodNeedsNew env stepsCleanPerturbedFailuresLongMain risk
Behaviour cloningAn expertNone78%13%21%0%Breaks off the expert's path
Filtered BCA stored bufferNone after collection80%27%25%0%Learns only what the buffer already does
Offline GRPOA stored buffer with log-probsNone after collection77%5%21%0%Stale log-probabilities, heavy clipping
GRPO, 2 epochs per batchAn environment and a verifier192 episodes per iteration80%3%19%0%No gain. Flat groups, drift to long episodes
GRPO, on-policy variantThe same768 episodes per iteration79%31%22%0%Five settings differ from the main run, so the cause of the gain is untested
GRPO, action creditThe same, plus a critic192 episodes per iterationnot runnot run21%0%No gain on the suites it evaluated
GRPO, curriculumThe same, plus a stage schedule192 episodes per iteration74%1%21%0%Never left stage 1 of 3
GRPO, activity rewardA reward that pays for calls192 episodes per iteration73%not runnot runnot runReward 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

Exercises

  1. 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 ScriptedExpert plan to get the next expert action. Forced steps stay masked.

  2. Try anchor-state groupsHard Trajectory groups compare whole episodes. Group-in-Group Policy Optimization compares actions taken from the same abstract state. Use signature from shift.py as the anchor, and compare against group_relative on 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.

  3. Add demotion and an automatic curriculumMedium Give Curriculum a demotion rule, then replace the fixed stages with sampling weights set by each level's zero-variance rate. Does it beat the fixed ladder?
  4. Break the verifierEasy Change FileSystemEnv.reward so 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.
  5. Train the real LMHard Use smollm_policy and the same train_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.

  1. Raw PyTorch training loopC1: tensors, autograd, optimizers, written by hand
  2. The Hugging Face stackC2: Transformers, Datasets, Trainer and Accelerate, opened up
  3. Attention libraryC3: MHA, GQA, MLA and fused kernels, with equivalence tests
  4. Modern LLMC4: RoPE, GQA, KV cache and generation
  5. Distributed LLM trainerC5: data pipeline, mixed precision, DDP and resume
  6. SFT, DPO and GRPO pipelineC6: post-training a real pretrained model
  7. Vision-language modelC7: encoder, connector and image-token splicing
  8. Multimodal training systemC8: stages, mixtures and evaluation
  9. Multimodal RL systemC9: preferences, hallucination and vision rewards
  10. Coding-agent harnessC10: tools, the loop, permissions and event logs
  11. Agent memory systemC11: context engineering and stored memory
  12. 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

References

Grouped by topic. Every entry links to its primary source.

Imitation and distribution shift

Models and code used