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.

~120 minBefore this: Bandits, Dynamic programming, Policy gradients

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 π∗∝π0 er/β\pi^* \propto \pi_0\, e^{r/\beta} (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:

  1. You learn by interacting. You can try actions and see what happens, as often as you like.
  2. The reward is given. Someone wrote down r(s,a)r(s, a) for you.
  3. 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.)
  4. 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:

RegionWhat changesShows up in LLMs asChapter
Model-based RL and planningUse a model to look aheadTest-time search, verifier-guided search17
Imitation learningLearn from demonstrations, no rewardSupervised fine-tuning (SFT), distillation11, 21
Learning rewards (inverse RL, preferences)Infer the reward instead of being given itReward models from human comparisons12
Offline RLNo new interaction, just a fixed datasetDPO; the KL leash13, 11
Maximum-entropy / KL-regularized RLObjective adds an entropy or KL termThe RLHF objective and its closed-form optimum11, 13
ExplorationReward the agent for seeing new thingsEntropy collapse, the pass@k debate19, 15
Multi-agent RL and self-playOther learners in the environmentSelf-play, debate, multi-agent setups18, 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 ss and aa, it predicts s′s' and rr. 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 (s,a,r,s′)(s, a, r, s') 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 nn 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).

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 1017010^{170}. 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:

  • NN: how many simulations have passed through it (its visit count),
  • WW: 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 +1+1, a loss −1-1, a draw 00.

So Q=W/NQ = W/N is the average result of that move for the player who chose it.

One simulation has four phases:

  1. 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.
  2. Expansion. Add one new child for one untried move.
  3. Rollout. From the new node, play random moves until the game ends. Call the result zz: +1+1 if X wins, −1-1 if O wins, 00 for a draw.
  4. Backup. Walk back up the path. Every node gets N+=1N \mathrel{+}= 1, and WW moves by +z+z or −z-z, 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 QQ? 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):

UCT(child)  =  WN⏟exploit  +  c ln⁡NparentN⏟explore.\text{UCT}(\text{child}) \;=\; \underbrace{\frac{W}{N}}_{\text{exploit}} \;+\; c\,\underbrace{\sqrt{\frac{\ln N_\text{parent}}{N}}}_{\text{explore}} .

This is the UCB formula from Chapter 2 almost word for word. NparentN_\text{parent} plays the role of the total number of pulls tt, and NN plays the role of Nt(a)N_t(a). 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 Nparent=20N_\text{parent} = 20 times, it has three children, and c=1.4c = 1.4:

ChildNNWWQ=W/NQ = W/Nbonus 1.4ln⁡20/N1.4\sqrt{\ln 20 / N}UCT
A1060.6000.7661.366
B620.3330.9891.323
C410.2501.2121.462

(ln⁡20≈2.996\ln 20 \approx 2.996.) Child C has the worst average so far but is selected next, because with only 4 visits its average is the least trustworthy. With c=0.5c = 0.5 the bonuses shrink to 0.274, 0.353 and 0.433, and A wins with 0.874. The constant cc sets the exchange rate between “looks good” and “barely tried”. Since our results live in [−1,1][-1, 1] (a range of 2, versus UCB1’s [0,1][0, 1]), values of cc 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?

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 NN, QQ, exploration bonus and UCT score, so you can check every number against the formula.

Interactive Monte Carlo tree search on tic-tac-toe

1 Select2 Expand3 Rollout4 Backup

moveNQbonusUCTperfect 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 1/6≈+0.171/6 \approx +0.17 after a corner and exactly +0.10+0.10 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 pθ(a∣s)p_\theta(a \mid s), first by supervised learning on expert human games and then by policy-gradient RL through self-play. It also trained a value network vθ(s)v_\theta(s) 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 pθ(⋅∣s)p_\theta(\cdot \mid s) and vθ(s)v_\theta(s). Selection uses the PUCT rule, UCT with a prior:

a=arg⁡max⁡a  Q(s,a)+cpuct pθ(a∣s) ∑bN(s,b)1+N(s,a).a = \arg\max_a \; Q(s, a) + c_\text{puct}\, p_\theta(a \mid s)\, \frac{\sqrt{\sum_b N(s, b)}}{1 + N(s, a)} .

Here Q(s,a)Q(s, a) is the average value of the child, W/NW/N as before, and N(s,a)N(s, a) is its visit count. The network’s prior pθp_\theta 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 vθv_\theta instead of a random game.

Training is a loop of self-play games. At every move, MCTS runs and produces visit counts N(s,a)N(s, a), which define a search policy πMCTS(a∣s)∝N(s,a)1/τ\pi_\text{MCTS}(a \mid s) \propto N(s, a)^{1/\tau}. Here τ\tau is a temperature (not a trajectory, its meaning elsewhere in this course): τ=1\tau = 1 copies the visit proportions, and τ→0\tau \to 0 puts all the probability on the most-visited move. When the game ends, let z=±1z = \pm 1 or 00 be the result from the point of view of the player to move in ss. The network is trained on each position ss to minimize:

L(θ)=(z−vθ(s))2  −  ∑aπMCTS(a∣s)log⁡pθ(a∣s)  +  weight decay.\mathcal{L}(\theta) = \big(z - v_\theta(s)\big)^2 \;-\; \sum_a \pi_\text{MCTS}(a \mid s) \log p_\theta(a \mid s) \;+\; \text{weight decay}.

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 hh and a dynamics function that maps (h,a)(h, a) 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 πθ(a∣s)\pi_\theta(a \mid s) to the expert’s state–action pairs by maximum likelihood:

