Module contents
Lesson 10 of 37Core 115 min

Temporal-difference learning: TD(0), n-step and TD(λ)

Learn temporal-difference prediction, multi-step returns, eligibility traces and batch certainty equivalence.

After this lesson you can

  • Derive TD errors and compare TD with Monte Carlo prediction.
  • Explain batch TD and its empirical certainty-equivalent model.
  • Analyze n-step and lambda returns, bootstrapping and termination.
  • Derive accumulating and replacing eligibility traces.
  • Implement online tabular TD(lambda) with correct terminal and truncation handling.

Before you start

Learning on the way home

You leave work and estimate how long it will take to get home. When you reach an avenue, you know the time already spent and can combine it with a new prediction of the remaining time. You can correct your earlier prediction before you park. The trade-off is that the new prediction can also be wrong.

In the previous lesson we averaged complete returns. Here we learn the value of a fixed policy from transitions, without knowing the model or necessarily waiting for the episode to end. The comparison depends on the observed state, learning rate and data. Neither method wins universally.

TD(0): a sampled Bellman equation

For a fixed policy in an MDP, the evaluation equation is vπ(s)=E[Rt+1+γvπ(St+1)∣St=s]v^\pi(s)=\mathbb E[R_{t+1}+\gamma v^\pi(S_{t+1})\mid S_t=s]. Replacing the expectation with an observed transition and the true value with our table VV gives the temporal-difference error

δt=Rt+1+γV(St+1)−V(St),V(St)←V(St)+αδt.\delta_t=R_{t+1}+\gamma V(S_{t+1})-V(S_t),\qquad V(S_t)\leftarrow V(S_t)+\alpha\delta_t.

This is TD(0). Conditional on St=sS_t=s and with the table frozen, the expectation of δt\delta_t is (TπV)(s)−V(s)(T^\pi V)(s)-V(s). Sampling noise approximates the root of a Bellman equation. The term γV(St+1)\gamma V(S_{t+1}) is bootstrapping, an estimate inside the target. If the episode truly terminates, the subsequent value is zero. If an external time limit truncates a continuing task, use the value of the observed final state. Confusing the cases changes the target.

TD can update after every transition. Monte Carlo needs the return from that visit to the end, but does not place an estimated value in the target of a complete episode. The TD target can be biased relative to the true return while VV is inaccurate. Its variance is not always lower: it depends on the process, the estimate and the quantity compared.

InteractiveLearning on a random walk

Preparando los paseos reproducibles.

Compare the measured TD and Monte Carlo errors and examine fixed-data behavior.

In the walk with five nonterminal states, a coin decides left or right and the walk starts in the middle. Reaching the right endpoint yields one and the left endpoint zero; all other rewards are zero. With γ=1\gamma=1, the true values are the probabilities of reaching the right endpoint: from the first to the fifth state they are 1/6,2/6,…,5/61/6,2/6,\ldots,5/6. RMS error compares the five predictions with these values. Averaging over seeds reduces noise but does not replace independent evaluation. When varying α\alpha, compare both methods over a range of step sizes instead of a single arbitrary point.

What batch TD learns

Consider eight fixed episodes. One transitions from A to B with reward zero, then from B to terminal with reward zero. Another starts at B and terminates with reward zero. The remaining six start at B and terminate with reward one. Overall, B ends with one six times and with zero twice. With γ=1\gamma=1, batch Monte Carlo fits the mean observed return for each state: VMC(A)=0V_{\mathrm{MC}}(A)=0 and VMC(B)=3/4V_{\mathrm{MC}}(B)=3/4. Batch TD sums TD errors from all transitions and repeatedly applies the batch update. Its fixed point satisfies V(A)=V(B)V(A)=V(B) and V(B)=3/4V(B)=3/4.

The distinction is structural. The certainty-equivalent model estimates transition probabilities and mean rewards from observed transitions, then solves its Bellman equation as if that model were exact. In this example it reproduces the TD fixed point. More generally, for observed states, zero aggregated tabular TD errors coincide with the empirical model equation. Uniqueness and convergence of the iterative procedure require assumptions, such as a transient empirical model in the episodic setting and a sufficiently small step size. A batch cannot identify states without observed transitions. Equivalence does not make the estimated model the true one. See the example and discussion in Sutton and Barto, chapter 6.

If an observation combines histories with different futures, it may cease to be Markov. TD by observation combines transitions as if the future depended only on that observation. MC estimates visit returns under the distribution of histories in the data. The disagreement does not guarantee lower MC error, but it explains why the Markov assumption matters.

