Sign in

Controller

World Models controller (C model)

The C model of World Models: one linear layer from the features [z, h] to the action, trained without gradients by the CMA-ES evolution strategy.

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

  1. Controller.act joins zz and hh, applies the weights and bias, squashes the result with tanh, and scales it into the range from action_low to action_high.
  2. get_params and set_params expose all weights and the bias as one flat vector, which is what the search works on.
  3. CMAES.ask samples a population of candidate vectors from a Gaussian with the current mean, step size and covariance.
  4. train_controller scores each candidate with episode_return, averaged over n_rollouts episodes. All candidates of a generation face the same start states.
  5. CMAES.tell ranks the candidates and moves the mean to a weighted average of the better half.
  6. 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.
  7. After n_generations the 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_rollouts full 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 zz and hh do not already expose what matters, no amount of search will help.
  • In the built-in PointEnv, position stands in for zz and velocity for hh. 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

IfUse instead
The policy needs many parameters or nonlinear layersA gradient-based method such as PPO or SAC on the same features
The features are not good enough for a linear mapRetrain the vision and memory models through the World Models training loop
There is no world model and states are simple vectorsPPO or SAC directly

Math foundations

  1. The controller

    a=alow+12(tanh⁡(W[z,h]+b)+1) (ahigh−alow)a = a_{\text{low}} + \tfrac{1}{2}\big(\tanh(W [z, h] + b) + 1\big)\,\big(a_{\text{high}} - a_{\text{low}}\big)

    A linear map of the features, squashed by tanh into (−1,1)(-1, 1) and rescaled to the action bounds. With bounds of −1-1 and 11 this is just tanh⁡(W[z,h]+b)\tanh(W[z, h] + b).

  2. Number of parameters

    n=A (Z+H+1)n = A \, (Z + H + 1)

    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 zz and a 256-dimensional hh, which gives 867.

  3. Sampling a generation

    xk=m+σ yk,yk∼N(0,C),k=1,…,λx_k = m + \sigma \, y_k, \qquad y_k \sim \mathcal{N}(0, C), \qquad k = 1, \dots, \lambda

    Candidates are drawn around the current best guess mm. The step size σ\sigma sets how far they spread overall and the covariance CC sets in which directions.

  4. Default population size

    λ=4+⌊3ln⁡n⌋,μ=⌊λ/2⌋\lambda = 4 + \lfloor 3 \ln n \rfloor, \qquad \mu = \lfloor \lambda / 2 \rfloor

    The standard choice when population is 0. It grows only with the logarithm of the number of parameters. The better half, μ\mu candidates, are the parents of the next mean.

  5. Moving the mean

    m←m+σ∑i=1μwi yi:λ,wi∝ln⁡ ⁣(μ+12)−ln⁡im \leftarrow m + \sigma \sum_{i=1}^{\mu} w_i \, y_{i:\lambda}, \qquad w_i \propto \ln\!\big(\mu + \tfrac{1}{2}\big) - \ln i

    The new mean is a weighted average of the best candidates, with the very best counting most. yi:λy_{i:\lambda} is the step of the candidate ranked ii by fitness.

  6. Adapting the step size

    σ←σ exp⁡ ⁣(cσdσ(∥pσ∥E∥N(0,I)∥−1))\sigma \leftarrow \sigma \, \exp\!\left( \frac{c_\sigma}{d_\sigma} \left( \frac{\lVert p_\sigma \rVert}{\mathbb{E}\lVert \mathcal{N}(0, I) \rVert} - 1 \right) \right)

    pσp_\sigma 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 σ\sigma grows. If it is shorter, the moves cancel and σ\sigma shrinks.

  7. Adapting the covariance

    C←(1−c1−cμ) C+c1 pc pc⊤+cμ∑i=1μwi yi:λ yi:λ⊤C \leftarrow (1 - c_1 - c_\mu) \, C + c_1 \, p_c \, p_c^{\top} + c_\mu \sum_{i=1}^{\mu} w_i \, y_{i:\lambda} \, y_{i:\lambda}^{\top}

    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

z,  hz,\; h
latent vector from the vision model and hidden vector from the memory model
W,  bW,\; b
the controller's weights and bias
alow,  ahigha_{\text{low}},\; a_{\text{high}}
bounds of every action component
A,  Z,  HA,\; Z,\; H
lengths of the action, latent and hidden vectors
nn
number of controller parameters
mm
mean of the search distribution
σ\sigma
overall step size of the search
CC
covariance matrix of the search
xk,  ykx_k,\; y_k
candidate k and its step away from the mean, in units of sigma
yi:λy_{i:\lambda}
the step of the candidate ranked i by fitness
λ,  μ\lambda,\; \mu
population size and number of parents
wiw_i
recombination weight of rank i; the weights sum to 1
pσ,  pcp_\sigma,\; p_c
evolution paths: running sums of recent moves of the mean
cσ,  dσ,  c1,  cμc_\sigma,\; d_\sigma,\; c_1,\; c_\mu
learning rates and damping, set from n by standard formulas

Worked by hand

With the default sizes A=Z=H=1A = Z = H = 1, count the parameters and the population. Then compute one action with W=(−1,−0.5)W = (-1, -0.5), b=0b = 0, features z=0.5z = 0.5 and h=0.2h = 0.2, and action bounds of −1-1 and 11.

n=1×(1+1+1)=3n = 1 \times (1 + 1 + 1) = 3
λ=4+⌊3ln⁡3⌋=4+⌊3.296⌋=7,μ=⌊7/2⌋=3\lambda = 4 + \lfloor 3 \ln 3 \rfloor = 4 + \lfloor 3.296 \rfloor = 7, \qquad \mu = \lfloor 7 / 2 \rfloor = 3
W[z,h]+b=−1×0.5−0.5×0.2+0=−0.6W[z, h] + b = -1 \times 0.5 - 0.5 \times 0.2 + 0 = -0.6
a=−1+12(tanh⁡(−0.6)+1)×2=tanh⁡(−0.6)=−0.537a = -1 + \tfrac{1}{2}\big(\tanh(-0.6) + 1\big) \times 2 = \tanh(-0.6) = -0.537

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 −0.537-0.537, 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 velocity
Read 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

  1. 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.

  2. 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.

  3. 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.

  4. 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.

  5. 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.