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. and are finite sets of states and actions. is the probability of moving to after action in , the reward received on that transition, and the discount. are the random state, action and reward at step . A policy gives the probability of action in state ; a deterministic policy is written . is the return from step ; and are the state and action values of , and the optimal ones. For a vector indexed by states, . is an expectation over trajectories generated by and .
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 from at the bottom left. Cell is a wall. Entering , the goal, gives a reward of ; entering , the pit, gives ; both end the episode. Every other step gives , 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 and slips to each side, at right angles, with probability . A move into the wall or off the grid leaves the agent where it is. We use the discount .
Ignore the slips and search finds the shortest path from : N, N, E, E, E. Executed blindly, this plan reaches the goal with probability : 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 , and otherwise stands somewhere on the grid with no plan left. Its expected discounted reward over the five steps is . The policy computed below, which reacts to where the agent actually is, is worth from the same start. A fixed plan cannot react; a policy can.
Markov decision processes#
A Markov decision process (MDP) is a tuple (Bellman, 1957; Puterman, 1994). Its defining assumption is the Markov property: the next state depends only on the current state and action,
the same property that defines a Markov chain, with the agent’s choice added. A policy fixed, the states form an ordinary Markov chain with transition matrix .
The agent’s objective is the return, the discounted sum of future rewards:
The discount does three jobs. It keeps the sum finite: if , then . It expresses a preference for reward sooner rather than later. And it can be read as a probability 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:
The optimal values are and . For a finite MDP with there is one deterministic, stationary policy that attains 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:
The Markov property is used in the third line: once is known, the rewards after it do not depend on or , so the conditional expectation of is the value of . The result is the Bellman expectation equation:
and in the same way .
These are linear equations in unknowns. In vector form, with the expected one-step reward,
The inverse exists: the rows of are probability vectors, so , and shrinks every vector by at least the factor ; the series converges to . Evaluating a policy in an MDP with known and is a linear solve. Worked example. The policy “always go N” never reaches the goal from except by slipping, and pays for every step on the way; solving the system gives .
The Bellman optimality equation#
Two steps lead to it.
From to . Take action in , land in , and from then on act optimally. By the Markov property the problem that starts in is the same whatever happened before, so the best expected return from is , and
From to . A policy that is free in can put all its probability on the best first action. Any other choice of gives a weighted average of the action values, , which is at most their maximum. So . Substituting the first line into the second:
This is the Bellman optimality equation. Unlike the expectation equation it is not linear, because of the maximum. Once is known, the optimal policy is greedy with respect to it: . The operation on the right-hand side, applied to any , is called a Bellman backup:
One Bellman backup at cell (3, 3)
- State. In , next to the goal, the four actions are candidates.
- Outcomes. Action E reaches the goal with probability , slips up into the edge and stays with , slips down to with .
- Backed-up values. Each outcome contributes its reward plus times the value of the state it lands in: for the goal, whose value is 0 because the episode ends; for staying; for .
- Average. .
- Maximum. The other actions give (N), (S) and (W), so , and the optimal action is E.
The value appears on both sides: 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 , for example , and applies the backup to every state at once, a sweep:
In the gridworld, after one sweep only , next to the goal, has a positive value, ; every other state has . After two sweeps and turn positive, at and . Value spreads backwards from the goal by one cell per sweep, and is the optimal value of acting for steps.
Why it converges: the backup is a contraction#
Step 1: a maximum moves by at most the largest change. For any two functions of , . If and maximizes , then ; the other case is symmetric.
Step 2: one sweep shrinks every difference by . For two value functions and any state , write for the bracket of the backup computed with :
Taking the maximum over :
is a contraction with modulus in the max norm. By the Banach fixed-point theorem it has exactly one fixed point, which is by the Bellman optimality equation, and iterating it from any start converges to that point geometrically: with and ,
Step 3: when to stop. is unknown, but the change between sweeps is observable. By the triangle inequality and the contraction, , so
Stopping as soon as a sweep changes no value by more than guarantees an error below . The greedy policy of a value function within of loses at most against the optimal one in any state (Singh and Yee, 1994), and in a finite MDP it is exactly optimal once is small enough.
Worked example. In the gridworld with , value iteration from converges to these values and this greedy policy:
Optimal values and policy in the 4 × 3 world
The bound promises an error below after 131 sweeps for and 1371 sweeps for . The actual numbers are 20 and 26:
The error of value iteration and the contraction bound
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:
- Evaluation. Compute exactly, by solving the linear system .
- Improvement. Make the policy greedy with respect to it: , with .
Why the improvement step improves. The greedy choice gives in every state. Unrolling this inequality one step at a time, with meaning that every later action follows :
This is the policy improvement theorem (Sutton and Barto, 2018, section 4.2). If the new policy is no better anywhere, then for every , which is the Bellman optimality equation, so is optimal. Otherwise some value strictly increases. There are finitely many deterministic policies, , 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 is , the first improvement turns the top row and most of the grid towards the goal, worth at ; the second fixes the start cell to go N instead of E, worth ; the third finds nothing to change. Three evaluations, against the 20 sweeps value iteration needed for a precision of ; each evaluation, however, is a linear solve that costs , while a sweep costs . 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 with probability after reaching by action (Kaelbling, Littman and Cassandra, 1998). The current observation is no longer enough to act on, but a probability distribution over states, the belief , is. After action and observation it is updated by Bayes’ rule, first predicting with the transition model, then weighting by the likelihood of what was seen:
Worked example. A cleaning robot’s sensor reports dirt correctly with probability . Its belief that the square is dirty is , and the sensor says “dirty”: . The waiting vacuum agent of the first note did the prediction half of this update without observations: its counter determined its belief 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 , 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#
| search | Markov decision process | |
|---|---|---|
| outcome of an action | one known state | a distribution |
| what is computed | a sequence of actions | a policy, an action for every state |
| criterion | path cost | expected discounted return |
| key equation | along paths | the Bellman equations, a fixed point |
| algorithm | A* over paths | value iteration, policy iteration over all states |
| in the gridworld | a plan that reaches the goal with probability 0.328 | a policy worth 0.374 from the start |
Limitations#
- The model must be known. Value and policy iteration need and 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 , 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 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 ; with close to 1, both the error bound and the effective horizon 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 with the Markov property; its solution is a policy, judged by the expected discounted return.
- The Bellman expectation equation, , follows from the recursive return, total expectation and the Markov property; evaluating a known policy is a linear solve.
- The Bellman optimality equation, , has the greedy policy as its solution.
- The backup is a -contraction in the max norm, so value iteration converges from any start, with error at most times the initial one; stop when a sweep changes values by less than .
- 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 and , 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#
- R. Bellman. Dynamic Programming. Princeton University Press, 1957.
- R. A. Howard. Dynamic Programming and Markov Processes. MIT Press, 1960.
- M. L. Puterman. Markov Decision Processes: Discrete Stochastic Dynamic Programming. Wiley, 1994. Section 6.2 (optimality equations, existence of a deterministic stationary optimal policy), sections 6.3–6.4 (value and policy iteration).
- R. S. Sutton, A. G. Barto. Reinforcement Learning: An Introduction, 2nd ed. MIT Press, 2018. Chapter 3 (finite MDPs, the Bellman equations), chapter 4 (policy evaluation, the policy improvement theorem in section 4.2, policy and value iteration).
- S. Russell, P. Norvig. Artificial Intelligence: A Modern Approach, 4th ed. Pearson, 2021. Chapter 17 (making complex decisions: the 4 × 3 world, value and policy iteration, POMDPs).
- S. P. Singh, R. C. Yee. An upper bound on the loss from approximate optimal-value functions. Machine Learning, 16:227–233, 1994.
- L. P. Kaelbling, M. L. Littman, A. R. Cassandra. Planning and acting in partially observable stochastic domains. Artificial Intelligence, 101(1–2):99–134, 1998.
- C. H. Papadimitriou, J. N. Tsitsiklis. The complexity of Markov decision processes. Mathematics of Operations Research, 12(3):441–450, 1987.
- D. Silver. Lectures on reinforcement learning. University College London, 2015. Lectures 2 (Markov decision processes) and 3 (planning by dynamic programming).
- CS188, Introduction to Artificial Intelligence. University of California, Berkeley. Lectures on Markov decision processes.