Type at least 2 letters. Enter opens the first result, Esc closes.

    Reinforcement Learning · Lesson 2 · MDPs and dynamic programming

    Dynamic programming: policy evaluation, policy iteration and value iteration

    Intermediate 70 min 4 interactive figures 3 videos Colab notebook

    Before this lesson: lesson 01 (MDPs, VπV^\pi, QπQ^\pi, the Bellman equations); the ∞\infty-norm (linear algebra 11); reading a proof by steps (foundations 09). Time: about 70 minutes, plus the notebook.


    Why this matters #

    DP is the exact version of reinforcement learning. Later lessons replace its parts with samples and neural networks: TD learning is sampled policy evaluation (lesson 04), Q-learning is sampled value iteration (lesson 05), actor-critic methods alternate approximate evaluation and improvement (lesson 08), and AlphaZero uses tree search as a policy improvement step and a network as the evaluation (lesson 10). The contraction argument of this lesson explains why these methods converge, and its failure explains why some of them diverge with function approximation (lesson 06).

    1. Predict first #

    2. The picture #

    Evaluation: apply the Bellman equation again and again #

    Lesson 01 solved Vπ=rπ+γPπVπV^\pi = r_\pi + \gamma P_\pi V^\pi with one linear solve. There is a second way. Start from any guess, for example V0=0V_0 = 0, and use the right side as an update:

    Vk+1=rπ+γPπVk.V_{k+1} = r_\pi + \gamma P_\pi V_k .

    Each sweep updates every state from the values of the previous sweep. On the 4×4 gridworld (random policy, reward −1-1 per step, γ=1\gamma = 1), the first row of VkV_k is:

    sweep kk first row of VkV_k
    0 0, 0, 0, 00,\ 0,\ 0,\ 0
    1 0, −1, −1, −10,\ -1,\ -1,\ -1
    2 0, −1.75, −2, −20,\ -1.75,\ -2,\ -2
    3 0, −2.44, −2.94, −30,\ -2.44,\ -2.94,\ -3
    10 0, −6.14, −8.35, −8.970,\ -6.14,\ -8.35,\ -8.97
    ∞\infty 0, −14, −20, −220,\ -14,\ -20,\ -22

    After kk sweeps, Vk(s)V_k(s) is the expected reward of the first kk steps. The values creep towards VπV^\pi. But look at the greedy policy with respect to VkV_k: from k=3k = 3 on, it is already the optimal policy (move straight to the nearest corner). Policies settle long before values do.

    Improvement: act greedily with respect to the values #

    Given values VV, the greedy policy picks in each state an action with the largest one-step lookahead Q(s,a)=R(s,a)+γ∑s′P(s′∣s,a)V(s′)Q(s, a) = R(s, a) + \gamma \sum_{s'} P(s' \mid s, a) V(s'). Evaluate and improve in turn, and you get policy iteration. Do one sweep, then improve, and you get value iteration.

    Interactive figure: loading…

    Press "Evaluate: one sweep" a few times, then "Improve (greedy)". The blue values are VkV_k; the orange arrows are the policy (several arrows = a tie, the agent picks one of them at random). After three sweeps the greedy arrows are already optimal. Then try "Run policy iteration" and "Run value iteration", and the other worlds: in the slippery world, raise the slip and watch the policy move away from the pit; in the cliff world, the safe path moves up when the slip is above 0.

    Generalized policy iteration #

    Both methods are instances of one pattern. Evaluation pushes VV towards VπV^\pi of the current policy. Improvement pushes π\pi towards the greedy policy of the current VV. Each move spoils the other a little: after improvement, VV is no longer the value of the new policy; after evaluation, the policy is no longer greedy. But the two together move to the only point where both are satisfied: the optimal value V∗V^* and an optimal policy π∗\pi^*. Sutton and Barto call this pattern generalized policy iteration (GPI).

    V*, π*evaluation: V → Vπimprovement: π → greedy(V)V = Vππ = greedy(V)
    Generalized policy iteration. The upper blue line is the set of value functions that are the value of the current policy; the lower orange line is the set of policies that are greedy with respect to the current values. Evaluation steps (blue arrows) and improvement steps (orange arrows) alternate. They need not reach their line exactly: any mix of partial evaluation and improvement moves towards the point where the two lines meet, the optimal value and policy.
    Quick check

    In the 4×4 gridworld you compute VπV^\pi for the random policy exactly (−14,−20,−22,…-14, -20, -22, \dots) and then take the greedy policy with respect to it. What do you get?

    3. Definitions and main results #

    Iterative policy evaluation #

    Algorithm (iterative policy evaluation).

    1. Start with V0V_0, for example V0=0V_0 = 0.
    2. Synchronous sweep: compute every state from the old vector, Vk+1(s)=∑aπ(a∣s)[R(s,a)+γ∑s′P(s′∣s,a)Vk(s′)]V_{k+1}(s) = \sum_a \pi(a \mid s)\big[R(s, a) + \gamma \sum_{s'} P(s' \mid s, a) V_k(s')\big].
    3. Stop when ∥Vk+1−Vk∥∞\|V_{k+1} - V_k\|_\infty is small (the stopping rule below says how small).

    In place. Keep one array and overwrite V(s)V(s) as soon as it is computed, so later states in the same sweep already use the new values. This uses half the memory and usually converges faster. On the 4×4 gridworld with tolerance 10−1010^{-10}, synchronous sweeps need 426 sweeps; in-place sweeps in row order need 272.

    Each sweep costs O(∣S∣2∣A∣)O(|\mathcal S|^2 |\mathcal A|) for a dense model, and much less when each state has only a few successors. Why does it converge? The next section answers this for γ<1\gamma < 1. For γ=1\gamma = 1 (the 4×4 gridworld), it converges when the policy ends every episode with probability 1: then PπP_\pi restricted to the non-terminal states has spectral radius below 1.

    The Bellman operators #

    Treat a value function as a vector V∈RSV \in \mathbb R^{\mathcal S}. Two maps from vectors to vectors:

    (TπV)(s)=∑aπ(a∣s)[R(s,a)+γ∑s′P(s′∣s,a)V(s′)],(T^\pi V)(s) = \sum_a \pi(a \mid s)\Big[R(s, a) + \gamma \sum_{s'} P(s' \mid s, a) V(s')\Big],
    (TV)(s)=max⁡a[R(s,a)+γ∑s′P(s′∣s,a)V(s′)].(T V)(s) = \max_a \Big[R(s, a) + \gamma \sum_{s'} P(s' \mid s, a) V(s')\Big].

    TπT^\pi is the Bellman expectation operator, TπV=rπ+γPπVT^\pi V = r_\pi + \gamma P_\pi V. TT is the Bellman optimality operator. In this language, the Bellman equations of lesson 01 say that VπV^\pi is a fixed point of TπT^\pi (TπVπ=VπT^\pi V^\pi = V^\pi) and V∗V^* is a fixed point of TT. Iterative policy evaluation is Vk+1=TπVkV_{k+1} = T^\pi V_k; value iteration will be Vk+1=TVkV_{k+1} = T V_k.

    Monotonicity. If V≤UV \le U in every state, then TπV≤TπUT^\pi V \le T^\pi U and TV≤TUTV \le TU. Reason: P≥0P \ge 0, so a larger VV gives a larger average, and the max of larger numbers is larger. We use this twice below.

    The max lemma #

    Lemma (max lemma). For two functions f,gf, g on a finite set, ∣max⁡af(a)−max⁡ag(a)∣≤max⁡a∣f(a)−g(a)∣\big|\max_a f(a) - \max_a g(a)\big| \le \max_a |f(a) - g(a)|.

    Proof. Suppose max⁡f≥max⁡g\max f \ge \max g (the other case is the same with ff and gg swapped). Let a∗a^* be a maximiser of ff. Then max⁡g≥g(a∗)\max g \ge g(a^*), so

    0≤max⁡f−max⁡g≤f(a∗)−g(a∗)≤max⁡a∣f(a)−g(a)∣.■0 \le \max f - \max g \le f(a^*) - g(a^*) \le \max_a |f(a) - g(a)|. \qquad \blacksquare

    In words: if no action changes its value by more than cc, the best value cannot change by more than cc either. The best action may change, but the best value moves at most as much as the values themselves.

    The contraction theorem #

    Interactive figure: loading…

    Drag the two points. The robot vacuum has two states, so a value function is a point (V(H),V(L))(V(H), V(L)). The blue VV and the violet UU are two guesses; the arrows show where TT sends them. The dashed square around VV has half-width ∥V−U∥∞\|V - U\|_\infty, so UU lies on its edge. The shaded square around TVTV is γ\gamma times smaller, and TUTU always lands inside it. Press "Apply T" a few times: both points move to the same fixed point V∗V^*. The small chart is the max lemma in state H: the gap between the two maxima is never larger than the largest vertical gap.

    Theorem (contraction). For 0≤γ<10 \le \gamma < 1 and all V,U∈RSV, U \in \mathbb R^{\mathcal S},

    ∥TV−TU∥∞≤γ ∥V−U∥∞.\|TV - TU\|_\infty \le \gamma\, \|V - U\|_\infty .

    Hence TT has exactly one fixed point V∗V^*, and value iteration Vk+1=TVkV_{k+1} = TV_k satisfies, from any start V0V_0,

    ∥Vk−V∗∥∞≤γk ∥V0−V∗∥∞and∥Vk+1−V∗∥∞≤γ1−γ ∥Vk+1−Vk∥∞.\|V_k - V^*\|_\infty \le \gamma^k\, \|V_0 - V^*\|_\infty \qquad\text{and}\qquad \|V_{k+1} - V^*\|_\infty \le \frac{\gamma}{1 - \gamma}\, \|V_{k+1} - V_k\|_\infty .

    Proof.

    1. Fix a state ss. Apply the max lemma with f(a)=R(s,a)+γ∑s′P(s′∣s,a)V(s′)f(a) = R(s, a) + \gamma \sum_{s'} P(s' \mid s, a) V(s') and g(a)g(a) the same expression with UU. The rewards cancel in f−gf - g: ∣(TV)(s)−(TU)(s)∣≤γmax⁡a∣∑s′P(s′∣s,a) (V(s′)−U(s′))∣|(TV)(s) - (TU)(s)| \le \gamma \max_a \big|\sum_{s'} P(s' \mid s, a)\,(V(s') - U(s'))\big|.
    2. The weights P(s′∣s,a)P(s' \mid s, a) are ≥0\ge 0 and sum to at most 1, so a weighted sum of numbers of size at most ∥V−U∥∞\|V - U\|_\infty has size at most ∥V−U∥∞\|V - U\|_\infty. So ∣(TV)(s)−(TU)(s)∣≤γ∥V−U∥∞|(TV)(s) - (TU)(s)| \le \gamma \|V - U\|_\infty.
    3. This holds for every ss; take the max over ss. This is the contraction.
    4. At most one fixed point. If V=TVV = TV and U=TUU = TU, then ∥V−U∥∞=∥TV−TU∥∞≤γ∥V−U∥∞\|V - U\|_\infty = \|TV - TU\|_\infty \le \gamma \|V - U\|_\infty. With γ<1\gamma < 1 this forces ∥V−U∥∞=0\|V - U\|_\infty = 0.
    5. A fixed point exists. By step 3, ∥Vk+1−Vk∥∞≤γk∥V1−V0∥∞\|V_{k+1} - V_k\|_\infty \le \gamma^k \|V_1 - V_0\|_\infty, so (Vk)(V_k) is a Cauchy sequence and has a limit V∗V^* (RS\mathbb R^{\mathcal S} is complete). TT is continuous, so TV∗=lim⁡TVk=lim⁡Vk+1=V∗TV^* = \lim TV_k = \lim V_{k+1} = V^*. (This is Banach's fixed-point theorem.)
    6. Rate. ∥Vk−V∗∥=∥TVk−1−TV∗∥≤γ∥Vk−1−V∗∥≤⋯≤γk∥V0−V∗∥\|V_k - V^*\| = \|TV_{k-1} - TV^*\| \le \gamma \|V_{k-1} - V^*\| \le \dots \le \gamma^k \|V_0 - V^*\|.
    7. Stopping rule. By step 6 and the triangle inequality, ∥Vk+1−V∗∥≤γ∥Vk−V∗∥≤γ(∥Vk−Vk+1∥+∥Vk+1−V∗∥)\|V_{k+1} - V^*\| \le \gamma \|V_k - V^*\| \le \gamma\big(\|V_k - V_{k+1}\| + \|V_{k+1} - V^*\|\big). Move the last term to the left: (1−γ)∥Vk+1−V∗∥≤γ∥Vk+1−Vk∥(1 - \gamma)\|V_{k+1} - V^*\| \le \gamma \|V_{k+1} - V_k\|. ■\blacksquare

    The same proof without the max (step 1 without the lemma) shows that TπT^\pi is a γ\gamma-contraction too. So iterative policy evaluation converges to VπV^\pi from any start, with the same rate and stopping rule.

    How many iterations? To shrink the error by a factor ε\varepsilon you need γk≤ε\gamma^k \le \varepsilon, that is

    k≥log⁡(1/ε)log⁡(1/γ)≈log⁡(1/ε)1−γ(γ close to 1).k \ge \frac{\log(1/\varepsilon)}{\log(1/\gamma)} \approx \frac{\log(1/\varepsilon)}{1 - \gamma}\quad (\gamma \text{ close to } 1).

    The number of iterations grows like the effective horizon 1/(1−γ)1/(1-\gamma).

    Interactive figure: loading…

    Move γ\gamma and predict the slope. On a log scale, the true error ∥Vk−V∗∥∞\|V_k - V^*\|_\infty (blue) follows the theorem's line γk∥V0−V∗∥∞\gamma^k \|V_0 - V^*\|_\infty (violet, dashed); the slope is log⁡γ\log \gamma. The grey dashed line is the stopping-rule bound, which you can compute without knowing V∗V^*. The orange line marks the iteration from which the greedy policy is optimal: on the 5×5 grid with γ=0.9\gamma = 0.9 this is iteration 29, while the value error is still about 1.15.

    Quick check

    Value iteration with γ=0.99\gamma = 0.99. About how many iterations does the theorem need to shrink the error by a factor 10610^6?

    Quick check

    On the robot vacuum (γ=0.9\gamma = 0.9), value iteration from V0=0V_0 = 0 gives V1=(2,1)V_1 = (2, 1), so ∥V1−V0∥∞=2\|V_1 - V_0\|_\infty = 2. What does the stopping rule guarantee?

    V∗V^* is the fixed point of TT #

    Lesson 01 used this fact. Here is the proof.

    Theorem. Let γ<1\gamma < 1, let Vˉ\bar V be the fixed point of TT, and let πˉ\bar\pi be greedy with respect to Vˉ\bar V. Then Vπˉ=VˉV^{\bar\pi} = \bar V, and Vπ≤VˉV^\pi \le \bar V for every policy π\pi. So Vˉ=V∗\bar V = V^*, and πˉ\bar\pi is optimal.

    Proof
    1. Greedy means TπˉVˉ=TVˉT^{\bar\pi} \bar V = T \bar V. With TVˉ=VˉT\bar V = \bar V, this gives TπˉVˉ=VˉT^{\bar\pi}\bar V = \bar V. VπˉV^{\bar\pi} is the only fixed point of TπˉT^{\bar\pi}, so Vπˉ=VˉV^{\bar\pi} = \bar V.
    2. For any policy π\pi and any VV, an average over actions is at most the max: TπV≤TVT^\pi V \le TV. So TπVˉ≤TVˉ=VˉT^\pi \bar V \le T\bar V = \bar V.
    3. Apply TπT^\pi again and use monotonicity: (Tπ)2Vˉ≤TπVˉ≤Vˉ(T^\pi)^2 \bar V \le T^\pi \bar V \le \bar V. By induction, (Tπ)kVˉ≤Vˉ(T^\pi)^k \bar V \le \bar V for all kk.
    4. Let k→∞k \to \infty: (Tπ)kVˉ→Vπ(T^\pi)^k \bar V \to V^\pi (contraction). So Vπ≤VˉV^\pi \le \bar V. With step 1, Vˉ=max⁡πVπ=V∗\bar V = \max_\pi V^\pi = V^*. ■\blacksquare

    This proof compares stationary policies. A classical result (Puterman 1994, ch. 6) shows that policies that use the whole history or the time cannot do better in a finite discounted MDP, so nothing is lost.

    The policy improvement theorem #

    Theorem (policy improvement). Let π\pi and π′\pi' be two policies with

    ∑aπ′(a∣s) Qπ(s,a)≥Vπ(s)for every state s.\sum_a \pi'(a \mid s)\, Q^\pi(s, a) \ge V^\pi(s) \quad\text{for every state } s.

    Then Vπ′(s)≥Vπ(s)V^{\pi'}(s) \ge V^\pi(s) for every state ss. If the first inequality is strict in some state, the second is strict there too.

    For a deterministic π′\pi' the condition reads Qπ(s,π′(s))≥Vπ(s)Q^\pi(s, \pi'(s)) \ge V^\pi(s): "take π′\pi''s action now, then follow π\pi" is at least as good as following π\pi. The theorem says: then following π′\pi' forever is also at least as good.

    Proof.

    1. The left side of the condition is (Tπ′Vπ)(s)(T^{\pi'} V^\pi)(s). So the condition says Tπ′Vπ≥VπT^{\pi'} V^\pi \ge V^\pi.
    2. Apply Tπ′T^{\pi'} and use monotonicity: (Tπ′)2Vπ≥Tπ′Vπ≥Vπ(T^{\pi'})^2 V^\pi \ge T^{\pi'} V^\pi \ge V^\pi. By induction the sequence (Tπ′)kVπ(T^{\pi'})^k V^\pi increases with kk.
    3. It converges to the fixed point of Tπ′T^{\pi'}, which is Vπ′V^{\pi'}. An increasing sequence stays above its first terms, so Vπ′≥Tπ′Vπ≥VπV^{\pi'} \ge T^{\pi'} V^\pi \ge V^\pi.
    4. If (Tπ′Vπ)(s)>Vπ(s)(T^{\pi'} V^\pi)(s) > V^\pi(s) in some state ss, step 3 gives Vπ′(s)>Vπ(s)V^{\pi'}(s) > V^\pi(s). ■\blacksquare

    The same idea, unrolled in time: Vπ(s)≤E[rt+γVπ(st+1)]V^\pi(s) \le \mathbb E[r_t + \gamma V^\pi(s_{t+1})] with the first action from π′\pi'; apply the condition again at st+1s_{t+1}, then at st+2s_{t+2}, and so on. Every rewritten step follows π′\pi', and the leftover term γkVπ(st+k)\gamma^k V^\pi(s_{t+k}) goes to 0.

    The greedy policy π′(s)∈arg⁡max⁡aQπ(s,a)\pi'(s) \in \arg\max_a Q^\pi(s, a) satisfies the condition, because the max is at least the π\pi-average: max⁡aQπ(s,a)≥∑aπ(a∣s)Qπ(s,a)=Vπ(s)\max_a Q^\pi(s, a) \ge \sum_a \pi(a \mid s) Q^\pi(s, a) = V^\pi(s).

    Policy iteration #

    Algorithm (policy iteration). Start from any policy π0\pi_0. For i=0,1,2,…i = 0, 1, 2, \dots:

    1. Evaluate: compute VπiV^{\pi_i} exactly (one linear solve, lesson 01).
    2. Improve: πi+1(s)∈arg⁡max⁡aQπi(s,a)\pi_{i+1}(s) \in \arg\max_a Q^{\pi_i}(s, a), where Qπi=R+γPVπiQ^{\pi_i} = R + \gamma P V^{\pi_i}. If the current action is already among the best, keep it.
    3. If πi+1=πi\pi_{i+1} = \pi_i, stop.

    Why it stops at an optimal policy.

    • Each step is at least as good: Vπi+1≥VπiV^{\pi_{i+1}} \ge V^{\pi_i} (policy improvement theorem).
    • If the policy changes, some state gets a strictly better action, so the value strictly increases there. Then no policy can appear twice.
    • There are at most ∣A∣∣S∣|\mathcal A|^{|\mathcal S|} deterministic policies, so the loop stops after finitely many steps.
    • When it stops, πi\pi_i is greedy with respect to its own values: TVπi=TπiVπi=VπiT V^{\pi_i} = T^{\pi_i} V^{\pi_i} = V^{\pi_i}. So VπiV^{\pi_i} is the fixed point of TT, which is V∗V^*.

    The rule "keep the current action when it is among the best" matters. Without it, two tied actions can make the policy switch back and forth forever (with floating-point numbers, use a small tolerance such as 10−1010^{-10}).

    Quick check

    Why can policy iteration never produce a policy that is worse than the previous one in some state?

    Value iteration and its relatives #

    Algorithm (value iteration). Start from any V0V_0 (often 0). Repeat Vk+1=TVkV_{k+1} = TV_k until γ1−γ∥Vk+1−Vk∥∞\frac{\gamma}{1-\gamma}\|V_{k+1} - V_k\|_\infty is below your tolerance. Return the greedy policy with respect to the final VV.

    Value iteration is policy iteration with one sweep. Let πk+1\pi_{k+1} be greedy with respect to VkV_k. Then TVk=Tπk+1VkTV_k = T^{\pi_{k+1}} V_k: one improvement, then one sweep of evaluation of the new policy, instead of a full solve.

    What is VkV_k? Vk=Tk0V_k = T^k 0 is the best expected discounted reward over the first kk steps only. It is not the value of any stationary policy in general. For example, V1=(2,1)V_1 = (2, 1) on the robot vacuum is just "the best reward now". Only the limit V∗V^* is a policy's value.

    Modified policy iteration. Do mm sweeps of evaluation after each improvement, V←(Tπ)mVV \leftarrow (T^{\pi})^m V. With m=1m = 1 this is value iteration; with m→∞m \to \infty it is policy iteration. Values in between often work best in practice.

    Generalized policy iteration is any scheme that interleaves some evaluation with some improvement, in any order and in any amount, state by state if you like. If both continue, the process converges to V∗V^* and π∗\pi^* (the GPI figure in section 2). Almost every RL algorithm has this form.

    Quick check

    Value iteration on the robot vacuum gives V2=(3.35,1.9)V_2 = (3.35, 1.9). Is there a stationary policy π\pi with Vπ=V2V^\pi = V_2?

    The cost of the two methods #

    one iteration costs (dense model) number of iterations
    policy iteration O(S3+S2A)O(S^3 + S^2 A): a linear solve, then the improvement few in practice (at most ASA^S)
    value iteration O(S2A)O(S^2 A): one max backup of every state about log⁡(1/ε)/log⁡(1/γ)\log(1/\varepsilon) / \log(1/\gamma); many when γ→1\gamma \to 1

    Here S=∣S∣S = |\mathcal S| and A=∣A∣A = |\mathcal A|. Policy iteration wins when γ\gamma is close to 1 and the state space is small enough for a linear solve. Value iteration wins when SS is large and γ\gamma is moderate, or when only a good policy (not exact values) is needed.

    Interactive figure: loading…

    Predict, then press "Step both" a few times, and then "Run both to the end". Each step is one iteration of each method. On the 5×5 grid, policy iteration finishes after 5 evaluations; value iteration needs 154 sweeps to reach ∥Vk+1−Vk∥∞<10−6\|V_{k+1} - V_k\|_\infty < 10^{-6}, but its greedy policy is optimal much earlier. The cost line uses the dense model of the table.

    Answers to section 1. (1) About 5: on the 5×5 grid, policy iteration needs 5 evaluations when tied actions share the probability (the widget above), and 3 when ties go to the lowest action index. (2) Before: the greedy policy is optimal from iteration 29, while the value error is still about 1.15. (3) About 10 times more, because the number of iterations grows like 1/(1−γ)1/(1-\gamma): on the 5×5 grid, 162 iterations for γ=0.9\gamma = 0.9 and 1904 for γ=0.99\gamma = 0.99 (error below 10−610^{-6}).

    Linear programming, asynchronous DP, and the curse of dimensionality

    A linear program. V∗V^* is also the solution of

    min⁡V∑sV(s)subject toV(s)≥R(s,a)+γ∑s′P(s′∣s,a)V(s′) for all (s,a).\min_V \sum_s V(s) \quad\text{subject to}\quad V(s) \ge R(s, a) + \gamma \sum_{s'} P(s' \mid s, a) V(s') \text{ for all } (s, a).

    Why: the constraints say V≥TVV \ge TV. By monotonicity, V≥TV≥T2V≥⋯→V∗V \ge TV \ge T^2 V \ge \dots \to V^*, so every feasible VV is ≥V∗\ge V^* in every state. And V∗V^* itself is feasible. So V∗V^* is the smallest feasible point, and it minimises any sum with positive weights. This gives a third exact method, and LP duality leads to the "occupancy measure" view used in offline RL and imitation learning.

    Asynchronous DP. You do not have to sweep all states in order. Update any state at any time, using the latest values of the others. As long as every state is updated infinitely often, the values still converge to VπV^\pi or V∗V^* (Bertsekas and Tsitsiklis). In-place sweeps are one example. Real-time DP updates only the states that an agent visits, which focuses the work on relevant states.

    The curse of dimensionality. DP needs the model and touches every state in every sweep. A state made of dd variables with 10 values each has 10d10^d states. Backgammon has about 102010^{20} positions and Go about 1017010^{170}. So we need two more ideas: learning from samples instead of the model (lessons 03–05) and function approximation instead of a table (lesson 06).

    4. Worked example #

    (a) Policy iteration on the robot vacuum (γ=0.9\gamma = 0.9, states H, L), starting from "always clean".

    Evaluation 1. From lesson 01: Vπ0=(130/11, 10)≈(11.82, 10)V^{\pi_0} = (130/11,\ 10) \approx (11.82,\ 10).

    Improvement 1. Compute Qπ0=R+γPVπ0Q^{\pi_0} = R + \gamma P V^{\pi_0}:

    • H: clean =2+0.9 (0.5⋅11.82+0.5⋅10)=11.82= 2 + 0.9\,(0.5 \cdot 11.82 + 0.5 \cdot 10) = 11.82; charge =0+0.9⋅11.82=10.64= 0 + 0.9 \cdot 11.82 = 10.64. Keep clean.
    • L: clean =1+0.9⋅10=10= 1 + 0.9 \cdot 10 = 10; charge =0.9⋅11.82=10.64= 0.9 \cdot 11.82 = 10.64. Switch to charge.

    Evaluation 2. For "clean in H, charge in L": Vπ1=(400/29, 360/29)≈(13.79, 12.41)V^{\pi_1} = (400/29,\ 360/29) \approx (13.79,\ 12.41) (lesson 01). Both states improved, as the theorem promises.

    Improvement 2.

    • H: clean =2+0.9 (0.5⋅13.79+0.5⋅12.41)=13.79= 2 + 0.9\,(0.5 \cdot 13.79 + 0.5 \cdot 12.41) = 13.79; charge =0.9⋅13.79=12.41= 0.9 \cdot 13.79 = 12.41. Keep clean.
    • L: clean =1+0.9⋅12.41=12.17= 1 + 0.9 \cdot 12.41 = 12.17; charge =0.9⋅13.79=12.41= 0.9 \cdot 13.79 = 12.41. Keep charge.

    Nothing changes, so the policy is optimal and V∗=(400/29, 360/29)V^* = (400/29,\ 360/29). Policy iteration needed two evaluations.

    (b) Value iteration on the robot vacuum, from V0=(0,0)V_0 = (0, 0). Each step takes, in each state, the max of "clean" and "charge".

    • k=1k = 1: H: max⁡(2+0.9⋅0, 0.9⋅0)=2\max(2 + 0.9 \cdot 0,\ 0.9 \cdot 0) = 2. L: max⁡(1+0, 0)=1\max(1 + 0,\ 0) = 1. So V1=(2,1)V_1 = (2, 1).
    • k=2k = 2: H: max⁡(2+0.9 (0.5⋅2+0.5⋅1), 0.9⋅2)\max\big(2 + 0.9\,(0.5 \cdot 2 + 0.5 \cdot 1),\ 0.9 \cdot 2\big) =max⁡(3.35, 1.8)=3.35= \max(3.35,\ 1.8) = 3.35. L: max⁡(1+0.9⋅1, 0.9⋅2)\max(1 + 0.9 \cdot 1,\ 0.9 \cdot 2) =max⁡(1.9, 1.8)=1.9= \max(1.9,\ 1.8) = 1.9. So V2=(3.35,1.9)V_2 = (3.35, 1.9).
    • k=3k = 3: H: max⁡(2+0.9 (0.5⋅3.35+0.5⋅1.9), 0.9⋅3.35)\max\big(2 + 0.9\,(0.5 \cdot 3.35 + 0.5 \cdot 1.9),\ 0.9 \cdot 3.35\big) =max⁡(4.3625, 3.015)=4.3625= \max(4.3625,\ 3.015) = 4.3625. L: max⁡(1+0.9⋅1.9, 0.9⋅3.35)\max(1 + 0.9 \cdot 1.9,\ 0.9 \cdot 3.35) =max⁡(2.71, 3.015)=3.015= \max(2.71,\ 3.015) = 3.015. So V3=(4.3625,3.015)V_3 = (4.3625, 3.015).

    At k=3k = 3, the max in L is "charge" for the first time: the greedy policy with respect to V2V_2 is already optimal. But the values are still far from V∗V^*:

    • true error: ∥V3−V∗∥∞=13.79−4.36=9.43\|V_3 - V^*\|_\infty = 13.79 - 4.36 = 9.43;
    • theorem: γ3∥V0−V∗∥∞=0.729⋅13.79=10.06≥9.43\gamma^3 \|V_0 - V^*\|_\infty = 0.729 \cdot 13.79 = 10.06 \ge 9.43 ✓;
    • stopping rule: 0.90.1∥V3−V2∥∞=9⋅max⁡(1.0125, 1.115)=10.04≥9.43\frac{0.9}{0.1}\|V_3 - V_2\|_\infty = 9 \cdot \max(1.0125,\ 1.115) = 10.04 \ge 9.43 ✓.

    (c) The 5×5 gridworld (Sutton and Barto, Example 3.5, γ=0.9\gamma = 0.9). From cell A every action earns +10+10 and jumps to A′ in the bottom row. With V∗(A′)=16.02V^*(A') = 16.02 (from value iteration):

    V∗(A)=10+0.9⋅V∗(A′)=10+0.9⋅16.02=24.42.V^*(A) = 10 + 0.9 \cdot V^*(A') = 10 + 0.9 \cdot 16.02 = 24.42 .

    The cell left of A has no reward of its own, and its best move is into A: V∗(0,0)=0+0.9⋅24.42=21.98V^*(0, 0) = 0 + 0.9 \cdot 24.42 = 21.98. Every optimal value is the best, over the four actions, of "reward now plus 0.90.9 times the value of the next cell": exactly the optimality equation.

    5. In code #

    NumPy and SciPy check the worked example: policy iteration, value iteration with the stopping rule, and the linear program of the deeper box as a third route to V∗V^*.

    import numpy as np
    from scipy.optimize import linprog
    
    gamma = 0.9
    P = np.zeros((2, 2, 2))                      # robot vacuum: P[s, a, s'], states (H, L)
    P[0, 0] = [0.5, 0.5]; P[0, 1] = [1, 0]       # actions (clean, charge)
    P[1, 0] = [0, 1];     P[1, 1] = [1, 0]
    R = np.array([[2.0, 0.0], [1.0, 0.0]])
    
    def evaluate(pi):                            # deterministic pi: one action per state
        P_pi, r_pi = P[[0, 1], pi], R[[0, 1], pi]
        return np.linalg.solve(np.eye(2) - gamma * P_pi, r_pi)
    
    # policy iteration from "always clean"
    pi = np.array([0, 0])
    while True:
        V = evaluate(pi)
        print(pi, V.round(3))                    # [0 0] [11.818 10.   ]  then  [0 1] [13.793 12.414]
        new = (R + gamma * P @ V).argmax(axis=1) # greedy (no ties here)
        if np.array_equal(new, pi):
            break
        pi = new
    
    # value iteration with the stopping rule
    V, k = np.zeros(2), 0
    while True:
        V_new = (R + gamma * P @ V).max(axis=1)
        k += 1
        done = gamma / (1 - gamma) * np.abs(V_new - V).max() < 1e-6
        V = V_new
        if done:
            break
    print(k, V.round(4))                         # 156 [13.7931 12.4138]
    
    # linear program: minimise sum V(s) subject to V(s) >= R(s,a) + gamma * sum_s' P V
    A_ub = gamma * P.reshape(4, 2) - np.repeat(np.eye(2), 2, axis=0)   # rows (s, a)
    res = linprog(c=np.ones(2), A_ub=A_ub, b_ub=-R.reshape(4), bounds=[(None, None)] * 2)
    print(res.x.round(3), 400 / 29, 360 / 29)    # [13.793 12.414] 13.793... 12.413...
    

    P[[0, 1], pi] picks the row P[s, pi[s]] for each state, which is PπP_\pi for a deterministic policy.

    6. Where it shows up #

    • Planning with a known model. Inventory control, queueing and maintenance problems in operations research, and small control problems in engineering, are solved exactly with value or policy iteration, or with the LP.
    • Q-learning and DQN are sampled value iteration on QQ; their targets r+γmax⁡a′Q(s′,a′)r + \gamma \max_{a'} Q(s', a') are one application of TT (lessons 05 and 06).
    • Actor-critic and PPO follow GPI: a critic does approximate evaluation, the policy update does a soft improvement (lessons 08 and 09).
    • AlphaZero and expert iteration use tree search as the improvement step and a value network as the evaluation (lesson 10).
    • Model-based RL learns PP and RR from data and then plans with DP-like updates (Dyna, lesson 10).
    • ML for science. Planning on a learned emulator, for example the control of a physical process with a fitted model, is DP on an approximate MDP. The contraction bound tells you how errors in the model or in the values propagate: an error ϵ\epsilon in each backup gives at most ϵ/(1−γ)\epsilon/(1-\gamma) in the final values.

    7. Common mistakes #

    • Expecting values and policies to converge together. The greedy policy is often optimal long before the values are accurate. Stop by the policy when you only need the policy.
    • Mixing synchronous and in-place updates by accident. V = r_pi + gamma * P_pi @ V is synchronous; a loop that writes V[s] and reads V in the same sweep is in place. Both converge, but the iteration counts differ.
    • Policy iteration that never stops. With ties and floating-point noise, the argmax can switch between equal actions forever. Keep the current action if it is within a small tolerance of the best.
    • Using the stopping rule with γ=1\gamma = 1. The factor γ/(1−γ)\gamma/(1-\gamma) is infinite; the contraction proof does not apply. Episodic problems with γ=1\gamma = 1 converge only for policies that end every episode.
    • Taking VkV_k as a policy's value. Value iteration's VkV_k is a kk-step value, not VπV^\pi of any policy. Evaluate the greedy policy if you need its true value.
    • Forgetting the model. Every method here needs PP and RR. Without them, use the sample-based methods of lessons 03–05.

    8. Check yourself #

    1. Show that TT is monotone: V≤UV \le U implies TV≤TUTV \le TU.
      AnswerFor each (s,a)(s, a), ∑s′P(s′∣s,a)V(s′)≤∑s′P(s′∣s,a)U(s′)\sum_{s'} P(s' \mid s, a) V(s') \le \sum_{s'} P(s' \mid s, a) U(s') because P≥0P \ge 0. So every term inside the max is at most the matching term for UU, and the max of smaller numbers is at most the max of larger numbers.
    2. Value iteration with γ=0.95\gamma = 0.95 gives ∥Vk+1−Vk∥∞=0.01\|V_{k+1} - V_k\|_\infty = 0.01. What is the guaranteed bound on ∥Vk+1−V∗∥∞\|V_{k+1} - V^*\|_\infty?
      Answer0.950.05⋅0.01=0.19\frac{0.95}{0.05} \cdot 0.01 = 0.19.
    3. Why does policy iteration stop after finitely many iterations?
      AnswerEach change gives a strictly better value in some state and no worse value anywhere, so no policy can repeat. There are at most ∣A∣∣S∣|\mathcal A|^{|\mathcal S|} deterministic policies. (This needs the rule that ties keep the current action.)
    4. Write one value-iteration step as "improvement plus evaluation".
      AnswerLet πk+1\pi_{k+1} be greedy with respect to VkV_k. Then Vk+1=TVk=Tπk+1VkV_{k+1} = TV_k = T^{\pi_{k+1}} V_k: one sweep of evaluation of the new greedy policy, starting from VkV_k.
    5. In the 5×5 gridworld, why is V∗(0,0)=0.9 V∗(A)V^*(0, 0) = 0.9\, V^*(A)?
      AnswerFrom the corner (0,0)(0, 0), the best action moves right into A with reward 0. The optimality equation gives V∗(0,0)=0+0.9⋅V∗(A)=0.9⋅24.42=21.98V^*(0,0) = 0 + 0.9 \cdot V^*(A) = 0.9 \cdot 24.42 = 21.98.
    6. You have 10 000 states, 4 actions and γ=0.999\gamma = 0.999. Would you start with policy iteration or value iteration? Why?
      AnswerPolicy iteration (or modified policy iteration). Value iteration needs about log⁡(1/ε)/(1−γ)≈1000⋅log⁡(1/ε)\log(1/\varepsilon)/(1-\gamma) \approx 1000 \cdot \log(1/\varepsilon) sweeps. Policy iteration needs a few linear solves; with sparse transitions an iterative solver handles 10410^4 states easily.
    Recall cardsAnswer in your head first, then reveal. Add the cards to your review deck to see them again just before you would forget.
    1. Define the Bellman optimality operator TT.

    2. State the contraction property of TT.

    3. State the max lemma.

    4. Give the stopping rule of value iteration.

    5. About how many value-iteration steps shrink the error by a factor ε\varepsilon?

    6. State the policy improvement theorem.

    7. What does one iteration of policy iteration cost, and of value iteration?

    8. Why is value iteration "policy iteration with one sweep"?

    9. What is generalized policy iteration, in one sentence?

    10. Compute the stopping-rule bound for γ=0.9\gamma = 0.9 and ∥Vk+1−Vk∥∞=2\|V_{k+1} - V_k\|_\infty = 2.

    Open the review →

    9. Interview angle #

    • "Policy iteration or value iteration?" PI: few, expensive iterations (a linear solve each); good when γ\gamma is close to 1 and SS is moderate. VI: cheap iterations, about log⁡(1/ε)/(1−γ)\log(1/\varepsilon)/(1-\gamma) of them. Modified PI sits in between.
    • "Why does value iteration converge?" TT is a γ\gamma-contraction in the ∞\infty-norm (max lemma plus P≥0P \ge 0, rows sum to at most 1), so Banach's theorem gives a unique fixed point and a geometric rate γk\gamma^k.
    • "Prove the policy improvement theorem." The condition is Tπ′Vπ≥VπT^{\pi'} V^\pi \ge V^\pi; monotonicity gives (Tπ′)kVπ≥Vπ(T^{\pi'})^k V^\pi \ge V^\pi, and the limit is Vπ′V^{\pi'}.
    • "Why do we need anything beyond DP?" DP needs the model and a table over all states. Real problems have unknown dynamics and huge state spaces, so we sample (TD, Q-learning) and approximate (neural networks).

    10. Practice #

    The notebook for this lesson runs in Colab. It has five exercises, each with a check cell and a folded solution:

    1. policy_evaluation_iterative: synchronous sweeps; count them on the 4×4 gridworld and compare with the linear solve.
    2. bellman_optimality_operator, and a numerical check of the contraction on 200 random pairs V,UV, U.
    3. value_iteration with the stopping rule; reproduce V∗V^* of the 5×5 gridworld (24.4224.42 at A).
    4. policy_iteration with stable tie-breaking; check that it agrees with value iteration and that values never decrease.
    5. The linear program with scipy.optimize.linprog: its solution equals V∗V^*.

    11. Watch and read #

    Policy evaluation, policy iteration, value iteration and the contraction argument, with the small gridworld of this lesson.
    Open on YouTube · the player loads from youtube-nocookie.com when you press play
    A visual summary of the Bellman equations, policy and value iteration, and the GPI picture.
    Open on YouTube · the player loads from youtube-nocookie.com when you press play
    Value iteration and policy iteration from the deep-RL point of view; the last part previews entropy-regularised RL (lesson 08).
    Open on YouTube · the player loads from youtube-nocookie.com when you press play