Skip to content

Model-based RL and planning: AlphaZero, MuZero, Dreamer

optionalcorefundamentalpaperrubric 11/122019 · arXiv 2019; Nature 588 (2020) · ~70 min

Julian Schrittwieser, Ioannis Antonoglou, Thomas Hubert, Karen Simonyan, Laurent Sifre, Simon Schmitt, Arthur Guez, Edward Lockhart, Demis Hassabis, Thore Graepel, Timothy Lillicrap, David Silver

Read first: Reinforcement Learning: An Introduction, Ch. 3–4 — Value Functions, Bellman Equations and Dynamic Programming · Reinforcement Learning: An Introduction, Ch. 5–6 — Monte Carlo, Temporal-Difference Learning and Q-learning · Actor–critic methods and the advantage function

Status

TL;DR. Most of the RL on the site so far is model-free: the agent learns values or a policy straight from experience (value iteration on the Bellman page is the exception: it plans with a supplied model). Model-based RL uses a model of the environment (what happens next, what reward you get), given or learned, to plan, i.e. to try actions in imagination before acting. This page builds the idea in five steps. Dyna replays imagined transitions from a learned model. MCTS with pUCT searches a tree of imagined futures, guided by a policy network (which moves look promising) and a value network (how good a position is). AlphaZero (Silver et al., 2017) trains those networks to imitate their own search, but needs the game rules as its model. MuZero (Schrittwieser et al., 2019), the primary source here, learns the model too, and the model predicts only what planning needs: reward, value and policy, never the next screen. DreamerV3 (Hafner et al., 2023; introduced in 2023, and the implementation details and results here follow the April 2024 arXiv v2 revision) learns a world model that does reconstruct observations and trains an actor–critic inside it, with one set of hyperparameters across over 150 tasks.

For LLM post-training, keep three distinctions: collecting real versus simulated experience; searching at inference time versus distilling search into a policy; and predicting observations versus predicting only decision-relevant quantities. Dyna, AlphaZero/MuZero and Dreamer illustrate different combinations, not a recipe to implement together.

Why it matters for you. Best-of-N, tree search over reasoning steps and LLM-simulated tools (ZeroSearch, Kimi K2’s tool simulator, DreamGym) are model-based ideas in LLM clothing. And the classic failure of model-based RL, a policy that exploits errors in its model, is exactly reward hacking against a simulator.

How to read it. First read: the model-free vs model-based paragraph, Dyna and its worked example, MCTS and the pUCT example, the MuZero loss, and the LLM section. Skip on a first read: MuZero’s min–max value normalisation and value transform, Reanalyze, Dreamer’s KL terms and free bits, and the symlog/twohot details. They matter for implementation, not for the idea.

A model is anything that answers “if I am in state ss and take action aa, what reward rr do I get and which state s′s' comes next?”. In the notation of the Bellman page, it is an estimate of p(s′,r∣s,a)p(s', r \mid s, a). Value iteration on that page assumed the model was given. MC, TD and Q-learning dropped it and learned from samples. Model-based RL learns the model from samples and then plans with it.

IR analogy. You have click logs and want a better ranker. The model-free route reweights logged clicks by inverse propensities (IPS) and optimises the ranker directly. The model-based route fits a click model (say a cascade model of how users scan and click) and then simulates users to train or evaluate new rankers cheaply. The second route is more sample-efficient and lets you ask “what if” questions, but every conclusion is only as good as the click model, and a ranker optimised hard against it will find where it is wrong.

2. Dyna: learn a model, then replay imagined steps

Section titled “2. Dyna: learn a model, then replay imagined steps”

Dyna (Sutton & Barto §8.2) adds one loop to Q-learning. After each real step (s,a,r,s′)(s, a, r, s'): (1) do the normal Q-learning update; (2) store (s,a)↦(r,s′)(s, a) \mapsto (r, s') in a model; (3) do nn extra planning updates, each on a previously seen (s,a)(s, a) whose outcome is looked up in the model instead of the world.

Worked example (search-or-answer MDP, from MDPs and returns). States Q (question only) and E (evidence retrieved); search costs −0.1 and moves to E; answer pays 1 with probability 0.3 from Q and 0.8 from E; γ = 0.9, step size α = 0.5, all Q-values start at 0. The agent sees one episode: search, then a correct answer.

  • Real update 1: Q(Q,search)←0+0.5 [−0.1+0.9×0−0]=−0.05Q(Q, \text{search}) \leftarrow 0 + 0.5\,[-0.1 + 0.9 \times 0 - 0] = -0.05.
  • Real update 2: Q(E,answer)←0+0.5 [1−0]=0.5Q(E, \text{answer}) \leftarrow 0 + 0.5\,[1 - 0] = 0.5.
  • One planning update on the stored (Q,search)↦(−0.1,E)(Q, \text{search}) \mapsto (-0.1, E): target −0.1+0.9×0.5=0.35-0.1 + 0.9 \times 0.5 = 0.35, so Q(Q,search)←−0.05+0.5×0.40=0.15Q(Q, \text{search}) \leftarrow -0.05 + 0.5 \times 0.40 = 0.15.

