← All tutorials

Model-Based RL: Dyna, AlphaZero and MuZero

Learn how the world responds, then plan or practice inside that model.

On this page

1 Dyna 2 AlphaZero and MuZero 3 World Models and Dreamer 4 Model-based methods in practice 5 References
act in the real worldlearn the modelplan or imaginereal stepsmodelbetterpolicyAlphaZero is given the ruleslook ahead with a searchAlphaZeroMuZeropractice inside the modelDynaWorld ModelsDreamer
Figure 1. Real steps train the model; planning with it improves the policy that acts.

A model-based agent learns, or is given, a model of the world. It plans or practices inside that model, and acts in the real world to collect steps that improve the model, the policy or both (Figure 1). The methods in Value-Based RL, Policy Gradients: REINFORCE, Actor-Critic and PPO and Continuous-Action Actor-Critic: TD3 and SAC learn from real steps only; they are model-free.

1 Dyna

A chess player tries moves in their head before touching a piece; a model lets an agent do the same before spending real steps.

A model predicts the next state and reward from a state and a move; planning uses it to look ahead or practice without the real world. Dyna (Sutton 1991) runs the Q-learning update from Value-Based RL on imagined steps as well as real ones.

A real step into the goal teaches one square; the model lets the agent replay the square before it without moving (Figure 2).

Q 0 to 0.0095one square backQ 0 to 0.1next to the goalGimagined replayreal step, r = 1
Figure 2. A real step into the goal, then an imagined replay one square back.
This is the Dyna-Q update: the same Q-learning update as Value-Based RL; the model only supplies extra steps to apply it to.
target = r + γ · max Q(s′, a′)
Q(s, a), the Q-value, is the future reward expected from move a in state s. r is the reward the step earned, 1 for the step into the goal. max Q(s′, a′) is the best score over every move a′ in the next state s′. γ, the discount, shrinks that future score for the delay, 0.95 in the book’s maze.
Q(s, a) ← Q(s, a)
+ α · (target − Q(s, a))
α, the learning rate, 0.1 here, moves the score that fraction of the way toward the target (the arrow means replace with). Together: the real step gives the square next to the goal 0.1, and a replay then carries value one square further back, 0.0095 (Figure 2). Builds on the Q-learning card of Value-Based RL; Dreamer in Section 3 is the other way to use a model.

Dyna-Q adds n imagined steps from a remembered model after each real one (Sutton and Barto’s RL textbook, 2018, section 8.2). The code runs one Dyna-Q step on the book’s 6 by 9 maze. env_step(s, a) is the maze’s rule, returning (r, s_next).

import random
import numpy as np

alpha, gamma, eps, n = 0.1, 0.95, 0.1, 5   # book's maze
Q = np.zeros((54, 4))   # 6 x 9 squares, 4 moves
model = {}              # (s, a) -> (r, s_next)
GOAL = 8                # top-right square, episode ends

def q_update(s, a, r, s_next):
    future = 0.0 if s_next == GOAL else Q[s_next].max()
    Q[s, a] += alpha * (r + gamma * future - Q[s, a])

def dyna_step(env_step, s):
    if random.random() < eps:
        a = random.randrange(4)
    else:
        a = int(random.choice(np.flatnonzero(Q[s] == Q[s].max())))
    r, s_next = env_step(s, a)
    q_update(s, a, r, s_next)
    model[(s, a)] = (r, s_next)
    for _ in range(n):
        (s_m, a_m), (r_m, s_m_next) = random.choice(list(model.items()))
        q_update(s_m, a_m, r_m, s_m_next)
    return s_next
  1. 1Sets the book’s maze values, the Q-table, an empty model and the goal square.
  2. 2The Q-learning update, line 2 of the Q-learning card above, with no future past the goal.
  3. 3Picks a move ε-greedily, the best-scoring move (ties at random) except for a small chance ε of a random one, and takes one real step.
  4. 4Learns from the real step and stores it in the model.
  5. 5Replays n imagined steps, each a stored step picked at random (the book picks a seen state, then a move tried there); n is the count that varies in Figure 3.

Each imagined step can carry value, a square’s best Q, one square further back from the goal, so the reward found there spreads through the maze without new real steps (the RL textbook, Example 8.1). Where a square has no value yet, all four moves there score 0 and the agent picks one at random; once value reaches the start, following the best move from each square gives a route to the goal. Reaching the goal ends an episode, and the agent starts again from the start.

Until the goal is first found every value is 0, so imagined steps change nothing and every n takes the same real steps to find it, on average. After that, a larger n forms the route in fewer real steps on average, at the cost of n + 1 updates per real step, and n = 0 is plain Q-learning, where each real step updates only the square it left. One random run can occasionally flip that order.

