Part I · Foundations · Chapter 5
Learning from experience: Monte Carlo and TD
Learning values without a model. TD(0), SARSA, Q-learning, and on- vs. off-policy.
At the end of Chapter 4 you could compute the best policy for any gridworld, as long as someone handed you the transition probabilities and the rewards . Almost nobody hands you those. A robot does not know the friction of the floor. A backgammon program does not have a formula for the chance of winning from a given board. A language model does not know in advance which answers a grader will like. What all of them can do is act, and watch what happens.
This chapter is about learning from that stream of experience alone. You will meet two ideas that run through the rest of the course. Monte Carlo learning waits until an episode ends and averages the returns it actually saw. Temporal-difference (TD) learning updates a guess from the next guess, one step later, without waiting. Then you will turn both into control algorithms: SARSA, Q-learning and Expected SARSA. You will also see why two of them, on the same cliff, learn to walk very different paths. In Chapter 1 you watched an agent learn a gridworld and were promised the algorithm later. This is where it comes from.
What you have when you don’t have a model
Recall the setup from Chapter 3. An agent in state takes action , receives reward , and lands in . An episode is one run from a start state to a terminal state :
The return from step is , and the value of a state under policy is its expected return, .
Dynamic programming computed by sweeping over all states and taking exact expectations with . Now we drop and . A method that learns without them is called model-free. All it gets is sampled episodes. We split the job in two, exactly as in Chapter 4:
- Prediction (policy evaluation): given a fixed policy , estimate from episodes generated by following .
- Control: find a good policy, which means estimating values and improving the policy at the same time.
We start with prediction, on the smallest interesting example.
The running example: a random walk
Five states in a row, A to E, with an exit at each end:
Every episode starts in C. At each step a fair coin sends you one state left or right. Leaving E to the right ends the episode with reward . Leaving A to the left ends it with reward . Every other step gives . There are no decisions to make, so this is pure prediction: the “policy” is the coin. Take , so the return of an episode is if it exits right and if it exits left. The value of a state is then the probability of exiting right from it.
This problem is small enough to solve exactly, which is why it is useful: you can check any learning method against the right answer. The Bellman expectation equation says , with boundary values beyond A and beyond E. A function whose value at every point is the average of its neighbours has zero second difference. It is the discrete Laplace equation, and its solution is a straight line between the boundary values:
Our learners will not know this. Each one starts from the guess everywhere and learns from episodes.
Monte Carlo: average what actually happened
The definition suggests the most direct method there is. Every time you visit , write down the return that followed. Average those returns. By the law of large numbers the average converges to . Methods that estimate expectations by averaging samples are called Monte Carlo (MC) methods, after the casino. Physicists use them for integrals. Here the integral is over all possible futures.
Two small choices define the variants:
- First-visit vs. every-visit. If a state appears twice in an episode, first-visit MC uses only the return from its first visit. Every-visit MC uses the return from every visit. Both converge to . First-visit gives independent samples, which makes the theory cleaner. Every-visit is simpler to code and is what most people write.
- Sample mean vs. constant step size. You can keep a running average, or you can use the incremental update from Chapter 2:
This is the pattern “estimate ← estimate + step size × (target − estimate)” again, with the return as the target. With it computes the exact sample mean. With a constant it weights recent returns more heavily, which helps when the policy (and therefore the true value) keeps changing, as it will during control. This version is called constant-α MC.
A worked example. Suppose the first episode is C → D → E → exit right. With , every step’s return is the final reward: from C, from D and from E. With , each visited state moves a tenth of the way from toward :
A and B were not visited, so they stay at . One episode has taught all three visited states something.
Every-visit constant-α Monte Carlo prediction
input: policy π, step size α
initialise V(s) arbitrarily (e.g. 0.5), V(terminal) = 0
repeat for each episode:
generate s0, a0, r0, ..., s_{T-1}, a_{T-1}, r_{T-1}, s_T by following π
G = 0
for t = T-1 down to 0: # backward pass computes all returns
G = r_t + γ G
store G_t = G
for t = 0 to T-1:
V(s_t) += α (G_t − V(s_t))
Monte Carlo has three properties worth stating plainly. Its target is an honest sample of the thing we want, so it is unbiased. It must wait until the episode ends before it can update anything, so it does not work for tasks that never end. And its target can be very noisy, because adds up the randomness of every future step. The next method trades the first property for relief on the other two.
TD(0): learn a guess from a guess
Start with something you already do. You leave the lab at 18:00 and estimate you will be home in 30 minutes. Here is how your predictions evolve on the way:
| Where you are | Minutes elapsed | Predicted minutes remaining | Predicted total |
|---|---|---|---|
| Leaving the lab | 0 | 30 | 30 |
| At the car: it is raining | 5 | 35 | 40 |
| Off the highway, fast | 20 | 15 | 35 |
| Stuck behind a truck | 30 | 10 | 40 |
| Home | 43 | 0 | 43 |
How should you correct the 18:00 guess of 30 minutes? The Monte Carlo answer: wait until you get home, see that the trip took 43, and push the 18:00 guess toward 43. The temporal-difference answer: you already learned something at the car. Five minutes in, your newer, better-informed prediction said 40 in total, so your 18:00 guess was about 10 minutes optimistic. Push it toward 40 now. Then push the “at the car” guess toward the “off the highway” guess, and so on. Each prediction learns from the next prediction.
The TD corrections are . They add up to , which is exactly the Monte Carlo correction . That is no accident (see the derivation below). TD spreads the same total correction over the steps where the information actually arrived.
The update
Now write this down for values. The Bellman expectation equation from Chapter 3 says the value of a state is the expected immediate reward plus the discounted value of where you land:
Dynamic programming computed that expectation exactly with . TD makes two substitutions. It replaces the expectation with the single transition you just experienced, and it replaces the unknown with your current estimate . The result is the TD target , and the update moves toward it:
The quantity in brackets has a name you will see in every remaining chapter, the TD error:
It measures surprise: how much better or worse the step turned out than your estimate of predicted. If is terminal, by definition. This method is called TD(0), or one-step TD, because the target looks one step ahead.
Updating an estimate using another estimate is called bootstrapping, after pulling yourself up by your own bootstraps. Dynamic programming bootstraps too (value iteration’s targets use ). Monte Carlo does not: its target contains only real rewards. TD is the method that both bootstraps (like DP) and learns from samples (like MC).
TD(0) prediction
input: policy π, step size α
initialise V(s) arbitrarily, V(terminal) = 0
repeat for each episode:
s = start state
repeat until s is terminal:
a = action from π(·|s)
take a, observe r, s'
V(s) += α (r + γ V(s') − V(s)) # update NOW, not at the end
s = s'
The worked example, TD version
Same first episode, C → D → E → exit right, same , all values :
- C → D, reward 0: . No change.
- D → E, reward 0: . No change.
- E → exit, reward 1: , so .
Only E moved. C and D had nothing to learn from their successors, because their successors’ estimates had not changed yet. Now suppose the second episode takes the same path:
- C → D: . No change.
- D → E: , so .
- E → exit: , so .
The news of the reward crawls backward one state per episode. On this example, that looks like a weakness compared with Monte Carlo, which moved all three states at once. The payoff comes when you look at noise rather than at a single lucky episode. That is the next section.
Quick check All values start at 0.5, γ = 1, α = 0.1. The first episode is C → B → A → exit left (reward 0). Which TD(0) estimates change?
The two inner steps have TD error 0 + 0.5 − 0.5 = 0. Only the last step, A → exit with reward 0, has a nonzero error: 0 + 0 − 0.5 = −0.5, so V(A) drops to 0.45. Monte Carlo would have moved C, B and A all toward 0.
∂ Why the TD errors add up to the Monte Carlo error
Hold fixed during an episode (no updates until the end). The return satisfies . Add and subtract :
Apply the same step to , and again, until the episode ends. At the end, and , so the last term vanishes:
The Monte Carlo error is the discounted sum of the TD errors along the way. In the commute, and the sum was . When is updated during the episode (as online TD does), the individual TD errors change, and the identity can pick up a small correction of order . Exercise 5.3 works out exactly when.
This identity comes back in Chapter 8: generalized advantage estimation (GAE) is a sum of TD errors in which the sum is cut off gradually with a weight .
Monte Carlo vs. TD: bias and variance
Both methods have the form “move toward a target”. They differ only in the target, so compare the targets as estimators of the thing we want, .
Bias. The MC target has expectation exactly . That is the definition of . It is unbiased, whatever your current estimates are. The TD target has expectation
The first term is by the Bellman equation. The second term is the error of your current estimates one step ahead. So the TD target is biased whenever is wrong, which early in learning is always. The bias shrinks as improves, and vanishes at .
Variance. depends on every random action, transition and reward from to the end of the episode. The TD target depends on just one of each. On the random walk, look at state C with the true values in hand. The MC target from C is or with probability each, so its variance is . The TD target from C is or , so its variance is . That is nine times smaller. On long episodes the gap is far larger, because the MC target accumulates noise from every step.
Which matters more? On most problems, variance does. A biased but steady target lets you take bigger steps. And TD’s bias corrects itself. Average a TD update over the random next step, and apply it to every state at once: you get , where is the Bellman operator from Chapter 4. That is a damped version of the iteration you proved converges there, because is a γ-contraction. So the bias shrinks geometrically as the estimates converge (Exercise 5.2 does the proof). The demo lets you see the result.
Press +1 episode to watch one walk, or Play.
| state | A | B | C | D | E | RMS err |
|---|---|---|---|---|---|---|
| true | 0.167 | 0.333 | 0.500 | 0.667 | 0.833 | 0 |
| TD(0) | ||||||
| MC |
What to try: press +1 episode a few times and read which states each method changed (TD changes a state only when its TD error is nonzero; at first that happens only next to an exit). Then press Play. The thin lines are this run; the thick lines average 100 runs at the current step sizes. Try to find an MC step size whose thick line beats TD's at α = 0.1 after 100 episodes (it can't be done). Then push both α to 0.3: errors fall fast, then level off high.
Three things are worth noticing in the demo.
- TD learns faster on average. With for both methods, TD’s averaged error after 100 episodes is around . MC’s is around , more than twice as large. Even at its best step size (around ), MC ends near , while TD at gets below .
- Large step sizes level off at a higher error. A constant step size never fully averages away the noise in the targets: the estimate keeps jumping toward the most recent sample. The floor is roughly proportional to times the target’s variance, which is why MC’s floor is higher.
- A single run is noisy. The thin lines wander. When you compare algorithms, average over many runs and seeds (the lab does this too).
Tabular TD(0) is guaranteed to converge to for a fixed policy if every state keeps being visited and the step sizes shrink in the usual way ( and , the Robbins–Monro conditions). With a small constant it converges in the mean and then hovers near , as in the demo.
Same data, different answers
There is a second, subtler difference. Suppose you stop collecting episodes and instead replay a fixed batch of data again and again until each method settles. Sutton & Barto’s Example 6.4 makes the point with eight episodes:
- A → B (reward 0) → exit (reward 0), once.
- B → exit (reward 1), six times.
- B → exit (reward 0), once.
Both methods agree that . For A they disagree. Batch Monte Carlo averages the returns that followed A. There is only one, and it was , so . Batch TD notices that A always led to B with reward , so .
TD’s answer is the value you would compute if you first fitted the most likely Markov model to the data (A goes to B with probability 1; B pays 1 with probability ) and then solved that model exactly. This is called the certainty-equivalence estimate. MC’s answer is the one that best fits the returns already observed. If the process really is Markov, TD’s answer generalizes better: it uses all six B-episodes to learn about A. That is a large part of why TD tends to win on Markov problems. Exercise 5.4 asks you to work out a case of your own.
Quick check You are in state s and want to estimate V^π(s). Which target is unbiased, no matter what your current value estimates are?
The expected return from s is V^π(s) by definition, so G is unbiased. The TD target uses your current estimate V(s′), so its expectation is off by γ times the expected error of that estimate. It becomes unbiased only once V = V^π.
n-step returns: the dial between them
MC and TD(0) are the two ends of a dial. TD(0) uses one real reward and then bootstraps. MC uses all the real rewards and never bootstraps. In between, the n-step return uses real rewards and then bootstraps from the estimate steps ahead:
If the episode ends before , the bootstrap term is dropped and is just . For this is the TD(0) target. For at least as long as the episode it is the MC target. The n-step update moves toward , and it must wait steps before making it.
Each extra real reward reduces bias (less weight on the estimate) and adds variance (more randomness in the target). In practice an intermediate is often best. Rather than pick one , you can average all of them with geometrically decaying weights. That gives the λ-return, and its practical form, GAE, is the heart of Chapter 8. We leave it there.
From prediction to control
Now let the agent choose its actions. The plan is the one from Chapter 4, generalized policy iteration (GPI): keep an estimate of the current policy’s values, keep making the policy greedy with respect to it, and let the two chase each other. Two adjustments are needed for the model-free setting.
Learn Q, not V. To act greedily with respect to you have to look one step ahead:
That needs and , which we no longer have. Acting greedily with respect to needs neither: . The action values already contain the one-step lookahead. So every control method in this chapter learns a table .
Keep exploring. If you always take the action that currently looks best, you never find out whether the others are better. This is the bandit problem of Chapter 2 again, now in every state. The standard fix is the ε-greedy policy: with probability take a uniformly random action, otherwise take (breaking ties at random). Every action keeps a probability of at least .
All three algorithms below share the same loop and the same form of update:
They differ only in the target. That one line decides which policy the table ends up describing.
SARSA: on-policy TD control
The most direct move is to apply TD(0) to action values. Take the Bellman equation for ,
and replace the expectation with one sample, exactly as before:
The update uses the five quantities , which is where the name SARSA comes from. The important detail is : it is the action the agent will actually take next, chosen by its ε-greedy policy. So the agent must pick its next action before it can update.
SARSA
initialise Q(s, a) = 0 for all s, a
repeat for each episode:
s = start state
a = ε-greedy action from Q(s, ·)
repeat until s is terminal:
take a, observe r, s'
a' = ε-greedy action from Q(s', ·) # choose the next action first
target = r if s' is terminal
r + γ Q(s', a') otherwise
Q(s, a) += α (target − Q(s, a))
s, a = s', a'
Since comes from the ε-greedy policy, the target is a sample of the Bellman equation for the ε-greedy policy. SARSA therefore learns for the policy it is actually following, exploration included. Meanwhile that policy keeps getting greedier with respect to the improving . That is GPI with one sample per evaluation step. If you also let decay to zero slowly enough that every pair is still tried infinitely often (a schedule called GLIE, “greedy in the limit with infinite exploration”), SARSA converges to an optimal policy.
Q-learning: off-policy TD control
Q-learning makes one change to the target. Instead of the value of the next action you will take, it uses the value of the best next action:
This is a sampled version of the Bellman optimality equation for from Chapter 4. You can read Q-learning as value iteration on , with one sampled transition in place of the exact sum over . Its fixed point is , however the agent is actually behaving.
Q-learning
initialise Q(s, a) = 0 for all s, a
repeat for each episode:
s = start state
repeat until s is terminal:
a = ε-greedy action from Q(s, ·) # behavior: explore
take a, observe r, s'
target = r if s' is terminal
r + γ max_a' Q(s', a') otherwise # target: greedy
Q(s, a) += α (target − Q(s, a))
s = s'
On-policy and off-policy, carefully
Q-learning acts with one policy and learns about another. To talk about this precisely we need two names:
- The behavior policy is the one that chooses the actions that generate the data. Here it is ε-greedy.
- The target policy is the one whose values you are learning. For Q-learning it is the greedy policy, the one that would take everywhere.
A method is on-policy if the two are the same: it learns about the policy that generates its data. SARSA is on-policy. A method is off-policy if they can differ. Q-learning is off-policy: its target policy is greedy, while its behavior can be ε-greedy, purely random, or a human driving the robot, as long as every state–action pair keeps being tried.
Why doesn’t Q-learning need to correct for the mismatch? Look at what each part of an update depends on. is defined given that action was taken in , so how was chosen does not matter. The next state and reward come from the environment, not from any policy. The only place a policy enters is the choice of the next action, and there Q-learning plugs in the target policy’s choice (the max) instead of the action the behavior will actually take. So the behavior policy affects only which pairs get updated and how often, never what they are updated toward. Watkins and Dayan (1992) proved that tabular Q-learning converges to under exactly those conditions: every pair visited infinitely often, and Robbins–Monro step sizes.
Off-policy learning is not always this cheap. If you wanted to evaluate a policy from whole Monte Carlo returns generated by a different policy , you would have to reweight each return by the product of ratios along the episode. That product is an importance-sampling correction, and over long episodes its variance can explode. Importance ratios come back as in Chapter 9, where they let PPO reuse slightly stale data.
Quick check An agent explores with ε = 0.3 and learns with Q-learning on a small problem. After a very long time, its Q-table approximates the action values of which policy?
Q-learning's target uses max over a′, the greedy choice, regardless of which action the agent takes next. Its fixed point is Q*. Exploration only controls which pairs get visited. SARSA with ε = 0.3 would instead learn the values of the ε-greedy policy.
Expected SARSA: average instead of sample
SARSA’s target uses one sampled next action . That sample adds noise. If you know the policy’s probabilities (you do: you chose ε-greedy), you can average over the next action instead of sampling it:
This is Expected SARSA. In expectation it makes the same update as SARSA, but without the randomness of , so it tolerates larger step sizes. For an ε-greedy over actions, the sum is . It also unifies the family. If is the ε-greedy behavior policy, Expected SARSA is on-policy, like SARSA. If is greedy, the sum collapses to and Expected SARSA is Q-learning.
| Method | Target | Learns the values of | On/off-policy |
|---|---|---|---|
| SARSA | the ε-greedy policy it follows | on | |
| Expected SARSA | (usually the ε-greedy policy) | on (off if ) | |
| Q-learning | the greedy policy, so | off |
Cliff walking: safe or optimal?
Here is the classic problem that shows the difference in a single picture (Sutton & Barto, Example 6.6). A 4 × 12 grid. You start at the bottom-left corner S and must reach the bottom-right corner G. The cells between them along the bottom row are a cliff. Every step costs . Stepping into the cliff costs and sends you back to S. The episode ends at G, and .
The optimal path walks along the edge of the cliff: up one, right eleven, down one, 13 steps, return . Both agents below explore with the same ε-greedy policy, use the same α, and see their episodes in lockstep. The only difference between them is the one line that computes the target.
Shading: how negative maxa Q(s, a) is (heavier = costlier). Arrows: greedy action in cells visited so far. Bold line: the greedy path from S. Dot: where the agent is now (with its trail at slow speeds).
| SARSA | Q-learning | |
|---|---|---|
| Episodes | ||
| Avg return, last 50 episodes (with exploration) | ||
| Cliff falls per episode, last 50 | ||
| Greedy path (no exploration) |
What to try: press Play and wait for about 300 episodes. Compare the two bold greedy paths, then the two curves and the 'avg return' row in the table. Next, set the speed to ¼ and watch where each agent actually falls. Then: (1) switch the on-policy agent to Expected SARSA; (2) set ε to 0 and press Reset; (3) put ε back to 0.1, set α to 1.0 and press Reset. Exercise 5.7 asks you to explain each one.
With the default settings (, ) you should see what Sutton & Barto report:
- Q-learning’s greedy path hugs the cliff edge (13 steps). Its values are those of the greedy policy, and the greedy policy never steps off the edge.
- SARSA’s greedy path takes a detour, usually along the top row (17 steps). Its values are those of the ε-greedy policy. From a cell next to the cliff, that policy has a chance per step of picking “down”, which costs 100. SARSA’s table has priced that in, so the cells next to the cliff look expensive and the greedy path avoids them.
- While learning, SARSA earns more per episode: around , against around for Q-learning. Q-learning’s agent walks the edge it believes is optimal, but it still explores, and an exploring agent on the edge falls off. Roughly once every three episodes, by the “falls per episode” row.
So which agent is right? Both, about different questions. Q-learning answers “what is the best thing to do, assuming I will act greedily from now on?”. SARSA answers “what is the best thing to do, given how I will actually behave, exploration and all?”. If your robot will keep making random moves (exploration, sensor noise, a slippery floor you didn’t model), SARSA’s caution is worth having. If you will switch exploration off before deployment, Q-learning’s path is the one you want. With decaying toward zero, the two answers converge, because the policies they evaluate converge.
Quick check On the cliff with ε = 0.1, which agent's GREEDY path is optimal, and which agent collects more reward per episode WHILE learning?
Q-learning learns Q*, so its greedy path is the optimal 13-step edge path. But both agents act ε-greedily while learning, and on the edge exploration is costly. SARSA learns the values of its ε-greedy behavior and keeps away from the edge, so it earns about −25 per episode against Q-learning's −50.
Maximization bias and Double Q-learning
Q-learning’s max hides a trap. Suppose that in some state all ten actions have true value , but your estimates are noisy: each equals the truth plus independent noise with standard deviation 1. The true value of the best action is . The expected value of your estimated max is not. The maximum of ten independent standard normal samples has expectation about . Taking the max of noisy estimates selects the ones whose noise happens to be positive. In general,
since the max is a convex function (this is Jensen’s inequality). Q-learning bootstraps from this max at every step, so the upward bias propagates backward through the table. This is called maximization bias. It is mild on deterministic problems like the cliff, where the targets are not noisy. It can be serious when rewards or transitions are random. Exercise 5.9 computes the bias exactly for two actions.
The fix is to stop using the same noisy numbers both to choose the best action and to evaluate it. Double Q-learning (van Hasselt, 2010) keeps two independent tables, and . On each step, flip a coin. On heads, update , letting pick the action and say what it is worth:
On tails, swap the roles of A and B. Act ε-greedily with respect to . Because ‘s noise is independent of the choice made, the evaluation is no longer biased upward (it can be slightly biased downward instead). The same idea, with the target network playing the role of , becomes Double DQN in Chapter 6.
Summary
- Model-free methods learn values from sampled experience, with no access to or .
- Monte Carlo moves toward the observed return . The target is unbiased but high-variance, and it is only available when the episode ends.
- TD(0) moves toward , using the TD error . It bootstraps: the target is biased by the current estimates but has low variance, and it updates after every step. The MC error is the discounted sum of TD errors.
- n-step returns interpolate between the two; their λ-weighted average becomes GAE in Chapter 8.
- For control, learn Q (so acting greedily needs no model) and explore with ε-greedy.
- SARSA (target uses the next action you will take) is on-policy: it learns the values of its own exploring policy. Q-learning (target uses the max) is off-policy: it learns whatever the behavior policy, as long as everything keeps being tried. Expected SARSA averages over the next action and contains both.
- On the cliff, SARSA learns the safe detour and earns more while exploring. Q-learning learns the optimal edge path and falls off more while exploring.
- The max in Q-learning is biased upward under noise. Double Q-learning decouples choosing an action from evaluating it.
Exercises
Three states X, Y, Z. Current estimates , , . Step size , discount . You observe one episode:
(a) Compute the returns and the new estimates after an every-visit constant-α MC update.
(b) Starting again from the original estimates, apply TD(0) online along the episode. Give each TD error and the new estimates.
(c) Which method moved in the “wrong” direction compared with the other, and why?
Solution
(a) Work backward. . . . Then
(b) Online, in order:
- , so .
- , so .
- (Z → terminal), so .
New estimates: .
(c) . Monte Carlo raised it (toward the actual 3.6), while TD lowered it (toward ). TD bootstrapped from , which was a bad estimate: Z was about to pay 4. This is TD’s bias in action. Once has learned (it is now 2), later TD updates of Y will pull it back up. These are the numbers used by test_mc_update_hand_example and test_td0_update_hand_example in the lab.
Fix a policy and let be any current estimate (a fixed table, not random).
(a) Show that .
(b) Show that the bias of the TD target, , equals , and that its absolute value is at most .
(c) Consider an idealized, averaged TD(0): every state is updated at once, toward its expected TD target. That is , where is the Bellman operator from Chapter 4. Use the contraction property from Chapter 4 to show that this iteration converges to for and , despite the bias of every target along the way.
Hint
Solution
(a) This is the definition of the state value: . Each observed return is one sample of that random variable, so its expectation is the value. Nothing about your current estimates enters.
(b) Add and subtract :
Subtract to get the bias. An expectation of a quantity is at most the quantity’s largest absolute value, so . The bias is zero for every when .
(c) Let . Since , also . Subtract and use the triangle inequality and the contraction :
The factor lies in for and , so the error shrinks geometrically to 0. The bias of the TD target is real, but it is proportional to the current error, and the update drives that error down. (Real TD updates one sampled state at a time, which adds noise around this mean behavior; the Robbins–Monro conditions on handle that noise.)
(a) Prove that if is held fixed during an episode, .
(b) Check the identity on the episode of Exercise 5.1 for , using the original estimates.
(c) In Exercise 5.1(b), TD updated during the episode, yet the TD errors you computed are the same as with fixed. Why, in that particular episode? Construct a short episode in which they would differ. Does the identity of (a) still hold, at , for the online TD errors of your episode?
Hint
Solution
(a) Using ,
Unrolling gives , and the last term is zero because and .
(b) Left side: . Right side, with : . They agree.
(c) The TD error at step reads and . In that episode each state appears once, and each state is updated only after its own TD error is computed. So always read original values: had not been updated yet, and is updated later. The individual errors change when a state is revisited. Same , , , , episode terminal. With fixed: . Online: raises to ; then , and . The second visit to X reads a value that the first visit already changed, so the online errors differ from the fixed- ones, by amounts proportional to .
Now the surprise. The return is , so with the original . The online errors give . The identity still holds exactly. The reason: the sum telescopes because the value of that reads (as “next state”) is cancelled by the value of that reads (as “current state”). Between those two reads, the only update is to . So the cancellation fails only if , a state that transitions to itself. Then the identity picks up an extra term for each such step . That is the “correction of order ” mentioned in the main text.
You are given five episodes (γ = 1) and asked to replay them until each method converges (“batch” updating):
- A → B with reward 0, then B → exit with reward 0.
- B → exit with reward 1.
- B → exit with reward 1.
- B → exit with reward 1.
- A → exit with reward 0.
(a) What does batch Monte Carlo give for and ?
(b) What does batch TD(0) give? (At convergence, the average TD error at every state must be zero.)
(c) Fit the maximum-likelihood Markov model to the data: estimate the transition probabilities out of A and B, and the expected reward of each transition. Solve that model exactly and compare with (b).
(d) You will see one more episode, starting in A. Which estimate would you bet on, and when would you change your mind?
Hint
Solution
(a) MC averages observed returns. B was visited in episodes 1–4 with returns , so . A was visited in episodes 1 and 5, with returns and , so .
(b) Batch TD’s fixed point makes the average TD error zero at each state, so is the average of over the transitions out of . Out of B: four transitions to exit with rewards , so . Out of A: one transition to B with reward 0 (target ) and one to exit with reward 0 (target ). So .
(c) Maximum-likelihood model: from A, go to B with probability and exit with probability , reward 0 either way. From B, exit with expected reward . Solving: and . This is exactly the batch TD answer: TD computes the certainty-equivalence estimate.
(d) If the process is Markov (what happens after B does not depend on whether you came from A), the TD estimate is the better bet. It uses all four observations of B to evaluate the half of A’s episodes that go through B, while MC uses the single episode in which A happened to lead to an unlucky B. You would prefer MC’s estimate if you suspected the state is not Markov, for example if B after A really is a worse place than B at the start. MC makes no Markov assumption; TD relies on it.
(a) In two or three sentences, explain why SARSA learns the values of the ε-greedy policy while Q-learning learns , even when both follow the same ε-greedy behavior.
(b) Write the fixed-point equation that SARSA’s expected update satisfies, and the one Q-learning’s satisfies. Which Bellman equations are they?
(c) If you set in both, are their updates the same? Is that a good way to make SARSA learn ?
(d) Q-learning never needs importance-sampling ratios. Off-policy Monte Carlo does. What is the difference?
Hint
Solution
(a) In SARSA’s target , the next action is drawn from the ε-greedy policy, so on average the target is the Bellman backup of the ε-greedy policy. Q-learning’s target evaluates the next state with the greedy choice, no matter what the agent will actually do. Behavior only decides which pairs get updated.
(b) SARSA, at its fixed point (for a fixed ε-greedy ):
the Bellman expectation equation for , so with ε-greedy. Q-learning:
the Bellman optimality equation, whose solution is .
(c) With both choose , so the updates are essentially identical. (There are small differences: SARSA picks before updating , which matters if , and random tie-breaking may pick different actions.) But it is a poor way to get : with no exploration, actions that look bad early are never tried again, and their estimates are never corrected. The proper route is GLIE: decay ε slowly, so SARSA’s policy becomes greedy only in the limit.
(d) An MC return contains rewards from all the steps after , and those depend on the actions chosen at all those steps by the behavior policy. To turn an average under into an average under , you must reweight by the probability ratio of that whole action sequence, . Q-learning’s one-step target contains only one real transition, . That transition is conditioned on (so how was chosen is irrelevant) and on the environment (which no policy controls), and everything after is summarized by , which already follows the target policy. No step in the target was generated by the behavior policy, so there is nothing to reweight.
Four actions. In the next state the current estimates are . You took action in , received , and . Use , , and an ε-greedy policy with .
(a) Write down and compute the Expected SARSA target and the updated .
(b) Compute the Q-learning target, and the SARSA target if the sampled next action was action 3 (value 2). Compare all three.
(c) Show that for any , the Expected SARSA target with ε-greedy equals , and that it equals the Q-learning target when .
Solution
(a) The greedy action is action 2 (value 3). Each action gets , and the greedy one gets an extra : . Expected next value: . Target: . Update: .
(b) Q-learning: . SARSA with sampled value 2: . Expected SARSA (1.43) sits between them. It is lower than Q-learning because it accounts for the 15% chance of exploring to a worse action, and unlike SARSA it does not depend on which action happened to be sampled. Averaged over the sampled , SARSA’s target is exactly 1.43.
(c) Under ε-greedy, for every action, plus shared among the actions that achieve the max. So
(Ties do not matter: every tied action has the max value, however the is split.) The first term is times the mean. At only remains, which is the Q-learning target. Check with (a): .
Use the cliff demo.
(a) With the defaults (ε = 0.1, α = 0.5), run about 300 episodes. Describe each agent’s greedy path, its average return while learning, and its falls per episode. Explain each difference in terms of which policy each agent’s Q-table describes.
(b) Switch the on-policy agent to Expected SARSA and run again. How does its greedy path and return compare with SARSA’s?
(c) Set ε = 0 and press Reset. Both agents still explore at first and both find the 13-step path. Where does the exploration come from, with no randomness at all?
(d) Set α = 1.0 (ε = 0.1) and press Reset. Compare SARSA, Expected SARSA and Q-learning. Which one becomes erratic, and why?
Hint
Solution
(a) Q-learning’s greedy path runs along the cliff edge (13 steps), SARSA’s takes a detour, usually along the top row (17 steps). While learning, SARSA averages about −25 per episode with few falls (a few per hundred episodes), Q-learning about −50 with about 0.3 falls per episode. Q-learning’s table is , the values of a greedy policy, which never steps off the edge, so the edge path looks best. But the agent acts ε-greedily: on each of the ~11 edge steps it moves down with probability , so it falls with probability roughly per episode or more, at each time. SARSA’s table describes the ε-greedy policy, so the cells next to the cliff carry that expected fall cost, and its greedy path stays away.
(b) Expected SARSA also takes a safe path, typically along the middle row (15 steps), and earns slightly more per episode than SARSA (around −20). It learns the same ε-greedy values as SARSA, but its targets are not noisy, so its estimates are more accurate at this large α. The path differs because the values differ slightly and both rows are reasonable: one row away from the edge, a random “down” step lands on the edge, not in the cliff.
(c) Zero is an optimistic initial value: every true value here is negative. Whenever the agent tries an action, its estimate drops below 0, so untried actions (still at 0) look better and get tried next. This is the “optimistic initial values” trick from Chapter 2, at work in every state. Once the estimates are realistic, the greedy agent settles on the shortest path, and since it never explores afterward, it never falls: both agents earn −13 per episode. On problems with stochastic rewards, or where some true values are positive, this trick is much less reliable.
(d) SARSA becomes erratic: its return collapses and its greedy path often loops. With α = 1, is overwritten by the latest target, and SARSA’s target depends on the sampled . One exploratory (say, toward the cliff) replaces a good value with a terrible one, and the next greedy replaces it back. Expected SARSA and Q-learning have deterministic targets here (the environment is deterministic and the next action is averaged or maximized, not sampled), so α = 1 is fine for them. Q-learning still earns about −50 per episode, for the reason in (a). This is the practical argument for Expected SARSA: same values as SARSA, less variance.
Use the random-walk demo.
(a) Press Reset, then +1 episode once. How many TD estimates changed, and which one? Explain why the answer does not depend on which path the walk took.
(b) Keep TD at α = 0.1. Move the MC step size and watch the status line (“averaged over 100 runs, after 100 episodes”). Roughly which MC step size gives the lowest error, and how does it compare with TD’s?
(c) Set both step sizes to 0.3. The errors fall fast and then stop improving. Why does a constant step size leave an error floor, and why is MC’s floor higher than TD’s?
Solution
(a) Exactly one: the last state before the exit (A or E). With all estimates at 0.5 and all intermediate rewards 0, every inner transition has TD error . Only the final transition sees a terminal value of 0 and a reward of 0 or 1, so only its error is nonzero ().
(b) MC does best around α = 0.02–0.03, with an averaged error near 0.08 after 100 episodes. TD at α = 0.1 is around 0.05, and at α = 0.05 below 0.04. No MC step size catches up within 100 episodes: a small α keeps MC’s noise low but makes it slow, and a large α makes it fast but noisy.
(c) With a constant α, each estimate is an exponentially weighted average of recent targets, with an effective memory of about samples. It never averages more than that many, so it keeps fluctuating with variance roughly proportional to times the variance of the target. For state C, the MC target (0 or 1) has variance while the TD target (near or ) has variance about , so MC’s floor is much higher. Decaying step sizes (for example ) remove the floor at the cost of slower adaptation.
A state has two actions, both with true value 0. Your estimates are and , independent, each .
(a) Compute exactly.
(b) Double Q-learning uses a second, independent pair of estimates . It picks and reports . Compute .
(c) Now suppose the true values are and (same noise). Without computing anything exactly, argue that the double estimator can be biased downward.
Hint
Solution
(a) . The first term has mean 0. , so . Hence
even though the true maximum is 0. With ten actions it grows to about . Q-learning feeds this bias into every target that maxes over this state.
(b) depends only on the ‘s, and the ‘s are independent of the ‘s. So, conditioning on : for each , and therefore . The double estimator is unbiased here. Choosing and evaluating with independent noise breaks the “pick whichever got lucky” effect.
(c) The true maximum is . With noise, the ‘s sometimes pick action 2 by mistake. Then the double estimator reports , whose mean is . So : every wrong choice is evaluated honestly, and an honest evaluation of a worse action is lower than the true max. That is van Hasselt’s observation: the double estimator trades overestimation for (usually milder) underestimation.
Download the lab below and work through td.py in order. Each task is a few lines.
- Task 1,
mc_update: every-visit constant-α Monte Carlo (backward pass for returns, then forward updates). - Task 2,
td0_update: online TD(0). - Task 3,
epsilon_greedy, with random tie-breaking. - Task 4, the three targets:
sarsa_target,q_learning_target,expected_sarsa_target. - Task 5,
sarsa_episodeandq_learning_episode: one episode of each control algorithm.
Then run python run.py. It reproduces the random-walk error curves and the cliff learning curves with your code, and prints both greedy paths as ASCII art.
Hint
Solution
The reference implementation is in solutions/td.py. The key lines:
mc_update:g = r_t + gamma * gwalking backward to fillG[t], thenV[s_t] += alpha * (G[t] - V[s_t])walking forward.td0_update:target = r if done else r + gamma * V[s_next], thenV[s] += alpha * (target - V[s]), inside the loop, so later transitions see earlier updates.epsilon_greedy:if rng.random() < epsilon: return rng.integers(n); elserng.choice(np.flatnonzero(q == q.max())). Without random tie-breaking, an all-zero Q-table always picks action 0.- Targets: SARSA
r + gamma * Q[s_next, a_next]; Q-learningr + gamma * Q[s_next].max(); Expected SARSAr + gamma * (epsilon * Q[s_next].mean() + (1 - epsilon) * Q[s_next].max()); all three returnrwhendone. sarsa_episode: chooseabefore the loop; inside, step, choosea_next, update withsarsa_target, thens, a = s_next, a_next.q_learning_episode: chooseaat the top of each iteration, step, update withq_learning_target, thens = s_next.
The test test_control_off_policy_q_learning_vs_on_policy_sarsa is worth reading: on a tiny corridor with a completely random behavior policy (ε = 1), Q-learning still recovers , while SARSA converges to the random policy’s value, . That is the whole on-/off-policy distinction in one assertion.
Expected output of run.py: TD’s RMS error around 0.04–0.07 after 100 episodes, against 0.085–0.11 for MC; on the cliff, SARSA about −25 and Q-learning about −49 per episode over the last 100 episodes; Q-learning’s printed path along the edge, SARSA’s along the top.
Files: README.md, td.py, envs.py, test_td.py, run.py
cd 05-td-learning
python -m pytest -q # your code: tests fail until you fill in the TODOs
RL_SOLUTIONS=1 python -m pytest -q # reference solutions: all passFirst time? See Exercises & setup.
Further reading
- Sutton & Barto (2018), Reinforcement Learning: An Introduction, 2nd ed., chapters 5–6. The canonical treatment, and the source of the random walk, the batch example and the cliff. Read 6.1–6.7; chapter 5 covers Monte Carlo control and off-policy importance sampling in more depth than we did; chapter 7 covers n-step methods.
- Sutton (1988), Learning to predict by the methods of temporal differences. The paper that introduced TD learning. Its argument that “multi-step prediction” differs from supervised learning is still worth reading.
- Watkins & Dayan (1992), Q-learning. The short convergence proof for tabular Q-learning, with exactly the conditions stated in this chapter.
- van Hasselt (2010), Double Q-learning. Clear statement of maximization bias, the double estimator, and examples where Q-learning overestimates badly.
- David Silver’s UCL course, lectures 4 and 5 (model-free prediction and control). Good slides and recorded lectures covering the same ground from a slightly different angle.
- Tesauro (1995), Temporal difference learning and TD-Gammon. The first big TD success: a backgammon program near the level of top human players, trained by self-play with TD. A short, readable history of why TD mattered.
Next, in Chapter 6, the table becomes a neural network. You will see why combining bootstrapping, off-policy learning and function approximation can make Q-learning diverge, and how DQN tamed it on Atari.