Simple Algorithm
Reinforcement Learning · Bootstrapping · 22 min

World Models: Learning in Imagination

Latent dynamics models that let agents practice in their own dreams.

An agent that sees its world through a camera cannot keep a table of states: images rarely repeat, and a single frame does not even show which way things are moving. A world model compresses what the agent has seen into a small internal state, learns how that state changes with each action, and lets the agent practice inside it. This lesson builds the pieces, follows an agent that learned to dodge fireballs entirely in its own dream, and opens up Dreamer's loop: collect, model, imagine, improve.

What you’ll learn

  • Name the parts of a world model (filter, latent transition, reward and continuation heads, optional decoder) and explain why its state must summarize the history of observations.
  • Explain how Ha and Schmidhuber's controller learned inside a dream, and how the dream's temperature traded exploitability against learnability.
  • Write Dreamer's training loop and compute a λ-return on an imagined trajectory.
  • Distinguish model errors that real experience corrects from those it does not, and describe the defenses: short imagination from real states, critics, and exploration toward what the model does not know.
  • Place transformer, diffusion and video world models in the same framework.

From pixels to a state you can predict

Dyna's table model keys on exact states. With camera images that fails twice. Images almost never repeat, so a table entry would never be reused. And one image is an observation, not a state: a single frame of a ball shows where it is, not where it is going. From the agent's point of view the environment is a POMDP, and whatever the model calls its state must summarize the history of observations and actions, an agent state.

A world model therefore does three jobs. It filters: it folds each new observation oto_t into a compact latent state st\mathbf s_t. It predicts: a latent transition model guesses st+1\mathbf s_{t+1} from st\mathbf s_t and ata_t without seeing ot+1o_{t+1}. And it scores: heads predict the reward and whether the episode continues. Many world models also decode st\mathbf s_t back into an image, not because the agent needs pictures but because reconstructing them gives the model a rich training signal.

PartComputesTrained to
Filter (encoder)st\mathbf s_t from st−1\mathbf s_{t-1}, at−1a_{t-1} and the new observation oto_tMake the other predictions possible
Latent transition (prior)A distribution over st+1\mathbf s_{t+1} from st\mathbf s_t and ata_t alonePredict what the filter will infer once ot+1o_{t+1} arrives
Reward and continuation headsr^\hat r and the probability that the episode goes onMatch observed rewards and terminations
Decoder (optional)A reconstruction of oto_t from st\mathbf s_tReproduce the observation
During training the filter sees real observations. During imagination only the transition runs, so everything the agent learns in imagination depends on how well the transition predicts what the filter would have seen.
Check your understanding

Why can't a world model for a ball game predict the next frame from the current frame alone, however large its network?

  1. Frames have too many pixels for a network to process
  2. A single frame does not determine the ball's velocity, so the next frame is not a function of it; the model's state must carry information from earlier frames
  3. The next frame depends only on the action, not on the current frame
  4. Rewards cannot be predicted from images
Show the answer

B. A single frame does not determine the ball's velocity, so the next frame is not a function of it; the model's state must carry information from earlier frames

The next frame depends on things one frame does not show, such as velocities or objects that just left the screen. That is partial observability, and the remedy is a recurrent state that integrates the history. Atari agents stack the last few frames for the same reason.

Learning inside a dream

Ha and Schmidhuber (2018) built an influential early agent of this kind from three parts. V, a variational autoencoder, compresses each 64×64 frame into a latent vector zz (32 numbers for a car-racing game, 64 for a Doom scenario). M, a recurrent network with a mixture-density output, predicts a mixture of five Gaussians over the next zz from the current zz, the action and its own hidden state hh. C, the controller, is tiny: a linear map from [z,h][z, h] to the action, with 867 parameters in car racing, trained by CMA-ES, an evolution strategy that needs only returns, not gradients.

In car racing, C was trained in the real game, using V and M as its senses, and averaged 906 points over 100 trials, above the 900 that counts as solving the task. In the Doom scenario, Take Cover, the agent must survive while monsters throw fireballs, and it counts as solved when it survives more than 750 time steps on average. Here C was trained entirely inside M: M generated whole virtual episodes, including whether a monster fires, and only the finished controller was run in the real game. A temperature τ\tau scaled the randomness of M's samples.

Predict before you look

At the lowest temperature, τ=0.1\tau = 0.1, the controller survived 2,086 steps on average in the dream, close to the maximum of 2,100. A random policy survives 210 steps in the real game. How long do you predict the dream-trained controller survives in the real game?

