Computer Engineering is coming soon

We're still writing and reviewing the notes for every subject, and we'll open it when every subject is ready. Meanwhile you can practise aptitude, ask Aria about any subject, or see the branches that are ready.

Sarsa and Q-learning

Clear, exam-ready notes on Sarsa (on-policy TD control) and Q-learning (off-policy TD control): definitions, derivations, formulas, worked numerical and short-program examples, common mistakes, and exam guidance.

Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.

Why it matters

Sarsa and Q-learning are the basic tabular reinforcement-learning algorithms for learning action-value functions in Markov decision processes. Engineers use them for model-free control: to learn how to act (a policy) from interaction data without knowing the environment model — for example, in simple robotics, resource scheduling, or as building blocks for deep RL methods like DQN.

Key ideas

Start from a Markov decision process (MDP): a tuple (S, A, P, R, γ) where S is a finite set of states, A is a finite set of actions, P(s'|s,a) is the transition probability, R(s,a,s') is the immediate reward (expected or sampled), and 0 ≤ γ < 1 is the discount factor; for episodic tasks with bounded returns, it is common to allow γ = 1. All these terms are defined before they are used.

A policy π is a mapping from states to a probability distribution over actions: π(a|s) = P(A_t=a | S_t=s). The goal in control is to find an optimal policy π* that maximises expected discounted return.

Define the action-value function (Q-function) for policy π:

  • Qπ(s,a) = Eπ[ G_t | S_t=s, A_t=a ], where G_t = sum_{k=0..∞} γ^k R_{t+k+1}. Qπ gives expected return starting from state s taking action a and following π thereafter.

The Bellman expectation equation for Qπ is: Qπ(s,a) = E[ R_{t+1} + γ * E_{A'~π}[ Qπ(S_{t+1}, A') ] | S_t=s, A_t=a ].

Temporal-difference (TD) control learns Qπ or Q* (optimal Q) by bootstrapping one-step samples.

Key algorithms:

  • Sarsa: an on-policy TD control method that learns Q for the policy actually followed (including its exploration). The name Sarsa is from the sequence (S_t, A_t, R_{t+1}, S_{t+1}, A_{t+1}) used in the update. Sarsa update uses the action A_{t+1} actually chosen by the behaviour policy.
  • Q-learning: an off-policy TD control method that learns Q* (the optimal action-value function) by bootstrapping using the maximum action-value at the next state, independent of the behaviour policy used to collect data.

On-policy vs off-policy: on-policy means learning about and improving the same policy used to generate data; off-policy means learning about a target policy (e.g., greedy) while following a different behaviour policy (e.g., exploratory ε-greedy). An ε-greedy policy selects a greedy action with probability 1−ε and a non-greedy action uniformly at random with probability ε.

Assumptions for convergence (high-level): finite state and action sets; each state-action pair is visited infinitely often (adequate exploration); step-size (learning rate) schedule α_t(s,a) satisfies sum_t α_t = ∞ and sum_t α_t^2 < ∞; for Sarsa to converge to the optimal Q, a suitable exploration schedule (GLIE: greedy in the limit with infinite exploration) is used. Precise technical statements and proofs are advanced; verify with standard textbooks (e.g., Sutton & Barto) or original papers.

What to draw for exam diagrams:

  • Draw a small MDP with 3 states (S1,S2,S3) as circles. Draw directed edges for actions labelled a1,a2. Annotate an edge with probability p and reward r. Beside each state draw a small table of Q(s,a) values before and after one update. For Sarsa vs Q-learning: draw an example transition S_t —(a_t,r)→ S_{t+1} with two arrows from S_{t+1}: one to chosen action a_{t+1} (Sarsa target) and one to best action a* (Q-learning target). Label targets explicitly.

Derivation idea universities ask: derive the Sarsa update from the TD(0) idea and the Bellman expectation for Qπ, and derive Q-learning update from the Bellman optimality equation for Q*.

Formulas

G_t = Σ_{k=0..∞} γ^k R_{t+k+1} — return from time t; γ is unitless and 0 ≤ γ < 1 for continuing tasks; for episodic tasks with finite length and bounded rewards, γ may be 1; applies to discounted infinite-horizon problems or finite-horizon episodes.

Qπ(s,a) = Eπ[ G_t | S_t=s, A_t=a ] — action-value for policy π; unit: same as reward; applies when π is fixed.

TD error (Sarsa): δ_t = R_{t+1} + γ · Q(S_{t+1}, A_{t+1}) - Q(S_t, A_t) — unit: same as reward; applies to Sarsa update step. If S_{t+1} is terminal, take the bootstrap term as 0 (i.e., use δ_t = R_{t+1} − Q(S_t, A_t)).

Sarsa update: Q(S_t, A_t) ← Q(S_t, A_t) + α · δ_t — α ∈ (0,1] is learning rate (unitless); applies each time-step when sample (S_t,A_t,R_{t+1},S_{t+1},A_{t+1}) is observed.

TD error (Q-learning): δ_t = R_{t+1} + γ · max_a Q(S_{t+1}, a) - Q(S_t, A_t) — unit: same as reward; applies to Q-learning. If S_{t+1} is terminal, set the max term to 0.

Q-learning update: Q(S_t, A_t) ← Q(S_t, A_t) + α · δ_t — α ∈ (0,1] is learning rate; applies with off-policy sample.

Bellman optimality equation for Q*: Q*(s,a) = E[ R_{t+1} + γ · max_{a'} Q*(S_{t+1}, a') | S_t=s, A_t=a ] — unit: reward; defines optimal Q.

