Simple Algorithm
Reinforcement Learning · Bootstrapping · 24 min

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 V(St)V(S_t) from one real reward and then trusts V(St+1)V(S_{t+1}); 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 nn real rewards and then bootstrap, the n-step return

Gt:t+n=Rt+1+γRt+2+⋯+γn−1Rt+n+γnV(St+n),G_{t:t+n} = R_{t+1} + \gamma R_{t+2} + \dots + \gamma^{n-1}R_{t+n} + \gamma^n V(S_{t+n}),

with Gt:t+n=GtG_{t:t+n} = G_t, the complete return, if the episode ends by time t+nt+n. n-step TD moves V(St)V(S_t) toward it.

V(St)←V(St)+α[ Gt:t+n−V(St) ]V(S_t) \leftarrow V(S_t) + \alpha\big[\,G_{t:t+n} - V(S_t)\,\big]
The target is complete only at time t+nt+n, so each update waits nn steps, and when the episode ends the last n−1n-1 states are updated toward returns that run to the end. The bootstrap uses the latest estimate of V(St+n)V(S_{t+n}). n=1n = 1 is TD(0); nn at least the length of the episode is Monte Carlo.
text
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 episode

n-step TD, as in Sutton and Barto's §7.1. Only the last nn rewards and states need to be stored.

Check your understanding

With n=3n = 3, at what point can n-step TD update V(S5)V(S_5), assuming the episode is still running?

  1. Immediately after the transition from S5S_5 to S6S_6
  2. After the transition to S8S_8, once R6R_6, R7R_7, R8R_8 and S8S_8 are known
  3. Only at the end of the episode
  4. After the transition to S7S_7
Show the answer

B. After the transition to S8S_8, once R6R_6, R7R_7, R8R_8 and S8S_8 are known

G5:8=R6+γR7+γ2R8+γ3V(S8)G_{5:8} = R_6 + \gamma R_7 + \gamma^2R_8 + \gamma^3V(S_8) needs three rewards and the state three steps later, all available right after the transition into S8S_8. In the pseudocode that is the iteration with t=7t = 7, where τ=t−n+1=5\tau = t - n + 1 = 5.

