Course contents 03 / 27

03 / 27 · Agents and Environments

Markov decision processes

Planning when actions have random outcomes: states, actions, transitions, rewards, discounting, policies and returns, the Bellman expectation and optimality equations derived step by step, value iteration as a contraction, policy iteration, a gridworld, and belief states.

On this page 8

Search returned a sequence of actions, which works when every action has one known outcome. When a step can go wrong, a wheel slips or a test is flaky, the agent cannot commit to a sequence in advance: after each step it may find itself somewhere it did not intend, and it needs to know what to do there too. The object to compute is then a policy, an action for every state, and the criterion is the expected sum of rewards rather than the cost of one path. This note sets up the standard model of that problem, the Markov decision process, derives the two Bellman equations that its values satisfy, and solves them with value iteration and policy iteration on a small gridworld. The same equations are the starting point of the whole reinforcement-learning section.

Notation. S\mathcal S and A\mathcal A are finite sets of states and actions. P(s′∣s,a)P(s' \mid s, a) is the probability of moving to s′s' after action aa in ss, R(s,a,s′)R(s, a, s') the reward received on that transition, and γ∈[0,1)\gamma \in [0, 1) the discount. St,At,Rt+1S_t, A_t, R_{t+1} are the random state, action and reward at step tt. A policy π(a∣s)\pi(a \mid s) gives the probability of action aa in state ss; a deterministic policy is written π(s)\pi(s). GtG_t is the return from step tt; VπV^\pi and QπQ^\pi are the state and action values of π\pi, V⋆V^\star and Q⋆Q^\star the optimal ones. For a vector VV indexed by states, ∥V∥∞=max⁡s∣V(s)∣\lVert V \rVert_\infty = \max_s |V(s)|. Eπ\mathbb E_\pi is an expectation over trajectories generated by π\pi and PP.

Baseline: a fixed plan in a random world#

The example of the note is the 4 × 3 gridworld of Russell and Norvig (2021), chapter 17. The agent moves on a grid of four columns and three rows, cells written (column,row)(\text{column}, \text{row}) from (1,1)(1, 1) at the bottom left. Cell (2,2)(2, 2) is a wall. Entering (4,3)(4, 3), the goal, gives a reward of +1+1; entering (4,2)(4, 2), the pit, gives −1-1; both end the episode. Every other step gives −0.04-0.04, a small cost of time. The actions are N, E, S and W, and they are unreliable: an action moves in its direction with probability 0.80.8 and slips to each side, at right angles, with probability 0.10.1. A move into the wall or off the grid leaves the agent where it is. We use the discount γ=0.9\gamma = 0.9.

Ignore the slips and search finds the shortest path from (1,1)(1, 1): N, N, E, E, E. Executed blindly, this plan reaches the goal with probability 0.85+0.14⋅0.8=0.327760.8^5 + 0.1^4 \cdot 0.8 = 0.32776: either every action succeeds, or the agent slips its way round the other side of the wall (E, E, N, N, then the final E succeeds). It ends in the pit with probability 0.0140.014, and otherwise stands somewhere on the grid with no plan left. Its expected discounted reward over the five steps is 0.0510.051. The policy computed below, which reacts to where the agent actually is, is worth 0.3740.374 from the same start. A fixed plan cannot react; a policy can.

Markov decision processes#

A Markov decision process (MDP) is a tuple (S,A,P,R,γ)(\mathcal S, \mathcal A, P, R, \gamma) (Bellman, 1957; Puterman, 1994). Its defining assumption is the Markov property: the next state depends only on the current state and action,

Pr⁡(St+1=s′∣St,At,St−1,At−1,…,S0)=P(s′∣St,At),\Pr(S_{t+1} = s' \mid S_t, A_t, S_{t-1}, A_{t-1}, \dots, S_0) = P(s' \mid S_t, A_t),

the same property that defines a Markov chain, with the agent’s choice added. A policy π\pi fixed, the states form an ordinary Markov chain with transition matrix Pπ(s,s′)=∑aπ(a∣s)P(s′∣s,a)P_\pi(s, s') = \sum_a \pi(a \mid s) P(s' \mid s, a).

The agent’s objective is the return, the discounted sum of future rewards:

Gt=Rt+1+γRt+2+γ2Rt+3+⋯=∑k=0∞γkRt+k+1.G_t = R_{t+1} + \gamma R_{t+2} + \gamma^2 R_{t+3} + \dots = \sum_{k=0}^{\infty} \gamma^k R_{t+k+1} .

The discount γ<1\gamma < 1 does three jobs. It keeps the sum finite: if ∣R∣≤Rmax⁡|R| \le R_{\max}, then ∣Gt∣≤Rmax⁡(1+γ+γ2+… )=Rmax⁡/(1−γ)|G_t| \le R_{\max}(1 + \gamma + \gamma^2 + \dots) = R_{\max}/(1 - \gamma). It expresses a preference for reward sooner rather than later. And it can be read as a probability 1−γ1 - \gamma that the process stops at each step. Episodic tasks, such as the gridworld, end in terminal states; we model them as absorbing states with reward 0, so the same formulas cover both cases.

The value of a policy is its expected return from each state, and the action value is the expected return after taking a given first action:

Vπ(s)=Eπ[ Gt∣St=s ],Qπ(s,a)=Eπ[ Gt∣St=s,At=a ].\begin{aligned} V^\pi(s) &= \mathbb E_\pi\big[\, G_t \mid S_t = s \,\big], \\ Q^\pi(s, a) &= \mathbb E_\pi\big[\, G_t \mid S_t = s, A_t = a \,\big] . \end{aligned}

The optimal values are 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). For a finite MDP with γ<1\gamma < 1 there is one deterministic, stationary policy π⋆\pi^\star that attains V⋆(s)V^\star(s) in every state at once (Puterman, 1994, section 6.2); the rest of the note computes it.

The Bellman expectation equation#

The value of a state is the expected reward of one step plus the discounted value of the state where that step lands. The derivation uses four facts in order: the return is recursive, expectation is linear, the law of total expectation splits over the first action and the next state, and the Markov property removes the past:

Vπ(s)=Eπ[ Rt+1+γGt+1∣St=s ]Gt=Rt+1+γGt+1=∑aπ(a∣s)∑s′P(s′∣s,a) Eπ[ Rt+1+γGt+1∣St=s,At=a,St+1=s′ ]total expectation over At,St+1=∑aπ(a∣s)∑s′P(s′∣s,a)(R(s,a,s′)+γ Eπ[ Gt+1∣St+1=s′ ])linearity; Markov property=∑aπ(a∣s)∑s′P(s′∣s,a)(R(s,a,s′)+γVπ(s′)).definition of Vπ\begin{aligned} V^\pi(s) &= \mathbb E_\pi\big[\, R_{t+1} + \gamma G_{t+1} \mid S_t = s \,\big] && G_t = R_{t+1} + \gamma G_{t+1} \\ &= \sum_a \pi(a \mid s) \sum_{s'} P(s' \mid s, a)\, \mathbb E_\pi\big[\, R_{t+1} + \gamma G_{t+1} \mid S_t = s, A_t = a, S_{t+1} = s' \,\big] && \text{total expectation over } A_t, S_{t+1} \\ &= \sum_a \pi(a \mid s) \sum_{s'} P(s' \mid s, a) \Big( R(s, a, s') + \gamma\, \mathbb E_\pi\big[\, G_{t+1} \mid S_{t+1} = s' \,\big] \Big) && \text{linearity; Markov property} \\ &= \sum_a \pi(a \mid s) \sum_{s'} P(s' \mid s, a) \big( R(s, a, s') + \gamma V^\pi(s') \big) . && \text{definition of } V^\pi \end{aligned}

The Markov property is used in the third line: once St+1=s′S_{t+1} = s' is known, the rewards after it do not depend on ss or aa, so the conditional expectation of Gt+1G_{t+1} is the value of s′s'. The result is the Bellman expectation equation:

  Vπ(s)=∑aπ(a∣s)∑s′P(s′∣s,a) (R(s,a,s′)+γVπ(s′))  \boxed{\; V^\pi(s) = \sum_a \pi(a \mid s) \sum_{s'} P(s' \mid s, a)\, \big( R(s, a, s') + \gamma V^\pi(s') \big) \;}

and in the same way Qπ(s,a)=∑s′P(s′∣s,a)(R(s,a,s′)+γ∑a′π(a′∣s′)Qπ(s′,a′))Q^\pi(s, a) = \sum_{s'} P(s' \mid s, a) \big( R(s, a, s') + \gamma \sum_{a'} \pi(a' \mid s') Q^\pi(s', a') \big).

These are ∣S∣|\mathcal S| linear equations in ∣S∣|\mathcal S| unknowns. In vector form, with Rπ(s)=∑aπ(a∣s)∑s′P(s′∣s,a)R(s,a,s′)R_\pi(s) = \sum_a \pi(a \mid s) \sum_{s'} P(s' \mid s, a) R(s, a, s') the expected one-step reward,

Vπ=Rπ+γPπVπ⟺Vπ=(I−γPπ)−1Rπ.V^\pi = R_\pi + \gamma P_\pi V^\pi \quad\Longleftrightarrow\quad V^\pi = (I - \gamma P_\pi)^{-1} R_\pi .

The inverse exists: the rows of PπP_\pi are probability vectors, so ∥PπV∥∞≤∥V∥∞\lVert P_\pi V \rVert_\infty \le \lVert V \rVert_\infty, and γPπ\gamma P_\pi shrinks every vector by at least the factor γ<1\gamma < 1; the series I+γPπ+γ2Pπ2+…I + \gamma P_\pi + \gamma^2 P_\pi^2 + \dots converges to (I−γPπ)−1(I - \gamma P_\pi)^{-1}. Evaluating a policy in an MDP with known PP and RR is a linear solve. Worked example. The policy “always go N” never reaches the goal from (1,1)(1, 1) except by slipping, and pays −0.04-0.04 for every step on the way; solving the system gives Vπ(1,1)=−0.319V^\pi(1, 1) = -0.319.

The Bellman optimality equation#

Two steps lead to it.

From V⋆V^\star to Q⋆Q^\star. Take action aa in ss, land in s′s', and from then on act optimally. By the Markov property the problem that starts in s′s' is the same whatever happened before, so the best expected return from s′s' is V⋆(s′)V^\star(s'), and

Q⋆(s,a)=∑s′P(s′∣s,a)(R(s,a,s′)+γV⋆(s′)).Q^\star(s, a) = \sum_{s'} P(s' \mid s, a) \big( R(s, a, s') + \gamma V^\star(s') \big) .

From Q⋆Q^\star to V⋆V^\star. A policy that is free in ss can put all its probability on the best first action. Any other choice of π(⋅∣s)\pi(\cdot \mid s) gives a weighted average of the action values, ∑aπ(a∣s)Q⋆(s,a)\sum_a \pi(a \mid s) Q^\star(s, a), which is at most their maximum. So V⋆(s)=max⁡aQ⋆(s,a)V^\star(s) = \max_a Q^\star(s, a). Substituting the first line into the second:

  V⋆(s)=max⁡a∑s′P(s′∣s,a) (R(s,a,s′)+γV⋆(s′))  \boxed{\; V^\star(s) = \max_{a} \sum_{s'} P(s' \mid s, a)\, \big( R(s, a, s') + \gamma V^\star(s') \big) \;}

This is the Bellman optimality equation. Unlike the expectation equation it is not linear, because of the maximum. Once V⋆V^\star is known, the optimal policy is greedy with respect to it: π⋆(s)=arg⁡max⁡aQ⋆(s,a)\pi^\star(s) = \arg\max_a Q^\star(s, a). The operation on the right-hand side, applied to any VV, is called a Bellman backup:

Figure

One Bellman backup at cell (3, 3)

One Bellman backup at cell (3, 3)A backup tree: the state (3, 3) on the left, its four actions N, E, S, W with action values 0.801, 0.928, 0.554, 0.648. Action E is expanded into three outcomes: the goal (4, 3) with probability 0.8, staying at (3, 3) with probability 0.1, and (3, 2) with probability 0.1. Their backed-up values 1.000, 0.795 and 0.486 average to 0.928, and the maximum over actions gives V* = 0.928.s(3, 3)NESW10.8(4, 3)goal0.1(3, 3)bumps the edge0.1(3, 2)slips down21 + 0.9 · 0.000 = 1.000−0.04 + 0.9 · 0.928 = 0.795−0.04 + 0.9 · 0.585 = 0.4863Q(s, E) = 0.8 · 1.000 + 0.1 · 0.795+ 0.1 · 0.486 = 0.9284Q = 0.801Q = 0.554Q = 0.648V* = 0.928V*(s) = max(0.801, 0.928, 0.554, 0.648) = 0.9285One Bellman backup at cell (3, 3)A backup tree: the state (3, 3) on the left, its four actions N, E, S, W with action values 0.801, 0.928, 0.554, 0.648. Action E is expanded into three outcomes: the goal (4, 3) with probability 0.8, staying at (3, 3) with probability 0.1, and (3, 2) with probability 0.1. Their backed-up values 1.000, 0.795 and 0.486 average to 0.928, and the maximum over actions gives V* = 0.928.s(3, 3)NESW10.8(4, 3)0.1(3, 3)0.1(3, 2)2(4, 3): 1 + 0.9 · 0.000 = 1.000(3, 3): −0.04 + 0.9 · 0.928 = 0.795(3, 2): −0.04 + 0.9 · 0.585 = 0.4863Q(s, E) = 0.8 · 1.000 + 0.1 · 0.795+ 0.1 · 0.486 = 0.9284V*(s) = max(0.801, 0.928, 0.554, 0.648)= 0.9285
The values of the next states are the optimal ones, from value iteration with γ = 0.9: V*(3, 3) = 0.928, V*(3, 2) = 0.585, and 0 at the goal, where the episode ends. Action E reaches the goal and the reward +1 with probability 0.8, slips up into the edge and stays put with probability 0.1, and slips down to (3, 2) with probability 0.1. The backup of V* holds exactly, because V* is the fixed point: the maximum of the four Q values gives 0.928 again.
  1. State. In s=(3,3)s = (3, 3), next to the goal, the four actions are candidates.
  2. Outcomes. Action E reaches the goal with probability 0.80.8, slips up into the edge and stays with 0.10.1, slips down to (3,2)(3, 2) with 0.10.1.
  3. Backed-up values. Each outcome contributes its reward plus γ\gamma times the value of the state it lands in: 1+0.9⋅0=11 + 0.9 \cdot 0 = 1 for the goal, whose value is 0 because the episode ends; −0.04+0.9⋅0.928=0.795-0.04 + 0.9 \cdot 0.928 = 0.795 for staying; −0.04+0.9⋅0.585=0.486-0.04 + 0.9 \cdot 0.585 = 0.486 for (3,2)(3, 2).
  4. Average. Q⋆(s,E)=0.8⋅1+0.1⋅0.795+0.1⋅0.486=0.928Q^\star(s, \text{E}) = 0.8 \cdot 1 + 0.1 \cdot 0.795 + 0.1 \cdot 0.486 = 0.928.
  5. Maximum. The other actions give 0.8010.801 (N), 0.5540.554 (S) and 0.6480.648 (W), so V⋆(3,3)=0.928V^\star(3, 3) = 0.928, and the optimal action is E.

The value 0.9280.928 appears on both sides: V⋆V^\star is a fixed point of the backup. That suggests computing it by applying the backup until nothing changes.

Value iteration#

Value iteration starts from any V0V_0, for example V0=0V_0 = 0, and applies the backup to every state at once, a sweep:

Vk+1(s)=max⁡a∑s′P(s′∣s,a)(R(s,a,s′)+γVk(s′)),written Vk+1=TVk.V_{k+1}(s) = \max_a \sum_{s'} P(s' \mid s, a) \big( R(s, a, s') + \gamma V_k(s') \big), \qquad \text{written } V_{k+1} = T V_k .

In the gridworld, after one sweep only (3,3)(3, 3), next to the goal, has a positive value, 0.8⋅1+0.2⋅(−0.04)=0.7920.8 \cdot 1 + 0.2 \cdot (-0.04) = 0.792; every other state has −0.04-0.04. After two sweeps (2,3)(2, 3) and (3,2)(3, 2) turn positive, at 0.5230.523 and 0.4310.431. Value spreads backwards from the goal by one cell per sweep, and VkV_k is the optimal value of acting for kk steps.

Why it converges: the backup is a contraction#

Step 1: a maximum moves by at most the largest change. For any two functions f,gf, g of aa, ∣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)|. If max⁡f≥max⁡g\max f \ge \max g and a⋆a^\star maximizes ff, then max⁡f−max⁡g≤f(a⋆)−g(a⋆)≤max⁡a∣f(a)−g(a)∣\max f - \max g \le f(a^\star) - g(a^\star) \le \max_a |f(a) - g(a)|; the other case is symmetric.

Step 2: one sweep shrinks every difference by γ\gamma. For two value functions U,WU, W and any state ss, write QU(s,a)Q_U(s, a) for the bracket of the backup computed with UU:

∣(TU)(s)−(TW)(s)∣=∣max⁡aQU(s,a)−max⁡aQW(s,a)∣definition of T≤max⁡a∣QU(s,a)−QW(s,a)∣Step 1=max⁡a∣γ∑s′P(s′∣s,a)(U(s′)−W(s′))∣the rewards cancel≤γmax⁡a∑s′P(s′∣s,a) ∥U−W∥∞∣U(s′)−W(s′)∣≤∥U−W∥∞=γ ∥U−W∥∞.∑s′P(s′∣s,a)=1\begin{aligned} |(TU)(s) - (TW)(s)| &= \big|\max_a Q_U(s, a) - \max_a Q_W(s, a)\big| && \text{definition of } T \\ &\le \max_a \big| Q_U(s, a) - Q_W(s, a) \big| && \text{Step 1} \\ &= \max_a \Big| \gamma \sum_{s'} P(s' \mid s, a) \big( U(s') - W(s') \big) \Big| && \text{the rewards cancel} \\ &\le \gamma \max_a \sum_{s'} P(s' \mid s, a)\, \lVert U - W \rVert_\infty && |U(s') - W(s')| \le \lVert U - W \rVert_\infty \\ &= \gamma\, \lVert U - W \rVert_\infty . && \textstyle\sum_{s'} P(s' \mid s, a) = 1 \end{aligned}

Taking the maximum over ss:

  ∥TU−TW∥∞≤γ ∥U−W∥∞  \boxed{\; \lVert TU - TW \rVert_\infty \le \gamma\, \lVert U - W \rVert_\infty \;}

TT is a contraction with modulus γ\gamma in the max norm. By the Banach fixed-point theorem it has exactly one fixed point, which is V⋆V^\star by the Bellman optimality equation, and iterating it from any start converges to that point geometrically: with U=VkU = V_k and W=V⋆=TV⋆W = V^\star = TV^\star,

∥Vk−V⋆∥∞≤γk ∥V0−V⋆∥∞.\lVert V_{k} - V^\star \rVert_\infty \le \gamma^k\, \lVert V_0 - V^\star \rVert_\infty .

Step 3: when to stop. V⋆V^\star is unknown, but the change between sweeps is observable. By the triangle inequality and the contraction, ∥Vk+1−V⋆∥≤γ∥Vk−V⋆∥≤γ(∥Vk−Vk+1∥+∥Vk+1−V⋆∥)\lVert V_{k+1} - V^\star \rVert \le \gamma \lVert V_k - V^\star \rVert \le \gamma \big( \lVert V_k - V_{k+1} \rVert + \lVert V_{k+1} - V^\star \rVert \big), so

∥Vk+1−V⋆∥∞≤γ1−γ ∥Vk+1−Vk∥∞.\lVert V_{k+1} - V^\star \rVert_\infty \le \frac{\gamma}{1 - \gamma}\, \lVert V_{k+1} - V_k \rVert_\infty .

Stopping as soon as a sweep changes no value by more than ε(1−γ)/γ\varepsilon (1 - \gamma)/\gamma guarantees an error below ε\varepsilon. The greedy policy of a value function within ε\varepsilon of V⋆V^\star loses at most 2γε/(1−γ)2\gamma\varepsilon/(1 - \gamma) against the optimal one in any state (Singh and Yee, 1994), and in a finite MDP it is exactly optimal once ε\varepsilon is small enough.

Worked example. In the gridworld with γ=0.9\gamma = 0.9, value iteration from V0=0V_0 = 0 converges to these values and this greedy policy:

Figure

Optimal values and policy in the 4 × 3 world

Optimal values and policy in the 4 × 3 worldA grid of four columns and three rows. Each cell shows its optimal value and an arrow for the optimal action. Top row: 0.610, 0.766, 0.928 with arrows to the right, then the goal +1. Middle row: 0.487 up, the wall, 0.585 up, then the pit −1. Bottom row: 0.374 up, 0.327 right, 0.428 up, 0.189 left.0.374↑(1, 1)0.487↑(1, 2)0.610→(1, 3)0.327→(2, 1)0.766→(2, 3)0.428↑(3, 1)0.585↑(3, 2)0.928→(3, 3)0.189←(4, 1)pit −1(4, 2)goal +1(4, 3)start: (1, 1) · γ = 0.9Optimal values and policy in the 4 × 3 worldA grid of four columns and three rows. Each cell shows its optimal value and an arrow for the optimal action. Top row: 0.610, 0.766, 0.928 with arrows to the right, then the goal +1. Middle row: 0.487 up, the wall, 0.585 up, then the pit −1. Bottom row: 0.374 up, 0.327 right, 0.428 up, 0.189 left.0.374↑(1, 1)0.487↑(1, 2)0.610→(1, 3)0.327→(2, 1)0.766→(2, 3)0.428↑(3, 1)0.585↑(3, 2)0.928→(3, 3)0.189←(4, 1)pit −1(4, 2)goal +1(4, 3)
An action succeeds with probability 0.8 and slips to either side with probability 0.1; bumping into the wall or the edge stays put. The reward is −0.04 per step, +1 for entering the goal and −1 for entering the pit, with γ = 0.9. The paler the cell, the lower its value. In (3, 1) and (3, 2) the policy goes up, next to the pit, and accepts a 0.1 chance of slipping into it from (3, 2): the way round through (1, 1) is longer, and γ = 0.9 discounts long paths. In (4, 1) it moves left, away from the pit, rather than up into it.

The bound γk∥V0−V⋆∥\gamma^k \lVert V_0 - V^\star \rVert promises an error below 10−610^{-6} after 131 sweeps for γ=0.9\gamma = 0.9 and 1371 sweeps for γ=0.99\gamma = 0.99. The actual numbers are 20 and 26:

Figure

The error of value iteration and the contraction bound

The error of value iteration and the contraction boundA log scale of the error from 1 to 10⁻⁸ against the number of sweeps from 0 to 30. For γ = 0.5, 0.9 and 0.99 the solid error curves fall below 10⁻⁶ after 14, 20 and 26 sweeps. The dashed bounds, γᵏ times the initial error, fall more slowly, and for γ = 0.99 they hardly fall at all.110⁻²10⁻⁴10⁻⁶10⁻⁸051015202530sweeps kmax error ‖Vₖ − V*‖γ = 0.5γ = 0.9γ = 0.99bound γᵏ‖V₀ − V*‖errorThe error of value iteration and the contraction boundA log scale of the error from 1 to 10⁻⁸ against the number of sweeps from 0 to 30. For γ = 0.5, 0.9 and 0.99 the solid error curves fall below 10⁻⁶ after 14, 20 and 26 sweeps. The dashed bounds, γᵏ times the initial error, fall more slowly, and for γ = 0.99 they hardly fall at all.110⁻²10⁻⁴10⁻⁶10⁻⁸051015202530sweeps kmax error ‖Vₖ − V*‖γ = 0.5γ = 0.9γ = 0.99bound γᵏ‖V₀ − V*‖error
Value iteration on the 4 × 3 world from V₀ = 0. Solid lines are the actual max-norm error after k sweeps; the dashed line of the same colour is the contraction guarantee γᵏ‖V₀ − V*‖. Every sweep shrinks the error by at least the factor γ, as the theorem promises; here by much more, because the episodes end: after 10 sweeps the error is 0.006 against a bound of 0.324 at γ = 0.9, and 0.058 against 0.863 at γ = 0.99. The bound describes the worst case, a task that never ends.

The bound is a worst case. It is nearly reached in a task that never ends, where every sweep only adds one more discounted step; in the gridworld most trajectories of a good policy end within a few steps, and the error falls as fast as the probability that an episode is still running.

Policy iteration#

Value iteration improves the values and reads off a policy at the end. Policy iteration (Howard, 1960) works with the policy directly and alternates two steps until the policy stops changing:

  1. Evaluation. Compute VπV^\pi exactly, by solving the linear system (I−γPπ)V=Rπ(I - \gamma P_\pi) V = R_\pi.
  2. Improvement. Make the policy greedy with respect to it: π′(s)=arg⁡max⁡aQπ(s,a)\pi'(s) = \arg\max_a Q^\pi(s, a), with Qπ(s,a)=∑s′P(s′∣s,a)(R(s,a,s′)+γVπ(s′))Q^\pi(s, a) = \sum_{s'} P(s' \mid s, a)(R(s, a, s') + \gamma V^\pi(s')).

Why the improvement step improves. The greedy choice gives Qπ(s,π′(s))≥Qπ(s,π(s))=Vπ(s)Q^\pi(s, \pi'(s)) \ge Q^\pi(s, \pi(s)) = V^\pi(s) in every state. Unrolling this inequality one step at a time, with Eπ′\mathbb E_{\pi'} meaning that every later action follows π′\pi':

Vπ(s)≤Qπ(s,π′(s))=E[ Rt+1+γVπ(St+1)∣St=s,At=π′(s) ]≤Eπ′[ Rt+1+γQπ(St+1,π′(St+1))∣St=s ]the same inequality at St+1=Eπ′[ Rt+1+γRt+2+γ2Vπ(St+2)∣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\big[\, R_{t+1} + \gamma V^\pi(S_{t+1}) \mid S_t = s, A_t = \pi'(s) \,\big] \\ &\le \mathbb E_{\pi'}\big[\, R_{t+1} + \gamma Q^\pi(S_{t+1}, \pi'(S_{t+1})) \mid S_t = s \,\big] && \text{the same inequality at } S_{t+1} \\ &= \mathbb E_{\pi'}\big[\, R_{t+1} + \gamma R_{t+2} + \gamma^2 V^\pi(S_{t+2}) \mid S_t = s \,\big] \\ &\le \dots \le \mathbb E_{\pi'}\big[\, R_{t+1} + \gamma R_{t+2} + \gamma^2 R_{t+3} + \dots \mid S_t = s \,\big] = V^{\pi'}(s) . \end{aligned}

This is the policy improvement theorem (Sutton and Barto, 2018, section 4.2). If the new policy is no better anywhere, then Vπ(s)=max⁡aQπ(s,a)V^\pi(s) = \max_a Q^\pi(s, a) for every ss, which is the Bellman optimality equation, so π\pi is optimal. Otherwise some value strictly increases. There are finitely many deterministic policies, ∣A∣∣S∣|\mathcal A|^{|\mathcal S|}, and none can repeat, so policy iteration stops after finitely many iterations at an optimal policy.

Worked example. From “always go N”, whose value at (1,1)(1, 1) is −0.319-0.319, the first improvement turns the top row and most of the grid towards the goal, worth 0.2630.263 at (1,1)(1, 1); the second fixes the start cell to go N instead of E, worth 0.3740.374; the third finds nothing to change. Three evaluations, against the 20 sweeps value iteration needed for a precision of 10−610^{-6}; each evaluation, however, is a linear solve that costs O(∣S∣3)O(|\mathcal S|^3), while a sweep costs O(∣S∣2∣A∣)O(|\mathcal S|^2 |\mathcal A|). Between the two lie variants that evaluate a policy approximately with a few sweeps before improving it.

Partially observable MDPs and belief states#

The MDP assumes that the agent sees the state. In a partially observable MDP (POMDP) it receives an observation oo with probability O(o∣s′,a)O(o \mid s', a) after reaching s′s' by action aa (Kaelbling, Littman and Cassandra, 1998). The current observation is no longer enough to act on, but a probability distribution over states, the belief b(s)b(s), is. After action aa and observation oo it is updated by Bayes’ rule, first predicting with the transition model, then weighting by the likelihood of what was seen:

b′(s′)=η O(o∣s′,a)∑sP(s′∣s,a) b(s),η=the constant that makes b′ sum to 1.\begin{aligned} b'(s') &= \eta\, O(o \mid s', a) \sum_{s} P(s' \mid s, a)\, b(s), \\ \eta &= \text{the constant that makes } b' \text{ sum to } 1 . \end{aligned}

Worked example. A cleaning robot’s sensor reports dirt correctly with probability 0.90.9. Its belief that the square is dirty is 0.30.3, and the sensor says “dirty”: b′=0.9⋅0.3/(0.9⋅0.3+0.1⋅0.7)=0.27/0.34=0.794b' = 0.9 \cdot 0.3 / (0.9 \cdot 0.3 + 0.1 \cdot 0.7) = 0.27/0.34 = 0.794. The waiting vacuum agent of the first note did the prediction half of this update without observations: its counter kk determined its belief 1−(1−p)k+11 - (1 - p)^{k+1} that the unseen square was dirty.

The belief is a sufficient statistic for the history, so a POMDP becomes an MDP whose states are beliefs: the belief MDP. Its state space is continuous, a simplex of dimension ∣S∣−1|\mathcal S| - 1, and solving it exactly is intractable in general (finite-horizon POMDPs are PSPACE-complete, Papadimitriou and Tsitsiklis, 1987). Practical agents approximate the belief: a filter, a learned recurrent state, or, for a language-model agent, the context window and its notes, which summarize what the agent has observed. Partial observability is the rule rather than the exception for the agents later in the course, and Context and memory treats what to keep in that summary.

What changed#

searchMarkov decision process
outcome of an actionone known statea distribution P(s′∣s,a)P(s' \mid s, a)
what is computeda sequence of actionsa policy, an action for every state
criterionpath costexpected discounted return
key equationg+hg + h along pathsthe Bellman equations, a fixed point
algorithmA* over pathsvalue iteration, policy iteration over all states
in the gridworlda plan that reaches the goal with probability 0.328a policy worth 0.374 from the start

Limitations#

  • The model must be known. Value and policy iteration need PP and RR for every state and action. When they are unknown, the agent must learn from experience, the subject of Q-learning and temporal-difference learning.
  • Every state is enumerated. A sweep touches all of S\mathcal S, and realistic state spaces, positions of a robot, boards of Go, contexts of a language model, are far too large. This is the curse of dimensionality; function approximation, sampling and search from the current state address it.
  • Rewards are given. The MDP takes RR as part of the problem. Choosing it is the performance-measure problem of the first note, and a badly chosen reward is optimized as faithfully as a good one.
  • The discount is a modelling choice. Values and policies change with γ\gamma; with γ\gamma close to 1, both the error bound and the effective horizon 1/(1−γ)1/(1 - \gamma) grow.
  • Partial observability is hard. Exact POMDP solutions are intractable beyond small problems; practical agents approximate the belief.

What you should remember#

  • An MDP is (S,A,P,R,γ)(\mathcal S, \mathcal A, P, R, \gamma) with the Markov property; its solution is a policy, judged by the expected discounted return.
  • The Bellman expectation equation, Vπ=Rπ+γPπVπV^\pi = R_\pi + \gamma P_\pi V^\pi, follows from the recursive return, total expectation and the Markov property; evaluating a known policy is a linear solve.
  • The Bellman optimality equation, V⋆(s)=max⁡a∑s′P(s′∣s,a)(R+γV⋆(s′))V^\star(s) = \max_a \sum_{s'} P(s' \mid s, a)(R + \gamma V^\star(s')), has the greedy policy as its solution.
  • The backup TT is a γ\gamma-contraction in the max norm, so value iteration converges from any start, with error at most γk\gamma^k times the initial one; stop when a sweep changes values by less than ε(1−γ)/γ\varepsilon(1 - \gamma)/\gamma.
  • Policy iteration alternates exact evaluation and greedy improvement; the policy improvement theorem makes every step an improvement, and it stops at an optimal policy after finitely many steps.
  • When the state is hidden, act on a belief updated by Bayes’ rule; the belief MDP is exact but intractable, and agents approximate it.

Code#

The 4 × 3 gridworld as arrays P[a,s,s′]P[a, s, s'] and R[a,s]R[a, s], the fixed plan as a baseline, value iteration with the stopping rule, a numerical check of the contraction, policy iteration, and a belief update. NumPy only; seeds are fixed, and exact digits can differ slightly across platforms. The script runs in about a second.

import numpy as np

# 1. the 4 x 3 gridworld: cells (column, row) from (1, 1) at the bottom left; a wall at (2, 2)
cells = [(x, y) for y in (1, 2, 3) for x in (1, 2, 3, 4) if (x, y) != (2, 2)]
ix = {c: i for i, c in enumerate(cells)}
GOAL, PIT = (4, 3), (4, 2)
ACTS = {'N': (0, 1), 'E': (1, 0), 'S': (0, -1), 'W': (-1, 0)}
SIDE = {'N': 'EW', 'S': 'EW', 'E': 'NS', 'W': 'NS'}
def move(c, a):
    n = (c[0] + ACTS[a][0], c[1] + ACTS[a][1])
    return n if n in ix else c                                  # walls and edges: stay put
nS, nA = len(cells), len(ACTS)
P = np.zeros((nA, nS, nS)); R = np.zeros((nA, nS))              # P[a, s, s'] and the expected reward R[a, s]
for a_i, a in enumerate(ACTS):
    for c in cells:
        s = ix[c]
        if c in (GOAL, PIT): P[a_i, s, s] = 1.0; continue      # terminal: absorbing, reward 0
        for b, prob in ((a, 0.8), (SIDE[a][0], 0.1), (SIDE[a][1], 0.1)):
            n = move(c, b)
            P[a_i, s, ix[n]] += prob
            R[a_i, s] += prob * (1.0 if n == GOAL else -1.0 if n == PIT else -0.04)
gamma = 0.9

# 2. the baseline: the plan N, N, E, E, E executed blindly from (1, 1)
d, ret = np.eye(nS)[ix[(1, 1)]], 0.0                            # distribution over cells, discounted reward
for t, a in enumerate('NNEEE'):
    a_i = list(ACTS).index(a)
    ret += gamma ** t * d @ R[a_i]; d = d @ P[a_i]
print(round(d[ix[GOAL]], 5), round(d[ix[PIT]], 3), round(ret, 3))   # 0.32776 0.014 0.051

# 3. value iteration with the stopping rule
def bellman(V, gamma):                                          # the optimality operator T
    return (R + gamma * P @ V).max(axis=0)
def value_iteration(gamma, eps=1e-10):
    V, history = np.zeros(nS), [np.zeros(nS)]
    while True:
        V_new = bellman(V, gamma); history.append(V_new)
        if np.abs(V_new - V).max() < eps * (1 - gamma) / gamma: return V_new, history
        V = V_new
V, hist = value_iteration(gamma)
print(np.round(hist[1], 3)[ix[(3, 3)]], np.round(hist[2], 3)[[ix[(2, 3)], ix[(3, 2)]]])   # 0.792 [0.523 0.431]
Q = R + gamma * P @ V
policy = [list(ACTS)[a] for a in Q.argmax(axis=0)]
for y in (3, 2, 1):
    print('  '.join('  wall ' if (x, y) not in ix else f'{V[ix[(x, y)]]:6.3f}' + (' ' if (x, y) in (GOAL, PIT) else policy[ix[(x, y)]])
                    for x in (1, 2, 3, 4)))
#  0.610E   0.766E   0.928E   0.000
#  0.487N    wall    0.585N   0.000
#  0.374N   0.327E   0.428N   0.189W
print({a: round(float(Q[i, ix[(3, 3)]]), 3) for i, a in enumerate(ACTS)})   # {'N': 0.801, 'E': 0.928, 'S': 0.554, 'W': 0.648}
for g in (0.5, 0.9, 0.99):
    Vg, h = value_iteration(g)
    err = [np.abs(v - Vg).max() for v in h]
    bound = int(np.ceil(np.log(1e-6 / err[0]) / np.log(g)))
    print(g, 'sweeps to 1e-6:', next(k for k, e in enumerate(err) if e < 1e-6), 'by the bound:', bound)
# 0.5 sweeps to 1e-6: 14 by the bound: 20
# 0.9 sweeps to 1e-6: 20 by the bound: 131
# 0.99 sweeps to 1e-6: 26 by the bound: 1371

# 4. the contraction, checked on random pairs of value functions
rng = np.random.default_rng(0)
ratios = [np.abs(bellman(U, gamma) - bellman(W, gamma)).max() / np.abs(U - W).max()
          for U, W in (rng.normal(size=(2, nS)) for _ in range(1000))]
print(round(max(ratios), 4))                                    # 0.9: never above gamma

# 5. policy iteration: exact evaluation by a linear solve, then greedy improvement
pi = np.zeros(nS, dtype=int)                                    # start: always go north
for it in range(1, 20):
    P_pi, R_pi = P[pi, np.arange(nS)], R[pi, np.arange(nS)]
    V_pi = np.linalg.solve(np.eye(nS) - gamma * P_pi, R_pi)    # (I - gamma P_pi) V = R_pi
    new = (R + gamma * P @ V_pi).argmax(axis=0)
    print(it, ''.join(list(ACTS)[a] for a in pi), round(V_pi[ix[(1, 1)]], 3))
    if (new == pi).all(): break
    pi = new
print(np.allclose(V_pi, V, atol=1e-8))
# 1 NNNNNNNNNNN -0.319
# 2 EENWNNNEEEN 0.263
# 3 NENWNNNEEEN 0.374
# True

# 6. a belief update: a noisy dirt sensor that is right 90% of the time
prior = np.array([0.3, 0.7])                                    # P(dirty), P(clean)
likelihood = np.array([0.9, 0.1])                               # P(sensor says "dirty" | dirty), (| clean)
posterior = likelihood * prior / (likelihood * prior).sum()
print(posterior.round(3))                                       # [0.794 0.206]

Next#

The MDP is solved here because its transitions and rewards are written down. Two settings break that. In a game, part of the “environment” is an opponent who chooses the next state to hurt us, and the state space is so large that only the states reachable from the current position can be examined. The next note handles both: minimax and alpha–beta search for adversaries, and Monte Carlo tree search, which estimates values by sampling instead of sweeping, the method behind AlphaGo, AlphaZero and MuZero.

References#