Average over what the policy does. Here the policy is random: each of the four moves with probability ¼.
Introduction to Reinforcement LearningPart 1 · Foundations
Lecture 3MDPs and dynamic programming
States and consequences come back: Markov decision processes, returns and discounting, value functions and the Bellman equations, and the dynamic-programming algorithms that solve an MDP when the model is known: policy evaluation, policy iteration and value iteration.
Key ideas, one per episode
- Ep. 10States, actions, dynamics, rewards, and a discount.
- Ep. 11Expected. Cumulative. Reward.
- Ep. 12Turn the equals sign into an update, and sweep.
- Ep. 13RL is an iteration of two problems: evaluation and control.
- Ep. 14One sweep, then improve. And sweep where it matters.
Based on: Lecture 3: Markov Decision Processes and Dynamic Programming, DeepMind × UCL Reinforcement Learning Lecture Series (2021), by Diana Borsa. The slides follow that order of topics, in our own words, figures and examples; they are not official material of the original course.
Watch
5 short episodes of ACML Explains for this lecture. Pick one from the list, and open the transcript to read along: each timestamp plays the episode from there. The narration is generated with a voice clone of Teddy, used with his permission.
Episode 10 · 5:02
From one state to many
A bandit has one state. Chess has more boards than you can count, and every move changes the next one. Welcome to Markov decision processes.
States, actions, dynamics, rewards, and a discount.
TranscriptEpisode 10
From one state to many
Welcome back. About three hundred million years have passed since the last episode. Roughly. Last module, Bit lived in a world with one state: a row of slot machines. Pull, get paid, pull again. Nothing he did changed the world. Real problems aren't like that. In chess, I take your queen, and on the next move you checkmate me. Today: many states, and consequences.
Markov
First, a name you'll hear a lot: Markov. And by the way, Markov is a surname. It's a person, not a thing. A Markov chain is a process with no memory. To predict what comes next, the present is enough. Knowing the whole history doesn't make the prediction any better. Is the weather Markov? Not really. Today's weather alone won't tell you that winter is coming. The season matters. Chess? Yes. Give me the board, and I don't care how you got there. Quick quiz. Let's find a victim. A card game where you only see your own hand. Markov? Not from your seat. Which cards were already played tells you a lot. The history matters. A Markov chain, you watch. Things happen to you, and you just observe. A Markov decision process, you act. Your choices change what happens next. That's the difference.
The MDP
So, formally, an MDP is a few things together. S: the set of all the states. A: the set of all the actions. p: the dynamics, the probability of landing in each next state, with each reward, after an action. And γ, the discount. We'll get to it in a minute. In chess, S is every legal board, and A is every legal move. Both are enormous. That problem will follow us all season. So an MDP is the rules of the game. The agent's job is to play it well.
Why probabilities?
Why probabilities? Picture a remote-controlled robot arm. You tell it: lift ten degrees. It lifts nine. The motor, the sensor, the control loop… infinite reasons. So the same action doesn't always land in the same place. Now, if I knew p perfectly, could I play perfectly? In principle, yes. Think two hundred moves ahead, in your head. Not feasible for big games. But in principle, p is everything. p is the dynamics. And we'll assume p never changes. If it does, the rules change under your feet. That's called concept drift. No concept drift in this course. Want concept drift? Do a PhD.
The can-collecting robot
An example. A robot that collects soda cans. Its battery is either high or low. Two states. With a high battery, it can search for cans, or wait for someone to bring one. With a low battery, it can also go back and recharge. And if it searches on low, it might run flat and need rescuing. Searching pays more than waiting. Rescues cost a lot. Those numbers are the reward, and we choose them. Now, a game. What if waiting paid more than searching? The best strategy is… wait. Forever. Is that what you want from a cleaning robot? Same lesson as before: define the reward properly. And notice: recharging now means more cleaning later. Today's choice changes tomorrow's options. That's what sequential means.
The return and the discount
So what is Bit after now? The return: the sum of the rewards from here on. Problem: if Bit gets one point every step, forever, the sum is infinity. Every policy that never stops looks the same. Also, honestly? We don't care that much about what happens in a thousand years. So we discount. Each step further away, multiply by γ, a number between zero and one. Now the sum is finite. Say every reward is at most 10. Then the return is at most 10 over one minus γ. With γ at 0.9: 100. γ near one: Bit looks far ahead. γ near zero: he looks only at the next step. γ equals zero: pure greed. Think of it like the horizon at sea. You know there's more out there, it just doesn't bother you. With γ at point nine, that horizon is about ten steps. At point nine nine, about a hundred.
Why discount?
Why else discount? Money now is worth more than money later: it earns interest. The future is uncertain, and our model of it is never perfect. People and animals prefer rewards sooner, too. There are other options, like the average reward per step. But the discounted return is the classic default. Average reward is handy for tasks that never end, like a server that runs forever. Does γ actually help your problem? Run it once with γ and once without. Congratulations, you just got a project idea.
What Bit will collect
One last thing. The return at time t isn't what Bit collected. It's what he will collect, from now on. It's in the future, so it's random. That's why next time we'll talk about its expected value. So, an MDP: states, actions, dynamics, rewards, and a discount. The whole sequential world in one tuple. Next: what does it mean for a policy to be the best? With me so far?
The policy
We all gathered here today for one reason: to find the policy. A policy, π, tells Bit what to do in every state. Tell me what the world looks like, and I'll tell you what to do in it. It can be fixed, one action per state, or random, a probability for each action. And remember the duality from module one: know the values, and you know how to act. Know the policy, and you can work out its values.
Values
Now, the value of a state, under a policy: the return Bit expects, starting there and following π. Notice the π in there. We now live inside a context: the policy. Every reward in the return comes from an action, and every action comes from the policy. Change the policy, change the value. Same state, two policies, two different values. A value always belongs to a policy. And q, the value of an action: take this action first, and then follow π. v answers: how good is it to be here? q answers: how good is it to do this, here?
Which policy is better?
Okay. So what's a better policy? If I say I'm better than you, I have to say better at what. We need an order. You can't just compare two policies. But each policy has a value, and values are numbers. So: π is at least as good as π prime if its value is at least as high in every single state. Every. A hundred million states, better in all of them but one, worse in one? Not better. Very strict. And some pairs of policies can't be compared at all. That's fine. Think of two students. One is better at maths, the other at history. Who's the better student? Depends who's asking.
The promise
Why bother with such a strict order? Because it buys us a promise. Each improvement only goes up. And values can't go up forever: rewards are bounded, so the return is bounded. Something that only goes up, and is bounded, converges. That's first-year calculus. And the theorem: there's always an optimal policy, π star, at least as good as every other policy, in every state. There may be several. They all share the same values: v star and q star. Two routes home of exactly the same length? Both optimal. Same value, different policies. This is the only course that makes you good promises. What did computer vision promise you? A headache, and a crazy GPU bill.
Greedy on q*
And if someone hands you q star, acting is easy. In every state, pick the action with the highest q star. That's an optimal policy. Done. So finding the best behaviour and finding the best values are the same problem, seen from two sides. That's why, from now on, we'll chase values. Get the values right, and the policy comes for free.
The Bellman equation
Now, the most basic equation in RL. We'll meet it all the time from now on: the Bellman equation. The value of a state is the reward you get now, plus γ times the value of where you land. Averaged over what π picks, and over where p sends you. Read it out loud once. It's the sentence this whole course is built on. It's recursive: a value, defined by other values. One step, then let the next state worry about the rest. Let's check one. Next episode we'll meet a grid where a square next to the exit is worth minus fourteen. Its four neighbours average out to minus thirteen. Minus one for the step: minus fourteen. Bellman holds. Same for q: the reward now, plus γ times the value of the next state and the next action.
Bellman optimality
And for the best policy, there's a twist. Instead of averaging over the actions, take the best one. v star of a state is the max over actions: reward now, plus γ times v star of where you land. That's the Bellman optimality equation. In plain words: the best you can do from here is the best first step, followed by the best you can do from there. That max makes it non-linear. Remember that. It'll matter next episode. So from now on: the expectation equation to evaluate, and the optimality equation to find the
A tiny example
best. A tiny example. From the start, going left pays one point, and the game ends. Going right pays nothing now, but leads to a state that pays five. With γ at point nine, right is worth four and a half. Bigger than one. Go right. With γ at point one, right is worth half a point. Now left wins. Same world, different γ, different best policy. That's Bellman doing its job: today's reward, plus the discounted best of tomorrow. And with γ equal to one? Right is worth five. No contest.
Three words
So what are we really trying to maximise? Three words. Expected. Cumulative. Reward. Repeat after me. Values tell you how good things are. The order tells you which policy is better. Bellman ties it all together. A promise: an optimal policy always exists. A recipe: be greedy on q star. A tool: Bellman. Next time: we actually solve these equations. Once with a matrix, and once with sweeps. With me so far?
Prediction and control
Last time, we wrote the Bellman equation. Today we solve it. There are two problems. Prediction: here's a policy, how good is it? That's also called policy evaluation. Control: find the best policy. Given this treatment protocol, or this trading strategy, what's my expected return? That's prediction. Which one should I use? That's control. Prediction is the inner loop. Control is what we actually want.
The matrix form
Start with prediction. For a fixed policy, the Bellman equation is linear. Stack all the values into one vector. The rewards into another. The transitions into a matrix. Then v equals r, plus γ times P times v. One line. Move things around, and v is the inverse of one minus γ P, times r. Done! Right? For a small problem, that really is the answer. Exact, in one shot. Write it for three states, and you could solve it by hand. Try it. It's a nice exercise.
What it costs
Computer science people will tell you: matrix inversion is n cubed. Polynomial. That's fine. Two thousand states: eight billion operations. A few seconds. Heavy, but feasible. A million states: ten to the eighteen operations. On one core doing a few billion a second, that's about ten years. And chess has far, far more than a million states. And for control, the Bellman optimality equation has a max in it. Not linear. No matrix trick at all. Polynomial, it turns out, isn't the same as practical.
Dynamic programming
So we need iterative methods. And the classic family is called dynamic programming. Where does the name come from? Richard Bellman, the same Bellman. Honestly, I always forget his first name is Richard. He later said that the nineteen fifties were not good years for mathematical research. So he picked a name that didn't sound like maths. And people say dynamic programming means storing computations so you don't repeat them. That's a side effect of programming. Dynamic programming has one property: break a problem into a smaller problem, again and again, until you reach one you can solve directly. And the Bellman equation is already built that way: the value of a state is the reward now, plus a smaller problem: the value of the next state. And it assumes we know the MDP perfectly. p, the rewards, everything. For now, we do.
Turn = into ←
Here's the trick. Take the Bellman equation, and turn the equals sign into an update. Value at step k plus one: the reward, plus γ times the value at step k of where you land. Start with all zeros. Sweep over every state. Then sweep again, using the new values. And again. Stop when the values stop moving, or when they change by less than some small number. That's iterative policy evaluation. In code: two arrays, old values and new values. Every state reads the old ones and writes a new one. Swap, and repeat. There's another way: one array, overwritten as you go. We'll get to it in two episodes.
Watching it sweep
Let's watch it. A four by four grid. Two corners are exits. Every step costs one point. The policy: totally random. Up, down, left, right, a quarter each. Sweep zero: all zeros. Bit has no preferences at all. Sweep one: every square is minus one. One step costs one. Sweep two: the squares next to an exit are at minus one point seven five. The others at minus two. Sweep three: minus two point four, minus two point nine, minus three. It keeps going. Keep sweeping, and it settles: minus fourteen next to the exits, minus twenty-two in the far corners. A random walker takes a long time to get out. And that minus fourteen from last episode? Here it is. Bellman, checked.
The arrows
Now, a trick. In each square, draw an arrow toward the best neighbour. At sweep zero, every direction ties. Nothing to choose. At sweep three, the arrows already point the shortest way home. The optimal policy. After three sweeps! Could we have stopped there? No. From inside, there's no way to know the arrows won't change again. The values were still far from the truth. Only the order happened to be right. Notice what mattered: not the numbers themselves, only their order. Minus three or minus twenty-two, the arrows are the same. The numbers tell you how long a random walker suffers. The arrows tell you what a smart walker should do. Different questions. If you can invent an order on policies that tells you when to stop early, come talk to me. We'll write a Nature paper.
Matrix or sweeps
So now we can evaluate any policy: with a matrix if it's small, with sweeps if it's not. And the arrows trick, acting greedily on the values, is the seed of the next idea. Each sweep touches every state, every action and every next state. Remember that cost. Prediction, solved. Now let's use it for control. Next time: evaluate, improve, evaluate, improve. Policy iteration, and a car rental business. With me so far?
Check, improve
Do you know how ABS brakes work? They measure the wheels, then act so the car doesn't skid. Measure, act, measure, act. Classic control engineering. And reinforcement learning borrowed exactly that loop. Your thermostat does it too. Measure the room, switch the heating, measure again. Check. Improve. Check. Improve. Check. Improve. Until it doesn't improve anymore.
Greedy improvement
We already know how to check: policy evaluation. Now, how to improve. In every state, look at q of π: the value of each action, if afterwards you follow your old policy. Pick the action with the highest q. That's the new policy. π prime is the arg max of q π. Don't let the math scare you. It says: given what you know now, do what looks best. A real example, from the problem we'll see in a minute. In one state, under the old lazy policy, doing nothing is worth five hundred nineteen dollars. Moving five cars is worth five hundred forty-one. So the new policy moves five. That's all improvement is.
Why it can't get worse
Why can't this make things worse? In each state, the greedy action is at least as good as what the old policy did. Take it once, then follow the old policy: no worse. Take it again at the next step: still no worse. Unroll it all the way. So the new policy's value is at least the old one's, in every state. Our strict order, satisfied. Better in every state: exactly the order from two episodes ago. And if the policy stops changing? Then the values satisfy the Bellman optimality equation. You're optimal. One warning. This greedy is not the greedy from bandits. There, greedy meant no exploration. Here, it's a step in the space of policies. Different job.
Policy iteration
Put it together: policy iteration. Start with any policy. I'd be happy if you started somewhere good. But I have no idea how to promise you that. Evaluate it. Act greedily on the values. That's a new policy. Evaluate it. Improve again. Each new policy makes the old values a bit wrong. So we evaluate again. It zigzags, and lands on the optimal values, and the optimal policy. How many rounds does it take? Usually, surprisingly few.
Jack's car rental
A real example: Jack's car rental. Jack runs two locations, and each holds up to twenty cars. Every car rented earns ten dollars. Customers arrive at random: about three a day at the first place, four at the second. Returns are random too: about three a day at the first, two at the second. Random arrivals like these follow a Poisson distribution. Three on average. Sometimes none, sometimes eight. Overnight, Jack can move up to five cars between the locations, at two dollars a car. And γ is point nine. The state: how many cars at each place. Twenty-one times twenty-one: four hundred forty-one states. And eleven possible moves in each, from five one way to five the other. Small enough for dynamic programming. The question: how many cars to move tonight, in each of those states?
Our run
We ran it. Start with the lazy policy: never move anything. Evaluate, improve: the first new policy already moves cars toward the busier location. Again, and again. The border between moving and not moving gets sharper each time. After four improvements, the policy stops changing. That's the optimal policy. Look at the shape: a staircase. The more cars piled up at the first place, the more you move. And the value: from about four hundred twenty dollars with an empty lot, to about six hundred forty with twenty cars at each. Why push cars to the second place? More customers there, and fewer returns. It keeps running dry. And never move more than you need. Every car costs two dollars, and a car in the wrong place earns nothing. None of this was programmed in. It fell out of evaluate and improve.
How much evaluation?
Look how long each evaluation took: a hundred twenty-six sweeps, then ninety-one, eighty, forty-five, fourteen. Each new policy starts from the old values, so evaluation gets faster as we go. Do we really need to evaluate all the way? Or can we stop when we're close? Stop early, and each step is cheaper. But the promise that each step improves gets weaker. Truncated evaluation. Cost-wise, one sweep is about m times n squared operations, with m actions and n states. Much less than n cubed, since we usually have far fewer actions than states. In practice, people stop early all the time. And it works. Push it to the extreme: one sweep, then improve. That has a name, and it's next episode.
An iteration of two problems
So here's the big picture. In supervised learning, you have one problem: fit the data. Reinforcement learning isn't one problem. It's an iteration of two: evaluation and control. Evaluate, to know where you stand. Then improve, to move. And repeat. You'll see these two steps inside almost every algorithm from now on. Sometimes in disguise. Next time: value iteration, and how to sweep smarter. With me so far?
Back up the max
Last time: evaluate a policy all the way, then improve it. What if we evaluate for just one sweep? Take the Bellman optimality equation, the one with the max, and turn it into an update. Policy iteration evaluates all the way, then improves. Value iteration improves after every single sweep. Value at k plus one: the max over actions of the reward, plus γ times the value at k of where you land. That's value iteration. Improvement and evaluation, squeezed into one line. Why does it work? If the values stop changing, they satisfy the Bellman optimality equation. And the only thing that does is v star. And each round is cheap: one sweep, no full evaluation inside.
The shortest path
Watch it on a tiny maze. A four by four grid, the goal in the top-left corner, minus one for every step. Sweep one: the goal is zero, everything else minus one. Sweep two: the goal's neighbours stay at minus one. Everyone else drops to minus two. Sweep three: minus three appears. The ripple grows by one ring per sweep. Each sweep, the news travels one step further from the goal. Like a ripple in a pond. By sweep six, every square knows its distance to the goal. One more sweep changes nothing. And notice: no explicit policy in between. The middle values might not belong to any policy at all. Only the final ones matter. And the policy at the end? In every square, step to the neighbour with the highest value. Greedy on v star. On this maze, value iteration does what a breadth-first search would do. But it works on any MDP, with randomness and rewards anywhere.
Three algorithms
So now we have three dynamic-programming algorithms. Let's put them in one table. Prediction, with the Bellman expectation equation: iterative policy evaluation. Control, with the expectation equation plus greedy improvement: policy iteration. Control, with the optimality equation: value iteration. All three need the model, and all three update every state, every sweep. That's called synchronous. Cost per sweep: m times n squared for state values. For action values, m squared times n squared. One reason we usually prefer v when we have the model. So the whole table is two questions: prediction or control, and which Bellman equation you turn into an update.
Asynchronous, in place
But who says you have to update every state, every time, in order? Asynchronous dynamic programming: update states one at a time, in any order. As long as every state keeps getting picked, it still converges. Picture a hundred workers, each updating their own corner of the map, whenever they're ready. Three simple ideas. First: in-place. Keep one copy of the values, not two. As soon as a state gets a new value, the next state uses it. News spreads faster, and you save memory. And the order matters. Sweep from the goal outwards, and one sweep can do the work of many. Synchronous is the textbook. Asynchronous is what people actually code.
Prioritised sweeping
Second: prioritised sweeping. Some states are badly wrong. Others are already right. Measure how wrong each one is: the gap between its value and what Bellman says it should be. Update the most wrong first. Then fix its neighbours, because their gaps just changed. Like a priority queue in an emergency room. In big problems, most states are fine most of the time. Prioritising saves a lot of work. Same instinct as a good doctor. Worst cases first. Don't spend time on the healthy
Real-time DP
ones. Third: real-time dynamic programming. Only update the states the agent actually visits, or expects to visit soon. A chess player doesn't think about impossible positions. Why should Bit? In a maze, Bit doesn't need perfect values in rooms he'll never enter. Spend your computation where the action is. That's how planning in games works: think hard about the positions you might actually reach, and ignore the rest of the universe.
Sample backups
One more problem. Every backup we did was full-width. To update one state, you look at every action, and every possible next state. Fine for a grid. For a big problem, even one backup is too expensive. That's the curse of dimensionality. And it needs p. All of it. Perfectly. The fix: sample backups. Instead of all the next states, use one that actually happened: a state, an action, a reward, a next state. And then you don't need p at all. The world does the sampling for you. That's model-free learning, and it's coming soon. Keep this sentence in mind: model-free learning is dynamic programming with samples instead of expectations.
Module three, done
And that's module three, done. We have Markov decision processes, returns, values, and the Bellman equations. And three ways to solve them when we know the model: evaluation, policy iteration, value iteration. All of it rests on one equation, from one man, in the nineteen fifties. But why does any of this converge? Why one answer, and why from any starting point? Next module: the theory. Contractions, fixed points, and one beautiful theorem. With me so far? See you there.
5:02Episode 10From one state to manyStates, actions, dynamics, rewards, and a discount.
5:04Episode 11What does “best” mean?Expected. Cumulative. Reward.
5:06Episode 12Solving BellmanTurn the equals sign into an update, and sweep.
5:20Episode 13Policy iterationRL is an iteration of two problems: evaluation and control.
5:24Episode 14Value iterationOne sweep, then improve. And sweep where it matters.
Interactive lab
Dynamic programming lab
Watch policy evaluation, value iteration and policy iteration sweep a small gridworld. Change the discount, make moves slippery, add walls, and see the values settle and the greedy arrows lock in.
Here the model is known: every move costs −1 and the two shaded corners end the episode, as in the 4×4 gridworld of Sutton and Barto (Example 4.1). Each sweep applies a Bellman equation once to every cell.
One Bellman update per cell, every sweep
q(s, a) = Σ p(s′ | s, a) [ r + γ v(s′) ] is what action a is worth in cell s, given the current values. The three algorithms differ only in what they do with it.
Take the best action instead of the average. The values converge to v*, and the greedy arrows to an optimal policy.
Evaluate the current policy until its values settle, make it greedy, and repeat until the policy stops changing.
Values start at 0. Press One sweep.
Values and greedy arrows
Darker cells are worse (further from an exit). The arrows are the greedy actions; ties show more than one.
How much the values still change
The largest change in any cell, per sweep, on a log scale. Dotted lines mark policy improvements.
Play
A game that goes with this lecture, and what to look for while you play.
Markov’s Maze
A maze where every step is a roll of the dice.
In this lecture: Every rune tile has its own transition probabilities: where you meant to go, the opposite way, left, right, or stay. Hover over a tile to read them. You are playing inside an MDP; plan for where you are likely to land, not only where you aim.
Each rune tile resolves your move with its own five probabilities: where you meant to go, the opposite way, left, right, or stay. Reach the goal seal without falling into traps or lava, while cursed knights patrol.

