Quy-Anh Dang

Quy-Anh Dang

Researcher, Knovel Engineering


← All work

Imagine Before You Act: World Models — Part 2: Learning in a Dream

November 21, 2026 · 8 min read · World Models, Reinforcement Learning, Machine Learning

In Part 1 the agent was handed the puck's exact position and velocity, four clean numbers. Real agents rarely get that. A robot gets camera images, a game-playing agent gets the screen. This part makes two changes at once:

  • the agent sees 64×64 images instead of the state, so it must learn to encode what it sees;
  • instead of searching for actions at every step, the agent learns a policy, and it learns it entirely inside its own imagination, never touching the real environment while training.

By the end you'll know:

  1. Dyna, the old idea of mixing real and imagined experience,
  2. the three parts of Ha and Schmidhuber's World Models: V (vision), M (memory) and C (controller),
  3. why our first vision model ignored the puck completely,
  4. how a policy trained in a dream learns to cheat the dream, and how a noisier dream fixes it.

1. Dyna: practise on imagined experience#

In 1991 Richard Sutton proposed Dyna. An agent collects real experience, learns a model from it, and then also trains its policy on imagined experience generated by the model. Every real step is followed by many cheap imagined ones, so the agent needs much less of the real thing.

Dyna is the "learn" arrow of the four-box diagram from Part 0. Part 1 used the model to plan (search at decision time). Dyna uses it to learn (train a policy ahead of time, then act instantly). Both ideas come back in Part 3, where Dreamer learns and PlaNet plans with the same model.

ELI5: planning is a chess player thinking hard before every move. Learning in imagination is a chess player who spends the week replaying games in their head, then plays fast on the day.

2. World Models: V, M and C#

In 2018 David Ha and Jürgen Schmidhuber showed an agent that learned to drive a simple racing car and dodge fireballs in a video game, with the policy trained only inside a dream generated by its own model. Their agent has three parts. We build a miniature copy for GapWorld:

PartJobOurs
V, visiona variational autoencoder (VAE) squeezes each 64×64 frame into a short vector has 32 numbers
M, memorya recurrent network reads and the action , keeps a memory , and predicts the distribution of an LSTM with 256 units, predicting a mixture of 5 Gaussians per number (an "MDN-RNN")
C, controllera tiny policy that picks the action from linear: , only 578 numbers

