Simple Algorithm
Reinforcement Learning · Bootstrapping · 24 min

SARSA & Q-Learning

On-policy and off-policy TD control, and the cliff that separates them.

Turning TD prediction into control takes one change: learn the values of actions, and act on them. After that, a single term separates the two classic algorithms. SARSA bootstraps from the action it will actually take next, exploration included; Q-learning bootstraps from the best action, whatever it does next. Beside a cliff, that term decides whether an agent learns a safe detour or the edge. This lesson derives both methods, states what each converges to and under which conditions, and meets the bias hidden in Q-learning's maximum.

What you’ll learn

  • Derive SARSA and Q-learning as sampled Bellman backups for action values, write them as code, and compute their updates by hand.
  • Explain why SARSA is on-policy and Q-learning off-policy, and predict and explain the routes they learn on the cliff.
  • State the convergence conditions of Q-learning (every pair updated infinitely often, Robbins–Monro step sizes) and of SARSA (the same, plus GLIE exploration), and say what each learns with a fixed ε.
  • Define expected SARSA as the method that contains both, and explain why a maximum over noisy estimates overestimates.

From prediction to control: SARSA

Prediction asked what a fixed policy is worth. Control asks for a better policy, and without a model a state-value estimate does not help: picking the best action from VV requires knowing where each action leads. So the agent learns action values Q(s,a)Q(s,a) instead, and improves by acting greedily on them. Generalized policy iteration then runs at the finest possible grain: one evaluation step after every transition, and one improvement step every time the agent picks its next action ε-greedily from the current QQ.

Action values obey the same kind of Bellman equation as state values, one step later:

Qπ(s,a)=Eπ[Rt+1+γ Qπ(St+1,At+1)∣St=s, At=a].Q^\pi(s,a) = \E_\pi\big[R_{t+1} + \gamma\,Q^\pi(S_{t+1},A_{t+1}) \mid S_t = s,\ A_t = a\big].

Sampling it, exactly as TD(0) samples the equation for VπV^\pi, gives SARSA. After taking AtA_t in StS_t and observing Rt+1R_{t+1} and St+1S_{t+1}, the agent first chooses its next action At+1A_{t+1} from the current policy, then updates.

Q(St,At)←Q(St,At)+α[ Rt+1+γ Q(St+1,At+1)−Q(St,At) ]Q(S_t,A_t) \leftarrow Q(S_t,A_t) + \alpha\big[\,R_{t+1} + \gamma\,Q(S_{t+1},A_{t+1}) - Q(S_t,A_t)\,\big]
The update reads the quintuple (St,At,Rt+1,St+1,At+1)(S_t, A_t, R_{t+1}, S_{t+1}, A_{t+1}), which gives SARSA its name; Q(St+1,⋅)=0Q(S_{t+1},\cdot) = 0 when St+1S_{t+1} is terminal. The bracket is the action-value TD error. The next action is chosen before the update, and it is then the action actually taken.
Check your understanding

Midway through learning, SARSA's policy π\pi is ε-greedy with respect to its current QQ. Averaged over the reward, the next state and the next action, what is SARSA's target Rt+1+γQ(St+1,At+1)R_{t+1} + \gamma Q(S_{t+1}, A_{t+1}), given St=sS_t = s and At=aA_t = a?

  1. (T⋆Q)(s,a)(\mathcal T^\star Q)(s,a), the optimality backup of QQ
  2. Q⋆(s,a)Q^\star(s,a)
  3. (TπQ)(s,a)(\mathcal T^\pi Q)(s,a), the backup of QQ for the current ε-greedy policy
  4. Qπ(s,a)Q^\pi(s,a) exactly, at every step of learning
Show the answer

C. (TπQ)(s,a)(\mathcal T^\pi Q)(s,a), the backup of QQ for the current ε-greedy policy

The next action is drawn from π\pi, so the expected target is r(s,a)+γ∑s′P(s′∣s,a)∑a′π(a′∣s′)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 backup of the current QQ for π\pi. Its fixed point is QπQ^\pi: SARSA evaluates the policy it is following, while the policy keeps improving as QQ changes.

Q-learning: learning about the greedy policy while exploring

