Imagine Before You Act: World Models — Part 1: Learn the Dynamics, Then Plan
November 21, 2026 · 9 min read · World Models, Reinforcement Learning, Machine Learning
Part 0 ended with a planner that imagined 200 random futures before every push and reached the goal 74% of the time. But it cheated: it imagined with the real simulator. In most problems there is no simulator. A robot can't call physics.step() on the real world.
This part replaces the simulator with a learned model: a neural network trained on recorded experience to predict what happens next. Then we plan with it and see what goes wrong. It's the simplest kind of world model, and it already shows the main problems the rest of the series deals with.
In the four-box picture we work on predict and use (plan). Encode is skipped: the agent gets the true state directly. Images come in Part 2.
By the end you'll know:
- how to learn a dynamics model from data,
- why its errors compound when you imagine many steps ahead,
- how to plan with it: the cross-entropy method inside model-predictive control,
- what an ensemble of models can tell you about the model's own uncertainty, and what it can't.
1. Learning the dynamics#
Data. We record 1,000 episodes of 50 steps, starting anywhere in the room, with random pushes. Purely random pushes would just make the puck jitter in place, so each push mostly repeats the last one with some random change. The puck travels, bumps into walls and slides through the gap. That gives 50,000 transitions . No reward is needed: the model only learns how the world moves.
Model. A small neural network (three layers of 200 units) takes the state and action and predicts the change in state:
Predicting the change instead of the next state is a small trick that matters a lot. Most of the next state is just the current state. Predicting the difference lets the network spend its capacity on what actually changes. We train it with plain mean squared error.
How good is it? On held-out episodes the average one-step position error is 0.0017 (the room is 1 unit wide). For comparison, guessing "the puck doesn't move" is off by 0.025, about 14 times more. By any ordinary standard, this is an excellent model.
2. Errors compound#
A planner doesn't ask the model one step ahead. It asks it 10, 20 or 50 steps ahead, feeding each prediction back in as the next input. Small errors then build on each other:
The median error grows from 0.0007 after one step to 0.0085 after ten steps, more than ten times larger. The median then levels off, because many paths end up resting against a wall, where there's little to get wrong. The worst cases keep growing: one rollout in ten is off by more than 0.08 after 40 steps, about twice the puck's radius.
Two reasons errors grow:
- Errors feed back. If the model puts the puck 0.002 too far right, the next prediction starts from the wrong place, and its own error adds on top.
- The model drifts off its data. After a few wrong steps, the imagined state may be one the model never saw in training (a speed that's slightly too high, a position slightly inside a wall). The model is less accurate there, so errors grow even faster.
The left panel shows where it hurts most: near walls. Collisions are sudden changes, hard for a smooth network to learn, and a small position error decides whether the imagined puck hits the wall or slides past it.
One-step accuracy is not the same as multi-step accuracy. This is the most important lesson about world models, and it comes back in every part of the series.
3. Planning: CEM inside MPC#
Now we use the model. The idea is the one from Part 0, with a better search.
The cross-entropy method (CEM) is a simple way to search over action sequences:
- Sample 400 sequences of pushes, 15 steps long, from a Gaussian.
- Roll each one forward in the model and score it: the sum of distances to the goal over the 15 steps (lower is better).
- Keep the best 40 (the "elites"), and refit the Gaussian's mean and spread to them.
- Repeat 5 times. The Gaussian narrows in on good plans.
Model-predictive control (MPC) decides how to use the plan: execute only the first push, observe where the puck really ended up, and plan again from there. Every step, the plan is corrected by reality.
ELI5: driving in fog. You can see 15 metres ahead, so you plan a short path, drive one metre, look again, and replan. You never commit to the whole route at once.
Here is how it does over 100 starts in the left room:
With a learned model, MPC reaches the goal in 72% of episodes, against 2% for random pushes and 100% for the same planner with the true dynamics. Two comparisons are worth a closer look.
Plan once vs replan every step#
"Plan once" searches for a full 50-step plan at the start, then executes it blindly, without looking. It succeeds only 33% of the time, and 31 of those 33 episodes touch the goal and then slide past it:
The imagined and real paths agree for the first 20 steps or so. Then the compounding errors from Section 2 take over, and the plan's last pushes, which made sense for where the model thought the puck was, send the real puck past the goal. MPC avoids this because it never relies on the model more than 15 steps ahead, and it re-anchors to reality every step. Feedback is the cheapest fix for model error.
Why the planner gets stuck#
The orange paths in the right panel all end in the same spot: pressed against the wall at , at exactly the height of the goal. The puck is as close to the goal as it can get on the wrong side of the wall.
You might guess the model thinks the wall is soft. It doesn't: asked what a push to the right does from there, the model correctly predicts the puck won't move. The real problem is the horizon. From that spot, the way around goes up to the gap and back down, and the first 15 or so steps all move away from the goal. A planner that looks 15 steps ahead and scores plans by distance sees no plan better than staying put. We checked: even MPC with the true dynamics can't escape from these 28 positions.
So why does the true-model planner reach the goal 100% of the time? It never gets there. From the start, it heads for the gap early. The learned model is least accurate around the gap and its corners (the heatmap in Section 4 shows this), exactly where the route has to go. A plausible reading is that those small errors make the gap route look slightly worse in some episodes, and once the puck drifts into the trap, no 15-step plan gets it out. A small model error plus a short-sighted planner produces a large failure. In real systems this is usually fixed with a longer horizon, a learned value function that estimates what happens beyond it (Part 3), or a cost that understands obstacles.
4. Knowing when not to trust the model#
A model that's wrong is dangerous. A model that's wrong and doesn't know it is worse. One practical way to estimate a model's uncertainty is an ensemble: train several models, each on a slightly different resample of the data (a bootstrap) and from a different random start. Where there was plenty of data, they agree. Where there wasn't, each fills in the gap its own way, and they disagree.
To test this, we train an ensemble of five models on data with a hole: every transition in the top-right corner is removed. Then we measure, all over the room, the ensemble's disagreement (the spread of the five predictions) and its actual error:
In the empty corner, disagreement is 4 times higher than elsewhere, and the actual error is 2.5 times higher. The ensemble knows what it doesn't know.
But look at the edges of the room in the right panel. The error is high along the outer walls, and the ensemble barely disagrees there. All five models learned the same smooth approximation of a sharp collision, so they are wrong in the same way. Disagreement catches missing data (epistemic uncertainty). It doesn't catch mistakes that all members share. Across the room, disagreement and error are correlated (0.60), but not tightly.
PETS (Chua et al., 2018) built this into planning. An ensemble of models imagines each candidate plan, and plans are scored by their average over the ensemble, so a plan that works in only one member's imagination scores poorly. We tried two versions:
- Average over 5 models: 68%, no better than the single model's 72%. Our data covers the whole room, so the members mostly agree, and averaging adds little. PETS mattered most in its experiments with little data, which isn't our setting.
- Average, plus a penalty for disagreement ("avoid what the models aren't sure about"): worse, 50% (and 40% with a larger penalty). The place where the models disagree most is the gap, the one place the puck must go through. A cautious planner avoids exactly the route it needs.
Neither is a general verdict on ensembles. They show what ensembles measure: where the data is thin. Whether avoiding those places helps depends on whether your task needs to go there. Avoiding thin data is very effective when you train without new data collection, so-called offline model-based RL (MOPO, MOReL), because there, exploring a region the model has never seen can't be checked against reality.
5. In code#
This trains a model on 50,000 transitions and plans with CEM inside MPC, all on a laptop CPU in about 20 seconds:
import numpy as np, torch, torch.nn as nn
import gapworld as g # scripts/blog/world_models/gapworld.py
torch.manual_seed(0)
rng = np.random.default_rng(0)
# 1. Data: 1,000 episodes of random (but persistent) pushes, starting anywhere in the room.
data = g.collect(1000, rng, res=0, anywhere=True)
S, A = data["states"], data["actions"]
s, a, s_next = (torch.tensor(x.reshape(-1, x.shape[-1])) for x in (S[:, :-1], A, S[:, 1:]))
# 2. Model: an MLP that predicts the *change* in state.
mu, sd = s.mean(0), s.std(0)
d_sd = (s_next - s).std(0)
net = nn.Sequential(nn.Linear(6, 200), nn.SiLU(), nn.Linear(200, 200), nn.SiLU(), nn.Linear(200, 4))
model = lambda s, a: s + net(torch.cat([(s - mu) / sd, a], -1)) * d_sd
opt = torch.optim.Adam(net.parameters(), 1e-3)
for epoch in range(30):
for idx in torch.randperm(len(s)).split(256):
loss = (((model(s[idx], a[idx]) - s_next[idx]) / d_sd) ** 2).mean()
opt.zero_grad(); loss.backward(); opt.step()
# 3. Plan with it: CEM inside MPC, for 20 starts at once.
@torch.no_grad()
def cem(state, H=15, N=400, iters=5, elite=40):
B = len(state)
mean, std = torch.zeros(B, H, 2), torch.full((B, H, 2), 0.7)
goal = torch.tensor(g.GOAL, dtype=torch.float32)
for _ in range(iters):
plans = (mean[:, None] + std[:, None] * torch.randn(B, N, H, 2)).clamp(-1, 1)
sim, cost = state.repeat_interleave(N, 0), 0
for t in range(H):
sim = model(sim, plans.reshape(B * N, H, 2)[:, t])
cost = cost + (sim[:, :2] - goal).norm(dim=-1)
best = cost.view(B, N).topk(elite, largest=False).indices
elites = plans[torch.arange(B)[:, None], best]
mean, std = elites.mean(1), elites.std(1) + 0.05
return mean[:, 0] # MPC: execute only the first push
state = g.reset(20, np.random.default_rng(123))
reached = np.zeros(20, bool)
for t in range(g.EPISODE_LEN):
push = cem(torch.tensor(state, dtype=torch.float32)).numpy()
state = g.dynamics(state, push) # the real world moves on
reached |= g.success(state)
print(f"training loss {loss.item():.4f}; reached the goal in {reached.sum()} of 20 episodes")
# training loss 0.0629; reached the goal in 11 of 20 episodes
This shorter version (fewer epochs, one model) reaches the goal 55% of the time over these 20 starts. The full experiments, with the ensemble, the data hole and all the figures, are in part1_train.py.
Recap#
- The simplest world model: a network trained on recorded transitions to predict the change in state.
- Errors compound. A one-step error of 0.0007 (median) became 0.0085 after ten steps, and the worst 10% of rollouts were off by 0.08 after 40. One-step accuracy says little about multi-step accuracy.
- CEM inside MPC plans with the model and replans every step. It reached the goal 72% of the time, against 33% for a single 50-step plan executed blindly. Feedback is the cheapest fix for model error.
- Failures came from a short horizon plus small model errors: the puck drifted into a dead end that even the true model, looking 15 steps ahead, couldn't escape.
- An ensemble's disagreement flags regions without data (4 times higher in the missing corner) but not errors all members share (collisions at the outer walls). Avoiding disagreement can also mean avoiding where you need to go.
Next up — Part 2: Learning in a Dream. The agent now sees only images. It compresses each frame with a VAE, predicts the future with a recurrent network, and trains a controller entirely inside its own dream, until the controller discovers that the dream has loopholes.
