Chapter 09

Solving MDPs

From the Bellman equations to actual algorithms that produce an optimal policy. Dynamic programming, iterative policy evaluation, the policy-improvement theorem, policy iteration, value iteration, and the linear-programming view — three families of method, all driving the same fixed point into existence.

Reading: ~42 min Interactive: 3 widgets Source: Restelli, Solving MDPs (Polimi ML lecture notes) · Sutton & Barto, Reinforcement Learning, Ch. 4 · Bertsekas, Dynamic Programming and Optimal Control

01 · Motivation

Why does this matter?

Chapter 8 introduced the language of Markov decision processes: states, actions, transitions, rewards, the Bellman equations that relate the value of a state to the values of its successors. We have the definition of what an optimal policy is. We do not yet have a way to actually find one. That is the missing piece, and it is what this chapter fills in.

Before we build any algorithm, let’s pin down what “solving an MDP” actually means. It is the conjunction of two outputs:

Optimal value function $V^*$
a vector in RS\mathbb{R}^{|S|} telling us, for each state, the best possible expected discounted return achievable from that state.
Optimal policy $\pi^*$
a rule π:SA\pi^* : S \to A that achieves VV^* — that is, Vπ(s)=V(s)V^{\pi^*}(s) = V^*(s) for every ss.

These two outputs are tightly coupled: once you have VV^*, the optimal policy is just “act greedily with respect to VV^*”; once you have π\pi^*, the optimal value function is just “evaluate π\pi^*”. The three algorithms in this chapter differ only in which of these two objects they compute first.

The naive approach is straightforward and catastrophic. Enumerate every deterministic Markov policy π:SA\pi : S \to A, evaluate each one, keep the best. The number of such policies is AS|A|^{|S|}: with just 20 states and 4 actions, that’s 42010124^{20} \approx 10^{12} policies. With 100 states the universe ends before we finish counting. We need a fundamentally smarter method.

Plans share structure

