Overview
A World Models agent is built in stages, each feeding the next. First the agent acts and records what it sees. The vision model learns to compress those frames. The memory model learns how the compressed codes change over time. Last, a tiny controller learns to act using only the code and the memory. There is a catch: the first data comes from random actions, so the first two models only know the parts of the world a random policy reaches. The fix is to go around again. Collect new data with the trained controller, which gets further, and retrain all three. This template is a compact version of every stage so the full loop runs in seconds.
A short history
David Ha and Jürgen Schmidhuber's 2018 World Models paper trained its three parts in order: the vision model on frames from random play, the memory model on the encoded sequences, then the controller. For simple tasks one pass was enough. The paper also described an iterative version for harder tasks, in which the improved controller collects new rollouts and the models are retrained on them, because random play never reaches the later parts of the environment.
How it works
collectrecordsepisodes_per_iterationreal episodes: with random actions on the first pass, and with the current controller plus Gaussian noise on later passes.train_visiontrainsTinyVAEon every frame recorded so far forvae_stepsminibatch steps.train_memoryencodes every recorded rollout with the current vision model and refitsTinyMemory, a fixed random recurrent layer with a ridge-regression readout that predicts the change in the latent.train_controllersearches over the weights of a linear controller with the cross-entropy method. Each candidate is scored by real episodes with the vision and memory models in the loop and held fixed.iterateruns these four stages once and returns their statistics. The memory's error is reported next to the error of predicting no change, as a baseline.run(n)repeats the pass. Each new pass adds episodes from a better controller to the data that V and M are trained on.
Watch out for
- The stages are trained one after another, never jointly. The vision model is not told what the controller needs, so it may spend its code on details that do not matter for reward.
- When the vision model is retrained, the meaning of its codes changes. The memory model and controller built on the old codes are then out of date, which is why each pass retrains all three in order.
- The controller is scored in the real environment here, which uses many more real episodes than collection does. Training it inside the memory model, as the dream template does, avoids that cost.
- With one iteration only, the models have seen just what a random policy reaches. On tasks where random actions fail early, a single pass is not enough.
- Every part is a small stand-in: a dense VAE, a fixed-weight recurrent memory and the cross-entropy method, where the paper uses a convolutional VAE, an LSTM with a mixture density output and CMA-ES.
Use cases
When to use it
Use it as the skeleton of a World Models experiment: it shows what data each stage needs and in what order the stages run. Add iterations when a random policy does not explore enough of the environment.
In industry
- Games and simulation
- Car racing and first-person game tasks learned from pixels, with data collection repeated as the controller reaches new parts of the track or level.
- Robotics research
- Alternating between collecting experience with the current policy and refitting a learned model, the loop behind most model-based robot learning.
- Research and teaching
- A complete, staged example of model-based reinforcement learning in which each stage can be inspected and tested separately.
Choosing it: what must hold
- An environment that can be run for data collection at each iteration.
- Storage for the collected rollouts, and compute to retrain the vision and memory models each time.
- Checks between stages, since a poor vision model limits everything trained after it.
When to choose something else
| If | Use instead |
|---|---|
| Random play already covers the states that matter | A single pass through the three stages, without iterating |
| You want model and policy trained together from state vectors | MBPO |
| Real steps are cheap and you do not need a model | PPO, or DQN for discrete actions |
Math foundations
Stage V: the vision loss
Trained on frames alone, with no actions or rewards. It asks only that a frame can be redrawn from its short code , and that codes stay close to a standard normal.
Stage M: the memory readout
Trained on sequences of codes and actions. The features are built from the hidden state , the code and the action, and the fit predicts how the code will change. The hidden state it maintains is passed on to the controller.
Stage C: the controller
Trained on episode return alone. It sees only what V and M provide, so it has weights, small enough to search without gradients.
The controller search
Each generation samples candidate weight vectors, scores each by its mean return over a few episodes, and refits the sampling distribution to the best ones.
Real episodes used by one pass
Collection uses a fixed number of episodes. Controller training uses generations times population times rollouts per candidate. The second term is usually much the larger.
Symbols
- a frame and its reconstruction by the vision model
- latent code of the frame at step t
- hidden state of the memory model at step t
- lengths of the latent code and of the hidden state
- KL weight and free-bits tolerance of the vision loss
- stacked memory features and observed changes in the latent
- ridge penalty and number of recorded steps
- weights of the linear controller
- mean and standard deviation of the search over controller weights
- episodes recorded per pass (episodes_per_iteration)
- generations, population and rollouts per candidate
Worked by hand
Count what one pass of the loop uses with the default settings: 30 collected episodes of 20 steps, a 2-dimensional code, a memory of 48 units, and a search of 10 generations with 24 candidates scored on 3 episodes each.
The vision and memory models learn from 30 episodes, but scoring controllers uses 720 more. That imbalance is the reason for training the controller inside the model when real episodes are expensive.
Visual example
Loading the example.
Try this
- Press Run the next stage four times and click each box after its stage to read what it measured.
- Press Finish the pass again and compare the collected episodes of pass 2 with those of pass 1.
- Start over with 5 episodes per pass and see what V and M can learn from so little data.
- Check the episode count: collecting uses 20 episodes a pass, scoring controllers uses 192.
Code sample
from impl import WorldModelTrainer
from config import TrainingConfig
trainer = WorldModelTrainer(TrainingConfig())
print(trainer.evaluate(range(50), policy="random")) # about -5
for stats in trainer.run(n_iterations=2):
print(stats) # losses and returns of each pass
print(trainer.evaluate(range(50))) # about -1 with V, M and C in the loopRead the implementation (263 lines)
"""The World Models training loop: collect rollouts, train V, then M, then C, and repeat with the new controller.
NumPy only. The folder stands alone, so it holds a compact version of each part: a pixel environment, a dense VAE
(V), a recurrent memory with trained readout (M), and a linear controller trained by an evolution strategy (C).
"""
from __future__ import annotations
import numpy as np
try:
from .config import TrainingConfig
except ImportError: # run from the template's own folder
from config import TrainingConfig
class PixelTrackEnv:
"""A dot on a strip of pixels that has to be steered to the middle.
The hidden state is a position p in [0, 1]. The agent sees only a frame of `frame_size` pixels with a
Gaussian blob at p. Action a in [-1, 1] moves the dot: p += 0.1 * a + noise. Reward is -|p - 0.5| after
the move. An episode starts at a random p and lasts `episode_length` steps.
"""
def __init__(self, frame_size: int = 12, episode_length: int = 20, noise_std: float = 0.005) -> None:
self.frame_size, self.episode_length, self.noise_std = frame_size, episode_length, noise_std
self.rng = np.random.default_rng(0)
self.p, self.t = 0.5, 0
def _frame(self) -> np.ndarray:
pixels = np.arange(self.frame_size)
return np.exp(-0.5 * (pixels - self.p * (self.frame_size - 1)) ** 2)
def reset(self, seed: int) -> np.ndarray:
"""Start the episode fixed by `seed`. Returns the first frame, shape (frame_size,), values in [0, 1]."""
self.rng = np.random.default_rng(seed)
self.p, self.t = float(self.rng.uniform(0.0, 1.0)), 0
return self._frame()
def step(self, action) -> tuple[np.ndarray, float, bool]:
"""Returns (frame (frame_size,), reward, done)."""
a = float(np.clip(np.asarray(action).ravel()[0], -1.0, 1.0))
self.p = float(np.clip(self.p + 0.1 * a + self.noise_std * self.rng.standard_normal(), 0.0, 1.0))
self.t += 1
return self._frame(), -abs(self.p - 0.5), self.t >= self.episode_length
def _sigmoid(x: np.ndarray) -> np.ndarray:
return 0.5 * (1.0 + np.tanh(0.5 * x))
class TinyVAE:
"""V: dense variational autoencoder, frame (D,) -> z (latent_size,). One tanh hidden layer on each side."""
def __init__(self, config: TrainingConfig, rng: np.random.Generator) -> None:
self.config, self.rng = config, rng
d, h, z = config.frame_size, config.vae_hidden, config.latent_size
shapes = {"enc_w": (d, h), "mu_w": (h, z), "lv_w": (h, z), "dec_w1": (z, h), "dec_w2": (h, d)}
self.params = {k: rng.normal(0.0, 1.0 / np.sqrt(s[0]), size=s) for k, s in shapes.items()}
self.params["lv_w"] *= 0.1
for k, s in shapes.items():
self.params[k.replace("_w", "_b")] = np.zeros(s[1])
self._m = {k: np.zeros_like(v) for k, v in self.params.items()}
self._v = {k: np.zeros_like(v) for k, v in self.params.items()}
self._t = 0
def encode(self, frames: np.ndarray) -> np.ndarray:
"""frames (B, D) -> the mean code mu (B, latent_size)."""
p = self.params
return np.tanh(frames @ p["enc_w"] + p["enc_b"]) @ p["mu_w"] + p["mu_b"]
def decode(self, z: np.ndarray) -> np.ndarray:
"""z (B, latent_size) -> frames (B, D) in (0, 1)."""
p = self.params
return _sigmoid(np.tanh(z @ p["dec_w1"] + p["dec_b1"]) @ p["dec_w2"] + p["dec_b2"])
def train_step(self, x: np.ndarray) -> float:
"""One Adam step on frames x (B, D).
loss = mean_b [ sum (x - x_hat)^2 + kl_weight * max(KL_b, kl_tolerance * latent_size) ]. Returns the loss.
"""
c, p, b = self.config, self.params, len(x)
enc_h = np.tanh(x @ p["enc_w"] + p["enc_b"])
mu, logvar = enc_h @ p["mu_w"] + p["mu_b"], enc_h @ p["lv_w"] + p["lv_b"]
eps = self.rng.standard_normal(mu.shape)
std = np.exp(0.5 * logvar)
z = mu + std * eps
dec_h = np.tanh(z @ p["dec_w1"] + p["dec_b1"])
x_hat = _sigmoid(dec_h @ p["dec_w2"] + p["dec_b2"])
kl = 0.5 * (np.exp(logvar) + mu**2 - 1.0 - logvar).sum(axis=1)
floor = c.kl_tolerance * c.latent_size
loss = float((((x - x_hat) ** 2).sum(axis=1) + c.kl_weight * np.maximum(kl, floor)).mean())
active = c.kl_weight * (kl > floor).astype(float)[:, None] / b
d_out = 2.0 * (x_hat - x) * x_hat * (1.0 - x_hat) / b
d_dec_h = (d_out @ p["dec_w2"].T) * (1.0 - dec_h**2)
d_z = d_dec_h @ p["dec_w1"].T
d_mu = d_z + active * mu
d_lv = d_z * eps * 0.5 * std + active * 0.5 * (np.exp(logvar) - 1.0)
d_enc_h = (d_mu @ p["mu_w"].T + d_lv @ p["lv_w"].T) * (1.0 - enc_h**2)
grads = {"dec_w2": dec_h.T @ d_out, "dec_b2": d_out.sum(0), "dec_w1": z.T @ d_dec_h, "dec_b1": d_dec_h.sum(0),
"mu_w": enc_h.T @ d_mu, "mu_b": d_mu.sum(0), "lv_w": enc_h.T @ d_lv, "lv_b": d_lv.sum(0),
"enc_w": x.T @ d_enc_h, "enc_b": d_enc_h.sum(0)}
self._t += 1
for k, w in p.items():
m, v, g = self._m[k], self._v[k], grads[k]
m *= 0.9
m += 0.1 * g
v *= 0.999
v += 0.001 * g * g
w -= c.vae_lr * (m / (1 - 0.9**self._t)) / (np.sqrt(v / (1 - 0.999**self._t)) + 1e-8)
return loss
class TinyMemory:
"""M: recurrent layer with fixed random weights, h' = tanh([z, a] W_in + h W_rec + b), and a ridge readout
that predicts z_{t+1} - z_t from [h', z, a, 1]. Its hidden state h is the memory feature the controller reads."""
def __init__(self, config: TrainingConfig, rng: np.random.Generator) -> None:
self.config = config
n_in, n = config.latent_size + 1, config.memory_size
self.w_in = rng.normal(size=(n_in, n))
self.bias = rng.uniform(-1.0, 1.0, size=n)
w_rec = rng.normal(size=(n, n))
self.w_rec = w_rec * (config.spectral_radius / np.abs(np.linalg.eigvals(w_rec)).max())
self.w_out = np.zeros((n + n_in + 1, config.latent_size))
def initial_state(self) -> np.ndarray:
return np.zeros(self.config.memory_size)
def advance(self, z: np.ndarray, action: float, h: np.ndarray) -> np.ndarray:
"""Hidden state after reading (z_t, a_t): z (Z,), h (H,) -> (H,)."""
return np.tanh(np.append(z, action) @ self.w_in + h @ self.w_rec + self.bias)
def predict_next(self, z: np.ndarray, action: float, h_next: np.ndarray) -> np.ndarray:
"""Predicted z_{t+1} (Z,) given z_t, a_t and the hidden state that has already read them."""
return z + np.concatenate([h_next, z, [action, 1.0]]) @ self.w_out
def fit(self, episodes: list[tuple[np.ndarray, np.ndarray]]) -> tuple[float, float]:
"""Fit the readout on episodes of (latents (T + 1, Z), actions (T,)).
Returns (rmse of the model's next-latent prediction, rmse of predicting no change).
"""
feats, targets = [], []
for latents, actions in episodes:
h = self.initial_state()
for t, a in enumerate(actions):
h = self.advance(latents[t], a, h)
feats.append(np.concatenate([h, latents[t], [a, 1.0]]))
targets.append(latents[t + 1] - latents[t])
x, y = np.array(feats), np.array(targets)
gram = x.T @ x + self.config.ridge * len(x) * np.eye(x.shape[1])
self.w_out = np.linalg.solve(gram, x.T @ y)
return float(np.sqrt(((x @ self.w_out - y) ** 2).mean())), float(np.sqrt((y**2).mean()))
class WorldModelTrainer:
"""Holds V, M and C and runs the iterative procedure: collect, train V, train M, train C, repeat."""
def __init__(self, config: TrainingConfig | None = None, env: PixelTrackEnv | None = None) -> None:
self.config = c = config or TrainingConfig()
self.env = env or PixelTrackEnv(frame_size=c.frame_size)
self.rng = np.random.default_rng(c.seed)
self.vision = TinyVAE(c, self.rng)
self.memory = TinyMemory(c, self.rng)
self.controller = np.zeros(c.latent_size + c.memory_size + 1) # weights for [z, h, 1]
self.rollouts: list[tuple[np.ndarray, np.ndarray]] = [] # (frames (T + 1, D), actions (T,))
self.iteration = 0
self._episode_seed = 10_000 + c.seed # seeds for data collection, kept apart from evaluation seeds
def act(self, z: np.ndarray, h: np.ndarray, params: np.ndarray | None = None) -> float:
"""C: action = tanh(w . [z, h, 1]), a number in [-1, 1]."""
w = self.controller if params is None else params
return float(np.tanh(w @ np.concatenate([z, h, [1.0]])))
def run_episode(self, seed: int, policy: str = "controller", params: np.ndarray | None = None,
record: bool = False) -> float:
"""Run one real episode.
policy: "controller" (V, M and C in the loop), "noisy" (the same plus Gaussian exploration noise) or
"random" (uniform actions, V and M not used). params: controller weights to use instead of the current ones.
record: store the episode's frames and actions for training. Returns the episode return.
"""
c = self.config
frame, done, total = self.env.reset(seed), False, 0.0
h = self.memory.initial_state()
frames, actions = [frame], []
while not done:
if policy == "random":
action = float(self.rng.uniform(-1.0, 1.0))
else:
z = self.vision.encode(frame[None])[0]
action = self.act(z, h, params)
if policy == "noisy":
action = float(np.clip(action + c.exploration_noise * self.rng.standard_normal(), -1.0, 1.0))
h = self.memory.advance(z, action, h)
frame, reward, done = self.env.step(action)
total += reward
frames.append(frame)
actions.append(action)
if record:
self.rollouts.append((np.array(frames), np.array(actions)))
return total
def collect(self, n_episodes: int, policy: str) -> float:
"""Record `n_episodes` real episodes with the given policy. Returns their mean return."""
returns = []
for _ in range(n_episodes):
self._episode_seed += 1
returns.append(self.run_episode(self._episode_seed, policy, record=True))
return float(np.mean(returns))
def train_vision(self) -> float:
"""Train V on every recorded frame for `vae_steps` minibatch steps. Returns the mean loss of the last 50."""
c = self.config
frames = np.concatenate([f for f, _ in self.rollouts])
losses = [self.vision.train_step(frames[self.rng.integers(0, len(frames), size=c.batch_size)])
for _ in range(c.vae_steps)]
return float(np.mean(losses[-50:]))
def train_memory(self) -> tuple[float, float]:
"""Encode every rollout with the current V and refit M. Returns (model rmse, no-change rmse)."""
return self.memory.fit([(self.vision.encode(frames), actions) for frames, actions in self.rollouts])
def train_controller(self) -> float:
"""Evolve C in the real environment with V and M fixed (cross-entropy method over its weights).
Every candidate of a generation is scored on the same `n_rollouts` episodes. Returns the best mean return
of the last generation.
"""
c = self.config
mean, std = self.controller.copy(), np.full(self.controller.shape, c.sigma_init)
best = 0.0
for generation in range(c.n_generations):
seeds = [20_000 + 1000 * self.iteration + 10 * generation + k for k in range(c.n_rollouts)]
candidates = mean + std * self.rng.standard_normal((c.population, len(mean)))
scores = np.array([np.mean([self.run_episode(s, params=w) for s in seeds]) for w in candidates])
elites = candidates[np.argsort(scores)[-c.n_elites :]]
mean, std = elites.mean(axis=0), elites.std(axis=0) + 0.01
best = float(scores.max())
self.controller = mean
return best
def evaluate(self, seeds, policy: str = "controller") -> float:
"""Mean return over the given episode seeds, without recording."""
return float(np.mean([self.run_episode(s, policy) for s in seeds]))
def iterate(self) -> dict:
"""One pass of the loop. The first pass collects with a random policy, later ones with the noisy controller.
Returns: iteration, collect_return, vae_loss, memory_rmse, no_change_rmse, controller_return, n_frames.
"""
c = self.config
collect_return = self.collect(c.episodes_per_iteration, "random" if self.iteration == 0 else "noisy")
vae_loss = self.train_vision()
memory_rmse, no_change_rmse = self.train_memory()
controller_return = self.train_controller()
self.iteration += 1
return {"iteration": self.iteration, "collect_return": collect_return, "vae_loss": vae_loss,
"memory_rmse": memory_rmse, "no_change_rmse": no_change_rmse,
"controller_return": controller_return, "n_frames": sum(len(f) for f, _ in self.rollouts)}
def run(self, n_iterations: int) -> list[dict]:
"""Run `n_iterations` passes. Returns the list of per-iteration statistics."""
return [self.iterate() for _ in range(n_iterations)]- Repository
- Not published yet
- Needs
- Python 3.10 and NumPy
- Tests
- 8, run with
python3 -m unittest -v
Practice
Create trainer = WorldModelTrainer(TrainingConfig()) and record trainer.evaluate(range(10), policy="random"). Call trainer.run(2) and print each pass's collect_return, memory_rmse, no_change_rmse and controller_return. Evaluate again with the controller. Then build a second trainer with exploration_noise=0.0 and compare its second pass with the first trainer's.
Check on learning
- On the second pass the data comes from a controller that already steers toward the middle. How does the set of frames differ from the first pass, and why might the vision model get worse on frames near the edges?
A way to think about it
Count how often the dot is near an edge under each policy. The training batches are drawn from all recorded frames, so check what share the edge frames now have.
- The memory model's error is reported next to the error of predicting no change at all. Why is that comparison needed to judge the model?
A way to think about it
If the code moves very little per step, a tiny error can still be useless. Ask what error a model that has learned nothing would show.
- Why must the memory model be refit after the vision model is retrained, even on exactly the same episodes?
A way to think about it
The memory model's inputs and targets are codes. Think about what happens to the code of a given frame when the encoder's weights change.
- The three parts are trained separately, each with its own objective. What is one advantage of that over training everything end to end on reward, and one disadvantage?
A way to think about it
Consider how much learning signal there is in a frame compared with one reward number, and who decides which features of the frame are worth keeping.
- The exploration noise is added when collecting with the trained controller. What would the new data look like without it, and what would the memory model fail to learn?
A way to think about it
A deterministic controller takes one action in each situation. Ask how the model could learn what the other actions would have done.