Between one step and a complete episode

The nn-step return observes several rewards and bootstraps if the episode has not ended:

Gt:t+n=∑k=0n−1γkRt+k+1+γnV(St+n).G_{t:t+n}=\sum_{k=0}^{n-1}\gamma^kR_{t+k+1}+\gamma^nV(S_{t+n}).

If the episode ends at T<t+nT<t+n, the sum stops at RTR_T and terminal bootstrapping is omitted. For n=1n=1 we obtain TD(0); if nn reaches the end, the target is the Monte Carlo return. With a frozen table, formally extend the terminal state as absorbing with zero value and reward. The bias of the target relative to vπv^\pi is then γnE[V(St+n)−vπ(St+n)∣St=s]\gamma^n\mathbb E[V(S_{t+n})-v^\pi(S_{t+n})\mid S_t=s]. Its magnitude is bounded by γn∥V−vπ∥∞\gamma^n\lVert V-v^\pi\rVert_\infty. With γ<1\gamma<1 this bound decreases with nn, although actual bias need not decrease monotonically. Noise and update frequency also change, so lower total error is not guaranteed.

InteractiveFinding a backup horizon

Preparando el barrido reproducible de n pasos.

Sweep the learning rate on a 19-state walk; each curve comes from simulated trajectories.

In the reference experiment of Sutton and Barto, figure 7.2, the walk has 19 states, terminal rewards −1 on the left and +1 on the right, and initial values zero. The book averages RMS over the first 10 episodes and 100 repetitions using the same trajectories for the compared configurations. There, some intermediate horizons outperform the extremes when α\alpha is also selected. The interactive and laboratory state their own budgets. A short run need not reproduce the published curve exactly or prove that an intermediate optimum always exists.

Mixing horizons and assigning credit

The forward view of the λ-return mixes all horizons of a finite episode:

Gtλ=(1−λ)∑n=1T−t−1λn−1Gt:t+n+λT−t−1Gt:T,0≤λ≤1.G_t^\lambda=(1-\lambda)\sum_{n=1}^{T-t-1}\lambda^{n-1}G_{t:t+n} +\lambda^{T-t-1}G_{t:T},\qquad 0\leq\lambda\leq1.

The last term collects all remaining weight, and Gt:TG_{t:T} is the complete return. At λ=0\lambda=0 the target is one-step; at λ=1\lambda=1 it is the complete return. Here the bootstrap targets use a single table frozen during the episode.

To assign credit without storing all futures, define an accumulating eligibility trace per state:

et(s)=γλet−1(s)+1{St=s},V(s)←V(s)+αδtet(s).e_t(s)=\gamma\lambda e_{t-1}(s)+\mathbf 1\{S_t=s\},\qquad V(s)\leftarrow V(s)+\alpha\delta_t e_t(s).

Initialize the traces to zero at the start of each episode. A visit adds one, and previous traces decay by γλ\gamma\lambda at each transition. A tabular replacing trace changes the second rule: after decay, set the visited state’s trace to one instead of adding one. With revisits, the two assign credit differently.

InteractiveA reward finds its traces
A →B →C →B →D→ terminal (+1)
A
0.269ΔV = 0.0537V = 0.0537
B
1.093ΔV = 0.2186V = 0.2186
C
0.518ΔV = 0.1037V = 0.1037
D
1.000ΔV = 0.2000V = 0.2000

Episodio explícito A→B→C→B→D→terminal, recompensas 0 salvo +1 al terminar. Se empieza con V=0 y trazas 0; α=0,2. Para cada transición, δ=r+γV(siguiente)−V(actual), con V(terminal)=0. Primero se multiplica toda traza por γλ; después se suma 1 en el estado actual o se reemplaza su traza por 1. Finalmente ΔV(s)=αδz(s). Las barras se escalan respecto de la mayor traza actual o de 1.

Las visitas a B se acumulan en una variante y se sustituyen en la otra. Con λ=0 solo conserva crédito el estado actual; con γλ=1 una traza acumulativa no decae. Aquí los errores anteriores al final son cero porque los valores empiezan en cero y solo hay recompensa terminal. Las trazas se reinician antes del episodio y no se identifica esta actualización online con una equivalencia exacta a paso constante con el λ-retorno offline.

Tipo de traza
0.90
0.80
5
Transición
5 / 5
Recompensa actual
1.0
Error TD δ
1.000
Step through the trajectory and compare accumulating and replacing traces as λ changes.

