Simple Algorithm
Artificial Intelligence · Hidden Layer · 24 min

Temporal-Difference Learning & Q-Learning

Learning from incomplete episodes.

A Monte Carlo agent learns nothing until an episode ends. A temporal-difference agent learns from every single step, by nudging one guess toward a slightly better guess. That one idea, bootstrapping, gives TD(0), TD(λ\lambda), SARSA and Q-learning, and it explains why two agents trained on the same cliff learn different paths.

What you’ll learn

  • Derive the TD(0) update as a sampled Bellman equation, and compare its bias and variance with Monte Carlo estimation.
  • Define nn-step returns and the λ\lambda-return, and prove that eligibility traces implement TD(λ\lambda) (the forward–backward equivalence).
  • Write SARSA, expected SARSA and Q-learning, and explain on-policy versus off-policy control with the cliff-walking example.
  • State when tabular TD methods converge, and what breaks once values are approximated by functions.

Monte Carlo versus temporal differences

How should an agent estimate the value Vπ(s)V^\pi(s) of a policy from experience alone, without the transition model that dynamic programming needs (Dynamic Programming in RL)? The Monte Carlo answer waits for the episode to end and moves the estimate toward the observed return Gt=Rt+1+γRt+2+⋯G_t=R_{t+1}+\gamma R_{t+2}+\cdots:

V(St)←V(St)+α[Gt−V(St)].V(S_t)\leftarrow V(S_t)+\alpha\big[G_t-V(S_t)\big].

Temporal-difference learning (Sutton, 1988) does not wait. One step later it already has a better guess, the reward it just received plus the discounted estimate of where it landed, and it moves toward that:

V(St)←V(St)+α δt,δt=Rt+1+γV(St+1)−V(St)V(S_t)\leftarrow V(S_t)+\alpha\,\delta_t,\qquad \delta_t=R_{t+1}+\gamma V(S_{t+1})-V(S_t)
δt\delta_t is the TD error. TD(0) updates a guess toward a guess (it bootstraps), so it learns online, from incomplete episodes, and in tasks that never end.
DerivationWhere the TD target comes from, and how it relates to Monte Carlo
  1. Vπ(s)=Eπ[Rt+1+γVπ(St+1) ∣ St=s]V^\pi(s)=\E_\pi\big[R_{t+1}+\gamma V^\pi(S_{t+1})\,\big|\,S_t=s\big]

    The Bellman expectation equation writes the value as the expectation of a one-step quantity:

  2. V(St)←(1−α) V(St)+α[Rt+1+γV(St+1)]V(S_t)\leftarrow(1-\alpha)\,V(S_t)+\alpha\big[R_{t+1}+\gamma V(S_{t+1})\big]

    Replace the expectation by the one sample you have, and VπV^\pi by the current estimate. Moving a fraction α\alpha toward a noisy sample of an expectation is the Robbins–Monro scheme of stochastic approximation: with suitably shrinking steps, the noise averages out.

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

    Now relate the two errors. Use Gt=Rt+1+γGt+1G_t=R_{t+1}+\gamma G_{t+1}, then add and subtract γV(St+1)\gamma V(S_{t+1}):

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

    Unroll to the terminal step TT, where GT=V(ST)=0G_T=V(S_T)=0. If VV is held fixed during the episode, the Monte Carlo error is the discounted sum of the TD errors along the way:

RL Foundations compared the three targets, the exact expectation of dynamic programming, the full return of Monte Carlo and the bootstrapped TD target, and showed that batch TD(0) computes the certainty-equivalence estimate of a Markov model fitted to the data. The identity above adds a sharper picture: TD(0) uses the first term of the sum on the right, Monte Carlo all of them, and the next step builds everything in between.

Check your understanding

An episode ends after three steps. With VV held fixed, its TD errors are δ0=δ1=δ2=0.4\delta_0=\delta_1=\delta_2=0.4, and γ=0.5\gamma=0.5. How far is the Monte Carlo target G0G_0 from the estimate V(S0)V(S_0)?

  1. 0.40.4
  2. 0.70.7
  3. 1.21.2
  4. 0.10.1
Show the answer

