Chapter 10
On-policy Control with Approximation
Control with a function approximator looks at first like a routine extension of Chapter 9: approximate action values instead of state values, act -greedily with respect to them, and let generalized policy iteration do the rest.Richard S. Sutton and Andrew G. Barto. Reinforcement Learning: An Introduction. Adaptive Computation and Machine Learning. MIT Press, Cambridge, MA, second edition, 2018. ISBN 978-0-262-03924-6. URL http://incompleteideas.net/book/the-book-2nd.html For episodic tasks this is exactly what we do, and the result is semi-gradient Sarsa. For continuing tasks the extension forces a surprising retreat. Once states can no longer be told apart, the discounted formulation stops defining a sensible problem: averaged over the states the policy visits, the discounted value of every policy is its average reward divided by , whatever is. We therefore replace discounting by the average-reward setting, with differential returns, values, Bellman equations and TD errors. This chapter develops both halves and proves the facts on which the change of setting rests.
10.1Episodic Semi-gradient Control#
Training examples now have the form , where is any approximation of : a Monte Carlo return, a one-step or an -step Sarsa target. The semi-gradient update (9.3) carries over word for word,
(10.1)and with the one-step target it becomes episodic semi-gradient Sarsa, the function-approximation form of Algorithm 6.6:
(10.2)For a fixed policy this is nothing new. The pairs form a Markov chain with transition probabilities , and with linear the update is linear TD(0) on that chain. Everything in Section 9.4 applies with state–action pairs in place of states: convergence to a TD fixed point, and the error bound Theorem 9.7 in the norm weighted by the on-policy distribution of pairs.
Control couples this evaluation with improvement. If the action set is finite and small, we compute for every , find the greedy action, and act -greedily; the same policy generates the data and is evaluated, so the method is on-policy. Large or continuous action sets make the maximization itself a problem, one of the reasons for the policy-gradient methods of Chapter 13.
Algorithm 10.1 (Episodic Semi-gradient Sarsa). Input: a differentiable . Parameters: , small . Initialize: arbitrarily (e.g. ).
- Loop for each episode: choose initial and (e.g. -greedy w.r.t. ). Repeat:
- Take , observe .
- If is terminal: , and go to the next episode.
- Choose -greedily w.r.t. .
- .
- , .
With a changing policy the guarantees weaken. The -greedy policy is a discontinuous function of : an arbitrarily small change of weights can flip the greedy action, which changes the on-policy distribution, which changes the fixed point. Gordon showed that linear Sarsa with -greedy improvement need not converge, but stays in a bounded region where it may chatter among policies;Geoffrey J. Gordon. Reinforcement Learning with Function Approximation Converges to a Region. In Advances in Neural Information Processing Systems 13 (NIPS 2000), pages 1040–1046. MIT Press, 2001 Perkins and Precup proved convergence when the improvement operator is a sufficiently smooth (Lipschitz) function of the action values.Theodore J. Perkins and Doina Precup. A Convergent Form of Approximate Policy Iteration. In Advances in Neural Information Processing Systems 15 (NIPS 2002), pages 1595–1602. MIT Press, 2003 The deeper reason, discussed in Section 10.4, is that with approximation the policy improvement theorem is lost.
10.1.1The Mountain Car#
An underpowered car sits in a valley and must reach the top of the hill on its right. Gravity is stronger than the engine, so the car must first back up the left slope and then use the momentum gained. Things have to get worse (farther from the goal) before they can get better, a structure on which many control methods fail without help. The state is position and velocity ; the actions are (full reverse, zero, full forward throttle); and the simplified physics is
where clips to the intervals, the velocity is reset to zero at the left wall, and reaching ends the episode. The reward is per step, so is the number of steps to go. Episodes start at a random with zero velocity.
Sutton and Barto tile-code the two continuous variables with eight grid tilings, asymmetrically offset, separately for each action, and run semi-gradient Sarsa with . The interesting part is exploration. All true values are negative, so initial weights are optimistic: every state–action pair the car has tried soon looks worse than those it has not, and even with the car is driven to new parts of state space, spiraling outwards in the plane until it swings high enough to escape. Optimistic initialization, a tabular trick of Chapter 2, survives generalization here because tile coding generalizes only locally. With step sizes around to (that is, to divided by the number of tilings, as (9.11) suggests), episodes shrink from about a thousand steps to a couple of hundred or fewer within a few hundred episodes.
10.2n-step Semi-gradient Sarsa#
Replacing the one-step target by the -step return of (7.1), now bootstrapping from ,
(10.3)for , with if , gives the update .
Algorithm 10.2 (Episodic Semi-gradient n-step Sarsa). Input: differentiable ; a policy if evaluating. Parameters: , , integer . Initialize: arbitrarily; stored may be indexed mod .
- Loop for each episode: store and ( or -greedy w.r.t. ); .
- For :
- If : take , store . If is terminal, ; else store chosen as in step 1.
- . If :
- ; if , .
- .
- Stop when .
On the mountain car the familiar pattern of Chapter 7 returns: learns faster and reaches shorter episodes than , and over the first fifty episodes an intermediate (four in Sutton and Barto’s sweep over and ) does best. Large also brings larger variance across runs, because long returns sum many random rewards. A Monte Carlo version () is possible in principle but nearly useless here: the first episodes are long, and nothing is learned until one of them ends.
10.3Average Reward: A New Problem Setting for Continuing Tasks#
Alongside the episodic and the discounted formulations of Chapter 3 there is a third classical one for continuing tasks, standard in dynamic programming: the agent cares about delayed rewards as much as immediate ones, and judges a policy by its average reward
(10.4)Here is the steady-state distribution, assumed to exist for every and not to depend on . This assumption on the MDP is called ergodicity: where the process starts, and any early decision, has only a transient effect. For a finite MDP it holds when every policy induces an irreducible, aperiodic chain, and we assume this throughout. The steady-state distribution is the one that reproduces itself under the policy,
(10.5)Policies are ordered by , and those attaining the maximum are optimal.Finer distinctions are possible among the policies with maximal average reward: one may also compare the transient rewards collected on the way to the steady state, which is what the differential values below measure. The sharpest criterion is Blackwell’s; see Section 10.6.2. Returns measure rewards relative to the average, through the differential return
(10.6)and the differential value functions , , with the same notation as before. The series converges: by ergodicity tends to zero geometrically. A one-step analysis, exactly as in Chapter 3 but with every removed and every reward replaced by its excess over the average, gives the differential Bellman equations
(10.7)They differ from the discounted ones in a way that matters: they do not determine by themselves.
Proposition 10.3 (Differential Bellman Equations Determine Values up to a Constant). Let be irreducible with stationary distribution , and . The system in the unknowns has solutions, every solution has , and the solutions in are exactly , . The differential value function is the unique solution with .
Proof. Multiply the equation by and use : , so . The difference of two solutions satisfies ; at a state where is largest, forces for every successor, and by irreducibility the maximum spreads to all states, so . The differential value function solves the system: splitting off the first reward in (10.6) gives the first line of (10.7). It is centered, because for every , so each term of vanishes. □
Only differences of differential values matter for choosing actions, so the additive constant is harmless; but it means that a learning algorithm may converge to plus an offset that depends on its initialization, and for linear approximation that the matrix is singular whenever the constant function is representable.
10.3.1Discounted Values Near γ = 1#
How do the discounted values of Chapter 3 relate to these new objects? They blow up as , and the way they blow up contains the whole average-reward theory.
Theorem 10.4 (Laurent Expansion of Discounted Values). Let be irreducible and aperiodic with stationary distribution , let , and define the deviation matrix . Then , and as
(10.8)Proof. Since , induction gives for . For an irreducible aperiodic chain , so the spectral radius of is less than one. Expanding the Neumann series,
where the term was rewritten as . The last two terms are analytic in on a neighborhood of , where they equal ; so they are . Multiply by and use . Finally , which is term by term. □
The leading term is the average reward, the same for all states; the constant term is the differential value; only higher-order terms distinguish discount rates. Equation (10.8) also gives the alternative definition , which remains meaningful for periodic chains where the series (10.6) oscillates (Exercise 10.11).
10.3.2Differential Semi-gradient Sarsa#
To learn, we need an estimate of and the differential TD errors
(10.9)for state and action values. With these in place of (6.2), the algorithms and much of the theory carry over. In particular, at the true average reward and the true differential values the expected differential TD error is zero in every state, for every offset in Proposition 10.3. The update of the weights is . The average-reward estimate is moved by the TD error too, , rather than by ; both converge, but has far lower variance once the values are roughly right, because it has the predictable part of the reward fluctuation removed (Exercise 10.10).
Algorithm 10.5 (Differential Semi-gradient Sarsa). Input: differentiable . Parameters: , . Initialize: and arbitrarily (e.g. and ); state and action .
- Loop for each step:
- Take , observe ; choose -greedily w.r.t. .
- .
- .
- .
- , .
This is the on-policy analogue of Schwartz’s R-learning.Anton Schwartz. A Reinforcement Learning Method for Maximizing Undiscounted Rewards. In Proceedings of the Tenth International Conference on Machine Learning (ICML 1993), pages 298–305. Morgan Kaufmann, 1993 Sutton and Barto’s test case is an access-control queuing task: customers of four priorities, paying or , arrive at a queue in front of ten servers; at each step the customer at the head is accepted (if a server is free) or rejected, and each busy server frees up with probability . Tabular differential Sarsa (, , two million steps) learns to accept the highest priority whenever possible and the lower priorities only when enough servers are free, with near . The problem is too large to be worth reproducing exactly here; the mechanism is visible on a two-state chain.
10.3.3In Wolfram Language#
Take two states and two actions, stay and go (to the other state). The policy goes with probability from state 1 and from state 2, and every step spent in state pays , whatever the action. First as the triple sum of (10.4):
is the normalized left null vector of ; the sum runs over states, actions and next states, with deterministic transitions.const P2 = await wl`{{1 - a, a}, {b, 1 - b}}`
const piGo = await wl`{a, b}`
const mu2 = await wl`With[{n = First[NullSpace[Transpose[${P2}] - IdentityMatrix[2]]]}, Simplify[n/Total[n]]]`
const rho = await show`Simplify[Sum[${mu2}[[s]] Sum[If[act == 2, ${piGo}[[s]], 1 - ${piGo}[[s]]] Sum[Boole[s2 == If[act == 2, 3 - s, s]] Subscript[r, s], {s2, 2}], {act, 2}], {s, 2}]]`Next the differential Bellman equations, solved for and with left free: is forced to be , and the values are fixed only up to the free constant, as Proposition 10.3 says.
Two equations, three unknowns : the solution leaves free.await show`Solve[Thread[{Subscript[v, 1], Subscript[v, 2]} == {Subscript[r, 1], Subscript[r, 2]} - \[Rho] + ${P2} . {Subscript[v, 1], Subscript[v, 2]}], {\[Rho], Subscript[v, 2]}]`The deviation matrix gives the centered solution, and we check that it satisfies the equations with any offset and that :
with .const Pstar = await wl`{${mu2}, ${mu2}}`
const H = await show`Simplify[Inverse[IdentityMatrix[2] - ${P2} + ${Pstar}] - ${Pstar}]`const rvec = await wl`{Subscript[r, 1], Subscript[r, 2]}`
const vdiff = await wl`Simplify[${H} . ${rvec}]`
await show`Simplify[{${vdiff}, ${rvec} - ${rho} + ${P2} . (${vdiff} + c) - (${vdiff} + c), ${mu2} . ${vdiff}}]`Now the Laurent expansion (10.8). The kernel expands the discounted value of state 1 around ; the pole is and the constant term is from the previous output.
Series of at , up to the constant term; the kernel writes powers of .const vgam = await wl`Simplify[Inverse[IdentityMatrix[2] - \[Gamma] ${P2}] . ${rvec}]`
await show`Series[${vgam}[[1]], {\[Gamma], 1, 0}]`await show`Simplify[Normal[Series[${vgam}, {\[Gamma], 1, 0}]] - (${rho}/(1 - \[Gamma]) + ${vdiff})]`10.4Deprecating the Discounted Setting#
Discounting served us well with tables, where each state’s return can be identified and averaged separately. Now imagine a continuing task whose states are seen only through features that barely tell them apart; in the extreme, all feature vectors are equal. All we have is a stream of rewards. To judge a policy we can average the rewards over a long time, which is the average-reward criterion. Or we can compute the discounted return from each time step and average those. In a continuing problem no time step is special, so averaging over time is the only option, and it gives nothing new: every reward appears in the return from time with weight , in the return from with weight , from with weight , for a total weight of . Hence the average discounted return is .
Proposition 10.6 (The Futility of Discounting in Continuing Problems). For every policy with stationary distribution and every ,
(10.10)Hence orders policies exactly as does, for every , including .
Proof. By the discounted Bellman equation and then stationarity (10.5),
Solve for . In matrix form: , so , the column-sum identity of Theorem 9.4 once more. □
The proposition concerns true discounted values. The same identity holds for the approximate values that semi-gradient TD actually finds, as soon as the features can represent constants.
Corollary 10.7 (Average of the TD Fixed Point). Let be linear with features whose span contains the constant function, and let be the TD fixed point (9.5) for policy under its on-policy distribution. Then .
Proof. The fixed point satisfies , so for every ; choose with . Since and , this reads . □
In the extreme case of a single constant feature, : the approximate discounted value is the average reward, rescaled. On the two-state chain:
First for the true discounted values; then the TD fixed point with the single feature , i.e. and .await show`Simplify[{${mu2} . ${vgam}, Inverse[Transpose[{{1}, {1}}] . DiagonalMatrix[${mu2}] . (IdentityMatrix[2] - \[Gamma] ${P2}) . {{1}, {1}}] . (Transpose[{{1}, {1}}] . DiagonalMatrix[${mu2}] . ${rvec})}]`If we optimized the discounted value averaged over the on-policy distribution, we would therefore be optimizing the average reward, and would play no role at all. Discounting may still be useful inside solution methods, to keep bootstrapped values bounded or to reduce variance; then changes from a parameter of the problem into a parameter of the algorithm. But a discounted control method with approximation is then no longer guaranteed to optimize anything in particular.Beyond Sutton and Barto (2018). Naik, Shariff, Yasui, Yao and Sutton (NeurIPS 2019 workshop on optimization foundations of RL) sharpened this into the claim that discounted reinforcement learning with function approximation in continuing tasks is not an optimization problem: with approximation there need not be any policy that maximizes the discounted values of all states at once, and the usual fixes (a start-state or on-policy-weighted objective) either do not apply to continuing tasks or collapse to the average reward, as above. They recommend the average-reward objective.Abhishek Naik, Roshan Shariff, Niko Yasui, Hengshuai Yao, and Richard S. Sutton. Discounted Reinforcement Learning Is Not an Optimization Problem, 2019. Optimization Foundations for Reinforcement Learning Workshop at NeurIPS 2019
The root of the difficulty is that with approximation we have lost the policy improvement theorem (Theorem 4.6). In the tabular case, making a policy greedy in one state could only help. With shared weights, improving the value of one state changes others, and there is no guarantee that -greedification improves the policy in any useful sense; it may chatter instead. This gap is shared by the episodic and the average-reward settings, and for methods that learn action values it is still largely open. The policy-gradient theorem of Chapter 13 supplies a substitute for parameterized policies.
10.5Differential Semi-gradient n-step Sarsa#
The differential version of the -step return (10.3) subtracts the estimated average from each reward and does not discount:
(10.11)and the -step differential TD error is , used both for and for .
Algorithm 10.8 (Differential Semi-gradient n-step Sarsa). Input: differentiable ; a policy if evaluating. Parameters: , integer . Initialize: , arbitrarily; store , . Stored may be indexed mod .
- For :
- Take ; store and ; store or -greedy w.r.t. .
- . If :
- .
- ; .
The step size must be small for to be a good long-run average, which makes slow to forget its initial value; Exercise 10.12 removes that bias.
10.6Beyond the Book: Average-Reward Learning Revisited#
10.6.1Differential Q-learning#
The tabular theory of average-reward off-policy control long rested on RVI Q-learning (Abounadi, Bertsekas and Borkar, 2001),Jinane Abounadi, Dimitri P. Bertsekas, and Vivek S. Borkar. Learning Algorithms for Markov Decision Processes with Average Cost. SIAM Journal on Control and Optimization, 40(3):681–698, 2001 which subtracts a reference function , for instance the value of a fixed reference state–action pair, in place of an average-reward estimate. Its performance depends heavily on that choice, and the best reference is a frequently visited pair, which is hard to know in advance. Wan, Naik and Sutton removed the reference function.Yi Wan, Abhishek Naik, and Richard S. Sutton. Learning and Planning in Average-Reward Markov Decision Processes. In Proceedings of the 38th International Conference on Machine Learning (ICML 2021), volume 139 of Proceedings of Machine Learning Research, 2021Beyond Sutton and Barto (2018). Wan, Naik and Sutton, Learning and planning in average-reward Markov decision processes, ICML 2021 (arXiv June 2020). Besides Differential Q-learning they give an off-policy prediction algorithm, Differential TD-learning, planning versions of both, and centered variants that converge to the differential values themselves rather than to values plus an offset. Their Differential Q-learning updates
with : the average-reward estimate moves by the TD error, as in Algorithm 10.5. The proof of convergence is a neat reduction. Every increment of is times an increment of , so with a constant fixed by the initial values; Differential Q-learning is therefore RVI Q-learning with the reference function on an MDP whose rewards are shifted by . Wan et al. extend the RVI theory to cover this and prove that in communicating MDPs, under the usual step-size conditions, converges almost surely to the optimal average reward and to a solution of the differential Bellman optimality equation (10.7).
10.6.2Blackwell Optimality#
Ordering policies by ignores everything transient. The Laurent expansion (10.8) suggests a lexicographic refinement: among policies with maximal average reward (the gain), prefer larger differential values (the bias), then larger higher-order coefficients. Blackwell showed that a finite MDP has a stationary deterministic policy that is optimal for the discounted criterion simultaneously for all in some interval .David Blackwell. Discrete Dynamic Programming. The Annals of Mathematical Statistics, 33(2):719–726, Institute of Mathematical Statistics, 1962. doi: 10.1214/aoms/1177704593Beyond Sutton and Barto (2018). Blackwell optimality is classical (Blackwell, Annals of Mathematical Statistics, 1962) and treated at length by Puterman (1994), but Sutton and Barto only allude to “subtle distinctions” among optimality criteria. It has recently been used to connect discounted and average-reward learning, for instance through the Blackwell discount factor above which discounted optimality implies Blackwell optimality (Grand-Clément and Petrik, 2023).Martin L. Puterman. Markov Decision Processes: Discrete Stochastic Dynamic Programming. John Wiley & Sons, New York, 1994. ISBN 978-0-471-61977-2. doi: 10.1002/9780470316887; and Julien Grand-Clément and Marek Petrik. Reducing Blackwell and Average Optimality to Discounted MDPs via the Blackwell Discount Factor. In Advances in Neural Information Processing Systems 36 (NeurIPS 2023), 2023 Such a Blackwell-optimal policy is gain-optimal and, among gain-optimal policies, bias-optimal: dividing the difference of two Laurent expansions by the leading nonzero power of shows why. This is the precise sense in which “discounting with close enough to one” solves the average-reward problem in the tabular case, and the reason it cannot be relied on with approximation: depends on the whole MDP and can be arbitrarily close to one, and Proposition 10.6 shows that the on-policy average cannot see anything beyond the gain.
10.6.3Deep Q-Networks#
The most visible use of semi-gradient control with a nonlinear approximator is the Deep Q-Network of Mnih et al., which learned to play 49 Atari games from pixels.Volodymyr Mnih, Koray Kavukcuoglu, David Silver, Andrei A. Rusu, Joel Veness, Marc G. Bellemare, Alex Graves, Martin Riedmiller, Andreas K. Fidjeland, Georg Ostrovski, Stig Petersen, Charles Beattie, Amir Sadik, Ioannis Antonoglou, Helen King, Dharshan Kumaran, Daan Wierstra, Shane Legg, and Demis Hassabis. Human-Level Control through Deep Reinforcement Learning. Nature, 518(7540):529–533, 2015. doi: 10.1038/nature14236 It is semi-gradient Q-learning, hence off-policy, and its replay memory and target network are described in Section 15.5.
Q-learning is the natural next step from the Sarsa methods of this chapter, and the one that breaks them. Chapter 11 shows that learning off-policy, with bootstrapping and function approximation together, can make semi-gradient methods diverge, and looks for objectives and algorithms that are stable again.
10.7Exercises#
Exercise 10.9. Three states form a ring traversed deterministically, , with reward on arrival in and otherwise. Find and the differential values. The chain is periodic; is the differential value still well defined?
Solution
Each state is occupied a third of the time and one transition in three pays , so . The differential Bellman equations are , , ; with the centering they give . The series (10.6) oscillates for a periodic chain, but the definition through (10.8), , exists and agrees:
The centered solution of the differential Bellman equations, and the limit of as .const ring = await wl`{{0, 1, 0}, {0, 0, 1}, {1, 0, 0}}`
await show`With[{v = {Subscript[v, A], Subscript[v, B], Subscript[v, C]}, r = {0, 0, 1}},
{Solve[Append[Thread[v == r - 1/3 + ${ring} . v], Total[v] == 0], v],
Limit[Simplify[Inverse[IdentityMatrix[3] - \[Gamma] ${ring}] . r - 1/3/(1 - \[Gamma])], \[Gamma] -> 1, Direction -> "FromBelow"]}]`Exercise 10.10. In the ring of Exercise 10.9, suppose already equals and the values are the true differential values. Write the sequences of errors and starting from . Which would give the more stable estimate of the average reward if were allowed to change?
Solution
Six steps from : first , then the differential TD error with the true values.await show`With[{v = {-1/3, 0, 1/3}, r = {0, 0, 1}, states = {1, 2, 3, 1, 2, 3, 1}},
{Table[r[[states[[t]]]] - 1/3, {t, 6}], Table[r[[states[[t]]]] - 1/3 + v[[states[[t + 1]]]] - v[[states[[t]]]], {t, 6}]}]`The raw error cycles through : an update keeps oscillating around with amplitude proportional to . The TD error is identically zero, so stays put. In general removes from the part that the current state predicts, , which is exactly the regular, non-random part of the fluctuation.
Exercise 10.11. An MDP produces the reward sequence from state and from state , under every policy. Show that even though the limit does not exist, and compute the values of and under the definition .
Solution
The Cesàro averages tend to , which is the first form of (10.4). From the centered rewards are , i.e. , and from their negatives:
The inner sums are and its negative; their limits as .await show`Limit[{Sum[\[Gamma]^t (-1)^t/2, {t, 0, Infinity}], Sum[-\[Gamma]^t (-1)^t/2, {t, 0, Infinity}]}, \[Gamma] -> 1, Direction -> "FromBelow"]`So and . They differ by , the advantage of collecting the first reward one step earlier, and average to zero, as differential values should.
Exercise 10.12. The estimate in Algorithm 10.8 needs a small to average over the long run, but is then biased by its initial value for a long time; a sample average would adapt quickly at first but too slowly later, and cannot track a changing policy. Adapt the unbiased constant-step-size trick of Chapter 2 (step size with , ) to the update of .
Solution
Keep a scalar trace , initialized to . Each time is updated, first set , then . At the first update , the step is and the initial is forgotten completely; afterwards geometrically and the step tends to , so the estimate becomes an exponential recency-weighted average with no trace of its initialization, and it still tracks a slowly changing policy.
Exercise 10.13. Give pseudocode for a differential version of semi-gradient Q-learning, and explain why it is off-policy.
Solution
Replace the Sarsa target in Algorithm 10.5 by the greedy one: after taking (chosen -greedily) and observing , set , then , , and choose the next action -greedily in . The target evaluates the greedy policy while the data come from the -greedy one, so the method is off-policy: in the tabular case it is Differential Q-learning of Section 10.6.1 with , and with function approximation it inherits the difficulties of Chapter 11.