AI Wiki中文/EN

Advantage estimation: accumulate a sequence of TD errors

优势估计

Derive finite-fragment GAE, check lambda limits and prevent traces crossing episode resets.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

Can an action’s evaluation use information from several later steps?

A critic predicts current value 0.2, then reward 1 arrives and next-state value is 0.4. With discount 0.9, this transition exceeds the critic’s prediction by 1.16. If several later transitions also have positive errors, should they improve the earlier action’s evaluation? Generalized advantage estimation, or GAE, accumulates TD residuals with weights that decay over distance. GAE paper

Lambda controls how far along the trajectory the estimator looks; gamma discounts future rewards. Their product appears in a recurrence, but they have different meanings. GAE supplies an advantage estimate for an actor update, not a new environment reward function. We first derive it without an intermediate reset, then handle collection boundaries.

Finite GAE retains endpoint bootstrap while cutting traces before a reset episode.
Finite GAE retains endpoint bootstrap while cutting traces before a reset episode.

From multi-step returns to residual sums

Let V_t be the critic’s fixed value at collected state s_t. For internal nonterminal transitions, define a TD residual. Expanding k successive discounted residuals cancels the intermediate value terms:

δt=rt+γVt+1−Vt,∑l=0k−1γlδt+l=∑l=0k−1γlrt+l+γkVt+k−Vt.\delta_t=r_t+\gamma V_{t+1}-V_t,\qquad \sum_{l=0}^{k-1}\gamma^l\delta_{t+l} =\sum_{l=0}^{k-1}\gamma^l r_{t+l}+\gamma^k V_{t+k}-V_t.

The right side is a k-step bootstrap return minus the current baseline. Geometrically weighting different k-step estimates produces GAE. For an infinite continuation under convergence conditions with lambda below 1, exchanging the summations gives each residual this total weight:

(1−λ)∑k=l+1∞λk−1γl=(γλ)l,A^tGAE=∑l=0∞(γλ)lδt+l.(1-\lambda)\sum_{k=l+1}^{\infty}\lambda^{k-1}\gamma^l=(\gamma\lambda)^l,\qquad \widehat A_t^{\mathrm{GAE}}=\sum_{l=0}^{\infty}(\gamma\lambda)^l\delta_{t+l}.

At lambda=1, use a limit of the residual sum or the telescoping expansion. Substituting zero for 1−lambda in the infinite weighted expression does not make the advantage zero. A finite fragment retains only observed residuals, while its last residual may still bootstrap from the endpoint. Check the infinite derivation separately from a finite rollout buffer. Residual expansion Buffer computation

Actual records require two masks. Let d_t indicate true termination and u_t indicate external truncation followed by reset. The bootstrap mask b_t=1−d_t retains the next value. The continuation mask c_t is true only when neither termination nor truncation occurs:

δt=rt+γbtV(st+1)−V(st),A^t=δt+γλctA^t+1,A^T=0.\delta_t=r_t+\gamma b_tV(s_{t+1})-V(s_t),\qquad \widehat A_t=\delta_t+\gamma\lambda c_t\widehat A_{t+1},\qquad \widehat A_T=0.

The last equation means no further observed residuals are available beyond the fragment, not that V(s_T) must be zero. A batch boundary without a task reset also stops this batch’s recurrence while retaining the endpoint value in the last residual. If true termination coincides with a time limit, termination wins: both bootstrap and continuation are removed.

For a nonterminal fragment of length T, setting lambda=1 cancels all intermediate values:

A^tλ=1=∑k=tT−1γk−trk+γT−tV(sT)−V(st).\widehat A_t^{\lambda=1}=\sum_{k=t}^{T-1}\gamma^{k-t}r_k+\gamma^{T-t}V(s_T)-V(s_t).

Finite-fragment lambda=1 can therefore retain endpoint-value error. For a complete terminal episode, endpoint value is zero and the estimate becomes Monte Carlo return minus a state baseline. An inaccurate state baseline shifts conditional advantage values without necessarily biasing the score-weighted expected gradient. Action-dependent next-state bootstrap error can introduce bias, as discussed in actor–critic.

Check the indices using rewards [1,2,3], state and endpoint values [0.2,0.4,0.6,0.8], gamma=0.9 and lambda=0.8:

δ=(1.16,2.14,3.12),A^=(4.318208,4.3864,3.12),A^0λ=1=5.6132.\delta=(1.16,2.14,3.12),\qquad \widehat A=(4.318208,4.3864,3.12),\qquad \widehat A_0^{\lambda=1}=5.6132.

