n-Step Returns & Eligibility Traces
Interpolating between TD and Monte Carlo with n-step and λ-returns.
TD(0) trusts its own next guess after a single step; Monte Carlo trusts nothing until the episode is over. Most problems are best served somewhere in between. This lesson builds the two dials that span the gap: n-step returns, which wait n steps before bootstrapping, and the λ-return, which averages every n at once. Then it shows the trick that makes λ practical: an eligibility trace that sends each TD error back to the states that earned it, online, at the cost of one extra number per state.
What you’ll learn
- Define the n-step return, implement n-step TD, and prove the error-reduction property.
- Explain with the 19-state random walk why intermediate n and λ learn fastest, in terms of bias and variance.
- Define the λ-return, derive its recursive form, and show that its error is a discounted sum of TD errors.
- Implement TD(λ) with accumulating traces, state when the forward and backward views coincide exactly, and extend traces to control with SARSA(λ).
n-step returns: wait, then bootstrap
TD(0) updates from one real reward and then trusts ; Monte Carlo uses every reward to the end of the episode and trusts no estimate at all. Between them lies a family of targets that use real rewards and then bootstrap, the n-step return
with , the complete return, if the episode ends by time . n-step TD moves toward it.
input: policy π, step size α, number of steps n
for each episode:
store S_0; T ← ∞
for t = 0, 1, 2, …:
if t < T:
take A_t ~ π(·|S_t); observe and store R_{t+1} and S_{t+1}
if S_{t+1} is terminal: T ← t + 1
τ ← t − n + 1 # the time whose state is updated now
if τ ≥ 0:
G ← Σ_{i = τ+1}^{min(τ+n, T)} γ^{i−τ−1} R_i
if τ + n < T: G ← G + γ^n V(S_{τ+n})
V(S_τ) ← V(S_τ) + α [G − V(S_τ)]
if τ = T − 1: end the episoden-step TD, as in Sutton and Barto's §7.1. Only the last rewards and states need to be stored.
With , at what point can n-step TD update , assuming the episode is still running?
- Immediately after the transition from to
- After the transition to , once , , and are known
- Only at the end of the episode
- After the transition to
Show the answer
B. After the transition to , once , , and are known
needs three rewards and the state three steps later, all available right after the transition into . In the pseudocode that is the iteration with , where .
Unroll the Bellman equation of for steps and subtract it from the expected -step return. The rewards cancel; only the bootstrap terms remain (both values are 0 at terminal states):
An average of quantities each at most in size is no larger than that.
The expected -step target is , so this is the -contraction of Bellman backups, and it is why n-step TD converges under the usual conditions. More precisely, the factor is times the probability that the episode is still running at time ; with , as in the random walk, termination does the contracting.
Which n? The 19-state random walk
Larger leans less on the estimates, which are wrong early on, but puts more random steps into every target. Which effect wins is an empirical question, and Sutton and Barto answer it on a longer random walk: 19 states, start in the middle, step left or right with probability ½, reward for leaving on the left and for leaving on the right, . The true values run from to in steps of 0.1, and all estimates start at 0.
Each setting is scored by the RMS error over the first 10 episodes, averaged over 100 runs, at its best step size. Which do you expect to score best on the 19-state walk?
Show the answer
4
: an error of 0.266 at , against 0.346 for (TD(0)) and 0.420 for , the closest to Monte Carlo. Both extremes lose: small propagates information slowly from the ends of the walk through wrong estimates, and large makes every target noisy.
The pattern is a bias–variance trade-off. The error-reduction property says that the bias inherited from the estimates shrinks with ; but the variance of a target grows with the number of random steps it contains, and noisy targets force small step sizes, which is why the best falls as grows. Neither extreme is best. On the 5-state walk, where walks last only 9 steps on average, the balance tips the other way: wins there, so the best depends on the problem.
The λ-return: averaging every n
Why commit to one ? Any average of -step returns with weights summing to 1 is also a sound target, with its own error reduction. The λ-return uses geometric weights, for the -step return, with :
With , and an episode that is still far from its end, what total weight does the λ-return give to the 1-, 2-, 3- and 4-step returns together?
Show the answer
0.59
. The one-step return alone gets 0.2. More than 40% of the weight lies on returns longer than four steps, which is how ends up behaving much like on the random walk.
The -step returns satisfy and for . Substitute both into the definition; the weights on sum to 1, and the remaining weights for form times the λ-return from :
So the λ-return bootstraps a fraction at every step and carries the fraction on. Subtract , and add and subtract to bring in the TD error :
Unroll to the end of the episode, holding fixed. The λ-return's error is the sum of the TD errors that follow, discounted by per step; with this is the Monte Carlo identity of Temporal-Difference Learning:
Updating every visited state toward its λ-return when the episode ends is the off-line λ-return algorithm. This is the forward view: to update one must look forward to rewards that have not yet arrived, so nothing can be learned during the episode. On the 19-state walk it behaves like n-step TD, with intermediate best (Sutton and Barto, Figure 12.3).
Eligibility traces: the backward view
The last line of the derivation is the key. With held fixed, the forward-view error of the visit at time is a sum of the TD errors that come after it, each discounted by per step. Turn the bookkeeping around: rather than waiting at each visit for the future, send each TD error , as soon as it is known, back to every earlier visit with weight . The total weight a state collects from all its past visits is its eligibility trace:
This is the accumulating trace. TD(λ) updates every state at every step by : the backward view, which needs nothing from the future.
import numpy as np
def td_lambda_walk(episodes=10, n=19, alpha=0.3, lam=0.8, seed=0):
"""Online TD(lambda), accumulating traces, on the n-state random walk (gamma = 1)."""
rng = np.random.default_rng(seed)
V = np.zeros(n + 2) # V[0] and V[n + 1] are the exits: stay 0
for _ in range(episodes):
z = np.zeros(n + 2) # traces start at 0 in every episode
s = (n + 1) // 2 # start in the middle
while 0 < s <= n:
s2 = s + (1 if rng.random() < 0.5 else -1)
r = 1.0 if s2 == n + 1 else (-1.0 if s2 == 0 else 0.0)
delta = r + V[s2] - V[s] # TD error
z *= lam # every trace decays (gamma = 1)
z[s] += 1.0 # the visited state's trace grows
V += alpha * delta * z # all eligible states learn at once
s = s2
return V[1:-1]The two exit entries never acquire a trace, so they stay at 0 as terminal values must. Cost per step: one pass over the states with nonzero traces, which in practice means dropping traces below a small threshold.
A state is visited at times 2 and 5 and not otherwise, with and accumulating traces. What is its trace at time 6?
Show the answer
1.56
Each visit contributes : . A recently revisited state can have a trace above 1, so it absorbs more than its share of each TD error; replacing traces cap it at 1 instead.
Online, the views drift apart. Real TD(λ) changes at every step, so later TD errors are computed with updated estimates and the identity holds only approximately, with discrepancies of second order in . For small the difference is negligible; for large and near 1, accumulating traces can make online TD(λ) unstable. Two other traces matter: the replacing trace sets on a visit instead of adding 1, and the dutch trace lies between the two and makes true online TD(λ) reproduce an online forward view exactly.
Traces for control: SARSA(λ)
Control needs traces on state–action pairs. SARSA(λ) keeps a trace for every pair, uses SARSA's TD error , and updates every pair in proportion to its trace. In a gridworld where only the goal pays, the first successful episode teaches one-step SARSA about a single action, the last one; n-step SARSA strengthens the last actions; SARSA(λ) strengthens every action of the episode, by an amount that fades with how long ago it was taken.
input: step size α, trace decay λ, exploration ε
Q(s, a) ← 0 for all s, a
for each episode:
z(s, a) ← 0 for all s, a
S ← initial state; A ← ε-greedy action for Q(S, ·)
while S is not terminal:
take A; observe R and S'
if S' is terminal: δ ← R − Q(S, A)
else: A' ← ε-greedy action for Q(S', ·); δ ← R + γ·Q(S', A') − Q(S, A)
z(S, A) ← z(S, A) + 1 # accumulating; replacing would set it to 1
for every pair (s, a) with z(s, a) > 0:
Q(s, a) ← Q(s, a) + α·δ·z(s, a)
z(s, a) ← γ·λ·z(s, a)
S, A ← S', A'Tabular SARSA(λ) (Rummery & Niranjan, 1994). With it is one-step SARSA.
Off-policy, traces need care. For Q-learning, the rewards that follow an exploratory action no longer describe the greedy policy whose values are being learned, so Watkins's Q(λ) cuts every trace to zero after a non-greedy action. With frequent exploration its traces are therefore short, which is the motivation for the more careful cuts of tree backup and Retrace.
Key takeaways
- The -step return uses real rewards and then bootstraps; its expectation is closer to than the current estimate by a factor in the worst state (error reduction).
- On the 19-state walk intermediate settings learn fastest (, ): larger trades bias from the estimates for variance from the rewards, and the best depends on the problem.
- The λ-return averages all -step returns with weights ; it satisfies , and its error is .
- An eligibility trace sends each TD error back to the states that earned it. Off-line, TD(λ)'s summed updates equal the λ-return algorithm's exactly; online they agree only approximately, which true online TD(λ) repairs.
- SARSA(λ) carries traces to control and credits a whole path at once; off-policy, traces must be cut or corrected, as Watkins's Q(λ) does crudely.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
What does the error-reduction property of -step returns guarantee?
- Each sampled -step return is closer to than is
- n-step TD learns faster than TD(0) on every problem
- The expected -step return is closer to than is, in the worst state, by at least a factor
- The variance of the -step return decreases as grows
Show the answer
C. The expected -step return is closer to than is, in the worst state, by at least a factor
, which in absolute value is at most . It is a statement about the mean of the target, and it says nothing about its variance or about speed in practice.
Why does an intermediate beat both and on the 19-state walk?
- Because divides the length of the walk
- Because large adds variance from more random steps while small leans on wrong estimates; intermediate balances the two
- Because n-step TD with large diverges
- Because the true values are linear in the state
Show the answer
B. Because large adds variance from more random steps while small leans on wrong estimates; intermediate balances the two
Bias shrinks like (or with the probability of still being in the episode), while variance grows with the number of random steps in the target, and noisy targets need smaller step sizes. The best trade-off depends on the problem: on the 5-state walk, with its short episodes, is best.
An episode ends 5 steps after time () and . What weight does the λ-return give to the complete return ?
- 0
Show the answer
D.
The weight left after the end is . The 1- to 4-step returns take , and the two add up to 1.
When are the summed TD(λ) updates of an episode exactly equal to the updates of the off-line λ-return algorithm?
- When the step size is small enough
- When the estimates are held fixed during the episode and the increments are applied at its end
- Only for and
- Whenever the environment is deterministic
Show the answer
B. When the estimates are held fixed during the episode and the increments are applied at its end
The proof exchanges two sums of TD errors computed with one fixed . Online, each TD error uses estimates already changed by earlier updates in the episode, and the equality becomes approximate, with discrepancies of order . True online TD(λ) restores an exact equality for a suitably defined online forward view.
In a gridworld where only reaching the goal pays, why does SARSA(λ) improve its policy after the first successful episode far more than one-step SARSA?
- Because SARSA(λ) uses a larger step size
- Because traces make it explore more
- Because it learns a model of the gridworld
- Because the goal's TD error reaches every pair with a nonzero trace, that is, every action taken earlier in the episode, with weight fading by per step
Show the answer
D. Because the goal's TD error reaches every pair with a nonzero trace, that is, every action taken earlier in the episode, with weight fading by per step
One-step SARSA updates only the pair just before the goal; the rest of the path learns about the goal only in later episodes, one step back each time. SARSA(λ) credits the whole path at once, with more credit for recent actions.
Go deeper
- Forward & Backward Views of TD(λ) · Why traces implement λ-returns, and true online TD(λ).
- Off-Policy Traces: Tree Backup & Retrace · Cutting traces safely: learning off-policy without exploding variance.
- Temporal Credit Assignment · Which action earned the reward? Long delays, hindsight and return decomposition.
Further reading
- R. S. Sutton, "Learning to predict by the methods of temporal differences," Machine Learning 3, 9–44 (1988).
- C. J. C. H. Watkins, Learning from Delayed Rewards, PhD thesis, University of Cambridge (1989).
- R. S. Sutton & A. G. Barto, Reinforcement Learning: An Introduction, ch. 7 and 12 (MIT Press, 2nd ed., 2018).