World Models: Compress the World into a Generative Model and Let the Agent Train in Its Own Dream
World Models (Ha and Schmidhuber, 2018) split an agent into a VAE for vision, an MDN-RNN for memory and a tiny linear controller trained by evolution strategies, even inside the model's own dream. Code checks the parameter counts and replays dream training on CartPole.
On this page
Why this paper matters
Policy networks in deep reinforcement learning are usually small: a footnote of the paper says that model-free RL models typically have to parameters, because the credit assignment problem makes it hard for traditional RL algorithms to learn millions of weights. World Models (Ha and Schmidhuber, March 2018, Google Brain, NNAISENSE and IDSIA, with an interactive version at worldmodels.github.io) proposes a split: train a large world model without supervision to do the “seeing” and the “predicting”, and then train a very small controller to make the decisions. The small controller leaves the optimizer a tiny search space, while the large model keeps the capacity.
The paper says its aim is to distill ideas from a series of Schmidhuber’s papers from 1990 to 2015 on combining RNN world models with controllers into a simple demonstration that works from pixels, not to write a survey. Its most striking result is that the controller can be trained entirely inside the environment dreamed up by the world model and then placed into the real environment.
Method
The agent has three components. At each step the observation goes through V to give , C picks an action from and M’s hidden state , and M updates its hidden state from and .
| Component | Role | CarRacing | Doom (Take Cover) |
|---|---|---|---|
| V | VAE that compresses a frame to | has 32 dims, 4,348,547 parameters | has 64 dims, 4,446,915 parameters |
| M | LSTM with mixture-density output, predicts the next | 256 hidden units, 422,368 parameters | 512 hidden units, 1,678,785 parameters, also predicts death |
| C | One linear layer | 867 parameters | 1,088 parameters |
- V (VAE). The input is resized to a 64×64 RGB image, four convolution layers encode it into a mean and a variance, and four deconvolution layers reconstruct it; the loss is the reconstruction distance plus a KL term. It is trained for 1 epoch on 10,000 random-policy rollouts.
- M (MDN-RNN). It models as a mixture of 5 Gaussians with diagonal covariance (no correlation between dimensions) and is trained for 20 epochs; during training the input is resampled from precomputed to avoid overfitting to one particular sample. At sampling time a temperature controls the uncertainty (as in SketchRNN). In Doom, M also predicts
done(death), and an episode ends when that probability exceeds 50%. - C (controller).
In CarRacing this has parameters; in Doom there is no bias and parameters (the input also includes the LSTM’s cell state). With so few parameters it can be optimized by the gradient-free evolution strategy CMA-ES: population 64, each individual runs 16 rollouts, and fitness is the average cumulative reward.
Training in a dream requires M to also emit a termination signal: V and M then form a complete environment interface. While the controller rolls out inside M no real pixels are needed, and everything happens in latent space.
Experiments and findings
CarRacing-v0 (Table 1). The task counts as solved at an average of 900 over 100 consecutive trials.
| Method | Average score |
|---|---|
| DQN (Prieur, 2017) | 343 ± 18 |
| A3C, continuous (Jang et al., 2017) | 591 ± 45 |
| A3C, discrete (Khan and Elibol, 2016) | 652 ± 10 |
| Gym leaderboard best (CEOBillionaire) | 838 ± 11 |
| V only: | 632 ± 251 |
| V only, one hidden layer (1443 parameters) | 788 ± 141 |
| Full World Model (V and M) | 906 ± 21 |
The full model scores 906 ± 21 over 100 random trials, and the paper calls it the first known solution to reach the solving threshold; the appendix says CMA-ES ran for 1800 generations and averaged 900.46 over 1024 rollouts. With only the car wobbles, which shows that M’s hidden state , which carries expectations about the future, really adds information.
VizDoom Take Cover (Table 2). The agent dodges fireballs shot by monsters. There is no explicit reward, so the return is the number of steps survived; an episode lasts at most 2100 steps, and the task is solved at an average above 750 steps over 100 consecutive episodes. This time the controller is trained only in dreams generated by M and then run in the real environment:
| Temperature | Virtual score | Actual score |
|---|---|---|
| 0.10 | 2086 ± 140 | 193 ± 58 |
| 0.50 | 2060 ± 277 | 196 ± 50 |
| 1.00 | 1145 ± 690 | 868 ± 511 |
| 1.15 | 918 ± 546 | 1092 ± 556 |
| 1.30 | 732 ± 269 | 753 ± 139 |
| Random policy | n/a | 210 ± 108 |
| Gym leaderboard best | n/a | 820 ± 58 |
Appendix A.5 also reports that at τ=1.15 the best agent averaged 959 over 1024 dream rollouts and 1092 ± 556 over 100 real rollouts; Table 2 lists 918 ± 546 as the virtual score at the same temperature, which differs from 959, and the paper does not say whether the two evaluations share the same setup.
Cheating and temperature. Section 4.5 records a typical exploit: in early experiments the agent learned a way of moving that made the monsters in some dream rollouts shoot no fireball at all, and even “extinguish” a forming fireball. At temperature 0.1 M behaves almost like a deterministic LSTM and mode-collapses: whatever the agent does, the dream monsters never fire, so the dream score is almost always perfect while the real environment is worse than a random policy. A moderately higher makes the dream harder and more random, so the controller cannot exploit M’s flaws as easily; but if is too high the dream is too hard to learn anything. The paper also notes that τ=1.30 gives a lower best score but a less risky strategy with lower variance in returns.
Checking it with code
Two things. (1) Count parameters. From the layer layout of the appendix’s Figure 22 (convolutions 32×4, 64×4, 128×4, 256×4, two dense heads, a 1024-dimensional dense layer, deconvolutions 128×5, 64×5, 32×6, 3×6) and the structure of M and C, I compute six parameter counts and compare them with the paper’s two tables. (2) A scaled-down “train in the dream” on CartPole. The real environment is my own CartPole; V is the identity (the state is already a low-dimensional vector); M is a small MLP that predicts a diagonal Gaussian over the state change, with scaling the sampling noise; C is a 5-parameter linear controller trained only inside M with a diagonal-covariance cross-entropy method (CEM, a simple evolution strategy, not CMA-ES); finally the controller runs in the real environment. I sweep two variables: the number of random-policy transitions used to train M (10 to 1000) and the temperature (0, 1, 2), with 10 seeds per cell (data set, M initialization and evolutionary search use independent seeds, and the three temperatures of one seed share one M). This is a teaching-scale version, not the paper’s experiment: there are no images, no RNN hidden state (the CartPole state is Markov), and M is a single Gaussian rather than a mixture.
import math
import random
import statistics as st
import torch
from torch import nn
torch.set_num_threads(1)
# ---- Part 1: count parameters from the appendix layer layout ----
def conv(i, o, k):
return i * o * k * k + o
def dense(i, o):
return i * o + o
def lstm(i, h):
return 4 * (h * (i + h) + h) # one bias vector per gate
def vae(nz): # Figure 22: 4 conv, 2 dense heads, 1 dense, 4 deconv
enc = conv(3, 32, 4) + conv(32, 64, 4) + conv(64, 128, 4)
enc += conv(128, 256, 4) + 2 * dense(1024, nz)
dec = dense(nz, 1024) + conv(1024, 128, 5) + conv(128, 64, 5)
return enc + dec + conv(64, 32, 6) + conv(32, 3, 6)
rows = [
("CarRacing V", vae(32), 4_348_547),
("CarRacing M", lstm(35, 256) + dense(256, 5 * 32 * 3), 422_368),
("CarRacing C", (32 + 256) * 3 + 3, 867),
("Doom V", vae(64), 4_446_915),
("Doom M", lstm(65, 512) + dense(512, 5 * 64 * 3 + 1), 1_678_785),
("Doom C", 64 + 2 * 512, 1_088),
]
print(f"{'':12s}{'mine':>10s}{'paper':>10s}{'diff':>8s}")
for name, mine, paper in rows:
print(f"{name:12s}{mine:>10,}{paper:>10,}{mine - paper:>8,}")
# ---- Part 2: training inside the dream on CartPole ----
LIM_X, LIM_TH, MAX_T = 2.4, 0.2095, 500
class CartPole: # the real environment: Euler steps of 0.02 s
def __init__(self, seed):
self.rng = random.Random(seed)
def reset(self):
self.s = [self.rng.uniform(-0.05, 0.05) for _ in range(4)]
self.t = 0
return list(self.s)
def step(self, action):
x, xd, th, thd = self.s
force = 10.0 if action == 1 else -10.0
c, s = math.cos(th), math.sin(th)
temp = (force + 0.05 * thd * thd * s) / 1.1
tha = (9.8 * s - c * temp) / (0.5 * (4 / 3 - 0.1 * c * c / 1.1))
xa = temp - 0.05 * tha * c / 1.1
self.s = [x + 0.02 * xd, xd + 0.02 * xa, th + 0.02 * thd,
thd + 0.02 * tha]
self.t += 1
out = abs(self.s[0]) > LIM_X or abs(self.s[2]) > LIM_TH
return list(self.s), out or self.t >= MAX_T
def collect(n, seed):
# n random-policy transitions; env and actions use independent seeds
env, rng = CartPole(10_000 + seed), random.Random(20_000 + seed)
data, s = [], env.reset()
for _ in range(n):
a = rng.randint(0, 1)
s2, done = env.step(a)
data.append((s, a, s2))
s = env.reset() if done else s2
S = torch.tensor([d[0] for d in data])
A = torch.tensor([d[1] for d in data], dtype=torch.float32)[:, None]
return S, A, torch.tensor([d[2] for d in data])
class Dyn(nn.Module): # M: diagonal Gaussian over the state change
def __init__(self, S, S2):
super().__init__()
self.mu_in, self.sd_in = S.mean(0), S.std(0) + 1e-6
d = S2 - S
self.mu_out, self.sd_out = d.mean(0), d.std(0) + 1e-6
self.f = nn.Sequential(nn.Linear(5, 64), nn.Tanh(),
nn.Linear(64, 64), nn.Tanh(),
nn.Linear(64, 8))
def forward(self, s, a):
out = self.f(torch.cat([(s - self.mu_in) / self.sd_in, a], 1))
return out[:, :4], out[:, 4:].clamp(-6, 2)
def sample(self, s, a, tau): # tau scales the sampling noise
mean, logsd = self(s, a)
d = mean + tau * logsd.exp() * torch.randn_like(mean)
return s + d * self.sd_out + self.mu_out
def fit_model(S, A, S2, seed, steps=3000):
torch.manual_seed(30_000 + seed)
m = Dyn(S, S2)
d = (S2 - S - m.mu_out) / m.sd_out
opt = torch.optim.Adam(m.parameters(), lr=2e-3)
for _ in range(steps):
i = torch.randint(0, len(S), (64,))
mean, logsd = m(S[i], A[i])
z = (d[i] - mean) / logsd.exp()
loss = (logsd + 0.5 * z ** 2).sum(1).mean()
opt.zero_grad()
loss.backward()
opt.step()
return m
@torch.no_grad()
def model_error(m, S, A, S2):
# one-step RMSE divided by the std of the true change
pred = m(S, A)[0] * m.sd_out + m.mu_out
true = S2 - S
return ((pred - true).pow(2).mean(0).sqrt() / true.std(0)).mean().item()
def policy(W, s): # C: linear controller, W has shape (k, 5)
z = torch.einsum("kd,knd->kn", W[:, :4], s) + W[:, 4:5]
return (z > 0).float()
@torch.no_grad()
def dream_returns(m, W, tau, n_ep, gen):
# run k*n_ep dreams in parallel inside M
k = W.shape[0]
s = (torch.rand(k, n_ep, 4, generator=gen) - 0.5) * 0.1
alive = torch.ones(k, n_ep, dtype=torch.bool)
ret = torch.zeros(k, n_ep)
for _ in range(MAX_T):
a = policy(W, s).reshape(-1, 1)
s = m.sample(s.reshape(-1, 4), a, tau).reshape(k, n_ep, 4)
ret += alive.float()
alive &= (s[..., 0].abs() <= LIM_X) & (s[..., 2].abs() <= LIM_TH)
if not alive.any():
break
return ret.mean(1)
def real_return(w, seed, n_ep=20):
# put the controller into the real environment
env, tot = CartPole(seed), 0
for _ in range(n_ep):
s, done = env.reset(), False
while not done:
z = sum(w[i] * s[i] for i in range(4)) + w[4]
s, done = env.step(1 if z > 0 else 0)
tot += 1
return tot / n_ep
def cem(m, tau, seed, gens=15, lam=32, elite=8, n_ep=8):
gen = torch.Generator().manual_seed(50_000 + seed)
mean, sd = torch.zeros(5), torch.ones(5)
for _ in range(gens):
W = mean + sd * torch.randn(lam, 5, generator=gen)
top = W[dream_returns(m, W, tau, n_ep, gen).topk(elite).indices]
mean, sd = top.mean(0), top.std(0) + 0.05
return mean
g = torch.Generator().manual_seed(1)
rand = [real_return(torch.randn(5, generator=g).tolist(), 80_000 + i, 5)
for i in range(60)]
hand = real_return([0, 0, 1, 1, 0], 85_000)
print(f"\nReal environment: random controllers {st.mean(rand):.1f}, "
f"hand-set [0,0,1,1,0] {hand:.1f}")
SIZES, TAUS, SEEDS = (10, 20, 30, 50, 100, 1000), (0.0, 1.0, 2.0), range(10)
test = collect(2000, 777)
res = {}
for n in SIZES:
for seed in SEEDS:
S, A, S2 = collect(n, seed)
m = fit_model(S, A, S2, seed)
err = model_error(m, *test)
for tau in TAUS:
torch.manual_seed(40_000 + seed)
w = cem(m, tau, seed)
g = torch.Generator().manual_seed(60_000 + seed)
dream = dream_returns(m, w[None], tau, 20, g).item()
real = real_return(w.tolist(), 70_000 + seed)
res[n, tau, seed] = (err, dream, real)
print("\n N tau M err dream return real return real>=475")
for n in SIZES:
for tau in TAUS:
e, d, r = zip(*(res[n, tau, s] for s in SEEDS))
print(f"{n:5d} {tau:4.1f} {st.mean(e):.3f} "
f"{st.mean(d):6.1f}±{st.stdev(d):5.1f} "
f"{st.mean(r):6.1f}±{st.stdev(r):5.1f} "
f"{sum(x >= 475 for x in r):2d}/{len(SEEDS)}")
print("\nReal-return difference, tau=2 minus tau=0 (paired, 10 seeds)")
for n in SIZES:
diff = [res[n, 2.0, s][2] - res[n, 0.0, s][2] for s in SEEDS]
print(f"N={n:5d}: {st.mean(diff):+6.1f} ± "
f"{st.stdev(diff) / len(diff) ** 0.5:5.1f} (s.e.)")
Output (CPU, one thread, about 6 minutes; individual numbers may differ slightly in another environment):
mine paper diff
CarRacing V 4,348,547 4,348,547 0
CarRacing M 422,368 422,368 0
CarRacing C 867 867 0
Doom V 4,446,915 4,446,915 0
Doom M 1,676,737 1,678,785 -2,048
Doom C 1,088 1,088 0
Real environment: random controllers 17.6, hand-set [0,0,1,1,0] 491.2
N tau M err dream return real return real>=475
10 0.0 0.741 221.5±174.5 21.0± 13.5 0/10
10 1.0 0.741 191.3±157.0 29.0± 19.9 0/10
10 2.0 0.741 158.3±134.6 28.3± 22.4 0/10
20 0.0 0.483 234.2±205.6 143.1±143.3 0/10
20 1.0 0.483 209.7±193.5 147.5±163.5 0/10
20 2.0 0.483 154.4±148.7 120.3±122.7 0/10
30 0.0 0.283 418.5±119.7 426.6±141.1 6/10
30 1.0 0.283 392.3±108.5 363.9±173.3 5/10
30 2.0 0.283 357.1±155.7 296.7±193.6 4/10
50 0.0 0.223 472.4± 70.4 337.0±175.2 5/10
50 1.0 0.223 434.8±133.4 327.2±185.5 5/10
50 2.0 0.223 396.9±152.5 324.3±179.9 4/10
100 0.0 0.163 498.1± 6.0 433.0±132.0 7/10
100 1.0 0.163 492.5± 23.8 459.5±126.4 9/10
100 2.0 0.163 474.4± 55.6 460.7±122.0 9/10
1000 0.0 0.086 500.0± 0.0 478.0± 69.6 9/10
1000 1.0 0.086 500.0± 0.0 488.9± 35.1 9/10
1000 2.0 0.086 481.2± 52.5 476.6± 74.1 9/10
Real-return difference, tau=2 minus tau=0 (paired, 10 seeds)
N= 10: +7.3 ± 4.3 (s.e.)
N= 20: -22.7 ± 26.4 (s.e.)
N= 30: -129.9 ± 65.7 (s.e.)
N= 50: -12.7 ± 57.9 (s.e.)
N= 100: +27.6 ± 29.9 (s.e.)
N= 1000: -1.4 ± 1.4 (s.e.)
How to read these numbers:
- Five of the six parameter counts match digit for digit. Both VAEs (4,348,547 and 4,446,915), CarRacing’s M (422,368) and C (867) and Doom’s C (1,088) agree with the paper, so my reading of Figure 22 and the appendix is right. Doom’s M is off by 2,048, which is exactly and fits an implementation with one extra 512-dimensional vector per LSTM gate (for example a second bias vector or a layer-norm gain); the text does not say, and I did not check the authors’ code, so this is only a guess.
- The task is solvable, but random search almost never finds it. A random linear controller lasts 17.6 steps on average in the real environment, while the hand-set [0, 0, 1, 1, 0] (push right when pole angle plus angular velocity is positive) lasts 491.2 steps, close to the 500-step cap.
- M’s error falls monotonically with data. The one-step prediction error (RMSE divided by the standard deviation of the true change, 0 is perfect) drops from 0.741 at to 0.086 at .
- With too little data there is a dream-reality gap. At the dream lasts 158 to 222 steps but the real environment only 21 to 29, about the same as a random controller’s 17.6: the controller has learned M’s mistakes rather than how to balance the pole. At the dream gives 154 to 234 steps and reality 120 to 148, with huge seed-to-seed variation (standard deviation 120 to 200).
- With enough data it transfers, but not reliably. For the dream and reality are close, real returns are 433 to 489, and 7 to 9 of the 10 seeds exceed 475 steps; at the dream return is always 500 for (it hits the cap, so dream returns can no longer tell controllers apart). The real return at (: 426.6) is higher than at (337.0), but the standard deviations are 141 and 175, the standard error over 10 seeds is about 45 to 55, and the difference is within noise, so I do not interpret it.
- Temperature has no consistent benefit in this toy. Paired comparison (same seed, real return at minus ): +7.3±4.3, −22.7±26.4, −129.9±65.7, −12.7±57.9, +27.6±29.9, −1.4±1.4 (standard errors). The cell is about 2 standard errors below zero, which is unsurprising among six cells, and I do not read it as “temperature hurts”. The paper’s Table 2 pattern, low temperature letting the controller cheat, did not show up, most likely because CartPole is deterministic: there is no discrete random event like “does the monster fire”, so M has no mode to collapse into at low temperature. This toy cannot test the paper’s claim about temperature.
Limitations and what to keep in mind
- The world model is fixed and the data comes from a random policy. The iterative training proposed in Section 5 (the controller explores, then M is updated) is only an outline; the paper says one iteration was enough for simple tasks and harder ones need active exploration.
- V does not know the task. An unsupervised VAE reproduces irrelevant detail (the brick pattern on the Doom walls) and can miss task-relevant detail (some tiles on the CarRacing road); the paper discusses training the VAE together with an M that predicts reward, at the price that V is then harder to reuse for other tasks.
- M has limited capacity. An LSTM world model may not hold a large amount of history; the paper mentions catastrophic forgetting and lists higher-capacity models or external memory as future work.
- Simple tasks and high variance. Both tasks are simple (the paper itself says data from a random policy is enough for a reasonable world model); the standard deviation of 1092 ± 556 in Table 2 is large, and the scores for τ=1.0, 1.15 and 1.30 differ by less than one standard deviation.
- Sample efficiency is not measured. Appendix A.5 states that the paper never trained an agent in the real VizDoom, only used it to collect random-policy data, so “how many samples dreaming saves compared with training in the real environment” is not quantified.
- Limits of the toy experiment. A single-Gaussian M, a 5-parameter controller, 10 seeds and a deterministic CartPole show a mechanism only and cannot replace the paper’s pixel experiments.
What to take from this paper
- Split the agent: a large model learns representation and prediction, a small controller learns decisions. A small controller makes gradient-free methods such as evolution strategies usable.
- A world model can be used as an environment. If it predicts the next observation and a termination signal, a policy can be trained inside it with no rendering and no game engine.
- The world model is imperfect and the policy will exploit it. A high dream score is not a high real score, so always evaluate in the real environment; adding randomness to the model (temperature) is the paper’s mitigation.
- The dream-reality gap shrinks as the world model improves. In my toy, with too little data the dream return and the real return differ by an order of magnitude.
- Iterative data collection is the road to harder tasks. The paper only sketches it, and later work implemented it.
Further reading
- Paper: World Models; interactive version: worldmodels.github.io
- Follow-up: Hafner et al., Mastering Diverse Domains through World Models (DreamerV3, 2023); paper breakdown: the world model and policy are trained together, with a set of robustness techniques that let one set of hyperparameters work across domains.
- Related Wiki on this site: Next-token prediction (M’s prediction of the next is the same kind of self-supervised objective as a language model’s next-word prediction), Reinforcement learning for reasoning
- Glossary: World model, Variational autoencoder, Evolution strategies
FAQ
- What do V, M and C do in World Models?
- V is a variational autoencoder (VAE) that compresses each 64×64 frame into a small vector z (32 dimensions in CarRacing, 64 in Doom). M is an LSTM with a mixture-density output (MDN-RNN) that predicts the distribution of the next z from the action, the current z and its hidden state h. C is a single linear layer, a_t = W_c[z_t h_t] + b_c, with only 867 parameters in CarRacing. V and M are trained without supervision on 10,000 random-policy rollouts, and C is optimized with the evolution strategy CMA-ES.
- How does the agent train in a dream, and why does that work?
- In the VizDoom experiment M also predicts whether the agent dies on the next step, so M is a complete reinforcement-learning environment: the controller can try things over and over in the latent sequences it generates, with no rendering and no game engine. The paper deploys the controller trained in a dream at temperature 1.15 into the real VizDoom Take Cover and gets an average survival of 1092 ± 556 steps over 100 rollouts, above the 750 steps required to solve the task.
- Why does the temperature τ matter so much?
- M is only an approximation of the real environment, and the controller exploits its flaws: in the paper the agent found a way to move so that the monsters in some dream rollouts never shoot a single fireball. At τ=0.1 the dream is almost always a perfect score (2086 ± 140) but the real environment gives only 193 ± 58, worse than the random policy's 210 ± 108; with τ between 1.0 and 1.3 the transfer is good (1092 ± 556 at τ=1.15). If τ is too high the dream becomes too hard to learn anything, so it is a hyperparameter to tune.
- How does this paper relate to today's world models?
- It built a simple version that works from pixels: first learn a model that predicts the future, then train a policy inside the model. Its world model is fixed and its data comes from a random policy; the iterative data collection proposed in Section 5 is only an outline. Later, the Dreamer family trains policies on imagined trajectories in a learned latent dynamics model, and models such as Genie learn interactive environments from video.