If VV remains frozen and updates are accumulated until the end, the backward sum of αδtet(s)\alpha\delta_t e_t(s) exactly equals the forward sum of α(Gtλ−V(St))\alpha(G_t^\lambda-V(S_t)) for each visit to ss. This is an algebraic identity, not a convergence claim. In ordinary online TD, VV changes within the episode, so equality with the frozen view is no longer exact. Van Seijen and Sutton construct a different online view and an algorithm that matches it exactly.

The Dutch trace for that algorithm, with linear features xtx_t and a constant step size, is

et=γλet−1+(1−αγλet−1Txt)xt.e_t=\gamma\lambda e_{t-1} +\bigl(1-\alpha\gamma\lambda e_{t-1}^{\mathsf T}x_t\bigr)x_t.

Inserting this trace into ordinary TD is insufficient: true online TD(λ) also adds correction terms for changes in estimated value. In the tabular case, xtx_t is the indicator vector of the state. With general features, one visit may change predictions for several states. This lesson’s equivalence proof concerns accumulating traces and a frozen table, not every combination of traces and updates.

When it converges and where it reappears

A typical tabular result assumes a finite MDP, fixed policy, γ<1\gamma<1, bounded rewards and infinitely many visits to each state of interest. With per-state step sizes satisfying ∑kαk(s)=∞\sum_k\alpha_k(s)=\infty and ∑kαk(s)2<∞\sum_k\alpha_k(s)^2<\infty, TD(0) converges almost surely under standard chain-sampling conditions. Intuitively, TπT^\pi is contractive and noise is averaged without step sizes vanishing too soon. This is a sketch, not a proof for neural networks, off-policy data or constant step sizes; see Jaakkola, Jordan and Singh.

The TD error also inspired an interpretation of dopamine signals: an unexpected reward, a predictive cue and an omitted expected reward produce different responses. Schultz, Dayan and Montague proposed a connection to prediction errors. This does not mean every dopamine neuron literally computes the tabular equation above.

The same operation reappears with approximate functions. Multi-step targets combine observed rewards with a value at the end. GAE sums TD errors weighted by (γλ)l(\gamma\lambda)^l to estimate advantages in an actor-critic (Schulman and colleagues). DQN trains action values with TD targets, while later variants use multiple steps. MuZero combines reward, policy and value prediction with search. These extensions add policies, networks and data outside the assumptions for tabular convergence.

Laboratory: compare without hand-picking the step size

The walk has nonterminal states 1 through 19, starts at 10 and ends at 0 or 20 with rewards −1 or +1 respectively. All other transitions have zero reward. With equiprobable steps, γ=1 and zero terminal values, the true value of state s is (s−10)/10. Walks are generated beforehand and shared by every combination of n and α. The code uses circular memory of n+1 states and updates online, without consulting a future position for bootstrapping. The target is simpler than the general n-step return because reward occurs only at termination.

[ ]n-step TD on 19 statesBrowser
import math
import random

def walks(seed,episodes=10):
    rng=random.Random(seed); result=[]
    for _ in range(episodes):
        state=10; path=[state]
        while 0<state<20:
            state+=1 if rng.random()<.5 else -1
            path.append(state)
        result.append(path)
    return result

def n_step_episode(V,path,n,alpha):
    if n<1: raise ValueError('n debe ser positivo')
    T=len(path)-1; ring=[0]*(n+1); ring[0]=path[0]
    terminal_reward=-1.0 if path[-1]==0 else 1.0
    t=0
    while True:
        if t<T:
            ring[(t+1)%(n+1)]=path[t+1]
        tau=t-n+1
        if 0<=tau<T:
            state=ring[tau%(n+1)]
            target=V[ring[(tau+n)%(n+1)]] if tau+n<T else terminal_reward
            V[state]+=alpha*(target-V[state])
            if tau==T-1: break
        t+=1
        # Tras terminar no llegan datos: salta solo rondas sin actualización.
        if t==T and t<n-1: t=n-1

def rms(V):
    return math.sqrt(sum((V[s]-(s-10)/10)**2 for s in range(1,20))/19)

assert walks(100,1)==walks(100,1)
# Trayectoria corta: n=1 propaga solo la recompensa al último estado.
V=[0.0]*21
n_step_episode(V,[18,19,20],1,1.0)
assert V[18]==0 and V[19]==1
V=[0.0]*21
n_step_episode(V,[18,19,20],2,1.0)
assert V[18]==1 and V[19]==1

