Overview
You cannot take the gradient of a black-box function, but you can take the gradient of an average. Natural evolution strategies (NES) keep a normal distribution over solutions, with a centre and a width per dimension. The quantity being improved is the average function value of samples drawn from that distribution. That average changes smoothly as the centre and widths change, even when the function itself is rough, so it has a gradient that can be estimated from samples. This template is the separable variant, SNES: one width per dimension and no correlations, which keeps the cost linear in the number of parameters.
A short history
Daan Wierstra, Tom Schaul, Jan Peters and Juergen Schmidhuber introduced natural evolution strategies in 2008, with a full account in the Journal of Machine Learning Research in 2014. The idea was to give evolution strategies a clear principle: treat the search distribution's parameters as the thing to optimise, and follow the natural gradient, a concept from Shun-ichi Amari, of expected fitness. Later large-scale evolution strategies build on it.
How it works
- Start with a centre x0 and the same width sigma0 in every dimension.
- ask draws population_size noise vectors from a standard normal and returns the candidates: centre plus width times noise. With mirrored on, the noise comes in pairs of opposite sign.
- Evaluate the candidates and pass the values to tell. Lower is better.
- tell sorts the noise vectors from best to worst candidate and gives each a fixed utility that depends only on its rank. The utilities sum to zero.
- The centre moves by the utility-weighted sum of the noise vectors, scaled by the widths and lr_mean.
- Each width is multiplied by the exponential of a utility-weighted sum of squared noise minus one. A width grows where good samples lay far out and shrinks where they lay close in.
- Repeat. minimize stops after the given generations, or when every width is tiny.
Watch out for
- The separable variant cannot learn correlations between parameters. On a narrow valley that runs diagonally it makes slow progress, where CMA-ES would tilt its search cloud.
- With a small population the gradient estimate is noisy, and the widths can collapse too early so the search freezes away from the optimum.
- Every width starts at the same sigma0. If the parameters have very different natural scales, the early generations are wasted until the widths adapt.
- The reported best_x is the best single sample ever seen. On a noisy objective that sample may just have been lucky, and the centre is the more reliable answer.
- Like all evolution strategies it needs many evaluations. If a gradient of the objective is available, use it.
Use cases
When to use it
For black-box problems with many parameters that interact little, where a full covariance matrix is too costly: large policy vectors, simulator settings, and objectives that are noisy or not differentiable.
In industry
- Reinforcement learning research
- Policies for control tasks are trained by sampling parameter vectors, scoring whole episodes and updating the search distribution.
- Adversarial robustness testing
- Black-box attacks on image classifiers use NES gradient estimates to find adversarial inputs with query access only.
- Black-box tuning
- Practitioners tune simulation or controller parameters where the objective is a program output with no usable gradient.
Choosing it: what must hold
- An objective that can be evaluated for any parameter vector but gives no usable gradient.
- A continuous parameter space and a search distribution, usually Gaussian, that suits it.
- Many evaluations per update, which pay off when they can run in parallel.
- Rank-based fitness shaping, so that outlier scores do not dominate the update.
When to choose something else
| If | Use instead |
|---|---|
| Backpropagation through the objective is possible | A gradient-based optimizer such as SGD or Adam |
| The dimension is modest and the problem is ill-conditioned | CMA-ES, which adapts a full covariance matrix |
| There are millions of parameters and many workers | OpenAI-style evolution strategies, with a fixed isotropic Gaussian |
| The search space is discrete | A genetic algorithm |
Math foundations
The objective
The expected function value of a sample from the search distribution with parameters , here the centre and the widths. NES improves , not directly.
The search gradient
The gradient of the average can be written as an average itself, so it can be estimated from samples. Only values of are needed, never its derivative.
Sampling
Each candidate is the centre plus standard normal noise stretched by the width of each dimension. The symbol means multiplying entry by entry.
Rank utilities
The function values are replaced by fixed numbers that depend only on the rank , with 1 the best. This is called fitness shaping. The search is then unaffected by outliers and by any increasing rescaling of .
Updating the centre
The natural-gradient step for the mean. Noise directions that produced good candidates have positive utility and pull the centre toward them. Bad ones have negative utility and push it away.
Updating the widths
The square is taken entry by entry. Standard normal noise has on average. If good samples had larger squared noise than that in some dimension, its width grows. The exponential keeps the widths positive.
Default width learning rate
The standard choice for SNES. It becomes smaller as the number of dimensions grows, because the estimate of each width is noisier.
Symbols
- the black-box function being minimised
- the parameters of the search distribution: the centre and the widths
- the density of the search distribution
- the expected value of f under the search distribution
- the centre (mean) and the vector of widths (sigma), one per dimension
- candidate k and the standard normal noise that produced it
- the number of candidates per generation (population_size)
- the utility of the candidate ranked k-th best
- the learning rates lr_mean and lr_sigma
- the number of dimensions (dim)
Worked by hand
Take candidates in one dimension, with , and . Sorted from best to worst, the noise values are , , and . Use and .
The better candidates lay below the centre, so the centre moves down from 2 to 1.135. The utilities sum to zero, so if the ranking carried no pattern the centre would not drift.
Visual example
Loading the example.
Try this
- Watch the spread shrink as the search grows confident.
Code sample
import numpy as np
from impl import NES
from config import NESConfig
target = np.array([1.0, -2.0, 3.0, 0.5])
es = NES(x0=np.zeros(4), config=NESConfig(sigma0=1.0, seed=0))
best_x, best_f = es.minimize(lambda x: float(np.sum((x - target) ** 2)), generations=400)
print(best_x, best_f) # close to the target, fitness near 0
es = NES(x0=np.zeros(4)) # the same loop written out
for _ in range(10):
candidates = es.ask() # (population_size, 4)
es.tell([float(np.sum((x - target) ** 2)) for x in candidates])Read the implementation (90 lines)
"""Natural evolution strategies, separable variant (SNES), for black-box minimisation.
NumPy only. The search distribution is a Gaussian with a mean and one standard deviation per dimension.
Each generation estimates the natural gradient of the expected fitness with respect to those parameters
from ranked samples and follows it. Memory and time per generation are linear in the dimension.
"""
from __future__ import annotations
import math
import numpy as np
try:
from .config import NESConfig
except ImportError: # run from the template's own folder
from config import NESConfig
def rank_utilities(n: int) -> np.ndarray:
"""Fitness-shaping utilities for n samples ordered from best to worst. Shape (n,), sums to 0.
u_k = max(0, ln(n/2 + 1) - ln(k)) for rank k = 1..n, normalised to sum 1, minus 1/n. Using ranks
instead of raw fitness makes the search invariant to monotone transformations of the objective.
"""
raw = np.maximum(0.0, math.log(n / 2 + 1) - np.log(np.arange(1, n + 1)))
return raw / raw.sum() - 1.0 / n
class NES:
"""Separable NES. x0: starting point, shape (dim,).
State: `mean` (dim,), `sigma` (dim,), `generation`, `best_x` (dim,) and `best_f`.
"""
def __init__(self, x0, config: NESConfig | None = None) -> None:
self.config = cfg = config or NESConfig()
self.mean = np.array(x0, dtype=float).reshape(-1)
n = self.dim = self.mean.shape[0]
self.sigma = np.full(n, float(cfg.sigma0))
self.rng = np.random.default_rng(cfg.seed)
lam = cfg.population_size or 4 + int(3 * math.log(n))
self.lam = lam + (lam % 2) if cfg.mirrored else lam
self.lr_sigma = cfg.lr_sigma or (3 + math.log(n)) / (5 * math.sqrt(n))
self.utilities = rank_utilities(self.lam)
self.generation = 0
self.best_x = self.mean.copy()
self.best_f = math.inf
self._noise: np.ndarray | None = None
def ask(self) -> np.ndarray:
"""Sample a generation: mean + sigma * noise. Returns candidates of shape (population_size, dim)."""
if self.config.mirrored:
half = self.rng.standard_normal((self.lam // 2, self.dim))
self._noise = np.vstack([half, -half])
else:
self._noise = self.rng.standard_normal((self.lam, self.dim))
return self.mean + self.sigma * self._noise
def tell(self, fitnesses) -> None:
"""Update mean and sigma 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._noise 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]}")
order = np.argsort(f, kind="stable")
if f[order[0]] < self.best_f:
self.best_f = float(f[order[0]])
self.best_x = self.mean + self.sigma * self._noise[order[0]]
s = self._noise[order] # noise vectors from best to worst
grad_mean = self.utilities @ s # natural gradient for the mean, in units of sigma
grad_sigma = self.utilities @ (s * s - 1.0) # natural gradient for log sigma
self.mean = self.mean + self.config.lr_mean * self.sigma * grad_mean
self.sigma = self.sigma * np.exp(0.5 * self.lr_sigma * grad_sigma)
self.generation += 1
self._noise = None
def minimize(self, fn, generations: int = 500, tol_sigma: float = 1e-12) -> tuple[np.ndarray, float]:
"""Minimise fn(x) -> float, x of shape (dim,). Returns (best_x, best_f).
Stops after `generations`, or earlier when every standard deviation is below `tol_sigma`.
"""
for _ in range(generations):
self.tell([fn(x) for x in self.ask()])
if self.sigma.max() < 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 in 10 dimensions from a start of all ones with NES and the default NESConfig, using ask and tell. Every 20 generations print the vector sigma and explain why the widths differ between dimensions. Call rank_utilities for 10 samples and check that it sums to zero. Then set mirrored to true and compare how fast best_f falls.
Check on learning
- The function may have jumps and flat regions, yet has a well-defined gradient. Why does averaging over a distribution make the problem smooth?
A way to think about it
Think of blurring a step: the average over a window changes gradually as the window slides across the jump.
- The utilities are built to sum to zero. What would the centre do if all utilities were positive, even when all candidates were equally good?
A way to think about it
With equal function values the ranking is arbitrary. Compute the update with constant positive weights and with weights that sum to zero.
- Why is the width updated through an exponential, and not by adding the gradient to it directly?
A way to think about it
A width must stay positive, and a change of 0.1 means something very different for a width of 0.01 than for a width of 100.
- Mirrored sampling evaluates each noise vector with both signs. For a function that is nearly linear around the centre, why does this give a much better estimate of the direction?
A way to think about it
Write the function near the centre as a constant plus a slope term and see which part cancels between a pair.