Simple Algorithm
Reinforcement Learning · Fixed Point · 28 min

MuZero: Planning with a Learned Model

Value-equivalent models that plan without predicting observations.

MuZero equaled AlphaZero at Go, chess and shogi and reached state-of-the-art Atari scores without ever being told the rules. It searches inside a model it learned itself, and that model predicts no observations at all: only the rewards, values and move probabilities its search needs. This lesson specifies the model and its training, shows why matching those quantities is enough for search, separates what the experiments show from what they are often taken to show, and surveys the extensions that made the approach sample-efficient, stochastic and continuous.

What you’ll learn

  • Specify MuZero's representation, dynamics and prediction functions, and how MCTS runs on hidden states with rewards, discounting and normalized values.
  • Write MuZero's KK-step unrolled loss with its targets, and prove that matching expected rewards and values along action sequences makes the search's backed-up returns correct, open loop.
  • Interpret MuZero's experiments, including search scaling and ablations, and the evidence that much of its benefit comes from search during learning rather than during acting.
  • Describe Reanalyze, EfficientZero, Sampled MuZero and Stochastic MuZero, and the open problems of planning with learned models.

Three functions and a search

s0=hθ(o1,…,ot),(rk, sk)=gθ(sk−1,ak),(pk, vk)=fθ(sk)s^0=h_\theta(o_1,\dots,o_t),\qquad\big(r^k,\,s^k\big)=g_\theta\big(s^{k-1},a^k\big),\qquad\big(\mathbf p^k,\,v^k\big)=f_\theta\big(s^k\big)
MuZero (Schrittwieser et al., 2020). The representation hh encodes past observations into a hidden state; the dynamics gg maps a hidden state and an action to a predicted reward and the next hidden state; the prediction ff outputs a policy and a value. The hidden states are trained to match nothing in the environment; they carry whatever the three predictions need.

Planning is MCTS over hidden states: expanding a node costs one call to gg and one to ff, so a search never touches the real environment. Because Atari has intermediate rewards and discounting, each simulation that ends at a leaf of depth ℓ\ell backs up, to each node at depth kk on its path, the discounted return

Gk=∑τ=0ℓ−1−kγτ rk+1+τ+γℓ−k vℓ,G^k=\sum_{\tau=0}^{\ell-1-k}\gamma^{\tau}\,r^{k+1+\tau}+\gamma^{\ell-k}\,v^{\ell},

and Q(s,a)Q(s,a) is the running mean of these returns. Selection uses PUCT with a slowly growing coefficient, c1+ln⁡((N(s)+c2+1)/c2)c_1+\ln\big((N(s)+c_2+1)/c_2\big) with c1=1.25c_1=1.25 and c2=19652c_2=19652, and with QQ normalized to [0,1][0,1] by the minimum and maximum values seen in the tree, since rewards have no known scale. MuZero searched with 800 simulations per move in board games and 50 in Atari.

Compared with AlphaZero, two things changed. The search no longer needs a simulator of the rules, and the model is a latent dynamics model trained only through its predictions. Compared with world models that reconstruct observations, MuZero spends no capacity on pixels that do not matter for decisions: it is the value-equivalence principle in practice (Model Errors & Value-Equivalent Models).

Training: unroll K steps, match three targets

ℓt(θ)=∑k=0K[ℓr(ut+k,rtk)+ℓv(zt+k,vtk)+ℓp(πt+k,ptk)]+c ∥θ∥2\ell_t(\theta)=\sum_{k=0}^{K}\Big[\ell^r\big(u_{t+k},r_t^k\big)+\ell^v\big(z_{t+k},v_t^k\big)+\ell^p\big(\boldsymbol\pi_{t+k},\mathbf p_t^k\big)\Big]+c\,\norm{\theta}^2
From a state tt in the replay buffer, the model is unrolled for K=5K=5 steps along the actions actually taken. At step kk its reward is matched to the observed reward ut+ku_{t+k}, its value to the target zt+kz_{t+k} and its policy to the stored search policy πt+k\boldsymbol\pi_{t+k}. Board games have no intermediate rewards, so the reward term is dropped there.

