Part I · Foundations · Chapter 4
Bellman equations and dynamic programming
Solving an MDP when you know the rules: policy evaluation, policy iteration, value iteration.
Suppose someone hands you the complete rulebook of a world: every transition probability and every expected reward . You want the best possible policy. In Chapter 3 you learned to evaluate any policy you are given: write down the Bellman expectation equation and solve a linear system. So why not evaluate every policy and keep the best one?
Count them. The gridworld in this chapter’s demo has 22 cells where the agent must choose among 4 actions. That makes deterministic policies. At a million evaluations per second, you would finish in about seven months. Yet the algorithms in this chapter solve that gridworld exactly in about two dozen cheap passes over the grid, which takes a fraction of a millisecond. The trick is an idea Richard Bellman named in the 1950s: dynamic programming (DP). (“Programming” here means planning, as in “linear programming”, not writing code.) It is the mathematical core of everything that follows in this course. Q-learning, actor-critic, PPO and even the critic in RLHF are all approximate, sampled versions of what you will do here exactly.
What you bring from Chapter 3
Here is a quick recap, in the notation of the notation page. A policy has a state-value function (expected return from if you follow ) and an action-value function (expected return if you take first and then follow ). They are related by
Substituting one into the other gives the Bellman expectation equation:
It is linear in . In matrix form it reads , so . That is how Chapter 3’s demo recomputed values live.
The first formula deserves a name of its own, because we will use it constantly. Given any vector of state values , the quantity is a one-step lookahead. It means: take action , collect the expected reward, then pretend that correctly scores wherever you land. Every algorithm in this chapter is built from this one computation.
A corridor to think with
Here is the small MDP we will compute by hand all chapter:
+0.5 ◄── [ A ] ◄──► [ B ] ◄──► [ C ] ──► +1
small exit big exit
There are three states, A, B, C, and two actions, left and right. Moves are deterministic. Walking left out of A ends the episode with reward . Walking right out of C ends it with . Every other move pays 0. (In the lab, the “exit” is an extra absorbing state with value 0.)
From A, should you grab the small prize now or walk two steps for the big one? Walking right earns on the third move, worth today. So it depends on the discount: for , and you should walk; for , and you should take the small exit. The crossover is at . This tiny example already shows the central fact: the best action in A depends on what you will do afterwards in B and C. Dynamic programming organizes that dependency.
The Bellman optimality equation
The principle of optimality
Think about driving routes. If the fastest route from Boston to Los Angeles passes through Chicago, then its Chicago-to-LA part must be the fastest route from Chicago to LA. If it weren’t, you could swap in the faster one and beat the “fastest” route. Bellman called this the principle of optimality: an optimal plan, from any point along it onward, is optimal for the problem that starts at that point.
So, to act optimally in you don’t need to search over whole futures. You need two things:
- the best value you can get from each possible next state, and
- a one-step choice of the action that leads to the best mix of immediate reward plus that future value.
Writing it down
Chapter 3 defined the optimal state-value function and optimal action-value function as the best achievable over all policies, and stated the equation they satisfy. Here we derive that equation from the principle of optimality, and then learn to solve it. The definitions are:
The principle of optimality turns into equations. If you take in and then behave optimally, you get
and behaving optimally in means picking the best : . Combine the two:
These are the Bellman optimality equations for and . Compare them with the expectation equation above. The only change is that the average over actions, , became a maximum, . That small change has a big consequence. The max makes the equation nonlinear, so there is no single matrix inversion that solves it. We need an iterative method, and the rest of the chapter builds two of them.
Solving the corridor by hand
For a small problem you can guess and check. Take and guess “always go right”. Then , , . Now check each state against the optimality equation:
| State | left: | right: | max | equals guess? |
|---|---|---|---|---|
| A | yes | |||
| B | yes | |||
| C | yes |
The guess satisfies the equation in every state. Later in the chapter we prove the equation has exactly one solution, so this is . The table’s left and right columns are exactly and .
Now repeat with . “Always right” gives . In A the check fails: . The equation itself tells you to switch A to left. With that switch, , and every state checks out.
Acting greedily on is optimal
Once you have , the optimal policy takes one line. In each state, pick the action with the best one-step lookahead:
A policy chosen this way is called greedy with respect to . “Greedy” usually sounds short-sighted, so why is it optimal here? Because has already folded the whole future into a single number per state. A one-step lookahead on top of the right value function is a full lookahead. That is the real magic of value functions: they turn long-horizon planning into a one-step decision. (The proof is below, in the contraction section, once we have the tools.)
Three facts follow, and all of them matter later in the course:
- One policy is best everywhere at once. The greedy policy achieves in every state simultaneously. You never have to trade off “good from A” against “good from B”.
- That policy can be deterministic. Randomizing never helps when you know the model. (Stochastic policies matter for exploration and for learning, as in Chapter 7, but not for optimality here.)
- lets you act without the model. Acting greedily on needs and to do the lookahead. Acting greedily on needs only an argmax over a table. That is why the model-free methods of Chapter 5 learn rather than .
Quick check In the corridor with γ = 0.8, which exit should the agent standing in A head for?
Walking right is worth γ² · 1 = 0.64 today, which beats 0.5. The two are equal at γ = 1/√2 ≈ 0.71; below that, take the small exit.
Policy evaluation by sweeping
We’ll build up to solving the optimality equation in two steps. The first is a better way to do Chapter 3’s job: computing for a fixed policy.
A linear solve costs about operations. That is fine for 22 states and hopeless for a million. There is a cheaper way. Take the Bellman expectation equation, which satisfies exactly, and use it as an update rule on a guess:
One pass of this update over all states is a sweep, and each single-state update is called a backup (information is “backed up” from successor states to their predecessor). Start from and sweep until nothing changes. This is iterative policy evaluation. You met it briefly at the end of Chapter 3. Here we look at how it behaves, and later in the chapter we prove that it converges.
Worked example: “always left” in the corridor
Take and the policy that always goes left. Each state’s update reads one neighbor:
| sweep | |||
|---|---|---|---|
| 0 | 0 | 0 | 0 |
| 1 | 0.5 | 0 | 0 |
| 2 | 0.5 | 0.45 | 0 |
| 3 | 0.5 | 0.45 | 0.405 |
| 4 | 0.5 | 0.45 | 0.405 |
Watch how the information moves. The reward at the left exit reaches A in sweep 1, B in sweep 2, and C in sweep 3. Each sweep pushes news one step further back. In a deterministic chain the values become exact after (chain length) sweeps. When transitions are random, every state feeds back into every other through many paths, so the values only converge in the limit, geometrically fast. You’ll see why in the contraction section.
Iterative policy evaluation
input: P, r, policy π, discount γ, tolerance tol
1. V ← 0 (any start works)
2. repeat:
3. for every state s:
4. V_new(s) ← Σ_a π(a|s) [ r(s,a) + γ Σ_s' P(s'|s,a) V(s') ]
5. Δ ← max_s |V_new(s) − V(s)|
6. V ← V_new
7. until Δ < tol
8. return V
Quick check A deterministic chain of states with a single reward at one end, like the corridor's exits. From the farthest state it takes 5 moves to collect that reward. You run synchronous policy-evaluation sweeps starting from V = 0. After which sweep does the farthest state first get a nonzero value?
Each synchronous sweep moves information one step backwards along the chain. The state one move from the reward learns in sweep 1 (like A in the table above), and the state 5 moves away learns in sweep 5.
Policy improvement
Now we have . Can we use it to find a better policy?
Here is the idea. Stand in state and consider deviating from for a single step: take action now, then go back to following . The value of that one-step deviation is exactly . Suppose some has . Then deviating once is better than not deviating. It would be odd if deviating every time you visit (and doing the same in other states) were worse. It isn’t, and that is the theorem.
∂ Proof of the policy improvement theorem
Let be deterministic (the stochastic case is the same with an extra average over actions). Write for the expectation over trajectories that start in and follow . Start from the assumption and expand one step:
Apply the assumption again, this time at : . Then expand that one step:
Repeating times:
Values are bounded (rewards are bounded and ), so the last term is at most . The sum converges to the return of . Letting gives .
For strictness, suppose at some . Since we now know everywhere,
The natural choice of is to be greedy everywhere at once:
This satisfies the theorem’s condition automatically, because . So greedy improvement never makes things worse.
What if it doesn’t make things better either? Suppose the greedy policy is no better than , so . By the strict part of the theorem, no state can have , because that state’s value would have gone up. Combined with , this gives in every state. Written out, that is exactly the Bellman optimality equation. So and was already optimal. Greedy improvement either strictly improves the policy somewhere or certifies that it is optimal.
Worked example
Improve “always left” in the corridor (). From the table above, . The one-step lookaheads are:
| State | greedy | ||
|---|---|---|---|
| A | left | ||
| B | left | ||
| C | right |
Only C switches. Notice that B doesn’t switch yet, even though right is ultimately better from B. Under the current policy, C is a poor place to be: its value 0.405 comes from walking all the way back left. Improvement only trusts the current values, so it fixes the state whose problem is visible right now.
Policy iteration
Alternate the two steps: evaluate, improve, evaluate, improve, until the policy stops changing. That is policy iteration (Howard, 1960).
Policy iteration
1. π ← any deterministic policy
2. repeat:
3. V ← evaluate(π) # policy evaluation
4. for every state s: # policy improvement
5. π_new(s) ← argmax_a [ r(s,a) + γ Σ_s' P(s'|s,a) V(s') ]
6. (keep π(s) unless another action is strictly better)
7. stable ← (π_new == π); π ← π_new
8. until stable
9. return π, V # π is optimal and V = V*
Here is the corridor run from “always left” (L = left, R = right):
| iteration | policy (A, B, C) | states that switch | |||
|---|---|---|---|---|---|
| 0 | L, L, L | 0.5 | 0.45 | 0.405 | C |
| 1 | L, L, R | 0.5 | 0.45 | 1 | B |
| 2 | L, R, R | 0.5 | 0.9 | 1 | A |
| 3 | R, R, R | 0.81 | 0.9 | 1 | none: optimal |
The good news about the big exit travels backward, one state per iteration, until A is convinced too.
Why it must stop. Each iteration either stops or produces a policy that is at least as good everywhere and strictly better somewhere. So no policy can ever appear twice. There are finitely many deterministic policies (), so the loop must end, and when it ends the policy is optimal. (Exercise 4.4 makes this precise. It also explains line 6: without the “strictly better” rule, round-off can flip a state between two equally good actions forever.) The bound is absurdly pessimistic. In practice policy iteration converges in a handful of iterations, even on large problems. The catch is that each iteration contains a full policy evaluation.
Value iteration
Policy iteration spends most of its time in step 3, evaluating policies to high precision. Yet early policies are bad and about to be replaced, so precise values for them are wasted effort. What if we evaluate with just one sweep, then improve, then do one more sweep, and so on? Say the current values are . The improvement step picks, in each state, the action with the largest lookahead . The single evaluation sweep for that new policy, starting from , then computes exactly that same lookahead for the chosen action. So the new value is the largest lookahead. Improvement and the one evaluation sweep merge into a single update:
This is value iteration. Look at it closely: it is the Bellman optimality equation, used as an update rule. Policy evaluation turned the expectation equation into an update. Value iteration does the same to the optimality equation.
Value iteration
input: P, r, discount γ, tolerance tol
1. V ← 0 (any start works)
2. repeat:
3. for every state s:
4. V_new(s) ← max_a [ r(s,a) + γ Σ_s' P(s'|s,a) V(s') ]
5. Δ ← max_s |V_new(s) − V(s)|
6. V ← V_new
7. until Δ < tol
8. π(s) ← argmax_a [ r(s,a) + γ Σ_s' P(s'|s,a) V(s') ] # extract the greedy policy
9. return V, π
Worked example: value iteration on the corridor
With and , each sweep computes , , and :
| sweep | max change | greedy policy w.r.t. | |||
|---|---|---|---|---|---|
| 0 | 0 | 0 | 0 | ||
| 1 | 0.5 | 0 | 1 | 1.0 | L, R, R |
| 2 | 0.5 | 0.9 | 1 | 0.9 | R, R, R (already optimal) |
| 3 | 0.81 | 0.9 | 1 | 0.31 | R, R, R |
| 4 | 0.81 | 0.9 | 1 | 0 | R, R, R |
Two things to notice.
has a meaning of its own. Starting from , is the best expected discounted return you can collect in steps from . After one sweep, A knows it can grab 0.5 and C knows it can grab 1. B needs two steps to reach anything. Value iteration solves ever-longer finite-horizon problems, and the horizon grows by one each sweep. Discounting makes the far future matter less and less, which is why the sequence converges.
The policy settles before the values do. After sweep 2, is still wrong (the truth is 0.81), yet the greedy policy is already optimal. The argmax only needs the ranking of actions to be right, not the values. Exercise 4.6 turns this into a theorem, and the demo shows it on a bigger problem: the arrows freeze long before the numbers do.
Quick check Value iteration can be read as policy iteration in which the evaluation step is cut down to…
One evaluation sweep under the greedy policy, merged with the improvement, is exactly the max-backup V(s) ← maxₐ [r + γ Σ P V]. Policy iteration is the other extreme, with evaluation run to convergence.
Watch it run
The demo runs value iteration on the gridworld from the introduction. There is a goal worth (right edge), a row of four pits worth , and a three-cell wall. The reward is paid on the step that enters the goal or a pit, and the episode then ends. With slip probability , the agent moves sideways (perpendicular to the intended direction, each way) instead of where it intended. Bumping into a wall or the edge leaves it where it is. Rows are counted from the top and columns from the left; the inspector shows the coordinates of the selected cell. Each cell’s color shows its current value , and the arrows show the greedy action(s). When several actions tie, all of them are drawn, so at the start you see crosses: no preference yet. The inspector shows the four one-step lookaheads for the selected cell, with the arithmetic for the best one. You can check every number against the backup formula. The chart plots the max change on a log axis, together with a dashed line falling like . The next section explains why that line is there.
● max change ‖Vk − Vk−1‖∞- - contraction bound δ1·γk−1
What to try: press Step a few times and watch value spread outward from the goal, one cell per sweep, while the cells next to the pits learn to avoid them. Press Play and note the sweep at which the arrows stop changing, compared with the sweep at which the values converge. Raise slip to 0.3: most cells beside the pits stop walking along them, and several start 'hugging the wall', pushing into a wall or the edge so that only the safe sideways slips move them. Then set the reward per step to −0.1 and watch the agent take the risky shortcut again. Press Random start: the values begin anywhere, yet end at the same V*. Switch to Policy iteration and count iterations versus evaluation sweeps. Tap with Wall/Goal/Pit to redesign the grid.
A few things are worth seeing for yourself. With the defaults (, slip ), value iteration stops (max change below ) after 24 sweeps, but the arrows stop changing at sweep 10. With slip 0, the value of the cell in row 3, column 1 is exactly . The goal is 5 moves away, and the reward arrives on the 5th move, so it is discounted 4 times. With slip it falls to : the risk of sliding into a pit costs you.
Why it works: the Bellman operator is a contraction
We have three algorithms and some faith that they converge. Now for the proof. It is short and beautiful, and it also answers the questions we skipped. Does the optimality equation have a solution? Is it unique? Is the greedy policy really optimal? How many sweeps do we need?
Operators on value vectors
Think of a value function as a vector . Define two maps from vectors to vectors, the Bellman expectation operator and the Bellman optimality operator :
Now everything is compact. The Bellman equations say that and are fixed points: and . Iterative policy evaluation is , and value iteration is . The question “does it converge?” becomes “does repeatedly applying the map approach a fixed point?”
Contraction in the sup norm
Measure the distance between two value functions by the largest disagreement in any state, the sup norm:
Here is why, in words. The backup builds each state’s new value from an average of next-state values (weights ), then multiplies by . Averaging can’t increase the worst-case disagreement, and the factor shrinks it. The max over actions doesn’t spoil this, because two maxima can’t differ by more than the largest difference between their arguments. The rewards are the same for both guesses, so they cancel.
∂ Proof that the Bellman optimality operator is a γ-contraction
Lemma. For any two functions on a finite set, .
Proof. Suppose without loss of generality that , and let be a maximizer of . Then .
Theorem. .
Proof. Fix a state . Apply the lemma with and the same with . The rewards cancel in :
The weights are nonnegative and sum to 1, so the weighted sum is at most the largest :
This holds for every . Take the max over on the left. The same argument without the lemma (an average over instead of a max) proves it for ; that’s Exercise 4.3.
Banach’s fixed-point theorem
A map that shrinks all distances by a fixed factor below one has a remarkable property.
∂ Complete proof of Banach's fixed-point theorem
Let , starting from any . Write for the sup norm.
Step 1: successive steps shrink geometrically. , so by induction .
Step 2: the sequence is Cauchy. For , by the triangle inequality and a geometric series,
which goes to 0 as , uniformly in .
Step 3: it has a limit. with any norm is complete: every Cauchy sequence converges. Call the limit .
Step 4: the limit is a fixed point. A contraction is Lipschitz, hence continuous. So .
Step 5: it is the only fixed point. If and , then . Since , this forces .
Step 6: the rate. .
What this buys us
Apply Banach to and to :
- Policy evaluation converges to from any start. You also get, for free, that the Bellman expectation equation has a unique solution. That is the invertibility of from Chapter 3, seen from a different angle.
- The optimality equation has exactly one solution, and value iteration converges to it from any start. That’s why the guess-and-check in the corridor was legitimate, and why the demo’s “Random start” always ends at the same values.
- The rate is geometric, with ratio γ. On a log axis, the error falls at least as fast as a straight line with slope per sweep. The same bound holds for the change between successive sweeps (Step 1 of the proof). The change is what the demo plots, since unlike the error it can be computed without knowing , and the dashed line is its bound .
How many sweeps does that mean? To shrink the initial error by a factor , you need , i.e.
For , that is 132 sweeps at and 1,375 at . The factor is the effective horizon from Chapter 3 again. Information must travel about that many steps, one step per sweep, before far-away rewards stop mattering.
We still need to close one gap. We defined as “the best over all policies” and then wrote down an equation it should satisfy. Is the unique solution of that equation really the best you can do, and does greedy play achieve it?
∂ Why the fixed point of T* is the optimal value, and greedy play achieves it
Let be the unique fixed point of . We use two easy properties of the operators.
- Max beats average: for every and every (componentwise).
- Monotonicity: if componentwise, then , because the weights are nonnegative.
No policy beats . For any stationary policy : . Apply to both sides of and use monotonicity: . Chaining, for all . The right side converges to by Banach, so .
The greedy policy achieves . Let be greedy with respect to . By definition of greedy, . So is a fixed point of . That operator is also a contraction, so its fixed point is unique, and that fixed point is . Hence .
Together: , and the deterministic greedy policy attains it in every state simultaneously. (A longer argument, in Puterman’s book, shows that even non-stationary or history-dependent policies can’t do better in a finite MDP.)
Quick check Value iteration with γ = 0.9 starts from a guess whose worst-state error is 10. What does the contraction property guarantee about the worst-state error after 20 sweeps?
The error is at most γ²⁰ · 10 = 0.9²⁰ · 10 ≈ 0.12 · 10 ≈ 1.2. The bound holds from any starting point; that's Banach's theorem.
A stopping rule you can trust. In practice you don’t know , but you can see the change . The contraction property links the two (Exercise 4.5):
So to be within of , stop when the change drops below . That threshold is much smaller than when is close to 1.
And policy iteration? It also converges, and usually in far fewer iterations than value iteration has sweeps. It is a classical result (Puterman and Brumelle, 1979) that policy iteration is Newton’s method applied to the equation . Like Newton’s method, it converges very fast once it is close. Each Newton step, however, needs a full policy evaluation. In the demo’s defaults, value iteration takes 24 sweeps, while policy iteration takes 8 iterations but over 300 evaluation sweeps. Which one is cheaper depends on the problem and on how you evaluate.
Generalized policy iteration
Step back and look at the two algorithms side by side. Both alternate two processes that pull against each other:
evaluation: make V consistent with π (V → V^π)
┌───────────────────────────────────────────────────┐
│ ▼
π V
▲ │
└───────────────────────────────────────────────────┘
improvement: make π greedy with respect to V
Evaluation makes the value function agree with the policy, and that usually makes the policy no longer greedy. Improvement makes the policy greedy, and that makes the value function out of date. Each step undoes some of the other’s work, yet together they converge to the only pair that is consistent both ways: and a greedy . Policy iteration runs evaluation to convergence. Value iteration runs one sweep. Modified policy iteration runs sweeps, anything in between, and works for every . Sutton and Barto call this whole family generalized policy iteration (GPI): any interleaving of (possibly partial) evaluation and (possibly partial) improvement.
The updates don’t even have to be organized into sweeps. Asynchronous DP backs up states one at a time, in any order, using the latest values (Gauss–Seidel taken to its logical end). It still converges as long as every state keeps getting updated. This frees you to spend computation where it matters. Prioritized sweeping updates first the states whose values are changing most. Real-time DP updates the states an agent actually visits as it moves through the world. That last idea, backing up the states along real experience, is a short step from the model-free learning of Chapter 5.
GPI is the pattern behind almost all of reinforcement learning, so it’s worth naming where each later algorithm puts its two halves:
| Method | Evaluation | Improvement |
|---|---|---|
| Policy / value iteration (this chapter) | exact backups with the model | greedy argmax |
| SARSA, Q-learning (Ch 5) | sampled backups of | ε-greedy w.r.t. |
| DQN (Ch 6) | a neural fitted to sampled backups | greedy w.r.t. the network |
| Actor-critic (Ch 8) | the critic learns | a small policy-gradient step for the actor |
| PPO (Ch 9) | advantage estimates from a critic | a clipped, conservative policy step |
What dynamic programming cannot do
DP is exact and elegant, and in practice you almost never get to use it directly. There are two reasons.
It needs the model. Every backup computes , so you must know and . A robot doesn’t know the physics of its gripper to that precision. A game-playing agent may know the rules but not the opponent. Usually all we can do is try things and see what happens. Chapter 5 replaces the expected backup with a backup from a single sampled transition, which turns DP into learning.
It needs to touch every state, every sweep. One sweep costs about (number of possible next states). That is fine for 22 cells and not fine for interesting problems. A robot arm with 10 joints, each discretized into 100 positions, has states. Backgammon has roughly positions, and Go about . Bellman himself coined the name for this: the curse of dimensionality. The number of states grows exponentially with the number of variables that describe a state. Chapter 6 answers it with function approximation: instead of a table with one entry per state, a neural network that generalizes across similar states.
There is also a subtle requirement hiding in the math: . With , the operators are no longer contractions. Values can be infinite in tasks that never end, and the fixed point can stop being unique. Exercise 4.7 explores what goes wrong and what people do instead. Episodic tasks in which every policy eventually terminates are fine. LLM responses are of this kind, which is why LLM RL often uses .
Summary
- The Bellman optimality equation says that optimal value is the best one-step lookahead on optimal future value. It is the expectation equation with the average over actions replaced by a max, which makes it nonlinear.
- Acting greedily on (or taking the argmax of ) is optimal, in every state at once, with a deterministic policy. Value functions turn long-horizon planning into one-step decisions.
- Iterative policy evaluation applies the expectation backup in sweeps. Information travels one step per sweep, like a relaxation method.
- Policy improvement theorem: acting greedily on gives a policy at least as good everywhere, and strictly better somewhere unless is already optimal. Policy iteration alternates evaluation and improvement and ends in finitely many iterations.
- Value iteration is the optimality equation used as an update. It equals policy iteration with one evaluation sweep, and is the optimal -step value. The greedy policy is often optimal long before the values converge.
- The Bellman operators are γ-contractions in the sup norm. By Banach’s theorem each has a unique fixed point, and iteration reaches it from any start, with error at most times the initial error, which takes about sweeps.
- Generalized policy iteration (interleaved evaluation and improvement, in any proportion and any order) is the template for nearly every RL algorithm in this course, including the ones used to train LLMs.
- DP needs the model and touches every state. Chapter 5 removes the first requirement by sampling, and Chapter 6 tackles the second with function approximation.
Exercises
(a) Which of these can you compute with a single linear solve, given and : for a fixed stochastic policy; for a fixed policy; ? Explain in one sentence each.
(b) A friend gives you for a gridworld but not the transition probabilities. Can you act optimally? What if they give you instead?
Solution
(a) : yes. The expectation equation is linear, so . : yes. Either compute first and then , or solve the linear system directly, where averages over . : no. The optimality equation contains , which is piecewise linear but not linear, so there is no single matrix to invert. (You could solve it as a linear program, a classic alternative to DP, but not with one linear solve.)
(b) With only , acting greedily requires the lookahead , which needs and . So you can’t, unless you can simulate the environment. With you just take , and no model is needed. has the lookahead “built in”. That’s why model-free control (Q-learning, Chapter 5) learns .
Make the corridor slippery: every move succeeds with probability 0.8, and with probability 0.2 the agent stays where it is (reward 0). Exits pay +0.5 (left of A) and +1 (right of C) only when the move succeeds. Use and .
(a) Write the one-step lookahead for all six state–action pairs in terms of .
(b) Compute and , and the max change after each sweep.
(c) What is the greedy policy with respect to ? Is it already optimal? (The exact is about .)
Hint
Solution
(a) Writing for and so on:
(b) Sweep 1 (): ; ; . So , max change .
Sweep 2 (using ):
- A: L ; R . So .
- B: L ; R . So .
- C: L ; R . So .
, max change (at B).
(c) Greedy with respect to :
- A: L ; R . So A goes right.
- B: R L . So B goes right.
- C: R L. So C goes right.
So the greedy policy is already “always right”, which is optimal. At , A’s right value beats left, . But is still far from . Once again the policy is right before the values are. (The decision at A is close at : 0.500 vs 0.485. One sweep earlier, A would still have chosen left.)
(a) Prove that .
(b) Prove that is monotone: componentwise implies .
(c) For , give a one-state MDP in which has infinitely many fixed points.
Hint
Solution
(a) The rewards cancel:
The weights are nonnegative and . So the absolute value is at most . Take the max over .
(b) If , every term is , so for every .
(c) One state , one action that loops back to with reward 0, and . Then for every number , so every vector is a fixed point. The “contraction” factor is 1, and Banach’s theorem says nothing. With the only fixed point is .
Prove that policy iteration, with the rule “switch an action only if the new one is strictly better”, stops after at most iterations, and that the final policy is optimal. Then explain what could go wrong without the “strictly better” rule.
Hint
Solution
Let be the improved version of . In every state, is either , with , or a strictly better action, with . By the policy improvement theorem, everywhere. If at least one state switched, the inequality is strict in that state, so .
So while the policy keeps changing, the value functions form a strictly increasing sequence: each is the previous one everywhere and somewhere. A policy can’t appear twice. If with , then , contradicting strict increase along . There are only deterministic policies, so after at most that many iterations no state switches.
When no state switches, no action beats the current one: for all . That is the Bellman optimality equation, whose unique solution is . So and is optimal.
Without the strict rule, take a state with two actions that are exactly tied in true value. Computed values carry round-off (or come from evaluation stopped at a tolerance), so the argmax can pick action 1 in one iteration and action 2 in the next, then back again. The value never changes, but the policy keeps changing, so “stop when the policy is stable” never fires. The strict rule (switch only if better by more than a tiny threshold) breaks the tie in favor of the incumbent. The lab’s policy_iteration uses a threshold of .
(a) Prove that for value iteration ,
(b) With , how small must the observed change be to guarantee that is within of in every state?
Hint
Solution
(a) Using , the contraction, and the triangle inequality:
Move the term to the left: . Divide by .
(b) We need , i.e. . The change must be a hundred times smaller than the accuracy you want. When is near 1, a small change between sweeps doesn’t yet mean you are close: the values may be creeping slowly toward something far away.
Let be the smallest gap between the best and the second-best action value in any state, where is the set of optimal actions in (ignore states where every action is optimal).
(a) Show that if , then every greedy action with respect to is optimal.
(b) Compute for the corridor with . How close to does (a) require to be? Compare with from the value-iteration table, whose greedy policy is already optimal. What does this tell you about the bound?
Hint
Solution
(a) For every : . Take an optimal action and a non-optimal action in state . Then , and so
Every optimal action scores strictly higher under than every non-optimal one, so the argmax of is an optimal action.
(b) From the guess-and-check table, the gaps are: A: ; B: ; C: . So , and (a) requires . But has error at A, more than three times larger, and its greedy policy is still optimal. The condition is sufficient but not necessary. It guards against the worst case, where all the error lands on exactly the wrong actions. In typical problems the errors are correlated and largely cancel in the comparison between actions. You saw this in the demo and in the lab’s FrozenLake plot.
Consider a continuing task (no terminal states) with .
(a) Two states, X and Y. One action moves X → Y and Y → X, with reward +1 each step. What does value iteration from produce?
(b) Same states, but the rewards are 0. What are the solutions of the Bellman equation?
(c) Why does the corridor still work with ? What do people do for genuinely continuing tasks?
Hint
Solution
(a) : each sweep adds 1. The values diverge, because the return is an infinite sum of +1s. There is no finite fixed point to converge to.
(b) The equations are and , so every vector is a solution. The fixed point exists but is not unique. Iteration from stays at forever, so the answer depends on where you started. Both failures are what Exercise 4.3(c) predicts: with the operator is not a strict contraction.
(c) In the corridor, every sensible policy reaches an exit and the episode ends, so returns are finite sums. Some policies bounce between A and B forever, but they collect 0 and are never optimal, since rewards are nonnegative and exits are reachable. For episodic problems in which the optimal policy terminates and non-terminating policies are bad (sometimes called stochastic shortest-path problems), value iteration with still converges, though the proof is more delicate. Value iteration on the corridor at gives in 3 sweeps. For truly continuing tasks the standard options are: use (and accept that it changes the objective), or switch to the average-reward formulation, which optimizes the long-run reward per step and uses a “differential” value function relative to that average (Sutton & Barto, section 10.3).
In the demo, use value iteration and press Play after each change (press Restore grid first).
(a) With slip 0, read the value of the cell in row 3, column 1. Explain the number exactly.
(b) Raise slip to 0.3. Which way do the arrows in row 3 (beside the pits) point now? And in the bottom row? Explain both.
(c) Keep slip at 0.3 and set the reward per step to −0.1. What happens to the route, and why?
(d) Set γ to 0.5 (slip 0.1, step reward 0). Why do most cells look almost uncolored, with values near 0?
Solution
(a) . The shortest route is 5 moves (along row 3 to the goal), the +1 arrives on the 5th move, and the reward on move is discounted by .
(b) Each move along row 3 or row 5 has a 15% chance of slipping sideways into a pit, which costs plus the lost goal. The policy now avoids those moves wherever it can.
- Row 3: four of the five arrows point up. Cell (3,1) leaves the pit-lined row and takes the long route up the left column and along the top row. The detour costs only a few extra steps of discounting. Cell (3,5) steps up out of the row before turning toward the goal. Cells (3,2) and (3,3) sit under the wall, so “up” bumps into it and never moves them up. Its slips, though, move them left or right along the row, and a slip can never send them down into a pit. Only cell (3,4) still risks walking right.
- Row 5 (bottom): the middle four arrows point down, into the edge. The same trick applies: “down” never succeeds, its sideways slips move you along the row, and you can never slip up into a pit. The agent drifts randomly along the row until it reaches a corner column, where going up is safe.
Pushing into a wall on purpose, so that only harmless slips can move you, is a clever, slightly absurd strategy. The agent discovered it from the equations alone.
(c) The route goes back to running straight along the pits. With a cost of per step, the long detour costs more in step penalties than the pit risk does, so haste wins. Values also become negative far from the goal. The optimal policy depends on the whole reward function, which is why reward design matters so much (Chapter 19 is about what happens when it goes wrong).
(d) With the effective horizon is about 2 steps. A reward 5 steps away is worth even with no slipping; with slip it’s about 0.002. Far cells barely “see” the goal, and the agent is very myopic. Values also converge fast, in about 16 sweeps, because the contraction factor is small.
(a) With the defaults, press Play. At which sweep do the arrows stop changing, and when does value iteration stop? Is the solid curve of max changes above or below the dashed line? Why is that allowed?
(b) Press Random start a few times and play to convergence. What is the same every time, and which theorem promised it?
(c) Set γ to 0.99 and play (raise the speed). Compare the number of sweeps with the bound from the text, which says about 1,375 sweeps are needed to shrink the error by .
(d) Switch to Policy iteration with the defaults and play. Compare iterations and evaluation sweeps with value iteration’s sweep count. Which one did less total work here?
Hint
Solution
(a) The arrows freeze at sweep 10, and value iteration stops after 24 sweeps (max change below ). The solid curve lies on or below the dashed line. The contraction gives only an upper bound. Here the error shrinks faster, because probability leaks into the terminal goal and pits at every step (the effective rate is with ).
(b) The final values and arrows are identical every time. Banach’s theorem says has a unique fixed point and that iteration reaches it from any start. The first deltas are larger (the random start is far from ), but the slope on the log plot is the same.
(c) It takes about 90 sweeps, far fewer than 1,375. The bound assumes the worst case, a state from which you never terminate. Here every good path ends at the goal quickly, so the error decays at the rate , not . Problems with long or endless trajectories do approach the bound.
(d) Policy iteration stabilizes after 8 iterations, but those iterations use a little over 300 evaluation sweeps in total (each evaluation is warm-started from the previous values and run to a tight tolerance). Value iteration needs 24 sweeps. On this small, quickly-mixing grid, value iteration does less work. Policy iteration wins when evaluation is cheap relative to the number of iterations saved, for example when you can evaluate by an exact linear solve on a modest number of states, or when convergence is slow because γ is near 1. Modified policy iteration, with a few evaluation sweeps per improvement, sits between the two.
In the lab (exercises/04-dynamic-programming/), fill in dp.py:
- Task 1
q_from_v(P, R, V, gamma): the one-step lookahead. - Task 2
policy_evaluation(P, R, policy, gamma): synchronous sweeps until the max change is belowtol. - Task 3
greedy_policy(P, R, V, gamma): one-hot argmax policy. - Task 4
value_iteration(P, R, gamma): returnsV, the greedy policy, and the per-sweep max changes. - Task 5
policy_iteration(P, R, gamma): evaluate, improve with the strict-improvement rule, stop when stable.
The tests check the corridor tables from this chapter (including the value-iteration deltas [1.0, 0.9, 0.31, 0.0] and the policy sequence LLL → LLR → LRR → RRR). They also check the contraction property, convergence from a random start, and agreement with a brute-force search over all 256 policies of a tiny slippery grid. Then run python run.py to solve the slippery 8×8 FrozenLake and plot convergence for three values of γ.
Hint
P of shape (S, A, S) and V of shape (S,), P @ V has shape (S, A). Policy evaluation is then (policy * q_from_v(...)).sum(axis=1), and value iteration replaces the weighted sum with .max(axis=1).Solution
The reference is in solutions/dp.py. Here are the key lines.
- Task 1 is one line:
return R + gamma * (P @ V). - Task 2 loops
V_new = (policy * q_from_v(P, R, V, gamma)).sum(axis=1). It computesdelta = np.max(np.abs(V_new - V)), replacesV, and breaks whendelta < tol. Computing the wholeV_newbefore replacingVis what makes it synchronous. The testtest_task2_policy_evaluation_is_synchronouschecks that after one sweep only A has a value. - Task 3:
best = np.argmax(q_from_v(...), axis=1), then setpolicy[np.arange(S), best] = 1. - Task 4 is Task 2 with
.max(axis=1)in place of the policy-weighted sum, appending eachdeltatodeltas. - Task 5: evaluate; compute
Q;current = argmax(policy),best = argmax(Q);switch = Q[rows, best] > Q[rows, current] + 1e-9. If nothing switches, stop; otherwise usenp.where(switch, best, current)as the new actions.
run.py with the reference solution reports for 8×8 FrozenLake at . Value iteration takes 662 sweeps to reach a change of , though its greedy policy is optimal from sweep 127. Policy iteration needs 10 evaluations. The middle panel shows the optimal policy often aiming away from holes, preferring to slide along a safe row than to risk the ice next to a hole.
Files: README.md, dp.py, envs.py, test_dp.py, run.py
cd 04-dynamic-programming
python -m pytest -q # your code: tests fail until you fill in the TODOs
RL_SOLUTIONS=1 python -m pytest -q # reference solutions: all passFirst time? See Exercises & setup.
Further reading
- Sutton & Barto (2018), Reinforcement Learning: An Introduction, ch. 4. The standard treatment of DP for RL, with the gambler’s problem and Jack’s car rental as extra worked examples. Section 4.6 is the origin of the term “generalized policy iteration”.
- David Silver (2015), UCL RL course, lecture 3: Planning by Dynamic Programming. Slides and video. A compact second explanation of this chapter, including the contraction argument.
- Agarwal, Jiang, Kakade & Sun (2019–2022), Reinforcement Learning: Theory and Algorithms. Free book; its first chapter proves this chapter’s results crisply, with convergence rates for both value and policy iteration. Read it when you want the theory to research standard.
- Puterman (1994), Markov Decision Processes: Discrete Stochastic Dynamic Programming. The reference for MDP theory: optimality of deterministic Markov policies, modified policy iteration, average-reward criteria, and policy iteration as Newton’s method.
- Bertsekas (2019), Reinforcement Learning and Optimal Control. DP from the control-theory side, with a strong emphasis on approximation in value and policy space, which bridges to Chapters 6–9.
- Szepesvári (2010), Algorithms for Reinforcement Learning. A short, mathematically tidy monograph (free PDF). Its opening chapter covers MDPs, Bellman operators and their contraction properties in a few dense pages.
Next, in Chapter 5, we throw away the model: the agent can only act and observe. You’ll see that TD learning and Q-learning are this chapter’s backups, run on single sampled transitions instead of full expectations.