max⁡θ  E(s,a)∼expert data[log⁡πθ(a∣s)].\max_\theta \; \mathbb{E}_{(s, a) \sim \text{expert data}} \big[\log \pi_\theta(a \mid s)\big].

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 ϵ\epsilon 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 TT. The chance that it has gone off course by step tt is at most tϵt\epsilon. So the expected number of steps spent off course is at most

∑t=1Tt ϵ  =  ϵ T(T+1)2  ≈  ϵT22.\sum_{t=1}^{T} t\,\epsilon \;=\; \epsilon\,\frac{T(T+1)}{2} \;\approx\; \frac{\epsilon T^2}{2}.

With ϵ=0.01\epsilon = 0.01 and T=100T = 100, that is up to about 50 bad steps, not the ϵT=1\epsilon T = 1 you might naively expect from a 1% error rate. Ross & Bagnell (2010) made this precise: behavior cloning’s cost can grow like T2ϵT^2 \epsilon. 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 TT. 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?

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 r=0r = 0 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 ∝exp⁡(return)\propto \exp(\text{return}). 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 rϕr_\phi was trained to predict those choices, and an RL agent maximized rϕr_\phi 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

P(1≻2)=σ(rϕ(clip1)−rϕ(clip2)),P(1 \succ 2) = \sigma\big(r_\phi(\text{clip}_1) - r_\phi(\text{clip}_2)\big),

with σ\sigma 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 D\mathcal{D} of transitions collected by some other behavior policy μ\mu, with no further interaction.

Q-learning is off-policy (Chapter 5), so you might think you can just run it on D\mathcal{D}. This fails, and the reason is worth understanding.

A worked example. One state, three actions. The dataset has 4 tries of a1a_1 (rewards 1, 1, 0, 1), 2 tries of a2a_2 (rewards 0.5, 0.5), and no tries of a3a_3. A table gives Q(a1)=0.75Q(a_1) = 0.75, Q(a2)=0.5Q(a_2) = 0.5, and Q(a3)Q(a_3) stays at its initial value. With a neural network, Q(a3)Q(a_3) is whatever the network extrapolates, say 1.3. The greedy policy picks a3a_3, the one action you know nothing about. In an online setting this would be harmless: you would try a3a_3, see its real reward, and correct the estimate. Offline, you never find out.

