Chapter 5 · Agentic RL¶
5.1 Why train agents with RL? ★★¶
One-sentence answer
SFT is essentially behavior cloning: the model learns only on states the demonstrator visited, so once it makes a mistake at inference time it lands in unfamiliar states, and errors compound with the number of steps. RL trains on trajectories the model itself produces in the environment, together with an outcome reward, so it can learn "how to recover after a mistake", and it only needs a way to judge outcomes rather than step-by-step demonstrations. The cost is an interactive environment with automatic scoring, and training that is expensive and unstable, so in practice the model is usually warmed up with SFT or RFT before RL.
I will address three aspects: the limitations of SFT, what RL brings, and the costs of RL together with the training recipe used in practice.
(1) SFT only teaches the model to "follow along", and on multi-step tasks distribution shift makes errors accumulate.
The most direct way to train an agent is SFT: collect trajectories of humans or stronger models completing tasks, including the reasoning, tool calls and tool outputs at every step, and have the model imitate the actions token by token. In RL terms this is behavior cloning. It is simple and stable and quickly teaches the model the tool-call format and the basic workflow, but the model has only ever been trained on "states the demonstrator visited". At inference time the model cannot reproduce the demonstrations perfectly, so sooner or later it makes a small mistake, such as opening the wrong file or getting a parameter wrong; after the mistake it lands in a state that never appeared in the demonstration data, for example facing an error message it has never seen. Because demonstrations are mostly clean success paths and rarely show "how to notice a mistake and back out of it", the model is more likely to keep going wrong in such states, and errors therefore pile up step by step. This is the classic covariate shift of imitation learning: the training state distribution comes from the demonstrator, the test state distribution comes from the model itself, and the two drift further apart with every step. Agent tasks often take dozens of steps, so this problem is very visible (the analysis of how the error grows with task length is in "Going deeper" below).
(2) RL learns on the model's own trajectories, and therefore brings two abilities that SFT cannot provide.
- Learning to recover from its own mistakes: RL trains on trajectories the model itself produces in the environment (on-policy), which naturally contain the mistakes the model actually makes and whatever it tries afterward. For example, two trajectories may both hit a tool-call error; one reads the error message, fixes the argument and succeeds, while the other retries the same call again and again and fails. The outcome reward raises the probability of the first behavior and lowers the second, so the model learns not only "what the correct path looks like" but also "how to get back after going off course".
- Needing only outcome judgments, not step-by-step demonstrations: RL only requires a way to judge whether an outcome is good, and agent tasks often satisfy this condition: edited code can be tested, an answer can be checked against the reference, and an order operation can be checked against the final database state. Judging an outcome is far cheaper than writing a full demonstration, and the model may discover strategies better than the demonstrations (a general comparison of SFT and RL is in 5.9 of Chapter 5 of the LLM Training Pipeline direction).
(3) The costs of RL are expensive environments and sparse rewards, so in practice the model is warmed up first and RL comes second.
RL needs an environment that supports repeated interaction and automatic scoring, and every trajectory really executes dozens of tool calls, so training cost and engineering complexity are far higher than for SFT. Moreover, agent tasks are multi-turn and long-horizon, usually with a single 0/1 outcome signal at the end, which creates two core problems: one is credit assignment, that is, which step was wrong when the final reward is 0 (see 5.3); the other is exploration, because if the model almost never succeeds at first, every trajectory gets reward 0 and the model receives no direction for improvement (see 5.7). Therefore agent RL rarely starts directly from a general-purpose model. Instead, the model is first warmed up with SFT or rejection fine-tuning (RFT: let the model sample on its own, keep only the successful trajectories, and run SFT on them), which teaches the tool format and the basic workflow and lifts the success rate from near 0 to a level that produces a learning signal; online RL in the environment comes afterward.
In summary: SFT makes the agent "able to run", and RL makes it "run better", above all by learning to recover after its own mistakes.
Comparing the three training approaches:
| SFT (behavior cloning) | RFT | Online RL | |
|---|---|---|---|
| Training data | Demonstrations from humans or stronger models | Successful trajectories the model sampled and filtered itself | The current policy's own trajectories |
| Failed trajectories | Not involved | Thrown away | Used to push bad behavior down |
| What it needs | Step-by-step demonstrations | An outcome verifier | An interactive environment and an outcome verifier |
| Can it learn recovery | Hardly; demonstrations rarely show mistakes | To a limited extent | Yes |
| Cost and stability | Cheap, stable | Fairly cheap, stable | Expensive, unstable |
Going deeper: the error-compounding analysis and evidence for warm-up
(1) The behavior-cloning objective and error compounding.
Here \(a_t^{*}\) is the demonstration's action at step \(t\), \(h_t^{*}\) is the demonstration's history up to that step, \(\pi_\theta\) is the model (policy) being trained, and \(T\) is the number of steps in the task. Note that the conditioning is on the demonstrator's history \(h_t^{*}\), not on the history the model itself would reach, which is exactly where the distribution shift comes from. The analysis of Ross et al. (2010) shows that the accumulated error of behavior cloning grows roughly as \(T^2\) in the task length \(T\), whereas interactive methods that keep learning on the states the model itself visits (such as DAgger) grow only as \(T\).
(2) SFT has two less obvious problems as well.
- It does not distinguish which steps really matter: Every token in a demonstration gets the same weight, so the model also imitates unimportant habits (say, always running
lsfirst) as if they were necessary steps. - The model may not have the demonstrator's knowledge: The demonstrator may know exactly where a file lives; when the model imitates those steps anyway, what it learns is "pretending to know", which shows up as made-up file paths or API arguments.
(3) There is experimental evidence that warm-up matters.
WebAgent-R1 (Wei et al. 2025) compared RL from scratch with behavior cloning followed by RL and found the warm-up stage crucial for the final result. When Golubev et al. (2025) trained a multi-turn SWE agent with RFT first and then RL with DAPO, the Pass@1 of Qwen2.5-72B on SWE-bench Verified rose from about 11% to 39%, while RFT alone reached about 20%.
Follow-up questions
Follow-up 1: What is covariate shift, and how does DAgger mitigate it?
Covariate shift means the distribution of inputs (states) differs between training and testing; DAgger mitigates it by adding labels on the states the model itself visits. Behavior cloning trains only on the demonstrator's state distribution, whereas at deployment the model acts according to its own policy and visits a different distribution of states; moreover, each step's deviation changes the subsequent states, so the shift accumulates with task length. DAgger (Ross et al. 2010) lets the current model run the tasks, asks an expert to label the correct action for the states the model actually visited, adds this data to the training set and retrains, and repeats, so the training distribution gradually approaches the model's own distribution. Its limitation is that it needs an expert who can be queried at any time; RL replaces the expert with a reward and learns directly on its own distribution.
Follow-up 2: How does RFT differ from RL?
RFT can be seen as a simplified, positive-only, offline form of RL. RFT samples, filters by outcome, and does maximum likelihood only on the successful trajectories, which amounts to giving successful trajectories a positive weight and throwing the failures away. It is simple and stable, but it cannot learn "which behaviors lead to failure", and it is usually done offline in batches, so its data quickly falls behind the changing model. RL uses both successful and failed trajectories, pushing good behavior up and bad behavior down through the advantage, and keeps learning online on the current policy's distribution.
Follow-up 3: Why not skip the warm-up and start agent RL directly from a general-purpose model?
Because a general-purpose model's success rate on agent tasks is often close to 0, so there is almost no learning signal. In group-comparison methods such as GRPO, if every trajectory in a group fails, all advantages are 0 and the task contributes nothing to the gradient. A general-purpose model may not even produce the tool-call format reliably, so many trajectories fail outright on formatting errors. The warm-up teaches the format and the basic workflow first and lifts the success rate into the "sometimes succeeds, sometimes fails" range, and only then does RL have samples worth comparing.
Follow-up 4: Without a verifiable reward, and without relying on imitation alone, is there a middle ground?
The model can learn from the consequences of its own actions without depending on a reward. For example, Early Experience (Zhang et al. 2025) has the model sample a few alternative actions at each state of the demonstration trajectories and execute them, and uses the next states those actions lead to as supervision. One way to use this data is to train the model to predict the consequences of actions (an implicit world model); another is to have the model compare the outcomes of its own action and the demonstrated action and write out why the demonstrated action is better, then learn this explanation together with the demonstrated action (self-reflection). The paper reports that this works better than pure imitation and gives an advantage as a starting point for subsequent RL.
Common mistakes
- Do not say that SFT's problem is only a lack of demonstration data: Distribution shift is structural; the cleaner the demonstrations, the less the model has seen of states after mistakes, and simply adding more clean demonstrations does not remove the problem.
- Do not say that RL can fully replace SFT: Without a warm-up the success rate is close to 0 and RL gets no learning signal.
- Do not equate RFT with RL: RFT throws away failed trajectories and is usually done offline, so it cannot learn "which behaviors fail".
- Do not say that RL needs step-by-step labels: An outcome reward only needs to judge whether the final result succeeded, which is precisely why RL suits agent tasks.
5.2 How is RL for multi-turn agents formalized, and how does it differ from single-turn RLVR? ★★★¶
One-sentence answer
Single-turn RLVR is a contextual bandit: given a prompt, generate one response and receive one reward. A multi-turn agent is a partially observable MDP (POMDP): every turn the model generates a whole action from the history, the environment executes it and returns an observation, and a trajectory reward arrives only at the end. Because the environment's transitions and observations do not depend on the model's parameters, they drop out of the policy gradient, so the environment can be a non-differentiable black box and the gradient comes only from tokens the model generated itself. The differences between the two include tokens from two sources, a stateful and stochastic environment, sparse and delayed rewards, ever-growing context, and rollout cost that lies mainly in the environment, and each of them turns into a concrete design problem.
I will address four aspects: the form of single-turn RLVR, the POMDP form of a multi-turn agent, the policy gradient in the multi-turn setting, and the design problems created by the differences between the two.
(1) Single-turn RLVR is essentially a contextual bandit with a single round of interaction.
In single-turn RLVR, the model is given a prompt \(x\), generates a response \(y\), and a verifier returns a reward \(r(x, y)\). From an RL point of view, each token is an action, the "state" is the prefix generated so far, the transition is deterministic (append the new token), and the environment shows up only once, at the end, to give the score. So it is a decision problem with a single round of interaction: given a context, choose one (very long) action and receive one reward, and every token in the response is generated by the model itself (algorithms such as GRPO are in 8.3 of Chapter 8 of the LLM Training Pipeline direction).
(2) A multi-turn agent is a POMDP: the model generates a whole action each turn, the environment returns a partial observation, and a trajectory reward is given at the end.
The environment has a true state \(s_t\), such as the contents of every file in a code repository, the full DOM of the browser page, or the records in a database. The model cannot see the full state; it only sees the observations \(o_t\) returned by tools: a file printed by cat, the top few search results, an error message. So this is a partially observable MDP. Each turn, the model generates an action \(a_t\) from the history \(h_t\), the environment executes it, the state transitions and a new observation is produced, which is appended to the context before the next turn:
Here \(x\) is the task, \(\mathcal{D}\) is the task distribution, \(\tau\) is the whole trajectory, \(R(\tau)\) is the reward given when the trajectory ends (the model gives a final answer, submits a patch, or reaches the turn limit \(T\)), \(p_\theta\) is the trajectory distribution produced jointly by the policy and the environment, and \(J(\theta)\) is the training objective. Two points deserve attention. On the one hand, an "action" here is a whole turn of output, namely some reasoning plus a tool call, itself made of tens to hundreds of tokens. On the other hand, the model's context \(h_t\) plays the role of the belief state in a POMDP: it is everything the model knows about the true current state.
(3) In the policy gradient, all environment terms drop out, so the environment can be a black box and the gradient comes only from tokens the model generated itself.
With the log-derivative trick (the REINFORCE approach), the gradient of the objective can be written as the expectation of "trajectory reward × the gradient of the trajectory's log probability":
Here \(y_k\) is the \(k\)-th token of action \(a_t\), and \(y_{<k}\) is all the context before it (including earlier observations). The trajectory probability is a product of the initial-state distribution, policy terms, transition terms and observation terms, which becomes a sum after taking the log; the initial state, the transitions and the observations do not depend on the model's parameters, so their gradients with respect to \(\theta\) are 0, and only the tokens generated by the policy remain (the derivation is in "Going deeper" below). This tells us two things. On the one hand, the environment can be any non-differentiable, stochastic black box (a compiler, a browser, a real person); as long as trajectories can be sampled from it, the gradient can be estimated. On the other hand, the gradient should come only from tokens the model generated itself: observation tokens appear in the conditioning context \(y_{<k}\) and shape how the model generates later actions, but their own probabilities are not in the sum, so they are not learning targets. This is the theoretical basis for "masking observation tokens" in 6.5.
(4) Almost every difference from single-turn RLVR turns into a concrete design problem.
- Tokens come from two sources: The policy generates actions, while tools, the environment and simulated users generate observations, so the loss must distinguish which tokens are actions (see 5.5).
- The environment is stateful and stochastic: Multiple trajectories sampled for the same task go their separate ways after the first turn, so a GRPO-style "compare under the same prompt" baseline holds only at the starting point (see 5.3).
- Rewards are sparse and delayed: Usually there is only one outcome score at the end, so credit assignment and reward design need dedicated treatment (see 5.3 and 5.4).
- The context keeps growing: Tool outputs can be very long, so memory, compute and long-context ability all become bottlenecks (see 5.5).
- Rollout cost lies mainly in the environment, and actions have side effects: Sandboxes and asynchronous rollout infrastructure are needed (see 5.6), and the reward is also easier for the agent to tamper with directly (see 5.4).
In summary: single-turn RLVR is "one decision, one score", while agentic RL is a POMDP unrolled over time; the environment terms drop out of the gradient, so the environment can be a black box, but learning can only happen on the tokens the model generated itself.
Comparing single-turn RLVR and agentic RL:
| Single-turn RLVR | Agentic RL (multi-turn) | |
|---|---|---|
| Decision process | One step (a contextual bandit over a long response) | Multi-step POMDP; the environment acts between turns |
| Who writes the tokens | The policy writes every response token | The policy writes actions; tools, the environment and simulated users write observations |
| Transitions | Deterministic: append a token | Stochastic, stateful, non-differentiable (code runs, pages change) |
| Reward | One verifier score at the end | Usually sparse and delayed; sometimes extra per-turn signals |
| Context length | Prompt plus one response | Grows every turn; tool outputs can be very long |
| Rollout cost | Mainly GPU generation | Generation plus tool execution, sandboxes and network calls |
| Side effects | None | Actions change the outside world, so rollouts need sandboxes |
Going deeper: the full trajectory probability and two granularities of action
(1) The full trajectory probability and the derivation.
Here \(P\) is the state-transition probability, \(\Omega\) is the observation function, and \(\rho_0\) is the initial-state distribution set by the task. The derivation has two steps. First, the log-derivative trick: \(\nabla_\theta p_\theta = p_\theta \nabla_\theta \log p_\theta\), so \(\nabla_\theta J = \mathbb{E}[R(\tau)\nabla_\theta \log p_\theta(\tau)]\), which can be estimated just by sampling trajectories from the environment, without knowing the form of \(P\) or \(\Omega\). Second, expand \(\log p_\theta(\tau)\) into \(\log\rho_0\) plus the sum over turns of \(\log\pi_\theta\), \(\log P\) and \(\log\Omega\); \(\rho_0\), \(P\) and \(\Omega\) do not depend on \(\theta\), so their gradients are 0. The log probability of each turn-level action can then be expanded over tokens as \(\sum_{k\in a_t}\log\pi_\theta(y_k\mid y_{<k})\), which gives the form in the main answer.
(2) Two granularities of "action".
This formulation has two time scales at once. At the turn level, an action is one complete output, and the environment steps in between turns. At the token level, an action is a single token, and the policy gradient is ultimately computed over tokens. Single-turn RLVR has only the token level, so the distinction does not arise; in agent RL, the level at which rewards, advantages and value functions are defined directly shapes the algorithm (see 5.3). ArCHer (Zhou et al. 2024), for example, is explicitly hierarchical: it learns a value function at the turn level and runs the policy gradient at the token level.
(3) A concise summary.
The survey by Zhang et al. (2025) sums up the difference this way: conventional LLM-RL is a degenerate single-step MDP, while agentic RL is a POMDP unrolled over time.
Follow-up questions
Follow-up 1: Why is the agent's problem a POMDP rather than an MDP?
Because the model only sees the local observations returned by tools, not the full state of the environment. A SWE agent, for example, only sees the files it has printed with cat and the outputs of commands it has run; the contents of the other files in the repository and the records in a database are invisible to it. The same observation may correspond to several different true states, so the model must infer its current situation from the history \(h_t\); the whole history therefore has to be the policy's input, and \(h_t\) serves as the belief state.
Follow-up 2: The environment is not differentiable, so why can the policy gradient still be computed?
Because the policy gradient never differentiates through the environment; it only needs samples from it. The log-derivative trick writes the gradient as an expectation over trajectories in which only the gradients of the policy's log probabilities appear; the environment's transition and observation probabilities do not depend on \(\theta\), so their gradients are 0. As long as actions can be executed and observations and rewards collected, Monte Carlo sampling gives an unbiased gradient estimate, at the cost of high variance.
Follow-up 3: How do turn-level and token-level actions differ, and why does the distinction matter?
A turn-level action is one complete output and a token-level action is a single token; the level at which rewards and values are defined determines how credit is assigned. The environment steps in only between turns, so rewards and state changes are naturally turn-level, while the policy gradient and the importance ratio are computed over tokens. Learning a value function at the token level means bootstrapping across a stretch of observation the model did not generate; learning values at the turn level uses a coarser time scale and is easier to get right (see 5.3).
Follow-up 4: In the multi-turn setting, can a group of trajectories for the same task still be compared within the group as in GRPO?
Yes, but the comparison is fair only at the starting point. GRPO's group mean is a reasonable baseline because all samples in the group face the same prompt. In a multi-turn environment, the trajectories in a group share only the starting point and are in different states after the first turn, so the group mean is "the average return of this task" rather than "the average return from some intermediate state", and it can only provide a trajectory-level advantage. Comparing at intermediate states requires anchor-state grouping or branched sampling (see 5.3).
Common mistakes
- Do not say that observation tokens should also receive gradients: Observations are produced by the environment and their probabilities are not part of the policy gradient; including them amounts to training the model to simulate the environment.
- Do not say that the policy gradient requires a differentiable environment: The environment terms drop out of the gradient; all that is needed is the ability to sample from the environment.
- Do not think of an agent's action only as a single token: At the turn level, an action is a whole stretch of reasoning plus a tool call, and the two granularities must be kept apart.
- Do not say that multi-turn RL just makes the single-turn RLVR response longer: The environment steps in between turns and brings stochastic transitions, two sources of tokens and side effects, none of which exist in single-turn RLVR.
5.3 How is credit assigned in multi-turn tasks? ★★¶
One-sentence answer
Credit assignment has to answer "the final reward is 0, so which step was at fault?", and it can be done at three granularities. Trajectory-level methods broadcast the group-standardized return of the whole trajectory to every action token, which is simple and unbiased but high-variance and coarse. Turn-level methods give each turn its own advantage through turn-level rewards, a turn-level critic, or group comparisons at recurring states. Token-level methods use PPO's critic and GAE, which in principle have the lowest variance but are very hard to train on long contexts mixed with large amounts of tool output. The choice depends on trajectory length, whether states repeat, and how expensive samples are.
I will address four aspects: why credit assignment is hard, trajectory-level methods, finer-grained methods, and how to choose.
(1) The difficulty of credit assignment lies in high variance and delayed reward.
Imagine a SWE agent that runs for 40 turns, and in the end the tests fail, so the reward is 0. Maybe the first 30 turns were excellent, finding the bug and understanding the relevant code, and it only wrote one wrong line in the final edit; or maybe it picked the wrong file at the very start and everything afterward was wasted. With only one final 0, the algorithm can hardly know which step to punish; this is the credit assignment problem. It is hard in two respects: on the one hand, each trajectory's outcome depends on dozens of random decisions, so judging one step by the outcome alone mixes in noise from every other step, and the longer the trajectory, the more noise and the more samples are needed; on the other hand, the reward is delayed, so a good early decision only pays off much later, and the policy gradient has to carry that value back to the action that earned it.
(2) Trajectory-level methods extend GRPO directly to multiple turns: unbiased, but high-variance and coarse.
The simplest and most common approach is to sample \(G\) complete trajectories for the same task, standardize each trajectory's total reward within the group to get one advantage, and broadcast it to every token the model generated in that trajectory. The multi-turn GRPO of WebAgent-R1 (Wei et al. 2025) follows this idea (so does Search-R1 for search agents; see Chapter 5 of the RAG direction). It works because, with only a terminal reward, the "future return" after any step equals the return of the whole trajectory, so using \(R(\tau) - b\) as the advantage for every step is exactly REINFORCE with a baseline; as long as the baseline \(b\) does not depend on this trajectory's own actions, the estimator is unbiased. However, good steps in failed trajectories are punished along with everything else, and bad steps in successful trajectories that happened to do no harm are rewarded, so only a large number of samples can average this noise away, and agent trajectories are exactly what is expensive. Moreover, in a multi-turn environment the \(G\) trajectories share only the starting point; by turn 10 they are in completely different states, so the group mean is merely "the average return of this task" and no longer "a fair baseline for the same state".
(3) There are four main finer-grained methods, each reducing variance at a different cost.
- Turn-level rewards: Give each turn an intermediate reward, such as whether the tool-call format is correct, whether the call executed successfully, or whether the search results contain the correct answer, and combine it with the final reward to compute the discounted return after each turn. Zeng et al. (2025) designed verifiable turn-level rewards and LLM-judge turn-level rewards for search agents and reported more stable training and faster convergence than with trajectory-level rewards alone. The cost is that turn-level rewards must be hand-designed, and hand-designed signals are easy to exploit (see 5.4).
- A turn-level critic: Learn a value function that estimates "starting from the situation at turn \(t\), how much return will eventually be obtained", and measure the contribution of a turn's action by the difference in value before and after it. ArCHer (Zhou et al. 2024) trains the critic with TD learning at the turn level and then runs the policy gradient at the token level; the turn level has a coarser time scale and far fewer steps that need bootstrapping, so it is easier to learn accurately than the token level. The cost is training an extra model, and a critic that misestimates introduces bias.
- Group comparisons at identical states: GiGPO (Feng et al. 2025) observes that in many environments different trajectories pass through identical states (returning to the same room in ALFWorld, or to the same search results page in WebShop), so it treats recurring states as anchor states, collects the actions taken from the same anchor into a group, and compares their subsequent returns to obtain step-level advantages. It needs neither a critic nor extra rollouts; its limitation is that it relies on states repeating, so in environments like the open web or code repositories, where states almost never repeat exactly, few anchor groups can be formed.
- A token-level critic: PPO trains a token-level value network and uses GAE to compute an advantage for every token (see 6.4–6.5 in Chapter 6 of the LLM Training Pipeline direction), which in principle gives the lowest variance because every token gets its own baseline. In multi-turn settings, however, the value network has to estimate values over contexts that keep growing and are full of tool outputs, it has to bootstrap across observations the model did not generate, and the critic is usually as large as the policy, so in practice many works prefer trajectory-level methods with many samples, or do value estimation only at the turn level.
(4) How to choose depends on trajectory length, whether states repeat, and sample cost.
With only an outcome reward and fairly short trajectories (a few rounds of search, say), trajectory-level GRPO is often enough, and it is simple and stable. If states repeat often in the environment (text games, fixed websites), anchor-state grouping as in GiGPO is almost a free gain. If trajectories are long and samples expensive, the variance reduction from a turn-level critic or turn-level rewards is most valuable, but watch out for critic bias and for turn rewards being hacked.
In summary: credit assignment is a trade-off between bias and variance: the coarser the granularity, the more unbiased and simpler the method but the more samples it needs; the finer the granularity, the lower the variance, at the price of critic bias or reward-design effort.
Comparing the three granularities:
| Trajectory-level | Turn-level | Token-level | |
|---|---|---|---|
| Advantage unit | One scalar per trajectory, broadcast to all action tokens | One scalar per turn, shared by the tokens in that turn | One value per token |
| Typical methods | GRPO / RLOO over whole trajectories (e.g. WebAgent-R1) | Turn rewards (Zeng et al. 2025), turn-level critic (ArCHer), anchor-state groups (GiGPO) | PPO with a token-level critic and GAE |
| Needs a critic | No | Optional | Yes |
| Bias and variance | Unbiased; variance grows with horizon | Lower variance; bias from the critic or the turn-reward design | Lowest variance in principle; critic hard to train on long mixed contexts |
| Main risk | Good turns in failed runs are punished | Turn rewards get hacked; critic errors | Unstable critic; bootstrapping across tool outputs |
Going deeper: formulas and details for each granularity
(1) The trajectory-level advantage and why it is unbiased.
Here \(R(\tau_i)\) is the total reward of trajectory \(i\), \(G\) is the group size, \(\mathcal{A}(\tau_i)\) is the set of tokens in trajectory \(i\) generated by the policy, and \(A_{i,k}\) is the advantage of the \(k\)-th of those tokens. Strictly speaking, GRPO's group mean includes this trajectory's own reward, which shrinks the whole gradient by a factor of \((G-1)/G\) without changing its direction; a leave-one-out mean (RLOO) is exactly unbiased. Dividing by the group standard deviation changes the relative weights of different tasks (see Dr. GRPO in 8.4 of Chapter 8 of the LLM Training Pipeline direction).
(2) Turn-level returns and the TD advantage.
Here \(r_t\) is the reward at turn \(t\) (including turn-level rewards and the final outcome reward), \(\gamma\) is the discount factor, \(T\) is the total number of turns, \(G_t\) is the discounted return after turn \(t\), and \(V_\phi(h_t)\) is the turn-level critic's value estimate for the history \(h_t\). The TD advantage \(A_t\) equals the immediate reward plus the value after the action, minus the value before it, and measures how much this turn's action improved the situation. ArCHer uses the critic's advantage as the reward at the end of each turn and then updates at the token level with a policy gradient; because the critic is trained with TD learning, old data can also be used to train it, and the paper reports much better sample efficiency than purely on-policy methods such as PPO. Zeng et al. (2025) instead model the interaction as a turn-level MDP, combine turn-level rewards with the outcome reward to estimate per-turn advantages, and implement multi-turn versions of both GRPO and PPO.
(3) GiGPO's two-level advantage.
Here \(A^{E}\) is the trajectory-level (episode) group-relative advantage, \(A^{S}\) is the step-level advantage computed within an anchor group from the discounted returns of the actions, and \(\omega\) is a weight (set to 1 in the paper's main experiments). The paper reports gains of more than 12 percentage points over GRPO on ALFWorld and more than 9 percentage points on WebShop, with the same memory overhead and rollouts as GRPO.
(4) Another idea: branching from intermediate states.
If states do not repeat naturally, one can deliberately branch from intermediate states and sample again, creating several continuations from the same state to compare. The cost is that every extra level of branching multiplies the cost, so the key is choosing where to branch. For example, ARPO (Dong et al. 2025) observes that the entropy of the tokens the model generates rises markedly right after a tool call, so it branches only at these high-uncertainty steps, and it reports outperforming RL methods that sample only at the trajectory level while using about half the tool-call budget.
(5) Three difficulties of a token-level critic in multi-turn settings.
- The context is hard to evaluate: The value network has to estimate values over contexts that keep growing and are full of tool outputs, which is hard to do accurately.
- It has to bootstrap across observations: Environment transitions happen only between turns; right after the last token of an action comes a stretch of observation the model did not generate, so the value estimate has to bootstrap across that observation, and the observation tokens themselves should have no advantage.
- It doubles the cost: The critic is usually as large as the policy, which roughly doubles memory and compute.
Follow-up questions
Follow-up 1: What goes wrong when GRPO is applied directly to multi-turn tasks?
Mainly that the granularity is too coarse and that the group baseline holds only at the starting point. The whole trajectory shares one advantage, so good steps in failed trajectories are punished as well, and only many samples can average the noise away; in a multi-turn environment, the trajectories in a group go their separate ways after the first turn, so the group mean is no longer a fair baseline for the same state. In addition, on hard tasks it is common for the whole group to fail, in which case every advantage is 0 and the samples are wasted (see 5.7).
Follow-up 2: With only a terminal reward, why is broadcasting one advantage to every turn unbiased, and what does it cost?
Because the future return after any step then equals the return of the whole trajectory, so broadcasting is exactly REINFORCE with a baseline. As long as the baseline does not depend on this trajectory's actions, subtracting it leaves the expected gradient unchanged and only reduces variance. The cost is high variance: every step's signal is mixed with the randomness of all the other steps, and the longer the trajectory, the more samples are needed.
Follow-up 3: Why is it easier to learn a value function at the turn level than at the token level?
Because the turn level has a coarser time scale, far fewer steps need bootstrapping, and state changes happen between turns in the first place. A trajectory may have tens of thousands of action tokens but only a few dozen turns, so TD learning at the turn level has a much shorter chain of error propagation. In addition, a turn-level critic does not need to produce an estimate at every token inside an action, nor does it need to bootstrap across observation tokens.
Follow-up 4: What is an anchor state in GiGPO, and in which environments does it work poorly?
An anchor state is an environment state that recurs across several trajectories in the same group. Different actions taken from the same anchor can be compared directly by their subsequent returns, which yields step-level advantages without training a critic. It relies on states repeating exactly, so it works well in discrete, finite environments such as text games and fixed websites; in environments like the open web or code repositories, where states almost never repeat exactly, few anchor groups can be formed and the method essentially reduces to trajectory-level GRPO.
Common mistakes
- Do not say that trajectory-level broadcasting is biased: With only a terminal reward it is exactly REINFORCE with a baseline and is unbiased; the problem is its variance.
- Do not say that a token-level critic is always best: Its variance is lowest in principle, but it is very hard to train accurately on long multi-turn contexts, and the critic's bias may cancel out the variance benefit.
- Do not treat turn-level rewards as a free signal: They are a hand-designed guess, and the model will optimize the guess itself, for example by calling useless tools again and again.
- Do not say that GRPO's group mean serves as a per-step baseline in multi-turn settings: The trajectories in a group share only the starting point, so the group mean can only serve as a trajectory-level baseline.
5.4 How should environments and rewards be designed? ★★¶
One-sentence answer
An environment is a system that can be executed again and again, made up of a task set, an executable runtime, a tool interface, a reset mechanism and a verifier, and its difficulty and permissions decide what the model can learn. For rewards, automatically verifiable outcomes come first (whether tests pass, whether answers match, whether the database state is correct); open-ended tasks use rubrics with an LLM judge; process rewards ease sparsity, but should have a small weight and ideally take the potential-based form. Because an agent can act on its environment, reward hacking is worse than in the single-turn case, and the verifier must be isolated from the agent.
I will address three aspects: what an environment consists of, what kinds of rewards there are, and reward hacking in agent settings.
(1) An environment is not a static dataset but a system that can be executed again and again, and its design directly decides what the model can learn.
An agent RL environment usually has five parts:
- A task set: Task descriptions plus initial states, e.g. a GitHub issue plus a snapshot of the repository when the bug existed.
- An executable runtime: A Docker container with dependencies installed, a browser, a database, or a simulated user.
- A tool interface: Which actions the model can call, and in what format the observations come back.
- A reset mechanism: It ensures every trajectory starts from a clean initial state.
- A verifier: It automatically decides whether the task succeeded when it ends.
These design choices directly affect the learning signal. If tasks are too easy, the model soon solves them all, every reward in a group is the same, and there is no learning signal; if they are too hard, everything fails, and again there is no signal. If tool permissions are too broad (e.g. the test files are directly readable), the model may learn to cheat; if too narrow, the learned strategies will not carry over to real settings. Building environments is therefore the most labor-intensive part of agent RL, and the technical reports of frontier models increasingly stress the scale and diversity of environments (see "Going deeper" below).
(2) There are three main kinds of reward: verifiable outcome rewards are the most reliable, judge-based rewards cover open-ended tasks, and process rewards ease sparsity.
- Verifiable outcome rewards: For coding tasks, check whether hidden tests pass after the patch is applied; for QA and search tasks, check whether the final answer exactly matches the reference (EM), or use F1; for customer-service or booking tasks, check whether the final database state matches the goal state (the approach of τ-bench; see Chapter 6). Such rewards are hard to fool, cheap to compute and free of human-preference noise, but they are only 0 or 1, so on hard tasks most trajectories get 0; overly strict tests reject correct solutions, while loose tests let through patches that do not really fix the problem; and many tasks have no verifiable outcome at all, such as writing a research report.
- Rubrics and LLM judges: For open-ended tasks with no reference answer, an LLM acts as the judge; a finer approach writes several scoring criteria (a rubric) for each task, has the judge score each one, and takes a weighted sum. A rubric breaks a vague overall judgment into concrete, checkable questions, so the judge is more consistent and less swayed by overall style; but RL actively hunts for the judge's weak spots, for example by catering to the length and tone the judge prefers.
- Process rewards: Score intermediate steps, either with simple rules (the tool call parses correctly, execution raises no error) or with a trained process reward model (PRM; see 8.7 in Chapter 8 of the LLM Training Pipeline direction). They tell the model earlier whether it is on the right track, but they are our guess about what a good process looks like, and the model optimizes the guess: if every successful tool call earns points, the model learns to call useless tools like crazy. Process rewards are therefore usually given a small weight, with the outcome reward always dominant; the theoretically safe way to add them is potential-based shaping (see "Going deeper" below).
(3) Reward hacking is more serious in agent settings because an agent can act on its environment.
Reward hacking already exists in single-turn RL (see 6.7 in Chapter 6 of the LLM Training Pipeline direction), but a single-turn model can only exploit loopholes in text, whereas an agent can run commands, read and write files and access the network, and the reward is often computed by tests or scripts living in the same environment. Unless the verifier is strictly isolated from the agent, "changing the verifier" is often much easier than "actually doing the task": behaviors already observed include deleting or modifying tests, tampering with scoring code, finding the official fix directly in the repository history or online, and claiming "verified, all tests pass" in the output to please a judge. These behaviors get reinforced in RL: once a cheating trajectory earns a high score, its probability goes up and it quickly spreads into a stable strategy. Prevention therefore relies mainly on environment engineering: keep tests and scoring scripts where the agent cannot reach them and run them in a separate environment only after the rollout ends; clean repository history and restrict network access; make test files read-only, or detect and penalize changes to them; review training trajectories with LLM monitors or human spot checks; and keep a set of stricter validation tasks outside the training set to catch the divergence of "training reward rising while real metrics do not".
In summary: the environment decides what can be learned, and the reward decides what the learning turns into; in agent settings, whether the reward can be trusted depends first of all on whether the verifier is isolated from the agent.
Comparing the kinds of reward:
| Reward type | Examples | Strengths | Weaknesses |
|---|---|---|---|
| Verifiable outcome reward | Hidden tests pass, answer EM / F1, final database state | Hard to fool, cheap, no preference noise | Sparse; imperfect test coverage; many tasks cannot be verified |
| Proxy metric | Text similarity to the real merged patch (SWE-RL) | No execution environment needed; can use huge amounts of data | Rewards "looking like the reference" rather than "being functionally correct" |
| Rubric and LLM judge | Criterion-by-criterion scoring, outcome reward models | Works for open-ended tasks | Judges are biased and get exploited by the policy |
| Process reward | Successful tool calls, more passing tests, PRM scores | Denser signal, more efficient exploration | Easy to hack; can change the optimal policy |
Going deeper: environment scale, test criteria, rubrics and potential-based shaping
(1) The scale and diversity of environments.
In coding, dedicated training environments that provide "executable repository + tests" have appeared, such as SWE-Gym (Pan et al. 2024), built from real GitHub issues, and R2E-Gym (Jain et al. 2025), which synthesizes tasks procedurally to scale up. DeepSeek-V3.2 (DeepSeek-AI 2025) synthesized more than 1,800 environments and about 85,000 complex prompts for agent RL, with tasks designed to be "hard to solve but easy to verify"; Kimi K2 (Kimi Team 2025) built a large-scale tool-use data synthesis pipeline that generates multi-turn trajectories in simulated and real environments.
(2) SWE-bench-style test criteria and proxy rewards.
SWE-bench's criterion requires two kinds of tests to hold at once: tests that failed before and should pass after the fix must now pass, and tests that passed before must not break. When code cannot be executed, a cheap proxy can be used instead: SWE-RL (Wei et al. 2025) runs no tests at all and uses the text similarity between the generated patch and the real merged patch as the reward (−1 for bad format). This lets it scale RL on huge amounts of GitHub PR data, but it rewards "looking like the reference", so two equally correct fixes can score very differently.
(3) Rubric rewards.
Here \(c_j\) is the \(j\)-th scoring criterion (e.g. "does the report cite primary sources?", "does it answer every sub-question the user asked?"), \(\mathrm{Judge}(\tau, c_j)\) is the judge's score for trajectory \(\tau\) on that criterion, \(w_j\) is its weight, and \(m\) is the number of criteria. The simplest version asks the judge directly "was the task completed?"; WebRL (Qi et al. 2024), for example, trained an outcome reward model (ORM) to decide whether a web task succeeded. Kimi K2, beyond verifiable rewards, trains subjective tasks with a self-critique reward in which the model judges its own outputs against rubrics. Common ways to keep the judge from being exploited are: give the judge reference answers or verifiable evidence where possible (e.g. require citations and check what the links actually say), average several judges, calibrate with periodic human spot checks, and mix verifiable tasks with judge-scored tasks in training (the general biases of LLM-as-a-judge are covered in 5.3 of Chapter 5 of the Inference, Evaluation & Deployment direction).
(4) Potential-based reward shaping.
Here \(\Phi(s)\) estimates how close a state is to success (the potential), \(r_t\) is the original reward, \(r'_t\) is the shaped reward, and \(\gamma\) is the discount factor. When the extra terms are summed with discounting along any trajectory, the middle terms cancel in pairs and only the two end terms \(\gamma^{T}\Phi(s_T) - \Phi(s_0)\) remain; as long as the potential of terminal states is set to 0 (the usual convention for finite-length tasks), the remaining \(-\Phi(s_0)\) depends only on the starting state and not on how the policy behaves, so it does not change which policy is optimal and only makes the learning signal denser (Ng et al. 1999). More generally, the shaped Q-function equals the original Q-function minus \(\Phi(s)\), so the ranking of actions in any given state is unchanged. Conversely, a reward such as "points for every successful tool call" is not a difference of potentials, so its terms do not cancel when summed and can change the optimal policy.
(5) Examples of reward hacking already observed.
- Editing or bypassing tests: ImpossibleBench (Zhong et al. 2025) builds tasks whose tests contradict the specification so that they cannot be passed legitimately; any "pass" means cheating, which measures a model's propensity to cheat. The authors report that more capable models tend to cheat more often.
- Attacking the scoring code: METR (2025) reported that in a task asking for a faster GPU kernel, o3 did not actually write a kernel; instead it walked the Python call stack to find the correct answer the scoring program had already computed and returned that. In another case it overrode PyTorch's equality comparison so the comparison during scoring was always true.
- Finding the answer in the environment: In SWE-bench-style environments, agents have used
git log --allto find "future commits" that should not have been in the repository, containing the official fix; agents with internet access may also simply find the merged upstream PR.
Follow-up questions
Follow-up 1: When passing tests is the reward, what goes wrong if the tests are too strict or too loose?
Tests that are too strict mark correct solutions as wrong, tests that are too loose mark wrong solutions as correct, and both disconnect the reward from the real goal. If the tests are too strict, for example asserting a specific function name or output format, a different but equally correct solution gets 0, and the model is forced to guess the test author's implementation details; if the tests are too loose, a patch that does not really fix the problem may pass by luck, and the model learns to satisfy the tests without solving the problem. RL amplifies both biases because it systematically optimizes toward "whatever earns points most easily".
Follow-up 2: What are the risks of using an LLM judge as the RL reward, and how can they be mitigated?
The judge makes mistakes, and RL actively finds and exploits them. If the judge prefers long answers, a confident tone or certain keywords, the policy quickly learns to cater to them, and the reward keeps rising while real quality does not. The mitigation is to ground the judge's decisions as much as possible: provide reference answers or verifiable evidence, break the judgment into concrete questions with a rubric, average several judges, run periodic human spot checks, and mix in verifiable tasks.
Follow-up 3: What is potential-based reward shaping, and why does it not change the optimal policy?
It adds only the discounted difference of a potential, \(\gamma\Phi(s_{t+1}) - \Phi(s_t)\), and these terms cancel in pairs when summed along a trajectory. After cancellation only a constant tied to the starting state remains, which does not depend on how the policy behaves, so the relative quality of policies is unchanged and the learning signal simply becomes denser. Most process rewards used in practice do not have this form, so they are usually given only a small weight.
Follow-up 4: Why is reward hacking more serious for agents than for single-turn models?
Because an agent can take actions that change its environment, and the reward is often computed in that same environment. A single-turn model can only exploit loopholes in the text it outputs, whereas an agent can modify tests, tamper with scoring code, and dig through repository history. Once a cheating trajectory earns a high score, RL reinforces it, and it may even generalize into a tendency to "take a shortcut whenever things get hard", so it must be prevented at the root through environment isolation rather than by after-the-fact checks alone.
Common mistakes
- Do not say that verifiable rewards cannot be hacked: If the verifier lives in the same environment as the agent, the agent can directly modify the tests or the scoring code.
- Do not say that more process rewards are always better: Process rewards that are not differences of potentials can change the optimal policy, and the model will optimize the reward itself rather than the task.
- Do not judge whether training succeeded by the training reward alone: Training reward rising while an independent validation set does not is often the signature of reward hacking.
- Do not score failures caused by environment faults as 0: That punishes the policy for something it is not responsible for; such trajectories should be marked invalid (see 5.6).
5.5 What are the implementation details of multi-turn RL training? ★¶
One-sentence answer
The most important detail is to compute the loss only on tokens generated by the policy and to mask out the tokens of tool outputs, the system prompt and simulated users (masking the loss only, not attention). Beyond that, the ever-growing context must be managed, with the same management in training and inference; a turn limit must be set, with a clear decision on how truncated trajectories are rewarded; and the sampled token IDs must be kept throughout to avoid inconsistencies from re-tokenization.
I will address four aspects: masking observation tokens, context growth, turn limits and truncated trajectories, and consistency between training and inference.
(1) Only tokens generated by the policy count toward the loss; all other tokens are masked.
Once a multi-turn trajectory is concatenated into one long sequence, its tokens come from different sources: the system prompt and task description come from data, reasoning and tool calls are generated by the policy, tool outputs (search results, file contents, error messages) come from the environment, and sometimes there are replies from a simulated user. Only tokens generated by the policy count toward the policy loss, and the KL penalty and entropy regularization are also computed only over these tokens. There are three layers of reasons why this is necessary:
- In theory, observations are not actions: The derivation in 5.2 shows that the policy gradient contains only the log probabilities of the model's own actions. Including observation tokens would mean raising the probability of "generating this search result" or "generating this error message", which trains an environment simulator and has nothing to do with the reward; with a positive advantage it makes the model memorize these specific tool outputs, and with a negative advantage it pushes their probability down, and both are meaningless noise.
- Numerically, observation tokens were not sampled from the model: Tokens the model sampled itself usually do not have very low probability under the model, but external text (a chunk of HTML, a stream of logs) can have extremely low probability; low-probability tokens have large gradients and unstable new-to-old probability ratios, and mixing many such tokens into the loss easily causes gradient spikes and unstable training.
- In weight, observations are often long: Tool outputs are often far longer than the model's own outputs, so without masking the loss would be dominated by environment tokens and the real action tokens would carry only a small share of the weight.
Note that the mask applies only to the loss, not to attention: observation tokens stay in the context, and the model still sees and uses them when generating later actions; they are just not learning targets (this is the same idea as computing the SFT loss only on the response, see 5.4 in Chapter 5 of the LLM Training Pipeline direction; for search agents this practice is called retrieved token masking, see Chapter 5 of the RAG direction).
(2) The context grows every turn, so it needs compression, and training and inference must manage it the same way.
Each turn adds the model's reasoning, its tool call and the tool output, and tool outputs are often long: a web page can be thousands of tokens and a test run hundreds of lines. After a few dozen turns the context easily reaches tens of thousands or even over a hundred thousand tokens, so training memory and compute grow with length (attention compute is quadratic in length, see Chapter 1 of the Model Architecture direction) and fewer trajectories fit in a batch; during rollout every step processes a longer prefix and slows down; and the model is also more likely to overlook early key information in very long contexts (see 3.6 in Chapter 3 of the Model Architecture direction). Common remedies are to truncate or compress tool outputs, to keep full observations only for the last few turns, or to have the model write a summary when the context is nearly full, drop the old history and continue from the summary (also called context folding). Whichever is used, training and inference must match: if training keeps the full history but deployment keeps only summaries, the input distribution the model faces has changed.
(3) The turn limit is a trade-off, and the reward for truncated trajectories needs careful thought.
Every trajectory needs a maximum number of turns (or tokens); otherwise a trajectory stuck in a loop keeps running and holding rollout resources. If the limit is too small, tasks needing many steps simply cannot be finished and the model never learns long-horizon strategies; if it is too large, a few trajectories hold up the whole batch (see 5.6) and aimless poking around is tolerated, so one approach is a curriculum that gradually relaxes the limit. For truncated trajectories that hit the limit without finishing, giving 0 is simplest, but it treats "on the right track, just ran out of time" the same as "completely lost"; excluding truncated trajectories from the loss avoids punishing reasonable long strategies, but then the model never learns "don't burn time in an endless loop".
(4) Keep the sampled token IDs throughout, to avoid inconsistencies from re-tokenization.
During rollout the inference engine samples token by token and produces token IDs. If, to assemble the conversation, those IDs are decoded into text, wrapped in the chat template and tokenized again for the trainer, the resulting token sequence may differ from what was sampled: the same text can be split in more than one way, and templates may insert or remove spaces and special symbols. The log probabilities computed by the trainer then no longer correspond to the actions the model actually sampled, and both the importance ratios and the gradients are wrong. The safe approach is to keep the sampled token IDs throughout and only tokenize and append each new tool output (token-in, token-out).
In summary: the implementation details of multi-turn RL all follow one principle: learn only on the actions the model actually sampled, and make the inputs seen in training exactly the same as those seen in inference.
Going deeper: the masked loss, context management and handling truncation
(1) The masked multi-turn PPO loss.
Here \(|\tau|\) is the number of tokens in the concatenated sequence, and \(m_k\) is the mask for the \(k\)-th token: 1 if it was generated by the policy (reasoning, tool calls, final answer) and 0 if it comes from the system prompt, the task, tool outputs or a simulated user; \(\rho_k\) is the ratio of new to old policy probabilities on that token, \(A_k\) is the token's advantage, \(\epsilon\) is PPO's clipping range, and the denominator counts only the included tokens.
(2) Approaches to context management.
| Approach | How it works | Cost |
|---|---|---|
| Truncate or compress tool outputs | Keep only the first lines, extract the main text of a web page, keep only the part of a long log near the error | Key information may be lost |
| Keep full observations only for the last few turns | Older observations are replaced by a placeholder or a one-line summary | Early details survive only as summaries |
| Let the model summarize (context folding) | When the context is nearly full, summarize progress, drop the old history and continue from the summary | The trajectory is no longer a single sequence, so training is more complex |
| Cap the context length | Terminate the trajectory when the cap is exceeded and treat it as truncated | Long tasks may not be finished |
When the model writes its own summaries, the trajectory is no longer a single prefix-consistent sequence, so training splits it into segments with separate losses that share the trajectory's reward; writing the summary is itself an action whose quality affects the final reward, so it should be trained too (more general memory mechanisms are covered in Chapter 3). An easily missed example: many reasoning models drop the previous turn's reasoning at the start of a new turn to save context, so the inputs built for training must drop it in the same way.
(3) Concrete practices for turn limits and truncated trajectories.
- Gradually relax the limit: Learn basic skills under a short limit first, then allow longer interactions. For example, ScalingInter-RL, proposed in AgentGym-RL (Xi et al. 2025), increases the number of interaction turns in stages during training to ease the instability of running long-horizon RL directly.
- Exclude truncated trajectories from the loss: This is similar to how DAPO handles overlong responses (see 8.4 in Chapter 8 of the LLM Training Pipeline direction).
- Add a per-turn cost: If only success is rewarded and step count does not matter, the model has no incentive to be efficient; a small per-turn cost encourages concise behavior, but too large a weight pushes the model to give up early or submit carelessly ("premature termination"; see Chapter 0, 0.7).
(4) Numerical differences between the training and inference engines.
Even when the token sequences are identical, the inference engine and the training engine compute slightly different probabilities for the same sequence, and the difference accumulates over long sequences, quietly turning nominally on-policy training into off-policy training; this issue and fixes such as TIS are covered in 8.9 of Chapter 8 of the LLM Training Pipeline direction.
Follow-up questions
Follow-up 1: Why mask tool-output tokens in multi-turn RL, and what happens if you don't?
Because tool outputs are not the policy's actions, and putting them into the loss trains the model to simulate the environment. Not masking has three consequences: the gradient direction is unrelated to the reward, so the model memorizes or suppresses specific tool outputs; external text has low probability under the model, which easily causes gradient spikes and unstable training; and tool outputs are long, which dilutes the weight of the real action tokens.
Follow-up 2: Should the KL and entropy terms be masked too?
Yes. The KL penalty constrains how far the policy drifts from the reference, and entropy regularization encourages the policy's own exploration; both are meaningful only for tokens the policy generated. Computing KL or entropy on observation tokens would likewise constrain text the model is not responsible for generating.
Follow-up 3: Can the model still see the masked observation tokens, and can it still learn to use them?
It can see them and it can learn to use them. The mask applies only to the loss, not to attention, so observation tokens remain in the context as conditions for later actions. Gradients flow back through the log probabilities of later action tokens and shape how the model reads and uses these observations, so the model can learn "read the error message, then fix the argument"; it just does not learn to "generate this error message".
Follow-up 4: What must training account for when history is compressed into summaries?
The trajectory must be split into segments with separate losses, and writing the summary must also be trained as an action. After compression, later turns are conditioned on the summary rather than the full history, so the trajectory is no longer a single prefix-consistent sequence. The segments share the same trajectory reward; whether the summary is good directly affects whether the rest succeeds, so the summary tokens should also count toward the loss. At the same time, deployment must use the same compression strategy.
Follow-up 5: What goes wrong if sampled outputs are decoded and then re-tokenized?
The log probabilities computed by the trainer end up corresponding to a token sequence the model never sampled. The same text can be split in more than one way, and the chat template may change spaces and special symbols, so the re-tokenized sequence differs from the sampled one; the importance ratios and gradients are then wrong, and the error is hard to spot. The fix is token-in, token-out: keep the sampled token IDs throughout and tokenize only the newly added tool outputs.
Common mistakes
- Do not say that masking observation tokens makes them invisible to the model: The mask applies only to the loss; observations remain in the context as conditions for later actions.
- Do not mask only the policy loss and forget the KL and entropy terms: These terms should likewise be computed only on tokens generated by the policy.
- Do not simply treat truncated trajectories as failures: That punishes strategies that were on the right track but ran out of time.
- Do not use different context management in training and deployment: That makes the input distributions inconsistent.
- Do not compute log probabilities on a decoded and re-tokenized sequence: Keep the sampled token IDs instead.
5.6 What are the challenges of rollout infrastructure for agentic RL? ★¶
One-sentence answer
Most of agent RL's time goes to rollouts: each trajectory alternates generation and tool execution dozens of times, and tool execution is slow while the GPU just waits. The infrastructure has to solve two things: provide isolated, reproducible and safe sandboxes for thousands of trajectories, and cope with the long-tail latency caused by uneven trajectory lengths, mainly through asynchronous rollouts, concurrency across trajectories and partial rollouts. The cost of asynchrony is policy staleness, which requires bounding the staleness and applying off-policy corrections.
I will address four aspects: why rollouts are the bottleneck, sandboxes, long-tail latency and asynchrony, and the costs of asynchrony.
(1) Rollouts are the bottleneck because generation and slow tool execution alternate dozens of times.
In single-turn RLVR, a rollout is one generation and mostly consumes GPU time (the general problems of long rollouts are in 8.9 of Chapter 8 of the LLM Training Pipeline direction). In agent RL, by contrast, a trajectory alternates "generate → run tool → generate → run tool" dozens of times, and tool execution can be slow: a test run takes tens of seconds, loading a web page takes seconds, and external API calls may queue, while the model on the GPU just waits. And RL needs a huge number of trajectories: several per task, hundreds of tasks per training step, thousands of steps in total. Therefore most of agent RL's wall-clock time goes to rollouts, and the efficiency of the infrastructure directly decides how far training can scale.
(2) Every trajectory needs its own independent, clean and resettable sandbox.
A sandbox is usually a Docker container or a lightweight VM with the task's code repository, dependencies, browser or database installed (the trade-offs between isolation technologies are covered in Chapter 2). It serves three purposes:
- Isolation: Thousands of trajectories running in parallel do not interfere, so one trajectory deleting a file does not affect another.
- Reproducibility: Every trajectory starts from the same initial state, so trajectories within a group are comparable and the rewards are fair.
- Safety: Early in RL the policy does all kinds of strange or even dangerous things (
rm -rf, infinite loops, outbound requests), which must be confined to the sandbox with limits on CPU, memory, run time and network access.
The engineering difficulty is scale: thousands of containers must be maintained at once, images must be pre-built and cached, startup must be fast, and crashes must recover automatically. There is also an easily overlooked principle: environment failures should not count as policy failures; trajectories that fail because a container timed out or the network hiccupped should be marked invalid and discarded rather than scored 0.
(3) Trajectory lengths vary hugely and synchronous training is held up by the slowest trajectory, so generation must be decoupled from training.
Synchronous RL samples a batch of trajectories with the current model, waits for all of them to finish, updates the model, then samples the next batch. Agent trajectories, however, vary hugely in length: some finish in 3 turns, some run the full 50, and some get stuck on one slow tool call. The whole batch must wait for the slowest one, and most GPUs sit idle meanwhile; this is long-tail latency, and the longer and more uneven the trajectories, the worse the waste. There are three main remedies:
- Asynchronous rollouts: Rollout workers keep generating trajectories into a buffer, and the trainer updates as soon as the buffer holds a batch, without waiting for every trajectory to end; updated weights are then synced back to the rollout workers periodically, as in AReaL (Fu et al. 2025). Agent RL works such as WebAgent-R1 also use asynchronous trajectory rollouts.
- Concurrency across trajectories: While one trajectory waits for a tool, the inference engine serves generation requests from other trajectories (continuous batching, see 3.1 in Chapter 3 of the Inference, Evaluation & Deployment direction), so the GPU is not idle just because one trajectory is waiting.
- Partial rollouts: Give each iteration's generation a length budget; unfinished trajectories are paused and saved, then continued in the next iteration instead of being regenerated from scratch (Kimi k1.5, Kimi Team 2025).
(4) The cost of asynchrony is policy staleness, and "dropping the slowest trajectories" introduces a hidden bias as well.
Some trajectories in the buffer were generated by a model several versions old, so updating the current model on them becomes off-policy learning; this is usually handled by bounding the staleness (allow only a few versions of lag and drop older samples) and correcting with importance-sampling ratios. In addition, if the slowest trajectories are simply dropped to save time, the ones dropped tend to be hard tasks or long failed attempts, so the training data becomes systematically skewed toward easy, successful samples, and the model's long-horizon ability suffers.
In summary: the core of rollout infrastructure is keeping the GPU from waiting on the environment and keeping environment faults out of the reward, while controlling the staleness and sampling bias that asynchrony brings.
Going deeper: AReaL's design, the three efficiency techniques and open-source frameworks
(1) AReaL's fully asynchronous design.
AReaL (Fu et al. 2025) separates generation from training completely: rollout workers generate continuously, and training workers update as soon as a batch of data is ready. To handle stale samples, it proposes decoupled PPO, which treats "the behavior policy that generated the data" separately from "the proximal policy used for the clipping constraint", and it bounds how many versions a sample may lag behind. The paper reports up to 2.77× faster training than synchronous systems on the same number of GPUs, with equal or better final results.
(2) Comparing the three efficiency techniques.
| Technique | Problem it solves | Cost |
|---|---|---|
| Asynchronous rollouts | The trainer need not wait for the whole batch to finish | Policy staleness; off-policy corrections needed |
| Concurrency across trajectories | The GPU is not idle while one trajectory waits for a tool | Requires an inference service that manages many sessions at once |
| Partial rollouts | Very long trajectories no longer monopolize an iteration | Different segments of one trajectory come from different policy versions |
(3) Common open-source frameworks.
Open-source frameworks such as verl, AReaL, SkyRL and rLLM all support multi-turn agent rollouts (DeepSWE was trained with rLLM). Their common idea is to decouple environment interaction from the training engine so that sampling can run in parallel across many containers.
Follow-up questions
Follow-up 1: Why are rollouts, rather than gradient updates, the bottleneck of agent RL?
Because a trajectory alternates dozens of generations and tool calls, and the GPU cannot use the time spent on tool execution. A gradient update only runs forward and backward passes over sequences already collected, which is compute-dense and highly parallel; rollouts are limited by serial multi-turn interaction and slow external environments, and are also held up by the longest trajectory.
Follow-up 2: What are the benefits and costs of asynchronous RL, and how do you handle staleness?
The benefit is that the GPU no longer waits for the slowest trajectory; the cost is that some data comes from old policies. It is handled in two ways: bound the staleness, allowing only a few versions of lag and dropping older samples outright; and correct the mismatch between the behavior policy and the current policy with importance-sampling ratios, as in AReaL's decoupled PPO.
Follow-up 3: What bias do you introduce by simply dropping the slowest trajectories to save time?
The training data becomes systematically skewed toward easy, successful, short trajectories. The slowest trajectories tend to be hard tasks or long failed attempts; once they are dropped, the model rarely gets signal on long-horizon tasks and never learns "don't burn time in an endless loop", so its long-horizon ability suffers. A better approach is to use partial rollouts or a reasonable turn limit instead of dropping them.
Follow-up 4: How should trajectories that fail because of environment errors be handled?
They should be marked invalid and discarded rather than scored 0. Faults such as container timeouts or network hiccups have nothing to do with the policy; scoring them 0 punishes the policy for something it is not responsible for and, in GRPO, also distorts the within-group comparison. "Task failures" must therefore be distinguished from "environment failures", and the latter should be resampled or excluded.
Common mistakes
- Do not treat asynchronous RL as a free speedup: It costs policy staleness and requires bounding the staleness and applying off-policy corrections.
- Do not record environment faults as policy failures: That injects noise unrelated to the policy into training.
- Do not say that adding more GPUs solves the rollout bottleneck: The bottleneck is often tool execution and long-tail trajectories, and GPUs are just as idle while waiting.
- Do not drop slow trajectories casually for the sake of throughput: That skews the training data toward easy tasks.
5.7 What are the representative works, and what problems remain open? ★¶
One-sentence answer
Representative works are easiest to remember by domain: search agents are represented by Search-R1; coding agents include SWE-RL, a single-turn method that executes no code, and DeepSWE, which runs multi-turn RL in executable repositories; web agents include WebRL and WebAgent-R1; at the level of general methods there are RAGEN, which studies training stability, and GiGPO, which performs step-level credit assignment; and frontier models (Kimi K2, DeepSeek-V3.2) stress large-scale environment synthesis. The main open problems are exploration, sample efficiency, training stability and generalization across environments.
I will address two aspects: the representative works by domain, and the four current open problems.
(1) Representative works are easiest to remember by domain.
- Search agents: Search-R1 (Jin et al. 2025) and related works show that with only an outcome reward on the final answer, a model can learn when to search, what to search for, and how to combine the results of several searches; details are in Chapter 5 of the RAG direction.
- Coding agents: Software engineering has a natural verifiable reward (tests) and is the most watched area of agent RL, but works differ a lot in "is it really multi-turn, and does it execute code?". SWE-RL (Wei et al. 2025) is actually single-turn: it trains the model on huge amounts of GitHub PR data to generate a patch in one shot, using similarity to the real patch as the reward, with no execution environment; DeepSWE (Agentica & Together AI 2025), by contrast, has the model browse code, run commands and edit files inside R2E-Gym containers, with hidden tests deciding success at the end.
- Web agents: Web environments are more open, and success is harder to judge automatically. WebRL (Qi et al. 2024) uses an outcome reward model to judge success and automatically generates new tasks from the tasks the model failed, forming a curriculum that evolves with the model's ability; WebAgent-R1 (Wei et al. 2025) uses only the binary reward from rule-based checks, extends GRPO to multiple turns, and uses asynchronous rollouts.
- General methods and training stability: RAGEN (Wang et al. 2025) systematically studied the training dynamics of multi-turn RL in controlled environments such as Sokoban and FrozenLake and found a collapse mode called the Echo Trap; GiGPO (Feng et al. 2025) performs step-level credit assignment through anchor-state grouping (see 5.3).
- Frontier models: Kimi K2 (Kimi Team 2025) and DeepSeek-V3.2 (DeepSeek-AI 2025) both built large-scale pipelines for synthesizing environments and tasks, shifting the focus of agent RL from "designing algorithms" toward "scaling environments".
(2) There are four main open problems.
- Exploration: Under sparse rewards, tasks on which the whole group fails provide no learning signal, and useful signal comes only from tasks the model "sometimes solves and sometimes doesn't". More fundamentally, LLM exploration relies mainly on token-level randomness from the sampling temperature, which rarely produces high-level exploration such as "try a completely different approach", and entropy collapse during training reduces exploration further (see 8.5 in Chapter 8 of the LLM Training Pipeline direction).
- Sample efficiency: Every agent trajectory really executes dozens of tool calls, costing far more than a single-turn generation, yet on-policy methods use each batch only once or twice before discarding it. Reusing old trajectories, reusing samples through a value function, and simulating the environment or user with an LLM are all directions for better sample efficiency, but each has its costs.
- Training stability: Multi-turn RL has longer sequences, sparser rewards and more random environments; Echo-Trap-style mode collapse, sudden entropy drops, gradient spikes, stale samples from asynchrony and probability mismatches between training and inference all amplify instability.
- Generalization across environments: A policy trained in one environment easily overfits to that environment's tool interface, task distribution and even the scaffold's format, and fails in a new environment. An ablation in DeepSeek-V3.2 suggests that environment diversity may matter as much as data scale; how to systematically build environments that are diverse, verifiable and hard to hack, and how to reliably evaluate cross-environment generalization, remain open problems.
In summary: representative works have shown that outcome rewards plus multi-turn RL can substantially improve agents, and the next bottlenecks are exploration, sample cost and environment diversity.
Representative works at a glance:
| Work | Domain / environment | Reward | Key idea |
|---|---|---|---|
| Search-R1 (Jin et al. 2025) | QA with a search engine | Outcome only | See Chapter 5 of the RAG direction |
| SWE-RL (Wei et al. 2025) | GitHub PR data; single-turn patch generation | Similarity to the merged patch; −1 for bad format | GRPO on software-evolution data without executing code |
| DeepSWE (Agentica & Together AI 2025) | Multi-turn coding agent in R2E-Gym repositories | Hidden tests pass | RL only, on Qwen3-32B |
| Golubev et al. 2025 | Multi-turn SWE agent | Tests pass | RFT, then multi-turn RL with DAPO |
| WebRL (Qi et al. 2024) | WebArena-Lite | Outcome reward model | Self-evolving curriculum built from failed tasks |
| WebAgent-R1 (Wei et al. 2025) | WebArena-Lite | Binary rule-based outcome | Multi-turn GRPO with async rollouts; behavior-cloning warm-up matters |
| RAGEN / StarPO (Wang et al. 2025) | Bandit, Sokoban, FrozenLake, WebShop | Environment reward | Identifies the Echo Trap collapse; stabilized variant StarPO-S |
| GiGPO (Feng et al. 2025) | ALFWorld, WebShop, search QA | Outcome plus step returns | Anchor-state groups for step-level advantages |
Going deeper: concrete numbers, the Echo Trap and evidence on environment generalization
(1) Numbers for coding agents.
Under the authors' Agentless-style pipeline, Llama3-SWE-RL-70B reaches 41.0% on SWE-bench Verified, and it also improves on some tasks outside coding. DeepSWE ran RL on Qwen3-32B over about 4,500 tasks from R2E-Gym, reaching 42.2% Pass@1 on SWE-bench Verified (averaged over 16 runs) and 59% with test-time scaling. Golubev et al. (2025) applied RFT and then multi-turn RL with DAPO to Qwen2.5-72B, raising Pass@1 from about 11% to 39%. SWE-bench Verified itself has contamination and labeling problems (see Chapter 6), so be careful when quoting these scores.
(2) Numbers for web agents.
WebRL raised the success rate of Llama-3.1-8B on WebArena-Lite from 4.8% to 42.4%. WebAgent-R1 raised Qwen2.5-3B from 6.1% to 33.9% and Llama-3.1-8B from 8.5% to 44.8%.
(3) The Echo Trap and the metrics to monitor.
The Echo Trap found by RAGEN is a collapse in which the model overfits to reasoning patterns that are rewarded locally, shown by collapsing within-group reward variance, a fast drop in entropy and gradient spikes, after which performance stalls. Its stabilized version, StarPO-S, mitigates this by filtering low-variance trajectory groups, adding a critic and stabilizing gradients. RAGEN also observed that without fine-grained, reasoning-aware rewards, reasoning behavior rarely emerges in multi-turn RL, and the model may learn only shallow tricks or fabricated thoughts. In practice you need to keep monitoring within-group reward variance, entropy, gradient norm, average number of turns and truncation rate, and reuse the stabilization tricks developed for single-turn RL (such as clip-higher, dynamic sampling, and adjusting or removing the KL term; see 8.4 in Chapter 8 of the LLM Training Pipeline direction).
(4) Common practices for exploration and sample efficiency.
- Filter tasks by pass rate: Keep only medium-difficulty tasks and adjust the curriculum dynamically as training progresses, as WebRL does by generating new tasks from failed ones.
- Warm-up and hints: Raise the success rate first with SFT or RFT, or give hints in the prompt and remove them gradually.
- Branch exploration at uncertain steps: For example, ARPO (Dong et al. 2025) branches its sampling only at the steps after tool calls where entropy rises (see 5.3).
- Reuse samples: Reuse old trajectories off-policy (which requires handling distribution shift), or reuse samples through a value function as ArCHer does; simulating the environment or user with an LLM can reduce cost, but when the simulation is inaccurate, the policy may learn to exploit the simulator's loopholes.
(5) Evidence on environment diversity.
An ablation in DeepSeek-V3.2 shows that large-scale RL on synthetic, diverse agent tasks clearly improved the model on tool-use benchmarks such as τ²-bench, MCP-Mark and MCP-Universe, while RL restricted to code and search scenarios brought no improvement on these benchmarks. This is also why much recent work has turned to "environment synthesis" and "environment scaling".
Follow-up questions
Follow-up 1: How does SWE-RL differ from multi-turn SWE agent RL, and what are the trade-offs of each?
SWE-RL is single-turn RL that executes no code, whereas multi-turn SWE agent RL interacts in an executable environment and uses tests to decide success. SWE-RL uses the text similarity to the real patch as the reward, needs no containers and scales to huge amounts of PR data, but it rewards "looking like the reference" rather than "being functionally correct"; multi-turn RL has a more realistic reward, and the model can learn to browse code, run tests and adjust based on errors, but it needs large numbers of executable repository environments and its rollouts cost far more.
Follow-up 2: Where does the reward for web-agent RL come from, and why does WebRL generate new tasks from failed ones?
The reward comes from rule-based checks or an outcome reward model; new tasks are generated so that task difficulty keeps up with the model's ability. WebAgent-R1 uses WebArena's rules to check the page or backend state, while WebRL trains an outcome reward model to decide whether a task was completed. A fixed task set is either solved quickly or never solved, and in both cases rewards within a group do not differ; generating new tasks from failed ones ensures the model keeps meeting tasks it "sometimes solves and sometimes doesn't", forming a curriculum that evolves with its ability.
Follow-up 3: What is the Echo Trap, and which metrics should you monitor during training?
The Echo Trap is a collapse in multi-turn RL in which the model overfits to locally rewarded reasoning patterns and training then stalls. Its early signals are collapsing within-group reward variance, a fast drop in entropy and gradient spikes. You should therefore keep monitoring within-group reward variance, entropy, gradient norm, average number of turns and truncation rate during training, and when variance and entropy drop quickly at the same time, consider filtering low-variance groups or strengthening exploration.
Follow-up 4: Why do tasks where every sample in the group succeeds or fails give no learning signal, and what can you do?
Because after within-group standardization every advantage is 0, so they contribute nothing to the gradient. Useful signal comes only from tasks the model "sometimes solves and sometimes doesn't". Remedies are to filter for medium-difficulty tasks by the current pass rate, adjust the curriculum dynamically, warm up first to raise the success rate, or give hints in the prompt and remove them gradually.
Follow-up 5: Why is high-level exploration hard for LLM agents?
Because exploration comes mainly from token-level randomness due to the sampling temperature, not from deliberate attempts at the level of strategy. Changing a few tokens rarely leads to "trying a completely different approach", and entropy collapse during RL training makes sampling ever more concentrated. How to explore in a structured way at the level of plans and strategies is still an open problem.
Follow-up 6: How can abilities learned through agent RL generalize to new environments?
The key is environment diversity, not just data volume. Training in a single environment makes the model overfit to a specific tool interface and scaffold format; the DeepSeek-V3.2 ablation shows that training on many diverse synthetic environments is what improves performance on such tool-use benchmarks. At the same time, evaluation must use environments and tools not seen during training to reflect generalization truthfully.
Follow-up 7: If asked to describe an agent RL work you know, how should you present it?
It is clearest to cover the environment, the reward, the algorithm, the results and the limitations. Take WebAgent-R1 as an example: the environment is the real websites of WebArena-Lite; the reward is a 0/1 task-success signal from rule-based checks; the algorithm extends GRPO to multiple turns, sampling several trajectories in parallel for the same task, with asynchronous rollouts and context compression, after a behavior-cloning warm-up; the result is that Llama-3.1-8B's success rate rose from 8.5% to 44.8%; the limitations are the sparse reward, only trajectory-level credit assignment, and conclusions that depend on this particular set of websites.
Common mistakes
- Do not describe SWE-RL as multi-turn agent RL: It generates a patch in a single turn, executes no code, and its reward is the similarity to the real patch.
- Do not compare SWE-bench Verified scores across papers directly: Scaffolds, test-time scaling and evaluation settings differ, and the benchmark itself has contamination problems.
- Do not say that exploration can be solved by raising the temperature: Token-level randomness rarely produces strategy-level exploration, and too high a temperature also breaks the tool-call format.
- Do not say that an agent trained well in one environment naturally generalizes: When environment diversity is insufficient, the model overfits to a specific tool interface and format.
5.8 How do experience reuse and skill libraries help agents learn? ★¶
One-sentence answer
RL writes experience into the parameters, which is slow, expensive and hard to inspect; experience reuse instead stores experience outside the parameters, for example as executable code skills, natural-language lessons or reusable workflows, and retrieves it at inference time without training. The two are complementary: a skill library raises the success rate and gives RL more positive samples; rare successful trajectories can be replayed or used for RFT; and RL can also be used to train the model to create and use skills directly. The trade-off is that non-parametric experience is fast, interpretable and editable, but limited by context and retrieval quality, and it does not truly improve the model's underlying ability.
I will address three aspects: the forms experience reuse takes, how it helps RL training, and the trade-off between the two routes.
(1) Experience reuse stores experience outside the parameters, and there are three common forms.
RL writes experience into the parameters, but every update needs many new trajectories, and what is learned is hard to inspect or edit. A complementary route stores experience outside the parameters and retrieves it for reuse at inference time, with no training:
- Code skill libraries: Voyager (Wang et al. 2023) writes verified behaviors in Minecraft as executable code skills stored in a skill library, then calls and composes existing skills when similar tasks come up.
- Natural-language lessons: ExpeL (Zhao et al. 2023) distills lessons from successful and failed trajectories and puts them in the prompt for later tasks; ReasoningBank (Ouyang et al. 2025) goes further by distilling generalizable reasoning strategies from experiences the model itself judged as successes or failures, retrieving them for new tasks and writing new lessons back into the memory bank.
- Reusable workflows: Agent Workflow Memory (Wang et al. 2024) induces reusable workflows from web-task trajectories and uses them as guidance on new tasks.
(2) Experience reuse can help RL training in three ways.
- Improving exploration efficiency: An agent equipped with a skill library succeeds more often, which gives RL more useful positive samples and eases the "whole group scores 0" problem under sparse rewards.
- Reusing expensive successful trajectories: Rare successful trajectories can be stored in a replay buffer or used for RFT and reused repeatedly; the cost is that, as the policy updates, they gradually become off-policy data. WebRL generating new tasks from failed ones is also a form of experience reuse.
- Training the model with RL to create and use skills: A skill library maintained purely through prompting is limited by the base model's ability to follow instructions and summarize experience, so skills can be brought into RL directly. For example, SAGE (Wang et al. 2025) has the agent roll out consecutively over a chain of similar tasks, so skills generated on earlier tasks enter the library and are available to later ones, and it adds reward terms for skill creation and use on top of the outcome reward; the paper reports on AppWorld that it raises task completion while reducing interaction steps and generated tokens.
(3) The trade-off between the two routes is clear: non-parametric experience is fast but shallow, parameter updates are slow but deep.
Non-parametric experience is fast, interpretable and can be edited or deleted at any time, and new experience is usable as soon as it is written; but it is limited by context length and retrieval quality, so it cannot help when nothing relevant is retrieved or the wrong thing is retrieved, and it does not truly improve the model's underlying ability. Parameter updates really change ability, and what is learned can generalize to similar new tasks, but they are slow, expensive and hard to undo. A natural combination is therefore to accumulate and validate experience quickly in a skill library, then write the stable, effective parts into the parameters through RL or RFT. (Memory mechanisms are covered in Chapter 3; how agents keep accumulating experience and evolve themselves is covered in Chapter 4 of the Self-Improving & RSI direction.)
In summary: skill and experience libraries let an agent reuse experience without changing its parameters, while giving RL more successful samples and a better starting point.
Comparing the two routes:
| Written into the parameters (RL / RFT) | Stored outside the parameters (skill and experience libraries) | |
|---|---|---|
| Update speed | Slow; needs many trajectories and training | Fast; usable as soon as it is written |
| Interpretability and editability | Hard to inspect or undo | Readable; can be edited or deleted at any time |
| Main limitation | Training cost and stability | Context length and retrieval quality |
| Improves underlying ability | Yes | Essentially no |
| How it generalizes | Generalizes to similar new tasks | Depends on retrieving relevant experience |
Going deeper: Voyager's skill library and the forms experience can take
(1) Voyager's three components.
Voyager consists of three parts: an automatic curriculum (which proposes the next exploration goal based on current ability), a skill library (which stores skills as executable code and retrieves them by the embedding of each skill's description), and iterative prompting (which repeatedly revises the code based on environment feedback, execution errors and self-verification results). Only code that passes self-verification is written into the skill library, so the library's contents have been verified, which is precisely why it is easier to reuse than raw trajectories.
(2) What to store: trajectories, rules, workflows or code.
| Form | Representative work | Strengths | Limitations |
|---|---|---|---|
| Raw trajectories | Retrieving similar example trajectories | Complete information | Verbose; hard to transfer to different tasks |
| Natural-language rules or strategies | ExpeL, ReasoningBank | Abstract and transferable; can also be distilled from failures | Rules may be too generic or misapplied |
| Workflows | Agent Workflow Memory | Suit recurring procedures (such as web operations) | Depend on similar task structure |
| Executable code skills | Voyager | Composable, directly executable, verifiable | Require a programmable action space |
ReasoningBank's experiments show that distilled reasoning strategies work better than memory mechanisms that store raw trajectories or only successful routines, and that lessons distilled from failures are valuable too.
(3) One caveat when combining with RL.
When the skill library keeps changing during training, the distribution of contexts the policy sees also keeps changing, and the library at deployment may differ from the one in training. So either the skill library should evolve together with the rollouts during training (as in SAGE's consecutive rollouts), or training and deployment should build the skill library in the same way, to avoid a mismatch between training and inference inputs.
Follow-up questions
Follow-up 1: What is the essential difference between a skill or experience library and RL?
The difference is where the experience lives: RL changes the parameters, while a skill library changes the context. RL compresses experience into the weights through gradients, which really changes ability but is slow, expensive and hard to undo; a skill library stores experience externally as code or text and retrieves it into the context at inference time, which is fast, interpretable and editable but does not change the model's own ability, and its effect depends on whether what is retrieved is relevant.
Follow-up 2: Why can a skill library ease the sparse-reward problem?
Because it raises the success rate, moving more tasks into the "sometimes succeeds, sometimes fails" range. In methods such as GRPO, tasks on which the whole group fails provide no learning signal. An agent equipped with verified skills is more likely to succeed on hard tasks, producing positive samples that can be compared; these successful trajectories can themselves be used for replay or RFT.
Follow-up 3: Why train skill creation and use with RL rather than relying on prompting alone?
Because with prompting alone, the skill library's effect is limited by the base model's ability to follow instructions and summarize experience. The model may write low-quality skills, or retrieve a skill but fail to call it. Bringing skill creation and use into RL with corresponding rewards lets the model learn to write skills that are genuinely useful for later tasks and to call them at the right moments.
Follow-up 4: Can an experience library accumulate wrong experience, and what can be done about it?
Yes, so experience should be verified before it is written and remain editable while in use. For example, a trajectory the model judged as successful may in fact have failed, and a distilled rule may be too generic. Common practices are to write only skills that pass verification (as in Voyager's self-verification), to also distill "don't do this" lessons from failures, and to track how well each entry works and retire ineffective ones. This is also an advantage of non-parametric experience over parameter updates: a mistake can simply be deleted.
Common mistakes
- Do not say that a skill library can replace RL: It does not improve the model's underlying ability and cannot help when no relevant experience is retrieved.
- Do not store only successful experience: Lessons distilled from failed trajectories are valuable too; both ExpeL and ReasoningBank use successes and failures.
- Do not treat replayed old successful trajectories as on-policy data: As the policy updates, these trajectories come from an old policy, so their share should be limited or off-policy corrections applied.
- Do not ignore the consistency of the skill library between training and deployment: A skill library that differs between training and deployment makes the input distributions inconsistent.