AnyLearn
All lessons
AIintermediate

What a World Model Is, and How an Agent Plans With One

A world model is a learned simulator that predicts what happens if an agent acts. This lesson covers its parts, why model-based learning needs far less real experience, Dyna versus model-predictive control, a working planner in code, and why a planner exploits model errors.

Updated · AI-authored, review-gated · how lessons are made

Progress1 / 10

The question a world model answers

A policy maps what an agent sees to what it does. A world model answers a different question: if I take this action in this situation, what happens next? It is a learned simulator. Trained on experience, it predicts how the environment will evolve, so an agent can try actions in imagination before committing to them in reality.

Definition: A world model is a learned, action-conditioned predictive model of an environment. Given a representation of the current state and an action, it predicts the next state, and usually the reward and what the agent would observe.

The term covers a wide range of systems, from a six-number linear model of a sliding block to a video generator that renders a playable 3D scene. What unites them is the action input. A model that only predicts the next video frame is a forecaster. A model that predicts the next frame given what the agent does can be used to choose what to do. This course follows that thread: the parts of a world model, planning in a learned latent space, interactive generative models built on video, and how these simulators are used and where they break.

Sign in free to save your progress and earn certificates.

Full lesson text

All 10 steps on one page, for reading, reference, and search.

Show

1. The question a world model answers

A policy maps what an agent sees to what it does. A world model answers a different question: if I take this action in this situation, what happens next? It is a learned simulator. Trained on experience, it predicts how the environment will evolve, so an agent can try actions in imagination before committing to them in reality.

Definition: A world model is a learned, action-conditioned predictive model of an environment. Given a representation of the current state and an action, it predicts the next state, and usually the reward and what the agent would observe.

The term covers a wide range of systems, from a six-number linear model of a sliding block to a video generator that renders a playable 3D scene. What unites them is the action input. A model that only predicts the next video frame is a forecaster. A model that predicts the next frame given what the agent does can be used to choose what to do. This course follows that thread: the parts of a world model, planning in a learned latent space, interactive generative models built on video, and how these simulators are used and where they break.

2. The parts of a world model

Reinforcement learning formalises an environment as a Markov decision process, covered in the lesson Markov Decision Processes. A world model learns the pieces of that process the agent is not given. Real agents rarely see the full state, only observations such as camera images, so most modern world models also learn a state representation:

ComponentWhat it learnsTypical form
Representation (encoder)a state sts_t from the observations so farCNN or transformer over images
Transition (dynamics)p(st+1∣st,at)p(s_{t+1} \mid s_t, a_t)recurrent net, transformer, diffusion model
Reward modelp(rt∣st,at)p(r_t \mid s_t, a_t)small regression head
Observation model (decoder)p(ot∣st)p(o_t \mid s_t)image decoder
Continuation modelwhether the episode ends at sts_tbinary classifier

The transition model is the heart; the others depend on the use. A planner needs a reward model to score imagined futures. A decoder is needed only if someone, or some training loss, must see predictions as images. Which heads to train and which to drop is one of the main design choices this course keeps returning to.

3. Model-free versus model-based

The lessons in Reinforcement Learning Foundations mostly teach model-free methods: Q-learning and policy gradients learn values or actions directly from experience and never predict what comes next. Model-based methods learn a model first and derive behaviour from it. The trade is structural:

Model-freeModel-based
What is learneda value function or policydynamics and reward, then behaviour
Signal per transitionone scalar rewarda whole next state, a dense supervised target
Real interactions neededmanytypically far fewer
Compute per decisionone network passpossibly many imagined rollouts
Main source of errornoisy value estimatesthe model being wrong
New goal, same worldretrainreuse the dynamics, swap the reward

The second row is the deep reason model-based methods tend to need fewer real interactions: every transition is a rich example of how the world works, not just a number saying how good it was. The fifth row is the price. A policy trained against a wrong model is confidently wrong, and the last lesson of this course is about paying that price.

4. Two ways to use a model

Once a model exists, there are two broad ways to turn it into behaviour, a distinction Sutton and Barto's Reinforcement Learning: An Introduction calls background planning and decision-time planning.

  • Background planning. Use the model to generate extra, imagined experience, and train an ordinary policy or value function on it. Richard Sutton's Dyna architecture (1990) is the template: every real transition updates both the value function and the model, and the model then supplies simulated transitions on which the same learning rule runs again. The agent acts with a fast learned policy; the model works offline, in the background. The Dreamer agents in the next lesson follow this pattern, in a learned latent space.
  • Decision-time planning. At every step, search through imagined futures starting from the current state, then act. Model-predictive control and tree search belong here. Each decision is expensive, but it is tailored to the exact situation. PlaNet and MuZero, also in the next lesson, plan this way, and MuZero also trains a policy that guides its search.

