Overview
AlphaZero needs the rules of the game to look ahead. MuZero removes that need by learning its own stand-in for the rules. It does not try to predict what the next observation will look like. It keeps a private summary of the situation, a hidden state, and learns how that summary changes when an action is taken. The summary only has to be good enough to answer three questions: what reward comes next, how good is this situation, and which action would a careful search choose. Tree search then runs entirely on these summaries, so the real environment is touched once per move. This template is a small single-player version on a five-cell corridor with scalar value and reward outputs.
A short history
Julian Schrittwieser and colleagues at DeepMind described MuZero in 2019 and published it in Nature in 2020. AlphaZero needed the exact rules of the game to search ahead. MuZero removed that need by learning its own model, one that predicts only what planning uses: reward, value and policy. It matched AlphaZero at Go, chess and shogi and also set a new best result on Atari, where no rules are given. The name is not an acronym.
How it works
MuZeroNetwork.represent(the function ) turns the current observation into a hidden state.LatentMCTS.searchgrows a tree from that state. To expand a node it callsdynamics() for the next hidden state and reward, andpredict() for a policy prior and a value.- Inside the tree, each step picks the child with the best pUCT score. Q values are rescaled to the range 0 to 1 using the smallest and largest seen in this tree.
- The leaf's value is carried back up the path, adding each predicted reward and discounting at every step.
MuZero.play_episodeacts from the visit counts, takes one real step, and records the observation, action, reward, root value and visit distribution.make_targetspicks a position and builds targets for it and the nextunroll_stepspositions: the visit distribution, an n-step return, and the observed reward.loss_and_gradsunrolls the model along the actions really taken and compares its predictions with those targets. Gradients flow back through every step of the unroll, halved at each dynamics step bydynamics_grad_scale.trainalternates self-play episodes and gradient steps on positions sampled uniformly from recent episodes.
Watch out for
- The hidden state has no required meaning. You cannot decode it into an observation to check the model, so model errors show up only as bad play.
- The model is trained for
unroll_stepssteps but the search may go deeper. Predictions beyond the trained depth are extrapolation and can mislead the search. - The value target bootstraps from the search's own root value. Early in training those values are poor, and the network can chase its own errors for a while.
- This version is single-player: values are not negated between levels of the tree. It would give wrong results on a two-player game without that change.
- The full method predicts value and reward as distributions over a transformed range and uses prioritized replay and reanalysis. This template uses scalars with squared error and uniform replay.
Use cases
When to use it
Use it when looking ahead would help but no simulator of the rules is available to plan with. When the rules are known and cheap to simulate, AlphaZero or a planner on the true model is simpler and more exact.
In industry
- Games
- Board games and Atari video games learned with one algorithm, without the agent being told the rules.
- Video compression
- DeepMind reported applying MuZero to choose encoding settings for video streaming at YouTube, reducing the bitrate needed for the same quality.
- Planning research
- Sequential decision problems where look-ahead helps but no exact simulator exists, such as control from logged data.
Choosing it: what must hold
- Discrete actions, or a variant designed for continuous or very large action sets.
- Very large compute: every acting step runs a tree search and training unrolls the model several steps.
- A problem where planning ahead clearly helps, with rewards the model can learn to predict.
When to choose something else
| If | Use instead |
|---|---|
| The exact rules are available as a simulator | AlphaZero |
| Compute is limited and actions are discrete | DQN or Rainbow |
| You want a learned model for continuous control | MBPO or PETS |
Math foundations
The three learned functions
Representation, dynamics and prediction. Together they are a model that can be stepped forward any number of times from one real observation, without the environment.
Selection in the tree (pUCT)
The same balance of result and exploration bonus as in AlphaZero. Rewards here have no fixed scale, so is first rescaled with the smallest and largest values seen in the tree. Otherwise one constant could not suit every environment.
Backing up through predicted rewards
The value of an action is the reward the model predicts for it plus the discounted value of the hidden state it leads to. is the average of all values backed up through that node.
The n-step value target
Add up the next real rewards, then let the search's root value from steps later stand in for the rest. If the episode ends first, the sum simply stops and nothing is bootstrapped.
The training loss
At every unrolled step the value, policy and reward predicted from the hidden state are compared with what really happened at that point. The template uses and after that, and drops the policy term for positions past the end of the episode.
Symbols
- the real observation at step t
- hidden state after k imagined steps
- the representation, dynamics and prediction functions
- action taken at imagined step k
- predicted reward, value and policy at imagined step k
- real reward received after the action at step t
- root value of the search run at step t
- visit distribution of the search run at step t
- n-step value target for step t
- visit counts and prior in the search tree
- discount factor
- steps in the value target (td_steps) and in the unroll (unroll_steps)
- weight of unroll step k in the loss
Worked by hand
In the default corridor the agent starts three steps from the goal. Suppose it moves right three times, with rewards , , , and the episode ends. Compute the value targets with and .
The episode ends before steps have passed, so no search value is bootstrapped and the targets are exact discounted returns. The value should rise from 0.81 to 1 as the agent nears the goal.
Visual example
Loading the example.
Try this
- With the error at 0, click s¹, s² and s³: predicted rewards and values match the real corridor, and v at s⁰ is 0.81.
- Raise the error to 1 and click s³: the model expects no reward yet while the real agent has reached the goal.
- Flip action 1 to left and see the model predict the dead end.
- Observe cell 2, where the prior is less sure, and raise the simulations from 2 to 60 to watch the visits settle.
Code sample
from impl import CorridorEnv, MuZero
from config import MuZeroConfig
env = CorridorEnv()
agent = MuZero(MuZeroConfig(), env.obs_dim, env.n_actions)
history = agent.train(env, n_iterations=12) # 120 self-play episodes
print(history[0]["mean_return"], history[-1]["mean_return"]) # self-play reaches the goal more and more often
print(agent.evaluate(env, n_episodes=20)) # share of greedy episodes that reach the goalRead the implementation (339 lines)
"""MuZero on a toy corridor: learned representation, dynamics and prediction networks, and MCTS in latent space.
NumPy only, manual backpropagation through the unrolled model. A small single-player version of the algorithm
with scalar value and reward heads.
"""
from __future__ import annotations
import math
import numpy as np
try:
from .config import MuZeroConfig
except ImportError: # run from the template's own folder
from config import MuZeroConfig
class CorridorEnv:
"""Cells 0..length-1. Action 0 steps left, action 1 steps right.
The episode starts one cell away from the dead end, so the goal is three steps away in the default corridor.
Reaching the goal ends the episode with reward 1; reaching the dead end ends it with reward 0; so does running
out of `max_steps`. By default the goal is the last cell and the start is cell 1; `mirror=True` flips the
corridor (goal at cell 0, start at cell length - 2). The observation is a one-hot vector of the cell.
"""
n_actions = 2
def __init__(self, length: int = 5, max_steps: int = 10, mirror: bool = False) -> None:
self.length, self.max_steps = length, max_steps
self.obs_dim = length
self.goal, self.dead_end = (0, length - 1) if mirror else (length - 1, 0)
self.start = length - 2 if mirror else 1
self.pos, self.t = self.start, 0
def _obs(self) -> np.ndarray:
obs = np.zeros(self.length)
obs[self.pos] = 1.0
return obs
def reset(self) -> np.ndarray:
self.pos, self.t = self.start, 0
return self._obs()
def step(self, action: int) -> tuple[np.ndarray, float, bool]:
"""Returns (obs (length,), reward, done)."""
self.pos += 1 if int(action) == 1 else -1
self.t += 1
at_goal = self.pos == self.goal
return self._obs(), float(at_goal), at_goal or self.pos == self.dead_end or self.t >= self.max_steps
def _softmax(logits: np.ndarray) -> np.ndarray:
z = logits - logits.max(axis=-1, keepdims=True)
e = np.exp(z)
return e / e.sum(axis=-1, keepdims=True)
class MuZeroNetwork:
"""The three MuZero functions with shared training.
h: obs (B, obs_dim) -> state (B, L). g: state, action -> next state (B, L), reward (B,).
f: state -> policy logits (B, A), value (B,).
"""
def __init__(self, config: MuZeroConfig, obs_dim: int, n_actions: int) -> None:
self.config, self.obs_dim, self.n_actions = config, obs_dim, n_actions
rng = np.random.default_rng(config.seed)
lat, hid = config.latent_size, config.hidden_size
shapes = {
"h_w": (obs_dim, lat), "h_b": (lat,),
"g_w1": (lat + n_actions, hid), "g_b1": (hid,),
"g_ws": (hid, lat), "g_bs": (lat,), "g_wr": (hid, 1), "g_br": (1,),
"f_w1": (lat, hid), "f_b1": (hid,),
"f_wp": (hid, n_actions), "f_bp": (n_actions,), "f_wv": (hid, 1), "f_bv": (1,),
}
self.params = {
name: rng.normal(0.0, 1.0 / math.sqrt(shape[0]), size=shape) if len(shape) == 2 else np.zeros(shape)
for name, shape in shapes.items()
}
self._m = {k: np.zeros_like(v) for k, v in self.params.items()}
self._v = {k: np.zeros_like(v) for k, v in self.params.items()}
self._t = 0
def represent(self, obs: np.ndarray) -> np.ndarray:
"""h: obs (B, obs_dim) -> hidden state (B, L) in (-1, 1)."""
return np.tanh(obs @ self.params["h_w"] + self.params["h_b"])
def dynamics(self, state: np.ndarray, actions: np.ndarray):
"""g: state (B, L), actions (B,) ints -> (next state (B, L), reward (B,), cache for backprop)."""
p = self.params
onehot = np.zeros((len(state), self.n_actions))
onehot[np.arange(len(state)), actions] = 1.0
x = np.concatenate([state, onehot], axis=1)
hid = np.tanh(x @ p["g_w1"] + p["g_b1"])
nxt = np.tanh(hid @ p["g_ws"] + p["g_bs"])
return nxt, (hid @ p["g_wr"] + p["g_br"])[:, 0], (x, hid, nxt)
def predict(self, state: np.ndarray):
"""f: state (B, L) -> (policy logits (B, A), value (B,), cache for backprop)."""
p = self.params
hid = np.tanh(state @ p["f_w1"] + p["f_b1"])
return hid @ p["f_wp"] + p["f_bp"], (hid @ p["f_wv"] + p["f_bv"])[:, 0], (state, hid)
def _predict_backward(self, cache, d_logits, d_value, grads) -> np.ndarray:
state, hid = cache
p = self.params
d_v = d_value[:, None]
d_hid = (d_logits @ p["f_wp"].T + d_v @ p["f_wv"].T) * (1.0 - hid**2)
grads["f_wp"] += hid.T @ d_logits
grads["f_bp"] += d_logits.sum(axis=0)
grads["f_wv"] += hid.T @ d_v
grads["f_bv"] += d_v.sum(axis=0)
grads["f_w1"] += state.T @ d_hid
grads["f_b1"] += d_hid.sum(axis=0)
return d_hid @ p["f_w1"].T
def _dynamics_backward(self, cache, d_next, d_reward, grads) -> np.ndarray:
x, hid, nxt = cache
p = self.params
d_pre = d_next * (1.0 - nxt**2)
d_r = d_reward[:, None]
d_hid = (d_pre @ p["g_ws"].T + d_r @ p["g_wr"].T) * (1.0 - hid**2)
grads["g_ws"] += hid.T @ d_pre
grads["g_bs"] += d_pre.sum(axis=0)
grads["g_wr"] += hid.T @ d_r
grads["g_br"] += d_r.sum(axis=0)
grads["g_w1"] += x.T @ d_hid
grads["g_b1"] += d_hid.sum(axis=0)
return (d_hid @ p["g_w1"].T)[:, : self.config.latent_size]
def loss_and_grads(self, batch: dict) -> tuple[float, dict]:
"""MuZero loss over a K-step unroll, and its gradients.
batch: obs (B, obs_dim); actions (B, K) ints; target_policy (B, K+1, A); target_value (B, K+1);
target_reward (B, K); policy_mask (B, K+1), 0 where the position lies past the end of the episode.
loss = mean_b sum_k w_k * [(v_k - z_k)^2 + mask_k * CE(pi_k, p_k) + (r_k - u_k)^2 for k >= 1],
with w_0 = 1 and w_k = 1 / K for the unrolled steps. Returns (loss, gradients keyed like params).
"""
obs, actions = batch["obs"], batch["actions"]
b, k_steps = actions.shape
scale = self.config.dynamics_grad_scale
grads = {k: np.zeros_like(v) for k, v in self.params.items()}
state = self.represent(obs)
root_state = state
loss, steps = 0.0, []
for k in range(k_steps + 1):
w = 1.0 if k == 0 else 1.0 / k_steps
d_reward, g_cache = None, None
if k > 0:
state, reward, g_cache = self.dynamics(state, actions[:, k - 1])
err_r = reward - batch["target_reward"][:, k - 1]
loss += w * float((err_r**2).sum()) / b
d_reward = w * 2.0 * err_r / b
logits, value, f_cache = self.predict(state)
probs = _softmax(logits)
mask = batch["policy_mask"][:, k]
target_pi = batch["target_policy"][:, k]
err_v = value - batch["target_value"][:, k]
cross_entropy = -(target_pi * np.log(probs + 1e-12)).sum(axis=1)
loss += w * float((err_v**2).sum() + (mask * cross_entropy).sum()) / b
d_logits = w * mask[:, None] * (probs * target_pi.sum(axis=1, keepdims=True) - target_pi) / b
steps.append((g_cache, d_reward, f_cache, d_logits, w * 2.0 * err_v / b))
d_state = np.zeros_like(state)
for g_cache, d_reward, f_cache, d_logits, d_value in reversed(steps):
d_state = d_state + self._predict_backward(f_cache, d_logits, d_value, grads)
if g_cache is not None:
d_state = scale * self._dynamics_backward(g_cache, d_state, d_reward, grads)
d_pre = d_state * (1.0 - root_state**2)
grads["h_w"] += obs.T @ d_pre
grads["h_b"] += d_pre.sum(axis=0)
return loss, grads
def train_step(self, batch: dict) -> float:
"""One Adam step on a batch. Returns the loss before the step."""
loss, grads = self.loss_and_grads(batch)
self._t += 1
lr = self.config.learning_rate
for name, p in self.params.items():
m, v, g = self._m[name], self._v[name], grads[name]
m *= 0.9
m += 0.1 * g
v *= 0.999
v += 0.001 * g * g
p -= lr * (m / (1 - 0.9**self._t)) / (np.sqrt(v / (1 - 0.999**self._t)) + 1e-8)
return loss
class _Node:
"""Search node: a hidden state reached by an action, with the reward the model predicted for that action."""
__slots__ = ("prior", "state", "reward", "visits", "value_sum", "children")
def __init__(self, prior: float) -> None:
self.prior, self.state, self.reward = prior, None, 0.0
self.visits, self.value_sum = 0, 0.0
self.children: dict[int, _Node] = {}
def value(self) -> float:
return self.value_sum / self.visits if self.visits else 0.0
class LatentMCTS:
"""pUCT search over hidden states. Q values are rescaled to [0, 1] with the min and max seen in the tree."""
def __init__(self, config: MuZeroConfig, network: MuZeroNetwork, rng: np.random.Generator) -> None:
self.config, self.network, self.rng = config, network, rng
def _expand(self, node: _Node, state: np.ndarray) -> float:
logits, value, _ = self.network.predict(state)
node.state = state
for a, p in enumerate(_softmax(logits[0])):
node.children[a] = _Node(float(p))
return float(value[0])
def search(self, obs: np.ndarray, add_noise: bool = False) -> tuple[np.ndarray, float]:
"""Search from one observation (obs_dim,). Returns (visit counts (A,), root value)."""
c = self.config
root = _Node(1.0)
value = self._expand(root, self.network.represent(obs[None]))
if add_noise:
noise = self.rng.dirichlet([c.dirichlet_alpha] * len(root.children))
for child, eta in zip(root.children.values(), noise):
child.prior = (1 - c.dirichlet_eps) * child.prior + c.dirichlet_eps * eta
root.visits, root.value_sum = 1, value
q_min, q_max = math.inf, -math.inf
for _ in range(c.n_simulations):
node, path = root, [root]
while node.children:
parent, best_score = node, -math.inf
explore = c.c_puct * math.sqrt(parent.visits)
for a, child in parent.children.items():
q = 0.0
if child.visits:
q = child.reward + c.gamma * child.value()
q = (q - q_min) / (q_max - q_min) if q_max > q_min else q
score = q + explore * child.prior / (1 + child.visits)
if score > best_score:
best_score, action, node = score, a, child
path.append(node)
state, reward, _ = self.network.dynamics(parent.state, np.array([action]))
node.reward = float(reward[0])
value = self._expand(node, state)
for node in reversed(path):
node.value_sum += value
node.visits += 1
value = node.reward + c.gamma * value
if node is not root:
q_min, q_max = min(q_min, value), max(q_max, value)
counts = np.array([root.children[a].visits for a in range(len(root.children))], dtype=float)
return counts, root.value()
def make_targets(game: dict, t: int, config: MuZeroConfig, n_actions: int, rng: np.random.Generator) -> dict:
"""Training targets for position `t` of one episode.
game: actions (T,), rewards (T,) (reward after each action), root_values (T,), policies (T, A), obs (T, obs_dim).
Returns obs, actions (K,), target_policy (K+1, A), target_value (K+1,), target_reward (K,), policy_mask (K+1,).
The value target at step i is the n-step return sum_{j<n} gamma^j r_{i+j} + gamma^n * root_value_{i+n}; past
the end of the episode every target is 0 and the policy loss is masked out.
"""
k_steps, n, gamma = config.unroll_steps, config.td_steps, config.gamma
length = len(game["actions"])
actions = np.zeros(k_steps, dtype=int)
target_policy = np.full((k_steps + 1, n_actions), 1.0 / n_actions)
target_value, target_reward, mask = np.zeros(k_steps + 1), np.zeros(k_steps), np.zeros(k_steps + 1)
for k in range(k_steps + 1):
i = t + k
if i < length:
target_policy[k], mask[k] = game["policies"][i], 1.0
value = sum(gamma**j * game["rewards"][i + j] for j in range(n) if i + j < length)
if i + n < length:
value += gamma**n * game["root_values"][i + n]
target_value[k] = value
if k < k_steps:
actions[k] = game["actions"][i] if i < length else int(rng.integers(n_actions))
target_reward[k] = game["rewards"][i] if i < length else 0.0
return {"obs": game["obs"][t], "actions": actions, "target_policy": target_policy, "target_value": target_value,
"target_reward": target_reward, "policy_mask": mask}
class MuZero:
"""Self-play, replay and training loop around the network and the latent search."""
def __init__(self, config: MuZeroConfig | None, obs_dim: int, n_actions: int) -> None:
self.config = config or MuZeroConfig()
self.n_actions = n_actions
self.rng = np.random.default_rng(self.config.seed)
self.network = MuZeroNetwork(self.config, obs_dim, n_actions)
self.mcts = LatentMCTS(self.config, self.network, self.rng)
self.games: list[dict] = []
def act(self, obs: np.ndarray, greedy: bool = True) -> int:
"""Search from `obs` and return the most visited action (or a sample by visit counts when not greedy)."""
counts, _ = self.mcts.search(obs, add_noise=not greedy)
if greedy:
return int(counts.argmax())
p = counts ** (1.0 / self.config.temperature)
return int(self.rng.choice(self.n_actions, p=p / p.sum()))
def play_episode(self, env, greedy: bool = False) -> dict:
"""Play one episode with search at every step. Returns the game record used by `make_targets`."""
game = {"obs": [], "actions": [], "rewards": [], "root_values": [], "policies": []}
obs, done = env.reset(), False
while not done:
counts, root_value = self.mcts.search(obs, add_noise=not greedy)
if greedy:
action = int(counts.argmax())
else:
p = counts ** (1.0 / self.config.temperature)
action = int(self.rng.choice(self.n_actions, p=p / p.sum()))
next_obs, reward, done = env.step(action)
for key, item in zip(game, (obs, action, reward, root_value, counts / counts.sum())):
game[key].append(item)
obs = next_obs
return {k: np.array(v) for k, v in game.items()}
def sample_batch(self) -> dict:
"""Uniformly sample `batch_size` positions from stored episodes and stack their targets."""
rows = []
for _ in range(self.config.batch_size):
game = self.games[int(self.rng.integers(len(self.games)))]
t = int(self.rng.integers(len(game["actions"])))
rows.append(make_targets(game, t, self.config, self.n_actions, self.rng))
return {k: np.stack([r[k] for r in rows]) for k in rows[0]}
def train(self, env, n_iterations: int) -> list[dict]:
"""Alternate self-play and gradient steps. Returns per iteration: loss and mean self-play return."""
c, history = self.config, []
for _ in range(n_iterations):
new = [self.play_episode(env) for _ in range(c.episodes_per_iteration)]
self.games = (self.games + new)[-c.buffer_size :]
losses = [self.network.train_step(self.sample_batch()) for _ in range(c.train_steps_per_iteration)]
history.append({"loss": float(np.mean(losses)), "mean_return": float(np.mean([g["rewards"].sum() for g in new]))})
return history
def evaluate(self, env, n_episodes: int = 20) -> float:
"""Mean undiscounted return of greedy play (in `CorridorEnv`, the share of episodes reaching the goal)."""
return float(np.mean([self.play_episode(env, greedy=True)["rewards"].sum() for _ in range(n_episodes)]))- Repository
- Not published yet
- Needs
- Python 3.10 and NumPy
- Tests
- 9, run with
python3 -m unittest -v
Practice
Create env = CorridorEnv() and agent = MuZero(MuZeroConfig(), env.obs_dim, env.n_actions). Record agent.evaluate(env), call agent.train(env, n_iterations=12), and evaluate again. Print the value from agent.network.predict(agent.network.represent(obs[None])) for the one-hot observation of each cell, compare with the worked example, and explain why the learned values are lower. Then predict what agent.evaluate(CorridorEnv(mirror=True)) returns before you run it.
Check on learning
- The model is never trained to reconstruct observations. What does it gain from that, and what does it lose?
A way to think about it
Think of an environment with a detailed moving background that has no effect on reward. Then think about how you would debug a model you cannot look inside.
- The policy target comes from the search and the search uses the policy as its prior. Where does new information enter this loop?
A way to think about it
Find every quantity in the targets that comes from the real environment and not from the network.
- Why is the model unrolled for several steps during training, when the search only ever calls the dynamics function one step at a time?
A way to think about it
In the search, the output of one dynamics call becomes the input of the next. Ask what inputs the dynamics function would see in training if it were only ever trained on states that come straight from an observation.
- After training on the default corridor, the agent is evaluated on the mirrored corridor, where the goal is at the other end. What will it do, and what does that tell you about what the model has learned?
A way to think about it
The observation is a one-hot cell number and looks the same in both corridors. The learned dynamics and values encode where reward used to be.
- With
td_stepsset to 1 the value target relies almost entirely on the search's root value. With a very large setting it is a full Monte Carlo return. What is the trade-off?A way to think about it
One extreme trusts estimates that may be wrong early on. The other uses only real rewards from a single episode that was played with exploration noise.