Chapter 15 · Section 15.5 · 50 min

Generalized advantage estimation

By the end of §15.4 we had two ways to estimate the advantage Aπ(st,at)A^\pi(s_t, a_t) of an action from one sampled trajectory, and they sit at opposite ends of a trade-off. The Monte Carlo estimate, Gt−V(st)G_t - V(s_t), 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, δt=rt+γV(st+1)−V(st)\delta_t = r_t + \gamma V(s_{t+1}) - V(s_t), 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, VV is the critic's current estimate (not necessarily the true VπV^\pi), γ\gamma is the discount, and the TD error at step tt is

δt=rt+γV(st+1)−V(st).\delta_t = r_t + \gamma V(s_{t+1}) - V(s_t).

Add up the next kk TD errors, discounting each by how far ahead it is. Writing each one out,

∑l=0k−1γlδt+l=∑l=0k−1γlrt+l+∑l=0k−1γl+1V(st+l+1)−∑l=0k−1γlV(st+l).\sum_{l=0}^{k-1}\gamma^l\delta_{t+l} = \sum_{l=0}^{k-1}\gamma^l r_{t+l} + \sum_{l=0}^{k-1}\gamma^{l+1}V(s_{t+l+1}) - \sum_{l=0}^{k-1}\gamma^l V(s_{t+l}).

The last two sums are the same list of terms shifted by one. The second runs over γ1V(st+1),…,γkV(st+k)\gamma^1V(s_{t+1}), \dots, \gamma^kV(s_{t+k}) and the third over γ0V(st),…,γk−1V(st+k−1)\gamma^0V(s_t), \dots, \gamma^{k-1}V(s_{t+k-1}), so everything cancels except the two ends. The sum telescopes,

A^t(k):=∑l=0k−1γlδt+l=−V(st)+rt+γrt+1+⋯+γk−1rt+k−1+γkV(st+k).\hat A_t^{(k)} := \sum_{l=0}^{k-1}\gamma^l\delta_{t+l} = -V(s_t) + r_t + \gamma r_{t+1} + \dots + \gamma^{k-1}r_{t+k-1} + \gamma^k V(s_{t+k}).

In plain words, the sum of kk discounted TD errors is the kk-step advantage estimate. Take kk real rewards, let the critic estimate everything after them, and subtract the critic's estimate of where you started. The part before the subtraction, Gt(k)=∑l<kγlrt+l+γkV(st+k)G_t^{(k)} = \sum_{l<k}\gamma^lr_{t+l} + \gamma^kV(s_{t+k}), is called the kk-step return.

The two estimators we already had are the ends of this family. With k=1k = 1 it is the TD error. With kk running to the end of the episode (or to infinity, where γkV→0\gamma^kV \to 0), the bootstrap term disappears and it is the Monte Carlo estimate Gt−V(st)G_t - V(s_t).

Where the bias lives, and how it shrinks

Suppose the critic is off by an error e(s)=V(s)−Vπ(s)e(s) = V(s) - V^\pi(s). Take the expectation of A^t(k)\hat A_t^{(k)} given sts_t and ata_t. Write V=Vπ+eV = V^\pi + e in the kk-step estimate. The part built from the true values has expectation exactly Aπ(st,at)A^\pi(s_t, a_t). To see it, use the Bellman equation Vπ(st+k−1)=E[rt+k−1+γVπ(st+k)∣st+k−1]V^\pi(s_{t+k-1}) = \mathbb{E}[r_{t+k-1} + \gamma V^\pi(s_{t+k})\mid s_{t+k-1}], which holds because the action at step t+k−1t+k-1 is drawn from π\pi, to fold the last reward and the bootstrap into γk−1Vπ(st+k−1)\gamma^{k-1}V^\pi(s_{t+k-1}), and repeat until one reward is left. What remains is E[rt+γVπ(st+1)∣st,at]−Vπ(st)=Qπ(st,at)−Vπ(st)\mathbb{E}[r_t + \gamma V^\pi(s_{t+1})\mid s_t, a_t] - V^\pi(s_t) = Q^\pi(s_t, a_t) - V^\pi(s_t), because the first action is fixed. The errors are left over,

