◆ AI All-in-One

Level 3 In-Depth AI · Reinforcement Learning

Model-Based RL and World Models

Instead of learning only what to do, learn how the world works, then practise and plan inside that learned model. Dyna, planning with learned dynamics, World Models, Dreamer and MuZero, and why it saves so much real experience.

Level
●●●●● Advanced
Reading
14 min
To learn it well
1.5 hours to read, an afternoon to practise
↗ Plan a path here

Read first

Markov Decision ProcessesNeural Networks

This leads to

—
The full path from zero — 16 concepts before this one
  1. What Is AI?
  2. Probability Basics
  3. Vectors
  4. Derivatives and Slopes
  5. How Machines Learn
  6. Partial Derivatives and Gradients
  7. Matrices and Matrix Multiplication
  8. Supervised, Unsupervised and Reinforcement Learning
  9. Gradient Descent
  10. Supervised Learning
  11. Reinforcement Learning: The Basics
  12. Linear Regression
  13. The Perceptron
  14. Markov Decision Processes
  15. Logistic Regression
  16. Neural Networks
  17. Model-Based RL and World Models

Read them roughly in this order. See it on the concept map →

Why it matters

Most of the methods in this part of the guide are model-free. Q-Learning, Deep Q-Networks, Policy Gradients and Proximal Policy Optimization learn what to do directly from trial and error, without ever building an explicit picture of how the environment works. That makes them general, but enormously wasteful. The Nature DQN trained on 50 million frames per Atari game. A person gets the hang of most of those games in minutes. On a real robot, where every trial takes time, wears out motors and risks damage, that much trial and error is out of the question.

Model-based reinforcement learning learns a world model: a predictor of what happens next, s′,r≈model(s,a)s', r \approx \text{model}(s, a). With a model, the agent can rehearse in its head. It can try out sequences of actions, evaluate them, and improve its policy using imagined experience that costs nothing. That can make learning far more sample-efficient, meaning it needs far fewer real interactions.

The idea runs through the most impressive RL systems. AlphaZero plans with a perfect model (the rules). MuZero plans with a learned one. Dreamer learns to act in Minecraft, Atari and robot tasks largely by dreaming. As of late 2026, building general "world models", video-like simulators that predict how a scene responds to actions, is one of the most active research directions in AI, with applications to robotics, games and self-driving cars.

The intuition

Before moving furniture, you might rearrange it in your head first. "If I put the sofa there, the door won't open." You have a mental model of the room. You don't need to drag the sofa across the floor ten times to find out. Chess players do the same when they calculate moves on a board they're only imagining.

A model-based agent works the same way, in two interleaved loops:

  1. The real loop. Act in the world, collect what actually happens, and use those observations to improve the model.
  2. The imagined loop. Use the model to simulate many possible futures, and use them to improve the policy, or to choose the next action by planning.
Real environment slow, costly, sometimes dangerous to explore Replay of real experience (s, a, r, s′) actually observed World model learned: given s and a, predicts s′ and r Policy / value trained or planned using the model's predictions collect fit the model imagine rollouts choose imagined actions act solid: the real loop (expensive) · dashed: the imagined loop inside the model (cheap, can run many times per real step)
Fig. 1 The two loops of model-based RL. Real experience (solid arrows) trains a world model. The agent then improves its policy or plans using imagined rollouts inside the model (dashed arrows), which is cheap and can run many times for each real step.

The imagined loop is where the savings come from. One real step can feed hundreds of imagined ones. The catch is that the model is never perfect. Plan too far ahead in a flawed model and the errors pile up. Worse, an optimiser will actively seek out the places where the model is wrong in your favour, imagined shortcuts that don't exist. Most of the research in this area is about getting the benefit of imagination without being fooled by it.