paths=[walks(410+seed) for seed in range(4)]
steps=(1,2,4,8,16,32,64,128,256,512)
alphas=(.05,.1,.2,.4,.6,.8)
for n in steps:
    row=[]
    for alpha in alphas:
        errors=[]
        for experiment in paths:
            V=[0.0]*21
            for path in experiment:
                n_step_episode(V,path,n,alpha)
                errors.append(rms(V))
        row.append(round(sum(errors)/len(errors),4))
    print('n',n,'α',alphas,'RMS medio',row)

The output averages RMS at the end of each of ten episodes and over four seeds. This is a small, real sweep of the experiment in Sutton and Barto, figure 7.2. The book averages 100 repetitions and explores a wider grid. This short test does not guarantee that the minimum lies at an intermediate n or reproduce the published figure’s precision. n=1 is TD(0); when n exceeds the duration, the target is the complete episode return.

The second check compares the forward view with accumulating traces with values frozen throughout the episode. It then illustrates online traces, which update values at each transition and do not match that offline calculation for a finite step size. A true terminal state contributes no bootstrap. An external truncation requires a continuation estimate and is not represented here as terminal.

[ ]λ-return and eligibility tracesBrowser
import math

def lambda_targets(states,rewards,V,gamma,lam):
    # states contiene T estados no terminales; se anexa None al terminar.
    T=len(rewards); targets=[]
    for t in range(T):
        mixture=0.0; power=1.0
        for n in range(1,T-t+1):
            ret=sum(gamma**j*rewards[t+j] for j in range(n))
            if t+n<T: ret+=gamma**n*V[states[t+n]]
            coefficient=(1-lam)*power if t+n<T else power
            mixture+=coefficient*ret
            power*=lam
        targets.append(mixture)
    return targets

def offline_updates(states,rewards,V,gamma,lam):
    targets=lambda_targets(states,rewards,V,gamma,lam)
    forward=[0.0]*len(V)
    for t,s in enumerate(states): forward[s]+=targets[t]-V[s]
    backward=[0.0]*len(V); trace=[0.0]*len(V)
    for t,s in enumerate(states):
        trace=[gamma*lam*e for e in trace]; trace[s]+=1
        next_value=V[states[t+1]] if t+1<len(states) else 0.0
        delta=rewards[t]+gamma*next_value-V[s]
        backward=[u+delta*e for u,e in zip(backward,trace)]
    return targets,forward,backward

def online_td_lambda(states,rewards,V,alpha,gamma,lam,kind):
    V=V.copy(); trace=[0.0]*len(V)
    if kind not in ('acumulativa','reemplazo'):
        raise ValueError('Traza desconocida')
    for t,s in enumerate(states):
        next_value=V[states[t+1]] if t+1<len(states) else 0.0
        delta=rewards[t]+gamma*next_value-V[s]
        trace=[gamma*lam*e for e in trace]
        trace[s]=trace[s]+1 if kind=='acumulativa' else 1.0
        V=[v+alpha*delta*e for v,e in zip(V,trace)]
    return V

states=[0,1,0]; rewards=[0.,0.,1.]; base=[.2,.4]
targets,forward,backward=offline_updates(states,rewards,base,.9,.7)
assert all(math.isclose(a,b,abs_tol=1e-12) for a,b in zip(forward,backward))
one_step=lambda_targets(states,rewards,base,.9,0.)
assert math.isclose(one_step[0],.9*base[1],abs_tol=1e-12)
mc=lambda_targets(states,rewards,base,.9,1.)
assert all(math.isclose(a,b,abs_tol=1e-12) for a,b in zip(mc,[.9**2,.9,1.]))
print('Objetivos λ congelados:',[round(x,6) for x in targets],
      'diferencia delante/detrás:',max(abs(a-b) for a,b in zip(forward,backward)))
for kind in ('acumulativa','reemplazo'):
    print('TD online',kind,online_td_lambda(states,rewards,base,.1,.9,.7,kind))

The trace is reset at the start of the episode. Replacing sets the current state’s trace to one; accumulating adds one. The exact match checked here concerns a sum of updates calculated from the same frozen table, not ordinary online TD. Dutch traces in true-online TD(λ) use a different update.

The following fixed set contains eight episodes: one A→B→terminal with final reward zero, another B→terminal with reward zero, and six B→terminal with reward one. MC fits the observed returns. Batch TD seeks the point where average per-state TD errors are zero. The maximum-likelihood model uses the same transitions. This does not compare performance on new data.

[ ]Batch TD and certainty equivalenceBrowser
import numpy as np

