# Evolution Strategies

Gradient descent is not the only option when learning optimal model parameters. Evolution Strategies (ES) works out well in the cases where we don’t know the precise analytic form of an objective function or cannot compute the gradients directly. This post dives into several classic ES methods, as well as how ES can be used in deep reinforcement learning.

Stochastic gradient descent is a universal choice for optimizing deep learning models. However, it is not the only option. With black-box optimization algorithms, you can evaluate a target function , even when you don’t know the precise analytic form of and thus cannot compute gradients or the Hessian matrix. Examples of black-box optimization methods include Simulated Annealing, Hill Climbing and Nelder-Mead method.

**Evolution Strategies (ES)** is one type of black-box optimization algorithms, born in the family of **Evolutionary Algorithms (EA)**. In this post, I would dive into a couple of classic ES methods and introduce a few applications of how ES can play a role in deep reinforcement learning.

- What are Evolution Strategies?
- Simple Gaussian Evolution Strategies
- Covariance Matrix Adaptation Evolution Strategies (CMA-ES)
- Natural Evolution Strategies
- Applications: ES in Deep Reinforcement Learning
- Extension: EA in Deep Learning
- References

## What are Evolution Strategies?

Evolution strategies (ES) belong to the big family of evolutionary algorithms. The optimization targets of ES are vectors of real numbers, .

Evolutionary algorithms refer to a division of population-based optimization algorithms inspired by *natural selection*. Natural selection believes that individuals with traits beneficial to their survival can live through generations and pass down the good characteristics to the next generation. Evolution happens by the selection process gradually and the population grows better adapted to the environment.

*Fig. 1. How natural selection works. (Image source: Khan Academy: Darwin, evolution, & natural selection)*

Evolutionary algorithms can be summarized in the following format as a general optimization solution:

Let’s say we want to optimize a function and we are not able to compute gradients directly. But we still can evaluate given any and the result is deterministic. Our belief in the probability distribution over as a good solution to optimization is , parameterized by . The goal is to find an optimal configuration of .

Here given a fixed format of distribution (i.e. Gaussian), the parameter carries the knowledge about the best solutions and is being iteratively updated across generations.

Starting with an initial value of , we can continuously update by looping three steps as follows:

- Generate a population of samples where .
- Evaluate the “fitness” of samples in .
- Select the best subset of individuals and use them to update , generally based on fitness or rank.

In **Genetic Algorithms (GA)**, another popular subcategory of EA, is a sequence of binary codes, . While in ES, is just a vector of real numbers, .

## Simple Gaussian Evolution Strategies

This is the most basic and canonical version of evolution strategies. It models as a -dimensional isotropic Gaussian distribution, in which only tracks the mean and standard deviation .

The process of Simple-Gaussian-ES, given :

- Initialize and the generation counter
- Generate the offspring population of size by sampling from the Gaussian distribution:

. - Select a top subset of samples with optimal and this subset is called
**elite**set. Without loss of generality, we may consider the first samples in to belong to the elite group — Let’s label them as

. - Then we estimate the new mean and std for the next generation using the elite set:

- Repeat steps (2)-(4) until the result is good enough ✌️

## Covariance Matrix Adaptation Evolution Strategies (CMA-ES)

The standard deviation accounts for the level of exploration: the larger the bigger search space we can sample our offspring population. In vanilla ES, is highly correlated with , so the algorithm is not able to rapidly adjust the exploration space when needed (i.e. when the confidence level changes).

**CMA-ES**, short for *“Covariance Matrix Adaptation Evolution Strategy”*, fixes the problem by tracking pairwise dependencies between the samples in the distribution with a covariance matrix . The new distribution parameter becomes:

where controls for the overall scale of the distribution, often known as *step size*.

Before we dig into how the parameters are updated in CMA-ES, it is better to review how the covariance matrix works in the multivariate Gaussian distribution first. As a real symmetric matrix, the covariance matrix has the following nice features (See proof & proof):

