AI Wiki中文/EN

SARSA: learn from the action you actually take next

SARSA

Carry a sampled next action into the next step and distinguish exploratory policy values from greedy targets.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

Which next action goes into the target?

Suppose the next state’s two action estimates are 4 and 1. An exploratory choice selects the second action. With reward 0 and discount 0.9, should the learning target be 3.6 or 0.9?

SARSA uses 0.9: the estimate for the sampled next action. It then carries that action into the next interaction, rather than sampling again and possibly taking a different action. Replacing the sampled value with the maximum 4 gives a Q-learning target instead. The distinction is visible in one update, before any long learning curve.

Sutton and Barto, Section 6.4 names the method after the state, action, reward, next state and next action in a transition. Silver’s control lecture places it among on-policy control methods: learning incorporates the behavior policy’s exploratory actions.

The sampled next action sets the SARSA target. Learned action values and model-derived state values are shown separately.
The sampled next action sets the SARSA target. Learned action values and model-derived state values are shown separately.

Prediction and improvement share a behavior policy

Let Q_t(s,a) estimate the return from taking action a in state s and then continuing with the policy being learned. After observing the next reward and state, sample A_(t+1) from that policy and update

Qt+1(St,At)=Qt(St,At)+αt[Rt+1+γQt(St+1,At+1)−Qt(St,At)].Q_{t+1}(S_t,A_t)=Q_t(S_t,A_t)+\alpha_t \left[R_{t+1}+\gamma Q_t(S_{t+1},A_{t+1})-Q_t(S_t,A_t)\right].

All target terms use the old table. Only the visited pair changes. If the successor is truly terminal, continuation is zero and no next action is required. The final reward remains in the target. In ordinary ongoing interaction, the already sampled next action is the one executed next, even if the update changes the table in the meantime.

Make exploration probabilities explicit

The program uses epsilon-greedy behavior with epsilon∈[0,1]. Let m be the number of available actions and B_t(s) the set of actions tied for the largest current value. It distributes exploratory mass uniformly over all actions and the remaining mass uniformly over the ties:

πt(a∣s)=ϵm+1−ϵ∣Bt(s)∣1[a∈Bt(s)].\pi_t(a\mid s)=\frac{\epsilon}{m} +\frac{1-\epsilon}{|B_t(s)|}\mathbf 1[a\in B_t(s)].

This tie convention avoids always selecting the lowest action ID during an initial all-zero table. With two actions, epsilon 0.2 and a unique best action, probabilities are 0.9 and 0.1. The best action also receives some exploratory mass. Silver’s epsilon-greedy discussion motivates coverage; the uniform split across all maximizing ties is this implementation’s explicit convention.

For a fixed table and fixed behavior policy, the expected sampled target is