At step 150, no route yet.

Figure 3. Value spreads from G ①; at the start ② a route forms ③ (one random run).

In the book’s averaged runs a good route took about 25, 5 and 3 episodes for n = 0, 5 and 50. Imagined steps matter most when real steps are slow or costly, as for a robot. DQN’s experience replay reuses stored real steps the same way, with a network in place of the table.

AlphaZero (Silver et al. 2018) uses a game’s rules for a tree search, a look-ahead over move sequences that a network steers, and learns from games against itself.

In one Go position the network’s first guesses are rough; 100 search visits sharpen them (Figure 4).

network psearch π (visits 70, 25, 5)0.60.70move 10.30.25move 20.10.05move 3+10−1z = +1v 0.2resultvalue term (1 − 0.2)² = 0.64move term 0.77 (0.75 if p matched π)
Figure 4. The search’s chances are sharper than the network’s guesses (toy numbers).
This is the AlphaZero loss: the search turns the network’s guesses into better move chances, and training makes the network match the search and the final result, so the next search starts better.
(p, v) = f(s)
From a position s, one network f gives p, a probability for each move, and v, the predicted result: 0.6, 0.3, 0.1 and 0.2 in Figure 4. The rules produce each next position. The search tries moves with high p, few visits and a high average v so far, and scores each position where a line stops with v instead of playing the game to the end.
π(a) ∝ N(a)
N(a) counts how often the search tried move a from the current position, and π is those counts scaled to probabilities (∝ reads “in proportion to”): visits 70, 25 and 5 of 100 give 0.70, 0.25 and 0.05. The move played is drawn from π or is its most visited move.
loss = (z − v)2 − π · log p
z is the game’s final result, −1 for a loss, 0 for a draw, +1 for a win. The first term is a squared gap to a target, as in the critic loss on Policy Gradients, here the real result: 0.64 in Figure 4. The second adds over moves the search’s chance times the network’s log chance (natural log; the categorical cross-entropy), where · multiplies move by move and adds; it is smallest when p matches π: 0.77, against 0.75 if they matched. The paper adds weight decay. Together: one loss teaches value and move chances from self-play. Builds on Dyna’s use of a model to plan ahead and on the return and the value of RL Basics; the MuZero card, next, repeats this loss at each unrolled step.

MuZero (Schrittwieser et al. 2020) learns the model instead. MuZero is not told the rules of Go; it must also predict what each move pays (Figure 5).

boardreprh0p, vh1p, vh2p, vmoverewardmoverewardfh0 = repr(board): a hidden state, not a picturedynamics(h0, move): predicted reward 0.2(real 0), next state h1f(h1): move chances 0.6, 0.3, 0.1, value 0.2this step’s loss 0.04 + 0.64 + 0.77 = 1.45
Figure 5. MuZero’s search runs on hidden states it imagines, never on pictures of the board.
This is the MuZero loss. MuZero learns its own rules inside a hidden state, a list of numbers the network makes up, so its loss is the AlphaZero loss at the root and at each of the 5 unrolled steps, plus a reward term at each unrolled step.
h0 = repr(observation)
repr, the representation network, turns what the agent sees, here the board, into h0: the first label in Figure 5.
(r, hk+1) = dynamics(hk, a)
The dynamics network stands in for the rules: from hidden state hk and move a, it predicts the reward and the next hidden state; the second label, a predicted reward of 0.2 where the real reward was 0.
(p, v) = f(hk)
The AlphaZero network read from the hidden state: the third label. The hidden state only has to predict rewards, moves and values, never to redraw the board.
loss = Σk [ℓ(uk, rk)
+ ℓ(zk, vk) + ℓ(πk, pk)]
MuZero replays a stored game and unrolls the dynamics 5 moves along the moves really played. ℓ is an error between a target and a prediction: squared error for reward and value in board games, the cross-entropy for p (the MuZero paper). The sum over the steps k pulls each predicted reward toward the reward u really seen, each value toward the observed return, and each p toward the search’s π at that step: one step’s loss is 1.45 in Figure 5. Together: the three predictions the search needs, trained together. Builds on the AlphaZero card; Dreamer, next, also learns a model but trains an actor and critic in it.

3 World Models and Dreamer

World Models (Ha and Schmidhuber 2018) train a small controller inside a learned model of the game, then run it for real. Making the model’s predictions more random kept the controller from exploiting the model’s errors. An agent that counts only the reward inside a fixed window of imagined steps turns shortsighted. Dreamer (Hafner et al. 2020) learns a compact hidden-state model from replayed experience and trains its actor and critic on imagined runs inside it; the critic estimates the reward past the window, so the actor still aims for rewards that come later.