Pure Q-learning needed three real episodes to reach 0.15 on the MC/TD page; Dyna gets there with one real episode and one imagined update. That is the whole sales pitch: reuse a model to squeeze more learning out of each real interaction.

Now the catch. The model stored the one outcome it saw: “answering in E pays 1”. Keep planning (50 updates in the lab below) and the values converge to Q(E,answer)=1.0Q(E, \text{answer}) = 1.0 and Q(Q,search)=−0.1+0.9×1.0=0.8Q(Q, \text{search}) = -0.1 + 0.9 \times 1.0 = 0.8, while the true optimal values are 0.8 and 0.62. More planning converges to the wrong model’s values: it removes planning error but not model error. Here the final estimates are actually closer to the truth than the initial ones (search: error 0.67 → 0.18; answer: 0.3 → 0.2), but they are optimistic, and once an estimate passes the true value, further planning can increase its error again. The example shows biased values; it does not show a worse action being preferred (searching is still the right move). Keep this example in mind for the LLM section.

3. Monte Carlo tree search with the pUCT rule

Section titled “3. Monte Carlo tree search with the pUCT rule”

Dyna plans by replaying single steps. Monte Carlo tree search (MCTS) plans at decision time: before each real move it grows a tree of imagined futures from the current state, then picks the move the tree likes best. Each simulation walks down the tree, adds one new leaf, evaluates it, and passes the result back up. AlphaZero and MuZero use 800 simulations per move in board games; MuZero uses 50 in Atari.

Plain words first. At every node the search faces a bandit problem: spend the next simulation on the move that looks best so far (exploit), or on a move that has been tried little (explore)? pUCT answers with “value so far plus a bonus”, where the bonus is large for moves the policy network likes and that have few visits. It is the same idea as UCB-style exploration in online learning to rank: show the ranker you are unsure about until the data makes you sure.

The rule (MuZero Eq. 2). UCT means upper-confidence bounds applied to trees; pUCT adds the policy prior PP to the exploration term. Here QQ is an edge’s backed-up search estimate, not necessarily a separately trained Q-network. At a node in state ss, pick

a⋆=arg⁡max⁡a[ Q(s,a)+P(s,a) ∑bN(s,b)1+N(s,a)(c1+log⁡∑bN(s,b)+c2+1c2)],a^\star = \arg\max_a \Big[\, Q(s,a) + P(s,a)\,\frac{\sqrt{\sum_b N(s,b)}}{1 + N(s,a)}\Big(c_1 + \log\frac{\sum_b N(s,b) + c_2 + 1}{c_2}\Big) \Big],

where N(s,a)N(s,a) is how many simulations have taken action aa from this node, Q(s,a)Q(s,a) is the mean return those simulations backed up, P(s,a)P(s,a) is the policy network’s prior probability for aa, and c1=1.25c_1 = 1.25, c2=19652c_2 = 19652. With a few hundred visits the log term is close to 0 (it reaches 0.25 only after about 5,600 visits), so in practice the bracket is ≈ 1.25: the older AlphaGo Zero rule with a constant. MuZero rescales QQ to [0,1][0, 1] using the smallest and largest values seen in the tree, because Atari returns are unbounded.

Expand and back up. When the walk reaches a leaf, the network gives a prior PP for the leaf’s children and a value vv for the leaf. The discounted return (rewards along the path plus γdepthv\gamma^{\text{depth}} v) is averaged into QQ of every edge on the path, and each NN is incremented (MuZero Eqs. 3–4). No random rollout to the end of the game is needed: the value network replaces it.

Worked example. A node has three children with P=(0.5,0.3,0.2)P = (0.5, 0.3, 0.2), N=(6,3,1)N = (6, 3, 1) and normalised Q=(0.55,0.60,0.40)Q = (0.55, 0.60, 0.40). Then ∑N=10\sum N = 10, 10≈3.162\sqrt{10} \approx 3.162, and the bracket is 1.25+log⁡(19663/19652)≈1.25061.25 + \log(19663/19652) \approx 1.2506.

ChildValue QQBonus P⋅3.162/(1+N)⋅1.2506P \cdot 3.162 / (1+N) \cdot 1.2506Score
a0.550.5 × 3.162 / 7 × 1.2506 ≈ 0.2820.832
b0.600.3 × 3.162 / 4 × 1.2506 ≈ 0.2970.897
c0.400.2 × 3.162 / 2 × 1.2506 ≈ 0.3950.795

Child b is simulated next. Note how c, with the lowest value, gets the biggest bonus because it has one visit.