Q-learning (Watkins, 1989) samples the Bellman optimality equation instead,

Q⋆(s,a)=E[Rt+1+γmax⁡a′Q⋆(St+1,a′)∣St=s, At=a],Q^\star(s,a) = \E\big[R_{t+1} + \gamma\max_{a'}Q^\star(S_{t+1},a') \mid S_t = s,\ A_t = a\big],

in which the expectation is over the environment alone: no policy appears.

Q(St,At)←Q(St,At)+α[ Rt+1+γmax⁡aQ(St+1,a)−Q(St,At) ]Q(S_t,A_t) \leftarrow Q(S_t,A_t) + \alpha\big[\,R_{t+1} + \gamma\max_{a}Q(S_{t+1},a) - Q(S_t,A_t)\,\big]
The target backs up the greedy action at St+1S_{t+1}, whichever action the agent then takes.

The target no longer depends on what the agent does next. The behavior decides only which pairs get updated and how often; every update backs up the greedy choice. So Q-learning is off-policy: its target policy is greedy with respect to QQ, while its behavior policy can be anything that keeps trying every action. No importance weights are needed, because the update is conditioned on the action actually taken, and the target contains no other choice of the behavior. SARSA is on-policy: its target uses the behavior's own next action, so it learns about the policy that generates the data.

python
import numpy as np

ROWS, COLS, START, GOAL = 4, 12, (3, 0), (3, 11)
MOVES = [(-1, 0), (0, 1), (1, 0), (0, -1)]          # up, right, down, left

def step(s, a):
    r = min(max(s[0] + MOVES[a][0], 0), ROWS - 1)
    c = min(max(s[1] + MOVES[a][1], 0), COLS - 1)
    if r == 3 and 0 < c < 11:                       # the cliff: -100, back to start
        return START, -100.0, False
    return (r, c), -1.0, (r, c) == GOAL

def policy(Q, s, eps, rng):                         # epsilon-greedy
    return int(rng.integers(4)) if rng.random() < eps else int(np.argmax(Q[s]))

def learn(method, episodes=500, alpha=0.5, eps=0.1, seed=0):
    rng, Q = np.random.default_rng(seed), np.zeros((ROWS, COLS, 4))
    for _ in range(episodes):
        s, done = START, False
        a = policy(Q, s, eps, rng)
        while not done:
            s2, r, done = step(s, a)
            a2 = policy(Q, s2, eps, rng)            # the action taken next
            nxt = Q[s2][a2] if method == "sarsa" else Q[s2].max()
            Q[s][a] += alpha * (r + (0.0 if done else nxt) - Q[s][a])
            s, a = s2, a2
    return Q

Sutton and Barto's cliff walk (every step costs 1; stepping into the cliff costs 100 and sends the agent back to the start; γ=1\gamma = 1), with both methods in one loop. Only the line that picks the bootstrap value differs. Both draw the next action before the update: SARSA needs it for its target, while Q-learning merely acts on it and ignores it in the target.

Check your understanding

Q(s,a)=−6Q(s,a) = -6. The agent takes aa, receives R=−1R = -1 and lands in s′s', where Q(s′,⋅)=(−5,−3,−8,−4)Q(s',\cdot) = (-5, -3, -8, -4) for (up, right, down, left); γ=1\gamma = 1 and α=0.5\alpha = 0.5. Its ε-greedy policy then happens to explore and pick down. What is the new Q(s,a)Q(s,a) under SARSA, and under Q-learning?

  1. SARSA −5.0-5.0; Q-learning −7.5-7.5
  2. SARSA −7.5-7.5; Q-learning −5.0-5.0
  3. Both −5.0-5.0, since the greedy action at s′s' is right
  4. SARSA −9-9; Q-learning −4-4
Show the answer

B. SARSA −7.5-7.5; Q-learning −5.0-5.0

SARSA bootstraps from the action it will take, down: target −1+(−8)=−9-1 + (-8) = -9, so Q←−6+0.5(−9+6)=−7.5Q \leftarrow -6 + 0.5(-9 + 6) = -7.5. Q-learning bootstraps from the best action, right: target −1+(−3)=−4-1 + (-3) = -4, so Q←−6+0.5(−4+6)=−5Q \leftarrow -6 + 0.5(-4 + 6) = -5. One exploratory step makes SARSA think worse of (s,a)(s,a); Q-learning does not care what the agent does next.

