Chapter 4
Dynamic Programming
Dynamic programming turns the Bellman equations of Chapter 3 into assignment statements. Given a perfect model , it computes by repeatedly replacing the left side of (3.9) with its right side, and computes the same way from (3.17).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; and Richard Bellman. Dynamic Programming. Princeton University Press, Princeton, NJ, 1957. A Rand Corporation Research Study; xxv+342 pp. The assumption of a perfect model and the cost of sweeping the whole state set limit its direct use, but almost every method in the rest of the book is an attempt to get the effect of dynamic programming (DP) with less computation and without the model. This chapter proves that the assignments work — they are contractions — proves the policy improvement theorem, and assembles policy iteration and value iteration from the two pieces. The pattern that emerges, generalized policy iteration, is the organizing idea of the whole book.
4.1Bellman Operators Are Contractions#
Value functions on a finite state set are vectors in , and we measure them with the max norm . Recall the operators of (3.13): , the right side of the Bellman equation, and , the right side of the optimality equation.
Lemma 4.1 (Contraction and Monotonicity). For every policy and all : (i) implies and ; (ii)
(4.1)Proof. (i) has nonnegative entries, and a maximum of monotone functions is monotone. (ii) , and each row of is a probability vector, so each component is an average of components of . For , fix and write and for the bracketed one-step lookaheads under and . Maxima over the same finite set satisfy : if, say, and attains , then . Finally is bounded by . □
with the max norm is complete, so the Banach fixed-point theorem (Theorem A.3) applies to both operators at once.
Theorem 4.2 (Fixed Points and Convergence of the Bellman Operators). Let and let be or . Then has a unique fixed point ( or , respectively), and for every the iterates satisfy
(4.2)Proof. Existence, uniqueness and the first bound are the Banach theorem applied to (4.1). For the second, ; solve for . □
The theorem closes the gap left in Theorem 3.5: the optimality equation has a solution, so is that solution, and any policy greedy with respect to it — in particular a deterministic one — is optimal. The first bound is an a priori rate; the second is an a posteriori stopping rule that uses only quantities the algorithm can see. For undiscounted episodic tasks the same conclusions hold when all policies are proper, with the max norm replaced by a weighted max norm in which the operators are again contractions.Dimitri P. Bertsekas and John N. Tsitsiklis. Neuro-Dynamic Programming. Athena Scientific, Belmont, MA, 1996. ISBN 1-886529-10-8
4.1.1In Wolfram Language#
On the two-state chain of Section 3.3.2 we can watch the contraction act. Each application of multiplies the error by the matrix .
for a symbolic starting vector : identically zero, so the error after sweeps is exactly .const chainP = await wl`{{p, 1 - p}, {1 - q, q}}`
const chainR = await wl`{Subscript[r, 1], Subscript[r, 2]}`
const chainV = await wl`Simplify[Inverse[IdentityMatrix[2] - \[Gamma] ${chainP}] . ${chainR}]`
const chainT = await wl`Function[{v}, ${chainR} + \[Gamma] ${chainP} . v]`
const errorIdentity = await show`Simplify[Nest[${chainT}, {Subscript[v, 1], Subscript[v, 2]}, 3] - ${chainV} - MatrixPower[\[Gamma] ${chainP}, 3] . ({Subscript[v, 1], Subscript[v, 2]} - ${chainV})]`const chainEig = await show`Eigenvalues[\[Gamma] ${chainP}]`The contraction of rests on a single inequality about maxima. The kernel can prove it for two actions by quantifier elimination over the reals.
for all real : the step in Lemma 4.1 that makes a contraction.const maxIneq = await show`Resolve[ForAll[{a, b, c, d}, Element[{a, b, c, d}, Reals], Abs[Max[a, b] - Max[c, d]] <= Max[Abs[a - c], Abs[b - d]]]]`4.2Policy Evaluation#
Iterative policy evaluation computes — the prediction problem — by iterating from an arbitrary (with at the terminal state):
(4.3)Each assignment is an expected update: it uses the probabilities of all successor states, not a sample of one. A literal implementation of (4.3) keeps two arrays, old and new, and is called synchronous or Jacobi-style. The usual implementation overwrites values in place, so that later states in a sweep already see the new values of earlier ones (Gauss–Seidel style).
Algorithm 4.3 (Iterative Policy Evaluation (in place)). Input: a policy , the model ; a threshold . Initialize: arbitrarily for , and .
- Repeat:
- .
- For each : ; ; .
- until . Return .
The in-place sweep is also a -contraction toward : when state is updated, the values it reads are either new ones, whose errors are already at most times the old maximal error, or old ones, whose errors are at most that maximal error; either way the new error at is at most times it. In practice the in-place version converges faster, by an amount that depends on the order of the sweep. With , stopping at guarantees for the synchronous version, by (4.2).
Example 4.4 (The Small Gridworld). A grid has terminal states in two opposite corners (formally one state) and fourteen nonterminal cells numbered in reading order. The four moves are deterministic, moves off the grid leave the agent in place, every transition gives reward , and . Under the equiprobable random policy, is the expected number of steps to termination.
The random policy is proper, so Proposition 3.4 applies with , and the kernel can skip the iteration altogether.
for the random policy on the grid, by solving exactly: the values are integers, the limits that the book’s iterative sweeps approach.const g4moves = await wl`{{-1, 0}, {1, 0}, {0, 1}, {0, -1}}`
const g4next = await wl`Function[{k, a}, With[{c = {Quotient[k - 1, 4] + 1, Mod[k - 1, 4] + 1} + a}, If[1 <= c[[1]] <= 4 && 1 <= c[[2]] <= 4, 4 (c[[1]] - 1) + c[[2]], k]]]`
const g4eval = await wl`Function[{pol}, Module[{P, r},
P = Table[If[k == 1 || k == 16, ConstantArray[0, 16], Sum[pol[[k, i]] UnitVector[16, ${g4next}[k, ${g4moves}[[i]]]], {i, 4}]], {k, 16}];
P[[All, {1, 16}]] = 0;
r = Table[If[k == 1 || k == 16, 0, -1], {k, 16}];
LinearSolve[IdentityMatrix[16] - P, r]]]`
const g4random = await wl`${g4eval}[ConstantArray[1/4, {16, 4}]]`
const g4show = await show`Partition[${g4random}, 4]`4.3Policy Improvement#
Why compute at all? To find a better policy. Knowing , we can evaluate any one-step deviation: is the return for taking once and then following . If , deviating once pays; the policy improvement theorem says that deviating every time pays too, and the gain is exactly accounted for by an identity.
Lemma 4.5 (Performance Difference). For any two policies and ,
(4.4)Equivalently, .
Proof. Subtract from to get , that is, . Invert. The series form is the Neumann expansion , since is the expectation of under . □
The quantity is the advantage of in ; the lemma says that the gain of switching to is the advantage of ’s actions, measured with ’s values, accumulated along ’s own trajectories.In this form the identity is usually credited to Kakade and Langford (2002). It underlies conservative policy iteration and, through the trust-region and proximal methods built on it, much of modern policy optimization (Chapter 13).Sham Kakade and John Langford. Approximately Optimal Approximate Reinforcement Learning. In Claude Sammut and Achim G. Hoffmann, editors, Proceedings of the Nineteenth International Conference on Machine Learning (ICML 2002), pages 267–274. Morgan Kaufmann, 2002
Theorem 4.6 (Policy Improvement). Let and be policies, deterministic or stochastic, such that for all
(4.5)Then for all . If the inequality (4.5) is strict at a state , then .
Proof. Let , which is by hypothesis. In (4.4), is the identity plus a matrix with nonnegative entries, so componentwise. At a state where this gives . □
The book proves the theorem by “unrolling”: start from , expand one step, apply the hypothesis at the next state, and repeat, accumulating ’s rewards until only is left. The matrix proof is the same argument with the bookkeeping done by the Neumann series. For both need to be proper.
The natural way to satisfy (4.5) everywhere is to be greedy:
(4.6)This is policy improvement. If the greedy policy is no better than , then — otherwise the theorem would give a strict improvement somewhere — so solves the optimality equation and is already optimal by Theorem 3.5. Greedy improvement either strictly improves a policy or certifies that it is optimal. With ties, a stochastic greedy policy may split its probability among the maximizing actions in any way; the theorem covers all such splits.
4.3.1In Wolfram Language#
The performance difference identity holds for any pair of policies, which the kernel confirms on a fully symbolic two-state MDP: two arbitrary transition matrices and reward vectors, one for each policy.
with six free parameters: zero, which is (4.4).const pdP1 = await wl`{{Subscript[p, 1], 1 - Subscript[p, 1]}, {1 - Subscript[q, 1], Subscript[q, 1]}}`
const pdP2 = await wl`{{Subscript[p, 2], 1 - Subscript[p, 2]}, {1 - Subscript[q, 2], Subscript[q, 2]}}`
const pdR1 = await wl`{Subscript[r, 1], Subscript[r, 2]}`
const pdR2 = await wl`{Subscript[r, 3], Subscript[r, 4]}`
const pdV = await wl`Function[{P, r}, Inverse[IdentityMatrix[2] - \[Gamma] P] . r]`
const pdCheck = await show`Simplify[${pdV}[${pdP2}, ${pdR2}] - ${pdV}[${pdP1}, ${pdR1}] - Inverse[IdentityMatrix[2] - \[Gamma] ${pdP2}] . (${pdR2} + \[Gamma] ${pdP2} . ${pdV}[${pdP1}, ${pdR1}] - ${pdV}[${pdP1}, ${pdR1}])]`On the small gridworld, one greedy step from the random policy already lands on an optimal policy: the greedy policy’s values are minus the shortest distances to a terminal corner.
Greedy (first maximizer) with respect to the random policy’s , then evaluated exactly: , against as low as .const g4greedy = await wl`Table[If[k == 1 || k == 16, {1, 0, 0, 0}, With[{q = Table[-1 + ${g4random}[[${g4next}[k, a]]], {a, ${g4moves}}]}, UnitVector[4, First[Ordering[q, -1]]]]], {k, 16}]`
const g4improved = await show`Partition[${g4eval}[${g4greedy}], 4]`4.4Policy Iteration#
Alternating the two steps produces a monotone sequence of policies,
where E is evaluation and I is greedy improvement. This is policy iteration, due to Howard.Ronald A. Howard. Dynamic Programming and Markov Processes. MIT Press, Cambridge, MA, 1960 One detail matters for termination: when several actions tie for the maximum, the current action should be kept, or the algorithm may cycle forever among equally good policies.
Algorithm 4.7 (Policy Iteration). Input: the model ; a threshold for evaluation. Initialize: and a deterministic arbitrarily, for all ; .
- Policy evaluation. Run Algorithm 4.3 for , starting from the current (or solve (3.11) exactly).
- Policy improvement. . For each :
- for all .
- If : set and .
- If , return and ; otherwise go to step 1.
Theorem 4.8 (Finite Termination of Policy Iteration). With exact evaluation and , policy iteration stops after at most improvement steps, and the policy it returns is optimal.
Proof. If step 2 changes , the new action has , and unchanged states satisfy (4.5) with equality. By Theorem 4.6, with strict inequality at the changed states. The value vectors therefore strictly increase in the partial order, so no policy can occur twice, and there are only deterministic policies. When the loop stops, is greedy with respect to its own value function, so and is optimal by Theorem 3.5. □
This is a second, purely combinatorial proof that a deterministic optimal policy exists. Policy iteration is also never slower than value iteration, iteration for iteration.
Proposition 4.9 (Policy Iteration Dominates Value Iteration). If is greedy with respect to , then . Consequently .
Proof. Since , monotonicity makes the sequence , , nondecreasing, and its limit is ; hence . Then , whose max norm is at most by Lemma 4.1. Iterate. □
In practice the bound of Theorem 4.8 is wildly pessimistic: policy iteration usually stops after a handful of iterations, because each improvement is global — every state switches to its best action at once.Puterman and Brumelle (1979) showed that policy iteration is Newton’s method applied to : the improvement step picks the linearization of this piecewise-linear map at , and the evaluation step solves the linearized equation, since by (4.4). This explains its very fast convergence near the solution.Martin L. Puterman and Shelby L. Brumelle. On the Convergence of Policy Iteration in Stationary Dynamic Programming. Mathematics of Operations Research, 4(1):60–69, 1979. doi: 10.1287/moor.4.1.60 Sutton and Barto’s Jack’s car rental problem illustrates this: two locations with up to 20 cars each ( states), Poisson requests and returns, and overnight moves of up to five cars at two dollars each; starting from the policy that never moves cars, policy iteration reaches an optimal policy after four improvements. Evaluation is warm-started from the previous value function, which changes little between iterations.
4.4.1In Wolfram Language#
A complete run of policy iteration on the recycling robot, with the parameters of Section 3.4.1 (, , , , ), exact evaluation, and the tie rule of Algorithm 4.7. One improvement step is a pure function from policies to policies; FixedPointList iterates it until the policy stops changing.
const rbP = await wl`{{{4/5, 1/5}, {1, 0}}, {{2/5, 3/5}, {0, 1}, {1, 0}}}`
const rbR = await wl`{{2, 1}, {0, 1, 0}}`
const rbQ = await wl`Function[{v}, Table[${rbR}[[s, a]] + 9/10 ${rbP}[[s, a]] . v, {s, 2}, {a, Length[${rbR}[[s]]]}]]`
const rbEval = await wl`Function[{pol}, LinearSolve[IdentityMatrix[2] - 9/10 Table[${rbP}[[s, pol[[s]]]], {s, 2}], Table[${rbR}[[s, pol[[s]]]], {s, 2}]]]`
const rbImprove = await wl`Function[{pol}, With[{q = ${rbQ}[${rbEval}[pol]]}, Table[If[q[[s, pol[[s]]]] == Max[q[[s]]], pol[[s]], First[Ordering[q[[s]], -1]]], {s, 2}]]]`
const rbPI = await show`Map[{#, ${rbEval}[#]} &, FixedPointList[${rbImprove}, {2, 2}]]`4.5Value Iteration#
Policy iteration evaluates each policy to convergence before improving it, which is wasteful far from the solution: in the small gridworld the greedy policy stops changing after three sweeps of evaluation, long before the values converge. The extreme alternative stops evaluation after one sweep and folds the improvement into it:
(4.7)that is, . This is value iteration: the optimality equation turned into an assignment, just as policy evaluation is the Bellman equation turned into one. Its convergence to at rate is Theorem 4.2.
Algorithm 4.10 (Value Iteration). Input: the model ; a threshold . Initialize: arbitrarily for , and .
- Repeat:
- .
- For each : ; ; .
- until .
- Return the deterministic policy .
Value iteration returns a policy, and what we care about is that policy’s value, not the accuracy of . The two are linked by a classical bound.
Proposition 4.11 (Loss of a Greedy Policy). Let , let , and let be greedy with respect to . Then
(4.8)Moreover, if is smaller than half the smallest gap divided by , then is optimal.
Proof. Greediness means . Hence , and by Lemma 4.1 the max norm of the right side is at most . Solve for . For the second claim, the one-step lookaheads computed from differ from by at most , less than half the gap, so no non-optimal action can attain the maximum. □
Together with (4.2): if a sweep changes no value by more than , the greedy policy loses at most .Satinder P. Singh and Richard C. Yee. An Upper Bound on the Loss from Approximate Optimal-Value Functions. Machine Learning, 16(3):227–233, 1994. doi: 10.1007/BF00993308; and Ronald J. Williams and Leemon C. Baird III. Tight Performance Bounds on Greedy Policies Based on Imperfect Value Functions. Technical Report NU-CCS-93-14, Northeastern University, College of Computer Science, Boston, MA, 1993 The second statement explains a phenomenon visible in every run: the greedy policy becomes optimal after finitely many sweeps, while the values converge only in the limit.
Between the two extremes lie the truncated or modified policy iteration algorithms, which improve the policy and then apply sweeps of evaluation, with greedy for : is value iteration and is policy iteration. All of them converge for discounted finite MDPs.Martin L. Puterman and Moon Chirl Shin. Modified Policy Iteration Algorithms for Discounted Markov Decision Problems. Management Science, 24(11):1127–1137, 1978. doi: 10.1287/mnsc.24.11.1127
4.5.1In Wolfram Language#
On the recycling robot, value iteration from in exact arithmetic lets us measure the a priori bound directly.
Rows for . The ratio stays below and settles near : the error shrinks essentially at rate . The greedy policy is optimal, , from on.const rbStar = await wl`${rbEval}[{1, 3}]`
const rbVI = await wl`NestList[Function[v, Map[Max, ${rbQ}[v]]], {0, 0}, 8]`
const rbRates = await show`Table[Join[{k, N[Max[Abs[${rbVI}[[k + 1]] - ${rbStar}]]/((9/10)^k Max[Abs[${rbStar}]]), 4]}, Map[First[Ordering[#, -1]] &, ${rbQ}[${rbVI}[[k + 1]]]]], {k, 0, 8}]`The same iteration solves the optimality equation of the gridworld of Section 3.3.2, in machine arithmetic this time; sweeps reduce the error below .
for the gridworld at by value iteration from : the book’s Figure 3.5 values, with as in Exercise 3.9.const g5step = 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 g5out = await wl`Table[${g5step}[s, a], {s, Tuples[{Range[5], Range[5]}]}, {a, {{-1, 0}, {1, 0}, {0, 1}, {0, -1}}}]`
const g5star = await show`NumberForm[Partition[Nest[Function[v, Map[Max, Map[Function[o, o[[2]] + 0.9 v[[5 (o[[1, 1]] - 1) + o[[1, 2]]]]], ${g5out}, {2}]]], ConstantArray[0., 25], 300], 5], {3, 1}]`4.5.2The Gambler’s Problem#
A gambler with capital stakes an integer on a coin that comes up heads with probability ; heads adds to the capital, tails removes it. The episode ends at or at the goal , and the only reward is on reaching the goal. With , is the maximal probability of reaching the goal from , and the optimality equation reads
(4.9)with and .
Every policy is proper — a run of at most heads ends any episode — so the conclusions of Chapter 3 hold with . For a subfair coin, , Dubins and Savage proved that bold play, staking , is optimal: an unfavorable game should be played as few times as possible.Lester E. Dubins and Leonard J. Savage. How to Gamble If You Must: Inequalities for Stochastic Processes. McGraw-Hill Series in Probability and Statistics. McGraw-Hill, New York, 1965 Bold play’s own value solves a linear system, for and for , so we can obtain in exact rational arithmetic and then test every action against it.
Remark 4.12. The book also allows the stake . That action leaves the state unchanged with reward , so it attains the maximum in (4.9) at every state — yet a policy that uses it can stall forever. This is the trap of the remark after Theorem 3.5: with , greedy with respect to is safe only among proper policies. We exclude .
On a smaller instance — goal and — the exact computation fits in two small tables and shows the ties among optimal actions.
Bold play’s value for goal in rationals, and for each capital the column . The residual row is , so bold play solves (4.9).const boldValue = await wl`Function[{n, ph}, Module[{v, eqs},
eqs = Table[v[s] == If[s <= n - s, ph v[2 s], ph + (1 - ph) v[2 s - n]], {s, 1, n - 1}] /. {v[0] -> 0, v[n] -> 1};
Join[{0}, Table[v[s], {s, 1, n - 1}] /. First[Solve[eqs, Table[v[s], {s, 1, n - 1}]]], {1}]]]`
const gamblerV = await wl`${boldValue}[8, 2/5]`
const gamblerQ = await wl`Table[Table[2/5 ${gamblerV}[[s + a + 1]] + 3/5 ${gamblerV}[[s - a + 1]], {a, 1, Min[s, 8 - s]}], {s, 1, 7}]`
const gamblerTable = await show`Transpose[Table[{s, ${gamblerV}[[s + 1]], Max[${gamblerQ}[[s]]] - ${gamblerV}[[s + 1]]}, {s, 1, 7}]]`const gamblerStakes = await show`Table[Flatten[Position[${gamblerQ}[[s]], Max[${gamblerQ}[[s]]]]], {s, 1, 7}]`The figure answers the book’s question about the shape of the family of optimal policies. is self-similar: by the equations above, its graph on is a copy of the whole graph scaled by , which is why the optimal stakes repeat at capitals , , , and so on. Numerically computed policies look jagged because floating-point value iteration breaks these exact ties arbitrarily.
4.6Asynchronous Dynamic Programming#
A sweep over backgammon positions would take millennia. Asynchronous DP drops the sweep: it updates the values of states in any order, in place, using whatever values the other states currently have, possibly updating some states many times before others once.Dimitri P. Bertsekas. Distributed Dynamic Programming. IEEE Transactions on Automatic Control, 27(3):610–616, 1982. doi: 10.1109/TAC.1982.1102980; and Dimitri P. Bertsekas and John N. Tsitsiklis. Parallel and Distributed Computation: Numerical Methods. Prentice-Hall, Englewood Cliffs, NJ, 1989
Proposition 4.13 (Convergence of Asynchronous Value Iteration). Let and apply the update (4.7) in place to one state at a time. If every state appears infinitely often in the sequence , then .
Proof. Let before some update. Updating replaces by , whose distance to is at most ; other components do not change. So never increases, and once every state has been updated at least once since a moment when the error was , all components have error at most . Divide time into consecutive intervals in each of which every state is updated; there are infinitely many, and after of them the error is at most . □
Mixing evaluation updates with optimality updates in the same way gives asynchronous versions of truncated policy iteration. Avoiding sweeps does not reduce the total work needed for a guarantee, but it removes the commitment to one long sweep, and it lets us choose where to compute. In particular, DP can run while an agent acts, updating the states the agent actually visits and feeding the latest greedy policy back into its behavior. This focusing on relevant states is developed in Chapter 8 (prioritized sweeping, real-time DP, trajectory sampling).
4.7Generalized Policy Iteration#
Policy iteration consists of two interacting processes. Evaluation makes the value function consistent with the current policy, pushing toward . Improvement makes the policy greedy with respect to the current value function, pushing toward . Policy iteration runs each to completion before starting the other; value iteration runs a single sweep of evaluation between improvements; asynchronous DP interleaves them state by state. In all cases the result is the same. Generalized policy iteration (GPI) is the name for this whole family: any scheme in which an approximate policy and an approximate value function are kept and each is repeatedly moved toward the target defined by the other, whatever the granularity.
Why must GPI end at optimality? Because its only resting points are optimal.
Proposition 4.14 (The Fixed Points of GPI). For a value function and a policy , the following are equivalent: (a) neither process changes anything, that is, and is greedy with respect to ; (b) and is optimal.
Proof. (a) ⇒ (b): because , and because is greedy; so , hence and is optimal by Theorem 3.5. (b) ⇒ (a): if is optimal then , so puts weight only on maximizing actions, that is, it is greedy with respect to . □
The two processes both compete and cooperate. They compete because each spoils the other’s target: making greedy changes , so is no longer accurate; making accurate usually changes which actions look greedy. They cooperate because, by the improvement theorem, each greedy step can only raise the true value, so the pair drifts toward the single point where both targets coincide. Figure 4.2 draws this in the value plane of the recycling robot, where both extremes of GPI can be seen at once.
GPI is the lens for the rest of the book. Every method keeps a policy and a value function and alternates, at some granularity, between evaluating and improving; they differ in how the evaluation is done and how greedy the improvement is.
| method | evaluation | improvement |
|---|---|---|
| policy and value iteration (this chapter) | expected updates with the model | exact greedy |
| Monte Carlo control (Chapter 5) | averages of sampled returns | greedy or -greedy, per episode |
| Sarsa (Chapter 6) | one sampled, bootstrapped update per step | -greedy with respect to the current |
| Q-learning (Chapter 6) | sampled update toward — sampled value iteration | implicit in the max |
| Dyna (Chapter 8) | real and simulated updates | -greedy |
| actor–critic (Chapter 13) | TD learning of (critic) | a small gradient step on the policy (actor) |
DP has one more property that the table hides. Its updates estimate the value of a state from estimates of the values of successor states; this is bootstrapping. Monte Carlo methods do not bootstrap and do not need a model; TD methods bootstrap without a model. Whether a method uses a model (expected updates) or samples, and whether it bootstraps, are separate choices, and the next chapters explore the combinations. With function approximation, finally, the evaluation step can no longer represent exactly, and the guarantees of this section are lost; Section 11.3 explains when GPI can then diverge.
4.8Efficiency and Linear Programming#
DP is often dismissed as impractical, but compared with the alternatives it is efficient. One sweep of value iteration costs operations, one exact policy evaluation , and the number of iterations needed is polynomial in , , and the number of bits of the input,Michael L. Littman, Thomas L. Dean, and Leslie Pack Kaelbling. On the Complexity of Solving Markov Decision Problems. In Proceedings of the Eleventh Conference on Uncertainty in Artificial Intelligence (UAI 1995), pages 394–402, 1995 whereas there are deterministic policies to search through. What makes large problems hard is the curse of dimensionality — Bellman’s phrase for the exponential growth of with the number of state variables — which is a property of the problems, not a weakness of DP. Today DP handles MDPs with millions of states; beyond that, asynchronous and sample-based methods take over.
4.8.1The Linear Programming Formulation#
MDPs can also be solved by linear programming, an observation as old as policy iteration: Manne formulated the average-cost problem as a linear program in 1960, and d’Epenoux the discounted one.Alan S. Manne. Linear Programming and Sequential Decisions. Management Science, 6(3):259–267, 1960. doi: 10.1287/mnsc.6.3.259; and F. d’Epenoux. A Probabilistic Production and Inventory Problem. Management Science, 10(1):98–108, 1963. doi: 10.1287/mnsc.10.1.98 Fix weights and consider
(4.10)Proposition 4.15 (The LP Solution is ). For , the unique solution of (4.10) is .
Proof. The constraints say . If is a deterministic optimal policy, then , and by monotonicity . So every feasible is componentwise, while itself is feasible. Any other feasible exceeds in some component, and since its objective is strictly larger. □
The dual LP has one variable per state–action pair, maximizes subject to , and its feasible points are exactly the discounted occupancy measures of policies started from ; an optimal dual solution is supported on optimal actions, and recovers an optimal policy. LP solvers have better worst-case guarantees than DP on some classes of problems but become impractical much sooner as grows. The formulation matters more as a theoretical bridge: the dual variables are the state–action visitation distributions that reappear in off-policy learning and in policy-gradient theory.
The LP (4.10) for the recycling robot with : the primal minimizer is , and the dual is positive only on and , the optimal pairs; its total mass is .const rbLP = await show`LinearOptimization[x + y, Flatten[Table[{x, y}[[s]] >= ${rbR}[[s, a]] + 9/10 ${rbP}[[s, a]] . {x, y}, {s, 2}, {a, Length[${rbR}[[s]]]}]], {x, y}, {"PrimalMinimizer", "DualMaximizer"}]`4.9Beyond the Book: The Complexity of Policy Iteration#
How many iterations does policy iteration need? Theorem 4.8 gives the exponential bound , practice suggests a handful, and for decades the truth was open.Beyond Sutton and Barto (2018). The strongly polynomial bounds for policy iteration (Ye 2011; Hansen, Miltersen and Zwick 2013; Scherrer 2016) and anchored value iteration (Lee and Ryu 2023) are not discussed in the book, whose Section 4.7 says only that DP is polynomial in the numbers of states and actions. Write and for the total number of actions.
Polynomial, but not strongly. Value iteration finds an -optimal policy in fewer than iterations, where is the number of bits of the input,Michael L. Littman, Thomas L. Dean, and Leslie Pack Kaelbling. On the Complexity of Solving Markov Decision Problems. In Proceedings of the Eleventh Conference on Uncertainty in Artificial Intelligence (UAI 1995), pages 394–402, 1995 and Proposition 4.9 transfers the same rate to policy iteration. Such bounds depend on the size of the numbers, not only on and ; an algorithm whose number of arithmetic operations is bounded by a polynomial in and alone is called strongly polynomial.
Policy iteration is strongly polynomial for a fixed discount. Ye proved that Howard’s policy iteration, and the simplex method with Dantzig’s pivoting rule on the LP of (4.10), terminate after iterations.Yinyu Ye. The Simplex and Policy-Iteration Methods Are Strongly Polynomial for the Markov Decision Problem with a Fixed Discount Rate. Mathematics of Operations Research, 36(4):593–603, 2011. doi: 10.1287/moor.1110.0516 Hansen, Miltersen and Zwick improved the bound for policy iteration to , and showed that the same strategy iteration solves two-player turn-based discounted stochastic games in strongly polynomial time for fixed .Thomas Dueholm Hansen, Peter Bro Miltersen, and Uri Zwick. Strategy Iteration Is Strongly Polynomial for 2-Player Turn-Based Stochastic Games with a Constant Discount Factor. Journal of the ACM, 60(1):1:1–1:16, 2013. doi: 10.1145/2432622.2432623 Scherrer removed the from the logarithm: policy iteration stops within iterations.Bruno Scherrer. Improved and Generalized Upper Bounds on the Complexity of Policy Iteration. Mathematics of Operations Research, 41(3):758–774, 2016. doi: 10.1287/moor.2015.0753 The common idea is an elimination argument. By Proposition 4.9 the error shrinks by per iteration; by the performance difference lemma, every action that a policy still uses carries part of that error as negative advantage . After about iterations the error is too small for the worst action in use to remain in use, and it is never chosen again; there are at most non-optimal actions to eliminate. The factor cannot simply be dropped: for undiscounted total-reward and average-reward MDPs, Fearnley built instances on which Howard’s policy iteration takes exponentially many iterations.John Fearnley. Exponential Lower Bounds for Policy Iteration. In Samson Abramsky, Cyril Gavoille, Claude Kirchner, Friedhelm Meyer auf der Heide, and Paul G. Spirakis, editors, Automata, Languages and Programming (ICALP 2010), Part II, volume 6199 of Lecture Notes in Computer Science, pages 551–562. Springer, 2010. doi: 10.1007/978-3-642-14162-1_46
Faster value iteration. Value iteration’s Bellman error decays like , which is slow when is close to . Lee and Ryu’s anchored value iteration mixes every iterate with the starting point,
(4.11)with or , and achieves a Bellman error of order — an rate that does not degrade as and holds even for when .Jongmin Lee and Ernest K. Ryu. Accelerating Value Iteration with Anchoring. In A. Oh, T. Naumann, A. Globerson, K. Saenko, M. Hardt, and S. Levine, editors, Advances in Neural Information Processing Systems, volume 36, pages 53924–53963. Curran Associates, Inc., 2023. doi: 10.52202/075280-2346 They also prove a lower bound showing that no method whose iterates lie in the span of the past Bellman residuals can do better than their rate by more than a factor of .
Linear programming with features. The LP of Section 4.8.1 has one variable per state. De Farias and Van Roy restricted it to for a feature matrix with few columns — the approximate linear program, minimize subject to — and proved that if the constant function is representable and is a probability distribution, the solution satisfies , with sharper bounds through Lyapunov-weighted norms.Daniela Pucci de Farias and Benjamin Van Roy. The Linear Programming Approach to Approximate Dynamic Programming. Operations Research, 51(6):850–865, 2003. doi: 10.1287/opre.51.6.850.24925 The weights play the role of the state distribution of Chapter 9: the approximation is good where the weights are large. The number of constraints is still , so in practice they are sampled.
Every method of this chapter, exact or approximate, still takes the model as given and sweeps it with expected updates. Chapter 5 drops the model: it estimates the same value functions from sampled episodes of experience, and keeps generalized policy iteration as the way to turn them into better policies.
4.10Exercises#
Exercise 4.16. In the small gridworld under the random policy, what are and ?
Solution
By the second relation of (3.8), . Moving down from cell reaches the terminal state, so ; moving down from reaches , so . In the kernel’s numbering the cell of the book is index .
for the two pairs, read off the exact .const exQ = await show`{-1 + ${g4random}[[${g4next}[12, {1, 0}]]], -1 + ${g4random}[[${g4next}[8, {1, 0}]]]}`Exercise 4.17. Add a state below cell of the small gridworld, whose moves lead to . (a) If the old transitions are unchanged, what is for the random policy? (b) What if, in addition, from now leads to ?
Solution
(a) No old state can reach , so the old values stand and , giving . (b) Now feeds back into , so in principle all values change; but the old together with still satisfies every equation, because from the new successor has the same value as the old successor itself. By uniqueness (Proposition 3.4) nothing changes.
Case (b) solved from scratch: the 17-index system with the new state at index and from cell (index ) redirected to it; we print and .const exState15 = await show`Module[{next, P, r, v},
next = Function[{k, a}, Which[
k == 17, {13, 14, 15, 17}[[Position[{{0, -1}, {-1, 0}, {0, 1}, {1, 0}}, a][[1, 1]]]],
k == 14 && a == {1, 0}, 17,
True, ${g4next}[k, a]]];
P = Table[If[k == 1 || k == 16, ConstantArray[0, 17], Sum[UnitVector[17, next[k, a]]/4, {a, ${g4moves}}]], {k, 17}];
P[[All, {1, 16}]] = 0;
r = Table[If[k == 1 || k == 16, 0, -1], {k, 17}];
v = LinearSolve[IdentityMatrix[17] - P, r];
{v[[14]], v[[17]]}]`Exercise 4.18. For goal and , a policy found by value iteration stakes everything at capital but only at capital . Why is this a good policy?
Solution
The game is subfair, so each additional bet costs probability in expectation; the best one can do from is a single all-or-nothing bet, which wins with probability . From , the bold stake wins outright with probability and otherwise leaves . The stake moves to or back to ; from the gambler then bets bold. Exact arithmetic shows that the two choices, and with them the whole family of tied stakes in Figure 4.1, give exactly the same probability of success, , larger than .
exactly, and the differences and , for goal and .const exGambler = await show`With[{v = ${boldValue}[100, 2/5], ph = 2/5}, {v[[52]], ph v[[53]] + (1 - ph) v[[51]] - v[[52]], ph v[[101]] + (1 - ph) v[[3]] - v[[52]]}]`Exercise 4.19. Write policy evaluation, policy iteration, and value iteration for action values , and explain what is gained by working with instead of .
Solution
Evaluation iterates (3.10): . Value iteration iterates (3.18): ; both are -contractions in the max norm over state–action pairs, by the proof of Lemma 4.1. Policy iteration alternates evaluation of with , keeping the current action on ties. The gain is that the improvement step needs no model: the one-step lookahead has already been done and stored in . When the expectations over in the evaluation step are in turn replaced by samples, these become Sarsa and Q-learning (Chapter 6).
Exercise 4.20. Suppose only -soft policies are allowed, with for all . How must steps 3, 2 and 1 of policy iteration change, and what does the algorithm converge to?
Solution
Step 3 (improvement): instead of the greedy action, choose the -greedy policy, with probability on a maximizing action and on each other action; the stopping test compares these policies. Step 2 (evaluation): evaluate the stochastic policy, averaging over as in (4.3). Step 1 (initialization): start from an -soft policy, such as the uniform one. The -greedy step satisfies (4.5) relative to any -soft , because it shifts all the freely assignable probability to a best action, so the theorem still applies; the algorithm converges to the best policy among -soft ones, which is generally not optimal in the unrestricted sense. This is the policy improvement step of on-policy Monte Carlo control in Chapter 5.