In a sequential problem it gets worse. The Q-learning target r+γmax⁡a′Q(s′,a′)r + \gamma \max_{a'} Q(s', a') 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, Q(a)−c/n(a)Q(a) - c/\sqrt{n(a)}, where n(a)n(a) is how often aa appears in the data. With c=1c = 1 the example gives 0.75−1/2=0.250.75 - 1/2 = 0.25 for a1a_1, 0.5−1/2≈−0.210.5 - 1/\sqrt 2 \approx -0.21 for a2a_2, and −∞-\infty for the untried a3a_3. Pessimism picks a1a_1.

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 QQ 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 μ\mu, for example with a penalty β KL(π∥μ)\beta\,\mathrm{KL}(\pi \Vert \mu). 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?

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 π0\pi_0 (think: a language model after SFT) and a reward rr. You want a new policy with high reward, but you don’t want to stray far from π0\pi_0. 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 π(a)\pi(a) over a finite set of actions. We measure “straying” with the KL divergence and trade it off against reward with a coefficient β>0\beta > 0:

J(π)  =  ∑aπ(a) r(a)⏟expected reward  −  β∑aπ(a)log⁡π(a)π0(a)⏟KL(π∥π0).J(\pi) \;=\; \underbrace{\sum_a \pi(a)\, r(a)}_{\text{expected reward}} \;-\; \beta \underbrace{\sum_a \pi(a) \log \frac{\pi(a)}{\pi_0(a)}}_{\mathrm{KL}(\pi \Vert \pi_0)} .

Call this the KL-regularized objective. Large β\beta means “stay very close to π0\pi_0”. Small β\beta means “mostly chase reward”.

The answer: tilt the reference by er/βe^{r/\beta}

The maximizer has a closed form:

π∗(a)  =  1Z π0(a) er(a)/β,Z=∑aπ0(a) er(a)/β,\pi^*(a) \;=\; \frac{1}{Z}\, \pi_0(a)\, e^{r(a)/\beta}, \qquad Z = \sum_a \pi_0(a)\, e^{r(a)/\beta},

and the best achievable value is J(π∗)=βlog⁡ZJ(\pi^*) = \beta \log Z.

In words: start from the reference and multiply each action’s probability by er/βe^{r/\beta}, then renormalize. Actions with high reward get boosted exponentially. β\beta sets how strongly. An action the reference never takes (π0(a)=0\pi_0(a) = 0) stays impossible, whatever its reward.

A worked example. Three actions with π0=(0.5,0.3,0.2)\pi_0 = (0.5, 0.3, 0.2), rewards r=(0,1,2)r = (0, 1, 2) and β=1\beta = 1.

  • Unnormalized weights π0(a)er(a)\pi_0(a) e^{r(a)}: 0.5⋅1=0.5000.5 \cdot 1 = 0.500,   0.3⋅e=0.816\;0.3 \cdot e = 0.816,   0.2⋅e2=1.478\;0.2 \cdot e^2 = 1.478.
  • Z=0.500+0.816+1.478=2.793Z = 0.500 + 0.816 + 1.478 = 2.793.
  • π∗=(0.179,  0.292,  0.529)\pi^* = (0.179,\; 0.292,\; 0.529).
  • Expected reward Eπ∗[r]=0.292+2(0.529)=1.350\mathbb{E}_{\pi^*}[r] = 0.292 + 2(0.529) = 1.350.
  • KL(π∗∥π0)=0.179ln⁡0.1790.5+0.292ln⁡0.2920.3+0.529ln⁡0.5290.2=0.323\mathrm{KL}(\pi^* \Vert \pi_0) = 0.179 \ln\frac{0.179}{0.5} + 0.292 \ln\frac{0.292}{0.3} + 0.529 \ln\frac{0.529}{0.2} = 0.323.
  • J(π∗)=1.350−0.323=1.027J(\pi^*) = 1.350 - 0.323 = 1.027, and βlog⁡Z=ln⁡2.793=1.027\beta \log Z = \ln 2.793 = 1.027. They agree.

Compare with two obvious alternatives. Copying the reference gives J(π0)=0.7J(\pi_0) = 0.7 (expected reward 0.3+0.40.3 + 0.4, zero KL). Going greedy, always action 3, gives reward 2 but pays KL=ln⁡(1/0.2)=1.609\mathrm{KL} = \ln(1/0.2) = 1.609, so J=0.391J = 0.391. 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 π∗\pi^* and solve it for the reward:

r(a)=βlog⁡π∗(a)π0(a)+βlog⁡Z.r(a) = \beta \log \frac{\pi^*(a)}{\pi_0(a)} + \beta \log Z .

Substitute this into J(π)J(\pi) for an arbitrary policy π\pi:

J(π)=∑aπ(a)[βlog⁡π∗(a)π0(a)+βlog⁡Z]−β∑aπ(a)log⁡π(a)π0(a)=βlog⁡Z  +  β∑aπ(a)[log⁡π∗(a)π0(a)−log⁡π(a)π0(a)]=βlog⁡Z  −  β∑aπ(a)log⁡π(a)π∗(a).\begin{aligned} J(\pi) &= \sum_a \pi(a) \Big[\beta \log \frac{\pi^*(a)}{\pi_0(a)} + \beta \log Z\Big] - \beta \sum_a \pi(a) \log \frac{\pi(a)}{\pi_0(a)} \\ &= \beta \log Z \;+\; \beta \sum_a \pi(a) \Big[\log \frac{\pi^*(a)}{\pi_0(a)} - \log \frac{\pi(a)}{\pi_0(a)}\Big] \\ &= \beta \log Z \;-\; \beta \sum_a \pi(a) \log \frac{\pi(a)}{\pi^*(a)} . \end{aligned}

In the second line we used ∑aπ(a)=1\sum_a \pi(a) = 1, and the π0\pi_0‘s cancel in the third. So:

That KL is non-negative (Gibbs’ inequality) follows from Jensen’s inequality: −KL(p∥q)=∑ap(a)log⁡q(a)p(a)≤log⁡∑ap(a)q(a)p(a)=log⁡1=0-\mathrm{KL}(p \Vert q) = \sum_a p(a) \log\frac{q(a)}{p(a)} \le \log \sum_a p(a) \frac{q(a)}{p(a)} = \log 1 = 0, with equality only if q/pq/p is constant, that is p=qp = q.

∂ The same result with a Lagrange multiplier (the route you'd try first)

Maximize J(π)=∑aπ(a)r(a)−β∑aπ(a)log⁡π(a)π0(a)J(\pi) = \sum_a \pi(a) r(a) - \beta \sum_a \pi(a) \log\frac{\pi(a)}{\pi_0(a)} subject to ∑aπ(a)=1\sum_a \pi(a) = 1. (The constraint π(a)≥0\pi(a) \ge 0 will turn out to hold automatically.) Form the Lagrangian

L(π,λ)=∑aπ(a)r(a)−β∑aπ(a)[log⁡π(a)−log⁡π0(a)]+λ(1−∑aπ(a)).\mathcal{L}(\pi, \lambda) = \sum_a \pi(a) r(a) - \beta \sum_a \pi(a)\big[\log \pi(a) - \log \pi_0(a)\big] + \lambda \Big(1 - \sum_a \pi(a)\Big).

Differentiate with respect to one component π(a)\pi(a), for an action with π0(a)>0\pi_0(a) > 0. Use ddp (plog⁡p)=log⁡p+1\frac{d}{dp}\,(p \log p) = \log p + 1:

∂L∂π(a)=r(a)−β[log⁡π(a)+1−log⁡π0(a)]−λ=0.\frac{\partial \mathcal{L}}{\partial \pi(a)} = r(a) - \beta\big[\log \pi(a) + 1 - \log \pi_0(a)\big] - \lambda = 0 .

Solve for log⁡π(a)\log \pi(a):

log⁡π(a)=log⁡π0(a)+r(a)β−1−λβ⟹π(a)=π0(a) er(a)/β⋅e−1−λ/β.\log \pi(a) = \log \pi_0(a) + \frac{r(a)}{\beta} - 1 - \frac{\lambda}{\beta} \quad\Longrightarrow\quad \pi(a) = \pi_0(a)\, e^{r(a)/\beta} \cdot e^{-1-\lambda/\beta} .

The last factor is the same for every aa, so it is a normalizing constant. The constraint ∑aπ(a)=1\sum_a \pi(a) = 1 fixes it to 1/Z1/Z with Z=∑aπ0(a)er(a)/βZ = \sum_a \pi_0(a) e^{r(a)/\beta}. This gives π∗(a)=π0(a)er(a)/β/Z\pi^*(a) = \pi_0(a) e^{r(a)/\beta}/Z, which is positive wherever π0\pi_0 is, so the non-negativity constraint never binds. Actions with π0(a)=0\pi_0(a) = 0 must get π(a)=0\pi(a) = 0, otherwise the KL is infinite.

Is this stationary point a maximum? JJ is concave: the expected reward is linear in π\pi, and −β KL(π∥π0)-\beta\,\mathrm{KL}(\pi \Vert \pi_0) is concave because plog⁡pp \log p is convex (second derivative 1/p>01/p > 0). A stationary point of a concave function on a convex set is the global maximum.

Finally, the value. Plug log⁡π∗(a)π0(a)=r(a)β−log⁡Z\log\frac{\pi^*(a)}{\pi_0(a)} = \frac{r(a)}{\beta} - \log Z into the KL:

KL(π∗∥π0)=∑aπ∗(a)[r(a)β−log⁡Z]=Eπ∗[r]β−log⁡Z,\mathrm{KL}(\pi^* \Vert \pi_0) = \sum_a \pi^*(a)\Big[\frac{r(a)}{\beta} - \log Z\Big] = \frac{\mathbb{E}_{\pi^*}[r]}{\beta} - \log Z ,

so J(π∗)=Eπ∗[r]−β KL(π∗∥π0)=βlog⁡ZJ(\pi^*) = \mathbb{E}_{\pi^*}[r] - \beta\,\mathrm{KL}(\pi^* \Vert \pi_0) = \beta \log Z.

Three ways to read the formula

1. It’s a Boltzmann distribution, and JJ is a free energy. Write the energy of action aa as E(a)=−r(a)E(a) = -r(a) and the temperature as T=βT = \beta. If π0\pi_0 is uniform, then KL(π∥π0)=log⁡K−H(π)\mathrm{KL}(\pi \Vert \pi_0) = \log K - H(\pi), with HH the entropy and KK the number of actions, and maximizing JJ is the same as minimizing

F(π)=Eπ[E]−T H(π),F(\pi) = \mathbb{E}_\pi[E] - T\, H(\pi),

the Helmholtz free energy U−TSU - TS. Its minimizer is the Boltzmann distribution π∝e−E/T=er/β\pi \propto e^{-E/T} = e^{r/\beta}, with Fmin=−Tlog⁡∑ae−E(a)/TF_\text{min} = -T \log \sum_a e^{-E(a)/T}, minus TT times the log of the physicist’s partition function. (That sum is KK times our ZZ, because our ZZ includes the weights π0(a)=1/K\pi_0(a) = 1/K. The difference, −Tlog⁡K-T \log K, is the constant that separates −F-F from JJ.) That’s the Gibbs variational principle of statistical mechanics, and the identity in the Key callout is its standard proof. A non-uniform π0\pi_0 acts like a density of states, a prior weight on each action before the energy is taken into account.

2. β\beta is a temperature knob. As β→∞\beta \to \infty, er/β→1e^{r/\beta} \to 1 and π∗→π0\pi^* \to \pi_0: the leash is so tight you just copy the reference. As β→0\beta \to 0, the action with the largest reward dominates and π∗\pi^* becomes greedy (among actions π0\pi_0 allows). In between you get a smooth compromise. With uniform π0\pi_0, π∗=softmax(r/β)\pi^* = \text{softmax}(r/\beta), and βlog⁡Z=βlog⁡1K∑aer(a)/β\beta \log Z = \beta \log \frac{1}{K}\sum_a e^{r(a)/\beta} is a “soft max” of the rewards that tends to max⁡ar(a)\max_a r(a) as β→0\beta \to 0.

3. Reward and policy determine each other. The rearranged form r(a)=βlog⁡π∗(a)π0(a)+βlog⁡Zr(a) = \beta \log\frac{\pi^*(a)}{\pi_0(a)} + \beta \log Z says that, up to a constant, the reward is the log-ratio of the optimal policy to the reference. If you know π∗\pi^* and π0\pi_0, you know the reward. Chapter 13 builds DPO on exactly this observation.

Interactive The tilted policy π* ∝ π₀ · exp(r / β)

reference π₀   optimum π*   best random challenger (after you press the button)

Optimum π* ∝ π₀·exp(r/β)
Eπ*[r]
KL(π* ‖ π₀)
J(π*) = E[r] − β·KL
β·log Z
Other policies, same objective J
J(π₀): just copy the reference
J(greedy): always the best action
J(best random challenger)—
β·log Z − β·KL(challenger ‖ π*)—

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 π₀?

Sequential decisions: soft values and SAC

The same idea extends to whole MDPs. Add −β KL(π(⋅∣s)∥π0(⋅∣s))-\beta\,\mathrm{KL}(\pi(\cdot \mid s) \Vert \pi_0(\cdot \mid s)) to the reward at every step (or +αH(π(⋅∣s))+\alpha H(\pi(\cdot \mid s)) with a uniform π0\pi_0; this is maximum-entropy RL). The Bellman equations of Chapter 4 keep their shape, but the hard max⁡\max becomes the soft max you just met:

Qsoft(s,a)=r(s,a)+γ Es′[Vsoft(s′)],Vsoft(s)=βlog⁡∑aπ0(a∣s) eQsoft(s,a)/β,Q_\text{soft}(s, a) = r(s, a) + \gamma\, \mathbb{E}_{s'}\big[V_\text{soft}(s')\big], \qquad V_\text{soft}(s) = \beta \log \sum_a \pi_0(a \mid s)\, e^{Q_\text{soft}(s, a)/\beta},

and the optimal policy at each state is again the tilted reference, π∗(a∣s)∝π0(a∣s) eQsoft(s,a)/β\pi^*(a \mid s) \propto \pi_0(a \mid s)\, e^{Q_\text{soft}(s, a)/\beta}. Each state solves the one-step problem above, with QsoftQ_\text{soft} in place of rr. 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 γ\gamma-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 α\alpha 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: r+=r+κ⋅bonus(s)r^+ = r + \kappa \cdot \text{bonus}(s), with κ\kappa a weight. Three families:

  • Count-based. bonus(s)=1/N(s)\text{bonus}(s) = 1/\sqrt{N(s)}, where N(s)N(s) counts visits to ss. 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 chapterIts LLM descendantWhere
MCTS: search guided by value estimatesBest-of-N, verifier-guided beam and tree search, long chain of thoughtCh 17
AlphaZero: train the policy to imitate the searchRejection sampling + SFT, expert iterationCh 15
Behavior cloning; compounding errorsSFT; exposure biasCh 11
DAgger: label the learner’s own statesOn-policy distillationCh 21
Rewards from preference comparisonsBradley–Terry reward models, RLHFCh 12
Offline RL; pessimism; stay near the dataDPO is offline; the KL leash; overoptimizationCh 13, Ch 19
π∗∝π0er/β\pi^* \propto \pi_0 e^{r/\beta}, the Gibbs variational principleThe RLHF optimum; DPO’s derivationCh 11, Ch 13
Intrinsic exploration; entropyEntropy collapse; pass@kCh 19, Ch 15
Self-playSelf-play and self-generated problemsCh 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 ϵT2\epsilon T^2) 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: max⁡πEπ[r]−β KL(π∥π0)\max_\pi \mathbb{E}_\pi[r] - \beta\,\mathrm{KL}(\pi \Vert \pi_0) is solved by π∗∝π0er/β\pi^* \propto \pi_0 e^{r/\beta}, with value βlog⁡Z\beta \log Z. For any π\pi, J(π)=βlog⁡Z−β KL(π∥π∗)J(\pi) = \beta \log Z - \beta\,\mathrm{KL}(\pi \Vert \pi^*). 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

