arl.. The next block sets up the gym and tokenizer exactly as Chapter 5 did.
15.1 Trajectory SFT and the action mask
A demonstration is a trajectory produced by someone other than the policy we train: a human, a scripted expert, or a stronger model. SFT fits the policy to demonstrations by maximum likelihood. For a single-turn response this is ordinary next-token cross-entropy. For an agent trajectory, the question is which tokens’ likelihood to maximize, and the answer follows from the probability of the trajectory itself. Write a demonstration as alternating actions and observations, , where is the prompt. Under a policy in a fixed environment, its probability factorizes into the policy’s choices and the environment’s responses: where is the history before action . Each action is a token string, so is the sum of its token log-probabilities (Section 3.1). Taking the log, only the middle product depends on : Maximum likelihood over demonstrations is therefore exactly the masked objective: sum the log-probabilities of policy-owned tokens, and condition on everything else. The action mask is not a heuristic that “avoids training on tool output”. It is the gradient of the trajectory log-likelihood, because the environment’s probabilities carry no parameters. Training on observation tokens optimizes a different objective, a model of the environment, which teaches the policy to predict, and eventually to invent, tool output. This is the same derivation that makes environment dynamics drop out of the policy gradient (Chapter 6), seen from the supervised side.sft_loss implements it on a collate batch. We average over action tokens (token mean). Chapter 6 discusses how this choice reweights long and short trajectories.
scripted_rollout, gives one demonstration per task. We compare the masked loss with the unmasked loss over all predicted positions on an untrained model, and count where the unmasked loss would put its weight.
15.2 Warm starts: format first, then skill
SFT plays two different roles in an agent pipeline, and the gym lets us separate them. The first is teaching format: the call grammar, the stop token, and the rhythm of turns. The second is teaching skill: which call to make given what was observed. Pretraining plus generic instruction tuning give a real model the first. We build TinyAgent’s analog by SFT on well-formed but unskilled play, a mixture of the blind and random scripted policies from Chapter 4. We call the result the weak base. It is the starting point for every recipe in this chapter. (Chapter 6 builds a similar base agent for Part II.)sft_train is a minimal loop: sample a minibatch of trajectories with replacement, take one AdamW step on sft_loss, and optionally call a hook every few steps so that experiments can evaluate or checkpoint without restarting the optimizer.
rollout_batch and average the reward. pass_rate returns the trajectories too, so callers can inspect them, and action_entropy reports the mean next-token entropy on the action tokens of a batch, the exploration statistic of Section 3.2.
read observation (keywords such as min or //) rather than from the function name, and that rule transfers to unseen functions. The cost is in the last column: the action entropy falls from 0.25 to 0.02 nats, an order of magnitude. The policy has become nearly deterministic, which matters the moment RL follows (Section 15.6).
Evidence. Measured here, on one seed, with 4 samples per task per evaluation (80 train and 40 held-out episodes), so each pass rate carries a standard error of up to about 0.06. The oracle is perfect and covers every family. Real demonstrations are neither, and Sections 15.3 to 15.5 show what changes when the data comes from the model itself.
15.3 Rejection sampling and expert iteration
Demonstrations are expensive. A verifier is often cheap. Rejection-sampling fine-tuning (RFT) replaces the demonstrator with the model itself: sample several episodes per task from the current policy, keep the ones the verifier accepts, and run SFT on the kept set. Repeating sample, filter, and fine-tune is expert iteration; STaR applies the loop to reasoning rationales, keeping rationales that lead to correct answers (Zelikman et al., 2022), and RFT for math reasoning reports that more distinct correct paths give larger gains (Yuan et al., 2023). The interesting question is how this relates to RL.RFT is a policy gradient with a 0/1 reward
Let and . The policy gradient of Chapter 6 is because is 0 on failures and 1 on successes. The right-hand expectation is the gradient of the log-likelihood of successful trajectories drawn from the current policy, which is exactly what one SFT step on the kept set estimates. So one RFT step on fresh samples is a policy-gradient step whose learning rate is divided by the success rate . Three differences separate the practical method from the estimator:- Normalization. SFT averages over kept tokens, policy gradient over all sampled tokens. When is small, RFT takes a larger step per unit of gradient signal.
- No negative signal. Failures contribute nothing. With a baseline , the policy gradient is ; RFT keeps only the first term. Nothing pushes probability away from failure modes, except indirectly through the softmax.
- Reuse. Several epochs on a fixed kept set are off-policy updates without importance correction. Fitting the kept set to convergence solves , the success-conditioned old policy. This is filtered behavior cloning, and each round of expert iteration is one such projection.
Expert iteration from the weak base
We run four rounds. Each round samples 16 episodes per training task (320 episodes), keeps the successes, and takes 15 SFT steps on them, continuing from the previous round’s model.init. The kept set contains no example of it, so no round can learn it: expert iteration can only sharpen behavior that already has support, which is the coverage limit of filtered cloning. And most kept successes begin with an edit, not a read (32 of the 49 in round 0 start with one of two edit ops, and only 10 with a read). They are blind guesses that happened to be right, and the cheapest rule that reproduces them maps the function name in the issue to an op. That rule is exact on training tasks and useless on held-out functions, whose names the model has never seen, so held-out stays near guessing. The final policy reads in only 30% of episodes. RFT is faithful to what produced the successes, and here that was luck. STaR’s “rationalization” step, which regenerates a rationale given the correct answer for problems the model fails, addresses the coverage half of this problem (Zelikman et al., 2022). Nothing in the filter addresses the shortcut half.
15.4 DPO for agent trajectories
RFT discards failures. Preference optimization uses them: given a pair of episodes on the same task, one preferred (, chosen) and one not (, rejected), increase the relative likelihood of the chosen one. Direct Preference Optimization (DPO) derives such an update from the KL-regularized RL objective without sampling during training (Rafailov et al., 2023). Start from . Its maximizer is , so the reward can be written through the policy as . Under the Bradley–Terry model, , the partition function cancels, and maximizing the likelihood of observed preferences gives the DPO loss For agent trajectories one more cancellation happens. Each contains the environment’s terms from Section 15.1, and the ratio divides them out, because both policies face the same environment. Each log-ratio is therefore the sum over action tokens only of . The action mask enters DPO for the same reason it enters SFT. Two more consequences are worth stating. Tokens that the two episodes share in an identical context, such as the issue and a common first call, contribute equal and opposite gradients and cancel, so DPO learns only from the point where the episodes diverge onward. And the loss constrains the policy only on the trajectories in the dataset; the KL regularization it was derived from is never evaluated on the policy’s own samples.dpo_loss takes summed sequence log-probabilities, so it is independent of how the caller masks and sums.
episode_logp sums the masked log-probabilities of a batch.
15.5 Experiment: four recipes from one weak base
We now compare recipes that all start from the weak base and are evaluated the same way:- SFT on oracle traces (Section 15.2): 20 demonstrations, 60 steps.
- RFT / expert iteration (Section 15.3): no demonstrations, 4 rounds of 320 sampled episodes and 15 steps each.
- SFT then RL: the oracle-SFT checkpoint at step 20 (pass rate 0.80 on train), followed by 40 RL steps.
- RL from the weak base: 60 RL steps, the comparison that shows what the cold start bought.
- With a perfect, covering demonstrator, SFT is very hard to beat. Twenty oracle traces and 40 steps reach 0.99 on train and about 0.9 on held-out. RL after a cold start ends in the same place (0.96/0.95), not above it: there is nothing for RL to add to a demonstrator whose behavior is already optimal and who reads before acting. This is why agent pipelines collect or synthesize demonstrations when they can.
- RFT from a weak base is bounded by the base. It improved fast, plateaued at the 16 tasks the base could solve, and learned a shortcut that does not transfer. Filtered cloning cannot create behavior the sampler never produced.
- A cold start makes RL work. From the step-20 checkpoint, 40 RL steps reach 0.96 on train and 0.95 on held-out, while RL from the weak base, given 60 steps, reaches 0.36/0.30. At step 20 the cold-started policy already reads the file and succeeds about 80% of the time, so most groups contain both outcomes and the advantages are informative (Section 15.6 measures 70%). The weak base rarely reads, and RL must first discover reading by chance.
- RL only is still moving. Its curve rises at the end, and Chapter 9 shows what a longer run with a tuned trainer reaches. The point here is the ordering at a fixed budget, not the asymptote.
Evidence. All four curves are single-seed CPU runs with evaluations of 80 and 40 episodes. Differences below about 0.1 are within noise. The ordering of RL only against the others is far outside it.
15.6 Design problems in practice
Problem: SFT reduces entropy and exploration before RL. Symptom: after a strong SFT stage, RL reward stays flat, most groups have zero reward variance, and the entropy curve starts near zero. Cause: SFT to convergence drives the policy toward the demonstrator’s deterministic choices (Section 15.2 measured 0.25 → 0.02 nats). A group-baseline advantage is , which is zero for every member of a group whose episodes all pass or all fail, so a near-deterministic policy produces almost no gradient, including on tasks it gets wrong. Options: (a) stop SFT early, at a checkpoint that still has entropy, as the step-20 cold start did, at the cost of a lower starting pass rate. (b) Raise the rollout temperature during RL, which changes the behavior policy (Section 3.3). (c) Add an entropy bonus (Chapter 10). (d) Mix diverse demonstrations so that SFT fits a distribution rather than one path. Default: choose the SFT checkpoint by the fraction of RL groups with nonzero reward variance on a probe set, not by SFT loss. The next block measures that fraction on held-out tasks.
Problem: demonstrations rendered with a different template than RL. Symptom: SFT loss is excellent, and the first RL rollouts (or the first evaluation) are far worse than the SFT validation numbers suggested. Cause: the demonstration pipeline rendered episodes with a different template from the rollout pipeline, so the policy is evaluated on prefixes it never trained on (Section 5.8). Options: (a) render all data through the rollout’s ownEpisodecode path, which is the cheapest fix. (b) Re-render legacy data with the RL template. (c) Assert token-level equality of a fixed conversation under both pipelines. Default: (a) and (c). The next block simulates a demonstration pipeline that omitted the<obs>and</obs>wrapper tokens and trains on its output.
Problem: off-policy degradation of DPO. Symptom: DPO’s training loss and reward accuracy improve steadily while the policy’s own rollouts get worse: more malformed outputs, longer or stranger episodes, falling held-out scores. Cause: the loss is evaluated only on the fixed pairs, and decreasing can be achieved by moving mass to sequences outside the data, where nothing constrains it (Section 15.4). The further the policy drifts from the policy that generated the pairs, the less the pairs say about its current behavior. Options: (a) add an NLL term on chosen episodes, as Iterative RPO does, reporting that it is “crucial” (Pang et al., 2024), which anchors the chosen behavior. (b) Regenerate pairs from the current policy every few hundred steps (iterative or online DPO), which costs sampling and labeling. (c) Use a larger or fewer steps, which limits drift and learning alike. Default: (a) always, and (b) when the policy moves far. The next block reruns Section 15.4 with an NLL weight of 1.
Problem: data mixture and deduplication. Symptom: after a few rounds of RFT, the kept set is dominated by a handful of tasks or by identical episodes, and the model overfits them while other tasks regress. Cause: success rates differ across tasks, so sampling the same number of episodes per task returns many copies of easy successes. A deterministic policy returns literally identical trajectories, which multiplies their weight in the SFT loss. Options: (a) deduplicate by action sequence, which RFT for math reasoning motivates by the value of distinct paths (Yuan et al., 2023). (b) Cap kept episodes per task. (c) Sample more episodes for hard tasks. (d) Mix in a fixed fraction of demonstrations or earlier data to prevent forgetting. Default: (a) plus (b), and log the per-family share of the kept set every round. The next block measures the round-1 kept set from Section 15.3.
range and compare families supply 72% of the raw set, because the policy has become nearly deterministic on them and returns the same episode again and again, while minmax successes are more varied. Deduplication reverses the order, and minmax becomes the largest share at 0.43. Neither row is “the right mixture”: deduplication is a reweighting decision with its own bias, and it cannot add the init family, which has share 0 in both rows. Deduplication changes weighting, not coverage.
Problem: SFT on hacked successes. Symptom: the RFT kept set grows each round, the training reward approaches 1, and the hidden-test or human evaluation falls. Cause: the filter is the reward, and a reward that checks only what the agent can see accepts exploits. With the public-test reward of Section 4.5, every hardcode_tests episode that submits passes the filter, and filtered cloning then copies it faithfully, with the -scaled step of Section 15.3. Options: (a) filter with held-out or hidden tests, at the cost of writing them. (b) Add a detector for known exploit patterns. (c) Audit a sample of kept episodes per round. Default: never filter on a signal the policy can observe, and log the gap between the filter’s pass rate and an independent check. The next block runs three rounds of RFT from the weak base with the public-test filter.
hardcode_tests from the random policy’s play, and the share grows to 64% (185 of 287) by the third round. The filter’s own pass rate climbs to 0.97 while the hidden-test pass rate stays near 0.35. The policy has not become worse at fixing bugs. It has learned that the exploit is the most reliable way to pass the filter.
Summary
- Trajectory SFT maximizes the log-likelihood of demonstrated actions. The environment’s probabilities carry no parameters, so the action mask is the exact gradient of the trajectory log-likelihood, not a heuristic. In the oracle demonstrations, only 19% of predicted tokens are actions.
- SFT teaches format and skill separately. A weak base trained on unskilled play has the format (0.06 malformed calls per episode) but guessing-level skill (0.14). Twenty oracle demonstrations take it to about 0.99 on train and 0.9 on held-out, and drive action entropy from 0.25 to 0.02 nats (measured here).
- Rejection-sampling fine-tuning is a 0/1-reward policy gradient with its step size divided by the success rate and without negative signal. Expert iteration is filtered behavior cloning: it rose from 0.15 to 0.68 in two rounds, then stalled below the 16 tasks the base could solve and copied lucky guesses that did not transfer (held-out 0.15).
- DPO for agent trajectories uses masked action log-probabilities, because the environment cancels in the policy/reference ratio. Offline, it lowered rejected log-probabilities by 45 nats while malformed calls rose more than thirtyfold. An NLL term on chosen episodes reduced the damage but did not fix the data.
- From the same weak base, oracle SFT reached 0.99/0.93 (train/held-out), SFT then RL 0.96/0.95, RFT 0.74/0.15, and RL only 0.36/0.30 at 60 steps. The cold start’s value was informative groups: 70% of its held-out groups carried signal, against 10% after longer SFT.
Exercises
- Prove that the token-mean 0/1 policy-gradient loss and the token-mean SFT loss on kept episodes have gradients with ratio exactly (kept action tokens)/(all action tokens), and verify it for a sequence-mean aggregation instead. Which aggregation makes RFT’s effective step size depend on episode length?
- Change an assumption: replace the weak base’s blind and random play with play from the
randompolicy only. How does the set of tasks the base can solve change, and what does expert iteration converge to? - Implement STaR’s rationalization for the gym: for tasks with no success in a round, roll out the current model with the correct op forced at the edit turn, keep successes, and mask the forced tokens out of the loss. Does the
initfamily become learnable, and is the result still filtered behavior cloning? - Add a group baseline to RFT by also training on failures with weight per group. Show that this recovers the baseline policy gradient up to scale, and measure whether it changes the plateau of Section 15.3.
- Build DPO pairs from the oracle-SFT step-20 checkpoint instead of the weak base, train for 100 steps, and compare malformed calls and held-out pass rate with Section 15.4. Explain the difference in terms of what the pairs’ chosen episodes contain.
- Measure the SFT-then-RL recipe from the step-10, step-20, and step-40 checkpoints, and plot final held-out pass rate against the starting fraction of informative groups.
- Design review: your team has 2,000 human demonstrations of a coding agent, a test-based verifier, and a budget for one more stage before RL. Argue for SFT on the demonstrations, RFT from the SFT model, or DPO on (demonstration, model failure) pairs, and name the dashboard metric that would tell you within one day that your choice was wrong.