edit and a pointless second swap_minmax in the same successful episode received identical credit, so the policy learned to stack edits.
Both costs come from the weight. The policy-gradient theorem allows any weight whose expectation, given the history and the action, equals the action’s advantage , how much better the action was than the policy’s average behavior in that state. This chapter builds the estimators of that quantity that production systems use: returns-to-go, temporal-difference errors and -step returns, generalized advantage estimation (GAE), and the critic-free group baselines of GRPO and RLOO. Every estimator is implemented on token sequences with masks, so that values and advantages exist only on policy tokens and the recursions skip tool spans. We also train a critic on TinyAgent and measure why critics are hard for language agents, and we finish with turn-level advantages, drawn token by token on a real multi-turn episode.
sample draws n_per_task episodes of each task in lockstep, so that consecutive episodes form a group of attempts at the same task.
7.1 Returns-to-go on token sequences
Section 6.5 showed that an action should be credited only with rewards that follow it, the return-to-go . On a token sequence two questions need answers before we can compute it: where do rewards live, and what counts as one step of time? The book’s convention answers both. A reward lives on the policy token that earned it. A terminal outcome lives on the last policy token of the episode, which in BugFix trajectories is the</call> of the final call, and a per-call cost lives on the last token of its call. Time advances only on policy tokens. Prompt, template, and tool tokens are not actions, so they are not steps of the decision process: the recursion passes over them, and is applied once per policy token. With , the book’s default for finite coding episodes (Section 2.9), the choice of time unit does not matter. With , it does, and Section 7.7 returns to it.
outcome_rewards puts one reward per trajectory on its last policy token, the input format every estimator in this chapter takes.
7.2 Values, TD errors, and n-step returns
The return-to-go is an unbiased sample of for the action it follows, and a noisy one: it carries all the randomness of every later action and observation. A value function removes that randomness by averaging over it. For a prefix that ends just before policy token , the token-level value is the expected return from that point on. It is defined only where a decision is about to be made, at policy positions. Let denote the next policy position after . Inside a call, and the transition is deterministic. At the end of a call, also contains the tool’s response, which is random. In both cases The temporal-difference (TD) error replaces the expectation with the one sample we have: If , then : one TD error is an unbiased estimate of the advantage, and it involves the randomness of a single transition rather than of the rest of the episode. Between the two extremes sit the -step returns, which use real rewards and then bootstrap from the value function. gives , and gives the return-to-go. A larger trusts the critic less and the samples more: less bias when is wrong, more variance. We verify the TD identity on the repair MDP of Chapter 2, where and are exact.sample_steps runs episodes in parallel and records them in the same [B, T] layout as token batches: states, actions, rewards, and a mask that is 1 while the episode is running.
7.3 Generalized advantage estimation
Each -step return gives an advantage estimate . A telescoping sum rewrites it in TD errors, writing for the -th policy position after : The intermediate values cancel in pairs, leaving the rewards, the bootstrap value , and . Generalized advantage estimation (Schulman et al., 2015) averages all of them with geometric weights : The second equality follows by exchanging the sums: appears in every with , with total weight . This is Equation (7.1). Two cases anchor it. With , , the one-step TD error: lowest variance, and biased whenever is wrong. With , the sum telescopes completely to , the return-to-go minus a baseline: unbiased for the policy gradient whatever is, because is then only a baseline (Equation 6.3), and with the full variance of the return. trades between them. The sum also has a one-line recursion, which is how it is computed: The masked implementation carries two quantities backward across non-policy positions: the value of the next policy position, needed by , and the advantage at that position, needed by the recursion. It also returns the value targets , which Chapter 8 uses to train the critic.-0.0 entries are rounding of zero). With , the advantage of position 1, the last token of the first call, is : it bootstraps from the value at the next policy position, 0.6, not from the garbage 9 at position 2. The naive recursion steps into the tool span and computes for that token, and 8.2 for the last token of the second call. In a real system the critic’s outputs at tool positions are not 9; they are untrained numbers that look plausible, so the bug changes training without crashing it.
Bias and variance across λ
How much bias a buys depends on how wrong the critic is. On the repair MDP we can measure the bias of the policy gradient itself, which is what matters, against the exact gradient from autograd. Every episode contributes , and for a softmax table that score is in row . We compare three critics: the exact ; a stale critic, the exact value of the uniform policy, which plays the role of a critic that has not caught up with the current policy; and no critic at all, .gae_advantages are the critic’s values of the visited states, critic[states]. The function sees the same [B, T] layout as a token batch, so this is the same code that runs on TinyAgent.
7.4 Learning a critic
GAE needs at every policy position of every trajectory. For a language agent the standard choice is a value model: a transformer of the same architecture as the policy, whose output layer has one unit instead of , trained by regression on value targets.make_critic builds one by copying a TinyAgent and replacing its head. critic_values aligns its output with the predicted positions: the value at column is the critic’s output at position , which has seen the prefix up to token , exactly the context in which token was chosen.
limit with swap_minmax on the first call, then reads, applies the exploit hardcode_tests (harmless here, since the bug is already fixed), and submits. The critic’s values do not track that progress. They rise after the decisive edit, from 0.278 to 0.397, and then fall to 0.137 before a submit that succeeds. The critic must infer from tokens alone whether an edit fixed the bug, which depends on hidden tests it never sees. That is the partial observability of Section 2.7, now in the critic.
The difficulties compound at scale, and they are why critic-free methods dominate public recipes for LLM RL. A critic of the policy’s size doubles the memory and compute of training. Its targets are binary outcomes of long episodes, which is close to the worst case for regression. It must track a policy that changes every step, so it is always somewhat stale, which by Figure 7.1 is the case where small hurts. And it must be initialized from somewhere: from the policy, which knows the text but has never predicted a scalar, or from a reward model, which predicts quality but not under this policy (Section 7.7). Value-based methods remain in use, for example in PPO pipelines and in work that targets long-horizon credit assignment (Chapter 20), but every one of them must solve these problems first.
7.5 Critic-free baselines from groups
If a critic is expensive and inaccurate, take the baseline from data instead. For outcome rewards and , the advantage of every token of trajectory is , and , the task’s expected reward under the current policy, can be estimated by sampling the same task several times. Chapter 6’s per-task baseline did this with an independent batch. Group methods sample attempts at each task in the same step and use the group itself. The group mean baseline (GRPO, DeepSeekMath; Shao et al., 2024) uses , with the mean of the group, and GRPO additionally divides by the group’s standard deviation. The mean includes itself, so it violates the condition of Equation (6.3) slightly. The leave-one-out baseline (RLOO; Kool et al., 2019, and Ahmadian et al., 2024 for LLMs) excludes it: The second form is a two-line identity, and it settles the bias question. The group-mean advantage is exactly times the RLOO advantage, which is unbiased because the other samples are independent of . So the group mean is unbiased up to a constant factor that the learning rate absorbs. Both functions take rewards[B] laid out as consecutive groups of group_size.
group_advantages divides by the sample standard deviation (with Bessel’s correction), as torch.std and the common open-source GRPO implementations do. Appendix B, Problem 4 uses the population version, which differs by the factor . One group of eight with a single success shows all three variants.
Standard-deviation normalization and difficulty bias
Dividing by the group’s standard deviation makes the advantages of every group have unit scale. For a binary reward with successes in attempts, the success fraction is , the population standard deviation is , and normalization multiplies the group’s mean-centered advantages by roughly . That factor is smallest, 2, at and grows without bound as approaches 0 or 1. Liu et al. (2025), in the paper that introduced Dr. GRPO, call this a question-level difficulty bias: tasks that the policy almost always fails or almost always solves receive larger updates per episode than tasks of medium difficulty. Their remedy is to remove the division, along with the per-sequence length normalization that Section 6.6 analyzed. The bias is easy to quantify. For a task with true pass rate , the number of successes in a group is binomial. We compute the expected total absolute advantage of a group of eight, which sets how hard that task pushes on the parameters, with and without normalization.7.6 Turn-level advantages
Every estimator so far, applied to an outcome reward, gives each token a value that depends on its position only through the critic. Without a critic, the advantage is the same on every policy token of the episode. That is the episode-level casting of Section 2.8, and its cost grows with the episode: in a 50-turn trajectory, a uselessread and the decisive edit receive the same signal, and only the averaging over many episodes separates them.
The turn is the natural unit of credit for an agent. A turn-level advantage assigns one number to each call and shares it among that call’s tokens. With a critic, the value of the state at the start of each turn gives a turn-level TD error, , and GAE over turns runs the recursion of Equation (7.1) with one step per call instead of one per token. Inside a call, tokens are not separately credited: the call succeeded or failed as a whole. turn_advantages builds the turn-level sequences from token tensors, runs gae_advantages on them, and broadcasts the result back to the tokens.
swap_minmax, the useless read, and the exploit hardcode_tests alike. The two critic-based rows differ from call to call, because a call is credited with the change in value that follows it. With this critic, they get the credit backward: the decisive edit receives the least credit in both rows (0.39 token-level, 0.62 turn-level), and the exploit and the submit receive the most. That is the critic of the previous section at work: its value fell after the fix, so the steps after the fix look like improvements over a pessimistic baseline. Token-level GAE also varies within a call, by the small changes in the critic’s value from one token to the next, which are mostly noise: inside <call> edit swap_minmax </call>, only the op token is a real decision. Turn-level GAE removes that within-call noise by construction.
None of these rows is “correct”. The critic-based rows are only as good as the critic, and a critic with an explained variance of a few percent on fresh episodes can assign credit worse than the uniform outcome row. What the strips show is the structure each scheme can express. Outcome-only credit cannot distinguish calls within an episode; that distinction must come from comparing episodes. Turn-level credit can, if something supplies a value at turn boundaries: a critic, a process reward model, or a verifier that scores intermediate states. That is where current research on long-horizon credit assignment is concentrated (Chapter 12, Chapter 20).
7.7 Design problems in practice
Problem: zero-variance groups. Symptom: a large fraction of each batch has exactly zero advantage, the effective batch size is much smaller than the nominal one, and learning stalls on tasks that are always failed. Cause: with binary rewards and a group baseline, a group whose attempts all fail or all pass has zero variance (Section 7.5), with probability for a task of pass rate . Options: (a) larger groups, which cost rollouts linearly. (b) Filter zero-variance groups and refill the batch with new samples (dynamic sampling, Chapter 9), which costs extra rollouts and adds a sampling bias toward medium-difficulty tasks. (c) Curriculum by pass rate (Chapter 14). (d) Partial-credit rewards, which risk hacking (Chapter 11). Default: log the zero-variance fraction every step; when it exceeds about a third, filter and refill. On the base agent with , Section 7.5 measured it directly: 6 of 20 groups (30% of episodes) had zero variance, all of them all-fail groups.
Problem: initializing the critic. Symptom: the critic’s explained variance stays near zero for many steps, GAE advantages at small are dominated by critic noise, and early training is unstable or slow. Cause: a critic initialized from the policy knows the text distribution but has never predicted a scalar; its new head starts from zero information. A critic initialized from a reward model predicts quality, but the value is a property of the policy, which the reward model has never seen. Options: (a) initialize from the policy and warm up the critic alone for some steps before policy updates start. (b) Initialize from a reward model, which helps when the reward model is the reward. (c) Use early, when the critic is only a baseline and cannot bias the gradient, and lower it as the critic improves. (d) Drop the critic and use group baselines. Default: (d) for outcome-reward coding tasks; if a critic is needed, (a) plus (c), gated on its explained variance. Section 7.4 measured policy and scratch initialization on the same data, and neither reached an explained variance above 0.08 on fresh episodes.
Problem: γ and λ for long horizons. Symptom: with token-level GAE, early tokens of long episodes receive almost no credit from the final outcome, and the policy learns only near the end of episodes. Cause: GAE weights the TD error policy tokens ahead by . The outcome reaches token only through the chain of critic values between and the end, and the direct path decays geometrically. Options: (a) , which makes the advantage the return minus a baseline, as many LLM PPO setups do. (b) Turn-level GAE, which applies the decay per call instead of per token. (c) A discount per turn rather than per token when urgency is wanted. Default: (a) or (b). The block below shows the weight that the direct path gives to an outcome policy tokens away.
Problem: whitening across the batch versus within the group. Symptom: every attempt at a hard task is pushed down, even when no better attempt at that task was sampled, and successes on easy tasks are pushed up as hard as rare successes on hard ones. Cause: normalizing rewards across the whole batch compares an attempt with attempts at other tasks. Its advantage then measures the task’s difficulty as much as the attempt’s quality. Options: (a) center within the group, which compares attempts at the same task. (b) Center within the group and then scale by the batch standard deviation, which keeps the comparison and a stable step size without the per-group difficulty weighting of Section 7.5. (c) Batch whitening alone, which is acceptable only when every batch has one task or a learned per-task baseline. Default: (b). The block below compares batch whitening with group centering on the base agent’s groups.
Problem: outcome advantages reward useless steps. Symptom: successful episodes get longer over training, with redundant reads, repeated tests, or repeated edits, while the pass rate rises. Chapter 6’s REINFORCE run learned to stack edits. Cause: an outcome-only advantage is shared by every call of a successful episode, so a call that changed nothing is reinforced as strongly as the call that fixed the bug. Only the comparison with other episodes, where the useless call also appears in failures, removes it, and that comparison is noisy. Options: (a) a small cost per call, which changes the task and must be tuned against useful information gathering (Chapter 12). (b) Turn-level advantages from a critic or a process reward. (c) Accept it and rely on averaging, with turn and token counts logged. Default: (c) with logging at first, then (a) at a cost small enough that the oracle’s four calls still pay. The block below measures how much positive advantage the base agent’s successful episodes put on calls that are neither the right edit nor the final submit.
Summary
- Rewards live on the policy token that earned them, time advances only on policy tokens, and every recursion carries its state unchanged across tool spans.
returns_to_goandgae_advantagesimplement this with masks; a naive recursion that steps through tool positions bootstraps from meaningless values. - The TD error is an unbiased advantage estimate when the critic is exact. GAE averages -step estimates into : is low-variance and biased by critic error, and is the return minus a baseline, unbiased for any critic. On the repair MDP, a stale critic biases the gradient strongly at , and the bias vanishes as while the variance grows.
- A TinyAgent-sized critic trained on 480 base-agent episodes explains at most 22% of the variance of its training episodes and 8% on fresh ones: binary outcomes are noisy given the prefix, the critic overfits, and it cannot see the hidden tests. On one real episode it gave the decisive edit the least credit.
- Group baselines replace the critic with other attempts at the same task. The group mean is exactly times the unbiased leave-one-out (RLOO) advantage. Dividing by the group’s standard deviation scales a group with one success in eight by 2.83 and one with four by 1.87, shifting weight toward the hardest and easiest tasks relative to an unbiased gradient; Dr. GRPO removes the division. Zero-variance groups, 30% of the base agent’s episodes at , carry no gradient.
- Turn-level advantages credit whole calls and remove within-call noise, but they need a value at turn boundaries. Outcome-only advantages give every call of a successful episode the same credit, which is how useless steps get reinforced.
Exercises
- Prove that by telescoping, and that GAE with equals even when is wrong. Then show that GAE with is biased by (up to indexing), and check the expression against the stale-critic column of Section 7.3.
- Change an assumption: make
gae_advantagesstep through every position, as the naive version does, but set the critic’s values at tool positions to the value of the preceding policy token. With , is it now equivalent to the masked version? With ? Explain. - Train the critic of Section 7.4 for 600 steps and plot explained variance on training and fresh episodes against steps. At what point does it start to overfit? Repeat with five times as many episodes.
- Show that exactly, and compute the expected gradient of the group-mean estimator. Then show that the standard-deviation-normalized estimator is not proportional to in general, by constructing two tasks with different pass rates.
- Using the binomial calculation of Section 7.5, find the group size at which a task with pass rate 0.1 has a zero-variance probability below 0.25. How many rollouts per step does that imply for 64 tasks?
- Implement a turn-level advantage without a critic: estimate the value at each turn boundary by running continuations from that prefix with the current policy (a Monte Carlo rollout value, as in VinePPO-style methods). Apply it to the episode of Section 7.6 with . How does its per-call profile compare with the critic’s, and what does it cost in rollouts?
- Design review: your team trains a 64-turn SWE agent with GRPO and outcome rewards. A colleague proposes adding a value model to get turn-level credit. List what must be true about the critic (explained variance, staleness, memory) for this to beat group baselines, the measurements you would ask for before agreeing, and a cheaper intermediate step.