E[A^t(k) ∣ st,at]=Aπ(st,at)+γk E[e(st+k) ∣ st,at]−e(st).\mathbb{E}\big[\hat A_t^{(k)}\,\big|\,s_t, a_t\big] = A^\pi(s_t, a_t) + \gamma^k\,\mathbb{E}\big[e(s_{t+k})\,\big|\,s_t, a_t\big] - e(s_t).

The last term, −e(st)-e(s_t), 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 kk steps later, so it does bias the gradient. But it is multiplied by γk\gamma^k. 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 kk 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 kk, average all of them, with weights that decay geometrically. For a parameter λ∈[0,1]\lambda \in [0, 1], define

A^tGAE(γ,λ)=(1−λ)(A^t(1)+λA^t(2)+λ2A^t(3)+…)=(1−λ)∑k=1∞λk−1A^t(k).\hat A_t^{\text{GAE}(\gamma,\lambda)} = (1-\lambda)\Big(\hat A_t^{(1)} + \lambda\hat A_t^{(2)} + \lambda^2\hat A_t^{(3)} + \dots\Big) = (1-\lambda)\sum_{k=1}^{\infty}\lambda^{k-1}\hat A_t^{(k)} .

The weights (1−λ)λk−1(1-\lambda)\lambda^{k-1} are positive and sum to one, so this is a weighted average of the kk-step estimates, leaning on short horizons when λ\lambda is small and long ones when λ\lambda is near 1. It looks expensive, an infinite sum of sums, but it collapses. Substitute each A^t(k)\hat A^{(k)}_t as its sum of TD errors and collect the coefficient of each δt+l\delta_{t+l}. The error δt+l\delta_{t+l} appears (with factor γl\gamma^l) in every A^t(k)\hat A^{(k)}_t with k≥l+1k \ge l + 1, so its total weight is

(1−λ)γl∑k=l+1∞λk−1=(1−λ)γl λl1−λ=(γλ)l.(1-\lambda)\gamma^l\sum_{k=l+1}^{\infty}\lambda^{k-1} = (1-\lambda)\gamma^l\,\frac{\lambda^l}{1-\lambda} = (\gamma\lambda)^l .

Therefore

A^tGAE(γ,λ)=∑l=0∞(γλ)l δt+l.\hat A_t^{\text{GAE}(\gamma,\lambda)} = \sum_{l=0}^{\infty}(\gamma\lambda)^l\,\delta_{t+l} .

In plain words, GAE is a discounted sum of future TD errors, with discount γλ\gamma\lambda instead of γ\gamma. 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,

A^t=δt+γλ A^t+1,\hat A_t = \delta_t + \gamma\lambda\,\hat A_{t+1},

so one backward pass over a trajectory produces every advantage, in O(T)O(T) time.

The two ends are the estimators we started with.

  • λ=0\lambda = 0 gives A^t=δt\hat A_t = \delta_t, the one-step TD error. Low variance, biased unless V=VπV = V^\pi.
  • λ=1\lambda = 1 gives A^t=∑lγlδt+l=Gt−V(st)\hat A_t = \sum_l\gamma^l\delta_{t+l} = G_t - V(s_t), by the telescoping above. Unbiased for the gradient whatever VV is, high variance.

Everything in between trades one for the other smoothly. The effective horizon of the advantage is 1/(1−γλ)1/(1 - \gamma\lambda) steps, about 17 for the common choice γ=0.99\gamma = 0.99, λ=0.95\lambda = 0.95.

Worked example. A three-step episode ends in a terminal state with rewards (0,0,1)(0, 0, 1). The critic predicts V(s0)=0.5V(s_0) = 0.5, V(s1)=0.6V(s_1) = 0.6, V(s2)=0.8V(s_2) = 0.8, and the terminal state has value 0. With γ=0.9\gamma = 0.9 the TD errors are