Show the answer

193

193 steps: slightly worse than random. At low temperature the mixture model almost never switched to the mode in which a fireball forms, so the dream contained hardly any danger, and in early experiments the controller even found moves that made fireballs vanish. A policy optimized against a model's errors inherits them.

Temperature τ\tauSteps survived in the dreamSteps survived in the real game
0.102,086193
0.502,060196
1.001,145868
1.159181,092
1.30732753
random policy—210
Ha & Schmidhuber (2018), Table 2: averages over 100 rollouts (standard deviations, which are large, omitted). The dream and real scores move in opposite directions until the dream becomes too hard to learn in.

Dreamer's loop

Ha and Schmidhuber's controller was small enough to evolve. Dreamer (Hafner, Lillicrap, Ba & Norouzi, 2020) learns rich behaviors with an actor and a critic trained by gradient descent on imagined trajectories, inside the recurrent state-space model (RSSM) of PlaNet (Hafner et al., 2019). The loop alternates between learning from a dataset of real experience and collecting more of it:

text
DREAMER(world model φ, actor π_θ, critic v_ψ):
    D ← S episodes of random actions                    # Dreamer: S = 5
    loop:
        repeat C times:                                  # C = 100 updates per episode
            draw B real sequences of length L from D      # B = L = 50
            filter them with the world model → states s_1 … s_L
            update φ: reconstruct o_t, predict r_t and termination,
                      and train the transition to predict the filtered state
            from every filtered state imagine H steps:    # H = 15
                a_k ~ π_θ(· | s_k),   s_k+1 ~ transition(s_k, a_k)
            compute λ-returns G^λ_k on the imagined steps
            update ψ: regress v_ψ(s_k) onto G^λ_k (targets held fixed)
            update θ: raise G^λ_k (backprop through the model, or REINFORCE)
        run π_θ in the real environment, filtering observations with φ
        add the new episode to D

Dreamer's loop with its published settings (Hafner et al., 2020). The world model is held fixed while the actor and critic learn, and the critic is what lets imagination stop after 15 steps.

Gkλ=r^k+1+γ c^k+1[(1−λ) vψ(sk+1)+λ Gk+1λ],GHλ=vψ(sH)G^\lambda_k=\hat r_{k+1}+\gamma\,\hat c_{k+1}\Big[(1-\lambda)\,v_\psi(\mathbf s_{k+1})+\lambda\,G^\lambda_{k+1}\Big],\qquad G^\lambda_H=v_\psi(\mathbf s_H)
The λ-return of an imagined trajectory, computed backward from the horizon. r^k+1\hat r_{k+1} is the reward the model predicts for the step from sk\mathbf s_k to sk+1\mathbf s_{k+1} and c^k+1\hat c_{k+1} its probability that the episode continues (the Dreamer papers index this reward by the state it is read from). With λ=0\lambda = 0 it is a one-step TD target; with λ=1\lambda = 1 it sums all imagined rewards and bootstraps only at the horizon. Dreamer used γ=0.99\gamma = 0.99 and λ=0.95\lambda = 0.95.
Predict before you look

An imagined trajectory has two steps: rewards r^1=1\hat r_1 = 1 and r^2=0\hat r_2 = 0, critic values v(s1)=2v(\mathbf s_1) = 2 and v(s2)=4v(\mathbf s_2) = 4, no termination, γ=0.9\gamma = 0.9 and λ=0.5\lambda = 0.5. What is G0λG^\lambda_0?

Show the answer

3.52

Backward: G2λ=v(s2)=4G^\lambda_2 = v(\mathbf s_2) = 4, then G1λ=0+0.9 (0.5⋅4+0.5⋅4)=3.6G^\lambda_1 = 0 + 0.9\,(0.5\cdot4 + 0.5\cdot4) = 3.6, then G0λ=1+0.9 (0.5⋅2+0.5⋅3.6)=3.52G^\lambda_0 = 1 + 0.9\,(0.5\cdot2 + 0.5\cdot3.6) = 3.52. Equivalently, it averages the one-step return 1+0.9⋅2=2.81 + 0.9\cdot2 = 2.8 and the two-step return 1+0+0.81⋅4=4.241 + 0 + 0.81\cdot4 = 4.24 with weights 1−λ1-\lambda and λ\lambda.