Dreamer’s walker practices inside its own model of the body, a few steps at a time (Figure 6).

step 1r = 0× 1step 2r = 0× 0.9step 3r = 1× 0.81criticv = 2× 0.729return 2.27without the critic: 0.81
Figure 6. A walker imagining 3 steps (toy), then the critic counts the rest.

The reward 1 comes when it reaches walking speed; γ is 0.9, as in the return strip of RL Basics.

This is the imagined return: add the rewards the model imagines over a short window, then let the critic’s guess stand in for everything after it.
return = r0 + γ r1
+ … + γH−1 rH−1 + γH v(sH)
The model imagines H steps ahead and predicts a reward rk at each; γk discounts it as in the return of RL Basics. γH v(sH) is the critic’s guess for every reward past the window: rewards 0, 0 and 1 and the critic’s 2 make 2.27 in Figure 6, against 0.81 without the critic. This is the k-step estimate of the Dreamer paper (section 4, eq. 5); Dreamer then averages such estimates over several window lengths (eq. 6) and trains the actor to raise it. Together: the return of RL Basics, cut after H steps and finished by the critic, as in the n-step return figure of Policy Gradients, section 2. Builds on the MuZero card’s learned model rolled forward on hidden states and on the critic of actor-critic methods; it is the last card on this page.

4 Model-based methods in practice

What is known about the rules and what a real step costs decide the pick; Choosing a method sets these methods beside the model-free ones.

MethodWhenHow often it learns or plansCarriesCost
Dyna-Qfew states that fit in a table, rules unknown, real steps cost more than computeone real update plus n imagined ones per real step; more n gets more from each real step at more compute, 0 is plain Q-learning; 5 or 50 in the bookthe Q-table and the stored model of seen stepsn + 1 updates per real step; maze.py
AlphaZerorules known and exactly simulated, as in board games800 search simulations per move; more simulations look further ahead at more compute per move, and AlphaZero played stronger with more thinking time per move (the AlphaZero paper’s thinking-time plot); network trained 700,000 steps on batches of 4,096 positionsthe network and its stored self-play games5,000 first-generation TPUs (Google’s AI chips) playing, 16 second-generation TPUs training
MuZerorules unknown, look-ahead matters800 simulations per move in board games, 50 in Atari, which has far fewer moves to pick from; more helped a lot in Go but leveled off near 100 in Atari, where even 1, the policy alone, played well (the MuZero paper’s search-scaling plots); the dynamics unroll 5 moves per replayed sample, always 5 in the paper, which does not test other values; a longer unroll trains the model to predict further ahead at more compute per sample; the playing copy refreshes every 1,000 training stepsthe three networks and a replay buffer of past gamesone learned-model step per imagined move
World Modelsrules unknown, pixels in; the idea Dreamer builds on10,000 random runs first, then the vision model, which compresses each frame, the memory model, which predicts the next compressed frame, then the controller by evolution, trying many random weight changes and keeping the bestthe vision, memory and controller modelscontroller 867 weights, vision model 4.3 million
Dreamerrules unknown, real steps costlybatches of 50 replayed sequences of 50 steps; imagines 15 steps ahead, 10 in Atari; a longer window counts more imagined reward before the critic takes over, and with its critic Dreamer stayed robust to the window length and did well even with short ones, unlike a version without a critic (the Dreamer paper’s horizon plot)the world model, actor, critic and a replay bufferno real steps for the actor and critic

The methods in this series ran on small examples such as a cliff walk, CartPole and a maze. What does it take to train one on a real agent, the banana collector from RL Basics that sees 37 sensor numbers? Deep Q-Networks (DQN) builds that agent with replay, a target network and the Double and Dueling changes from Value-Based RL.

5 References

  1. Sutton, R. S., and Barto, A. G. (2018). Reinforcement Learning: An Introduction (2nd ed.). MIT Press. Book site.
  2. Sutton, R. S. (1991). Dyna, an Integrated Architecture for Learning, Planning, and Reacting. ACM SIGART Bulletin, 2(4), 160-163.
  3. Silver, D., et al. (2018). A general reinforcement learning algorithm that masters chess, shogi, and Go through self-play. Science, 362, 1140-1144.
  4. Schrittwieser, J., et al. (2020). Mastering Atari, Go, Chess and Shogi by Planning with a Learned Model. Nature, 588, 604-609. arXiv:1911.08265.
  5. Ha, D., and Schmidhuber, J. (2018). World Models. arXiv:1803.10122.
  6. Hafner, D., et al. (2020). Dream to Control: Learning Behaviors by Latent Imagination. ICLR. arXiv:1912.01603.