The two combine freely. A learned policy can propose candidate actions that a search then refines, and a search can produce better targets for training the policy.

5. The Dyna loop

Real experience feeds two learners. The world model turns it into imagined experience, which trains the policy a second time.

flowchart LR
  A["Act in the real environment"] --> B["Store real transitions"]
  B --> C["Fit the world model"]
  B --> E["Update policy and values"]
  C --> D["Generate imagined transitions"]
  D --> E
  E --> A

6. Planning by model-predictive control

The simplest decision-time planner treats the model as a black box and searches over action sequences. At each step it solves

at:t+H∗=arg⁡max⁡at:t+H∑k=0H−1r^(s^t+k,at+k),s^t+k+1=fθ(s^t+k,at+k),s^t=sta^{*}_{t:t+H} = \arg\max_{a_{t:t+H}} \sum_{k=0}^{H-1} \hat r\left(\hat s_{t+k}, a_{t+k}\right), \qquad \hat s_{t+k+1} = f_\theta\left(\hat s_{t+k}, a_{t+k}\right), \quad \hat s_t = s_t

where fθf_\theta is the learned dynamics and r^\hat r the learned reward, and HH is the planning horizon. Two classic optimisers:

  1. Random shooting. Sample many action sequences, roll each through the model, keep the best.
  2. Cross-entropy method (CEM). Sample from a Gaussian over sequences, keep the top few, refit the Gaussian to them, repeat a few times. This concentrates the search where returns are high.

Either way, the controller executes only the first action of the best sequence, observes the real result, and plans again from scratch. This receding-horizon trick matters: each new plan starts from a real, observed state, so a model error can mislead one plan but cannot accumulate across the whole episode.

7. A world model and a planner in 30 lines

Here is the whole loop on a toy problem: a block on a frictional track, pushed by a force between minus one and plus one, that should come to rest at position 1. The agent never sees true_step. It learns a linear model from 200 random pushes, then plans with random shooting.

import numpy as np
rng = np.random.default_rng(0)

def true_step(s, a):                      # the environment (unknown to the agent)
    pos, vel = s
    return np.array([pos + 0.1 * vel, 0.95 * vel + 0.1 * a])

# 1. Collect 200 random transitions and fit s' = [s, a] @ W by least squares
S, A, S2 = [], [], []
s = np.zeros(2)
for _ in range(200):
    a = rng.uniform(-1, 1)
    s2 = true_step(s, a)
    S.append(s); A.append(a); S2.append(s2); s = s2
X = np.column_stack([np.array(S), np.array(A)])
W, *_ = np.linalg.lstsq(X, np.array(S2), rcond=None)
print("learned model:\n", W.T.round(3))

# 2. Random-shooting MPC: imagine 500 action sequences, keep the best first action
def plan(s, goal=1.0, horizon=15, n=500):
    seqs = rng.uniform(-1, 1, size=(n, horizon))
    cost = np.zeros(n)
    sim = np.tile(s, (n, 1))
    for t in range(horizon):
        sim = np.column_stack([sim, seqs[:, t]]) @ W   # roll the MODEL, not the world
        cost += (sim[:, 0] - goal) ** 2
    return seqs[np.argmin(cost), 0]

s = np.zeros(2)
for step in range(60):
    s = true_step(s, plan(s))                # act in the real world, then replan
    if step % 15 == 14:
        print(f"step {step + 1}: position {s[0]:.3f}, velocity {s[1]:.3f}")

Output:

learned model:
 [[ 1.    0.1   0.  ]
 [-0.    0.95  0.1 ]]
step 15: position 0.618, velocity 0.786
step 30: position 1.002, velocity 0.051
step 45: position 0.999, velocity 0.004
step 60: position 1.000, velocity 0.035

