skip to content

Temporal-Difference Learning

Updating a value estimate from the very next step instead of waiting for the episode to end. Interviewers use the Monte-Carlo versus TD contrast to test bias-variance thinking.

on this pageshow

questions

4

How does the one-step TD(0) update revise a state-value estimate?

level: middleimportance: must knowfreq 74%

answer

  1. one transition is enough
  2. predicted value versus one-step-better value
  3. the target contains another estimate
  4. delta scaled by a step size
  5. r plus gamma times V of next state

basics

~20 s

After one transition, TD(0) moves the estimate a fraction of the way toward the observed reward plus the discounted estimate of the next state: V(s) <- V(s) + alpha * [r + gamma * V(s') - V(s)]. The bracketed quantity is the TD error.

solid answer

~50 s

TD(0) treats `r + gamma * V(s')` as a stand-in for the true value of `s` and corrects toward it. Concretely: `delta = r + gamma * V(s') - V(s)` is the **TD error**, the gap between what the estimate predicted and what one step of experience plus the next estimate now suggest. The update is `V(s) <- V(s) + alpha * delta`, where `alpha` is a step size in `(0, 1]` that controls how much of the surprise to absorb. The crucial property is that the target contains `V(s')`, another estimate — this is **bootstrapping**, and it is why the update can happen after a single transition instead of at the end of the episode. That makes TD usable online, in continuing tasks with no episode boundary, and cheap in memory. Sutton's driving-home example captures it: you revise your predicted arrival time at each landmark rather than waiting until you park.

code

python · 19 lines
python
import random

V = {"start": 0.0, "mid": 0.0, "goal": 0.0}   # goal is terminal, value stays 0
alpha, gamma = 0.1, 0.9

def step(s):                                   # sampled experience only
    if s == "start":
        return (1.0, "mid") if random.random() < 0.8 else (0.0, "start")
    return (10.0, "goal")

for _ in range(2000):
    s = "start"
    while s != "goal":
        r, s_next = step(s)
        td_error = r + gamma * V[s_next] - V[s]   # delta
        V[s] += alpha * td_error                  # V(s) <- V(s) + alpha * delta
        s = s_next

print({k: round(v, 2) for k, v in V.items()})

go deeper

for a junior

Be ready to write the update from memory and name each symbol: current estimate, step size, reward, discount, next-state estimate. Knowing that TD updates after one step, not one episode, is the core recall.

for a middle

Explain the mechanics: why the target is a one-step-improved prediction, what the step size controls, and why terminal states anchor the table. Expect to be asked what bootstrapping means in your own words.

for a senior

Demonstrate that you have tuned this. Talk about constant versus decaying step sizes in non-stationary environments, how slowly credit propagates back through long chains, and what diverging or oscillating TD errors are telling you.

for a principal

Own the framing of when self-consistent bootstrapped estimation is the right learning signal at all, and what it costs a team in debuggability compared with predicting an observable outcome directly.

## What the update is trying to do We want `V(s)`, an estimate of the expected discounted return from state `s` under the current behaviour. We cannot see that expectation; we can only see experience. TD(0) takes the smallest possible slice of experience — one transition `s -> r, s'` — and uses it to improve the estimate. The reasoning is a consistency requirement. If our estimates were correct, then the value of `s` should equal the immediate reward plus the discounted value of wherever we land. So after observing one transition we can form the **TD target**: ``` target = r + gamma * V(s') ``` and compare it to what we currently believe: ``` delta = r + gamma * V(s') - V(s) # the TD error V(s) = V(s) + alpha * delta # the TD(0) update ``` `gamma` in `[0, 1]` discounts future reward; `alpha` in `(0, 1]` is the step size. If `delta` is positive, the step turned out better than predicted and `V(s)` rises; if negative, it falls; if zero, nothing moves — the estimate was already self-consistent with that transition. ## Reading the pieces **The TD error is a surprise signal.** It is not the prediction error against ground truth — ground truth is never observed — it is the error against a one-step-improved version of the agent's own prediction. Interpreted that way, learning is a long process of removing self-inconsistency from a table of estimates until nothing contradicts anything else. **The step size controls memory.** A constant `alpha` makes the estimate an exponentially weighted average of recent targets, which is what you want in a non-stationary environment. Averaging step sizes that shrink over time (satisfying the usual stochastic-approximation conditions — the sum of step sizes diverges while the sum of their squares converges) are what tabular TD(0) needs to converge to the true value function of the behaviour being followed. **Terminal states have value zero.** When `s'` ends the episode, the target collapses to `r`, which is what anchors the whole table: real reward enters at the terminal edge and propagates backwards through the bootstrapped targets. ## Bootstrapping and why it buys online learning The defining feature is that the target contains an estimate, `V(s')`, rather than only observed quantities. This is **bootstrapping** — building an estimate on top of other estimates. The alternative, Monte-Carlo, waits for the episode to finish and uses the realised return `G` as its target: `V(s) <- V(s) + alpha * [G - V(s)]`. That needs an episode to end, which rules out continuing tasks and delays every update until the end of a possibly very long trajectory. Bootstrapping removes that wait. Sutton's driving-home example is the clearest picture: you leave the office predicting a 30-minute drive, hit unexpected traffic at the first junction, and immediately revise the prediction upward — you do not withhold all learning until you park and know the true duration. Each landmark gives you a new estimate that improves the previous one. The practical consequences are: - **Online, incremental learning.** One transition, one update, constant memory. - **Works in continuing tasks.** No episode boundary required. - **Learns from incomplete sequences.** A truncated or abandoned trajectory still yields useful updates. - **Credit spreads gradually.** Reward information moves back one state per update through the chain of estimates, so with tabular TD(0) a distant reward takes several passes to reach early states. ## The obvious objection Updating an estimate toward a target that contains an estimate sounds circular. Why does it not simply reinforce whatever nonsense the table was initialised with? Because the target is not purely estimate. Each target contains a **real sampled reward**, and the terminal targets contain no bootstrap at all. Real information is injected at every step and, in tabular problems with a fixed policy and a suitable step-size schedule, TD(0) is guaranteed to converge to the true value function. Empirically the bootstrap is a strength rather than a tax: TD-Gammon learned a strong backgammon board evaluation almost entirely from self-play, with each position's value trained against the value of the position that followed it. ## What interviewers listen for Get the direction and the contents right. The target is `r + gamma * V(s')`, **not** `r + gamma * V(s)`, and the update moves `V(s)` a *fraction* `alpha` of the way toward it rather than replacing it. Saying "TD sets the value to the observed reward" or dropping the discount on the bootstrapped term are the two most common wrong answers, and both change what the algorithm converges to.

  • What happens to learning if the step size alpha is held constant instead of decayed?
    A constant step size makes the estimate an exponentially weighted average of recent TD targets: it never fully settles, keeps chasing the latest experience, and retains a residual fluctuation around the true value. That is the right choice in a non-stationary environment where old experience should be forgotten. For convergence to a fixed value function under a fixed policy, you want step sizes that shrink over time.
  • Why is the TD error zero a meaningful stopping signal?
    A TD error of zero means the estimate for that state already equals the reward plus the discounted estimate of the successor, so that transition contains no information the table has not absorbed. When TD errors are near zero across all states the value function is self-consistent with the observed dynamics, which is the fixed point TD(0) is driving toward.
  • How does the update change when the next state is terminal?
    Terminal states have value zero by definition, so the target collapses to the immediate reward `r` with no bootstrapped term. That is where genuine, non-estimated information enters the system. Every other state's value is ultimately anchored by these terminal targets propagating backwards through the chain of bootstrapped updates.

You predict a 30-minute drive home, hit traffic at the first junction and revise to 40 straight away — rather than withholding every lesson until you park.

saying these in an interview costs you the question

  • Writes the target as r plus gamma times V of the current state
  • Says TD replaces the estimate with the observed reward
  • Forgets the discount factor on the bootstrapped term
  • Claims TD needs the episode to finish first
  • Treats the TD error as error against known ground truth

context

open as a page

What separates model-free from model-based reinforcement learning?

level: juniorimportance: should knowfreq 62%

basics

~20 s

A model-based agent has (or learns) the environment's transition and reward dynamics and can plan against them. A model-free agent never builds those dynamics; it estimates values or a policy directly from sampled experience. Temporal-difference learning is model-free.

open as a page

Why is a Monte-Carlo return unbiased while a one-step TD target is biased?

level: middleimportance: should knowfreq 55%

basics

~20 s

A first-visit Monte-Carlo return is an actual sampled return, so on average it equals the true value — unbiased, but noisy because it accumulates every random reward to the end of the episode. A TD target uses the current estimate of the next state, which is wrong early on, so it is biased but far lower variance.

open as a page

How do you choose n in n-step TD returns when the reward arrives far in the future?

level: seniorimportance: nice to knowfreq 28%

basics

~20 s

Pick n on the delay between action and reward. Small n gives low-variance but myopic targets that propagate credit one state per pass; large n propagates credit fast but carries the noise of a long trajectory. Tune n empirically; intermediate values usually beat both extremes.

open as a page