The value target bootstraps nn steps into the future from the search value ν\nu stored when acting, zt=ut+1+γut+2+⋯+γn−1ut+n+γnνt+nz_t=u_{t+1}+\gamma u_{t+2}+\dots+\gamma^{n-1}u_{t+n}+\gamma^n\nu_{t+n}, with n=10n=10 on Atari; in board games it is simply the final outcome. Three details keep the unrolled training stable: each unrolled step's loss is scaled by 1/K1/K, the gradient entering the dynamics function is halved, and each hidden state is min–max scaled to [0,1][0,1] to bound the activations. On Atari, training states are drawn by prioritized replay with priority ∣ν−z∣\abs{\nu-z}.

python
import torch.nn.functional as F

def scale_grad(x, c):                                   # same value, gradient multiplied by c
    return x * c + x.detach() * (1 - c)

def muzero_loss(h, g, f, obs, actions, pi, z, u):
    """actions: (B, K) actions taken after obs; pi, z: (B, K+1, ...) search policies and value
    targets; u: (B, K) rewards observed after each action. f returns (policy logits, value)."""
    K = actions.shape[1]
    s = h(obs)                                          # hidden state s^0
    logits, v = f(s)
    loss = F.cross_entropy(logits, pi[:, 0]) + F.mse_loss(v, z[:, 0])
    for k in range(K):
        r, s = g(scale_grad(s, 0.5), actions[:, k])     # dynamics: reward, next hidden state
        logits, v = f(s)
        step = F.mse_loss(r, u[:, k]) + F.cross_entropy(logits, pi[:, k + 1]) + F.mse_loss(v, z[:, k + 1])
        loss = loss + step / K                          # each unrolled step weighted 1/K
    return loss

A sketch of the unrolled loss (weight decay omitted). F.cross_entropy accepts probability targets such as the search policies. Squared errors keep the sketch short; MuZero uses other loss functions for some heads on Atari.

Predict before you look

With n=3n=3 and γ=0.9\gamma=0.9, the rewards after time tt are ut+1=1u_{t+1}=1, ut+2=0u_{t+2}=0, ut+3=2u_{t+3}=2, and the search value stored at t+3t+3 is νt+3=5\nu_{t+3}=5. What is the value target ztz_t?

Show the answer

6.27

zt=1+0.9×0+0.81×2+0.729×5=1+1.62+3.645=6.265z_t=1+0.9\times0+0.81\times2+0.729\times5=1+1.62+3.645=6.265. Three real rewards, then the search's own estimate of what follows, discounted by γ3\gamma^3: a bootstrapped target whose bias shrinks as nn grows and whose variance grows with it.

DerivationWhy matching rewards and values is enough for the search
  1. rk=E[Rt+k∣o,a1:k](1≤k≤ℓ),vℓ=E[V(St+ℓ)∣o,a1:ℓ]r^k=\E\big[R_{t+k}\mid o,a^{1:k}\big]\quad(1\le k\le\ell),\qquad v^\ell=\E\big[V(S_{t+\ell})\mid o,a^{1:\ell}\big]

    Fix the history oo at the root and an action sequence a1,…,aℓa^1,\dots,a^\ell. Suppose the model's predictions along it equal the true conditional expectations of the rewards, and of a value function VV at the state reached:

  2. G0=∑k=1ℓγk−1rk+γℓvℓ=E[∑k=1ℓγk−1Rt+k+γℓV(St+ℓ) ∣ o,a1:ℓ]G^0=\sum_{k=1}^{\ell}\gamma^{k-1}r^k+\gamma^\ell v^\ell=\E\Big[\sum_{k=1}^{\ell}\gamma^{k-1}R_{t+k}+\gamma^\ell V(S_{t+\ell})\ \Big|\ o,a^{1:\ell}\Big]

    By linearity of expectation the search's backed-up return at the root equals the true expected return of committing to that sequence, with VV at the end, whatever the hidden states look like:

  3. Two caveats follow. The equality is open loop: the actions are fixed in advance, so in a stochastic environment a deterministic latent model evaluates plans that cannot react to chance outcomes, which is what Stochastic MuZero repairs. And the training data only pin down the predictions along action sequences the agent actually took. Grimm et al. (2021) show that, under a mild smoothness condition, minimizing MuZero's loss minimizes an upper bound on a squared proper-value-equivalence loss with respect to one policy, the one that generated the data. Off that policy's path, the model is constrained only by generalization.