Exercise 10.1Which region of the map?Concept●○○

For each scenario, say which region(s) of this chapter’s map it belongs to, and why.

  1. 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.
  2. A robot arm is trained to fold towels from 200 recorded human demonstrations.
  3. A Go program spends 30 seconds per move searching ahead before playing.
  4. Annotators see two chatbot answers and click the better one; a model is trained to predict their clicks.
  5. A poker bot is trained by playing millions of hands against earlier versions of itself.
  6. A game agent receives an extra reward the first few times it enters a room.
Solution
  1. 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.
  2. 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.
  3. Model-based planning at decision time (MCTS). The rules are a perfect model; the search spends compute per decision.
  4. Learning the reward from preferences (Christiano et al. 2017; reward models in Chapter 12).
  5. Multi-agent RL / self-play. Training against a pool of earlier versions (not just the latest) protects against cycling.
  6. Exploration with a count-based intrinsic reward.
Exercise 10.2UCT by hand, and how it differs from UCB1Pen & paper●●○

A root node has been visited 30 times. It has three children with (N,W)(N, W) equal to (15,9)(15, 9), (10,4)(10, 4) and (5,1)(5, 1). Results are in [−1,1][-1, 1], stored from the chooser’s point of view.

(a) Compute the UCT score of each child with c=1c = 1. Which is selected?

