From the root, go down to the child with the highest UCB score: good so far (Q/N), or tried too little.
Introduction to Reinforcement LearningPart 3 · Deep RL and planning
Lecture 9Planning and models
Letting the agent learn how the world works and plan with it: models and their errors, Dyna, whether experience replay is a model, forward search and Monte Carlo tree search, and the road from AlphaGo to AlphaZero.
Key ideas, one per episode
- Ep. 31Learn the dynamics once; plan with them for any goal.
- Ep. 32A model turns a little real data into a lot of imagined data.
- Ep. 33Real steps teach the model; imagined steps teach the values.
- Ep. 34A buffer remembers; a model imagines.
- Ep. 35Plan for the state you're in, not the whole world.
- Ep. 36Every node is a bandit; the visits are the answer.
- Ep. 37A policy is good; a policy plus search is better.
Based on: Planning and Models, DeepMind × UCL Reinforcement Learning Lecture Series (2021), by Matteo Hessel; and, for MCTS and AlphaZero, Lecture 14: Monte Carlo Tree Search, Stanford CS234 (Spring 2024), by Emma Brunskill. The slides follow that order of topics, in our own words, figures and examples; they are not official material of the original course.
Watch
7 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 31 · 5:13
Learn the world first
Learn how the world moves once, and plan with it for any goal you like.
Learn the dynamics once; plan with them for any goal.
TranscriptEpisode 31
Recorded forever
I'm recording this. So everything silly I say is saved forever. Well, at least two years. Forever or two years, whichever comes first. Module nine: planning, models and search. A quick recap. So far, we told Bit nothing about the world. It tried things, got rewards, and learned values. Remember the ninety nine and the hundred gold coins? Bit learned they're related. But what gold actually is, it has no idea. Close to its data, it does fine. Far from its data, it can't extrapolate. But we know a tool that's great at exactly that. Show it data, and it finds the hidden pattern. Supervised learning.
Best of both
So far we had two worlds. Dynamic programming: hand me the model, and I'll solve it. But on big problems, it explodes. Model-free learning: assume nothing, and learn values straight from experience. What if we take the best of both? Learn a model from experience, then plan with it. That's model-based reinforcement learning. The loop changes a little. Experience no longer teaches the values directly. It teaches a model, and the model teaches the values. Careful with words, by the way. Until now, the model usually meant the policy. Today, a model means a model of the world.
Why bother
Let's start with the downside. We added a stage. And what happens when you add stages? I see engineers in the audience. More failure points. The model can be wrong, and then the values built on top of it are wrong too. Two sources of error instead of one. Now the upsides. Supervised learning is very good at this job. And many models can tell you how confident they are. Low confidence somewhere interesting? Maybe invest more effort there. Sounds familiar? That was the bandits. And the big one: fewer real samples. Simulating a thousand poker games is cheap. Running a robot is not. A robot run needs a robot, a room, sensors and people. On a bad day, the robot breaks. Asking a model costs a few chips and some electricity.
What's a model
Formally, a model approximates the dynamics of the MDP, with weights we call eta. Give it a state and an action, and it predicts the reward and the next state. Can every world be learned like this? In class, I played a game with a student. I say numbers, you guess the next one. The trick: every new run is longer than everything before it. Whatever pattern you learn, the next run breaks it. No function keeps up. Luckily, the real world lives in R n. It's a metric space, and there it works. This is my course, so I decide what's true.
Dynamics, not policy
So learning a model is supervised learning. The inputs: a state and an action. The targets: the reward and the next state. The data is our experience. A history is one episode. Experience is many of them. Notice what we're learning here. Not the policy. The dynamics. Many people get this wrong. Predicting two outputs at once is painful regression. So we train two models: one for the reward, one for the next state. That's all the genius.
Dynamics vs desires
Here's why keeping them apart matters. The reward depends on what I want. The transition does not. Teach a robot one task, and along the way it learns how the world moves. Now ask it for a different task. Do you learn the dynamics again? No. You got them for free. Chess puzzles teach you how the pieces move, and that carries over to a full game. Some worlds are deterministic, like chess. Some are not, like ice skating. Trust me on this one. You fall, randomly, and hard.
Into the wall
The simplest model predicts the expected next state. And expectations can bite. Say an action sends you left of a wall or right of it, half the time each. The expected next state? Right inside the wall. On a grid, the expectation can land half a cell away. A place that doesn't exist. Linear models suffer less here. A straight line has fewer ways to surprise you. And with linear values, the expected next state even gives the right expected value.
Expectations lie
Another one. A world gives minus a million once, plus a million once, and zero nine hundred and ninety eight times. The expectation: zero. The model did its job faithfully. And it's still useless. Sample one of those millions, and everything shifts. So make the model stochastic. Feed it some noise, and let it predict a next state from that noise. If you've met diffusion models, it's the same spirit. Start from noise, and shape it into something that fits the condition. A stochastic model can be chained, step after step, even when it's non-linear. It just adds some noise along the way.
The A-B table
The humblest model of all is a table. Count how often each state and action led where, and average the rewards. The A B example, eight episodes. A, zero, B, zero. Then six times B, one. And once, B, zero. From A, we always went to B, with reward zero. From B, reward one six times out of eight. Seventy five percent. That's a whole model, learned by counting. No action choices in this one. Things just happen. Next time, we plan with it. And find out it can lie to us.
What planning means
Planning. A word that means different things to different people. Ask someone in robotics, and planning is close to prediction. Ask a mechanical engineer, and it's closer to optimisation. For us, planning means spending compute to improve values and policies, without touching the real world. Dynamic programming is the best example we've seen so far. But it assumed someone handed us the model. Today, nobody hands us anything. We learn the model ourselves, and plan with what we learned.
Option one: DP
Option one: learn the model, then run your favourite dynamic programming on it. Value iteration, policy iteration, whatever you like. But remember the tree. Dynamic programming sweeps every branch, level after level. On big problems, it explodes. Most of those branches you'll never visit anyway. Why pay for them? Option one also needs a full model, with a probability for each possible next state. Often, all we can learn is a model we can sample
Option two: sample
from. Option two is simple and powerful. Use the model only to generate samples. Imagine experience. Ask the model what happens next, again and again. Then run plain model-free learning on the imagined data. Monte Carlo, SARSA, Q-learning. The real world gave us a little data. The model turns it into as much data as we want. A model, in other words, is just a simulator you learned yourself. Cheap to run, and as honest as the data it came from.
A and B, imagined
Back to A and B. We built our table model by counting the eight real episodes. Now we sample eight imagined episodes from it, and run Monte Carlo on those. In our draw, A came out at one, and B at point eight seven five. From the real data, Monte Carlo says V of A is zero. It saw A exactly once, and that time it got nothing. So which one is right? Neither. Under the model, the answer is point seven five. The dynamics look perfect, and the values are still off. More samples fix it. With twenty thousand imagined episodes, V of A lands on point seven six. The law of large numbers, again. Just because you learned that law long ago doesn't mean you forgot it. It means you had lots of time to practise it. So even a model that's exactly right about the data can give wrong values, simply because we sampled too little from it.
The limits
Now the limits. Give me an imperfect model, which is most of the time, and planning can hand you a suboptimal policy. So I stop promising you a global optimum. I don't even promise a local one. Your performance is capped by the model. Non-linear dynamics with a linear model? Sample forever. You'll never get there. Model-based learning is only as good as the estimated model. It sits in the middle, and if it's bad, everything after it is bad. You can check a model like any supervised model: train, test, validation. But that only covers the things you've already seen. And in reinforcement learning, there are always things you haven't seen yet. That's the whole game.
Three ways out
So how do we live with a wrong model? Approach one: when the model is wrong, fall back to model-free learning. Approach two: reason about the model's uncertainty. Bayesian methods, if you've met them. Approach three: combine model-based and model-free learning in one algorithm. That's next episode. In practice, you rarely know the model is wrong. You find out when reality disagrees with it.
The always-wrong trader
Now a fun question. Can a model's mistakes actually help you learn? You want to get rich. So you build an algorithmic trading model. And it's wrong every single time. When you should buy, it says sell. When you should sell, it says buy. A hundred percent of the time. Good model, or bad model? Excellent model. Do the opposite, and you're rich. Extreme, I know. But it makes the point. Less extreme: a model that's wrong in a consistent way still tells you something. Errors you can predict are information.
Over the hill
A less extreme case. Picture a loss with a hill in the way. The best point sits behind it. To get there, things must look worse for a while. TD, with a limited number of tries, prefers not to climb. Bellman promises you'll get there if you try infinitely often. We never do. Now and then, a slightly wrong model, plus some luck, says: why not try over there? And it lands you past the hill. That's rare, and it's luck. The deliberate fixes are simulated annealing, which comes from heating and cooling metals, and population methods. Simulated annealing: heat a metal, and its atoms jump around. Cool it slowly, and they settle into a better arrangement. Jumping is the point.
Science → art
So: models turn a little real data into a lot of imagined data. That's the whole point. Asking a model is cheap. The real world is not. Their weakness: they cap you. A bad model means bad values. The first lectures of this course were science: promises, optimality, proofs. From here on, it's more of an art. Guess, think, try. Next time: the best of both worlds. Bit learns and dreams at the same time. It's called Dyna.
Why a model
Why do we even bother with a model? Not because it's more accurate. A model-free learner has fewer places to break. One reason only. Real samples are expensive, and the model saves them. So should I average the model and the real world, half and half? Then every imagined sample costs me a real one. I saved nothing. Better: for every real step, take many imagined steps. Nine imagined ones for each real one, and I get ten times the updates. Of course, that only helps if the imagined steps are any good. Early on, they aren't. We'll get to that.
The Dyna loop
That's Dyna. Real experience does two jobs. It updates the values directly, like plain Q-learning. And it teaches the model. The model then generates imagined experience, which updates the same values again. Real or imagined, the update looks exactly the same. The values don't care where a sample came from. Draw it as a loop: act, see, learn. And next to it, a second loop that never touches the world: imagine, learn.
Dyna-Q in code
What I love about reinforcement learning: the core of the code is tiny. Dyna Q is about twenty lines. Pick an action, epsilon greedy. Take it. See the next state and the reward. Update Q exactly as in Q-learning. Then store what happened in the model: this state and this action led there, with this reward. And then plan. N times: pick a state you've already seen, an action you already took there, ask the model, and update Q again. That's it. The rest is bookkeeping: storing the model, and picking samples from it.
Only seen states
Why only states we've already seen? Because a model can't invent new states. Or worse, it invents them by mistake. In chess, a white pawn can never stand on the first row. Pawns start on the second row, and only move forward. A sloppy model might predict exactly that. So we only plan from places we've actually been.
The maze, our runs
Does it work? We ran Dyna Q on a small maze. Six by nine, a few walls, a start and a goal. Thirty runs each. With no planning at all, that's plain Q-learning, the second episode still takes about six hundred and thirty steps. With five planning steps per real step: about a hundred and fifty. With fifty: thirty seven. By episode ten, five or fifty planning steps both walk the maze in about seventeen steps. Without planning: still about a hundred and forty. Why so fast? When the goal is first reached, only one state learns about it. With planning, that news spreads backwards through the whole maze before the next episode starts. Same real experience. The imagined steps did the
Growing the planning
rest. One thing I do in practice. At the start, the model is awful. So why trust it? I let the number of planning steps grow. Start small, even zero, and increase it as the model improves. In our maze, growing from zero to fifty planning steps reached the same seventeen steps by episode ten. Fixed at fifty did even better early on, because our model is just a table of what happened. It's never wrong about what it saw. With a learned, noisy model, waiting matters much more. The best numbers for that schedule? That's a riddle. Tune them for your problem.
A shortcut opens
But a model is also a prior. And priors resist change. We ran a maze that gets easier. Halfway through, a shortcut opens in the wall. Plain Dyna Q keeps taking the old road: about eighteen steps to the goal, before and after. Its model says the wall is closed, and it never checks. Dyna Q plus adds a small bonus for trying things it hasn't tried in a while. It finds the shortcut: about twelve steps. The bonus isn't free. Before the change, Dyna Q plus needed about twenty steps per goal, against eighteen. Exploration always costs something. When the world changes, a model-free learner just updates. A model-based learner must first fix its model, and only then its values.
The boat
A real example. I worked on an autonomous boat. A day of sea trials costs tens of thousands of shekels. A big ship carries the small boat out. A crew of six or seven. And someone has to sit in a beach cafe and make sure it all works. That's me. So we built a physics simulation of the boat. A digital twin. Not my favourite term. Simulating physics at high resolution is expensive too. But it's still tens of times cheaper than a day at sea. And the sea is a terrible place. Turbulence, temperature, jammed GPS. Reinforcement learning doesn't need to solve the turbulence. Give the boat a goal, and enough practice. That's what a model is for. An expensive world, swapped for a cheap one, as long as the cheap one is good enough.
Learn and dream
Dyna, in one line: real steps teach the model, and imagined steps teach the values. Sink in more compute, and learn more from every real step. That matters most when real data is slow, expensive or unsafe. Robots. Cars. Boats. Next time: wait a second. Isn't the replay buffer already a model?
Two boxes
Old textbooks sorted algorithms into two neat boxes. Model-free: update values or policies, with no model of the dynamics. Model-based: learn transitions and rewards, then plan with them. Then everyone started storing experience in a replay buffer. And the boxes got blurry. Today: is a replay buffer a model? And if it is, why would anyone build anything fancier?
The buffer is a model
Think about what replay actually does. Store real transitions. Later, sample them, and run model-free updates on them. That's Dyna. The buffer is the model. A non-parametric one: it doesn't predict, it remembers. Dyna asks the model: given this state and action, what happens? Replay just pulls out a whole remembered transition. Same benefit. Many updates on old data, for every new step in the world. And we already used it. DQN, back in module seven, was Dyna in disguise.
Replay vs Dyna
We checked on our maze. Q-learning with replay, five replayed updates per real step, against Dyna Q with five planning steps. Second episode: about two hundred and ten steps with replay, a hundred and fifty with the model. By episode ten, both are at about seventeen. In a small, deterministic table world, a perfect model and a replay buffer give the same answer for every state and action they've seen. So why the gap early on? Replay draws transitions as often as they happened. Our model picks seen pairs evenly. Different information, slightly different paths. And the same answer only holds when the model is perfect. A learned model has errors, and there the two part ways. Could those errors make learning better? Unlikely, if you only imagine transitions from states and actions you've actually tried. Then a buffer is just as good.
Markov, and poker
Now a confession. We assume Markov: the present state is enough. So why remember where we came from? Markov is a lovely theoretical idea. In practice, it's often better to know more. More information never hurts. Engineering costs aside. Poker. Technically, the cards in your hand decide your next move. But remember what the others did at the table, and you might learn some psychology on the way. Who bluffs, who folds early, who gets nervous. None of that is in your cards. All of it is in the history.
Fill, use, empty
How do I sample from a buffer? Honestly, nothing fancy. Fill the buffer. Use it. Empty it. The most naive thing there is. There are papers showing that smarter sampling helps, and I don't dismiss them for a second. My two cents: fill, use, empty. It works great too. It depends on so many things. The size of the buffer, the problem, how often you update. Try it on yours. And replay gives you something else. The same data, seen again in a new context. A bit like epochs in deep learning.
Memory vs compute
A common story. Engineers make the buffer bigger, and learning gets faster. What fun. So they make it bigger again. Every trick has a limit. The early speed-up flattens out, and you're left holding lots of useless memory. It's a classic trade. Spend memory to save compute, or spend compute to save memory. And on that axis, models and buffers differ. Querying a buffer is cheap, but it grows with its capacity. A big generative model can be expensive to sample, but it stays the same size. So, a rule of thumb: a big buffer is good. But the returns diminish. Watch for the point where more memory stops buying you speed.
What only a model can do
So why bother with a parametric model at all? Because it can answer questions a buffer can't. Plan for action selection: ask about actions you could take in the future. Counterfactuals: ask about actions you could have taken in the past, but didn't. The road not taken. Plan backwards: which states could have led to this outcome? And plan in jumps, at different time scales. A buffer can only replay what happened. A model can imagine what didn't. That's planning with things that never happened. Powerful, and also exactly where a model can fool
It's all ratios
you. Is asking the model worth it? It's all about ratios. Say a model call costs ten milliseconds, and a real step costs a hundred. Nine model calls instead of one real step, and you're saving. Eleven, and you're wasteful. For real robots and boats, the ratio is huge, and models win easily. For a board game you can simulate for free? Much less so. And don't forget: the model must be trained first, and that costs real samples too. Model-free pays per step. Model-based pays up front. So before you build a model, ask yourself one question: how much does a real sample cost me?
Remember vs imagine
So: a replay buffer is a model too. A simple, cheap, honest one. A learned model costs more. But it can imagine what never happened. Use the buffer when the past is enough. Build a model when you need to ask about what never happened. Next time, we use a model differently. Not to improve values everywhere, but to choose the very next move. Look before you leap.
Plan for now
So far, the model improved our values everywhere. Today, we plan only for the state we're in, right now. The states you'll meet in the next few moves are a tiny slice of the world. You can get them much more right than the whole map. And a wrong model here mostly leads to some interesting exploration, not to bad updates everywhere. Think of a chess player. They don't evaluate every position in chess. Just the ones that can follow from the board in front of them.
Forward search
Forward search. Build a tree with your current state at the root, and use the model to look ahead. Imagine the game in your head. You play against your own model of the world. It takes a state and an action, and gives back the next state. No need to solve the whole MDP. Just the smaller one that starts from here. I like to call it shadowing. Like a shadow that follows you around. Except this shadow runs ahead of
Expectimax explodes
you. With a perfect model, you can compute the best action exactly. An expectimax tree: take the max over your actions, and average over the world's answers. The catch: the tree grows like states times actions, to the power of the depth. Tic-tac-toe has three hundred sixty two thousand eight hundred and eighty ways to fill the board, move by move. Go has three hundred sixty one first moves. Four moves deep, that's about seventeen billion lines. And the world often answers at random, so every action branches again into many possible next states. So we sample instead.
Simulate whole episodes
Simulation-based search. From the current state, simulate whole episodes with the model, and run model-free learning on them. The simplest version: for each action, simulate K episodes, average the returns, and pick the best action. Before, we used the model like TD: one step, one prediction. Now we use it like Monte Carlo: a whole imagined episode, all the way to the end. And if the imagined road turns out bad in reality? You still learned something important. You thought it was good, and now you know better. The cost: for every action, many imagined episodes. Each one is cheap, but they add up.
MCTS in four steps
Now the star of the show: Monte Carlo tree search. It sits at the heart of AlphaGo. Keep a tree of the states you've visited, with a value for each action. Every simulation has four steps. Select: walk down the tree, picking actions by their values. Expand: add one new node. Roll out: play to the end with a simple policy, often just random moves. Back up: update every value along the path with the result. When time runs out, stop searching, and play the best action at the root. Which one is best? Usually the one with the most visits, not the highest average. A few lucky playouts can fool an average. Many visits are much harder to fool. The rollout doesn't need to be smart. It just needs to finish the game, so you get a result.
Monte Carlo in two layers
The way I like to think about it: Monte Carlo, in two layers. Layer one is the Monte Carlo you know. Start from a board, and play until the game ends. Win, lose or draw. Layer two: where do you start? Pick, at random, one of the boards you've already seen, and play it out from there. In class: a cute new robot faces a chess board. Fifty moves later, the game ends. Next, it pulls out a board it has already seen, and plays from there. Two random processes, one on top of the other. And the chance of repeating a long line exactly is tiny, so every playout teaches you something new.
One dense cloud
Why does this work so well? It builds one big, dense cloud of samples around where you are. Classic sampling gives you lots of small clouds, spread over a huge space. And dense data is exactly what supervised models love. That's one reason tree search fits so nicely inside model-based reinforcement learning. And it's fast for the same reason. It spends its effort on what matters for the next move, not on the far corners of the game. Think of a tourist with one free afternoon. You don't study the map of the whole city. You study the streets around your hotel.
Half the world
The weakness? A silly example. A first screen: choose right, and you enter one game. Choose left, and you enter a different game. Start on the right, keep searching inside the right game, and you'll never see the left one. You just lost half the world. Plain Monte Carlo would stumble into the left side now and then. Tree search builds on itself. And one more sad fact. You work hard, you grow a beautiful tree, you make one single decision, and most of the tree dies. Only the branch you took survives.
Pros and cons
The advantages: highly selective, best first. It evaluates states on the fly. It only needs samples, so a black box model is fine. And you can stop it any time. But the tree itself is a lookup table. It doesn't generalise between similar states. The fix comes from earlier in this course: put a learned value function on top of the tree, so it can extrapolate between states. Next time: how should the tree choose which branch to explore? Spoiler: bandits. They're back.
Which branch?
Inside the tree, every simulation has to choose: which action do I try next? Always the best one so far, and you might miss a better branch. Always at random, and you waste your budget on silly moves. Sounds familiar? Explore or exploit. Our old friend, the multi-armed bandit. Every node is a little room full of slot machines. Pull an arm, get a simulated result, update your average.
A bandit per node
UCT, upper confidence trees, treats every node as its own bandit. Each action is an arm. Score each arm by its average return, plus a bonus that grows when it's been tried rarely. Square root of log big N, over small n. Pick the arm with the highest upper bound. Go down. Repeat at the next node. It's the same UCB we met in module two, with Hoeffding behind it. There, the arms were slot machines. Here, they're moves. So the policy that grows the tree changes from one simulation to the next. It learns while it searches. Log big N grows slowly with the visits to the parent. Small n counts the visits to this arm. An arm that's rarely tried gets a big bonus.
Two policies
That gives us two policies. The tree policy, which improves as the search runs. And the rollout policy, which stays fixed. Often, just random. The tree policy is smart near the root. The rollout policy just finishes the game, so we get a result to back up. In the first AlphaGo, the rollouts came from a small, fast policy. In AlphaZero, there are no rollouts at all. More on that next time. Why random rollouts at all? Because they're cheap. And averaged over many games, even random play says something about a position.
UCT vs random
We built one. UCT for tic-tac-toe, with random rollouts. Two hundred games against a random player, for each budget. Ten simulations per move: it wins seventy eight percent of games, and loses seventeen. Fifty simulations: eighty five percent wins, four percent losses. A thousand simulations: ninety seven and a half percent wins, and not a single loss. The rest are draws. Against a random player, draws mean the random player got lucky. Not that our search was clever. Look at the jump from ten to fifty. Five times the budget, and the losses fall from seventeen percent to four.
Find the win
Now a position where X can win in one move. Five empty squares, one of them wins. With five simulations, it finds the winning square twenty percent of the time. That's a pure guess: one in five. With fifty simulations: sixty nine percent. With one hundred: ninety six percent. With two hundred: every time. Early on, the bonus pushes it to try everything. With enough simulations, the averages win the argument. That's the bandit trade-off in miniature: spend some simulations checking everything, then commit to what works.
Where the time goes
From the empty board, with two thousand simulations, where does the search spend its time? The centre gets four hundred and seventy six visits. The corners, about two hundred and twenty each. The edges, about a hundred and sixty. The visit counts are the answer. The most visited move is the one to play. Centre first, like every child learns eventually. Nobody told it about the centre. It found that out from nothing but random games and
UCT vs UCT
counting. Then we let two UCT players meet, a thousand simulations each. Forty games. Forty draws. Tic-tac-toe is a draw with perfect play. Both of them found it, from random rollouts and a bandit formula. Two perfect players, and no winner. Like most arguments about the best programming language. Against each other, they can't exploit any mistakes, because neither of them makes one.
Regret in a dream
Now something slightly strange. Why did we like upper confidence bounds in the first place? Because exploring costs real reward. Inside the tree, nothing is real. A bad simulated move costs nothing but compute. So minimising regret inside the simulations isn't quite the right goal. What we really want is the best decision at the root. People study this as choosing which computation to run. UCT works very well in practice anyway. Theory and practice, as usual, are not always on speaking terms. When does the bandit view still make sense? When simulations are expensive. Every simulation spent on a bad move is one not spent on a good move.
Flat vs UCT
One more comparison. Flat Monte Carlo, with two hundred simulations spread evenly over the moves, won ninety two and a half percent against the random player. UCT, with the same two hundred, won ninety five percent. Spending simulations where they matter pays off, even in a game this small. And the search never knew a single tic-tac-toe strategy. The rules, random rollouts, and one formula. Tic-tac-toe is tiny. Go is not. To scale this up, the tree needs a much better guess at each leaf than a random game. Next time: put a neural network inside the tree, let it play itself millions of times, and beat the best Go players in the world.
Why Go is hard
Go. More than two and a half thousand years old. Black and white stones on a nineteen by nineteen board. The rules are simple. Surround stones to capture them, and the player with more territory wins. The strategy is anything but simple. Classic game tree search, the kind that conquered chess, failed at Go. Too many moves, and no good way to judge a position. Go has three hundred sixty one points to play at the start, and on average about two hundred and fifty legal moves per turn. So you can't look far ahead, and you can't easily tell who's winning. Search needs both.
AlphaGo, 2016
In March twenty sixteen, DeepMind's AlphaGo beat Lee Sedol, one of the strongest players in the world, four games to one. AlphaGo learned first from human games, then improved by playing itself, and searched with Monte Carlo tree search. Its search used two networks, one proposing moves and one judging positions, plus fast rollouts to the end. And then they asked: what if we drop the humans completely?
Self-play
The key idea: self-play. The agent plays against itself. At every position, it computes its best move. For the opponent's move, it does the same. The only bottleneck is compute. No humans needed. Self-play gives you a perfectly matched opponent, always. Never too weak, never too strong. As you improve, so does your opponent. The reward is sparse: win or lose, once, at the very end of the game. And there's no curriculum to design. Your teacher is always exactly one step ahead of you, because your teacher is you.
One network, two heads
AlphaGo Zero used one network with two heads. Give it a board. One head gives a probability for every move. The other gives a value: how likely am I to win from here? Inside the tree search, the policy head says which moves look promising, so the search tries those first. At a leaf, no random rollout. The value head simply says how good the position is. Run many simulations, then turn the visit counts at the root into a policy. More visits, more probability. Those visit counts are smarter than the raw network. That's the whole trick: search turns a good policy into a better one. Early in a self-play game, it picks moves in proportion to their visits, to explore. Later on, it plays the most visited move.
The training loop
Play a whole game this way, move after move, until someone wins. Then train the network. The policy head learns to predict what the search chose. The value head learns to predict who won. A better network makes a better search. A better search makes better training data. And round and round it goes. Look familiar? It's policy iteration. The search improves the policy, and the network learns to imitate the improvement. Each move used sixteen hundred simulations. About point four seconds of thinking. Fewer simulations than you'd expect, for a game this big. The network makes every simulation count.
Results
The results, from DeepMind's paper in Nature, twenty seventeen. No human games at all. Just the rules. After three days of self-play, AlphaGo Zero beat the version that had beaten Lee Sedol. A hundred games to zero. After forty days, it was stronger than every earlier version. In those first three days, it played about four point nine million games against itself. No opening books, no human games, no hand-made features. The board, the rules, and itself.
The search
So what made it so strong? People asked three questions. One: the search. The network on its own, just playing its first instinct, was rated about three thousand and fifty five Elo. With tree search on top: about five thousand one hundred and eighty five. Same network. Searching at play time was worth more than two thousand Elo points. The raw network on its own sat a little below AlphaGo Fan, the version that first beat a professional player. The search did the rest.
No humans, AlphaZero
Two: the architecture. One residual network for both policy and value, instead of two separate networks, was a clear part of the gain in their comparisons. Three: human data. Starting from zero, with no human games, it ended up stronger than the versions that learned from humans first. Remember module eight: a network that learns its own representation. Here, that pays off in full. Then AlphaZero did the same for chess and shogi too. One algorithm, just the rules. In the paper's runs: nine hours of training for chess, twelve for shogi, thirty four for Go.
Module nine, done
Everything in this module, in one system. A learned evaluation, a model to search with, Monte Carlo, bandits in the tree, and self-play to make the data. One footnote. AlphaZero was given the rules. Its model was perfect. When the model has to be learned too, everything we said about wrong models comes back. A later system, MuZero, took on exactly that. And one thing to keep from all of this: a policy is good. A policy plus search is better. And that's module nine, done. Next module, we forget values for a while, and learn the policy directly. Policy gradients.
5:13Episode 31Learn the world firstLearn the dynamics once; plan with them for any goal.
5:09Episode 32Planning in your headA model turns a little real data into a lot of imagined data.
5:11Episode 33Learn and dreamReal steps teach the model; imagined steps teach the values.
5:07Episode 34Is replay a model?A buffer remembers; a model imagines.
5:15Episode 35Look before you leapPlan for the state you're in, not the whole world.
5:06Episode 36Bandits in the treeEvery node is a bandit; the visits are the answer.
5:11Episode 37From AlphaGo to AlphaZeroA policy is good; a policy plus search is better.
Interactive lab
MCTS lab
Play tic-tac-toe against Bit, who plans with Monte Carlo tree search: random play-outs, and UCB to choose which branch to try next. Change how many simulations it gets and look inside its last search.
Before each move Bit runs a number of simulations from the current board. Each one walks down the tree by UCB, adds a node, plays randomly to the end and backs the result up. Then Bit plays the move it visited most.
Search a little, with random play-outs
Each simulation has four steps. More simulations mean better estimates near the top of the tree.
No knowledge of tic-tac-toe is used beyond its rules: the play-out is completely random.
Add the result to N and Q of every node on the path, each from the view of the player who made that move. Then play the most visited move.
Your move: you are X.
The game
Inside the last search
For each possible move: how often it was visited (N) and its value for the player to move (Q/N).
Yellow: the move chosen (the most visited). Darker blue: more visits.
Play
A game that goes with this lecture, and what to look for while you play.
Echo Heist
Teach a little robot. Steal back a city.
In this lecture: Among Echo Heist’s learners is a planning one. Try it on a mission and compare it with learning purely from trial and error.
Choose what your partner Echo senses, which actions it can take and what success means, then let a real learner train in your browser: tabular, planning, policy-gradient, deep-RL or imitation. When the door opens, the policy is frozen and Echo runs with what it learned.