DerivationProof
  1. Eπ[Gt:t+n∣St=s]−Vπ(s)=γn Eπ[V(St+n)−Vπ(St+n)∣St=s]\E_\pi\big[G_{t:t+n} \mid S_t = s\big] - V^\pi(s) = \gamma^n\,\E_\pi\big[V(S_{t+n}) - V^\pi(S_{t+n}) \mid S_t = s\big]

    Unroll the Bellman equation of VπV^\pi for nn steps and subtract it from the expected nn-step return. The rewards cancel; only the bootstrap terms remain (both values are 0 at terminal states):

  2. ∣Eπ[Gt:t+n∣St=s]−Vπ(s)∣≤γnmax⁡s′∣V(s′)−Vπ(s′)∣\Big|\E_\pi\big[G_{t:t+n} \mid S_t = s\big] - V^\pi(s)\Big| \le \gamma^n\max_{s'}\big|V(s') - V^\pi(s')\big|

    An average of quantities each at most max⁡s′∣V(s′)−Vπ(s′)∣\max_{s'}\abs{V(s') - V^\pi(s')} in size is no larger than that. ■\blacksquare

  3. The expected nn-step target is (Tπ)nV(\mathcal T^\pi)^nV, so this is the γn\gamma^n-contraction of nn Bellman backups, and it is why n-step TD converges under the usual conditions. More precisely, the factor is γn\gamma^n times the probability that the episode is still running at time t+nt + n; with γ=1\gamma = 1, as in the random walk, termination does the contracting.

Which n? The 19-state random walk

Larger nn 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 −1-1 for leaving on the left and +1+1 for leaving on the right, γ=1\gamma = 1. The true values run from −0.9-0.9 to 0.90.9 in steps of 0.1, and all estimates start at 0.

Predict before you look

Each setting is scored by the RMS error over the first 10 episodes, averaged over 100 runs, at its best step size. Which nn do you expect to score best on the 19-state walk?

Show the answer

4

n=4n = 4: an error of 0.266 at α=0.35\alpha = 0.35, against 0.346 for n=1n = 1 (TD(0)) and 0.420 for n=64n = 64, the closest to Monte Carlo. Both extremes lose: small nn propagates information slowly from the ends of the walk through wrong estimates, and large nn 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 nn; 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 α\alpha falls as nn grows. Neither extreme is best. On the 5-state walk, where walks last only 9 steps on average, the balance tips the other way: n=1n = 1 wins there, so the best nn depends on the problem.

The λ-return: averaging every n

Why commit to one nn? Any average of nn-step returns with weights summing to 1 is also a sound target, with its own error reduction. The λ-return uses geometric weights, (1−λ)λn−1(1-\lambda)\lambda^{n-1} for the nn-step return, with 0≤λ≤10 \le \lambda \le 1:

Gtλ=(1−λ)∑n=1T−t−1λn−1 Gt:t+n  +  λT−t−1 GtG_t^\lambda = (1-\lambda)\sum_{n=1}^{T-t-1}\lambda^{n-1}\,G_{t:t+n} \;+\; \lambda^{T-t-1}\,G_t
For an episode that ends at time TT, all the weight beyond the end falls on the complete return GtG_t. λ=0\lambda = 0 gives the one-step TD target and λ=1\lambda = 1 the Monte Carlo return. The weights halve every ln⁡2/ln⁡(1/λ)\ln 2/\ln(1/\lambda) steps: about 3.1 steps for λ=0.8\lambda = 0.8.
Predict before you look

With λ=0.8\lambda = 0.8, 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

(1−λ)(1+λ+λ2+λ3)=1−λ4=1−0.4096≈0.59(1-\lambda)(1 + \lambda + \lambda^2 + \lambda^3) = 1 - \lambda^4 = 1 - 0.4096 \approx 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 λ=0.8\lambda = 0.8 ends up behaving much like n=4n = 4 on the random walk.

DerivationA recursion, and the λ-return error as a sum of TD errors
  1. Gtλ=Rt+1+γ[(1−λ) V(St+1)+λ Gt+1λ]G_t^\lambda = R_{t+1} + \gamma\Big[(1-\lambda)\,V(S_{t+1}) + \lambda\,G_{t+1}^\lambda\Big]

    The nn-step returns satisfy Gt:t+1=Rt+1+γV(St+1)G_{t:t+1} = R_{t+1} + \gamma V(S_{t+1}) and Gt:t+n=Rt+1+γGt+1:t+nG_{t:t+n} = R_{t+1} + \gamma G_{t+1:t+n} for n≥2n \ge 2. Substitute both into the definition; the weights on Rt+1R_{t+1} sum to 1, and the remaining weights (1−λ)λn−1(1-\lambda)\lambda^{n-1} for n≥2n \ge 2 form λ\lambda times the λ-return from t+1t+1:

  2. Gtλ−V(St)=δt+γλ(Gt+1λ−V(St+1))G_t^\lambda - V(S_t) = \delta_t + \gamma\lambda\big(G_{t+1}^\lambda - V(S_{t+1})\big)

    So the λ-return bootstraps a fraction 1−λ1-\lambda at every step and carries the fraction λ\lambda on. Subtract V(St)V(S_t), and add and subtract γV(St+1)\gamma V(S_{t+1}) to bring in the TD error δt=Rt+1+γV(St+1)−V(St)\delta_t = R_{t+1} + \gamma V(S_{t+1}) - V(S_t):

  3. Gtλ−V(St)=∑k=tT−1(γλ)k−t δkG_t^\lambda - V(S_t) = \sum_{k=t}^{T-1}(\gamma\lambda)^{k-t}\,\delta_k

    Unroll to the end of the episode, holding VV fixed. The λ-return's error is the sum of the TD errors that follow, discounted by γλ\gamma\lambda per step; with λ=1\lambda = 1 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 StS_t 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 λ\lambda best (Sutton and Barto, Figure 12.3).

Eligibility traces: the backward view

The last line of the derivation is the key. With VV held fixed, the forward-view error of the visit at time tt is a sum of the TD errors that come after it, each discounted by γλ\gamma\lambda per step. Turn the bookkeeping around: rather than waiting at each visit for the future, send each TD error δk\delta_k, as soon as it is known, back to every earlier visit t≤kt \le k with weight (γλ)k−t(\gamma\lambda)^{k-t}. The total weight a state collects from all its past visits is its eligibility trace:

zk(s)=∑t≤k: St=s(γλ)k−t,computed aszk(s)=γλ zk−1(s)+1[Sk=s].z_k(s) = \sum_{t \le k:\ S_t = s}(\gamma\lambda)^{k-t},\qquad\text{computed as}\qquad z_k(s) = \gamma\lambda\,z_{k-1}(s) + \mathbb 1[S_k = s].

This is the accumulating trace. TD(λ) updates every state at every step by V(s)←V(s)+α δk zk(s)V(s) \leftarrow V(s) + \alpha\,\delta_k\,z_k(s): the backward view, which needs nothing from the future.

python
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.

Predict before you look

A state is visited at times 2 and 5 and not otherwise, with γλ=0.9\gamma\lambda = 0.9 and accumulating traces. What is its trace z6z_6 at time 6?

Show the answer

1.56

Each visit contributes (γλ)time since the visit(\gamma\lambda)^{\text{time since the visit}}: 0.94+0.91=0.656+0.9=1.5560.9^{4} + 0.9^{1} = 0.656 + 0.9 = 1.556. 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 VV at every step, so later TD errors are computed with updated estimates and the identity holds only approximately, with discrepancies of second order in α\alpha. For small α\alpha the difference is negligible; for large α\alpha and λ\lambda near 1, accumulating traces can make online TD(λ) unstable. Two other traces matter: the replacing trace sets z(s)=1z(s) = 1 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 z(s,a)z(s,a) for every pair, uses SARSA's TD error δt=Rt+1+γQ(St+1,At+1)−Q(St,At)\delta_t = R_{t+1} + \gamma Q(S_{t+1},A_{t+1}) - Q(S_t,A_t), 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 nn actions; SARSA(λ) strengthens every action of the episode, by an amount that fades with how long ago it was taken.

text
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 λ=0\lambda = 0 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 nn-step return uses nn real rewards and then bootstraps; its expectation is closer to VπV^\pi than the current estimate by a factor γn\gamma^n in the worst state (error reduction).
  • On the 19-state walk intermediate settings learn fastest (n=4n = 4, λ=0.8\lambda = 0.8): larger nn trades bias from the estimates for variance from the rewards, and the best nn depends on the problem.
  • The λ-return averages all nn-step returns with weights (1−λ)λn−1(1-\lambda)\lambda^{n-1}; it satisfies Gtλ=Rt+1+γ[(1−λ)V(St+1)+λGt+1λ]G_t^\lambda = R_{t+1} + \gamma[(1-\lambda)V(S_{t+1}) + \lambda G_{t+1}^\lambda], and its error is ∑k(γλ)k−tδk\sum_k(\gamma\lambda)^{k-t}\delta_k.
  • An eligibility trace z(s)←γλz(s)+1[S=s]z(s) \leftarrow \gamma\lambda z(s) + \mathbb 1[S = s] 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.

Question 1

What does the error-reduction property of nn-step returns guarantee?

  1. Each sampled nn-step return is closer to Vπ(St)V^\pi(S_t) than V(St)V(S_t) is
  2. n-step TD learns faster than TD(0) on every problem
  3. The expected nn-step return is closer to VπV^\pi than VV is, in the worst state, by at least a factor γn\gamma^n
  4. The variance of the nn-step return decreases as nn grows
Show the answer

C. The expected nn-step return is closer to VπV^\pi than VV is, in the worst state, by at least a factor γn\gamma^n

Eπ[Gt:t+n∣St=s]−Vπ(s)=γnEπ[(V−Vπ)(St+n)]\E_\pi[G_{t:t+n} \mid S_t = s] - V^\pi(s) = \gamma^n\E_\pi[(V - V^\pi)(S_{t+n})], which in absolute value is at most γnmax⁡∣V−Vπ∣\gamma^n\max\abs{V - V^\pi}. It is a statement about the mean of the target, and it says nothing about its variance or about speed in practice.

Question 2

Why does an intermediate nn beat both n=1n = 1 and n=64n = 64 on the 19-state walk?

  1. Because n=4n = 4 divides the length of the walk
  2. Because large nn adds variance from more random steps while small nn leans on wrong estimates; intermediate nn balances the two
  3. Because n-step TD with large nn diverges
  4. Because the true values are linear in the state
Show the answer

B. Because large nn adds variance from more random steps while small nn leans on wrong estimates; intermediate nn balances the two

Bias shrinks like γn\gamma^n (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, n=1n = 1 is best.

Question 3

An episode ends 5 steps after time tt (T−t=5T - t = 5) and λ=0.5\lambda = 0.5. What weight does the λ-return GtλG_t^\lambda give to the complete return GtG_t?

  1. 0
  2. 0.50.5
  3. 0.031250.03125
  4. 0.06250.0625
Show the answer

D. 0.06250.0625

The weight left after the end is λT−t−1=0.54=0.0625\lambda^{T-t-1} = 0.5^4 = 0.0625. The 1- to 4-step returns take (1−λ)(1+λ+λ2+λ3)=0.9375(1-\lambda)(1 + \lambda + \lambda^2 + \lambda^3) = 0.9375, and the two add up to 1.

Question 4

When are the summed TD(λ) updates of an episode exactly equal to the updates of the off-line λ-return algorithm?

  1. When the step size is small enough
  2. When the estimates are held fixed during the episode and the increments are applied at its end
  3. Only for λ=0\lambda = 0 and λ=1\lambda = 1
  4. 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 VV. Online, each TD error uses estimates already changed by earlier updates in the episode, and the equality becomes approximate, with discrepancies of order α2\alpha^2. True online TD(λ) restores an exact equality for a suitably defined online forward view.

Question 5

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?

  1. Because SARSA(λ) uses a larger step size
  2. Because traces make it explore more
  3. Because it learns a model of the gridworld
  4. 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 γλ\gamma\lambda 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 γλ\gamma\lambda 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

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).