The least-squares fit recovers the true coefficients (0.1 for velocity's effect on position, 0.95 for friction, 0.1 for the push) to three decimals, because the real dynamics happen to be linear. The planner then imagines 500 fifteen-step futures per decision, all inside the model, and the block settles at the goal.

Try it: After the model is fitted, change the friction in true_step to 0.80 so the model is now wrong. The block still settles at the goal, only several steps later, because every plan restarts from the real state. Replanning absorbs a modest model error; it cannot absorb a large one.

8. Knowing what the model does not know

Neural dynamics models are confident everywhere, including where they have never seen data. Chua, Calandra, McAllister and Levine's PETS (probabilistic ensembles with trajectory sampling, NeurIPS 2018) made uncertainty part of the model:

  • Each network outputs a distribution over next states, capturing aleatoric uncertainty, noise inherent in the system.
  • Several networks trained on different data samples form an ensemble. Where they disagree, the model is guessing: epistemic uncertainty, which more data would shrink.
  • The CEM planner propagates imagined trajectories through randomly chosen ensemble members, so plans that only look good under one lucky network score poorly on average.
Predict first

On the half-cheetah simulated locomotion task, roughly how many times fewer environment samples did PETS need than the model-free PPO algorithm?

9. What should the model predict?

The toy model above predicts the full state, because the state is two numbers. With camera images, predicting everything becomes the central design question, and the field has settled on three answers:

TargetWhat is predictedStrengthWeakness
Observationsfuture images, via a decoderrich training signal, inspectablespends capacity on irrelevant detail
Latent statesfuture embeddings, no pixel losscheap, abstracts away noiseneeds care to avoid collapse
Value-equivalentonly reward, value and policyspends nothing on irrelevant detailcannot be reused for a new goal or inspected

Most agents in the next lesson sit in the first row but plan in a compact latent space: they reconstruct images during training, yet imagine futures as small vectors. MuZero takes the third row to its logical end. The second row is the JEPA approach, covered in the lesson From I-JEPA to V-JEPA: World Models and Planning, which this course does not repeat. Interactive generative models, the subject of lesson 3, return to the first row at full fidelity, because there the pixels are the product.

10. Where the risk lives

Every advantage of a world model rests on one assumption: that its predictions are right in the places the agent will actually go. That assumption is weakest exactly where it matters most.

Gotcha: A planner is an optimiser, and an optimiser aimed at an imperfect model will find the imperfections. If the model wrongly predicts that some odd action yields a huge reward, the planner will choose that action precisely because it is wrong. Model errors are not random noise to a planner; they are targets.

The model is accurate where it has data, and the planner, by searching for high reward, tends to push into states the data never covered. This is why the methods in this course share a small set of defences: replanning from real observations, short imagined horizons, uncertainty estimates that penalise unfamiliar regions, and a loop that keeps collecting real data wherever the agent goes. The last lesson takes these failure modes, and the harder problem of evaluating a learned simulator at all, in detail.

Check your understanding

The lesson ends with a 5-question quiz. Take it in the player above to see your score.

  1. What distinguishes a world model from a model that simply forecasts the next video frame?
    • It produces higher-resolution frames
    • Its predictions are conditioned on the action the agent takes
    • It is always trained with reinforcement learning
    • It never uses an image decoder
  2. Why do model-based methods typically need fewer real interactions than model-free ones?
    • They use larger neural networks
    • They ignore the reward signal entirely
    • They only work in deterministic environments
    • Each transition provides a dense supervised target, the whole next state, rather than one scalar reward
  3. In model-predictive control, why execute only the first action of the best plan and then replan?
    • Each new plan starts from a real observed state, so model errors cannot accumulate over the whole episode
    • Executing the full plan would require a reward model
    • The first action is always the most rewarding one
    • Replanning reduces the number of imagined rollouts per decision
  4. In Sutton's Dyna architecture, what does the learned model contribute?
    • A replacement for the reward function
    • A search tree evaluated at every decision
    • Extra simulated transitions on which the same learning update is run
    • Labels that turn reinforcement learning into supervised learning
  5. In the 30-line code example, what are the 500 candidate action sequences rolled through when the planner scores them?
    • The true_step function, the real environment
    • The least-squares model W fitted from 200 random transitions
    • A neural network ensemble
    • A lookup table of previously visited states

Related lessons

AI
advanced

Dreaming in Latent Space: World Models, PlaNet, Dreamer and MuZero

How agents learn compact latent world models from pixels and plan inside them. Covers Ha and Schmidhuber's dream-trained controller, PlaNet's recurrent state-space model, Dreamer's actor-critic in imagination with lambda-returns in code, the later Dreamer versions, and MuZero's value-equivalent model.

12 steps·~18 min
AI
intermediate

Learned Simulators for Robots and Cars, and How World Models Fail

How world models train and test robots and driving systems, and where they break. Covers learning to walk in an hour with DayDreamer, driving world models, ranking robot policies in a video simulator, compounding error in code, model exploitation and its defences, hallucinated physics, and why evaluation is the hardest part.

10 steps·~15 min
AI
intermediate

Interactive Generative World Models: From Video to Playable Worlds

How a video generator becomes a world you can act in. Covers learning controls from unlabeled video with Genie's latent actions, a toy version in code, autoregressive drift and how GameNGen fights it, agents trained inside DIAMOND, the Genie 2 and 3 consistency gains, and how neural and engine simulators differ.

10 steps·~15 min
Science
advanced

How the Brain Computes: Prediction, Reward, and an Energy Budget

What brains compute and how theory meets data. Covers Marr's levels, dopamine as a reward prediction error with a working TD-learning model, predictive coding, Bayesian cue combination, the brain's energy budget, and an honest comparison with artificial neural networks, separating established findings from contested theories.

10 steps·~15 min