Sign in

OpenAI-ES

OpenAI-style evolution strategies

Estimates a gradient by trying random perturbations of the parameters and weighting each perturbation by the score it earned.

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

  1. Start from parameters theta0 and choose a noise size sigma and a learning rate lr.
  2. 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.
  3. Evaluate every candidate and pass the values to tell. Lower is better.
  4. If rank_transform is on, replace the values by their ranks, scaled to run from −0.5-0.5 for the lowest to 0.50.5 for the highest.
  5. estimate_gradient sums the noise vectors weighted by those values and divides by the population size and by sigma.
  6. If weight_decay is set, add that coefficient times the parameters to the estimate.
  7. 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

IfUse instead
Gradients are available through backpropagationA gradient-based optimizer such as SGD or Adam
Only a few hundred parameters and an ill-conditioned objectiveCMA-ES
You have a single machine and a differentiable policyA policy gradient reinforcement learning method
You want the search distribution's spread to adapt as wellNatural evolution strategies

Math foundations

  1. The smoothed objective

    J(θ)=Eε∼N(0,I)[f(θ+σε)]J(\theta) = \mathbb{E}_{\varepsilon \sim \mathcal{N}(0, I)}\big[f(\theta + \sigma \varepsilon)\big]

    The average score of noisy copies of the parameters. It is a blurred version of ff, smooth even where ff is not.

  2. Its gradient

    ∇θJ(θ)=1σ Eε[f(θ+σε) ε]\nabla_\theta J(\theta) = \frac{1}{\sigma}\,\mathbb{E}_{\varepsilon}\big[f(\theta + \sigma \varepsilon)\,\varepsilon\big]

    For normal noise the gradient of the average equals the average of score times noise, divided by σ\sigma. No derivative of ff appears.

  3. The sample estimate

    g^=1nσ∑i=1nFi εi,Fi=f(θ+σεi)\hat{g} = \frac{1}{n \sigma} \sum_{i=1}^{n} F_i\,\varepsilon_i, \qquad F_i = f(\theta + \sigma \varepsilon_i)

    The expectation is replaced by an average over nn sampled noise vectors. This is what estimate_gradient computes.

  4. Antithetic pairs

    g^=1nσ∑i=1n/2[f(θ+σεi)−f(θ−σεi)] εi\hat{g} = \frac{1}{n \sigma} \sum_{i=1}^{n/2} \big[f(\theta + \sigma \varepsilon_i) - f(\theta - \sigma \varepsilon_i)\big]\,\varepsilon_i

    Each noise vector is used with both signs. The part of ff that is the same on both sides cancels, which removes much of the noise. Each term is a finite difference along a random direction.

  5. Centred ranks

    Fi←rank⁡(Fi)n−1−12,rank⁡∈{0,…,n−1}F_i \leftarrow \frac{\operatorname{rank}(F_i)}{n - 1} - \frac{1}{2}, \qquad \operatorname{rank} \in \{0, \dots, n - 1\}

    Scores are replaced by their rank, scaled to lie between −0.5-0.5 and 0.50.5. Outliers lose their grip and the scale of ff no longer matters.

  6. The parameter step

    θ←θ−α step⁡ ⁣(g^+c θ)\theta \leftarrow \theta - \alpha\,\operatorname{step}\!\big(\hat{g} + c\,\theta\big)

    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

θ\theta
the parameters being optimised (theta)
ff
the black-box score function, lower is better
ε, εi\varepsilon,\ \varepsilon_i
a standard normal noise vector, and the i-th one sampled
σ\sigma
the fixed noise size (sigma)
J(θ)J(\theta)
the smoothed objective
nn
the number of candidates per generation (population_size)
FiF_i
the score of candidate i, or its centred rank
g^\hat{g}
the estimated gradient
α\alpha
the learning rate (lr)
cc
the weight_decay coefficient

Worked by hand

Take f(θ)=θ2f(\theta) = \theta^2 in one dimension at θ=1\theta = 1, where the true gradient is 2θ=22\theta = 2. Use σ=0.1\sigma = 0.1 and one antithetic pair with ε=+1\varepsilon = +1 and ε=−1\varepsilon = -1, without the rank transform.

f(1+0.1)=1.21,f(1−0.1)=0.81f(1 + 0.1) = 1.21, \qquad f(1 - 0.1) = 0.81
g^=12×0.1 [1.21×(+1)+0.81×(−1)]\hat{g} = \frac{1}{2 \times 0.1}\,\big[1.21 \times (+1) + 0.81 \times (-1)\big]
g^=0.400.20=2\hat{g} = \frac{0.40}{0.20} = 2

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 f(θ)=∑jθj2f(\theta) = \sum_j \theta_j^2 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 2θ2\theta 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

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

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

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

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