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.

~100 minBefore this: MDPs, Dynamic programming

At the end of Chapter 4 you could compute the best policy for any gridworld, as long as someone handed you the transition probabilities P(s′∣s,a)P(s' \mid s, a) and the rewards r(s,a)r(s, a). 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 sts_t takes action ata_t, receives reward rtr_t, and lands in st+1s_{t+1}. An episode is one run from a start state to a terminal state sTs_T:

s0,a0,r0,  s1,a1,r1,  …,  sT−1,aT−1,rT−1,  sT.s_0, a_0, r_0, \; s_1, a_1, r_1, \; \dots, \; s_{T-1}, a_{T-1}, r_{T-1}, \; s_T .

The return from step tt is Gt=rt+γrt+1+γ2rt+2+⋯+γT−t−1rT−1G_t = r_t + \gamma r_{t+1} + \gamma^2 r_{t+2} + \dots + \gamma^{T-t-1} r_{T-1}, and the value of a state under policy π\pi is its expected return, Vπ(s)=Eπ[Gt∣st=s]V^\pi(s) = \mathbb{E}_\pi[G_t \mid s_t = s].

Dynamic programming computed VπV^\pi by sweeping over all states and taking exact expectations with PP. Now we drop PP and rr. 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 π\pi, estimate VπV^\pi from episodes generated by following π\pi.
  • 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:

0  ←  A  ↔  B  ↔  C  ↔  D  ↔  E  →  +1\boxed{0} \;\leftarrow\; A \;\leftrightarrow\; B \;\leftrightarrow\; C \;\leftrightarrow\; D \;\leftrightarrow\; E \;\rightarrow\; \boxed{+1}

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 +1+1. Leaving A to the left ends it with reward 00. Every other step gives 00. There are no decisions to make, so this is pure prediction: the “policy” is the coin. Take γ=1\gamma = 1, so the return of an episode is 11 if it exits right and 00 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 V(s)=12V(left of s)+12V(right of s)V(s) = \tfrac12 V(\text{left of } s) + \tfrac12 V(\text{right of } s), with boundary values 00 beyond A and 11 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:

V(A),V(B),V(C),V(D),V(E)  =  16,  26,  36,  46,  56.V(A), V(B), V(C), V(D), V(E) \;=\; \tfrac16,\; \tfrac26,\; \tfrac36,\; \tfrac46,\; \tfrac56 .

Our learners will not know this. Each one starts from the guess V=0.5V = 0.5 everywhere and learns from episodes.

Monte Carlo: average what actually happened

The definition Vπ(s)=Eπ[Gt∣st=s]V^\pi(s) = \mathbb{E}_\pi[G_t \mid s_t = s] suggests the most direct method there is. Every time you visit ss, write down the return that followed. Average those returns. By the law of large numbers the average converges to Vπ(s)V^\pi(s). 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 VπV^\pi. 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:
V(st)  ←  V(st)+α(Gt−V(st)).V(s_t) \;\leftarrow\; V(s_t) + \alpha \big( G_t - V(s_t) \big).

This is the pattern “estimate ← estimate + step size × (target − estimate)” again, with the return GtG_t as the target. With α=1/N(s)\alpha = 1/N(s) it computes the exact sample mean. With a constant α\alpha 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 γ=1\gamma = 1, every step’s return is the final reward: G=1G = 1 from C, from D and from E. With α=0.1\alpha = 0.1, each visited state moves a tenth of the way from 0.50.5 toward 11:

V(C)=V(D)=V(E)=0.5+0.1 (1−0.5)=0.55.V(C) = V(D) = V(E) = 0.5 + 0.1\,(1 - 0.5) = 0.55 .

A and B were not visited, so they stay at 0.50.5. 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 GtG_t 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 GtG_t 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 areMinutes elapsedPredicted minutes remainingPredicted total
Leaving the lab03030
At the car: it is raining53540
Off the highway, fast201535
Stuck behind a truck301040
Home43043

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 +10,−5,+5,+3+10, -5, +5, +3. They add up to +13+13, which is exactly the Monte Carlo correction 43−3043 - 30. 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:

Vπ(s)=Eπ[ rt+γVπ(st+1)  ∣  st=s ].V^\pi(s) = \mathbb{E}_\pi\big[\, r_t + \gamma V^\pi(s_{t+1}) \;\big|\; s_t = s \,\big].

Dynamic programming computed that expectation exactly with PP. TD makes two substitutions. It replaces the expectation with the single transition you just experienced, and it replaces the unknown Vπ(st+1)V^\pi(s_{t+1}) with your current estimate V(st+1)V(s_{t+1}). The result is the TD target rt+γV(st+1)r_t + \gamma V(s_{t+1}), and the update moves V(st)V(s_t) toward it:

V(st)  ←  V(st)+α(rt+γV(st+1)−V(st)).V(s_t) \;\leftarrow\; V(s_t) + \alpha \big( r_t + \gamma V(s_{t+1}) - V(s_t) \big).

The quantity in brackets has a name you will see in every remaining chapter, the TD error:

δt=rt+γV(st+1)−V(st).\delta_t = r_t + \gamma V(s_{t+1}) - V(s_t).

It measures surprise: how much better or worse the step turned out than your estimate of sts_t predicted. If st+1s_{t+1} is terminal, V(st+1)=0V(s_{t+1}) = 0 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 VkV_k). Monte Carlo does not: its target GtG_t 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 α=0.1\alpha = 0.1, all values 0.50.5:

  • C → D, reward 0: δ=0+0.5−0.5=0\delta = 0 + 0.5 - 0.5 = 0. No change.
  • D → E, reward 0: δ=0+0.5−0.5=0\delta = 0 + 0.5 - 0.5 = 0. No change.
  • E → exit, reward 1: δ=1+0−0.5=0.5\delta = 1 + 0 - 0.5 = 0.5, so V(E)=0.5+0.1×0.5=0.55V(E) = 0.5 + 0.1 \times 0.5 = 0.55.

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: δ=0+0.5−0.5=0\delta = 0 + 0.5 - 0.5 = 0. No change.
  • D → E: δ=0+0.55−0.5=0.05\delta = 0 + 0.55 - 0.5 = 0.05, so V(D)=0.505V(D) = 0.505.
  • E → exit: δ=1−0.55=0.45\delta = 1 - 0.55 = 0.45, so V(E)=0.595V(E) = 0.595.

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?