What the experiments show

On the 57 Atari games MuZero set a new state of the art for both mean and median human-normalized score, beating the model-free R2D2 on 42 of the 57 games and the model-based SimPLe on every game where SimPLe had been evaluated. In Go it slightly exceeded AlphaZero while using less computation per node (16 residual blocks per evaluation against 20), and in chess and shogi it matched AlphaZero's superhuman performance.

The ablations say more. In Go, the learned model kept pace with the true simulator as the search time per move grew to 10 seconds, about two orders of magnitude beyond the 0.1 seconds used in training. In Atari the gains from more simulations plateaued around 100, and even a single simulation, which means acting with the policy network alone, performed well by the end of training. Replacing MuZero's objective with a Q-learning objective on Ms. Pac-Man matched R2D2's result but learned more slowly than MuZero and converged to a much lower final score, and training with only 6 simulations per move, fewer than Ms. Pac-Man's 8 actions, still learned an effective policy.

Check your understanding

In a stochastic environment, MuZero's predicted rewards and values along every fixed action sequence equal their true expectations. What does its search then evaluate correctly?

  1. The value of the optimal closed-loop policy from the root
  2. The expected return of committing to each action sequence in advance, which can undervalue plans that would react to chance outcomes
  3. Nothing: a deterministic model cannot be right in a stochastic world
  4. The exact distribution of future observations
Show the answer

B. The expected return of committing to each action sequence in advance, which can undervalue plans that would react to chance outcomes

Matching conditional expectations makes every backed-up return equal the true expected open-loop return, by linearity. But a good player in backgammon chooses later moves after seeing the dice; an open-loop plan cannot, so it can look worse than it is. Stochastic MuZero's chance nodes restore the ability to branch on outcomes.

Extensions: Reanalyze, sample efficiency, large actions, chance

  • Reanalyze. Old trajectories are re-searched with the latest network, so their policy targets improve after they were collected; in MuZero Reanalyze these fresh targets were used for 80% of updates, with value targets bootstrapped from a target network. With 200 million frames per game it reached a median human-normalized score of 731% on Atari, against 192%, 231% and 431% for IMPALA, Rainbow and LASER. Schrittwieser et al. (2021) then used Reanalyse across data budgets differing by orders of magnitude, including learning entirely from fixed datasets (MuZero Unplugged).
  • EfficientZero (Ye et al., 2021) adapted MuZero to 100,000 Atari interactions, about two hours of real-time play, reaching 194.3% mean and 109.0% median human-normalized score, with three changes: a self-supervised temporal-consistency loss on the hidden states, after SimSiam; predicting the value prefix, the cumulative reward, end to end instead of rewards step by step, to curb compounding error; and using the model to correct stale off-policy value targets.
  • Sampled MuZero (Hubert et al., 2021) searches over KK actions sampled from a proposal β\beta, usually the policy itself, with the prior corrected to (β^/β) π(\hat\beta/\beta)\,\pi, where β^\hat\beta is the empirical distribution of the samples; the sample-based improvement operator converges to the full one as K→∞K\to\infty. In Go about 50 sampled moves out of 362 came close to full search, and on continuous-control suites K=20K=20 was used.
  • Stochastic MuZero (Antonoglou et al., 2022) learns afterstates, the situation after the agent's action but before chance acts, and a discrete code for the chance outcome, and searches with chance nodes. It matched or exceeded the state of the art in 2048 and backgammon while keeping MuZero's performance in Go.

