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 . Replacing the expectation with an observed transition and the true value with our table gives the temporal-difference error
This is TD(0). Conditional on and with the table frozen, the expectation of is . Sampling noise approximates the root of a Bellman equation. The term 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 is inaccurate. Its variance is not always lower: it depends on the process, the estimate and the quantity compared.
Preparando los paseos reproducibles.
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 , the true values are the probabilities of reaching the right endpoint: from the first to the fifth state they are . RMS error compares the five predictions with these values. Averaging over seeds reduces noise but does not replace independent evaluation. When varying , 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 , batch Monte Carlo fits the mean observed return for each state: and . Batch TD sums TD errors from all transitions and repeatedly applies the batch update. Its fixed point satisfies and .
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 -step return observes several rewards and bootstraps if the episode has not ended:
If the episode ends at , the sum stops at and terminal bootstrapping is omitted. For we obtain TD(0); if 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 is then . Its magnitude is bounded by . With this bound decreases with , although actual bias need not decrease monotonically. Noise and update frequency also change, so lower total error is not guaranteed.
Preparando el barrido reproducible de n pasos.
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 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:
The last term collects all remaining weight, and is the complete return. At the target is one-step; at 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:
Initialize the traces to zero at the start of each episode. A visit adds one, and previous traces decay by 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.
If remains frozen and updates are accumulated until the end, the backward sum of exactly equals the forward sum of for each visit to . This is an algebraic identity, not a convergence claim. In ordinary online TD, 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 and a constant step size, is
Inserting this trace into ordinary TD is insufficient: true online TD(λ) also adds correction terms for changes in estimated value. In the tabular case, 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, , bounded rewards and infinitely many visits to each state of interest. With per-state step sizes satisfying and , TD(0) converges almost surely under standard chain-sampling conditions. Intuitively, 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 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.
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.
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.
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
Step 1 of 2. What do you sum when expanding the discounted errors from t?
Step 1 of 2. What is the forward-view increment for state s across all visits?
def td_lambda(env, policy, alpha, gamma, lam, trace):
pass
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)