∂ Why the TD errors add up to the Monte Carlo error

Hold VV fixed during an episode (no updates until the end). The return satisfies Gt=rt+γGt+1G_t = r_t + \gamma G_{t+1}. Add and subtract γV(st+1)\gamma V(s_{t+1}):

Gt−V(st)=rt+γV(st+1)−V(st)⏟δt+γ(Gt+1−V(st+1)).G_t - V(s_t) = \underbrace{r_t + \gamma V(s_{t+1}) - V(s_t)}_{\delta_t} + \gamma \big( G_{t+1} - V(s_{t+1}) \big).

Apply the same step to Gt+1−V(st+1)G_{t+1} - V(s_{t+1}), and again, until the episode ends. At the end, GT=0G_T = 0 and V(sT)=0V(s_T) = 0, so the last term vanishes:

Gt−V(st)=δt+γδt+1+γ2δt+2+⋯+γT−t−1δT−1=∑k=0T−t−1γkδt+k.G_t - V(s_t) = \delta_t + \gamma \delta_{t+1} + \gamma^2 \delta_{t+2} + \dots + \gamma^{T-t-1} \delta_{T-1} = \sum_{k=0}^{T-t-1} \gamma^k \delta_{t+k}.

The Monte Carlo error is the discounted sum of the TD errors along the way. In the commute, γ=1\gamma = 1 and the sum was 10−5+5+3=1310 - 5 + 5 + 3 = 13. When VV 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 α\alpha. 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 (γλ)k(\gamma\lambda)^k.

Monte Carlo vs. TD: bias and variance

Both methods have the form “move V(st)V(s_t) toward a target”. They differ only in the target, so compare the targets as estimators of the thing we want, Vπ(st)V^\pi(s_t).

Bias. The MC target GtG_t has expectation exactly Vπ(st)V^\pi(s_t). That is the definition of VπV^\pi. It is unbiased, whatever your current estimates are. The TD target has expectation

E[rt+γV(st+1)∣st=s]=E[rt+γVπ(st+1)∣st=s]+γ E[V(st+1)−Vπ(st+1)∣st=s].\mathbb{E}\big[ r_t + \gamma V(s_{t+1}) \mid s_t = s \big] = \mathbb{E}\big[ r_t + \gamma V^\pi(s_{t+1}) \mid s_t = s \big] + \gamma\, \mathbb{E}\big[ V(s_{t+1}) - V^\pi(s_{t+1}) \mid s_t = s \big].

The first term is Vπ(s)V^\pi(s) by the Bellman equation. The second term is the error of your current estimates one step ahead. So the TD target is biased whenever VV is wrong, which early in learning is always. The bias shrinks as VV improves, and vanishes at V=VπV = V^\pi.

Variance. GtG_t depends on every random action, transition and reward from tt 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 00 or 11 with probability 12\tfrac12 each, so its variance is 14\tfrac14. The TD target from C is V(B)=13V(B) = \tfrac13 or V(D)=23V(D) = \tfrac23, so its variance is (16)2=136(\tfrac16)^2 = \tfrac1{36}. 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 V←V+α(TπV−V)V \leftarrow V + \alpha(\mathcal{T}^\pi V - V), where Tπ\mathcal{T}^\pi is the Bellman operator from Chapter 4. That is a damped version of the iteration you proved converges there, because Tπ\mathcal{T}^\pi 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.

Interactive TD(0) vs. Monte Carlo on the random walk

Press +1 episode to watch one walk, or Play.

Value estimates (this run)
RMS error (vs. true values) per episode
stateABCDERMS err
true0.1670.3330.5000.6670.8330
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.

  1. TD learns faster on average. With α=0.1\alpha = 0.1 for both methods, TD’s averaged error after 100 episodes is around 0.0550.055. MC’s is around 0.140.14, more than twice as large. Even at its best step size (around α=0.02\alpha = 0.02), MC ends near 0.080.08, while TD at α=0.05\alpha = 0.05 gets below 0.040.04.
  2. 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 α\alpha times the target’s variance, which is why MC’s floor is higher.
  3. 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 VπV^\pi for a fixed policy if every state keeps being visited and the step sizes shrink in the usual way (∑kαk=∞\sum_k \alpha_k = \infty and ∑kαk2<∞\sum_k \alpha_k^2 < \infty, the Robbins–Monro conditions). With a small constant α\alpha it converges in the mean and then hovers near VπV^\pi, 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 V(B)=68=0.75V(B) = \tfrac68 = 0.75. For A they disagree. Batch Monte Carlo averages the returns that followed A. There is only one, and it was 00, so V(A)=0V(A) = 0. Batch TD notices that A always led to B with reward 00, so V(A)=0+V(B)=0.75V(A) = 0 + V(B) = 0.75.

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 68\tfrac68) 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?

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 nn real rewards and then bootstraps from the estimate nn steps ahead:

Gt:t+n=rt+γrt+1+⋯+γn−1rt+n−1+γnV(st+n).G_{t:t+n} = r_t + \gamma r_{t+1} + \dots + \gamma^{n-1} r_{t+n-1} + \gamma^n V(s_{t+n}).

If the episode ends before t+nt + n, the bootstrap term is dropped and Gt:t+nG_{t:t+n} is just GtG_t. For n=1n = 1 this is the TD(0) target. For nn at least as long as the episode it is the MC target. The n-step update moves V(st)V(s_t) toward Gt:t+nG_{t:t+n}, and it must wait nn 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 nn is often best. Rather than pick one nn, 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 VV you have to look one step ahead:

