Overview
Add small random noise to the parameters many times and score each noisy copy. If copies nudged in some direction score better, that direction is probably downhill. Averaging the noise vectors, each weighted by its score, gives an estimate of the gradient without ever differentiating the function. That estimate is then handed to an ordinary optimizer such as Adam. The noise size is fixed, not adapted. Because each copy is evaluated independently, the work spreads easily over many machines. In this template the evaluations run in one process.
A short history
Tim Salimans, Jonathan Ho, Xi Chen, Szymon Sidor and Ilya Sutskever of OpenAI published "Evolution Strategies as a Scalable Alternative to Reinforcement Learning" in 2017. They simplified natural evolution strategies to a fixed Gaussian and showed that workers need to exchange only random seeds and scores, so training spreads over more than a thousand CPU cores. It matched reinforcement learning methods of the time on Atari and MuJoCo tasks.
How it works
- Start from parameters theta0 and choose a noise size sigma and a learning rate lr.
- ask draws population_size standard normal noise vectors and returns the parameters plus sigma times each. With antithetic on, the second half of the vectors is the negative of the first half.
- Evaluate every candidate and pass the values to tell. Lower is better.
- If rank_transform is on, replace the values by their ranks, scaled to run from for the lowest to for the highest.
- estimate_gradient sums the noise vectors weighted by those values and divides by the population size and by sigma.
- If weight_decay is set, add that coefficient times the parameters to the estimate.
- Take one SGD or Adam step against the estimate, and repeat.
Watch out for
- The estimate is very noisy in high dimensions. Its variance grows with the number of parameters, so large models need large populations.
- The method optimises a smoothed version of the function, blurred over the noise size. A large sigma hides narrow optima, and a small sigma gives estimates dominated by noise.
- Without the rank transform a single extreme score dominates the sum and throws the step off. With it, the estimate keeps the direction but loses the true size of the gradient.
- The noise size is fixed and isotropic. Unlike CMA-ES or NES, it does not adapt to parameters with different sensitivities.
- best_x is the best noisy candidate ever seen, while minimize returns the centre theta. The two can differ, and on a noisy objective the centre is the safer result.
Use cases
When to use it
For reinforcement learning policies and other objectives where backpropagation is unavailable or unhelpful, such as long episodes, sparse rewards or non-differentiable simulators, and where many evaluations can run in parallel.
In industry
- Reinforcement learning research
- The original work trained Atari and simulated locomotion policies across large CPU clusters, with no backpropagation through time.
- Robotics simulation
- Researchers train controllers in simulators where rewards are sparse or delayed, since the method only needs the total score of an episode.
- Non-differentiable systems
- Teams optimise parameters of pipelines with discrete steps or external programs, where a gradient cannot be computed.
Choosing it: what must hold
- A scalar score for a whole run of the model, with no need for gradients.
- Many parallel workers. The method uses far more evaluations than gradient methods and gains its speed from parallelism.
- A noise scale and learning rate tuned to the problem, and usually rank shaping of the scores.
- An objective smooth enough that small parameter perturbations change the score in an informative way.
When to choose something else
| If | Use instead |
|---|---|
| Gradients are available through backpropagation | A gradient-based optimizer such as SGD or Adam |
| Only a few hundred parameters and an ill-conditioned objective | CMA-ES |
| You have a single machine and a differentiable policy | A policy gradient reinforcement learning method |
| You want the search distribution's spread to adapt as well | Natural evolution strategies |
Math foundations
The smoothed objective
The average score of noisy copies of the parameters. It is a blurred version of , smooth even where is not.
Its gradient
For normal noise the gradient of the average equals the average of score times noise, divided by . No derivative of appears.
The sample estimate
The expectation is replaced by an average over sampled noise vectors. This is what estimate_gradient computes.
Antithetic pairs
Each noise vector is used with both signs. The part of that is the same on both sides cancels, which removes much of the noise. Each term is a finite difference along a random direction.
Centred ranks
Scores are replaced by their rank, scaled to lie between and . Outliers lose their grip and the scale of no longer matters.
The parameter step
The estimate, plus an optional weight decay term, is passed to SGD with momentum or to Adam, which turns it into a step. The minus sign is there because the score is minimised.
Symbols
- the parameters being optimised (theta)
- the black-box score function, lower is better
- a standard normal noise vector, and the i-th one sampled
- the fixed noise size (sigma)
- the smoothed objective
- the number of candidates per generation (population_size)
- the score of candidate i, or its centred rank
- the estimated gradient
- the learning rate (lr)
- the weight_decay coefficient
Worked by hand
Take in one dimension at , where the true gradient is . Use and one antithetic pair with and , without the rank transform.
The estimate equals the true gradient 2. The pair acts as a central finite difference, which is exact for a quadratic. With many dimensions each pair measures the slope along one random direction only, so many pairs are needed.
Visual example
Loading the example.
Try this
- Each point is the centre plus noise. The centre moves toward the noise that scored well.
Code sample
import numpy as np
from impl import OpenAIES
from config import OpenAIESConfig
target = np.array([1.0, -2.0, 3.0])
es = OpenAIES(theta0=np.zeros(3), config=OpenAIESConfig(population_size=40, sigma=0.1, lr=0.05, seed=0))
theta, loss = es.minimize(lambda x: float(np.sum((x - target) ** 2)), generations=300)
print(theta, loss) # close to the target
es = OpenAIES(theta0=np.zeros(3)) # the same loop written out
for _ in range(10):
candidates = es.ask() # (population_size, 3); evaluate these in parallel if you can
es.tell([float(np.sum((x - target) ** 2)) for x in candidates])Read the implementation (106 lines)
"""OpenAI-style evolution strategies: estimate a gradient from random parameter perturbations.
NumPy only. The parameters are perturbed with isotropic Gaussian noise of fixed size, every perturbed copy is
evaluated, and the fitness-weighted sum of the noise vectors estimates the gradient of the smoothed objective
E[f(theta + sigma * eps)]. That estimate is fed to SGD or Adam. Fitness is minimised. In the original work
the evaluations run on many workers that share random seeds; here they run in one process, and the ask / tell
split marks the place where a parallel evaluation would go.
"""
from __future__ import annotations
import math
import numpy as np
try:
from .config import OpenAIESConfig
except ImportError: # run from the template's own folder
from config import OpenAIESConfig
def centered_ranks(values) -> np.ndarray:
"""Ranks of the values scaled to [-0.5, 0.5]: the smallest gets -0.5, the largest 0.5. Shape (n,)."""
values = np.asarray(values, dtype=float).reshape(-1)
ranks = np.empty(len(values))
ranks[np.argsort(values, kind="stable")] = np.arange(len(values))
return ranks / max(len(values) - 1, 1) - 0.5
class OpenAIES:
"""Evolution strategy with fixed noise scale. theta0: starting parameters, shape (dim,).
State: `theta` (dim,), `generation`, `best_x` (dim,) and `best_f` (best perturbed candidate seen).
"""
def __init__(self, theta0, config: OpenAIESConfig | None = None) -> None:
self.config = cfg = config or OpenAIESConfig()
self.theta = np.array(theta0, dtype=float).reshape(-1)
self.dim = self.theta.shape[0]
self.rng = np.random.default_rng(cfg.seed)
self.pop = cfg.population_size + (cfg.population_size % 2 if cfg.antithetic else 0)
self.generation = 0
self.best_x = self.theta.copy()
self.best_f = math.inf
self._noise: np.ndarray | None = None
self._m = np.zeros(self.dim) # momentum (sgd) or first moment (adam)
self._v = np.zeros(self.dim) # second moment (adam)
def ask(self) -> np.ndarray:
"""Sample a generation: theta + sigma * eps. Returns candidates of shape (population_size, dim).
With antithetic sampling the second half of the rows uses the negated noise of the first half.
"""
if self.config.antithetic:
half = self.rng.standard_normal((self.pop // 2, self.dim))
self._noise = np.vstack([half, -half])
else:
self._noise = self.rng.standard_normal((self.pop, self.dim))
return self.theta + self.config.sigma * self._noise
def estimate_gradient(self, fitnesses) -> np.ndarray:
"""Gradient estimate (dim,) from the fitness of the last `ask`: sum_i F_i * eps_i / (n * sigma).
With `rank_transform` the F_i are centred ranks, so the result is a search direction with the sign of
the gradient but not its scale.
"""
if self._noise is None:
raise RuntimeError("call ask before tell")
f = np.asarray(fitnesses, dtype=float).reshape(-1)
if f.shape[0] != self.pop:
raise ValueError(f"expected {self.pop} fitness values, got {f.shape[0]}")
shaped = centered_ranks(f) if self.config.rank_transform else f
return shaped @ self._noise / (self.pop * self.config.sigma)
def tell(self, fitnesses) -> None:
"""Take one optimizer step on the gradient estimated from `fitnesses` (lower is better).
fitnesses: shape (population_size,), in the order of the candidates returned by `ask`.
"""
cfg = self.config
grad = self.estimate_gradient(fitnesses)
f = np.asarray(fitnesses, dtype=float).reshape(-1)
i = int(np.argmin(f))
if f[i] < self.best_f:
self.best_f, self.best_x = float(f[i]), self.theta + cfg.sigma * self._noise[i]
if cfg.weight_decay:
grad = grad + cfg.weight_decay * self.theta
self.generation += 1
if cfg.optimizer == "adam":
t = self.generation
self._m = 0.9 * self._m + 0.1 * grad
self._v = 0.999 * self._v + 0.001 * grad * grad
step = (self._m / (1 - 0.9**t)) / (np.sqrt(self._v / (1 - 0.999**t)) + 1e-8)
else:
self._m = cfg.momentum * self._m + grad
step = self._m
self.theta = self.theta - cfg.lr * step
self._noise = None
def minimize(self, fn, generations: int = 200) -> tuple[np.ndarray, float]:
"""Minimise fn(theta) -> float, theta of shape (dim,), for `generations` generations.
Returns (theta, fn(theta)) for the final parameters, the centre of the search distribution.
"""
for _ in range(generations):
self.tell([fn(x) for x in self.ask()])
return self.theta.copy(), float(fn(self.theta))- Repository
- Not published yet
- Needs
- Python 3.10 and NumPy
- Tests
- 9, run with
python3 -m unittest -v
Practice
Minimise in 20 dimensions from a start of all ones. Create an OpenAIES with rank_transform off through OpenAIESConfig, call ask, evaluate, and compare estimate_gradient with the true gradient by the angle between them. Repeat for population_size 10, 100 and 1000, with antithetic on and off. Then run minimize with the defaults and plot the score per generation.
Check on learning
- Why does the quality of the gradient estimate get worse as the number of parameters grows, for a fixed population size?
A way to think about it
Each antithetic pair measures the slope along one random direction. Ask how many directions are needed to pin down a vector in that many dimensions.
- With the rank transform on, multiplying the score function by 1000 changes nothing in the updates. Why is that useful, and what is lost?
A way to think about it
Think about tuning a learning rate across tasks with very different reward scales. Then ask whether the method can still tell a steep slope from a gentle one.
- The noise size plays two roles: it sets how far the search looks and how blurred the objective is. What happens at an optimum that sits in a valley much narrower than the noise size?
A way to think about it
Most noisy copies land outside the valley. Consider what the average score looks like around that point after blurring.
- Backpropagation gives an exact gradient in one backward pass. Why would anyone prefer a noisy estimate that needs hundreds of evaluations?
A way to think about it
List the cases where the exact gradient does not exist, is zero almost everywhere, or must be carried through thousands of time steps. Add the fact that evaluations can run in parallel.