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
- Start with every table entry at
initial_q. In the first state, choose an action with the epsilon-greedy rule. - Take the action and observe the reward and next state .
- Choose the next action in with the same epsilon-greedy rule. This is the action that will really be taken.
- Form the target: plus times , or just if the episode terminated.
- Move a fraction of the way toward the target.
- Make and the current state and action and repeat.
- With
expectedset, replace 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 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 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
evaluateafter training. - If 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
| If | Use instead |
|---|---|
| You want the value of the best policy regardless of how you explore | Tabular Q-learning |
| States are too many for a table | DQN, or an actor-critic such as A2C if you want to stay on-policy |
| Real steps are expensive | Dyna |
Math foundations
The Bellman equation for a fixed policy
The value of an action under policy equals the expected reward plus the discounted value of the next state and action, where the next action is drawn from itself. There is no maximum.
The SARSA target
One sample of the right-hand side, using the current table and the action the agent has actually chosen for the next step. When is terminal the target is just .
The update
Move the stored value a fraction of the way toward the target. The bracket is the TD error, which the template's
updatereturns.The Expected SARSA target
The average over next actions is computed exactly instead of being sampled. The target has the same expected value and less variance.
The epsilon-greedy policy
Here this policy both gathers the data and appears in the target.
policy_probsreturns these probabilities, sharing the greedy share equally when several actions tie.
Symbols
- current state and the action taken in it
- reward received for that step
- next state and the action the agent really takes there
- the table entry: estimated return after taking a in s and then following the policy
- the true action values of policy pi
- the epsilon-greedy policy being followed
- discount factor (1.0 by default in the template)
- step size (learning_rate)
- probability of a random action (epsilon)
- number of actions
- the TD target
Worked by hand
Use the defaults , , with four actions. The entry is , the reward is and the next row is . First suppose the agent draws the exploratory third action, worth . Then compute the Expected SARSA target for the same step.
One unlucky sample moved the entry down to . The expected target moves it up to , the direction the average of many samples would take. Q-learning would have used 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 edgeRead 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
- 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.
- What would SARSA's table converge to if 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 equals when is always the best action in .
- 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.
- 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.