(b) Find the smallest cc (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
ln⁡30≈3.401\ln 30 \approx 3.401. For (b), set the two UCT scores equal and solve for cc. For (c), think about whether the “arm means” stay fixed while the search runs.
Solution

(a) ln⁡30=3.401\ln 30 = 3.401.

  • Child 1: Q=9/15=0.600Q = 9/15 = 0.600, bonus =3.401/15=0.2267=0.476= \sqrt{3.401/15} = \sqrt{0.2267} = 0.476, UCT =1.076= 1.076.
  • Child 2: Q=0.400Q = 0.400, bonus =0.3401=0.583= \sqrt{0.3401} = 0.583, UCT =0.983= 0.983.
  • Child 3: Q=0.200Q = 0.200, bonus =0.6802=0.825= \sqrt{0.6802} = 0.825, UCT =1.025= 1.025.

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 0.2+0.825c>0.6+0.476c0.2 + 0.825c > 0.6 + 0.476c, that is 0.349c>0.40.349c > 0.4, so c>1.15c > 1.15 (more precisely 0.4/0.3486=1.1470.4/0.3486 = 1.147).

(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 [−1,1][-1, 1], not [0,1][0, 1], so the right scale for cc 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 cc instead of using the theoretical value.
Exercise 10.3Break MCTS on purposeExplore the demo●●○

Use the MCTS demo.

(a) Choose “Block or lose (O to move)”. Set c=0c = 0 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 c=1.4c = 1.4. Explain what you see using Chapter 2’s greedy bandit.

(b) Choose “Fork trap (O to move)”. With c=1.4c = 1.4, run 100 simulations and then 1,000, resetting a few times. Then set c=10c = 10 and repeat. Which setting finds an edge move more reliably at 1,000 simulations, and why might a very large cc behave like flat Monte Carlo?

Hint
(a) With c=0c = 0, once every child has one visit, selection always takes the child with the best average so far. What happens to a move whose single random rollout came out badly? (b) If cc is huge, how evenly does the search spread visits over the root’s children, and over their children?
Solution

(a) With c=0c = 0, after each root move has been tried once, selection is purely greedy on W/NW/N. The single rollout through the blocking move 9 is a random game, and O often loses it anyway, which leaves 9 with Q=−1Q = -1. 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 −1-1 and always look better. You should see MCTS find 9 only some of the time (about half of the seeds). With c=1.4c = 1.4, the bonus ln⁡N/N\sqrt{\ln N / N} 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) c=1.4c = 1.4 finds an edge essentially every time by 1,000 simulations; c=10c = 10 still fails roughly one time in four (over 200 seeds: 100% vs about 75%). With a very large cc, 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 1/6≈+0.171/6 \approx +0.17 vs +0.10+0.10 for O). The tree helps only when selection exploits inside the tree, so that the opponent’s best replies dominate the averages. Too little cc (part a) or too much (part b) both hurt.