Conditions for convergence (high-level): each (s,a) visited infinitely often; α_t(s,a) satisfies Σ α_t = ∞ and Σ α_t^2 < ∞; MDP finite. (Verify precise technical forms before citing in an exam answer.)

Worked examples

Example 1 — Numerical single-step update (tabular, hand calculation). Given: Q(S_t,A_t) = 2.0, reward R_{t+1} = 1.0, discount γ = 0.9, learning rate α = 0.5. Case A (Sarsa): A_{t+1} was chosen and Q(S_{t+1}, A_{t+1}) = 1.5.

  • Formula: Q ← Q + α [ R + γ · Q(S',A') - Q ].
  • Compute target: R + γ·Q(S',A') = 1.0 + 0.9·1.5 = 1.0 + 1.35 = 2.35.
  • TD error: 2.35 - 2.0 = 0.35.
  • Update: Δ = 0.5 · 0.35 = 0.175.
  • New Q = 2.0 + 0.175 = 2.175.

Case B (Q-learning): max_a Q(S_{t+1}, a) = 2.5.

  • Formula: Q ← Q + α [ R + γ · max_a Q(S',a) - Q ].
  • Target: 1.0 + 0.9·2.5 = 1.0 + 2.25 = 3.25.
  • TD error: 3.25 - 2.0 = 1.25.
  • Update: Δ = 0.5 · 1.25 = 0.625.
  • New Q = 2.0 + 0.625 = 2.625.

This example highlights that Q-learning pushes toward the greedy (max) estimate while Sarsa uses the action actually taken.

Example 2 — Short derivation model answer (exam-style): show Q-learning update from Bellman optimality.

  • Start from Bellman optimality: Q*(s,a) = E[ R_{t+1} + γ max_{a'} Q*(S_{t+1},a') | s,a ].
  • We cannot compute expectation without model; instead sample one-step transition (s,a,r,s'). Use the sample estimate of right-hand side: r + γ max_a' Q(s',a').
  • Use stochastic approximation to move Q(s,a) toward sample target: Q(s,a) ← Q(s,a) + α [ r + γ max_a' Q(s',a') - Q(s,a) ].
  • This is the Q-learning update. Under the stated convergence conditions, repeated application converges to Q* with probability 1.

Example 3 — short Python snippet (single-step update functions). Code:

def sarsa_update(Q, s, a, r, s2, a2, alpha=0.5, gamma=0.9):
    td = r + gamma * Q.get((s2,a2),0.0) - Q.get((s,a),0.0)
    Q[(s,a)] = Q.get((s,a),0.0) + alpha * td
    return Q

def q_learning_update(Q, s, a, r, s2, Q_values_s2, alpha=0.5, gamma=0.9):
    # Q_values_s2: dict of action->Q for s2
    max_q = max(Q_values_s2.values()) if Q_values_s2 else 0.0
    td = r + gamma * max_q - Q.get((s,a),0.0)
    Q[(s,a)] = Q.get((s,a),0.0) + alpha * td
    return Q

Sample input and exact output (interpreting dictionaries):

  • Input for Sarsa: Q = {('s','a'):2.0, ('s2','a2'):1.5}, call sarsa_update(Q,'s','a',1.0,'s2','a2').
  • Output Q becomes {('s','a'):2.175, ('s2','a2'):1.5}.
  • Input for Q-learning: Q = {('s','a'):2.0}, Q_values_s2 = {'a1':2.5,'a2':1.0}, call q_learning_update(Q,'s','a',1.0,'s2',Q_values_s2).
  • Output Q becomes {('s','a'):2.625}.

(These match the numerical worked example above.)

Common mistakes

  • Not ensuring sufficient exploration: if some (s,a) are never visited, convergence guarantees fail.
  • Wrong sign in TD error (subtracting in reverse) or forgetting γ factor.
  • Using constant α that is too large (divergence/noisy) or too small (very slow); and claiming convergence without the required α schedule conditions.
  • Confusing value-function notation V(s) with Q(s,a) in derivations.

For your exam

Kinds of questions:

  • Definitions: define MDP, policy, Qπ, Bellman equations, on-policy/off-policy.
  • Short notes: compare Sarsa and Q-learning; explain exploration-exploitation, ε-greedy, GLIE.
  • Derivations: derive Sarsa update from Bellman expectation; derive Q-learning from Bellman optimality and explain why off-policy learning is possible.
  • Numericals: perform one or more tabular update steps given numbers (like the worked example). Show steps and final numeric values.
  • Programs: short pseudocode or Python snippet implementing one-step update or loop for tabular algorithms.
  • Diagrams: draw a small MDP and show Sarsa vs Q-learning targets graphically.

What a full-marks answer includes:

  • Clear definitions of all terms before use, correct formulas written, step-by-step algebra for derivations, explanation of on-policy vs off-policy, conditions for convergence stated (and caveated if exact technical conditions omitted), and a small worked numeric example or diagram if asked.

Quick check

Q1: In a sample (S_t,A_t,R_{t+1},S_{t+1}), which additional item is needed to perform a Sarsa update but not a Q-learning update? Q2: Which algorithm uses the target R_{t+1} + γ · max_a Q(S_{t+1},a)? Q3: Name two high-level conditions required (informally) for convergence of tabular Q-learning. Answers: A1: The next action A_{t+1} actually taken (for Sarsa). A2: Q-learning. A3: (1) Every state-action pair visited infinitely often (sufficient exploration); (2) step-sizes α_t with Σ α_t = ∞ and Σ α_t^2 < ∞ (diminishing, but not too fast).

Finished this topic? Mark it so your progress, study plan and readiness keep up.

Stuck on something here?