π(s)=arg⁡max⁡a[r(s,a)+γ∑s′P(s′∣s,a) V(s′)].\pi(s) = \arg\max_a \Big[ r(s, a) + \gamma \sum_{s'} P(s' \mid s, a)\, V(s') \Big].

That needs PP and rr, which we no longer have. Acting greedily with respect to QQ needs neither: π(s)=arg⁡max⁡aQ(s,a)\pi(s) = \arg\max_a Q(s, a). The action values already contain the one-step lookahead. So every control method in this chapter learns a table Q(s,a)Q(s, a).

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 ϵ\epsilon take a uniformly random action, otherwise take arg⁡max⁡aQ(s,a)\arg\max_a Q(s, a) (breaking ties at random). Every action keeps a probability of at least ϵ/∣A∣\epsilon / \lvert \mathcal{A} \rvert.

All three algorithms below share the same loop and the same form of update:

Q(st,at)  ←  Q(st,at)+α(target−Q(st,at)).Q(s_t, a_t) \;\leftarrow\; Q(s_t, a_t) + \alpha \big( \text{target} - Q(s_t, a_t) \big).

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 QπQ^\pi,

Qπ(s,a)=Eπ[ rt+γ Qπ(st+1,at+1)  ∣  st=s,at=a ],Q^\pi(s, a) = \mathbb{E}_\pi\big[\, r_t + \gamma\, Q^\pi(s_{t+1}, a_{t+1}) \;\big|\; s_t = s, a_t = a \,\big],

and replace the expectation with one sample, exactly as before:

Q(st,at)  ←  Q(st,at)+α(rt+γ Q(st+1,at+1)−Q(st,at)).Q(s_t, a_t) \;\leftarrow\; Q(s_t, a_t) + \alpha \big( r_t + \gamma\, Q(s_{t+1}, a_{t+1}) - Q(s_t, a_t) \big).

The update uses the five quantities (st,at,rt,st+1,at+1)(s_t, a_t, r_t, s_{t+1}, a_{t+1}), which is where the name SARSA comes from. The important detail is at+1a_{t+1}: 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 at+1a_{t+1} comes from the ε-greedy policy, the target is a sample of the Bellman equation for the ε-greedy policy. SARSA therefore learns QQ for the policy it is actually following, exploration included. Meanwhile that policy keeps getting greedier with respect to the improving QQ. That is GPI with one sample per evaluation step. If you also let ϵ\epsilon 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:

Q(st,at)  ←  Q(st,at)+α(rt+γmax⁡a′Q(st+1,a′)−Q(st,at)).Q(s_t, a_t) \;\leftarrow\; Q(s_t, a_t) + \alpha \big( r_t + \gamma \max_{a'} Q(s_{t+1}, a') - Q(s_t, a_t) \big).

This is a sampled version of the Bellman optimality equation for Q∗Q^* from Chapter 4. You can read Q-learning as value iteration on QQ, with one sampled transition in place of the exact sum over s′s'. Its fixed point is Q∗Q^*, 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 bb is the one that chooses the actions that generate the data. Here it is ε-greedy.
  • The target policy π\pi is the one whose values you are learning. For Q-learning it is the greedy policy, the one that would take arg⁡max⁡aQ(s,a)\arg\max_a Q(s, a) 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. Q(s,a)Q(s, a) is defined given that action aa was taken in ss, so how aa was chosen does not matter. The next state s′s' and reward rr 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 Q∗Q^* 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 π\pi from whole Monte Carlo returns generated by a different policy bb, you would have to reweight each return by the product of ratios π(ak∣sk)/b(ak∣sk)\pi(a_k \mid s_k) / b(a_k \mid s_k) along the episode. That product is an importance-sampling correction, and over long episodes its variance can explode. Importance ratios come back as ρt(θ)\rho_t(\theta) 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?

Expected SARSA: average instead of sample

SARSA’s target uses one sampled next action at+1a_{t+1}. 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:

Q(st,at)  ←  Q(st,at)+α(rt+γ∑a′π(a′∣st+1) Q(st+1,a′)−Q(st,at)).Q(s_t, a_t) \;\leftarrow\; Q(s_t, a_t) + \alpha \Big( r_t + \gamma \sum_{a'} \pi(a' \mid s_{t+1})\, Q(s_{t+1}, a') - Q(s_t, a_t) \Big).

This is Expected SARSA. In expectation it makes the same update as SARSA, but without the randomness of at+1a_{t+1}, so it tolerates larger step sizes. For an ε-greedy π\pi over ∣A∣\lvert\mathcal{A}\rvert actions, the sum is ϵ⋅meana′Q(s′,a′)+(1−ϵ)max⁡a′Q(s′,a′)\epsilon \cdot \text{mean}_{a'} Q(s', a') + (1 - \epsilon) \max_{a'} Q(s', a'). It also unifies the family. If π\pi is the ε-greedy behavior policy, Expected SARSA is on-policy, like SARSA. If π\pi is greedy, the sum collapses to max⁡a′Q(s′,a′)\max_{a'} Q(s', a') and Expected SARSA is Q-learning.

MethodTargetLearns the values ofOn/off-policy
SARSArt+γ Q(st+1,at+1)r_t + \gamma\, Q(s_{t+1}, a_{t+1})the ε-greedy policy it followson
Expected SARSArt+γ∑a′π(a′∣st+1) Q(st+1,a′)r_t + \gamma \sum_{a'} \pi(a' \mid s_{t+1})\, Q(s_{t+1}, a')π\pi (usually the ε-greedy policy)on (off if π≠b\pi \neq b)
Q-learningrt+γmax⁡a′Q(st+1,a′)r_t + \gamma \max_{a'} Q(s_{t+1}, a')the greedy policy, so Q∗Q^*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 −1-1. Stepping into the cliff costs −100-100 and sends you back to S. The episode ends at G, and γ=1\gamma = 1.

The optimal path walks along the edge of the cliff: up one, right eleven, down one, 13 steps, return −13-13. 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.

Interactive SARSA vs. Q-learning on the cliff
SARSA
Q-learning

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).

Return per episode while learning (average of the last 20 episodes)
SARSAQ-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 (ϵ=0.1\epsilon = 0.1, α=0.5\alpha = 0.5) 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 ϵ/4=2.5%\epsilon/4 = 2.5\% 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 −25-25, against around −50-50 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 ϵ\epsilon 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?

Maximization bias and Double Q-learning

Q-learning’s max hides a trap. Suppose that in some state all ten actions have true value 00, but your estimates are noisy: each Q(s,a)Q(s, a) equals the truth plus independent noise with standard deviation 1. The true value of the best action is 00. The expected value of your estimated max is not. The maximum of ten independent standard normal samples has expectation about 1.541.54. Taking the max of noisy estimates selects the ones whose noise happens to be positive. In general,

E[max⁡aQ^(a)]  ≥  max⁡aE[Q^(a)],\mathbb{E}\big[\max_a \hat{Q}(a)\big] \;\ge\; \max_a \mathbb{E}\big[\hat{Q}(a)\big],

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, QAQ_A and QBQ_B. On each step, flip a coin. On heads, update QAQ_A, letting QAQ_A pick the action and QBQ_B say what it is worth:

QA(st,at)  ←  QA(st,at)+α(rt+γ QB(st+1,arg⁡max⁡a′QA(st+1,a′))−QA(st,at)).Q_A(s_t, a_t) \;\leftarrow\; Q_A(s_t, a_t) + \alpha \Big( r_t + \gamma\, Q_B\big(s_{t+1}, \arg\max_{a'} Q_A(s_{t+1}, a')\big) - Q_A(s_t, a_t) \Big).

On tails, swap the roles of A and B. Act ε-greedily with respect to QA+QBQ_A + Q_B. Because QBQ_B‘s noise is independent of the choice QAQ_A 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 QBQ_B, becomes Double DQN in Chapter 6.

Summary

  • Model-free methods learn values from sampled experience, with no access to PP or rr.
  • Monte Carlo moves V(st)V(s_t) toward the observed return GtG_t. The target is unbiased but high-variance, and it is only available when the episode ends.
  • TD(0) moves V(st)V(s_t) toward rt+γV(st+1)r_t + \gamma V(s_{t+1}), using the TD error δt=rt+γV(st+1)−V(st)\delta_t = r_t + \gamma V(s_{t+1}) - V(s_t). 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 Q∗Q^* 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

Exercise 5.1MC and TD updates by handPen & paper●○○

Three states X, Y, Z. Current estimates V(X)=1V(X) = 1, V(Y)=2V(Y) = 2, V(Z)=0V(Z) = 0. Step size α=0.5\alpha = 0.5, discount γ=0.9\gamma = 0.9. You observe one episode:

X→  r0=1  Y→  r1=0  Z→  r2=4  terminal.X \xrightarrow{\;r_0 = 1\;} Y \xrightarrow{\;r_1 = 0\;} Z \xrightarrow{\;r_2 = 4\;} \text{terminal}.

(a) Compute the returns G0,G1,G2G_0, G_1, G_2 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 V(Y)V(Y) in the “wrong” direction compared with the other, and why?

Solution

(a) Work backward. G2=4G_2 = 4. G1=r1+γG2=0+0.9×4=3.6G_1 = r_1 + \gamma G_2 = 0 + 0.9 \times 4 = 3.6. G0=r0+γG1=1+0.9×3.6=4.24G_0 = r_0 + \gamma G_1 = 1 + 0.9 \times 3.6 = 4.24. Then

  • V(X)=1+0.5 (4.24−1)=2.62V(X) = 1 + 0.5\,(4.24 - 1) = 2.62
  • V(Y)=2+0.5 (3.6−2)=2.8V(Y) = 2 + 0.5\,(3.6 - 2) = 2.8
  • V(Z)=0+0.5 (4−0)=2V(Z) = 0 + 0.5\,(4 - 0) = 2

(b) Online, in order:

  • δ0=1+0.9×V(Y)−V(X)=1+1.8−1=1.8\delta_0 = 1 + 0.9 \times V(Y) - V(X) = 1 + 1.8 - 1 = 1.8, so V(X)=1+0.5×1.8=1.9V(X) = 1 + 0.5 \times 1.8 = 1.9.
  • δ1=0+0.9×V(Z)−V(Y)=0+0−2=−2\delta_1 = 0 + 0.9 \times V(Z) - V(Y) = 0 + 0 - 2 = -2, so V(Y)=2+0.5×(−2)=1V(Y) = 2 + 0.5 \times (-2) = 1.
  • δ2=4+0−V(Z)=4\delta_2 = 4 + 0 - V(Z) = 4 (Z → terminal), so V(Z)=0+0.5×4=2V(Z) = 0 + 0.5 \times 4 = 2.

New estimates: V=(1.9, 1, 2)V = (1.9,\ 1,\ 2).

(c) V(Y)V(Y). Monte Carlo raised it (toward the actual 3.6), while TD lowered it (toward 0+0.9×V(Z)=00 + 0.9 \times V(Z) = 0). TD bootstrapped from V(Z)=0V(Z) = 0, which was a bad estimate: Z was about to pay 4. This is TD’s bias in action. Once V(Z)V(Z) 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.

Exercise 5.2The MC target is unbiased; the TD target is notPen & paper●●○

Fix a policy π\pi and let VV be any current estimate (a fixed table, not random).

(a) Show that Eπ[Gt∣st=s]=Vπ(s)\mathbb{E}_\pi[G_t \mid s_t = s] = V^\pi(s).

(b) Show that the bias of the TD target, Eπ[rt+γV(st+1)∣st=s]−Vπ(s)\mathbb{E}_\pi[r_t + \gamma V(s_{t+1}) \mid s_t = s] - V^\pi(s), equals γ Eπ[V(st+1)−Vπ(st+1)∣st=s]\gamma\, \mathbb{E}_\pi[V(s_{t+1}) - V^\pi(s_{t+1}) \mid s_t = s], and that its absolute value is at most γmax⁡s′∣V(s′)−Vπ(s′)∣\gamma \max_{s'} \lvert V(s') - V^\pi(s') \rvert.

(c) Consider an idealized, averaged TD(0): every state is updated at once, toward its expected TD target. That is V←V+α(TπV−V)V \leftarrow V + \alpha (\mathcal{T}^\pi V - V), where (TπV)(s)=Eπ[rt+γV(st+1)∣st=s](\mathcal{T}^\pi V)(s) = \mathbb{E}_\pi[r_t + \gamma V(s_{t+1}) \mid s_t = s] is the Bellman operator from Chapter 4. Use the contraction property from Chapter 4 to show that this iteration converges to VπV^\pi for 0<α≤10 < \alpha \le 1 and γ<1\gamma < 1, despite the bias of every target along the way.

Hint
For (b), add and subtract γVπ(st+1)\gamma V^\pi(s_{t+1}) inside the expectation and use the Bellman equation. For (c), write the update as V←(1−α)V+αTπVV \leftarrow (1 - \alpha) V + \alpha \mathcal{T}^\pi V and bound ∥Vk+1−Vπ∥∞\lVert V_{k+1} - V^\pi \rVert_\infty using Vπ=(1−α)Vπ+αTπVπV^\pi = (1 - \alpha) V^\pi + \alpha \mathcal{T}^\pi V^\pi.
Solution

(a) This is the definition of the state value: Vπ(s):=Eπ[Gt∣st=s]V^\pi(s) := \mathbb{E}_\pi[G_t \mid s_t = s]. 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 γVπ(st+1)\gamma V^\pi(s_{t+1}):

Eπ[rt+γV(st+1)∣s]=Eπ[rt+γVπ(st+1)∣s]⏟=Vπ(s) (Bellman)+γ Eπ[V(st+1)−Vπ(st+1)∣s].\mathbb{E}_\pi[r_t + \gamma V(s_{t+1}) \mid s] = \underbrace{\mathbb{E}_\pi[r_t + \gamma V^\pi(s_{t+1}) \mid s]}_{= V^\pi(s) \text{ (Bellman)}} + \gamma\, \mathbb{E}_\pi[V(s_{t+1}) - V^\pi(s_{t+1}) \mid s].

Subtract Vπ(s)V^\pi(s) to get the bias. An expectation of a quantity is at most the quantity’s largest absolute value, so ∣bias∣≤γmax⁡s′∣V(s′)−Vπ(s′)∣\lvert \text{bias} \rvert \le \gamma \max_{s'} \lvert V(s') - V^\pi(s') \rvert. The bias is zero for every ss when V=VπV = V^\pi.

(c) Let Vk+1=(1−α)Vk+αTπVkV_{k+1} = (1 - \alpha) V_k + \alpha \mathcal{T}^\pi V_k. Since Vπ=TπVπV^\pi = \mathcal{T}^\pi V^\pi, also Vπ=(1−α)Vπ+αTπVπV^\pi = (1 - \alpha) V^\pi + \alpha \mathcal{T}^\pi V^\pi. Subtract and use the triangle inequality and the contraction ∥TπU−TπW∥∞≤γ∥U−W∥∞\lVert \mathcal{T}^\pi U - \mathcal{T}^\pi W \rVert_\infty \le \gamma \lVert U - W \rVert_\infty:

∥Vk+1−Vπ∥∞≤(1−α)∥Vk−Vπ∥∞+αγ∥Vk−Vπ∥∞=(1−α(1−γ))∥Vk−Vπ∥∞.\lVert V_{k+1} - V^\pi \rVert_\infty \le (1 - \alpha) \lVert V_k - V^\pi \rVert_\infty + \alpha \gamma \lVert V_k - V^\pi \rVert_\infty = \big(1 - \alpha (1 - \gamma)\big) \lVert V_k - V^\pi \rVert_\infty .

The factor 1−α(1−γ)1 - \alpha(1 - \gamma) lies in [0,1)[0, 1) for 0<α≤10 < \alpha \le 1 and γ<1\gamma < 1, 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 α\alpha handle that noise.)

Exercise 5.3TD errors add up to the Monte Carlo errorPen & paper●●○

(a) Prove that if VV is held fixed during an episode, Gt−V(st)=∑k=0T−t−1γkδt+kG_t - V(s_t) = \sum_{k=0}^{T-t-1} \gamma^k \delta_{t+k}.

(b) Check the identity on the episode of Exercise 5.1 for t=0t = 0, using the original estimates.

(c) In Exercise 5.1(b), TD updated VV during the episode, yet the TD errors you computed are the same as with VV fixed. Why, in that particular episode? Construct a short episode in which they would differ. Does the identity of (a) still hold, at t=0t = 0, for the online TD errors of your episode?

Hint
For (a), start from Gt=rt+γGt+1G_t = r_t + \gamma G_{t+1} and add zero in the form γV(st+1)−γV(st+1)\gamma V(s_{t+1}) - \gamma V(s_{t+1}), then unroll. For (c), the TD error at step tt reads V(st)V(s_t) and V(st+1)V(s_{t+1}). Which states had already been updated when they were read? For the last question, just compute both sides.
Solution

(a) Using Gt=rt+γGt+1G_t = r_t + \gamma G_{t+1},

Gt−V(st)=rt+γV(st+1)−V(st)+γ(Gt+1−V(st+1))=δt+γ(Gt+1−V(st+1)).G_t - V(s_t) = r_t + \gamma V(s_{t+1}) - V(s_t) + \gamma \big( G_{t+1} - V(s_{t+1}) \big) = \delta_t + \gamma \big( G_{t+1} - V(s_{t+1}) \big).

Unrolling gives δt+γδt+1+⋯+γT−t−1δT−1+γT−t(GT−V(sT))\delta_t + \gamma \delta_{t+1} + \dots + \gamma^{T-t-1}\delta_{T-1} + \gamma^{T-t}(G_T - V(s_T)), and the last term is zero because GT=0G_T = 0 and V(terminal)=0V(\text{terminal}) = 0.

(b) Left side: G0−V(X)=4.24−1=3.24G_0 - V(X) = 4.24 - 1 = 3.24. Right side, with δ=(1.8,−2,4)\delta = (1.8, -2, 4): 1.8+0.9×(−2)+0.81×4=1.8−1.8+3.24=3.241.8 + 0.9 \times (-2) + 0.81 \times 4 = 1.8 - 1.8 + 3.24 = 3.24. They agree.

(c) The TD error at step tt reads V(st)V(s_t) and V(st+1)V(s_{t+1}). In that episode each state appears once, and each state is updated only after its own TD error is computed. So δt\delta_t always read original values: V(st)V(s_t) had not been updated yet, and V(st+1)V(s_{t+1}) is updated later. The individual errors change when a state is revisited. Same V(X)=1V(X) = 1, V(Y)=2V(Y) = 2, α=0.5\alpha = 0.5, γ=0.9\gamma = 0.9, episode X→1Y→0X→4X \xrightarrow{1} Y \xrightarrow{0} X \xrightarrow{4} terminal. With VV fixed: δ=(1.8, 0+0.9×1−2, 4−1)=(1.8, −1.1, 3)\delta = (1.8,\ 0 + 0.9 \times 1 - 2,\ 4 - 1) = (1.8,\ -1.1,\ 3). Online: δ0=1.8\delta_0 = 1.8 raises V(X)V(X) to 1.91.9; then δ1=0+0.9×1.9−2=−0.29\delta_1 = 0 + 0.9 \times 1.9 - 2 = -0.29, and δ2=4−1.9=2.1\delta_2 = 4 - 1.9 = 2.1. The second visit to X reads a value that the first visit already changed, so the online errors differ from the fixed-VV ones, by amounts proportional to α\alpha.

Now the surprise. The return is G0=1+0.9×(0+0.9×4)=4.24G_0 = 1 + 0.9 \times (0 + 0.9 \times 4) = 4.24, so G0−V(X)=3.24G_0 - V(X) = 3.24 with the original V(X)=1V(X) = 1. The online errors give 1.8+0.9×(−0.29)+0.81×2.1=1.8−0.261+1.701=3.241.8 + 0.9 \times (-0.29) + 0.81 \times 2.1 = 1.8 - 0.261 + 1.701 = 3.24. The identity still holds exactly. The reason: the sum telescopes because the value of st+1s_{t+1} that δt\delta_t reads (as “next state”) is cancelled by the value of st+1s_{t+1} that δt+1\delta_{t+1} reads (as “current state”). Between those two reads, the only update is to V(st)V(s_t). So the cancellation fails only if st+1=sts_{t+1} = s_t, a state that transitions to itself. Then the identity picks up an extra term γk−t+1αδk\gamma^{k-t+1} \alpha \delta_k for each such step kk. That is the “correction of order α\alpha” mentioned in the main text.

Exercise 5.4Same data, two answersPen & paper●●○

You are given five episodes (γ = 1) and asked to replay them until each method converges (“batch” updating):

  1. A → B with reward 0, then B → exit with reward 0.
  2. B → exit with reward 1.
  3. B → exit with reward 1.
  4. B → exit with reward 1.
  5. A → exit with reward 0.

(a) What does batch Monte Carlo give for V(A)V(A) and V(B)V(B)?

(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
For (b), at convergence V(s)V(s) equals the average of r+V(s′)r + V(s') over all transitions observed out of ss, with V(exit)=0V(\text{exit}) = 0. B appears in four episodes; A in two.
Solution

(a) MC averages observed returns. B was visited in episodes 1–4 with returns 0,1,1,10, 1, 1, 1, so V(B)=3/4V(B) = 3/4. A was visited in episodes 1 and 5, with returns 00 and 00, so V(A)=0V(A) = 0.

(b) Batch TD’s fixed point makes the average TD error zero at each state, so V(s)V(s) is the average of r+V(s′)r + V(s') over the transitions out of ss. Out of B: four transitions to exit with rewards 0,1,1,10, 1, 1, 1, so V(B)=3/4V(B) = 3/4. Out of A: one transition to B with reward 0 (target 0+V(B)=3/40 + V(B) = 3/4) and one to exit with reward 0 (target 00). So V(A)=12(3/4+0)=3/8V(A) = \tfrac12 (3/4 + 0) = 3/8.

(c) Maximum-likelihood model: from A, go to B with probability 1/21/2 and exit with probability 1/21/2, reward 0 either way. From B, exit with expected reward 3/43/4. Solving: V(B)=3/4V(B) = 3/4 and V(A)=12(0+V(B))+12⋅0=3/8V(A) = \tfrac12 (0 + V(B)) + \tfrac12 \cdot 0 = 3/8. 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 3/83/8 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.

Exercise 5.5Why is Q-learning off-policy?Concept●●○

(a) In two or three sentences, explain why SARSA learns the values of the ε-greedy policy while Q-learning learns Q∗Q^*, 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 ϵ=0\epsilon = 0 in both, are their updates the same? Is that a good way to make SARSA learn Q∗Q^*?

(d) Q-learning never needs importance-sampling ratios. Off-policy Monte Carlo does. What is the difference?

Hint
Look at where a policy appears in each target, and ask which policy it is. For (d), ask what in an MC return depends on actions chosen after step t.
Solution

(a) In SARSA’s target r+γQ(s′,a′)r + \gamma Q(s', a'), the next action a′a' is drawn from the ε-greedy policy, so on average the target is the Bellman backup of the ε-greedy policy. Q-learning’s target r+γmax⁡a′Q(s′,a′)r + \gamma \max_{a'} Q(s', a') 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 π\pi):

Q(s,a)=r(s,a)+γ∑s′P(s′∣s,a)∑a′π(a′∣s′) Q(s′,a′),Q(s, a) = r(s, a) + \gamma \sum_{s'} P(s' \mid s, a) \sum_{a'} \pi(a' \mid s')\, Q(s', a'),

the Bellman expectation equation for QπQ^\pi, so Q=QπQ = Q^\pi with π\pi ε-greedy. Q-learning:

Q(s,a)=r(s,a)+γ∑s′P(s′∣s,a)max⁡a′Q(s′,a′),Q(s, a) = r(s, a) + \gamma \sum_{s'} P(s' \mid s, a) \max_{a'} Q(s', a'),

the Bellman optimality equation, whose solution is Q∗Q^*.

(c) With ϵ=0\epsilon = 0 both choose a′=arg⁡max⁡Q(s′,⋅)a' = \arg\max Q(s', \cdot), so the updates are essentially identical. (There are small differences: SARSA picks a′a' before updating Q(s,a)Q(s, a), which matters if s′=ss' = s, and random tie-breaking may pick different actions.) But it is a poor way to get Q∗Q^*: 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 GtG_t contains rewards from all the steps after tt, and those depend on the actions chosen at all those steps by the behavior policy. To turn an average under bb into an average under π\pi, you must reweight by the probability ratio of that whole action sequence, ∏kπ(ak∣sk)/b(ak∣sk)\prod_k \pi(a_k \mid s_k) / b(a_k \mid s_k). Q-learning’s one-step target contains only one real transition, (s,a,r,s′)(s, a, r, s'). That transition is conditioned on aa (so how aa was chosen is irrelevant) and on the environment (which no policy controls), and everything after s′s' is summarized by max⁡a′Q(s′,a′)\max_{a'} Q(s', a'), which already follows the target policy. No step in the target was generated by the behavior policy, so there is nothing to reweight.

Exercise 5.6Expected SARSA by handPen & paper●○○

Four actions. In the next state s′s' the current estimates are Q(s′,⋅)=(1,3,2,0)Q(s', \cdot) = (1, 3, 2, 0). You took action aa in ss, received r=−1r = -1, and Q(s,a)=0.5Q(s, a) = 0.5. Use γ=0.9\gamma = 0.9, α=0.5\alpha = 0.5, and an ε-greedy policy with ϵ=0.2\epsilon = 0.2.

(a) Write down π(⋅∣s′)\pi(\cdot \mid s') and compute the Expected SARSA target and the updated Q(s,a)Q(s, a).

(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 Q(s′,⋅)Q(s', \cdot), the Expected SARSA target with ε-greedy π\pi equals r+γ[ϵ meana′Q(s′,a′)+(1−ϵ)max⁡a′Q(s′,a′)]r + \gamma[\epsilon\, \text{mean}_{a'} Q(s', a') + (1 - \epsilon) \max_{a'} Q(s', a')], and that it equals the Q-learning target when ϵ=0\epsilon = 0.

Solution

(a) The greedy action is action 2 (value 3). Each action gets ϵ/4=0.05\epsilon / 4 = 0.05, and the greedy one gets an extra 0.80.8: π=(0.05, 0.85, 0.05, 0.05)\pi = (0.05,\ 0.85,\ 0.05,\ 0.05). Expected next value: 0.05×1+0.85×3+0.05×2+0.05×0=0.05+2.55+0.10=2.70.05 \times 1 + 0.85 \times 3 + 0.05 \times 2 + 0.05 \times 0 = 0.05 + 2.55 + 0.10 = 2.7. Target: −1+0.9×2.7=1.43-1 + 0.9 \times 2.7 = 1.43. Update: Q(s,a)=0.5+0.5 (1.43−0.5)=0.965Q(s, a) = 0.5 + 0.5\,(1.43 - 0.5) = 0.965.

(b) Q-learning: −1+0.9×3=1.7-1 + 0.9 \times 3 = 1.7. SARSA with sampled value 2: −1+0.9×2=0.8-1 + 0.9 \times 2 = 0.8. 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 a′a', SARSA’s target is exactly 1.43.

(c) Under ε-greedy, π(a′∣s′)=ϵ/∣A∣\pi(a' \mid s') = \epsilon / \lvert\mathcal{A}\rvert for every action, plus (1−ϵ)(1 - \epsilon) shared among the actions that achieve the max. So

∑a′π(a′∣s′)Q(s′,a′)=ϵ∣A∣∑a′Q(s′,a′)+(1−ϵ)max⁡a′Q(s′,a′).\sum_{a'} \pi(a' \mid s') Q(s', a') = \frac{\epsilon}{\lvert\mathcal{A}\rvert} \sum_{a'} Q(s', a') + (1 - \epsilon) \max_{a'} Q(s', a').

(Ties do not matter: every tied action has the max value, however the 1−ϵ1 - \epsilon is split.) The first term is ϵ\epsilon times the mean. At ϵ=0\epsilon = 0 only max⁡a′Q(s′,a′)\max_{a'} Q(s', a') remains, which is the Q-learning target. Check with (a): 0.2×1.5+0.8×3=0.3+2.4=2.70.2 \times 1.5 + 0.8 \times 3 = 0.3 + 2.4 = 2.7.

Exercise 5.7Explaining the cliffExplore the demo●●○

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
(c) All rewards are negative and Q starts at 0. Compare with “optimistic initial values” in Chapter 2. (d) With α = 1, each update replaces Q(s, a) with the target. Which targets are random in this deterministic environment?
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 Q∗Q^*, 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 0.1/40.1/4, so it falls with probability roughly 1−0.97511≈0.241 - 0.975^{11} \approx 0.24 per episode or more, at −100-100 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, Q(s,a)Q(s, a) is overwritten by the latest target, and SARSA’s target r+γQ(s′,a′)r + \gamma Q(s', a') depends on the sampled a′a'. One exploratory a′a' (say, toward the cliff) replaces a good value with a terrible one, and the next greedy a′a' 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.

Exercise 5.8Reading the random-walk demoExplore the demo●○○

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 0+0.5−0.5=00 + 0.5 - 0.5 = 0. Only the final transition sees a terminal value of 0 and a reward of 0 or 1, so only its error is nonzero (±0.5\pm 0.5).

(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 1/α1/\alpha samples. It never averages more than that many, so it keeps fluctuating with variance roughly proportional to α\alpha times the variance of the target. For state C, the MC target (0 or 1) has variance 1/41/4 while the TD target (near 1/31/3 or 2/32/3) has variance about 1/361/36, so MC’s floor is much higher. Decaying step sizes (for example αk=1/k\alpha_k = 1/k) remove the floor at the cost of slower adaptation.

Exercise 5.9How big is maximization bias?Pen & paper●●●

A state has two actions, both with true value 0. Your estimates are Q^(1)=X1\hat Q(1) = X_1 and Q^(2)=X2\hat Q(2) = X_2, independent, each N(0,σ2)\mathcal{N}(0, \sigma^2).

(a) Compute E[max⁡(X1,X2)]\mathbb{E}[\max(X_1, X_2)] exactly.

(b) Double Q-learning uses a second, independent pair of estimates Y1,Y2∼N(0,σ2)Y_1, Y_2 \sim \mathcal{N}(0, \sigma^2). It picks a∗=arg⁡max⁡aXaa^* = \arg\max_a X_a and reports Ya∗Y_{a^*}. Compute E[Ya∗]\mathbb{E}[Y_{a^*}].

(c) Now suppose the true values are μ1=0\mu_1 = 0 and μ2=−1\mu_2 = -1 (same noise). Without computing anything exactly, argue that the double estimator can be biased downward.

Hint
(a) Write max⁡(x,y)=12(x+y)+12∣x−y∣\max(x, y) = \tfrac12(x + y) + \tfrac12 \lvert x - y \rvert, and use E∣Z∣=s2/π\mathbb{E}\lvert Z \rvert = s\sqrt{2/\pi} for Z∼N(0,s2)Z \sim \mathcal{N}(0, s^2). (b) Condition on a∗a^*.
Solution

(a) max⁡(X1,X2)=12(X1+X2)+12∣X1−X2∣\max(X_1, X_2) = \tfrac12 (X_1 + X_2) + \tfrac12 \lvert X_1 - X_2 \rvert. The first term has mean 0. X1−X2∼N(0,2σ2)X_1 - X_2 \sim \mathcal{N}(0, 2\sigma^2), so E∣X1−X2∣=2 σ2/π=2σ/π\mathbb{E}\lvert X_1 - X_2 \rvert = \sqrt{2}\,\sigma \sqrt{2/\pi} = 2\sigma/\sqrt{\pi}. Hence

E[max⁡(X1,X2)]=σπ≈0.56 σ,\mathbb{E}[\max(X_1, X_2)] = \frac{\sigma}{\sqrt{\pi}} \approx 0.56\,\sigma,

even though the true maximum is 0. With ten actions it grows to about 1.54 σ1.54\,\sigma. Q-learning feeds this bias into every target that maxes over this state.

(b) a∗a^* depends only on the XX‘s, and the YY‘s are independent of the XX‘s. So, conditioning on a∗a^*: E[Ya∗∣a∗=a]=E[Ya]=0\mathbb{E}[Y_{a^*} \mid a^* = a] = \mathbb{E}[Y_a] = 0 for each aa, and therefore E[Ya∗]=0\mathbb{E}[Y_{a^*}] = 0. The double estimator is unbiased here. Choosing and evaluating with independent noise breaks the “pick whichever got lucky” effect.

(c) The true maximum is μ1=0\mu_1 = 0. With noise, the XX‘s sometimes pick action 2 by mistake. Then the double estimator reports Y2Y_2, whose mean is −1-1. So E[Ya∗]=P(a∗=1)⋅0+P(a∗=2)⋅(−1)<0\mathbb{E}[Y_{a^*}] = P(a^* = 1) \cdot 0 + P(a^* = 2) \cdot (-1) < 0: 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.

Exercise 5.10The lab: build all four learnersCode●●○

Download the lab below and work through td.py in order. Each task is a few lines.

  1. Task 1, mc_update: every-visit constant-α Monte Carlo (backward pass for returns, then forward updates).
  2. Task 2, td0_update: online TD(0).
  3. Task 3, epsilon_greedy, with random tie-breaking.
  4. Task 4, the three targets: sarsa_target, q_learning_target, expected_sarsa_target.
  5. Task 5, sarsa_episode and q_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
The hand-checkable tests use the numbers from Exercise 5.1 and from the two random-walk episodes in the TD(0) section, so if one fails, redo that calculation on paper and compare line by line. In Task 5 the two loops differ in exactly one structural way: SARSA must choose the next action before its update, because its target needs it.
Solution

The reference implementation is in solutions/td.py. The key lines:

  • mc_update: g = r_t + gamma * g walking backward to fill G[t], then V[s_t] += alpha * (G[t] - V[s_t]) walking forward.
  • td0_update: target = r if done else r + gamma * V[s_next], then V[s] += alpha * (target - V[s]), inside the loop, so later transitions see earlier updates.
  • epsilon_greedy: if rng.random() < epsilon: return rng.integers(n); else rng.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-learning r + gamma * Q[s_next].max(); Expected SARSA r + gamma * (epsilon * Q[s_next].mean() + (1 - epsilon) * Q[s_next].max()); all three return r when done.
  • sarsa_episode: choose a before the loop; inside, step, choose a_next, update with sarsa_target, then s, a = s_next, a_next.
  • q_learning_episode: choose a at the top of each iteration, step, update with q_learning_target, then s = 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 Q∗(0,right)=−2Q^*(0, \text{right}) = -2, while SARSA converges to the random policy’s value, −5-5. 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 pass

First 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 Q(s,a)Q(s, a) 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.