Generalized advantage estimation
By the end of §15.4 we had two ways to estimate the advantage of an action from one sampled trajectory, and they sit at opposite ends of a trade-off. The Monte Carlo estimate, , waits for every reward that follows and subtracts the critic's prediction. Whatever the critic gets wrong, it is a valid baseline, so the policy gradient stays unbiased, but it carries the noise of an entire future. The TD error, , looks one step ahead and trusts the critic for the rest. It is quiet, but if the critic is wrong, the gradient is wrong.
Is there anything in between? There is a whole family of estimators, and one parameter moves smoothly from one end to the other. Schulman, Moritz, Levine, Jordan, and Abbeel (2016) named it generalized advantage estimation (GAE). It is the advantage estimator inside PPO, and therefore inside RLHF (§16.4), and it is a five-line backward loop that interviewers love to ask for, because it is easy to get almost right. This section derives it, measures its bias and variance against exact advantages, and handles the part that actually breaks in code, the ends of episodes.
Sums of TD errors
Throughout, is the critic's current estimate (not necessarily the true ), is the discount, and the TD error at step is
Add up the next TD errors, discounting each by how far ahead it is. Writing each one out,
The last two sums are the same list of terms shifted by one. The second runs over and the third over , so everything cancels except the two ends. The sum telescopes,
In plain words, the sum of discounted TD errors is the -step advantage estimate. Take real rewards, let the critic estimate everything after them, and subtract the critic's estimate of where you started. The part before the subtraction, , is called the -step return.
The two estimators we already had are the ends of this family. With it is the TD error. With running to the end of the episode (or to infinity, where ), the bootstrap term disappears and it is the Monte Carlo estimate .
Where the bias lives, and how it shrinks
Suppose the critic is off by an error . Take the expectation of given and . Write in the -step estimate. The part built from the true values has expectation exactly . To see it, use the Bellman equation , which holds because the action at step is drawn from , to fold the last reward and the bootstrap into , and repeat until one reward is left. What remains is , because the first action is fixed. The errors are left over,
The last term, , depends only on the state, so it is a baseline and does not bias the policy gradient (§15.4). The middle term depends on the action, because the action influences where you are steps later, so it does bias the gradient. But it is multiplied by . In plain words, the further you look ahead before trusting the critic, the less the critic's mistakes matter, and they matter geometrically less.
The variance goes the other way. Each extra step adds one more random reward and one more random transition to the estimate. So is a bias-variance dial, but an awkward one. It is an integer, the best value depends on the problem, and it throws away the information in all the other horizons.
GAE, an average over every horizon
Instead of choosing one , average all of them, with weights that decay geometrically. For a parameter , define
The weights are positive and sum to one, so this is a weighted average of the -step estimates, leaning on short horizons when is small and long ones when is near 1. It looks expensive, an infinite sum of sums, but it collapses. Substitute each as its sum of TD errors and collect the coefficient of each . The error appears (with factor ) in every with , so its total weight is
Therefore
In plain words, GAE is a discounted sum of future TD errors, with discount instead of . Each TD error is a small surprise, "this step went better (or worse) than the critic expected", and GAE adds up the surprises that follow an action, fading them out with distance.
The sum satisfies a recursion, the same one that returns satisfy, which is how it is always computed,
so one backward pass over a trajectory produces every advantage, in time.
The two ends are the estimators we started with.
- gives , the one-step TD error. Low variance, biased unless .
- gives , by the telescoping above. Unbiased for the gradient whatever is, high variance.
Everything in between trades one for the other smoothly. The effective horizon of the advantage is steps, about 17 for the common choice , .
Worked example. A three-step episode ends in a terminal state with rewards . The critic predicts , , , and the terminal state has value 0. With the TD errors are
With , so , the backward recursion gives , then , then . With it gives , which matches the Monte Carlo estimate . With it is just . The three answers differ by a factor of eight, which is the whole point. They make different bets on how much to trust the critic.
n-step advantages
For a single episode that terminates after its last step, implement n_step_advantage(rewards, values, n, gamma) with rewards and values of shape (T,) (values[t] , and the terminal state has value 0). Return the array of , shape (T,), where any reward or value past the end of the episode counts as zero (so near the end the estimate becomes the Monte Carlo one).
Two views of the same number
GAE has a twin in the older literature. The -return of Sutton's TD() (Sutton 1988; Sutton and Barto, chapter 12) averages -step returns with the same weights, . Since each and the weights sum to one,
So GAE is the -return with the baseline subtracted, and conversely is the -return. That second form is how PPO trains its critic. The value targets are , regression targets that interpolate between TD targets () and Monte Carlo returns () with the same dial.
What is the difference between the two knobs, and ? Both shrink the weight of the distant future and so reduce variance. But they bias different things. A changes the objective. It makes the agent care less about the far future, and it biases the gradient even with a perfect critic. A keeps the objective and only adds bias through the critic's errors, so with an accurate critic it is free. Schulman et al. (2016) found that the best is typically well below the best , which their analysis attributes to introducing much less bias than for an accurate value function. On their cart-pole task the fastest learning came from between 0.92 and 0.98 at . PPO's defaults, and , come from this line of work.
Bias and variance, measured
In the gridworld we can do what is impossible in a real problem, compute the true advantage of every state and action exactly and compare every estimate against it. Fix the uniformly random policy. Solve for and exactly (§15.2). Then give the agent a wrong critic, , with independent Gaussian errors of standard deviation 0.2 in each state, sample 2,000 episodes, compute GAE for several values of , and compare each estimate with its target.
What is the right target? By §15.4, the critic's error at the current state is a baseline and harmless, so the honest target is , the true action value minus the critic's own baseline. Deviations from it are what actually reach the gradient. We split the mean squared error, for every visited state and action, into the squared bias of the average estimate and the variance around that average.
The table is the bias-variance trade-off in four columns. At half the error is bias, the critic's mistakes about the next state leaking straight into the estimate. As grows the bias falls toward zero (what remains at is sampling noise in our measurement), while the variance grows more than fourfold. The total error is smallest in the middle, around for this critic. A better critic moves the best down, toward trusting it more, and a worse one moves it up. The widget below lets you do exactly that.
Episode ends, termination, truncation, and rollout buffers
The recursion is easy. Getting the edges right is where real implementations break, and there are three different edges.
Termination. If is a terminal state (the goal, the pit, the end-of-sequence token), its value is zero by definition. So , with no bootstrap, and the recursion must not carry anything back from step , which in a rollout buffer belongs to the next episode.
Truncation. If the episode was cut off at step by a time limit, the world did not end. The agent would have kept collecting reward. So the TD error must bootstrap from the value of the state it actually reached, , but the recursion must still stop, because the next entry in the buffer is a fresh episode. Treating a time-out as a terminal state teaches the critic that the world ends when the clock runs out, a bug that Pardo et al. (2018) studied in detail. Gymnasium separates the two cases into terminated and truncated flags for exactly this reason.
The end of the rollout. PPO collects a fixed number of steps per environment, so the buffer usually ends in the middle of an episode. The last step's TD error bootstraps from the critic's value of the state after the last step, and the recursion starts there with .
All three are handled by one convention. Store, for every step, the value of the true next state (computed before any reset), a terminated flag, and a truncated flag. Then
In plain words, termination kills the bootstrap and the recursion, truncation kills only the recursion, and the end of the buffer is a truncation that bootstraps from the last next-state value.
GAE for a rollout buffer, with terminations and truncations
Implement gae(rewards, values, next_values, terminated, truncated, gamma, lam) returning (advantages, returns). All inputs have shape (T,) for one environment or (T, N) for environments stepped in parallel (time is always axis 0). values[t] . next_values[t] for the true next state, recorded before any reset. terminated[t] and truncated[t] are 0 or 1 and describe the transition at step . The buffer's last step is cut off by the end of the rollout whatever its flags say, so treat it as truncated if it did not terminate. Return the GAE advantages and the value targets returns = advantages + values.
GAE is an average of n-step advantages, even in a finite episode
In an infinite episode the weights on are . In an episode that terminates steps after (so for every ), all the weight from onward piles onto the Monte Carlo estimate. Implement gae_weights(m, lam) returning the length- array of weights such that equals the GAE advantage at step , and check your formula against gae by computing both for random episodes.
In PyTorch
Production code computes GAE on tensors of shape (T, N) with exactly the backward loop above, vectorized over environments, under torch.no_grad(), because advantages are targets and must never carry gradients. Here it is next to our NumPy version on a random buffer.
Read more
- Schulman, Moritz, Levine, Jordan & Abbeel (2016). High-Dimensional Continuous Control Using Generalized Advantage Estimation. The GAE paper, with the -just analysis of bias and the experiments on and .
- Sutton (1988). Learning to Predict by the Methods of Temporal Differences. TD() and the -return that GAE is built on.
- Sutton & Barto (2018). Reinforcement Learning: An Introduction, 2nd edition. Chapters 7 and 12 cover n-step returns and eligibility traces in depth.
- Pardo, Tavakoli, Levdik & Kormushev (2018). Time Limits in Reinforcement Learning. Why a time-out is not a terminal state, and what goes wrong when it is treated as one.
- Huang et al. (2022). The 37 Implementation Details of Proximal Policy Optimization. Detail 5 covers GAE, value bootstrapping, and the TD() value targets exactly as PPO implements them.