Sign in

SARSA

State-Action-Reward-State-Action

A table of action values updated toward the reward plus the value of the action the agent really takes next, so it learns about the policy it follows.

Overview

SARSA keeps the same table as Q-learning: one estimate per state and action. The difference is one term in the update. Q-learning assumes the best action will be taken next. SARSA waits to see which action the agent actually picks next, exploration included, and uses that entry. The table therefore describes the policy being followed, with its occasional random moves. This is what on-policy means. Near a hazard that matters: if a random step can be disastrous, the values of nearby states are pulled down and the agent learns to keep its distance. The name spells out the five things one update uses: state, action, reward, next state, next action. The template includes the 4 by 12 cliff-walking grid.

A short history

Gavin Rummery and Mahesan Niranjan described the method in a 1994 Cambridge technical report under the name modified connectionist Q-learning. Richard Sutton proposed the name SARSA in 1996, after the five values each update uses: the state, the action, the reward, the next state and the next action. Unlike Q-learning it learns the value of the policy it is really following, exploration included, which makes it the standard example of on-policy temporal difference control.

How it works

  1. Start with every table entry at initial_q. In the first state, choose an action with the epsilon-greedy rule.
  2. Take the action and observe the reward rr and next state s′s'.
  3. Choose the next action a′a' in s′s' with the same epsilon-greedy rule. This is the action that will really be taken.
  4. Form the target: rr plus γ\gamma times Q(s′,a′)Q(s', a'), or just rr if the episode terminated.
  5. Move Q(s,a)Q(s, a) a fraction α\alpha of the way toward the target.
  6. Make s′s' and a′a' the current state and action and repeat.
  7. With expected set, replace Q(s′,a′)Q(s', a') in the target by the average of the next row weighted by the policy's probabilities. That is Expected SARSA.

Watch out for

  • The table describes the exploring policy, not the best one. With a fixed ε\varepsilon it settles on a path that is safe under exploration, which on the cliff is longer than the shortest path.
  • The sampled next action adds noise: the same transition gives a different target depending on which a′a' was drawn. Expected SARSA removes that source of noise.
  • The greedy read-out of an on-policy table can be poor in states the policy rarely visits, because those entries are barely trained. Check evaluate after training.
  • If ε\varepsilon is never reduced, the values never become those of the best policy. Convergence to the best policy needs exploration that fades over time.

Use cases

When to use it

Small problems with discrete states and actions where the reward collected while learning matters, or where exploratory mistakes are expensive. Use Q-learning when only the final greedy policy counts.

In industry

Research and teaching
Taught beside Q-learning on the cliff walking example, where it learns the safer path because it accounts for its own exploration.
Online control
Small systems that must learn while operating, where the cost of exploratory mistakes during learning counts.
Operations
Tabular queue or resource decisions with a few states, when the deployed policy will keep some randomness.

Choosing it: what must hold

  • A small number of discrete states and actions, so a table is practical.
  • A policy that keeps exploring, with exploration reduced over time if the best policy is the goal.
  • Performance during learning matters, not only the final policy.

When to choose something else

IfUse instead
You want the value of the best policy regardless of how you exploreTabular Q-learning
States are too many for a tableDQN, or an actor-critic such as A2C if you want to stay on-policy
Real steps are expensiveDyna

