Chapter 15 · Section 15.2 · 65 min

Bellman equations and dynamic programming

At the end of §15.1 we estimated the value of a random walker in the gridworld by running it 2,000 times and averaging the returns. That worked, but it was wasteful in a way that should bother you. The value of the start cell and the value of the cell just above it are not unrelated numbers. Once you have taken one step from the start, the rest of your return is a return from the cell you landed in. So the values of neighboring states must be consistent with each other, and that consistency condition is strong enough to pin them down exactly, without a single simulation.

The condition is the Bellman equation (Bellman 1957), and it is the most important equation in reinforcement learning. This section derives it in its two forms, for evaluating a policy and for finding the best one, proves that the obvious way of solving each form converges, and uses them to solve the gridworld exactly. Then we drop the assumption that we know the environment, and the same equations give us temporal-difference learning and Q-learning, which learn from experience alone.

The Bellman expectation equation

Fix a policy π\pi. As in §15.1, Vπ(s)=Eπ[Gt∣st=s]V^\pi(s) = \mathbb{E}_\pi[G_t \mid s_t = s] is the expected return from state ss, where Gt=∑k≥0γkrt+kG_t = \sum_{k\ge0}\gamma^k r_{t+k} is the discounted return, r(s,a)r(s,a) is the expected reward for action aa in state ss, and P(s′∣s,a)P(s'\mid s, a) is the probability of moving to s′s'. We want an equation that VπV^\pi satisfies.

Start from the recursion for returns, Gt=rt+γGt+1G_t = r_t + \gamma G_{t+1}, and take the expectation given st=ss_t = s,

Vπ(s)=Eπ[rt∣st=s]+γ Eπ[Gt+1∣st=s].V^\pi(s) = \mathbb{E}_\pi[r_t \mid s_t = s] + \gamma\, \mathbb{E}_\pi[G_{t+1} \mid s_t = s].

The first term averages the immediate reward over the action, Eπ[rt∣st=s]=∑aπ(a∣s) r(s,a)\mathbb{E}_\pi[r_t \mid s_t = s] = \sum_a \pi(a\mid s)\, r(s, a). For the second term we condition on what happens next, the action at=aa_t = a and the next state st+1=s′s_{t+1} = s', and use the law of total expectation,

Eπ[Gt+1∣st=s]=∑aπ(a∣s)∑s′P(s′∣s,a)  Eπ[Gt+1∣st=s,at=a,st+1=s′].\mathbb{E}_\pi[G_{t+1} \mid s_t = s] = \sum_a \pi(a \mid s) \sum_{s'} P(s' \mid s, a)\; \mathbb{E}_\pi[G_{t+1} \mid s_t = s, a_t = a, s_{t+1} = s'] .

This is the step where the Markov property earns its keep. Everything that happens from time t+1t+1 on (the actions, drawn from π(⋅∣st+1),…\pi(\cdot \mid s_{t+1}), \dots, and the transitions, drawn from PP) depends on the past only through st+1s_{t+1}. So conditioning on sts_t and ata_t as well changes nothing, and the inner expectation is just the value of s′s',

Eπ[Gt+1∣st=s,at=a,st+1=s′]=Eπ[Gt+1∣st+1=s′]=Vπ(s′).\mathbb{E}_\pi[G_{t+1} \mid s_t = s, a_t = a, s_{t+1} = s'] = \mathbb{E}_\pi[G_{t+1} \mid s_{t+1} = s'] = V^\pi(s').

Putting the pieces together gives the Bellman expectation equation,

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

In plain words, the value of a state is the average, over what the policy does and where the world sends you, of the reward you get now plus the discounted value of where you land.

The same argument for the action-value function, now with the first action fixed, gives

Qπ(s,a)=r(s,a)+γ∑s′P(s′∣s,a)∑a′π(a′∣s′) Qπ(s′,a′),Q^\pi(s, a) = r(s, a) + \gamma \sum_{s'} P(s' \mid s, a) \sum_{a'} \pi(a' \mid s')\, Q^\pi(s', a'),

which is the pair of relations from §15.1, Qπ(s,a)=r(s,a)+γ∑s′P(s′∣s,a)Vπ(s′)Q^\pi(s,a) = r(s,a) + \gamma\sum_{s'}P(s'\mid s,a)V^\pi(s') and Vπ(s′)=∑a′π(a′∣s′)Qπ(s′,a′)V^\pi(s') = \sum_{a'}\pi(a'\mid s')Q^\pi(s',a'), substituted into each other.

The matrix form, and solving it exactly

With finitely many states, the Bellman expectation equation is a system of ∣S∣|\mathcal{S}| linear equations in ∣S∣|\mathcal{S}| unknowns. Collect the policy's average reward and average transitions,

(rπ)s=∑aπ(a∣s) r(s,a)∈R∣S∣,(Pπ)ss′=∑aπ(a∣s) P(s′∣s,a)∈R∣S∣×∣S∣,(\mathbf{r}_\pi)_s = \sum_a \pi(a\mid s)\, r(s,a) \in \R^{|\mathcal{S}|}, \qquad (\mathbf{P}_\pi)_{s s'} = \sum_a \pi(a \mid s)\, P(s' \mid s, a) \in \R^{|\mathcal{S}| \times |\mathcal{S}|},

where Pπ\mathbf{P}_\pi is a row-stochastic matrix (nonnegative entries, each row summing to 1), the transition matrix of the Markov chain you get by running π\pi. Writing v\mathbf{v} for the vector of values Vπ(s)V^\pi(s), the Bellman equation reads

v=rπ+γ Pπv⟹v=(I−γPπ)−1 rπ.\mathbf{v} = \mathbf{r}_\pi + \gamma\, \mathbf{P}_\pi \mathbf{v} \qquad\Longrightarrow\qquad \mathbf{v} = (\mathbf{I} - \gamma \mathbf{P}_\pi)^{-1}\, \mathbf{r}_\pi .

Is the inverse guaranteed to exist? Yes, when γ<1\gamma < 1. For any vector x\mathbf{x}, each entry of Pπx\mathbf{P}_\pi\mathbf{x} is an average of entries of x\mathbf{x}, so ∥Pπx∥∞≤∥x∥∞\lVert \mathbf{P}_\pi \mathbf{x}\rVert_\infty \le \lVert\mathbf{x}\rVert_\infty and every eigenvalue of γPπ\gamma\mathbf{P}_\pi has magnitude at most γ<1\gamma < 1 (its spectral radius, in the language of §0.10, is at most γ\gamma). Then I−γPπ\mathbf{I} - \gamma\mathbf{P}_\pi has no zero eigenvalue, and its inverse is the convergent Neumann series,

(I−γPπ)−1rπ=rπ+γPπrπ+γ2Pπ2rπ+…(\mathbf{I} - \gamma\mathbf{P}_\pi)^{-1}\mathbf{r}_\pi = \mathbf{r}_\pi + \gamma\mathbf{P}_\pi\mathbf{r}_\pi + \gamma^2\mathbf{P}_\pi^2\mathbf{r}_\pi + \dots

In plain words, the kk-th term is the expected reward kk steps from now (Pπk\mathbf{P}_\pi^k is the kk-step transition matrix), discounted by γk\gamma^k, which is the definition of the value read off term by term. This is the "exact value" we used in §15.1. It costs one linear solve, O(∣S∣3)O(|\mathcal{S}|^3), which is nothing for 11 states and hopeless for a game of Go.

Python · cell 1

Those are the values of the random walker in every cell, all negative, because a random walk in this world blunders into the pit far more often than it finds the goal. The two terminal cells show 0 because the episode is over there (the ±1\pm1 is paid on the step that enters them).

Core

Evaluate a policy exactly

Implement evaluate_policy(P, R, pi, gamma) for a finite MDP with P of shape (S, A, S), R of shape (S, A), a stochastic policy pi of shape (S, A) whose rows sum to 1, and 0≤γ<10 \le \gamma < 1. Return VπV^\pi of shape (S,) by solving the Bellman expectation equation as a linear system. Do not iterate.

Hidden tests, hints, and AI help, from $1.99 a month.

Iterative policy evaluation and contraction

The linear solve does not scale, and it does not generalize to the case where we cannot write Pπ\mathbf{P}_\pi down. The alternative is to treat the right-hand side of the Bellman equation as an operator on value functions and apply it repeatedly. Define the Bellman expectation operator Tπ\mathcal{T}^\pi, which takes any value vector v\mathbf{v} (a guess, not necessarily anyone's true value) and returns

(Tπv)(s)=∑aπ(a∣s)[r(s,a)+γ∑s′P(s′∣s,a) v(s′)],that isTπv=rπ+γPπv.(\mathcal{T}^\pi \mathbf{v})(s) = \sum_a \pi(a\mid s)\Big[r(s,a) + \gamma\sum_{s'} P(s'\mid s,a)\, v(s')\Big], \qquad\text{that is}\qquad \mathcal{T}^\pi\mathbf{v} = \mathbf{r}_\pi + \gamma\mathbf{P}_\pi\mathbf{v}.

The Bellman equation says VπV^\pi is a fixed point, TπVπ=Vπ\mathcal{T}^\pi V^\pi = V^\pi. Iterative policy evaluation starts anywhere, say v0=0\mathbf{v}_0 = \mathbf{0}, and repeats vk+1=Tπvk\mathbf{v}_{k+1} = \mathcal{T}^\pi\mathbf{v}_k. Why should that converge, and to the right answer? Because Tπ\mathcal{T}^\pi is a contraction.

Claim. For any two value vectors u\mathbf{u} and v\mathbf{v},

∥Tπu−Tπv∥∞≤γ ∥u−v∥∞,\lVert \mathcal{T}^\pi\mathbf{u} - \mathcal{T}^\pi\mathbf{v} \rVert_\infty \le \gamma\, \lVert \mathbf{u} - \mathbf{v}\rVert_\infty ,

where ∥x∥∞=max⁡s∣xs∣\lVert\mathbf{x}\rVert_\infty = \max_s |x_s| is the largest absolute entry.

Proof. The rewards cancel, so Tπu−Tπv=γPπ(u−v)\mathcal{T}^\pi\mathbf{u} - \mathcal{T}^\pi\mathbf{v} = \gamma\mathbf{P}_\pi(\mathbf{u} - \mathbf{v}). Entry ss of the right side is γ\gamma times a weighted average of the entries of u−v\mathbf{u} - \mathbf{v}, with weights (Pπ)ss′≥0(\mathbf{P}_\pi)_{ss'} \ge 0 that sum to 1. An average is never larger in magnitude than the largest thing being averaged, so every entry is at most γ∥u−v∥∞\gamma\lVert\mathbf{u}-\mathbf{v}\rVert_\infty in magnitude. □\square

In plain words, one application of the operator brings any two guesses at least a factor γ\gamma closer together, measured by their worst disagreement.

That one inequality gives everything. Apply it with u=vk\mathbf{u} = \mathbf{v}_k and v=Vπ\mathbf{v} = V^\pi (using TπVπ=Vπ\mathcal{T}^\pi V^\pi = V^\pi),

∥vk−Vπ∥∞=∥Tπvk−1−TπVπ∥∞≤γ∥vk−1−Vπ∥∞≤⋯≤γk∥v0−Vπ∥∞.\lVert \mathbf{v}_{k} - V^\pi \rVert_\infty = \lVert \mathcal{T}^\pi\mathbf{v}_{k-1} - \mathcal{T}^\pi V^\pi \rVert_\infty \le \gamma \lVert \mathbf{v}_{k-1} - V^\pi\rVert_\infty \le \dots \le \gamma^k \lVert \mathbf{v}_0 - V^\pi\rVert_\infty .

So the error shrinks geometrically, by at least a factor γ\gamma per sweep, from any starting point. The fixed point is also unique. If u\mathbf{u} and v\mathbf{v} were both fixed points, the claim would give ∥u−v∥∞≤γ∥u−v∥∞\lVert\mathbf{u}-\mathbf{v}\rVert_\infty \le \gamma\lVert\mathbf{u}-\mathbf{v}\rVert_\infty, which forces u=v\mathbf{u} = \mathbf{v}. This is the Banach fixed-point theorem in action. A contraction on a complete space has exactly one fixed point, and iterating it from anywhere converges there. Every convergence result in this section is that theorem applied to a different operator.

How many sweeps do you need? To shrink an initial error by a factor ϵ\epsilon you need γk≤ϵ\gamma^k \le \epsilon, so k≥ln⁡(1/ϵ)/ln⁡(1/γ)≈ln⁡(1/ϵ)/(1−γ)k \ge \ln(1/\epsilon)/\ln(1/\gamma) \approx \ln(1/\epsilon)/(1-\gamma). With γ=0.9\gamma = 0.9, a millionfold reduction takes about 131 sweeps. With γ=0.99\gamma = 0.99 it takes about 1,375. Long horizons are slow to evaluate, which is the effective horizon of §15.1 showing up as a convergence rate.

Python · cell 2

The error always sits at or below the γk\gamma^k line, as the proof promises, and in this world it falls faster, because the walker is absorbed by a terminal cell well before the discount alone would wash the future out.

The Bellman optimality equation

Evaluating policies is half the job. We want the best one. Recall from §15.1 that V⋆(s)=max⁡πVπ(s)V^\star(s) = \max_\pi V^\pi(s) and Q⋆(s,a)=max⁡πQπ(s,a)Q^\star(s,a) = \max_\pi Q^\pi(s,a). An optimal agent in state ss takes the action that maximizes immediate reward plus the discounted optimal value of where it lands, so the optimal values should satisfy the Bellman optimality equations,

V⋆(s)=max⁡a[r(s,a)+γ∑s′P(s′∣s,a) V⋆(s′)],Q⋆(s,a)=r(s,a)+γ∑s′P(s′∣s,a) max⁡a′Q⋆(s′,a′).V^\star(s) = \max_a \Big[ r(s, a) + \gamma \sum_{s'} P(s' \mid s, a)\, V^\star(s') \Big], \qquad Q^\star(s, a) = r(s, a) + \gamma \sum_{s'} P(s' \mid s, a)\, \max_{a'} Q^\star(s', a').

In plain words, the best you can do from here is the best first move followed by the best you can do from wherever it takes you. The averaging over the policy's actions in the expectation equation has become a maximum.

That paragraph is a heuristic (Bellman's principle of optimality), and it hides a real question, since V⋆V^\star is defined by a maximum over all policies separately in each state. Here is a complete proof that the equation has exactly one solution, that the solution is V⋆V^\star, and that acting greedily with respect to it is optimal in every state at once. It is short, and it uses only the contraction idea from above.

∂ Proof that the Bellman optimality equation characterizes the optimal policy

Define the Bellman optimality operator (T⋆v)(s)=max⁡a[r(s,a)+γ∑s′P(s′∣s,a)v(s′)](\mathcal{T}^\star\mathbf{v})(s) = \max_a [r(s,a) + \gamma\sum_{s'}P(s'\mid s,a)v(s')], and for brevity write qv(s,a)=r(s,a)+γ∑s′P(s′∣s,a)v(s′)q_{\mathbf{v}}(s, a) = r(s,a) + \gamma\sum_{s'}P(s'\mid s,a)v(s'), so that (T⋆v)(s)=max⁡aqv(s,a)(\mathcal{T}^\star\mathbf{v})(s) = \max_a q_{\mathbf{v}}(s,a). We restrict attention to stationary policies π(a∣s)\pi(a\mid s) (the same rule at every time step). Puterman (1994, Chapter 6) shows that history-dependent policies can do no better, so nothing is lost.

Step 1, a fact about maxima. For any two functions f,gf, g of the action, ∣max⁡af(a)−max⁡ag(a)∣≤max⁡a∣f(a)−g(a)∣|\max_a f(a) - \max_a g(a)| \le \max_a |f(a) - g(a)|. To see it, let a1a_1 maximize ff. Then max⁡f−max⁡g≤f(a1)−g(a1)≤max⁡a∣f(a)−g(a)∣\max f - \max g \le f(a_1) - g(a_1) \le \max_a|f(a) - g(a)|, and swapping the roles of ff and gg bounds the difference from the other side.

Step 2, T⋆\mathcal{T}^\star is a γ\gamma-contraction. By Step 1, for every state,

∣(T⋆u)(s)−(T⋆v)(s)∣≤max⁡a∣qu(s,a)−qv(s,a)∣=γmax⁡a∣∑s′P(s′∣s,a)(u(s′)−v(s′))∣≤γ∥u−v∥∞.|(\mathcal{T}^\star\mathbf{u})(s) - (\mathcal{T}^\star\mathbf{v})(s)| \le \max_a |q_{\mathbf{u}}(s,a) - q_{\mathbf{v}}(s,a)| = \gamma\max_a\Big|\sum_{s'}P(s'\mid s,a)(u(s') - v(s'))\Big| \le \gamma\lVert\mathbf{u}-\mathbf{v}\rVert_\infty .

So, exactly as for Tπ\mathcal{T}^\pi, there is a unique fixed point, which we call vˉ\bar{\mathbf{v}}, and iterating T⋆\mathcal{T}^\star from anywhere converges to it geometrically.

Step 3, monotonicity. Both operators preserve order. If u≤v\mathbf{u} \le \mathbf{v} entrywise, then Tπu≤Tπv\mathcal{T}^\pi\mathbf{u} \le \mathcal{T}^\pi\mathbf{v} and T⋆u≤T⋆v\mathcal{T}^\star\mathbf{u} \le \mathcal{T}^\star\mathbf{v}, because Pπ\mathbf{P}_\pi and PP have nonnegative entries. Also Tπv≤T⋆v\mathcal{T}^\pi\mathbf{v} \le \mathcal{T}^\star\mathbf{v} for every policy and every v\mathbf{v}, because an average over actions is at most the maximum over actions.

Step 4, no policy beats vˉ\bar{\mathbf{v}}. Take any policy π\pi. Using its own Bellman equation and Step 3,

Vπ=TπVπ≤T⋆Vπ.V^\pi = \mathcal{T}^\pi V^\pi \le \mathcal{T}^\star V^\pi .

Apply the monotone operator T⋆\mathcal{T}^\star to both sides again and again, Vπ≤T⋆Vπ≤(T⋆)2Vπ≤…V^\pi \le \mathcal{T}^\star V^\pi \le (\mathcal{T}^\star)^2 V^\pi \le \dots. The right side converges to the fixed point vˉ\bar{\mathbf{v}} by Step 2, so Vπ≤vˉV^\pi \le \bar{\mathbf{v}} in every state.

Step 5, the greedy policy achieves vˉ\bar{\mathbf{v}}. Let πg\pi_g be the deterministic policy that picks πg(s)∈arg⁡max⁡aqvˉ(s,a)\pi_g(s) \in \arg\max_a q_{\bar{\mathbf{v}}}(s, a). By construction Tπgvˉ=T⋆vˉ=vˉ\mathcal{T}^{\pi_g}\bar{\mathbf{v}} = \mathcal{T}^\star\bar{\mathbf{v}} = \bar{\mathbf{v}}, so vˉ\bar{\mathbf{v}} is a fixed point of Tπg\mathcal{T}^{\pi_g}. That operator has only one fixed point, VπgV^{\pi_g}, so Vπg=vˉV^{\pi_g} = \bar{\mathbf{v}}.

Conclusion. Steps 4 and 5 together say vˉ=max⁡πVπ=V⋆\bar{\mathbf{v}} = \max_\pi V^\pi = V^\star, with the maximum attained in every state by the single deterministic policy πg\pi_g. So V⋆V^\star is the unique solution of the Bellman optimality equation, and any policy that is greedy with respect to it is optimal. Since Q⋆(s,a)=qV⋆(s,a)Q^\star(s,a) = q_{V^\star}(s,a), the greedy policy is π⋆(s)=arg⁡max⁡aQ⋆(s,a)\pi^\star(s) = \arg\max_a Q^\star(s, a), as claimed in §15.1. □\square

Value iteration

The proof is also an algorithm. Value iteration starts from v0=0\mathbf{v}_0 = \mathbf{0} and applies the optimality operator, vk+1=T⋆vk\mathbf{v}_{k+1} = \mathcal{T}^\star\mathbf{v}_k, until the values stop changing, then reads off the greedy policy. Each sweep costs O(∣S∣2∣A∣)O(|\mathcal{S}|^2|\mathcal{A}|) for a dense PP.

When should it stop? We cannot measure the distance to the unknown V⋆V^\star, but we can bound it by the change in the last sweep. By the triangle inequality and the contraction,

∥vk+1−V⋆∥∞≤γ∥vk−V⋆∥∞≤γ(∥vk−vk+1∥∞+∥vk+1−V⋆∥∞),\lVert\mathbf{v}_{k+1} - V^\star\rVert_\infty \le \gamma\lVert\mathbf{v}_k - V^\star\rVert_\infty \le \gamma\big(\lVert\mathbf{v}_k - \mathbf{v}_{k+1}\rVert_\infty + \lVert\mathbf{v}_{k+1} - V^\star\rVert_\infty\big),

and moving the last term to the left gives

∥vk+1−V⋆∥∞≤γ1−γ ∥vk+1−vk∥∞.\lVert\mathbf{v}_{k+1} - V^\star\rVert_\infty \le \frac{\gamma}{1-\gamma}\,\lVert\mathbf{v}_{k+1} - \mathbf{v}_k\rVert_\infty .

In plain words, if a sweep changes no value by more than ϵ\epsilon, you are within γϵ/(1−γ)\gamma\epsilon/(1-\gamma) of the optimum, a guarantee you can check without knowing the answer. The greedy policy usually becomes optimal long before the values settle, so in practice value iteration finds the right policy early and then spends many sweeps polishing numbers.

Python · cell 3

With γ=1\gamma = 1 these are exactly the utilities printed in Russell and Norvig's textbook for this world (0.812, 0.868, 0.918 along the top row, and so on), a good check that our transition model matches theirs. Value iteration converges here even though γ=1\gamma = 1 breaks the contraction proof, because every sensible policy ends up in a terminal cell. The optimal policy is worth studying. From the start cell it goes up and around the top, the long way. In the cell left of the pit it moves up, never right, since right walks straight into the pit, and it accepts the 10% chance that an upward move slips sideways into the pit because every safer route costs more steps. And in the bottom-right corner, at γ=1\gamma = 1, it goes left, the long way round, rather than risking the walk up past the pit. At γ=0.9\gamma = 0.9 the agent is more impatient. The cell just left of that corner now goes up, past the pit, instead of taking the long way, and the cell to its left heads right to join it. The discount changed the optimal behavior, just as in the two-state example of §15.1.

How does value iteration discover the best route, and how does the discount change it?
Each press of Step applies one Bellman optimality backup to every cell. Arrows show the greedy action with respect to the current values (several arrows mean a tie).
Loading interactive figure…
Interview

Value iteration with a provable stopping rule

Implement value_iteration(P, R, gamma, tol) for an MDP with P of shape (S, A, S) and R of shape (S, A). Start from v0=0\mathbf{v}_0 = \mathbf{0}, apply vk+1=T⋆vk\mathbf{v}_{k+1} = \mathcal{T}^\star\mathbf{v}_k with no Python loop over states or actions, and stop at the first kk where ∥vk+1−vk∥∞<\lVert\mathbf{v}_{k+1} - \mathbf{v}_k\rVert_\infty < tol. Return (V, pi, n_sweeps) with V =vk+1= \mathbf{v}_{k+1} of shape (S,), pi the greedy actions with respect to the Q table computed in the last sweep (an int array of shape (S,)), and n_sweeps =k+1= k+1, the number of times you applied the operator.

Hidden tests, hints, and AI help, from $1.99 a month.

Policy iteration

Value iteration improves values a little at a time and lets the policy emerge. Policy iteration (Howard 1960) alternates two complete steps on the policy itself.

  1. Evaluate. Compute VπV^{\pi} exactly, with the linear solve of Exercise 15.2a.
  2. Improve. Replace π\pi by the greedy policy π′(s)=arg⁡max⁡aQπ(s,a)\pi'(s) = \arg\max_a Q^\pi(s, a), where Qπ(s,a)=r(s,a)+γ∑s′P(s′∣s,a)Vπ(s′)Q^\pi(s,a) = r(s,a) + \gamma\sum_{s'}P(s'\mid s,a)V^\pi(s').

Stop when the policy no longer changes. Why does the improvement step never make things worse? This is the policy improvement theorem, and its proof is three lines with the tools above. By the definition of π′\pi', Tπ′Vπ=T⋆Vπ≥TπVπ=Vπ\mathcal{T}^{\pi'}V^\pi = \mathcal{T}^\star V^\pi \ge \mathcal{T}^\pi V^\pi = V^\pi. Applying the monotone operator Tπ′\mathcal{T}^{\pi'} repeatedly gives Vπ≤Tπ′Vπ≤(Tπ′)2Vπ≤⋯→Vπ′V^\pi \le \mathcal{T}^{\pi'}V^\pi \le (\mathcal{T}^{\pi'})^2V^\pi \le \dots \to V^{\pi'}. So Vπ′≥VπV^{\pi'} \ge V^\pi in every state. If the greedy step changes nothing, then T⋆Vπ=TπVπ=Vπ\mathcal{T}^\star V^\pi = \mathcal{T}^\pi V^\pi = V^\pi, so VπV^\pi solves the Bellman optimality equation and π\pi is optimal. If π\pi is not optimal, then T⋆Vπ\mathcal{T}^\star V^\pi exceeds VπV^\pi in some state, and so does Vπ′≥Tπ′Vπ=T⋆VπV^{\pi'} \ge \mathcal{T}^{\pi'}V^\pi = \mathcal{T}^\star V^\pi. So each round strictly improves the policy until it is optimal, no policy can be visited twice, and since there are only finitely many deterministic policies, policy iteration terminates in a finite number of rounds. In practice that number is tiny.

Python · cell 4

Policy iteration finishes in a handful of rounds, each one an exact linear solve, where value iteration needed 32 cheaper sweeps (and would need far more for γ\gamma near 1). The initial "always up" policy is terrible (from the start cell it climbs to the top-left corner and keeps bumping into the top edge, paying the step cost and reaching the goal only through lucky sideways slips), and the very first improvement step changes the action in six of the nine states.

each step costssteps neededwhen to use
value iterationone backup, O(∣S∣2∣A∣)O(\lvert\mathcal{S}\rvert^2\lvert\mathcal{A}\rvert)about ln⁡(1/ϵ)/(1−γ)\ln(1/\epsilon)/(1-\gamma)large state spaces, cheap sweeps
policy iterationa linear solve, O(∣S∣3)O(\lvert\mathcal{S}\rvert^3), plus a backupa few (finite, often under 10)small state spaces, exact answers
modified policy iterationmm evaluation sweeps plus a backupin betweenthe practical compromise

All three are instances of what Sutton and Barto call generalized policy iteration, two processes running against each other, one making the values consistent with the policy and one making the policy greedy with respect to the values. Almost every RL algorithm, including actor-critic methods (§15.4) and PPO (§15.6), has this shape, with a critic that evaluates and an actor that improves.

Core

Policy iteration

Implement policy_iteration(P, R, gamma) returning (V, pi, n_rounds). Start from the policy that takes action 0 in every state. Each round, evaluate the current deterministic policy exactly (a linear solve), then improve it greedily with argmax over actions. Stop when the improved policy equals the current one, and return that policy, its values, and the number of evaluation rounds performed (including the last one, which found no change).

Hidden tests, hints, and AI help, from $1.99 a month.

Learning without a model, temporal differences

Everything so far needed PP and rr in hand. That is called planning or dynamic programming. In most problems the agent does not have them. It can only act and observe what happens. Can it still use the Bellman equation?

It can, by replacing the expectation over next states with a single sample. Suppose the agent, following π\pi, is in state sts_t, receives reward rtr_t, and lands in st+1s_{t+1}. The Bellman equation says Vπ(st)V^\pi(s_t) equals the expected value of rt+γVπ(st+1)r_t + \gamma V^\pi(s_{t+1}). So rt+γV(st+1)r_t + \gamma V(s_{t+1}), computed with the current estimate VV, is a one-sample guess of what V(st)V(s_t) should be, and we can nudge the estimate toward it with the incremental-mean update from §15.1,

V(st)←V(st)+α δt,δt=rt+γV(st+1)−V(st),V(s_t) \leftarrow V(s_t) + \alpha\,\delta_t, \qquad \delta_t = r_t + \gamma V(s_{t+1}) - V(s_t),

with a step size α∈(0,1]\alpha \in (0, 1] (we follow Sutton and Barto in writing α\alpha for tabular step sizes). This is TD(0), temporal-difference learning (Sutton 1988), and δt\delta_t is the TD error, the difference between the bootstrapped target and the current estimate. If st+1s_{t+1} is terminal, its value is zero by definition, and the target is just rtr_t. In plain words, after every single step, move your estimate of where you were toward what you got plus your estimate of where you are now.

Compare it with the Monte Carlo update, V(st)←V(st)+α (Gt−V(st))V(s_t) \leftarrow V(s_t) + \alpha\,(G_t - V(s_t)), which waits for the episode to end and uses the actual return.

Monte Carlo target GtG_tTD target rt+γV(st+1)r_t + \gamma V(s_{t+1})
biasunbiased, E[Gt∣st]=Vπ(st)\mathbb{E}[G_t \mid s_t] = V^\pi(s_t)biased while VV is wrong (it trusts its own guess)
variancehigh, a sum of many random rewardslow, one random reward and one random transition
needsthe end of the episodeonly the next step, works online and in continuing tasks
uses the Markov structurenoyes, it bootstraps from the next state's estimate

This bias-variance trade-off between the full return and a one-step bootstrap is one of the deepest themes in RL. §15.5 builds a continuous dial between the two, generalized advantage estimation, and PPO uses it on every step. With step sizes that shrink appropriately (the Robbins and Monro conditions ∑tαt=∞\sum_t\alpha_t = \infty and ∑tαt2<∞\sum_t\alpha_t^2 < \infty, met for instance by αt=1/t\alpha_t = 1/t per state), tabular TD(0) converges to VπV^\pi with probability 1 (Dayan 1992).

Python · cell 5

The result depends on the step size, and both halves of the bias-variance table show up. With a small step (α=0.02\alpha = 0.02), Monte Carlo is ahead after 100 episodes, because TD's knowledge of the terminal rewards has to creep backward one state per update while its early, wrong estimates bias every target. By 400 episodes TD has overtaken it. With a larger step (α=0.1\alpha = 0.1), TD is ahead throughout, by a factor of two to three, because each Monte Carlo update chases a single noisy return and the large step lets that noise kick the estimate around. TD's targets are quieter, so it can afford the larger step. That is the usual pattern, though not a law. When the value estimates are poor and stay poor, bootstrapping from them hurts.

Q-learning

TD(0) evaluates a fixed policy. To control, we need action values, because, as §15.1 noted, choosing an action from VV needs a model to look ahead, while choosing from QQ needs only an argmax. Two TD methods learn QQ.

SARSA applies the Bellman expectation equation for QπQ^\pi to the sample (st,at,rt,st+1,at+1)(s_t, a_t, r_t, s_{t+1}, a_{t+1}), using the next action the agent actually takes,

Q(st,at)←Q(st,at)+α[rt+γQ(st+1,at+1)−Q(st,at)].Q(s_t, a_t) \leftarrow Q(s_t, a_t) + \alpha\big[r_t + \gamma Q(s_{t+1}, a_{t+1}) - Q(s_t, a_t)\big].

Q-learning (Watkins 1989) applies the Bellman optimality equation instead,

Q(st,at)←Q(st,at)+α[rt+γmax⁡a′Q(st+1,a′)−Q(st,at)],Q(s_t, a_t) \leftarrow Q(s_t, a_t) + \alpha\big[r_t + \gamma \max_{a'} Q(s_{t+1}, a') - Q(s_t, a_t)\big],

with the target reduced to rtr_t when st+1s_{t+1} is terminal. In plain words, move the estimate toward the reward plus the value of the best next action, whatever action the agent will actually take next.

That one change, a max instead of the next sampled action, makes Q-learning off-policy. It learns Q⋆Q^\star, the values of the optimal policy, while the agent behaves according to some other policy (for example ε\varepsilon-greedy, which keeps exploring), because the target never refers to the behavior policy's choices. Watkins and Dayan (1992) proved that tabular Q-learning converges to Q⋆Q^\star with probability 1, provided every state-action pair keeps being tried and the step sizes satisfy the Robbins and Monro conditions. SARSA is on-policy. It learns the value of the policy it follows, exploration included, which makes it more cautious near cliffs, since it accounts for its own random steps.

Interview

The Q-learning update

Implement q_learning_update(Q, s, a, r, s_next, terminated, alpha, gamma) for a tabular Q of shape (S, A). Return (Q_new, td_error), where Q_new is a new array (leave the input unchanged) with only entry (s, a) updated by the Q-learning rule, and td_error is δ=target−Q(s,a)\delta = \text{target} - Q(s, a) computed before the update. If terminated is true, s_next is a terminal state and must not be bootstrapped from.

Hidden tests, hints, and AI help, from $1.99 a month.

Here is Q-learning solving the gridworld from experience alone. The agent never sees PP. It explores with ε\varepsilon-greedy actions and starts each episode in a random non-terminal cell, so that every state-action pair keeps being visited, as the convergence theorem requires. We compare what it learned with the Q⋆Q^\star that value iteration computed from the model.

Python · cell 6

After about 16,000 steps the greedy policy is optimal in every cell, though some action values are still off by more than 0.1. Finding the right ranking of actions is much easier than finding their exact values, which is also why value iteration's policy settled long before its values did.

From tables to networks

Real problems have far too many states for a table, so QQ becomes a network Qψ(s,a)Q_\psi(s, a) with parameters ψ\psi, trained to regress onto the Q-learning target. Doing this naively is unstable, and DQN (Mnih et al. 2015), which learned to play 49 Atari games from pixels, needed two stabilizers. An experience replay buffer stores past transitions and trains on random minibatches of them, which breaks the correlation between consecutive samples. A target network, a periodically refreshed copy QψˉQ_{\bar\psi}, computes the targets r+γmax⁡a′Qψˉ(s′,a′)r + \gamma\max_{a'}Q_{\bar\psi}(s', a'), so the regression target does not move with every gradient step. Two further problems are worth knowing by name. The max in the target is biased upward when the estimates are noisy (the maximum of noisy estimates overestimates the maximum of the true values), which double Q-learning fixes by choosing the action with one estimate and evaluating it with another (van Hasselt 2010). And combining function approximation, bootstrapping, and off-policy data, which Sutton and Barto call the deadly triad, can make the values diverge even on tiny problems.

Offline RL, learning from a fixed dataset

Off-policy learning suggests a tempting extreme. If Q-learning can learn from data that some other policy collected, why collect any new data at all? Learning entirely from a fixed log of transitions, with no further interaction, is offline (or batch) RL, and it is what you would want wherever exploring is dangerous or expensive, in medicine, in driving, or with a recommender serving real users.

It is much harder than it looks, and the max in the Q-learning target is the reason. At the next state the max picks whichever action the network rates highest, including actions the dataset never contains, whose values are pure extrapolation. Online, an overrated action gets tried, disappoints, and is corrected. Offline it is never tried, so the error stays, and bootstrapping copies it backward to every state that leads there. The usual result is a policy that heads confidently for exactly the actions the data knows least about, and a deep Q-network trained this way can do worse than just imitating the logged actions (behavior cloning).

The fixes all keep the learned policy close to the data. BCQ (Fujimoto, Meger, and Precup 2019) only considers actions that a model of the logging policy makes likely. Conservative Q-learning (Kumar et al. 2020) adds a penalty that pushes down the values of actions the learned policy favors and pushes up the values of actions in the data, so unseen actions are underrated instead of overrated. Implicit Q-learning (Kostrikov, Nair, and Levine 2022) never evaluates an unseen action at all, replacing the max by an upper expectile of the values of the actions that do appear. Levine et al. (2020) survey the field. The same tension returns with language models. Training on a fixed set of preference pairs, as DPO does, is learning from someone else's samples, and the comparison of online and offline preference learning shows what that costs, while the KL penalty toward a reference model in §15.7 is the same stay-near-the-data idea in another form.

Value-based methods dominate when actions are few and data is cheap to reuse. Language models are the opposite case. They start from a strong pretrained policy (the next-token distribution) that we want to adjust gently, and the policy-gradient methods of §15.3 to §15.6 do exactly that. The Bellman equations do not go away, though. The critic in PPO is a learned VπV^\pi trained with TD-style targets, and its TD errors are the raw material of the advantage estimates in §15.5.

In PyTorch

Here is the loss DQN optimizes, written the way production code writes it, with a target network, a batch of transitions, and a terminal mask. We fill a replay buffer with random gridworld transitions and take a few gradient steps on a small network.

🔥 In PyTorchfor a machine with PyTorch

Read more

Watch next

🎬 RL Course by David Silver - Lecture 3: Planning by Dynamic Programming · Google DeepMindPolicy evaluation, policy iteration, and value iteration, including the contraction mapping argument.
🎬 Bellman Equations, Dynamic Programming, Generalized Policy Iteration | Reinforcement Learning Part 2 · Mutual InformationA visual explanation of the Bellman equations and generalized policy iteration.
🎬 Temporal Difference Learning (including Q-Learning) | Reinforcement Learning Part 4 · Mutual InformationTD(0), SARSA, and Q-learning, and why bootstrapping helps.
🎬 L1 MDPs, Exact Solution Methods, Max-ent RL (Foundations of Deep RL Series) · Pieter AbbeelPieter Abbeel's compact lecture on exact solution methods for MDPs.