Skip to content
Reinforcement learning Advanced 31 min read

Model-based RL and planning: AlphaZero, MuZero

A model of the world lets an agent think before it acts: imagine what each action would lead to, and learn from experience it never had. Planning turns computation into competence. AlphaZero showed how far that goes when search and learning improve each other; MuZero showed the model itself can be learned, and need only predict what matters for deciding.

10,000 ft

Everything so far on this track has been model-free: Q-learning and actor-critic learn values and policies straight from experience and never ask what will happen next. Model-based RL learns, or is given, a model \(\hat p(s', r\mid s,a)\) and uses it to plan: compute better decisions without new real data. Dynamic programming is planning with a perfect model; chess engines plan with the rules and a hand-written evaluation. The modern story joins planning to learning: Dyna (1990) replays imagined transitions; Monte Carlo tree search (2006) made computer Go competitive; AlphaGo (2016) beat Lee Sedol; AlphaZero (2017) learned chess, shogi and Go from the rules alone; MuZero (2019) learned the rules too; Dreamer learns behaviour entirely inside a learned world model. Search reappears in language models as test-time compute, in AlphaProof's Lean proofs, and as an open question for reasoning models. Sutton's Bitter Lesson names search and learning as the two general methods that keep scaling with compute; this page is where they meet.

2,000 ft

A model can be used in two places, and the best systems use both.

  • Background planning: generate simulated experience from the model and learn from it as if it were real (Dyna, Dreamer, MBPO). The model multiplies your data.
  • Decision-time planning: at each real step, search forward from the current state with the model and act on the result (model-predictive control, Monte Carlo tree search). The model multiplies your thinking.
  • Search as a teacher (AlphaZero, MuZero): search at decision time with a network as guide, then train the network to predict the search's result. The network gets better, so the next search gets better: policy iteration, with search as the improvement step.

Learning and planning in one loop (after Sutton's Dyna)
Learning and planning in one loop (after Sutton's Dyna). Real environment, Real experience (s, a, r, s′), Model p̂(s′, r | s, a), Planning: simulated experience or tree search, Value / policy, Acting, model learning, direct RL, indirect RLLearning and planning in one loop (after Sutton's Dyna). Real environment, Real experience (s, a, r, s′), Model p̂(s′, r | s, a), Planning: simulated experience or tree search, Value / policy, Acting, model learning, direct RL, indirect RL

Ground level

What a model buys, and what it costs

A model predicts the environment's response: a distribution model gives \(\hat p(s',r\mid s,a)\); a sample model (a simulator) just produces one plausible \((s', r)\). With either, you can generate experience without acting. Three things follow.

  • Sample efficiency. Real interaction is the scarce resource for a robot, a patient, or a customer. Simulated interaction costs only compute. In the maze below, the same real experience gives a near-optimal policy within 5 episodes with planning, against dozens without.
  • Look-ahead. A policy network answers "what do I usually do here?". A search answers "what happens if I do this, here, now?", computation targeted at the one state that matters.
  • Reuse. A model of the dynamics serves any reward. Change the goal and you can re-plan without re-learning how the world works.

The cost is model error, and it compounds. Take a two-dimensional system whose true dynamics rotate the state 10° and shrink it by 1% per step, and a learned model that rotates by 10.5° and shrinks by 0.5%, under 1% wrong per step. Roll both forward:

import numpy as np
# A learned model that is almost right: true dynamics rotate the state by 10 degrees and shrink it 1%
# per step; the model rotates by 10.5 degrees and shrinks it 0.5%. One-step error: under 1%.
def M(deg, gain):
    t = np.radians(deg); return gain * np.array([[np.cos(t), -np.sin(t)], [np.sin(t), np.cos(t)]])
A_true, A_model = M(10, 0.99), M(10.5, 0.995)
x = y = np.array([1.0, 0.0])
for k in range(1, 51):
    x, y = A_true @ x, A_model @ y
    if k in (1, 5, 10, 20, 50):
        print(f"{k:2d}-step rollout: relative error {np.linalg.norm(x - y) / np.linalg.norm(x):6.1%}")
 1-step rollout: relative error   1.0%
 5-step rollout: relative error   5.1%
10-step rollout: relative error  10.3%
20-step rollout: relative error  21.2%
50-step rollout: relative error  56.8%

The error grows roughly linearly here and much faster in chaotic or contact-rich systems. Worse, a planner is an optimiser, and an optimiser seeks out the model's errors: if the model wrongly believes some action sequence pays well, search will find that sequence. It is the maximisation bias of Q-learning in a new form. The remedies recur below: short rollouts, uncertainty estimates (ensembles), re-planning at every real step, and models that predict only what decisions need.

Dyna: learn from real and imagined experience

Sutton's Dyna architecture (1990) is the simplest way to use a learned model. After each real step, do three things: an ordinary model-free update from the real transition, record the transition in the model, and then perform \(n\) planning updates on transitions recalled from the model at previously visited state–action pairs. With a table and Q-learning, that is Dyna-Q:

  1. Act ε-greedily in \(s\); observe \(r, s'\).
  2. Direct RL: \(Q(s,a) \leftarrow Q(s,a) + \alpha[r + \gamma\max_{a'}Q(s',a') - Q(s,a)]\).
  3. Model learning: \(\text{Model}(s,a) \leftarrow (s', r)\) (deterministic world).
  4. Planning, \(n\) times: pick a previously seen \((\tilde s,\tilde a)\), look up \((\tilde s', \tilde r)\) from the model, apply the same Q-learning update.

On Sutton and Barto's 6 × 9 maze (Example 8.1), with identical real experience:

020040060080021020304050episodesteps per episoden = 0 planning steps (plain Q-learning)n = 5 planning stepsn = 50 planning steps
Dyna-Q on the Dyna maze (Sutton and Barto, Example 8.1), averaged over 30 runs from the code in Build it. Every agent sees exactly the same real experience; the only difference is how many simulated updates it replays from its learned model after each real step. The shortest path is 14 steps.
n =  0 planning steps: steps in episode 2 =  573.0, episode 5 = 295.9, episode 10 = 109.0, episode 50 = 17.4
n =  5 planning steps: steps in episode 2 =  170.4, episode 5 =  27.1, episode 10 =  17.6, episode 50 = 16.6
n = 50 planning steps: steps in episode 2 =   37.8, episode 5 =  17.0, episode 10 =  17.0, episode 50 = 16.1

Why it works so well: in episode 1 the agent finds the goal once, and Q-learning updates only the last state before the goal. Every later episode must propagate that value one step further back. With 50 planning updates per real step, the model replays the whole remembered maze and pushes value back along the path within the second episode. The data are the same; the compute per datum is 51 times larger.

Two refinements from the same chapter of Sutton and Barto: prioritised sweeping (spend planning updates where values just changed, working backwards from them, instead of uniformly), and Dyna-Q+ (add an exploration bonus \(\kappa\sqrt{\tau}\) for transitions not tried for \(\tau\) steps, so the agent notices when the world has changed and its model is stale).

Decision-time planning and model-predictive control

Background planning improves a policy everywhere. Decision-time planning focuses all the computation on the current state: search forward through the model from \(s_t\), choose the best first action, execute it, observe the real next state, and search again from there. Re-planning at every step means the model only needs to be right a few steps ahead, and the real world corrects the rest. In control engineering this is model-predictive control (MPC). Chua et al.'s PETS (2018) learned an ensemble of probabilistic neural-network dynamics models (the spread of the ensemble estimates the model's uncertainty) and planned with the cross-entropy method at every step. On the half-cheetah task it matched model-free asymptotic performance with 8 times fewer samples than SAC and 125 times fewer than PPO.

In games, the model is the rules, and the problem is purely computational: the game tree is far too big to search exhaustively (Go has roughly 250 legal moves per position). Monte Carlo tree search builds an asymmetric tree, spending simulations on promising lines. Each simulation has four phases:

  1. Select: from the root, descend by repeatedly choosing the child with the best score, a balance of how good it has looked and how little it has been tried.
  2. Expand: at a leaf, add a new child node.
  3. Evaluate: estimate the new node's value, originally by a random playout to the end of the game, in AlphaZero by a value network.
  4. Back up: add the result to the statistics of every node on the path (with the sign flipped at each ply for two-player games).

After the budget is spent, play the most-visited root move. Kocsis and Szepesvári's UCT (2006) treats the choice at each node as a multi-armed bandit and applies the UCB1 rule from bandits:

\[ a = \arg\max_a\ \Big[\, \bar Q(s,a) + c\sqrt{\frac{\ln N(s)}{N(s,a)}}\ \Big]. \]

Worked example: one UCT selection

A node visited \(N = 100\) times has three children: A with mean value 0.6 over 60 visits, B with 0.5 over 30, C with 0.2 over 10. With \(c = 1.4\), the exploration bonuses are \(1.4\sqrt{\ln 100/n}\) = 0.388, 0.549, 0.950, so the scores are 0.988, 1.049, 1.150. UCT descends into C, the worst-looking but least-tried child. If C's next results are poor its \(\bar Q\) stays low while its bonus shrinks, and the search returns to A. Every move is tried infinitely often in the limit, and visits concentrate on the best move.

The evaluator turns out to be everything. In Build it, MCTS plays Nim (a pile of stones, take 1–3, taking the last stone wins; the winning move is always to leave a multiple of 4) on every winning position from 5 to 23 stones, once with random-playout evaluation and once with a "value network" that is simply wrong about 30% of positions:

    0 sims: winning move found  random rollouts    n/a   noisy value net  56.2%
   10 sims: winning move found  random rollouts  34.2%   noisy value net  63.4%
  100 sims: winning move found  random rollouts  50.2%   noisy value net  74.9%
 1000 sims: winning move found  random rollouts  66.5%   noisy value net  79.4%

Two lessons from four lines. Random playouts are a weak evaluator in deep games: even 1,000 simulations find the winning move only two times in three. And search amplifies a flawed evaluator: on its own, the 70%-accurate network picks the right move 56% of the time; wrapped in 1,000 simulations, 79%. The search compares many positions, and the network's errors on different positions partly cancel. That is the core of AlphaGo.

AlphaGo, AlphaGo Zero, AlphaZero

AlphaGo (Silver et al., 2016) combined MCTS with two deep networks: a policy network, trained first by supervised learning on human expert games and then by self-play policy gradient, to propose moves (the search's prior), and a value network, trained on self-play outcomes, to evaluate positions, mixed with fast rollouts. It won 99.8% of games against other Go programs, beat the European champion Fan Hui 5–0, the first defeat of a human professional on a full board, and in March 2016 beat Lee Sedol 4–1.

AlphaGo Zero (2017) removed the human data, the rollouts and the hand-crafted input features: one residual network with a policy head and a value head, trained only by self-play, starting from random play. It beat the version that defeated Lee Sedol 100–0. AlphaZero (Silver et al., 2017; Science 2018) generalised the same algorithm to chess and shogi as well as Go, with no game-specific changes beyond the rules and input/output encodings.

AlphaZero: search improves the network, the network improves the search
AlphaZero: search improves the network, the network improves the search. Network f_θ(s) → (p, v), MCTS, 800 simulations guided by p, evaluated by v, Search policy π (visit counts), Self-play game moves sampled from π, Outcome z ∈, Training data (s, π, z), Loss (z − v)² − πᵀ log p + c‖θ‖², gradient stepAlphaZero: search improves the network, the network improves the search. Network f_θ(s) → (p, v), MCTS, 800 simulations guided by p, evaluated by v, Search policy π (visit counts), Self-play game moves sampled from π, Outcome z ∈, Training data (s, π, z), Loss (z − v)² − πᵀ log p + c‖θ‖², gradient step

The loop, precisely: for each position of a self-play game, run MCTS guided by the current network; play a move sampled from (or, later, the argmax of) the root's visit-count distribution \(\pi\); at the end of the game record the outcome \(z\) for every position; train the network so that \(p\) moves toward \(\pi\) (cross-entropy) and \(v\) toward \(z\) (squared error). Look at what each half does. MCTS is a policy-improvement operator: its visit distribution is a better policy than the raw network prior, because it has looked ahead. Training is policy evaluation and distillation: \(v\) learns the value of the improved policy, and \(p\) learns to produce, in one forward pass, what search found with 800. This is policy iteration, with search for the improvement step and a network for the representation. Anthony et al. independently described the same scheme as expert iteration (2017): the search is the expert, the network the apprentice.

The numbers from the AlphaZero preprint: 800 simulations per move during training; Dirichlet noise added to the root prior for exploration, with \(\alpha\) = 0.3, 0.15 and 0.03 for chess, shogi and Go (scaled inversely with the typical number of legal moves); 700,000 training steps on mini-batches of 4,096 positions; 5,000 first-generation TPUs generating self-play games and 64 second-generation TPUs training. It surpassed Stockfish after 4 hours (300k steps), Elmo after under 2 hours, and AlphaGo Lee after 8 hours. In a 100-game match against Stockfish it won 28 games, drew 72, and lost none, while searching about 80 thousand positions per second against Stockfish's 70 million. It examines a thousand times fewer positions, and the network's judgement makes up the difference.

The selection rule is PUCT, UCB with the network's prior \(P(s,a)\) in the exploration term. In MuZero's form:

\[ a = \arg\max_a\ \Big[\, Q(s,a) + P(s,a)\,\frac{\sqrt{N(s)}}{1 + N(s,a)}\Big(c_1 + \log\frac{N(s) + c_2 + 1}{c_2}\Big) \Big], \qquad c_1 = 1.25,\ c_2 = 19{,}652 . \]

The prior decides where to look; the visit counts decide how long. With the same three children as the UCT example and priors (0.6, 0.3, 0.1), the bonuses are 0.123, 0.121 and 0.114, the scores 0.723, 0.621 and 0.314, and search goes back to A. The network has said C is not worth exploring, and at \(N = 100\) the prior still outweighs C's small visit count. In Go, with about 250 legal moves, that pruning is what makes 800 simulations enough.

MuZero: planning with a learned model

AlphaZero needs a perfect simulator: the rules. Most of the world has none. MuZero (Schrittwieser et al., 2019; Nature 2020) learns a model and searches inside it, with three functions:

  • representation \(s^0 = h_\theta(o_1,\dots,o_t)\): encode the observations into a hidden state;
  • dynamics \(r^k, s^k = g_\theta(s^{k-1}, a^k)\): predict the reward and next hidden state;
  • prediction \(p^k, v^k = f_\theta(s^k)\): policy and value from a hidden state, as in AlphaZero.
MuZero unrolls a learned model K steps and trains every prediction
MuZero unrolls a learned model K steps and trains every prediction. Observations o_1 … o_t, h (representation), s⁰, g (dynamics), s¹, s², f (prediction) at each sᵏ → policy pᵏ, value vᵏ, rewards r¹, r², …MuZero unrolls a learned model K steps and trains every prediction. Observations o_1 … o_t, h (representation), s⁰, g (dynamics), s¹, s², f (prediction) at each sᵏ → policy pᵏ, value vᵏ, rewards r¹, r², …

Training samples a trajectory from a replay buffer, unrolls the model for \(K = 5\) steps along the actions actually taken, and penalises, at every step, the predicted reward against the real reward, the predicted value against an \(n\)-step return (or the game outcome), and the predicted policy against the search policy that MCTS produced when that move was played. Nothing asks \(s^k\) to resemble a real state or to reconstruct the screen. The hidden state only has to support correct predictions of reward, value and policy. This is the value-equivalence idea: two models that give the same values for every policy are equally good for planning, whatever they say about pixels (Grimm et al., 2020, formalise it).

Results (Schrittwieser et al., Table 1): on the 57 Atari games, a median human-normalised score of 2,041% and mean 4,999% after 20 billion frames, against R2D2's 1,921% and 4,025% after 37.5 billion, with 50 simulations per move; on Go, chess and shogi, with 800 simulations, it matched AlphaZero's superhuman performance without being given the rules. The sample-efficient variant MuZero Reanalyze, which re-runs search on old trajectories with the latest network to refresh their targets, reached a 731% median with 200 million frames, against 231% for Rainbow. EfficientZero (Ye et al., 2021) pushed the same design to the Atari 100k benchmark, two hours of play per game: 194.3% mean and 109.0% median human-normalised score.

Learning in imagination: World Models, Dreamer, MBPO

The other branch uses a learned model for background planning: train the policy on imagined trajectories. Ha and Schmidhuber's World Models (2018) compressed frames with a VAE, predicted the next latent with a recurrent network, and trained a small controller entirely inside that "dream". Hafner's Dreamer line learns a recurrent latent-state model (the RSSM) from pixels and trains an actor-critic on large batches of imagined latent rollouts, never touching the real environment during policy updates. DreamerV3 (2023; Nature 2025) used one fixed configuration across more than 150 tasks and was the first algorithm to collect diamonds in Minecraft from scratch, without human data or curricula, a long sparse-reward exploration problem from pixels.

Janner et al.'s MBPO (2019) asked how far to trust the model. Their analysis bounds how model error accumulates with rollout length, and their algorithm uses short model rollouts branched from real states in the replay buffer, feeding them to SAC. Short branches keep the compounding error of the rotation example small while still multiplying the data. It matched the asymptotic performance of the best model-free methods with far fewer samples.

Planning with language models

A language model is a superb sample model of text, and reasoning is a sequential decision problem, so the planning toolkit carries over. Best-of-\(N\) sampling with a verifier is one level of search. Tree of Thoughts (Yao et al., 2023) ran breadth- and depth-first search over intermediate "thoughts", with the model evaluating its own partial solutions: on the Game of 24, GPT-4 with chain-of-thought prompting solved 4% of problems, with ToT 74%. AlphaProof (Hubert et al., Nature 2025) is an AlphaZero-inspired agent that searches for formal proofs in Lean, trained by RL on millions of auto-formalised problems; with AlphaGeometry 2 it reached silver-medal standard at the 2024 International Mathematical Olympiad.

But the 2025 reasoning models mostly did not use explicit tree search. DeepSeek reported trying an AlphaZero-style MCTS over reasoning steps and abandoning it: the token-level search space is exponentially larger than a board game's, and "training a fine-grained value model is inherently difficult", so iterative self-improvement through search did not scale (DeepSeek-AI, 2025, section 4.2). What scaled instead was RL that teaches the model to search inside one long chain of thought (proposing, checking, backtracking), covered in RL with verifiable rewards. AlphaGo's lesson that search is only as good as its evaluator explains both outcomes: where a perfect verifier exists (Lean, a game's rules), explicit search wins; where values must be learned over free text, it has so far lost to learned, implicit search.

History

Arthur Samuel's checkers program (1959) already had the two halves: look-ahead search, and an evaluation function that improved by playing itself. Sutton's Dyna (1990) gave the unified view of learning and planning used on this page. Computer Go resisted alpha-beta search until Coulom's Crazy Stone and Kocsis and Szepesvári's UCT (both 2006) introduced Monte Carlo tree search, which lifted programs to strong amateur level within a few years. DeepMind's AlphaGo (2016), AlphaGo Zero (2017), AlphaZero (2017–18) and MuZero (2019–20) followed. In parallel, the robotics and continuous-control community developed learned-model methods: PILCO's Gaussian processes, then neural ensembles (PETS, MBPO) and latent world models (PlaNet, Dreamer). From 2023 the question moved to language: how much a model gains from thinking longer, and whether that thinking should be explicit search or learned behaviour.

First principles

Why planning can beat a bigger network. A policy network amortises: one set of weights must answer for every state, so its capacity is spread thin. Search spends computation on the one state you are in and checks its conclusions against a model, so its errors are local and correctable. The Nim experiment shows the effect with a toy evaluator; AlphaZero's 80 thousand positions per second beating Stockfish's 70 million shows it at scale, with the roles reversed: less search, a much better evaluator.

Why MCTS-plus-training converges to something good. Each self-play iteration does two things that dynamic programming does: improve the policy using look-ahead with the current value estimates (the search), and evaluate the improved policy (training \(v\) on outcomes \(z\)). Policy iteration converges because each step is an improvement and evaluation tracks it. With function approximation and sampled search, there is no such proof, but the structure is why the loop is stable in practice, far more stable than the self-play of earlier methods.

Why a learned model's errors hurt more than they look. Planning maximises over the model's predictions, so it selects the actions on which the model is optimistic, including wrongly optimistic ones. The expected error of the chosen plan is therefore larger than the model's average error: the optimiser's curse, the same mechanism as Q-learning's maximisation bias. Ensembles help by measuring disagreement, and re-planning helps by checking the model against reality at every step.

Why value equivalence is enough. The quantity a planner compares across actions is the value. If a model predicts rewards and values correctly for every action sequence the search will consider, the planner's decisions are exactly those it would make with the true model. Detail the value does not depend on (the background of an Atari screen) can be dropped, which frees model capacity for what matters.

Why exploration at the root. Self-play can lock into a narrow repertoire, because the network trains only on positions its own search reaches. AlphaZero adds Dirichlet noise to the root prior so that every legal move is sometimes searched seriously. It is the bandit lesson again: without exploration, a learner cannot discover that an untried option is better.

The maths

Model learning. Fit \(\hat p_\psi\) by maximum likelihood on real transitions, \(\max_\psi \sum_{(s,a,r,s')}\log\hat p_\psi(s',r\mid s,a)\); for a deterministic Gaussian model this is mean-squared error on \((s', r)\). MuZero instead minimises

\[ \ell_t(\theta) = \sum_{k=0}^{K}\Big[\ell^{r}\big(u_{t+k}, r^{k}_t\big) + \ell^{v}\big(z_{t+k}, v^{k}_t\big) + \ell^{p}\big(\pi_{t+k}, p^{k}_t\big)\Big] + c\,\|\theta\|^2, \]

with \(u\) the real rewards, \(z_{t+k} = u_{t+k+1} + \gamma u_{t+k+2} + \dots + \gamma^{n-1}u_{t+k+n} + \gamma^n \nu_{t+k+n}\) an \(n\)-step return bootstrapped from the search value \(\nu\) (or the game outcome), \(\pi\) the MCTS visit distribution, cross-entropy for \(\ell^p\), and (in Atari) cross-entropy over a categorical representation of \(r\) and \(v\). AlphaZero's loss is the \(K = 0\) case with no reward term: \((z - v)^2 - \pi^\top\log p + c\|\theta\|^2\).

Derivation: the simulation lemma (how model error becomes value error)

Let the true and learned models share rewards, and let \(\|p(\cdot\mid s,a) - \hat p(\cdot\mid s,a)\|_1 \le \epsilon\) for all \((s,a)\). Fix a policy \(\pi\) and write \(P, \hat P\) for its state-transition matrices. The Bellman equations give \(V = r + \gamma PV\) and \(\hat V = r + \gamma\hat P\hat V\). Subtract and add \(\gamma\hat P V\):

\[ V - \hat V = \gamma (P - \hat P)V + \gamma\hat P (V - \hat V). \]

Take max norms. Each row of \((P - \hat P)V\) is at most \(\|p - \hat p\|_1\|V\|_\infty \le \epsilon\|V\|_\infty\), and \(\hat P\) is a stochastic matrix, so \(\|\hat P x\|_\infty \le \|x\|_\infty\):

\[ \|V - \hat V\|_\infty \le \gamma\epsilon\|V\|_\infty + \gamma\|V - \hat V\|_\infty \quad\Longrightarrow\quad \|V - \hat V\|_\infty \le \frac{\gamma\epsilon\|V\|_\infty}{1-\gamma} \le \frac{\gamma\epsilon R_{\max}}{(1-\gamma)^2}. \]

The horizon enters squared: once because errors accumulate over \(\sim 1/(1-\gamma)\) steps, and once because each error is multiplied by values of size up to \(R_{\max}/(1-\gamma)\). With \(\gamma = 0.99\), a 1% model error can mean value errors of order \(R_{\max}\) times 99. Planning with the learned model then loses at most twice this bound relative to the best policy (apply it to both the learned model's optimal policy and the true optimum).

UCT (above) and PUCT (above, with the AlphaZero form \(Q + c_\text{puct}P\sqrt{N(s)}/(1 + N(s,a))\) using a constant in place of MuZero's slowly growing log term). UCB1's \(\sqrt{2\ln N/n}\) bonus comes from Hoeffding's inequality: with \(n\) samples of a \([0,1]\) reward, the probability that the true mean exceeds the empirical one by more than \(\sqrt{2\ln N/n}\) is at most \(N^{-4}\). Kocsis and Szepesvári proved that with a suitable constant, the probability of choosing a suboptimal root action under UCT goes to zero as simulations grow.

Root policy. After search, \(\pi(a\mid s) \propto N(s,a)^{1/\tau}\): \(\tau = 1\) samples in proportion to visits (exploration in self-play), \(\tau\to0\) is the argmax.

Dyna-Q. Real step: \(Q(s,a) \mathrel{+}= \alpha[r + \gamma\max_{a'}Q(s',a') - Q(s,a)]\). Then \(n\) times: sample a previously observed \((\tilde s,\tilde a)\), take \((\tilde s',\tilde r) = \text{Model}(\tilde s,\tilde a)\), apply the same update. With \(n = 0\) this is Q-learning; as \(n\to\infty\) between real steps it is value iteration on the empirical model.

Build it

NumPy. Part 1 is Dyna-Q on the Dyna maze; changing n_plan from 0 to 50 is the whole difference between model-free and model-based. Part 2 is Monte Carlo tree search (UCT) on Nim, with two evaluators. The model-error example is in Ground level.

import numpy as np
# Dyna-Q on the Dyna maze (Sutton & Barto, Example 8.1): 6 x 9 grid, walls, +1 at the goal, gamma 0.95.
H, W, START, GOAL = 6, 9, (2, 0), (0, 8)
WALLS = {(1, 2), (2, 2), (3, 2), (4, 5), (0, 7), (1, 7), (2, 7)}
MOVES = [(-1, 0), (1, 0), (0, -1), (0, 1)]
def step(s, a):
    r, c = s[0] + MOVES[a][0], s[1] + MOVES[a][1]
    if not (0 <= r < H and 0 <= c < W) or (r, c) in WALLS: r, c = s
    return (r, c), float((r, c) == GOAL)

def dyna_q(n_plan, episodes=50, alpha=0.1, gamma=0.95, eps=0.1, rng=None):
    Q, model, lengths = np.zeros((H, W, 4)), {}, []
    for _ in range(episodes):
        s, t = START, 0
        while s != GOAL:
            q = Q[s]; a = rng.integers(4) if rng.random() < eps else rng.choice(np.flatnonzero(q == q.max()))
            s2, r = step(s, a)
            Q[s][a] += alpha * (r + gamma * Q[s2].max() * (s2 != GOAL) - Q[s][a])   # (a) direct RL
            model[(s, a)] = (s2, r)                                                # (b) model learning
            keys = list(model)
            for i in rng.integers(len(keys), size=n_plan):                         # (c) planning
                (ps, pa), (ps2, pr) = keys[i], model[keys[i]]
                Q[ps][pa] += alpha * (pr + gamma * Q[ps2].max() * (ps2 != GOAL) - Q[ps][pa])
            s, t = s2, t + 1
        lengths.append(t)
    return np.array(lengths)

rng = np.random.default_rng(0)
for n in (0, 5, 50):
    L = np.mean([dyna_q(n, rng=rng) for _ in range(30)], axis=0)
    print(f"n = {n:2d} planning steps: steps in episode 2 = {L[1]:6.1f}, episode 5 = {L[4]:5.1f},"
          f" episode 10 = {L[9]:5.1f}, episode 50 = {L[49]:4.1f}")
n =  0 planning steps: steps in episode 2 =  573.0, episode 5 = 295.9, episode 10 = 109.0, episode 50 = 17.4
n =  5 planning steps: steps in episode 2 =  170.4, episode 5 =  27.1, episode 10 =  17.6, episode 50 = 16.6
n = 50 planning steps: steps in episode 2 =   37.8, episode 5 =  17.0, episode 10 =  17.0, episode 50 = 16.1
import numpy as np, math
# MCTS on Nim: a pile of n stones, players alternately remove 1-3, whoever takes the last stone wins.
# A pile divisible by 4 is lost for the player to move, so the winning move is to take n % 4.
rng = np.random.default_rng(0)
def rollout(n):                                    # random playout; +1 if the player to move wins
    sign = 1
    while True:
        n -= rng.integers(1, min(3, n) + 1)
        if n == 0: return sign
        sign = -sign

class Node:
    def __init__(self, n): self.n, self.N, self.W, self.kids = n, 0, 0.0, {}

def simulate(node, evaluate, c=1.4):               # returns the value for the player to move at node
    if node.n == 0: v = -1                         # the opponent took the last stone
    else:
        untried = [m for m in (1, 2, 3) if m <= node.n and m not in node.kids]
        if untried:                                # expand one child and evaluate it
            child = node.kids[untried[0]] = Node(node.n - untried[0])
            cv = -1 if child.n == 0 else evaluate(child.n)
            child.N += 1; child.W += cv; v = -cv
        else:                                      # select with UCB1, from this player's view
            m = max(node.kids, key=lambda k: -node.kids[k].W / node.kids[k].N
                    + c * math.sqrt(math.log(node.N) / node.kids[k].N))
            v = -simulate(node.kids[m], evaluate, c)
    node.N += 1; node.W += v
    return v

def best_move(n, sims, evaluate):
    root = Node(n)
    for _ in range(sims): simulate(root, evaluate)
    return max(root.kids, key=lambda m: root.kids[m].N), root

m, root = best_move(10, 2000, rollout)
print("pile 10, 2000 sims, rollouts: visits", {k: c.N for k, c in root.kids.items()},
      "values", {k: round(-c.W / c.N, 2) for k, c in root.kids.items()}, "(winning move: 2)")
piles = [n for n in range(5, 25) if n % 4]         # every position that has a winning move
def net():                                          # a "value network" wrong on 30% of positions
    truth = np.array([1.0 if n % 4 else -1.0 for n in range(25)])
    return np.where(rng.random(25) < 0.3, -truth, truth)
for sims in (0, 10, 100, 1000):
    acc_r = np.mean([best_move(n, sims, rollout)[0] == n % 4 for n in piles for _ in range(40)]) if sims else np.nan
    acc_v = []
    for _ in range(100):
        v = net()
        for n in piles:
            if sims == 0:                           # no search: trust the network one move ahead
                acc_v.append(min((1, 2, 3), key=lambda k: v[n - k] if n - k > 0 else -2) == n % 4)
            else:
                acc_v.append(best_move(n, sims, lambda x: v[x])[0] == n % 4)
    r = "   n/a" if sims == 0 else f"{acc_r:6.1%}"
    print(f"{sims:5d} sims: winning move found  random rollouts {r}   noisy value net {np.mean(acc_v):6.1%}")
pile 10, 2000 sims, rollouts: visits {1: 4, 2: 1975, 3: 21} values {1: -1.0, 2: 0.93, 3: -0.14} (winning move: 2)
    0 sims: winning move found  random rollouts    n/a   noisy value net  56.2%
   10 sims: winning move found  random rollouts  34.2%   noisy value net  63.4%
  100 sims: winning move found  random rollouts  50.2%   noisy value net  74.9%
 1000 sims: winning move found  random rollouts  66.5%   noisy value net  79.4%

The AlphaZero search step, as most implementations write it (Python, schematic; net(s) returns a prior over legal moves and a value for the player to move):

import math

def puct_search(root_state, net, sims=800, c_puct=1.5):
    root = {"N": 0, "kids": {}}
    for _ in range(sims):
        node, state, path = root, root_state, [root]
        while node["kids"]:                                   # 1. select
            n_tot = math.sqrt(node["N"])
            a, node = max(node["kids"].items(), key=lambda kv: kv[1]["Q"]
                          + c_puct * kv[1]["P"] * n_tot / (1 + kv[1]["N"]))
            state = state.play(a); path.append(node)
        if state.is_over():
            v = state.score_for_player_to_move()
        else:                                                 # 2-3. expand and evaluate
            prior, v = net(state)
            node["kids"] = {a: {"N": 0, "W": 0.0, "Q": 0.0, "P": p, "kids": {}} for a, p in prior.items()}
        for n in reversed(path):                              # 4. back up, flipping sign each ply
            n["N"] += 1
            if n is not root:
                v = -v; n["W"] += v; n["Q"] = n["W"] / n["N"]
    return {a: k["N"] for a, k in root["kids"].items()}       # visit counts -> search policy π

Things to try

  • Part 1: after 25 episodes, open a shortcut in the maze wall. Dyna-Q, whose model never revisits the old wall, may never find it; add the Dyna-Q+ bonus \(\kappa\sqrt\tau\) and watch it adapt.
  • Part 1: replace uniform sampling of remembered pairs with prioritised sweeping and compare the number of planning updates needed.
  • Part 2: change the network's error rate from 30% to 10% and 45%. At what error rate does search stop helping?
  • Part 2: replace UCB1 with PUCT and give the network a prior that is right 70% of the time. How many simulations do you now need?
  • Close the loop: train a tabular "network" on Nim from MCTS visit counts and outcomes, AlphaZero style, starting from a uniform prior, and plot its accuracy by iteration.

Check yourself

What is the difference between background planning and decision-time planning? Give an algorithm for each.

Background planning uses the model to generate simulated experience that improves a value function or policy for all states (Dyna, Dreamer, MBPO). Decision-time planning uses the model to search forward from the current state to choose the current action, then discards most of the work (MPC, MCTS). AlphaZero does both: decision-time search whose results are distilled into the network.

In Dyna-Q on the maze, why does n = 50 reach a near-optimal path in about 5 episodes while Q-learning needs dozens?

Q-learning propagates value one step back per real visit, so a reward discovered at the goal takes many episodes to reach the start. Dyna-Q replays remembered transitions from its model 50 times per real step, propagating value along the whole remembered path within an episode or two, using the same real data.

Why does MCTS use UCB at each node rather than always descending into the best-looking child?

Values at a node are estimates from few simulations. Greedy descent would never revisit a move whose first evaluations were unlucky. UCB adds an exploration bonus that shrinks with visits, so every move keeps being tried while visits concentrate on the best; it is the bandit problem at every node.

In AlphaZero, what are the training targets for the policy head and the value head, and why is the policy target better than the network's own prior?

The policy head is trained toward the MCTS visit distribution \(\pi\), the value head toward the final game outcome \(z\). \(\pi\) is better than the prior \(p\) because the search looked ahead with \(p\) and \(v\) and concentrated visits on moves that held up: MCTS is a policy-improvement operator.

MuZero's model is never trained to reconstruct observations. Why can it still plan?

Planning only needs correct predictions of rewards, values and policies along candidate action sequences. MuZero's model is trained exactly on those, by unrolling \(K\) steps along real actions. Value-equivalent models give the same decisions as the true model even if their hidden states look nothing like real states.

Using the simulation lemma, why are long-horizon tasks especially sensitive to model error?

The value error bound is \(\gamma\epsilon R_{\max}/(1-\gamma)^2\). The effective horizon \(1/(1-\gamma)\) appears squared, so doubling the horizon roughly quadruples the worst-case value error for the same one-step model error. Hence short rollouts (MBPO), re-planning (MPC), and bootstrapping from a value function at the end of a search.

Hard: DeepSeek abandoned MCTS for reasoning. Which of AlphaZero's preconditions fail for text?

A small, well-defined action space (Go has about 250 moves; a reasoning step is an unbounded string), a perfect simulator (the rules; for text, the "transition" is trivial but the step boundaries are ill-defined), and a learnable, accurate value function (game outcomes are clean; estimating the probability that a partial proof will succeed is hard). Without an accurate value model, search amplifies its errors instead of correcting them.

Go deeper

Papers

Videos and lectures

Articles and blog posts

  • MuZero Intuition — Julian Schrittwieser, 2020. MuZero explained by its first author.
  • The Bitter Lesson — Rich Sutton, 2019. Why search and learning win in the long run.

Books and code

Where this leads