Model-free prediction and control: Monte Carlo, TD, SARSA, Q-learning

Learning values and policies from experience alone: Monte Carlo and TD, the n-step and TD(λ) dial, SARSA, Expected SARSA, Q-learning and Double Q-learning, importance sampling, and the deadly triad, with Sutton and Barto's figures rerun live beside each claim. A child page of Topic: rl. Sources checked October 2026. Reading: 34 min, plus 9 in closed details.

The idea in one screen

Without a model you cannot compute dynamic programming's expectation over next states, so you replace it with a sample: the whole return (Monte Carlo), or one real reward plus your own estimate of where you landed (TD). Every method on this page is one choice of that target: how many real rewards before it trusts an estimate (a bias-variance dial), and which next action it assumes (the one taken: on-policy; the best one: off-policy).

Two choices define every target: how far it looks, and which next action it trusts

  1. One episode of the walk. States A to E run across and time runs towards you: the episode of section 1 goes C, D, E, then off the right end, with rewards 0, 0 and 1. Every estimate starts at 0.5 (the bars).
  2. Dynamic programming: every successor, one step deep. From C the model says B or D, each with probability 0.5, so the target 0.5 × V(B) + 0.5 × V(D) = 0.5 averages them (both values stream into it). It needs those probabilities, which a model-free learner does not have.
  3. Monte Carlo: the whole sampled return. Wait for the end and use what actually happened, G = 1, which flows back along the episode. Real rewards are unbiased but carry every coin flip of the walk. With α = 0.1, V(C), V(D) and V(E) each move from 0.5 to 0.55.
  4. TD(0): one real reward, then trust V(D). The target is 0 + V(D) = 0.5, so the TD error is 0 and V(C) stays at 0.5. The bootstrapped estimate at the end of the bracket is low-noise and possibly wrong.
  5. Two real rewards, then V(E). G(2) = 0 + 0 + V(E) = 0.5. Each extra real reward moves the target towards Monte Carlo's.
  6. TD(λ) blends them. With λ = 0.5 the weights are 0.5, 0.25 and 0.25 on G(1), G(2) and the full return, so Gλ = 0.625, between TD's 0.5 and Monte Carlo's 1: the dial of section 2.
  7. The second choice: which next action. A different transition, the one of section 4: beside a cliff the agent moved right, R = −1, into S′. The bars are now costs (−Q): at S′, right is worth −4, up −5, left −6 and down, into the cliff, −100. Exploration happened to pick down.
  8. Three targets for Q(S, right). SARSA trusts the action actually taken: −1 + (−100) = −101. Expected SARSA averages over the ε-greedy policy (ε = 0.1): −7.475. Q-learning trusts the best action, whatever the agent does: −1 + (−4) = −5. The streams show where each draws from: SARSA from down alone, Expected SARSA from all four in proportion to their chance, Q-learning from right.

You need: the Bellman expectation backup and policy evaluation from Dynamic programming (this page samples its backups), and the loop, return and value vocabulary of Topic: rl (its Method atlas tab dates every method here). ε-greedy and other exploration rules are on Bandits and exploration.

Target, step size α
every update is estimate ← estimate + α(target − estimate); the methods differ only in the target.
Return Gt
Rt+1 + γRt+2 + ... to the end of the episode.
Bootstrapping
a target that contains an existing estimate. DP bootstraps without sampling, MC samples without bootstrapping, TD does both.
TD error δ
R + γV(S′) − V(S): the surprise on one step.
Prediction, control
estimating a fixed policy's values; finding a good policy.
On-, off-policy
learning about the policy that generates the data, or about a target policy π from data of a behaviour policy (b or μ).
Eligibility trace
a per-state memory of recent visits that lets each TD error update earlier states.
Importance ratio ρ
∏ π(A|S) / b(A|S), how much more likely the target policy was to act this way.
Deadly triad
function approximation + bootstrapping + off-policy data: together they can diverge.
MethodThe target (what stands in for the expectation)Bias and varianceWhose values
Monte CarloThe whole sampled return Gt to the end of the episodeUnbiased; high variance; needs episodes that endThe policy that generated the data (another one, with importance sampling)
TD(0)One real reward plus the current estimate, R + γV(S′)Biased by the estimate; low variance; one step of experienceThe policy that generated the data
n-step TD, TD(λ)n real rewards, then the estimate; or a geometric blend of all nA dial between the two above (n steps, or eligibility traces)The policy that generated the data
SARSAR + γQ(S′, A′), A′ the action actually taken nextAs TD(0)On-policy: the exploring policy it runs
Expected SARSAR + γ Σa π(a | S′) Q(S′, a)Removes the variance of the next actionEither; with a greedy π it is Q-learning
Q-learningR + γ maxa Q(S′, a)As TD(0), plus an upward maximisation biasOff-policy: the greedy policy, whatever the agent does
Double Q-learningR + γQ2(S′, argmaxa Q1(S′, a))Removes the maximisation bias; two tablesOff-policy, greedy
Off-policy Monte CarloThe return reweighted by the importance ratio ρOrdinary: unbiased, variance can be infinite; weighted: biased, low varianceAny target policy π covered by the behaviour b

Rows jump to their section. The modern targets are these ones: DQN regresses a network onto the Q-learning target, PPO's critic learns a TD target and its advantage is a TD(λ) average, and GRPO's end-of-sequence reward is a Monte Carlo return (section 8). Every chart below reruns a figure of Sutton and Barto's book live and seeded; numbers are published with the source linked, unless marked derived (computed here, formula shown) or illustrative.

1Monte Carlo and TD prediction: wait for the return, or trust the next estimate

