Overview
Suppose you can evaluate a function but cannot differentiate it. CMA-ES keeps a cloud of likely solutions, described by a centre, an overall size and a shape. Each generation it draws candidates from the cloud, ranks them by how good they are, and moves the centre toward the best ones. It also learns from the steps that worked. If good steps keep pointing along a diagonal valley, the cloud stretches along that valley. If consecutive steps keep pointing the same way, the cloud grows, and if they cancel out, it shrinks. Only the ranking of the candidates is used, never the raw function values.
A short history
Evolution strategies began in Germany in the 1960s with Ingo Rechenberg and Hans-Paul Schwefel. Nikolaus Hansen and Andreas Ostermeier introduced covariance matrix adaptation in 1996 and gave the standard form in a 2001 paper. It learns the shape of the search distribution from successful steps, so it copes with ill-conditioned and rotated problems. It became a reference method for black-box optimisation in continuous spaces.
How it works
- Start with a centre x0, a step size sigma0 and a round cloud (the covariance matrix is the identity).
- ask draws population_size candidates from a normal distribution with that centre, size and shape.
- Evaluate every candidate and pass the results to tell. Lower is better.
- tell sorts the candidates and keeps the better half. The new centre is their weighted average, with larger weights for better ranks.
- Two running sums of recent centre moves, called evolution paths, are updated. One is used for the step size and one for the shape.
- The covariance matrix is nudged toward the directions of the winning steps and of the shape path, so the cloud stretches where progress is made.
- The step size grows if the step-size path is longer than random steps would give, and shrinks if it is shorter.
- Repeat. minimize runs this loop until the candidates of a generation are nearly equal in value or the step size is tiny.
Watch out for
- The covariance matrix has entries and is eigendecomposed every generation at a cost of order . Beyond a few hundred dimensions this becomes too slow.
- A step size sigma0 that is far too small makes the search crawl or stall in a nearby local optimum. Choose it so the optimum is likely within about three step sizes of x0.
- The method assumes the variables have comparable scales at the start. If one parameter ranges over 0.001 and another over 1000, rescale them first.
- It needs many function evaluations. When a gradient is available and the surface is smooth, a gradient method is far cheaper.
- On a function with many local optima, the default small population can converge to a poor one. Restarting with a larger population helps, and that is left to the caller here.
Use cases
When to use it
For hard black-box problems with up to a few hundred continuous parameters: no gradients, noisy or rugged surfaces, and variables that are strongly coupled or badly scaled. Typical uses are hyperparameter tuning, control policies and simulator calibration.
In industry
- Engineering design
- Engineers tune shapes and parameters of parts such as aerofoils or antennas where each candidate is scored by a simulation that gives no gradient.
- Robotics
- Researchers optimise gait and controller parameters of simulated and real robots, where the reward is measured over a whole trial.
- Machine learning
- Hyperparameter tuning libraries such as Optuna offer a CMA-ES sampler, and the World Models paper trained its small controller network with it.
Choosing it: what must hold
- A continuous search space of modest size, up to roughly a few thousand dimensions, since the full covariance matrix grows with the square of the dimension.
- An objective you can evaluate but not differentiate, or one that is noisy or has many local optima.
- A budget of many evaluations, ideally run in parallel within each generation.
- A reasonable starting point and initial step size for the search.
When to choose something else
| If | Use instead |
|---|---|
| Gradients are available | A gradient-based optimizer such as SGD or Adam |
| There are many thousands to millions of parameters | OpenAI-style evolution strategies, or NES with a diagonal covariance |
| The search space is discrete or structural | A genetic algorithm |
| Each evaluation is very expensive and there are few dimensions | Bayesian optimisation |
Math foundations
Sampling a generation
Each candidate is the centre plus a random step. The matrix sets the shape of the cloud and the number sets its overall size.
Selection weights
Only the best candidates get a weight, and the weights fall off with rank and sum to 1. measures how many candidates effectively contribute.
Moving the centre
The new centre is the weighted average of the best candidates. is the step of the candidate ranked -th.
The step-size path
A fading sum of recent centre moves, measured in coordinates where the cloud is round. If successive moves agree in direction the path grows long. If they cancel it stays short.
Adapting the step size
The path length is compared with the length expected from purely random steps. Longer means the steps were too timid, so grows. Shorter means they overshoot, so shrinks.
The shape path
The same kind of fading sum, kept in the original coordinates. It records the direction in which the centre has been travelling. The template pauses this update when the step-size path is unusually long.
Adapting the covariance
The old shape fades a little. The rank-one term stretches the cloud along the travel direction, and the rank- term stretches it along the steps of this generation's winners. The template adds a small correction term when the shape path was paused.
Symbols
- the centre of the search distribution (mean)
- the step size, the overall width of the cloud (sigma)
- the covariance matrix, the shape of the cloud
- the number of parameters (dim)
- the candidates per generation, and how many of the best are used (half)
- candidate k and its step from the centre in units of the step size
- the step of the candidate ranked i-th best
- the weight of the i-th best candidate
- the effective number of selected candidates
- the weighted average step of the winners
- the evolution paths for the step size and for the covariance
- the learning rate and damping of the step-size update
- the learning rates of the shape path, the rank-one term and the rank-mu term
Worked by hand
For a problem with parameters, find the default population size, the number of selected candidates, the selection weights and . Use and .
Ten candidates are drawn and the best five are used. The best alone gets 46 percent of the weight, and the five together count like about 3.2 equally weighted candidates.
Visual example
Loading the example.
Try this
- On the narrow valley the cloud stretches along the valley floor.
Code sample
import numpy as np
from impl import CMAES
from config import CMAESConfig
def rosenbrock(x):
return float(np.sum(100.0 * (x[1:] - x[:-1] ** 2) ** 2 + (1.0 - x[:-1]) ** 2))
es = CMAES(x0=np.zeros(4), config=CMAESConfig(sigma0=0.5, seed=0))
best_x, best_f = es.minimize(rosenbrock, max_generations=800) # best_x close to [1, 1, 1, 1]
es = CMAES(x0=np.zeros(4)) # the same loop written out, for when you evaluate candidates yourself
for _ in range(50):
candidates = es.ask() # (population_size, 4)
es.tell([rosenbrock(x) for x in candidates])Read the implementation (115 lines)
"""CMA-ES: covariance matrix adaptation evolution strategy for black-box minimisation.
NumPy only. The (mu/mu_w, lambda) variant with rank-one and rank-mu covariance updates and cumulative
step-size adaptation, with the default constants of Hansen's tutorial. Use the ask / tell loop when you
evaluate candidates yourself, or `minimize` for a plain function. The covariance matrix is eigendecomposed
every generation, which costs O(dim^3) and suits problems up to a few hundred dimensions.
"""
from __future__ import annotations
import math
import numpy as np
try:
from .config import CMAESConfig
except ImportError: # run from the template's own folder
from config import CMAESConfig
class CMAES:
"""Search distribution N(mean, sigma^2 * C) that adapts its mean, step size and shape.
x0: starting point, shape (dim,). State: `mean` (dim,), `sigma` (float), `C` (dim, dim),
`generation`, `best_x` (dim,) and `best_f` (the best candidate evaluated so far).
"""
def __init__(self, x0, config: CMAESConfig | None = None) -> None:
self.config = cfg = config or CMAESConfig()
self.mean = np.array(x0, dtype=float).reshape(-1)
n = self.dim = self.mean.shape[0]
self.sigma = float(cfg.sigma0)
self.rng = np.random.default_rng(cfg.seed)
# selection: the best mu of lambda candidates, with log-decreasing positive weights
self.lam = cfg.population_size or 4 + int(3 * math.log(n))
self.mu = self.lam // 2
w = math.log(self.mu + 0.5) - np.log(np.arange(1, self.mu + 1))
self.weights = w / w.sum()
self.mueff = 1.0 / float(np.sum(self.weights**2))
# adaptation constants
self.cc = (4 + self.mueff / n) / (n + 4 + 2 * self.mueff / n)
self.cs = (self.mueff + 2) / (n + self.mueff + 5)
self.c1 = 2 / ((n + 1.3) ** 2 + self.mueff)
self.cmu = min(1 - self.c1, 2 * (self.mueff - 2 + 1 / self.mueff) / ((n + 2) ** 2 + self.mueff))
self.damps = 1 + 2 * max(0.0, math.sqrt((self.mueff - 1) / (n + 1)) - 1) + self.cs
self.chi_n = math.sqrt(n) * (1 - 1 / (4 * n) + 1 / (21 * n * n)) # E||N(0, I)||
self.pc = np.zeros(n) # evolution path of the covariance
self.ps = np.zeros(n) # evolution path of the step size
self.C = np.eye(n)
self.B = np.eye(n) # eigenvectors of C, columns
self.D = np.ones(n) # square roots of the eigenvalues of C
self.generation = 0
self.best_x = self.mean.copy()
self.best_f = math.inf
self._candidates: np.ndarray | None = None
def ask(self) -> np.ndarray:
"""Sample a generation. Returns candidates of shape (population_size, dim)."""
z = self.rng.standard_normal((self.lam, self.dim))
y = (z * self.D) @ self.B.T # rows ~ N(0, C)
self._candidates = self.mean + self.sigma * y
return self._candidates.copy()
def tell(self, fitnesses) -> None:
"""Update the distribution from the fitness (lower is better) of the candidates last returned by `ask`.
fitnesses: shape (population_size,), in the order of the candidates.
"""
if self._candidates is None:
raise RuntimeError("call ask before tell")
f = np.asarray(fitnesses, dtype=float).reshape(-1)
if f.shape[0] != self.lam:
raise ValueError(f"expected {self.lam} fitness values, got {f.shape[0]}")
n = self.dim
order = np.argsort(f, kind="stable")
if f[order[0]] < self.best_f:
self.best_f, self.best_x = float(f[order[0]]), self._candidates[order[0]].copy()
y = (self._candidates[order[: self.mu]] - self.mean) / self.sigma # (mu, dim) steps of the winners
y_w = self.weights @ y
self.mean = self.mean + self.sigma * y_w
# step-size path uses the step in the coordinate system where C is the identity
inv_sqrt_c_y = self.B @ ((self.B.T @ y_w) / self.D)
self.ps = (1 - self.cs) * self.ps + math.sqrt(self.cs * (2 - self.cs) * self.mueff) * inv_sqrt_c_y
norm_ps = float(np.linalg.norm(self.ps))
correction = math.sqrt(1 - (1 - self.cs) ** (2 * (self.generation + 1)))
hsig = 1.0 if norm_ps / correction / self.chi_n < 1.4 + 2 / (n + 1) else 0.0
self.pc = (1 - self.cc) * self.pc + hsig * math.sqrt(self.cc * (2 - self.cc) * self.mueff) * y_w
rank_one = np.outer(self.pc, self.pc) + (1 - hsig) * self.cc * (2 - self.cc) * self.C
rank_mu = (y * self.weights[:, None]).T @ y
self.C = (1 - self.c1 - self.cmu) * self.C + self.c1 * rank_one + self.cmu * rank_mu
self.sigma *= math.exp((self.cs / self.damps) * (norm_ps / self.chi_n - 1))
self.C = 0.5 * (self.C + self.C.T)
eigenvalues, self.B = np.linalg.eigh(self.C)
self.D = np.sqrt(np.maximum(eigenvalues, 1e-30))
self.generation += 1
self._candidates = None
def minimize(self, fn, max_generations: int = 1000) -> tuple[np.ndarray, float]:
"""Minimise fn(x) -> float, x of shape (dim,). Returns (best_x, best_f).
Stops after max_generations, or earlier when the fitness spread of a generation drops below
`tol_fun` or the step size below `tol_sigma`.
"""
for _ in range(max_generations):
candidates = self.ask()
f = np.array([fn(x) for x in candidates], dtype=float)
self.tell(f)
if f.max() - f.min() < self.config.tol_fun or self.sigma < self.config.tol_sigma:
break
return self.best_x.copy(), self.best_f- Repository
- Not published yet
- Needs
- Python 3.10 and NumPy
- Tests
- 8, run with
python3 -m unittest -v
Practice
Minimise the tilted ellipse from the start using CMAES with the default CMAESConfig and the ask and tell loop. Every 10 generations print sigma and the eigenvalues of C. Explain why one eigenvalue becomes about 100 times the other. Then compare the number of generations with a run where sigma0 is 0.001.
Check on learning
- CMA-ES uses only the rank order of the candidates, not their function values. What does that make it immune to, and what information does it give up?
A way to think about it
Apply any increasing function, such as a cube or an exponential, to the objective. See whether the ranking changes. Then ask what a huge gap between first and second place could have told you.
- Why does a long evolution path signal that the step size is too small, and a short one that it is too large?
A way to think about it
Imagine walking down a straight slope with tiny steps: every step points the same way. Now imagine jumping back and forth across a valley floor.
- On a narrow diagonal valley, a search with a round cloud makes slow progress. How does adapting the covariance fix this, and what does the adapted matrix resemble near a minimum?
A way to think about it
Most round samples land on the steep walls. A stretched cloud places samples along the floor. Compare the learned shape with the inverse of the curvature of the function.
- The covariance matrix for 10000 parameters has 100 million entries. What would you give up by keeping only its diagonal, and for which problems would that be acceptable?
A way to think about it
The diagonal can scale each parameter separately but cannot tilt the cloud. Think about whether the parameters interact.