Reinforcement Learning, from Bellman to AlphaZero
How do you learn to act when nobody tells you the right action, only how things turned out?
The part opens in Seoul in March 2016, on AlphaGo's move 37 against Lee Sedol, a move its own model of human play rated at one in ten thousand. It then starts from Thorndike's puzzle boxes and the agent-environment loop, and meets exploration on a ten-armed bandit, where the upper confidence bound is derived from Hoeffding's inequality. Bellman's equation is derived on a slippery gridworld of 44 states, and value iteration is proved to converge because the Bellman operator is a contraction. The part turns when the model and the sweep over every state are taken away: temporal differences, Sarsa and Q-learning learn from sampled experience on the random walk and the cliff walk, and DQN and PPO are trained on the cart-pole with their training replayed. Search enters with minimax, alpha-beta and Monte Carlo tree search on Connect Four, and joins learning in AlphaGo and AlphaZero; the part's own AlphaZero for Connect Four is graded move by move against a perfect solver. It ends with MuZero's learned model and with games of hidden information, where regret matching and CFR find the equilibrium of Kuhn poker.
What you need. Probability and expectations (Part 5), gradients (Part 4) and a first idea of a neural network (Part 9); no game theory is assumed.
- Mathematics and history
- bandits and UCB, Bellman, TD, Q-learning and DQN, policy gradients, PPO, MCTS, AlphaGo, AlphaZero, MuZero, CFR
- Models, data
- our own AlphaZero (Connect Four)
What you will be able to do
Undergraduate
- Write the return, the value of a state and Bellman's equation for a small Markov decision process, and run value iteration on it by hand for a few sweeps.
- Explain the difference between learning a value from complete episodes and from temporal differences, and between Sarsa's and Q-learning's path on the cliff walk.
Master's
- Prove that the Bellman operator is a contraction in the max norm and deduce that value iteration converges at rate gamma.
- Derive the UCB bonus from Hoeffding's inequality and the policy gradient with a baseline from the log-derivative trick.
- Describe the four steps of Monte Carlo tree search and how AlphaZero uses search as a policy improvement operator.
Research
- State the Lai-Robbins lower bound and UCB1's regret, and prove that no-regret play by both players of a zero-sum game gives an approximate Nash equilibrium.
- Explain what MuZero's value-equivalent model must predict and what it is free to ignore.
Engineering
- Implement tabular Q-learning and a DQN with replay and a target network, and diagnose divergence from the deadly triad.
- Read PPO's clipped objective term by term and say which updates it stops and which it does not.
Contents
Each chapter has a home level. Choose a track to see what to read and watch: Undergraduate 22 min · Master's 58 min · Research 65 min · Engineering 36 min.
- 0The move nobody would playUndergraduate2 min
- 1Learning from consequencesUndergraduate5 min
- 2Explore or exploitMaster's6 min
- 3Bellman's equationUndergraduate4 min
- 4Why value iteration worksMaster's4 min
- 5Temporal differencesUndergraduate5 min
- 6Q-learningMaster's3 min
- 7Deep Q-networksEngineering5 min
- 8Policy gradientsMaster's5 min
- 9Trust regions and PPOEngineering3 min
- 10Search before learningUndergraduate3 min
- 11Monte Carlo tree searchMaster's4 min
- 12AlphaGoUndergraduate3 min
- 13Learning from zeroEngineering5 min
- 14Planning with a learned modelResearch2 min
- 15Beyond perfect informationResearch5 min
- Recap, problems, and where this comes backAll tracks2 min
Also on this page: Lecture · Key results · Try it · Lab · Problems · Notes and sources · 中文 · Build the film.
Lecture
The text of each chapter is the film's narration, as it is spoken, so you can read along or revise without the film. The pictures are in the film. A dashed box stands for a number the film computes when it is rendered (hover over it to see what is computed); the README's figures for each chapter, where it lists them, follow the chapter's text.
The move nobody would playUndergraduate2 min
Seoul, March 2016. A computer program, AlphaGo, is playing Lee Sedol, one of the best Go players in the world. On its thirty-seventh move it plays here, a move so unusual that the commentators assume it's a mistake. AlphaGo's own model of human play put the chance that a person would play it at one in ten thousand. It wins the game, and the match. A year and a half later, its successor learns Go with no human games at all, from random play, in three days, and beats it a hundred games to nothing.
That is the question of this part: how do you learn to act, when nobody tells you the right action, only how things turned out? We'll follow the answer from a psychologist's puzzle boxes, through Bellman's equation and the algorithms that learned backgammon, Atari and the cart-pole, to AlphaGo and AlphaZero, deriving each step. And we'll train an AlphaZero of our own, on the computer making this video, and grade every move it makes against a perfect player.
This is Part 26 of AI, Built, and the start of its fifth act: agency. In this part: the reinforcement learning problem and the dilemma of exploration; Bellman's equation and why its algorithms converge; learning from experience, from temporal differences to deep Q-networks; policy gradients and PPO, the algorithm behind ChatGPT's training; search, from minimax to AlphaZero and MuZero; and games with hidden information, like poker.
1Learning from consequencesUndergraduate5 min
In the 1890s the psychologist Edward Thorndike put cats in puzzle boxes. To get out, and get to the fish outside, a cat had to pull a loop of string. The first time it took minutes of scrabbling. Each time after, a little less, until the cat went straight for the loop. In 1911 he called it the law of effect: what is followed by satisfaction gets stamped in. Reinforcement learning is that law, made into mathematics. Nobody shows the learner the right action. There is only a number, a reward, that arrives after it acts, sometimes long after.
Here is the setting, in its modern form. An agent and an environment take turns. At each step t the agent sees the state, s t, and chooses an action, a t. The environment answers with a reward, r t plus one, and a new state. And again, and again. Unrolled, the interaction is one long sequence: state, action, reward, state, action, reward. A game of Go is one such sequence, with every reward zero except the last: plus one for a win, minus one for a loss.
The mathematical object is a Markov decision process. A set of states, a set of actions; the probability of each next state given the current state and action; a reward for each state and action; and a discount, gamma, that we'll meet in a moment. The word Markov carries the key assumption: the next state depends on the past only through the present state and action. Whatever history matters must be folded into the state. The framework is Richard Bellman's, from the 1950s, made for planning problems at the RAND Corporation long before anyone thought of learning.
What the agent wants is not the next reward but all of them. The return from time t, G t, adds them up, with each reward k steps away discounted by gamma to the k. With gamma zero point nine, a reward ten steps away counts for a third of one now. Turn gamma down, and the agent becomes short-sighted; gamma near one is a patient agent. The discount also keeps the sum finite even if the game never ends: if every reward is at most r max, the return is at most r max times a geometric series, r max over one minus gamma. And the return has a recursive shape. Pull out the first reward, and what is left is gamma times the return from the next step: G t equals r t plus one plus gamma G t plus one. The next three chapters are built on this one line.
Two more definitions, and we have the whole vocabulary. A policy, pi of a given s, is the agent's rule: a probability for each action in each state. The value of a state under a policy, V pi of s, is the return you expect if you start there and follow pi. Its cousin, the action value Q pi of s and a, is the expected return if you first take action a, and only then follow pi. Averaging Q over the policy's choices gives back V. Values are what everything in this part computes. Dynamic programming computes them exactly, temporal differences learn them from experience, and AlphaZero's network guesses them at a glance.
Three things make this harder than learning from labelled examples. Credit assignment: in Go the reward arrives two hundred moves after the moves that earned it. Which of them deserves the credit? Exploration: you only see what happens after actions you actually try, so a learner that always does what looks best may never find out what is better. And the data depends on the learner: change the policy, and you change the states you see. In supervised learning every example comes with its answer, and the examples sit still. Here, neither is true.
2Explore or exploitMaster's6 min
Before states and long horizons, take reinforcement learning with every complication removed but one. You face k slot machines, one-armed bandits. Each pays a random reward from its own distribution, and you don't know which is best. Pull one arm per step, for as many steps as you're given, and collect as much as you can. This is the problem a doctor faces choosing between treatments, and a website choosing which version of a page to show: Thompson posed it in 1933 about patients. There's one state, so no credit assignment and no planning. What's left is pure exploration: every pull spent learning about an arm that might be worse is a pull not spent on the arm that looks best.
The obvious strategy: keep an average of the rewards from each arm, and always pull the arm with the best average. That's the greedy rule. Here it is on the standard testbed from Sutton and Barto's book: ten arms whose means are themselves random, two thousand runs. Greedy settles early on whichever arm happened to pay well at first, and finds the best arm only percent of the time. The fix is to explore on purpose. Epsilon-greedy pulls a random arm one time in ten: it finds the best arm percent of the time. But it never stops exploring. Even after it knows, it wastes a tenth of its pulls.
To compare strategies we need a score. The regret after T pulls is what you would have earned by always pulling the best arm, minus what you expect to earn. Each pull of a worse arm a costs its gap, delta a, so the regret is the sum over arms of the gap times the expected number of pulls of that arm. Epsilon-greedy pulls every arm a fixed fraction of the time forever, so its regret grows in proportion to T. A good strategy pulls the bad arms less and less often, so its regret grows much more slowly than T.
A cleverer idea: optimism in the face of uncertainty. Act as if each arm is as good as it plausibly could be. How good is plausible? For independent rewards in zero to one, Hoeffding's inequality from Part 5: after n pulls, the chance that an arm's true mean lies more than epsilon above its average is at most e to the minus two n epsilon squared. Choose epsilon so that this chance is tiny, t to the minus four, and epsilon is the square root of two log t over n. That's the upper confidence bound algorithm, UCB: pull the arm with the highest average plus bonus. An arm pulled rarely has a big bonus, so it gets tried; the bonus shrinks as its pulls pile up, and grows like the square root of log t for arms left alone. The payoff is a theorem: each worse arm has an expected pull count of order log T over its gap squared times, so the regret grows like log T. And Lai and Robbins proved in 1985 that uniformly efficient strategies on Bernoulli bandits face an asymptotic logarithmic lower bound. For a fixed bandit with positive gaps, UCB1 matches that order.
Watch it work on five arms. The white dot is each arm's average, the bar above it the bonus, and the arm with the highest top gets pulled, boxed in blue. This demonstration uses Gaussian rewards, so the bounded-reward confidence guarantee above does not apply directly. Early on every arm's bar is tall, and the pulls go round. As an arm is pulled its bar shrinks, and arms whose averages are low drop out of contention. After pulls, percent went to the best arm, and the worst was tried only a handful of times, just enough to be sure.
There's an older idea, from Thompson himself. Keep a posterior for each arm's mean, Bayes's rule from Part 5, updated after every pull. Then, at each step, draw one plausible mean from each posterior and pull the arm whose draw is largest. An arm is pulled exactly as often as it is likely to be the best: well-known bad arms almost never, uncertain ones sometimes. On the ten-armed testbed it finds the best arm percent of the time, the best of the four. And on a pair of coins, plotted against the log of the number of pulls, epsilon-greedy's regret bends upward and leaves the chart: it grows like T. UCB and Thompson sampling settle into straight lines here, like log T, and Thompson's line is the flattest. Remember the upper confidence bound. Ten chapters from now it will be steering the search inside AlphaGo.
3Bellman's equationUndergraduate4 min
Start from the definition: the value of s is the expected return from s. Now use the recursion from chapter one: the return is the next reward plus gamma times the return after it. Take the expectation in two stages: first over the action the policy picks, then over the state the environment sends you to. And here the Markov property does its work. Once you are in s prime, the expected return from there is just the value of s prime: nothing about how you got there matters. This is the Bellman equation. The value of a state is the reward you expect now, plus gamma times the value of where you expect to land. One equation per state, each tying a state's value to its neighbours'.
Draw it as a tree. At the top, the state s. The policy chooses among the actions, the small dots, with probabilities pi. Each action can lead to several next states, with probabilities from the environment, and a reward along the way. The Bellman equation says: value flows back up this tree. Average the next states' values, weighted by how likely you are to land there, discount that average, add the reward, and average over actions. Sutton and Barto call these backup diagrams. Every algorithm in this part is a different way of doing that backup: exactly, or from samples, or inside a search tree.
Here is a world to try it on: a grid with walls, a goal worth plus one, and a pit worth minus one, right below it. Moves are slippery: you go where you meant eighty percent of the time, and slip to either side ten percent each. For a fixed policy, the Bellman equations are linear equations in unknowns. In matrix form, V is the expected reward vector plus gamma times the transition matrix times V. Gather the V's, and one matrix inverse gives the values exactly. For the policy that moves at random, here they are: hardly anything is worth much, and the start is worth : a random walker is about as likely to fall into the pit as to find the goal.
That was one policy's value. What we want is the best policy. Its value, V star, satisfies the same equation with the average over actions replaced by a maximum: the Bellman optimality equation. And if you know V star, the best policy is to act greedily on it: in each state, pick the action with the best expected backed-up value. Here is V star for the gridworld, with its greedy policy. Look at the cell just under the pit. Its arrow points down, away from the goal. Up would walk into the pit, and a step sideways slips into it one time in ten, so the best plan takes the long way round. The max makes these equations nonlinear, so there's no single matrix inverse. The next chapter solves them anyway, by iteration, and proves it works.
4Why value iteration worksMaster's4 min
Bellman's own answer to the nonlinear equations was to iterate them. Start with every value at zero. Apply the right-hand side of the optimality equation to every state at once, and call the result the new values. Then do it again. After one sweep, only the cells at the goal and the pit know their exit rewards. The next sweep reaches their neighbours; each sweep pushes the news one step further, and the values spread out from the goal like heat. After a few dozen sweeps nothing changes any more: we have V star, and the arrows of the last chapter.
Why must this work? Write the right-hand side as an operator, T, that takes a table of values and returns a new one. One small lemma: two maxima can't differ by more than the biggest difference between the things being maximized. Compare T applied to two different tables, V and U. The rewards are the same, so they cancel, and what's left is gamma times an average of differences. An average is never bigger than the largest entry. So T shrinks the distance between any two tables, in the max norm, by a factor gamma. It's a contraction. And Banach's fixed point theorem from 1922 finishes the job: a contraction has exactly one fixed point, and repeating it from any start converges there geometrically, at rate gamma. That fixed point satisfies the Bellman optimality equation: it is V star.
Here's the theorem at work. Run value iteration twice on the gridworld: once from all zeros, once from random values. On a log scale, here is the largest difference between the two runs, sweep by sweep. The theorem says it must stay under the dashed line, gamma to the k times the initial distance. At most of the previous distance remains in the least-contracting sweep. Then it falls faster. Wherever you start, you end at the same V star.
There's a second classic algorithm, policy iteration, from Ronald Howard in 1960. Start with any policy: here, always go up. Evaluate it exactly, with the linear solve from chapter three. Then improve it: in every state, switch to the action that looks best by those values. The policy improvement theorem says the new policy is at least as good everywhere. The proof just unrolls the inequality one step at a time. Evaluate, improve, evaluate, improve: here it takes policies, and then the policy stops changing. It is optimal. Evaluation and improvement, chasing each other: Sutton and Barto call it generalized policy iteration. Almost every method in this part is a version of it, AlphaZero included.
Both algorithms need two things we usually don't have. The model: the transition probabilities, written down. And a sweep over every state. Our gridworld has forty-four states. Backgammon has about ten to the twenty. Chess, by Claude Shannon's estimate in 1950, about ten to the forty-three. Go has two times ten to the one hundred and seventy legal positions, more than the square of the number of atoms in the visible universe. The way forward is to learn from samples of experience, without the model, and to approximate the value function instead of tabulating it. That's the next three chapters.
5Temporal differencesUndergraduate5 min
Without a model, we learn values from experience: play episodes, and watch what happens. The simplest way is Monte Carlo: after an episode ends, nudge each state's value toward the return that actually followed it. Alpha is the step size. Average enough returns and you get the value. But you have to wait until the end, and a single return can be wildly noisy. Temporal-difference learning doesn't wait. After one step, it nudges the value toward the reward just received plus gamma times its own current estimate of the next state. The bracket is the TD error, delta: the difference between what you predicted a moment ago and what you predict now. Learning a guess from a guess sounds circular, but it converges, and Richard Sutton made it a theory in 1988. The idea goes back to Arthur Samuel's checkers program of 1959, which tuned its evaluation of a position toward its own evaluation a few moves later.
A small test, from Sutton and Barto: five states in a row. You start in the middle and step left or right at random. Leaving on the right pays one; on the left, nothing. The true value of each state is the chance of leaving on the right: one sixth up to five sixths. Start every estimate at one half and run TD. After one episode, only the state next to the exit it took has moved. After ten, the news has spread inward. After a hundred, the estimates sit near the truth.
Now compare the two methods properly: the error of the estimates, averaged over a hundred runs, for several step sizes. Monte Carlo, in orange, improves slowly. TD, in blue, learns faster at every step size we tried. The reason is the Markov property again. Monte Carlo treats each state's returns separately. TD's update for C uses the current estimate of D, which every past visit to D has improved, so experience is shared between states.
Monte Carlo and TD are the two ends of a spectrum. Use n real rewards, then a guess: that's the n-step return. Blend all of them, with weights falling off like lambda to the n: lambda zero is one-step TD, and the limit as lambda approaches one gives episodic Monte Carlo. The backward view keeps a fading trace of recently visited states, and spreads each TD error back over them: that's an eligibility trace. With fixed value estimates it matches the forward return; changing estimates online requires care for exact equivalence. On a longer walk, the error after ten episodes, at each lambda's best step size, is lowest in between: here at lambda . The best methods mix real rewards with their own guesses.
The first great success of these ideas came in 1992, from Gerald Tesauro at IBM. TD-Gammon was a neural network that looked at a backgammon board and estimated the chance of winning. It learned only from games against itself, nudging each position's value toward the next position's by TD lambda. After a million and a half games, it played close to the level of the world's best players, and some of its unusual opening moves were adopted by human experts. Self-play, a learned value, temporal differences: keep those three in mind.
And there's a postscript from neuroscience. In monkeys, dopamine neurons fire a burst when a reward arrives unexpectedly. Once a cue reliably predicts the reward, the burst moves to the cue, and the reward itself gets no response. And if the predicted reward doesn't come, firing dips below normal, exactly when it was due. In 1997 Schultz, Dayan and Montague pointed out that this is the TD error: surprise about future reward, positive or negative, moving back to the earliest thing that predicts it.
6Q-learningMaster's3 min
To act without a model, learn values of actions rather than states. With Q, acting is easy: pick the action with the highest Q, no transition probabilities needed. The TD idea carries over directly. After each step, nudge Q of s and a toward the reward plus gamma times the value of the next step. One version uses the action the agent really takes next: state, action, reward, state, action, so it's called Sarsa. Chris Watkins's version, in his 1989 thesis, uses the best action at the next state instead, whatever the agent actually does. That's Q-learning. It learns the value of acting optimally while behaving differently, exploring, and in a finite discounted MDP with bounded rewards, Watkins and Dayan proved it converges to Q star, provided every action keeps being tried and the step sizes shrink at the right rate.
Watch both learn on the cliff walk from Sutton and Barto. Start at S, reach G; every step costs one, and stepping off the cliff costs a hundred and sends you back to the start. Both explore, taking a random step one time in ten. Here is the opening of Q-learning's first episode: recorded positions, including falls. Now the training, replayed: the colours are the learned values, the line is the path each would take if it stopped exploring. Every value starts at zero, so at first everywhere looks equally good. The values grow back from the goal, and the paths straighten out. And they settle on different answers. Q-learning learns the optimal path, right along the edge. Sarsa learns the safe path, along the top: it values each action by what its own exploring self will do next, and one random step on the edge is a fall.
Which is better depends on what you score. Plot the reward each collects per episode while it is still exploring. Q-learning's optimal path runs along the edge, and every so often a random step tips it over: it averages . Sarsa's longer, safer path averages . Off-policy learning finds the best policy for a world without exploration; on-policy learning finds the best policy for the agent as it actually behaves.
A table of Q values can't hold Go, or even a video game screen, so the next step is to approximate Q with a function, a neural network. And here lies a trap. Function approximation, bootstrapping, and off-policy learning: together these can make the values diverge to infinity, even on tiny problems, as Leemon Baird showed in 1995. Sutton and Barto call it the deadly triad. Q-learning with a neural network has all three.
7Deep Q-networksEngineering5 min
In 2013 a small London company, DeepMind, showed a Q-learning agent playing Atari video games from the raw screen. The input is the last four frames, shrunk to 84 by 84 pixels. Three convolutional layers, the vision networks of Part 10, and then a layer that outputs one Q value for each joystick action, up to eighteen. The 2015 paper in Nature trained the same network, with the same settings, on forty-nine different games, from Pong to Breakout to Space Invaders. It reached the level of a professional human games tester overall, and over three quarters of the tester's score on twenty-nine of them. The only signal was the change in the game score.
DQN is Q-learning with the update turned into a loss: the squared TD error, minimized by gradient descent. Two tricks keep the deadly triad at bay. First, experience replay, an idea of Long-Ji Lin's from 1992. Every transition goes into a large memory, and each update trains on a random batch from it. Consecutive frames are almost identical, so training on them in order is like studying one page over and over. Random batches look independent, and each experience is used many times. Second, a target network: the target is computed by a frozen copy of the network, refreshed only every ten thousand steps, so the network isn't chasing a target that moves with every step it takes.
Here is DQN learning a classic control task on this machine: the cart-pole. Push the cart left or right to keep the pole upright; a reward of one each step, for episodes capped at five hundred. On the right, what the network has learned: for each pole angle and angular velocity, which push it prefers. Before training, these preferences come only from random initialization. Let's replay the training of the best of our runs, chosen by their average near the end of training. Every few thousand steps, freeze the network and let it balance. A useful push moves the cart back under the falling pole. The boundary depends on both the lean and angular speed. Nobody told it any physics.
Do the tricks matter? Train it three ways, runs each. The numbers here equally average the windowed episode lengths across the fixed grid of training steps. Without a replay memory, learning from each step as it comes: about . With replay but no target network: about . With both: about .
Compare the largest absolute Q predictions, on a log scale. With one point per step and discounting, no true value exceeds . With a target network, the final sampled magnitude is . Without one, the predictions ; the final sampled magnitude is . This is one run of each condition. A moving target can amplify approximation errors: the deadly triad is a risk, not a guarantee of divergence in every run.
There's a subtler flaw in the max. The Q values are noisy estimates, and the max picks whichever happens to be too high. By Jensen's inequality, the expected max of the estimates is at least the max of their means; for unbiased estimates, those are the true values. If ten actions are all truly worth zero and each estimate has noise of size one, the max averages . Q-learning keeps bootstrapping on that optimism. In Sutton and Barto's test, a branch with ten slightly losing actions looks attractive, and Q-learning goes down it far more often than it should. The fix, from Hado van Hasselt: let one set of estimates choose the action and another evaluate it. The errors no longer line up, and double Q-learning heads for the right choice almost at once. Double DQN applies it with the target network as the second set.
Atari became the proving ground for a decade. Double DQN, replay that samples surprising transitions more often, and networks that split value from advantage. Distributional RL, which learns the whole distribution of returns instead of only its average. Rainbow combined six of these ideas in 2018, and in 2020 Agent57 was the first to beat the human baseline on all fifty-seven games, including Montezuma's Revenge, where rewards are so rare that exploring is everything.
8Policy gradientsMaster's5 min
Value methods learn how good things are, and act greedily. Policy-gradient methods skip that and adjust the policy itself. Make it a network with parameters theta that outputs a probability for each action. The objective is the expected total reward of an episode, J of theta. Climb it by gradient ascent. This handles continuous actions, like a torque or a steering angle, where taking a max over actions is a problem in itself. It can learn policies that are deliberately random, which the best play in rock-paper-scissors, or poker, has to be. And behaviour changes smoothly with theta, instead of jumping whenever two Q values swap order.
The gradient of an expectation over episodes looks hopeless: the probabilities of episodes depend on theta, and on the environment's dynamics, which we don't know. Here use finite episodes with gamma one. The log-derivative trick from Part 5 rescues it: the gradient of p is p times the gradient of log p. So the gradient is itself an average over episodes, and an average can be estimated by sampling: play some episodes and average. Better still, the log-probability of an episode splits into the policy's choices and the environment's transitions, and the environment's part doesn't depend on theta. Its gradient is zero. We never need the model. One refinement: an action can't affect rewards that came before it, so each action is credited only with the return that followed it. This is REINFORCE, Ronald Williams's algorithm from 1992.
In plain terms: the policy tries actions. Each one is followed by some return. Nudge the log-probability of every action taken, up in proportion to its return. Actions followed by good outcomes become more likely, and since the probabilities sum to one, everything else gives way. It is trial and error, Thorndike's law of effect, written as a gradient.
The catch is variance. In the cart-pole, every return is positive, so every action gets pushed up, and the signal is the small difference between big numbers. The cure is to subtract a baseline, any function of the state, from the return. It costs nothing: averaged over the action, the baseline term is b times the gradient of the sum of the probabilities, and the sum of the probabilities is always one. Its gradient is zero. The estimate stays unbiased, and can get much less noisy.
Here is what that buys, measured. Take a half-trained cart-pole policy, play three hundred episodes, and compute the gradient each episode alone would give. Each dot is one estimate, projected onto the pooled sample-mean direction and one other. Without a baseline the estimates scatter widely; the orange arrow is their pooled empirical mean, not an exact gradient. With a baseline, the average return at each time step, they cluster: the variance is times smaller. Same expected gradient. The variance is measured in the full parameter space; the picture omits outlying dots for readability.
A standard baseline is the state's value, V. Then what multiplies the gradient estimates the advantage: how much better this action turned out than what you'd expect in this state anyway. We don't know V, so learn it with a second network, the critic, trained by TD. Its TD error is itself an estimate of the advantage. And just as TD lambda blends n-step returns, generalized advantage estimation blends n-step advantages, with lambda trading bias for variance. An actor that acts, and a critic that judges: actor-critic, an architecture that goes back to Barto, Sutton and Anderson's pole-balancer of 1983, the very task on screen in this chapter.
On the cart-pole, with the same policy architecture and nominal experience budget, runs each: plain REINFORCE, REINFORCE with a baseline, and actor-critic with generalized advantages. Equally averaging windowed episode lengths across the fixed training-step grid gives , and steps.
9Trust regions and PPOEngineering3 min
Policy gradients have a fragile point: the step size. The gradient is only a local guess about which way is up. Step too far, and the policy can land somewhere terrible. In supervised learning you'd recover on the next batch, but here the bad policy generates the next batch: it plays badly, sees only bad states, and may never find its way back. And the data was collected by the old policy. The further the new one moves, the less that data says about it. So: only trust steps inside a region where the new policy stays close to the old.
To reuse the old policy's data, weigh each sample by the ratio of the new policy's probability to the old one's. That gives a surrogate objective, estimated entirely from data already collected, whose gradient at the old parameters is exactly the policy gradient. TRPO, John Schulman's trust region method of 2015, maximizes it subject to a limit on the KL divergence between old and new policies. Solving that constraint leads to the natural gradient of Part 11: precise, but heavy, with second-order computations at every step.
In 2017 Schulman's team found a much simpler way to stay close, and it became the default: proximal policy optimization, PPO. Clip the ratio to a band, one minus epsilon to one plus epsilon, typically epsilon is 0.2, and take the smaller of the clipped and unclipped objectives. For a good action, raising its probability helps, but only until the ratio reaches 1.2; beyond that the objective goes flat, and so does the gradient. For a bad action, lowering it helps until 0.8, and no further. Taking the minimum keeps the pessimistic branch: a step that makes things worse is never clipped away. So you can run several epochs of gradient steps on the same batch. Clipping removes the incentive for a large change in that sample's term; it does not enforce a hard bound on the policy change, so step size and KL monitoring still matter.
Here is PPO learning the cart-pole, replayed from seed zero. The map starts with the random network's action probabilities, near one half with small differences. At each saved checkpoint, freeze the policy and sample one episode. Its length can rise or fall; more training does not guarantee a longer trial. The boundary between preferred pushes changes, and actions can stay mixed near it. These are action probabilities, not uncertainty bounds.
PPO went everywhere. OpenAI Five used it, at enormous scale, to beat the world champions at Dota 2 in 2019, after the equivalent of forty-five thousand years of self-play. For robots, soft actor-critic adds the policy's entropy to the reward, so it keeps exploring. And it is the RL in RLHF, the step that turned language models into ChatGPT, in Part 27. Its descendant GRPO, which drops the critic, trains today's reasoning models, in Part 28.
10Search before learningUndergraduate3 min
Games are where search was born. A game tree: from the current position, your possible moves, then the replies to each, and so on. Look a few moves ahead, and score the positions at the bottom with an evaluation function, a hand-made judgment of who's ahead. Then back the scores up. Where the opponent moves, assume the reply that's worst for you: the minimum. Where you move, take the best: the maximum. The root's value is what you can guarantee against any reply. That's minimax, from von Neumann's 1928 theorem on games, and the first programs, Shannon's design in 1950 and Samuel's checkers, played this way. But most of this tree never needed looking at. Once a reply shows a move is worse than one you already have, the move's other replies don't matter. Skipping them is alpha-beta pruning, and here it skips of the positions without changing the answer.
How much does it save? On Connect Four, searching nine moves deep: plain minimax examines about million positions. Alpha-beta, trying moves in random order, a fraction of that. Try the best-looking move first, and it examines . Knuth and Moore proved that with perfect ordering, the cost falls from b to the d to about b to the d over two: alpha-beta lets you search twice as deep for the same work.
This recipe beat the world chess champion. In 1997 IBM's Deep Blue defeated Garry Kasparov over six games. It ran alpha-beta on four hundred and eighty special-purpose chess chips, about two hundred million positions a second, with an evaluation function of some eight thousand features tuned by grandmasters and engineers. Search, plus a human-designed sense of what a good position looks like.
Go was different. A chess position offers about thirty-five moves; a Go position, about two hundred and fifty, and a game lasts about a hundred and fifty moves. The full game tree has something like ten to the three hundred and sixty positions. Worse, nobody could make hand-designed evaluation functions strong enough. Counting material works in chess; in Go, who is ahead depends on shape and influence that strong players feel rather than calculate. Nearly twenty years after Deep Blue, the best Go programs were still far below the best humans.
11Monte Carlo tree searchMaster's4 min
Go programs found a way around the missing evaluation function: don't evaluate, sample. To judge a position, finish the game from it many times, with both sides playing at random, and count who wins. A random game is a terrible game, but averaged over thousands, the share of wins is a rough measure of who stands better. Bernd Brügmann tried it on Go in 1993.
Random games from the root waste effort on bad moves. Monte Carlo tree search grows a tree instead, spending its simulations where they matter. Each simulation has four steps. Select: from the root, step down the tree, at each node choosing the child with the best score. The score is the upper confidence bound from chapter two: the win rate so far, plus a bonus for children tried rarely. Every node is a little bandit problem. Expand: when you reach the edge of the tree, add a child. Simulate: from there, play randomly to the end. Back up: add the result to every node on the path. Rémi Coulom named it Monte Carlo tree search in 2006, and Kocsis and Szepesvári proved the same year that this UCT rule converges to the minimax move as the simulations grow.
Here is plain MCTS thinking about a Connect Four position, its tree drawn with each branch as thick as the simulations through it. After simulations, every move has been tried once or twice. As the count grows, the tree grows lopsided: the search keeps returning to the moves that look best, and looks deeper there, while hopeless moves get only enough visits to stay hopeless. After simulations it likes column best.
The perfect solver says column : with perfect play; the move MCTS chose, column , . Our rollout policy takes an immediate win when it sees one and otherwise plays randomly. It can still miss longer tactical traps, so a move can look better under these playouts than under optimal replies. This finite-budget search inherits that limited evaluation.
We can measure this exactly. Connect Four is solved, so for selected tactical positions we know every move's true value. Call a move right if it keeps the best result the position allows: the win, or the draw. A random move is right percent of the time. Plain MCTS improves with more simulations, reaching percent at per move in this experiment. The positions were selected because legal moves have different solved outcomes. This is one seeded comparison on that cohort. These finite budgets do not establish a ceiling: UCT is asymptotically consistent, but can need far more search.
MCTS transformed computer Go. Crazy Stone and MoGo, from 2006, climbed from beginner to strong amateur. In 2013 Crazy Stone beat a professional, but with a four-stone head start. What was missing was a better judge: something that could look at a position and see who was winning, the way a strong player does. That is what a neural network would provide.
12AlphaGoUndergraduate3 min
This is the position from the opening of this part: Seoul, March 2016, the second game of five between DeepMind's AlphaGo and Lee Sedol, one of the strongest players of the previous decade. AlphaGo, playing black, placed its thirty-seventh stone here: a shoulder hit on the fifth line. Professional commentators thought it was a mistake; textbook play keeps such stones lower. AlphaGo's own network, trained on human games, put the chance that a human would play it at about one in ten thousand. It played it anyway, because its search said it was good, and it went on to win the game.
AlphaGo, described in Nature in January 2016, put deep networks inside Monte Carlo tree search. It had four parts. A policy network, a thirteen-layer convolutional net trained on thirty million positions from games between strong amateurs to predict the next move: it got the human move fifty-seven percent of the time, far beyond earlier programs. Then a second copy, improved by reinforcement learning, the policy gradient of chapter eight, playing against earlier versions of itself. It beat its supervised parent eighty percent of the time. A value network, the missing judge: it looks at a position and estimates who will win. It was trained on positions from the reinforced network's self-play games, only one position per game, so it couldn't simply memorize games. And a tiny, fast policy for quick playouts, as in classic MCTS.
The search is MCTS with two changes. When it selects a move, the exploration bonus is weighted by the policy network's prior, P: moves a strong player would consider get explored first, and the bonus fades as a move's visits pile up. It's the same optimism as UCB, steered by intuition. And when it reaches a leaf, it doesn't rely on random games alone: the leaf's value is half the value network's judgment and half the result of one fast rollout. The policy network narrows the search; the value network shortens it.
In October 2015 AlphaGo had beaten the European champion Fan Hui five games to nothing, the first time a program beat a professional on a full board without a head start. In Seoul it beat Lee Sedol four games to one. The one he won, game four, turned on his own move seventy-eight, a wedge that AlphaGo, by its own policy network, had also rated about one in ten thousand. Its search hadn't looked there, and it went astray. Search guided by a network inherits the network's blind spots: remember that for chapter fifteen.
13Learning from zeroEngineering5 min
Eighteen months after Seoul, DeepMind published AlphaGo Zero, and took almost everything away. No human games: it starts from random play. No hand-designed features: the input is just the stones. No random rollouts. And one network instead of separate policy and value networks. After three days and four point nine million games against itself, it beat the version that had beaten Lee Sedol, a hundred games to nothing. After forty days, it beat AlphaGo Master, the version that had won sixty straight online games against top professionals, eighty-nine to eleven. A stronger system, with less hand-designed knowledge.
The whole algorithm is one loop. A single network looks at a position and outputs two things: a probability for each move, p, and a value, v, its estimate of who will win. It plays games against itself, choosing every move by a Monte Carlo tree search guided by the network itself. Every position played is saved with two labels: pi, the search's visit counts, and z, who eventually won. Then the network is trained on them: the value head to predict the result, the policy head to predict what the search chose, plus weight decay. And the improved network plays the next games.
Why does this work? Search can look beyond the network's first guess, and its visit counts become a training target for the network's policy. So training the network to imitate the search aims to improve the policy, and training the value head on game results evaluates it. It is policy iteration from chapter four, with search doing the improvement and a neural network holding both the policy and its value. Each generation's network and search try to strengthen one another; improvement is not guaranteed at every step. In December 2017 the same learning and search recipe, with rule-specific encodings and exploration noise, learned chess and shogi too, and beat the strongest programs within hours. The 2017 paper reports eighty thousand chess positions a second against seventy million for Stockfish, roughly a thousand times fewer: the network focused the search.
Now we do it ourselves, at toy scale, on this computer. The game is Connect Four. The network is small, residual blocks; each move gets simulations of search; each generation plays games against itself and then trains on them. generations took about hours. And unlike Go, Connect Four is solved: a perfect player exists, so we can grade every move the network makes.
Here is the training, replayed through one position. Above each column, the network's probability for playing there, before any search. Below, the perfect solver's verdict: a tick for the moves that keep the best result. In generation zero the network is untrained: nearly flat bars, and a value of . Watch the generations go by. The probability moves around, as the network's understanding changes,
Graded on four hundred test positions, generation by generation. The network alone, with no search at all, goes from random to choosing a right move, one that keeps the win or the draw, percent of the time; with its simulations of search, percent. And in head-to-head games, rated like chess players, : the final generation is about Elo points above the untrained network,
Finally, watch it play out a position where only one move keeps the win, against itself, at different stages, every move checked by the solver: green for a right move, red for a mistake that gives away a win or a draw. Generation gets of its moves right. Generation , of .
Three ingredients made it work. Self-play, which always provides an opponent of exactly the right strength. Search, which turns a network into a slightly better teacher for itself. And a learned value function, the judge that Go programs had lacked for decades. It's TD-Gammon's recipe from 1992, plus search.
14Planning with a learned modelResearch2 min
AlphaZero searches by playing moves forward in its head, and for that it needs the rules: a perfect simulator that says what the board looks like after each move. Most problems have no rulebook. A robot, a video game seen as pixels, a cooling plant. So: learn a model of the world from experience, and search inside the model.
MuZero, from DeepMind in 2019, does exactly that with three learned functions. A representation function h turns the current observation into a hidden state. A dynamics function g takes a hidden state and an action, and predicts the reward and the next hidden state: an imagined step. And a prediction function f, AlphaZero's network, gives a policy and a value for any hidden state. The tree search runs entirely on hidden states. They are trained together: unroll the model five steps along real trajectories and make its predicted rewards, values and policies match the real rewards, the returns, and the search's choices. The crucial choice: the hidden state is never asked to reconstruct the screen or the board. It only has to predict what matters for planning. A model of the world that knows only what's useful.
MuZero matched AlphaZero at Go, chess and shogi without ever being given the rules, and set a new state of the art on the Atari games. EfficientZero made it frugal: its human-normalized score exceeds the human baseline in the median across twenty-six Atari 100k games, with about two hours of experience per game. Gumbel MuZero made search provably improve the policy with few simulations when action values are correctly evaluated. Learned approximations do not carry an unconditional guarantee. And a version went to work compressing YouTube videos, saving about four percent of the bits. Models that learn how the world works, and plan inside it, come back in Part 29.
15Beyond perfect informationResearch5 min
Chess and Go show both players everything. Poker doesn't. You know your own card, not your opponent's, so you can't search a tree of positions: you only know which set of positions you might be in, an information set. And the best play is necessarily random. If you always bet with good hands and never with bad ones, your bets give your cards away; you have to bluff, with the right probability. The target is a Nash equilibrium: a strategy for each player such that neither can gain by changing alone. In a two-player zero-sum game, playing it guarantees you the game's value, against anyone.
The tool is regret. After each round, ask of every action: how much better would I have done had I played it every time so far? Regret matching plays each action in proportion to its positive regret. Here two regret matchers play rock-paper-scissors against each other, the triangle being all mixtures of the three. Their current strategies chase each other round and round: whatever one favours, the other learns to beat. But the average of their strategies spirals in to a third, a third, a third: the equilibrium. That's a theorem: in two-player zero-sum games, if each player's regret grows slower than the number of rounds, the average strategies approach a Nash equilibrium.
For a card game, apply regret matching separately at every information set, every situation a player might be in, weighting each by how likely the opponent's play is to lead there. That's counterfactual regret minimization, CFR, from Martin Zinkevich and colleagues in 2007. Here it is on Kuhn poker, a toy with three cards. Exploitability, how much a perfect opponent could win against the average strategy, falls steadily, about like one over the square root of the iterations. And the value it settles on is : the known value of the game, minus one eighteenth. The first player is at a slight disadvantage, and the strategy it finds includes bluffing with the jack.
Scaled up with abstraction and real-time search, CFR conquered poker. Cepheus essentially solved two-player limit Texas hold'em in 2015. Libratus beat top professionals at no-limit hold'em in 2017, and Pluribus beat elite professionals in six-player games in 2019, after training that cost under a hundred and fifty dollars of computing.
In games with many strategies, plain self-play can go in circles, just like the current strategies in the triangle: each new version beats the last and forgets how to beat the one before. For StarCraft II, AlphaStar trained a whole league: main agents, exploiters whose only job is to find the main agents' weaknesses, and a pool of past selves everyone must keep beating. It reached Grandmaster, above ninety-nine point eight percent of ranked human players.
There's a sobering coda. In 2023, researchers trained a program, weak at Go in any normal sense, for one purpose: to beat KataGo, an open-source superhuman descendant of AlphaZero. It found a blind spot: a loop-shaped group of stones that the network misjudges. A human amateur learned the trick and beat a top program in fourteen games out of fifteen. Remember move seventy-eight. Superhuman on average is not the same as robust in the worst case, a lesson that returns in the last part of the series.
The AlphaZero recipe has also been turned on problems that aren't games at all, by making them into games. AlphaTensor treated finding a matrix multiplication algorithm as a one-player game, and found a way to multiply four by four matrices in forty-seven multiplications in binary arithmetic, beating the record of forty-nine that had stood since Strassen in 1969. AlphaDev played a game of writing assembly code, and found faster sorting routines for short lists that are now part of the standard C++ library used by LLVM. And the same tools, policy gradients, PPO, search and self-play, are how today's language models are taught to follow instructions and to reason.
Recap, problems, and where this comes backAll tracks2 min
Let's take stock. Learning to act starts with exploring, and the optimism of an upper confidence bound explores just enough. Bellman's equation ties each state's value to its neighbours', and because its operator is a contraction, iterating it always converges. Temporal differences learn values from experience by bootstrapping, and Q-learning learns to act; with replay and a target network, a deep network can do it too. Policy gradients improve the policy directly, and PPO's clip discourages overly large changes without guaranteeing safety. Search, guided by a learned policy and value, trained on its own games, gave us AlphaZero. And where information is hidden, minimizing regret finds the equilibrium.
All of this comes back. PPO, with a reward learned from human preferences, is how chat models are trained, in Part 27. Policy gradients on checkable answers, and search over chains of thought, make reasoning models, in Part 28. Learned world models and long horizons are the subject of Part 29. And what happens when an agent optimizes a flawed reward, or a superhuman system has a blind spot, comes back in the last part.
Here are six problems to try, from the confidence bound behind UCB to regret and equilibrium. Pause here, and work through them; full solutions are in this part's notes.
Next time: how a language model that only predicts text becomes an assistant. Supervised examples, a reward model learned from human preferences, and the PPO of this part, on a leash to the model it started from: post-training and alignment.
Sutton and Barto's book is the place to go deeper: everything in this part is in it, written for people learning it the first time. Thanks for watching, and see you in Part 27.
Where it goes next. PPO with a reward learned from human preferences trains chat models in Part 27; policy gradients on checkable answers and search over chains of thought make the reasoning models of Part 28; learned world models and long horizons are Part 29; an agent optimizing a flawed reward returns as reward hacking in Part 31.
Key results
The part's results in one place, for revision.
Try it
Lab 26 · Bellman's contraction, sweep by sweep
On the 44-state slippery gridworld of chapters 3 and 4, run value iteration from zeros and from random values, check that every sweep shrinks their distance by at least gamma, solve the greedy policy's linear system, and let Q-learning find nearly the same values from sampled moves alone.
python -m videos.ai.labs 26
needs numpy, scipy, matplotlib · download lab26.py ·
source on GitHubstates, discount 44, gamma = 0.95
largest ratio of successive gaps (two starts) 0.9500 (theorem: at most 0.95)
sweeps until within 1e-6 of V* 43 (bound from gamma^k: 270)
V* at the start cell 0.3774 linear solve for the greedy policy: 0.3774
Q-learning: largest error in max_a Q 0.020 after 4000 rounds (0.566 after 20)
value its greedy policy gives up 0.0058 at the start cell, at most 0.0975 in any state
Each sweep shrinks the distance between any two value tables by at least gamma, so value iteration converges from anywhere; Q-learning reaches nearly the same values from samples, without the model.
The code (127 lines; it asserts its own result)
"""Lab 26: run value iteration from two starts on the film's gridworld and watch the contraction; then learn Q from samples."""
import numpy as np
from videos.coursekit import labs
TITLE = "Bellman's contraction, sweep by sweep"
GOAL = ("On the 44-state slippery gridworld of chapters 3 and 4, run value iteration from zeros and from random values, "
"check that every sweep shrinks their distance by at least gamma, solve the greedy policy's linear system, and "
"let Q-learning find nearly the same values from sampled moves alone.")
TASKS = [
"Set gamma = 0.99. How many sweeps does value iteration now need, and how does that compare with log(tol)/log(gamma)?",
"Give every step a cost (step_reward = -0.04) and print the greedy path from S. Where does the policy change?",
"Replace Q-learning's max over next actions by the action actually taken (Sarsa) and compare the two learned paths.",
]
GRID = [".........",
"..#####..",
"......#.G",
".##...#.P",
"......#..",
"S........"] # the film's layout: a goal (+1), a pit (-1), walls
MOVES = [(-1, 0), (0, 1), (1, 0), (0, -1)] # up, right, down, left
def gridworld(slip=0.1, step_reward=0.0):
"""P[a, s, s'] and R[a, s]: a move goes where intended with probability 1 - 2 slip and to either side with slip."""
cells = [(r, c) for r in range(6) for c in range(9) if GRID[r][c] != "#"]
index = {rc: i for i, rc in enumerate(cells)}
n = len(cells)
P, R = np.zeros((4, n, n)), np.zeros((4, n))
terminal = np.array([GRID[r][c] in "GP" for r, c in cells])
for s, (r, c) in enumerate(cells):
for a in range(4):
if terminal[s]: # a terminal cell pays its reward once and ends
R[a, s] = 1.0 if GRID[r][c] == "G" else -1.0
continue
R[a, s] = step_reward
for b, p in ((a, 1 - 2 * slip), ((a + 1) % 4, slip), ((a + 3) % 4, slip)):
rr, cc = r + MOVES[b][0], c + MOVES[b][1]
ok = 0 <= rr < 6 and 0 <= cc < 9 and GRID[rr][cc] != "#"
P[a, s, index[(rr, cc)] if ok else s] += p
return cells, index, P, R, terminal
def run(seed=0):
rng = np.random.default_rng(seed)
gamma = 0.95
cells, index, P, R, terminal = gridworld()
n = len(cells)
T = lambda V: (R + gamma * P @ V).max(0) # the Bellman optimality operator
# value iteration from two starts
V, U = np.zeros(n), rng.uniform(-1, 1, n)
gap, err_trace = [np.abs(V - U).max()], []
for _ in range(400):
V, U = T(V), T(U)
gap.append(np.abs(V - U).max())
v_star = V
gap = np.array(gap)
ratios = gap[1:40] / gap[:39]
W = np.zeros(n)
for _ in range(120):
err_trace.append(np.abs(W - v_star).max())
W = T(W)
sweeps = int(np.argmax(np.array(err_trace) < 1e-6))
# the greedy policy, evaluated exactly: V = (I - gamma P_pi)^-1 r_pi
Q_star = R + gamma * P @ v_star
pi = Q_star.argmax(0)
P_pi, r_pi = P[pi, np.arange(n)], R[pi, np.arange(n)]
v_pi = np.linalg.solve(np.eye(n) - gamma * P_pi, r_pi)
# Q-learning: no model in the update, only one sampled next state per (state, action) in every round
Q, rounds = np.zeros((n, 4)), 4000
cum = P.cumsum(-1).transpose(1, 0, 2) # [s, a, s']
q_err = []
for k in range(1, rounds + 1):
q_err.append(np.abs(Q.max(1) - v_star).max())
s2 = np.minimum((rng.random((n, 4, 1)) > cum).sum(-1), n - 1)
target = R.T + gamma * Q.max(1)[s2] * ~terminal[:, None]
Q += (target - Q) / k ** 0.6
q_err.append(np.abs(Q.max(1) - v_star).max())
live = ~terminal
# how much value the learned greedy policy gives up, measured exactly
pi_q = Q.argmax(1)
v_q = np.linalg.solve(np.eye(n) - gamma * P[pi_q, np.arange(n)], R[pi_q, np.arange(n)])
loss, loss_start = (v_star - v_q)[live].max(), (v_star - v_q)[index[(5, 0)]]
lab = labs.Lab()
lab.row("states, discount", f"{n}, gamma = {gamma}")
lab.row("largest ratio of successive gaps (two starts)", f"{ratios.max():.4f} (theorem: at most {gamma})")
lab.row("sweeps until within 1e-6 of V*", f"{sweeps} (bound from gamma^k: {int(np.ceil(np.log(1e-6) / np.log(gamma)))})")
lab.row("V* at the start cell", f"{v_star[index[(5, 0)]]:.4f} linear solve for the greedy policy: {v_pi[index[(5, 0)]]:.4f}")
lab.row("Q-learning: largest error in max_a Q", f"{q_err[-1]:.3f} after {rounds} rounds ({q_err[20]:.3f} after 20)")
lab.row("value its greedy policy gives up", f"{abs(loss_start):.4f} at the start cell, at most {abs(loss):.4f} in any state")
lab.note = ("Each sweep shrinks the distance between any two value tables by at least gamma, so value iteration "
"converges from anywhere; Q-learning reaches nearly the same values from samples, without the model.")
assert n == 44, "the film's gridworld"
assert np.all(gap[1:] <= gamma * gap[:-1] + 1e-12), "the Bellman operator is a gamma-contraction in the max norm"
assert np.all(gap[1:60] <= gamma ** np.arange(1, 60) * gap[0] + 1e-12), "under the dashed line gamma^k"
assert np.abs(v_pi - v_star).max() < 1e-8, "V* is the value of its own greedy policy"
assert np.abs(T(v_star) - v_star).max() < 1e-9, "V* is the fixed point"
assert q_err[-1] < 0.06 and q_err[-1] < 0.2 * q_err[20], "Q-learning approaches V* from samples"
assert loss_start < 0.03 and loss <= 2 * q_err[-1] / (1 - gamma), "and its greedy policy is nearly optimal"
fig, ax = labs.figure(2, size=(11, 4.2))
k = np.arange(len(gap))
ax[0].semilogy(k[:100], np.maximum(gap[:100], 1e-16), color=labs.BLUE, label="distance between the two runs")
ax[0].semilogy(k[:100], gamma ** k[:100] * gap[0], color=labs.GOLD, ls="--", label=r"bound $\gamma^k\,\|V_0-U_0\|_\infty$")
ax[0].set(title="Value iteration from two starts", xlabel="sweep k", ylabel="largest difference (log scale)")
ax[0].legend()
g = np.full((6, 9), np.nan)
for i, (r, c) in enumerate(cells):
g[r, c] = v_star[i]
im = ax[1].imshow(g, cmap="RdYlGn", vmin=-1, vmax=1)
arrows = "↑→↓←"
for i, (r, c) in enumerate(cells):
mark = "G" if GRID[r][c] == "G" else "P" if GRID[r][c] == "P" else arrows[pi_q[i]]
ax[1].text(c, r, mark, ha="center", va="center", color="black", fontsize=11,
fontweight="bold" if mark in "GP" else "normal")
ax[1].set(title="V* (colour) and Q-learning's greedy moves (arrows)", xticks=[], yticks=[])
ax[1].grid(False)
fig.colorbar(im, ax=ax[1], shrink=0.8)
lab.fig = fig
return lab
Now change it
- Set gamma = 0.99. How many sweeps does value iteration now need, and how does that compare with log(tol)/log(gamma)?
- Give every step a cost (step_reward = -0.04) and print the greedy path from S. Where does the policy change?
- Replace Q-learning's max over next actions by the action actually taken (Sarsa) and compare the two learned paths.
Problems, with solutions
Try each problem before opening its solution.
1. The UCB bonus. For rewards in [0, 1], show that the true mean exceeds μ̂_a + √(2 ln t / n_a) with probability at most t^{-4}.
Solution
Hoeffding's inequality for the average of n independent rewards in [0, 1] gives P(μ_a − μ̂_a ≥ ε) ≤ exp(−2nε²). With ε = √(2 ln t / n), 2nε² = 4 ln t, so the bound is exp(−4 ln t) = t^{-4}.
2. A contraction. Show that the Bellman operator T^π of a fixed policy is a γ-contraction in the max norm, and that V^π is its only fixed point.
Solution
(T^π V)(s) = Σ_a π(a|s) Σ_{s'} P(s'|s,a)[r(s,a) + γV(s')]. The rewards cancel in a difference: |(T^π V)(s) − (T^π U)(s)| = γ |Σ_a π(a|s) Σ_{s'} P(s'|s,a)(V(s') − U(s'))| ≤ γ Σ_a π(a|s) Σ_{s'} P(s'|s,a) ‖V − U‖∞ = γ ‖V − U‖∞, since the weights are nonnegative and sum to one. If V and U are both fixed points, ‖V − U‖∞ = ‖T^π V − T^π U‖∞ ≤ γ ‖V − U‖∞ with γ < 1, so ‖V − U‖∞ = 0. V^π is a fixed point by the Bellman equation, so it is the only one (and Banach's theorem gives one exists, since ℝ^n is complete).
3. The random walk, exactly. Solve the Bellman equations of the five-state walk.
Solution
With no discount and rewards only at the exits, V(k) = ½ V(k−1) + ½ V(k+1) for k = 1, …, 5, with V(0) = 0 (leaving left pays nothing) and V(6) = 1 (leaving right pays one). Second differences vanish, so V is linear in k: V(k) = k/6, that is 1/6, 2/6, 3/6, 4/6, 5/6 for A to E.
4. Baselines. Show that a baseline b(s) leaves the policy gradient unbiased, and find the variance-minimizing constant baseline for (G − b) ∇log π.
Solution
E_{a∼π}[b(s) ∇log π(a|s)] = b(s) Σ_a π(a|s) ∇log π(a|s) = b(s) Σ_a ∇π(a|s) = b(s) ∇ Σ_a π(a|s) = b(s) ∇1 = 0. For a constant b and g = ∇log π, the mean doesn't depend on b, so minimize E[(G − b)² ‖g‖²]: its derivative in b is −2 E[(G − b)‖g‖²] = 0, so b* = E[G ‖g‖²] / E[‖g‖²], a return average weighted by the squared size of the score.
5. PPO's clip. For  > 0, show that the gradient of the clipped objective is zero once ρ > 1 + ε. What about  < 0?
Solution
The objective is min(ρÂ, clip(ρ, 1−ε, 1+ε)Â). For  > 0 and ρ > 1 + ε, the clipped term is (1+ε) < ρÂ, so the minimum is (1+ε)Â, a constant: zero gradient, no incentive to raise the probability further. For  < 0 and ρ < 1 − ε, the clipped term (1−ε) is smaller than ρÂ, so the minimum is the constant (1−ε)Â: no incentive to lower it further. But for  < 0 and ρ > 1 + ε, ρ < (1+ε)Â, the minimum is the unclipped ρ and its gradient pushes ρ back down: a step that made a bad action more likely is never clipped away.
6. No regret gives equilibrium. In a two-player zero-sum game, if both players' average regrets are at most ε, their average strategies form a 2ε-Nash equilibrium.
Solution
Let player 1 maximize xᵀAy, let x_t, y_t be the strategies played and x̄, ȳ their averages, and v̄ = (1/T) Σ_t x_tᵀ A y_t. Player 1's average regret: max_x xᵀAȳ − v̄ ≤ ε. Player 2's: v̄ − min_y x̄ᵀAy ≤ ε. So for every x, xᵀAȳ ≤ v̄ + ε ≤ min_y x̄ᵀAy + 2ε ≤ x̄ᵀAȳ + 2ε: player 1 gains at most 2ε by deviating; and for every y, x̄ᵀAy ≥ min_y x̄ᵀAy ≥ v̄ − ε ≥ max_x xᵀAȳ − 2ε ≥ x̄ᵀAȳ − 2ε: player 2 gains at most 2ε. That is a 2ε-equilibrium.
Notes and sources
About this partfrom its README
Part 26 of a thirty-one-part series on how modern AI works and how it came to be (see the series plan and the syllabus); the first part of Act V, Agency. How to learn to act when nobody gives the right action, only how it turned out: from Thorndike's law of effect and Bellman's equation, through temporal differences, Q-learning, DQN, policy gradients and PPO, to search, AlphaGo, AlphaZero, MuZero, and games of hidden information. Every learner here is trained on this computer, and its training is replayed on screen: the cliff walk's values and paths, DQN's and PPO's cart-pole policies, and our own AlphaZero for Connect Four, graded move by move against a perfect solver.
- The move nobody would play. AlphaGo against Lee Sedol, game 2, move 37, from the game record; AlphaGo Zero.
- 1. Learning from consequences. Thorndike (1911); the agent–environment loop; Markov decision processes (Bellman 1957); returns, discounting, the bound r_max / (1 − γ) and the recursion G_t = r_{t+1} + γ G_{t+1}; policies, V and Q; credit assignment, exploration, non-stationary data.
- 2. Explore or exploit. k-armed bandits (Thompson 1933); greedy against ε-greedy on the 10-armed testbed; regret = Σ Δ_a E[N_a]; UCB derived from Hoeffding; UCB1's O(log T) regret and the Lai–Robbins lower bound; UCB run live on five arms; Thompson sampling; regret on two coins over 50,000 pulls.
- 3. Bellman's equation. Derived from the recursion and the Markov property; backup diagrams; a slippery gridworld; the linear solve V = (I − γP_π)^{-1} r_π; the optimality equation and the greedy policy.
- 4. Why value iteration works. Value iteration sweep by sweep; the Bellman operator is a γ-contraction (proved); Banach's fixed-point theorem; two starts converging; policy iteration (Howard 1960) and the policy improvement theorem; generalized policy iteration; state counts from 44 to 2.08 × 10^170.
- 5. Temporal differences. Monte Carlo against TD(0) (Sutton 1988, Samuel 1959); the random walk replayed; RMS error over episodes; n-step returns, TD(λ) and eligibility traces; TD-Gammon (Tesauro 1992); dopamine and the TD error (Schultz, Dayan & Montague 1997).
- 6. Q-learning. Sarsa and Q-learning (Watkins 1989); convergence (Watkins & Dayan 1992); the cliff walk's training replayed for both; on- against off-policy; the deadly triad (Baird 1995).
- 7. Deep Q-networks. DQN on Atari (Mnih et al. 2013, 2015); replay and target networks; DQN's training on the cart-pole replayed (greedy action over angle × angular velocity, the pole balancing at each checkpoint); the ablation; overestimation (Jensen), double Q-learning; Rainbow, Agent57.
- 8. Policy gradients. The log-derivative trick and REINFORCE (Williams 1992), derived; baselines are unbiased (proved) and halve the variance here (measured); actor–critic, advantages, GAE; the curves.
- 9. Trust regions and PPO. Why step size matters; the importance-sampled surrogate; TRPO; PPO's clip, plotted; PPO's training replayed; OpenAI Five, soft actor-critic, RLHF, GRPO.
- 10. Search before learning. Minimax and alpha–beta on a tree; node counts on Connect Four (37.5 million for minimax at depth 9, 36,594 for well-ordered alpha–beta); Knuth & Moore; Deep Blue (1997); why Go resisted.
- 11. Monte Carlo tree search. Random playouts (Brügmann 1993); select, expand, simulate, back up; UCT (Kocsis & Szepesvári 2006); a real tree growing; the solver's verdict (plain MCTS picks a losing move here); MCTS strength against simulations; Crazy Stone and MoGo.
- 12. AlphaGo. Move 37; the four networks (Silver et al. 2016); search with priors and a value network; Fan Hui, Lee Sedol, move 78 of game 4.
- 13. Learning from zero. AlphaGo Zero and AlphaZero (2017–18); the self-play loop and its loss; MCTS as policy improvement; our own AlphaZero for Connect Four: its prior on one position across every generation, how often its move keeps the win or the draw, with and without search, Elo ratings, and games at successive generations.
- 14. Planning with a learned model. MuZero (2019–20): representation, dynamics, prediction, value equivalence; EfficientZero, Gumbel MuZero, video compression.
- 15. Beyond perfect information. Information sets and Nash equilibria; regret matching on rock-paper-scissors (current against average strategy); CFR on Kuhn poker (exploitability, the value −1/18); Cepheus, Libratus, Pluribus; AlphaStar's league; adversarial policies against KataGo; AlphaTensor and AlphaDev.
- Recap, where it comes back, the problem set, Part 27's teaser, references.
Run from the repo root:
Companion material in this repository
The syllabus's plan for this partfrom SYLLABUS.md, the plan of record
- The RL problem: MDPs, return, discount.
- Bandits: ε-greedy, UCB from Hoeffding, the regret lower bound, Thompson sampling.
- Bellman equations; the γ-contraction proof; value and policy iteration; the policy-improvement theorem.
- Monte Carlo vs TD(0); TD(λ) and eligibility traces; TD-Gammon (1992).
- SARSA and Q-learning; off-policy; the deadly triad.
- DQN: replay, target nets, Atari.
- Double DQN: the max-of-noisy-estimates bias proved; dueling, distributional (C51), Rainbow.
- Policy gradients: REINFORCE, baselines, actor–critic, GAE derived; TRPO, PPO's clip (Parts 27–28 build on it); maximum-entropy RL (SAC).
- Search, from Part 2's minimax and alpha–beta to MCTS and UCT; history from Samuel's checkers and TD-Gammon.
- AlphaGo (2016): SL policy, RL policy, value net, rollouts, PUCT; move 37 (prior ≈ 1/10,000, cited).
- AlphaGo Zero and AlphaZero: MCTS as a policy-improvement operator; the loss (z − v)² − πᵀlog p + c‖θ‖²; tabula rasa Go, chess, shogi.
- MuZero: learned representation, dynamics and prediction; value-equivalent models; EfficientZero; Gumbel MuZero.
- Imperfect information: regret matching and CFR (Libratus, Pluribus); AlphaStar's league; OpenAI Five.
- Adversarial policies that beat superhuman KataGo.
- Games for algorithms: AlphaTensor, AlphaDev.
- From games to language (Parts 27–28).
Computed:
- gridworld DP/TD;
- bandit regret;
- the double-Q bias;
- PPO on a classic control task;
- AlphaZero on Connect Four, trained on CPU and graded move by move against a perfect solver;
- Elo across self-play generations by round-robin.
Visuals: SearchTree growing with visit counts as branch weight; Board heatmaps; value diffusing across a
gridworld; Bellman contraction as shrinking balls.
中文讲义
本讲的中文部分(与英文版对应)。
习题与解答
1. UCB的加分。 奖励在[0, 1]之内时,证明真实均值超过 μ̂_a + √(2 ln t / n_a) 的概率至多为 t^{-4}。
解答
对n个取值在[0, 1]的独立奖励的平均值,霍夫丁不等式给出 P(μ_a − μ̂_a ≥ ε) ≤ exp(−2nε²)。取 ε = √(2 ln t / n),则 2nε² = 4 ln t,上界为 exp(−4 ln t) = t^{-4}。
2. 压缩映射。 证明固定策略的贝尔曼算子 T^π 在最大范数下是γ-压缩,并由此说明 V^π 是它唯一的不动点。
解答
两个值表之差中奖励相互抵消:|(T^π V)(s) − (T^π U)(s)| = γ|Σ_a π Σ_{s'} P (V − U)(s')| ≤ γ‖V − U‖∞,因为权重非负 且和为1。若V、U都是不动点,则 ‖V − U‖∞ ≤ γ‖V − U‖_∞,而γ < 1,所以两者相等。V^π满足贝尔曼方程,因而就是那个唯一的不动点。
3. 随机游走的精确解。 解出五状态随机游走的贝尔曼方程。
解答
不打折、只有出口有奖励时,V(k) = ½V(k−1) + ½V(k+1),k = 1,…,5,边界 V(0) = 0、V(6) = 1。二阶差分为零, 所以V关于k是线性的:V(k) = k/6,即A到E依次为1/6、2/6、3/6、4/6、5/6。
4. 基线。 证明基线b(s)不改变策略梯度的期望,并求使 (G − b)∇log π 方差最小的常数基线。
解答
E_{a∼π}[b ∇log π] = b Σ_a ∇π = b ∇Σ_a π = b ∇1 = 0。常数b不影响均值,只需最小化 E[(G − b)²‖g‖²](g = ∇log π): 对b求导令其为零,得 b* = E[G‖g‖²] / E[‖g‖²],即以得分函数长度平方加权的回报平均。
5. PPO的裁剪。 优势为正时,证明 ρ > 1 + ε 之后裁剪目标的梯度为零。优势为负时呢?
解答
目标为 min(ρÂ, clip(ρ, 1−ε, 1+ε)Â)。 > 0 且 ρ > 1+ε 时,裁剪项 (1+ε) 小于 ρÂ,最小值为常数,梯度为零。  < 0 且 ρ < 1−ε 时,最小值是常数 (1−ε)Â,同样不再推动。但  < 0 且 ρ > 1+ε 时,ρ 更小,取的是未裁剪项,梯度把ρ 往回拉:让坏动作变得更可能的那一步,永远不会被裁剪掉。
6. 无悔即均衡。 在二人零和博弈中,若双方的平均遗憾都不超过ε,则双方的平均策略构成2ε-纳什均衡。
解答
记玩家1最大化 xᵀAy,平均策略为 x̄、ȳ,平均收益 v̄ = (1/T)Σ x_tᵀAy_t。由玩家1的遗憾:max_x xᵀAȳ ≤ v̄ + ε; 由玩家2的遗憾:min_y x̄ᵀAy ≥ v̄ − ε。于是对任意x,xᵀAȳ ≤ v̄ + ε ≤ min_y x̄ᵀAy + 2ε ≤ x̄ᵀAȳ + 2ε;对任意y, x̄ᵀAy ≥ v̄ − ε ≥ max_x xᵀAȳ − 2ε ≥ x̄ᵀAȳ − 2ε。任何一方单独偏离至多获益2ε,即2ε-均衡。
Build the film
python -m videos.ai.ai26.compute # the part's numbers, into .cache/ai26
python tools/build.py ai26 # render and assemble the film
EXPLAINER_TTS=silent python tools/qa_scene.py ai26 Hook # one chapter, silent, with a contact sheet
Scenes: videos/ai/ai26. Setup: see the course page. Source of these notes: the README and the scenes' narration.