Temporal-Difference Learning

Dive into Deep Learning · §14.3

Temporal-Difference Learning
sampled backups · Q-learning & SARSA · double-sampling bias · Robbins-Monro step sizes · maximization bias · certainty-equivalent planning

Learning to Act Without the Transition Table P

Motivation & Mental Model

Dynamic programming summed over all possible slips using the known tensor P(s' \mid s, a), whereas an agent dropped onto an unknown lake observes only one realized transition per step:

  • Single-sample reality: Commanding down at cell 9 yields one draw (r, s') from the environment, never the full distribution (1/3, 1/3, 1/3) over cells 8, 13, and 10.
  • Stochastic approximation: Sutton (1988) and Watkins (1989) replaced the exact expectation in the Bellman backup with a single observed successor and took a small damped step \alpha toward it.

Why Model-Free Control Learns Action Values Q

State Values vs. Action Values

(\mathcal{T}Q)(s, a) = r(s, a) + \gamma \sum_{s' \in \mathcal{S}} P(s' \mid s, a) \max_{a' \in \mathcal{A}} Q(s', a')

  • Why V^*(s) cannot be sampled: In \max_a \mathbb{E}_{s'}[r + \gamma V(s')], \max_a sits outside the expectation.
  • Why Q^*(s, a) can be sampled: For fixed (s, a), \mathbb{E}_{s'} sits outside \max_{a'} Q(s', a'), making r + \gamma \max_{a'} Q(s', a') an unbiased sample of (\mathcal{T}Q)(s, a).

From Exact Bellman Backups to Sampled Targets

The Q-Learning Backup

Panel (c) vs. Panel (d) shows how Q-learning replaces the environment average with the single observed transition while keeping the greedy maximization at the next state s':

\delta_t = r_t + \gamma \max_{a' \in \mathcal{A}} Q(s_{t+1}, a') - Q(s_t, a_t), \qquad Q(s_t, a_t) \leftarrow Q(s_t, a_t) + \alpha\,\delta_t

  • Temporal-difference (TD) error \delta_t: Measures the discrepancy between the one-step bootstrapped target y_t = r_t + \gamma \max_{a'} Q(s_{t+1}, a') and the current estimate Q(s_t, a_t).

Bootstrapping vs. Monte Carlo Estimation

Bias-Variance Trade-Off in Value Targets

  • Monte Carlo target (R_t = \sum_{k \geq 0} \gamma^k r_{t+k}): Must wait until episode termination; unbiased for behavior Q^{\pi_e}, but accumulates high transition variance over the full episode tail.
  • One-step TD target (y_t = r_t + \gamma \max_{a'} Q(s_{t+1}, a')): Updates online after every single transition with low single-step variance, trading tail noise for current table bias while estimating Q^* off-policy.

Tracing Backward Value Flow Across Visits

Worked Hand Calculation

  • First goal entry (14 \xrightarrow{\textrm{right}} 15): Terminal target y = 1 updates Q(14, \textrm{right}) \leftarrow 0.500.
  • Step into 14 (13 \xrightarrow{\textrm{right}} 14): Bootstraps y = 0.95(0.500) = 0.475, setting Q(13, \textrm{right}) \leftarrow 0.238.
  • Slip to unvisited 10 (14 \xrightarrow{\textrm{right}} 10): Target y = 0 pulls Q(14, \textrm{right}) \leftarrow 0.250, showing why \alpha_n must decay.

Why Q-Learning Is Semi-Gradient, Not Least Squares

The Double-Sampling Problem

L(Q) = \mathbb{E}_d\big[(Q - \mathcal{T}Q)^2\big] + \mathbb{E}_d\big[\textrm{Var}(y \mid s, a)\big]

  • Why full gradient on \delta^2 fails (Baird, 1995): Minimizing empirical \delta_i^2 penalizes transition variance \textrm{Var}(y \mid s, a), pulling stochastic branch values Q(u_1), Q(u_2) toward each other.
  • Semi-gradient fix: Hold y_i = r_i + \gamma \max_{a'} Q(s_i', a') fixed during the step so \mathbb{E}[\delta \mid s, a] = (\mathcal{T}Q)(s, a) - Q(s, a).

Robbins-Monro Step Sizes and Convergence

Averaging Out Transition Noise

At the n-th visit to pair (s, a), setting \alpha_n = 1/n computes the exact sample mean of targets; more generally, Robbins and Monro (1951) require:

\sum_{n=1}^{\infty} \alpha_n = \infty, \qquad \sum_{n=1}^{\infty} \alpha_n^2 < \infty

  • Asymptotic convergence theorem (Watkins & Dayan, 1992): In a finite MDP with \gamma < 1, if every pair (s, a) is visited infinitely often and \alpha_n(s, a) satisfies Robbins-Monro, then Q_n \to Q^* with probability 1.
  • Finite-budget pitfall of \alpha_n = 1/n: Equal weighting gives early targets (bootstrapped when Q was still mostly zero) the same weight as late targets, requiring exponentially many updates in 1/(1-\gamma) (Even-Dar & Mansour, 2003).
  • Polynomial-weight default: Our schedule \alpha_n = 1/(1 + 0.1\,n) satisfies Robbins-Monro while weighting the k-th target in proportion to \approx k^9, rapidly forgetting early zero targets.

Masking Bootstraps on Termination Only

Handling Episode Ends Correctly

When a step lands in s', we must zero the bootstrap \max_{a'} Q(s', a') on physical termination (terminated=True) but keep it on clock truncation (truncated=True):

\delta = r + \gamma\big(1 - \mathbf{1}(s'\text{ terminal})\big)\max_{a'} Q(s', a') - Q(s, a)

  • Terminal holes & goal: Have zero future return, so (1 - terminated) masks out Q[s_next].max().
  • 100-step time limit: Cuts recording on live ice; masking on truncated would falsely drive values near step 100 toward zero.

Epsilon-Greedy Behavior Policy with Tie-Breaking

Ensuring All Pairs Are Tried

To prevent greedy selection from getting stuck on an unvisited zero table or permanently ignoring an underestimated action, the behavior policy \pi_e explores with probability \epsilon:

\pi_e(a \mid s) = \begin{cases} 1 - \epsilon + \epsilon / |\mathcal{A}| & \text{if } a = \mathrm{argmax}_{a'} Q(s, a') \\ \epsilon / |\mathcal{A}| & \text{otherwise} \end{cases}

def epsilon_greedy(q, epsilon, rng):
    """Explore with probability epsilon, else act greedily on the values q."""
    if rng.random() < epsilon:
        return int(rng.integers(len(q)))
    # Ties are coin flips: np.argmax would always pick action 0 on a zero
    # table, and an agent that only ever moves left never finds the goal.
    return int(rng.choice(np.flatnonzero(q == q.max())))
  • Why random tie-breaking is essential: On an all-zero table, np.argmax deterministically returns index 0 (left), whereas breaking ties uniformly explores even when \epsilon is small.

The Tabular Q-Learning Training Loop

Implementation in NumPy

q_learning decays \epsilon linearly from 1.0 to 0.05 over the first half of training and scales each pair’s step size by its visit count visits[s, a]:

for episode in range(num_episodes):
    s, done, ret = env.reset()[0], False, 0.0
    while not done:
        a = epsilon_greedy(Q[s], epsilon(episode), rng)
        s_next, r, terminated, truncated, _ = env.step(a)
        visits[s, a] += 1
        delta = r + gamma * (1 - terminated) * Q[s_next].max() - Q[s, a]
        Q[s, a] += alpha(visits[s, a]) * delta
        s, done, ret = s_next, terminated or truncated, ret + r
  • Pure index arithmetic: Each environment step updates a single table entry Q[s, a] in O(|\mathcal{A}|) time using only (s, a, r, s_next, terminated).

Why the Training Curve Plateaus Near 0.50

Behavior Return vs. Greedy Evaluation

Across 5 seeds of 4{,}000 episodes on slippery FrozenLake, the 200-episode moving average of training returns climbs and flattens near 0.50:

  • What the curve actually measures: Training returns grade the behavior policy \pi_e, which still takes a random action one step in twenty (\epsilon = 0.05) after episode 2{,}000.
  • The exploration tax: Even the exact optimal policy \pi^*, when forced to act randomly at \epsilon = 0.05, sees its 100-step success rate drop from 73.0\% to 54.2\%.

Grading Learned Tables Against Exact V* and Q*

Exact Model Evaluation

Evaluating the learned greedy policies \mathrm{argmax}_a \hat{Q}(s, a) with \epsilon = 0 via exact policy evaluation reveals that every seed recovered an optimal policy:

  max_s |V_Qhat(s) - V*(s)|: [0.019 0.012 0.021 0.008 0.006]
      max_(s,a) |Qhat - Q*|: [0.131 0.079 0.113 0.087 0.075]
max_s V*(s) - Q*(s, greedy): [0. 0. 0. 0. 0.]
greedy success in 100 steps: [0.73 0.73 0.73 0.73 0.73]
success of pi* 0.730, of pi* at epsilon = 0.05 0.537; median environment steps 95,569
  • Zero greedy regret: Every seed achieves 0.000 regret under Q^* and the full 73.0\% success rate after a median of \approx 96{,}000 environment steps.
  • Asymmetric error: State values \max_a \hat{Q}(s, a) match V^* within 0.03, whereas suboptimal action entries have larger error (0.05–0.17) because they are visited only during random exploration steps.

Learned Q-Table vs. Exact Value Iteration

Visualizing the Greedy Policy

Comparing seed 0’s learned values \max_a \hat{Q}(s, a) and greedy commands against exact value iteration confirms the slip-aware strategy:

  • Exact tie resolution at cell 6: Seed 0 commands right (>) at cell 6 while value iteration picked left (<); both actions have identical Q^*(6, \textrm{left}) = Q^*(6, \textrm{right}) and 1/3 hole risk.

Step-Size Schedules on Calm vs. Slippery Ice

Finite-Budget Convergence Dynamics

On deterministic calm ice, targets have zero transition variance so constant \alpha = 0.9 solves the lake in 3{,}500 steps; on slippery ice, tracking Q(s_0, \textrm{left}) against Q^*(s_0, \textrm{left}) = 0.180 separates three schedules:

  • Constant \alpha = 0.9: Never settles, oscillating wildly between 0.05 and 0.25+ as individual slips arrive.
  • Sample mean 1/(1+n): Stays trapped below 0.03 because early zero targets retain full 1/n weight.
  • Default 1/(1+0.1n): Decays slowly enough to forget early zeros and settles near 0.180.

alpha = 0.9 (constant): final estimates [0.056 0.221 0.206 0.265 0.236]
alpha =  1/(1 + 0.1 n): final estimates [0.19  0.186 0.195 0.184 0.18 ]
alpha =      1/(1 + n): final estimates [0.003 0.024 0.008 0.009 0.002]
peak of each 1/(1 + 0.1 n) run:  [0.228 0.291 0.262 0.324 0.205]

Off-Policy Q-Learning vs. On-Policy SARSA

Target Policy vs. Behavior Policy

\delta_{\textrm{Q}} = r + \gamma \max_{a'} Q(s', a') - Q(s, a) \delta_{\textrm{SARSA}} = r + \gamma\,Q(s', a') - Q(s, a)

  • Off-policy (Q-learning): Learns Q^* for the greedy target policy regardless of which behavior policy generated (s, a, r, s').
  • On-policy (SARSA): Bootstraps from the action a' \sim \pi_e(\cdot \mid s') actually taken next, converging to Q^{\pi_e}.

Maximization Bias and Double Q-Learning

Why Noisy Maxima Overshoot

In the step-size trace of Q(s_0, \textrm{left}) above, exact backups from zero approach 0.180 monotonically from below, yet Q-learning overshoots to 0.22–0.33 between episodes 500 and 1,500:

\mathbb{E}\Big[\max_{a' \in \mathcal{A}} \hat{Q}(s', a')\Big] \geq \max_{a' \in \mathcal{A}} \mathbb{E}\big[\hat{Q}(s', a')\big]

  • Jensen’s inequality on \max: Taking the maximum over noisy estimates selects whichever action currently has a positive estimation error, biasing every bootstrapped target upward.
  • Double Q-learning (van Hasselt, 2010): Maintains two independent tables \hat{Q}_A and \hat{Q}_B, using \hat{Q}_A to select a^* = \mathrm{argmax}_{a'} \hat{Q}_A(s', a') and \hat{Q}_B(s', a^*) to evaluate its target, which eliminates upward maximization bias.

Certainty-Equivalent Planning in a Learned Model

Sample Efficiency: Model-Free vs. Model-Based

Instead of discarding each transition (s, a, r, s') after one TD step, we can tally empirical transition counts N(s, a, s') into \hat{P}(s' \mid s, a) = N(s, a, s')/N(s, a) and run value iteration on (\hat{P}, \hat{r}):

500 episodes, median 9,984 steps (medians over 5 seeds)
  Q-learning:        max |V - V*| 0.084, success 0.486
  planning in model: max |V - V*| 0.096, success 0.639
2000 episodes, median 47,282 steps (medians over 5 seeds)
  Q-learning:        max |V - V*| 0.023, success 0.730
  planning in model: max |V - V*| 0.011, success 0.730
  • Global vs. local propagation: At 500 episodes (\approx 10{,}000 steps), planning in \hat{P} reaches a 63.9\% median success rate vs. 48.6\% for Q-learning because value iteration sweeps rewards across all recorded transitions simultaneously.

Concept Check: Temporal-Difference Control

Check Your Understanding

Test your understanding of TD updates, step sizes, and empirical models:

  1. Hand TD update: Suppose Q(14, \textrm{right}) = 0.25 and on the next visit right slides into the terminal goal (r = 1). With \alpha = 0.5, what is the TD error \delta and the updated entry?
  2. Robbins-Monro conditions: Why does \alpha_n = 1/(1 + n) satisfy the Robbins-Monro convergence theorem yet perform poorly after 4{,}000 episodes on slippery FrozenLake?
  3. Model-based pitfall: In certainty-equivalent planning, what does the empirical kernel \hat{P} assume about a state-action pair (s, a) that was tried only once and happened to slip into a hole?

Answers:

  1. Since the goal is terminal, the target is y = 1.0, the TD error is \delta = 1.0 - 0.25 = +0.75, and Q(14, \textrm{right}) \leftarrow 0.25 + 0.5(0.75) = 0.625.
  2. \alpha_n = 1/(1+n) weights all targets equally (1/n sample mean); because early targets are bootstrapped from an all-zero table, it takes exponentially many visits in 1/(1-\gamma) = 20 to wash out those zeros.
  3. With N(s, a) = 1, \hat{P}(\textrm{hole} \mid s, a) = 1/1 = 1.0; the planner trusts the empirical estimate completely and treats (s, a) as a guaranteed hole until exploration forces another visit.

Summary: Model-Free and Model-Based Tabular Control

Key Takeaways

Method Target / Update Rule Policy Type & Key Properties
Monte Carlo Q(s_t, a_t) \leftarrow Q + \alpha(R_t - Q(s_t, a_t)) Unbiased target; high variance over full episode tail
SARSA Q(s, a) \leftarrow Q + \alpha(r + \gamma Q(s', a') - Q(s, a)) On-policy TD; learns Q^{\pi_e} including exploration risk
Q-Learning Q(s, a) \leftarrow Q + \alpha(r + \gamma \max_{a'} Q(s', a') - Q(s, a)) Off-policy semi-gradient TD; converges to Q^* under Robbins-Monro
Double Q-Learning y = r + \gamma Q_B(s', \mathrm{argmax}_{a'} Q_A(s', a')) Decouples action selection from evaluation to remove max bias
Empirical Planning Solve V = \mathcal{T}_{\hat{P}, \hat{r}} V on \hat{P} = N(s,a,s')/N(s,a) High sample efficiency; requires O(|\mathcal{S}|^2|\mathcal{A}|) model storage