n-step TD and TD(λ) with eligibility traces
Blend one-step TD and Monte Carlo: n-step returns, the λ-return and eligibility traces.
Animated explanation
The idea
TD(0) looks one step ahead; Monte Carlo looks all the way to the end. Neither is always best. n-step TD looks real rewards ahead and then bootstraps, trading bias against variance with a single integer.
TD(λ) goes further and averages all n-step returns, giving weight to the -step return. With it is TD(0); with it is Monte Carlo. The elegant way to compute it online is with eligibility traces: a short-term memory of which states were visited recently. Each TD error then updates all of them at once, so credit for a reward flows back quickly along the path that led to it.
Forward and backward views
The forward view defines the target (the λ-return), which needs future rewards. The backward view uses traces to apply equivalent updates incrementally, one step at a time; for offline updating the two are exactly equivalent (and "true online TD(λ)" makes them match online too). Intermediate λ (0.7–0.9) often learns fastest.
Traces for control
SARSA(λ) keeps traces over state–action pairs. For Q-learning, traces must be cut whenever a non-greedy action is taken (Watkins's Q(λ)), because the greedy target no longer describes what happened. In deep RL the same bias–variance dial appears as n-step returns and GAE, used by A2C and PPO.
The algorithm, step by step
- 1Initialise V(s) and traces e(s) = 0 at the start of each episode.
- 2At each step: compute δ = r + γV(s′) − V(s).
- 3Decay all traces e ← γλe, then e(s) ← e(s) + 1 (accumulating) for the current state.
- 4Update all states: V ← V + αδe. Move on to s′.
The maths
n-step return
λ-return
Trace update
TD(λ) update
Strengths and weaknesses
Strengths
- One knob spans TD(0) to Monte Carlo
- Faster credit assignment than one-step TD
- Online and incremental via traces
Weaknesses
- Extra memory and computation for traces
- Another hyperparameter (λ)
- Off-policy traces need care
Reach for it when…
Check your understanding
Lambdian Lab
n-step TD and TD(λ) on the random walk
The random walk is provided (γ = 1).
- n_step_td(episodes, n, alpha, seed): n-step TD prediction from V = 0.5; return V.
- td_lambda(episodes, lam, alpha, seed): backward-view TD(λ) with accumulating traces (reset each episode); return V.
- With lam = 0, td_lambda must equal TD(0) step for step.