Sign in

CMA-ES

Covariance Matrix Adaptation Evolution Strategy

A search method that needs no gradients: it samples candidates from a bell-shaped cloud and reshapes the cloud toward where the good candidates were.

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

  1. Start with a centre x0, a step size sigma0 and a round cloud (the covariance matrix is the identity).
  2. ask draws population_size candidates from a normal distribution with that centre, size and shape.
  3. Evaluate every candidate and pass the results to tell. Lower is better.
  4. tell sorts the candidates and keeps the better half. The new centre is their weighted average, with larger weights for better ranks.
  5. Two running sums of recent centre moves, called evolution paths, are updated. One is used for the step size and one for the shape.
  6. 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.
  7. The step size grows if the step-size path is longer than random steps would give, and shrinks if it is shorter.
  8. 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 n2n^2 entries and is eigendecomposed every generation at a cost of order n3n^3. 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

IfUse instead
Gradients are availableA gradient-based optimizer such as SGD or Adam
There are many thousands to millions of parametersOpenAI-style evolution strategies, or NES with a diagonal covariance
The search space is discrete or structuralA genetic algorithm
Each evaluation is very expensive and there are few dimensionsBayesian optimisation

Math foundations

  1. 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), \quad k = 1, \dots, \lambda

    Each candidate is the centre plus a random step. The matrix CC sets the shape of the cloud and the number σ\sigma sets its overall size.

  2. Selection weights

    wi=ln⁡(μ+12)−ln⁡i∑j=1μ(ln⁡(μ+12)−ln⁡j),μeff=1∑i=1μwi2w_i = \frac{\ln(\mu + \tfrac{1}{2}) - \ln i}{\sum_{j=1}^{\mu} \big(\ln(\mu + \tfrac{1}{2}) - \ln j\big)}, \qquad \mu_{\text{eff}} = \frac{1}{\sum_{i=1}^{\mu} w_i^2}

    Only the best μ\mu candidates get a weight, and the weights fall off with rank and sum to 1. μeff\mu_{\text{eff}} measures how many candidates effectively contribute.

  3. Moving the centre

    yw=∑i=1μwi yi:λ,m←m+σ ywy_w = \sum_{i=1}^{\mu} w_i\,y_{i:\lambda}, \qquad m \leftarrow m + \sigma\,y_w

    The new centre is the weighted average of the best candidates. yi:λy_{i:\lambda} is the step of the candidate ranked ii-th.

  4. The step-size path

    pσ←(1−cσ) pσ+cσ(2−cσ) μeff C−1/2 ywp_\sigma \leftarrow (1 - c_\sigma)\,p_\sigma + \sqrt{c_\sigma (2 - c_\sigma)\,\mu_{\text{eff}}}\ C^{-1/2}\,y_w

    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.

  5. Adapting the step size

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

    The path length is compared with the length expected from purely random steps. Longer means the steps were too timid, so σ\sigma grows. Shorter means they overshoot, so σ\sigma shrinks.

  6. The shape path

    pc←(1−cc) pc+cc(2−cc) μeff ywp_c \leftarrow (1 - c_c)\,p_c + \sqrt{c_c (2 - c_c)\,\mu_{\text{eff}}}\ y_w

    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.

  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 old shape fades a little. The rank-one term stretches the cloud along the travel direction, and the rank-μ\mu 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

mm
the centre of the search distribution (mean)
σ\sigma
the step size, the overall width of the cloud (sigma)
CC
the covariance matrix, the shape of the cloud
nn
the number of parameters (dim)
λ, μ\lambda,\ \mu
the candidates per generation, and how many of the best are used (half)
xk, ykx_k,\ y_k
candidate k and its step from the centre in units of the step size
yi:λy_{i:\lambda}
the step of the candidate ranked i-th best
wiw_i
the weight of the i-th best candidate
μeff\mu_{\text{eff}}
the effective number of selected candidates
ywy_w
the weighted average step of the winners
pσ, pcp_\sigma,\ p_c
the evolution paths for the step size and for the covariance
cσ, dσc_\sigma,\ d_\sigma
the learning rate and damping of the step-size update
cc, c1, cμc_c,\ c_1,\ c_\mu
the learning rates of the shape path, the rank-one term and the rank-mu term

Worked by hand

For a problem with n=10n = 10 parameters, find the default population size, the number of selected candidates, the selection weights and μeff\mu_{\text{eff}}. Use ln⁡10≈2.303\ln 10 \approx 2.303 and ln⁡5.5≈1.705\ln 5.5 \approx 1.705.

λ=4+⌊3ln⁡10⌋=4+⌊6.91⌋=10,μ=⌊10/2⌋=5\lambda = 4 + \lfloor 3 \ln 10 \rfloor = 4 + \lfloor 6.91 \rfloor = 10, \qquad \mu = \lfloor 10 / 2 \rfloor = 5
ln⁡5.5−ln⁡i=1.705, 1.012, 0.606, 0.318, 0.095(sum 3.736)\ln 5.5 - \ln i = 1.705,\ 1.012,\ 0.606,\ 0.318,\ 0.095 \quad (\text{sum } 3.736)
w=(0.456, 0.271, 0.162, 0.085, 0.026)w = (0.456,\ 0.271,\ 0.162,\ 0.085,\ 0.026)
μeff=10.4562+0.2712+0.1622+0.0852+0.0262≈3.17\mu_{\text{eff}} = \frac{1}{0.456^2 + 0.271^2 + 0.162^2 + 0.085^2 + 0.026^2} \approx 3.17

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 f(x)=(x0+x1)2+100 (x0−x1)2f(x) = (x_0 + x_1)^2 + 100\,(x_0 - x_1)^2 from the start (3,−2)(3, -2) 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

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

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

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

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