Overview
The vision model describes the present. The memory model predicts what comes next. It reads the current latent code and the action, updates a running summary of everything seen so far, and outputs a prediction for the next code. The future is often uncertain in a lumpy way: a car at a fork goes left or right, never down the middle. A single bell curve would predict the middle. So the model outputs a mixture of several bell curves and can put weight on each distinct outcome. Its running summary, the hidden state, is also useful by itself: it tells the controller where things are heading. This template uses a 32-unit LSTM where the paper uses 256 or more.
A short history
The memory model joins two older ideas. Christopher Bishop introduced mixture density networks in 1994 so that a network could output a full distribution with several peaks. Sepp Hochreiter and Jürgen Schmidhuber introduced the LSTM in 1997. Alex Graves combined them for handwriting generation in 2013. In 2018 David Ha and Schmidhuber used the same design in World Models to predict the next latent vector from the current one and the action, giving the agent a compact model of how its world changes.
How it works
- At each step the LSTM cell in
MDNRNNreceives the latent joined with the action , plus its previous hidden and cell states. - Three gates decide what to forget from the cell state, what new content to write, and what to expose. The exposed part is the new hidden state .
- A linear head turns into mixture weights, means and log standard deviations for every dimension of the next latent, and a second head gives a logit for the episode ending.
loss_and_gradsscores the observed next latent under the mixture (negative log-likelihood) and the done flag with binary cross-entropy.- Gradients are passed backward through the whole sequence, step by step, and
train_stepclips them before an Adam update. - After training,
stepadvances the state one step at a time, andsample_nextdraws the next latent from the mixture with a temperature. A dream environment calls it in a loop.
Watch out for
- Each dimension of the latent gets its own independent mixture. The model cannot express that two dimensions change together, so sampled latents can combine outcomes that never occur jointly.
- A component can shrink its standard deviation onto a single data point and drive the likelihood up without limit. The floor
min_log_sigmaprevents that collapse. - Prediction errors compound when the model is run on its own samples for many steps. Training only ever shows it real latents as input.
- Episode endings are rare, so the done head can score well by always predicting that the episode continues. Check it on the steps where episodes do end.
- Gradients through long sequences can grow very large. Without
grad_clip, one bad batch can undo the training.
Use cases
When to use it
Use it as the predictive model of a World Models agent, or for any sequence where the next value is uncertain and may have several distinct outcomes that a single Gaussian would average together.
In industry
- Games and simulation
- Predicting how a compressed game frame will change after an action, so a controller can anticipate what comes next.
- Sequence generation
- The same mixture density recurrent design generates handwriting strokes and sketches, where the next pen movement has several likely values.
- Forecasting research
- Modelling time series whose next value is uncertain with more than one plausible outcome, where a single predicted mean would mislead.
Choosing it: what must hold
- A trained vision model, since the memory model works on its latent vectors, not on raw frames.
- Recorded sequences of latent vectors, actions and episode endings to train on.
- A future that is uncertain with several possible outcomes, which is what the mixture output is for.
When to choose something else
| If | Use instead |
|---|---|
| The dynamics are low-dimensional state vectors with no need for memory | The probabilistic ensemble models in PETS or MBPO |
| You only need features, not predictions of the future | The World Models vision lesson on its own |
| The model is only needed for planning toward reward | MuZero, which predicts reward, value and policy and never the observation |
Math foundations
The LSTM cell
The cell state is a memory that is partly kept and partly rewritten at each step. The gates , , are sigmoids of a linear map of and so lie between 0 and 1. The candidate content is a tanh of another such map.
The mixture density output
For each dimension of the next latent the model outputs weights that sum to 1, means and standard deviations. All of them are computed from , so the prediction depends on the whole history.
The training loss
The first part is small when the observed next latent lies where the mixture puts its mass. The second is the binary cross-entropy of the predicted ending against the real done flag.
Responsibilities
Given an observed value, this is the share of the explanation that belongs to component . It decides how the gradient is split among the components.
Gradients for one observed value
Here is the negative log-likelihood of one value and is the logit behind . The component that explains the point best moves its mean toward it and gains weight. The others are barely touched.
Sampling with a temperature
The temperature flattens or sharpens the choice of component and scales the variance. Above 1 the imagined futures are more varied, and below 1 they are more predictable.
Symbols
- latent vector and action at step t
- hidden state and cell state of the LSTM
- forget, input and output gates, and the candidate content
- number of Gaussians in each mixture (n_mixtures)
- weight, mean and standard deviation of component k
- the logit behind the weight of component k
- responsibility of component k for an observed value
- sequences in a batch and steps in a sequence
- weight of the done loss (done_weight)
- negative log-likelihood of one observed value
- sampling temperature
- a standard normal draw
Worked by hand
A mixture has two components with weights 0.5 each, means and , and standard deviation 0.5. The observed value is . Compare its loss with a single Gaussian of the same overall mean 0 and variance .
The mixture gives the observed value a loss of 0.919 against 1.431 for the single Gaussian, because it puts its mass where the data is. Component 2 takes almost all the responsibility, so almost all of the gradient goes to it.
Visual example
Loading the example.
Try this
- Set K to 1: the single Gaussian sits between the two groups, where nothing was ever observed.
- Set K to 2, press Untrained, then Train, and watch each component claim one group.
- Slide the observed z from −1 to 1 and watch the responsibility pass from one component to the other.
- Lower the temperature to 0.3, then raise it to 2, and compare the dashed sampling curve with the data.
Code sample
import numpy as np
from impl import MDNRNN, toy_sequences
from config import MemoryConfig
rng = np.random.default_rng(0)
z, actions, z_next, done = toy_sequences(64, 12, rng) # (64, 12, 2), (64, 12, 1), (64, 12, 2), (64, 12)
model = MDNRNN(MemoryConfig())
losses = model.fit(z, actions, z_next, done, n_steps=300)
print(losses[0], losses[-1])
state = model.initial_state(1) # dream one step from the first latent
z1, done_prob, state = model.sample_next(z[:1, 0], actions[:1, 0], state, rng, temperature=1.0)Read the implementation (214 lines)
"""M of World Models: an LSTM with a mixture density output, P(z_{t+1} | a_t, z_t, h_t), plus a done prediction.
NumPy only, backpropagation through time written by hand.
"""
from __future__ import annotations
import math
import numpy as np
try:
from .config import MemoryConfig
except ImportError: # run from the template's own folder
from config import MemoryConfig
_LOG_SQRT_2PI = 0.5 * math.log(2.0 * math.pi)
def toy_sequences(n: int, length: int, rng: np.random.Generator, noise: float = 0.02):
"""Latent trajectories with a known rule: a 2-D point turning around the origin.
z_{t+1} = rotate(z_t, 0.4 * a_t) + noise, with a_t uniform in [-1, 1]. done_t = 1 when z_{t+1}[0] > 0.7.
Returns (z (n, length, 2), actions (n, length, 1), z_next (n, length, 2), done (n, length)).
"""
z = np.zeros((n, length + 1, 2))
angle0 = rng.uniform(0.0, 2.0 * math.pi, size=n)
z[:, 0] = np.stack([np.cos(angle0), np.sin(angle0)], axis=1) * rng.uniform(0.5, 1.0, size=(n, 1))
actions = rng.uniform(-1.0, 1.0, size=(n, length, 1))
for t in range(length):
angle = 0.4 * actions[:, t, 0]
cos, sin = np.cos(angle), np.sin(angle)
x, y = z[:, t, 0], z[:, t, 1]
z[:, t + 1] = np.stack([cos * x - sin * y, sin * x + cos * y], axis=1) + noise * rng.standard_normal((n, 2))
return z[:, :-1], actions, z[:, 1:], (z[:, 1:, 0] > 0.7).astype(float)
def _sigmoid(x: np.ndarray) -> np.ndarray:
return 0.5 * (1.0 + np.tanh(0.5 * x))
class MDNRNN:
"""LSTM over (z, a) sequences with a mixture-of-Gaussians head for the next z and a done logit."""
def __init__(self, config: MemoryConfig | None = None) -> None:
self.config = c = config or MemoryConfig()
self.rng = np.random.default_rng(c.seed)
n_in, h = c.latent_size + c.action_size, c.hidden_size
n_out = 3 * c.latent_size * c.n_mixtures
bias = np.zeros(4 * h)
bias[h : 2 * h] = 1.0 # forget gate starts open
self.params = {
"lstm_w": self.rng.normal(0.0, 1.0 / math.sqrt(n_in + h), size=(n_in + h, 4 * h)), "lstm_b": bias,
"mdn_w": self.rng.normal(0.0, 1.0 / math.sqrt(h), size=(h, n_out)), "mdn_b": np.zeros(n_out),
"done_w": self.rng.normal(0.0, 1.0 / math.sqrt(h), size=(h, 1)), "done_b": np.zeros(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 initial_state(self, batch: int) -> tuple[np.ndarray, np.ndarray]:
"""Zero LSTM state (h, c), each of shape (batch, hidden_size)."""
h = self.config.hidden_size
return np.zeros((batch, h)), np.zeros((batch, h))
def _cell(self, x: np.ndarray, state):
"""One LSTM step. x (B, latent + action). Returns ((h, c), cache)."""
h_prev, c_prev = state
n = self.config.hidden_size
xh = np.concatenate([x, h_prev], axis=1)
gates = xh @ self.params["lstm_w"] + self.params["lstm_b"]
i, f, o = _sigmoid(gates[:, :n]), _sigmoid(gates[:, n : 2 * n]), _sigmoid(gates[:, 2 * n : 3 * n])
g = np.tanh(gates[:, 3 * n :])
c = f * c_prev + i * g
tanh_c = np.tanh(c)
return (o * tanh_c, c), (xh, i, f, o, g, c_prev, tanh_c)
def _head(self, h: np.ndarray):
"""Mixture parameters and done logit from hidden states h (..., H).
Returns (logit_pi, mu, log_sigma, done_logit, raw_log_sigma); the first three have shape (..., Z, K).
"""
c = self.config
out = h @ self.params["mdn_w"] + self.params["mdn_b"]
out = out.reshape(*h.shape[:-1], 3, c.latent_size, c.n_mixtures)
raw = out[..., 2, :, :]
done_logit = (h @ self.params["done_w"] + self.params["done_b"])[..., 0]
return out[..., 0, :, :], out[..., 1, :, :], np.maximum(raw, c.min_log_sigma), done_logit, raw
def forward(self, z_seq: np.ndarray, a_seq: np.ndarray, state=None) -> dict:
"""Run the LSTM over whole sequences.
z_seq (B, T, Z), a_seq (B, T, A). Returns a dict: logit_pi, mu, log_sigma (B, T, Z, K), done_logit (B, T),
h (B, T, H), the final `state`, and the `caches` needed by backpropagation.
"""
b, t_len, _ = z_seq.shape
state = state or self.initial_state(b)
hs, caches = [], []
for t in range(t_len):
state, cache = self._cell(np.concatenate([z_seq[:, t], a_seq[:, t]], axis=1), state)
hs.append(state[0])
caches.append(cache)
h = np.stack(hs, axis=1)
logit_pi, mu, log_sigma, done_logit, raw = self._head(h)
return {"logit_pi": logit_pi, "mu": mu, "log_sigma": log_sigma, "done_logit": done_logit, "h": h,
"state": state, "caches": caches, "raw_log_sigma": raw}
def loss_and_grads(self, z_seq, a_seq, z_next, done) -> tuple[float, dict, dict]:
"""Sequence loss and its gradients by backpropagation through time.
z_seq (B, T, Z), a_seq (B, T, A), z_next (B, T, Z), done (B, T) in {0, 1}.
loss = mean_{b,t} [ -sum_d log sum_k pi_k N(z_next_d; mu_k, sigma_k) + done_weight * BCE(done) ].
Returns (loss, gradients keyed like params, parts with the mean `nll` and `done_bce`).
"""
c = self.config
out = self.forward(z_seq, a_seq)
b, t_len = done.shape
n = b * t_len
logit_pi, mu, log_sigma = out["logit_pi"], out["mu"], out["log_sigma"]
log_pi = logit_pi - logit_pi.max(axis=-1, keepdims=True)
log_pi = log_pi - np.log(np.exp(log_pi).sum(axis=-1, keepdims=True))
u = (z_next[..., None] - mu) / np.exp(log_sigma)
joint = log_pi - 0.5 * u**2 - log_sigma - _LOG_SQRT_2PI # log pi_k N_k, shape (B, T, Z, K)
top = joint.max(axis=-1, keepdims=True)
log_lik = top[..., 0] + np.log(np.exp(joint - top).sum(axis=-1))
nll = float(-log_lik.sum() / n)
logit = out["done_logit"]
bce = float((np.logaddexp(0.0, logit) - done * logit).sum() / n)
resp = np.exp(joint - top)
resp = resp / resp.sum(axis=-1, keepdims=True) # responsibility of each component
d_out = np.zeros((b, t_len, 3, c.latent_size, c.n_mixtures))
d_out[:, :, 0] = (np.exp(log_pi) - resp) / n
d_out[:, :, 1] = -resp * u / np.exp(log_sigma) / n
d_out[:, :, 2] = resp * (1.0 - u**2) / n * (out["raw_log_sigma"] > c.min_log_sigma)
d_out = d_out.reshape(b, t_len, -1)
d_done = (c.done_weight * (_sigmoid(logit) - done) / n)[..., None]
p, hid = self.params, c.hidden_size
grads = {k: np.zeros_like(v) for k, v in p.items()}
h_all = out["h"].reshape(n, hid)
grads["mdn_w"] = h_all.T @ d_out.reshape(n, -1)
grads["mdn_b"] = d_out.sum(axis=(0, 1))
grads["done_w"] = h_all.T @ d_done.reshape(n, 1)
grads["done_b"] = d_done.sum(axis=(0, 1))
d_h_seq = d_out @ p["mdn_w"].T + d_done @ p["done_w"].T
d_h_next, d_c_next = np.zeros((b, hid)), np.zeros((b, hid))
for t in reversed(range(t_len)):
xh, i, f, o, g, c_prev, tanh_c = out["caches"][t]
d_h = d_h_seq[:, t] + d_h_next
d_c = d_c_next + d_h * o * (1.0 - tanh_c**2)
d_gates = np.concatenate([d_c * g * i * (1 - i), d_c * c_prev * f * (1 - f),
d_h * tanh_c * o * (1 - o), d_c * i * (1 - g**2)], axis=1)
grads["lstm_w"] += xh.T @ d_gates
grads["lstm_b"] += d_gates.sum(axis=0)
d_h_next = (d_gates @ p["lstm_w"].T)[:, -hid:]
d_c_next = d_c * f
return nll + c.done_weight * bce, grads, {"nll": nll, "done_bce": bce}
def train_step(self, z_seq, a_seq, z_next, done) -> float:
"""One Adam step (with gradient clipping) on a batch of sequences. Returns the loss before the step."""
loss, grads, _ = self.loss_and_grads(z_seq, a_seq, z_next, done)
self._t += 1
clip = self.config.grad_clip
for name, p in self.params.items():
m, v, g = self._m[name], self._v[name], np.clip(grads[name], -clip, clip)
m *= 0.9
m += 0.1 * g
v *= 0.999
v += 0.001 * g * g
p -= self.config.learning_rate * (m / (1 - 0.9**self._t)) / (np.sqrt(v / (1 - 0.999**self._t)) + 1e-8)
return loss
def fit(self, z_seq, a_seq, z_next, done, n_steps: int) -> list[float]:
"""Train on random minibatches of the given sequences. Returns the loss of each step."""
batch = min(self.config.batch_size, len(z_seq))
losses = []
for _ in range(n_steps):
idx = self.rng.integers(0, len(z_seq), size=batch)
losses.append(self.train_step(z_seq[idx], a_seq[idx], z_next[idx], done[idx]))
return losses
def step(self, z: np.ndarray, action: np.ndarray, state) -> dict:
"""Advance one step. z (B, Z), action (B, A), state from `initial_state` or a previous step.
Returns a dict: logit_pi, mu, log_sigma (B, Z, K), done_prob (B,), and the new `state` (h, c).
"""
state, _ = self._cell(np.concatenate([z, action], axis=1), state)
logit_pi, mu, log_sigma, done_logit, _ = self._head(state[0])
return {"logit_pi": logit_pi, "mu": mu, "log_sigma": log_sigma, "done_prob": _sigmoid(done_logit), "state": state}
def sample_next(self, z, action, state, rng: np.random.Generator, temperature: float | None = None):
"""Draw z_{t+1} from the predicted mixture.
The temperature divides the mixture logits and multiplies the variances, as in the paper.
Returns (z_next (B, Z), done_prob (B,), new state).
"""
tau = self.config.temperature if temperature is None else temperature
out = self.step(z, action, state)
logits = out["logit_pi"] / tau
probs = np.exp(logits - logits.max(axis=-1, keepdims=True))
probs = probs / probs.sum(axis=-1, keepdims=True)
pick = (probs.cumsum(axis=-1) < rng.random((*probs.shape[:-1], 1))).sum(axis=-1)
pick = np.minimum(pick, self.config.n_mixtures - 1)[..., None]
mu = np.take_along_axis(out["mu"], pick, axis=-1)[..., 0]
sigma = np.exp(np.take_along_axis(out["log_sigma"], pick, axis=-1)[..., 0])
return mu + sigma * math.sqrt(tau) * rng.standard_normal(mu.shape), out["done_prob"], out["state"]
def mean_next(self, z, action, state) -> tuple[np.ndarray, np.ndarray, tuple]:
"""Mixture mean sum_k pi_k mu_k of the next z. Returns (mean (B, Z), done_prob (B,), new state)."""
out = self.step(z, action, state)
logits = out["logit_pi"]
probs = np.exp(logits - logits.max(axis=-1, keepdims=True))
probs = probs / probs.sum(axis=-1, keepdims=True)
return (probs * out["mu"]).sum(axis=-1), out["done_prob"], out["state"]- Repository
- Not published yet
- Needs
- Python 3.10 and NumPy
- Tests
- 9, run with
python3 -m unittest -v
Practice
Generate data with z, a, z_next, done = toy_sequences(200, 20, np.random.default_rng(0)), create model = MDNRNN(MemoryConfig()) and call model.fit(z, a, z_next, done, n_steps=300), checking that the losses fall. Then start from model.initial_state(1) and roll the model forward 20 steps twice, once feeding mean_next back in and once sample_next at temperature 1.5, and compare both paths with a true toy trajectory under the same actions.
Check on learning
- A point at a fork goes left or right with equal chance. What would a model with one Gaussian predict as the most likely next position, and why is that the worst possible answer for planning?
A way to think about it
Find the single mean that minimizes the error against both outcomes, then ask whether the point is ever actually there.
- The responsibilities send almost all of the gradient to the component nearest the data. How do the other components ever become useful?
A way to think about it
Consider a different data point that the leading component explains poorly, and which component has the largest responsibility for that one.
- Why can the likelihood of a mixture grow without limit if the standard deviations are not floored, while a single Gaussian fit to many points does not have this problem?
A way to think about it
Put one component's mean exactly on one data point and let its standard deviation shrink. Check what the other component must do to keep the remaining points likely.
- During training the LSTM always receives the real latent as input. In a dream it receives its own samples. What kind of error can appear in the dream that never appeared in training?
A way to think about it
After one imperfect sample the input is slightly off the data. Follow what the model predicts from an input unlike anything it was trained on.
- The controller reads as well as . What can tell it that the current latent cannot?
A way to think about it
A single frame of a moving object shows position. Ask what you would need in order to know its speed and direction.