From visits to a policy target. After all simulations, the root’s visit counts are the search’s answer. Distinguish the stored policy target from the distribution used to act. MuZero’s released pseudocode stores πtarget(a)=N(a)/∑bN(b)\pi_{\text{target}}(a) = N(a)/\sum_b N(b) for policy training; with counts (6, 3, 1) that is (0.6,0.3,0.1)(0.6, 0.3, 0.1). To select the real action it applies the temperature rule pact(a)∝N(a)1/Tp_{\text{act}}(a) \propto N(a)^{1/T} (MuZero Eq. 6): with T=1T = 1 this equals the target, and with T=0.5T = 0.5 counts are squared, (36,9,1)/46≈(0.78,0.20,0.02)(36, 9, 1)/46 \approx (0.78, 0.20, 0.02). Changing TT sharpens the acting distribution, not the stored target in that implementation. MuZero’s Atari actors decay TT from 1 to 0.5 to 0.25 over training; at evaluation AlphaZero plays the most-visited move.

Section titled “4. AlphaZero: search, then imitate the search”

AlphaZero has one network (p,v)=fθ(s)(\mathbf{p}, v) = f_\theta(s) that outputs move probabilities p\mathbf{p} and a value vv estimating the game outcome. It plays itself, choosing each move by MCTS. When a game ends with outcome z∈{−1,0,+1}z \in \{-1, 0, +1\} (loss, draw, win), every position sts_t of that game becomes a training example (AlphaZero Eq. 1):

l=(z−v)2−π⊤log⁡p+c ∥θ∥2.l = (z - v)^2 - \boldsymbol{\pi}^\top \log \mathbf{p} + c\,\lVert\theta\rVert^2 .

In words: make the value head predict who won, and make the policy head match the search’s visit distribution π\boldsymbol\pi; cc weights L2 regularisation. The target zz is from the perspective of the player to move at that position, not the same signed outcome for both players’ positions; backups must use a consistent player perspective. Worked numbers: if the game was won (z=1z = 1), the network said v=0.2v = 0.2 and p=(0.5,0.3,0.2)\mathbf{p} = (0.5, 0.3, 0.2), and the search returned π=(0.6,0.3,0.1)\boldsymbol\pi = (0.6, 0.3, 0.1), the value loss is 0.82=0.640.8^2 = 0.64 and the policy loss is −(0.6ln⁡0.5+0.3ln⁡0.3+0.1ln⁡0.2)≈0.938-(0.6\ln 0.5 + 0.3\ln 0.3 + 0.1 \ln 0.2) \approx 0.938. The smallest achievable policy loss is the entropy of π\boldsymbol\pi, ≈ 0.898, so the gap of 0.040 is the KL divergence still to close.

Why this works. Search aims to improve on the prior by combining it with look-ahead evaluation. With finite compute or an inaccurate model or value function, improvement is not guaranteed; MuZero’s experiments measure when it occurs. Training the prior toward the search is a policy-improvement step; training vv on outcomes of search-guided games is policy evaluation. Repeat and you have approximate policy iteration. For an IR reader: the search is an expensive reranker, the policy head is the cheap first-stage model, and the loss distils one into the other, so the next search starts from a better candidate list.

What AlphaZero does not learn is the model. It uses the game rules for three things inside the search: computing the next position, knowing which moves are legal, and detecting the end of the game (MuZero Appendix A). That is what MuZero removes.

5. MuZero: learn a model of only what planning needs

Section titled “5. MuZero: learn a model of only what planning needs”

MuZero replaces the rules with three learned functions (Figure 1):

  • Representation s0=hθ(o1,…,ot)s^0 = h_\theta(o_1, \dots, o_t): encodes past observations (board positions, or the last 32 Atari frames and actions) into a hidden state.
  • Dynamics rk,sk=gθ(sk−1,ak)r^k, s^k = g_\theta(s^{k-1}, a^k): given a hidden state and an imagined action, predicts the immediate reward and the next hidden state.
  • Prediction pk,vk=fθ(sk)\mathbf{p}^k, v^k = f_\theta(s^k): AlphaZero’s policy and value heads, applied to a hidden state.

MCTS runs exactly as above, except a newly expanded edge calls gg instead of the rules; later visits reuse the stored hidden state and reward. Each simulation makes at most one new dynamics call and one new prediction call. The key design choice: the hidden state has no required meaning. The paper says there is no requirement for it “to capture all information necessary to reconstruct the original observation”. It only has to make reward, value and policy predictions come out right, an idea called value equivalence. Like a retriever trained for relevance rather than to reconstruct the document, it can ignore whatever does not affect the decision.

Training: unroll K steps along real actions. Sample a position tt from the replay buffer. Encode with hh, then apply gg five times along the actions that were actually taken, at+1,…,at+Ka_{t+1}, \dots, a_{t+K} with K=5K = 5. At each step kk, compare the predictions with what really happened kk steps later (Eq. 1):

lt(θ)=∑k=0K[lr(ut+k,rtk)⏟reward+lv(zt+k,vtk)⏟value+lp(πt+k,ptk)⏟policy]+c∥θ∥2.l_t(\theta) = \sum_{k=0}^{K} \Big[ \underbrace{l^r(u_{t+k}, r_t^k)}_{\text{reward}} + \underbrace{l^v(z_{t+k}, v_t^k)}_{\text{value}} + \underbrace{l^p(\pi_{t+k}, \mathbf{p}_t^k)}_{\text{policy}} \Big] + c\lVert\theta\rVert^2 .

