Imagine Before You Act: World Models — Part 3: Latent Dynamics: PlaNet and Dreamer
November 21, 2026 · 9 min read · World Models, Reinforcement Learning, Machine Learning
Part 2 built an agent from three separately trained pieces: a VAE for vision, a recurrent network for memory, and a tiny controller. It worked, but the pieces didn't help each other. The VAE didn't know which details the memory would need, and all the data came from random pushes.
This part trains one model, end to end, and keeps collecting new data as the agent improves. It's the design behind PlaNet (Hafner et al., 2019) and the Dreamer family (2020–2025), some of the most successful world-model agents. In the four-box picture we change predict: the state that the model carries forward in imagination.
By the end you'll know:
- why a good latent state needs both a deterministic memory and a random part,
- how the RSSM is trained: reconstruction, reward, and a KL term that keeps imagination honest,
- two ways to use it: planning in latent space (PlaNet) and learning in imagination (Dreamer),
- what changed in DreamerV3, and what our miniature version leaves out.
1. What should the state carry forward?#
To imagine many steps ahead, the model needs a state that it can roll forward without looking at new frames. Two natural designs, and why both fall short:
- Fully deterministic (a plain recurrent network, ). Great at remembering things, such as the puck's speed from earlier frames. But it can only imagine one future. When the future is uncertain, it learns the average future, which may not be a possible future at all, like a blurred puck halfway between two places.
- Fully random (a state sampled fresh each step, ). It can represent uncertainty, but everything it remembers has to survive a sampling step every time, and over many steps information leaks away.
The recurrent state-space model (RSSM) uses both:
- a deterministic memory (a GRU with 200 units), updated from the last state and action: ;
- a random state (30 numbers), drawn from a Gaussian whose mean and spread are predicted from .
The model's full state is the pair . The memory carries what's certain, and the random part carries what isn't.
ELI5: a weather forecaster keeps a notebook of everything they know for sure (the memory), and for tomorrow says "70% chance of rain" (the random part). They don't pretend to know whether it will rain, and they don't forget yesterday's storm.
2. Prior, posterior, and how the RSSM learns#
The random state has two versions:
- The prior : what the model expects before seeing frame . This is all it has while imagining.
- The posterior : what it believes after seeing the frame (the dashed arrows above). Used while observing real data.
Training uses sequences of 50 real frames and actions from a replay buffer. The model runs the posterior along the sequence and is trained on three losses:
The third term is the key. It pushes the prior (imagination) to predict what the posterior (observation) will say. If the prior learns this well, then imagining without frames gives states like those the model would have from real frames, and the decoder and reward head, trained on posterior states, work in imagination too.
The KL term also stops the posterior from cramming in every detail of the frame. To make sure the model isn't over-penalized for useful information, the KL is only applied above 3 nats ("free nats"). Below that, the posterior can say what it likes.
3. Using the model: PlaNet plans, Dreamer learns#
We train one RSSM on GapWorld frames and use it two ways.
PlaNet: plan in latent space. Exactly the planner from Part 1, CEM inside MPC, but the imagined rollouts happen in the latent space: start from the current posterior state, roll the prior forward for 12 steps under each candidate plan, and score plans with the reward head. No pixels are generated while planning.
Dreamer: learn an actor and critic in imagination. Planning every step is expensive. Dreamer instead trains two small networks on imagined trajectories:
- an actor that picks actions,
- a critic that estimates how much reward is still to come.
From every real state in a training batch (1,600 of them), Dreamer imagines 15 steps ahead with the actor choosing actions. The critic gives the value of the state at the end, so the actor can see beyond the horizon. That is the fix for Part 1's short-sightedness. The target is the λ-return, a blend of "rewards so far plus the critic's estimate" over different horizons. The actor is updated by backpropagating through the model's dynamics: the model is a differentiable function, so we can ask how the imagined return would change if the action changed slightly, and nudge the actor that way.
ELI5: PlaNet is a chess player who calculates moves at every turn. Dreamer is a player who studied so many imagined games that they now just see the good move.
The training loop alternates between the world and the dream: 100 gradient steps (model, then actor and critic in imagination), then 10 new real episodes played by the current actor with some exploration noise, which go into the replay buffer. We repeat this 120 times, starting from 50 episodes of random pushes. The model keeps improving exactly where the agent now goes, unlike Part 2's random-only data.
4. Results#
How good is the model's imagination? We show it 5 real frames, then give it only the actions and let it imagine 36 more:
The top pair is an episode played by the agent itself. The imagined puck goes through the gap and settles next to the goal, almost exactly as the real one does, 36 steps with no frame to correct it. The bottom pair uses random pushes in the top-right corner, a place the agent never goes. There the imagination is simply wrong: the puck shows up on the other side of the wall. A model trained on the agent's own experience is good where the agent has been, and only there. That's efficient, because the model spends its capacity on the states that matter for the task. It's also a warning, because nothing in the model says "I've never seen this".
Does the agent solve the task?
| Agent | Reached the goal | Return |
|---|---|---|
| Random pushes | 0% | −33.7 |
| Part 2: controller trained in a fixed dream | 57% | −14.7 |
| PlaNet: CEM in latent space, 12 steps ahead | 68% | −13.7 |
| Dreamer: actor and critic learned in imagination | 99% | −9.9 |
(PlaNet, Dreamer and random pushes: 100 starts in the left room that were not used for anything else. The Part 2 row is that part's own result on its own 100 starts. For Dreamer we kept the actor from the evaluation with the highest success rate, at 60,000 steps, and then tested it on the fresh starts.)
Dreamer solves GapWorld from pixels, with 62,500 real environment steps in total. It beats even Part 1's planner, which had the true state (72%). Two things from this part explain the jump over Part 2: the model keeps learning from the agent's own data, so it gets accurate exactly where the agent goes, and the critic lets the actor look past the 15-step horizon.
PlaNet, with the very same model, reaches 68%. Its failures are the dead end from Part 1 again: a planner that looks 12 steps ahead and has no critic pushes the puck against the wall across from the goal and can't find the way around. The model is the same. What differs is how it's used.
Training was not smooth, and that's worth seeing. The left panel shows two runs of the same script. In the second run (blue), success wobbled between 24% and 83% for most of training before reaching 100%. The first run (grey) is stranger. It reached 100%, and then, after 52,500 steps, the actor changed to stopping about 0.15 short of the goal, on every episode: 0% success by our measure, although its return was still good, because it got close quickly. We checked that the model's predicted reward at that spot was accurate (−0.155 predicted against −0.16 real), so this was not the model being fooled. It was the actor and critic settling on a worse habit. Two lessons: evaluate often and keep the best checkpoint, and never judge an RL method by one run or one number.
5. What DreamerV3 changed#
Our model is roughly DreamerV1 (2020) in miniature. Later versions kept the RSSM idea and fixed what made it fragile:
- Discrete latents (DreamerV2): 32 categorical variables with 32 classes each, instead of a Gaussian. They were easier to optimize and better at multi-modal futures.
- KL balancing: train the prior towards the posterior faster than the posterior towards the prior, so the model learns to predict rather than learning to make its states easy to predict.
- Symlog predictions and two-hot rewards (DreamerV3): squash large values so the same settings work whether rewards are 0.01 or 10,000.
- Return normalization and fixed hyperparameters: DreamerV3 used one set of settings for over 150 tasks, from robot control to Atari to Minecraft. It was the first agent to collect diamonds in Minecraft from scratch, without human data.
6. Honest limits#
- Scale. Our RSSM has 5.4 million parameters (most of them in the image decoder) and saw 62,500 environment steps. DreamerV3's models range up to 200 million parameters and train for millions of steps. The design is the same, the reach is not.
- Two runs. RL results vary a lot between random seeds, as the two curves above show. Treat the success rates as "this is what a run can look like", not as precise measurements.
- Tuning. We copied DreamerV1's settings where possible and did not tune them for GapWorld. A few hours of tuning would likely raise all numbers.
7. In code#
The heart of the RSSM is two short functions:
def img_step(self, h, z, a):
"""Imagine one step: update the memory, then predict the random state (the prior)."""
h = self.gru(self.pre(torch.cat([z, a], -1)), h)
prior = self.dist(self.prior_net(h))
return h, prior
def obs_step(self, h, z, a, emb):
"""Observe one step: the same, plus a posterior that also sees the frame's embedding."""
h, prior = self.img_step(h, z, a)
post = self.dist(self.post_net(torch.cat([h, emb], -1)))
return h, prior, post
And Dreamer's actor update is a loop through img_step, then gradient ascent on the imagined return:
# inside Agent.train_step, after the world-model update (h, z: posterior states of the batch)
hh, zz = h.detach().flatten(0, 1), z.detach().flatten(0, 1) # start from every real state
feats = [torch.cat([hh, zz], -1)]
for _ in range(15): # imagine 15 steps
a, _ = self.actor(feats[-1].detach())
hh, pr = wm.img_step(hh, zz, a)
zz = pr.rsample() # reparameterized: gradients flow
feats.append(torch.cat([hh, zz], -1))
feats = torch.stack(feats)
rew = wm.reward(feats).squeeze(-1)
val = self.critic_t(feats).squeeze(-1) # a slowly updated copy of the critic
ret = lambda_return(rew[1:], val[1:]) # rewards + critic beyond the horizon
disc = (0.99 ** torch.arange(ret.shape[0], device=DEV))[:, None]
actor_loss = -(disc * ret).mean() # backprop through the dynamics
The full training loop, with the replay buffer, the critic and the evaluation, is part3_train.py (about 330 lines). One run takes about 16 minutes on one GPU.
Recap#
- The RSSM state has a deterministic memory (for what's certain) and a random state (for what isn't).
- It learns from three losses: reconstruct the frame, predict the reward, and a KL that trains the prior (imagination) to match the posterior (observation).
- PlaNet plans with CEM in latent space. Dreamer learns an actor and a critic entirely on imagined trajectories, backpropagating through the model, and the critic lets it see beyond the imagination horizon.
- Training alternates between the dream (gradient steps) and the world (new episodes with the current actor), so the model improves where the agent goes.
- DreamerV3 made the recipe robust: discrete latents, KL balancing, symlog targets and one fixed set of settings for 150+ tasks.
Next up — Part 4: What Should a World Model Predict? Every model so far has been trained to redraw the frame. Is that even a good idea? We add a fly that buzzes around at random and compare three objectives: predict pixels, predict only rewards and values, or predict an embedding of the next frame (JEPA).
