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(), 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 -step returns and the -return, and prove that eligibility traces implement TD() (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 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 :
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:
The Bellman expectation equation writes the value as the expectation of a one-step quantity:
Replace the expectation by the one sample you have, and by the current estimate. Moving a fraction toward a noisy sample of an expectation is the Robbins–Monro scheme of stochastic approximation: with suitably shrinking steps, the noise averages out.
Now relate the two errors. Use , then add and subtract :
Unroll to the terminal step , where . If 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.
An episode ends after three steps. With held fixed, its TD errors are , and . How far is the Monte Carlo target from the estimate ?
Show the answer
B.
. TD(0) would move toward a target only above it; Monte Carlo toward one above. The later errors reach only if something carries them back, which is what -step returns and eligibility traces do.
n-step returns and TD(λ)
One real reward, or all of them? The -step return interpolates:
with the TD(0) target and the Monte Carlo return. Its expectation is closer to than is, by a factor in the worst case: . Larger means less bias from the estimate and more variance from the rewards, and intermediate usually learns fastest.
Rather than pick one , average them all with geometric weights. The -return is
where, in an episode, all the weight beyond its end falls on the full return. Updating toward is the forward view of TD(). It needs the future, but an eligibility trace computes the same updates looking backward: each state keeps a trace that jumps by 1 when the state is visited and decays by per step, and each TD error updates every state in proportion to its trace.
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(), backward view. Each step costs one update per state with a nonzero trace; in practice traces below a threshold are dropped.
The -step returns satisfy and . Substitute them into the definition of and collect terms:
Subtract and add and subtract , exactly as for the Monte Carlo error, then unroll:
Sum over the visits to and swap the order of summation; the inner sum is the trace:
With online updating, where values change at every step, the two views differ slightly. True online TD() restores exact equivalence for online updates with a modified ("dutch") trace (van Seijen & Sutton, 2014).
Think first What do and reduce to?
With the trace is the indicator of the current state, so only moves, by : TD(0). With the forward target is the full return , so offline TD(1) performs every-visit Monte Carlo, but incrementally and without storing the episode. 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 and act ε-greedily with respect to them. This is generalized policy iteration with evaluation and improvement interleaved step by step: every update changes , and the next action already uses it. The three classic TD control methods share the update and differ only in the target :
| Method | Target | Learns | Notes |
|---|---|---|---|
| SARSA (Rummery & Niranjan, 1994) | of the behavior policy (on-policy) | uses the next action actually taken: the quintuple | |
| Expected SARSA | for the policy in the sum | removes the variance of sampling (van Seijen et al., 2009) | |
| Q-learning (Watkins, 1989) | , whatever the behavior (off-policy) | expected SARSA with a greedy |
# 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 . The shortest route hugs the edge: 13 steps, return . Moves never slip, , and both agents explore with and learn with .
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 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.
During training Q-learning earns less per episode than SARSA, but after you set it earns more ( against ). Why?
- Setting turns Q-learning's update into SARSA's
- SARSA's values diverge once exploration stops
- 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 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 , the values of the greedy policy, while behaving ε-greedily; its behavior pays for exploration near the edge, its target policy does not. SARSA estimates 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 if every state is visited infinitely often and the step sizes satisfy the Robbins–Monro conditions and (Jaakkola, Jordan & Singh, 1994; Dayan & Sejnowski, 1994). SARSA converges to if, in addition, its policy becomes greedy in the limit while still trying every action infinitely often (Singh et al., 2000).
Write the update of the visited state as a noisy step toward the Bellman backup. The noise is the gap between the sampled target and its expectation, so it has mean zero given the past:
Without the noise this is a damped Bellman backup. is a -contraction in the sup norm (Bellman Equations & Contraction), so each step shrinks the error at the updated state:
With at every state, these contractions compound without limit. The noise enters as , a martingale whose variance is at most when the noise variance is bounded by , so it converges and its tail vanishes. Together they force 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 .
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 toward , a sampled Bellman backup that learns online; the Monte Carlo error is the discounted sum of TD errors.
- -step returns and the -return interpolate between TD(0) and Monte Carlo; eligibility traces implement the -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 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.
An agent with has estimates and . It moves from to and receives reward . With , what is after the TD(0) update?
Show the answer
C.
, so . The estimate moves halfway toward the TD target .
Offline TD() with , applied at the end of each episode, is equivalent to which method?
- TD(0)
- Every-visit Monte Carlo
- Q-learning
- Value iteration
Show the answer
B. Every-visit Monte Carlo
With the -return is the full return , and the forward–backward equivalence says the summed trace updates equal the summed Monte Carlo updates over every visit. Traces let TD(1) do this incrementally.
Why is Q-learning called an off-policy method?
- It does not use a policy to choose actions
- It needs importance-sampling weights to correct for the behavior policy
- It can only learn from data generated by other agents
- Its target uses the greedy next action whatever the behavior does, so it learns while acting ε-greedily
Show the answer
D. Its target uses the greedy next action whatever the behavior does, so it learns while acting ε-greedily
The behavior policy only decides which pairs get updated. The target evaluates the greedy policy, so with enough exploration Q-learning converges to , the values of a policy it never actually follows.
Expected SARSA bootstraps from . If its target policy is greedy with respect to , it becomes:
- SARSA
- Q-learning
- Monte Carlo control
- TD(0) on state values
Show the answer
B. Q-learning
A greedy puts all its weight on , so the expected value is : Q-learning's target. With equal to the ε-greedy behavior policy, expected SARSA is the on-policy method with SARSA's fixed point and less variance.
Tabular Q-learning with a constant step size runs forever in a world whose moves sometimes slip at random. What happens to the Q-table?
- It keeps fluctuating around , because constant steps never average the transition noise away
- It converges exactly to
- It diverges to infinity
- It converges to the values of the ε-greedy policy
Show the answer
A. It keeps fluctuating around , because constant steps never average the transition noise away
Each update moves by times a random error, so the table jitters around forever. Exact convergence needs steps with and 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
- Convergence of Q-Learning · Stochastic approximation and the deadly triad.
- Deep Q-Networks · Replay buffers, target networks and Atari.
- Off-Policy Learning & Importance Sampling · Learning about one policy from another.
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).