Generalized Advantage Estimation
λ-weighted advantages: the bias–variance dial of modern policy gradients.
Almost every PPO implementation computes its advantages with one short backward loop, . Behind it is an exponentially weighted average of -step advantage estimators, two knobs that trade bias for variance in different ways, and an easily missed rule about where episodes really end. This lesson derives generalized advantage estimation, puts numbers on its bias and variance, and writes the loop correctly.
What you’ll learn
- Derive GAE as an exponentially weighted average of -step advantage estimators, and relate it to λ-returns and to reward shaping.
- Compute GAE's bias when the critic is wrong and bound its variance when the critic is right, as functions of and .
- Explain why biases the estimate against the undiscounted objective whatever the critic, while biases it only through critic errors.
- Implement GAE with correct handling of terminations and time-limit truncations, and fit the critic to λ-return targets.
An average of k-step advantages
Schulman, Moritz, Levine, Jordan and Abbeel (2016) start from the -step advantage estimators of Actor–Critic Methods, written with the critic's TD errors :
Average the -step estimators with the λ-return weights , which sum to 1:
Swap the sums. appears in every with , with total weight :
The extremes are the one-step TD error and the Monte Carlo advantage:
And the sum obeys a one-line recursion, which is how it is computed, backward through a rollout:
Two more readings of the same sum.
- λ-returns. With the λ-return that bootstraps from (the forward view of Forward & Backward Views of TD(λ)), . TD(λ) estimates values and GAE estimates advantages, with the same weights.
- Reward shaping. is the reward shaped with the potential : . Potential-based shaping leaves optimal policies unchanged (Ng, Harada & Russell, 1999), and GAE is the -discounted return of the shaped reward. A good potential makes the shaped reward informative at once, so a steeply discounted sum of it loses little.
With , and TD errors , , , after which the episode terminates, what is ?
Show the answer
3
. Backward: , , .
Bias and variance, precisely
Let be the critic's error and the TD error of the true value, so . Summing with weights regroups the errors by the state they belong to:
Take expectations given . For , under the policy, while . The term depends only on the state, so it acts as a baseline. The last term can depend on , and it is the bias that matters for the gradient:
Its size is at most times the total weight below, which falls from at to at . Only how varies with the action matters, and that dependence fades as grows and the chain forgets its starting action, so the actual bias is usually well below this worst case:
Variance with a correct critic. If , the TD errors after step are martingale differences: each has mean zero given everything before it, so they are uncorrelated with one another and with . If every TD error has conditional variance at most , then . With an imperfect critic the TD errors are correlated, but the same factor still indicates how many steps of noise the estimate accumulates.
| (with ) | worst-case weight on critic errors, | variance factor, | effective horizon, |
|---|---|---|---|
| 0 | 0.99 | 1 | 1 |
| 0.9 | 0.91 | 4.9 | 9.2 |
| 0.95 | 0.83 | 8.7 | 16.8 |
| 0.99 | 0.50 | 25.4 | 50.3 |
| 1 | 0 | 50.3 | 100 |
Two dials: γ and λ
The two parameters are not interchangeable. If the objective you care about is the undiscounted return, taking biases the policy gradient whatever the critic: it changes the target from to , and with it the problem being solved (Discounting & Horizons). Taking biases it only through the critic's errors. Schulman et al. found the best results at intermediate values of both: on cart-pole and ; on 3D bipedal locomotion and ; and in general an intermediate in . PPO's published settings use and . The large on-policy study of Andrychowicz et al. (2020) recommends starting from , and counts among the most important hyperparameters, to be tuned per environment starting from 0.99.
Fitting the critic. The critic's regression targets are usually the λ-returns , so actor and critic see consistent estimates. Schulman et al. also limited each critic update with a trust region: minimize subject to , with the old critic's mean squared error, which they note is equivalent to bounding the average KL divergence between the old and new value functions read as Gaussians. It keeps one noisy batch from wrecking the critic. The value-loss clipping found in some PPO implementations aims at the same worry; Andrychowicz et al. recommend against it.
Normalizing advantages. Most implementations standardize the advantages in each batch to zero mean and unit variance before the policy update: a constant baseline plus a rescaled step size, cheap and usually helpful.
Your critic is perfect, exactly. Which choice still biases the policy gradient with respect to the undiscounted return?
- Both
- Neither
Show the answer
B.
With an exact critic every gives the same expected gradient: that of the discounted objective. But the discounted objective differs from the undiscounted one whenever , because the estimator targets , not . The discount decides what is estimated; only decides how.
Computing GAE correctly
Implementations collect rollouts of a fixed length from vectorized environments, so a rollout can contain episode boundaries, and its last state is usually not terminal. Two kinds of boundary need different treatment (Pardo, Tavakoli, Levdik & Kormushev, 2018):
- Termination: the task really ended (the pole fell, the goal was reached). The next state's value is 0, so do not bootstrap, and do not let advantages flow back across the boundary.
- Truncation: a time limit cut the episode, or the rollout simply ended. The state is not terminal, so bootstrap from of the actual next observation. At a time-limit boundary still cut the recursion, because the next step of the rollout belongs to a new episode.
Treating truncations as terminations teaches the critic that states near the time limit are worth less, which it cannot explain from the state unless the remaining time is part of it. In vectorized environments that reset automatically, the bootstrap needs the true final observation of the finished episode, not the first observation of the next one; how it is exposed depends on the library's reset mode.
import numpy as np
def compute_gae(rewards, values, next_values, terminated, truncated, gamma=0.99, lam=0.95):
"""One environment's rollout of length T (NumPy arrays).
values[t] = V(S_t); next_values[t] = V of the true next observation S_{t+1}
(for a truncated step: the final observation of that episode, before any reset)."""
T = len(rewards)
adv = np.zeros(T)
gae = 0.0
for t in reversed(range(T)):
# bootstrap unless the episode really ended: a time-limit cut still has a future
delta = rewards[t] + gamma * next_values[t] * (1.0 - terminated[t]) - values[t]
# never let advantages flow back across an episode boundary of either kind
boundary = terminated[t] or truncated[t]
gae = delta + gamma * lam * (1.0 - boundary) * gae
adv[t] = gae
returns = adv + values # λ-return targets for the critic
return adv, returnsThe common shortcut done = terminated or truncated, used for both purposes, is exactly the bug described above. At the end of the rollout the recursion starts from 0 and bootstraps from , which truncates the λ-sum there. The critic is then regressed onto returns, and the advantages are standardized per batch before the policy update.
Key takeaways
- GAE averages the -step advantages with weights ; the average collapses to , is computed backward as , and equals the λ-return minus .
- Its gradient-relevant bias is , zero at or with an exact critic; with an exact critic its variance is at most .
- biases the estimate against the undiscounted objective whatever the critic; only through critic errors. In practice with between about 0.9 and 0.99.
- Bootstrap at truncations but not at terminations, and never let the recursion cross an episode boundary.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
What are GAE and GAE?
- The one-step TD error , and the discounted return minus
- The discounted return, and the one-step TD error
- Zero, and the λ-return
- The state value, and the action value
Show the answer
A. The one-step TD error , and the discounted return minus
With only the term of survives. With the TD errors telescope: the intermediate values cancel and what remains is .
When does GAE with bias the policy gradient of the discounted objective?
- Always, because cuts off the distant future
- When the critic's errors at future states depend, in expectation, on the current action
- Only when
- Never
Show the answer
B. When the critic's errors at future states depend, in expectation, on the current action
The gradient-relevant bias is , up to a state-only term that acts as a baseline. With an exact critic it vanishes for every ; with an inexact one, only its action-dependent part biases the gradient.
A rollout step ends because the episode hit its 1000-step time limit, not because the task ended. Which handling is right?
- Use for the next state, and continue the recursion into the next episode
- Treat it as a termination: no bootstrap, and cut the recursion
- Drop the step from the batch
- Bootstrap from of the true final observation, and cut the GAE recursion at the boundary
Show the answer
D. Bootstrap from of the true final observation, and cut the GAE recursion at the boundary
The state at the time limit is not terminal, so its future value is real and should be estimated by the critic. But the next step of the rollout starts a new episode, so advantages must not flow back across the boundary.
With and TD errors , the episode terminating after step 2, what is ?
- 1
- 4
- 2
- 0
Show the answer
C. 2
Backward: , , . Equivalently .
Further reading
- J. Schulman, P. Moritz, S. Levine, M. I. Jordan & P. Abbeel, "High-dimensional continuous control using generalized advantage estimation," ICLR (2016).
- F. Pardo, A. Tavakoli, V. Levdik & P. Kormushev, "Time limits in reinforcement learning," ICML (2018).
- A. Y. Ng, D. Harada & S. Russell, "Policy invariance under reward transformations: Theory and application to reward shaping," ICML (1999).
- M. Andrychowicz et al., "What matters in on-policy reinforcement learning? A large-scale empirical study," arXiv:2006.05990 (2020).