Chapter 3
Finite Markov Decision Processes
A bandit has one situation and many actions; the problems Sutton and Barto study have many situations, and the action taken in one of them decides which ones come next. The Markov decision process (MDP) is the mathematical form of that problem: rewards are still evaluative, as in Chapter 2, but they are now delayed, because an action changes the state and therefore every reward that follows.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 This chapter sets up the objects that every later chapter manipulates — dynamics, returns, policies, value functions — and derives the two families of equations that tie them together: the Bellman equations for a fixed policy, which are linear, and the Bellman optimality equations, which are not. Everything in the rest of the book is a way of solving one of them, exactly or approximately, with or without a model.
3.1The Agent–Environment Interface#
An agent interacts with an environment at discrete times . At time it observes a state , chooses an action , and one step later receives a reward together with the next state . The interaction produces a trajectory
(3.1)Reward and next state carry the same index because they are produced jointly by the environment’s response to .Both conventions, and for the reward due to , are common in the literature. Sutton and Barto’s choice makes the joint distribution of the primitive object, which is what sample-based methods observe.
Definition 3.1 (Finite Markov Decision Process). A finite MDP consists of finite sets of states (with in episodic tasks), actions for each , and rewards , together with a dynamics function ,
(3.2)such that the conditional law of given the whole past depends on it only through , and is given by .
The last clause is the Markov property. It is best read as a requirement on the state, not on the world: the state must summarize everything about the past interaction that matters for the future. A robot whose state is its position but not its velocity lives in a non-Markov process; adding the velocity restores the property. Throughout Part I we assume that the state given to the agent is Markov; Chapter 16 returns to what can be done when it is not.
The four-argument determines every other quantity one might want, and three of them recur:
(3.3)These are the state-transition probabilities, the expected reward of a state–action pair, and the expected reward of a transition. Classical MDP texts start from and ; the four-argument form is preferred in reinforcement learning because learning methods see sampled rewards, not their expectations.The theory of MDPs is older than reinforcement learning by three decades: Bellman’s Dynamic Programming (1957) and Howard’s policy iteration (1960) are the sources, and Puterman (1994) is the standard modern reference for the finite case.Richard Bellman. Dynamic Programming. Princeton University Press, Princeton, NJ, 1957. A Rand Corporation Research Study; xxv+342 pp.; Ronald A. Howard. Dynamic Programming and Markov Processes. MIT Press, Cambridge, MA, 1960; and 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
Where to draw the boundary between agent and environment is a modeling choice with one firm rule: anything the agent cannot change arbitrarily belongs to the environment. A robot’s motors, its sensors, and even the computation of its reward are outside the agent. The boundary marks the limit of the agent’s control, not of its knowledge — an agent may know its environment completely, as we know the rules of chess, and still face a hard problem.
Example 3.2 (The Recycling Robot). A can-collecting robot has two battery levels, , with and . Searching yields cans, waiting ; recharging yields nothing. A search from keeps the battery high with probability ; a search from keeps it low with probability , and otherwise the battery dies, the robot is rescued (reward ), and it restarts with a full battery. Treating the number of cans as deterministic for simplicity, the dynamics have these nonzero entries:
| with probability | ||
|---|---|---|
| : ; : | ||
| : | ||
| : ; : | ||
| : | ||
| : |
3.1.1In Wolfram Language#
We encode the robot once, as a list of outcomes for each of the five state–action pairs (states numbered , ), and let the kernel derive (3.3) from it.
For each pair in the order of the table: total probability, the transition row , and the expected reward . Every row sums to , as (3.2) demands.const robotDyn = await wl`{
{{1, Subscript[r, search], \[Alpha]}, {2, Subscript[r, search], 1 - \[Alpha]}},
{{1, Subscript[r, wait], 1}},
{{1, -3, 1 - \[Beta]}, {2, Subscript[r, search], \[Beta]}},
{{2, Subscript[r, wait], 1}},
{{1, 0, 1}}}`
const robotDerived = await show`Map[Function[o, {Total[o[[All, 3]]],
Total[Select[o, Function[x, x[[1]] == 1]][[All, 3]]],
Total[Select[o, Function[x, x[[1]] == 2]][[All, 3]]],
Simplify[o[[All, 2]] . o[[All, 3]]]}], ${robotDyn}]`3.2Goals, Rewards, and Returns#
The goal of the agent is encoded entirely in the scalar reward. Sutton and Barto, crediting Michael Littman, state this as the reward hypothesis: “all of what we mean by goals and purposes can be well thought of as the maximization of the expected value of the cumulative sum of a received scalar signal (called reward).”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 A corollary is a discipline in designing rewards: they should say what we want achieved, not how. A chess program rewarded for capturing pieces will learn to capture pieces, even at the price of the game; prior knowledge about how to win belongs in the initial policy or value function, not in the reward. Whether the hypothesis is actually true turns out to be a mathematical question, answered only recently (Section 3.6).
What exactly is maximized is the expected return , a function of the rewards after . In episodic tasks the interaction breaks into episodes that end at a random time in a terminal state, and the return can be the plain sum . In continuing tasks there is no end, and a plain sum may diverge; the remedy is discounting with a rate :
(3.4)With and rewards bounded by , . A reward steps ahead is worth times its face value; makes the agent myopic, and makes it far-sighted. The single most useful fact about returns is that they are recursive:
(3.5)Every bootstrapping method in the book — dynamic programming, TD learning, Q-learning — is an expectation, or a sample, of this identity.
3.2.1One Notation for Both Kinds of Task#
The two cases merge if termination is treated as entry into an absorbing state that loops on itself with reward . The sequence then becomes , and its sum, discounted or not, is unchanged. So we may always write
(3.6)allowing or , but not both; (3.5) then holds for all with the convention . With the absorbing state the terminal value is automatically , which is why every algorithm in the book initializes and never updates it.The MDP literature speaks of finite-horizon, indefinite-horizon (terminating, but at no fixed time), and infinite-horizon problems. Episodic and continuing tasks are close to the last two; the book prefers its terms because they describe the interaction rather than the objective. Chapter 10 adds a third objective, the average reward, for continuing tasks without discounting.
3.3Policies and Value Functions#
A policy maps each state to a distribution over actions: is the probability that when . Together with it determines the distribution of the whole trajectory, and we write for expectations under it. The state-value function and action-value function of are
(3.7)for , ; the terminal state has value . By the Markov property and the stationarity of and , neither depends on . Conditioning on the first action, and then on the first transition, gives the two relations that connect them:
(3.8)The first is an average over the agent’s choice, the second an average over the environment’s response. Substituting each into the other gives the central equations of the chapter.
Proposition 3.3 (Bellman Equations for a Policy). For every policy , every , and every ,
(3.9)(3.10)Proof. By (3.5) and linearity, . Condition both terms on , which has probability given . The first term becomes . For the second we need
This is where the Markov property enters: is a function of , whose joint law given the past is generated by and from alone, so the extra conditioning on is irrelevant; and since and do not depend on time, the result is the same function evaluated at . Adding the two terms gives (3.9). The same argument started from , with fixed rather than averaged, gives , and substituting the first relation of (3.8) for gives (3.10). □
Read (3.9) as an expectation over the triple with probability : the value of a state is the expected immediate reward plus the discounted value of where you land. A backup diagram draws this as a two-level tree: an open circle for the state at the root, filled dots for the actions it may take (branching by ), and open circles for the successor states (branching by , each edge carrying a reward). Value information flows up the tree, from leaves to root; that transfer is a backup, and every algorithm of Part I is characterized by the shape of the tree it backs up and by whether it averages over all branches or samples one (Figure 3.1).
3.3.1The Bellman Equation as a Linear System#
For a fixed , write for the expected one-step reward and for the state-to-state transition matrix of the Markov chain that induces (restricted to nonterminal states in episodic tasks). Then (3.9) is the linear system
(3.11)Proposition 3.4 (Unique Solution of the Bellman Equation). If , the matrix is invertible and
(3.12)The same holds for in an episodic task if is proper, that is, reaches the terminal state with probability one from every state.
Proof. Rows of are nonnegative and sum to at most , so . If , then , forcing ; and makes the Neumann series converge to the inverse. In the proper case, sums to the probability of not having terminated after steps; properness of a finite chain makes this decay geometrically, so again converges and inverts . □
The series is just the definition of read again: , so (3.12) is . Solving linear equations costs ; Chapter 4 replaces the direct solution by iteration, and the rest of the book replaces the known and by samples.
It is convenient to name the right-hand sides of the Bellman equations as operators on value functions :
(3.13)In vector form , and is the unique fixed point of . Two properties are immediate: both operators are monotone ( pointwise implies , since ), and iterating from any gives
(3.14)the expected -step return with as a terminal payoff. The second operator, , is the subject of Section 3.4.
3.3.2In Wolfram Language#
We first evaluate a policy of the recycling robot in closed form. Actions are numbered as in the table, so the policy “search when high, recharge when low” is .
A generic evaluator: assemble and for a deterministic policy and return , here for .const robotP = await wl`{{{\[Alpha], 1 - \[Alpha]}, {1, 0}}, {{1 - \[Beta], \[Beta]}, {0, 1}, {1, 0}}}`
const robotR = await wl`{{Subscript[r, search], Subscript[r, wait]}, {\[Beta] Subscript[r, search] - 3 (1 - \[Beta]), Subscript[r, wait], 0}}`
const robotEval = await wl`Function[{pol}, Simplify[Inverse[IdentityMatrix[2] - \[Gamma] Table[${robotP}[[s, pol[[s]]]], {s, 2}]] . Table[${robotR}[[s, pol[[s]]]], {s, 2}]]]`
const vSearchRecharge = await show`${robotEval}[{1, 3}]`Recharging when low gives exactly — one step of delay, no reward — and is the per-step reward inflated by and deflated by the factor that accounts for the steps spent recharging. From we get by the second relation of (3.8), and the differences for the actions does not take tell us whether a single deviation would pay.
for , , , with written as . If all three are , no one-step deviation helps; we shall see that this makes optimal.const robotQ = await wl`Function[{v}, Table[${robotR}[[s, a]] + \[Gamma] ${robotP}[[s, a]] . v, {s, 2}, {a, Length[${robotR}[[s]]]}]]`
const robotAdv = await show`With[{q = ${robotQ}[${vSearchRecharge}], v = ${vSearchRecharge}}, FullSimplify[{q[[1, 2]] - v[[1]], q[[2, 1]] - v[[2]], q[[2, 2]] - v[[2]]} /. Subscript[r, search] -> Subscript[r, eff] (1 + \[Gamma] (1 - \[Alpha]))]]`Each condition is readable: waiting when high is worse if is below the effective per-step reward of the search–recharge cycle, waiting when low is worse if , and searching when low is worse if the expected rescue penalty exceeds . The general two-state chain shows the structure of (3.12) with nothing specific to robots.
for a two-state chain that stays in state with probability and in state with probability .const chainP = await wl`{{p, 1 - p}, {1 - q, q}}`
const chainR = await wl`{Subscript[r, 1], Subscript[r, 2]}`
const chainV = await show`Simplify[Inverse[IdentityMatrix[2] - \[Gamma] ${chainP}] . ${chainR}]`The common factor says that the values blow up as , at a rate set by the long-run average reward. Multiplying by isolates that rate.
: both components tend to the same number, the reward averaged over the chain’s stationary distribution .const chainAvg = await show`Assuming[0 < p < 1 && 0 < q < 1, FullSimplify[Limit[(1 - \[Gamma]) ${chainV}, \[Gamma] -> 1]]]`This is the first appearance of the average reward of Section 10.3: as , , a constant that is the same in every state plus a state-dependent correction.This expansion is the starting point of Blackwell’s (1962) analysis of the discounted problem for near . He proved that a finite MDP has a stationary deterministic policy that is optimal simultaneously for all discount factors in some interval , now called a Blackwell-optimal policy; such a policy is in particular optimal for the average-reward criterion.David Blackwell. Discrete Dynamic Programming. The Annals of Mathematical Statistics, 33(2):719–726, Institute of Mathematical Statistics, 1962. doi: 10.1214/aoms/1177704593
Finally, the gridworld of the book’s Example 3.5: a grid, four deterministic moves, reward for bumping into the edge, and two special cells (row 1, column 2) and (row 1, column 4) that teleport the agent to and with rewards and . For the equiprobable random policy and , (3.11) is a system with rational coefficients, which the kernel solves exactly.
Build and for the uniform random policy, solve exactly in rationals, and print to one decimal: these are the book’s values for Figure 3.2, now verified.const gridStep = await wl`Function[{s, a}, Which[
s == {1, 2}, {{5, 2}, 10},
s == {1, 4}, {{3, 4}, 5},
1 <= (s + a)[[1]] <= 5 && 1 <= (s + a)[[2]] <= 5, {s + a, 0},
True, {s, -1}]]`
const gridMoves = await wl`{{-1, 0}, {1, 0}, {0, 1}, {0, -1}}`
const gridStates = await wl`Tuples[{Range[5], Range[5]}]`
const gridPr = await wl`Table[Total[Table[UnitVector[25, First[FirstPosition[${gridStates}, ${gridStep}[s, a][[1]]]]]/4, {a, ${gridMoves}}]], {s, ${gridStates}}]`
const gridRr = await wl`Table[Total[Table[${gridStep}[s, a][[2]]/4, {a, ${gridMoves}}]], {s, ${gridStates}}]`
const gridV = await wl`LinearSolve[IdentityMatrix[25] - 9/10 ${gridPr}, ${gridRr}]`
const gridShow = await show`NumberForm[N[Partition[${gridV}, 5]], {3, 1}]`The exact value of is the ratio of a 27-digit integer to a 26-digit one, about : less than the immediate , because sits on the bottom edge where the random walk keeps bumping into the wall.
3.4Optimal Policies and Optimal Value Functions#
Value functions order policies: if for every state. This is only a partial order — one policy may be better in some states and worse in others — so it is not obvious that a single policy can be best everywhere. Define the optimal value functions
(3.15)pointwise, and call an optimal policy if in every state. Acting optimally after a first action gives
(3.16)Combining the two in both orders gives the Bellman optimality equations:
(3.17)(3.18)The first says . Unlike (3.9), it contains no policy at all, and because of the it is a nonlinear system of equations. The heuristic derivation just given assumes that an optimal policy exists, which is what we must prove. The theorem below does the half that needs only this chapter’s tools; the other half, existence of a solution, is constructive and is the business of Chapter 4.
Theorem 3.5 (Verification Theorem for the Bellman Optimality Equation). Let , and let be any function satisfying , that is, (3.17) with in place of . Then:
- for every policy ;
- every policy that is greedy with respect to — that puts positive probability only on actions attaining the maximum in — satisfies .
Hence , the optimality equation has at most one solution, and any greedy policy, in particular a deterministic one, is optimal in every state simultaneously.
Proof. (1) For any , the average never exceeds the maximum, so . Applying the monotone operator repeatedly, , and by (3.14) the right side tends to . (2) If is greedy with respect to , the average equals the maximum: . Then is a fixed point of , whose only fixed point is (Proposition 3.4). Together, for every , so and is optimal. If and both solve the equation, both equal . □
Remark 3.6. For the argument needs every policy to be proper. Without that assumption greedy policies can fail: if some action leaves the state and reward unchanged (a “do nothing” move with reward ), it attains the maximum in any undiscounted optimality equation, yet the policy that always takes it never terminates and collects nothing. The gambler’s problem of Chapter 4 has exactly this trap.
The theorem also explains why we restrict attention to stationary policies : part (1) holds just as well for policies that depend on the entire history, by the same induction on the horizon, so nothing is gained by remembering the past when the state is Markov.For finite discounted MDPs the optimal value over all history-dependent randomized policies equals and is attained by a stationary deterministic policy; see Puterman (1994), Chapter 6. The practical message is the one to remember: once is known, acting optimally is a one-step lookahead. The greedy action looks only at immediate consequences, yet is optimal in the long run, because has already folded all of the future into a number available locally. With even the lookahead disappears: needs no model of the environment at all. This is why model-free control methods such as Q-learning (Chapter 6) estimate action values rather than state values: caches the result of every one-step search.
3.4.1In Wolfram Language#
The recycling robot has deterministic policies, so we can check the theorem by brute force. We fix , , , , and evaluate every policy exactly.
Rows: the policy as (action in , action in ) with , , , then and in exact arithmetic. One row, , dominates all others in both states.const robotNums = await wl`{\[Alpha] -> 4/5, \[Beta] -> 3/5, Subscript[r, search] -> 2, Subscript[r, wait] -> 1, \[Gamma] -> 9/10}`
const robotTable = await show`Table[Join[pol, ${robotEval}[pol] /. ${robotNums}], {pol, Tuples[{{1, 2}, {1, 2, 3}}]}]`That a single policy wins in every state at once is the content of the theorem: here . Plugging it into the optimality equation confirms that it is a fixed point of and that the greedy policy is the winner of the table.
The residual at , and the greedy action in each state: and .const robotBOE = await show`With[{q = ${robotQ}[${vSearchRecharge}] /. ${robotNums}, v = ${vSearchRecharge} /. ${robotNums}}, {Map[Max, q] - v, Map[First[Ordering[#, -1]] &, q]}]`3.5Optimality and Approximation#
Solving (3.17) exactly requires three things that are rarely available together: an accurate model , a Markov state, and enough computation. Backgammon has a known model and a Markov state, but some states, so its optimality equations cannot even be written down. Two constraints shape everything that follows. Computation per time step is limited, so exact solutions must be replaced by iterative approximations that can be interrupted. Memory is limited, so the tabular representation with one entry per state, used throughout Part I, must eventually give way to parameterized functions in Part II.
Reinforcement learning has one structural advantage in this situation: because it learns from the agent’s own experience, it spends its effort where the agent actually goes. Tesauro’s backgammon player plays superbly although its evaluations of positions that never arise between strong players may be poor. An approximation that is accurate on the states visited under good play and crude elsewhere is often all that is needed; this focusing by the on-policy distribution reappears as the weighting of the prediction objective in Chapter 9.
3.6Beyond the Book: What Rewards Can Express#
The reward hypothesis of Section 3.2 was, in the book, a working assumption. Since 2021 it has become a theorem with precise hypotheses, and with known counterexamples when they fail.Beyond Sutton and Barto (2018). Abel et al. (NeurIPS 2021) characterized which tasks a Markov reward can express; Bowling, Martin, Abel and Dabney (ICML 2023) gave axioms that are necessary and sufficient for goals to be representable as expected cumulative reward. Neither result is in the book.
What a Markov reward cannot say. Abel and coauthors formalize a “task” in three ways: a set of acceptable policies, a partial order on policies, or a partial order on trajectories. For each, they show that some environment–task pairs admit no Markov reward function under which exactly the desired policies or orderings come out optimal.David Abel, Will Dabney, Anna Harutyunyan, Mark K. Ho, Michael L. Littman, Doina Precup, and Satinder Singh. On the Expressivity of Markov Reward. In M. Ranzato, A. Beygelzimer, Y. Dauphin, P. S. Liang, and J. Wortman Vaughan, editors, Advances in Neural Information Processing Systems, volume 34, pages 7799–7812. Curran Associates, Inc., 2021 Their simplest example is “always move in the same direction” in a grid. The intuition comes from Theorem 3.5: a Markov reward judges actions state by state, so the policies it makes optimal are closed under combining optimal actions from different states, whereas combining “always up” in some cells with “always left” in others yields an unacceptable policy. The positive side is constructive: for a finite environment, a reward that realizes a given task, or a certificate that none exists, can be found in polynomial time by linear programming (when rewards may take arbitrarily many values; with a fixed finite set of reward values the problem is NP-hard).
When the hypothesis is exactly right. Bowling and coauthors start from preferences over lotteries of finite histories.Michael Bowling, John D. Martin, David Abel, and Will Dabney. Settling the Reward Hypothesis. In Proceedings of the 40th International Conference on Machine Learning, volume 202 of Proceedings of Machine Learning Research, pages 3003–3020. PMLR, 2023. URL https://proceedings.mlr.press/v202/bowling23a.html If satisfies the four von Neumann–Morgenstern axioms (completeness, transitivity, independence, continuity), it has a utility . Their new fifth axiom, temporal -indifference, ties the utility of a history to that of its continuation, and the main theorem states that the five axioms hold if and only if there are a reward and a discount for each transition with
(3.19)which is the return recursion (3.5) with a transition-dependent discount; is unique up to a positive scale. So goals are expressible as expected cumulative reward precisely when the agent’s preferences are rational in the vNM sense and obey this temporal axiom; the episodic, discounted and total-reward settings of this chapter are special choices of . A fixed for all transitions is a further restriction, not a consequence.
At the other extreme, Silver, Singh, Precup and Sutton conjecture that reward maximization is not just sufficient to express goals but enough to produce intelligence: that perception, language, social skills and generalization can all be understood as serving the maximization of reward by an agent acting in a rich environment.David Silver, Satinder Singh, Doina Precup, and Richard S. Sutton. Reward is Enough. Artificial Intelligence, 299:103535, 2021. doi: 10.1016/j.artint.2021.103535 That is a research hypothesis, not a theorem; the two results above mark where its formal counterpart is known to hold.
With the problem and its Bellman equations in place, Chapter 4 solves them when the dynamics are known, turning each equation into an iterative update and proving that the iteration converges; the existence of a solution of the optimality equation, left open by Theorem 3.5, comes out of that analysis.
3.7Exercises#
Exercise 3.7. (a) In a continuing task with discount , show that adding a constant to every reward adds the same constant to every state value under every policy, and find . (b) In an episodic task such as running a maze, does adding to every reward leave the task unchanged? Give an example.
Solution
(a) The new return is , so every value increases by , independently of the state and the policy; relative values, hence the ordering of policies, are unchanged.
The constant added to every value by a constant reward shift .const shiftSum = await show`Sum[\[Gamma]^k c, {k, 0, Infinity}, Assumptions -> 0 < \[Gamma] < 1]`(b) In an episodic task the shift is (or for ), which depends on the remaining episode length. With reward per step in a maze the agent hurries to the exit; adding makes every step worth and the agent now prefers to wander forever. The task has changed, because termination interacts with the shift.
Exercise 3.8. A continuing MDP has a single decision state. Action gives reward and leads to a state that returns with reward ; action gives and leads to a state that returns with reward . For which is each of the two deterministic policies optimal?
Solution
From the decision state the reward sequences are and , so and . In the two other states there is no choice. Hence is optimal if and only if :
Solve for .const lrReduce = await show`Reduce[2 \[Gamma]/(1 - \[Gamma]^2) > 1/(1 - \[Gamma]^2) && 0 <= \[Gamma] < 1, \[Gamma]]`So is optimal for , both are optimal at , and is optimal for . The optimal policy depends on , which is part of the problem specification.
Exercise 3.9. In the gridworld of Section 3.3.2, an optimal policy from jumps to and walks straight back up to in four steps. Express symbolically and evaluate it at .
Solution
The reward sequence from is with period , so .
The exact value at and its decimal expansion; the book reports .const gridA = await show`With[{v = 10/(1 - (9/10)^5)}, {v, N[v, 6]}]`That no better policy exists from follows from the theorem: this value, together with the values of the other cells under the same policy, satisfies (3.17), which Chapter 4 checks by value iteration.
Exercise 3.10. Write the Bellman optimality equation (3.18) for the recycling robot as five equations in the five unknowns , and verify it for the numerical instance of Section 3.4.1.
Solution
Abbreviating and and writing ,
By (3.16), is the one-step lookahead of ; the check is that its row maxima reproduce and that it is a fixed point of the right-hand side.
from , and the residual of the optimality equation (all zeros).const robotQstar = await show`With[{q = ${robotQ}[${vSearchRecharge}] /. ${robotNums}}, {q, (${robotQ}[Map[Max, q]] /. ${robotNums}) - q}]`