Monte Carlo and temporal-difference learning¶
Without a model of the world you can still learn values, from experience alone. Monte Carlo methods wait until an episode ends and average the returns they actually saw. Temporal-difference methods update a guess from the next guess, one step later, without waiting. That second idea, learning a prediction from a later prediction, is the one most specific to reinforcement learning, and it runs inside Q-learning, actor-critic, PPO's value head and, by most accounts, the dopamine system.
10,000 ft
Dynamic programming computes values exactly but needs the transition probabilities. Real agents rarely have them: nobody hands a robot, a game player or a recommender the equations of its world. This page is where reinforcement learning becomes learning. Monte Carlo (MC) methods estimate values by averaging sampled returns. Temporal-difference (TD) methods, introduced by Sutton (1988), combine Monte Carlo's sampling with DP's bootstrapping. Sutton and Barto open their TD chapter with: "If one had to identify one idea as central and novel to reinforcement learning, it would undoubtedly be temporal-difference (TD) learning." TD made TD-Gammon a world-class backgammon player in the early 1990s, it is the critic in every actor-critic method, it becomes Q-learning when applied to the optimality equation, and its λ-returns reappear as the generalised advantage estimation (GAE) used in RLHF with PPO. In neuroscience, the TD error turned out to resemble the firing of dopamine neurons.
2,000 ft
Every method on this page updates an estimate towards a target: \(V(S_t) \leftarrow V(S_t) + \alpha\,[\text{target} - V(S_t)]\), the same rule as the bandit average. They differ only in the target.
- Monte Carlo: target = the actual return \(G_t\). Unbiased, high variance, must wait for the episode to end.
- TD(0): target = \(R_{t+1} + \gamma V(S_{t+1})\). Biased by the current guess, low variance, updates every step, exploits the Markov property.
- n-step TD and TD(λ) interpolate: use \(n\) real rewards then bootstrap, or average all such targets with weights \((1-\lambda)\lambda^{n-1}\). Eligibility traces implement TD(λ) online.
- Control applies the same targets to action values inside generalised policy iteration: MC control, SARSA (on-policy), Expected SARSA, and Q-learning (off-policy).
- Off-policy learning from another policy's data reweights returns by importance sampling ratios \(\prod \pi/b\), whose variance can explode.
Ground level¶
Learning from experience¶
The prediction problem: given a policy \(\pi\), estimate \(v_\pi\) (or \(q_\pi\)) from episodes generated by following \(\pi\), without knowing \(p(s', r \mid s, a)\). The control problem: find a good policy the same way. As in DP, control will be prediction plus improvement, so prediction comes first.
Throughout, we use Sutton and Barto's random walk (their Example 6.2), a Markov reward process with no decisions so that only prediction matters. Five states A–E in a row; every episode starts in C and steps left or right with probability ½; leaving on the left gives reward 0, leaving on the right gives reward 1; every other reward is 0 and \(\gamma = 1\). The value of a state is therefore the probability of exiting right: \(v(\text{A}), \dots, v(\text{E}) = \tfrac16, \tfrac26, \tfrac36, \tfrac46, \tfrac56\). A learner sees only trajectories such as C, B, C, D, E, exit-right.
Monte Carlo prediction: average what actually happened¶
Value is expected return, so estimate it by averaging returns. For each episode, compute the return \(G_t\) that followed each visit to each state, and move that state's estimate towards it:
With \(\alpha = 1/N(S_t)\) this is the running sample mean; with constant \(\alpha\) it is an exponentially weighted one. First-visit MC uses only the first visit to \(s\) in each episode (each return is then an independent, unbiased sample of \(v_\pi(s)\)); every-visit MC uses all visits (slightly biased per episode, also consistent, and simpler with function approximation).
Monte Carlo has three properties worth naming, because TD will trade each of them away:
- Unbiased. \(G_t\) is a sample of exactly the quantity you want; nothing in the target depends on your current estimates.
- High variance. \(G_t\) sums many random rewards and transitions. In a long episode its variance can dwarf the differences you are trying to learn.
- Episode-bound and Markov-free. You can only update when the episode ends, which rules out continuing tasks; but MC never uses the state of the next step, so it does not care whether your states are Markov.
Monte Carlo is the method behind the "average many rollouts" evaluations you will meet everywhere: the MC check of \(v_\pi(\text{Fresh}) = 15.05 \pm 0.02\) on the MDP page, rollouts in game-tree search, and REINFORCE's use of full returns in policy gradients.
TD(0): update a guess from a guess¶
The return obeys \(G_t = R_{t+1} + \gamma G_{t+1}\), and in expectation the tail \(G_{t+1}\) is \(v_\pi(S_{t+1})\). TD replaces the tail by your current estimate of it and updates as soon as the next state is known:
Using an estimate to update an estimate is called bootstrapping. The target is a sample of the right-hand side of the Bellman expectation equation: DP's full backup with the expectation over \(s'\) replaced by the one \(s'\) you observed.
One episode by hand. Start with every \(V = 0.5\) and \(\alpha = 0.1\). The episode is C → D → E → exit right (reward 1).
| Transition | TD(0) target | TD error | TD(0) update | Monte Carlo update (\(G = 1\) for every state) |
|---|---|---|---|---|
| C → D, r = 0 | \(0 + V(\text{D}) = 0.5\) | 0 | \(V(\text{C})\) stays 0.5 | \(V(\text{C}) = 0.5 + 0.1(1 - 0.5) = 0.55\) |
| D → E, r = 0 | \(0 + V(\text{E}) = 0.5\) | 0 | \(V(\text{D})\) stays 0.5 | \(V(\text{D}) = 0.55\) |
| E → exit, r = 1 | \(1 + 0 = 1\) | 0.5 | \(V(\text{E}) = 0.55\) | \(V(\text{E}) = 0.55\) |
Monte Carlo credits the whole path with the final success at once. TD changes only E, the state right before the reward; the news reaches D the next time an episode passes from D to E, and C after that. TD propagates information backwards one step per visit, like the DP sweeps on the previous page, except that it moves only along the transitions you actually experience.
Driving home
You leave the office expecting a 30-minute drive. It starts raining, and at the car you now expect 40 minutes in total. Monte Carlo waits until you are home to learn anything about how good "leaving the office" was. TD updates the moment your prediction changes: the change from 30 to 40 is the error signal. This is Sutton and Barto's Example 6.1. Each prediction is trained towards the next one, and only the last is trained towards reality.
Head to head on the random walk¶
Run both methods for 100 episodes, 200 independent runs, from \(V = 0.5\) everywhere, and measure the root-mean-square error against the true values (the code is in Build it):
| Method | step size \(\alpha\) | RMS error after 10 episodes | after 50 | after 100 |
|---|---|---|---|---|
| TD(0) | 0.05 | 0.174 | 0.054 | 0.034 |
| TD(0) | 0.10 | 0.128 | 0.051 | 0.055 |
| Monte Carlo | 0.02 | 0.196 | 0.110 | 0.082 |
| Monte Carlo | 0.04 | 0.178 | 0.107 | 0.110 |
TD wins at every step size tried, in speed and in final error. No theorem says TD always learns faster than MC, but on Markov problems it usually does, and the next section shows why.
Why TD wins here: batch updating and certainty equivalence¶
Freeze the data. Replay a fixed batch of episodes over and over, applying the summed updates after each pass, until the values stop moving (batch updating). Both methods then converge, but to different answers. Sutton and Barto's Example 6.4 ("You are the predictor") makes it stark with eight episodes:
- once: A, reward 0, → B, reward 0, → end;
- six times: B, reward 1, → end;
- once: B, reward 0, → end.
Everyone agrees \(V(\text{B}) = 6/8 = 0.75\). For A there are two defensible answers, and the two methods pick different ones (computed in Build it):
| \(V(\text{A})\) | \(V(\text{B})\) | Reasoning | |
|---|---|---|---|
| Batch Monte Carlo | 0.000 | 0.750 | The one return observed from A was 0. This minimises squared error on the training data. |
| Batch TD(0) | 0.750 | 0.750 | A always led to B with reward 0, and B is worth 0.75. This is the value under the most likely model of the process. |
Batch TD computes the certainty-equivalence estimate: fit the maximum-likelihood Markov model (empirical transition frequencies and mean rewards), then solve its Bellman equation exactly, as if the model were certain. Batch MC ignores the Markov structure and just fits the observed returns. If the process really is Markov, the TD answer generalises better: the next time you see A, 0.75 is the better prediction. That is the source of TD's advantage, and also its weakness: if the states are not Markov, TD's model-based reasoning is built on a false premise, and MC's model-free averaging is safer.
n-step TD: a dial between the two¶
There is nothing special about bootstrapping after exactly one step. The n-step return uses \(n\) real rewards and then the current estimate:
with \(G_{t:t+n} = G_t\) if the episode ends before \(t+n\). \(n = 1\) is TD(0); \(n = \infty\) is Monte Carlo. The update for \(S_t\) has to wait \(n\) steps for its rewards.
On Sutton and Barto's 19-state random walk (their Example 7.1: reward −1 for exiting left, +1 for exiting right, start in the middle), sweeping the step size for each \(n\) and measuring the RMS error averaged over the first 10 episodes and 100 runs:
| \(n\) | 1 | 2 | 4 | 8 | 16 | 32 | 512 (≈ MC) |
|---|---|---|---|---|---|---|---|
| best \(\alpha\) | 0.80 | 0.60 | 0.40 | 0.25 | 0.15 | 0.075 | 0.02 |
| RMS error | 0.345 | 0.275 | 0.261 | 0.274 | 0.309 | 0.361 | 0.488 |
An intermediate \(n\) beats both extremes. Short \(n\) propagates information slowly (one step per visit); long \(n\) is noisy and forces a small step size. This U-shape, best somewhere in the middle, is the most robust empirical regularity in this part of RL, and it is why DQN's successors use 3-step returns and why PPO uses λ-returns.
TD(λ) and eligibility traces¶
Instead of choosing one \(n\), average all of them. The λ-return weights the \(n\)-step return by \((1-\lambda)\lambda^{n-1}\), weights that sum to 1:
\(\lambda = 0\) gives TD(0); \(\lambda = 1\) gives the Monte Carlo return. Updating towards \(G^\lambda_t\) is the forward view of TD(λ): conceptually clean, but it looks into the future.
The backward view does the same work online with an eligibility trace, a short-term memory of which states were visited recently. Every state's trace decays by \(\gamma\lambda\) each step, and the visited state's trace is bumped by 1. Every TD error then updates all states in proportion to their traces:
If the values are held fixed during an episode, the sum of the backward-view updates over the episode equals the forward-view update exactly (derivation in the maths). With updates applied online they differ slightly; true online TD(λ) (van Seijen and Sutton, 2014) uses a modified "dutch" trace that makes the online algorithm match an online forward view exactly.
On the same 19-state walk, with accumulating traces and the best step size for each λ:
| λ | 0 | 0.4 | 0.8 | 0.9 | 0.95 | 1 |
|---|---|---|---|---|---|---|
| best \(\alpha\) | 0.80 | 0.70 | 0.30 | 0.20 | 0.10 | 0.02 |
| RMS error (first 10 episodes) | 0.345 | 0.271 | 0.260 | 0.288 | 0.334 | 0.501 |
The same U-shape as \(n\)-step TD, with almost the same best error. At \(\lambda = 1\) with large step sizes (\(\alpha \ge 0.6\)) accumulating traces diverged: a state visited many times in one episode builds a trace above 1, and the update overshoots. Replacing traces (reset to 1 on a visit instead of adding 1; Singh and Sutton, 1996) avoid this.
GAE is TD(λ) for advantages
Schulman et al.'s Generalized Advantage Estimation (2015) estimates the advantage of each action as \(\hat A_t = \sum_{k \ge 0} (\gamma\lambda)^k \delta_{t+k}\), the discounted sum of future TD errors of a learned value function. That is exactly \(G^\lambda_t - V(S_t)\) from the derivation below. Its λ (typically 0.95) is this page's λ, chosen for the same bias–variance reason. Read section 3 (the estimator) and the γ–λ sweeps in section 6.3 alongside actor-critic and PPO.
From prediction to control: SARSA and its relatives¶
For control, learn action values \(Q(s, a)\) instead of \(V(s)\), so that improvement needs no model (the DP page needed \(p\) to act greedily on \(V\)). Then run generalised policy iteration: improve the policy towards greedy with respect to \(Q\) after every episode or every step, while evaluation chases the moving policy. Two practical issues appear immediately.
Exploration. A greedy policy never tries the actions it currently rates low, so their \(Q\) values are never corrected: the bandit lock-in again. Either start episodes from random state–action pairs (exploring starts, rarely possible outside simulation) or keep the policy ε-soft, for example ε-greedy. Convergence to the optimal policy needs the exploration to fade slowly: GLIE (greedy in the limit with infinite exploration), such as \(\varepsilon_k = 1/k\).
Which target. All the control methods use \(Q(S_t, A_t) \leftarrow Q(S_t, A_t) + \alpha[\text{target} - Q(S_t, A_t)]\):
SARSA is TD(0) on action values. It uses the quintuple \((S_t, A_t, R_{t+1}, S_{t+1}, A_{t+1})\), which gives it its name: the next action \(A_{t+1}\) is the one the agent will really take. It evaluates the policy it is following, exploration included, and with GLIE exploration it converges to the optimal policy (Singh, Jaakkola, Littman and Szepesvári, 2000). Expected SARSA replaces the sampled \(Q(S', A')\) by its expectation under the policy, removing the variance from the choice of \(A'\). Q-learning uses the greedy max and learns the optimal values while behaving any other way.
One update, three targets. Take \(Q(s,a) = 2.0\), reward \(r = 1\), next-state values \(Q(s', \cdot) = (5.0, 3.0, -1.0)\), \(\gamma = 0.9\), \(\alpha = 0.1\), an ε-greedy policy with \(\varepsilon = 0.1\) over 3 actions, and suppose the ε-greedy draw picks the third action next.
| Method | target | new \(Q(s,a)\) |
|---|---|---|
| SARSA | \(1 + 0.9 \times (-1.0) = 0.10\) | \(2.0 + 0.1(0.10 - 2.0) = 1.810\) |
| Expected SARSA | \(1 + 0.9\,(0.933 \times 5 + 0.033 \times 3 + 0.033 \times (-1)) = 5.26\) | \(2.326\) |
| Q-learning | \(1 + 0.9 \times 5.0 = 5.50\) | \(2.350\) |
SARSA is pulled down by the exploratory move it actually made; Q-learning ignores it; Expected SARSA averages over the moves it might make. That one difference is why, on the cliff-walking task, SARSA learns a safe path away from the edge while Q-learning learns the optimal path along it and falls off during training (Q-learning and DQN).
Off-policy learning and importance sampling¶
Often the data come from a different policy than the one you want to evaluate: logged data from yesterday's system, an exploratory behaviour policy, a human demonstrator. Call the data-generating policy \(b\) (behaviour) and the policy of interest \(\pi\) (target). Returns from \(b\) have the wrong distribution, but you can reweight them. The probability of a trajectory under a policy is the product of policy probabilities and transition probabilities; the transitions are the same under both policies and cancel in the ratio, leaving
You never need the model, only the two policies' action probabilities. Averaging \(\rho G\) gives ordinary importance sampling (unbiased); dividing by the sum of the ratios instead of the count gives weighted importance sampling (biased, consistent, and far more stable).
How bad the variance gets. Suppose \(\pi\) always takes action "right", \(b\) picks left or right with probability ½, and episodes are 10 steps long with reward 1 only if every step went right. Then \(v_\pi = 1\). Under \(b\), a matching episode has probability \(2^{-10} = 1/1024\) and ratio \(2^{10} = 1024\); every other episode has ratio 0. Ordinary IS is unbiased, \(\mathbb{E}[\rho G] = 1\), but each sample has standard deviation \(\sqrt{1024 - 1} \approx 32\), so even 1,000 episodes leave a standard error of about 1.0, as large as the value itself; and in 38% of such batches no episode matches and the estimate is exactly 0. Weighted IS returns exactly 1 whenever at least one episode matches (62% of batches of 1,000) and is undefined otherwise. The ratio grows exponentially with the horizon, which is why practical off-policy methods avoid long products:
- Q-learning needs no ratios at all, because its target does not depend on which action the behaviour policy takes next.
- Per-decision and truncated ratios (Retrace, V-trace) clip each factor to keep variance bounded, at some cost in bias.
- PPO uses a one-step ratio \(\pi_\theta(a\mid s)/\pi_{\text{old}}(a\mid s)\) and clips it, the same idea for policy updates (actor-critic and PPO).
- Offline RL must evaluate policies from fixed logs, where these variance problems are central (offline RL and RL for language models).
With function approximation, and the deadly triad¶
Tables do not scale. Replace \(V(s)\) by \(\hat v(s; \mathbf{w})\) and turn each update into a step on the weights:
This is called semi-gradient TD: it differentiates the prediction but treats the target as a constant, even though the target also depends on \(\mathbf{w}\). It is not gradient descent on any objective, and that matters. For on-policy data and linear features it still converges, to the TD fixed point, whose error is at most \(\frac{1}{1-\gamma}\) times the best error the features allow (Tsitsiklis and Van Roy, 1997; Sutton and Barto eq. 9.14). Monte Carlo with the same features converges to the best error itself: the bias of bootstrapping, made quantitative.
Combine all three of function approximation, bootstrapping and off-policy training, and the weights can diverge to infinity even on tiny problems where a perfect solution exists (Baird's counterexample, 1995). Sutton and Barto call this combination the deadly triad; any two are safe. Deep Q-learning has all three, which is why DQN needed a target network and experience replay, and why the theory of deep RL is still incomplete.
TD in the brain¶
In the 1990s, recordings from monkeys showed that midbrain dopamine neurons fire at an unexpected reward; after learning, they fire at the cue that predicts the reward instead and no longer at the reward itself; and when a predicted reward is omitted, their firing dips below baseline at the moment the reward should have come. Schultz, Dayan and Montague (1997) pointed out that this is exactly the behaviour of a TD error \(\delta_t\): positive when things are better than predicted, zero when the prediction is right, negative when worse, and moving back in time to the earliest reliable predictor. The reward-prediction-error hypothesis of dopamine is one of the clearest cases of a machine-learning algorithm explaining biological data; for the wider two-way traffic between neuroscience and AI, see brains and machines.
First principles¶
Why bootstrapping is allowed at all. The true value function satisfies \(v_\pi(s) = \mathbb{E}[R_{t+1} + \gamma v_\pi(S_{t+1}) \mid S_t = s]\). So if you already had \(v_\pi\), the TD target would be an unbiased sample of \(v_\pi(s)\). TD's target is biased only because \(V\) is not yet \(v_\pi\), and the expected TD update is exactly DP's expected update, a contraction towards \(v_\pi\). Sampling adds noise, and a decreasing step size averages the noise away (stochastic approximation, the same theory as stochastic gradient descent). So TD is "DP on samples": the fixed point is right, the noise is controlled, and the bias vanishes as the estimates improve.
Why TD has lower variance. The Monte Carlo target \(G_t\) contains the randomness of every future reward and transition. The TD target contains the randomness of one reward and one transition; everything after that is summarised by \(V(S_{t+1})\), a number, not a random variable. The price is that the number is wrong while learning is incomplete. The n-step and λ dials set how much future randomness you accept in exchange for less dependence on your own errors.
Why TD exploits the Markov property and MC does not. TD's target uses \(V(S_{t+1})\), which is the same whichever way you reached \(S_{t+1}\). That pooling of evidence across paths is exactly the certainty-equivalence computation, and it is correct only if the future depends on the past through the state alone. MC's target is the return that followed this particular visit, so it is correct for any process, Markov or not, and it pays for that generality with variance and with learning nothing until the end.
Why credit assignment needs traces or patience. When a reward arrives, the actions that caused it may lie many steps back. TD(0) gives credit only to the previous state; the credit travels back one step each time the path is revisited, which can take many episodes. Traces broadcast the error to all recently visited states at once, with credit decaying by how long ago they were visited, a computationally cheap stand-in for remembering the whole trajectory. Every long-horizon method, from GAE in PPO to the per-token credit problem in RL for language models, is a choice on this axis.
The maths¶
Notation
Episodes \(S_0, A_0, R_1, S_1, \dots, S_T\); return \(G_t = \sum_{k=0}^{T-t-1}\gamma^k R_{t+k+1}\); TD error \(\delta_t = R_{t+1} + \gamma V(S_{t+1}) - V(S_t)\) with \(V(\text{terminal}) = 0\); step size \(\alpha\); trace \(z_t(s)\); behaviour policy \(b\), target policy \(\pi\).
Stochastic approximation: when do the updates converge?
Every update on this page has the form \(V \leftarrow V + \alpha_n(\text{target} - V)\) with a noisy target. For tabular TD(0) with a fixed policy, \(V\) converges to \(v_\pi\) with probability 1 if every state is visited infinitely often and each state's step sizes satisfy the Robbins–Monro conditions
(the first lets the estimate travel any distance, the second makes the noise die out; \(1/n\) satisfies both). Convergence in the mean was shown by Sutton (1988) and with probability 1 by Dayan (1992); Jaakkola, Jordan and Singh (1994) and Tsitsiklis (1994) gave general proofs. With constant \(\alpha\) the estimates do not converge but fluctuate around \(v_\pi\) with variance of order \(\alpha\), which is what the plateaus in the random-walk figure show.
Derivation: batch TD(0) converges to the certainty-equivalence estimate
In batch mode the values stop changing when, for every state \(s\), the summed TD errors over all its visits in the batch are zero:
where \(N(s)\) is the visit count, \(\hat p(s' \mid s)\) the fraction of visits to \(s\) followed by \(s'\), and \(\hat r(s)\) the average reward observed after \(s\). That is the Bellman equation of the maximum-likelihood model. On the A/B batch: \(\hat p(\text{B}\mid\text{A}) = 1\), \(\hat r(\text{A}) = 0\), so \(V(\text{A}) = V(\text{B}) = \hat r(\text{B}) = 6/8\).
Batch MC instead stops when \(\sum_{i:S_i=s}(G_i - V(s)) = 0\), so \(V(s)\) is the mean observed return from \(s\): the least-squares fit to the data, which ignores what is known about \(s'\).
The n-step error-reduction property
For any \(V\), the expected \(n\)-step return is closer to \(v_\pi\) than \(V\) is, by a factor \(\gamma^n\) in the worst state:
Proof: \(\mathbb{E}_\pi[G_{t:t+n} \mid S_t = s] - v_\pi(s) = \gamma^n\,\mathbb{E}_\pi[V(S_{t+n}) - v_\pi(S_{t+n}) \mid S_t = s]\), because the first \(n\) rewards appear in both and cancel in expectation. The right-hand side is a weighted average of errors, times \(\gamma^n\). (It is the \(n\)-fold application of the \(\gamma\)-contraction \(T^\pi\).) Larger \(n\) shrinks the bias from bootstrapping geometrically and pays with the variance of \(n\) random rewards.
Derivation: the forward and backward views of TD(λ) agree (offline)
The λ-return satisfies the recursion \(G^\lambda_t = R_{t+1} + \gamma\big[(1-\lambda)V(S_{t+1}) + \lambda G^\lambda_{t+1}\big]\) (with \(G^\lambda_T = 0\) at the end). Subtract \(V(S_t)\) and add and subtract \(\gamma V(S_{t+1})\):
So the λ-return error is a discounted sum of future TD errors (this is the GAE formula). Now sum the forward-view updates to a state \(s\) over an episode, holding \(V\) fixed, and swap the order of summation:
The inner sum is exactly the accumulating trace \(z_k(s)\) defined by \(z_k(s) = \gamma\lambda z_{k-1}(s) + \mathbf{1}[S_k = s]\). So the backward view's total update equals the forward view's, and it needs only the past. With \(\lambda = 1\) and \(\gamma = 1\) the trace is a visit count, and TD(1) reproduces every-visit Monte Carlo.
Derivation: importance sampling for returns
The probability of the trajectory \(A_t, S_{t+1}, \dots, S_T\) given \(S_t\) under policy \(\pi\) is \(\prod_{k=t}^{T-1}\pi(A_k\mid S_k)\,p(S_{k+1}\mid S_k, A_k)\). Under \(b\) it is the same with \(b\) in place of \(\pi\). Their ratio is \(\rho_{t:T-1} = \prod_k \pi(A_k\mid S_k)/b(A_k\mid S_k)\), the dynamics cancelling. For any function \(f\) of the trajectory, \(\mathbb{E}_\pi[f] = \sum_\tau P_\pi(\tau) f(\tau) = \sum_\tau P_b(\tau)\frac{P_\pi(\tau)}{P_b(\tau)}f(\tau) = \mathbb{E}_b[\rho f]\), provided \(b(a \mid s) > 0\) wherever \(\pi(a \mid s) > 0\) (coverage). With \(f = G_t\):
OIS is unbiased; its variance is \(\mathbb{E}_b[\rho^2G^2] - v_\pi^2\), and \(\mathbb{E}_b[\rho^2]\) can grow exponentially in the horizon (it is 1024 in the 10-step example above) or be infinite. WIS is biased (with one sample it returns \(G\) whatever \(\rho\) is) but the bias vanishes as data grows and its estimates stay within the range of observed returns.
Linear TD and its fixed point
With \(\hat v(s;\mathbf{w}) = \mathbf{w}^\top\mathbf{x}(s)\), the expected semi-gradient TD(0) update on on-policy data is \(\mathbb{E}[\Delta\mathbf{w}] = \alpha(\mathbf{b} - A\mathbf{w})\) with \(A = \mathbb{E}\big[\mathbf{x}_t(\mathbf{x}_t - \gamma\mathbf{x}_{t+1})^\top\big]\) and \(\mathbf{b} = \mathbb{E}[R_{t+1}\mathbf{x}_t]\). It converges to the TD fixed point \(\mathbf{w}_{\text{TD}} = A^{-1}\mathbf{b}\) when \(A\) is positive definite, which holds when states are weighted by the on-policy distribution. Off-policy weighting can make \(A\) indefinite, and then the iteration diverges: the deadly triad in one line of linear algebra. LSTD solves \(A\mathbf{w} = \mathbf{b}\) directly from sample estimates of \(A\) and \(\mathbf{b}\).
History¶
From checkers to dopamine
Arthur Samuel's checkers program (1959) adjusted its evaluation of a position towards the evaluation of positions later in the game: the first TD-like learning rule, decades before the name. Barto, Sutton and Anderson (1983) trained an "adaptive critic" with TD errors and used it to train an actor on pole balancing, the first actor-critic; Sutton's 1988 paper Learning to predict by the methods of temporal differences named TD learning, introduced TD(λ) and the random walk, and proved batch-TD's optimality. Watkins (1989) extended TD to control with Q-learning. Gerald Tesauro's TD-Gammon (1992–1995) trained a neural network by self-play with TD(λ): TD-Gammon 0.0, with essentially no backgammon knowledge, matched the best existing programs after about 300,000 games, and later versions with 1.5 million training games competed with the world's best players. Rummery and Niranjan (1994) introduced the on-policy algorithm that Sutton named "Sarsa" in 1996; Singh and Sutton (1996) introduced replacing traces. Schultz, Dayan and Montague (1997) connected the TD error to dopamine. Van Seijen and Sutton (2014) found true online TD(λ); Schulman et al. (2015) carried λ-returns into deep policy optimisation as GAE.
Build it¶
TD(0) against constant-α Monte Carlo on the random walk, and batch TD against batch MC on the "You are the predictor" data (NumPy, a few seconds):
import numpy as np
# 1. The 5-state random walk (Sutton & Barto Example 6.2): A..E = 1..5, exits 0 and 6, +1 on exit 6
true = np.arange(1, 6) / 6 # v(s) = probability of exiting right
def episode(rng):
s, states = 3, [3] # start in C
while 0 < s < 6:
s += rng.choice((-1, 1)); states.append(s)
return states
def learn(method, alpha, episodes=100, runs=200, seed=0):
rng, rms = np.random.default_rng(seed), np.zeros(episodes)
for _ in range(runs):
V = np.full(7, 0.5); V[0] = V[6] = 0.0 # terminal values are 0
for ep in range(episodes):
states = episode(rng); G = float(states[-1] == 6) # gamma = 1: return = final reward
for s, s_next in zip(states[:-1], states[1:]):
r = float(s_next == 6)
target = r + V[s_next] if method == "TD" else G # bootstrap vs full return
V[s] += alpha * (target - V[s])
rms[ep] += np.sqrt(np.mean((V[1:6] - true) ** 2))
return rms / runs
for method, alpha in [("TD", 0.05), ("TD", 0.1), ("MC", 0.02), ("MC", 0.04)]:
e = learn(method, alpha)
print(f"{method} alpha={alpha:<4} RMS error after 10, 50, 100 episodes: "
f"{e[9]:.3f} {e[49]:.3f} {e[99]:.3f}")
# 2. "You are the predictor" (Example 6.4): replay a fixed batch until the values stop moving
batch = [[("A", 0, "B"), ("B", 0, None)]] + [[("B", 1, None)]] * 6 + [[("B", 0, None)]]
def batch_values(method, alpha=0.01, sweeps=5000):
V = {"A": 0.0, "B": 0.0, None: 0.0}
for _ in range(sweeps):
delta = {"A": 0.0, "B": 0.0}
for ep in batch:
G = sum(r for _, r, _ in ep) # undiscounted return from the first step
for s, r, s_next in ep:
target = G if method == "MC" else r + V[s_next]
delta[s] += alpha * (target - V[s])
G -= r # return from the next step
for s in delta: V[s] += delta[s]
return V["A"], V["B"]
for method in ("MC", "TD"):
print("batch %s: V(A) = %.3f, V(B) = %.3f" % (method, *batch_values(method)))
TD alpha=0.05 RMS error after 10, 50, 100 episodes: 0.174 0.054 0.034
TD alpha=0.1 RMS error after 10, 50, 100 episodes: 0.128 0.051 0.055
MC alpha=0.02 RMS error after 10, 50, 100 episodes: 0.196 0.110 0.082
MC alpha=0.04 RMS error after 10, 50, 100 episodes: 0.178 0.107 0.110
batch MC: V(A) = 0.000, V(B) = 0.750
batch TD: V(A) = 0.750, V(B) = 0.750
The only line that differs between the two methods is the target. Everything else on this
page, n-step returns, traces, SARSA, is a change to that one line or to which states it updates.
Things to try
- Replace the
targetwith an \(n\)-step return (store the episode, then update each state towards \(n\) rewards plus \(V\) of the state \(n\) steps later). Reproduce the U-shaped table for the 19-state walk, then try it on the 5-state walk: is the best \(n\) the same? - Implement TD(λ) with accumulating traces, then with replacing traces, and find the step size at which each diverges for \(\lambda = 1\).
- Make the random walk non-Markov: let the learner observe only "left half / middle / right half" instead of the exact state. Which of batch MC and batch TD now gives better predictions?
- Write SARSA and Q-learning for the cliff-walking grid (4 × 12, −1 per step, −100 for the cliff) and plot online return per episode. Then switch SARSA to Expected SARSA and raise \(\alpha\) to 1.0: which methods survive?
- Evaluate a deterministic "always right" policy from uniformly random episodes of length 10, with ordinary and weighted importance sampling, and plot both estimates against the number of episodes.
In practice¶
- Default to bootstrapping with a short lookahead. Pure TD(0) propagates credit slowly; pure Monte Carlo is noisy. Deep RL practice uses \(n\)-step returns (\(n = 3\) in Rainbow) or λ-returns (\(\lambda \approx 0.95\) in PPO's GAE).
- Monte Carlo is still the right tool when episodes are short, rewards arrive only at the end and states are not Markov. RL for language models often scores a whole completion with one terminal reward and uses Monte Carlo-style returns or group averages instead of a learned value function (RL with verifiable rewards).
- Watch the TD error. Its running mean should approach 0 for a converged on-policy evaluator; a persistent positive or negative mean means your values are biased, often from a wrong terminal value (forgetting to zero \(V\) at terminal states is the classic bug) or from treating a time-limit truncation as a true terminal state.
- Time limits are not terminals. If an episode is cut off at step 1,000 for convenience, bootstrap
from \(V(S_{1000})\) rather than using 0; otherwise you teach the agent that the state is worthless
because a clock ran out. Gymnasium separates
terminatedfromtruncatedfor exactly this reason. - Step size and γ interact. Larger γ means longer effective horizons, larger value magnitudes and noisier targets; scale or normalise rewards and use smaller step sizes as γ approaches 1.
Check yourself¶
Write the TD(0) update and say which part is the TD error. What is the target a sample of?
\(V(S_t) \leftarrow V(S_t) + \alpha[R_{t+1} + \gamma V(S_{t+1}) - V(S_t)]\); the bracket is the TD error \(\delta_t\). The target \(R_{t+1} + \gamma V(S_{t+1})\) is a sample of the right-hand side of the Bellman expectation equation, \(\mathbb{E}_\pi[R_{t+1} + \gamma V(S_{t+1}) \mid S_t]\), with the current estimate \(V\) in place of \(v_\pi\).
On one episode C → D → E → exit right, starting from V = 0.5 everywhere, which states does TD(0) change and which does MC change? Why the difference?
TD(0) changes only E (TD error \(1 - 0.5 = 0.5\)); the TD errors at C and D are zero because \(V(\text{D}) = V(\text{C})\) and \(V(\text{E}) = V(\text{D})\). Monte Carlo moves all three towards the return 1. TD learns from differences between successive predictions, and only the last one was surprised; the information reaches earlier states on later episodes.
In the A/B batch example, which answer for V(A) is right?
It depends on whether the process is Markov. If it is, 0.75 (batch TD) is the better prediction: A always leads to B, and B's value is well estimated from eight samples. Batch MC's 0 is based on a single return and ignores what is known about B. If the process is not Markov (say, reaching B via A really does make B worse), MC's answer could be right. Batch TD computes the certainty-equivalence estimate; batch MC computes the least-squares fit to observed returns.
Why does an intermediate n (or λ) usually beat both TD(0) and Monte Carlo?
Bias and variance. The \(n\)-step target's bias from bootstrapping shrinks like \(\gamma^n\) times the current value error (the error-reduction property), while its variance grows with the number of random rewards and transitions included. TD(0) has the most bias and the slowest propagation of information; Monte Carlo has no bias but the most variance and forces small step sizes. In the 19-state walk the best RMS error was at \(n = 4\) (0.261) and \(\lambda = 0.8\) (0.260), against 0.345 for TD(0) and about 0.49 for Monte Carlo.
SARSA and Q-learning see the same transition. When do their updates differ, and what does each converge to?
They differ when the next action actually taken, \(A'\), is not greedy: SARSA uses \(Q(S', A')\), Q-learning uses \(\max_a Q(S', a)\). SARSA converges to the values of the ε-greedy policy it follows (and to optimal values only if ε decays to 0 under GLIE); Q-learning converges to \(q_\ast\) whatever exploring behaviour is used, as long as every pair keeps being tried. In the worked example SARSA moved \(Q\) to 1.810 and Q-learning to 2.350.
A behaviour policy chooses uniformly between 2 actions; the target policy is deterministic. For episodes of length 20, what are the possible values of the importance ratio and the variance of the ordinary IS estimator of a return that is 1 when the target policy is followed?
The ratio is \(2^{20} \approx 1.05 \times 10^6\) if every action matches the target policy (probability \(2^{-20}\)) and 0 otherwise. \(\mathbb{E}[\rho G] = 1\), \(\mathbb{E}[\rho^2G^2] = 2^{-20}\cdot 2^{40} = 2^{20}\), so the variance is \(2^{20} - 1 \approx 10^6\): you would need around a million episodes for a standard error of 1. Long-horizon off-policy evaluation by full importance sampling is hopeless; this is why Q-learning, truncated ratios and one-step ratios (PPO) exist.
Hard: semi-gradient TD is not gradient descent. What objective would true gradient descent on the TD error minimise, and why is it not used by default?
The mean squared TD error, \(\mathbb{E}[\delta_t^2]\), or the mean squared Bellman error \(\mathbb{E}[(\mathbb{E}[\delta_t \mid S_t])^2]\). The full gradient of \(\delta_t^2\) includes the term \(\gamma\nabla\hat v(S_{t+1})\) from the target (the residual-gradient algorithm of Baird, 1995). It converges more robustly but is slow, and minimising \(\mathbb{E}[\delta^2]\) from samples is biased towards smoothing values (unbiased estimation of the Bellman error needs two independent samples of \(S_{t+1}\) from the same state, which a single trajectory does not provide). Gradient-TD methods (GTD2, TDC) minimise the projected Bellman error instead, with a second set of weights, and are stable off-policy; semi-gradient TD remains the default because it is simpler and usually faster on-policy.
Go deeper¶
Papers
- Learning to Predict by the Methods of Temporal Differences — Richard Sutton, Machine Learning 1988 (DOI). The paper that named TD, introduced TD(λ) and the random walk, and argued why TD beats supervised MC on Markov problems.
- Some Studies in Machine Learning Using the Game of Checkers — Arthur Samuel, IBM Journal 1959. The first program to learn an evaluation function from its own later evaluations.
- Temporal Difference Learning and TD-Gammon — Gerald Tesauro, Communications of the ACM 1995. TD(λ) plus a neural network plus self-play: the 1990s proof that RL could reach world-class play.
- A Neural Substrate of Prediction and Reward — Schultz, Dayan and Montague, Science 1997. Dopamine neurons behave like a TD error; the figure on reward omission is the one to remember.
- Reinforcement Learning with Replacing Eligibility Traces — Singh and Sutton, Machine Learning 1996. Accumulating versus replacing traces, and the equivalence of TD(1) and Monte Carlo.
- Convergence Results for Single-Step On-Policy Reinforcement-Learning Algorithms — Singh, Jaakkola, Littman and Szepesvári, Machine Learning 2000. Why SARSA with GLIE exploration converges to optimal.
- An Analysis of Temporal-Difference Learning with Function Approximation — Tsitsiklis and Van Roy, IEEE TAC 1997. Linear TD converges on-policy, to a fixed point with a bounded error; and why off-policy can diverge.
- True Online TD(λ) — van Seijen and Sutton, ICML 2014. Dutch traces make the online backward view exact; the extended version is arXiv 1512.04087.
- High-Dimensional Continuous Control Using Generalized Advantage Estimation — Schulman, Moritz, Levine, Jordan and Abbeel, 2015. TD(λ) for advantages: the estimator inside PPO and RLHF.
Videos and lectures
- RL Course by David Silver, Lecture 4: Model-Free Prediction — DeepMind x UCL. MC, TD and TD(λ) with the forward and backward views drawn side by side.
- RL Course by David Silver, Lecture 5: Model-Free Control — DeepMind x UCL. GLIE, SARSA, SARSA(λ), importance sampling and Q-learning.
- DeepMind x UCL RL Lecture Series 2021 — Hado van Hasselt, Diana Borsa and Matteo Hessel. A more modern pass; the model-free prediction and control lectures add the deep-RL perspective.
Courses and books
- Reinforcement Learning: An Introduction, chapters 5, 6, 7 and 12 — Sutton and Barto, 2nd ed. 2018. Monte Carlo, TD, n-step and eligibility traces; every example on this page is from here.
- Algorithms for Reinforcement Learning — Csaba Szepesvári, 2010 (free). Chapter 2 treats TD, LSTD and gradient-TD compactly and rigorously.
Code
- Gymnasium — Farama Foundation. The standard environment API (
CliffWalking-v1,FrozenLake-v1,Blackjack-v1for the Monte Carlo examples), withterminatedandtruncatedkept separate.
Where this leads¶
- Q-learning and DQN — TD on the Bellman optimality equation, then with a neural network and the tricks that tame the deadly triad.
- Policy gradients and REINFORCE — use Monte Carlo returns to improve a parameterised policy directly.
- Actor-critic and PPO — a TD-trained critic plus GAE inside the algorithm behind RLHF.
- Model-based RL and planning — learn the model that TD only implicitly estimates, and plan with it.