Exercise 10.4Why behavior cloning compounds errorsPen & paper●●○

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 ϵ\epsilon. 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 tt is at most tϵt\epsilon.

(b) Show that the expected total cost over TT steps is at most ϵT(T+1)/2\epsilon T(T+1)/2. Evaluate for ϵ=0.01\epsilon = 0.01, T=100T = 100.

(c) Explain in words why DAgger’s guarantee scales like ϵT\epsilon T instead.

Hint
(a) Before the first deviation the learner is in expert-distribution states, so each step’s error probability is at most ϵ\epsilon. Use a union bound over the first tt steps. (b) Expected cost at step tt = probability of having deviated by step tt.
Solution

(a) Let DkD_k be the event “the first deviation happens at step kk”. Before the first deviation the learner has acted exactly like the expert, so it is in a state from the expert’s distribution, and P(Dk)≤ϵP(D_k) \le \epsilon. The event “deviated at or before step tt” is the union of D1,…,DtD_1, \dots, D_t. By the union bound its probability is at most ∑k=1tP(Dk)≤tϵ\sum_{k=1}^{t} P(D_k) \le t\epsilon. (Exactly, if each step independently errs with probability ϵ\epsilon, it is 1−(1−ϵ)t≤tϵ1 - (1-\epsilon)^t \le t\epsilon.)

(b) The cost at step tt is 1 if the policy has deviated by then and 0 otherwise, so its expectation is the probability from (a), at most tϵt\epsilon. By linearity of expectation,

E[total cost]≤∑t=1Ttϵ=ϵT(T+1)2.\mathbb{E}[\text{total cost}] \le \sum_{t=1}^{T} t\epsilon = \epsilon \frac{T(T+1)}{2}.

For ϵ=0.01\epsilon = 0.01, T=100T = 100: 0.01⋅5050=50.50.01 \cdot 5050 = 50.5. 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 ∑t=1100[1−0.99t]≈37.2\sum_{t=1}^{100} [1 - 0.99^t] \approx 37.2, still far above ϵT=1\epsilon T = 1.)