The test problem is the five-state random walk (Sutton and Barto, Example 6.2): states A to E in a row, every episode starts in C and steps left or right with probability 0.5 until it falls off an end; falling off the right pays 1, every other reward is 0, γ = 1. So the true value of a state is its chance of ending on the right, Vπ = (1/6, 2/6, 3/6, 4/6, 5/6). Estimates start at 0.5; α = 0.1. One episode: C → D → E → off the right end, rewards 0, 0, 1.

TD(0) updates after every step

  • C → D: δ = 0 + 0.5 − 0.5 = 0, so V(C) stays 0.5.
  • D → E: δ = 0 + 0.5 − 0.5 = 0, so V(D) stays 0.5.
  • E → end: δ = 1 + 0 − 0.5 = 0.5, so V(E) becomes 0.5 + 0.1 × 0.5 = 0.55.

Monte Carlo waits for the end

Every visited state had return G = 1, so V(C), V(D) and V(E) each become 0.5 + 0.1 × (1 − 0.5) = 0.55.

MC moved three states by the full surprise; TD moved one. TD's information travels back one state per episode (next time the walk passes D → E, D's target is 0 + 0.55 and D rises to 0.505), but each TD target carries one step of randomness, while each MC credit carries the whole walk's luck. As updates:

MC: V(St) ← V(St) + α ( Gt − V(St) )     TD(0): V(St) ← V(St) + α ( Rt+1 + γV(St+1) − V(St) )
Gt
the return actually observed to the end of the episode, computed backwards as Gt = Rt+1 + γGt+1
Rt+1 + γV(St+1)
the TD target (V = 0 at a terminal state); its gap to V(St) is the TD error δt (Sutton 1988 named and introduced the method)
α
1/N(St), the visit count, gives MC the exact running mean; a constant α ("constant-α MC") forgets old episodes and tracks a changing problem

TD is DP's policy-evaluation backup, V(s) ← Eπ[R + γV(S′) | s], with the expectation replaced by one sample and a step of size α towards it: it "updates a guess towards a guess" (Silver, Lecture 4).

Predict, then play: over 100 walks, does any Monte Carlo step size end below the worst TD one?

The replay beside this opens after 10 walks, a point of the book's left graph; Play runs the rest a move at a time.

The same walks through TD(0) and Monte Carlo: TD's error stays lower at every step size

The book's left graph shows TD after episodes; jump there.
TD(0), α
Monte Carlo, α
RMS error, averaged over the five states and the runs

Bars: estimates; dashed: true values. Every TD curve stays below every MC curve; TD with α = 0.15 bottoms out and rises again (Exercise 6.5): a large constant step keeps reacting to the latest walks. The starting error is √(1/18) = 0.236. Batch mode replays all episodes so far to convergence: batch Monte Carlo gives each state the mean return seen after it, batch TD the values of the Markov chain estimated from the transitions (certainty equivalence, p. 128).

