AnyLearn
All lessons
AIadvanced

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.

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

Progress1 / 12

Why plan in a latent space

The previous lesson's planner rolled hundreds of futures through a six-number model. With camera input that recipe breaks: a single 64 by 64 colour frame is 12,288 numbers, and a planner may need thousands of imagined rollouts per decision. Predicting every future pixel of every candidate is far too slow, and most of those pixels do not matter for the decision.

The fix shared by every agent in this lesson is to learn a compact latent state from images and run the dynamics there:

  • Ha and Schmidhuber's World Models compress each frame, learn the dynamics of the compressed codes, and evolve a tiny controller on top.
  • PlaNet learns a latent dynamics model and plans in it at every step.
  • Dreamer learns the same kind of model but trains an actor and critic entirely on imagined latent trajectories.
  • MuZero drops images altogether and learns a latent state that only has to predict reward, value and policy.

Read them as four answers to two questions from the previous lesson: what should the model predict, and is it used for background or decision-time planning?

Sign in free to save your progress and earn certificates.

Full lesson text

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

Show

1. Why plan in a latent space

The previous lesson's planner rolled hundreds of futures through a six-number model. With camera input that recipe breaks: a single 64 by 64 colour frame is 12,288 numbers, and a planner may need thousands of imagined rollouts per decision. Predicting every future pixel of every candidate is far too slow, and most of those pixels do not matter for the decision.

The fix shared by every agent in this lesson is to learn a compact latent state from images and run the dynamics there:

  • Ha and Schmidhuber's World Models compress each frame, learn the dynamics of the compressed codes, and evolve a tiny controller on top.
  • PlaNet learns a latent dynamics model and plans in it at every step.
  • Dreamer learns the same kind of model but trains an actor and critic entirely on imagined latent trajectories.
  • MuZero drops images altogether and learns a latent state that only has to predict reward, value and policy.

Read them as four answers to two questions from the previous lesson: what should the model predict, and is it used for background or decision-time planning?

2. Vision, memory, controller

David Ha and Jürgen Schmidhuber's World Models (2018) split the agent into three parts, with sizes from the paper's interactive article for the CarRacing driving task:

PartJobCarRacing size
V, a variational autoencodercompress each frame into a 32-number code ztz_tabout 4.3 million parameters
M, an MDN-RNNpredict the next code as a mixture of 5 Gaussians, from ztz_t, the action and its LSTM memory hth_t256 hidden units, about 422,000 parameters
C, a linear controllermap ztz_t and hth_t to an action867 parameters

V and M are trained without any reward, on 10,000 rollouts of a random policy. C is then optimised with CMA-ES, an evolution strategy, using a population of 64 candidates that each run 16 rollouts.

Key idea: Almost all the capacity sits in the world model and almost none in the policy. Because V and M already summarise what the scene is and where it is heading, a controller with 867 numbers is enough to drive.

3. What the memory buys

The task counts as solved at an average of 900 points over 100 random tracks. The paper's ablation isolates the contribution of the learned dynamics:

CarRacing-v0 score, average over 100 random tracks
points02004006008001k343591652632906DQNA3C continuousA3C discreteV only (no memory)Full world model
Source: Ha and Schmidhuber, World Models (2018), results table; 900 counts as solved

Feeding the controller only the compressed frame ztz_t gives 632 points with a huge spread (plus or minus 251). Adding the memory state hth_t from M lifts the score to 906 plus or minus 21, the only entry above the 900 threshold in the paper's comparison, ahead of DQN (343) and both A3C variants (591 and 652). The memory state carries what a single frame cannot: speed, heading, and where the track is about to bend. That is the predictive part of the world model doing its job, even though here M is only used as a feature extractor, not yet as a place to train.

4. Training inside the dream

The paper's second experiment, the VizDoom game Take Cover, goes further: the controller is trained entirely inside M, which samples imagined frames and imagined deaths, and only then is it tested in the real game. Solving means surviving more than 750 time steps on average. A temperature τ\tau scales the randomness of M's predictions.

Predict first

At temperature 0.10 the controller survives 2,086 steps on average inside the dream, almost the 2,100-step maximum. How well does that controller do in the real game?

The paper names the problem directly: the controller can find an adversarial policy that fools the dynamics model. That sentence is the seed of the failure-mode lesson at the end of this course.

5. PlaNet's recurrent state-space model

Hafner and colleagues' PlaNet (ICML 2019) trains the encoder and dynamics jointly, and its core, the recurrent state-space model (RSSM), is still the backbone of the Dreamer line. Its state has two halves:

ht=f(ht−1,st−1,at−1)deterministic memoryh_t = f\left(h_{t-1}, s_{t-1}, a_{t-1}\right) \qquad \text{deterministic memory} prior: st∼p(st∣ht)posterior: st∼q(st∣ht,ot)\text{prior: } s_t \sim p\left(s_t \mid h_t\right) \qquad \text{posterior: } s_t \sim q\left(s_t \mid h_t, o_t\right)