The critic regresses GλG^\lambda, and the actor is pushed toward actions that raise it. Dreamer did this by backpropagating GλG^\lambda through the differentiable model: through the reparameterized actions and every imagined state. Later versions also use REINFORCE with the critic as a baseline, which needs no gradients of the model at all. The Fixed Point lesson derives both and explains when each wins.

Practice in imagination, correct with reality

Dreamer's loop is Dyna's loop at scale: real experience trains the model, imagined experience trains the behavior, and new real experience corrects the model. Which model errors does that correction catch? There are two kinds. An optimistic error promises something the world does not deliver, such as a passage through a wall. A pessimistic error rules out something the world allows, such as a new opening.

A policy trained in imagination walks straight into its model's optimistic errors, and the real transitions it collects there refute them. Pessimistic errors steer the policy away, so no real experience ever contradicts them. Dyna's mazes show both at once.

World models face the same asymmetry in spaces far too large to explore by chance. Plan2Explore (Sekar et al., 2020) attacks the pessimistic side directly. It trains an ensemble of one-step latent predictors, uses their disagreement as an intrinsic reward, and trains an exploration policy in imagination to seek it, so the agent plans its way toward what the model does not yet know. After this task-free exploration, the world model can be reused for new reward functions with few or no further interactions.

What has worked, and what goes wrong

Three results mark the progress of learning in imagination.

  • DreamerV2 (Hafner, Lillicrap, Norouzi & Ba, 2021) was the first agent to reach human-level performance on the 55-game Atari benchmark by learning behaviors inside a separately trained world model, with one GPU and 200 million frames.
  • DreamerV3 (Hafner, Pasukonis, Ba & Lillicrap; preprint 2023, Nature 2025) used one fixed configuration across more than 150 tasks in 8 domains, and was the first algorithm reported to collect diamonds in Minecraft from scratch, without human data or curricula. In the published version every agent trained on Minecraft found diamonds within 100 million environment steps (the preprint had reported diamonds in 24 of 40 seeds). Following earlier work, blocks break faster than in the normal game, because a stochastic policy rarely repeats one action long enough to break a block.
  • DayDreamer (Wu, Escontrela, Hafner, Goldberg & Abbeel, 2022) ran Dreamer on four physical robots without simulators; a quadruped learned to roll off its back, stand up and walk in about an hour.
Failure modeWhat happensDefense
Model exploitationThe policy steers into states where the model overrates the returnFresh real data where the policy goes; short rollouts from real states; uncertainty penalties
Compounding errorEach imagined state is fed back in, so errors accumulate and rollouts drift off the dataShort imagination with a critic beyond the horizon
Objective mismatchReconstruction spends capacity on every pixel and can blur a small object that decides the rewardOther prediction targets (What Should a World Model Predict?)
Unmodeled noveltyThe model is confidently wrong about places it has never seenExploration toward model disagreement, as in Plan2Explore
Several possible futuresA single averaged prediction blends them into one impossible futureStochastic latents; categorical latents in DreamerV2 and V3
Check your understanding

During training, a Dreamer agent's imagined returns keep climbing while its returns in the real environment fall. Which explanation fits best?

  1. The critic is overfitting to real data
  2. The actor has found states or actions where the world model overestimates the return, and is exploiting them
  3. The imagination horizon is too short to see the rewards
  4. The environment has become easier
Show the answer

B. The actor has found states or actions where the world model overestimates the return, and is exploiting them

A widening gap between imagined and real return is the signature of model exploitation. The remedies are to collect more real data where the policy now goes, which corrects optimistic errors, to shorten imagination, or to penalize model uncertainty.

Beyond recurrent latents

Recurrent latent models are one design among several. Transformer world models such as IRIS (Micheli, Alonso & Fleuret, 2023) turn each frame into a handful of discrete tokens and predict the next frame's tokens one by one, like a language model. Diffusion world models such as DIAMOND (Alonso et al., 2024) generate the next frame by iterative denoising and keep visual details that a compressed latent can lose. Interactive video models such as Genie (Bruce et al., 2024) and GameNGen (Valevski et al., 2025) learn playable worlds from recorded video, Genie even without action labels. All of them can serve as environments to imagine in, and all of them face the same questions of exploitation, compounding and memory, now with far more expensive steps.

Think first Dreamer's world model has a decoder, yet the actor and critic never look at decoded images while learning behavior. Why not, and what is the decoder for?

The actor and critic read the latent state directly, so decoding would only cost time; skipping it is what makes imagination cheap enough to roll out thousands of trajectories in parallel. The decoder's job is to shape the latent space while the model is trained: reconstructing every observation forces the state to keep what the observations contain. Generative world models that render frames pay for every pixel at every imagined step.

