Sign in

NES

Natural Evolution Strategies

A gradient-free optimizer that improves a search distribution by following the natural gradient of its expected fitness, estimated from ranked samples.

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

  1. Start with a centre x0 and the same width sigma0 in every dimension.
  2. 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.
  3. Evaluate the candidates and pass the values to tell. Lower is better.
  4. 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.
  5. The centre moves by the utility-weighted sum of the noise vectors, scaled by the widths and lr_mean.
  6. 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.
  7. 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

IfUse instead
Backpropagation through the objective is possibleA gradient-based optimizer such as SGD or Adam
The dimension is modest and the problem is ill-conditionedCMA-ES, which adapts a full covariance matrix
There are millions of parameters and many workersOpenAI-style evolution strategies, with a fixed isotropic Gaussian
The search space is discreteA genetic algorithm

Math foundations

  1. The objective

    J(θ)=Ez∼π(⋅∣θ)[f(z)]J(\theta) = \mathbb{E}_{z \sim \pi(\cdot \mid \theta)}\big[f(z)\big]

    The expected function value of a sample zz from the search distribution with parameters θ\theta, here the centre and the widths. NES improves JJ, not ff directly.

  2. The search gradient

    ∇θJ(θ)=Ez[f(z) ∇θln⁡π(z∣θ)]≈1λ∑k=1λf(zk) ∇θln⁡π(zk∣θ)\nabla_\theta J(\theta) = \mathbb{E}_{z}\big[f(z)\,\nabla_\theta \ln \pi(z \mid \theta)\big] \approx \frac{1}{\lambda} \sum_{k=1}^{\lambda} f(z_k)\,\nabla_\theta \ln \pi(z_k \mid \theta)

    The gradient of the average can be written as an average itself, so it can be estimated from samples. Only values of ff are needed, never its derivative.

  3. Sampling

    zk=μ+σ⊙sk,sk∼N(0,I)z_k = \mu + \sigma \odot s_k, \qquad s_k \sim \mathcal{N}(0, I)

    Each candidate is the centre plus standard normal noise stretched by the width of each dimension. The symbol ⊙\odot means multiplying entry by entry.

  4. Rank utilities

    uk=max⁡ ⁣(0, ln⁡(λ2+1)−ln⁡k)∑j=1λmax⁡ ⁣(0, ln⁡(λ2+1)−ln⁡j)−1λu_k = \frac{\max\!\big(0,\ \ln(\tfrac{\lambda}{2} + 1) - \ln k\big)}{\sum_{j=1}^{\lambda} \max\!\big(0,\ \ln(\tfrac{\lambda}{2} + 1) - \ln j\big)} - \frac{1}{\lambda}

    The function values are replaced by fixed numbers that depend only on the rank kk, with 1 the best. This is called fitness shaping. The search is then unaffected by outliers and by any increasing rescaling of ff.

  5. Updating the centre

    μ←μ+ημ σ⊙∑k=1λuk sk\mu \leftarrow \mu + \eta_\mu\,\sigma \odot \sum_{k=1}^{\lambda} u_k\,s_k

    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.

  6. Updating the widths

    σ←σ⊙exp⁡ ⁣(ησ2∑k=1λuk (sk2−1))\sigma \leftarrow \sigma \odot \exp\!\left(\frac{\eta_\sigma}{2} \sum_{k=1}^{\lambda} u_k\,\big(s_k^2 - 1\big)\right)

    The square is taken entry by entry. Standard normal noise has s2=1s^2 = 1 on average. If good samples had larger squared noise than that in some dimension, its width grows. The exponential keeps the widths positive.

  7. Default width learning rate

    ησ=3+ln⁡d5d\eta_\sigma = \frac{3 + \ln d}{5 \sqrt{d}}

    The standard choice for SNES. It becomes smaller as the number of dimensions grows, because the estimate of each width is noisier.

Symbols

ff
the black-box function being minimised
θ\theta
the parameters of the search distribution: the centre and the widths
π(z∣θ)\pi(z \mid \theta)
the density of the search distribution
J(θ)J(\theta)
the expected value of f under the search distribution
μ, σ\mu,\ \sigma
the centre (mean) and the vector of widths (sigma), one per dimension
zk, skz_k,\ s_k
candidate k and the standard normal noise that produced it
λ\lambda
the number of candidates per generation (population_size)
uku_k
the utility of the candidate ranked k-th best
ημ, ησ\eta_\mu,\ \eta_\sigma
the learning rates lr_mean and lr_sigma
dd
the number of dimensions (dim)

Worked by hand

Take λ=4\lambda = 4 candidates in one dimension, with μ=2\mu = 2, σ=1\sigma = 1 and ημ=1\eta_\mu = 1. Sorted from best to worst, the noise values are −1.0-1.0, −0.5-0.5, 0.50.5 and 1.01.0. Use ln⁡3≈1.099\ln 3 \approx 1.099 and ln⁡2≈0.693\ln 2 \approx 0.693.

max⁡(0, ln⁡3−ln⁡k)=1.099, 0.405, 0, 0(sum 1.504)\max(0,\ \ln 3 - \ln k) = 1.099,\ 0.405,\ 0,\ 0 \quad (\text{sum } 1.504)
u=(0.730, 0.270, 0, 0)−0.25=(0.480, 0.020, −0.25, −0.25)u = (0.730,\ 0.270,\ 0,\ 0) - 0.25 = (0.480,\ 0.020,\ -0.25,\ -0.25)
∑kuksk=0.480(−1.0)+0.020(−0.5)−0.25(0.5)−0.25(1.0)=−0.865\sum_k u_k s_k = 0.480(-1.0) + 0.020(-0.5) - 0.25(0.5) - 0.25(1.0) = -0.865
μ←2+1×1×(−0.865)=1.135\mu \leftarrow 2 + 1 \times 1 \times (-0.865) = 1.135

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 f(x)=∑j(j+1) xj2f(x) = \sum_j (j + 1)\,x_j^2 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

  1. The function ff may have jumps and flat regions, yet JJ 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.

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

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

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