- It is always diagonalizable.
- Always positive semi-definite.
- All of its eigenvalues are real non-negative numbers.
- All of its eigenvectors are orthogonal.
- There is an orthonormal basis of consisting of its eigenvectors.

Let the matrix have an *orthonormal* basis of eigenvectors , with corresponding eigenvalues . Let .

The square root of is:

Symbol | Meaning |
---|---|

the -th samples at the generation (t) | |

mean of the generation (t) | |

step size | |

covariance matrix | |

a matrix of ’s eigenvectors as row vectors | |

a diagonal matrix with ’s eigenvalues on the diagnose. | |

evaluation path for at the generation (t) | |

evaluation path for at the generation (t) | |

learning rate for ’s update | |

learning rate for | |

damping factor for ’s update | |

learning rate for | |

learning rate for ’s rank-min(λ, n) update | |

learning rate for ’s rank-1 update |

### Updating the Mean

CMA-ES has a learning rate to control how fast the mean should be updated. Usually it is set to 1 and thus the equation becomes the same as in vanilla ES, .

### Controlling the Step Size

The sampling process can be decoupled from the mean and standard deviation:

The parameter controls the overall scale of the distribution. It is separated from the covariance matrix so that we can change steps faster than the full covariance. A larger step size leads to faster parameter update. In order to evaluate whether the current step size is proper, CMA-ES constructs an *evolution path* by summing up a consecutive sequence of moving steps, . By comparing this path length with its expected length under random selection (meaning single steps are uncorrelated), we are able to adjust accordingly (See Fig. 2).

*Fig. 2. Three scenarios of how single steps are correlated in different ways and their impacts on step size update. (Image source: additional annotations on Fig 5 in CMA-ES tutorial paper)*

Each time the evolution path is updated with the average of moving step in the same generation.

By multiplying with , the evolution path is transformed to be independent of its direction. The term transformation works as follows:

- contains row vectors of ’s eigenvectors. It projects the original space onto the perpendicular principal axes.
- Then scales the length of principal axes to be equal.
- transforms the space back to the original coordinate system.

In order to assign higher weights to recent generations, we use polyak averaging to update the evolution path with learning rate . Meanwhile, the weights are balanced so that is conjugate, both before and after one update.

The expected length of under random selection is , that is the expectation of the L2-norm of a random variable. Following the idea in Fig. 2, we adjust the step size according to the ratio of :

where is a damping parameter, scaling how fast should be changed.

### Adapting the Covariance Matrix

For the covariance matrix, it can be estimated from scratch using of elite samples (recall that ):

The above estimation is only reliable when the selected population is large enough. However, we do want to run *fast* iteration with a *small* population of samples in each generation. That’s why CMA-ES invented a more reliable but also more complicated way to update . It involves two independent routes,

*Rank-min(λ, n) update*: uses the history of , each estimated from scratch in one generation.*Rank-one update*: estimates the moving steps and the sign information from the history.

The first route considers the estimation of from the entire history of . For example, if we have experienced a large number of generations, would be a good estimator. Similar to , we also use polyak averaging with a learning rate to incorporate the history:

A common choice for the learning rate is .

The second route tries to solve the issue that loses the sign information. Similar to how we adjust the step size , an evolution path is used to track the sign information and it is constructed in a way that is conjugate, both before and after a new generation.

We may consider as another way to compute (notice that both ) while the entire history is used and the sign information is maintained. Note that we’ve known in the last section,

Then the covariance matrix is updated according to :

The *rank-one update* approach is claimed to generate a significant improvement over the *rank-min(λ, n)-update* when is small, because the signs of moving steps and correlations between consecutive steps are all utilized and passed down through generations.

Eventually we combine two approaches together,

In all my examples above, each elite sample is considered to contribute an equal amount of weights, . The process can be easily extended to the case where selected samples are assigned with different weights, , according to their performances. See more detail in tutorial.

*Fig. 3. Illustration of how CMA-ES works on a 2D optimization problem (the lighter color the better). Black dots are samples in one generation. The samples are more spread out initially but when the model has higher confidence in finding a good solution in the late stage, the samples become very concentrated over the global optimum. (Image source: Wikipedia CMA-ES)*