(c) DAgger trains on the states the learner visits, and those states are labeled by the expert. So the learner’s error rate ϵ\epsilon 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 ϵ\epsilon expected cost no matter what happened before, and summing over TT steps gives about ϵT\epsilon T (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.

Exercise 10.5Tilt a distribution by handPen & paper●○○

Use the chapter’s example, π0=(0.5,0.3,0.2)\pi_0 = (0.5, 0.3, 0.2) and r=(0,1,2)r = (0, 1, 2), but with β=0.5\beta = 0.5.

(a) Compute π∗\pi^*, Eπ∗[r]\mathbb{E}_{\pi^*}[r], KL(π∗∥π0)\mathrm{KL}(\pi^* \Vert \pi_0), J(π∗)J(\pi^*) and βlog⁡Z\beta \log Z.

(b) Compute JJ for the reference policy and for the greedy policy (always action 3). Check that π∗\pi^* beats both.

(c) Compared with β=1\beta = 1, did the expected reward go up or down? The KL? Why?

Solution

(a) Weights π0(a)er(a)/0.5=π0(a)e2r(a)\pi_0(a) e^{r(a)/0.5} = \pi_0(a) e^{2r(a)}: 0.5⋅1=0.5000.5 \cdot 1 = 0.500,   0.3e2=2.217\;0.3 e^{2} = 2.217,   0.2e4=10.920\;0.2 e^{4} = 10.920. Z=13.636Z = 13.636.

π∗=(0.037,0.163,0.801)\pi^* = (0.037, 0.163, 0.801).

E[r]=0.163+2⋅0.801=1.764\mathbb{E}[r] = 0.163 + 2 \cdot 0.801 = 1.764.

KL=0.037ln⁡0.0370.5+0.163ln⁡0.1630.3+0.801ln⁡0.8010.2=−0.096−0.099+1.111=0.916\mathrm{KL} = 0.037 \ln\frac{0.037}{0.5} + 0.163 \ln\frac{0.163}{0.3} + 0.801 \ln\frac{0.801}{0.2} = -0.096 - 0.099 + 1.111 = 0.916 (using unrounded values: 0.9155).

J=1.764−0.5⋅0.916=1.306J = 1.764 - 0.5 \cdot 0.916 = 1.306. And βlog⁡Z=0.5ln⁡13.636=0.5⋅2.613=1.306\beta \log Z = 0.5 \ln 13.636 = 0.5 \cdot 2.613 = 1.306. They agree, as the theory says.

(b) J(π0)=0.3⋅1+0.2⋅2=0.7J(\pi_0) = 0.3 \cdot 1 + 0.2 \cdot 2 = 0.7 (KL = 0). Greedy: reward 2, KL=ln⁡(1/0.2)=1.609\mathrm{KL} = \ln(1/0.2) = 1.609, J=2−0.5⋅1.609=1.195J = 2 - 0.5 \cdot 1.609 = 1.195. Both are below 1.306. Greedy is now much closer than at β=1\beta = 1 (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 β\beta makes deviating from π0\pi_0 cheaper, so the optimum moves further from π0\pi_0 toward the high-reward action. As β→0\beta \to 0 it becomes greedy.

Exercise 10.6Derive the Gibbs variational principlePen & paper●●●

Let π0\pi_0 be a distribution on a finite set with π0(a)>0\pi_0(a) > 0 for all aa, rr any real function, and β>0\beta > 0.

(a) Prove Gibbs’ inequality: KL(p∥q)≥0\mathrm{KL}(p \Vert q) \ge 0, with equality iff p=qp = q.

(b) Prove that for every distribution π\pi,   Eπ[r]−β KL(π∥π0)=βlog⁡Z−β KL(π∥π∗)\;\mathbb{E}_\pi[r] - \beta\,\mathrm{KL}(\pi \Vert \pi_0) = \beta \log Z - \beta\,\mathrm{KL}(\pi \Vert \pi^*), where π∗=π0er/β/Z\pi^* = \pi_0 e^{r/\beta}/Z. Conclude that π∗\pi^* is the unique maximizer.

(c) Specialize to uniform π0\pi_0 on KK actions. Show that the problem becomes “maximize Eπ[r]+βH(π)\mathbb{E}_\pi[r] + \beta H(\pi)” (up to a constant), with solution softmax(r/β)\text{softmax}(r/\beta).

(d) Show that βlog⁡Z→max⁡ar(a)\beta \log Z \to \max_a r(a) as β→0\beta \to 0 in case (c), when π0\pi_0 is uniform. (Hint: bound ZZ above and below.) Then show that π∗→π0\pi^* \to \pi_0 as β→∞\beta \to \infty.

Hint
(a) Jensen’s inequality on the concave function log⁡\log, applied to Ep[q/p]\mathbb{E}_p[q/p]. (b) Write rr in terms of log⁡(π∗/π0)\log(\pi^*/\pi_0) and substitute. (d) With m=max⁡ar(a)m = \max_a r(a), 1Kem/β≤Z≤em/β\frac{1}{K} e^{m/\beta} \le Z \le e^{m/\beta}.
Solution

(a) Sum over aa with p(a)>0p(a) > 0. Since log⁡\log is concave, Jensen gives

−KL(p∥q)=∑ap(a)log⁡q(a)p(a)≤log⁡∑ap(a)q(a)p(a)=log⁡∑a:p(a)>0q(a)≤log⁡1=0.-\mathrm{KL}(p \Vert q) = \sum_a p(a) \log \frac{q(a)}{p(a)} \le \log \sum_a p(a) \frac{q(a)}{p(a)} = \log \sum_{a: p(a) > 0} q(a) \le \log 1 = 0 .

log⁡\log is strictly concave, so equality in Jensen requires q(a)/p(a)q(a)/p(a) to be the same constant for all aa with p(a)>0p(a) > 0, and the last inequality requires qq to put no mass outside pp‘s support. Together, q=pq = p.

(b) From π∗(a)=π0(a)er(a)/β/Z\pi^*(a) = \pi_0(a) e^{r(a)/\beta}/Z, taking logs: r(a)=βlog⁡π∗(a)π0(a)+βlog⁡Zr(a) = \beta \log\frac{\pi^*(a)}{\pi_0(a)} + \beta \log Z. Then

Eπ[r]−β KL(π∥π0)=∑aπ(a)[βlog⁡π∗(a)π0(a)+βlog⁡Z−βlog⁡π(a)π0(a)]=βlog⁡Z∑aπ(a)  +  β∑aπ(a)log⁡π∗(a)π(a)=βlog⁡Z−β KL(π∥π∗).\begin{aligned} \mathbb{E}_\pi[r] - \beta\,\mathrm{KL}(\pi \Vert \pi_0) &= \sum_a \pi(a)\Big[\beta \log \tfrac{\pi^*(a)}{\pi_0(a)} + \beta \log Z - \beta \log \tfrac{\pi(a)}{\pi_0(a)}\Big] \\ &= \beta \log Z \sum_a \pi(a) \;+\; \beta \sum_a \pi(a) \log \tfrac{\pi^*(a)}{\pi(a)} \\ &= \beta \log Z - \beta\,\mathrm{KL}(\pi \Vert \pi^*). \end{aligned}

The first term doesn’t depend on π\pi. By (a) the second is ≤0\le 0 with equality iff π=π∗\pi = \pi^*. So π∗\pi^* is the unique maximizer, and the maximum is βlog⁡Z\beta \log Z.

(c) With π0(a)=1/K\pi_0(a) = 1/K:

KL(π∥π0)=∑aπ(a)log⁡π(a)+log⁡K=log⁡K−H(π).\mathrm{KL}(\pi \Vert \pi_0) = \sum_a \pi(a) \log \pi(a) + \log K = \log K - H(\pi).

So the objective is Eπ[r]+βH(π)−βlog⁡K\mathbb{E}_\pi[r] + \beta H(\pi) - \beta \log K. The constant doesn’t change the maximizer, which is π∗(a)=(1/K)er(a)/β∑b(1/K)er(b)/β=softmax(r/β)a\pi^*(a) = \frac{(1/K) e^{r(a)/\beta}}{\sum_b (1/K) e^{r(b)/\beta}} = \text{softmax}(r/\beta)_a. That is maximum-entropy RL’s one-step solution, with the temperature equal to β\beta.

(d) With m=max⁡ar(a)m = \max_a r(a): the largest term in Z=1K∑aer(a)/βZ = \frac{1}{K}\sum_a e^{r(a)/\beta} is 1Kem/β\frac{1}{K} e^{m/\beta}, and every term is at most 1Kem/β\frac{1}{K} e^{m/\beta}, so 1Kem/β≤Z≤em/β\frac{1}{K} e^{m/\beta} \le Z \le e^{m/\beta}. Taking βlog⁡\beta \log:

m−βlog⁡K  ≤  βlog⁡Z  ≤  m.m - \beta \log K \;\le\; \beta \log Z \;\le\; m .

As β→0\beta \to 0, both bounds go to mm. (The log-sum-exp is a “soft max”, and β\beta controls how soft.) For β→∞\beta \to \infty: er(a)/β→1e^{r(a)/\beta} \to 1 for each aa, so Z→∑aπ0(a)=1Z \to \sum_a \pi_0(a) = 1 and π∗(a)→π0(a)\pi^*(a) \to \pi_0(a).

Exercise 10.7What makes offline RL hardConcept●●○

A dataset for a one-step problem with actions a1,…,a4a_1, \dots, a_4 contains: a1a_1 tried 50 times with mean reward 0.60; a2a_2 tried 3 times with mean reward 0.90; a3a_3 tried once with reward 1.00; a4a_4 never tried.

(a) Which action does “greedy on the sample means” choose? What if QQ is a neural network that extrapolates Q(a4)=1.2Q(a_4) = 1.2?

(b) Rank the actions by the pessimistic score rˉ(a)−1/n(a)\bar r(a) - 1/\sqrt{n(a)}. Which is chosen?

(c) Why would the optimistic score rˉ(a)+1/n(a)\bar r(a) + 1/\sqrt{n(a)} 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
(b) For n=0n = 0, treat the score as −∞-\infty. (c) Ask what happens after you pick the action in each setting.
Solution

(a) Greedy on sample means picks a3a_3 (1.00 from a single sample). With an extrapolating network it picks a4a_4 (1.2), an action with no data at all. In both cases it trusts the estimates it has the least evidence for.

(b) Scores: a1a_1: 0.60−1/50=0.60−0.141=0.4590.60 - 1/\sqrt{50} = 0.60 - 0.141 = 0.459. a2a_2: 0.90−1/3=0.90−0.577=0.3230.90 - 1/\sqrt 3 = 0.90 - 0.577 = 0.323. a3a_3: 1.00−1=0.001.00 - 1 = 0.00. a4a_4: −∞-\infty. Pessimism picks a1a_1, 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).

Exercise 10.8Match each idea to its LLM descendantConcept●●○

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.

  1. 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 π0er/β/Z\pi_0 e^{r/\beta}/Z

A. The KL penalty to πref\pi_\text{ref} 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
For each pair, ask: who generates the data (the expert, or the learner itself)? Is something expensive (search, many samples) producing a better target for a cheaper policy? Is a learned quantity only trustworthy near some reference distribution?
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 σ(r1−r2)\sigma(r_1 - r_2) 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 πref er/β/Z\pi_\text{ref}\, e^{r/\beta}/Z. Inverting it expresses rr through the policy’s log-ratio, which DPO plugs into Bradley–Terry (Chapter 13).

Exercise 10.9Lab: build MCTS for tic-tac-toeCode●●○

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, +∞+\infty 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): N+=1N \mathrel{+}= 1 and W+=result×player_just_movedW \mathrel{+}= \text{result} \times \text{player\_just\_moved} 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
Write 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 result

