Run TD(lambda) with accumulating and replacing eligibility traces
Why it matters Eligibility traces are the bridge between one-step TD and Monte Carlo, and the same lambda appears in GAE for PPO.
TD(lambda) spreads each TD error back over recently visited states, weighted by an eligibility trace that decays by gamma * lambda every step.
Write td_lambda(V, transitions, alpha, gamma, lam, trace). Work on a float copy of V. Keep a trace vector e of zeros. For each (s, r, s_next, done) in order:
1. delta = r - V[s] if done else r + gamma * V[s_next] - V[s] (use the values before this step's update).
2. e = gamma * lam * e, then e[s] += 1 if trace == "accumulate", or e[s] = 1 if trace == "replace".
3. V += alpha * delta * e.
4. If done, reset e to zeros (a new episode may follow in the same list).
Return V.
def td_lambda(V, transitions, alpha, gamma, lam, trace)Example
td_lambda([0, 0, 0], [(0, 0, 1, False), (1, 1, 2, True)], 0.5, 1.0, 0.5, "accumulate") gives array([0.25, 0.5, 0.]).
Understand the idea
When something good happens, the states you passed through recently deserve some credit too. An eligibility trace is a fading memory of where you have been: each step every trace shrinks by gamma * lambda, and the state you are in gets bumped up. The TD error is then shared by all states in proportion to their trace.
Example with alpha 0.5, gamma 1, lambda 0.5: first step from state 0 gives delta 0, nothing changes, e = [1, 0, 0]. Second step from state 1 earns reward 1 at the end, delta = 1. Traces decay to [0.5, 0, 0] and state 1 is bumped to 1. Values become [0.25, 0.5, 0].
Rule: e <- gamma * lambda * e; e(s) += 1 (accumulate) or e(s) = 1 (replace); V <- V + alpha * delta * e.
lambda = 0 is TD(0), lambda = 1 behaves like Monte Carlo. GAE in PPO uses the same lambda for advantages.