Dynamic programming¶
If you know the rules of the world (every transition probability and every expected reward), you can compute the optimal policy without ever acting. Dynamic programming does it by turning the Bellman equations into update rules and sweeping them over the state space until nothing changes. Every learning algorithm in RL is dynamic programming with something missing: the model, the full sweep, or the table.
10,000 ft
The Bellman equations say what optimal values must satisfy; dynamic programming (DP) is how you actually find them when the model \(p(s', r \mid s, a)\) is known. Richard Bellman named the method in the 1950s, and its two classic algorithms, policy iteration (Howard, 1960) and value iteration, are the templates for the rest of this track. Monte Carlo and TD learning are DP with the expectation replaced by samples; Q-learning and DQN are sampled, approximate value iteration; actor-critic methods are approximate policy iteration; AlphaZero is policy iteration with tree search as the improvement step. DP is also the same idea as the shortest-path, Viterbi and edit-distance algorithms of computer science. Its limit is the curse of dimensionality: it needs a value for every state, and real problems have astronomically many.
2,000 ft
DP alternates two operations on a table of values. Evaluation asks "how good is this policy?" and answers it by repeatedly applying the Bellman expectation equation as an update. Improvement asks "can I do better?" and answers it by acting greedily on those values. Doing them in turn is generalised policy iteration (GPI), the pattern behind almost every RL algorithm.
- Policy evaluation: sweep \(V(s) \leftarrow \sum_a \pi(a\mid s)\sum_{s',r} p(s',r\mid s,a)[r + \gamma V(s')]\) until it stops changing. It converges to \(v_\pi\) because the update is a contraction.
- Policy improvement: set \(\pi'(s) = \arg\max_a \sum_{s',r} p(s',r\mid s,a)[r + \gamma v_\pi(s')]\). The policy improvement theorem guarantees \(v_{\pi'} \ge v_\pi\) everywhere.
- Policy iteration repeats 1 and 2 to convergence. It ends at an optimal policy in a finite (and in practice tiny) number of iterations.
- Value iteration fuses them: one sweep of \(V(s) \leftarrow \max_a \sum_{s',r} p(s',r\mid s,a)[r + \gamma V(s')]\), repeated. Error shrinks by a factor \(\gamma\) per sweep.
- Asynchronous DP updates states in any order, as long as none is starved. This freedom is what lets learning algorithms update only the states they visit.
Ground level¶
What "dynamic programming" means¶
A problem has a DP solution when it has two properties. Optimal substructure: the best solution is built from best solutions to smaller subproblems. Overlapping subproblems: the same subproblems recur, so solving each once and storing the answer (a table) saves exponential work. In an MDP the subproblems are "act optimally from state \(s\)", their stored answers are the values \(v(s)\), and the Bellman equation is the recipe for combining them. The word "programming" is in the old sense of planning or scheduling, as in "linear programming", not writing code.
The simplest case is a finite horizon: with \(k\) steps left, the best you can do from \(s\) is the best immediate action plus the best you can do from the next state with \(k-1\) steps left. Start from \(v_0 = 0\) (no steps left, no reward) and work backwards:
This is backward induction. On the Fresh/Tired MDP from the previous page with \(\gamma = 0.9\):
| Steps to go \(k\) | \(v_k(\text{Fresh})\) | \(v_k(\text{Tired})\) | best action in Tired |
|---|---|---|---|
| 1 | 2.000 | 1.000 | work (1 now beats 0 now) |
| 2 | 3.530 | 1.900 | work: \(1 + 0.9 \times 1 = 1.9\) beats rest: \(0.9(0.8 \times 2 + 0.2 \times 1) = 1.62\) |
| 3 | 4.737 | 2.884 | rest: \(0.9(0.8 \times 3.53 + 0.2 \times 1.9) = 2.884\) beats work: \(1 + 0.9 \times 1.9 = 2.71\) |
| ∞ | 15.046 | 13.211 | rest |
With one or two steps left it is right to grind on while tired; with three or more, resting pays for itself. Now notice that value iteration is exactly backward induction run for longer and longer horizons: \(v_k\) is the optimal \(k\)-step value, and as \(k \to \infty\) the discounted tail becomes negligible and \(v_k \to v_\ast\). That is the cleanest way to remember what value iteration computes at every intermediate step.
A financial plan is a finite-horizon decision problem
A FIRE plan has the same shape: the state is (age, corpus), the actions are how much to save or withdraw and how to allocate, and the horizon ends at a planning age. Choosing the best withdrawal rule is backward induction from the last year: the value at 84 depends only on the corpus at 84, the value at 83 on the best action at 83 given the value at 84, and so on. Simulating one plan forward, as Finny's engine does, is policy evaluation; optimising over rules is the improvement step. See the Jarvis case study for how the engine and the language model divide that work.
Policy evaluation: the Bellman equation as an update rule¶
You know from the MDP page that \(v_\pi\) solves a linear system, \(\mathbf{v} = \mathbf{r}_\pi + \gamma P_\pi \mathbf{v}\). For a few thousand states, solve it directly. For more, iterate: start anywhere and repeatedly apply the right-hand side.
Each application is one sweep and costs \(O(|\mathcal{S}|^2 |\mathcal{A}|)\) for dense dynamics, far less when each state has only a few successors. The update is called a full backup (or expected update): it averages over every action and every successor, weighted by their true probabilities. The learning methods of the next pages will replace it with a sample backup that uses one observed successor.
Worked example: the 4 × 4 gridworld. Sutton and Barto's Example 4.1: 14 ordinary cells and two terminal corners; four moves (bumping a wall leaves you in place); reward \(-1\) per move; \(\gamma = 1\). Evaluate the equiprobable random policy, starting from \(V_0 = 0\):
| Sweep | values (row by row, terminal corners are 0) |
|---|---|
| \(k = 1\) | every non-terminal cell is \(-1.0\) |
| \(k = 2\) | \(-1.8\) next to a corner, \(-2.0\) elsewhere |
| \(k = 3\) | \(-2.4\), \(-2.9\), \(-3.0\) by distance |
| \(k = 10\) | \(-6.1\) next to a corner up to \(-9.0\) in the far corners |
| \(k = 173\) | converged (change below \(10^{-4}\)) |
The converged values have a concrete meaning: \(-22\) in the far corner says a random walker starting there takes 22 moves on average to stumble into an exit. Values propagate outwards from the terminal states at one cell per sweep, which is why early sweeps only distinguish "next to a corner" from "not".
Two implementation choices matter more than they look:
- Two arrays or one. The textbook update computes all of \(V_{k+1}\) from \(V_k\) (two arrays). Updating in place, so later states in the sweep already see this sweep's new values, also converges and is usually faster: 114 sweeps instead of 173 here, because improvements propagate within a sweep. The sweep order then matters; sweeping from the exits outwards is fastest.
- When to stop. Iterative evaluation never reaches \(v_\pi\) exactly. Stop when the largest change in a sweep is below a tolerance; the maths turns that change into a bound on the remaining error.
γ = 1 needs proper policies
With \(\gamma = 1\) the evaluation update is a contraction only if every policy you evaluate reaches a terminal state with probability 1. A deterministic policy that walks into a wall forever has value \(-\infty\) in this gridworld, and iterative evaluation of it never converges. Either use \(\gamma < 1\), or make sure every policy you evaluate is proper (the random policy and every policy greedy with respect to its finite values are).
Policy improvement: why greedy cannot hurt¶
Having \(v_\pi\), consider deviating in one state \(s\): take action \(a\) now, then follow \(\pi\). That is worth \(q_\pi(s, a) = \sum_{s', r} p(s', r \mid s, a)[r + \gamma v_\pi(s')]\). If some \(a\) has \(q_\pi(s,a) > v_\pi(s)\), deviating once is better than not deviating. The policy improvement theorem says more: if you deviate like this every time you visit every such state, you are still better off.
Policy improvement theorem
Let \(\pi, \pi'\) be deterministic policies with \(q_\pi(s, \pi'(s)) \ge v_\pi(s)\) for all \(s\). Then \(v_{\pi'}(s) \ge v_\pi(s)\) for all \(s\). If the first inequality is strict in some state, the second is strict in that state.
In particular, the greedy policy \(\pi'(s) = \arg\max_a q_\pi(s, a)\) satisfies the condition, since \(\max_a q_\pi(s,a) \ge q_\pi(s, \pi(s)) = v_\pi(s)\). So greedy improvement never makes any state worse. And if greedy improvement changes nothing, then \(v_\pi(s) = \max_a q_\pi(s,a)\) for every \(s\): that is the Bellman optimality equation, so \(\pi\) is optimal. The proof is short and is in the maths.
In the gridworld, the greedy policy for the random policy's values is already optimal (right panel above): every arrow points down a shortest path. That is luck of the geometry, not a general rule, but it shows how much information even a bad policy's values contain.
Policy iteration¶
Alternate full evaluation and greedy improvement:
Each policy is strictly better than the last until none can be improved, and a finite MDP has only \(|\mathcal{A}|^{|\mathcal{S}|}\) deterministic policies, so policy iteration terminates. That counting bound is wildly pessimistic. On the Fresh/Tired MDP, starting from the worst policy:
| Iteration | policy (Fresh, Tired) | \(v_\pi\) by exact solve | \(q_\pi\) (rows Fresh, Tired; columns work, rest) | greedy |
|---|---|---|---|---|
| 1 | rest, rest | (0, 0) | (2.0, 0.0), (1.0, 0.0) | work, work |
| 2 | work, work | (12.703, 10.000) | (12.703, 11.432), (10.000, 10.946) | work, rest |
| 3 | work, rest | (15.046, 13.211) | (15.046, 13.541), (12.890, 13.211) | unchanged: optimal |
Three evaluations. On the gridworld, also three: the first improvement is already optimal, and the second changes only which of two tied arrows is chosen. On a random MDP with 100 states and 4 actions (sparse Dirichlet-random transitions, uniform random rewards in [0, 1]), policy iteration needs 4 iterations at both \(\gamma = 0.9\) and \(\gamma = 0.99\).
How many iterations can it take in the worst case? For a fixed discount factor, Ye (2011) proved policy iteration is strongly polynomial: the number of iterations is bounded by a polynomial in the number of states and actions, independent of the reward values. Scherrer (2013) tightened Howard's policy iteration to at most \(O\big(\frac{m}{1-\gamma}\log\frac{1}{1-\gamma}\big)\) iterations, where \(m\) is the total number of state–action pairs. The \(1/(1-\gamma)\) factor is the horizon: discount problems with long horizons can still be slow. Each iteration costs an exact evaluation, \(O(|\mathcal{S}|^3)\) with a linear solve.
Value iteration¶
Policy iteration evaluates each policy to convergence, but the improvement step only needs values good enough to rank actions. Truncate evaluation to a single sweep and fold the greedy max into it:
This is the Bellman optimality equation used as an update, and it is the backward induction of the first section run for ever. The contraction argument guarantees \(\|V_k - v_\ast\|_\infty \le \gamma^k \|V_0 - v_\ast\|_\infty\) from any start. On Fresh/Tired (\(\gamma = 0.9\), \(V_0 = 0\)):
| \(k\) | \(V_k(\text{F})\) | \(V_k(\text{T})\) | greedy policy | \(\lVert V_k - v_\ast\rVert_\infty\) | change this sweep |
|---|---|---|---|---|---|
| 1 | 2.000 | 1.000 | work, work | 13.046 | 2.000 |
| 3 | 4.737 | 2.884 | work, rest | 10.327 | 1.207 |
| 10 | 10.113 | 8.278 | work, rest | 4.933 | 0.548 |
| 20 | 13.326 | 11.491 | work, rest | 1.720 | 0.191 |
| 50 | 14.973 | 13.138 | work, rest | 0.073 | 0.008 |
| 100 | 15.045 | 13.211 | work, rest | 0.0002 | 0.00002 |
The greedy policy is optimal from sweep 3, while the values are still 10 away from correct. That is the general pattern and the reason value iteration works in practice: the policy converges long before the values do, because ranking actions needs only the differences between their values to be right.
The cost is the horizon. Error shrinks by \(\gamma\) per sweep, so reaching error \(\varepsilon\) from an initial error of \(R_{\max}/(1-\gamma)\) takes about
sweeps (using \(-\ln\gamma \approx 1-\gamma\)). For \(\gamma = 0.99\), \(R_{\max} = 1\) and \(\varepsilon = 10^{-6}\) that is about 1,830; the measured number on the random MDP below is 1,816. At \(\gamma = 0.9\) it is about 150 (measured: 152).
Between the two: modified policy iteration and asynchronous DP¶
Policy iteration and value iteration are the two ends of one dial. Modified policy iteration (Puterman and Shin, 1978) does \(m\) evaluation sweeps per improvement: \(m = 1\) is value iteration, \(m = \infty\) is policy iteration. Evaluation sweeps of a fixed policy have no max over actions, so they are \(|\mathcal{A}|\) times cheaper than value-iteration sweeps; in practice a modest \(m\) is often the fastest option overall.
Asynchronous DP drops the sweep altogether. Update any state, in any order, using whatever values the others currently hold; as long as every state keeps being updated, value iteration still converges (Bertsekas's work on distributed DP in the 1980s). This freedom is what makes the rest of RL possible, and it also gives three practical algorithms:
- Gauss–Seidel / in-place sweeps: the in-place evaluation above.
- Prioritised sweeping (Moore and Atkeson, 1993): keep a priority queue of states whose values would change most, and update those first. Changes propagate along the paths that matter instead of everywhere.
- Real-time DP (Barto, Bradtke and Singh, 1995): update only the states the agent actually visits while acting greedily. States that an optimal agent never reaches are never computed, which can be most of the state space. This is the bridge from planning to learning: replace the known model with samples and you have TD learning.
The curse of dimensionality, and what DP became¶
Bellman coined the phrase curse of dimensionality for the problem that kills tabular DP: the number of states grows exponentially with the number of variables describing a state. A robot with 10 joints, each discretised into 100 angles, has \(100^{10} = 10^{20}\) configurations before you count velocities. Backgammon has more than \(10^{20}\) states (Sutton and Barto); legal Go positions on a 19 × 19 board number about \(2.1 \times 10^{170}\) (Tromp and Farnebäck's count). A sweep over such a space is impossible, and so is a table to store it.
Everything in the rest of this track is a way around that, and each keeps one half of DP:
| What DP needs | What breaks at scale | What replaces it | Where |
|---|---|---|---|
| A model \(p(s', r \mid s, a)\) | Usually unknown | Samples of real transitions | MC and TD, Q-learning |
| A full sweep over states | Too many states | Update only visited states (RTDP, replay buffers) | DQN |
| A table of values | Too many states to store | A function approximator \(V_\theta\), \(Q_\theta\) | Fitted value iteration: regress \(Q_\theta\) onto \(r + \gamma \max Q\) (Munos and Szepesvári, 2008; DQN is its online form) |
| An exact max over actions | Continuous or huge action sets | A policy network | Policy gradients, actor-critic |
| Exact evaluation | Too expensive | A critic trained by TD | Approximate policy iteration |
| Exact improvement | Too expensive | Look-ahead search from the current state | AlphaZero and MuZero |
The price of approximation is real. With exact evaluation and improvement, policy iteration improves monotonically. With an evaluation error of up to \(\varepsilon\) at each iteration, the classic guarantee (Bertsekas and Tsitsiklis, Neuro-Dynamic Programming, 1996) is only that the policies eventually stay within \(2\gamma\varepsilon/(1-\gamma)^2\) of optimal: a loss that can be \(2 \times 0.99 / 0.0001 \approx 20{,}000\) times the per-step error at \(\gamma = 0.99\). Errors in values compound through the bootstrap. That is the theoretical shadow of the instability that DQN's target network was invented to tame.
DP outside reinforcement learning¶
The same recipe (define values of subproblems, write a recursion, fill the table) runs a surprising share of algorithms you already use:
- Shortest paths. Bellman–Ford is value iteration on a deterministic MDP whose rewards are the negated edge lengths; Dijkstra's algorithm is an asynchronous DP with a clever update order. The gridworld above is a shortest-path problem.
- Viterbi decoding finds the most likely hidden-state path in an HMM by a max-sum recursion over time steps on log-probabilities, run forwards instead of backwards, then traced back.
- Edit distance and sequence alignment fill a table of best costs for prefixes.
- Linear–quadratic control (LQR): with linear dynamics and quadratic costs, the value function stays quadratic and backward induction becomes the Riccati recursion, solvable exactly for continuous states. It is the one continuous case where DP is easy.
- CTC loss in speech recognition sums over all alignments with a forward–backward DP.
First principles¶
Why iterating the Bellman equation must work. The Bellman operators are \(\gamma\)-contractions in the max norm (proof on the MDP page): applying one to two value functions shrinks the largest gap between them by at least a factor \(\gamma\). Apply it to your current guess and to the true solution (which the operator leaves fixed) and the gap to the truth shrinks geometrically. Nothing about the start matters, and nothing about the order of updates matters either, as long as every state keeps being updated, because each single-state update also never increases the max-norm gap.
Why greedy improvement is safe. A policy's values summarise its whole future. If in state \(s\) there is an action whose one-step look-ahead on those values beats the policy's own choice, then "take that action, then behave as before" beats "behave as before". Switching to the better action everywhere can only help further, because every state you land in is now at least as good as it was. The argument fails the moment the values are wrong: greedy improvement with respect to inaccurate values can make things worse, which is the whole difficulty of approximate DP.
Why policy iteration is so fast. Policy iteration is Newton's method on the Bellman optimality equation (Puterman and Brumelle, 1979). Write the equation as \(F(\mathbf{v}) = T^\ast\mathbf{v} - \mathbf{v} = 0\). Where the greedy policy \(\pi\) is unique, \(T^\ast\) is locally the affine map \(\mathbf{r}_\pi + \gamma P_\pi \mathbf{v}\), so the Jacobian of \(F\) is \(\gamma P_\pi - I\), and one Newton step from \(\mathbf{v}\) is
which is exactly "improve to the greedy policy, then evaluate it". Newton's method converges quadratically near the solution; value iteration is a fixed-point iteration and converges only linearly, at rate \(\gamma\). The error sequence of policy iteration in the figure above (36, 1.3, 0.0067, 0) is that quadratic convergence. Bertsekas builds his modern account of RL, including AlphaZero-style look-ahead, on this Newton view.
Why the policy converges before the values. The greedy action depends only on which \(q(s,a)\) is largest in each state. Errors that shift all of a state's action values by the same amount do not change the argmax, and the dominant error in early value iteration is exactly such a common shift (the not-yet-counted tail of rewards, similar for all actions). Once the remaining error is smaller than half the gap between the best and second-best action values, the policy is fixed for good.
Why the curse is a curse of tables, not of decisions. DP's cost is linear in the number of states, which is perfectly good; the problem is that the state count is exponential in the problem's description. Any method that represents the value of each state separately inherits it. Generalisation (similar states have similar values) is the only escape, and it is what neural networks bring to RL.
The maths¶
Notation
Finite MDP, \(n = |\mathcal{S}|\) states. For a deterministic policy \(\pi\): \(\mathbf{r}_\pi(s) = r(s, \pi(s))\), \(P_\pi(s, s') = p(s' \mid s, \pi(s))\). Operators \(T^\pi\mathbf{v} = \mathbf{r}_\pi + \gamma P_\pi\mathbf{v}\) and \((T^\ast\mathbf{v})(s) = \max_a [r(s,a) + \gamma\sum_{s'} p(s'\mid s,a)v(s')]\), both \(\gamma\)-contractions in \(\|\cdot\|_\infty\), with fixed points \(\mathbf{v}_\pi\) and \(\mathbf{v}_\ast\). \(\mathbf{u} \ge \mathbf{v}\) means \(u(s) \ge v(s)\) for every \(s\).
Proof: the policy improvement theorem
Assume \(q_\pi(s, \pi'(s)) \ge v_\pi(s)\) for all \(s\). Expand \(v_\pi(s)\) by repeatedly applying the assumption at the state reached, following \(\pi'\):
The tail term \(\gamma^k \mathbb{E}_{\pi'}[v_\pi(S_{t+k})]\) vanishes as \(k \to \infty\) because \(v_\pi\) is bounded and \(\gamma < 1\). In operator form the proof is two lines: \(T^{\pi'}\mathbf{v}_\pi \ge \mathbf{v}_\pi\), and \(T^{\pi'}\) is monotone (it preserves \(\ge\)), so \(\mathbf{v}_\pi \le T^{\pi'}\mathbf{v}_\pi \le (T^{\pi'})^2\mathbf{v}_\pi \le \cdots \to \mathbf{v}_{\pi'}\).
Policy iteration terminates at an optimal policy
Each iteration either leaves the policy unchanged or produces \(\mathbf{v}_{\pi_{k+1}} \ge \mathbf{v}_{\pi_k}\) with strict inequality somewhere (keep the current action unless another is strictly better, so the policy changes only when some state strictly improves). No policy can repeat, and there are at most \(|\mathcal{A}|^n\) deterministic policies, so the process stops. At the stopping point \(\pi\) is greedy with respect to \(\mathbf{v}_\pi\), so \(\mathbf{v}_\pi = T^\pi\mathbf{v}_\pi = T^\ast\mathbf{v}_\pi\): \(\mathbf{v}_\pi\) is the unique fixed point of \(T^\ast\), that is \(\mathbf{v}_\ast\).
Derivation: when to stop value iteration, and how good the greedy policy is
From the change per sweep to the distance to \(v_\ast\). With \(\mathbf{v}_{k+1} = T^\ast\mathbf{v}_k\) and \(T^\ast\mathbf{v}_\ast = \mathbf{v}_\ast\):
So a sweep that changes nothing by more than \(\delta\) leaves you within \(\gamma\delta/(1-\gamma)\) of the truth. Note the factor: at \(\gamma = 0.99\) a change of \(10^{-3}\) only guarantees an error below \(0.099\).
From a value error to a policy loss. Let \(\|\mathbf{v} - \mathbf{v}_\ast\| \le \varepsilon\) and let \(\pi\) be greedy with respect to \(\mathbf{v}\), so \(T^\pi\mathbf{v} = T^\ast\mathbf{v}\). Then
Combining the two: stop when \(\|\mathbf{v}_{k+1} - \mathbf{v}_k\| < \varepsilon(1-\gamma)/(2\gamma)\);
then \(\mathbf{v}_{k+1}\) is within \(\varepsilon/2\) of \(\mathbf{v}_\ast\) and its greedy policy is
within \(\varepsilon\) of optimal (Puterman, 1994, Theorem 6.3.1, gives the same rule). The
value_iteration function in Build it uses exactly this test.
Cost summary
| Method | Cost per iteration | Iterations |
|---|---|---|
| Exact evaluation | \(O(n^3)\) (linear solve) | 1 |
| Iterative evaluation / value-iteration sweep | \(O(n^2\lvert\mathcal{A}\rvert)\) dense, \(O(n\lvert\mathcal{A}\rvert b)\) with \(b\) successors per action | \(\approx \ln(1/\varepsilon')/(1-\gamma)\) for relative error \(\varepsilon'\) |
| Policy iteration | \(O(n^3 + n^2\lvert\mathcal{A}\rvert)\) | \(O\big(\frac{n\lvert\mathcal{A}\rvert}{1-\gamma}\log\frac{1}{1-\gamma}\big)\) worst case (Scherrer, 2013); a handful in practice |
| Linear programming | polynomial in the input size | 1 LP (dual form on the MDP page) |
History¶
From RAND to AlphaZero
Richard Bellman developed dynamic programming at the RAND Corporation in the early 1950s; his 1954 address The Theory of Dynamic Programming and his 1957 book Dynamic Programming set out the principle of optimality and the functional equation. In his autobiography, Eye of the Hurricane (1984), he said he chose the name to hide the mathematics from a Secretary of Defense hostile to research, since "dynamic" was a word not even a Congressman could object to (historians note he was using the term before Wilson took office, so the story is at least tidied up). Ronald Howard's Dynamic Programming and Markov Processes (1960) introduced policy iteration. Puterman and Shin (1978) unified the two classic methods as modified policy iteration, and Puterman and Brumelle (1979) showed policy iteration is Newton's method. Bertsekas developed asynchronous and distributed DP in the 1980s. Then the AI community connected DP to learning: Moore and Atkeson's prioritised sweeping (1993), Barto, Bradtke and Singh's real-time DP (1995), and Bertsekas and Tsitsiklis's Neuro-Dynamic Programming (1996), which named the combination of DP with neural network approximation. On the theory side, Ye (2011) settled a long-open question by proving that policy iteration is strongly polynomial for a fixed discount, and Scherrer (2013) tightened the bound.
Build it¶
Policy evaluation, policy iteration and value iteration for any finite MDP given as arrays
P[s, a, s'] and R[s, a], applied to the gridworld and to Fresh/Tired (NumPy):
import numpy as np
def gridworld(n=4):
"""Sutton & Barto Example 4.1 as arrays: P[s, a, s'], R[s, a]. Corners are terminal."""
S = n * n; P = np.zeros((S, 4, S)); R = np.full((S, 4), -1.0)
for s in range(S):
r, c = divmod(s, n)
for a, (dr, dc) in enumerate([(-1, 0), (0, 1), (1, 0), (0, -1)]): # up right down left
r2, c2 = r + dr, c + dc
s2 = r2 * n + c2 if 0 <= r2 < n and 0 <= c2 < n else s
P[s, a, s2] = 1.0
for t in (0, S - 1): # terminal: absorbing, zero reward
P[t] = 0; P[t, :, t] = 1; R[t] = 0
return P, R
def evaluate(P, R, pi, g, tol=1e-8): # iterative policy evaluation, pi[s, a] = prob
v, sweeps = np.zeros(len(R)), 0
while True:
v_new = (pi * (R + g * P @ v)).sum(1); sweeps += 1
if np.abs(v_new - v).max() < tol: return v_new, sweeps
v = v_new
def policy_iteration(P, R, g):
pi = np.full(R.shape, 1 / R.shape[1]); it = 0
while True:
v, _ = evaluate(P, R, pi, g); it += 1
best = (R + g * P @ v).argmax(1) # greedy improvement (first max on ties)
new = np.eye(R.shape[1])[best]
if (new == pi).all(): return v, best, it
pi = new
def value_iteration(P, R, g, tol=1e-8):
v, k = np.zeros(len(R)), 0
while True:
v_new = (R + g * P @ v).max(1); k += 1
if np.abs(v_new - v).max() < tol * (1 - g) / (2 * g): # => greedy policy is tol-optimal
return v_new, (R + g * P @ v_new).argmax(1), k
v = v_new
P, R = gridworld()
v, sweeps = evaluate(P, R, np.full((16, 4), 0.25), g=1.0, tol=1e-4)
print(f"random policy, {sweeps} sweeps:\n{v.reshape(4, 4).round(1)}")
v, best, it = policy_iteration(P, R, g=1.0)
print(f"policy iteration: {it} iterations\n{v.reshape(4, 4)}")
arrows = np.array(list("^>v<"))[best]; arrows[[0, 15]] = "*"
print(arrows.reshape(4, 4))
F = np.zeros((2, 2, 2)); FR = np.array([[2.0, 0.0], [1.0, 0.0]]) # Fresh/Tired MDP
F[0, 0], F[0, 1], F[1, 0], F[1, 1] = [0.7, 0.3], [1, 0], [0, 1], [0.8, 0.2]
for name, solve in [("PI", policy_iteration), ("VI", value_iteration)]:
v, best, n = solve(F, FR, 0.9)
print(f"{name} Fresh/Tired: v = {v.round(3)}, policy = {np.array(['work', 'rest'])[best]}, {n} iterations")
random policy, 173 sweeps:
[[ 0. -14. -20. -22.]
[-14. -18. -20. -20.]
[-20. -20. -18. -14.]
[-22. -20. -14. 0.]]
policy iteration: 3 iterations
[[ 0. -1. -2. -3.]
[-1. -2. -3. -2.]
[-2. -3. -2. -1.]
[-3. -2. -1. 0.]]
[['*' '<' '<' 'v']
['^' '^' '^' 'v']
['^' '^' '>' 'v']
['^' '>' '>' '*']]
PI Fresh/Tired: v = [15.046 13.211], policy = ['work' 'rest'], 3 iterations
VI Fresh/Tired: v = [15.046 13.211], policy = ['work' 'rest'], 207 iterations
The whole algorithm is the expression R + g * P @ v: an array of shape (S, A) holding the
one-step look-ahead \(r(s,a) + \gamma\sum_{s'}p(s'\mid s,a)v(s')\) for every state and action.
Evaluation averages it under the policy, improvement and value iteration take its max. Value
iteration needs 207 sweeps here, more than the 136 needed for a \(10^{-6}\) change, because the
stopping test asks for a policy guaranteed within \(10^{-8}\) of optimal.
Things to try
- Switch
evaluateto in-place updates (loop over states, write intovdirectly) and count the sweeps for the random policy. Then sweep the states in reverse order. Which is faster, and why? - Implement modified policy iteration with \(m\) evaluation sweeps per improvement. Plot total work (counting a max-sweep as \(|\mathcal{A}|\) times an evaluation sweep) against \(m\) on a random MDP with \(\gamma = 0.99\).
- The gambler's problem (Sutton and Barto, Example 4.3): capital \(s \in \{1..99\}\), stake any amount up to \(\min(s, 100 - s)\), win with probability 0.4, reward 1 only on reaching 100. Run value iteration and plot the optimal stake against capital. Why is the policy so jagged, and why are there many optimal policies?
- Run policy iteration on the gridworld with \(\gamma = 1\) starting from "always move up". What happens, and how does \(\gamma = 0.99\) fix it?
- Build a 30 × 30 maze and compare plain value iteration with prioritised sweeping by the number of single-state updates needed.
In practice¶
- Tabular DP is still the right tool whenever the model is known and the state space fits in memory: inventory, maintenance and queueing problems, small games, and as the ground truth you test learning algorithms against. Up to millions of states with sparse transitions, value iteration in NumPy or a sparse linear solver for policy evaluation is fast.
- Prefer policy iteration for long horizons (\(\gamma \ge 0.99\)): its iteration count barely depends on \(\gamma\), while value iteration's grows like \(1/(1-\gamma)\).
- Stop on the policy, not the values, when the policy is what you need: check whether the greedy policy changed over the last few sweeps, and use the \(2\gamma\varepsilon/(1-\gamma)\) bound to certify it.
- Discretising continuous states turns DP back on, but the grid size explodes with dimension. Beyond about four or five continuous dimensions, approximate the value function instead.
- Use DP to debug learning code. On any small environment, compute \(q_\ast\) exactly with value iteration and compare your Q-learning or TD estimates against it, as you can for the cliff-walking values on the Q-learning page.
Check yourself¶
What is the difference between a full backup and a sample backup, and which does DP use?
A full (expected) backup computes \(\sum_{s',r} p(s',r\mid s,a)[r + \gamma V(s')]\), averaging over every possible successor with its true probability; it needs the model. A sample backup uses one observed transition, \(r + \gamma V(s')\), and moves the estimate a step towards it. DP uses full backups. TD learning and Q-learning use sample backups, which is why they need no model but do need many updates and a step size.
In value iteration on Fresh/Tired, the greedy policy is optimal from sweep 3 while the value error is still above 10. How can the policy be right when the values are so wrong?
The greedy choice depends only on which action has the larger look-ahead value. Early in value iteration the error is mostly the missing tail of future rewards, which is similar for both actions, so it shifts both \(q\)-values by a similar amount and leaves the comparison intact. Once the remaining difference in errors between actions is smaller than the true gap between them (here \(q_\ast(T,\text{rest}) - q_\ast(T,\text{work}) = 0.32\)), the greedy action is correct.
State the policy improvement theorem. Why does it imply that policy iteration ends at an optimal policy?
If \(q_\pi(s,\pi'(s)) \ge v_\pi(s)\) for all \(s\), then \(v_{\pi'}(s) \ge v_\pi(s)\) for all \(s\). Greedy improvement satisfies the condition, so each iteration weakly improves every state, and strictly improves some state unless the policy is already greedy with respect to its own values. A finite MDP has finitely many deterministic policies and none can repeat, so the process ends. When it ends, \(v_\pi(s) = \max_a q_\pi(s,a)\) for all \(s\), which is the Bellman optimality equation; its unique solution is \(v_\ast\).
Value iteration's last sweep changed no value by more than 0.001, with γ = 0.99. How far can the values be from v*, and how far can the greedy policy's value be from optimal?
\(\|\mathbf{v}_{k+1} - \mathbf{v}_\ast\| \le \frac{\gamma}{1-\gamma}\times 0.001 = 99 \times 0.001 = 0.099\). The greedy policy's loss is at most \(\frac{2\gamma\varepsilon}{1-\gamma}\) with \(\varepsilon = 0.099\): \(2 \times 0.99 \times 0.099 / 0.01 \approx 19.6\). Small changes per sweep say little when \(\gamma\) is close to 1; that is why the stopping threshold scales with \((1-\gamma)/(2\gamma)\).
Why is policy iteration's iteration count nearly independent of γ while value iteration's grows like 1/(1−γ)?
Value iteration is a fixed-point iteration whose error contracts by exactly \(\gamma\) per sweep, so it needs about \(\ln(1/\varepsilon)/(1-\gamma)\) sweeps. Policy iteration is Newton's method on \(T^\ast\mathbf{v} - \mathbf{v} = 0\): each iteration solves the local linearisation exactly, which converges quadratically near the solution, and the number of policy changes needed is governed by the structure of the MDP rather than the horizon. (The worst-case bounds still carry a \(1/(1-\gamma)\) factor, but typical counts are a handful.) The cost moves into each iteration: a linear solve whose conditioning worsens as \(\gamma \to 1\).
Show that asynchronous value iteration that updates one state at a time still converges if every state is updated infinitely often.
Updating a single state \(s\) with \(T^\ast\) replaces \(v(s)\) by \((T^\ast\mathbf{v})(s)\), whose distance to \(v_\ast(s) = (T^\ast\mathbf{v}_\ast)(s)\) is at most \(\gamma\|\mathbf{v} - \mathbf{v}_\ast\|_\infty\), and leaves other states unchanged. So no update increases the max-norm error. After a stretch of updates in which every state has been updated at least once, every coordinate's error is at most \(\gamma\) times the max error at the start of the stretch. Infinitely many such stretches drive the error to zero.
Hard: the approximate policy iteration bound is 2γε/(1−γ)². Where does each factor of 1/(1−γ) come from, and what does it suggest about long-horizon RL with neural critics?
One factor comes from turning a per-iteration evaluation error \(\varepsilon\) into a loss for the greedy policy: a wrong value in one state misleads choices that compound over an effective horizon of \(1/(1-\gamma)\) steps (the same factor as in the \(2\gamma\varepsilon/(1-\gamma)\) greedy-loss bound). The second comes from accumulation across iterations: errors made at each iteration feed into the next evaluation and decay only at rate \(\gamma\), so their sum is up to \(1/(1-\gamma)\) times one error. With \(\gamma = 0.99\) the multiplier is about \(2 \times 10^4\). It suggests that critics must be very accurate, or that horizons should be kept short (a lower \(\gamma\), \(n\)-step returns, or look-ahead search that reduces reliance on the critic), which is what practical deep RL does.
Go deeper¶
Papers and primary sources
- The theory of dynamic programming — Richard Bellman, Bulletin of the AMS 1954. The founding exposition: the principle of optimality and the functional equation, in Bellman's words.
- Modified Policy Iteration Algorithms for Discounted Markov Decision Problems — Puterman and Shin, Management Science 1978. The dial between value and policy iteration.
- The Simplex and Policy-Iteration Methods Are Strongly Polynomial for the Markov Decision Problem with a Fixed Discount Rate — Yinyu Ye, Mathematics of Operations Research 2011. Why policy iteration is never as slow as the counting bound suggests.
- Improved and Generalized Upper Bounds on the Complexity of Policy Iteration — Bruno Scherrer, 2013. The tightest iteration bounds for Howard's policy iteration; the introduction is a good survey.
- Prioritized sweeping: Reinforcement learning with less data and less time — Moore and Atkeson, Machine Learning 1993. Asynchronous DP that updates where it matters.
- Learning to act using real-time dynamic programming — Barto, Bradtke and Singh, Artificial Intelligence 1995. The bridge from planning to learning: DP only on states the agent visits.
- Finite-Time Bounds for Fitted Value Iteration — Munos and Szepesvári, JMLR 2008. What value iteration with a function approximator can guarantee, and the "inherent Bellman error" that limits it.
Videos and lectures
- RL Course by David Silver, Lecture 3: Planning by Dynamic Programming — DeepMind x UCL. Policy evaluation, policy and value iteration, and the contraction proof, worked on the same gridworld.
- Reinforcement Learning and Optimal Control videolectures — Dimitri Bertsekas, ASU. DP from the control-theory side, including the Newton-step view of policy iteration and AlphaZero.
Courses and books
- Reinforcement Learning: An Introduction, chapter 4 — Sutton and Barto, 2nd ed. 2018. The gridworld, Jack's car rental and the gambler's problem; read section 4.6 on GPI twice.
- A Course in Reinforcement Learning — Bertsekas, 2nd ed. 2025 (free download from the author's page). The most rigorous modern treatment of approximate DP, rollout and policy iteration.
- Algorithms for Reinforcement Learning — Csaba Szepesvári, 2010 (free). Chapter 1 covers the DP operators and their properties in 20 dense pages.
- Reinforcement Learning: Theory and Algorithms — Agarwal, Jiang, Kakade and Sun. Chapter 1 proves the convergence and complexity results for value and policy iteration.
Where this leads¶
- Monte Carlo and temporal-difference learning — drop the model: estimate the same values from sampled experience.
- Q-learning and DQN — value iteration on \(q\), with sample backups and then a neural network for the table.
- Actor-critic and PPO — approximate policy iteration with a learned critic and a policy network.
- Model-based RL and planning — when you have (or learn) a model, search from the current state instead of sweeping every state.