Simple Algorithm
Reinforcement Learning · Fixed Point · 26 min

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, A^t=δt+γλ A^t+1\hat A_t=\delta_t+\gamma\lambda\,\hat A_{t+1}. Behind it is an exponentially weighted average of kk-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 kk-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 γ\gamma and λ\lambda.
  • Explain why γ<1\gamma<1 biases the estimate against the undiscounted objective whatever the critic, while λ<1\lambda<1 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 kk-step advantage estimators of Actor–Critic Methods, written with the critic's TD errors δt=Rt+1+γV(St+1)−V(St)\delta_t=R_{t+1}+\gamma V(S_{t+1})-V(S_t):

A^t(k)=∑l=0k−1γl δt+l=−V(St)+Rt+1+γRt+2+⋯+γk−1Rt+k+γkV(St+k)\hat A^{(k)}_t=\sum_{l=0}^{k-1}\gamma^l\,\delta_{t+l}=-V(S_t)+R_{t+1}+\gamma R_{t+2}+\dots+\gamma^{k-1}R_{t+k}+\gamma^kV(S_{t+k})
DerivationExponential weighting collapses to one sum
  1. A^tGAE(γ,λ)=(1−λ)∑k≥1λk−1A^t(k)=(1−λ)∑k≥1λk−1∑l=0k−1γl δt+l\hat A^{\text{GAE}(\gamma,\lambda)}_t=(1-\lambda)\sum_{k\ge1}\lambda^{k-1}\hat A^{(k)}_t=(1-\lambda)\sum_{k\ge1}\lambda^{k-1}\sum_{l=0}^{k-1}\gamma^l\,\delta_{t+l}

    Average the kk-step estimators with the λ-return weights (1−λ)λk−1(1-\lambda)\lambda^{k-1}, which sum to 1:

  2. A^tGAE(γ,λ)=∑l≥0(γλ)l δt+l\hat A^{\text{GAE}(\gamma,\lambda)}_t=\sum_{l\ge0}(\gamma\lambda)^l\,\delta_{t+l}

    Swap the sums. δt+l\delta_{t+l} appears in every A^t(k)\hat A^{(k)}_t with k>lk>l, with total weight (1−λ)∑k>lλk−1=λl(1-\lambda)\sum_{k>l}\lambda^{k-1}=\lambda^l:

  3. A^tGAE(γ,0)=δt,A^tGAE(γ,1)=∑l≥0γlδt+l=∑l≥0γlRt+l+1−V(St)\hat A^{\text{GAE}(\gamma,0)}_t=\delta_t,\qquad\hat A^{\text{GAE}(\gamma,1)}_t=\sum_{l\ge0}\gamma^l\delta_{t+l}=\sum_{l\ge0}\gamma^lR_{t+l+1}-V(S_t)

    The extremes are the one-step TD error and the Monte Carlo advantage:

  4. A^tGAE=δt+γλ A^t+1GAE\hat A^{\text{GAE}}_t=\delta_t+\gamma\lambda\,\hat A^{\text{GAE}}_{t+1}

    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 GtλG^\lambda_t the λ-return that bootstraps from VV (the forward view of Forward & Backward Views of TD(λ)), A^tGAE=Gtλ−V(St)\hat A^{\text{GAE}}_t=G^\lambda_t-V(S_t). TD(λ) estimates values and GAE estimates advantages, with the same weights.
  • Reward shaping. δt\delta_t is the reward shaped with the potential VV: Rt+1+γV(St+1)−V(St)R_{t+1}+\gamma V(S_{t+1})-V(S_t). Potential-based shaping leaves optimal policies unchanged (Ng, Harada & Russell, 1999), and GAE is the γλ\gamma\lambda-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.
Predict before you look

With γ=1\gamma=1, λ=0.5\lambda=0.5 and TD errors δt=1\delta_t=1, δt+1=2\delta_{t+1}=2, δt+2=4\delta_{t+2}=4, after which the episode terminates, what is A^tGAE\hat A^{\text{GAE}}_t?

Show the answer

3

1+0.5×2+0.25×4=31+0.5\times2+0.25\times4=3. Backward: A^t+2=4\hat A_{t+2}=4, A^t+1=2+0.5×4=4\hat A_{t+1}=2+0.5\times4=4, A^t=1+0.5×4=3\hat A_t=1+0.5\times4=3.

Bias and variance, precisely