The deterministic path hth_t, a recurrent network, carries information reliably over many steps. The stochastic part sts_t represents what cannot be known for sure, letting the model predict several possible futures. The paper reports that both are needed: purely stochastic models struggle to remember, purely deterministic ones cannot express uncertainty.

Training is a variational autoencoder stretched across time. The posterior sees the real image; the prior must guess the same state without it. The loss reconstructs images and rewards from the posterior and penalises the KL divergence between posterior and prior. The prior is exactly what planning uses, because imagined futures have no images. PlaNet's latent overshooting adds multi-step versions of that KL term, so the prior stays accurate several steps ahead, not just one.

6. One step of the RSSM

During training the posterior sees the image; during imagination only the prior runs, so no image is ever decoded.

flowchart LR
  P["Previous memory, state and action"] --> H["Deterministic memory h_t"]
  H --> PR["Prior: guess s_t without the image"]
  O["Camera image o_t"] --> PO["Posterior: infer s_t from h_t and the image"]
  H --> PO
  PO --> D["Decode image and reward for the loss"]
  PO --> K["KL penalty between posterior and prior"]
  PR --> K
  PR --> I["Imagination: roll the prior forward"]

7. Planning with PlaNet

With the RSSM trained, PlaNet acts by the model-predictive control loop from the previous lesson, run entirely in latent space:

  1. Infer the current latent state from recent images with the posterior.
  2. Use the cross-entropy method to search over action sequences, rolling each one forward with the prior and summing predicted rewards only. No images are generated during planning.
  3. Execute the first action of the best sequence, observe the new image, and repeat.

Google Research's announcement of PlaNet describes the agent evaluating 10,000 imagined action sequences at each step, cheaply, because each imagined step is a small vector operation rather than an image. On image-based continuous control tasks with contacts, partial observability and sparse rewards, the same announcement reports PlaNet using on average about 50 times less environment interaction than the model-free agents A3C and D4PG while competing with them on final performance.

In practice: The cost moves from data to compute. PlaNet needs few real episodes, but every single action requires a full CEM search. That per-step cost is what Dreamer set out to remove.

8. Dreamer: learning behaviour by imagination

Dreamer (Hafner, Lillicrap, Ba and Norouzi, ICLR 2020) keeps the RSSM but replaces online search with background planning. From states sampled out of real experience, it imagines trajectories a fixed number of steps ahead with the prior, then trains two networks on those imagined trajectories alone:

  • an actor that picks actions in latent states;
  • a critic that predicts the value of latent states, so rewards beyond the imagination horizon are not ignored.

The critic's regression target is the lambda-return, a blend of short and long lookahead:

Vtλ=rt+γ[(1−λ) v(st+1)+λ Vt+1λ],VHλ=v(sH)V^{\lambda}_t = r_t + \gamma \left[ (1-\lambda)\, v(s_{t+1}) + \lambda\, V^{\lambda}_{t+1} \right], \qquad V^{\lambda}_H = v(s_H)

Because the whole imagined trajectory is a differentiable computation, Dreamer trains the actor by backpropagating value gradients through the learned dynamics: it asks how a small change in each action would change the predicted return, and follows that gradient. The original paper reports that on 20 visual control tasks Dreamer exceeded existing approaches in data efficiency, computation time and final performance. Acting is now one fast actor pass; all the planning happened beforehand, in imagination.

9. Lambda-returns in code

The lambda-return is short enough to compute by hand. Here it runs on one imagined five-step trajectory where the world model predicts a single reward at step 2:

import numpy as np

def lambda_returns(rewards, values, gamma=0.99, lam=0.95):
    """rewards[t] and values[t] for t = 0..H-1, plus values[H] to bootstrap."""
    H = len(rewards)
    out = np.zeros(H)
    nxt = values[H]                       # the critic's guess beyond the horizon
    for t in reversed(range(H)):
        nxt = rewards[t] + gamma * ((1 - lam) * values[t + 1] + lam * nxt)
        out[t] = nxt
    return out

# One imagined 5-step rollout: the world model predicts rewards,
# the critic scores each imagined latent state.
rewards = np.array([0.0, 0.0, 1.0, 0.0, 0.0])
values  = np.array([0.8, 0.9, 0.5, 0.4, 0.4, 0.4])

for lam in (0.0, 0.95, 1.0):
    print(f"lambda={lam}:", lambda_returns(rewards, values, lam=lam).round(3))

Output:

lambda=0.0: [0.891 0.495 1.396 0.396 0.396]
lambda=0.95: [1.296 1.331 1.389 0.392 0.396]
lambda=1.0: [1.36  1.374 1.388 0.392 0.396]

Read the first column. With λ=0\lambda = 0 the target at step 0 is the one-step TD target, reward 0 plus the discounted critic value 0.9, giving 0.891: it trusts the critic completely, and the critic undervalues the states before the reward. With λ=1\lambda = 1 the imagined reward at step 2 flows back undiluted, giving 1.36. The value 0.95 sits close to that end while still leaning slightly on the critic, which damps noise from long imagined rollouts. The steps after the reward (columns 4 and 5) barely change, because nothing interesting is imagined there.