E[Yt∣St=s,At=a,Qt]=r(s,a)+γ∑s′P(s′∣s,a)∑a′πt(a′∣s′)Qt(s′,a′).\mathbb E[Y_t\mid S_t=s,A_t=a,Q_t] =r(s,a)+\gamma\sum_{s'}P(s'\mid s,a) \sum_{a'}\pi_t(a'\mid s')Q_t(s',a').

A single SARSA update samples that inner action average. Expected SARSA would compute the action average explicitly when available. Q-learning substitutes a maximum instead. For the same table,

∑a′πt(a′∣s′)Qt(s′,a′)≤max⁡a′Qt(s′,a′).\sum_{a'}\pi_t(a'\mid s')Q_t(s',a') \leq\max_{a'}Q_t(s',a').

The inequality follows because an average cannot exceed its largest term. It does not rank the algorithms’ final performance: their tables, data and behavior can evolve differently. At epsilon zero, a greedy sampled target matches the maximum, including tied maxima; at a positive exploration rate, a lower-valued sampled action can change the target.

Exploration changes the value being followed

Use the original arcade with entry 0, room 1 and terminal 2. Leaving entry earns 2; advancing earns 0 and reaches the room. Leaving the room earns 4; spinning earns 1.6 and moves to entry, room or terminal with probabilities 0.4, 0.4 and 0.2. Suppose the greedy choices have stabilized to advance/spin, while epsilon stays at 0.2. Each state still chooses exit with probability 0.1. At discount 0.9, this fixed behavior policy has values

v0=0.2+0.81v1,v1=1.84+0.324v0+0.324v1.v_0=0.2+0.81v_1,\qquad v_1=1.84+0.324v_0+0.324v_1.

The constants average immediate rewards; the coefficients multiply behavior probabilities, transition probabilities and discount. Solving gives approximately v0=3.930748, v1=4.605861. These are state values of the exploratory policy, not the largest entries in its action-value table. The no-exploration optimal values are approximately 4.556962 and 5.063291. Keeping exploration is part of the evaluated behavior, not necessarily a defect in learning.

A fixed epsilon is not GLIE

Convergence to optimal action values needs stronger conditions than having run many episodes. In the standard finite tabular setting, with bounded rewards and 0≤gamma<1, the usual conditions include infinite pair visitation, greediness in the limit and suitable pair-specific step sizes:

Nt(s,a)→∞,Pr⁡πt(A∉Bt(s)∣s)→0,∑kαk(s,a)=∞,∑kαk(s,a)2<∞.N_t(s,a)\to\infty,\qquad \Pr_{\pi_t}(A\notin B_t(s)\mid s)\to0,\qquad \sum_k\alpha_k(s,a)=\infty,\quad \sum_k\alpha_k(s,a)^2<\infty.

The first two requirements describe GLIE: greedy in the limit with infinite exploration. Silver’s convergence slide also specifies the step-size conditions. A decaying epsilon schedule alone does not prove all pairs will be reached in an arbitrary MDP. Our fixed-epsilon demonstration does not claim to meet GLIE or prove convergence to q*.

Sample once, update, carry the action

Save the standalone standard-library program as sarsa.py and run with Python 3.12. The update helper does not mutate its input. The environment and action-choice random streams use separate seeds.

"""Original sarsa teaching example; synthetic episodes, not benchmark reproduction."""
import json
import math
import random


def unit(x, name):
    if isinstance(x, bool) or not isinstance(x, (int, float)) or not math.isfinite(x) or not 0 <= x <= 1:
        raise ValueError(name+' must be finite in [0,1]')


def sequence(states, rewards, values, terminated):
    if type(terminated) is not bool or len(values)<2 or any(not math.isfinite(x) for x in values) or values[-1]!=0:
        raise ValueError('finite values with a zero terminal component required')
    if not rewards or len(states)!=len(rewards)+1 or any(not math.isfinite(r) for r in rewards):
        raise ValueError('nonempty finite rewards and one extra state required')
    terminal=len(values)-1
    if any(type(s) is not int or not 0<=s<=terminal for s in states):
        raise ValueError('state index outside table')
    if terminal in states[:-1] or (states[-1]==terminal)!=terminated:
        raise ValueError('termination flag must match the final state only')


class Arcade:
    def __init__(self, seed):
        self.rng = random.Random(seed)
        self.state = 2

    def reset(self):
        self.state = 0
        return self.state

    def step(self, action):
        if type(action) is not int or action not in (0, 1) or self.state == 2:
            raise ValueError('valid action and a nonterminal state required')
        if self.state == 0:
            self.state, reward = (2, 2.0) if action == 0 else (1, 0.0)
        elif action == 0:
            self.state, reward = 2, 4.0
        else:
            u = self.rng.random()
            self.state = 0 if u < .4 else 1 if u < .8 else 2
            reward = 1.6
        return self.state, reward, self.state == 2


def table(q):
    if len(q)!=3 or any(len(row)!=2 or any(not math.isfinite(x) for x in row) for row in q) or q[2]!=[0,0]:
        raise ValueError('finite 3 by 2 table with zero terminal row required')


def choose(q,state,epsilon,rng):
    table(q);unit(epsilon,'epsilon')
    if type(state) is not int or state not in (0,1):raise ValueError('nonterminal state required')
    if rng.random()<epsilon:return rng.randrange(2)
    best=max(q[state]);ties=[a for a in range(2) if q[state][a]==best]
    return rng.choice(ties)


def step(q,state,action,reward,next_state,next_action,terminated,alpha=.5,gamma=.9):
    table(q);unit(alpha,'alpha');unit(gamma,'gamma')
    sequence([state,next_state],[reward],[0,0,0],terminated)
    if type(action) is not int or action not in (0,1):raise ValueError('valid action required')
    if (terminated and next_action is not None) or (not terminated and (type(next_action) is not int or next_action not in (0,1))):
        raise ValueError('sampled next action required exactly when nonterminal')
    target=reward+(0 if terminated else gamma*q[next_state][next_action]);delta=target-q[state][action]
    out=[row.copy() for row in q];out[state][action]+=alpha*delta
    return out,dict(target=target,delta=delta)


def train(episodes=20000,epsilon=.2,seed=41,max_steps=1000):
    unit(epsilon,'epsilon')
    if type(episodes) is not int or episodes<1 or type(max_steps) is not int or max_steps<1:raise ValueError('positive budgets required')
    env=Arcade(seed);rng=random.Random(seed+1);q=[[0.0,0.0] for _ in range(3)];counts=[[0,0] for _ in range(3)];cutoffs=0
    for _ in range(episodes):
        s=env.reset();a=choose(q,s,epsilon,rng)
        for k in range(max_steps):
            nxt,r,done=env.step(a);nxt_a=None if done else choose(q,nxt,epsilon,rng)
            counts[s][a]+=1;alpha=.8/counts[s][a]**.6
            q,_=step(q,s,a,r,nxt,nxt_a,done,alpha)
            if done:break
            s,a=nxt,nxt_a
        if not done:cutoffs+=1
    return dict(q=q,counts=counts,greedy=[max(range(2),key=lambda a:q[s][a]) for s in (0,1)],cutoffs=cutoffs)


def demo():
    q=[[2.,5.],[4.,1.],[0.,0.]];updated,row=step(q,0,1,0,1,1,False)
    # A fixed epsilon policy around [advance,spin], not an input to training.
    p=.2/2;g=.9;v1=(4*p+1.6*(1-p)+g*.4*(1-p)*2*p)/(1-g*.4*(1-p)-g*g*.4*(1-p)**2)
    return dict(sampled_update=dict(**row,q=updated),max_action_target=.9*4,trained=train(),
                epsilon=.2,fixed_behavior_reference=[2*p+g*(1-p)*v1,v1,0],optimal_reference=[360/79,400/79,0])


if __name__=='__main__':
    print(json.dumps(demo(),indent=2,allow_nan=False))

In the one-update example, the current pair has value 5 and the sampled successor action value 1. The target is 0.9, the error is −4.1, and alpha 0.5 produces 2.95. Choosing the maximum successor value would instead use target 3.6.

Training uses 20,000 episodes, environment seed 41, action seed 42, epsilon 0.2 and step size 0.8/N(s,a)^0.6. The resulting nonterminal rows are approximately [[2,4.178836],[4,4.745020]], with counts [[4050,35869],[5996,49611]]; greedy actions are [1,1]. No episode in this run reaches the 1,000-step collection cap. These sampled action values are not exact policy values or a benchmark score.

If the cap is reached, the program still bootstraps from the final nonterminal state and sampled continuation action, reports a cutoff, and resets data collection. That sampled action represents the continuing-task target even though the collection boundary prevents executing it in this rollout. True termination requires next_action=None and zero continuation. Neither case uses the new reset state as the old episode’s successor.

The generic table update arithmetic touches one pair, but this small implementation checks and copies its table and scans actions to choose one. For a generalized S × A table written this way, a transition costs O(SA) and memory is O(SA); it is a transparent teaching implementation, not a sparse optimized solver. Here S=3, A=2. Validation checks that the terminal row stays zero and that a next action is present exactly when required.

On-policy does not mean without exploration

An exploratory action can lower a target, which can be appropriate when that same behavior will continue. A separate greedy evaluation asks a different question. Report which policy produced evaluation returns and whether exploration was active.

The training policy changes with the table; finite-run values are not exact solutions to one permanently fixed policy. Function approximation, off-policy replay, partial observations and changing rewards add assumptions absent from this small example. Q-learning has a different target; eligibility traces extend credit across earlier visits but require their own update conventions.

Keep the fifth element of the transition

  1. Why sample the next action before updating, then reuse it?

    Answer: It keeps the sampled continuation in the target aligned with the next action in the observed trajectory. Resampling after the table changes can produce a different continuation from the one used in that update.

  2. With current value 5, reward 0, next sampled value 1, gamma 0.9 and alpha 0.5, calculate the update.

    Answer: Target 0.9; error 0.9−5=−4.1; new value 5+0.5×(−4.1)=2.95. The alternative maximum 4 is not used by this SARSA sample.

  3. With two actions and epsilon 0.2, what are the probabilities when there is one best action? What if both tie?

    Answer: A unique best gets 0.2/2+0.8=0.9, the other 0.1. If both tie under the stated uniform rule, each gets 0.1+0.8/2=0.5.

  4. You lower epsilon every episode and observe a good greedy policy. Have you established optimal convergence?

    Answer: No. Check visitation and pair-specific step-size assumptions, as well as the finite Markov setting. A finite run cannot establish infinite exploration, and decreasing epsilon does not by itself make rarely reachable pairs adequately sampled.

Read the algorithm and the convergence conditions separately

The working draft’s SARSA section gives the five-element update and terminal convention; its historical convergence remark is attributed there to personal communication. Silver’s control lecture explicitly lists GLIE and step-size conditions. This article uses those as stated assumptions, not as a newly audited full theorem proof. The program is original and does not reproduce the lecture’s windy-gridworld experiment.

Make a prediction, then check

The sampled next action has Q=1 while another action has Q=4. With reward0 and gamma0.9, what is the SARSA target?

Choose one answer

Learning objectives

  • Implement the five-element SARSA transition without resampling the carried action.
  • Distinguish a fixed exploration rate from GLIE and state the visitation and step-size conditions.

Prerequisites & connections

Explore related knowledge →

References

  1. Reinforcement Learning: An Introduction — second-edition working draft (2014–2015)
    Richard S. Sutton; Andrew G. Barto · 2015
  2. Lecture 5: Model-Free Control
    David Silver · 2015

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-23 · Single AI author. Scoped reading: PDF168–169 §6.4/Fig6.9: state-action transitions, carried action, terminal row zero; old draft personal-communication convergence remark is not a new published proof. Read2026-09-23. Read PDF5,11,15,20,23 and visually inspected the image-only algorithm on PDF22. On/off-policy distinction, epsilon exploration, carried next action, GLIE and step-size conditions. Infinite state-action visitation is a separate assumption; a decaying epsilon schedule alone is not proved sufficient for arbitrary MDPs. Course year from author teaching page; no benchmark replication. 6 paired equations and four explained exercises. Checked sampled-action targets, pre-update action reuse, greedy tie sampling, epsilon endpoints, terminal and cutoff actions, seeded control and a separate fixed-epsilon policy oracle. Fixed epsilon is not GLIE; action values are not state values.

  • Checked sampled-action targets, pre-update action reuse, greedy tie sampling, epsilon endpoints, terminal and cutoff actions, seeded control and a separate fixed-epsilon policy oracle. Fixed epsilon is not GLIE; action values are not state values.
  • Four computed SVG variants per topic;12 numeric/geometry tests and36 responsive cases passed. All twelve selected current captures directly viewed; browser inputs bound by SHA before integration. Full article acceptance recorded separately.

Source locations checked:

  • Reinforcement Learning: An Introduction — second-edition working draft (2014–2015) · PDF168–169 §6.4/Fig6.9: state-action transitions, carried action, terminal row zero; old draft personal-communication convergence remark is not a new published proof. Read2026-09-23.
  • Lecture 5: Model-Free Control · Read PDF5,11,15,20,23 and visually inspected the image-only algorithm on PDF22. On/off-policy distinction, epsilon exploration, carried next action, GLIE and step-size conditions. Infinite state-action visitation is a separate assumption; a decaying epsilon schedule alone is not proved sufficient for arbitrary MDPs. Course year from author teaching page; no benchmark replication.

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.