rollout 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.

Exercise 10.10Lab: the KL-regularized optimum, numericallyCode●●○

In the lab’s gibbs.py:

  • Task 5a gibbs_policy(pi0, r, beta): return π0er/β/Z\pi_0 e^{r/\beta}/Z. It must not overflow for r/βr/\beta around 10510^5, and must give zero probability where π0=0\pi_0 = 0.
  • Task 5b kl_objective(pi, pi0, r, beta): return Eπ[r]−β KL(π∥π0)\mathbb{E}_\pi[r] - \beta\,\mathrm{KL}(\pi \Vert \pi_0) with 0log⁡0=00 \log 0 = 0.

The tests check the worked example, the limits β→0\beta \to 0 and β→∞\beta \to \infty, that 2,000 random policies never beat π∗\pi^*, and the identity J(π)=βlog⁡Z−β KL(π∥π∗)J(\pi) = \beta \log Z - \beta\,\mathrm{KL}(\pi \Vert \pi^*) for each of them.

Hint
Work with logits ℓ(a)=log⁡π0(a)+r(a)/β\ell(a) = \log \pi_0(a) + r(a)/\beta. Subtract max⁡aℓ(a)\max_a \ell(a) before exponentiating; the shift cancels in the normalization. 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 * kl

Subtracting the max is the same trick as a numerically stable softmax: it multiplies every weight by the same constant e−max⁡ℓe^{-\max \ell}, 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 β\beta: KL rises to −log⁡π0(best)=−log⁡0.03≈3.5-\log \pi_0(\text{best}) = -\log 0.03 \approx 3.5 as β→0\beta \to 0, and falls to 0 as β\beta 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 pass

First time? See Exercises & setup.

Further reading

Next, Part III begins: Chapter 11 treats a language model as a policy and puts the KL-regularized optimum you just derived to work.