B. 0.70.7

G0−V(S0)=δ0+γδ1+γ2δ2=0.4+0.2+0.1=0.7G_0-V(S_0)=\delta_0+\gamma\delta_1+\gamma^2\delta_2=0.4+0.2+0.1=0.7. TD(0) would move V(S0)V(S_0) toward a target only 0.40.4 above it; Monte Carlo toward one 0.70.7 above. The later errors reach S0S_0 only if something carries them back, which is what nn-step returns and eligibility traces do.

n-step returns and TD(λ)

One real reward, or all of them? The nn-step return interpolates:

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

with n=1n=1 the TD(0) target and n≥T−tn\ge T-t the Monte Carlo return. Its expectation is closer to VπV^\pi than VV is, by a factor γn\gamma^n in the worst case: max⁡s∣Eπ[Gt:t+n∣St=s]−Vπ(s)∣≤γnmax⁡s∣V(s)−Vπ(s)∣\max_s\abs{\E_\pi[G_{t:t+n}\mid S_t=s]-V^\pi(s)}\le\gamma^n\max_s\abs{V(s)-V^\pi(s)}. Larger nn means less bias from the estimate and more variance from the rewards, and intermediate nn usually learns fastest.

Rather than pick one nn, average them all with geometric weights. The λ\lambda-return is

Gtλ=(1−λ)∑n≥1λn−1Gt:t+n,0≤λ≤1,G_t^\lambda=(1-\lambda)\sum_{n\ge1}\lambda^{n-1}G_{t:t+n},\qquad0\le\lambda\le1,

where, in an episode, all the weight beyond its end falls on the full return. Updating toward GtλG_t^\lambda is the forward view of TD(λ\lambda). It needs the future, but an eligibility trace computes the same updates looking backward: each state keeps a trace e(s)e(s) that jumps by 1 when the state is visited and decays by γλ\gamma\lambda per step, and each TD error updates every state in proportion to its trace.

text
input: policy π, step size α, discount γ, trace decay λ
V(s) ← 0 for every state s                 # V(terminal) stays 0
repeat for each episode:
    e(s) ← 0 for every state s
    S ← initial state
    while S is not terminal:
        take A ~ π(·|S); observe R and S'
        δ ← R + γ·V(S') − V(S)
        e(S) ← e(S) + 1                     # accumulating trace
        for every state s:
            V(s) ← V(s) + α·δ·e(s)
            e(s) ← γ·λ·e(s)
        S ← S'

Tabular TD(λ\lambda), backward view. Each step costs one update per state with a nonzero trace; in practice traces below a threshold are dropped.

DerivationProof
  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}. Substitute them into the definition of GtλG_t^\lambda and collect terms:

  2. Gtλ−V(St)=δt+γλ(Gt+1λ−V(St+1))=∑k≥t(γλ)k−t δkG_t^\lambda-V(S_t)=\delta_t+\gamma\lambda\big(G^\lambda_{t+1}-V(S_{t+1})\big)=\sum_{k\ge t}(\gamma\lambda)^{k-t}\,\delta_k

    Subtract V(St)V(S_t) and add and subtract γV(St+1)\gamma V(S_{t+1}), exactly as for the Monte Carlo error, then unroll:

  3. ∑t1[St=s]∑k≥t(γλ)k−tδk=∑kδk∑t≤k(γλ)k−t 1[St=s]⏟ek(s)\sum_t\mathbf 1[S_t=s]\sum_{k\ge t}(\gamma\lambda)^{k-t}\delta_k=\sum_k\delta_k\underbrace{\sum_{t\le k}(\gamma\lambda)^{k-t}\,\mathbf 1[S_t=s]}_{e_k(s)}

    Sum over the visits to ss and swap the order of summation; the inner sum is the trace:

  4. With online updating, where values change at every step, the two views differ slightly. True online TD(λ\lambda) restores exact equivalence for online updates with a modified ("dutch") trace (van Seijen & Sutton, 2014).

Think first What do λ=0\lambda=0 and λ=1\lambda=1 reduce to?