DerivationThe bias when the critic is wrong
  1. A^tGAE=∑l≥0(γλ)l δt+l⋆  −  e(St)  +  (1−λ)∑l≥1γlλl−1 e(St+l)\hat A^{\text{GAE}}_t=\sum_{l\ge0}(\gamma\lambda)^l\,\delta^\star_{t+l}\;-\;e(S_t)\;+\;(1-\lambda)\sum_{l\ge1}\gamma^l\lambda^{l-1}\,e(S_{t+l})

    Let e=V−Vπ,γe=V-V^{\pi,\gamma} be the critic's error and δt⋆\delta^\star_t the TD error of the true value, so δt=δt⋆+γe(St+1)−e(St)\delta_t=\delta^\star_t+\gamma e(S_{t+1})-e(S_t). Summing with weights (γλ)l(\gamma\lambda)^l regroups the errors by the state they belong to:

  2. E[A^tGAE∣St,At]=Aπ,γ(St,At)−e(St)+(1−λ)∑l≥1γlλl−1 E[e(St+l)∣St,At]⏟harmful part\E\big[\hat A^{\text{GAE}}_t\mid S_t,A_t\big]=A^{\pi,\gamma}(S_t,A_t)-e(S_t)+\underbrace{(1-\lambda)\sum_{l\ge1}\gamma^l\lambda^{l-1}\,\E\big[e(S_{t+l})\mid S_t,A_t\big]}_{\text{harmful part}}

    Take expectations given (St,At)(S_t,A_t). For l≥1l\ge1, E[δt+l⋆∣St+l]=0\E[\delta^\star_{t+l}\mid S_{t+l}]=0 under the policy, while E[δt⋆∣St,At]=Aπ,γ(St,At)\E[\delta^\star_t\mid S_t,A_t]=A^{\pi,\gamma}(S_t,A_t). The term −e(St)-e(S_t) depends only on the state, so it acts as a baseline. The last term can depend on AtA_t, and it is the bias that matters for the gradient:

  3. (1−λ)∑l≥1γlλl−1=γ(1−λ)1−γλ(1-\lambda)\sum_{l\ge1}\gamma^l\lambda^{l-1}=\frac{\gamma(1-\lambda)}{1-\gamma\lambda}

    Its size is at most ∥e∥∞\norm e_\infty times the total weight below, which falls from γ\gamma at λ=0\lambda=0 to 00 at λ=1\lambda=1. Only how E[e(St+l)∣St,At]\E[e(S_{t+l})\mid S_t,A_t] varies with the action matters, and that dependence fades as ll 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 V=Vπ,γV=V^{\pi,\gamma}, the TD errors after step tt are martingale differences: each has mean zero given everything before it, so they are uncorrelated with one another and with δt⋆\delta^\star_t. If every TD error has conditional variance at most σ2\sigma^2, then Var⁡(A^tGAE∣St,At)≤σ2∑l≥0(γλ)2l=σ2/(1−γ2λ2)\Var\big(\hat A^{\text{GAE}}_t\mid S_t,A_t\big)\le\sigma^2\sum_{l\ge0}(\gamma\lambda)^{2l}=\sigma^2/(1-\gamma^2\lambda^2). With an imperfect critic the TD errors are correlated, but the same factor still indicates how many steps of noise the estimate accumulates.

λ\lambda (with γ=0.99\gamma=0.99)worst-case weight on critic errors, γ(1−λ)1−γλ\frac{\gamma(1-\lambda)}{1-\gamma\lambda}variance factor, 11−γ2λ2\frac{1}{1-\gamma^2\lambda^2}effective horizon, 11−γλ\frac{1}{1-\gamma\lambda}
00.9911
0.90.914.99.2
0.950.838.716.8
0.990.5025.450.3
1050.3100
The worst-case bias weight falls slowly until λ\lambda is close to 1, while the variance factor climbs. The worst case assumes the critic's errors at every future state depend fully on the current action; because that dependence fades, the bias at moderate λ\lambda is usually much smaller than the table's column suggests.

Two dials: γ and λ

The two parameters are not interchangeable. If the objective you care about is the undiscounted return, taking γ<1\gamma<1 biases the policy gradient whatever the critic: it changes the target from AπA^\pi to Aπ,γA^{\pi,\gamma}, and with it the problem being solved (Discounting & Horizons). Taking λ<1\lambda<1 biases it only through the critic's errors. Schulman et al. found the best results at intermediate values of both: on cart-pole γ∈[0.96,0.99]\gamma\in[0.96,0.99] and λ∈[0.92,0.99]\lambda\in[0.92,0.99]; on 3D bipedal locomotion γ∈[0.99,0.995]\gamma\in[0.99,0.995] and λ∈[0.96,0.99]\lambda\in[0.96,0.99]; and in general an intermediate λ\lambda in [0.9,0.99][0.9,0.99]. PPO's published settings use γ=0.99\gamma=0.99 and λ=0.95\lambda=0.95. The large on-policy study of Andrychowicz et al. (2020) recommends starting from λ=0.9\lambda=0.9, and counts γ\gamma 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 V^ttarg=A^tGAE+Vold(St)\hat V^{\text{targ}}_t=\hat A^{\text{GAE}}_t+V_{\text{old}}(S_t), so actor and critic see consistent estimates. Schulman et al. also limited each critic update with a trust region: minimize ∑n∥Vϕ(sn)−V^n∥2\sum_n\norm{V_\phi(s_n)-\hat V_n}^2 subject to 1N∑n∥Vϕ(sn)−Vϕold(sn)∥2/(2σ2)≤ε\frac1N\sum_n\norm{V_\phi(s_n)-V_{\phi_{\text{old}}}(s_n)}^2/(2\sigma^2)\le\varepsilon, with σ2\sigma^2 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.

