Compute Generalized Advantage Estimation

PPO, the algorithm behind classic RLHF, estimates advantages with GAE, a smooth blend between one-step TD errors and full Monte Carlo returns.

Inputs for one rollout of length T: rewards (T,), values (T + 1,) where values[T] is the bootstrap value of the state after the last step, dones (T,) where dones[t] = True means the episode ended after step t.
delta_t = r_t + gamma * V_{t+1} * (1 - done_t) - V_t
A_t = delta_t + gamma * lam * (1 - done_t) * A_{t+1}, with A_T = 0

Write gae(rewards, values, dones, gamma, lam) returning (advantages, returns) where returns = advantages + values[:T]. Both as NumPy arrays.

Signaturedef gae(rewards, values, dones, gamma, lam)

Understand the idea

GAE estimates how much better an action was than expected. It starts from one-step TD errors, delta_t = r_t + gamma V_{t+1} - V_t, then blends them backwards with weight gamma x lam, so lam = 0 gives plain TD error and lam = 1 gives a full Monte Carlo estimate minus the baseline. Episode ends cut both the bootstrap value and the recursion. Worked example: rewards [1, 1], values [0.5, 0.5, 0.5], no dones, gamma 0.9, lam 0.95. delta_1 = 1 + 0.45 - 0.5 = 0.95, delta_0 = 0.95. A_1 = 0.95. A_0 = 0.95 + 0.9 x 0.95 x 0.95 = 1.762. Returns = A + V = [2.262, 1.45]. If dones[0] were True, delta_0 = 1 + 0 - 0.5 = 0.5 and A_0 = 0.5. Rule: delta_t = r_t + gamma V_{t+1} (1 - d_t) - V_t; A_t = delta_t + gamma lam (1 - d_t) A_{t+1}, A_T = 0; returns = A + V[:T]. PPO, including RLHF for LLMs, uses GAE.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks the hidden tests with Pro.

  • Sample 1: no episode endgae(_r, _v, [False] * 5, 0.99, 0.95)[0]
  • Sample 2: episode ends mid-rolloutgae(_r, _v, [False, True, False, False, False], 0.99, 0.95)[0]