With λ=0\lambda=0 the trace is the indicator of the current state, so only V(St)V(S_t) moves, by αδt\alpha\delta_t: TD(0). With λ=1\lambda=1 the forward target is the full return GtG_t, so offline TD(1) performs every-visit Monte Carlo, but incrementally and without storing the episode. λ\lambda is a dial from bootstrapping to sampling, and intermediate values usually work best.

Control: SARSA, expected SARSA and Q-learning

To act well, learn action values Q(s,a)Q(s,a) and act ε-greedily with respect to them. This is generalized policy iteration with evaluation and improvement interleaved step by step: every update changes QQ, and the next action already uses it. The three classic TD control methods share the update Q(St,At)←Q(St,At)+α [Yt−Q(St,At)]Q(S_t,A_t)\leftarrow Q(S_t,A_t)+\alpha\,[Y_t-Q(S_t,A_t)] and differ only in the target YtY_t:

MethodTarget YtY_tLearnsNotes
SARSA (Rummery & Niranjan, 1994)Rt+1+γ Q(St+1,At+1)R_{t+1}+\gamma\,Q(S_{t+1},A_{t+1})QπQ^\pi of the behavior policy (on-policy)uses the next action actually taken: the quintuple (S,A,R,S′,A′)(S,A,R,S',A')
Expected SARSARt+1+γ∑aπ(a∣St+1) Q(St+1,a)R_{t+1}+\gamma\sum_a\pi(a\mid S_{t+1})\,Q(S_{t+1},a)QπQ^\pi for the policy π\pi in the sumremoves the variance of sampling At+1A_{t+1} (van Seijen et al., 2009)
Q-learning (Watkins, 1989)Rt+1+γmax⁡aQ(St+1,a)R_{t+1}+\gamma\max_aQ(S_{t+1},a)Q∗Q^*, whatever the behavior (off-policy)expected SARSA with a greedy π\pi
On-policy methods evaluate the policy that generates the data, exploration included; off-policy methods evaluate a different target policy. One-step Q-learning needs no importance weights: its update conditions on the action taken, and its target does not depend on which next action the behavior picks.
text
# Q(s, a) ← 0 for all s and a; Q(terminal, ·) = 0
# Q-learning (off-policy)
for each episode:
    S ← start
    while S is not terminal:
        A ← ε-greedy action for Q(S, ·)
        take A; observe R and S'
        Q(S, A) ← Q(S, A) + α·[R + γ·max_a Q(S', a) − Q(S, A)]
        S ← S'

# SARSA (on-policy): pick the next action first, then bootstrap from it
for each episode:
    S ← start;  A ← ε-greedy action for Q(S, ·)
    while S is not terminal:
        take A; observe R and S'
        A' ← ε-greedy action for Q(S', ·)
        Q(S, A) ← Q(S, A) + α·[R + γ·Q(S', A') − Q(S, A)]
        S, A ← S', A'

The only difference is the bootstrap: the greedy next action (Q-learning) or the next action actually chosen (SARSA).

Cliff walking: on-policy versus off-policy

Sutton and Barto's cliff walk makes the difference visible. The agent starts at the bottom left of a 4 × 12 grid and must reach the goal at the bottom right; the cells between them are a cliff. Each step costs 1, stepping off the cliff costs 100 more and (in this version) ends the episode, and the goal pays +10+10. The shortest route hugs the edge: 13 steps, return −13+10=−3-13+10=-3. Moves never slip, γ=1\gamma=1, and both agents explore with ε=0.1\varepsilon=0.1 and learn with α=0.25\alpha=0.25.

Which agent is right? Each answers a different question. Q-learning asks what the best return would be if it stopped exploring; SARSA asks what the best return is while it keeps exploring like this. If ε\varepsilon decays toward 0 slowly enough, so that the policy becomes greedy in the limit while every action is still tried infinitely often, SARSA also converges to the optimal policy (Singh et al., 2000). For a system that must keep exploring, such as a robot working near a staircase, SARSA's caution is the point.

Check your understanding

During training Q-learning earns less per episode than SARSA, but after you set ε=0\varepsilon=0 it earns more (−3-3 against −7-7). Why?

  1. Setting ε=0\varepsilon=0 turns Q-learning's update into SARSA's
  2. SARSA's values diverge once exploration stops
  3. Q-learning's values describe the greedy policy, whose edge route is safe once nothing is random; SARSA's describe the ε-greedy policy, for which the top row is safer
  4. Q-learning was trained on more episodes
Show the answer

C. Q-learning's values describe the greedy policy, whose edge route is safe once nothing is random; SARSA's describe the ε-greedy policy, for which the top row is safer

Q-learning estimates Q∗Q^*, the values of the greedy policy, while behaving ε-greedily; its behavior pays for exploration near the edge, its target policy does not. SARSA estimates QQ of the ε-greedy policy it follows, for which a cell beside the cliff really is dangerous. Remove the randomness and the greedy edge route is best.

When TD converges, and where to go deeper

In the tabular case the theory is clean. TD(0) for prediction converges with probability 1 to VπV^\pi if every state is visited infinitely often and the step sizes satisfy the Robbins–Monro conditions ∑tαt=∞\sum_t\alpha_t=\infty and ∑tαt2<∞\sum_t\alpha_t^2<\infty (Jaakkola, Jordan & Singh, 1994; Dayan & Sejnowski, 1994). SARSA converges to Q∗Q^* if, in addition, its policy becomes greedy in the limit while still trying every action infinitely often (Singh et al., 2000).

DerivationWhy tabular TD(0) converges (sketch)
  1. Vt+1(St)=(1−αt) Vt(St)+αt[(TπVt)(St)+wt],E[wt∣past]=0V_{t+1}(S_t)=(1-\alpha_t)\,V_t(S_t)+\alpha_t\big[(T^\pi V_t)(S_t)+w_t\big],\qquad\E[w_t\mid\text{past}]=0

    Write the update of the visited state as a noisy step toward the Bellman backup. The noise wtw_t is the gap between the sampled target and its expectation, so it has mean zero given the past:

  2. ∣Vt+1(St)−Vπ(St)∣≤(1−αt(1−γ)) ∥Vt−Vπ∥∞\big|V_{t+1}(S_t)-V^\pi(S_t)\big|\le\big(1-\alpha_t(1-\gamma)\big)\,\norm{V_t-V^\pi}_\infty

    Without the noise this is a damped Bellman backup. TπT^\pi is a γ\gamma-contraction in the sup norm (Bellman Equations & Contraction), so each step shrinks the error at the updated state:

  3. With ∑tαt=∞\sum_t\alpha_t=\infty at every state, these contractions compound without limit. The noise enters as ∑tαtwt\sum_t\alpha_tw_t, a martingale whose variance is at most σ2∑tαt2<∞\sigma^2\sum_t\alpha_t^2<\infty when the noise variance is bounded by σ2\sigma^2, so it converges and its tail vanishes. Together they force Vt→VπV_t\to V^\pi with probability 1. The Deep Layer lesson Convergence of Q-Learning makes the argument precise for Q-learning, with the optimality operator in place of TπT^\pi.

With function approximation the guarantees weaken. Linear TD with on-policy sampling still converges, to a fixed point near the best linear fit, but the combination of function approximation, bootstrapping and off-policy updates, the deadly triad, can make the weights diverge even when an exact solution exists. Deep RL lives inside the triad: DQN (Mnih et al., 2015) made Q-learning work on Atari with experience replay and a slowly updated target network.

Key takeaways

  • TD(0) moves V(St)V(S_t) toward Rt+1+γV(St+1)R_{t+1}+\gamma V(S_{t+1}), a sampled Bellman backup that learns online; the Monte Carlo error is the discounted sum of TD errors.
  • nn-step returns and the λ\lambda-return interpolate between TD(0) and Monte Carlo; eligibility traces implement the λ\lambda-return incrementally, exactly so for offline updates.
  • SARSA (on-policy), expected SARSA and Q-learning (off-policy) differ only in the bootstrapped target; Q-learning's max learns Q∗Q^* whatever the behavior, at the price of maximization bias.
  • On the cliff, Q-learning learns the optimal edge path but its exploring behavior keeps falling off; SARSA learns a safer path because it values its own exploration.
  • Tabular TD and Q-learning converge with Robbins–Monro step sizes and infinite visits; function approximation plus bootstrapping plus off-policy data (the deadly triad) can diverge.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

An agent with γ=0.8\gamma=0.8 has estimates V(A)=0.5V(A)=0.5 and V(B)=1.0V(B)=1.0. It moves from AA to BB and receives reward 0.10.1. With α=0.5\alpha=0.5, what is V(A)V(A) after the TD(0) update?

  1. 0.80.8
  2. 0.90.9
  3. 0.70.7
  4. 0.30.3
Show the answer

C. 0.70.7

δ=0.1+0.8×1.0−0.5=0.4\delta=0.1+0.8\times1.0-0.5=0.4, so V(A)←0.5+0.5×0.4=0.7V(A)\leftarrow0.5+0.5\times0.4=0.7. The estimate moves halfway toward the TD target 0.90.9.

Question 2

Offline TD(λ\lambda) with λ=1\lambda=1, applied at the end of each episode, is equivalent to which method?

  1. TD(0)
  2. Every-visit Monte Carlo
  3. Q-learning
  4. Value iteration
Show the answer

B. Every-visit Monte Carlo

With λ=1\lambda=1 the λ\lambda-return is the full return GtG_t, and the forward–backward equivalence says the summed trace updates equal the summed Monte Carlo updates α[Gt−V(St)]\alpha[G_t-V(S_t)] over every visit. Traces let TD(1) do this incrementally.

Question 3

Why is Q-learning called an off-policy method?

  1. It does not use a policy to choose actions
  2. It needs importance-sampling weights to correct for the behavior policy
  3. It can only learn from data generated by other agents
  4. Its target uses the greedy next action whatever the behavior does, so it learns Q∗Q^* while acting ε-greedily
Show the answer

D. Its target uses the greedy next action whatever the behavior does, so it learns Q∗Q^* while acting ε-greedily

The behavior policy only decides which pairs get updated. The target R+γmax⁡aQ(S′,a)R+\gamma\max_aQ(S',a) evaluates the greedy policy, so with enough exploration Q-learning converges to Q∗Q^*, the values of a policy it never actually follows.

Question 4

Expected SARSA bootstraps from ∑aπ(a∣S′)Q(S′,a)\sum_a\pi(a\mid S')Q(S',a). If its target policy π\pi is greedy with respect to QQ, it becomes:

  1. SARSA
  2. Q-learning
  3. Monte Carlo control
  4. TD(0) on state values
Show the answer

B. Q-learning

A greedy π\pi puts all its weight on arg max⁡aQ(S′,a)\argmax_aQ(S',a), so the expected value is max⁡aQ(S′,a)\max_aQ(S',a): Q-learning's target. With π\pi equal to the ε-greedy behavior policy, expected SARSA is the on-policy method with SARSA's fixed point and less variance.

Question 5

Tabular Q-learning with a constant step size α=0.5\alpha=0.5 runs forever in a world whose moves sometimes slip at random. What happens to the Q-table?

  1. It keeps fluctuating around Q∗Q^*, because constant steps never average the transition noise away
  2. It converges exactly to Q∗Q^*
  3. It diverges to infinity
  4. It converges to the values of the ε-greedy policy
Show the answer

A. It keeps fluctuating around Q∗Q^*, because constant steps never average the transition noise away

Each update moves QQ by α\alpha times a random error, so the table jitters around Q∗Q^* forever. Exact convergence needs steps with ∑tαt=∞\sum_t\alpha_t=\infty and ∑tαt2<∞\sum_t\alpha_t^2<\infty for every pair, such as one over the visit count. In a deterministic world the targets stop being random and a constant step suffices.

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 & P. Dayan, "Q-learning," Machine Learning 8, 279–292 (1992).
  • G. A. Rummery & M. Niranjan, "On-line Q-learning using connectionist systems," Technical Report CUED/F-INFENG/TR 166, Cambridge University Engineering Department (1994).
  • R. S. Sutton & A. G. Barto, Reinforcement Learning: An Introduction, ch. 6, 7 and 12 (MIT Press, 2nd ed., 2018).