## Natural Evolution Strategies

Natural Evolution Strategies (**NES**; Wierstra, et al, 2008) optimizes in a search distribution of parameters and moves the distribution in the direction of high fitness indicated by the *natural gradient*.

### Natural Gradients

Given an objective function parameterized by , let’s say our goal is to find the optimal to maximize the objective function value. A *plain gradient* finds the steepest direction within a small Euclidean distance from the current ; the distance restriction is applied on the parameter space. In other words, we compute the plain gradient with respect to a small change of the absolute value of . The optimal step is:

Differently, *natural gradient* works with a probability distribution space parameterized by , (referred to as “search distribution” in NES paper). It looks for the steepest direction within a small step in the distribution space where the distance is measured by KL divergence. With this constraint we ensure that each update is moving along the distributional manifold with constant speed, without being slowed down by its curvature.

### Estimation using Fisher Information Matrix

But, how to compute precisely? By running Taylor expansion of at , we get:

where

Finally we have,

where is called the **Fisher Information Matrix** and it is the covariance matrix of since .

The solution to the following optimization problem:

can be found using a Lagrangian multiplier,

where only extracts the direction of the optimal moving step on , ignoring the scalar .

*Fig. 4. The natural gradient samples (black solid arrows) in the right are the plain gradient samples (black solid arrows) in the left multiplied by the inverse of their covariance. In this way, a gradient direction with high uncertainty (indicated by high covariance with other samples) are penalized with a small weight. The aggregated natural gradient (red dash arrow) is therefore more trustworthy than the natural gradient (green solid arrow). (Image source: additional annotations on Fig 2 in NES paper)*

### NES Algorithm

The fitness associated with one sample is labeled as and the search distribution over is parameterized by . NES is expected to optimize the parameter to achieve maximum expected fitness:

Using the same log-likelihood trick in REINFORCE:

Besides natural gradients, NES adopts a couple of important heuristics to make the algorithm performance more robust.

