Part II · Deep RL · Chapter 10
The wider RL landscape
Model-based RL and AlphaZero/MuZero, offline RL, exploration, and where each idea resurfaces in LLMs.
In March 2016 a program called AlphaGo beat Lee Sedol, one of the strongest Go players in the world, four games to one. Nothing in Chapters 1–9 explains how. Q-learning, REINFORCE and PPO all learn from trial and error, one action at a time. AlphaGo also thought ahead: before every move it searched thousands of possible futures. Six years later, ChatGPT learned what “a good answer” means from people comparing pairs of answers, an idea that also isn’t in Chapters 1–9.
So far you have followed one road: learn values (Chapters 3–6), then learn policies (Chapters 7–9). This chapter is a map of the country around that road. It covers seven regions, briefly, and each one turns out to matter for language models. Two of them get full treatment because Part III depends on them: Monte Carlo tree search (the search inside AlphaGo, and the ancestor of test-time search for LLMs), and the KL-regularized optimum (the formula behind RLHF and DPO). For the rest you get the core idea, one concrete example, and a pointer to where it comes back.
A map of the territory
Everything in Chapters 3–9 shares four hidden assumptions:
- You learn by interacting. You can try actions and see what happens, as often as you like.
- The reward is given. Someone wrote down for you.
- You don’t use a model. The agent never asks “what would happen if…” before acting. (Chapter 4’s dynamic programming used a model, but there you had the exact one for free.)
- You are the only learner. The environment doesn’t adapt to you.
Each region of the landscape drops one of these assumptions, or changes the objective:
| Region | What changes | Shows up in LLMs as | Chapter |
|---|---|---|---|
| Model-based RL and planning | Use a model to look ahead | Test-time search, verifier-guided search | 17 |
| Imitation learning | Learn from demonstrations, no reward | Supervised fine-tuning (SFT), distillation | 11, 21 |
| Learning rewards (inverse RL, preferences) | Infer the reward instead of being given it | Reward models from human comparisons | 12 |
| Offline RL | No new interaction, just a fixed dataset | DPO; the KL leash | 13, 11 |
| Maximum-entropy / KL-regularized RL | Objective adds an entropy or KL term | The RLHF objective and its closed-form optimum | 11, 13 |
| Exploration | Reward the agent for seeing new things | Entropy collapse, the pass@k debate | 19, 15 |
| Multi-agent RL and self-play | Other learners in the environment | Self-play, debate, multi-agent setups | 18, 21 |
Keep this table in mind. The chapter walks down it row by row.
Model-based RL and planning
A model is anything that predicts what the environment will do: given and , it predicts and . With a model you can plan: try actions in your head before trying them in the world. Chapter 4’s value iteration was pure planning with a perfect model. Chapter 5’s Q-learning was pure learning with no model. Model-based RL sits in between: learn a model from experience, then use it.
Dyna: learn a model, then rehearse
The simplest version is Sutton’s Dyna (1990). Every real transition gets used twice: once for an ordinary Q-learning update, and once to update a model. The model is just a table that remembers what happened. Then, between real steps, the agent replays imaginary transitions sampled from that model, and does a Q-learning update on each.
Dyna-Q (tabular)
loop forever:
take action a in state s (ε-greedy on Q); observe r, s'
Q(s,a) += α [ r + γ max_a' Q(s',a') − Q(s,a) ] # learn from the real step
Model(s,a) ← (r, s') # remember what happened
repeat n times: # planning: rehearse
pick a previously seen (s̃, ã) at random
(r̃, s̃') ← Model(s̃, ã)
Q(s̃,ã) += α [ r̃ + γ max_a' Q(s̃',a') − Q(s̃,ã) ]
s ← s'
Why does this help? Think of a gridworld where the agent finally reaches the goal after a long random walk. Plain Q-learning updates only the last state’s value; the news travels back one step per episode. With Dyna, the planning updates replay old transitions next to the goal, so the value spreads backwards through many states before the next real step. Real experience is expensive and imaginary experience is cheap, so you squeeze more learning out of each real step. Sutton & Barto’s maze example (section 8.2) shows a large cut in the number of episodes needed once you add planning steps.
The catch is that the model is learned, so it is wrong in places, and a planner will find and exploit those mistakes. If the model wrongly believes a wall has a gap, the planner will happily route through it. This “the optimizer exploits the errors of whatever it is optimizing against” pattern is the single most important failure mode in this course. In Part III the thing being exploited is a learned reward model (Chapter 19).
Monte Carlo tree search
In a board game, the model is free: you know the rules exactly. The problem is size. Tic-tac-toe has only 5,478 legal positions, so you can solve it exactly with Chapter 4’s methods. Go has more than . You can’t compute a value for every state, so you compute values only for the states that matter right now: the ones reachable from the current position. That is planning at decision time, and the best general method for it is Monte Carlo tree search (MCTS).
Here is the idea in one sentence: grow a search tree from the current position, one path at a time, spending more effort on the moves that look promising, and estimate how good a position is by playing random games from it.
Each node of the tree is a position. It stores two numbers:
- : how many simulations have passed through it (its visit count),
- : the total result of those simulations, counted from the point of view of the player who made the move into this node. A win counts , a loss , a draw .
So is the average result of that move for the player who chose it.
One simulation has four phases:
- Selection. Start at the root. While every legal move from the current node already has a child node (the node is fully expanded), step to the child with the highest score (below). Stop at a node that still has an untried move, or at the end of the game.
- Expansion. Add one new child for one untried move.
- Rollout. From the new node, play random moves until the game ends. Call the result : if X wins, if O wins, for a draw.
- Backup. Walk back up the path. Every node gets , and moves by or , depending on whose move led into that node.
After a few hundred simulations, you play the root move with the largest visit count. (Why not the largest ? A move with 3 lucky visits can have the best average. A move that selection kept choosing hundreds of times is one the search trusts.)
Selection is a bandit problem (UCT)
How should selection pick a child? At each node you face exactly Chapter 2’s dilemma. Each child is an arm. Pulling it means running a simulation through it. You want to pull the best arm often (exploit), but you are not sure which arm is best (explore). Kocsis and Szepesvári (2006) had the idea of using UCB1 at every node. The result is called UCT (Upper Confidence bounds applied to Trees):
This is the UCB formula from Chapter 2 almost word for word. plays the role of the total number of pulls , and plays the role of . A child that has never been visited gets an infinite score, so every move is tried once before any is tried twice.
A worked example. Suppose the root has been visited times, it has three children, and :
| Child | bonus | UCT | |||
|---|---|---|---|---|---|
| A | 10 | 6 | 0.600 | 0.766 | 1.366 |
| B | 6 | 2 | 0.333 | 0.989 | 1.323 |
| C | 4 | 1 | 0.250 | 1.212 | 1.462 |
(.) Child C has the worst average so far but is selected next, because with only 4 visits its average is the least trustworthy. With the bonuses shrink to 0.274, 0.353 and 0.433, and A wins with 0.874. The constant sets the exchange rate between “looks good” and “barely tried”. Since our results live in (a range of 2, versus UCB1’s ), values of around 1 to 2 work well.
Here is the whole algorithm:
MCTS(root position, n simulations, c):
for i in 1..n:
node ← root; path ← [root]
# 1. selection
while node is not terminal and node has no untried moves:
node ← child of node maximizing W/N + c·sqrt(ln N_node / N_child)
path.append(node)
# 2. expansion
if node is not terminal:
m ← pop a random untried move of node
node ← new child of node for move m; path.append(node)
# 3. rollout
z ← result of random play from node (+1 X wins, −1 O wins, 0 draw)
# 4. backup
for v in path:
v.N += 1
v.W += z × (+1 if X moved into v else −1)
return the root move with the largest N
Quick check The root has three children with (N, W) = (10, 6), (6, 2), (4, 1), and N_parent = 20. With a very large c, say c = 100, which child does UCT select?
With a huge c the exploration bonus dominates, and the bonus is largest for the least-visited child: sqrt(ln 20 / 4) beats sqrt(ln 20 / 6) and sqrt(ln 20 / 10). Very large c spreads visits almost evenly, so the search stops focusing.
See it run
The demo runs exactly the pseudocode above on tic-tac-toe. Step through single simulations phase by phase, then add simulations in bulk and watch the tree grow. The table shows each root move’s , , exploration bonus and UCT score, so you can check every number against the formula.
| move | N | Q | bonus | UCT | perfect play |
|---|
What to try: (1) On the empty board, press Step about 40 times (10 full simulations). The first 9 simulations each expand a different root move (unvisited means UCT = ∞), and only then does selection go deeper. (2) Press +100 a few times: the centre (5) usually collects the most visits, with the corners next. (3) Switch to 'Block or lose', set c = 0 and press +100 several times. Pure exploitation can lock onto the first move that got lucky, exactly like greedy in Chapter 2. Press Reset search a few times with different seeds and compare with c = 1.4. (4) 'Fork trap' needs a few hundred simulations before MCTS reliably picks an edge. Tick 'Reveal perfect-play values' to check. (5) Play a game against it with a budget of 5, then 500.
The fork trap deserves a closer look, because it shows what the tree adds. The position is X . . / . O . / . . X with O to move (cells numbered 1–9 row by row, as in the demo).
- Perfect play. The free corners (3 and 7) lose. Say O plays 3. That threatens 3-5-7, so X must block at 7. But X’s block also makes two threats at once (1-4-7 and 7-8-9), a fork, and O can only stop one. The edges (2, 4, 6, 8) draw.
- Random play. Now average over random continuations instead. If both players move uniformly at random after O’s move, O’s expected result is exactly after a corner and exactly after an edge. (You can enumerate every random game to check.) A random X rarely finds the fork, so the corners look better.
Flat Monte Carlo (rollouts from each move, no tree) estimates exactly those random-play values. So it picks a corner, and with more rollouts the noise shrinks around the wrong answer: it gets more confidently wrong. MCTS gets it right. The tree grows below O’s corner move, discovers X’s blocking-and-forking reply, and from then on selection plays that reply in every simulation through that branch. The node’s value becomes “what happens if both players play the tree’s moves”, not “what happens under random play”. The lab’s run.py plots this: MCTS’s accuracy climbs to 100% while flat Monte Carlo’s falls.
AlphaGo → AlphaZero → MuZero
Random rollouts are fine for tic-tac-toe and hopeless for Go: a random game of Go says almost nothing about who is ahead. DeepMind’s systems replaced the two weakest parts of MCTS with neural networks.
AlphaGo (Silver et al., 2016) trained a policy network , first by supervised learning on expert human games and then by policy-gradient RL through self-play. It also trained a value network to predict the winner from a position. Inside MCTS, the policy network’s probabilities guided which moves to explore, and leaf positions were evaluated by mixing the value network with a fast rollout.
AlphaGo Zero (2017) and AlphaZero (Silver et al., 2017/2018, the same algorithm applied to chess, shogi and Go) removed the human data and the rollouts. A single network outputs both and . Selection uses the PUCT rule, UCT with a prior:
Here is the average value of the child, as before, and is its visit count. The network’s prior tells the search where to look first: a move the network likes gets a large bonus until it has been visited a few times. The leaf value comes from instead of a random game.
Training is a loop of self-play games. At every move, MCTS runs and produces visit counts , which define a search policy . Here is a temperature (not a trajectory, its meaning elsewhere in this course): copies the visit proportions, and puts all the probability on the most-visited move. When the game ends, let or be the result from the point of view of the player to move in . The network is trained on each position to minimize:
Read the second term carefully: it is a cross-entropy loss that makes the raw network imitate the search. Search with a network is stronger than the network alone. Training the network on the search’s output makes the network stronger, which makes the next search stronger, and so on. This is policy iteration again, with MCTS as the improvement operator, and it is often called expert iteration (Anthony, Tian & Barber 2017): the search is the expert, the network is the apprentice.
MuZero (Schrittwieser et al., 2019/2020) removed the last piece of given knowledge: the rules. It learns a model, but not a model that predicts the next board image. It learns a hidden state and a dynamics function that maps to the next hidden state and the reward, trained only so that its predicted rewards, values and policies match reality. MCTS then runs inside this learned latent space. MuZero matched AlphaZero at Go, chess and shogi without being told the rules, and set a new state of the art on Atari.
Imitation learning: copying an expert
Sometimes writing down a reward is harder than showing what you want. You can’t easily write a reward for “drive like a careful human”, but you can record careful humans driving. Imitation learning learns a policy from demonstrations: a dataset of states and the actions an expert took in them.
The simplest method is behavior cloning (BC): treat it as supervised learning. Fit to the expert’s state–action pairs by maximum likelihood:
This works surprisingly often. It also fails in a characteristic way.
Why errors compound
Picture a self-driving car trained by behavior cloning on a human who always stays in the middle of the lane. The training data contains only centered states. At test time the car makes a small mistake and drifts toward the edge. Now it is in a state the expert never visited, so the training data has no example of how to recover. It makes another mistake, drifts further, and the states get stranger. This is covariate shift: the learner’s own mistakes change the distribution of states it sees, away from the training distribution.
Here is the arithmetic. Suppose the cloned policy disagrees with the expert with probability on any state from the expert’s distribution, and that one disagreement can knock it off course for the rest of an episode of length . The chance that it has gone off course by step is at most . So the expected number of steps spent off course is at most
With and , that is up to about 50 bad steps, not the you might naively expect from a 1% error rate. Ross & Bagnell (2010) made this precise: behavior cloning’s cost can grow like . That’s the compounding-error problem. Exercise 10.4 walks through the argument.
DAgger (Dataset Aggregation; Ross, Gordon & Bagnell 2011) fixes the root cause. Run the learner’s policy, record the states it actually visits, ask the expert what it would have done in each of them, add those labels to the dataset, retrain, and repeat. Now the training distribution matches the states the learner visits, including its mistakes, and the error grows only linearly in . The price: you need an expert you can query on demand.
Quick check Why does training on more expert demonstrations not, by itself, fix compounding errors in behavior cloning?
More expert data lowers ε on the expert's state distribution, but the learner's mistakes take it to states outside that distribution, where there are still no labels. DAgger fixes this by labelling the learner's own states.
Learning the reward
Imitation copies actions. A different idea is to recover the goal and then optimize it with RL. If you know what the expert was trying to do, you can sometimes do it better than they did, or do it in situations they never saw.
Inverse reinforcement learning (IRL; Ng & Russell 2000) asks: given expert behavior, which reward function makes it optimal? The problem is badly underdetermined. The reward makes every policy optimal, and many different rewards explain the same behavior. Practical IRL methods add assumptions to pick one. A famous one, maximum-entropy IRL (Ziebart et al. 2008), assumes the expert picks trajectories with probability . That is a Boltzmann distribution, and you will meet it again shortly.
A more practical way to learn a reward is to ask people to compare. Christiano et al. (2017), “Deep reinforcement learning from human preferences”, showed a human two short video clips of an agent’s behavior and asked which one was better. A reward model was trained to predict those choices, and an RL agent maximized while more comparisons were collected. Comparisons are much easier for people than writing a reward function or giving a numeric score. The paper reports learning Atari games and simulated robot tasks with human feedback on less than 1% of the agent’s interactions, and teaching a simulated robot novel behaviors such as a backflip from about an hour of human time.
The model of human choice they used is the Bradley–Terry model: the probability that a person prefers clip 1 over clip 2 is
with the logistic sigmoid. Chapter 12 derives this model and trains reward models with it. That paper’s pipeline (collect comparisons → fit a reward model → run RL against it) is the RLHF pipeline. InstructGPT and ChatGPT ran it on language models five years later.
Offline RL: learning from a fixed dataset
Everything since Chapter 5 assumed you can keep collecting data. In many settings you can’t. A hospital has records of past treatments and outcomes, and nobody will let you experiment on patients to fill in the gaps. Offline RL (also called batch RL) learns a policy from a fixed dataset of transitions collected by some other behavior policy , with no further interaction.
Q-learning is off-policy (Chapter 5), so you might think you can just run it on . This fails, and the reason is worth understanding.
A worked example. One state, three actions. The dataset has 4 tries of (rewards 1, 1, 0, 1), 2 tries of (rewards 0.5, 0.5), and no tries of . A table gives , , and stays at its initial value. With a neural network, is whatever the network extrapolates, say 1.3. The greedy policy picks , the one action you know nothing about. In an online setting this would be harmless: you would try , see its real reward, and correct the estimate. Offline, you never find out.
In a sequential problem it gets worse. The Q-learning target takes a max over actions, and the max preferentially picks exactly the actions whose values are overestimated, which are often the actions the data never covers. Those errors then get bootstrapped into earlier states. This is the distribution shift problem of offline RL: the learned policy wants to go where the data isn’t, and that’s where its value estimates are least reliable. It is Chapter 5’s maximization bias and Chapter 6’s deadly triad, with no way to collect the data that would correct them.
The fix is pessimism: in the face of uncertainty, assume the worst. Online, Chapter 2’s UCB was optimistic: a bonus for being uncertain, because trying the arm will resolve the uncertainty. Offline nothing gets resolved, so you flip the sign. Use a lower confidence bound, , where is how often appears in the data. With the example gives for , for , and for the untried . Pessimism picks .
Deep offline RL methods implement this idea in two main ways:
- Conservative value estimates. Conservative Q-learning (CQL; Kumar et al. 2020) adds a term to the usual TD loss that pushes down on actions the current policy likes and up on actions that appear in the data, so out-of-distribution actions can’t look attractive.
- Stay close to the data. Constrain the learned policy to stay near the behavior policy , for example with a penalty . Then it rarely picks the actions whose values are pure extrapolation.
Quick check Online, UCB adds an exploration bonus to uncertain actions. Why do offline RL methods do the opposite?
Optimism works online because acting on an overestimate is self-correcting: you try it and learn the truth. Offline, an overestimated action just gets chosen, and you never find out. Being pessimistic about unfamiliar actions is the safe default.
Maximum-entropy and KL-regularized RL
This section is the one Part III leans on most, so we take it slowly. Here is the question.
You have a reference policy (think: a language model after SFT) and a reward . You want a new policy with high reward, but you don’t want to stray far from . What is the best possible policy?
To keep things concrete, start with a single decision (one state: a bandit, as in Chapter 2), so a policy is just a probability distribution over a finite set of actions. We measure “straying” with the KL divergence and trade it off against reward with a coefficient :
Call this the KL-regularized objective. Large means “stay very close to ”. Small means “mostly chase reward”.
The answer: tilt the reference by
The maximizer has a closed form:
and the best achievable value is .
In words: start from the reference and multiply each action’s probability by , then renormalize. Actions with high reward get boosted exponentially. sets how strongly. An action the reference never takes () stays impossible, whatever its reward.
A worked example. Three actions with , rewards and .
- Unnormalized weights : , , .
- .
- .
- Expected reward .
- .
- , and . They agree.
Compare with two obvious alternatives. Copying the reference gives (expected reward , zero KL). Going greedy, always action 3, gives reward 2 but pays , so . The tilted policy beats both.
Why it’s the maximum
There is a slick proof that also tells you how much worse any other policy is. Take the definition of and solve it for the reward:
Substitute this into for an arbitrary policy :
In the second line we used , and the ‘s cancel in the third. So:
That KL is non-negative (Gibbs’ inequality) follows from Jensen’s inequality: , with equality only if is constant, that is .
∂ The same result with a Lagrange multiplier (the route you'd try first)
Maximize subject to . (The constraint will turn out to hold automatically.) Form the Lagrangian
Differentiate with respect to one component , for an action with . Use :
Solve for :
The last factor is the same for every , so it is a normalizing constant. The constraint fixes it to with . This gives , which is positive wherever is, so the non-negativity constraint never binds. Actions with must get , otherwise the KL is infinite.
Is this stationary point a maximum? is concave: the expected reward is linear in , and is concave because is convex (second derivative ). A stationary point of a concave function on a convex set is the global maximum.
Finally, the value. Plug into the KL:
so .
Three ways to read the formula
1. It’s a Boltzmann distribution, and is a free energy. Write the energy of action as and the temperature as . If is uniform, then , with the entropy and the number of actions, and maximizing is the same as minimizing
the Helmholtz free energy . Its minimizer is the Boltzmann distribution , with , minus times the log of the physicist’s partition function. (That sum is times our , because our includes the weights . The difference, , is the constant that separates from .) That’s the Gibbs variational principle of statistical mechanics, and the identity in the Key callout is its standard proof. A non-uniform acts like a density of states, a prior weight on each action before the energy is taken into account.
2. is a temperature knob. As , and : the leash is so tight you just copy the reference. As , the action with the largest reward dominates and becomes greedy (among actions allows). In between you get a smooth compromise. With uniform , , and is a “soft max” of the rewards that tends to as .
3. Reward and policy determine each other. The rearranged form says that, up to a constant, the reward is the log-ratio of the optimal policy to the reference. If you know and , you know the reward. Chapter 13 builds DPO on exactly this observation.
reference π₀ optimum π* best random challenger (after you press the button)
What to try: (1) With the worked example at β = 1, check the readouts against the numbers in the text (π* = 0.18, 0.29, 0.53; J = β log Z = 1.027). (2) Drag β to the far right: π* collapses onto π₀ and the KL goes to 0. Drag it to the far left: π* puts all its mass on the best action and J approaches J(greedy). (3) Press 'Try 2,000 random policies' a few times: the best challenger can get very close (J is flat near its maximum) but never beats π*, and the last two rows always agree, J(challenger) = β log Z − β·KL(challenger ‖ π*), which is the Gibbs identity. (4) In the six-action scenario, note how action F (highest reward, only 3% under the reference) needs a small β before it dominates. The reference's prior matters as much as the reward.
Quick check Under π* ∝ π₀·exp(r/β), what happens to an action that has the highest reward but probability zero under the reference π₀?
π*(a) is π₀(a) times a finite factor, so π₀(a) = 0 gives π*(a) = 0. Any policy that put mass there would have infinite KL from π₀. For language models, this means the KL-regularized optimum can only reweight responses the reference model already gives probability to. Responses the reference makes vanishingly unlikely stay vanishingly unlikely unless their reward is enormous.
Sequential decisions: soft values and SAC
The same idea extends to whole MDPs. Add to the reward at every step (or with a uniform ; this is maximum-entropy RL). The Bellman equations of Chapter 4 keep their shape, but the hard becomes the soft max you just met:
and the optimal policy at each state is again the tilted reference, . Each state solves the one-step problem above, with in place of . For a finite horizon, the proof applies the one-step result backwards in time, from the last step to the first. For an infinite discounted horizon, the soft Bellman operator is a -contraction, just like the ordinary one in Chapter 4, so it has a unique fixed point.
Why add entropy at all, in classic RL? Stochastic policies keep exploring, they don’t put all their eggs in one basket when two actions are nearly equally good, and the soft max makes optimization smoother. The best-known algorithm here is Soft Actor-Critic (SAC; Haarnoja et al. 2018), an off-policy actor-critic for continuous control. It learns a soft Q-function and a Gaussian policy that maximizes reward plus times entropy, and it is one of the strongest baselines for robot control.
Exploration beyond ε-greedy
Chapter 2’s bandits had a few arms. Optimism (UCB) and posterior sampling (Thompson) handled exploration well. In a large MDP, the problem changes character: rewards can be so rare that random behavior never sees one. The standard example is the Atari game Montezuma’s Revenge, where the first reward requires a long, precise sequence of jumps and ladders. DQN, which explored with ε-greedy, scored essentially zero there (Mnih et al. 2015).
The fix is to give the agent an intrinsic reward for novelty, added to the environment’s reward: , with a weight. Three families:
- Count-based. , where counts visits to . This is UCB’s bonus spread over states. In big state spaces you never see the same state twice, so methods estimate pseudo-counts from a density model of states (Bellemare et al. 2016).
- Curiosity / prediction error. Train a model to predict the next state (in a learned feature space), and reward the agent where the model is wrong, because that’s where something new is happening (Pathak et al. 2017).
- Random Network Distillation (RND; Burda et al. 2018). Train a network to match the outputs of a fixed, randomly initialized network on visited states. Its error is low on familiar states and high on new ones, so the error is a novelty signal. RND made large progress on Montezuma’s Revenge.
Prediction-error bonuses have a known failure, the noisy-TV problem. A source of pure randomness (a TV showing static) stays unpredictable forever, so a curious agent can stare at it forever. That’s reward hacking of the exploration bonus, the same pattern as the planner exploiting a wrong model.
Multi-agent RL and self-play
When several agents learn in the same environment, each one’s environment includes the others, and they keep changing. From any single agent’s point of view, the environment is non-stationary, which breaks the convergence guarantees from Chapters 4–5. Settings range from fully cooperative (a team sharing one reward) to fully competitive (two-player zero-sum games, where one’s gain is the other’s loss), with general-sum games in between.
The competitive two-player case has the cleanest success story: self-play, where the agent trains against copies of itself. TD-Gammon (Tesauro, early 1990s) learned backgammon this way, and AlphaZero learned Go, chess and shogi this way. Self-play gives you an automatic curriculum: your opponent is always exactly as strong as you are. It can also cycle. In rock-paper-scissors-like games, a policy that beats the current version may lose to an older one. Systems like DeepMind’s AlphaStar (StarCraft II) therefore trained against a league of past and present agents rather than just the latest copy.
Back to the map
Here is the table from the start of the chapter, now with the link you should remember from each row:
| Idea from this chapter | Its LLM descendant | Where |
|---|---|---|
| MCTS: search guided by value estimates | Best-of-N, verifier-guided beam and tree search, long chain of thought | Ch 17 |
| AlphaZero: train the policy to imitate the search | Rejection sampling + SFT, expert iteration | Ch 15 |
| Behavior cloning; compounding errors | SFT; exposure bias | Ch 11 |
| DAgger: label the learner’s own states | On-policy distillation | Ch 21 |
| Rewards from preference comparisons | Bradley–Terry reward models, RLHF | Ch 12 |
| Offline RL; pessimism; stay near the data | DPO is offline; the KL leash; overoptimization | Ch 13, Ch 19 |
| , the Gibbs variational principle | The RLHF optimum; DPO’s derivation | Ch 11, Ch 13 |
| Intrinsic exploration; entropy | Entropy collapse; pass@k | Ch 19, Ch 15 |
| Self-play | Self-play and self-generated problems | Ch 21 |
Summary
- Planning uses a model to look ahead. Dyna rehearses imagined transitions from a learned model. Planners exploit model errors, a pattern that returns as reward hacking.
- MCTS grows a tree one simulation at a time: select (UCT, which is UCB1 at every node), expand, roll out, back up. Store each node’s value from the point of view of the player who moved into it. The tree is what makes it better than flat Monte Carlo.
- AlphaZero replaces rollouts with a value network and guides search with a policy prior (PUCT), then trains the network to imitate the search’s visit counts: policy iteration with search as the improvement step. MuZero also learns the model.
- Behavior cloning is supervised learning on demonstrations. Its errors compound (up to about ) because the learner drifts into states the expert never showed. DAgger labels the learner’s own states. SFT is behavior cloning.
- Learning rewards from comparisons (Christiano et al. 2017) is the template for RLHF’s reward models.
- Offline RL must avoid actions the data doesn’t cover. It is pessimistic where online methods are optimistic. DPO is offline, and the KL leash keeps RLHF near the data.
- The KL-regularized optimum: is solved by , with value . For any , . This is the Gibbs variational principle (minimize free energy) and the foundation of Chapters 11 and 13.
- Exploration bonuses (counts, curiosity, RND) help with sparse rewards. Self-play gives an automatic curriculum in competitive games.
Exercises
For each scenario, say which region(s) of this chapter’s map it belongs to, and why.
- A recommender system must be improved using only last year’s logs of what was shown and what users clicked. No A/B tests are allowed.
- A robot arm is trained to fold towels from 200 recorded human demonstrations.
- A Go program spends 30 seconds per move searching ahead before playing.
- Annotators see two chatbot answers and click the better one; a model is trained to predict their clicks.
- A poker bot is trained by playing millions of hands against earlier versions of itself.
- A game agent receives an extra reward the first few times it enters a room.
Solution
- Offline RL. A fixed dataset collected by a different behavior policy (last year’s recommender), no new interaction. The danger is recommending items the old system never showed, whose value estimates are pure extrapolation; pessimism is the standard remedy.
- Imitation learning (behavior cloning, or DAgger if a human can correct the robot during its own attempts). Expect compounding errors when the towel ends up in a configuration no demonstration covered.
- Model-based planning at decision time (MCTS). The rules are a perfect model; the search spends compute per decision.
- Learning the reward from preferences (Christiano et al. 2017; reward models in Chapter 12).
- Multi-agent RL / self-play. Training against a pool of earlier versions (not just the latest) protects against cycling.
- Exploration with a count-based intrinsic reward.
A root node has been visited 30 times. It has three children with equal to , and . Results are in , stored from the chooser’s point of view.
(a) Compute the UCT score of each child with . Which is selected?
(b) Find the smallest (to two decimals) at which the third child would be selected over the first.
(c) UCT applies UCB1 at every node, but the bandit at an interior node is not the bandit of Chapter 2. Name two ways it differs.
Hint
Solution
(a) .
- Child 1: , bonus , UCT .
- Child 2: , bonus , UCT .
- Child 3: , bonus , UCT .
Child 1 is selected (1.076). Child 3 comes second, ahead of child 2, despite the lowest average.
(b) Child 3 beats child 1 when , that is , so (more precisely ).
(c) Any two of:
- Non-stationary arms. A child’s average is computed from simulations whose in-tree moves keep changing as the subtree below it learns. Early simulations were played badly and later ones well, so the “arm’s mean” drifts over time (usually toward the minimax value). UCB1’s guarantee assumes fixed means.
- Alternating objectives. Each level maximizes for a different player; the backup flips signs.
- Reward range. Results are in , not , so the right scale for changes (the range doubles).
- The goal is different. A bandit cares about cumulative regret; MCTS only cares that the final recommendation (the most-visited root move) is right, which is a “best-arm identification” problem. That’s one reason practitioners tune instead of using the theoretical value.
Use the MCTS demo.
(a) Choose “Block or lose (O to move)”. Set and press +100 three times. Note the move with the most visits. Press “Reset search” (it changes the random seed) and repeat four or five times. How often does MCTS find the only good move, 9? Now do the same with . Explain what you see using Chapter 2’s greedy bandit.
(b) Choose “Fork trap (O to move)”. With , run 100 simulations and then 1,000, resetting a few times. Then set and repeat. Which setting finds an edge move more reliably at 1,000 simulations, and why might a very large behave like flat Monte Carlo?
Hint
Solution
(a) With , after each root move has been tried once, selection is purely greedy on . The single rollout through the blocking move 9 is a random game, and O often loses it anyway, which leaves 9 with . Greedy then never selects it again: the other moves’ averages are measured under random play, where X often fails to complete its diagonal, so they settle somewhere above and always look better. You should see MCTS find 9 only some of the time (about half of the seeds). With , the bonus of the neglected move keeps growing as the parent’s count grows, so it gets re-tried, its true value shows, and MCTS finds 9 essentially every time by 100 simulations. This is the greedy failure from Chapter 2: an arm with one unlucky sample is abandoned forever.
(b) finds an edge essentially every time by 1,000 simulations; still fails roughly one time in four (over 200 seeds: 100% vs about 75%). With a very large , the exploration term dominates at every node, so visits are spread almost evenly over all moves, at the root and inside the tree. Then the subtree under O’s corner move never concentrates on X’s winning fork reply. X’s replies are sampled roughly uniformly, like a random player. The node values approach “average result if X plays randomly”, which is what flat Monte Carlo measures, and under random play the corners look better than the edges (exactly vs for O). The tree helps only when selection exploits inside the tree, so that the opponent’s best replies dominate the averages. Too little (part a) or too much (part b) both hurt.
A policy is trained by behavior cloning. On states drawn from the expert’s distribution it picks a different action than the expert with probability at most . Assume the worst case: once it has deviated, it is in unfamiliar territory and incurs cost 1 at every remaining step. While it has not deviated, it incurs cost 0.
(a) Show that the probability of having deviated by step is at most .
(b) Show that the expected total cost over steps is at most . Evaluate for , .
(c) Explain in words why DAgger’s guarantee scales like instead.
Hint
Solution
(a) Let be the event “the first deviation happens at step ”. Before the first deviation the learner has acted exactly like the expert, so it is in a state from the expert’s distribution, and . The event “deviated at or before step ” is the union of . By the union bound its probability is at most . (Exactly, if each step independently errs with probability , it is .)
(b) The cost at step is 1 if the policy has deviated by then and 0 otherwise, so its expectation is the probability from (a), at most . By linearity of expectation,
For , : . Half the episode can be spent off course, from a policy that is “99% accurate”. (In this worst-case model with independent errors the exact value is , still far above .)
(c) DAgger trains on the states the learner visits, and those states are labeled by the expert. So the learner’s error rate holds on its own state distribution, including states after earlier mistakes. In those states it now knows how to recover. Each step then contributes at most about expected cost no matter what happened before, and summing over steps gives about (Ross, Gordon & Bagnell 2011 make this precise with no-regret online learning). The quadratic came from “one error ruins every later step”; DAgger removes that cascade.
Use the chapter’s example, and , but with .
(a) Compute , , , and .
(b) Compute for the reference policy and for the greedy policy (always action 3). Check that beats both.
(c) Compared with , did the expected reward go up or down? The KL? Why?
Solution
(a) Weights : , , . .
.
.
(using unrounded values: 0.9155).
. And . They agree, as the theory says.
(b) (KL = 0). Greedy: reward 2, , . Both are below 1.306. Greedy is now much closer than at (where it scored 0.391 vs 1.027), because KL is cheaper.
(c) Expected reward went up (1.350 → 1.764) and KL went up (0.323 → 0.916). A smaller makes deviating from cheaper, so the optimum moves further from toward the high-reward action. As it becomes greedy.
Let be a distribution on a finite set with for all , any real function, and .
(a) Prove Gibbs’ inequality: , with equality iff .
(b) Prove that for every distribution , , where . Conclude that is the unique maximizer.
(c) Specialize to uniform on actions. Show that the problem becomes “maximize ” (up to a constant), with solution .
(d) Show that as in case (c), when is uniform. (Hint: bound above and below.) Then show that as .
Hint
Solution
(a) Sum over with . Since is concave, Jensen gives
is strictly concave, so equality in Jensen requires to be the same constant for all with , and the last inequality requires to put no mass outside ‘s support. Together, .
(b) From , taking logs: . Then
The first term doesn’t depend on . By (a) the second is with equality iff . So is the unique maximizer, and the maximum is .
(c) With :
So the objective is . The constant doesn’t change the maximizer, which is . That is maximum-entropy RL’s one-step solution, with the temperature equal to .
(d) With : the largest term in is , and every term is at most , so . Taking :
As , both bounds go to . (The log-sum-exp is a “soft max”, and controls how soft.) For : for each , so and .
A dataset for a one-step problem with actions contains: tried 50 times with mean reward 0.60; tried 3 times with mean reward 0.90; tried once with reward 1.00; never tried.
(a) Which action does “greedy on the sample means” choose? What if is a neural network that extrapolates ?
(b) Rank the actions by the pessimistic score . Which is chosen?
(c) Why would the optimistic score be a good idea online, and a bad idea here?
(d) A colleague says: “DPO is offline RL”. Give one reason this matters in practice.
Hint
Solution
(a) Greedy on sample means picks (1.00 from a single sample). With an extrapolating network it picks (1.2), an action with no data at all. In both cases it trusts the estimates it has the least evidence for.
(b) Scores: : . : . : . : . Pessimism picks , the well-understood, decent action.
(c) Online, picking an uncertain action produces a new sample, which shrinks its uncertainty and corrects the estimate. Optimism is self-correcting, and that’s why UCB’s regret is small. Offline, picking an action produces no new data. An overestimated action is just chosen and deployed, and the error is never seen during training. So the uncertain actions that optimism favors are exactly the ones most likely to be overestimated.
(d) Any of: DPO can’t explore, so it learns only from responses in the dataset, which may be unlike what the current model generates (distribution shift). It can raise the probability of responses outside the data in uncontrolled ways (its implicit reward is unconstrained there). Its quality depends heavily on how well the dataset covers the responses the trained model will actually produce, which is why online and iterative DPO variants, which regenerate pairs from the current model, often work better (Chapter 13).
Without looking at the table at the end of the chapter, match each classic idea (1–6) with its LLM technique (A–F), and write one sentence on what the two share.
- Behavior cloning 2. AlphaZero’s training target (visit counts) 3. Pessimism / staying near the behavior policy 4. Learning rewards from pairwise comparisons 5. DAgger 6. The Boltzmann policy
A. The KL penalty to in RLHF B. Supervised fine-tuning on human-written answers C. On-policy distillation from a teacher model D. Training on the best of many sampled solutions (rejection sampling + SFT) E. The optimum of the RLHF objective, inverted to derive DPO F. Bradley–Terry reward models
Hint
Solution
1–B: both maximize the likelihood of an expert’s actions (tokens) in the expert’s states (prefixes), and both suffer covariate shift (exposure bias).
2–D: both use an expensive improvement procedure (tree search / sampling many answers and keeping the good ones) to produce better targets, then train the fast policy to imitate them (expert iteration).
3–A: both stop the learned policy from wandering into regions where the learned values or rewards are unreliable, because they were fit on data from the behavior / reference policy.
4–F: both fit a scalar reward so that predicts which of two behaviors a human prefers (Christiano et al. 2017 → Chapter 12).
5–C: both let the learner act and have the expert (teacher) label the states the learner itself visits, which removes compounding errors.
6–E: the RLHF optimum is . Inverting it expresses through the policy’s log-ratio, which DPO plugs into Bradley–Terry (Chapter 13).
In the lab’s mcts.py (game logic is provided in tictactoe.py):
- Task 1
uct_score(child_W, child_N, parent_N, c): the UCT formula, for unvisited children. - Task 2
rollout(board, rng): random play to the end; return the result from X’s point of view. - Task 3
backup(path, result): and along the path. - Task 4
run_simulation(root, c, rng): selection, expansion, rollout, backup.
The tests check the UCT table from this chapter, the backup signs, that selection follows the UCT scores, tree bookkeeping, three puzzles (win in one, block, fork trap), and that MCTS with 500 simulations per move does not lose to a random player. Then run run.py and look at the middle panel: why does flat Monte Carlo get worse with more rollouts in the fork trap?
Hint
backup first and test it on a 3-node path by hand; most MCTS bugs are sign bugs. In run_simulation, selection must stop at the first node that still has untried moves, which is the root itself for the first 9 simulations from an empty board.Solution
The reference code is in solutions/mcts.py. The key lines:
def uct_score(child_W, child_N, parent_N, c):
if child_N == 0:
return math.inf
return child_W / child_N + c * math.sqrt(math.log(parent_N) / child_N)
def backup(path, result):
for node in path:
node.N += 1
node.W += result * node.player_just_moved # flip sign for O's nodes
def run_simulation(root, c, rng):
node, path = root, [root]
while not node.terminal and not node.untried and node.children: # 1. select
node = max(node.children, key=lambda ch: uct_score(ch.W, ch.N, node.N, c))
path.append(node)
if not node.terminal and node.untried: # 2. expand
move = node.untried.pop(rng.randrange(len(node.untried)))
node = Node(play(node.board, move), move, node)
node.parent.children.append(node)
path.append(node)
result = rollout(node.board, rng) # 3. rollout
backup(path, result) # 4. backup
return resultrollout loops board = play(board, rng.choice(legal_moves(board))) until winner(board) is not None.
Why flat Monte Carlo gets worse: it estimates each move’s value under random continuation, and that estimate is biased. Against a random X, O’s corner moves score better than edges (a random X rarely finds the fork). More rollouts just shrink the noise around the wrong answer, so flat Monte Carlo converges to the corner. MCTS’s tree makes X’s in-tree replies good ones, so the values converge toward the minimax values instead.
In the lab’s gibbs.py:
- Task 5a
gibbs_policy(pi0, r, beta): return . It must not overflow for around , and must give zero probability where . - Task 5b
kl_objective(pi, pi0, r, beta): return with .
The tests check the worked example, the limits and , that 2,000 random policies never beat , and the identity for each of them.
Hint
np.log(0) is -inf and np.exp(-inf) is 0, which handles zero-probability actions for free (silence the warning with np.errstate(divide="ignore")).Solution
From solutions/gibbs.py:
def gibbs_policy(pi0, r, beta):
with np.errstate(divide="ignore"):
logits = np.log(pi0) + r / beta # -inf where pi0 == 0
logits = logits - logits.max() # stability: largest weight becomes e^0 = 1
w = np.exp(logits)
return w / w.sum()
def kl_objective(pi, pi0, r, beta):
m = pi > 0 # 0 log 0 = 0
kl = np.sum(pi[m] * np.log(pi[m] / pi0[m]))
return pi @ r - beta * klSubtracting the max is the same trick as a numerically stable softmax: it multiplies every weight by the same constant , which cancels when you divide by the sum, and it guarantees the largest exponent is 0, so nothing overflows. Panel 3 of run.py sweeps : KL rises to as , and falls to 0 as grows.
Files: README.md, tictactoe.py, mcts.py, gibbs.py, test_mcts.py, test_gibbs.py, run.py
cd 10-landscape
python -m pytest -q # your code: tests fail until you fill in the TODOs
RL_SOLUTIONS=1 python -m pytest -q # reference solutions: all passFirst time? See Exercises & setup.
Further reading
- Sutton & Barto (2018), Reinforcement Learning: An Introduction, ch. 8. Planning and learning in one framework: Dyna, prioritized sweeping, decision-time planning and MCTS. Read 8.1–8.3 and 8.11.
- Browne et al. (2012), A Survey of Monte Carlo Tree Search Methods. The standard MCTS reference: UCT, its variants and enhancements, with clear pseudocode.
- Silver et al. (2017), Mastering Chess and Shogi by Self-Play with a General Reinforcement Learning Algorithm. AlphaZero: PUCT search plus a policy-value network trained to imitate the search. Short, and the methods section is the algorithm.
- Schrittwieser et al. (2019), Mastering Atari, Go, Chess and Shogi by Planning with a Learned Model. MuZero: search inside a learned latent model that only predicts reward, value and policy.
- Ross, Gordon & Bagnell (2011), A Reduction of Imitation Learning and Structured Prediction to No-Regret Online Learning. DAgger, and the clearest statement of why behavior cloning’s errors compound.
- Christiano et al. (2017), Deep Reinforcement Learning from Human Preferences. Reward models from pairwise human comparisons; the direct ancestor of RLHF.
- Levine, Kumar, Tucker & Fu (2020), Offline Reinforcement Learning: Tutorial, Review, and Perspectives on Open Problems. Why offline RL is hard (distribution shift) and the main families of fixes.
- Levine (2018), Reinforcement Learning and Control as Probabilistic Inference. Maximum-entropy RL, soft value functions and the Boltzmann optimum derived carefully; the bridge to SAC and to the KL-regularized view of RLHF.
Next, Part III begins: Chapter 11 treats a language model as a policy and puts the KL-regularized optimum you just derived to work.