Part I · Foundations · Chapter 3
Markov decision processes
States, transitions, returns, discounting, policies, and value functions.
You run a small workshop with one machine. Each morning it is new, worn, or broken. A tune-up costs money today. Skipping it earns you more today, but a worn machine is likely to break, and a major repair is expensive. Should you pay for the tune-up?
The bandit agents of Chapter 2 can’t even ask this question. In a bandit, pulling an arm gives you a reward and leaves the world unchanged, so the only thing an action affects is the reward it earns right now. In the workshop, today’s action changes tomorrow’s situation, and tomorrow’s situation decides which rewards are even possible. This chapter builds the standard language for such problems, the Markov decision process (MDP), and the central quantity of all of reinforcement learning: the value of a state, meaning how much reward you can expect from here on. By the end you will compute values exactly, by hand for the three-state machine and with one line of linear algebra for a gridworld. You will also see why the answer to the tune-up question depends on how patient you are.
From bandits to sequential decisions
Here is the workshop as a table. There are two actions: run the machine for a day, or repair it. Running a broken machine produces nothing, so “run” in the broken state really means “leave it broken”.
| Today the machine is… | Action | Reward today | Tomorrow it is… |
|---|---|---|---|
| new | run | new (prob. 0.6), worn (0.4) | |
| worn | run | worn (0.5), broken (0.5) | |
| broken | run | broken (1) | |
| new or worn | repair | new (1) | |
| broken | repair | new (1) |
A worn machine earns nothing. Its output only covers the extra power and scrap. Now try to act greedily, the way a bandit agent would, by picking the action with the best immediate reward. When the machine is worn, run gives 0 and repair gives , so greedy runs it. Then half the time it breaks, and you face a repair or a dead machine. The greedy choice looks wrong, but by how much? To answer that you have to add up rewards that arrive over many future days, and those depend on what you will do on those days too. Making this precise is the job of the rest of the chapter.
Three things are new compared with bandits:
- There is a state , the situation at time (here: new, worn or broken).
- Your action affects not only the reward but also the next state .
- So you have to plan for delayed consequences: an action with a bad reward now can be the best one because of where it leads.
A bandit is the special case with a single state, where every action leads back to that same state.
States and the Markov property
What should count as “the state”? The answer that makes everything else work: the state must contain everything about the past that matters for the future.
The Markov property. A state signal is Markov if, once you know the current state and action, the rest of the history tells you nothing more about what happens next:
The future is independent of the past given the present.
You have met this idea in mechanics. The position of a pendulum alone is not a state: two pendulums at the same angle can be swinging in opposite directions. The pair (angle, angular velocity) is a state, because Newton’s law is second order in the angle but first order in (angle, velocity). Phase space is exactly the choice of variables that makes dynamics depend only on the present. The Markov property is the probabilistic version of the same requirement.
Some examples:
- A chess position (plus whose turn it is, castling and en-passant rights) is Markov. How you got there doesn’t matter for what can happen next. (The threefold-repetition and fifty-move rules technically break this, because they depend on the past; programs add a repetition count and a move counter to the state.)
- A single frame of an Atari game is not Markov: you see where the ball is but not where it is going. DQN (Chapter 6) fixed this by stacking the last four frames into one state.
- The workshop: if a worn machine’s chance of breaking grows with how many days it has been worn, then “worn” alone is not Markov. “Worn for 3 days” is.
The general fix is always the same: put more history into the state. The full history is Markov by construction, because nothing about the past is left out. So a Markov state always exists. The price is a bigger state space. In practice you look for a compact summary that keeps what matters, like velocity for the pendulum.
Quick check Which of these is NOT a Markov state for the stated system?
Two balls at the same position can be moving differently, so position alone does not determine what happens next. Add the velocity and it becomes Markov. The full history (last option) is always Markov, just large.
The MDP: five ingredients
A Markov decision process is a tuple :
- , the set of states. In this chapter it is finite: 3 states for the workshop, 11 cells for the gridworld below.
- , the set of actions. It may depend on the state; here it doesn’t.
- , the transition probabilities: the chance of landing in after taking in . For each this is a probability distribution over .
- , the expected reward for taking in .
- , the discount factor, which says how much less a reward is worth for each step it is delayed. More on it in the next section.
and together are called the model of the environment, or its dynamics. In this chapter and the next we assume we know them. From Chapter 5 on we won’t.
The agent and environment interact in a loop. In state the agent picks ; the environment returns a reward and a next state ; repeat. One run of this loop is a trajectory:
The running example: a slippery gridworld
This is the gridworld of this chapter’s demo and lab. Its layout is the classic 4×3 world from Russell and Norvig’s AI textbook, so you may meet it elsewhere. It has 4 columns and 3 rows, and cells are named (row, column) with row 0 at the top. (Chapter 4 moves to a bigger grid.)
col 0 col 1 col 2 col 3
row 0 . . . G G = goal: +1 for stepping into it, then the episode ends
row 1 . # . P P = pit: −1 for stepping into it, then the episode ends
row 2 S . . . # = wall, S = start
- Actions: up, right, down, left.
- Slip: with probability you move where you intended. With probability each, you slip to one of the two perpendicular directions. Moving into the wall or off the edge leaves you where you were (a “bump”).
- Rewards: every step costs (reward ), a small penalty for dawdling. Stepping into G adds and stepping into P adds .
One transition, worked out. You are at (0, 2), just left of the goal, slip , and you choose right:
- 0.8: you move right into the goal.
- 0.1: you slip up, bump the top edge, and stay at (0, 2).
- 0.1: you slip down to (1, 2).
So , , , and the expected reward is
In code we store the whole model as two arrays: P[s, a, s2] with shape (12, 4, 12) and R[s, a] with shape (12, 4). State is cell number row * 4 + col. The lab keeps the wall cell as a dummy state that nothing ever enters, so the numbering stays that simple, which is why there are 12 states rather than 11. That’s 576 transition numbers, most of them zero. Building them is Task 1 of the lab.
Episodes, continuing tasks, and one trick to unify them
The gridworld is episodic: it has terminal states (G and P) where the interaction stops, and each run from start to terminal is an episode. Games, mazes and an LLM writing one response are episodic. The workshop is continuing: it never ends, like a thermostat or a recommender system.
A simple trick puts both in one framework. Make each terminal state absorbing: every action leads back to the same state with reward 0. An episode that “ends” is now a continuing trajectory that sits in the terminal state collecting zeros forever, which changes no sums. In the lab, and for every action. One consequence trips people up, so note it now: the value of a terminal state is 0. The belongs to the step into the goal, so it is counted in of the cell you came from.
Quick check You are at (2, 3), the bottom-right cell just below the pit, slip = 0.2, step reward −0.04, and you choose up. What is the expected reward r((2,3), up)?
With prob. 0.8 you enter the pit (−1); with 0.1 you slip left to (2, 2); with 0.1 you slip right, bump the edge and stay. So r = −0.04 + 0.8 × (−1) = −0.84.
Return and discounting
The agent’s goal is not the next reward but the sum of all the rewards to come. The return from time is
For an episodic task the sum stops at the end of the episode, or, with the absorbing-state trick, just picks up zeros.
A worked return. With slip , walk from the start along right, right, up, up, right. That takes 5 steps, and the last one enters the goal, so the rewards are . With :
Hold on to this number; you’ll see it again in the demo.
The single most useful fact about returns is that they are recursive:
The return from now is the reward now plus the discounted return from the next step. Everything in the rest of this chapter, and most of RL, grows out of this one line.
Why discount?
Four reasons, from most to least fundamental:
- Finite sums. In a continuing task, an undiscounted sum of rewards can be infinite, and then “which policy is better” stops making sense. With and rewards bounded by , by the geometric series.
- Uncertainty about the future. Suppose that after every step, the world ends with probability : the machine is sold, the game is interrupted, the user closes the tab. Then the expected undiscounted total reward equals the expected discounted return. Discounting is survival probability.
- Sooner is better. A reward now can be reinvested. With interest rate , money one period later is worth today, a discount factor.
- A practical knob. Smaller means shorter-horizon problems, which are easier to learn and have lower variance. Chapter 8 uses this deliberately.
∂ Discounting as survival probability
Let the process continue after each step with probability , independently of everything else. Then the agent is still “alive” to collect with probability . Write for the indicator that it is alive at step . The expected total undiscounted reward is
using independence of and . This is the expected discounted return. The expected lifetime is steps.
The effective horizon
How far ahead does a -discounted agent look? The weight on a reward steps away is , and for near 1, . So
exponential decay with a time constant of steps. This is the effective horizon. It is also the total weight , and the expected lifetime from the survival picture.
| 0 | 0.5 | 0.9 | 0.99 | 0.999 | |
|---|---|---|---|---|---|
| horizon | 1 step | 2 | 10 | 100 | 1000 |
At the agent is myopic: , and it maximizes immediate reward only, exactly like the greedy bandit agent that never repairs the machine. At it is far-sighted.
Quick check Roughly how many steps ahead does an agent with γ = 0.99 effectively care about?
The effective horizon is 1/(1 − γ) = 1/0.01 = 100 steps. After 100 steps the weight is 0.99^100 ≈ 0.37 ≈ 1/e, and it keeps decaying.
Policies
A policy says what the agent does in each state. It can be:
- deterministic, a function . Example: the workshop policy run-to-failure = (new: run, worn: run, broken: repair), and maintain = (new: run, worn: repair, broken: repair).
- stochastic, a distribution . Example: the uniform random gridworld policy, for every action. A deterministic policy is the special case that puts probability 1 on one action.
Our policies look only at the current state, not at the time or the history. For an MDP that loses nothing: Chapter 4 shows there is always an optimal policy of this form. Stochastic policies matter for two reasons we’ll meet later. Exploration needs randomness (Chapter 5), and policy-gradient methods optimize smooth, stochastic policies (Chapter 7). A language model that samples its next token is a stochastic policy.
In code, a policy is an array pi[s, a] whose rows sum to 1.
Value functions: how good is a state?
The return is random: the policy may be random, and the environment certainly is. To compare states and policies we need its average. The state-value function of a policy is
the expected return if you start in and follow from then on. "" averages over everything random: actions drawn from , next states drawn from .
Read it as “how good is it to be here, if I keep doing what I do?” A value always belongs to a policy. The same machine state is worth a lot to a careful owner and little to a careless one.
The action-value function asks a slightly different question:
the expected return if you take action in now, even if wouldn’t, and follow afterwards. Read it as “how good is it to do here, once, and then go back to my usual behavior?” That one-time deviation is exactly what you need for deciding whether to change your behavior, which is why is the workhorse of Chapters 4 to 6.
The two relations between V and Q
The two functions are linked by two short equations, and between them they contain the whole chapter.
V from Q: average over what the policy does. In state , the policy picks with probability , after which the expected return is :
Q from V: one step of lookahead. Taking in earns on average and lands you in with probability . From there, following is worth , discounted by one step:
A picture helps. Read it from the top down: from a state the policy branches over actions, and from each action the environment branches over next states.
s V(s) = Σ_a π(a|s) · Q(s,a) ← policy's choice
/ | \
a a a Q(s,a) = r(s,a) + γ Σ_s' P(s'|s,a) · V(s') ← environment's choice
/|\ /|\ /|\
s' s' s' ... V(s') ... and so on, one level down
One more definition, because you will see it everywhere from Chapter 8 on. The advantage is how much better action is than what the policy does on average in . Positive advantage: do more of . Most of the RL algorithms for LLMs in Part III are, at heart, ways to estimate it.
Quick check A policy is deterministic and picks action a in state s. Which is always true?
V(s) = Σ π(b|s) Q(s,b), and π puts all its probability on a, so V(s) = Q(s, a). The third option is not guaranteed: the policy may be picking a bad action. That gap is exactly what policy improvement exploits.
The Bellman expectation equation
Substitute the second relation into the first and you get an equation in alone:
This is the Bellman expectation equation. It is the expectation of the return recursion .
What makes it powerful: was defined as an average over infinitely long random futures. The Bellman equation replaces that with a local consistency condition between each state and its immediate neighbors. With states it is linear equations in unknowns. No sampling or infinite sums are needed: you solve them.
The derivation is short, but every step uses something specific, so here it is in full.
∂ Deriving the Bellman expectation equation from the return's recursion
Start from the definition and the recursion :
(Linearity of expectation. For and bounded rewards all the sums converge absolutely, so swapping sums and expectations is allowed.)
Condition on the action (law of total expectation, with ):
The first term is by definition.
Condition on the next state in the second term:
Use the Markov property. is built from , which depend on future actions (drawn from given the current state only) and future transitions (Markov). Given , neither depends on or , so
Use stationarity. , and don’t depend on time, so the expected return from at time is the same function as at time :
Put the pieces together:
The same steps without the first averaging over give , the “Q from V” relation. Exercise 3.3 asks you to write the equation in alone.
A worked example: the workshop by hand
Let’s answer the opening question for the two workshop policies. To keep the arithmetic friendly, take : an impatient owner with a horizon of about 2 days. (We redo it at in the next section.) Write for .
Policy run-to-failure (run, run, repair). Each state has one action, so the sum over disappears and the Bellman equation for each state reads straight off the table:
Solve by substitution. The second equation gives , so , so . The third gives in terms of . Substitute both into the first:
Then and . Always check by plugging back in: . ✓
So under run-to-failure, . A worn machine is worth : it is likely to break, and a broken one costs to fix.
Policy maintain (run, repair, repair):
Substitute into the first: , so and . Then and .
| new | worn | broken | |
|---|---|---|---|
| run-to-failure | 2 | −3 | −9 |
| maintain | 3 | 0.5 | −8.5 |
Maintain is better in every state, even for this impatient owner.
Now the punchline: Q. Suppose you follow run-to-failure but, just once, repair a worn machine. Is that a good idea? That is exactly what measures:
while . Deviating once is better by 3. The maintain policy is what you get by making that deviation permanent, and it improved every state. That’s no coincidence. It is the policy improvement theorem, which Chapter 4 proves and turns into an algorithm.
Finally, look at the myopic owner, . Then , so a agent never maintains. That is the greedy bandit agent from the start of the chapter, and its mistake is now a number.
Quick check Under 'maintain' at γ = 0.5, Q(broken, run) = 0 + 0.5 × V(broken) = −4.25, while V(broken) = −8.5. What does this tell you?
Q(s, a) > V(s) means doing a once and then following π beats following π from the start. With a 2-day horizon the −10 repair never pays for itself. Exercise 3.6 shows that at γ = 0.9 the answer flips: patience changes the optimal policy.
The matrix form: all states at once
Solving by substitution gets tedious beyond three states. Linear algebra does it in one line.
Fix the policy and average out its action choice. That gives a Markov chain over states and a reward per state:
is an stochastic matrix: non-negative entries, every row summing to 1. is a vector of length . Stack the values into a vector too, and the Bellman expectation equation for all states at once reads
For run-to-failure on the workshop (states ordered new, worn, broken):
and np.linalg.solve(I - 0.5 * P_pi, r_pi) returns , the same as by hand. Now changing costs nothing. At , run-to-failure gives and maintain gives . The longer the horizon, the more maintenance pays.
What the inverse means
Is always invertible? For , yes (Exercise 3.5 proves it). Expanding the inverse as a geometric (Neumann) series also tells you what it means:
is the probability of being in exactly steps after starting in , so is the expected reward at step . The value is the discounted sum of expected rewards over all future times. If you know Green’s functions, is a resolvent: a sum over all paths of all lengths, each weighted by its probability and its discount.
Iterating instead of inverting
A linear solve costs . That’s nothing for 12 states, and hopeless for backgammon’s roughly states. There is a second way that uses only matrix–vector products: treat the Bellman equation as an update rule and iterate it,
Subtract the true and you get . Since averages (rows sum to 1), the largest error shrinks by at least a factor per sweep: . This is iterative policy evaluation. Chapter 4 builds on it, and proves the convergence properly with the contraction mapping theorem. (Starting from , after sweeps is the expected discounted reward of the first steps, the Neumann series cut off after terms.)
Policy evaluation, given the model P[s, a, s'], R[s, a], a policy pi[s, a], and gamma < 1
1. P_pi[s, s'] = Σ_a pi[s, a] · P[s, a, s'] # Markov chain under pi
2. r_pi[s] = Σ_a pi[s, a] · R[s, a] # expected reward per step
3a. exact: V = solve(I − gamma · P_pi, r_pi)
3b. iterative: V = 0; repeat V ← r_pi + gamma · P_pi @ V until max |change| < tol
4. Q[s, a] = R[s, a] + gamma · Σ_s' P[s, a, s'] · V[s'] # one-step lookahead
Both routes need the model, and . In almost every interesting problem you don’t have it, and you learn from sampled experience instead. That is the subject of Chapter 5. And when there are too many states to list, you approximate with a function (Chapter 6).
Explore: values of a policy you design
Time to get a feel for all of this. The demo shows the gridworld. Each cell shows the policy’s arrow, its value , and a color: green for positive, red for negative. The values are computed exactly, by solving , every time you change anything. How to use it:
- Choose a policy with the preset buttons at the top. “Uniform random” draws all four faint arrows in each cell.
- Tap a cell to inspect it. The side panel shows the Bellman equation for that cell with the actual numbers plugged in (it always checks out), and the cell’s four values.
- Change the selected cell’s action by tapping it again (this cycles through ↑ → ↓ ←), with the arrow buttons in the panel, or with the arrow keys.
- Move the sliders to change γ, the slip probability and the reward per step.
- Sample an episode draws one random run from the selected cell and adds up its return. Average 1,000 episodes compares the average return with .
negative zero positive
Tap any cell to inspect it. Tap the selected cell again, or use these buttons, to change its action.
Episodes start from the selected cell. Each sample is one random run of the policy; V(s) is what their returns average to.
What to try: (1) Set slip to 0. 'Shortest path' and 'Safe detour' then give the same V(start) = 0.492, the return computed by hand above. Now raise slip: which wins, and which cell explains why? (2) Set γ to 0: every value collapses to the immediate reward. (3) In 'Shortest path', inspect the start cell: Q says ↑ beats →. Switch it and watch V(start) rise. (4) Pick 'Always →', set slip to 0, γ to 0.99 and the reward per step to +0.1. Which cells are suddenly worth the most, and why is that a warning about reward design?
A few things worth noticing as you play:
- Values are averages of returns. “Sample an episode” gives a different return every time. “Average 1,000 episodes” lands within a standard error or two of . The linear solve and the sampling compute the same expectation in two different ways. Chapter 5 is built on the sampling route.
- Change one arrow and many values move. A cell’s value depends on the cells it can reach, so editing one action changes the value of every state that can reach it.
- The value of an arrow depends on the slip. With slip 0, both preset paths take 5 steps. With slip 0.2, the shortest path passes (1, 2), right next to the pit, and every step up from there has a 10% chance of sliding in.
Optimal values and optimal policies
We can now evaluate any policy. The obvious next question: what is the best one?
Compare policies state by state. Say if in every state . In the workshop, maintain run-to-failure. This is only a partial order: two policies can each be better in different states. The optimal value functions are the best achievable values:
For finite MDPs (with ), there is a remarkable fact: there is a single policy that achieves in every state at the same time, and it can be taken deterministic. Chapter 4 proves this. Once you know , acting optimally is a lookup:
No lookahead and no model are needed. That is why Q-learning (Chapter 5) and DQN (Chapter 6) learn directly. With only , you’d need one step of lookahead through to find the best action.
satisfies its own Bellman equation, with the average over the policy replaced by a max:
This is the Bellman optimality equation. Because of the max it is no longer linear, so one call to solve won’t do. Solving it, by value iteration and policy iteration, is the whole of Chapter 4. For now, two facts you can check yourself. In the demo with the default settings, “Shortest path” with the start switched to ↑ happens to be optimal, with . In the workshop, the optimal policy changes with : Exercise 3.6.
Summary
- An MDP extends a bandit with states: actions earn rewards and move you to a new state, so good decisions must weigh delayed consequences.
- A state is Markov if it contains everything about the past that matters for the future. You can always make it so by adding history to the state (velocity for a pendulum, the whole prefix for an LLM).
- The return satisfies . The discount gives an effective horizon of steps; is myopic.
- A policy maps states to (distributions over) actions. is the expected return from , and is the expected return after doing once and then following .
- and . Combined, they give the Bellman expectation equation: value now = expected reward now + discounted expected value next.
- In matrix form, : one linear solve, or iterate , which converges geometrically for .
- tells you when a one-time deviation beats the policy. Making such deviations permanent improves the policy, a preview of Chapter 4.
- , and define optimality. Finding them needs the nonlinear Bellman optimality equation: Chapter 4.
Exercises
For each candidate state, say whether it is Markov for the system described. If it isn’t, say what you would add to make it Markov.
- The positions (only) of the planets in a Newtonian simulation, recorded once a day.
- The positions and momenta of the planets in the same simulation.
- The position of a pollen grain in water (Brownian motion), recorded once per second.
- In poker: your own two cards plus the cards on the table.
- A thermostat that sees only the current room temperature, where the heater takes ten minutes to warm up after switching on.
- The text of a chat so far, for an LLM choosing its next token.
Solution
- Not Markov. Same positions, different velocities, different futures. This is the pendulum example again.
- Markov. Positions and momenta are the phase-space state; Hamilton’s equations are first order in them.
- Markov to an excellent approximation. A pollen grain’s velocity decorrelates in well under a microsecond (it is overdamped), far shorter than the one-second sampling interval. So the velocity carries no usable memory between samples, and position alone predicts the future as well as the full history does. “Markov” can depend on the time scale you sample at.
- Not Markov. The betting so far carries information about the opponents’ hidden cards: someone who raised hard probably has a strong hand. The full history of bets is better. This is a partially observable problem (a POMDP), and the principled Markov state is your belief over the hidden cards.
- Not Markov. Two rooms at the same temperature behave differently if the heater was switched on a minute ago in one of them. Add the heater’s state and how long it has been on.
- Markov. The state is the entire history of tokens, so nothing about the past is missing.
- An episode has rewards and then ends. With , compute and , and check that .
- A continuing task pays every step forever. Compute for general , then for and .
- What fraction of the total weight falls on the first steps? Evaluate it for with , and find its limit as .
Solution
- . . Check: . ✓
- (geometric series). : 10. : 100. This matches the effective-horizon reading: a reward of 1 per step over a horizon of steps.
- The first terms sum to , so the fraction is . For , : . As with : (since ), so the fraction tends to . About two-thirds of what the agent cares about lies within one horizon. That’s what “time constant” means for an exponential.
Derive the Bellman expectation equation written in alone:
Then say in one sentence how it differs from the version in where the policy’s choice appears.
Hint
Start from . Condition on first, then on , and use the Markov property as in the derivation of the equation.
Solution
Using and linearity,
Condition on the next state , which has probability :
By the Markov property and stationarity, the inner expectation equals . Now condition on the next action , chosen with probability :
Substituting gives the result. Equivalently: plug “V from Q” into “Q from V”.
The difference: in the equation the policy’s average over actions comes first (at , before the environment’s average over ). In the equation the first action is fixed and the policy’s average comes after the transition, at . This is why can evaluate actions the policy wouldn’t take, and why Q-learning and SARSA (Chapter 5) are built on it.
An ice-cream stand has one policy (it always opens), so this is an MDP with one action per state. On a sunny day it earns 2, and tomorrow is sunny with probability 0.8. On a rainy day it earns 0, and tomorrow is sunny with probability 0.4. Let .
- Write the two Bellman equations and solve for and .
- Rainy days earn nothing, yet is not much smaller than . Why? Find with a one-line shortcut.
- The weather chain has a stationary distribution with . Find it, and check that . Then prove this identity holds for any MDP and policy.
Hint
For part 2, subtract the two Bellman equations: you get one equation in the difference . For part 3, multiply on the left by .
Solution
1. Write for the two values:
The second gives , so . The first gives . Multiply by 23: , so and
Check: . ✓
2. The value counts all future days, discounted. With an effective horizon of 10 days and weather that forgets itself within a few days, most of the value comes from the long-run mix of sunny and rainy days, which is nearly the same whichever day you start on. Subtract the equations:
✓ (.) Notice the factor : it measures how much today’s weather predicts tomorrow’s. If the weather had no memory it would be 0, and would be just today’s difference in reward, 2.
3. The stationary distribution solves with , so , giving . Then , and . ✓
Proof: from , multiply on the left by and use :
If you start from the stationary distribution, the expected value is the long-run average reward times the horizon.
Let be any stochastic matrix (non-negative entries, rows summing to 1) and .
- Show that is invertible.
- Show that has non-negative entries and that every row of sums to . Conclude that .
- Show that (the case ) is always singular. What does that mean for policy evaluation with ?
Hint
For part 1, suppose and look at the component of with the largest absolute value. For part 2, use the Neumann series and the vector of all ones, .
Solution
1. Suppose , i.e. . Let be the index with the largest . Because row of is a probability distribution,
Since , this forces , so . The null space is trivial, hence the matrix is invertible. (In words: averaging can’t make the biggest entry bigger, and the factor then shrinks it.)
2. In the max-row-sum norm, , so the Neumann series converges. Multiplying it by telescopes to , so it equals . Every term has non-negative entries, so does too. For the row sums, gives , so
Then . Each row of is times a probability distribution: the discounted occupancy of each state.
3. , so is in the null space. Then has either no solution (when returns diverge, e.g. a policy that bumps into a wall forever, paying per step) or infinitely many (add any constant to the values in an absorbing class whose rewards are 0). For episodic tasks you can still use : fix at the terminal states and solve only for the non-terminal ones. The reduced matrix is invertible as long as the policy reaches a terminal state with probability 1 from everywhere. This is how LLM training gets away with .
The workshop has deterministic policies.
- Using the maintain values at , , compute all six . In which state does a one-time deviation help?
- Let abandon be the policy (run, repair, run): maintain, but leave a broken machine broken. Evaluate it by hand at , and check that no single-state deviation from it helps.
- At , the matrix solve gives . Show that now repairing a broken machine is the better choice.
- Find the exact discount factor at which repairing and abandoning a broken machine are equally good.
Hint
Use . For part 2, note that from “new” the abandon policy never reaches “broken”. For part 4: under maintain/abandon, satisfies a linear equation in alone. Repairing pays iff .
Solution
1. With and :
The policy’s own actions have , as they must. The only improvement is in broken: run (leave it) gives .
2. Abandon: , so . From new you only ever visit new and worn, where abandon acts like maintain, so and as before. , at least as good as maintain everywhere. The deviations:
None helps. Chapter 4 shows that “no one-step deviation helps” means the policy is optimal, so abandon is optimal at . The impatient owner scraps a broken machine.
3. At , with , the two actions in broken are worth
- (this is , the policy’s own action),
- .
So leaving it broken for a day, then repairing, is now worse than repairing at once, and repairing wins. You can see the same thing from abandon’s side: abandon has and the same (it never visits broken from new), so . A patient owner fixes the machine because the many good days afterwards outweigh the .
Checking the other states as well, and . No one-step deviation from maintain helps anywhere, so maintain is optimal at .
4. Under maintain (or abandon, identical away from broken), and , so
Repair ties with abandon when :
(At , and , so : a worn machine is still repaired, so it was right to use the maintain/abandon values for .)
Below (horizon under about 9 days), scrap it. Above, repair it. Same machine, same rewards: only patience changed, and with it the optimal policy.
Use the demo above.
- Set slip to 0. Compare V(start) under “Shortest path” and “Safe detour”. Then set slip to 0.2 and compare again. Which cell explains the difference?
- Choose “Uniform random” and move the slip slider. The values don’t change at all. Why not?
- Choose “Shortest path” with the default settings. Inspect the start cell, note , then switch the start to ↑. The new V(start) is slightly larger than the Q value you noted. Why?
- Choose “Always →”, slip 0, γ = 0.99, step reward +0.1. Which cells are worth the most? Compute the value of (2, 0) by hand.
Hint
For part 3: Q(start, ↑) means “go up once, then follow the old policy”. What does the old policy do if a slip sends you back to the start? For part 4: where does “Always →” take you from the bottom row, and does that episode ever end?
Solution
- With slip 0 both give , the return we computed by hand. Both paths take 5 steps, and nothing is random. With slip 0.2: shortest path , safe detour . The shortest path goes up through (1, 2), next to the pit, where every attempt to go up has a 10% chance of slipping right into the . The detour reaches (1, 2) only if it slips down from (0, 2).
- Slipping replaces the intended direction with a perpendicular one. If the intended direction is already uniformly random over the four directions, the actual direction is still uniformly random: is identical for every slip value, so the values are too.
- Before switching, . After switching, . Q assumed you go up once. If a slip leaves you at the start (slipping left bumps the edge), the old policy then goes right. The new policy goes up again, which is better again. One improvement step compounds through every revisit, so the new value is at least the Q value. This is the policy improvement theorem in miniature (Chapter 4). This policy is in fact optimal for these settings.
- The bottom row and (1, 0) are worth about . From the bottom row ”→” leads to (2, 3) and then bumps the right edge forever, and (1, 0) bumps the wall forever. The episode never ends, so the agent collects per step indefinitely: . Meanwhile the top row, which walks into the goal, is worth only about –. With a positive per-step reward, the “best” behavior is to never finish the task. This is a tiny case of specification gaming: the reward said “stay alive”, not “reach the goal”. Chapters 1 and 19 have the real-world versions.
A language model writes a response to a prompt , one token at a time, with a vocabulary of 50,000 tokens and at most 100 response tokens. A reward model scores the finished response.
- Write down , , , and a sensible .
- Is the state Markov? Is the transition stochastic?
- In words, what is for a half-written response ?
- Roughly how many states are there? What does that imply for the methods of this chapter?
- What changes if the conversation has several turns, with a human replying between the model’s turns?
Hint
Map each piece of the MDP tuple onto “write one more token”. The reward model only sees finished responses, so ask what the reward is for every token before the last one. For part 4, count the possible responses of exactly 100 tokens.
Solution
- : all sequences (prompt, partial response) up to the length limit. : the 50,000 tokens. : deterministic, with the chosen token appended. Ending with the end-of-sequence token (or hitting 100 tokens) moves to a terminal state. : 0 for every token except the final one, whose reward is the reward model’s score . is fine, because every episode ends within 100 steps.
- Markov: yes, the state is the whole history. Transitions: deterministic. All the randomness is in the policy, the model’s sampling.
- The expected final reward-model score if the model continues from this partial response, sampling as it normally does. A promising start has a high value; a response that has already said something wrong has a low one.
- About (times the number of prompts). You can’t list the states, store , or solve . Everything must be done from sampled responses (Chapter 5) with function approximation: a neural network as the value function (Chapter 6, Chapter 12), or no value function at all (Chapter 15).
- The human’s reply is the environment’s move: it is not chosen by the policy and it is random from the model’s point of view, so transitions become stochastic. The human’s tokens become part of the state but are not actions, so they shouldn’t be trained on. Rewards might come per turn or only at the end. This is the setting of Chapter 18.
In the coding lab (below), open mdp.py and implement:
- Task 1
build_gridworld(slip, step_reward): fill inP[s, a, s2]andR[s, a]. - Task 2
policy_matrices(P, R, pi): returnP_piandr_pi. - Task 3
evaluate_exact(P, R, pi, gamma): solve .
The tests check your arrays on hand-computable transitions (including the (0, 2)-going-right example from this chapter). They check your workshop values against and . And they simulate 3,000 episodes to check that really is an average return.
Hint
In Task 1, move(s, a) and perpendicular(a) from envs.py do the geometry. Two outcomes can land in the same cell (two bumps), so use +=. Terminal states need P[s, a, s] = 1 and R[s, a] = 0. In Task 3 use np.linalg.solve, not np.linalg.inv.
Solution
The core of Task 1, for a non-terminal s:
side1, side2 = perpendicular(a)
P[s, a, move(s, a)] += 1.0 - slip
P[s, a, move(s, side1)] += slip / 2
P[s, a, move(s, side2)] += slip / 2
bonus = sum(P[s, a, s2] * EXIT_REWARD.get(kind(s2), 0.0) for s2 in range(N_STATES))
R[s, a] = step_reward + bonusThe += matters: from the top-left corner going up, the intended move and the slip to the left both bump and stay put, so . A = would give 0.1 and rows that don’t sum to 1. is the expected reward, which is why the landing bonus is weighted by .
Task 2 is two averages over the policy: P_pi = np.einsum("sa,sat->st", pi, P) and r_pi = (pi * R).sum(axis=1). Task 3 is np.linalg.solve(np.eye(n) - gamma * P_pi, r_pi). Solving is faster and more accurate than forming the inverse. The full reference is in solutions/mdp.py.
- Task 4
evaluate_iterative(P, R, pi, gamma, tol): iterate from until the largest change is belowtol; return and the number of sweeps. - Task 5
q_from_v(P, R, V, gamma): return .
Then answer: for the uniform random policy on the gridworld, how many sweeps does Task 4 need at with tol = 1e-10? Compare with the bound from the chapter. Why is the real count smaller than the bound predicts?
Hint
P @ V with P of shape (S, A, S) and V of shape (S,) gives shape (S, A). For the last question: the bound assumes the error never leaves the system. What happens to an agent that reaches a terminal state?
Solution
Task 4 is a loop: V_new = r_pi + gamma * P_pi @ V; stop when np.max(np.abs(V_new - V)) < tol. Task 5 is one line, R + gamma * P @ V. The tests check (pi * Q).sum(axis=1) == V (the “V from Q” relation). They also check that switching the start to the action with the largest improves everywhere, the same experiment as Exercise 3.7.3.
Sweep counts for the random policy (from the reference solution): about 29 at , 142 at , 419 at . The bound predicts about 32, 216 and 2,300 sweeps. Reality is faster because the error shrinks by more than per sweep. Under the random policy the agent leaks into the absorbing terminal states, where the error is 0, so restricted to the non-terminal states has spectral radius below . The bound is tight only for a chain that never terminates. run.py plots the error against the bound on a log axis: both are straight lines (geometric convergence), with different slopes.
Files: mdp.py, envs.py, test_mdp.py, run.py, README.md
cd 03-mdps
python -m pytest -q # your code: tests fail until you fill in the TODOs
RL_SOLUTIONS=1 python -m pytest -q # reference solutions: all passFirst time? See Exercises & setup.
Further reading
- Sutton & Barto (2018), Reinforcement Learning: An Introduction, ch. 3. The canonical treatment of finite MDPs, returns, and value functions. Note their reward index is shifted by one relative to ours (see the notation page).
- David Silver, UCL Course on RL, Lecture 2: Markov Decision Processes. A clear 90-minute lecture with slides that build the same story: Markov chain, then Markov reward process, then MDP.
- OpenAI Spinning Up, Part 1: Key Concepts in RL. A compact summary in deep-RL notation, useful as a cheat sheet when you get to Parts II and III.
- Puterman (1994), Markov Decision Processes: Discrete Stochastic Dynamic Programming. The rigorous reference, if you want the measure-theoretic details and the full theory of optimality criteria.
- Kaelbling, Littman & Cassandra (1998), Planning and acting in partially observable stochastic domains. The standard introduction to POMDPs and belief states.
Next, Chapter 4 turns the Bellman equations into algorithms that find the optimal policy when you know the model: policy iteration, value iteration, and the contraction argument that makes them converge.