For example, A1=2.14+0.72 times 3.12=4.3864, then recurse backward. The last reward has exponent T−t−1, while the bootstrap exponent is T−t. This short example detects an accidental two extra discount factors when transcribing a long expression.

Adding the old state value back to advantage produces a lambda-return target for the critic. An actor using the estimate must retain the time weights appropriate to its objective:

V^ttarget=A^t+V(st),g^=∑tγt∇log⁡πθ(at∣st)A^t.\widehat V_t^{\mathrm{target}}=\widehat A_t+V(s_t),\qquad \widehat g=\sum_t\gamma^t\nabla\log\pi_\theta(a_t\mid s_t)\widehat A_t.

Targets and advantages stay fixed for this optimization round; gradients do not pass through the old critic that generated them. The GAE paper also treats gamma as a bias/variance parameter for an undiscounted objective. Its g_gamma convention must not be confused with the outer gamma^t of our start-discounted objective. Objective convention

One backward loop with two boundary switches

The standard-library program receives each transition’s current and actual successor values explicitly rather than guessing the successor from the next row of a concatenated buffer. It checks array lengths, finite values and Boolean boundary flags, then computes advantages and value targets backward. Endpoint values may come from a critic; this program computes the estimator without training an actor or critic.

"""Finite GAE with separate bootstrap and trace-continuation masks."""
import json
import math


def gae(rewards, values, next_values, terminated, truncated, gamma=0.9, lam=0.8):
    n = len(rewards)
    if not all(len(x) == n for x in (values, next_values, terminated, truncated)):
        raise ValueError('transition arrays must have equal lengths')
    if not 0 <= gamma <= 1 or not 0 <= lam <= 1:
        raise ValueError('gamma and lambda must lie in [0,1]')
    if not all(math.isfinite(x) for seq in (rewards, values, next_values) for x in seq):
        raise ValueError('finite rewards and values required')
    if not all(type(x) is bool for seq in (terminated, truncated) for x in seq):
        raise ValueError('termination flags must be booleans')
    deltas = [r+(0. if end else gamma*nv)-v
              for r, v, nv, end in zip(rewards, values, next_values, terminated)]
    advantages, carry = [0.]*n, 0.
    for t in reversed(range(n)):
        continuation = not (terminated[t] or truncated[t])
        carry = deltas[t] + (gamma*lam*carry if continuation else 0.)
        advantages[t] = carry
    return {'deltas': deltas, 'advantages': advantages,
            'value_targets': [a+v for a, v in zip(advantages, values)]}


def main():
    args = ([1., 2., 3.], [0.2, 0.4, 0.6], [0.4, 0.6, 0.8], [False]*3, [False, False, True])
    print(json.dumps({'fragment': gae(*args), 'lambda_one': gae(*args, lam=1.),
                     'terminal': gae([2.], [0.4], [10.], [True], [False]),
                     'time_limit': gae([2.], [0.4], [10.], [False], [True]),
                     'reset_boundary': gae([1., 100.], [0., 0.], [2., 0.],
                                           [False, True], [True, False])}, indent=2))


if __name__ == '__main__':
    main()
Inspect the complete recorded output
{
  "fragment": {
    "deltas": [
      1.1600000000000001,
      2.14,
      3.12
    ],
    "advantages": [
      4.318208,
      4.3864,
      3.12
    ],
    "value_targets": [
      4.5182080000000004,
      4.7864,
      3.72
    ]
  },
  "lambda_one": {
    "deltas": [
      1.1600000000000001,
      2.14,
      3.12
    ],
    "advantages": [
      5.613200000000001,
      4.948,
      3.12
    ],
    "value_targets": [
      5.813200000000001,
      5.348000000000001,
      3.72
    ]
  },
  "terminal": {
    "deltas": [
      1.6
    ],
    "advantages": [
      1.6
    ],
    "value_targets": [
      2.0
    ]
  },
  "time_limit": {
    "deltas": [
      10.6
    ],
    "advantages": [
      10.6
    ],
    "value_targets": [
      11.0
    ]
  },
  "reset_boundary": {
    "deltas": [
      2.8,
      100.0
    ],
    "advantages": [
      2.8,
      100.0
    ],
    "value_targets": [
      2.8,
      100.0
    ]
  }
}

The terminal example gives advantage 1.6; the time-limit example gives 10.6. In the concatenated example, a truncated transition has reward 1 and next value 2, followed by a different episode with reward 100. The first advantage remains 2.8: the 100 must not flow backward across the reset. Reverse recurrence takes O(T) time, O(T) output space and O(1) extra accumulator space. Summing all later residuals separately at every position takes O(T squared) work.