The cliff: two answers to two questions

The widget's cliff is Sutton and Barto's 4 × 12 grid with two changes: stepping into the cliff ends the episode (with −100-100 on top of the step's −1-1), and reaching the goal pays +10+10. With every step costing 1, the route along the edge takes 13 steps and returns −13+10=−3-13 + 10 = -3; the route one row higher takes 15 steps (−5-5), and the top row 17 (−7-7). There is no slip and no discounting (γ=1\gamma = 1), and the two agents share the same exploration rate and step size, ε=0.1\varepsilon = 0.1 and α=0.25\alpha = 0.25.

Q-learning's greedy route from the start normally matches value iteration's: the edge is optimal, and Q-learning learns Q⋆Q^\star (cells far from the route may still be off after only 200 episodes). But the agent that learned those arrows keeps exploring. On each of the 11 steps where the cliff is one move away (the start, and the ten cells above the cliff), an exploratory move picks the fatal direction with probability ε/4=0.025\varepsilon/4 = 0.025, since exploration chooses among four actions. A walk along the edge therefore falls roughly once in four times: 1−0.97511≈0.241 - 0.975^{11} \approx 0.24, a rough figure that ignores detours.

SARSA's values include those exploratory steps. For SARSA an edge step carries an expected penalty of roughly 0.025×100=2.50.025 \times 100 = 2.5 on top of its cost of 1, so the ten edge steps cost about 25 more than they would for an agent that never explores, while climbing one or two rows costs only 2 or 4 extra steps. Its arrows climb away from the edge: SARSA learns the best route for an agent that keeps exploring with ε=0.1\varepsilon = 0.1. Q-learning learns the best route for an agent that will stop exploring. Both are right about different questions, and if ε\varepsilon decays to zero appropriately, SARSA's route converges to the edge as well.

Think first Now let every move slip sideways with probability 0.1 (0.05 to each side), and ask for the optimal route of an agent that never explores. Is it still the edge?

No. Walking east along the edge, a slip to the south lands in the cliff, so each edge step costs about 0.05×100=50.05 \times 100 = 5 in expectation, while one row higher a slip south only costs a step back up. (Leaving the start is risky on every route, since the first step north can slip east into the cliff.) The environment itself is now stochastic, Q⋆Q^\star changes, and the optimal route leaves the edge. Q-learning follows it, because it learns Q⋆Q^\star of whatever environment it is in. Set the widget's noise to 0.1 and rerun value iteration to see the new route.

What each method converges to, and when

The conditions are the Robbins–Monro conditions of stochastic approximation, imposed separately on each pair; αn=1/n\alpha_n = 1/n, a running average of each pair's targets, satisfies them. Q-learning asks nothing more of the behavior than to keep visiting. SARSA's target follows its own behavior, so the behavior must turn greedy for the limit to be Q⋆Q^\star, and not too fast: a global schedule such as εk=1/k\varepsilon_k = 1/k per episode can stop exploring states that need two exploratory moves in a row, which is why per-state schedules are used (Monte Carlo Control & Its Convergence works this out).

The widget's constant α=0.25\alpha = 0.25 violates ∑α2<∞\sum\alpha^2 < \infty. For Q-learning on the deterministic cliff that is harmless: given (s,a)(s,a) its target is not random, so a constant step converges. SARSA's target contains the random next action, so even on the cliff its estimates keep jittering by an amount that shrinks with α\alpha, and with random rewards or transitions every method does.

PropertySARSAQ-learningExpected SARSA
TargetRt+1+γQ(St+1,At+1)R_{t+1} + \gamma Q(S_{t+1},A_{t+1})Rt+1+γmax⁡aQ(St+1,a)R_{t+1} + \gamma\max_aQ(S_{t+1},a)Rt+1+γ∑aπ(a∣St+1)Q(St+1,a)R_{t+1} + \gamma\sum_a\pi(a \mid S_{t+1})Q(S_{t+1},a)
Learns aboutthe behavior itself (on-policy)the greedy policy (off-policy)any chosen policy π\pi
With a fixed ε=0.1\varepsilon = 0.1values of its ε-greedy behavior; aims at the best ε-greedy policyQ⋆Q^\starQπQ^\pi for its π\pi
Needs from the behaviorGLIE, to reach Q⋆Q^\starevery pair tried infinitely oftenGLIE if π\pi is the behavior; coverage of π\pi's actions otherwise
Can learn from an old log?no: it learns the logging policy's valuesyesyes, for a fixed π\pi
Randomness of the target given St+1S_{t+1}the sampled At+1A_{t+1}nonenone
Expected SARSA, the subject of the last step, contains both: with π\pi equal to the ε-greedy behavior it is a lower-variance SARSA, and with π\pi greedy it is exactly Q-learning.
Check your understanding

In a finite MDP where every state is reachable, an agent behaves uniformly at random forever and runs Q-learning with αn(s,a)=1/n\alpha_n(s,a) = 1/n. What happens to its QQ?

  1. It never reaches Q⋆Q^\star, because the behavior must become greedy in the limit
  2. It converges to Q⋆Q^\star with probability 1, although the agent never acts well
  3. It converges to the values of the random policy
  4. It diverges, because random actions make the targets too noisy
Show the answer

B. It converges to Q⋆Q^\star with probability 1, although the agent never acts well

Random behavior keeps visiting every pair, and 1/n1/n satisfies both Robbins–Monro conditions, so the theorem applies. The target always backs up max⁡aQ(St+1,a)\max_a Q(S_{t+1},a), so what is learned is Q⋆Q^\star, and the greedy policy read off it is optimal, even though the behavior itself never uses it.

Expected SARSA, and the trouble with the maximum

SARSA samples the next action and Q-learning maximizes over it. A third choice averages over it: expected SARSA uses the target

Rt+1+γ∑aπ(a∣St+1) Q(St+1,a).R_{t+1} + \gamma\sum_a\pi(a \mid S_{t+1})\,Q(S_{t+1},a).

With π\pi the ε-greedy behavior it is on-policy and removes the noise of the sampled At+1A_{t+1}: its target is the average of SARSA's target over At+1A_{t+1}, so its variance is never larger. With π\pi greedy it is Q-learning. On Sutton and Barto's cliff, in experiments adapted from van Seijen et al. (2009), expected SARSA keeps SARSA's advantage over Q-learning, beats SARSA over a wide range of step sizes, and because the cliff's transitions are deterministic it can even use α=1\alpha = 1.

Predict before you look

Same numbers as before: R=−1R = -1, γ=1\gamma = 1, Q(s′,⋅)=(−5,−3,−8,−4)Q(s',\cdot) = (-5, -3, -8, -4), and π\pi is ε-greedy with ε=0.1\varepsilon = 0.1 over the four actions. What is expected SARSA's target?

Show the answer

-4.2

The greedy action (right) has probability 1−ε+ε/4=0.9251 - \varepsilon + \varepsilon/4 = 0.925 and each other action 0.0250.025. The expected next value is 0.925×(−3)+0.025×(−5−8−4)=−2.775−0.425=−3.20.925 \times (-3) + 0.025 \times (-5 - 8 - 4) = -2.775 - 0.425 = -3.2, so the target is −1−3.2=−4.2-1 - 3.2 = -4.2: slightly below Q-learning's −4-4, because it charges the 7.5% chance of exploring, and far from the −9-9 SARSA used after sampling down. With α=0.5\alpha = 0.5, Q(s,a)Q(s,a) moves from −6-6 to −5.1-5.1.

Every one of these targets contains a maximum, explicitly (Q-learning) or through the greedy part of an ε-greedy policy. A maximum over noisy estimates is biased upward: this is maximization bias. Suppose ten actions each truly pay −0.1-0.1 on average, with reward variance 1, and each is estimated from four rewards. Each estimate is unbiased with standard deviation 1/21/2, but the largest of ten such estimates averages about −0.1+1.539/2≈0.67-0.1 + 1.539/2 \approx 0.67: comfortably positive, although every action loses.

Key takeaways

  • SARSA samples the Bellman expectation equation for QπQ^\pi using the next action actually taken: it is on-policy and learns the values of the exploring policy it follows.
  • Q-learning samples the Bellman optimality equation: its target backs up the greedy action, so it learns Q⋆Q^\star from any behavior that keeps trying every action, without importance weights.
  • Beside the cliff, Q-learning's greedy route is the optimal one along the edge, yet the still-exploring agent falls often; SARSA charges its values for its own exploration and takes a detour. With slip noise, the optimal route itself leaves the edge.
  • Q-learning converges to Q⋆Q^\star under Robbins–Monro steps when every pair is updated infinitely often; SARSA also needs GLIE exploration.
  • Expected SARSA averages over the next action, contains both methods, and has lower target variance than SARSA; every target with a maximum over noisy estimates is biased upward.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

You have a large log of transitions recorded long ago by a fixed exploratory policy, and you replay it many times. Which method's estimates converge to Q⋆Q^\star, assuming every state–action pair appears often enough and the step sizes decay suitably?

  1. SARSA, because it uses the next action actually recorded
  2. Both, because both are TD methods
  3. Neither, because learning from another policy's data always needs importance sampling
  4. Q-learning, because its target does not depend on which action comes next
Show the answer

D. Q-learning, because its target does not depend on which action comes next

Q-learning's target maximizes over the next action, so the logged behavior only determines which pairs are updated. SARSA's target uses the logged next action, so on this log it would learn the action values of the old exploratory policy, not Q⋆Q^\star. One-step Q-learning needs no importance weights because its update conditions on the action that was taken.

Question 2

SARSA runs on the cliff with ε\varepsilon fixed at 0.1 forever. Which route does its greedy policy settle on, and why?

  1. A route away from the edge, because its values include the risk of its own exploratory steps
  2. The edge, because SARSA converges to Q⋆Q^\star for any fixed ε\varepsilon
  3. No route at all: with constant exploration SARSA's values diverge
  4. The edge, but only after Q-learning has found it
Show the answer

A. A route away from the edge, because its values include the risk of its own exploratory steps

With fixed ε\varepsilon, SARSA evaluates and improves ε-greedy behavior, for which cells beside the cliff are genuinely dangerous. It reaches the optimal (edge) route only if exploration decays in a GLIE way, which makes its target approach Q-learning's.

Question 3

In a deterministic environment with deterministic rewards, which target is still random given (St,At)(S_t, A_t) and the current QQ?

  1. Q-learning's
  2. Expected SARSA's
  3. SARSA's
  4. None of them
Show the answer

C. SARSA's

Given (St,At)(S_t, A_t), the reward and next state are fixed, so Q-learning's and expected SARSA's targets are fixed numbers. SARSA's target still depends on the sampled next action At+1A_{t+1}, which is random under exploration. That variance is what expected SARSA removes, and why it tolerates larger step sizes.

Question 4

Expected SARSA is run with a target policy π\pi that is greedy with respect to QQ, while the agent behaves ε-greedily. Which algorithm is this?

  1. SARSA
  2. Double Q-learning
  3. Monte Carlo control
  4. Q-learning
Show the answer

D. Q-learning

With a greedy π\pi, ∑aπ(a∣St+1)Q(St+1,a)=max⁡aQ(St+1,a)\sum_a\pi(a \mid S_{t+1})Q(S_{t+1},a) = \max_aQ(S_{t+1},a), so the target is exactly Q-learning's. Expected SARSA with a general target policy is the common generalization of SARSA's on-policy average and Q-learning's maximum.

Go deeper

Further reading

  • C. J. C. H. Watkins & P. Dayan, "Q-learning," Machine Learning 8, 279–292 (1992).
  • G. A. Rummery & M. Niranjan, "On-line Q-learning using connectionist systems," Technical Report CUED/F-INFENG/TR 166, Cambridge University Engineering Department (1994).
  • R. S. Sutton & A. G. Barto, Reinforcement Learning: An Introduction, ch. 6 (MIT Press, 2nd ed., 2018).