The value of being in state ss is determined by the values of the states you reach in one step. If we already know V(s)V(s') for every successor ss', computing V(s)V(s) takes one Bellman backup. Subproblems overlap massively.

The Bellman equations are recursive

Recursion + caching = dynamic programming. The Bellman expectation and optimality equations are textbook examples of “the principle of optimality applies.”

A model unlocks planning

When PP and RR are known, we don’t need experience — we can plan. The agent computes the optimal policy offline, then executes it. This is the foundation that model-free RL (Ch. 10) tries to imitate without a model.

why

The conceptual shift

Chapter 8 was a language: how to write down a sequential decision problem. Chapter 9 is a workshop: three different machines that take that description and return an optimal policy. All three are mathematically equivalent — they compute the same fixed point — but each exposes a different facet of the structure, and each pays a different computational price.

recall

Quick recap from Chapter 8 — V and Q

The state-value Vπ(s)V^\pi(s) is the expected discounted return starting from ss and following π\pi thereafter. The action-value Qπ(s,a)Q^\pi(s, a) starts from ss, takes action aa right now, and follows π\pi only from the next step. They are linked by

Qπ(s,a)=R(s,a)+γsP(ss,a)Vπ(s),Vπ(s)=aπ(as)Qπ(s,a).Q^\pi(s, a) = R(s, a) + \gamma \sum_{s'} P(s' \mid s, a)\, V^\pi(s'), \qquad V^\pi(s) = \sum_a \pi(a \mid s)\, Q^\pi(s, a).

Their starred versions VV^* and QQ^* replace the policy-weighted sum with a maximum. The Q-form is the natural object for comparing actions — we reach for it whenever we improve a policy.

This chapter assumes full knowledge of the MDP — every P(ss,a)P(s' \mid s, a) and every R(s,a)R(s, a) is given. That assumption is what distinguishes planning (this chapter) from reinforcement learning (next chapter). When the model is unknown, we’ll estimate values from sampled experience — but the algorithms there are direct relatives of the ones we build here.

02 · Intuition

The idea in plain language

Forget the algebra for a moment. Imagine you stand at the entrance of a maze with a one-step lookahead. You want to know “how good is each cell” — if I follow the best plan from here, how much reward will I collect? The trick that makes the whole chapter tick: the value of a cell is the immediate reward for moving, plus a discounted copy of the value of wherever you land. The far future is already baked into the values of your neighbours. If you knew your neighbours’ values, computing your own is one arithmetic operation. We never enumerate plans.

Reward information flowing backward through states

Imagine the rewards as drops of dye placed at certain transitions. A Bellman backup at state ss inspects the dye at the immediately reachable transitions and stains ss a little. After two backups, dye from two steps away has reached ss; after kk backups, dye from kk steps away has soaked in. In the limit, every state knows about every reachable reward — discounted by distance. Both value iteration and the inner loop of policy iteration are doing exactly this: pumping reward information backward through the transition graph, one hop per sweep. With γ<1\gamma < 1, far-away rewards fade as they propagate, so finitely many sweeps suffice to any chosen accuracy.

Two nested loops, two ways to break the recursion

The Bellman equations talk about a value function that satisfies itself. There are two ways to handle the circular reference, and they give us the two main algorithms.

Policy iteration

Lock the policy. Solve the (now-linear) Bellman equations exactly for it — policy evaluation. Then update the policy by acting greedily with respect to those values — policy improvement. Repeat until the policy stops changing. Few iterations, each one a linear solve.

Value iteration

Don’t bother with explicit policies. Treat the Bellman optimality equation as an update rule: plug any current estimate into the right-hand side, get a better one, repeat. The values converge to VV^*; read off the greedy policy at the end. Many iterations, each one cheap.

And as a third voice, linear programming. The Bellman optimality equation with its max\max can be linearised by replacing the max\max with one inequality per action. The result is a textbook LP — solve once, get VV^* directly. Different machinery, same answer.

Why greedy improvement cannot hurt

Here is the load-bearing intuition for policy iteration. Suppose you’ve evaluated π\pi and know VπV^\pi and QπQ^\pi. In some state ss there is an action aπ(s)a' \neq \pi(s) with Qπ(s,a)>Vπ(s)Q^\pi(s, a') > V^\pi(s). Modify π\pi to take aa' at ss but keep it identical everywhere else. Two things happen: at ss you now collect strictly more expected return (by definition of QπQ^\pi); and after that single deviation you revert to π\pi, so the tail of the trajectory is unchanged in distribution. The new policy is at least as good at ss and identical elsewhere — so it is globally at least as good. One greedy step is never a step backwards.

key

The chapter in one sentence

Plug the Bellman equations into themselves until they stop changing. Policy iteration alternates “solve the linear Bellman expectation for a fixed policy” and “be greedy.” Value iteration iterates the non-linear Bellman optimality directly. LP solves the optimality equation as a set of inequalities. All three machines drive the same fixed point, VV^*, into existence.

A value function silently contains a policy

Once you have any value function VV — optimal or not — there is automatically a corresponding greedy policy: the one that, at each state, picks the action with the highest one-step lookahead value,

πV(s)=argmaxa[R(s,a)+γsP(ss,a)V(s)].\pi_V(s) = \arg\max_a \Bigl[ R(s, a) + \gamma \sum_{s'} P(s' \mid s, a)\, V(s') \Bigr].

This is why value iteration doesn’t track policies during the loop. Every VkV_k silently induces πVk\pi_{V_k}; at convergence πV=π\pi_{V^*} = \pi^*. Policy iteration just makes this greedy extraction explicit at every step, which lets it terminate exactly rather than asymptotically. Two sides of one coin.

Why iterating converges at all

Why doesn’t the loop oscillate forever or diverge? Because the Bellman optimality operator is a contraction: applying it to two different value estimates always brings them closer together by a factor of at least γ<1\gamma < 1. Any two starting points converge to the same fixed point, geometrically fast. The reason is the discount factor — it scales down all disagreements between iterations. Discounting is what makes infinite-horizon dynamic programming possible at all; without it, the future could swamp the present and iterates would never settle.

03 · Formalism

Definitions and equations

We assume the setting of Chapter 8: a discounted infinite-horizon MDP S,A,P,R,γ,μ\langle S, A, P, R, \gamma, \mu \rangle with finite SS and AA, γ[0,1)\gamma \in [0, 1).

The Bellman operators (recap from Ch. 8)

For a fixed policy π\pi, the Bellman expectation operator TπT^\pi acts on a value function V:SRV : S \to \mathbb{R} by

Bellman expectation
(TπV)(s)=aπ(as)[R(s,a)+γsP(ss,a)V(s)].(T^\pi V)(s) = \sum_{a} \pi(a \mid s) \Bigl[ R(s, a) + \gamma \sum_{s'} P(s' \mid s, a)\, V(s') \Bigr].

In matrix form, with PπRS×SP^\pi \in \mathbb{R}^{|S| \times |S|} and RπRSR^\pi \in \mathbb{R}^{|S|}, this is simply TπV=Rπ+γPπVT^\pi V = R^\pi + \gamma P^\pi V. Linear in VV.

The Bellman optimality operator TT^* replaces the policy-weighted sum with a maximum:

Bellman optimality
(TV)(s)=maxaA[R(s,a)+γsP(ss,a)V(s)].(T^* V)(s) = \max_{a \in A} \Bigl[ R(s, a) + \gamma \sum_{s'} P(s' \mid s, a)\, V(s') \Bigr].

Non-linear in VV because of the max\max. Still a contraction in \|\cdot\|_\infty.

Fixed points
VπV^\pi is the unique fixed point of TπT^\pi; VV^* is the unique fixed point of TT^*.
Contraction
for any V,UV, U: TπVTπUγVU\|T^\pi V - T^\pi U\|_\infty \le \gamma\, \|V - U\|_\infty, and the same for TT^*.
Monotonicity
if VUV \le U componentwise, then TVTUT^* V \le T^* U.
Deep dive

Before the infinite-horizon machinery, the cleanest possible DP. If the agent acts for exactly NN steps, the optimal value is computed by backward recursion:

Vk(s)=maxaAk[Rk(s,a)+sPk(ss,a)Vk+1(s)],k=N1,,0,V^*_k(s) = \max_{a \in A_k} \Bigl[ R_k(s, a) + \sum_{s'} P_k(s' \mid s, a)\, V^*_{k+1}(s') \Bigr], \quad k = N-1, \ldots, 0,

with terminal condition VN(s)=0V^*_N(s) = 0. The optimal action at stage kk is the argmax of the same bracket. Total cost O(NS2A)O(N |S|^2 |A|) — versus ANS|A|^{N|S|} for brute force. The infinite-horizon discounted case is the limit NN \to \infty: the recursion no longer terminates, so we replace “step backward from the horizon” with “iterate the Bellman operator to its fixed point.”

Iterative policy evaluation

For a fixed policy π\pi, VπV^\pi satisfies the linear system Vπ=Rπ+γPπVπV^\pi = R^\pi + \gamma P^\pi V^\pi. Two ways to compute it:

Direct solve
Vπ=(IγPπ)1Rπ.V^\pi = (I - \gamma P^\pi)^{-1}\, R^\pi.

Cost O(S3)O(|S|^3). Always invertible because γ<1\gamma < 1 makes IγPπI - \gamma P^\pi strictly diagonally dominant.

Iterative evaluation
Vk+1(s)aπ(as)[R(s,a)+γsP(ss,a)Vk(s)].V_{k+1}(s) \leftarrow \sum_a \pi(a \mid s) \Bigl[ R(s, a) + \gamma \sum_{s'} P(s' \mid s, a)\, V_k(s') \Bigr].

Cost per sweep O(S2A)O(|S|^2 |A|). Converges geometrically: VkVπγkV0Vπ\|V_k - V^\pi\|_\infty \le \gamma^k \|V_0 - V^\pi\|_\infty.

Policy improvement

Given any value function VV, the greedy policy with respect to VV is

Greedy policy
π(s)argmaxaA[R(s,a)+γsP(ss,a)V(s)].\pi'(s) \in \arg\max_{a \in A} \Bigl[ R(s, a) + \gamma \sum_{s'} P(s' \mid s, a)\, V(s') \Bigr].

Ties broken arbitrarily. If V=VπV = V^\pi, this is the action that maximises Qπ(s,a)Q^\pi(s, a).

thm

Policy improvement theorem

Let π,π\pi, \pi' be deterministic policies. If Qπ(s,π(s))Vπ(s)Q^\pi(s, \pi'(s)) \ge V^\pi(s) for every sSs \in S, then Vπ(s)Vπ(s)V^{\pi'}(s) \ge V^\pi(s) for every sSs \in S.

In particular, the greedy policy with respect to VπV^\pi is at least as good as π\pi. If equality holds everywhere, π\pi is already optimal. (Proof in the exam-intel section — the unrolling argument is short and worth memorising.)

Policy iteration

Putting the pieces together:

Policy iteration
π0evalVπ0greedyπ1evalVπ1greedyπ2πV.\pi_0 \xrightarrow{\text{eval}} V^{\pi_0} \xrightarrow{\text{greedy}} \pi_1 \xrightarrow{\text{eval}} V^{\pi_1} \xrightarrow{\text{greedy}} \pi_2 \to \cdots \to \pi^* \to V^*.

Two phases per iteration: policy evaluation (solve the linear system) and policy improvement (act greedily). Terminates exactly when the policy stops changing.

Because there are only finitely many deterministic policies and each iteration strictly improves the policy (or terminates), PI converges in a finite number of steps.

Value iteration

Iterate the Bellman optimality operator directly:

Value iteration
Vk+1(s)maxaA[R(s,a)+γsP(ss,a)Vk(s)].V_{k+1}(s) \leftarrow \max_{a \in A} \Bigl[ R(s, a) + \gamma \sum_{s'} P(s' \mid s, a)\, V_k(s') \Bigr].

No explicit policy. After convergence, extract π\pi^* as the greedy policy of VV^*.

An equivalent formulation works directly with Q-values:

Q-value iteration
Qk+1(s,a)R(s,a)+γsP(ss,a)maxaQk(s,a).Q_{k+1}(s, a) \leftarrow R(s, a) + \gamma \sum_{s'} P(s' \mid s, a)\, \max_{a'} Q_k(s', a').

Reads off the optimal policy with no separate greedy step: π(s)=argmaxaQ(s,a)\pi^*(s) = \arg\max_a Q^*(s, a). Memory is SA|S|\cdot|A| instead of S|S|, but no model query at extraction time — exactly why model-free RL (Ch. 10) prefers Q-values.

thm

Value iteration converges

For any initial V0V_0, the sequence Vk=TVk1V_k = T^* V_{k-1} converges to VV^* in \|\cdot\|_\infty, with VkVγkV0V\|V_k - V^*\|_\infty \le \gamma^k \|V_0 - V^*\|_\infty.

stop

A practical stopping rule

If Vk+1Vk<ε\|V_{k+1} - V_k\|_\infty < \varepsilon, then

Vk+1Vγε1γ.\|V_{k+1} - V^*\|_\infty \le \frac{\gamma\,\varepsilon}{1 - \gamma}.

A looser but commonly cited form replaces γ\gamma with 2γ2\gamma in the numerator. We can only measure successive-iterate differences, never the gap to VV^* directly — this inequality converts the measurable signal into a certificate.

Linear programming — primal

The fixed-point condition VTVV \ge T^* V (componentwise) characterises supersolutions of the Bellman equation. VV^* is the smallest supersolution — which is exactly an LP:

Primal LP
minVRSsμ(s)V(s)s.t.V(s)R(s,a)+γsP(ss,a)V(s),s,  a.\begin{aligned} \min_{V \in \mathbb{R}^{|S|}} \quad & \sum_{s} \mu(s)\, V(s) \\ \text{s.t.} \quad & V(s) \ge R(s, a) + \gamma \sum_{s'} P(s' \mid s, a)\, V(s'),\quad \forall s,\;\forall a. \end{aligned}

S|S| variables, SA|S|\cdot|A| constraints. The weights μ(s)>0\mu(s) > 0 (often the initial-state distribution) make the objective strictly proper without changing the optimum.

The constraints encode ”VV lies above the Bellman backup.” Among all such VV, the LP picks the one with smallest weighted sum — and that point is exactly VV^*.

Linear programming — dual

The dual introduces variables λ(s,a)0\lambda(s, a) \ge 0, one per state-action pair:

Dual LP
maxλ0s,aλ(s,a)R(s,a)s.t.aλ(s,a)=μ(s)+γs,aλ(s,a)P(ss,a),s.\begin{aligned} \max_{\lambda \ge 0} \quad & \sum_{s, a} \lambda(s, a)\, R(s, a) \\ \text{s.t.} \quad & \sum_{a'} \lambda(s', a') = \mu(s') + \gamma \sum_{s, a} \lambda(s, a)\, P(s' \mid s, a),\quad \forall s'. \end{aligned}

SA|S|\cdot|A| variables, S|S| equality constraints. The dual variables admit a beautiful interpretation.

The dual variables λ(s,a)\lambda(s, a) are the discounted state-action occupancy measures under a policy π\pi: how often, in present value, the agent visits (s,a)(s, a) when starting from μ\mu and following π\pi,

λ(s,a)=t=0γtPr(st=s,at=as0μ,π).\lambda(s, a) = \sum_{t = 0}^{\infty} \gamma^t \, \Pr(s_t = s, a_t = a \mid s_0 \sim \mu, \pi).

The equality constraints are the discounted Chapman–Kolmogorov flow equations: occupancy in ss' comes from initial probability μ(s)\mu(s') plus discounted transitions into ss'. Maximising λR\sum \lambda R over flows gives the best long-run reward, and the optimal policy is read off as π(s)=argmaxaλ(s,a)\pi^*(s) = \arg\max_{a} \lambda^*(s, a).

Three machines, one fixed point

Policy Iteration

Alternate exact evaluation and greedy improvement. Few iterations, each expensive (a linear system). Terminates exactly in finitely many steps. Cost: eval O(S3)O(|S|^3) + improve O(S2A)O(|S|^2|A|).

Value Iteration

Iterate Bellman optimality. Many iterations, each cheap. Geometric convergence at rate γ\gamma. Stop when iterates differ by less than ε(1γ)/(2γ)\varepsilon(1-\gamma)/(2\gamma). Cost: O(S2A)O(|S|^2|A|) per sweep.

Linear Programming

One LP, polynomial-time solver. Strong worst-case bounds; impractical at large state-action counts due to constraint blow-up. The dual exposes occupancy measures. Cost: poly(S,A)\mathrm{poly}(|S|, |A|).

04 · Worked example

Three states, two actions, by hand

We solve a tiny MDP three different ways — policy iteration, value iteration, and the LP — and watch the same answer drop out.

setup

Why this example is instructive

Three things to watch. One: the “obvious greedy” plan (grab the +10+10 from s2s_2 immediately) turns out suboptimal — the discounted infinite loop beats it. That kind of finding requires a solver. Two: the three algorithms reach the same answer through visibly different paths. Three: the LP’s constraints “select” the optimal action at each state by going tight.

Worked example Solving the 3-state MDP three ways

1 · The MDP

Three states S={s1,s2,s3}S = \{s_1, s_2, s_3\}, where s3s_3 is an absorbing terminal with zero reward. Two actions A={a,b}A = \{a, b\} in s1s_1 and s2s_2. Discount γ=0.9\gamma = 0.9. Transitions deterministic; rewards on transition.

StateActionNext stateReward
s1s_1aas2s_2+5+5
s1s_1bbs3s_3+1+1
s2s_2aas1s_100
s2s_2bbs3s_3+10+10
s3s_3·s3s_300

Intuition first: the big prize is the +10+10 at s2s3s_2 \to s_3. We should reach s2s_2 from s1s_1 (action aa, reward 5), then cash out (action bb, reward 10). Let’s confirm by algorithm.

2 · Policy iteration — from a bad guess

Start with π0\pi_0 that always picks bb: π0(s1)=b\pi_0(s_1) = b, π0(s2)=b\pi_0(s_2) = b. Evaluate: both states go straight to s3s_3, so Vπ0(s1)=1V^{\pi_0}(s_1) = 1, Vπ0(s2)=10V^{\pi_0}(s_2) = 10. Improve greedily:

Q(s1,a)=5+0.910=14>Q(s1,b)=1,Q(s2,a)=0.91=0.9<Q(s2,b)=10.Q(s_1, a) = 5 + 0.9 \cdot 10 = 14 > Q(s_1, b) = 1, \qquad Q(s_2, a) = 0.9 \cdot 1 = 0.9 < Q(s_2, b) = 10.

So π1(s1)=a\pi_1(s_1) = a, π1(s2)=b\pi_1(s_2) = b — the policy changed at s1s_1. Continue.

3 · Policy iteration — the surprise, then convergence

Evaluate π1\pi_1: Vπ1(s2)=10V^{\pi_1}(s_2) = 10, Vπ1(s1)=5+0.910=14V^{\pi_1}(s_1) = 5 + 0.9 \cdot 10 = 14. Improve:

Qπ1(s2,a)=0.914=12.6>Qπ1(s2,b)=10.Q^{\pi_1}(s_2, a) = 0.9 \cdot 14 = 12.6 > Q^{\pi_1}(s_2, b) = 10.

At s2s_2, action aa now beats bb! Update to π2(s1)=a\pi_2(s_1) = a, π2(s2)=a\pi_2(s_2) = a. Evaluate π2\pi_2: now both states cycle, s1a,+5s2a,0s1s_1 \xrightarrow{a,+5} s_2 \xrightarrow{a,0} s_1:

V(s1)=5+0.9V(s2),V(s2)=0.9V(s1)    V(s1)=510.8126.32,  V(s2)23.68.V(s_1) = 5 + 0.9\, V(s_2), \quad V(s_2) = 0.9\, V(s_1) \;\Rightarrow\; V(s_1) = \tfrac{5}{1 - 0.81} \approx 26.32,\; V(s_2) \approx 23.68.

Improve once more: Q(s1,a)26.32>1Q(s_1, a) \approx 26.32 > 1 and Q(s2,a)23.68>10Q(s_2, a) \approx 23.68 > 10. Policy unchanged. Stop. π=(a,a)\pi^* = (a, a), V(26.32,23.68,0)V^* \approx (26.32,\, 23.68,\, 0).

The optimal policy says: stay in the loop forever, collecting +5+5 every two steps. Our naive intuition was wrong — discounting doesn’t kill the loop because 5/(10.81)26>105/(1 - 0.81) \approx 26 > 10.

4 · Value iteration

Initialise V0=0V_0 = 0 and sweep the optimality operator. At k=1k = 1, V1(s1)=max(5+0,1+0)=5V_1(s_1) = \max(5 + 0,\, 1 + 0) = 5 and V1(s2)=max(0,10)=10V_1(s_2) = \max(0,\, 10) = 10. The values march toward VV^* at rate γ=0.9\gamma = 0.9:

kkV(s1)V(s_1)V(s2)V(s_2)VkVk1\lVert V_k - V_{k-1}\rVert_\infty
00.000.00
15.0010.0010.00
214.0010.009.00
314.0012.602.60
516.3414.712.11
1022.0819.87
5026.3123.68
\infty26.3223.68

Once stable, the greedy policy is π(s1)=a\pi^*(s_1) = a (since 5+0.923.68>15 + 0.9 \cdot 23.68 > 1) and π(s2)=a\pi^*(s_2) = a (since 0.926.32>100.9 \cdot 26.32 > 10). Same answer as PI.

5 · The LP view

Set μ=(1/3,1/3,1/3)\mu = (1/3, 1/3, 1/3). The primal LP is

minV1,V2,V3  13(V1+V2+V3)s.t.{V15+0.9V2,V11+0.9V3,V20+0.9V1,V210+0.9V3,V30.\min_{V_1, V_2, V_3}\; \tfrac{1}{3}(V_1 + V_2 + V_3) \quad \text{s.t.}\quad \begin{cases} V_1 \ge 5 + 0.9\, V_2, \\ V_1 \ge 1 + 0.9\, V_3, \\ V_2 \ge 0 + 0.9\, V_1, \\ V_2 \ge 10 + 0.9\, V_3, \\ V_3 \ge 0. \end{cases}

At the optimum, exactly one constraint per state is tight — the optimal action. The tight set V1=5+0.9V2V_1 = 5 + 0.9 V_2, V2=0.9V1V_2 = 0.9 V_1, V3=0V_3 = 0 is the same linear system we solved in step 3: V=(26.32,23.68,0)V^* = (26.32,\, 23.68,\, 0). The slack on the two non-tight constraints (action bb at s1s_1 and s2s_2) certifies those actions are suboptimal.

map

Three lenses, one fixed point

  • PI: 3 iterations until the policy stops changing; each solved a 2×2 linear system exactly.
  • VI: dozens of one-step max-backups; geometrically convergent.
  • LP: a single 3-variable, 5-constraint program, solved by simplex in a constant number of pivots.

All three return V(s1)26.32V^*(s_1) \approx 26.32, V(s2)23.68V^*(s_2) \approx 23.68, V(s3)=0V^*(s_3) = 0, with optimal action aa at both non-terminal states.

05 · Visual explanation

The geometry of dynamic programming

The Bellman backup as a tree

Every Bellman update is a one-step game tree: from a state, branch on actions; from each action, branch on possible next states (weighted by PP); collect reward; bring back the discounted value of the leaf. TπT^\pi averages over actions using π\pi; TT^* takes the max.

Bellman expectation · Tπ s a₁ π(a₁∣s) a₂ π(a₂∣s) s′ s′ s′ s′ average over actions, then over next states Bellman optimality · T* s max a₁ a₂ s′ s′ s′ s′ max over actions, then average over s′

The shape is identical. The only difference is the action node: expectation averages with π(as)\pi(a \mid s); optimality takes a max\max. That one symbol — sum vs max — is the entire algorithmic gap between evaluating a policy and finding the best one.

Why the iteration converges

Picture the space of value functions as RS\mathbb{R}^{|S|}. The operator TT^* maps this space to itself, and applying it to any two value functions brings them at least a factor γ\gamma closer in max-norm. After kk sweeps the disagreement with VV^* has radius γkV0V\gamma^k \|V_0 - V^*\|_\infty. For γ=0.9\gamma = 0.9 the error halves every 7\approx 7 sweeps; for γ=0.99\gamma = 0.99, every 69\approx 69. Convergence is geometric but slows as γ1\gamma \to 1 — you can watch this directly in the contraction widget below.

Generalized Policy Iteration — the unifying picture

Every algorithm in this chapter is an instance of one master pattern. Two arrows are in tension: one pulls VV toward VπV^\pi (evaluation makes the value consistent with the policy); the other pulls π\pi toward greedy(V)\text{greedy}(V) (improvement makes the policy consistent with the value). Both arrows are zero at exactly one point: (V,π)(V^*, \pi^*).

V-space π-space V₀ π₀ V* π* evaluation V ← V^π improvement π ← greedy(V) V₀ → V^π₀ → V^π₁ → … → V* π₀ → π₁ → π₂ → … → π*

Policy iteration takes the evaluation arrow all the way (exact VπV^\pi) before improving. Value iteration applies one tiny piece of evaluation before each improvement — and because the greedy step is implicit in the max\max of TT^*, the two arrows fuse into a single update. Modified policy iteration sits between: run the inner evaluation loop for kk sweeps instead of to convergence, then improve. k=1k = 1 recovers value iteration; k=k = \infty recovers exact policy iteration; intermediate kk is often fastest in practice.

The LP polytope

In the primal LP, each constraint V(s)R(s,a)+γsP(ss,a)V(s)V(s) \ge R(s, a) + \gamma \sum_{s'} P(s' \mid s, a) V(s') is a half-space in RS\mathbb{R}^{|S|}. The feasible set — the intersection of these half-spaces — contains all overestimates of VV^*, anything satisfying VTVV \ge T^* V. The objective sμ(s)V(s)\sum_s \mu(s) V(s) with positive μ\mu picks the smallest such overestimate, which is VV^* itself, sitting at a vertex where exactly one constraint per state is tight — and the tight constraint names the optimal action there.

06 · Hands-on

Try it yourself

Three widgets, each illustrating one core idea. Drag, click, watch the numbers update.

First, step value or policy iteration on a 4×4 gridworld (constant 1-1 reward, two terminal corners). Press Step to apply one Bellman optimality backup (VI) or one full evaluation + greedy improvement (PI), and watch VV converge and the greedy arrows settle.

Hands-on 1

Step value & policy iteration on a 4×4 gridworld

A 4×4 grid; the top-left and bottom-right squares are terminal (shaded). Every move costs −1 until termination. Pick a discount γ, choose VI or PI, and press Step to apply one Bellman optimality sweep (VI) or one full evaluation + greedy improvement (PI). Numbers are Vₖ; arrows show the greedy policy.

0.90
iter 0
VI · iteration 0
×0.00.00.00.00.00.00.00.00.00.00.00.00.00.0×cells: Vₖ · arrows: greedy policy× terminal · reward −1 per step
‖Vₖ − Vₖ₋₁‖∞
‖Vₖ − V*‖∞ bound
policy changes
‖Vₖ − V*‖∞ true
init
Try thisRun VI step by step at γ = 0.9: after step 1 every non-terminal cell holds −1 (one move from termination if it could teleport); deeper cells fill in over the next sweeps and the values keep creeping for a while. Now switch to PI and reset — it reaches the same optimal arrows in just 2–3 iterations, but each PI iteration solves a 14×14 linear system internally.
TakeawayVI does many cheap iterations; PI does a few expensive ones. Crucially, the greedy policy(the arrows) usually freezes well before the values stop moving — once the arrows settle you already have π*, even while the numbers keep inching toward V*. That is why VI's stopping rule certifies the gap with the 2γε/(1−γ) bound rather than waiting for exact equality.

Next, walk policy iteration through the exact 3-state worked example, alternating evaluation and greedy improvement with the full QQ-table exposed — watch the argmax flip and the policy converge to (a,a)(a, a).

Hands-on 2

Policy iteration, evaluation ↔ improvement

The 3-state worked-example MDP. Pick a starting policy and a discount, then step the algorithm: each iteration evaluates the current policy exactly (a 2×2 linear system) and improves it greedily from the full Q-table. PI stops the moment the greedy action equals the current action in every state.

0.90
π₀(s₁)
π₀(s₂)
Iteration 1 · evaluate π = (s₁→b, s₂→b)
Vπ(s₁)
1.00
Vπ(s₂)
10.00
Vπ(s₃)
0.00
Q(s₁, a)
14.00
Q(s₁, b)
1.00
Q(s₂, a)
0.90
Q(s₂, b)
10.00
greedy → (s₁→a, s₂→b)policy changed
iterating…
Try thisStart from π₀ = (b, b) at γ = 0.9 — the deliberately bad "grab the +10 now" guess. Watch the Q-table flip: iteration 1 fixes s₁ to a, iteration 2 discovers that even at s₂ the loop (action a) beats cashing out, and iteration 3 confirms nothing changes. Now drop γ below ~0.82: the discount no longer rewards looping, so PI keeps s₂→b.
TakeawayEach green cell is the action the greedy step "selects"; improvement simply reads the argmax of the Q-row. By the policy-improvement theorem each iteration is monotone — the values never go down — and because there are only finitely many deterministic policies, PI terminates exactly when the greedy policy matches the one it just evaluated.

Finally, feel the contraction: run value iteration on the same 3-state MDP and plot VkV\|V_k - V^*\|_\infty on a log scale against kk. Slide γ\gamma and watch the slope — it is exactly logγ\log\gamma, the geometric rate the contraction guarantees.

Hands-on 3

Feel the contraction — how fast does VI converge?

Value iteration on the 3-state MDP of §04. The plot shows ‖Vₖ − V*‖∞ on a log scale against the sweep count k. The dashed amber line is the contraction guarantee γᵏ·‖V₀ − V*‖∞ — slide γ and watch the actual error hug a straight line of slope log γ.

0.90
60
10⁻⁸10⁻⁶10⁻⁴10⁻²1010²0714212835424956iteration k‖Vₖ − V*‖∞ (log₁₀)actual VI errorγᵏ·‖V₀ − V*‖∞
geometric rate
0.90
half-life (sweeps)
6.6
iters for ε = 10⁻³
97
final ‖Vₖ − V*‖∞
3.04e-2

V* ≈ (s₁: 26.32, s₂: 23.68, s₃: 0.00)

Try thisAt γ = 0.5 VI hits 10⁻³ error in about 10 sweeps; at γ = 0.9 it needs roughly 65; at γ = 0.99 around 700. The dependence is log ε / log γ — as γ → 1 the line flattens and convergence slows dramatically. Watch the actual error sit right on the dashed bound.
TakeawayDiscounting is not just modelling taste — it is the engine of convergence. The closer γ is to 1, the longer the effective planning horizon, the smaller each shrinkage step, and the more sweeps you need. The contraction factor γ is literally the slope of this log-error line.

07 · Exam intel

What the exam actually tests

This chapter loads several short proofs and at least one numerical walk-through. Seven patterns cover essentially every question.

Q1

Prove the policy improvement theorem

Hypothesis: Qπ(s,π(s))Vπ(s)Q^\pi(s, \pi'(s)) \ge V^\pi(s) for all ss. Goal: Vπ(s)Vπ(s)V^{\pi'}(s) \ge V^\pi(s) for all ss. One chain of inequalities, applying the hypothesis once per unrolling step:

Vπ(s)Qπ(s,π(s))=Eπ[rt+1+γVπ(st+1)st=s]Eπ[rt+1+γQπ(st+1,π(st+1))st=s]Eπ[rt+1+γrt+2+γ2rt+3+st=s]=Vπ(s).\begin{aligned} V^\pi(s) &\le Q^\pi(s, \pi'(s)) = \mathbb{E}_{\pi'}\bigl[ r_{t+1} + \gamma V^\pi(s_{t+1}) \mid s_t = s \bigr] \\ &\le \mathbb{E}_{\pi'}\bigl[ r_{t+1} + \gamma\, Q^\pi(s_{t+1}, \pi'(s_{t+1})) \mid s_t = s \bigr] \\ &\le \cdots \le \mathbb{E}_{\pi'}\bigl[ r_{t+1} + \gamma r_{t+2} + \gamma^2 r_{t+3} + \cdots \mid s_t = s \bigr] = V^{\pi'}(s). \end{aligned}

The infinite sum converges because γ<1\gamma < 1 and rewards are bounded. Corollary: greedy improvement either strictly improves the policy or leaves it unchanged — in which case Bellman optimality holds and π=π\pi = \pi^*.

Q2

Show that T-star is a γ-contraction in max-norm

Fix a state ss and let aa^* maximise the backup for VV, so (TV)(s)=R(s,a)+γsP(ss,a)V(s)(T^* V)(s) = R(s, a^*) + \gamma \sum_{s'} P(s' \mid s, a^*) V(s'). Then

(TV)(s)(TU)(s)γsP(ss,a)[V(s)U(s)]γVU.(T^* V)(s) - (T^* U)(s) \le \gamma \sum_{s'} P(s' \mid s, a^*) \bigl[ V(s') - U(s') \bigr] \le \gamma \|V - U\|_\infty.

A symmetric argument (swap VV and UU) gives the lower bound, so TVTUγVU\|T^* V - T^* U\|_\infty \le \gamma \|V - U\|_\infty. Banach’s fixed-point theorem then gives existence, uniqueness, and the geometric rate γk\gamma^k.

Q3

Derive the practical stopping rule

Suppose Vk+1Vk<ε\|V_{k+1} - V_k\|_\infty < \varepsilon. By the contraction, Vk+mVk+m1γm1ε\|V_{k+m} - V_{k+m-1}\|_\infty \le \gamma^{m-1}\varepsilon. Telescoping and the triangle inequality give, for MM \to \infty (so VMVV_M \to V^*),

VVk+1m=2γm1ε=γ1γε.\|V^* - V_{k+1}\|_\infty \le \sum_{m=2}^{\infty} \gamma^{m-1}\varepsilon = \frac{\gamma}{1-\gamma}\,\varepsilon.

The §3 version with a factor of 2 also accounts for the gap at iterate kk itself, giving 2γε1γ\frac{2\gamma\varepsilon}{1-\gamma}. Either form works; the tighter one is preferable when available.

Q4

Run policy iteration on a small MDP

Typical setup: 2–3 states, 2 actions, γ0.9\gamma \approx 0.9. Start from a given policy, evaluate exactly (solve a 2×2 or 3×3 system), greedily improve, repeat — expect 2–3 iterations. Three things to nail: (i) write the Bellman equations in matrix form and solve; (ii) compute the full Q-table at each improvement, not just one action; (iii) stop only when every state’s greedy action matches the current policy.

Q5

State and interpret the dual LP

Write down both primal and dual. The dual variables λ(s,a)\lambda(s, a) are discounted occupancy measures, λ(s,a)=tγtPr(st=s,at=aμ,π)\lambda(s, a) = \sum_{t} \gamma^t \Pr(s_t = s, a_t = a \mid \mu, \pi). The flow constraint aλ(s,a)=μ(s)+γs,aλ(s,a)P(ss,a)\sum_a \lambda(s', a) = \mu(s') + \gamma \sum_{s,a} \lambda(s,a) P(s' \mid s, a) says occupancy at ss' = initial probability + discounted inflow. Maximising λR\sum \lambda R finds the occupancy pattern collecting the most discounted reward; read off π(s)=argmaxaλ(s,a)\pi^*(s) = \arg\max_a \lambda^*(s, a).

Q6

Expectation vs optimality — which goes where?

A reliable trap. The Bellman expectation TπT^\pi (sum over actions weighted by π\pi) appears in iterative policy evaluation and the inner loop of policy iteration. The Bellman optimality TT^* (max over actions) appears in the value-iteration backup, the primal LP constraints, and policy improvement (one-step lookahead). The mnemonic: expectation evaluates, optimality optimises.

Q7

Compare the costs of DP methods

MethodPer iterationIterations
Iterative policy evalO(S2A)O(\lvert S\rvert^2 \lvert A\rvert)O(log(1/ε)/log(1/γ))O(\log(1/\varepsilon)/\log(1/\gamma))
Direct policy evalO(S3)O(\lvert S\rvert^3) once1
Value iterationO(S2A)O(\lvert S\rvert^2 \lvert A\rvert)O(log(1/ε)/log(1/γ))O(\log(1/\varepsilon)/\log(1/\gamma))
Policy iterationcubic eval + O(S2A)O(\lvert S\rvert^2\lvert A\rvert) improvefew (strongly polynomial)
Linear programmingpoly(S,A)\mathrm{poly}(\lvert S\rvert, \lvert A\rvert) end-to-end

08 · Common mistakes

Where students get this wrong

×

Value iteration produces a policy at every step

Intermediate iterates VkV_k need not correspond to any achievable policy — they are abstract fixed-point iterates. Only after convergence do we extract a policy by being greedy w.r.t. VV^*. The greedy policy greedy(Vk)\text{greedy}(V_k) can even be a non-monotone function of kk; what is monotone is the contraction toward VV^*.

×

PI converges in fewer iterations, therefore PI is faster

Fewer iterations, yes — but each PI iteration solves a full linear system (or runs many evaluation sweeps). VI iterations are individually much cheaper. Which wins depends on γ\gamma, S|S|, A|A|, structure, and implementation. Modified PI (truncated evaluation) is often best in practice.

×

The iterate difference tells me the gap to V-star

Almost. The exact relation is Vk+1V2γε1γ\|V_{k+1} - V^*\|_\infty \le \frac{2\gamma\varepsilon}{1-\gamma} when Vk+1Vk<ε\|V_{k+1} - V_k\|_\infty < \varepsilon — a multiplicative blow-up by 2γ1γ\frac{2\gamma}{1-\gamma}. With γ=0.99\gamma = 0.99 that factor is 198\approx 198: an iterate change of 10310^{-3} only guarantees a gap of 0.2\approx 0.2, not 10310^{-3}.

×

Confusing T-pi and T-star

TπT^\pi is linear in VV — just Rπ+γPπVR^\pi + \gamma P^\pi V. TT^* is non-linear because of the max\max. Iterative policy evaluation uses TπT^\pi (no policy update); value iteration uses TT^* (the greedy policy is updated implicitly every step). Mixing them up is the single most common slip on “which algorithm does what” questions.

×

DP is polynomial, so MDPs are easy

Polynomial in the number of states — and the number of states is typically exponential in the number of state variables (the curse of dimensionality). A 10×10 screen with 256 colours already has 256100256^{100} states, far beyond any DP method. That is exactly the motivation for function approximation and deep RL.

×

Classical PI evaluates the policy approximately

Classical PI evaluates exactly. The variant that evaluates approximately (run kk sweeps of iterative evaluation, then improve) is modified policy iteration. k=1k = 1 is value iteration; k=k = \infty is exact PI. Related, but not the same algorithm.

09 · Self-check

Can you answer these?

Which statement about value iteration is true?

Policy iteration in a fully observable MDP with |S| states and |A| actions:

In the LP formulation of an MDP, what does the dual variable λ(s, a) mean?

You run value iteration with γ = 0.95 and observe ‖V_{k+1} − V_k‖∞ < 10⁻³. What can you conclude?

10 · Recap

One-screen summary

Chapter 09 — load-bearing ideas

  1. Brute-force is impossible. AS|A|^{|S|} deterministic policies. Dynamic programming exploits the Bellman recursion to cache and reuse subproblem solutions.
  2. Two operators run the show. The Bellman expectation TπT^\pi is linear in VV; the optimality TT^* is non-linear (the max). Both are γ-contractions in \|\cdot\|_\infty.
  3. Policy evaluation. Solve Vπ=Rπ+γPπVπV^\pi = R^\pi + \gamma P^\pi V^\pi either directly in O(S3)O(|S|^3) or iteratively as Vk+1=TπVkV_{k+1} = T^\pi V_k at O(S2A)O(|S|^2|A|) per sweep with rate γ\gamma.
  4. Policy improvement theorem. If Qπ(s,π(s))Vπ(s)Q^\pi(s, \pi'(s)) \ge V^\pi(s) everywhere, then VπVπV^{\pi'} \ge V^\pi everywhere. Greedy improvement is always safe.
  5. Policy iteration. Alternate exact evaluation and greedy improvement. Terminates exactly in finitely many iterations — few iterations, each expensive.
  6. Value iteration. Iterate Vk+1=TVkV_{k+1} = T^* V_k to VV^* with VkVγkV0V\|V_k - V^*\|_\infty \le \gamma^k \|V_0 - V^*\|_\infty. Stop when Vk+1Vk<ε\|V_{k+1} - V_k\|_\infty < \varepsilon and certify Vk+1V<2γε1γ\|V_{k+1} - V^*\|_\infty < \frac{2\gamma\varepsilon}{1-\gamma}.
  7. Linear programming. Primal: minμV\min \mu^\top V s.t. VTVV \ge T^* V. Dual: optimise reward-weighted occupancy λ(s,a)=tγtPr(st=s,at=a)\lambda(s, a) = \sum_t \gamma^t \Pr(s_t = s, a_t = a). Optimal policy π(s)=argmaxaλ(s,a)\pi^*(s) = \arg\max_a \lambda^*(s, a).
  8. Curse of dimensionality. DP is polynomial in S|S|, but S|S| is typically exponential in the problem variables — the motivation for the approximate, sample-based methods of Chapter 10.

Could you teach this back?

Without looking back, can you: state what “solving an MDP” means in terms of VV^* and π\pi^*; write the Bellman expectation and optimality equations and say which appears in which algorithm; explain in plain English why one greedy improvement step cannot make a policy worse; explain why value iteration converges (contraction) and at what rate (γ\gamma); sketch one iteration of policy iteration on a 2-state MDP; and write the primal LP and state what its dual variables mean physically? If any of those stick, revisit the matching section. If all six flow, you’re ready for Chapter 10 — where the model goes away and we learn these same values from samples.