Lambda does not automatically remove bias

Smaller lambda relies more on short bootstrap estimates, while larger lambda uses longer stretches of realized random rewards. The usual bias/variance trend is useful but is not a strict monotonic theorem for every environment, critic and sample. Exact value is a common sufficient condition; an inexact value may sometimes add only a canceling state-baseline shift.

The paper’s gamma-just condition concerns the score-weighted expectation, not unbiased advantage values for every state-action pair. Advantage normalization is a separate operation. Dividing by batch standard deviation changes scale, and subtracting a same-batch mean introduces data dependence; the fixed-baseline proof does not automatically apply. Zero variance needs a guard. Our program omits normalization to preserve hand-checkable values. Original definition Implementation boundaries

Put the boundary into the equation

  1. What are the example’s advantages at lambda=0? Answer: [1.16,2.14,3.12], the individual TD residuals. Gamma has not become zero.
  2. Why is A0=5.6132 at lambda=1? Answer: It is 1+0.9 times 2+0.9 squared times 3+0.9 cubed times 0.8−0.2. The final two terms are endpoint bootstrap and current baseline.
  3. Which mask closes when a reset episode immediately follows a truncation? Answer: Close residual continuation c but retain bootstrap b if the original task did not truly terminate. The next value must correspond to the pre-reset observation.
  4. How can lambda=0.2 and 0.9 be compared without relying on one update? Answer: Fix the environment, sampling policy and critic; repeatedly sample to estimate gradient mean and variance. Use a small exactly solvable environment to measure bias separately. Report fragment length and boundary treatment before discussing training returns.

The selected version and the actual implementation

GAE was first posted 2015-06-08 and identifies ICLR 2016. The actual reading here uses arXiv v6 dated 2018-10-20, PDF 1–5, covering residual expansion, gamma-just and estimator conditions. Later result tables and appendices were not audited. GAE v6

Spinning Up commit 038665d, PPO documentation 1–139 and specified PyTorch code ranges were read for buffer and optimization boundaries. Its backward discounted-sum idea provides a comparison, while this program explicitly separates termination, truncation and reset. Upstream code was neither executed nor copied, and no control benchmark was reproduced. Implementation reference

Make a prediction, then check

At an external time limit with a valuable continuing next state, how should GAE handle the boundary?

Choose one answer

Learning objectives

  • Derive weighted TD-residual sums and their reverse recurrence from multi-step bootstrap returns.
  • Distinguish bootstrap and trace-continuation masks, retaining the endpoint value at lambda=1 on a finite fragment.

Prerequisites & connections

Explore related knowledge →

References

  1. High-Dimensional Continuous Control Using Generalized Advantage Estimation — arXiv v6
    John Schulman; Philipp Moritz; Sergey Levine; Michael I. Jordan; Pieter Abbeel · 2018
  2. Spinning Up — scoped PPO documentation and PyTorch buffer/update
    OpenAI; Joshua Achiam and contributors · 2020

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-23 · Single AI author. Scoped reading: First2015-06-08, ICLR2016, selected v6 dated2018-10-20. Read PDF1–5, viewed5; gamma-just, TD and GAE, keeping its undiscounted-objective surrogate distinct from the ordinary discounted gradient. Later result tables and appendices unread. Read docs1–139; PyTorch ppo.py1–86,224–289,302–328. GAE, fixed old logp and early stopping; sample KL may be negative, stopping does not roll back, normalization lacks a zero-variance guard. MIT reference, no upstream execution or copying. 6 paired equations and four explained exercises. Independent finite residual sums and lambda1 telescoping match reverse GAE. Bootstrap and trace-continuation masks separately test termination, truncation, reset and simultaneous flags; endpoint value retained. Gamma-just, conditional advantage bias and start-discount objective conventions distinguished.

  • Independent finite residual sums and lambda1 telescoping match reverse GAE. Bootstrap and trace-continuation masks separately test termination, truncation, reset and simultaneous flags; endpoint value retained. Gamma-just, conditional advantage bias and start-discount objective conventions distinguished.
  • Four computed SVG variants per topic;16 numeric/geometry tests and36 current responsive cases passed. All twelve selected current captures directly viewed. Three groups retain initial captures; three use their actually viewed revised captures. Actual assets and manuscripts are SHA bound. Full article acceptance recorded separately.

Source locations checked:

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.