Generalized Advantage Estimation: Blending TD Errors

Reinforcement LearningMedium+15 XP+15

Generalized Advantage Estimation: Blending TD Errors

There are two ways to estimate an advantage, and both are flawed. The one-step version uses a single real reward and then trusts the critic — low noise, but it inherits every bias in the critic's estimate. The full-return version uses nothing but real rewards — unbiased, but enormously noisy over a long episode.

GAE blends across all of them at once with a single knob, lambda.

Start with the one-step TD error at every step:

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

Then GAE is an exponentially-weighted sum of the errors from there to the end — which collapses, like discounted returns, into one backward pass:

At=δt+γλAt+1A_t = \delta_t + \gamma \lambda A_{t+1}At​=δt​+γλAt+1​

Task: write gae(rewards, values, gamma, lam) returning one advantage per step, each rounded to 4 decimal places.

  • values is one entry longer than rewards: it holds the value of every visited state plus the bootstrap value of the state after the last step. So values[t + 1] is always safe to read.
  • Walk backwards from the final step, carrying the running total. It starts at 0.
  • lam = 0 leaves you with exactly the one-step advantages, δ_t. lam = 1 gives the full discounted-return advantage. Anything between trades bias against variance.

The two test cases at the extremes are the ones to study: at lam = 0 each step depends only on its own reward and the critic, and at lam = 1 information from the end of the episode propagates all the way back to the first step.

Examples

rewards = [1.0, 1.0]
values = [0.0, 0.0, 0.0]
gamma = 0.99
lam = 0.95
returns [1.9405, 1.0]
rewards = [0.0, 2.0]
values = [1.0, 1.0, 1.0]
gamma = 0.9
lam = 0.0
returns [-0.1, 1.9]

Hints

Solve it to unlock the solution

Once your code passes every test, a reference solution shows up here so you can compare it with yours.

solution.py
CtrlEnterto run