- NES applies
**rank-based fitness shaping**, that is to use the*rank*under monotonically increasing fitness values instead of using directly. Or it can be a function of the rank (“utility function”), which is considered as a free parameter of NES. - NES adopts
**adaptation sampling**to adjust hyperparameters at run time. When changing , samples drawn from are compared with samples from using [Mann-Whitney U-test(https://en.wikipedia.org/wiki/Mann%E2%80%93Whitney_U_test)]; if there shows a positive or negative sign, the target hyperparameter decreases or increases by a multiplication constant. Note the score of a sample has importance sampling weights applied .

## Applications: ES in Deep Reinforcement Learning

### OpenAI ES for RL

The concept of using evolutionary algorithms in reinforcement learning can be traced back long ago, but only constrained to tabular RL due to computational limitations.

Inspired by NES, researchers at OpenAI (Salimans, et al. 2017) proposed to use NES as a gradient-free black-box optimizer to find optimal policy parameters that maximizes the return function . The key is to add Gaussian noise $\epsilon$ on the model parameter $\theta$ and then use the log-likelihood trick to write it as the gradient of the Gaussian pdf. Eventually only the noise term is left as a weighting scalar for measured performance.

Let’s say the current parameter value is (the added hat is to distinguish the value from the random variable ). The search distribution of is designed to be an isotropic multivariate Gaussian with a mean and a fixed covariance matrix ,

The gradient for update is:

In one generation, we can sample many and evaluate the fitness *in parallel*. One beautiful design is that no large model parameter needs to be shared. By only communicating the random seeds between workers, it is enough for the master node to do parameter update. This approach is later extended to adaptively learn a loss function; see my previous post on Evolved Policy Gradient.

*Fig. 5. The algorithm for training a RL policy using evolution strategies. (Image source: ES-for-RL paper)*

To make the performance more robust, OpenAI ES adopts virtual batch normalization (BN with mini-batch used for calculating statistics fixed), mirror sampling (sampling a pair of for evaluation), and fitness shaping.

### Exploration with ES

Exploration (vs exploitation) is an important topic in RL. The optimization direction in the ES algorithm above is only extracted from the cumulative return . Without explicit exploration, the agent might get trapped in a local optimum.

Novelty-Search ES (**NS-ES**; Conti et al, 2018) encourages exploration by updating the parameter in the direction to maximize the *novelty* score. The novelty score depends on a domain-specific behavior characterization function . The choice of is specific to the task and seems to be a bit arbitrary; for example, in the Humanoid locomotion task in the paper, is the final location of the agent.

- Every policy’s is pushed to an archive set .
- Novelty of a policy is measured as the k-nearest neighbor score between and all other entries in . (The use case of the archive set sounds quite similar to episodic memory.)

The ES optimization step relies on the novelty score instead of fitness:

NS-ES maintains a group of independently trained agents (“meta-population”), and picks one to advance proportional to the novelty score. Eventually we select the best policy. This process is equivalent to ensembling; also see the same idea in SVPG.

where is the number of Gaussian perturbation noise vectors and is the learning rate.

NS-ES completely discards the reward function and only optimizes for novelty to avoid deceptive local optima. To incorporate the fitness back into the formula, another two variations are proposed.

**NSR-ES**:

**NSRAdapt-ES (NSRA-ES)**: the adaptive weighting parameter initially. We start decreasing if performance stays flat for a number of generations. Then when the performance starts to increase, we stop decreasing but increase it instead. In this way, fitness is preferred when the performance stops growing but novelty is preferred otherwise.

*Fig. 6. (Left) The environment is Humanoid locomotion with a three-sided wall which plays a role as a deceptive trap to create local optimum. (Right) Experiments compare ES baseline and other variations that encourage exploration. (Image source: NS-ES paper)*

### CEM-RL

*Fig. 7. Architectures of the (a) CEM-RL and (b) ERL algorithms (Image source: CEM-RL paper)*

The CEM-RL method (Pourchot & Sigaud, 2019) combines Cross Entropy Method (CEM) with either DDPG or TD3. CEM here works pretty much the same as the simple Gaussian ES described above and therefore the same function can be replaced using CMA-ES. CEM-RL is built on the framework of *Evolutionary Reinforcement Learning* (*ERL*; Khadka & Tumer, 2018) in which the standard EA algorithm selects and evolves a population of actors and the rollout experience generated in the process is then added into reply buffer for training both RL-actor and RL-critic networks.

Workflow:

- 1) The mean actor of the CEM population is is initialized with a random actor network.
- 2) The critic network is initialized too, which will be updated by DDPG/TD3.
- 3) Repeat until happy:
- a. Sample a population of actors .
- b. Half of the population is evaluated. Their fitness scores are used as the cumulative reward and added into replay buffer.
- c. The other half are updated together with the critic.
- d. The new and is computed using top performing elite samples. CMA-ES can be used for parameter update too.

## Extension: EA in Deep Learning

(This section is not on evolution strategies, but still an interesting and relevant reading.)

The *Evolutionary Algorithms* have been applied on many deep learning problems. POET (Wang et al, 2019) is a framework based on EA and attempts to generate a variety of different tasks while the problems themselves are being solved. POET has been introduced in my last post on meta-RL. Evolutionary Reinforcement Learning (ERL) is another example; See Fig. 7 (b).

Below I would like to introduce two applications in more detail, *Population-Based Training (PBT)* and *Weight-Agnostic Neural Networks (WANN)*.

### Hyperparameter Tuning: PBT

*Fig. 8. Paradigms of comparing different ways of hyperparameter tuning. (Image source: PBT paper)*

Population-Based Training (Jaderberg, et al, 2017), short for **PBT** applies EA on the problem of hyperparameter tuning. It jointly trains a population of models and corresponding hyperparameters for optimal performance.