Here uu is the observed reward, πt+k\pi_{t+k} the stored search policy at that real time step, and zz the value target. In board games zz is the final outcome and the reward loss is dropped. In Atari, zz is an nn-step return with n=10n = 10 and γ=0.997\gamma = 0.997, bootstrapped from the stored search value ν\nu:

zt=ut+1+γut+2+⋯+γn−1ut+n+γnνt+n,γ10=0.99710≈0.970.z_t = u_{t+1} + \gamma u_{t+2} + \dots + \gamma^{n-1} u_{t+n} + \gamma^{n} \nu_{t+n}, \qquad \gamma^{10} = 0.997^{10} \approx 0.970 .

Count the pieces for one sample: 1 call to hh, 5 to gg (giving rewards r1…r5r^1 \dots r^5), 6 to ff (values and policies for k=0…5k = 0 \dots 5). Each head’s loss is scaled by 1/K1/K and the gradient entering gg is halved, to keep gradient size similar however far you unroll (Appendix G). Implementation note: the released pseudocode leaves the root (k=0k = 0) prediction gradient at scale 1 and scales only the recurrent predictions by 1/K1/K, so treat the schematic loss as the idea, not a complete training specification, and follow one version consistently. Policy loss is cross-entropy; Atari values and rewards use cross-entropy over 601 bins after a square-root-like rescaling (skip on first read).

What changed from AlphaZero, in one line: same search and same “imitate the search” loss, plus a reward head, plus a learned transition function trained only through those three losses. MuZero uses environment-provided legal-action masking at the root, but no legality mask inside the tree. It has no separate legality or termination head: training suppresses actions that never occur in real trajectories, and terminal states are treated as absorbing so that predicted rewards and values stay sensible even if the search continues past them (Appendix A).

6. DreamerV3: learn a world model, train the policy in imagination

Section titled “6. DreamerV3: learn a world model, train the policy in imagination”

Dreamer takes the other branch: no tree search at all. Actions in the real environment are sampled from an actor network “without lookahead planning”. The world model learns from replayed real observations, rewards and continuation labels. The actor learns from imagined latent trajectories. In the cited April 2024 revision, the critic also gets a replay-trajectory loss (weight 0.3) in addition to its imagination loss.

The world model is a Recurrent State-Space Model (RSSM). Plain words: a recurrent network carries a deterministic memory hth_t; an encoder turns each observation xtx_t into a discrete stochastic code ztz_t; a dynamics predictor tries to guess ztz_t from hth_t alone (that is what lets it imagine without observations); and heads predict reward rtr_t, an episode-continues flag ctc_t, and a reconstruction of xtx_t (Eq. 1). The model state is st=(ht,zt)s_t = (h_t, z_t). The loss (Eqs. 2–3) has three parts with fixed weights: a prediction loss (reconstruct inputs, predict reward and continuation; weight 1), a dynamics loss (pull the predictor toward the encoder’s code; weight 1) and a representation loss (pull the code toward what is predictable; weight 0.1). Both KL terms are clipped below 1 nat (“free bits”) so they switch off once small. Skip these details on a first read.

Actor–critic in imagination. Starting from states of replayed real data, the model and actor roll forward T=16T = 16 imagined steps. A critic learns λ-returns (the GAE idea applied to returns) with γ=0.997\gamma = 0.997. The actor is trained with REINFORCE (from the policy-gradient page) plus an entropy bonus with fixed weight η=3×10−4\eta = 3\times10^{-4}, using advantages divided by max⁡(1,S)\max(1, S), where SS is a running estimate of the 5th-to-95th-percentile range of returns (Eqs. 6–7). Dividing only when returns are large keeps small, sparse rewards from being amplified into noise.

Fixed hyperparameters via symlog. Rewards and observations differ by orders of magnitude between domains. Dreamer predicts transformed targets symlog⁡(x)=sign⁡(x)ln⁡(∣x∣+1)\operatorname{symlog}(x) = \operatorname{sign}(x)\ln(|x| + 1) and inverts with symexp⁡\operatorname{symexp} (Eqs. 8–9). Examples: symlog(0.5) ≈ 0.41, symlog(1000) ≈ 6.91, symlog(−1000) ≈ −6.91. Values near zero barely change, huge values are squashed, signs are kept. Reward and critic heads predict a distribution over exponentially spaced bins with a “twohot” target, so gradient size does not depend on the target’s scale (Eqs. 10–11). These tricks, plus return normalisation, are what the paper credits for using one configuration across all its domains; I verified the claim of “fixed hyperparameters across domains” in the abstract and Figure 1.

AlphaZero (arXiv version, Table 1; 100-game matches, 1 minute per move). Training used 700,000 steps of 4,096 positions, 800 simulations per move, and took 9 h (chess), 12 h (shogi) and 34 h (Go) on 5,000 first-generation TPUs for self-play.

GameOpponentAlphaZero wins / draws / losses
ChessStockfish (2016 TCEC champion)28 / 72 / 0
ShogiElmo (2017 CSA champion)90 / 2 / 8
GoAlphaGo Zero after 3 days60 / – / 40