Key takeaways

  • MuZero learns hh, gg and ff and runs MCTS on hidden states with predicted rewards, discounting, PUCT and min–max normalized values; the hidden states are trained only through their predictions.
  • The loss unrolls K=5K=5 steps and matches rewards, nn-step value targets and search policies; if predicted rewards and values equal their true conditional expectations, the search's backed-up returns are exact for open-loop plans.
  • MuZero matched AlphaZero in board games and set a new state of the art on Atari; its learned model scaled with search in Go, while in Atari much of the gain came from search as a training signal (Hamrick et al., 2021; Muesli).
  • Reanalyze refreshes targets on old data, EfficientZero made the approach sample-efficient on Atari 100k, Sampled MuZero handles large and continuous action spaces, and Stochastic MuZero adds afterstates and chance nodes.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

What is MuZero's learned model trained to predict?

  1. The next observation, pixel by pixel
  2. The true environment state
  3. The game rules, as a symbolic program
  4. Along action sequences actually taken, the observed rewards, the value targets and the search policies
Show the answer

D. Along action sequences actually taken, the observed rewards, the value targets and the search policies

The unrolled loss matches predicted rewards, values and policies to targets at each of KK steps; the hidden states are free to encode anything that serves those predictions. That is value equivalence, not reconstruction.

Question 2

Which statement matches MuZero's search-scaling experiments?

  1. In both Go and Atari, performance improved steadily with every increase in search
  2. In Go, the learned model scaled with search time as well as the true simulator, far beyond the training budget; in Atari, gains plateaued around 100 simulations and the policy network alone performed well
  3. In Go, the learned model failed when searching longer than in training
  4. In Atari, search with the learned model hurt performance
Show the answer

B. In Go, the learned model scaled with search time as well as the true simulator, far beyond the training budget; in Atari, gains plateaued around 100 simulations and the policy network alone performed well

The contrast between Go and Atari is the point: precise lookahead pays in Go, while in Atari the model's value is mostly as a training signal. Hamrick et al. (2021) reached a similar conclusion across environments.

Question 3

What does Reanalyze do?

  1. It re-runs the search with the latest network on stored trajectories, producing fresher policy and value targets for old data
  2. It collects new data from the environment more often
  3. It retrains the model on reconstructed observations
  4. It removes old trajectories from the replay buffer
Show the answer

A. It re-runs the search with the latest network on stored trajectories, producing fresher policy and value targets for old data

The network improves faster than old targets can reflect, so recomputing targets with today's network extracts more learning from each stored step, which is why Reanalyze helps most when data are scarce, and in the fully offline setting of MuZero Unplugged.

Further reading

  • J. Schrittwieser et al., "Mastering Atari, Go, chess and shogi by planning with a learned model," Nature 588, 604–609 (2020).
  • C. Grimm, A. Barreto, G. Farquhar, D. Silver & S. Singh, "Proper value equivalence," NeurIPS (2021).
  • J. B. Hamrick, A. L. Friesen, F. Behbahani, A. Guez, F. Viola, S. Witherspoon, T. Anthony, L. Buesing, P. Veličković & T. Weber, "On the role of planning in model-based deep reinforcement learning," ICLR (2021).
  • W. Ye, S. Liu, T. Kurutach, P. Abbeel & Y. Gao, "Mastering Atari games with limited data," NeurIPS (2021).
  • I. Antonoglou, J. Schrittwieser, S. Ozair, T. Hubert & D. Silver, "Planning in stochastic environments with a learned model," ICLR (2022).