Overview
Once a model can predict the next state, the reward and whether the episode ends, it can stand in for the environment. Feed it an action, take its prediction as what happened, and repeat: that loop is a dream. Dream episodes cost no real interaction, so a controller can practise in thousands of them. The risk is that the dream is wrong in ways a controller can exploit, winning in imagination by means that fail in reality. Making the dream noisier is the defence: a controller cannot rely on a precise flaw in a world that keeps shifting. This template uses a small echo state network as M and the cross-entropy method as the search, where the paper uses an LSTM with a mixture density output and CMA-ES.
A short history
The idea of learning inside a model's imagination goes back to Richard Sutton's Dyna in 1990 and to Jürgen Schmidhuber's work on recurrent world models from the same period. In 2018 David Ha and Schmidhuber showed it working with deep networks: they trained a controller for a VizDoom task entirely inside the memory model's predictions and then transferred it to the real game. They also found that the controller can exploit model flaws, and that making the dream more random reduces this.
How it works
collect_random_episodesruns a random policy in the realBalanceEnvand records latents, actions, rewards and done flags.ReservoirMemory.fitruns its fixed random recurrent layer over those episodes and fits three linear readouts: the change in the latent, the reward, and the probability that the episode ends.DreamEnv.resetpicks a real first latent to start from and zeroes the hidden state. No real environment is used after this.DreamEnv.stepasks the model for the next latent's mean, the reward and the done probability, then adds Gaussian noise scaled by the square root oftemperatureto the mean.- The dream episode ends when the done probability passes
done_thresholdor aftermax_steps. train_in_dreamsamples a population of controller parameters, scores each by its mean return over dream episodes, refits the sampling Gaussian to the best ones, and repeats.RealWithMemorywraps the real environment so it returns the same features, andevaluatethen tests the dream-trained controller for real.
Watch out for
- A controller can score well in the dream by exploiting model errors, such as a state where the model never predicts the episode ending. Always compare the dream return with the real return.
- The model was fit on data from a random policy. A trained controller visits states the random policy never reached, where the model's predictions are guesses.
- With
temperatureat 0 the dream is deterministic and easiest to exploit. Raising it makes the controller more robust but can make the task too hard to learn. - Predicted rewards are clipped to the range seen in the data. That closes one way of cheating the dream but not the others, such as a done prediction that fires too late.
- The echo state network here has fixed random recurrent weights and only its readouts are trained. It is a compact stand-in, not as expressive as a trained LSTM.
Use cases
When to use it
Use it when real interaction is slow or costly and a learned model is good enough to practise in: collect a few random episodes, fit M, train C in the dream, then check C in the real environment.
In industry
- Games and simulation
- Training a policy inside a learned model of a game, then checking that it transfers to the real game.
- Robotics research
- Imagination-based training, continued by later agents such as the Dreamer family, to cut the number of real robot interactions.
- Autonomous driving research
- Learned simulators generate driving scenarios for training and testing policies without real road time.
Choosing it: what must hold
- A memory model accurate enough over the length of an episode, including a prediction of when the episode ends.
- A way to compute reward inside the dream, either predicted by the model or defined from its outputs.
- A final check in the real environment, since a policy can learn to exploit errors in the model.
When to choose something else
| If | Use instead |
|---|---|
| The policy exploits model errors | Raise the temperature of the dream, or train the controller in the real environment instead |
| Long imagined episodes drift too far from reality | MBPO, which uses short rollouts started from real states |
| The real environment is cheap to run | Train the controller directly, or use PPO |
Math foundations
The memory's hidden state
A recurrent layer whose weights are random and never trained. Because is scaled so its largest eigenvalue has size below 1, the influence of old inputs fades, and holds a blurred record of the recent past.
The readout features and prediction
Everything the model predicts is a linear function of this feature vector. The latent readout predicts the change in , which is small and easier to fit than itself.
Fitting a readout by ridge regression
A closed-form least-squares fit with a penalty that keeps the weights small. stacks the feature vectors of all recorded steps and the observed changes in the latent. The reward readout is fit the same way.
One dream step
The next latent is the model's prediction plus noise. is the standard deviation of the model's errors on the training data, and the temperature multiplies the variance.
Ending a dream episode
A logistic readout predicts the chance that the episode ends at this step. The dream ends when that chance passes the threshold, or at the step limit.
What the search maximizes
The controller's parameters are chosen to maximize the return predicted by the model, estimated by averaging a few dream episodes. Each generation moves the search onto the highest-scoring candidates.
Symbols
- latent, action and the memory's hidden state at step t
- fixed random input weights, recurrent weights and bias
- feature vector the readouts see
- readout weights for the latent change and for the done logit
- all feature vectors and all observed latent changes, stacked by rows
- ridge penalty
- number of recorded steps
- the model's predicted next latent, reward and done probability
- standard deviation of the model's next-latent errors
- dream temperature
- standard normal noise
- done threshold and step limit of a dream episode
- the controller's parameters
Worked by hand
The model predicts a next latent of 0.30 and its error standard deviation is . The noise draw happens to be . Compute the dreamed next latent at temperatures 0, 1 and 4.
Temperature 4 doubles the size of the noise, since the noise scales with the square root. In BalanceEnv, where the point is unstable, these small differences are multiplied by 1.1 at every later step.
Visual example
Loading the example.
Try this
- Press One more generation in the dream and compare the two bars each time: the blue one is imagined, the orange one is real.
- Lower the random real episodes to 1 and press Untrained controller, then step again: the dream says the controller is doing well while the real return collapses.
- Set the temperature to 0, then to 4, and watch how far the dreamed line strays from the real one.
Code sample
from impl import (BalanceEnv, DreamEnv, LinearController, RealWithMemory, ReservoirMemory,
collect_random_episodes, evaluate, train_in_dream)
from config import DreamConfig
cfg = DreamConfig()
env = BalanceEnv()
episodes = collect_random_episodes(env, n_episodes=60) # the only real data used for training
model = ReservoirMemory(cfg)
model.fit(episodes)
dream = DreamEnv(model, [ep["z"][0] for ep in episodes], cfg)
controller = LinearController(cfg)
train_in_dream(controller, dream, cfg) # no real steps here
print(evaluate(controller, RealWithMemory(env, model), seeds=range(500, 520))) # steps survived in reality, of 50Read the implementation (243 lines)
"""Dream environment of World Models: an environment made of the memory model M, and training C inside it.
NumPy only. The folder stands alone, so it carries a small M of its own (`ReservoirMemory`), a real toy
environment to learn from (`BalanceEnv`), a linear controller and a simple evolution strategy.
"""
from __future__ import annotations
import numpy as np
try:
from .config import DreamConfig
except ImportError: # run from the template's own folder
from config import DreamConfig
class BalanceEnv:
"""Keep an unstable point inside [-1, 1] for as long as possible.
x' = 1.1 * x + 0.2 * action + noise, action in [-1, 1]. The episode ends when |x'| > 1 or after `max_steps`.
Reward is 1 for every step survived, so the return is the number of steps the point stayed inside.
The observation is the latent z = [x], shape (1,).
"""
def __init__(self, max_steps: int = 50, noise_std: float = 0.02) -> None:
self.max_steps, self.noise_std = max_steps, noise_std
self.rng = np.random.default_rng(0)
self.x, self.t = 0.0, 0
self.total_steps = 0 # real steps taken since construction
def reset(self, seed: int) -> np.ndarray:
self.rng = np.random.default_rng(seed)
self.x, self.t = float(self.rng.uniform(-0.3, 0.3)), 0
return np.array([self.x])
def step(self, action) -> tuple[np.ndarray, float, bool]:
"""Returns (z (1,), reward, done)."""
force = float(np.clip(np.asarray(action).ravel()[0], -1.0, 1.0))
self.x = 1.1 * self.x + 0.2 * force + self.noise_std * self.rng.standard_normal()
self.t += 1
self.total_steps += 1
out = abs(self.x) > 1.0
return np.array([self.x]), 0.0 if out else 1.0, out or self.t >= self.max_steps
def collect_random_episodes(env, n_episodes: int, seed: int = 0) -> list[dict]:
"""Roll out a uniformly random policy in the real environment.
Returns one dict per episode: z (T + 1, Z) latents, actions (T, A), rewards (T,), dones (T,).
"""
rng = np.random.default_rng(seed)
episodes = []
for ep in range(n_episodes):
z, done = env.reset(seed + ep), False
zs, actions, rewards, dones = [z], [], [], []
while not done:
action = rng.uniform(-1.0, 1.0, size=1)
z, reward, done = env.step(action)
zs.append(z)
actions.append(action)
rewards.append(reward)
dones.append(float(done))
episodes.append({"z": np.array(zs), "actions": np.array(actions), "rewards": np.array(rewards), "dones": np.array(dones)})
return episodes
def _sigmoid(x: np.ndarray) -> np.ndarray:
return 0.5 * (1.0 + np.tanh(0.5 * x))
class ReservoirMemory:
"""A small M: a recurrent network with fixed random weights and trained linear readouts (an echo state network).
h_{t+1} = tanh([z_t, a_t] W_in + h_t W_rec + b). From the features [h_{t+1}, z_t, a_t, 1] it predicts a Gaussian
over z_{t+1} (mean by ridge regression, standard deviation from the residuals), the reward (ridge
regression) and the probability that the episode ends (logistic regression).
"""
def __init__(self, config: DreamConfig | None = None) -> None:
self.config = c = config or DreamConfig()
rng = np.random.default_rng(c.seed)
n_in, n = c.latent_size + c.action_size, c.hidden_size
self.w_in = c.input_scale * rng.normal(size=(n_in, n))
self.bias = c.input_scale * rng.uniform(-1.0, 1.0, size=n) # without it every unit is an odd function
w_rec = rng.normal(size=(n, n))
self.w_rec = w_rec * (c.spectral_radius / np.abs(np.linalg.eigvals(w_rec)).max())
n_feat = n + n_in + 1
self.w_next = np.zeros((n_feat, c.latent_size))
self.w_reward = np.zeros(n_feat)
self.w_done = np.zeros(n_feat)
self.next_std = np.ones(c.latent_size)
self.reward_range = (-np.inf, np.inf) # rewards seen in the data; predictions are clipped to it
def initial_state(self) -> np.ndarray:
"""Zero hidden state, shape (hidden_size,)."""
return np.zeros(self.config.hidden_size)
def advance(self, z: np.ndarray, action: np.ndarray, h: np.ndarray) -> np.ndarray:
"""Hidden state after reading (z_t, a_t). z (Z,), action (A,), h (H,) -> (H,)."""
return np.tanh(np.concatenate([z, action]) @ self.w_in + h @ self.w_rec + self.bias)
def _features(self, z, action, h_next) -> np.ndarray:
return np.concatenate([h_next, z, action, [1.0]])
def predict(self, z: np.ndarray, action: np.ndarray, h: np.ndarray):
"""One step of the model. Returns (mean of z_{t+1} (Z,), reward, done probability, h_{t+1} (H,))."""
h_next = self.advance(z, action, h)
feat = self._features(z, action, h_next)
reward = float(np.clip(feat @ self.w_reward, *self.reward_range))
return z + feat @ self.w_next, reward, float(_sigmoid(feat @ self.w_done)), h_next
def fit(self, episodes: list[dict]) -> dict:
"""Fit the readouts to real episodes (see `collect_random_episodes` for the format).
Returns the training errors: next_rmse, reward_rmse and done_accuracy.
"""
feats, d_next, rewards, dones = [], [], [], []
for ep in episodes:
h = self.initial_state()
for t in range(len(ep["actions"])):
h = self.advance(ep["z"][t], ep["actions"][t], h)
feats.append(self._features(ep["z"][t], ep["actions"][t], h))
d_next.append(ep["z"][t + 1] - ep["z"][t])
rewards.append(ep["rewards"][t])
dones.append(ep["dones"][t])
x, d_next, rewards, dones = np.array(feats), np.array(d_next), np.array(rewards), np.array(dones)
n, k = x.shape
gram = x.T @ x + self.config.ridge * n * np.eye(k)
self.w_next = np.linalg.solve(gram, x.T @ d_next)
self.w_reward = np.linalg.solve(gram, x.T @ rewards)
self.reward_range = (float(rewards.min()), float(rewards.max()))
residual = d_next - x @ self.w_next
self.next_std = residual.std(axis=0) + 1e-6
w = np.zeros(k) # logistic regression by Newton steps
for _ in range(25):
p = _sigmoid(x @ w)
grad = x.T @ (p - dones) / n + self.config.ridge * w
hess = (x * (p * (1 - p))[:, None]).T @ x / n + self.config.ridge * np.eye(k)
w -= np.linalg.solve(hess, grad)
self.w_done = w
return {
"next_rmse": float(np.sqrt((residual**2).mean())),
"reward_rmse": float(np.sqrt(((x @ self.w_reward - rewards) ** 2).mean())),
"done_accuracy": float(((_sigmoid(x @ w) > 0.5) == (dones > 0.5)).mean()),
}
class DreamEnv:
"""An environment whose every step is a sample from M. No real environment is involved."""
def __init__(self, model: ReservoirMemory, start_latents: np.ndarray, config: DreamConfig | None = None) -> None:
"""start_latents: (N, Z) real first latents; each dream episode starts from one of them."""
self.model, self.config = model, config or model.config
self.start_latents = np.asarray(start_latents, dtype=float)
self.rng = np.random.default_rng(self.config.seed)
self.z, self.h, self.t = self.start_latents[0], model.initial_state(), 0
def reset(self, seed: int) -> tuple[np.ndarray, np.ndarray]:
"""Start the dream episode fixed by `seed`. Returns the features (z (Z,), h (H,))."""
self.rng = np.random.default_rng(seed)
self.z = self.start_latents[int(self.rng.integers(len(self.start_latents)))].copy()
self.h, self.t = self.model.initial_state(), 0
return self.z, self.h
def step(self, action) -> tuple[tuple[np.ndarray, np.ndarray], float, bool]:
"""Imagine one step. Returns ((z, h), reward, done).
z_{t+1} = mean + sqrt(temperature) * std * noise. The episode ends when the predicted done probability
passes `done_threshold` or after `max_steps`.
"""
c = self.config
action = np.clip(np.atleast_1d(np.asarray(action, dtype=float)), -1.0, 1.0)
mean, reward, done_prob, self.h = self.model.predict(self.z, action, self.h)
noise = self.rng.standard_normal(mean.shape) if c.temperature > 0 else 0.0
self.z = mean + np.sqrt(c.temperature) * self.model.next_std * noise
self.t += 1
return (self.z, self.h), reward, done_prob > c.done_threshold or self.t >= c.max_steps
class RealWithMemory:
"""The real environment seen through M: it returns (z, h) like the dream does, with h tracked by the model."""
def __init__(self, env, model: ReservoirMemory) -> None:
self.env, self.model = env, model
self.z, self.h = None, model.initial_state()
def reset(self, seed: int) -> tuple[np.ndarray, np.ndarray]:
self.z, self.h = self.env.reset(seed), self.model.initial_state()
return self.z, self.h
def step(self, action) -> tuple[tuple[np.ndarray, np.ndarray], float, bool]:
action = np.clip(np.atleast_1d(np.asarray(action, dtype=float)), -1.0, 1.0)
self.h = self.model.advance(self.z, action, self.h)
self.z, reward, done = self.env.step(action)
return (self.z, self.h), reward, done
class LinearController:
"""action = tanh(W [z, h] + b), in [-1, 1]."""
def __init__(self, config: DreamConfig | None = None) -> None:
self.config = c = config or DreamConfig()
self.shape = (c.action_size, c.latent_size + c.hidden_size + 1) # the last column is the bias
self.params = np.zeros(self.shape[0] * self.shape[1])
def act(self, z: np.ndarray, h: np.ndarray) -> np.ndarray:
"""z (Z,), h (H,) -> action (A,)."""
return np.tanh(self.params.reshape(self.shape) @ np.concatenate([z, h, [1.0]]))
def evaluate(controller: LinearController, env, seeds) -> float:
"""Mean episode return of the controller over the given seeds, in a `DreamEnv` or a `RealWithMemory`."""
total = 0.0
for seed in seeds:
(z, h), done = env.reset(seed), False
while not done:
(z, h), reward, done = env.step(controller.act(z, h))
total += reward
return total / len(seeds)
def train_in_dream(controller: LinearController, dream: DreamEnv, config: DreamConfig | None = None) -> list[float]:
"""Train the controller entirely inside the dream with a simple evolution strategy.
Each generation samples `population` parameter vectors from a diagonal Gaussian, scores each by its mean
dream return over `n_rollouts` episodes, and refits the Gaussian to the `n_elites` best (the cross-entropy
method). The controller ends with the final mean. Returns the best dream return of each generation.
"""
c = config or controller.config
rng = np.random.default_rng(c.seed)
mean, std = controller.params.copy(), np.full(controller.params.shape, c.sigma_init)
history = []
for generation in range(c.n_generations):
seeds = [c.seed + 1000 * generation + k for k in range(c.n_rollouts)]
candidates = mean + std * rng.standard_normal((c.population, len(mean)))
scores = np.zeros(c.population)
for i, params in enumerate(candidates):
controller.params = params
scores[i] = evaluate(controller, dream, seeds)
elites = candidates[np.argsort(scores)[-c.n_elites :]]
mean, std = elites.mean(axis=0), elites.std(axis=0) + 0.01
history.append(float(scores.max()))
controller.params = mean
return history- Repository
- Not published yet
- Needs
- Python 3.10 and NumPy
- Tests
- 9, run with
python3 -m unittest -v
Practice
Collect episodes = collect_random_episodes(BalanceEnv(), 30) and fit model = ReservoirMemory(DreamConfig()). Build dream = DreamEnv(model, np.array([ep["z"][0] for ep in episodes])), create controller = LinearController(DreamConfig()) and call train_in_dream(controller, dream). Score the result with evaluate(controller, dream, range(100, 110)) and with evaluate(controller, RealWithMemory(BalanceEnv(), model), range(100, 110)). Repeat with temperature=0.0 and compare the gap.
Check on learning
- A controller reaches the maximum return in the dream but fails quickly in the real environment. List two different kinds of model error that could cause this.
A way to think about it
The dream return depends on three predictions: the next latent, the reward and the ending. Consider how a mistake in each could be turned into free reward.
- Why does adding noise to the dream make the controller behave better in reality, even though the real environment is less noisy than the dream?
A way to think about it
A strategy that needs the world to respond in one exact way breaks under noise. Ask which strategies survive when the response varies.
- The model is fit on random episodes, most of which in
BalanceEnvend well before the 50-step limit. The trained controller keeps the point balanced for 50 steps. Why is the model being asked something it was not trained for?A way to think about it
Compare the lengths and the states of the training episodes with those of a successful episode. Think about what the hidden state looks like after 50 steps.
- The reward prediction is clipped to the range seen in the data. What specific cheat does that prevent?
A way to think about it
A linear readout can output any number if its input is pushed far enough. Ask what a search for high predicted reward would do with that.
- If you could afford 30 more real episodes, would you use them to refit the model with data from the trained controller, or to test the controller more thoroughly? Explain.
A way to think about it
One choice improves the model exactly where the controller now goes. The other only measures a gap without closing it.