Math foundations

  1. The Bellman equation for a fixed policy

    Qπ(s,a)=Eπ[r+γ Qπ(s′,a′)  ∣  s,a]Q^{\pi}(s, a) = \mathbb{E}_{\pi}\bigl[ r + \gamma\, Q^{\pi}(s', a') \;\big|\; s, a \bigr]

    The value of an action under policy π\pi equals the expected reward plus the discounted value of the next state and action, where the next action is drawn from π\pi itself. There is no maximum.

  2. The SARSA target

    y=r+γ Q(s′,a′),a′∼π(⋅∣s′)y = r + \gamma\, Q(s', a'), \qquad a' \sim \pi(\cdot \mid s')

    One sample of the right-hand side, using the current table and the action the agent has actually chosen for the next step. When s′s' is terminal the target is just rr.

  3. The update

    Q(s,a)←Q(s,a)+α (y−Q(s,a))Q(s, a) \leftarrow Q(s, a) + \alpha\, \bigl( y - Q(s, a) \bigr)

    Move the stored value a fraction α\alpha of the way toward the target. The bracket is the TD error, which the template's update returns.

  4. The Expected SARSA target

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

    The average over next actions is computed exactly instead of being sampled. The target has the same expected value and less variance.

  5. The epsilon-greedy policy

    π(a∣s)={1−ε+ε∣A∣if a=arg⁡max⁡bQ(s,b)ε∣A∣otherwise\pi(a \mid s) = \begin{cases} 1 - \varepsilon + \dfrac{\varepsilon}{|\mathcal{A}|} & \text{if } a = \arg\max_{b} Q(s, b) \\[1ex] \dfrac{\varepsilon}{|\mathcal{A}|} & \text{otherwise} \end{cases}

    Here this policy both gathers the data and appears in the target. policy_probs returns these probabilities, sharing the greedy share equally when several actions tie.

Symbols

s,as, a
current state and the action taken in it
rr
reward received for that step
s′,a′s', a'
next state and the action the agent really takes there
Q(s,a)Q(s, a)
the table entry: estimated return after taking a in s and then following the policy
QπQ^{\pi}
the true action values of policy pi
π\pi
the epsilon-greedy policy being followed
γ\gamma
discount factor (1.0 by default in the template)
α\alpha
step size (learning_rate)
ε\varepsilon
probability of a random action (epsilon)
∣A∣|\mathcal{A}|
number of actions
yy
the TD target

Worked by hand

Use the defaults α=0.25\alpha = 0.25, γ=1\gamma = 1, ε=0.1\varepsilon = 0.1 with four actions. The entry is Q(s,a)=−6Q(s, a) = -6, the reward is −1-1 and the next row is (−5,−3,−9,−5)(-5, -3, -9, -5). First suppose the agent draws the exploratory third action, worth −9-9. Then compute the Expected SARSA target for the same step.

y=−1+(−9)=−10,Q(s,a)←−6+0.25×(−10−(−6))=−7y = -1 + (-9) = -10, \qquad Q(s, a) \leftarrow -6 + 0.25 \times (-10 - (-6)) = -7
π(best)=0.9+0.025=0.925,π(other)=0.025\pi(\text{best}) = 0.9 + 0.025 = 0.925, \qquad \pi(\text{other}) = 0.025
∑bπ(b∣s′) Q(s′,b)=0.925×(−3)+0.025×(−5−9−5)=−3.25\sum_{b} \pi(b \mid s')\, Q(s', b) = 0.925 \times (-3) + 0.025 \times (-5 - 9 - 5) = -3.25
y=−1+(−3.25)=−4.25,Q(s,a)←−6+0.25×(−4.25−(−6))=−5.5625y = -1 + (-3.25) = -4.25, \qquad Q(s, a) \leftarrow -6 + 0.25 \times (-4.25 - (-6)) = -5.5625

One unlucky sample moved the entry down to −7-7. The expected target moves it up to −5.5625-5.5625, the direction the average of many samples would take. Q-learning would have used −3-3 and ignored exploration entirely.

Visual example

Loading the example.

Try this

  • Run to 500 episodes and compare the two paths: SARSA keeps a row or two away from the cliff.
  • Set ε to 0 and train again: with no random moves the two rules learn the same path.
  • Switch the target to Expected SARSA and read how the target in the last line changes.

Code sample

from impl import CliffWalk, SARSA
from config import SARSAConfig

env = CliffWalk()
agent = SARSA(env.n_states, env.n_actions, SARSAConfig(episodes=1000))
returns = agent.train(env)        # return of every training episode
print(agent.evaluate(env))        # about -17: a safe path away from the cliff edge
Read the implementation (139 lines)
"""SARSA and Expected SARSA, with a cliff-walking environment to learn on.

SARSA keeps a table Q[state, action] and moves each entry toward
reward + gamma * Q[next_state, next_action], where next_action is the action the agent really takes
next. The table therefore describes the exploring policy itself (on-policy), which makes the agent
keep away from states where a random exploratory step is costly.
"""
from __future__ import annotations

import numpy as np

try:
    from .config import SARSAConfig
except ImportError:  # run from the template's own folder
    from config import SARSAConfig


class CliffWalk:
    """Cliff walking (Sutton and Barto, example 6.6): a rows x cols grid, start bottom-left, goal bottom-right.

    The bottom-row cells between start and goal are the cliff: stepping there gives -100 and sends the
    agent back to the start. Every other step gives -1. States are integers row * cols + col.
    Actions: 0 up, 1 right, 2 down, 3 left. A move into a wall leaves the agent where it is.
    `step` returns (state, reward, terminated, truncated). The shortest safe path runs along the cliff
    edge and has return -(cols + 1), which is -13 for the default 4 x 12 grid.
    """

    n_actions = 4
    _MOVES = ((-1, 0), (0, 1), (1, 0), (0, -1))

    def __init__(self, rows: int = 4, cols: int = 12, max_steps: int = 500) -> None:
        if rows < 2 or cols < 3:
            raise ValueError("the grid needs at least 2 rows and 3 columns")
        self.rows, self.cols, self.max_steps = rows, cols, max_steps
        self.n_states = rows * cols
        self.start = (rows - 1) * cols
        self.goal = rows * cols - 1
        self.state = self.start
        self.t = 0

    @property
    def optimal_return(self) -> float:
        return -float(self.cols + 1)

    def is_cliff(self, state: int) -> bool:
        """True for the bottom-row cells strictly between start and goal."""
        return self.start < state < self.goal

    def reset(self) -> int:
        self.state = self.start
        self.t = 0
        return self.state

    def step(self, action: int):
        """Apply one action (0..3). Returns (state, reward, terminated, truncated)."""
        row, col = divmod(self.state, self.cols)
        d_row, d_col = self._MOVES[int(action)]
        row = min(max(row + d_row, 0), self.rows - 1)
        col = min(max(col + d_col, 0), self.cols - 1)
        self.state = row * self.cols + col
        self.t += 1
        reward = -1.0
        if self.is_cliff(self.state):
            reward = -100.0
            self.state = self.start
        terminated = self.state == self.goal
        truncated = not terminated and self.t >= self.max_steps
        return self.state, reward, terminated, truncated


class SARSA:
    """Tabular SARSA agent with an epsilon-greedy policy.

    n_states, n_actions: size of the table. States and actions are integers starting at 0.
    With `expected=True` in the config the target averages Q[next_state, .] over the epsilon-greedy
    policy instead of using the one sampled next action (Expected SARSA).
    """

    def __init__(self, n_states: int, n_actions: int, config: SARSAConfig | None = None) -> None:
        self.config = config or SARSAConfig()
        self.n_states, self.n_actions = n_states, n_actions
        self.q = np.full((n_states, n_actions), self.config.initial_q, dtype=float)
        self.rng = np.random.default_rng(self.config.seed)

    def act(self, state: int, greedy: bool = False) -> int:
        """Epsilon-greedy action for `state`. greedy=True always takes the first best action."""
        if greedy:
            return int(np.argmax(self.q[state]))
        if self.rng.random() < self.config.epsilon:
            return int(self.rng.integers(self.n_actions))
        row = self.q[state]
        return int(self.rng.choice(np.flatnonzero(row == row.max())))  # break ties at random

    def policy_probs(self, state: int) -> np.ndarray:
        """Action probabilities of the epsilon-greedy policy in `state`, shape (n_actions,)."""
        row = self.q[state]
        best = row == row.max()
        return self.config.epsilon / self.n_actions + (1.0 - self.config.epsilon) * best / best.sum()

    def update(self, state: int, action: int, reward: float, next_state: int, next_action: int,
               terminated: bool) -> float:
        """One SARSA step for the transition (s, a, r, s', a'). Returns the TD error before the update."""
        cfg = self.config
        if terminated:
            next_value = 0.0
        elif cfg.expected:
            next_value = float(self.policy_probs(next_state) @ self.q[next_state])
        else:
            next_value = self.q[next_state, next_action]
        td_error = reward + cfg.gamma * next_value - self.q[state, action]
        self.q[state, action] += cfg.learning_rate * td_error
        return float(td_error)

    def train(self, env, episodes: int | None = None) -> list[float]:
        """Run `episodes` episodes of epsilon-greedy control. Returns the return of each episode."""
        returns = []
        for _ in range(self.config.episodes if episodes is None else episodes):
            state, done, total = env.reset(), False, 0.0
            action = self.act(state)
            while not done:
                next_state, reward, terminated, truncated = env.step(action)
                next_action = self.act(next_state)
                self.update(state, action, reward, next_state, next_action, terminated)
                state, action = next_state, next_action
                total, done = total + reward, terminated or truncated
            returns.append(total)
        return returns

    def evaluate(self, env) -> float:
        """Return of one episode of the greedy policy (no exploration, no learning)."""
        state, done, total = env.reset(), False, 0.0
        while not done:
            state, reward, terminated, truncated = env.step(self.act(state, greedy=True))
            total, done = total + reward, terminated or truncated
        return total

    def greedy_policy(self) -> np.ndarray:
        """Best action in every state, shape (n_states,)."""
        return np.argmax(self.q, axis=1)
Repository
Not published yet
Needs
Python 3.10 and NumPy
Tests
8, run with python3 -m unittest -v

Practice

Using the template, train SARSA on CliffWalk() for 1000 episodes and print evaluate, then reshape greedy_policy to 4 by 12 and compare the path with the cliff-edge path of return -13. Call policy_probs on the next row of the worked example to check the probabilities. Repeat the training with SARSAConfig(expected=True) and compare the spread of the returns list.

Check on learning

  1. On the cliff grid SARSA learns a longer path than Q-learning, yet collects more reward per episode during training. How can the worse path give the better result?
    A way to think about it

    Count what a random step costs on each path. Beside the cliff one bad draw costs 100. A row further up, the same draw costs a step or two. The table is scoring the path as walked by an agent that sometimes stumbles.

  2. What would SARSA's table converge to if ε\varepsilon were slowly reduced to zero during training, and how would it then compare with Q-learning's?
    A way to think about it

    Look at the two targets when the policy is fully greedy. Ask what Q(s′,a′)Q(s', a') equals when a′a' is always the best action in s′s'.

  3. Expected SARSA and SARSA have targets with the same average. Why would you expect Expected SARSA to tolerate a larger step size?
    A way to think about it

    The step size has to be small enough to average out noise in the target. Identify which source of noise the expected form removes and which it leaves.

  4. Why does SARSA have to choose the next action before it can update, whereas Q-learning can update as soon as it sees the next state?
    A way to think about it

    List the quantities each target needs. One of them needs to know the agent's next decision, the other only needs the table row of the next state.