What the rerun checks, and what reproduces (live numbers)

    Example 6.2 (right graph) and Figure 6.2 reproduce in shape: the book gives its curves only as images, so values are not read off them. After one episode both batch methods give 0.412, above the top of the book's axis (0.25), so the book's plot must be cut off there; it does not say.

    Monte CarloTD
    TargetActual return GtR + γV(S′), bootstrapped
    Bias / varianceUnbiased / high: Gt carries every random action, transition and reward to the endBiased (the estimate may be wrong) / low: one step of randomness
    When it learnsAt the end of an episode; episodic tasks onlyAfter every step; continuing tasks too
    Initial valuesMatter littleMatter more
    Markov propertyNot used: better when the state is partly observedExploited: usually more sample-efficient when it holds
    On a fixed batchLeast-squares fit to the observed returnsExact values of the maximum-likelihood Markov model
    Tabular convergenceTo Vπ, by the law of large numbersTo Vπ: in the mean for a small constant α (Sutton 1988), with probability 1 for decreasing step sizes (Σα = ∞, Σα2 < ∞; Dayan 1992)
    With function approximationConverges (to a local optimum with a non-linear approximator)Linear and on-policy: converges to the TD fixed point; otherwise can diverge (section 7)

    Batch MC and batch TD converge to different answers on the same data (Example 6.4). Eight episodes: A, 0, B, 0 once; B, 1 six times; B, 0 once. Both give V(B) = 6/8 = 0.75. Batch MC gives V(A) = 0, the only return seen from A; batch TD gives V(A) = 0.75, because A always led to B. TD's answer is the value under the maximum-likelihood Markov model of the data (certainty equivalence), which predicts future data better if the process is Markov (the optimality of batch TD(0) is from Sutton 1988); that is why batch TD beats batch MC on the walk (switch the chart to Batch). Silver's version: you nearly crash and the episode ends fine; MC credits every state with the good ending, TD marks down the states before the moment the crash looked certain.

    Monte Carlo details: first against every visit, why model-free, history (depth)

    First-visit MC uses only the first visit to a state in each episode; every-visit MC uses all of them. First-visit returns are independent, identically distributed samples of Vπ(s), so each average is unbiased and its standard error falls as 1/√n; every-visit returns from one episode are correlated and its estimate is biased for a finite number of episodes, but it also converges and "extends more naturally to function approximation and eligibility traces" (Sutton and Barto, §5.1; Singh and Sutton 1996 compare the two and tie first-visit MC to replacing traces, every-visit to accumulating ones). The incremental form follows from μk = μk−1 + (1/k)(xk − μk−1).

    Because MC does not bootstrap, the cost of estimating one state does not depend on the number of states: generate episodes from the states you care about and ignore the rest (§5.1). Model-free methods also apply when a model exists but is only usable by sampling (Go, Silver, Lecture 5), or when its probabilities are hard to write down: blackjack's rules are fully known, yet "it is not easy to determine" each outcome's probability for DP, while sample games are easy (§5.1). The price is the exploration problem of section 3: you learn only about states you visit. DP's full-width backups touch every successor; model-free sample backups cost the same whatever the number of states.

    History: "Monte Carlo" dates from the 1940s at Los Alamos; an early RL use was Michie and Chambers (1968), who averaged episode durations in pole balancing, "similar in spirit to Monte Carlo ES with every-visit MC estimates"; Monte Carlo ES first appeared in the 1998 edition of the book (chapter 5 notes).

    2The dial between them: n-step returns, TD(λ) and eligibility traces

    Between one step and the whole episode lie the n-step returns: take n real rewards, then bootstrap (Sutton and Barto, §7.1). TD(λ) averages all of them with geometrically decaying weights, the λ-return (forward view from Watkins 1989; TD(λ) itself from Sutton 1988). On the walk episode above, from C with all values 0.5: G(1) = 0 + V(D) = 0.5, G(2) = 0 + 0 + V(E) = 0.5, G(3) = G = 1. With λ = 0.5 the weights are 0.5, 0.25 and the remaining 0.25, so Gλ = 0.625, between TD's 0.5 and MC's 1. Move λ:

    Gt(n) = Rt+1 + γRt+2 + ... + γn−1Rt+n + γnV(St+n),    Gtλ = (1 − λ) Σn≥1 λn−1 Gt(n)
    n = 1, n = ∞
    the TD(0) target and the Monte Carlo return (the book writes Gt:t+n; past the end of the episode an n-step return is the plain return)
    λ = 0, λ = 1
    all weight on G(1) (one-step TD), or on Gt (Monte Carlo); in an episode ending at T, the weights of every n ≥ T − t collect into one lump λT−t−1 on Gt

    λ slides the target from TD's 0.5 (λ = 0) to Monte Carlo's 1 (λ = 1)

    The λ-return is a forward view: like MC, it needs the rest of the episode. The backward view gets nearly the same update online with an eligibility trace per state that records how recently and how often it was visited, and broadcasts each one-step TD error back in proportion (§12.2):

    Et(s) = γλEt−1(s) + 1(St = s),    V(s) ← V(s) + α δt Et(s) for every s
    Et(s)
    the trace of s (starting at 0); this is the accumulating trace
    λ = 1
    with updates applied at the end of the episode the total update equals MC's exactly, because the discounted TD errors telescope into Gt − V(St) (Silver, Lecture 4); online, TD(1) is "a way of implementing Monte Carlo algorithms that is more general", for discounted continuing tasks too (§12.2)

    Predict: on the 19-state walk, which n gives the lowest error at its best step size, 1, 4 or 512 (Monte Carlo)?

    In deep RL the same dial is generalised advantage estimation (GAE; Schulman et al. 2015), Ât = Σl≥0 (γλ)l δt+l, the advantage of actor-critic methods, worked through on Policy gradients and actor-critic.

    Error reduction, and the three kinds of trace (depth)

    Error-reduction property: the worst error of the expected n-step return is at most γn times the worst error of V (§7.1, equation 7.3), so each extra real reward shrinks the bias the estimate can pass on. n-step TD updates V(St) only n steps later.

    Traces. The accumulating trace adds 1 on every visit. The replacing trace resets it to 1, so a state revisited in a loop never builds a trace above 1 (Singh and Sutton 1996). The dutch trace makes the online backward view exactly equal to the online λ-return with linear approximation: true online TD(λ) (van Seijen and Sutton 2014; §12.5). Sutton and Barto now see replacing traces as "crude approximations to dutch traces, which largely supersede them" (§12.6).

    The replay beside this opens on the walk's last step: n-step TD updates only the state n steps back, while TD(λ) shares the final TD error out along the traces.

    One walk through n-step TD and TD(λ), then every setting across step sizes: the middle of the dial wins

    The 19-state walk of Example 7.1: −1 off the left, +1 off the right, values start at 0 (true values −0.9 to 0.9), α = 0.4 in the replay. The bracket shows which estimate an n-step update borrows; the bars under TD(λ) are the traces.

    n-step TD, n
    TD(λ), λ
    RMS error over the 19 states, averaged over the first 10 episodes and the runs

    An intermediate setting is best: n = 4 or λ = 0.8 in this rerun, with error rising toward both ends; the more an update relies on actual returns, the smaller the step size it tolerates. The axis stops at 0.55 as the book's does; every curve starts at √0.3 = 0.548. Online TD(λ) only approximates the λ-return: close below the best α, apart above it, and it diverges for λ ≥ 0.9 (Figure 12.6). Tap a legend entry to hide a curve.

    What the rerun checks, and what reproduces (live numbers)

      Figures 7.2 and 12.3 reproduce in shape (the off-line λ-return slightly beats n-step TD at the best setting, 0.277 against 0.278, and at high α, as the caption says). Figure 12.6 reproduces partly: TD(λ) is worse at high α and diverges for λ ≥ 0.9, but below the best α the book calls the two "virtually identical", and here they are close (within 0.031), not identical, because the online updates differ even at λ = 0.

      3Control from samples: learn Q, and keep exploring

      Control runs DP's loop, evaluate then improve (generalised policy iteration, §5.3; taught on Dynamic programming), and sampling breaks both halves. Improvement greedy on V needs the model, π′(s) = argmaxa [R(s, a) + γ Σs′ P(s′ | s, a) V(s′)], so model-free control learns Q(s, a), where greedy is a plain argmax. And evaluation only covers what the agent visits, so a greedy policy can lock onto a wrong action it never retries: the policy must keep exploring.

      ε-greedy: with probability 1 − ε the greedy action, otherwise one of the m actions uniformly, so the greedy action has probability 1 − ε + ε/m and every other ε/m. The ε-greedy policy with respect to Qπ is at least as good as any ε-soft π (every action at least ε/m), because its value puts the 1 − ε mass on the largest Q (§5.4, equation 5.2). The catch: improvement then finds only the best ε-soft policy. For the optimum, exploration must fade: a schedule is GLIE (greedy in the limit with infinite exploration) when every pair is visited infinitely often and the policy converges to greedy; εk = 1/k on the k-th episode is GLIE (Silver, Lecture 5).

      Monte Carlo control: exploring starts, GLIE MC control, blackjack (depth)

      Monte Carlo ES starts every episode from a random state-action pair, every pair possible, so all pairs are visited however greedy the policy is; after each episode it averages the returns that followed each first visit into Q and makes the policy greedy at the visited states (§5.3, box). On blackjack it finds a policy matching Thorp's (1966) basic strategy except one notch in the usable-ace policy, which the authors are "confident" is optimal for their version (Example 5.3, Figure 5.2). It cannot settle on a suboptimal policy, but "convergence to this optimal fixed point ... has not yet been formally proved", "one of the most fundamental open theoretical questions in reinforcement learning" (partial solution: Tsitsiklis 2002). Exploring starts are easy in a simulator and rarely possible with real interaction.

      GLIE Monte Carlo control: sample the k-th episode with the ε-greedy policy; for each visited pair increment N(St, At) and move Q(St, At) by (1/N)(Gt − Q); set ε ← 1/k. It converges to Q* (Silver, Lecture 5).

      4SARSA, Expected SARSA and Q-learning: which next action the target assumes

      Put TD in the control loop: update Q after every step, act ε-greedily on the latest Q. One transition shows the whole difference. illustrative The agent is in S beside a cliff, took A = right, got R = −1; γ = 1, α = 0.5, Q(S, right) = −5. In S′, Q(S′, right) = −4 is best and Q(S′, down) = −100 steps into the cliff; exploration happened to pick A′ = down.

      • SARSA uses the action taken: target −1 + (−100) = −101, new Q(S, right) = −5 + 0.5 × (−101 + 5) = −53.
      • Q-learning uses the best action: target −1 + (−4) = −5, so Q(S, right) stays −5.

      SARSA's value of "right, beside the cliff" absorbs the risk that its own exploration stumbles in; Q-learning's assumes greedy behaviour from S′ on. Change the numbers (the two other actions in S′ are −5 and −6, for Expected SARSA's average):

      SARSA: Q(S, A) ← Q(S, A) + α ( R + γQ(S′, A′) − Q(S, A) )
      Expected SARSA: target R + γ Σa′ π(a′ | S′) Q(S′, a′)    Q-learning: target R + γ maxa′ Q(S′, a′)
      A′
      the action the agent actually takes next, chosen ε-greedily; the update uses the quintuple (S, A, R, S′, A′), hence the name. Computing one A′ for the update and executing another builds something that is neither SARSA nor Q-learning.
      terminal S′
      every Q(S′, ·) is 0; bootstrapping from a stale estimate there leaks value past the end of the episode

      SARSA learns the value of the policy it runs, exploration included: on-policy TD control. Q-learning (Watkins 1989; proof Watkins and Dayan 1992) behaves ε-greedily (the behaviour policy) but its target evaluates the greedy policy (the target policy): off-policy, and needing no importance ratio, because the target never uses the action the behaviour chose next; behaviour only decides which pairs get updated. That is what lets DQN learn from a replay buffer. Its max is the Bellman optimality backup, so it is sampled value iteration. Expected SARSA removes the variance of the random A′ and, with a greedy target policy, is exactly Q-learning (§6.6).

      The same transition, three targets

      Predict: in the episode beside this list, which learner's value for the step just before the fall changes most?

      One recorded episode, four learners: only the target differs

      1. Four copies of one table. Each grid is the same 3 × 6 cliff: start S bottom left, goal G bottom right, the four red cells between them the cliff. Every cell has four bars, one per action, standing towards up, down, right and left; a bar's height grows with the square root of −Q, the cost to the goal, so the tall bars are the moves into the cliff. All four learners start from the same table, which already knows the edge path.
      2. Up, a random bump, right. Greedy up from the start, a random move left into the wall, then right along the middle row. The dots stream from the next state's value into the bar each TD learner updates. Each target is −1 plus a value close to the current one, so the TD learners' bars barely move, and Monte Carlo changes nothing until the episode ends.
      3. The moment: A′ is a random step down. From the middle row, column 2, a random move right; the next action, also random, is down into the cliff. SARSA's target uses it, −1 + (−50.25) = −51.25, and Q(S, right) drops from −5.00 to −28.12 (the highlighted bar). Expected SARSA weighs that action by its 2.5% chance: target −6.18, new value −5.59. Q-learning uses the best action: target −5.00, no change.
      4. The fall. The agent takes that step: down into the cliff, −100, back to the start. All three TD learners pull Q(column 3, down) from −50.25 to about −79 (SARSA and Q-learning −78.62, Expected SARSA −79.80, whose target averages over the start's actions). Monte Carlo still waits.
      5. Back along the middle row. Up, right, right, a random left, right again and on to the last column. Twice more the agent takes right from column 2, now with a harmless next action, and SARSA pulls its value back up, to −16.81 and then −10.91.
      6. The goal, and Monte Carlo at last. Down into G ends the episode. Only now does Monte Carlo update (its return streams back along the whole episode), all 14 pairs at once, each towards the return that followed it: −113 from the start (13 moves and the fall), down to −1 for the last move. The pair before the fall, visited three times, goes to −57.50, −32.25 and finally −18.62.
      7. Same moves, four tables. Q(S, right) for the step before the fall ends at −10.91 for SARSA, −6.60 for Expected SARSA, −5.00 for Q-learning and −18.62 for Monte Carlo (total change over the table 53.0, 35.7, 29.6 and 151.5). SARSA and Monte Carlo charge the safe-looking step for the stumble that followed it; Q-learning does not, because its target assumes greedy play from the next state on.

      A 3 × 6 cliff (start S bottom left, goal G bottom right, four cliff cells between; −1 per move, −100 and back to the start for a fall). illustrative setup, exact arithmetic: the starting table is Q-learning's after 30 seeded episodes (α = 0.5, ε = 0.1); the episode is ε-greedy on that table, held fixed so all four see the same moves; α = 0.5, ε = 0.1, γ = 1; Monte Carlo is every-visit constant-α. Checked against src/checks/recompute.py.

      Cliff walking (Example 6.6; Gymnasium, Cliff Walking) turns this into reward. A 4 by 12 grid, start bottom left, goal bottom right, the ten cells between them the cliff: −1 per step, −100 and back to the start for a fall, undiscounted, ε = 0.1. The optimal path hugs the edge: up 1, right 11, down 1, 13 steps, return −13, and Q-learning learns its values. But on each of the ten edge cells the random 10% of actions picks "down" a quarter of the time, 0.1/4 = 0.025 per step, so a pass survives with probability 0.97510 ≈ 0.776 and about 22% of passes fall at least once derived. SARSA learns a longer path through the upper part of the grid, because its values include its own stumbles, and so earns more while ε stays at 0.1.

      Which is "right" depends on the question. Q-learning answers "what is optimal if I stop exploring?"; SARSA "what is best given that I keep exploring like this?". For a robot exploring on real hardware, SARSA's answer is the safer one; Q-learning's values are not the return you will get while exploration continues (−50.8 expected, against −13 for the greedy path).

      Convergence conditions, Expected SARSA at α = 1, n-step SARSA and SARSA(λ), history (depth)

      SARSA converges to Q* with probability 1 under GLIE policies and Robbins-Monro step sizes, Σt αt = ∞ and Σt αt2 < ∞: big enough in total to overcome any initial values, shrinking fast enough for the noise to average out (§6.4; proof Singh, Jaakkola, Littman and Szepesvári 2000). Those conditions are for proofs: they "are seldom used in applications and empirical research", where a constant α is the norm and never fully settles but tracks change (§2.5). With ε fixed, SARSA settles on the best policy given that it keeps exploring.

      Q-learning needs only that every pair keeps being updated, plus "a variant of the usual stochastic approximation conditions" on the step sizes (§6.5; general proofs Jaakkola, Jordan and Singh 1994, Tsitsiklis 1994); ε need not decay for the values to converge, only for the behaviour to become optimal.

      Expected SARSA on the deterministic cliff "can safely set α = 1 without suffering any degradation of asymptotic performance, whereas Sarsa can only perform well in the long run at a small value of α" (Figure 6.3, from van Seijen, van Hasselt, Whiteson and Wiering 2009); it "subsumes and generalizes Q-learning while reliably improving over Sarsa", at a small extra cost per step.

      n-step SARSA targets Rt+1 + ... + γn−1Rt+n + γnQ(St+n, At+n) (§7.2); SARSA(λ) keeps one trace per state-action pair (§12.7). On a gridworld with one reward at the goal, an episode of one-step SARSA strengthens only the last action before the goal, n-step SARSA the last n (Figure 7.4). Expected SARSA goes back to George John (1994).

      History: SARSA came after Q-learning. Rummery and Niranjan introduced it in 1994 as "Modified Connectionist Q-learning"; the name "Sarsa" is from Sutton (1996) (chapter 6 notes).

      The cliff replay beside this opens on the tables after the last of 500 episodes; Play replays the run from the start.

      How often the exploring agent falls off the edge path derived

      SARSA against Q-learning on the cliff: Q-learning knows the shortest path and keeps falling off it

      Sum of rewards during the episode, averaged over runs

      Shading: the best Q-value in each cell (darker is worse); arrows: the greedy move; trail: this episode, falls crossed. Over episodes 401 to 500 (100 runs; the book does not state α, 0.5 is assumed): SARSA −27.4 per episode, Q-learning −50.3, and Expected SARSA −20.8 if you pick it. Acting ε-greedily around the edge path is worth exactly −50.80 per episode (policy evaluation on the known grid), which is where Q-learning's average settles. The axis is cut at −100 as the book's is, so early episodes (several hundred) leave the bottom. With ε decaying, both would converge to the edge path.

      What the rerun checks, and which path SARSA learns (live numbers, a correction)
        Which path SARSA learns
        The parent page's overview said SARSA learns "a safer path one row up". After 500 episodes SARSA's greedy path is a 17-step route that climbs to the top row (up 3, right 11, down 3) in 73 of 100 runs, 19 or 21 steps in 11, and in 16 its greedy moves loop through rarely visited cells; the 15-step route one row above the edge never appears. Q-learning's greedy path is the 13-step edge path in all 100 runs. The book's wording is "the longer but safer path through the upper part of the grid".

        5Maximisation bias and Double Q-learning

        A max over noisy estimates is biased upwards. If 10 actions are all truly worth 0 and each estimate carries unit noise, the expected largest estimate is 1.539 derived: whichever got lucky wins. Q-learning's target is that max, and an ε-greedy SARSA uses it through the greedy part of its policy; the optimism flows back into every state that leads there (§6.7). The cause is using the same samples to pick the action and to value it. Double learning keeps two independent estimates and values one's choice with the other, Q2(argmaxa Q1(a)), whose expectation is the true value of the chosen action.

        Q1(S, A) ← Q1(S, A) + α ( R + γQ2(S′, argmaxa Q1(S′, a)) − Q1(S, A) )
        Q1, Q2
        two tables; a coin flip on each step picks which one updates, with the roles swapped on tails (van Hasselt 2010). Double the memory, the same computation per step
        behaviour
        ε-greedy on Q1 + Q2

        The max of unbiased estimates is not unbiased

        Example 6.7 makes the bias cost reward. From A, right ends with reward 0; left goes to B, whose actions all end with a reward drawn from a normal with mean −0.1 and variance 1. Left is always a mistake, yet Q-learning "initially learns to take the left action much more often than the right action", while Double Q-learning "is essentially unaffected". Both act ε-greedily with ε = 0.1, α = 0.1, estimates starting at 0; the book says only that B has "many possible actions", so 10 are assumed here, as in Zhang's reproduction.

        Double DQN is the same idea with the two networks DQN already has (van Hasselt, Guez and Silver 2015; on Value-based deep RL).

        The replay beside this opens after episode 100 of one seeded run; compare how often each learner has gone left (under each panel).

        Q-learning goes left because B's luckiest estimate looks good; Double Q-learning does not

        Q-learning
        Double Q-learning

        Dots: the estimates of B's actions (Double Q-learning: the average of its two tables); Q-learning's target for "left" is the highest dot. Bars: the two estimates in A.

        Share of runs that take left from A, by episode (Figure 6.5)

        The dashed 5% is the best an ε-greedy agent can do: a random action 10% of the time, half of them left. 10,000 runs, as the book.

        What the rerun checks (live numbers)

          Figure 6.5 reproduces in shape: every statement of the caption and text holds live. The peak height depends on the number of actions in B, which the book does not state. The curves exist only as an image, so values are not compared.

          6Off-policy Monte Carlo: importance sampling

          Off-policy learning learns about a target policy π from data of a behaviour policy b: from demonstrations or other agents, from old policies' data, a greedy target while behaving exploratorily, several policies from one stream (Silver, Lecture 5). It needs coverage: every action π might take has non-zero probability under b (§5.5). Q-learning gets away without a correction; a Monte Carlo return does not, because the whole rest of the episode followed b's choices. The correction weights each return by how much more likely π was to produce it; the transition probabilities appear in both policies' trajectory probabilities and cancel. Concretely: if b took an action with probability 0.25 that π takes with probability 0.5, the sample counts double (ρ = 2); an action π never takes gives weight 0 to the whole return from before it.

          ρt:T−1 = ∏k=tT−1 π(Ak | Sk) / b(Ak | Sk),   Eb[ρt:T−1 Gt | St = s] = vπ(s);   ordinary V = Σ ρG / n,   weighted V = Σ ρG / Σ ρ
          ordinary
          first-visit version unbiased, variance in general unbounded
          weighted
          biased (after one return it equals that return), the bias falling to zero; with bounded returns its variance goes to zero "even if the variance of the ratios themselves is infinite" (Precup, Sutton and Dasgupta 2001). "In practice, the weighted estimator usually has dramatically lower variance and is strongly preferred" (§5.5). Every-visit versions of both are biased, the bias vanishing asymptotically. Normalising is what makes it biased, not unbiased.

          Predict: on one blackjack state learned from random play, which estimator is closer to the truth after 10 episodes?

          The replay beside this opens on all 200 episodes of one run; scrub to episode 10 to check your prediction.

          One blackjack state from someone else's play: the weighted estimate is far better early, both reach the truth

          Example 5.4 (p. 106): the dealer shows a 2, the player holds 13 with a usable ace. π sticks only on 20 or 21; b hits or sticks with probability ½ each, so ρ doubles for every decision that matches π and drops to 0 at the first that does not. Infinite deck, dealer hits below 17; win +1, draw 0, loss −1 (Example 5.1).

          This episode
          Running estimates, one run
          Mean squared error over runs, 10,000 episodes each (Figure 5.3; episodes on a log scale)

          The state's value, −0.27726 in the book from 100 million simulated games, is −0.27720 computed exactly here by recursion over the infinite deck derived, within the book's sampling error (about 0.0001): an independent reproduction. Each run starts from an estimate of 0; the axis stops at 5 as the book's does.

          What the rerun checks (live numbers)

            Figure 5.3 reproduces in shape; values are not read off the image.

            When π loops, ordinary importance sampling can have infinite variance (Example 5.5). One state; right ends with reward 0; left returns to the state with probability 0.9 or ends with +1 with probability 0.1. π always goes left, so vπ = 1; b goes either way with probability ½. An episode with k lefts has ρ = 2k and G = 1, so every scaled return has expectation 1, but E[(ρG)2] = Σk≥1 (½)k 0.9k−1 0.1 · 4k = 0.2 Σj≥0 1.8j = ∞: rare long all-left episodes carry enormous weights.

            Incremental weighted IS, off-policy MC control, n-step ratios, tree backup, Retrace (depth)
            • Incrementally: keep a cumulative weight C per pair; for each new return with weight W, C ← C + W and Q ← Q + (W/C)(G − Q) (equations 5.7 and 5.8, §5.6). With π = b every W is 1 and this is the running mean.
            • Off-policy MC control makes the target greedy and the behaviour soft, walks each episode backwards and stops at the first non-greedy action, where π's weight becomes 0 (§5.7). "This method learns only from the tails of episodes": slow if non-greedy actions are common. TD is the usual remedy.
            • Off-policy n-step methods multiply the ratios inside the window: n-step SARSA uses ρt+1:t+n, one step later than n-step TD's ρt:t+n−1, because the first action is given (§7.3). Tree backup avoids ratios by taking expectations over the actions not taken; its one-step case is Expected SARSA (§7.5). Watkins's Q(λ) cuts its traces at the first exploratory action (§12.10). Deep RL's Retrace truncates the ratios at 1 (Munos et al. 2016).

            The same ratio, clipped, is the heart of PPO and GRPO: their rollouts come from a slightly stale copy of the policy and from an inference engine whose probabilities differ slightly from the trainer's, so language-model RL is mildly off-policy and corrects per token (RL for LLMs; Policy gradients and actor-critic).

            Ten runs of ordinary importance sampling are still scattered after millions of episodes

            First-visit MC with ordinary importance sampling, ten runs (Figure 5.4; episodes on a log scale)

            Weighted importance sampling (dashed) is exactly 1 from the first episode consistent with π, because only those returns get any weight, and all are 1. The book runs to 100 million episodes; 10 million is the most offered here, for a phone.

            What the rerun checks (live numbers)

              7Beyond tables: function approximation and the deadly triad

              Every method so far stores one number per state or state-action pair and learns nothing about a state it has not visited, which fails as soon as the state space is large or continuous. Replace the table with v̂(s, w) and move the weights along the gradient of the estimate, treating the target as fixed: semi-gradient TD(0), w ← w + α [R + γv̂(S′, w) − v̂(S, w)] ∇v̂(S, w) (§9.3). Monte Carlo with the same update is true gradient descent on squared error; TD is not, because its target moves with w. With linear features and on-policy data it still converges, to the TD fixed point, whose error is at most 1/(1 − γ) times the best the features allow (§9.4, equation 9.14): a factor of 100 at γ = 0.99 derived.

              Correction to the old page
              The old page's table said TD with function approximation "not always" converges, without the condition. Linear on-policy semi-gradient TD(0) provably converges, to the TD fixed point above; the failures need non-linear approximation or off-policy updates.

              The failure has a name. The deadly triad is function approximation (generalising across states), bootstrapping (targets built from current estimates, as in TD and DP) and off-policy training (updates on a distribution other than the target policy's): "If any two elements of the deadly triad are present, but not all three, then instability can be avoided" (§11.3). It needs neither control nor sampling: it appears in prediction, even with DP's expected updates. The smallest case is two states whose estimates share one weight, w and 2w, with a transition from the first to the second paying 0 (§11.2): the TD error is γ · 2w − w = (2γ − 1)w, so each update multiplies w by 1 + α(2γ − 1), above 1 whenever γ > 0.5. With α = 0.1 and γ = 1, w goes 10, 11, 12.1 derived: raising the first state raises the second twice as much. On-policy, the 2w state's own update would pull w back; off-policy, nothing does. With the on-policy distribution of updates, convergence is guaranteed (§11.2).

              Baird's counterexample is the complete version (Baird 1995; Figure 11.1). Seven states, eight weights: the six upper states have value 2wi + w8, the seventh w7 + 2w8; every reward is 0, so every true value is 0, which w = 0 represents exactly. The target policy always takes the "solid" action to state 7; the behaviour policy takes "dashed" (to a random upper state) with probability 6/7, so all seven states are updated equally often. With γ = 0.99 the weights diverge "for any positive step size, no matter how small", even with expected updates of every state at once.

              Predict: which single switch below stops the weights from growing? Then flip each one.

              Q-learning with a network and a replay buffer has all three legs, which is why DQN needed target networks and replay, and why Double DQN and multi-step targets help: that story, the measured "soft divergence" of DQN variants on Atari and the gradient-TD fixes are on Value-based deep RL.

              Remove any one leg of the triad and Baird's weights stop growing

              Largest |estimated value| over the 7 states (every true value is 0), per sweep, log scale

              Expected (DP-style) semi-gradient updates, one sweep over the states being updated, α = 0.01, γ = 0.99, w0 = (1, 1, 1, 1, 1, 1, 10, 1): the setting of Figure 11.2 (right). With all three legs, after 1,000 sweeps w8 reaches 335, w1 to w6 114 and w7 6.85 derived, the book's shape (it prints only curves). "A table" gives each state its own weight, starting at the same values (3 and 12); "Monte Carlo" uses the true return under the target policy, 0. The bounded cases shrink slowly because each target keeps 99% of an estimate. Checked against src/checks/recompute.py.

              8The map: DP and TD backups, what to use, where it goes next

              Each TD control method samples a DP method on Q, with x ←α y meaning x ← x + α(y − x) (Silver, Lecture 5). His "unified view" adds the other two corners: full-width to the end of the episode is exhaustive search, sampled to the end is Monte Carlo; Expected SARSA sits between the columns, sampling the next state but not the next action.

              Bellman equationFull backup (DP, needs the model)Sample backup (TD, model-free)
              Expectation, VIterative policy evaluation: V(s) ← E[R + γV(S′) | s]TD learning: V(S) ←α R + γV(S′)
              Expectation, QQ-policy iteration: Q(s, a) ← E[R + γQ(S′, A′) | s, a]SARSA: Q(S, A) ←α R + γQ(S′, A′)
              Optimality, QQ-value iteration: Q(s, a) ← E[R + γ maxa′ Q(S′, a′) | s, a]Q-learning: Q(S, A) ←α R + γ maxa′ Q(S′, a′)
              ChoicePickBecause
              Prediction, continuing task or long episodes, state close to MarkovTD, or an intermediate n or λLearns mid-episode, lower variance; the middle of the dial usually beats both ends
              Prediction, short episodes, state partly observedMonte Carlo or a large λDoes not rely on the Markov property; more robust with function approximation
              Control, reward while learning matters (real hardware)SARSA or Expected SARSAOptimises the exploring policy it actually runs
              Control in a simulator, or from old or someone else's dataQ-learning (Expected SARSA with a greedy target)Learns the greedy optimum; one-step off-policy needs no ratio
              Noisy rewards, many competing actionsDouble Q-learning (Double DQN with networks)Removes maximisation bias
              Off-policy Monte CarloWeighted importance samplingBounded variance; expect slow learning when π and b often disagree
              Step size α, exploration εConstant α; decay ε (GLIE) when the final policy should be greedyLarger α learns faster and fluctuates more, and tracks a changing problem; more ε finds better actions and costs reward while learning

              Where it goes next. Replace the table with a network, plus a replay buffer (legitimate because Q-learning is off-policy) and a frozen target network: Value-based deep RL, where Double DQN is the double-learning fix and n-step targets return in Rainbow. Actor-critic methods learn a critic with TD targets and use GAE as the dial (Policy gradients and actor-critic). Dyna mixes Q-learning on real experience with Q-learning on experience simulated from a learned model (Model-based RL and planning). Learning from a fixed dataset with no interaction is offline RL, a different problem from off-policy learning (Offline RL and imitation). In language-model RL (RL for LLMs: RLHF, GRPO, RLVR), GRPO's single end-of-sequence reward against a group mean is a Monte Carlo return (unbiased, no value model, high variance), and PPO with a value model sits partway along the TD(λ) dial through GAE, its λ choosing the trade-off. On Topic: rl's axes all four methods are model-free and value-based; SARSA is on-policy and Q-learning off-policy; Monte Carlo does not bootstrap and TD does.

              Depth: misconceptions, and how the experiments are run

              Misconceptions worth a second look (seven)
              • "TD is always better than MC." Usually, on Markov tasks with a table; but it is biased, leans more on initial values, and can diverge with non-linear approximation or off-policy data where MC does not.
              • "MC and TD converge to the same thing on finite data." On a fixed batch MC fits the observed returns and TD solves the maximum-likelihood Markov model: V(A) = 0 against 0.75 in the AB example.
              • "Q-learning is off-policy, so it needs importance sampling." One-step Q-learning does not; off-policy MC and n-step methods do, and their ratios multiply along the trajectory (infinitely, in Example 5.5).
              • "On-policy means online, off-policy means offline." Q-learning is off-policy and online; the distinction is which policy the values describe.
              • "SARSA is older and Q-learning improved on it." The other way round: Q-learning is from 1989, SARSA from 1994, introduced as a modification of Q-learning.
              • "Weighted importance sampling is unbiased because it is normalised." The ordinary (first-visit) estimator is the unbiased one; the weighted one wins on variance.
              • "The Robbins-Monro conditions are how you set α." They are what the proofs need; practice uses a constant α.
              How the experiments are run, checked and defined (provenance)
              • Seeded and deterministic. Every random draw comes from a seeded generator (mulberry32), one stream per purpose and run, so a run replays identically, both sides of a comparison see the same walks where that makes sense, and a Python port matches the page exactly. Long averages run in small slices between frames, so the page stays responsive on a phone; each starts when its chart scrolls into view.
              • Checked against Python. src/lab/check.py ports the engine of the random-walk, 19-state and cliff experiments line by line and reproduces their numbers bit for bit; it also checks independently: true values by linear solve, the batch closed forms against replayed batches, the λ-return recursion against equation 12.3, the cases where methods coincide (n = 1 and λ = 0 are TD(0); n ≥ episode length and λ = 1 are Monte Carlo), and the cliff's exact ε-greedy returns by linear solve. src/checks/recompute.py does the same for the maximisation-bias, importance-sampling and Baird experiments and the four-learner animation.
              • Exact definitions. Undiscounted everywhere except Baird's (γ = 0.99). Monte Carlo on the walks is every-visit constant-α (equation 6.1). n-step TD follows the box in Section 7.1. The off-line λ-return takes its targets from the values held at the start of the episode and applies them in time order at its end (equation 12.4). TD(λ) uses accumulating traces. On the cliff, ties between equal Q-values break at random; the greedy path reported takes the first best move and counts as "none" if it loops or falls.
              • Assumed, and not compared. The book does not state α for the cliff (0.5 here) or how many runs its cliff graph averages, nor how many actions B has in Example 6.7 (10 here); it states 100 runs for the random walks and 10 episodes for the 19-state sweeps, used here. Its results exist only as plotted curves, and this page never reads numbers off a plot: it tests the shapes and orderings the text and captions state.
              • Origin. The random-walk, 19-state and cliff experiments were built for the Estimator lab of Topic: rl and moved here when that page became an overview; its fourth experiment (Figure 4.1, model against samples) went to Dynamic programming.

              Sources: Sutton and Barto, Reinforcement Learning: An Introduction (2nd ed., 2018), chapters 5 to 7, 9, 11 and 12; David Silver's UCL Lectures 4 and 5; the primary papers linked in each paragraph. Further reading, with times, is in the last tab.