10. From DreamerV2 to Dreamer 4

Later versions kept the recipe and attacked robustness and scale:

VersionMain changeReported result
DreamerV2 (ICLR 2021)discrete categorical latent statesfirst agent to reach human-level performance on the 55-game Atari benchmark by learning behaviour inside a separately trained world model
DreamerV3 (Nature, 2025)normalisation, balancing and transformation tricks so one configuration works everywherea single configuration beats specialised methods on over 150 tasks; first algorithm to collect diamonds in Minecraft from scratch without human data or curricula
Dreamer 4 (Hafner, Yan and Lillicrap, 2025 preprint)a scalable transformer world model that learns mostly from unlabeled video, with real-time inference on a single GPUfirst agent to obtain Minecraft diamonds purely from offline data, a task needing over 20,000 mouse and keyboard actions from raw pixels

A representative DreamerV3 trick is the symlog transform, which squashes targets of wildly different scale (a game scoring 1 point per level, another scoring thousands) into one range before regression:

symlog⁡(x)=sign⁡(x) ln⁡(∣x∣+1)\operatorname{symlog}(x) = \operatorname{sign}(x)\,\ln\left(|x| + 1\right)

Dreamer 4's shift matters for the next lesson: once a world model learns its dynamics mostly from video without actions, it starts to look like a video generator with controls.

11. MuZero: a model of only what matters

Schrittwieser and colleagues' MuZero (Nature, 2020) takes the value-equivalent answer from the previous lesson to its end. It learns three functions:

s0=hθ(o1,…,ot),rk,sk=gθ(sk−1,ak),pk,vk=fθ(sk)s^0 = h_\theta\left(o_1, \dots, o_t\right), \qquad r^k, s^k = g_\theta\left(s^{k-1}, a^k\right), \qquad p^k, v^k = f_\theta\left(s^k\right)

The representation hh encodes past observations into a hidden state, the dynamics gg steps it forward and predicts the reward, and the prediction ff outputs a policy and a value. Training unrolls the model for 5 hypothetical steps along real trajectories and matches only rewards, values and the search's improved policy. The paper is explicit that there is no requirement for the hidden state to capture what would be needed to reconstruct the observation.

At decision time MuZero runs Monte Carlo tree search inside this learned model, with 800 simulations per move in board games and 50 in Atari. Without being given the rules, it matched AlphaZero's superhuman play in Go, chess and shogi, and on 57 Atari games reached a median human-normalised score of 2041.1 percent, against 1920.6 percent for the model-free R2D2 in the paper's comparison table.

12. Four designs side by side

World ModelsPlaNetDreamer lineMuZero
Latent trained toreconstruct framesreconstruct frames and rewardsreconstruct frames, rewards, continuationpredict reward, value, policy only
DynamicsMDN-RNNRSSMRSSM, later a transformerdeterministic learned network
Behaviour fromevolved linear controllerCEM search every stepactor-critic trained in imaginationtree search guided by a learned policy
Planning stylebackgrounddecision-timebackgrounddecision-time and learned policy
Signature domainCarRacing, VizDoompixel continuous controlAtari, control, Minecraft, real robotsGo, chess, shogi, Atari

Gotcha: "Value-equivalent" is not free. A model that only predicts what matters for one reward cannot be repurposed for a different goal, and it cannot be inspected: there is no frame to look at when it goes wrong. Reconstruction-based models pay for irrelevant pixels but stay reusable and debuggable. That trade, more than any benchmark, decides which design fits a problem.

Check your understanding

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

  1. In Ha and Schmidhuber's CarRacing agent, where does almost all of the learned capacity sit?
    • In the linear controller C, which has millions of parameters
    • In a reward model trained before the vision model
    • In the vision model V and memory model M, while C has only 867 parameters
    • Evenly split between V, M and C
  2. Why did the VizDoom controller trained in a dream at temperature 0.10 score worse than random in the real game?
    • The low-temperature dream collapsed so monsters barely fired, and the controller exploited that model error
    • The controller was too small to learn the task
    • Temperature 0.10 made the dream too difficult to learn in
    • The real game used a different action space
  3. In PlaNet's recurrent state-space model, what does the deterministic path contribute?
    • It decodes images during planning
    • It replaces the reward model
    • It removes the need for a KL penalty
    • Reliable memory over many steps, while the stochastic part captures uncertainty about the future
  4. How does Dreamer turn its world model into behaviour, compared with PlaNet?
    • Both run a CEM search at every step
    • Dreamer trains an actor and critic on imagined latent trajectories, while PlaNet searches online at every step
    • Dreamer uses Monte Carlo tree search, while PlaNet evolves a controller
    • Dreamer trains only on real transitions, while PlaNet trains on imagined ones
  5. What is MuZero's learned model trained to predict?
    • The next observation, pixel by pixel
    • The game rules as explicit symbolic transitions
    • Rewards, values and policies, with no requirement to reconstruct observations
    • Only the final outcome of the game

Related lessons

AI
intermediate

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.

10 steps·~15 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