Each part is trained separately:

  1. Collect 2,000 episodes of random pushes (100,000 frames). No rewards are needed for V and M.
  2. Train V to reconstruct frames through the 32-number bottleneck.
  3. Train M to predict the next from the current and action. We also train a small head that reads the reward from . (The original paper used the real reward in one task and a learned "death" signal in the other. GapWorld's reward is a distance, so we learn it.)
  4. Train C inside the dream. Start from encoded real first frames, then let M generate everything: C picks an action, M samples the next , the reward head scores it, for 50 steps. C is improved with CMA-ES, an evolution strategy: try 64 slightly different controllers, keep the best, and repeat for 150 generations. CMA-ES needs no gradients, which suits a controller this small.

Why a mixture for M, and not a single best guess? Because the future isn't always determined by what the model can see. A single frame doesn't show the puck's speed, and the effect of a push near a wall can go one way or another. A mixture lets M say "probably here, possibly there". When we sample from it, the dream contains surprises, as the real world does.

3. The VAE that ignored the puck#

Our first VAE trained happily and reached a low reconstruction error. Its reconstructions showed the room, the wall and the goal, and no puck at all. A plain autoencoder without the VAE's noise did the same.

The reason: the puck covers about 20 of the 4,096 pixels. Drawing the empty room already gets almost every pixel right, and the small extra gain from also drawing the puck was too weak to pull training out of that comfortable spot, even after thousands of steps. The bottleneck wasn't the problem. The loss was. Pixel error says every pixel matters equally, and nearly all pixels are background.

The fix was simple: subtract the average frame from the input and the target, so the model only has to describe how each frame differs from the average, which is mostly the puck. After that, V learned the puck within a few thousand steps. Remember this failure. In Part 4 it becomes the main argument against predicting pixels at all.

With V and M trained, here is what the dream looks like. Both rows start from the same real frame and get the same pushes. The top row is the real world. The bottom row is generated entirely by M and decoded by V:

Two examples of real frames and dreamed frames over 30 steps. The dreamed puck follows nearly the same path as the real one, with some blur and a small drift.

The dream is good. The puck moves the right way, stops at the walls, and drifts only slowly from the real path. Now we train C inside it.

4. The controller that cheated its dream#

We train C three times, each inside a dream sampled at a different temperature . Temperature controls how random the dream is. At , M almost always picks its single most likely next state, so the dream is nearly deterministic. At , M samples from its predicted distribution as trained. At , it is more random than M itself believes.

Left: dream and real returns while training. For tau = 0.1 the dream return climbs to about -8 while the real return stays flat near -20. For tau = 1.5 the dream return rises to about -10.5 and the real return improves from -20 to about -14. Random pushes score about -34. Right: share of 100 real episodes reaching the goal: 0% for tau 0.1, 35% for tau 1.0, 57% for tau 1.5.

The dashed lines are what C scores in the dream, the solid lines what it scores in the real room (the return is the sum of the 50 rewards, so higher is better). At , the dream score keeps improving, from −13.6 to −8.0. That's the best dream score of all three controllers. In the real room it never improves, stays near −20, and never reaches the goal. At the dream score is lower, but the real score improves along with it, and 57% of real episodes reach the goal.

What did the controller learn? We can watch its dreams:

Left: decoded dream frames at tau = 0.1. In one dream the puck fades out and reappears on the far side of the wall; in another it fades out at the bottom of the wall. Right: the same controller in the real room pushes the puck into the bottom of the wall or into the bottom-right corner, never to the goal.

It found holes in the dream. In one dream, a hard push into the bottom of the wall makes the puck fade away and reappear on the other side. In another, the puck simply vanishes, and with no puck in the frame the reward head returns an optimistic guess. Both moves score well in the dream. In the real room, the same pushes just jam the puck against the wall.

This is the central danger of learning in imagination. An optimizer looks for whatever scores highest. If the model has errors, the highest scores are often in the errors, because that's where the model promises things the real world can't deliver. The stronger the optimizer and the more deterministic the dream, the more reliably it finds them.

Why does a hotter dream help? At the same exploit only works sometimes: in some dreams the puck slips through the wall, in others it doesn't. A controller can't rely on a trick that fails half the time, so it learns the honest route through the gap, which works in every dream. Ha and Schmidhuber saw exactly this in their game experiments and fixed it the same way. A noisier dream is a crude form of the uncertainty-awareness from Part 1. Both say: don't trust any single imagined future too much.

ELI5: if you practise a speech only in front of a mirror that always smiles, you learn to perform for the mirror. Practise in front of a mirror that sometimes frowns at random and you learn a speech that works on real people.

5. Honest limits#

  • Only partial success. The best controller reaches the goal 57% of the time. The planner in Part 1, which had the true state and searched at every step, did better. A linear controller trained with a weak, single-start dream is a simple agent, and the dream's errors still cost it.
  • Results vary. CMA-ES with 64 candidates is noisy. Real success for the same controller over training jumped between 26% and 65% from one checkpoint to the next. We report the final controller on 100 fixed starts.
  • One round of data. All data came from random pushes. Random pushing rarely carries the puck through the gap, so the model is weakest exactly where the task needs it. Ha and Schmidhuber's harder task used iterative training: collect new data with the current controller, retrain the model, repeat. Dreamer, in Part 3, does this continuously.

6. In code#

The whole loop fits on a screen. Given the trained V, M and a controller's 578 parameters, this rolls the controller forward inside the dream, then runs it in the real room:

import numpy as np, torch
import gapworld as g
from part2_train import VAE, MDNRNN, controller, to_t, HID   # scripts/blog/world_models/

ckpt = torch.load(".cache/part2_models.pt")
vae, rnn = VAE().cuda(), MDNRNN().cuda()
vae.load_state_dict(ckpt["vae"]); rnn.load_state_dict(ckpt["rnn"])

@torch.no_grad()
def dream(params, z, tau, steps=50):
    """Roll the controller forward entirely inside the model. Returns the imagined return."""
    h, state, ret = torch.zeros(len(z), HID, device="cuda"), None, 0
    for t in range(steps):
        a = controller(params[None], z, h)                 # C: act from what it "sees"
        h, state = rnn.step(z, a, state)                   # M: remember, and predict...
        z = MDNRNN.sample(*rnn.mdn(h), tau=tau)            # ...a next state, sampled at temperature tau
        ret += rnn.rew(z).squeeze(-1)                      # imagined reward
    return ret.mean().item()

@torch.no_grad()
def reality(params, n=100):
    s = g.reset(n, np.random.default_rng(123))
    h, state, ret = torch.zeros(n, HID, device="cuda"), None, 0
    for t in range(50):
        z = vae.encode(to_t(g.render(s) * 255))[0]         # V: compress the real frame
        a = controller(params[None], z, h)
        h, state = rnn.step(z, a, state)
        s = g.dynamics(s, a.cpu().numpy())
        ret += g.reward(s)
    return ret.mean()

z0 = vae.encode(to_t(g.collect(256, np.random.default_rng(11), T=0)["frames"][:, 0]))[0]
for tau in [0.1, 1.5]:
    params = torch.as_tensor(np.load(f".cache/part2_controller_tau{tau}.npy"), device="cuda")
    print(f"controller trained at tau={tau}: dream return {dream(params, z0, tau):.1f}, real return {reality(params):.1f}")
# controller trained at tau=0.1: dream return -8.6, real return -19.7
# controller trained at tau=1.5: dream return -10.7, real return -14.7

Training is in part2_train.py: about six minutes on one GPU for data, V, M and all three controllers.

Recap#

  • Dyna: use a learned model to generate imagined experience, and train the policy on it.
  • World Models splits the agent into V (a VAE that compresses each frame), M (a recurrent network that predicts a distribution over next latents) and C (a tiny controller trained with CMA-ES entirely inside the dream).
  • A pixel-reconstruction loss can ignore small, important things. Our VAE skipped the puck until we subtracted the average frame.
  • An optimizer inside a dream finds the model's errors. At the controller got the best dream score by making the puck vanish or slip through the wall, and failed every real episode.
  • A noisier dream () made those tricks unreliable, and the controller learned the honest route: 57% real success.

Next up — Part 3: Latent Dynamics: PlaNet and Dreamer. Instead of training V, M and C separately, we train one model end to end, with a state that has both a reliable memory and an honest amount of randomness, and collect new data as the agent improves. We use it two ways: to plan (PlaNet) and to learn an actor and critic in imagination (Dreamer).


© 2026 Quy-Anh Dang. All rights reserved.