episodes=[[(0,0.0,1),(1,0.0,None)],[(1,0.0,None)]]+[[(1,1.0,None)] for _ in range(6)]
counts=np.zeros(2); reward_sum=np.zeros(2); transitions=np.zeros((2,2)); mc_sum=np.zeros(2)
for episode in episodes:
    G=0.0
    for s,r,next_state in reversed(episode):
        G=r+G; mc_sum[s]+=G
    for s,r,next_state in episode:
        counts[s]+=1; reward_sum[s]+=r
        if next_state is not None: transitions[s,next_state]+=1
P=transitions/counts[:,None]; r=reward_sum/counts
maximum_likelihood=np.linalg.solve(np.eye(2)-P,r)
V=np.zeros(2)
for iteration in range(10000):
    error=r+P@V-V
    if np.max(np.abs(error))<1e-12: break
    V+=.2*error
assert np.allclose(V,maximum_likelihood,atol=1e-10,rtol=0)
print('MC por lotes:',mc_sum/counts,'TD por lotes:',V,
      'modelo de máxima verosimilitud:',maximum_likelihood,
      'residuo:',float(np.max(np.abs(r+P@V-V))))

The example is episodic and terminates with probability one in the estimated model. The TD/model match requires a well-defined fixed point for the estimated system and observed states. It does not automatically extend to arbitrary function approximation.

Exercises

ProofFrom TD error to Monte Carlo error
Prove: Prove the identity for a complete episodic trajectory.
0
The episode ends at T, γ lies between 0 and 1, V is frozen throughout the trajectory, and V(S_T)=0. Define δ_k=R_{k+1}+γV(S_{k+1})−V(S_k).

Step 1 of 2. What do you sum when expanding the discounted errors from t?

ProofInterchanging the two sums
Prove: Prove the equivalence of offline forward and backward updates for tabular accumulating traces.
0
In a finite episode, freeze V, calculate every δ using that V, and accumulate updates without applying them until the end. For each visit, Gᵏλ−V(S_k)=Σ_{t=k}^{T−1}(γλ)^{t−k}δ_t. The trace starts at zero and e_t(s)=γλe_{t−1}(s)+1{S_t=s}.

Step 1 of 2. What is the forward-view increment for state s across all visits?

NumericThree steps and a λ mixture
In a four-transition episode, rewards are 1, 2, −1 and 3, with γ=0.5. Frozen V values for the three intermediate states are 2, 4 and 5, and the terminal value is 0. What is the λ-return from the start with λ=0.5?
NumericBefore reaching the end
In the previous episode, with rewards 1, 2, −1 and 3, γ=0.5 and frozen value 5 at the third intermediate state, compute the three-step target from the start.
QuizAn observation hiding history
Every observed episode is x → x → terminal. The first transition gives reward 1 and the second 0. γ=1 and one shared V(x) entry is used. What are the every-visit MC mean and the batch TD fixed point, respectively?
CodeA trajectory with traces
Implement td_lambda(env, policy, alpha, gamma, lam, trace), tabular online TD(λ) for one episode. env.n_states is positive; env.reset() returns a state index; policy(s) returns an action and env.step(a) returns (next, reward, terminated, truncated). All indices lie between 0 and n_states−1, rewards are finite real numbers, and the episode ends in finitely many steps. Start V and traces at zero. At each transition calculate δ=r+γ·V(next)−V(s), except when terminated is true, when bootstrap is zero even if truncated is also true. Multiply the entire trace by γλ; then add 1 at s for trace='accumulating' or set e[s]=1 for trace='replacing'. Update V[i]+=alpha·δ·e[i] simultaneously for all states. Return V as a list and stop after terminated or truncated, retaining bootstrap for truncation. alpha, gamma and lam are finite real numbers in [0,1]; reject out-of-range values and unsupported trace names with ValueError. Do not reuse traces between calls.
def td_lambda(env, policy, alpha, gamma, lam, trace):
  pass
Shift+Enter to run
[ ]Check the targets and non-Markov exampleBrowser
rewards=[1,2,-1,3]
values=[2,4,5,0]
gamma=lam=.5
returns=[]
for n in range(1,5):
    target=sum(gamma**j*rewards[j] for j in range(n))
    if n<4: target+=gamma**n*values[n-1]
    returns.append(target)
weights=[(1-lam)*lam**j for j in range(3)]+[lam**3]
print('Objetivos de 1 a 4 pasos:',returns)
print('Pesos:',weights,'retorno λ:',sum(a*b for a,b in zip(returns,weights)))
print('Aliasing: MC',sum([1,0])/2,'TD',1/(1-.5)*.5)