Key idea Model-based RL learns how the world works, p(s′,r∣s,a)p(s', r \mid s, a), and then improves the policy or plans with simulated experience. It can need far fewer real interactions than model-free RL, but only as long as the agent doesn't trust its model beyond where the model is accurate.

How it works

What is a model?

In Markov Decision Processes terms, a model is an estimate of the dynamics function p(s′,r∣s,a)p(s', r \mid s, a). It comes in two flavours:

  • A distribution model gives the probabilities of every possible next state and reward. That is what value iteration needs.
  • A sample model generates one plausible next state and reward. That is easier to learn, and enough for simulation.

For a small discrete problem, a model can be a table of counts: "from ss taking aa, I landed in s′s' 8 times out of 10". For images or robot sensors it is a neural network, often a recurrent network or The Transformer that predicts the next state from a history.

Once you have a model, there are three main ways to use it:

  1. Generate extra training data for a model-free learner: Dyna, MBPO.
  2. Plan at decision time: search ahead from the current state each time an action is needed. Examples are MCTS in AlphaZero and MuZero, and model predictive control (MPC), which optimises a short sequence of actions, executes the first one, then re-plans from the new state.
  3. Learn behaviour entirely in imagination: train an actor-critic on rollouts of the model, as World Models and Dreamer do.

Dyna: learning, planning and acting in one loop

Dyna (Richard Sutton, 1990) is the simplest and clearest version. Each real step does three things:

  1. Direct RL: an ordinary Q-Learning update from the real transition (s,a,r,s′)(s, a, r, s').
  2. Model learning: record what happened. For a deterministic world, simply store Model(s,a)←(s′,r)\text{Model}(s, a) \leftarrow (s', r).
  3. Planning: nn times, pick a previously seen state–action pair at random, ask the model what happens, and apply the same Q-learning update to that imagined transition.

With n=0n = 0 this is plain Q-learning. With larger nn, each real step is followed by nn rehearsals. The effect is dramatic. In Sutton and Barto's maze, plain Q-learning needs about 25 episodes to find a good path. Dyna-Q with 50 planning steps finds it by the third episode. In the first episode the agent learns nothing useful until it stumbles on the goal. After that single success, planning spreads the news backwards through the whole remembered maze in one go, instead of one step per real visit.

Worked example. Suppose the agent has just reached the goal for the first time, from square AA, getting reward 1, with α=0.1\alpha = 0.1 and γ=0.95\gamma = 0.95. Q-learning sets Q(A,→)=0.1×1=0.1Q(A, \rightarrow) = 0.1 \times 1 = 0.1. Every other entry is still 0. Without planning, the square before AA only learns about this the next time the agent physically walks through it. With planning, a random replay might pick the stored transition (square before AA, →, AA, reward 0), and its update gives 0.1×(0+0.95×0.1)=0.00950.1 \times (0 + 0.95 \times 0.1) = 0.0095. That is small, but it is non-zero and points the right way, and it happened without taking a single real step. Fifty such replays per step quickly propagate value along the whole remembered path.

Learned models of high-dimensional worlds

Real observations are images, not grid squares, and predicting every pixel of the next frame is hard and wasteful. The breakthrough idea is to learn a compact latent state, a small vector summarising what matters, and to model latent dynamics in that space:

  • World Models (David Ha and Jürgen Schmidhuber, 2018) used three parts. A variational autoencoder compresses each frame into a small latent vector. A recurrent network predicts the next latent vector. A tiny controller picks actions from the latent state and the network's memory. They reported solving a car-racing task this way, and in a Doom game they trained the controller entirely inside the model's "dream" and then transferred it to the real game.
  • PlaNet (2019) and Dreamer (Danijar Hafner and colleagues, 2019–2020) learn a recurrent latent model from pixels, then train an Actor-Critic Methods entirely on imagined latent trajectories. Gradients flow back through the learned dynamics. DreamerV2 (2020) reached human-level performance on the Atari benchmark. DreamerV3 (preprint 2023, Nature 2025) used a single set of hyperparameters across more than 150 tasks. It was the first algorithm to collect diamonds in Minecraft from scratch, with no human data or hand-made curriculum, a long, sparse-reward task needing many steps in the right order.
  • MuZero (DeepMind, 2019) learns a latent model trained only to predict rewards, values and policies, the things planning needs, not the observations. It runs MCTS inside it (Monte Carlo Tree Search and AlphaGo). Its successor EfficientZero (2021) reached above-human average scores on the "Atari 100k" benchmark, which allows only 100,000 agent steps per game, about two hours of real-time play.

Why models fail: compounding error and exploitation

Two problems dominate:

  • Compounding error. A model that is 99% accurate per step is far less accurate over 100 steps. Each prediction feeds the next, and small errors grow. The fix is to keep imagined rollouts short (MBPO uses rollouts of only a few steps, starting from real states), or to re-plan frequently from the real current state (MPC).
  • Model exploitation. The policy optimiser will find any action sequence that the model wrongly thinks is great, such as walking through a wall the model has never seen. Ensembles of models help. Where they disagree, the model is unsure, and the planner can be told to be pessimistic there or to go and gather real data.

There is also a deeper question of what to model. Pixel-perfect prediction spends capacity on irrelevant details like the texture of the clouds. MuZero's answer is to model only what matters for value. Many researchers argue that the right world model predicts in an abstract representation space, not in pixels.

In code

Dyna-Q on Sutton and Barto's 6 × 9 maze (start on the left, goal at the top right, a few wall segments in between). The only difference between the three agents is n_planning, the number of imagined Q-learning updates after each real step.

import random
from collections import defaultdict

ROWS, COLS, START, GOAL = 6, 9, (2, 0), (0, 8)
WALLS = {(1, 2), (2, 2), (3, 2), (4, 5), (0, 7), (1, 7), (2, 7)}   # Sutton & Barto's Dyna maze
MOVES = [(-1, 0), (1, 0), (0, -1), (0, 1)]

def step(s, a):                                    # the real environment
    r, c = s[0] + MOVES[a][0], s[1] + MOVES[a][1]
    if not (0 <= r < ROWS and 0 <= c < COLS) or (r, c) in WALLS: r, c = s
    return (r, c), (1.0 if (r, c) == GOAL else 0.0)

def dyna_q(n_planning, episodes=30, alpha=0.1, gamma=0.95, eps=0.1):
    Q, model, steps_per_episode = defaultdict(float), {}, []
    greedy = lambda s: max(range(4), key=lambda a: (Q[(s, a)], random.random()))
    for _ in range(episodes):
        s, steps = START, 0
        while s != GOAL:
            a = random.randrange(4) if random.random() < eps else greedy(s)
            s2, r = step(s, a)                                        # 1. act in the real world
            Q[(s, a)] += alpha * (r + gamma * max(Q[(s2, b)] for b in range(4)) - Q[(s, a)])
            model[(s, a)] = (s2, r)                                   # 2. learn the model
            for _ in range(n_planning):                               # 3. plan: replay imagined steps
                (ps, pa), (ps2, pr) = random.choice(list(model.items()))
                Q[(ps, pa)] += alpha * (pr + gamma * max(Q[(ps2, b)] for b in range(4)) - Q[(ps, pa)])
            s, steps = s2, steps + 1
        steps_per_episode.append(steps)
    return steps_per_episode

random.seed(0)
for n in (0, 5, 50):
    runs = [dyna_q(n) for _ in range(20)]
    avg = [sum(r[i] for r in runs) / len(runs) for i in range(30)]
    print(f"planning steps n={n:2d}: steps to goal in episodes 1-8:",
          " ".join(f"{x:5.0f}" for x in avg[:8]), f"... episode 30: {avg[-1]:.0f}")

# planning steps n= 0: steps to goal in episodes 1-8:   652   771   590   315   334   198   244   144 ... episode 30: 18
# planning steps n= 5: steps to goal in episodes 1-8:   807   126    72    38    23    19    18    17 ... episode 30: 16
# planning steps n=50: steps to goal in episodes 1-8:   779    43    17    17    17    18    17    18 ... episode 30: 17

Every agent needs hundreds of steps in the first episode, because nobody knows where the goal is. After that, planning makes all the difference. With 50 planning steps the agent is on a near-shortest path (the shortest is 14 steps, and its ε-greedy exploration adds a few) by the third episode. Plain Q-learning is still wandering for hundreds of steps and takes about 25 episodes to catch up.

0 200 400 600 800 1 5 10 15 20 25 30 n = 0 (plain Q-learning) n = 5 planning steps n = 50 planning steps shortest path: 14 steps episode steps to reach the goal (average of 20 runs)
Fig. 2 Steps per episode for Dyna-Q in the maze, averaged over 20 runs, from the code above. Plain Q-learning (n = 0) needs about 25 episodes. With 5 planning steps per real step it needs about 5, and with 50 about 3.

The price is computation. With n=50n = 50, each real step costs 51 updates instead of 1. That is a good trade whenever real experience is the expensive part, which on a robot, in a slow simulator, or with real users it almost always is.

The next step: learned models for continuous control

For real tasks the model is a neural network. A minimal pattern is to fit a network to predict (s′,r)(s', r) from (s,a)(s, a) on collected data, then plan by random shooting: sample many random action sequences, roll each out in the model, and execute the first action of the best sequence. Then repeat at the next step. This sketch assumes Gymnasium and PyTorch and isn't run here:

import gymnasium as gym, numpy as np, torch, torch.nn as nn

env = gym.make("Pendulum-v1")                                # state: 3 numbers, action: 1 torque
model = nn.Sequential(nn.Linear(4, 128), nn.ReLU(), nn.Linear(128, 4))   # (s, a) -> (s' - s, r)
# 1. collect random transitions (s, a, r, s2) with env.step, then fit `model` by regression
#    on the target (s2 - s, r) with an MSE loss, like any supervised problem.

def plan(s, horizon=15, n_candidates=500):
    """Random-shooting MPC: imagine many action sequences, keep the best first action."""
    actions = torch.rand(n_candidates, horizon, 1) * 4 - 2   # torques in [-2, 2]
    state = torch.tensor(s, dtype=torch.float32).repeat(n_candidates, 1)
    total = torch.zeros(n_candidates)
    with torch.no_grad():
        for t in range(horizon):
            out = model(torch.cat([state, actions[:, t]], dim=1))
            state, total = state + out[:, :3], total + out[:, 3]
    return actions[total.argmax(), 0].numpy()                # execute only the first action

Common pitfalls

  • Trusting long imagined rollouts. Errors compound. Keep model rollouts short, branch them from real states, and re-plan often.
  • The optimiser exploits the model. If imagined returns soar while real returns don't, the policy has found the model's blind spots. Use ensembles, penalise uncertainty, and keep collecting real data.
  • Modelling the wrong things. Predicting every pixel wastes capacity. Predict in a learned latent space, or only what's needed for value and reward.
  • Stale models in changing worlds. If the environment changes (a door opens in the maze), a model learned earlier is now wrong. Sutton and Barto's Dyna-Q+ adds an exploration bonus for state–action pairs not tried in a long time, so the agent re-checks its beliefs.
  • Ignoring stochasticity. A deterministic model of a random world predicts an average outcome that may never actually happen, such as a ball that ends up "half left, half right". Use probabilistic models when outcomes are genuinely random.

Watch out A model-based agent's imagined performance is not evidence of real performance. Always evaluate in the real environment (or a trusted simulator) and compare the model's predicted returns with what actually happens.

Where it leads

  • Monte Carlo Tree Search and AlphaGo: planning with a perfect model (AlphaZero) or a learned latent model (MuZero).
  • Robotics and control: MPC with learned dynamics is widely used for robots that must learn from little data.
  • Video world models: as of late 2026, large generative models trained on video, such as DeepMind's Genie series (Genie 3 in 2025, Genie 4 as a research preview in October 2026), aim to simulate interactive worlds from images and actions. They connect this chapter to Video Generation and Diffusion Models, and they could become training grounds for agents.
  • Language models as world models: LLMs carry a great deal of implicit knowledge about how the world works, and agents built on them (AI Agents) increasingly "simulate" consequences in text before acting.
  • Back to the beginning: model-based and model-free RL are two ends of a spectrum. Most strong modern agents mix them, using a model for planning or data generation and model-free learning to fix the model's mistakes.

A bit of history

Planning with a known model is as old as dynamic programming (1950s) and as old as optimal control. Kenneth Craik suggested in 1943 that brains carry "small-scale models" of reality and use them to try out alternatives, an idea that inspired much later work. In RL, Richard Sutton introduced Dyna in 1990, uniting learning, planning and acting. Jürgen Schmidhuber explored neural-network world models for RL around the same time. In 2011, Marc Deisenroth and Carl Rasmussen's PILCO showed that a probabilistic model could let a real cart-pole learn to swing up and balance from only a handful of trials. The deep-learning era brought World Models (2018), PlaNet and MuZero (2019), Dreamer (2019–2020), and DreamerV3 (2023), whose Minecraft diamond result was published in Nature in 2025. As of late 2026, interactive video world models and "foundation models" for robotics are drawing large investments, and whether general world models are the missing ingredient for more capable AI agents is one of the field's big open questions.

Try it

  1. Run Dyna-Q with n_planning set to 1, 10 and 200. How do the curves change, and where do returns diminish?
  2. Make the maze change. After episode 15, remove the wall at (3, 2) to open a shortcut. Does the agent discover it? Does more planning help or hurt?
  3. Make the world stochastic: 10% of the time, the move goes in a random direction. The stored model (s2, r) now records only the last outcome. What goes wrong, and how would you store a distribution instead?

Hint for 2: the model only changes when the agent actually tries the new move, and an agent that trusts its model has little reason to try it. This is the problem Dyna-Q+ was designed for.

Check your understanding

5 quick questions. Pick an answer to see whether you were right and why. Your best score is saved on this device.

  1. In a maze, plain Q-learning needs about 25 episodes to find a good path, but Dyna-Q with 50 planning steps needs about 3. Where does the speed-up come from?

  2. An agent's imagined returns in its learned model keep rising, but its real returns do not. What is happening?

  3. A model is 99% accurate per step. Why is it risky to plan 100 steps ahead in it?

  4. What does model predictive control (MPC) do at each step?

  5. In a world where moves randomly go the wrong way 10% of the time, a Dyna agent stores only the last outcome for each state–action pair. What goes wrong?

Finished this chapter?

Learn more

Hand-picked courses, books, videos and tutorials for going deeper. See all resources →

Paper

World Models

David Ha & Jürgen Schmidhuber · 2018 · Intermediate · Free

A VAE compresses frames, an RNN predicts the next compressed frame, and a tiny controller is trained, even entirely inside the model's own 'dream'.

Article

World Models (interactive article)

David Ha & Jürgen Schmidhuber · 2018 · Intermediate · Free

An interactive web version of the World Models paper: watch an agent learn a compressed model of a racing game and then train inside its own dream.

Paper

Mastering Diverse Domains through World Models

Hafner, Pasukonis, Ba & Lillicrap · 2023 · Advanced · Free

DreamerV3: one set of hyperparameters across many domains, and the first algorithm to collect diamonds in Minecraft from scratch without human data.

Course

UCL Course on Reinforcement Learning

David Silver · 2015 · Intermediate · Free

Ten recorded lectures with slides by the lead researcher behind AlphaGo. Covers MDPs, dynamic programming, TD learning, function approximation, policy gradients and planning; follows Sutton & Barto closely.

Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/rl/model-based-rl.md