Overview
In a World Models agent the hard work is done before the controller is reached. The vision model has compressed the frame and the memory model has summarized where things are heading. The controller only has to map that short summary to an action, so it is kept as simple as possible: one linear layer. So few parameters make a different kind of training practical. Instead of following gradients, try a population of parameter settings, see which earn the most reward over whole episodes, and move the search toward them. This needs nothing but the episode return, so it works even when reward is sparse or the system cannot be differentiated.
A short history
David Ha and Jürgen Schmidhuber published World Models in 2018. Their agent had three parts, and the controller was kept deliberately tiny: a single linear layer acting on features from the vision and memory models. With so few parameters it could be trained by CMA-ES, the covariance matrix adaptation evolution strategy developed by Nikolaus Hansen and Andreas Ostermeier, which needs no gradients. The paper's point was that most of the agent's complexity can live in the learned world model.
How it works
Controller.actjoins and , applies the weights and bias, squashes the result with tanh, and scales it into the range fromaction_lowtoaction_high.get_paramsandset_paramsexpose all weights and the bias as one flat vector, which is what the search works on.CMAES.asksamples a population of candidate vectors from a Gaussian with the current mean, step size and covariance.train_controllerscores each candidate withepisode_return, averaged overn_rolloutsepisodes. All candidates of a generation face the same start states.CMAES.tellranks the candidates and moves the mean to a weighted average of the better half.- It then adapts the search shape: the step size grows if successive moves keep pointing the same way and shrinks if they cancel, and the covariance stretches along directions that have paid off.
- After
n_generationsthe controller is set to the mean of the final search distribution.
Watch out for
- This CMA-ES keeps a full covariance matrix, whose size grows with the square of the parameter count. It is not practical for policies with many thousands of parameters.
- Each generation costs population times
n_rolloutsfull episodes. When episodes are slow, the search is slow. - Episode returns are noisy. With too few rollouts per candidate, a lucky candidate is ranked above a better one and the search follows the luck.
- A linear controller can only make decisions that are linear in its features. If and do not already expose what matters, no amount of search will help.
- In the built-in
PointEnv, position stands in for and velocity for . In the full pipeline they come from the vision and memory models.
Use cases
When to use it
Use it as the last stage of a World Models agent, or whenever a small policy must be tuned from episode returns alone. CMAES is also a general black-box optimizer for up to a few hundred parameters.
In industry
- Games and simulation
- The original agent solved a car racing task from pixels with a controller of under a thousand parameters on top of learned features.
- Robotics research
- Small policies on top of pretrained perception features, optimised by evolution strategies when the reward is not differentiable.
- Research and teaching
- Showing how good features let a very simple policy succeed, and how gradient-free optimisation works.
Choosing it: what must hold
- Trained vision and memory models that already supply compact, informative features.
- A controller with few parameters, since CMA-ES scales poorly beyond a few thousand.
- Many parallel episode evaluations, because each candidate is scored by full episodes.
When to choose something else
| If | Use instead |
|---|---|
| The policy needs many parameters or nonlinear layers | A gradient-based method such as PPO or SAC on the same features |
| The features are not good enough for a linear map | Retrain the vision and memory models through the World Models training loop |
| There is no world model and states are simple vectors | PPO or SAC directly |
Math foundations
The controller
A linear map of the features, squashed by tanh into and rescaled to the action bounds. With bounds of and this is just .
Number of parameters
One weight per feature and one bias, for each action dimension. This count is small on purpose. The agent in the paper's car racing task has 3 actions, a 32-dimensional and a 256-dimensional , which gives 867.
Sampling a generation
Candidates are drawn around the current best guess . The step size sets how far they spread overall and the covariance sets in which directions.
Default population size
The standard choice when
populationis 0. It grows only with the logarithm of the number of parameters. The better half, candidates, are the parents of the next mean.Moving the mean
The new mean is a weighted average of the best candidates, with the very best counting most. is the step of the candidate ranked by fitness.
Adapting the step size
is a running sum of recent moves of the mean. If it is longer than a random walk would give, the moves agree and the steps are too small, so grows. If it is shorter, the moves cancel and shrinks.
Adapting the covariance
The covariance is nudged toward the direction the mean has been travelling (the rank-one term) and toward the spread of this generation's best steps (the rank-mu term). A small correction used when the path update is paused is left out here.
Symbols
- latent vector from the vision model and hidden vector from the memory model
- the controller's weights and bias
- bounds of every action component
- lengths of the action, latent and hidden vectors
- number of controller parameters
- mean of the search distribution
- overall step size of the search
- covariance matrix of the search
- candidate k and its step away from the mean, in units of sigma
- the step of the candidate ranked i by fitness
- population size and number of parents
- recombination weight of rank i; the weights sum to 1
- evolution paths: running sums of recent moves of the mean
- learning rates and damping, set from n by standard formulas
Worked by hand
With the default sizes , count the parameters and the population. Then compute one action with , , features and , and action bounds of and .
Three parameters, seven candidates per generation, three parents. With position 0.5 and velocity 0.2 this controller pushes back toward the origin with force , the behaviour of a damped spring.
Visual example
Loading the example.
Try this
- Press Next generation a few times and watch the mean follow the green parents.
- Press Run and see the ellipse stretch while the search travels, then shrink once it arrives.
- Start over with the step size at 0.1, then at 1, and compare how many generations it takes.
- Set the episodes per candidate to 1: the ranking gets noisy and the mean wanders.
Code sample
from impl import Controller, PointEnv, episode_return, train_controller
from config import ControllerConfig
cfg = ControllerConfig()
controller, env = Controller(cfg), PointEnv()
print(episode_return(controller, env, seed=0)) # untrained: all-zero weights, the mass is left alone
history = train_controller(controller, env, cfg) # best mean return of each generation
print(history[0], history[-1], controller.get_params()) # negative weights: push against position and velocityRead the implementation (175 lines)
"""C of World Models: a linear controller [z, h] -> action, and the CMA-ES evolution strategy that trains it.
NumPy only.
"""
from __future__ import annotations
import math
from typing import Callable
import numpy as np
try:
from .config import ControllerConfig
except ImportError: # run from the template's own folder
from config import ControllerConfig
class PointEnv:
"""Point mass to bring to rest at the origin. Position plays the role of z, velocity the role of h.
velocity += dt * force; position += dt * velocity; reward = -(position^2 + 0.1 * velocity^2) of the state
reached. Episodes last `episode_length` steps and start at a random position in [-1, 1] with zero velocity.
"""
def __init__(self, dt: float = 0.2, episode_length: int = 30) -> None:
self.dt, self.episode_length = dt, episode_length
self.pos, self.vel, self.t = 0.0, 0.0, 0
def reset(self, seed: int) -> tuple[np.ndarray, np.ndarray]:
"""Start the episode fixed by `seed`. Returns the features (z (1,), h (1,))."""
self.pos, self.vel, self.t = float(np.random.default_rng(seed).uniform(-1.0, 1.0)), 0.0, 0
return np.array([self.pos]), np.array([self.vel])
def step(self, action) -> tuple[np.ndarray, np.ndarray, float, bool]:
"""Returns (z (1,), h (1,), reward, done)."""
self.vel += self.dt * float(np.clip(np.asarray(action).ravel()[0], -1.0, 1.0))
self.pos += self.dt * self.vel
self.t += 1
reward = -(self.pos**2 + 0.1 * self.vel**2)
return np.array([self.pos]), np.array([self.vel]), reward, self.t >= self.episode_length
class Controller:
"""action = low + (tanh(W [z, h] + b) + 1) / 2 * (high - low)."""
def __init__(self, config: ControllerConfig | None = None) -> None:
self.config = c = config or ControllerConfig()
self.n_features = c.latent_size + c.hidden_size
self.weights = np.zeros((c.action_size, self.n_features))
self.bias = np.zeros(c.action_size)
@property
def n_params(self) -> int:
return self.weights.size + self.bias.size
def get_params(self) -> np.ndarray:
"""All parameters as one flat vector: the weights row by row, then the bias."""
return np.concatenate([self.weights.ravel(), self.bias])
def set_params(self, flat: np.ndarray) -> None:
flat = np.asarray(flat, dtype=float)
if flat.shape != (self.n_params,):
raise ValueError(f"expected {self.n_params} parameters, got shape {flat.shape}")
self.weights = flat[: self.weights.size].reshape(self.weights.shape).copy()
self.bias = flat[self.weights.size :].copy()
def act(self, z: np.ndarray, h: np.ndarray | None = None) -> np.ndarray:
"""z (latent_size,) or (B, latent_size), h likewise with hidden_size -> action (action_size,) or (B, action_size)."""
features = np.asarray(z, dtype=float) if h is None else np.concatenate([z, h], axis=-1)
c = self.config
squashed = np.tanh(features @ self.weights.T + self.bias)
return c.action_low + 0.5 * (squashed + 1.0) * (c.action_high - c.action_low)
class CMAES:
"""Covariance matrix adaptation evolution strategy (maximizes fitness)."""
def __init__(self, n_params: int, sigma: float = 0.5, population: int = 0, seed: int = 0,
mean: np.ndarray | None = None) -> None:
n = self.n = n_params
self.rng = np.random.default_rng(seed)
self.mean = np.zeros(n) if mean is None else np.array(mean, dtype=float)
self.sigma = sigma
self.population = population or 4 + int(3 * math.log(n))
self.n_parents = self.population // 2
w = math.log(self.n_parents + 0.5) - np.log(np.arange(1, self.n_parents + 1))
self.recombination = w / w.sum()
self.mu_eff = 1.0 / float((self.recombination**2).sum())
me = self.mu_eff
self.c_c = (4 + me / n) / (n + 4 + 2 * me / n)
self.c_sigma = (me + 2) / (n + me + 5)
self.c_1 = 2 / ((n + 1.3) ** 2 + me)
self.c_mu = min(1 - self.c_1, 2 * (me - 2 + 1 / me) / ((n + 2) ** 2 + me))
self.damping = 1 + 2 * max(0.0, math.sqrt((me - 1) / (n + 1)) - 1) + self.c_sigma
self.chi_n = math.sqrt(n) * (1 - 1 / (4 * n) + 1 / (21 * n * n)) # expected length of an N(0, I) vector
self.path_c, self.path_sigma = np.zeros(n), np.zeros(n)
self.cov = np.eye(n)
self._basis, self._scales = np.eye(n), np.ones(n) # eigenvectors and square roots of eigenvalues of cov
self.generation = 0
self.best_params, self.best_fitness = self.mean.copy(), -math.inf
def ask(self) -> np.ndarray:
"""Sample `population` candidates from N(mean, sigma^2 * cov). Returns shape (population, n_params)."""
noise = self.rng.standard_normal((self.population, self.n))
return self.mean + self.sigma * (noise * self._scales) @ self._basis.T
def tell(self, candidates: np.ndarray, fitness: np.ndarray) -> None:
"""Update the search distribution from the candidates of `ask` and their fitness (higher is better)."""
fitness = np.asarray(fitness, dtype=float)
order = np.argsort(-fitness)
if fitness[order[0]] > self.best_fitness:
self.best_fitness, self.best_params = float(fitness[order[0]]), candidates[order[0]].copy()
self.generation += 1
n, me = self.n, self.mu_eff
steps = (candidates[order[: self.n_parents]] - self.mean) / self.sigma # (parents, n)
mean_step = self.recombination @ steps
self.mean = self.mean + self.sigma * mean_step
inv_sqrt_cov = (self._basis / self._scales) @ self._basis.T
self.path_sigma = (1 - self.c_sigma) * self.path_sigma + math.sqrt(self.c_sigma * (2 - self.c_sigma) * me) * (inv_sqrt_cov @ mean_step)
norm = float(np.linalg.norm(self.path_sigma))
stalled = norm / math.sqrt(1 - (1 - self.c_sigma) ** (2 * self.generation)) / self.chi_n < 1.4 + 2 / (n + 1)
h_sigma = 1.0 if stalled else 0.0
self.path_c = (1 - self.c_c) * self.path_c + h_sigma * math.sqrt(self.c_c * (2 - self.c_c) * me) * mean_step
rank_one = np.outer(self.path_c, self.path_c) + (1 - h_sigma) * self.c_c * (2 - self.c_c) * self.cov
rank_mu = (steps * self.recombination[:, None]).T @ steps
self.cov = (1 - self.c_1 - self.c_mu) * self.cov + self.c_1 * rank_one + self.c_mu * rank_mu
self.sigma *= math.exp((self.c_sigma / self.damping) * (norm / self.chi_n - 1))
self.cov = 0.5 * (self.cov + self.cov.T)
eigenvalues, self._basis = np.linalg.eigh(self.cov)
self._scales = np.sqrt(np.maximum(eigenvalues, 1e-20))
def optimize(self, fitness_fn: Callable[[np.ndarray], float], n_generations: int) -> list[float]:
"""Run ask / tell for `n_generations`. Returns the best fitness of each generation."""
history = []
for _ in range(n_generations):
candidates = self.ask()
fitness = np.array([fitness_fn(x) for x in candidates])
self.tell(candidates, fitness)
history.append(float(fitness.max()))
return history
def episode_return(controller: Controller, env, seed: int) -> float:
"""Total reward of one episode of `env` (started with `seed`) under the controller."""
z, h = env.reset(seed)
total, done = 0.0, False
while not done:
z, h, reward, done = env.step(controller.act(z, h))
total += reward
return total
def train_controller(controller: Controller, env, config: ControllerConfig | None = None) -> list[float]:
"""Evolve the controller's parameters with CMA-ES to maximize the mean episode return.
Every candidate of a generation is scored on the same `n_rollouts` start states, and the start states change
from generation to generation. The controller ends up with the mean of the final search distribution.
Returns the best mean return of each generation.
"""
c = config or controller.config
search = CMAES(controller.n_params, c.sigma_init, c.population, c.seed, mean=controller.get_params())
history = []
for generation in range(c.n_generations):
seeds = [c.seed + 1000 * generation + k for k in range(c.n_rollouts)]
def fitness(params: np.ndarray) -> float:
controller.set_params(params)
return float(np.mean([episode_return(controller, env, s) for s in seeds]))
candidates = search.ask()
scores = np.array([fitness(x) for x in candidates])
search.tell(candidates, scores)
history.append(float(scores.max()))
controller.set_params(search.mean)
return history- Repository
- Not published yet
- Needs
- Python 3.10 and NumPy
- Tests
- 9, run with
python3 -m unittest -v
Practice
Create controller = Controller(ControllerConfig()) and env = PointEnv(). Compute the mean of episode_return(controller, env, s) over seeds 0 to 9, call train_controller(controller, env), and compute it again. Plot the returned history. Print controller.get_params() and interpret the signs of the two weights. Then repeat with n_rollouts=1 and compare how smooth the history is.
Check on learning
- The trained controller for the point mass has negative weights on both position and velocity. Why does a good controller need the velocity term at all?
A way to think about it
Imagine a controller that pushes toward the origin in proportion to position only. Follow the mass as it arrives at the origin with speed.
- Every candidate in a generation is scored on the same start states, and the start states change between generations. What would go wrong with different starts per candidate, and what with the same starts forever?
A way to think about it
For the first, ask whether a ranking reflects the candidate or its luck. For the second, ask what a policy tuned to four particular starts has learned.
- Gradient methods train networks with millions of weights, while this search is limited to a few hundred parameters. Why does the cost of an evolution strategy grow with dimension in a way that backpropagation's does not?
A way to think about it
Each candidate gives one number, its fitness. Compare how many numbers about the search direction you get per episode from that with what a gradient provides.
- If successive moves of the mean keep pointing the same way, CMA-ES raises the step size. If they zigzag, it lowers it. Why is each response sensible?
A way to think about it
Many small steps in one direction could have been one large step. Steps that undo each other suggest the search is jumping across the place it should settle.
- The World Models design deliberately puts almost all parameters in V and M and almost none in C. What does this division make possible, and what does it assume?
A way to think about it
V and M can be trained with gradients on prediction errors, without any reward. Ask what must be true of their features for a linear map to be enough.