PBT starts with a set of random candidates, each containing a pair of model weights initialization and hyperparameters, . Every sample is trained in parallel and asynchronously evaluates its own performance periodically. Whenever a member deems ready (i.e. after taking enough gradient update steps, or when the performance is good enough), it has a chance to be updated by comparing with the whole population:

: When this model is under-performing, the weights could be replaced with a better performing model.`exploit()`

: If the model weights are overwritten,`explore()`

`explore`

step perturbs the hyperparameters with random noise.

In this process, only promising model and hyperparameter pairs can survive and keep on evolving, achieving better utilization of computational resources.

*Fig. 9. The algorithm of population-based training. (Image source: PBT paper)*

### Network Topology Optimization: WANN

*Weight Agnostic Neural* Networks (short for **WANN**; Gaier & Ha 2019) experiments with searching for the smallest network topologies that can achieve the optimal performance without training the network weights. By not considering the best configuration of network weights, WANN puts much more emphasis on the architecture itself, making the focus different from NAS. WANN is heavily inspired by a classic genetic algorithm to evolve network topologies, called *NEAT* (“Neuroevolution of Augmenting Topologies”; Stanley & Miikkulainen 2002).

The workflow of WANN looks pretty much the same as standard GA:

- Initialize: Create a population of minimal networks.
- Evaluation: Test with a range of
*shared*weight values. - Rank and Selection: Rank by performance and complexity.
- Mutation: Create new population by varying best networks.

*Fig. 10. mutation operations for searching for new network topologies in WANN (Image source: WANN paper)*

At the “evaluation” stage, all the network weights are set to be the same. In this way, WANN is actually searching for network that can be described with a minimal description length. In the “selection” stage, both the network connection and the model performance are considered.

*Fig. 11. Performance of WANN found network topologies on different RL tasks are compared with baseline FF networks commonly used in the literature. “Tuned Shared Weight” only requires adjusting one weight value. (Image source: WANN paper)*

As shown in Fig. 11, WANN results are evaluated with both random weights and shared weights (single weight). It is interesting that even when enforcing weight-sharing on all weights and tuning this single parameter, WANN can discover topologies that achieve non-trivial good performance.

Cited as:

```
@article{weng2019ES,
title = "Evolution Strategies",
author = "Weng, Lilian",
journal = "lilianweng.github.io/lil-log",
year = "2019",
url = "https://lilianweng.github.io/lil-log/2019/09/05/evolution-strategies.html"
}
```

## References

[1] Nikolaus Hansen. “The CMA Evolution Strategy: A Tutorial” arXiv preprint arXiv:1604.00772 (2016).

[2] Marc Toussaint. Slides: “Introduction to Optimization”

[3] David Ha. “A Visual Guide to Evolution Strategies” blog.otoro.net. Oct 2017.

[4] Daan Wierstra, et al. “Natural evolution strategies.” IEEE World Congress on Computational Intelligence, 2008.

[5] Agustinus Kristiadi. “Natural Gradient Descent” Mar 2018.

[6] Razvan Pascanu & Yoshua Bengio. “Revisiting Natural Gradient for Deep Networks.” arXiv preprint arXiv:1301.3584 (2013).

[7] Tim Salimans, et al. “Evolution strategies as a scalable alternative to reinforcement learning.” arXiv preprint arXiv:1703.03864 (2017).

[8] Edoardo Conti, et al. “Improving exploration in evolution strategies for deep reinforcement learning via a population of novelty-seeking agents.” NIPS. 2018.

[9] Aloïs Pourchot & Olivier Sigaud. “CEM-RL: Combining evolutionary and gradient-based methods for policy search.” ICLR 2019.

[10] Shauharda Khadka & Kagan Tumer. “Evolution-guided policy gradient in reinforcement learning.” NIPS 2018.

[11] Max Jaderberg, et al. “Population based training of neural networks.” arXiv preprint arXiv:1711.09846 (2017).

[12] Adam Gaier & David Ha. “Weight Agnostic Neural Networks.” arXiv preprint arXiv:1906.04358 (2019).