It searched about 80 thousand positions per second in chess versus 70 million for Stockfish: a learned evaluation lets the search be far more selective. It passed Stockfish’s Elo after 4 hours (300k steps). The Elo curves are figures only; neither paper gives numeric Elo values in the text. The later Science version used longer matches; these numbers are from the preprint.

MuZero, Atari (Table 1, 57 games, human-normalised scores; 100% = human level).

AgentMedianMeanFrames
R2D2 (model-free, previous best)1920.6%4024.9%37.5B
MuZero2041.1%4999.2%20.0B
Rainbow231.1%–200M
MuZero Reanalyze731.1%2168.9%200M

MuZero beat R2D2 on 42 of 57 games and SimPLe, the best previous model-based method, on every game where SimPLe was evaluated (36 of 57). Reanalyze reruns MCTS on old trajectories with the latest network to refresh targets. Board games: MuZero matched AlphaZero in chess and shogi and slightly exceeded it in Go (Figure 2), without being given the rules for its internal transitions (root legality still comes from the environment), using 16 residual blocks per evaluation instead of 20.

What search buys (Figure 3). In Go, the learned model kept improving with search up to 10 s per move, about 100× longer than the roughly 0.1 s searches it was trained with. In Atari, gains plateaued around 100 simulations, which the authors attribute to a less accurate model; even 1 simulation (just the policy network) did well. On Ms. Pac-Man, replacing MuZero’s loss with a Q-learning loss and no search matched R2D2 but learned slower and ended much lower, and training with only 6 simulations per move, fewer than the 8 actions, still worked.

DreamerV3. One configuration on 8 domains and over 150 tasks: Atari (200M frames, where the paper reports beating MuZero with a fraction of the compute), ProcGen, DMLab, Atari100k, proprioceptive and visual control, BSuite and Minecraft. It was the first algorithm to collect diamonds in Minecraft from scratch with no human data, and every Dreamer agent trained on Minecraft found diamonds within 100M environment steps, using 1 GPU for 9 days. VPT used human data and 720 GPUs for 9 days. Ablations on 14 tasks: every robustness trick helps on average, the KL objective most; stopping the reconstruction gradients hurts more than stopping the reward and value gradients. Model size (12M to 400M parameters) and replay ratio both improve score and data efficiency.

Test-time search connects to planning, but a verifier is not a world model. Best-of-N proposes complete answers and ranks them; it needs no learned environment dynamics. For a tree over textual reasoning states, appending a generated step is a known transition, the LLM proposes actions, and a verifier scores them. A tool-using agent additionally needs real or simulated tool outcomes to evaluate future branches. Best-of-N is the shallowest tree: one level, N children, pick the best by a reward model. Self-consistency votes over N leaves. Beam or tree search over reasoning steps with a process reward model (PRM) is MCTS-like: a step is an action, the LLM’s probabilities play the prior PP, and the PRM plays the value vv. Snell et al. find that the best way to spend that compute depends on question difficulty, and that difficulty-aware allocation beats best-of-N by more than 4× in efficiency. DeepSeek-R1 reports AlphaZero-style MCTS as an unsuccessful attempt: token generation has an “exponentially larger search space” than chess and a fine-grained value model is hard to train. That is the same two ingredients this page needs, a tractable action space and a good vv, failing.

LLMs as world models for agent RL. When the environment is a tool or a user, an LLM can play the dynamics function gg:

  • ZeroSearch fine-tunes an LLM to act as the search engine during RL, writing useful or noisy documents; the abstract reports a 7B simulator comparable to a real engine and a 14B one surpassing it.
  • Kimi K2 synthesises tool-use data with a stateful tool simulator, which the report calls “functionally equivalent to a world model”.
  • DreamGym and Simia have a reasoning model predict next states and rewards. Agent World Model instead has an LLM write code-backed environments once, so transitions are executed rather than imagined. Both kinds are mapped in the environments map.

These are Dreamer-style (the simulator produces the observation the policy reads), not MuZero-style: an LLM policy needs text to condition on, so a value-equivalent latent is of little use as the actor’s input (it could still drive a planner that picks real actions).