δ0=0+0.9(0.6)−0.5=0.04,δ1=0+0.9(0.8)−0.6=0.12,δ2=1+0−0.8=0.2.\delta_0 = 0 + 0.9(0.6) - 0.5 = 0.04, \qquad \delta_1 = 0 + 0.9(0.8) - 0.6 = 0.12, \qquad \delta_2 = 1 + 0 - 0.8 = 0.2 .

With λ=0.5\lambda = 0.5, so γλ=0.45\gamma\lambda = 0.45, the backward recursion gives A^2=0.2\hat A_2 = 0.2, then A^1=0.12+0.45(0.2)=0.21\hat A_1 = 0.12 + 0.45(0.2) = 0.21, then A^0=0.04+0.45(0.21)=0.1345\hat A_0 = 0.04 + 0.45(0.21) = 0.1345. With λ=1\lambda = 1 it gives A^0=0.04+0.9(0.12)+0.81(0.2)=0.31\hat A_0 = 0.04 + 0.9(0.12) + 0.81(0.2) = 0.31, which matches the Monte Carlo estimate G0−V(s0)=0.81−0.5G_0 - V(s_0) = 0.81 - 0.5. With λ=0\lambda = 0 it is just 0.040.04. 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.

Python · cell 1
Core

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] =V(st)= V(s_t), and the terminal state has value 0). Return the array of A^t(n)=∑l=0n−1γlrt+l+γnV(st+n)−V(st)\hat A^{(n)}_t = \sum_{l=0}^{n-1}\gamma^l r_{t+l} + \gamma^nV(s_{t+n}) - V(s_t), 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).

Hidden tests, hints, and AI help, from $1.99 a month.

Two views of the same number

GAE has a twin in the older literature. The λ\lambda-return of Sutton's TD(λ\lambda) (Sutton 1988; Sutton and Barto, chapter 12) averages kk-step returns with the same weights, Gtλ=(1−λ)∑kλk−1Gt(k)G_t^\lambda = (1-\lambda)\sum_k\lambda^{k-1}G_t^{(k)}. Since each A^t(k)=Gt(k)−V(st)\hat A_t^{(k)} = G^{(k)}_t - V(s_t) and the weights sum to one,

A^tGAE(γ,λ)=Gtλ−V(st).\hat A_t^{\text{GAE}(\gamma,\lambda)} = G_t^\lambda - V(s_t).

So GAE is the λ\lambda-return with the baseline subtracted, and conversely A^t+V(st)\hat A_t + V(s_t) is the λ\lambda-return. That second form is how PPO trains its critic. The value targets are R^t=A^t+Vold(st)\hat R_t = \hat A_t + V_{\text{old}}(s_t), regression targets that interpolate between TD targets (λ=0\lambda = 0) and Monte Carlo returns (λ=1\lambda = 1) with the same dial.

What is the difference between the two knobs, γ\gamma and λ\lambda? Both shrink the weight of the distant future and so reduce variance. But they bias different things. A γ<1\gamma < 1 changes the objective. It makes the agent care less about the far future, and it biases the gradient even with a perfect critic. A λ<1\lambda < 1 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 λ\lambda is typically well below the best γ\gamma, which their analysis attributes to λ\lambda introducing much less bias than γ\gamma for an accurate value function. On their cart-pole task the fastest learning came from λ\lambda between 0.92 and 0.98 at γ=0.99\gamma = 0.99. PPO's defaults, γ=0.99\gamma = 0.99 and λ=0.95\lambda = 0.95, 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 VπV^\pi and QπQ^\pi exactly (§15.2). Then give the agent a wrong critic, V=Vπ+noiseV = V^\pi + \text{noise}, with independent Gaussian errors of standard deviation 0.2 in each state, sample 2,000 episodes, compute GAE for several values of λ\lambda, 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 Qπ(st,at)−V(st)Q^\pi(s_t,a_t) - V(s_t), 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.

