Models, planning and imitation: Dyna, MCTS and AlphaZero
Before this lesson: lesson 02 (policy iteration), lesson 03 (UCB1), lesson 05 (Q-learning), lesson 07 (softmax policies); information theory 04 (cross-entropy) and supervised classification (logistic regression). Time: about 90 minutes, plus the notebook.
Why this matters #
- Games. AlphaGo, AlphaGo Zero and AlphaZero reached superhuman play in Go, chess and shogi with Monte Carlo tree search guided by a neural network. MuZero did the same without being told the rules.
- Discovery by search. AlphaZero-style agents (search plus a policy and value network) found new matrix multiplication algorithms (AlphaTensor, 2022) and faster sorting routines (AlphaDev, 2023). MCTS with neural networks plans chemical syntheses (Segler, Preuss and Waller, 2018).
- Sample efficiency. Real experience is expensive for robots, for plants in industry and for experiments in science. A learned model lets the agent reuse each sample many times (MBPO, Dreamer, model-predictive control).
- Language models. Supervised fine-tuning on demonstrations is behaviour cloning. On-policy distillation, where the teacher labels tokens that the student generated, is the DAgger idea.
- ML for science. A learned weather or fluid emulator that is rolled out step by step has the same compounding error as a learned dynamics model (ML for science 16).
1. Predict first #
2. The picture #
Learning and planning #
A model of the environment predicts what happens after an action: the next state and the reward . A distribution model gives the probabilities and the expected reward , as in lesson 02. A sample model only returns one possible , like a simulator. Planning is any computation that uses a model to improve a policy or a value function, without new real experience.
- Model-free RL (lessons 04–09) learns , or directly from real transitions.
- Model-based RL learns a model from real transitions (or is given one), then plans with it.
There are two ways to plan. Background planning improves or for all states, between real steps; Dyna-Q is the classic example. Decision-time planning searches from the current state only, just before choosing the next action; Monte Carlo tree search and model-predictive control do this.
Dyna-Q (Sutton, 1990) is Q-learning plus planning. After each real step it does one normal Q-learning update, stores the transition in a table (the model), and then makes more Q-learning updates on transitions replayed from the model. With it is plain Q-learning.
Predict, then run two episodes. With , how many cells get an arrow (a value above 0) after episode 2? With ? Run two episodes for each and count. Then press Run 10 episodes and Compare to see the steps per episode (log scale). Blue cells have a positive value (darker = higher); G is the goal. All need a long first episode, because all values are 0 and the agent walks at random.
What to notice. The reward is 0 everywhere except at the goal. With the value of the goal moves back about one cell per episode: after episode 2 only about 2 cells have a value. With the planning updates replay the old transitions, so the value spreads back over almost the whole maze during episode 2. In our runs (30 seeds), episode 2 took on average 726 steps with , 156 with , and 41 with . Dyna-Q with finds a near-shortest path in about 3 episodes; plain Q-learning needs about 25 to 30. The shortest path has 14 steps.
Rollouts drift: compounding model error #
A learned model is used again and again: the predicted next state is the input of the next prediction. A small error in one step changes the input of the next step, and the errors add up. If the true dynamics push nearby states apart, the errors also grow.
Predict first. The model's one-step error is about 1%. Is its error after 50 steps about 50%? Move the horizon . The real state (dark line) grows as ; the model predicts . The lower chart shows the relative error and, dashed, times the one-step error. Then switch to open loop vs MPC: the open-loop run executes the whole plan and drifts away; MPC plans again at every step and stays at 0.
Two lessons follow. First, a model must be judged by its multi-step error, not only by its one-step error. Second, a plan made with an imperfect model should not be run blindly: run its first action, look at the real state, and plan again. This is model-predictive control (section 3).
Search trees: Monte Carlo tree search in four phases #
In a game like Go or chess, the agent knows the rules, so it has a perfect model. The difficulty is the size of the tree of possible futures. Monte Carlo tree search (MCTS) grows a small part of this tree, from the current position, and spends its time on the promising branches. Each iteration has four phases:
- Select. Start at the root. At each node, choose a child with a bandit rule that balances a high mean result (exploit) and few visits (explore). Stop at a node that is not yet in the tree.
- Expand. Add that node to the tree.
- Evaluate. Estimate how good the node is: play the game to the end with random moves (a playout or rollout), or ask a value network.
- Backup. Add the result to the visit count and the total value of every node on the path. The mean is the node's estimated value.
After many iterations, the agent plays the move at the root with the most visits.
Predict, then step. Click the move (A, B or C) that you think the next Select will choose, then press Next phase four times: Select, Expand, Evaluate, Backup. The orange path is the selection; edge width grows with the visit count ; Q is the mean result for the player who made the move. Under each leaf, p is your win probability there. Then press Run 100 a few times. Move A has the best average (0.633), but the opponent can answer it with A3 (). Watch the visits move to B, the best move against a good opponent. Set and press Reset a few times: without exploration the search can lock onto a wrong move.
Two players. Here you move first and the opponent replies. The opponent wants your result to be low. We store each node's for the player who made the move into it, so every player maximises at their own nodes. The backup therefore flips the sign: a result (you win) adds to your moves and to the opponent's moves on the path. Forgetting the flip makes the opponent help you.
Why B wins. At first, A looks best, because random replies are mostly good for you. But once A is visited often, the selection at A finds the opponent's strong reply A3 and visits it most. The mean of A then moves towards . B's worst reply is still worth . MCTS approaches the minimax answer, not the average answer.
In the backup of a two-player MCTS, a playout from your move B through the opponent's reply B2 ends with (you win). What is added to of B and of B2?
Each node stores the value for the player who made the move into it. B is your move, so it gets your result . B2 is the opponent's move, and your win is the opponent's loss, so it gets . Both get . With the sign flip, every player maximises at their own nodes.
Copying an expert also drifts #
Imitation learning learns a policy from an expert's demonstrations instead of from rewards. The simplest method, behaviour cloning (BC), is supervised learning on the expert's state–action pairs. The problem is the data: the expert stays on the road, so the data contains only on-road states. After one mistake the learner is in a state it has never seen. There it has no reason to act well, so one mistake can cost many later steps. DAgger lets the learner drive, asks the expert what to do in the states the learner visited, and adds these labels to the data.
Predict first: if you double the horizon , how much does the expected cost of BC grow? Move . BC cars leave the road and never come back, because their data has only on-road states (the dots on the left show where the data has expert labels). Switch to the DAgger rounds: each round adds the positions the learner visited, labelled by the expert, and the cars return to the road. The chart compares the costs with and .
BC's expected cost grows like , DAgger's like . Section 3 proves this.
3. Definitions and main results #
Models and Dyna-Q #
In a deterministic environment the simplest learned model is a table: , the last outcome seen after in . In a stochastic environment the table can store all outcomes and sample one of them.
Algorithm (tabular Dyna-Q, Sutton and Barto §8.2). Initialise and an empty model. At every real step:
- In state , choose ε-greedily with respect to . Take it; observe and .
- Direct RL: (the Q-learning update of lesson 05; after a terminal state).
- Model learning: .
- Planning: repeat times: pick a previously seen pair at random, read , and apply the same Q-learning update to .
Why it helps. Dyna-Q makes Q-learning updates per real step, and each real transition is used again in many planning updates. The values then spread backwards through all known transitions, not only along the path of the current episode. The price is computation ( updates per step) and memory for the model.
Two refinements from Sutton and Barto, chapter 8. Prioritized sweeping (§8.4) replays first the pairs whose values would change most, instead of random pairs. Dyna-Q+ (§8.3) adds a small bonus to the reward of a pair not tried for steps, so the agent checks again whether the world has changed. A model of an old world can be worse than no model.
Planning with a learned model: MPC #
With continuous states and actions, a table is not enough. We fit a model (and often a reward model ) by supervised regression on real transitions, for example a neural network or an ensemble of networks.
Model-predictive control (MPC), also called receding-horizon control. At every real step:
- In the model, search for an action sequence that maximises the predicted return , where and .
- Run only the first action in the real environment.
- Observe the real next state and start again from step 1.
The search in step 1 is often derivative-free:
- Random shooting: sample random action sequences, predict the return of each in the model, and keep the best one.
- Cross-entropy method (CEM): keep a Gaussian over action sequences with mean and standard deviation (both of size ). Repeat a few times: sample sequences, keep the best ("elites"), and set and to the mean and standard deviation of the elites. Return . At the next real step, start from shifted by one step (a warm start).
MPC corrects model errors with feedback: every plan starts from the real state. PETS (Chua et al., 2018) is MPC with CEM on an ensemble of learned probabilistic models.
An MPC controller plans a sequence of actions in its learned model. How many of these actions does it run in the real environment before it plans again?
MPC runs only the first action, observes the real next state and plans again from there (receding horizon). Running the whole open-loop plan lets model errors and noise add up, as the open loop vs MPC view of the figure shows.
Model bias and compounding error #
Model bias. A planner or a policy that is optimised inside the model looks for the actions with the highest predicted return. If the model is wrong somewhere, the optimiser finds those places, because errors that look good are exactly what it searches for. So the plan is often better in the model than in reality.
Compounding error. Let the true dynamics be and the model , both run with the same actions from the same start .
Theorem (open-loop error). Assume the one-step model error is at most : for all , and that is -Lipschitz in : . Then the error after steps satisfies
Proof.
- Write , so .
- Add and subtract : .
- The first term is at most ; the second is at most . So .
- Unroll from : .
When the dynamics expand () the bound grows geometrically with . In the figure, the true system is and the model is . The relative error after steps is exactly : 0.0095 for , 0.099 for , and 0.61 for , more than the that a linear growth would give.
The trade-off. Model-based methods usually need far fewer real samples, because every sample is reused in planning. Model-free methods often reach a better final performance, because they optimise the real return and do not depend on the accuracy of a model. Practical methods take the middle road:
- MBPO (Janner et al., 2019) trains an ensemble of models, makes only short model rollouts ( steps, often 1 to a few) that start from real states in the replay buffer, and trains SAC (lesson 08) on real and model data. Short rollouts keep the compounding error small; the ensemble shows where the models disagree.
The infinite-horizon version: the simulation lemma
Let be a model with for all , with the true rewards and rewards in . For any policy , the Bellman equations of lesson 01 give . Each row of is at most in absolute value, and multiplies the max-norm by at most . So
The effective horizon is , so this is "horizon squared" again, the same order as the behaviour cloning bound below.
Monte Carlo tree search and UCT #
MCTS keeps, for each edge of the tree, a visit count , a total value and the mean . is the visit count of node . One iteration runs the four phases of section 2. The rule used in the selection phase is the tree policy; the rule used in random playouts is the default policy (or rollout policy).
UCT (Kocsis and Szepesvári, 2006) uses UCB1 from lesson 03 as the tree policy, at every node:
and tries every unvisited child first ( counts as ). With and results in this is exactly UCB1: each node is a bandit whose arms are its children. Two differences from the bandit of lesson 03: the rewards of an arm are not stationary (the policy below it keeps changing), and the arms are nested. Kocsis and Szepesvári showed that, with a suitable , the value estimate at the root converges to the optimal (minimax) value, and the probability of choosing a wrong move goes to 0 as the number of iterations grows.
Choosing the move. After the search, play the child of the root with the most visits (the "robust child"). A child with a high but few visits may just be lucky; the visit count includes the search's confidence.
Two-player games (lesson 01 has one agent; here two agents alternate). Store and for the player who moved into the node, and add or in the backup by whose move it was (the negamax convention). An equivalent convention stores all values for the first player and lets the second player choose of .
A node has . Child 1 has , ; child 3 has , . Use and . What are their UCT scores, approximately?
Child 1: . Child 3: . Child 3 has the larger bonus because it has only 2 visits, so UCT explores it next. Using only the mean is greedy search, which can lock onto a wrong move.
Imitation learning: behaviour cloning and its error bound #
Behaviour cloning (BC): supervised learning of on expert pairs , for example by maximum likelihood (minimise the cross-entropy , see information theory 04). Supervised fine-tuning of an LLM on demonstrations is BC.
Setting (Ross and Bagnell, 2010). Horizon ; a deterministic expert ; a cost per step in ; is the expected total cost of over steps. Note: here is a cost, so smaller is better (in lesson 07 was a return). Let be the probability that picks a different action from at a state drawn from the expert's state distribution at step , and . So is the error rate on the expert's own data: the test error of the supervised problem.
Theorem (compounding error of behaviour cloning). .
Proof.
- Run and with the same environment randomness. Until their first disagreement they visit the same states and pay the same costs.
- Before step the two runs are identical, so the state at step has the expert's distribution. The first disagreement is at step only if disagrees with there: probability at most .
- After a first disagreement at step , the learner pays at most more than the expert, because each cost is in .
- So .
The bound is tight in order: there are problems where a policy with error on the expert's states pays an extra cost of order (DAgger paper, §2). The road of section 2 is one. The reason is distribution shift: the learner is trained on the expert's states but tested on its own.
DAgger #
If were measured on the learner's own state distribution, the extra cost would be only : each mistake costs a bounded amount, because the learner also knows how to recover. DAgger (Dataset Aggregation; Ross, Gordon and Bagnell, 2011) makes the training distribution the learner's own:
- Train on expert data .
- For : run the policy (the expert with probability , often and then ) and record the states it visits.
- Ask the expert for the correct action in each recorded state.
- Add these pairs to (aggregate), train on all of , and repeat.
Guarantee (Theorem 3.2 of the paper, simplified). After rounds, one of the trained policies satisfies : linear in . Here is the error of the best policy in the class on the aggregated data, and bounds how much one wrong action can increase the expert's cost-to-go ( when the cost is the 0–1 disagreement with the expert). The price: an expert that can be queried during training, not just a fixed dataset.
A cloned policy has error rate on the expert's states, and every mistake can cost up to the rest of the episode. If you make the horizon ten times longer, how does the worst-case extra cost of behaviour cloning grow?
About first mistakes can happen, and each can cost up to steps, because after a mistake the learner is in states that its data does not cover. So the bound is , and the horizon gives the bound. DAgger trains on the learner's own states and brings the order down to .
AlphaZero: search as the expert, the network as the student #
AlphaZero (Silver et al., 2018) learns Go, chess and shogi from self-play only. One neural network takes a position and returns
- a vector of move probabilities (the policy head), and
- a scalar value , the predicted game result for the player to move (the value head).
Search with PUCT. AlphaZero runs MCTS from every position it plays (800 simulations per move in self-play). It changes MCTS in two ways:
- No random playouts. A new leaf is evaluated by the network: its value is backed up, and its prior probabilities are stored on its new edges.
- PUCT selection, which uses the prior:
The bonus is large for moves that the network likes and that the search has not visited much. Unlike UCT, an unvisited move is not tried automatically: a move with a tiny prior may never be tried. To keep some exploration, AlphaZero adds Dirichlet noise to the priors at the root. (The published pseudocode also lets grow slowly with ; a constant is the usual simplified form.)
Self-play targets. After the search from position , the visit counts at the root give the search policy
with a temperature (: proportional to the visits; : the most visited move). The move is sampled from in the first moves of a game, and later the most visited move is played. When the game ends with result , each position gets the target , from the view of the player to move at . The data is the set of triples .
The loss. The network is trained by gradient descent on
the squared error of the value, the cross-entropy from the search policy to the network policy , and weight decay.
Why the visit counts are the policy target. The search looks ahead with the network's own priors and values, so its move choice is usually stronger than the raw : MCTS is a policy improvement operator. Training towards copies the improvement into the network; the next search starts from a better prior and improves again. The value is trained towards the real game result , a Monte Carlo target for the current policy (as in lesson 04).
AlphaZero as approximate policy iteration. Compare with lesson 02:
| Policy iteration | AlphaZero |
|---|---|
| policy improvement: | MCTS with the current network gives , a better policy |
| policy evaluation: compute | train towards the self-play results |
| exact, all states | approximate, only the states that self-play visits |
AlphaZero as imitation. The search is the expert and the network is the student; this is expert iteration (Anthony, Tian and Barber, 2017). The student is trained on the states that it reaches in its own games, with labels from the expert: exactly the DAgger recipe, so there is no distribution shift. And unlike a human expert, this expert gets better every time the student does.
What is AlphaZero's policy head trained to match?
The loss term is the cross-entropy from the search policy (visit counts, with temperature ) to . The search is stronger than the raw network, so this is policy improvement. AlphaZero uses no human games (AlphaGo in 2016 started from human games). The highest- move ignores how much the search trusts each estimate.
MuZero and Dreamer: planning in a learned latent space
MuZero (Schrittwieser et al., 2020) does not get the rules. It learns three functions: a representation that maps the observations to a latent state, a dynamics function that maps a latent state and an action to the next latent state and a reward, and a prediction function that gives a policy and a value from a latent state. MCTS runs in the latent space with as the model. The model is trained to predict, steps ahead, the rewards, the values and the search policies, not the observations. So it only needs to model what matters for planning. MuZero matched AlphaZero in Go, chess and shogi and set a new state of the art on Atari at the time.
Dreamer (Hafner et al., 2020) learns a recurrent latent world model from pixels, then trains an actor and a critic only on imagined latent rollouts of the model, by backpropagating value estimates through the learned dynamics. Real data is used only to train the world model. DreamerV3 uses one set of hyperparameters across many domains and collected diamonds in Minecraft from scratch.
Answers to section 1. (1) About 3 episodes. The first episode is a long random walk for both, because all values are 0. After that, Dyna-Q's planning updates spread the goal's value over the whole maze, while Q-learning moves it back about one cell per episode (the figure in section 2). (2) Move 3: its UCT score is , larger than for move 1 (section 4 has all the numbers). (3) Much more: about 2.47 steps, 25 times more. One mistake leaves the road for the rest of the episode, so the cost grows like (section 4).
4. Worked example #
(a) One MCTS node: UCT and PUCT. The node has visits and three children with = (10, 0.6, 0.5), (8, 0.5, 0.3), (2, 0.2, 0.2). We need and .
UCT with :
| child | bonus | score + bonus | |
|---|---|---|---|
| 1 | 0.774 | 0.6 + 0.774 = 1.374 | |
| 2 | 0.865 | 0.5 + 0.865 = 1.365 | |
| 3 | 1.731 | 0.2 + 1.731 = 1.931 |
UCT explores child 3, the one with few visits.
PUCT with , bonus :
| child | bonus | score |
|---|---|---|
| 1 | 0.6 + 0.305 = 0.905 | |
| 2 | 0.5 + 0.224 = 0.724 | |
| 3 | 0.2 + 0.447 = 0.647 |
PUCT picks child 1. The prior of child 3 is small, so its bonus is small too: the network's prior decides where the search explores.
Policy target. The visit shares are with . With we square the counts: . With we get .
(b) A backup with the sign flip. Your move B has , (). The opponent's reply B2 has , ( for the opponent). An iteration selects root → B → B2, and the playout ends with (you lose).
- B is your move: , , .
- B2 is the opponent's move: , , . B2 now looks better for the opponent, so the selection at B is more likely to pick it again.
- The root gets .
(c) Behaviour cloning vs DAgger on a narrow road. steps, error rate per step. A wrong action drives the car off the road; the cloned policy has never seen off-road states and never comes back; every step off the road costs 1.
- The car is off the road after step if any of the first actions was wrong: probability .
- Expected cost: . For small , , so the sum is about . Both are below the bound .
- With DAgger the data also contains off-road states, labelled with the expert's recovery action. If one mistake costs one extra step (), the expected extra cost is at most : 25 times less. The gap grows with : for BC costs 9.46 and DAgger about 0.2.
(d) Compounding model error. True dynamics , model , both from . One step: , about 1%. After steps the relative error is :
- : ;
- : , while .
(e) Two Dyna-Q updates by hand. In the maze, , , all . Call the cell just below G and the cell below . The first episode ends with the step "up" from into G, reward 1. Direct RL: . Now a planning step replays the stored transition with reward 0: . Without the model, this second value would have to wait for the next real visit to .
5. In code #
NumPy checks the numbers of the worked example. The notebook has these cells, the Dyna maze, CEM planning, UCT for tic-tac-toe, and the exercises.
import numpy as np
# (a) one MCTS node: N(s) = 20, children (N, Q, P)
N_s = 20
N = np.array([10, 8, 2]); Q = np.array([0.6, 0.5, 0.2]); P = np.array([0.5, 0.3, 0.2])
uct = Q + np.sqrt(2) * np.sqrt(np.log(N_s) / N)
puct = Q + 1.5 * P * np.sqrt(N_s) / (1 + N)
print(uct.round(3), uct.argmax()) # [1.374 1.365 1.931] 2
print(puct.round(3), puct.argmax()) # [0.905 0.724 0.647] 0
for tau in (1.0, 0.5):
pi = N ** (1 / tau) / np.sum(N ** (1 / tau))
print(tau, pi.round(3)) # 1.0 [0.5 0.4 0.1] 0.5 [0.595 0.381 0.024]
# (c) behaviour cloning vs DAgger on the road
T, eps = 50, 0.002
t = np.arange(1, T + 1)
print(np.sum(1 - (1 - eps) ** t), eps * T * (T + 1) / 2, eps * T**2, eps * T)
# 2.4687 2.55 5.0 0.1
# (d) compounding model error: true a = 1.05, model 1.06
for H in (1, 10, 50):
print(H, (1.06 / 1.05) ** H - 1, H * (1.06 / 1.05 - 1))
# 1 0.0095 0.0095 10 0.0994 0.0952 50 0.6063 0.4762
6. Where it shows up #
- Board games. AlphaGo (2016) used MCTS with policy and value networks and rollouts, trained first on human games. AlphaGo Zero (2017) and AlphaZero (2018) removed the human data and the rollouts. MuZero (2020) also removed the rules. KataGo and Leela Chess Zero are open-source AlphaZero-style engines.
- Search for algorithms and molecules. AlphaTensor (matrix multiplication algorithms) and AlphaDev (sorting routines) use AlphaZero-style search with a policy and value network. Retrosynthesis planners search over chemical reactions with MCTS and neural networks.
- Robotics and control. MPC is standard in industry and robotics; with a learned model it becomes model-based RL (PETS, MBPO). Dreamer learns control tasks from pixels with few real samples. Robot policies learned from human demonstrations are behaviour cloning; their failures far from the demonstrated states are compounding error.
- LLMs. Supervised fine-tuning is behaviour cloning. On-policy distillation (the student generates, the teacher labels its tokens) applies the DAgger idea. Some reasoning systems search over partial solutions with tree search guided by a value or reward model.
- ML for science. Autoregressive emulators of weather, climate or fluids are rolled out for many steps, so they are often trained or fine-tuned with multi-step rollout losses. MPC with an emulator inherits model bias: check the multi-step error and whether the controller drives the system outside the training data.
7. Common mistakes #
- Running the whole MPC plan. Run only the first action, observe the real state, and plan again. The plan is only as good as the model, and noise adds up.
- Judging a model by its one-step error. Long open-loop rollouts can drift far; measure the error over the horizon that the planner uses.
- Trusting what the planner found. A plan that is much better in the model than in reality is a sign of model bias: the planner found the model's errors. Use ensembles, short rollouts or MPC.
- Forgetting the sign flip in a two-player backup. Then the opponent chooses the moves that are best for you, and the search plays as if the opponent helps.
- Playing the child with the highest . A child with two lucky visits can have a high ; play the most visited child.
- UCT's with the wrong value range. fits results in . With results in the range is twice as large, so should be larger (or rescale the results).
- "BC error is ." Only on the expert's states. On the learner's own states the error can compound to .
- DAgger without an expert to ask. DAgger needs expert labels for the learner's states; a fixed dataset of demonstrations is not enough.
- An old model in a changed world. Dyna plans with what the model remembers. If the environment changes, planning spreads wrong values until real experience corrects the model (Dyna-Q+ adds an exploration bonus for this).
8. Check yourself #
- Write the four steps of Dyna-Q at each real step.
Answer
Act ε-greedily and observe ; do a Q-learning update on the real transition; store ; do Q-learning updates on transitions replayed from the model at previously seen pairs. - Why does the open-loop error of a learned model grow faster than linearly in the horizon when the
dynamics expand nearby states?
Answer
Each step adds the new one-step error and also multiplies the old error by up to : . Unrolled, , which is geometric in . - A node has and two children: (N = 40, Q = 0.55) and (N = 10, Q = 0.45). Compute the UCT
scores with . Which child is selected?
Answer
. Child 1: . Child 2: . Child 2 is selected. - In AlphaZero, which quantity is the target of the value head, and which of the policy head?
Answer
Value head: the game result from the view of the player to move. Policy head: the MCTS visit-count distribution at the root (with temperature ). - Why is DAgger's extra cost linear in while BC's can be quadratic?
Answer
BC is trained only on the expert's states, so after a mistake the learner is in states without labels and may never recover: up to cost per mistake. DAgger adds expert labels for the states the learner visits, so its training and test distributions match and each mistake costs a bounded amount (), giving . - Name one reason why model-based RL often reaches a worse final performance than model-free RL, and
one method that reduces the problem.
Answer
Model bias: the planner exploits model errors, and compounding error limits long rollouts. MBPO uses an ensemble and short rollouts from real states; MPC replans from the real state at every step.
What does Dyna-Q do after each real step?
One Q-learning update on the real transition, store , then Q-learning updates on transitions replayed from the model.
What is model-predictive control (receding horizon)?
At every step, plan an action sequence in the model, run only its first action, observe the real next state, and plan again.
Bound the open-loop error after steps for one-step model error and -Lipschitz dynamics.
.
Write the UCT selection rule.
, with unvisited children first; it is UCB1 at every node.
Write the PUCT selection rule of AlphaZero.
, where is the network's prior.
Give the four phases of one MCTS iteration in one sentence.
Select down the tree with a bandit rule, expand a new node, evaluate it (playout or value network), and back up the result along the path.
Write AlphaZero's loss.
: value error to the game result, cross-entropy to the MCTS visit distribution, weight decay.
What is the extra-cost bound of behaviour cloning, and why is it quadratic?
: about first mistakes can happen, and each can cost up to steps in states the data does not cover.
What is the idea of DAgger?
Run the learner, ask the expert for the right action in the states the learner visits, add them to the data and retrain; the extra cost becomes linear in .
What does MuZero's model predict, and what does it not predict?
Rewards, values and search policies from a learned latent state, a few steps ahead; it does not predict observations.
9. Interview angle #
- "Model-based or model-free?" — Model-based is more sample-efficient because each sample is reused in planning; model-free often wins at the end because it does not suffer from model bias. Mention short rollouts (MBPO), ensembles and MPC.
- "Explain MCTS." — Four phases; UCT = UCB1 per node; play the most visited move; sign flip for two players. Know one UCT computation by heart.
- "How does AlphaZero train?" — Self-play with PUCT search; targets ; loss ; MCTS is policy improvement, so the loop is approximate policy iteration; no human data.
- "What is the problem with behaviour cloning?" — Distribution shift: compounding error . Fixes: DAgger (needs a queryable expert), noise injection and recovery data, or RL fine-tuning.
- "How is SFT related to RL?" — SFT is behaviour cloning; RLHF then optimises a reward with a KL constraint to the SFT policy (lesson 09).
- "Why would a planner do badly with a model that has a low test error?" — Low one-step error on the data distribution says nothing about long rollouts or about states the planner drives into.
10. Practice #
The notebook for this lesson runs in Colab. It has five exercises, each with a check cell and a folded solution:
- Dyna-Q vs Q-learning on the Dyna maze: implement
dyna_qand compare . - Plan with a learned model: fit a linear model by least squares and implement CEM planning with MPC; compare the true and the learned model.
- UCT and PUCT scores: implement
uct_scoresandpuct_scoresand check them on the worked example. - UCT for tic-tac-toe: implement MCTS with random playouts and the sign flip; it must find a win in one move, block a threat, and beat a random player in almost every game.
- Behaviour cloning vs DAgger on the toy road: implement the DAgger loop and compare the costs as grows.
11. Watch and read #
- Sutton and Barto, Reinforcement Learning: An Introduction, 2nd ed., free PDF: chapter 8 (§8.1–8.4 models, Dyna and prioritized sweeping; §8.11 MCTS).
- Kocsis and Szepesvári, Bandit based Monte-Carlo Planning (UCT), 2006.
- Silver et al., Mastering Chess and Shogi by Self-Play with a General Reinforcement Learning Algorithm (AlphaZero), 2017.
- Anthony, Tian and Barber, Thinking Fast and Slow with Deep Learning and Tree Search (expert iteration), 2017.
- Schrittwieser et al., Mastering Atari, Go, Chess and Shogi by Planning with a Learned Model (MuZero), 2019.
- Ross, Gordon and Bagnell, A Reduction of Imitation Learning and Structured Prediction to No-Regret Online Learning (DAgger), §2–3.
- Ross and Bagnell, Efficient Reductions for Imitation Learning (the bound), 2010.
- Janner, Fu, Zhang and Levine, When to Trust Your Model: Model-Based Policy Optimization (MBPO).
- Chua, Calandra, McAllister and Levine, Deep Reinforcement Learning in a Handful of Trials using Probabilistic Dynamics Models (PETS).
- Hafner, Lillicrap, Ba and Norouzi, Dream to Control: Learning Behaviors by Latent Imagination (Dreamer).
Runs in your browser with nothing to install. The notebook repeats the key demos and has exercises with checks; solutions are inside, folded.
No Google account needed: Python runs inside your browser. The first start downloads about 40 MB; your changes are saved in this browser only.