Model exploitation is reward hacking. In the Dyna example, the policy learned to value a state the model was wrong about. An RL policy trained in a simulator does the same at scale: it drifts toward the states where the simulator is most generous. ZeroSearch’s simulator sees the question’s gold answer in its prompt, which creates a risk that it returns answer-bearing text even for a poor query. This is a plausible shortcut to test, not a demonstrated failure in the paper, whose reported evaluation uses real search; a direct test would hold the query fixed, remove or change the answer conditioning, and compare simulated and real outputs. The defences are the classic model-based ones: model the outcome distribution rather than one sample, inject noise (ZeroSearch’s curriculum of noisy documents), keep some real interaction in the loop (Dyna’s real steps; MuZero always acts in the real environment), and evaluate in the real environment. For an IR reader, this is the same lesson as tuning a ranker against an LLM relevance assessor or a nugget judge: the harder you optimise, the more you measure the judge’s blind spots. See specification gaming (which lists simulator bugs as a cause) and Goodhart variants.

  • MuZero’s dynamics are deterministic. The paper leaves stochastic transitions to future work, and imperfect-information games such as poker are out of scope. The search-or-answer MDP’s random answer rewards can be represented by their expectations, 0.3 and 0.8, and all its state transitions are deterministic, so it does not by itself need a stochastic extension (the lab’s expected-reward MCTS solves it). Explicitly branching on different stochastic next states is the limitation that matters for a learned tool simulator.
  • Compute is large. Each board game used 16 TPUs for training and 1,000 for self-play. Dreamer’s authors note MuZero had no released implementation and many components, making it hard to reproduce.
  • Search helps less where the model is worse. Atari gains plateaued at about 100 simulations while Go kept improving. A learned simulator for tools or users will be closer to the Atari case.
  • “Better than the real environment” claims need care. A simulator that outperforms the real tool during training may be teaching easier lessons, not better ones; always compare on the real environment, with matched budgets.
  • Elo and “superhuman” claims are figure-level. The texts report match results and curves, not Elo tables.

The hand calculations above are sufficient for this lesson. The short script checks Dyna and a simplified tree search; it is not MuZero: it uses an expected-reward model, a fixed depth, zero leaf value and per-node normalisation. Save it as mbrl_lab.py and run python3 mbrl_lab.py (laptop CPU, pure Python, under a second). I ran this exact script.

Lab 1–2 script: Dyna-Q and pUCT tree search on the search-or-answer MDP
import math, random
random.seed(0)
G, ACTS = 0.9, ('answer', 'search')
P_OK = {'Q': 0.3, 'E': 0.8} # chance an answer is correct
# Lab 1: Dyna-Q with a model learned from experience
def dyna(episodes, n_plan, alpha=0.5):
Q = {(s, a): 0.0 for s in 'QE' for a in ACTS}
model = {} # (s, a) -> (r, s'): last outcome seen
def update(s, a, r, s2):
target = r + (G * max(Q[s2, b] for b in ACTS) if s2 else 0.0)
Q[s, a] += alpha * (target - Q[s, a])
for ep in episodes:
for s, a, r, s2 in ep:
update(s, a, r, s2) # learn from the real step
model[s, a] = (r, s2) # learn the model
for _ in range(n_plan): # plan: replay imagined steps
ps, pa = random.choice(list(model))
update(ps, pa, *model[ps, pa])
return {k: round(v, 3) for k, v in Q.items()}
lucky = [('Q', 'search', -0.1, 'E'), ('E', 'answer', 1.0, None)]
print('no planning :', dyna([lucky], 0))
print('50 plan steps:', dyna([lucky], 50))
# Lab 2: MCTS with the pUCT rule (MuZero Eq. 2) on an expected-reward model
def model_step(s, a):
return (P_OK[s], None) if a == 'answer' else (-0.1, 'E')
def mcts(root, n_sims, prior=(0.5, 0.5), c1=1.25, c2=19652, depth=3):
N, W = {}, {} # visit counts, summed returns per (path, a)
for _ in range(n_sims):
s, path, rewards = root, (), []
while s is not None and len(path) < depth:
tot = sum(N.get((path, b), 0) for b in ACTS)
qs = [W[path, b] / N[path, b] for b in ACTS if N.get((path, b))]
lo, hi = (min(qs), max(qs)) if qs else (0, 1) # per node; MuZero uses the whole tree
def score(i, b):
n = N.get((path, b), 0)
q = (W[path, b] / n - lo) / (hi - lo or 1) if n else 0.0
c = c1 + math.log((tot + c2 + 1) / c2)
return q + prior[i] * math.sqrt(tot) / (1 + n) * c
a = max(enumerate(ACTS), key=lambda ib: score(*ib))[1]
r, s = model_step(s, a)
rewards.append(r); path += (a,)
g = 0.0 # leaf value v = 0 (no value network)
for k in range(len(path) - 1, -1, -1):
g = rewards[k] + G * g
key = (path[:k], path[k])
N[key] = N.get(key, 0) + 1; W[key] = W.get(key, 0) + g
counts = [N.get(((), b), 0) for b in ACTS]
return counts, [round(c / sum(counts), 2) for c in counts]
for n in (2, 10, 50):
print(n, 'simulations -> root visits (answer, search), policy target:', mcts('Q', n))

Expected output: without planning, Q(Q,search)=−0.05Q(Q, \text{search}) = -0.05 and Q(E,answer)=0.5Q(E, \text{answer}) = 0.5; with 50 planning steps, 0.8 and 1.0 (the optimistic model at work). MCTS from Q puts 9 of 10 and 46 of 50 root visits on search, so the policy target is about 0.9 for searching, matching q∗(Q,search)=0.62>q∗(Q,answer)=0.3q^*(Q, \text{search}) = 0.62 > q^*(Q, \text{answer}) = 0.3. Try: (1) make the Dyna model store the average reward per (s,a)(s, a) and feed it 20 sampled episodes; the values should approach 0.8 and 0.62. (2) Give MCTS a bad prior, prior=(0.9, 0.1), and see how many simulations it takes for visits to favour search.

