GAE: High-Dimensional Continuous Control Using Generalized Advantage Estimation
Score each action by a decaying sum of a learned value function's one-step prediction errors, and policy gradients get far less noisy for a small, tunable bias.
A policy gradient makes actions that turned out better than expected more likely. Generalized advantage estimation measures "better than expected" as a weighted sum of the value function's errors after each action, with weights that shrink by a factor per step. The parameter moves the estimate between a one-step version, low in noise but biased by every error in the value function, and the full observed return, unbiased but noisy.
Explaining the paperHigh-Dimensional Continuous Control Using Generalized Advantage EstimationA 2015 Berkeley paper that trained 3D simulated robots to run and to stand up from raw joint states. Its estimator became the advantage computation in PPO and in most on-policy RL code written since.
The paper has two parts. The first is an estimator: given one sampled trajectory and an imperfect value function, how to score each action so that a policy gradient built from those scores has low variance and little bias. The second is an algorithm: TRPO for the policy, a similar trust region for the value network, and the estimator between them, which together learned bipedal and quadrupedal running gaits and a getting-up motion in the MuJoCo simulator. The networks map the robot's 33 (or 29) state numbers straight to 10 (or 8) joint torques, with no hand-designed gait structure.
The page follows the paper's order. It starts with the policy gradient and why its raw form is noisy, defines the advantage function and the discount, builds the estimator from one-step prediction errors, and then spends two sections on its bias: where it comes from, and how the two parameters and trade it against variance. The value-function fit, the full algorithm, the experiments and the released code follow.
Why policy gradients are noisy
A stochastic policy is a network that outputs a probability distribution over actions; for the robots, as in TRPO, the network outputs the mean of a Gaussian over the 10 joint torques. A trajectory is the sequence produced by sampling an action, stepping the simulator, and repeating, with a reward after every step. The goal is to maximize the expected total reward. Policy gradient methods estimate the gradient of that expectation with respect to from sampled trajectories, and every estimator the paper considers has the form
is the direction in parameter space that makes the action actually taken at step more probable. is a scalar that says how much, and with what sign, to move along it. The simplest choice sets to the trajectory's total reward (REINFORCE, Williams 1992): every action in a good episode becomes more likely and every action in a bad episode less likely. The estimate is unbiased and, on long episodes, very noisy.
Take one of the paper's biped episodes: up to 2,000 steps of 0.01 seconds each. If the robot stumbles at step 1,500, the total reward drops, and that drop multiplies the gradient term of the action at step 10 as much as the action at step 1,499. Over many episodes, the actions that had nothing to do with the stumble average out, but only slowly, because each action's effect is mixed with the effects of thousands of other random actions. The paper puts it as the variance of the estimator scaling unfavorably with the time horizon. The usual fixes are to drop rewards that came before (they cannot depend on it) and to subtract a baseline. The paper lists six choices of :
- the total reward of the trajectory, ;
- the reward following the action, ;
- the same minus a baseline ;
- the state-action value ;
- the advantage ;
- the TD residual .
The last three use value functions, defined in the next section. The paper argues for the advantage: a gradient step should raise the probability of better-than-average actions and lower that of worse-than-average ones, and points the term toward a more probable exactly when the action beat the policy's average. The paper says this choice gives "almost the lowest possible variance" and refers to Greensmith et al. (2004) for the formal analysis. The advantage is unknown and has to be estimated from the same samples, and the rest of the paper is about how.
The advantage and the discount
The value function is the expected sum of future rewards from state if the policy chooses every action. The state-action value is the same expectation with the first action fixed to . The advantage is their difference:
The subscripts on list what is averaged over: future states drawn from the simulator and future actions drawn from the policy. averages over as well; does not. A positive means that taking and then following the policy is better, in expectation, than following the policy from directly.
The problem the paper solves is undiscounted: maximize the plain sum of rewards. It then introduces a discount anyway, as a knob on the estimator rather than part of the goal. Rewards steps after an action are multiplied by , which shrinks the contribution of delayed, mostly unrelated rewards to each action's score. The discounted value functions , , (equations 4 and 5) are (2) and (3) with in place of , and the gradient they define is
is already a biased version of the true gradient whenever , because it ignores the tail of each action's effect. With the weights , rewards more than about steps out barely count: 100 steps at , 200 steps at . At the robots' 0.01-second timestep that is 1 or 2 seconds of simulated time, and any consequence of an action that arrives later is mostly invisible to the gradient.
From here on, the target is , and the question is which estimates of leave it unbiased. The paper calls an estimator , which may depend on the whole trajectory, γ-just if substituting it for in (6) gives the same expectation:
Proposition 1 gives a sufficient condition. If , where may depend on anything from step on but averages to , and depends only on states and actions before , then is γ-just. The proof rests on one identity. For any fixed state,
so a baseline that does not change with multiplies a quantity that is zero on average and adds nothing to the expected gradient. It can still change the variance a great deal. Four examples are γ-just: the discounted return , , itself, and the one-step residual built from the exact value function:
One-step errors and k-step estimates
Let be an approximate value function, in practice a neural network. Its TD residual at step is
It compares two predictions of the same discounted return: , made before the step, and , made after seeing the reward and the next state. If the step went better than the network expected, . With the exact , the expected residual is exactly the advantage, because averaging over the next state gives :
With any other , the residual is biased, and the bias is the error of at (scaled by ) that does not cancel. The paper's next step is to sum consecutive residuals. The intermediate values cancel in pairs, the of one residual against the of the next once it is multiplied by , leaving a -step return with the value function at both ends:
A three-step example with : rewards 0, 0, 1, value predictions , , , and a terminal with value 0. The residuals and the three estimates are
The first is the one-step estimate. The second equals , and the third equals , the observed discounted return minus the baseline.
In (14) the term is a baseline: it does not depend on , so it adds no bias. All of the bias sits in the bootstrap term , and its weight shrinks as grows. Variance moves the other way, because each extra step adds one more random reward to the sum. As the bootstrap vanishes and
the empirical return minus a value-function baseline, choice 3 in the list above. A3C, published the next year, picks one per state (up to 5 steps on Atari), where GAE averages over all of them.
How GAE works
The generalized advantage estimator takes an exponentially weighted average of the -step estimators, with weight on . The weights sum to 1 for any . Written in terms of the residuals, residual appears in every estimator with , multiplied by , so its total weight is times the sum of those estimators' weights, a geometric tail that sums to :
Figure 1 lays the regrouping out as a grid. Each row is one -step estimator and the residuals it contains, shaded by the row's weight; the bars underneath are the column sums times . Pick a column and compare the readout with .
column 2: row weights sum to 0.490 = λ2 = 0.490 · times γ2 → weight on δt+2 = 0.480
At , the default in the figure, column 2 collects 0.7² = 0.49 of the row weight, and the weight on is . The two ends of the slider are the estimators from the previous section:
is γ-just whatever the accuracy of , since appears only as a baseline, and it has high variance from the long sum of rewards. is γ-just only when and otherwise biased, and it typically has much lower variance. Values in between trade one for the other. The construction is the one behind TD(λ), with a different target: TD(λ) averages -step returns to train a value function, while (16) averages -step advantages. Since each -step advantage is the -step return minus , GAE is the λ-return minus .
Equation (16) also gives a cheap way to compute it. Splitting off the first term gives the recursion
so one backward pass over a trajectory produces every advantage in time. Figure 2 runs that computation on an 8-step segment that ends without terminating, so the last residual uses the value of the state after the cut (the hollow dot). A reward of +1 arrives at step 5, which the value network underpredicted.
Â0 = 0.384 · λ=0 (one step): 0.044 · λ=1 (Monte Carlo): 0.482
weight halves every 11.3 steps
At step 0, gives : the first step looks barely better than expected, because the value network's prediction rose only from 0.55 to 0.60. gives 0.482, which includes the full surprise at step 5. The figure starts at , which gives 0.384; at the paper's robot setting , the product halves the weight every 15 steps.
Where the bias comes from
The previous section said that adds bias only when is wrong. Expanding (16) shows which values of enter the estimate. Collecting the terms of each residual,
which follows because appears as in residual (weight ) and as in residual (weight ). The first sum is a return discounted by instead of . is a baseline. The last sum puts the value network's predictions at later states into the score, and those states depend on , so an error in there becomes an error in the gradient. At the last sum vanishes and the first becomes the ordinary discounted return. When , the later-state values supply exactly the expected return that the steeper discount cut away.
Section 4 of the paper reads the same algebra as reward shaping. Ng, Harada and Russell (1999) showed that adding to every reward, for any function of the state, leaves the optimal policy of a discounted problem unchanged:
Summed along a trajectory with discount , the added terms cancel in pairs and leave only , so the shaped problem has , and the same advantage (equations 22 to 24). Choose and the shaped reward is the TD residual, . GAE is then the sum of shaped rewards under the steeper discount :
To say how much a steeper discount loses, the paper defines the response function: how much the expected reward steps later changes when the action is fixed to , compared with the policy's average,
The advantage is the discounted sum of the responses,
so the response function spreads the advantage across timesteps. A delayed consequence is a response at a large lag . Any discount weights the response by its envelope, and the part at lags well beyond is lost. Shaping with the exact moves the entire response to lag 0: once is known, the expected future shaped reward is zero, so only carries information about , and no discount can lose anything. A good but imperfect moves part of it. In the paper's words, GAE reshapes the rewards with to shrink the temporal extent of the response, then uses the steeper discount to cut off the noise from long delays.
Consider a small example. At step 0 a policy chooses between two actions with probability 0.5 each. The good action pays +1 exactly 20 steps later and the other pays nothing; no other reward depends on the choice. The value network is a blend , where is the exact value function and assigns no value to the pending reward. Working through the residuals, the difference between the two actions shows up as in and as in , and zero at every other lag. GAE weights the second by , so the credit the estimator gives the good action is
against a true, undiscounted value of 1. The factor is the bias from (0.818 at ). The bracket is the bias from , and it equals 1 when or . Figure 3 draws the two responses; move κ to 0 and the teal mass jumps to lag 0, where no discount touches it.
credited to the good action: 0.590 = 0.409 at lag 0 + 0.50 × (γλ)20 · γ-ceiling γ20 = 0.818 · truth = 1
At the default , : 0.409 lands at lag 0 and survives intact, and 0.5 lands at lag 20, of which survives, for a total of 0.590. With (no useful value function) the credit is , and at it is zero: the one-step estimate uses only , which contains none of a reward that the value function did not predict.
Choosing γ and λ
Both parameters lower variance by shortening the sum, and both can add bias, but the paper separates their roles. sets the scale of the value function the network has to learn, , which does not depend on . biases the gradient regardless of how accurate the value function is. biases it only when the value function is inaccurate. The paper reports that the best is much lower than the best , likely because adds far less bias for a reasonably accurate value function.
Figure 4, a toy of this page's rather than the paper's, adds noise to the example above and measures the policy gradient itself. The episode runs 200 steps and every reward carries independent Gaussian noise with standard deviation 0.3. With a two-action policy at , write for the good action and for the other; the gradient with respect to the policy's logit from one episode is , and its true undiscounted value is 0.25. The curves show, as fractions of 0.25, the bias, the noise of an average over episodes, and the root-mean-square error that combines them. All three are exact formulas, checked against a 4,000-episode simulation.
at λ = 0.96: bias 0.410 · noise 0.274 · total 0.493
lowest total at λ = 0.98 (0.474) · signal kept = γ20·[1 − κ(1 − λ20)] = 0.590
At and , has a total error of 0.597, almost all bias; has 0.626, mostly noise (its bias, 0.182, is the part alone); the minimum is 0.474 at . Three settings show the paper's claims. Set and the best is 0, because an exact value function makes the one-step estimate unbiased. Set and becomes the worst choice (1.202) while the minimum moves to 0.413 at , since nothing then limits the 200 noisy rewards in the sum. Lower to 0.9 and every curve is dominated by the factor, a bias no value function can remove.
The noise in Figure 4 has one source, the reward noise, and it grows with the effective length of the sum: the standard deviation of at is 2.18 times its value at . In the robot tasks much of the noise comes from the randomness of later actions and their effect on the dynamics, and it grows with the length of the sum in the same way.
Fitting the value function
Every estimate above uses a value network . The simplest way to fit it is regression onto the discounted returns observed in the batch:
where runs over all timesteps of the batch (50,000 for the biped). The targets are Monte Carlo returns, sometimes called TD(1) targets. The paper also tried TD(λ) targets and saw no difference.
The returns from one batch are noisy, and a large network fitted to convergence on them would chase that noise. The paper constrains each fit with a trust region instead. It first measures how well the old network fits the new targets,
and then solves
In words: the mean squared change in predictions over the batch may be at most , so the root-mean-square change is capped at . If is read as the mean of a Gaussian with variance , the left side is the average KL divergence between the old and new Gaussians, since the KL divergence between two Gaussians with equal variance is , the same form as the KL constraint on the policy step.
To solve it, the paper linearizes the objective and approximates the constraint with the Gauss-Newton matrix , where . The conjugate gradient method, using only products , approximately solves the resulting quadratic program (equation 30): it finds the direction , with the gradient of the objective, and rescales the step to the boundary of the constraint. is, up to a factor of , the Fisher information matrix of that Gaussian, so this is a natural-gradient step for the value network, the same procedure TRPO uses for the policy.
Figure 5 runs one such step on a one-dimensional problem small enough to solve exactly: 30 noisy return targets, a value function that is linear in 8 parameters, and an old fit that is close to the truth but not equal to it. Watch the two error curves at the bottom as ε grows.
step = 84% of the way to the batch least-squares fit · RMS change in V = 0.285 (cap σ√(2ε) = 0.285, σ = 0.637)
error on batch 0.542 · vs true V 0.229 · lowest vs true V at ε ≈ 0.025
At the fit does not move. As grows, the step moves the parameters along the natural-gradient direction toward the batch's least-squares fit; for a linear model with squared error, that straight line is the exact solution path of (29). The error on the batch falls all the way. The error against the true value function falls, bottoms out, and rises again once the step starts fitting this batch's noise, the overfitting to the most recent batch that the paper names as the reason for the trust region. The paper does not report the it used.
The full algorithm
The policy update is TRPO. Each iteration it approximately solves
where is the KL divergence between the old and new action distributions, averaged over the batch's states, and is the GAE estimate at timestep of the batch. Linearizing the objective and taking a quadratic approximation of the constraint gives a step along , where is the average Fisher information matrix of the policy and the policy gradient estimate: the natural policy gradient direction, with TRPO's own rule for the step length.
One iteration of the algorithm simulates the current policy for timesteps, computes at every step with the current value network , computes , takes the TRPO step to , and then takes the value step (30) to . In code, with the shapes of a biped batch:
for i in range(n_iters):
paths = simulate(policy_theta, n_steps=50_000) # biped batch: 50,000 steps
for p in paths: # obs (T, 33), act (T, 10)
p.adv, p.vtarg = gae(p.rew, V_phi(p.obs), v_last(p))
# Policy step, eq. (31). adv is a constant: no gradient reaches phi here.
theta = trpo_step(theta, paths) # grad flows via log pi only
# Value step, eq. (30), AFTER the policy step, on the same batch.
phi = vf_trust_region_step(phi, paths) # regress V_phi on vtargThe advantages are computed once from the network outputs and then treated as constants. The policy loss differentiates through only, and the value network's parameters receive gradient only from the regression loss. If the value network were updated first, on the same batch, it would partly absorb that batch's returns, and the residuals that score the policy would shrink toward zero. In the extreme case of a value network that fits every return exactly, every is zero and so is the policy gradient.
The per-trajectory advantage and value-target computation, written out:
import numpy as np
def gae(rewards, values, v_last, gamma=0.99, lam=0.96):
"""One trajectory of T steps. values[t] = V(s_t) from the value net
BEFORE this iteration's update; v_last = V(s_T), or 0.0 if s_T is
terminal. Returns advantages and value targets, both of shape (T,)."""
T = len(rewards)
v_next = np.append(values[1:], v_last)
deltas = rewards + gamma * v_next - values # TD residuals
adv = np.zeros(T)
run = 0.0
for t in reversed(range(T)): # A_t = d_t + g*l*A_{t+1}
run = deltas[t] + gamma * lam * run
adv[t] = run
ret = np.zeros(T) # targets for eq. (28)
run = 0.0
for t in reversed(range(T)):
run = rewards[t] + gamma * run
ret[t] = run
return adv, retWhat the experiments show
The experiments ask two questions: how and affect learning when the optimizer is held fixed, and whether GAE with the two trust regions can train large neural network policies on hard control problems. All results are reported as cost, the negative reward, so lower is better. "No VF" in the plots is a baseline that depends only on the timestep: the average return at that timestep across the batch.
Cart-pole. A linear policy and a value network with one 20-unit hidden layer, 20 trajectories per batch of at most 1,000 steps, averaged over 21 random seeds. At , the paper compares = 0, 0.36, 0.68, 0.84, 0.92, 0.96, 0.98, 0.99 and 1, plus no value function; the fastest improvement comes from in [0.92, 0.98]. A heat map of cost after 20 iterations over a grid of and puts the best region at and .
3D robots. The policy and value networks share an architecture: three tanh hidden layers of 100, 50 and 25 units with a linear output layer. The simulated humanoid has 33 state dimensions and 10 actuated joints, the quadruped 29 and 8. Episodes end after 2,000 steps of 0.01 s, and the walking episodes end earlier if the center of mass falls below 0.8 m (biped) or 0.2 m (quadruped). The rewards for biped walking, quadruped walking and biped getting up are
with the forward velocity, the joint torques, the impact forces and the head height. The constant offset pays the walkers for staying up; without it, the quadratic penalties could make ending the episode early the best policy.
Biped locomotion. 50,000 timesteps per batch, nine seeds, about 2 hours per run on a 16-core machine. The plotted conditions vary from 0.96 to 1 at , and from 0.92 to 1 at , plus without a value function. The best curves come from and . After 1,000 iterations the gait is fast, smooth and stable. The paper converts this to robot time: seconds is 5.8 days of simulated experience, short enough that the authors call training on a real robot plausible if it could be reset safely.
Quadruped and standing up. 200,000 timesteps per batch, five seeds, about 4 hours per run on a 32-core machine, and a smaller comparison: , , and no value function (the Provenance panel below covers a mismatch between the text and the plots here). For the quadruped, is best. For standing up, a value function always helps, and and end up about the same. The standing-up curves run 500 iterations; at 200,000 steps each that is 11.6 days of simulated time. With the 5.8 days of the walking run, that roughly matches the abstract's "1-2 weeks" for the biped tasks.
The discussion summarizes the sweep as: an intermediate in [0.9, 0.99] usually works best. It also reports that , the one-step estimate, was too biased to perform well on these tasks, and contrasts this with DDPG and related concurrent work, which differentiate a learned Q-function with respect to the action and made one-step methods work on lower-dimensional problems with careful tuning. The paper compares no other algorithms; it relies on the TRPO paper for those comparisons.
The paper leaves several questions open. Its analysis is, in its own words, "intuitive but informal": there is no bound relating the value function's error to the gradient's error, so the choice of regression loss for is not matched to what the policy gradient needs. and are fixed by hand. And the policy and value networks are separate; sharing features between them is listed as future work.
Implementation notes
John Schulman's modular_rl repository has the reference implementation, released after the paper. Its compute_advantage function is equation (16) with three practical additions. A trajectory that ended in a terminal state bootstraps the last residual with 0; one cut off by the time limit bootstraps it with the last predicted value of the path, an approximation to . The discounted sum is computed with a backward linear filter (scipy.signal.lfilter), which evaluates the backward recursion from the GAE section in vectorized form. And the advantages are standardized to mean 0 and standard deviation 1 across the whole batch before the policy step.
The released value fit differs from Section 5. It runs 25 iterations of L-BFGS with a small L2 penalty, and instead of a trust region it regresses onto targets mixed 10% new return and 90% old prediction, which also limits how far one batch can move the network. The value network gets the normalized timestep t / timestep_limit as an extra input, which lets it represent the shrinking return near a time limit. The command-line defaults are and .
PPO (2017) kept GAE and replaced the TRPO step with a clipped objective. Its MuJoCo runs use and on segments of 2,048 steps, with the sum in (16) truncated at the segment end and bootstrapped there. Its value target is , which by the identity in the GAE section is the λ-return, the TD(λ) target the paper's footnote describes.
Questions you might still have
Is GAE the same thing as TD(λ)?
It uses the same construction for a different quantity. TD(λ) averages n-step returns with weights (1 − λ)λ^(n−1) to get a target for the value function. GAE averages k-step advantage estimates with the same weights. Each k-step advantage is the k-step return minus V(s_t), so GAE(γ, λ) is exactly the λ-return minus V(s_t). PPO uses that identity in reverse: its value target is the GAE advantage plus the old value prediction.
Why not learn a Q-function and use Q(s, a) − V(s) as the advantage?
Appendix A.2 gives two reasons. A state-value function has a smaller input (no action), so it is easier to learn, and GAE can move smoothly from the high-bias one-step estimate (λ = 0) to the low-bias Monte Carlo one (λ = 1). A learned Q-function gives only a high-bias estimate, and the authors found the one-step estimate too biased on their tasks. DDPG, published the same year, made the Q-function approach work on lower-dimensional problems.
Why does the policy update use the old value function?
Because the value step regresses V toward returns from the same batch. If V were fitted first and fitted perfectly, every residual r + γV(s') − V(s) on that batch would be zero, and so would the advantages and the policy gradient. Fitting V afterwards keeps the batch out of the baseline that scores it. The paper calls the opposite order a source of additional bias.
Which γ and λ should I use?
The paper's best results sit at γ between 0.96 and 0.995 and λ between 0.92 and 0.99, with λ well below γ, and its discussion recommends λ in [0.9, 0.99]. PPO later used γ = 0.99 and λ = 0.95 on MuJoCo. A useful check is the effective horizon 1/(1 − γλ): at 0.99 and 0.95 it is about 17 steps, so residuals more than a few dozen steps after an action contribute almost nothing.
Does GAE work with data from an older policy, such as a replay buffer?
Not without corrections. The analysis assumes the trajectory was sampled from the policy being updated: the residuals after step t reflect what the current policy would do next. With off-policy data the sum mixes in another policy's behavior. PPO stays close to this assumption by reusing each batch for only a few epochs with a clipped objective that limits how far the policy moves; fully off-policy methods use importance-weighted corrections instead.
How are episodes that hit the time limit handled?
The sum in GAE is infinite, and a trajectory cut off by a time limit did not end, so the last residual needs a value for the state after the cut. The authors' released code bootstraps with the last predicted value of the path; a terminal state gets 0. Treating a time-limit cut as a true termination would tell the value function the episode ends there, which biases V near the limit.
Does it matter that the code standardizes the advantages?
Rescaling every advantage by the same positive factor does not change a TRPO step: the natural-gradient direction scales by that factor and the KL-constrained step length divides it back out. Subtracting the batch mean acts like an extra constant baseline, which mainly changes the variance of the gradient rather than its expected direction. With a fixed learning rate, as in plain policy gradient, the scale matters and standardization sets it.
Footnotes & further reading
- The paper: Schulman, Moritz, Levine, Jordan & Abbeel, High-Dimensional Continuous Control Using Generalized Advantage Estimation (ICLR 2016; arXiv v6, October 2018). Videos of the learned gaits are linked from the paper.
- Reference code: joschu/modular_rl,
modular_rl/core.py(compute_advantage,NnRegression,NnVf) andmodular_rl/agentzoo.py. - The policy optimizer: Schulman et al., Trust Region Policy Optimization (ICML 2015), covered in the TRPO explainer. Its successor, Schulman et al., Proximal Policy Optimization Algorithms (2017), uses GAE; see the PPO explainer.
- Reward shaping: Ng, Harada & Russell, Policy Invariance Under Reward Transformations: Theory and Application to Reward Shaping (ICML 1999).
- TD(λ) and the λ-return: Sutton & Barto, Reinforcement Learning: An Introduction, chapter 12 of the second edition. The policy-gradient baseline argument goes back to Williams, Simple statistical gradient-following algorithms for connectionist reinforcement learning (1992); its variance is analyzed in Greensmith, Bartlett & Baxter, Variance Reduction Techniques for Gradient Estimates in Reinforcement Learning (JMLR 2004).
- The one-step, Q-function route the paper contrasts itself with: Lillicrap et al., Continuous control with deep reinforcement learning (2015), in the DDPG explainer. The single-k bootstrapped advantage is in the A3C explainer.
How could this explainer be improved? Found an error, or something unclear? I read every message.