Check your understanding

Your critic is perfect, V=Vπ,γV=V^{\pi,\gamma} exactly. Which choice still biases the policy gradient with respect to the undiscounted return?

  1. λ=0.9\lambda=0.9
  2. γ=0.99\gamma=0.99
  3. Both
  4. Neither
Show the answer

B. γ=0.99\gamma=0.99

With an exact critic every λ\lambda gives the same expected gradient: that of the discounted objective. But the discounted objective differs from the undiscounted one whenever γ<1\gamma<1, because the estimator targets Aπ,γA^{\pi,\gamma}, not AπA^\pi. The discount decides what is estimated; λ\lambda only decides how.

Computing GAE correctly

Implementations collect rollouts of a fixed length TT 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 VV 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.

python
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, returns

The 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 V(ST)V(S_T), 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 kk-step advantages with weights (1−λ)λk−1(1-\lambda)\lambda^{k-1}; the average collapses to ∑l(γλ)lδt+l\sum_l(\gamma\lambda)^l\delta_{t+l}, is computed backward as A^t=δt+γλA^t+1\hat A_t=\delta_t+\gamma\lambda\hat A_{t+1}, and equals the λ-return minus V(St)V(S_t).
  • Its gradient-relevant bias is (1−λ)∑l≥1γlλl−1E[e(St+l)∣St,At](1-\lambda)\sum_{l\ge1}\gamma^l\lambda^{l-1}\E[e(S_{t+l})\mid S_t,A_t], zero at λ=1\lambda=1 or with an exact critic; with an exact critic its variance is at most σ2/(1−γ2λ2)\sigma^2/(1-\gamma^2\lambda^2).
  • γ<1\gamma<1 biases the estimate against the undiscounted objective whatever the critic; λ<1\lambda<1 only through critic errors. In practice γ≈0.99\gamma\approx0.99 with λ\lambda 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.

Question 1

What are GAE(γ,0)(\gamma,0) and GAE(γ,1)(\gamma,1)?

  1. The one-step TD error δt\delta_t, and the discounted return minus V(St)V(S_t)
  2. The discounted return, and the one-step TD error
  3. Zero, and the λ-return
  4. The state value, and the action value
Show the answer

A. The one-step TD error δt\delta_t, and the discounted return minus V(St)V(S_t)

With λ=0\lambda=0 only the l=0l=0 term of ∑l(γλ)lδt+l\sum_l(\gamma\lambda)^l\delta_{t+l} survives. With λ=1\lambda=1 the TD errors telescope: the intermediate values cancel and what remains is ∑lγlRt+l+1−V(St)\sum_l\gamma^lR_{t+l+1}-V(S_t).

Question 2

When does GAE(γ,λ)(\gamma,\lambda) with λ<1\lambda<1 bias the policy gradient of the discounted objective?

  1. Always, because λ<1\lambda<1 cuts off the distant future
  2. When the critic's errors at future states depend, in expectation, on the current action
  3. Only when γ=1\gamma=1
  4. 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 (1−λ)∑l≥1γlλl−1E[e(St+l)∣St,At](1-\lambda)\sum_{l\ge1}\gamma^l\lambda^{l-1}\E[e(S_{t+l})\mid S_t,A_t], up to a state-only term that acts as a baseline. With an exact critic it vanishes for every λ\lambda; with an inexact one, only its action-dependent part biases the gradient.

Question 3

A rollout step ends because the episode hit its 1000-step time limit, not because the task ended. Which handling is right?

  1. Use V=0V=0 for the next state, and continue the recursion into the next episode
  2. Treat it as a termination: no bootstrap, and cut the recursion
  3. Drop the step from the batch
  4. Bootstrap from VV of the true final observation, and cut the GAE recursion at the boundary
Show the answer

D. Bootstrap from VV 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.

Question 4

With γλ=0.5\gamma\lambda=0.5 and TD errors (δ0,δ1,δ2)=(2,−2,4)(\delta_0,\delta_1,\delta_2)=(2,-2,4), the episode terminating after step 2, what is A^0\hat A_0?

  1. 1
  2. 4
  3. 2
  4. 0
Show the answer

C. 2

Backward: A^2=4\hat A_2=4, A^1=−2+0.5×4=0\hat A_1=-2+0.5\times4=0, A^0=2+0.5×0=2\hat A_0=2+0.5\times0=2. Equivalently 2−0.5×2+0.25×4=22-0.5\times2+0.25\times4=2.

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).