Key takeaways

  • A world model filters observations into a latent state, predicts how that state evolves under actions, and predicts rewards and terminations; a decoder, when present, is a training signal.
  • Ha and Schmidhuber's dream-trained controller worked in reality only when the dream was noisier than the world: a policy optimized against a model inherits the model's errors.
  • Dreamer alternates model learning on replayed real sequences, actor–critic learning on short imagined trajectories with λ-returns, and real data collection.
  • Optimistic model errors are corrected by acting on them; pessimistic ones persist without directed exploration, such as Plan2Explore's disagreement reward.
  • DreamerV2 and DreamerV3 brought learning in imagination to Atari, to more than 150 tasks with one configuration and to Minecraft diamonds; transformer, diffusion and video world models extend the idea with richer generators.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

In Ha and Schmidhuber's Doom experiment, why did the controller trained in the low-temperature dream (τ=0.1\tau = 0.1) survive 2,086 steps there but only 193 in the real game?

  1. The real game ran at a different frame rate
  2. The controller had too few parameters to dodge fireballs
  3. The near-deterministic dream almost never produced fireballs, so the controller learned a policy that only works in the dream
  4. The autoencoder could not encode the real game's frames
Show the answer

C. The near-deterministic dream almost never produced fireballs, so the controller learned a policy that only works in the dream

At low temperature the mixture model rarely jumped to the mode in which a fireball forms, so the dream was far easier than reality, and the controller exploited quirks that made fireballs vanish. The same architecture trained at τ=1.15\tau = 1.15 survived 1,092 steps in the real game.

Question 2

What does the critic contribute to Dreamer's learning in imagination?

  1. It estimates returns beyond the imagination horizon, so imagined trajectories can stay short
  2. It makes the world model's predictions more accurate
  3. It replaces the reward head
  4. It plans actions by lookahead at every real step
Show the answer

A. It estimates returns beyond the imagination horizon, so imagined trajectories can stay short

Imagination stops after about 15 steps; the λ-return bootstraps from vψv_\psi there, so the actor optimizes long-horizon returns without long, error-prone rollouts.

Question 3

Which model error gets corrected by itself in a Dyna- or Dreamer-style loop, simply by acting on the model and collecting new real data?

  1. A pessimistic error about a region the policy avoids
  2. Any error, given enough imagined experience
  3. No error: only random exploration ever corrects a model
  4. An optimistic error about states the policy is drawn to visit
Show the answer

D. An optimistic error about states the policy is drawn to visit

The policy seeks out what the model overrates, collects real transitions there and refutes the error. A pessimistic error keeps the policy away, so it persists unless something rewards going there, such as Dyna-Q+'s bonus or Plan2Explore's disagreement reward.

Question 4

Where do Dreamer's imagined trajectories start, and why there?

  1. At the environment's initial state, so that whole episodes are imagined
  2. At latent states the filter inferred from replayed real sequences, so imagination begins where the model was trained and stays short
  3. At random latent vectors, to cover the whole latent space
  4. At the decoder's reconstructions of real frames
Show the answer

B. At latent states the filter inferred from replayed real sequences, so imagination begins where the model was trained and stays short

Every filtered state in a training batch is a starting point for a 15-step imagined rollout. Starting on the data keeps imagination where the model is accurate and gives the actor a wide spread of realistic situations.

Question 5

During imagination, what does Dreamer's transition model have to do without that the filter had during training?

  1. The action
  2. The previous latent state
  3. The next observation
  4. The reward function
Show the answer

C. The next observation

The filter folds the real observation into the state; the transition must predict that state from the previous state and the action alone. Training the transition to match what the filter infers is what makes imagined trajectories resemble filtered real ones.

Go deeper

Further reading

  • D. Ha & J. Schmidhuber, "World models," arXiv:1803.10122 (2018); a version appeared as "Recurrent world models facilitate policy evolution," NeurIPS (2018).
  • D. Hafner, T. Lillicrap, J. Ba & M. Norouzi, "Dream to control: learning behaviors by latent imagination," ICLR (2020).
  • D. Hafner, J. Pasukonis, J. Ba & T. Lillicrap, "Mastering diverse control tasks through world models," Nature 640, 647–653 (2025).
  • R. Sekar, O. Rybkin, K. Daniilidis, P. Abbeel, D. Hafner & D. Pathak, "Planning to explore via self-supervised world models," ICML (2020).