Python · cell 2
Python · cell 3

The table is the bias-variance trade-off in four columns. At λ=0\lambda = 0 half the error is bias, the critic's mistakes about the next state leaking straight into the estimate. As λ\lambda grows the bias falls toward zero (what remains at λ=1\lambda = 1 is sampling noise in our measurement), while the variance grows more than fourfold. The total error is smallest in the middle, around λ=0.5\lambda = 0.5 for this critic. A better critic moves the best λ\lambda down, toward trusting it more, and a worse one moves it up. The widget below lets you do exactly that.

How does λ trade the critic's bias against the variance of the future?
The random walker in the gridworld, with a critic whose value in each cell is off by Gaussian noise. Left, one episode. Click a step to see how GAE weights the TD errors after it. Right, error of GAE against the exact advantages, over 1,000 episodes.
Loading interactive figure…

Episode ends, termination, truncation, and rollout buffers

The recursion A^t=δt+γλA^t+1\hat A_t = \delta_t + \gamma\lambda\hat A_{t+1} is easy. Getting the edges right is where real implementations break, and there are three different edges.

Termination. If st+1s_{t+1} is a terminal state (the goal, the pit, the end-of-sequence token), its value is zero by definition. So δt=rt−V(st)\delta_t = r_t - V(s_t), with no bootstrap, and the recursion must not carry anything back from step t+1t+1, which in a rollout buffer belongs to the next episode.

Truncation. If the episode was cut off at step tt 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, δt=rt+γV(st+1)−V(st)\delta_t = r_t + \gamma V(s_{t+1}) - V(s_t), 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 A^T=0\hat A_{T} = 0.

All three are handled by one convention. Store, for every step, the value of the true next state V(st+1)V(s_{t+1}) (computed before any reset), a terminated flag, and a truncated flag. Then

δt=rt+γ (1−termt) V(st+1)−V(st),A^t=δt+γλ (1−termt)(1−trunct) A^t+1.\delta_t = r_t + \gamma\,(1 - \text{term}_t)\,V(s_{t+1}) - V(s_t), \qquad \hat A_t = \delta_t + \gamma\lambda\,(1 - \text{term}_t)(1 - \text{trunc}_t)\,\hat A_{t+1}.

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.

Interview

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 NN environments stepped in parallel (time is always axis 0). values[t] =V(st)= V(s_t). next_values[t] =V(st+1)= V(s_{t+1}) for the true next state, recorded before any reset. terminated[t] and truncated[t] are 0 or 1 and describe the transition at step tt. 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.

Hidden tests, hints, and AI help, from $1.99 a month.
Research

GAE is an average of n-step advantages, even in a finite episode

In an infinite episode the weights on A^(1),A^(2),…\hat A^{(1)}, \hat A^{(2)}, \dots are (1−λ)λn−1(1-\lambda)\lambda^{n-1}. In an episode that terminates mm steps after tt (so A^t(n)=A^t(m)\hat A^{(n)}_t = \hat A^{(m)}_t for every n≥mn \ge m), all the weight from n=mn = m onward piles onto the Monte Carlo estimate. Implement gae_weights(m, lam) returning the length-mm array of weights w1,…,wmw_1, \dots, w_m such that ∑n=1mwnA^t(n)\sum_{n=1}^m w_n\hat A^{(n)}_t equals the GAE advantage at step tt, and check your formula against gae by computing both for random episodes.

Hidden tests, hints, and AI help, from $1.99 a month.

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.

🔥 In PyTorchfor a machine with PyTorch

Read more

Watch next

🎬 L3 Policy Gradients and Advantage Estimation (Foundations of Deep RL Series) · Pieter AbbeelOne of the GAE authors explains n-step advantage estimates and generalized advantage estimation.
🎬 RL Course by David Silver - Lecture 4: Model-Free Prediction · Google DeepMindn-step returns, the lambda-return, and TD(lambda), the ideas GAE is built from.