Lab 3 (optional, one GPU, hours). Skip this unless you specifically want to study Dreamer’s implementation: see the official DreamerV3 code, danijar/dreamerv3, and its README for setup.

  • Say what a model is, and give one benefit and one risk of planning with a learned one.
  • Run Dyna by hand for one episode and explain why more planning converges to the model’s (possibly biased) values rather than the true ones.
  • Compute pUCT scores for a node, turn root visit counts into a stored policy target, and give action-selection probabilities at any temperature.
  • Write AlphaZero’s loss and explain why imitating the search is policy improvement.
  • Name MuZero’s three functions, count the terms in its K-step loss, and say what it deliberately does not predict.
  • Explain how Dreamer trains its actor in imagination while continuing to collect real experience for its world model, and what symlog is for.
  • Map best-of-N, PRM tree search and LLM-simulated tools onto these pieces, and explain why simulator exploitation is reward hacking.

Questions to think through

These questions have no single right answer. Write or say your answer before you open the hints. Mark a question once you could defend your answer in a reading group.

  1. Derive / compute

    A MuZero search node has three children with priors P = (0.4, 0.4, 0.2), visit counts N = (8, 1, 1) and min–max normalised values Q̄ = (0.70, 0.55, 0.50). With c1 = 1.25 and c2 = 19652, compute each child's pUCT score and say which child the next simulation descends into and why it is not the child with the highest value. Separately, a finished 800-simulation search ends with root visit counts (560, 200, 40): give the stored policy target, then the action-selection probabilities at temperatures 1 and 0.25.

    What a strong answer covers
    • ΣN = 10, √10 ≈ 3.162; the log term is log((10 + 19652 + 1)/19652) ≈ 0.0006, so the multiplier is ≈ 1.2506 (with small counts the rule is effectively AlphaGo Zero's constant c_puct).
    • Bonuses: 0.4·3.162/9·1.2506 ≈ 0.176, 0.4·3.162/2·1.2506 ≈ 0.791, 0.2·3.162/2·1.2506 ≈ 0.395; scores ≈ 0.876, 1.341, 0.896.
    • The second child wins: its prior equals the first child's but it has 1 visit instead of 8, so the bonus dominates the 0.15 value gap. The third child (lowest value) even outranks the first.
    • For a fixed parent count the bonus shrinks with the child's visits; as the parent count grows, neglected children can earn exploration visits again. A low-value child is not permanently excluded just because its value stays low.
    • Stored policy target (released pseudocode): N/ΣN = (0.70, 0.25, 0.05). Acting at T = 1 uses the same probabilities; acting at T = 0.25 uses counts to the 4th power, ≈ (0.983966, 0.016008, 0.0000256), close to greedy.
  2. Derive / compute

    MuZero trains on Atari with K = 5 unroll steps, n = 10-step value targets and discount γ = 0.997. For one sampled start time t, count the network calls and loss terms in Eq. 1, list exactly which stored quantities from the trajectory are needed (up to which time index), compute the weight on the bootstrapped search value in the value target, and explain why no term compares a predicted observation with a real one.

    What a strong answer covers
    • Calls: one representation call h on o_1..o_t, five dynamics calls g along the real actions a_(t+1)..a_(t+5), and six prediction calls f (for s^0 to s^5).
    • Eq. 1 sums k = 0..5 over three heads: six policy and six value terms; reward predictions r^1..r^5 come from g (k = 0 has no simulated transition); board games drop the reward loss entirely.
    • Targets: search policies π_t..π_(t+5); observed rewards u_(t+1)..u_(t+5) for the reward heads; for the value target at k = 5, rewards up to u_(t+15) and the stored search value ν_(t+15).
    • z = Σ γ^i u_(t+1+i) for i = 0..9 plus γ^10·ν_(t+10); γ^10 = 0.997^10 ≈ 0.970, so the bootstrap carries almost full weight.
    • Appendix G scales each head's loss by 1/K and the gradient entering the dynamics function by 1/2, to keep gradient size stable across unroll steps; the released pseudocode keeps the root (k = 0) terms at scale 1 and applies 1/K only to the recurrent steps.
    • No observation term by design: hidden states only need to predict reward, value and policy (value equivalence), so capacity is not spent on irrelevant pixels.
  3. Mechanism

    AlphaZero and MuZero train the policy head toward the root visit-count distribution of MCTS rather than toward the action that was taken or a Q-learning target. Explain why visit counts can improve on the network's prior and when model error, value error or a small search budget could invalidate that improvement, why repeating "search, then imitate the search" behaves like policy iteration, and what MuZero's Ms. Pac-Man comparison with a Q-learning objective suggests about the strength of this learning signal.

    What a strong answer covers
    • pUCT allocates simulations using both the prior and backed-up estimates. Distilling the resulting visits approximates a policy-improvement step, but finite-search targets are not guaranteed to be better in every state (inaccurate model or value, too few simulations).
    • The cross-entropy −π·log p distils the expensive search into the network, like distilling a slow cross-encoder reranker into a fast first-stage model; the next search starts from a better prior.
    • The value head regresses on game outcomes or n-step returns of the search policy (policy evaluation); the two heads alternate like evaluation and improvement in policy iteration.
    • MuZero Fig. 3C: the same network trained with an R2D2-style Q-learning loss and no search matched R2D2 but learned slower and ended much lower; the authors conjecture search targets are a stronger signal than high-bias, high-variance Q-learning targets.
    • Fig. 3D: even 6 simulations per move (fewer than the 8 actions) produced an effective policy, and more simulations learned faster.
  4. What if…

    DreamerV3's Figure 6b stops reconstruction gradients from shaping the representation (it does not delete the decoder or reward head). MuZero uses reward, value and search-policy supervision and never reconstructs observations. Predict the effect of removing reconstruction supervision from Dreamer, or adding it to MuZero, in (a) a sparse-reward task and (b) a visually busy task with irrelevant detail. Which outcomes does the published ablation support, and which remain hypotheses?

    What a strong answer covers
    • Dreamer Figure 6b: stopping reconstruction gradients hurts more than stopping reward and value gradients, so its representation rests mostly on reconstruction. The ablation stops gradients from selected heads; it does not remove what the heads do.
    • Before useful reward is found, reconstruction still trains perception. MuZero's policy and value targets exist at every sampled position but are produced partly by its own model and search, so they can be uninformative or self-confirming; search alone does not make it immune to sparse reward.
    • Adding reconstruction to a capacity-limited MuZero in a busy visual task could spend capacity on irrelevant pixels, or could help as auxiliary supervision. That is a prediction, not an ablation the MuZero paper ran.
    • Dreamer's free bits and representation-loss weight 0.1 balance informative codes against predictable ones; they do not guarantee that only task-relevant pixels are represented.
    • Test: matched architectures and compute, with and without each supervision path, measuring reward discovery, task success and model/value error. Different results can come from different data, tasks and learning signals rather than a contradiction.
  5. Critique

    On the search-or-answer MDP, a Dyna-Q agent sees one lucky episode (search, then a correct answer) and stores a deterministic model of what it saw. After 50 planning steps it values Q(E, answer) = 1.0 and Q(Q, search) = 0.8, while the true optimal values are 0.8 and 0.62. Explain the failure, relate it to ZeroSearch's simulator, which sees the gold answer in its prompt, and propose an experiment that would detect the same failure in an LLM-simulated tool environment.

    What a strong answer covers
    • The last-sample model mistakes one Bernoulli reward sample for its mean. Planning converges to that model's values, 1.0 and −0.1 + 0.9·1.0 = 0.8, instead of the true 0.8 and 0.62; more planning removes planning error but cannot remove this model bias.
    • The estimates are not worse than their starting errors here (search: 0.67 → 0.18; answer: 0.3 → 0.2), and the optimal root action is unchanged. Showing model exploitation would need an action chosen only because the model is wrong in its favour.
    • ZeroSearch Table 2 shows the simulator prompt includes the gold answer, which could permit poor-query shortcuts; test it with real-tool replay and controlled changes to the simulator prompt rather than treating it as an established exploit.
    • Fixes from the page: learn expected outcomes or a distribution (not the last sample), mix real and simulated steps, inject noise (ZeroSearch's curriculum of noisy documents), and evaluate in the real environment.
    • Experiment: replay the trained policy's actual tool calls against the real tool; plot the gap between simulated and real success as training proceeds. A widening gap while simulated reward rises is the signature.
  6. Research idea

    Pitch a project that trains a search agent over a fixed corpus (for example BrowseComp-Plus) with a learned simulator of the search tool instead of real retrieval for most rollouts. State the hypothesis, decide whether the simulator should generate documents (Dreamer/ZeroSearch style) or predict only what the policy needs (MuZero style), and design the minimal experiment, including the result that would falsify your hypothesis.

    What a strong answer covers
    • Hypothesis example: a Dyna-style mix (a fraction of rollouts on the real retriever, the rest simulated) matches real-only training at a fraction of the retrieval cost, and the gap is predictable from simulator fidelity.
    • An observation-generating simulator fits an unchanged text-in/text-out actor. A latent value-equivalent model can instead drive a planner that picks real actions, or a latent actor with a suitable interface; it is not inherently unusable for LLM agents.
    • Ground the simulator: condition it on retrieved real passages, train it on logged query–document pairs, and keep gold answers out of its prompt (the possible shortcut introduced by gold-answer conditioning).
    • Minimal experiment: one policy size, three arms (real-only, simulated-only, mixed), evaluated only with the real retriever; also measure the simulated-minus-real success gap during training.
    • Report both matched-update and matched-total-cost comparisons, including simulator training and inference cost; equal policy-update counts alone do not test the cost-saving hypothesis.
    • Falsified if the mixed arm is worse than real-only at matched cost, or if the gap grows with training while simulated reward rises (the policy is exploiting the simulator).

Done with this page?

Status