1.1 From Predicting Tokens to Taking Actions
Write the language model as a conditional distribution over the next token given its prefix . Pretraining and supervised fine-tuning (SFT) fit this distribution to text that someone else wrote. Nothing the model samples during training has consequences: the next prefix is taken from the dataset, not from the model. An agent is the same distribution placed inside a loop with an environment. Some of the model’s output is parsed as an action, a call to a tool. The environment executes it and returns an observation, which is appended to the context. The model continues from a prefix that now contains text it did not write and that depends on what it did. After some number of turns, the episode ends and a reward scores the outcome. The model is now a policy in the sense of reinforcement learning: a rule for choosing actions whose consequences feed back into its own future inputs. Chapter 2 makes those words precise.The clamp issue
Our running example is a one-line bug. It is task 0 of the BugFix gym that Chapter 4 builds. A function that should clamp a value into an interval hasmin and max swapped. We store the issue text and both versions of the source as constants, the only code this chapter saves.
max(value, upper) is at least upper, which is at least lower, so min(lower, ...) always returns lower. The buggy function passes exactly those cases whose answer happens to be lower. A reward that checked only the second case would call this code correct, a first hint of how verifiers can be fooled.
Tests define success
An issue states intent in prose; tests make it checkable. We write two sets. The public tests are the ones an agent can run with itstest tool while it works. The hidden tests are held back and used only to compute the final reward. The split is the difference between a training signal the agent can see and a measurement it cannot fit directly.
1.2 One Episode, Step by Step
An agent needs tools, an action grammar for calling them, and an environment that executes calls and keeps state. We use the same four tools and grammar as the full gym in Chapter 4:readreturns the current source file.testruns the public tests and returnsPASS/FAILlines.edit <op>applies one named source transformation from a fixed menu.submitends the episode; the hidden tests then compute the reward.
<call> tool [arg] </call>. Anything else is malformed. Here is a minimal parser.
swap_minmax is the real fix for this bug family. hardcode_tests is an exploit: it inserts special cases that return the expected answer for exactly the public test inputs and leaves the bug in place. We include it because a learning agent with access to anything like it will eventually find it, and the book needs a reproducible way to study that (Chapter 11).
step takes the policy’s text, parses it, executes the tool, and returns (observation, reward, done). The reward is 0 on every step except submit, where it is 1 if the final source passes all public and hidden tests. A malformed call is not an exception; it returns an error message as the observation and uses up a turn, exactly as a real harness must.
step until the episode ends or a turn budget runs out. Here the messages come from a script, not a model. The transcript records who produced each piece of text.
1.3 What Makes Agentic RL Different
Most readers have seen two kinds of RL post-training for language models. In RLHF, a model writes one response to a prompt, a learned reward model scores it, and the policy is updated to raise the score while staying close to a reference model. In RLVR (RL from verifiable rewards), the reward model is replaced by a program, such as a math answer checker or a unit test run. Both are single-turn: one prompt, one response, one reward. Chapter 2 shows that they are contextual bandits. The episode above differs in six ways, and each one creates engineering problems that the rest of the book addresses. 1. Long horizons. The episode took five decisions, and real coding episodes take dozens of turns and tens of thousands of tokens. Every decision must be right for the final reward to be 1. If each turn succeeds independently with probability , an episode of turns succeeds with probability .hardcode_tests showed. The more capable the tool set, the larger the space of exploits: editing the tests, reading the grader, or special-casing inputs. Reward design and environment isolation are therefore part of the learning algorithm (Chapter 11).
6. Partial observability. The agent never sees the hidden tests, sees the repository only through what it chooses to read, and learns whether an edit worked only by testing it. Information-gathering actions such as read and test earn no reward directly but change what the agent knows. Chapter 2 quantifies this on a small MDP.
1.4 The Training Stack
How does a model learn to produce the solver’s transcript instead of a random one? Every RL system for agents has the same components, and the book builds each one. Before any of them exists, we can run the loop with the simplest possible policy: an untrained agent that picks each message uniformly at random from a small menu. The menu includes a malformed message so that format errors are possible.hacked marks episodes that were submitted with a source that passes every public test but fails the hidden reward, which is the signature of the exploit. Run 2,000 episodes.
1.5 Where SFT, Preferences, RLVR, and Distillation Fit
RL is one of several ways to post-train an agent, and a training pipeline may combine several of them. It helps to see them in one frame. Each of the following methods raises the log-probability of some token sequences and lowers others. They differ in where the sequences come from and how each sequence is weighted:
The differences in weight are easy to see on a small batch. Suppose four attempts at one task received rewards 1, 0, 0, 1.
1.6 Public Reference Points
Several public systems show that RL on real repositories improves coding agents. We use them as reference points for scale and design, not as results we reproduce. Every number below is reported by its authors. The book’s own experiments are CPU-scale demonstrations of mechanisms, not benchmark results.- SWE-bench (Jimenez et al., 2023) defines the task family. Each of its 2,294 instances is a real GitHub issue from one of 12 popular Python repositories, paired with the pull request that resolved it. An agent succeeds when its patch makes the repository’s tests pass. When the benchmark was published, the best model it evaluated resolved 1.96% of the issues. The agent systems below report results on SWE-bench Verified, a subset of SWE-bench.
- SWE-RL (Wei et al., 2025) applies RL to Llama 3 using open-source software evolution data: issues, code snapshots, and pull requests. Its reward is a lightweight rule-based score of similarity between the generated patch and the ground-truth patch, not test execution. The authors report a 41.0% solve rate on SWE-bench Verified for their 70B model.
- R2E-Gym (Jain et al., 2025) builds executable training environments procedurally, from repository commits, with test generation and back-translation of issues. Its environment set is described as having more than 8.7K tasks. The authors report 34.4% pass@1 on SWE-bench Verified for a 32B model and 51% with test-time scaling that combines execution-based and execution-free verifiers.
- DeepSWE (Together AI and Agentica, 2025) trains Qwen3-32B with RL alone in R2E-Gym environments, using 4.5K problems after filtering out repositories that appear in SWE-bench Verified. The training framework is rLLM, and the algorithm, called GRPO++, combines several published modifications of GRPO. Among them are clip-higher, no KL loss, no reward standard-deviation normalization, and a leave-one-out baseline, together with the authors’ own compact filtering. The report gives 42.2% pass@1 (averaged over 16 runs) and 59% with hybrid test-time scaling on SWE-bench Verified. Training used 64 H100 GPUs over six days.
Evidence. These are claims reported by the cited sources and were checked against those sources on 2026-10-13 (see sources.md). They have not been reproduced here. Benchmark numbers depend on the harness, the scaffold, the turn budget, and test-time compute; they are not directly comparable across reports.Each component of the DeepSWE recipe corresponds to a chapter of this book. GRPO and its variants are covered in Chapter 9, the KL term and its removal in Chapter 10, executable environments in Chapter 4, and filtering of truncated or degenerate episodes in Chapter 12. By the capstone, the reader should be able to read such a recipe as a list of design decisions and argue for or against each one.
1.7 Roadmap
The book is organized as one build. Each chapter saves the functions it derives into theagentrl library, and later chapters import them (Chapter 0).
- Part I, Foundations (Chapters 1–5). The RL formalism on a tabular repair MDP (Chapter 2); a language model as a policy, and TinyAgent, the small transformer the book trains (Chapter 3); the BugFix gym with its tools, parser, and test runner (Chapter 4); and the conversion of a multi-turn episode into token ids, masks, and log-probabilities (Chapter 5).
- Part II, Policy optimization (Chapters 6–10). Policy gradients from first principles (6), advantages and credit assignment (7), PPO and safe sample reuse (8), GRPO and the critic-free family, together with the book’s main training loop (9), and KL and entropy regularization (10).
- Part III, Rewards and agents (Chapters 11–12). Verifiers, reward models, and reward hacking (11), and multi-turn behavior and long horizons (12).
- Part IV, Systems (Chapters 13–14). Rollout architectures, asynchrony, and the mismatch between training and inference log-probabilities (13), and packing, batching, and data filtering (14).
- Part V, Beyond pure RL (Chapters 15–16). SFT, rejection sampling, and preferences (15), and distillation for agents (16).
- Part VI, Practice (Chapters 17–20). Evaluation (17), debugging RL runs (18), a capstone that trains a coding agent end to end (19), and the research frontier (20).
1.8 Design Problems in Practice
Problem: choosing the unit of action. Symptom: a team debates whether advantages, ratios, and KL penalties should be computed per token, per turn, or per episode, and different parts of the codebase silently assume different answers. Cause: a trajectory admits three valid MDP castings (Chapter 2, Section 2.8). The model’s probabilities are per token, the environment acts per turn, and the reward arrives per episode. Options: (a) token-level everything, which matches the model exactly but gives a horizon of thousands of decisions; (b) turn-level advantages with token-level log-probabilities, which gives better credit assignment but requires per-turn value estimates or rewards; (c) a single episode-level advantage broadcast to every policy token, which is simple and needs no critic but assigns the same credit to useless and decisive actions. Default: compute log-probabilities and ratios per token, apply a mask per turn, and start with an episode-level advantage. Move to turn-level credit when measurements show that useless actions are being reinforced (Chapter 12).
Problem: deciding what counts as success. Symptom: reward climbs during training while held-out quality does not, or agents learn behaviors like hardcode_tests. Cause: the reward is a measurement of intent, and any measurement that the policy can observe or influence can be optimized directly. In Section 1.2, public-test success and true success came apart in a single edit. Options: (a) hidden tests that the agent cannot run, which is robust but needs more tests per task; (b) patch similarity to a reference, as SWE-RL reports, which is cheap and needs no execution but penalizes valid alternative fixes; (c) a learned judge, which is flexible but itself exploitable; (d) combinations, with monitoring for known exploits. Default: execution of held-out tests in an isolated environment, with the agent’s tools unable to read or modify them, plus explicit checks for exploits you can name. Keep the evaluation reward separate from the training reward (Chapter 11).
Problem: deciding when RL is worth its cost compared with SFT. Symptom: an RL run burns GPU-days and the reward does not move, or SFT on demonstrations plateaus on tasks that require recovery from errors. Cause: RL learns only from the variation in rewards among the samples it draws. If a task’s success rate under the current policy is and we sample a group of attempts, the group carries a learning signal only when it contains both successes and failures, which happens with probability . Options: (a) SFT or a cold start first when is near 0 on most tasks or format errors dominate; (b) RL when a reliable verifier exists and is neither 0 nor 1 on a meaningful fraction of tasks; (c) curricula or filtering that keep tasks in the learnable range (Chapter 14); (d) distillation when a stronger teacher exists and is affordable (Chapter 16). Default: measure the pass rate of the starting policy per task before choosing. Use RL when that distribution has mass in the middle; otherwise fix the starting policy first.The informative fraction is easy to compute.
Summary
- An agent is a language model placed in a loop with an environment: its actions are parsed tool calls, its observations are tool outputs appended to its context, and a reward scores the finished episode.
- The
clampepisode shows the complete interface: toolsread,test,edit <op>, andsubmit, with the call grammar<call> tool [arg] </call>. Public tests guide the agent, and hidden tests define the reward. - Agentic RL differs from single-turn RLHF and RLVR in its long horizons, its observation tokens that the policy did not generate, its environment latency, its reliance on verifiers, its exposure to exploitation, and its partial observability.
- The training stack is rollout, reward, advantage, masked update, and evaluation, scheduled by a systems layer. Each later chapter builds one part of it.
- SFT, rejection sampling, preference learning, RL, and distillation all raise and lower sequence log-probabilities. They differ in where the sequences come from and how each sequence is weighted. RL and on-policy distillation learn on the policy’s own states.
- RL needs variation in reward: measure the starting policy’s pass rates before choosing it.
Exercises
- Write a third edit op,
drop_min, that replacesmin(lower, max(value, upper))withmax(value, upper). Which public and hidden tests does the result pass? Would a reward based on the fraction of public tests passed rank it above or below the buggy source? - Add a hidden test that
hardcode_testspasses by accident. What does that tell you about how hidden tests should be chosen relative to public tests? - Change
random_rolloutsto drop the malformed message from the menu. Predict, then measure, the change in success rate and in the hacked fraction. - Using
run_tests, design a reward that gives partial credit (the fraction of hidden tests passed). Compute it for the buggy, hacked, and fixed sources. Which exploit does partial credit invite? - For per-turn success , find the largest horizon with episode success above 50%. Repeat for .
- Change an assumption: set the group size to and in the last code block. How does the pass-rate range in which most groups are informative change? What does this imply for choosing the group size on hard tasks?
- Design review: a colleague proposes training on SWE-style tasks with SFT on 10,000 successful agent trajectories from a stronger model, and no RL. List the behaviors this is likely to teach well, the behaviors it is likely to miss, and one measurement that would show the difference.