Black-Box Optimization in RL
local graph
Chapter 17 — Black-Box Optimization in RL
Section titled “Chapter 17 — Black-Box Optimization in RL”In this chapter, we will change our perspective on reinforcement learning (RL) training again and switch to the so-called black-box optimizations. These methods are at least a decade old, but recently, several research studies were conducted that showed their applicability to large-scale RL problems and their competitiveness with the value iteration and policy gradient methods. Despite their age, this family of methods is still more efficient in some situations. In particular, this chapter will cover two examples of black-box optimization methods:
- Evolution strategies
- Genetic algorithms
Black-box methods
Section titled “Black-box methods”To begin with, let’s discuss the whole family of black-box methods and how it differs from what we’ve covered so far. Black-box optimization methods are the general approach to the optimization problem, when you treat the objective that you’re optimizing as a black box, without any assumptions about the differentiability, the value function, the smoothness of the objective, and so on. The only requirement that those methods expose is the ability to calculate the fitness function, which should give us the measure of suitability of a particular instance of the optimized entity at hand. One of the simplest examples in this family is random search, which is when you randomly sample the thing you’re looking for (in the case of RL, it’s the policy, π(a|s)), check the fitness of this candidate, and if the result is good enough (according to some reward criteria), then you’re done. Otherwise, you repeat the process again and again. Despite the simplicity and even naivety of this approach, especially when compared to the sophisticated methods that you’ve seen so far, this is a good example to illustrate the idea of black-box methods.
Furthermore, with some modifications, as you will see shortly, this simple approach can be compared in terms of efficiency and the quality of the resulting policies to the deep Q-network (DQN) and policy gradient methods. In addition to that, black-box methods have several very appealing properties:
- They are at least two times faster than gradient-based methods, as we don’t need to perform the backpropagation step to obtain the gradients.
- There are very few assumptions about the optimized objective and the policy that are treated as a black box. Traditional methods struggle with situations when the reward function is non-smooth or the policy contains steps with random choice. All of this is not an issue for black-box methods, as they don’t expect much from the black-box internals.
- The methods can generally be parallelized very well. For example, the aforementioned random search can easily scale up to thousands of central processing units (CPUs) or graphics processing units (GPUs) working in parallel, without any dependency on each other. This is not the case for DQN or policy gradient methods, when you need to accumulate the gradients and propagate the current policy to all parallel workers, which decreases the parallelism.
The downside of the preceding is usually lower sample efficiency. In particular, the naïve random search of the policy, parameterized with the neural network (NN) with half a million parameters, has a very low probability of succeeding.
Evolution strategies
Section titled “Evolution strategies”One subset of black-box optimization methods is called evolution strategies (ES), and it was inspired by the evolution process. With ES, the most successful individuals have the highest influence on the overall direction of the search. There are many different methods that fall into this class, and in this chapter, we will consider the approach taken by the OpenAI researchers Salimans et al. in their paper, Evolution strategies as a scalable alternative to reinforcement learning [Sal+17], published in March 2017.
The underlying idea of ES methods is that on every iteration, we perform random perturbation of our current policy parameters and evaluate the resulting policy fitness function. Then, we adjust the policy weights proportionally to the relative fitness function value.
The concrete method used by Salimans et al. is called covariance matrix adaptation evolution strategy (CMA-ES), in which the perturbation performed is the random noise sampled from the normal distribution with the zero mean and identity variance. Then, we calculate the fitness function of the policy with weights equal to the weights of the original policy plus the scaled noise. Next, according to the obtained value, we adjust the original policy weights by adding the noise multiplied by the fitness function value, which moves our policy toward weights with a higher value of the fitness function. To improve the stability, the update of the weights is performed by averaging the batch of such steps with different random noise.
More formally, this method could be expressed as the following sequence of steps:
- Initialize the learning rate, α, the noise standard deviation, σ, and the initial policy parameters, 𝜃 0.
- For t = 0,1,… perform:
- The sample batch of noise with the shape of the weights from the normal distribution with zero mean and variance of one: 𝜖 1,…,𝜖 n ∼𝒩(0,I)
- Compute returns F i = F(𝜃 t + σ𝜖 i) for i = 1,…,n
- Update weights:
![π (a |s) = P[At = a|St = s]](https://static.packt-cdn.com/products/9781835882702/graphics/Images/eq69.png)
This algorithm is the core of the method presented in the paper, but, as usual in the RL domain, the method alone is not enough to obtain good results. So, the paper includes several tweaks to improve the method, although the core is the same.
Implementing ES on CartPole
Section titled “Implementing ES on CartPole”Let’s implement and test the method from the paper on our fruit fly environment: CartPole. You’ll find the complete example in Chapter17/01_cartpole_es.py.
In this example, we will use the single environment to check the fitness of the perturbed network weights. Our fitness function will be the undiscounted total reward for the episode.
We start with the imports:
import gymnasium as gymimport timeimport numpy as npimport typing as tt
import torchimport torch.nn as nn
from torch.utils.tensorboard.writer import SummaryWriterFrom the import statements, you will notice how self-contained our example is. We’re not using PyTorch optimizers, as we don’t perform backpropagation at all. In fact, we could avoid using PyTorch completely and work only with NumPy, as the only thing we use PyTorch for is to perform a forward pass and calculate the network’s output.
Next, we define the hyperparameters:
MAX_BATCH_EPISODES = 100MAX_BATCH_STEPS = 10000NOISE_STD = 0.001LEARNING_RATE = 0.001
TNoise = tt.List[torch.Tensor]The number of hyperparameters is also small and includes the following values:
- MAX_BATCH_EPISODES and MAX_BATCH_STEPS: The limit of episodes and steps we use for training
- NOISE_STD: The standard deviation, σ, of the noise used for weight perturbation
- LEARNING_RATE: The coefficient used to adjust the weights on the training step
We alse define a type alias for list of tensors containing weights’ noises. It will simplify the code, as we’ll deal with noise a lot.
Now let’s check the network:
class Net(nn.Module): def __init__(self, obs_size: int, action_size: int): super(Net, self).__init__() self.net = nn.Sequential( nn.Linear(obs_size, 32), nn.ReLU(), nn.Linear(32, action_size), nn.Softmax(dim=1) )
def forward(self, x: torch.Tensor) -> torch.Tensor: return self.net(x)The model we’re using is a simple one-hidden-layer NN, which gives us the action to take from the observation. We’re using PyTorch NN machinery here only for convenience, as we need only the forward pass, but it could be replaced by the multiplication of matrices and nonlinearities application.
The evaluate() function plays a full episode using the given policy and returns the total reward and the number of steps:
def evaluate(env: gym.Env, net: Net) -> tt.Tuple[float, int]: obs, _ = env.reset() reward = 0.0 steps = 0 while True: obs_v = torch.FloatTensor(np.expand_dims(obs, 0)) act_prob = net(obs_v) acts = act_prob.max(dim=1)[1] obs, r, done, is_tr, _ = env.step(acts.data.numpy()[0]) reward += r steps += 1 if done or is_tr: break return reward, stepsThe reward will be used as a fitness value, while the count of steps is needed to limit the amount of time we spend on forming the batch. The action selection is performed deterministically by calculating argmax from the network output. In principle, we could do the random sampling from the distribution, but we’ve already performed the exploration by adding noise to the network parameters, so the deterministic action selection is fine here.
In the sample_noise() function, we create random noise with zero mean and unit variance equal to the shape of our network parameters:
def sample_noise(net: Net) -> tt.Tuple[TNoise, TNoise]: pos = [] neg = [] for p in net.parameters(): noise = np.random.normal(size=p.data.size()) noise_t = torch.FloatTensor(noise) pos.append(noise_t) neg.append(-noise_t) return pos, negThe function returns two sets of noise tensors: one with positive noise and another with the same random values taken with a negative sign. These two samples are later used in a batch as independent samples. This technique is known as mirrored sampling and is used to improve the stability of the convergence. In fact, without the negative noise, the convergence becomes very unstable because positive noise pushes weights in a single direction.
The eval_with_noise() function takes the noise array created by sample_noise() and evaluates the network with noise added:
def eval_with_noise(env: gym.Env, net: nn.Module, noise: TNoise, noise_std: float, get_max_action: bool = True, device: torch.device = torch.device("cpu") old_params = net.state_dict() for p, p_n in zip(net.parameters(), noise): p.data += NOISE_STD * p_n r, s = evaluate(env, net) net.load_state_dict(old_params) return r, sTo achieve this, we add the noise to the network’s parameters and call the evaluate function to obtain the reward and number of steps taken. After this, we need to restore the network weights to their original state, which is completed by loading the state dictionary of the network.
The last and the central function of the method is train_step(), which takes the batch with noise and respective rewards and calculates the update to the network parameters by applying the formula:
![π (a |s) = P[At = a|St = s]](https://static.packt-cdn.com/products/9781835882702/graphics/Images/eq69.png)
This can be implemented as follows:
def train_step(net: Net, batch_noise: tt.List[common.TNoise], batch_reward: tt.List[float], writer: SummaryWriter, step_idx: int): weighted_noise = None norm_reward = np.array(batch_reward) norm_reward -= np.mean(norm_reward) s = np.std(norm_reward) if abs(s) > 1e-6: norm_reward /= sIn the beginning, we normalize rewards to have zero mean and unit variance, which improves the stability of the method.
Then, we iterate every pair (noise, reward) in our batch and multiply the noise values with the normalized reward, summing together the respective noise for every parameter in our policy:
for noise, reward in zip(batch_noise, norm_reward): if weighted_noise is None: weighted_noise = [reward * p_n for p_n in noise] else: for w_n, p_n in zip(weighted_noise, noise): w_n += reward * p_nAs a final step, we use the accumulated scaled noise to adjust the network parameters:
m_updates = []for p, p_update in zip(net.parameters(), weighted_noise): update = p_update / (len(batch_reward) * NOISE_STD) p.data += LEARNING_RATE * update m_updates.append(torch.norm(update))writer.add_scalar("update_l2", np.mean(m_updates), step_idx)Technically, what we do here is a gradient ascent, although the gradient was not obtained from backpropagation but from the random sampling (also known as Monte Carlo sampling). This fact was also demonstrated by Salimans et al., where the authors showed that CMA-ES is very similar to the policy gradient methods, differing in just the way that we get the gradients’ estimation.
The preparation before the training loop is simple; we create the environment and the network:
if __name__ == "__main__": writer = SummaryWriter(comment="-cartpole-es") env = gym.make("CartPole-v1")
net = Net(env.observation_space.shape[0], env.action_space.n) print(net)Every iteration of the training loop starts with batch creation, where we sample the noise and obtain rewards for both positive and negated noise:
step_idx = 0while True: t_start = time.time() batch_noise = [] batch_reward = [] batch_steps = 0 for _ in range(MAX_BATCH_EPISODES): noise, neg_noise = sample_noise(net) batch_noise.append(noise) batch_noise.append(neg_noise) reward, steps = eval_with_noise(env, net, noise) batch_reward.append(reward) batch_steps += steps reward, steps = eval_with_noise(env, net, neg_noise) batch_reward.append(reward) batch_steps += steps if batch_steps > MAX_BATCH_STEPS: breakWhen we reach the limit of episodes in the batch, or the limit of the total steps, we stop gathering the data and do a training update.
To perform the update of the network, we call the train_step() function that we’ve already seen:
step_idx += 1m_reward = float(np.mean(batch_reward))if m_reward > 199: print("Solved in %d steps" % step_idx) break
train_step(net, batch_noise, batch_reward, writer, step_idx)The goal of the train_step() function is to scale the noise according to the total reward and then adjust the policy weights in the direction of the averaged noise.
The final steps in the training loop write metrics into TensorBoard and show the training progress on the console:
writer.add_scalar("reward_mean", m_reward, step_idx)writer.add_scalar("reward_std", np.std(batch_reward), step_idx)writer.add_scalar("reward_max", np.max(batch_reward), step_idx)writer.add_scalar("batch_episodes", len(batch_reward), step_idx)writer.add_scalar("batch_steps", batch_steps, step_idx)speed = batch_steps / (time.time() - t_start)writer.add_scalar("speed", speed, step_idx)print("%d: reward=%.2f, speed=%.2f f/s" % ( step_idx, m_reward, speed))CartPole results
Section titled “CartPole results”Training can be started by just running the program without the arguments:
Chapter17$ ./01_cartpole_es.pyNet( (net): Sequential( (0): Linear(in_features=4, out_features=32, bias=True) (1): ReLU() (2): Linear(in_features=32, out_features=2, bias=True) (3): Softmax(dim=1) ))1: reward=10.00, speed=7458.03 f/s2: reward=11.93, speed=8454.54 f/s3: reward=13.71, speed=8677.55 f/s4: reward=15.96, speed=8905.25 f/s5: reward=18.75, speed=9098.71 f/s6: reward=22.08, speed=9220.68 f/s7: reward=23.57, speed=9272.45 f/s...From my experiments, it usually takes ES about 40–60 batches to solve CartPole. The convergence dynamics for the preceding run are shown in Figure 17.1 and Figure 17.2.

Figure 17.1: The maximum reward (left) and policy update (right) for ES on CartPole

Figure 17.2: The mean (left) and standard deviation (right) of reward for ES on CartPole
The preceding graphs looks quite good—being able to solve the environment in 30 seconds is on par with the cross-entropy method from Chapter 4.
ES on HalfCheetah
Section titled “ES on HalfCheetah”In the next example, we will go beyond the simplest ES implementation and look at how this method can be parallelized efficiently using the shared seed strategy proposed by Salimans et al. To show this approach, we will use the HalfCheetah environment using the MuJoCo physics simulator. We already experimented with it in the previous chapter, so if you haven’t installed the gymnasium[mujoco] package, you should do so.
First, let’s discuss the idea of shared seeds. The performance of the ES algorithm is mostly determined by the speed at which we can gather our training batch, which consists of sampling the noise and checking the total reward of the perturbed noise. As our training batch items are independent, we can easily parallelize this step to a large number of workers sitting on remote machines. (That’s a bit similar to the example from Chapter 12, when we gathered gradients from A3C workers.) However, naïve implementation of this parallelization will require a large amount of data to be transferred from the worker process to the central master, which is supposed to combine the noise checked by the workers and perform the policy update. Most of this data is the noise vectors, the size of which is equal to the size of our policy parameters.
To avoid this overhead, a quite elegant solution was proposed by Salimans et al. As noise sampled on a worker is produced by a pseudo-random number generator, which allows us to set the random seed and reproduce the random sequence generated, the worker can transfer to the master only the seed that was used to generate the noise. Then, the master can generate the same noise vector again using the seed. Of course, the seed on every worker needs to be generated randomly to still have a random optimization process. This has the effect of dramatically decreasing the amount of data that needs to be transferred from workers to the master, improving the scalability of the method. For example, Salimans et al. reported linear speed up in optimizations involving 1,440 CPUs in the cloud. In our example, we will look at local parallelization using the same approach.
Implementing ES on HalfCheetah
Section titled “Implementing ES on HalfCheetah”The code is placed in Chapter17/02_cheetah_es.py. As the code significantly overlaps with the CartPole version, we will focus here only on the differences.
We will begin with the worker, which is started as a separate process using the PyTorch multiprocessing wrapper. The worker’s responsibilities are simple: for every iteration, it obtains the network parameters from the master process, and then it performs the fixed number of iterations, where it samples the noise and evaluates the reward. The result with the random seed is sent to the master using the queue.
The following dataclass is used by the worker to send the results of the perturbed policy evaluation to the master process:
@dataclass(frozen=True)class RewardsItem: seed: int pos_reward: float neg_reward: float steps: intIt includes the random seed, the rewards obtained with the positive and negative noise, and the total number of steps we performed in both tests.
On every training iteration, the worker waits for the network parameters to be broadcasted from the master:
def worker_func(params_queue: mp.Queue, rewards_queue: mp.Queue, device: torch.device, noise_std: float): env = make_env() net = Net(env.observation_space.shape[0], env.action_space.shape[0]).to(device) net.eval()
while True: params = params_queue.get() if params is None: break net.load_state_dict(params)The value of None means that the master wants to stop the worker.
The rest is almost the same as the previous example, with the main difference being in the random seed generated and assigned before the noise generation. This allows the master to regenerate the same noise, only from the seed:
for _ in range(ITERS_PER_UPDATE): seed = np.random.randint(low=0, high=65535) np.random.seed(seed) noise, neg_noise = common.sample_noise(net, device=device) pos_reward, pos_steps = common.eval_with_noise(env, net, noise, noise_std, get_max_action=False, device=device) neg_reward, neg_steps = common.eval_with_noise(env, net, neg_noise, noise_std, get_max_action=False, device=device) rewards_queue.put(RewardsItem(seed=seed, pos_reward=pos_reward, neg_reward=neg_reward, steps=pos_steps+neg_steps))Another difference lies in the function used by the master to perform the training step:
def train_step(optimizer: optim.Optimizer, net: Net, batch_noise: tt.List[common.TNoise], batch_reward: tt.List[float], writer: SummaryWriter, step_idx: int, noise_std: float): weighted_noise = None norm_reward = compute_centered_ranks(np.array(batch_reward))In the CartPole example, we normalized the batch of rewards by subtracting the mean and dividing by the standard deviation. According to Salimans et al., better results could be obtained using ranks instead of actual rewards. As ES has no assumptions about the fitness function (which is a reward in our case), we can make any rearrangements in the reward that we want, which wasn’t possible in the case of DQN, for example.
Here, rank transformation of the array means replacing the array with indices of the sorted array. For example, array [0.1, 10, 0.5] will have the rank array [0, 2, 1]. The compute_centered_ranks function takes the array with the total rewards of the batch, calculates the rank for every item in the array, and then normalizes those ranks. For example, an input array of [21.0, 5.8, 7.0] will have ranks [2, 0, 1], and the final centered ranks will be [0.5, -0.5, 0.0].
Another major difference in the training function is the use of PyTorch optimizers:
for noise, reward in zip(batch_noise, norm_reward): if weighted_noise is None: weighted_noise = [reward * p_n for p_n in noise] else: for w_n, p_n in zip(weighted_noise, noise): w_n += reward * p_nm_updates = []optimizer.zero_grad()for p, p_update in zip(net.parameters(), weighted_noise): update = p_update / (len(batch_reward) * noise_std) p.grad = -update m_updates.append(torch.norm(update))writer.add_scalar("update_l2", np.mean(m_updates), step_idx)optimizer.step()To understand why they are used and how this is possible without doing backpropagation, some explanations are required.
First, Salimans et al. showed that the optimization method used by the ES algorithm is very similar to gradient ascent on the fitness function, with the difference being how the gradient is calculated. The way the stochastic gradient descent (SGD) method is usually applied is that the gradient is obtained from the loss function by calculating the derivative of the network parameters with respect to the loss value. This imposes the limitation on the network and loss function to be differentiable, which is not always the case; for example, the rank transformation performed by the ES method is not differentiable.
On the other hand, optimization performed by ES works differently. We randomly sample the neighborhood of our current parameters by adding the noise to them and calculating the fitness function. According to the fitness function change, we adjust the parameters, which pushes our parameters in the direction of a higher fitness function. The result of this is very similar to gradient-based methods, but the requirements imposed on our fitness function are much looser: the only requirement is our ability to calculate it.
However, if we’re estimating some kind of gradient by randomly sampling the fitness function, we can use standard optimizers from PyTorch. Normally, optimizers adjust the parameters of the network using gradients accumulated in the parameters’ grad fields.
Those gradients are accumulated after the backpropagation step, but due to PyTorch’s flexibility, the optimizer doesn’t care about the source of the gradients. So, the only thing we need to do is copy the estimated parameters’ update in the grad fields and ask the optimizer to update them. Note that the update is copied with a negative sign, as optimizers normally perform gradient descent (as in a normal operation, we minimize the loss function), but in this case, we want to do gradient ascent. This is very similar to the actor-critic method we covered in Chapter 12, when the estimated policy gradient is taken with the negative sign, as it shows the direction to improve the policy. The last chunk of differences in the code is taken from the training loop performed by the master process. Its responsibility is to wait for data from worker processes, perform the training update of the parameters, and broadcast the result to the workers. The communication between the master and workers is performed by two sets of queues. The first queue is per-worker and is used by the master to send the current policy parameters to use. The second queue is shared by the workers and is used to send the already mentioned RewardItem structure with the random seed and rewards:
params_queues = [mp.Queue(maxsize=1) for _ in range(PROCESSES_COUNT)]rewards_queue = mp.Queue(maxsize=ITERS_PER_UPDATE)workers = []
for params_queue in params_queues: p_args = (params_queue, rewards_queue, device, args.noise_std) proc = mp.Process(target=worker_func, args=p_args) proc.start() workers.append(proc)
print("All started!")optimizer = optim.Adam(net.parameters(), lr=args.lr)At the beginning of the master, we create all those queues, start the worker processes, and create the optimizer.
Every training iteration starts with the network parameters being broadcast to the workers:
for step_idx in range(args.iters): params = net.state_dict() for q in params_queues: q.put(params)Then, in the loop, the master waits for enough data to be obtained from the workers:
t_start = time.time()batch_noise = []batch_reward = []results = 0batch_steps = 0while True: while not rewards_queue.empty(): reward = rewards_queue.get_nowait() np.random.seed(reward.seed) noise, neg_noise = common.sample_noise(net) batch_noise.append(noise) batch_reward.append(reward.pos_reward) batch_noise.append(neg_noise) batch_reward.append(reward.neg_reward) results += 1 batch_steps += reward.steps
if results == PROCESSES_COUNT * ITERS_PER_UPDATE: break time.sleep(0.01)Every time a new result arrives, we reproduce the noise using the random seed.
As the last step in the training loop, we call the train_step() function:
train_step(optimizer, net, batch_noise, batch_reward, writer, step_idx, args.noise_std)You’ve already seen this function, which calculates the update from the noise and rewards, and calls the optimizer to adjust the weights.
HalfCheetah results
Section titled “HalfCheetah results”The code supports the optional —dev flag, but from my experiments, I got a slowdown if GPU was enabled: without GPU, the average speed was 20-21k observations per second, but with CUDA, it was just 9k. This might look counter-intuitive, but we can explain this with the very small network and batch size of a single observation. Potentially, we might decrease the gap (or even get some speedup) with a higher batch size, but it will complicate our code.
During the training, we show the mean reward, the speed of training (in observations per second), and two timing values (showing how long it took to gather data and perform the training step):
$ ./02_cheetah_es.pyNet( (mu): Sequential( (0): Linear(in_features=17, out_features=64, bias=True) (1): Tanh() (2): Linear(in_features=64, out_features=6, bias=True) (3): Tanh() ))All started!0: reward=-505.09, speed=17621.60 f/s, data_gather=6.792, train=0.0181: reward=-440.50, speed=20609.56 f/s, data_gather=5.815, train=0.0072: reward=-383.76, speed=20568.74 f/s, data_gather=5.827, train=0.0073: reward=-326.02, speed=20413.63 f/s, data_gather=5.871, train=0.0074: reward=-259.58, speed=20181.74 f/s, data_gather=5.939, train=0.0075: reward=-198.80, speed=20496.81 f/s, data_gather=5.848, train=0.0076: reward=-113.22, speed=20467.71 f/s, data_gather=5.856, train=0.007The dynamics of the training show very quick policy improvement in the beginning: in just 100 updates, which is 9 minutes of training, the agent was able to reach the score of 1,500-1,600. After 30 minutes, the peak reward was 2,833; but with more training, the policy was degrading.
The maximum, mean, and standard deviation of reward are shown in Figure 17.3 and Figure 17.4.

Figure 17.3: The maximum reward (left) and policy update (right) for ES on HalfCheetah

Figure 17.4: The mean (left) and standard deviation (right) of reward for ES on HalfCheetah
Genetic algorithms
Section titled “Genetic algorithms”Another popular class of black-box methods is genetic algorithms (GAs). It is a large family of optimization methods with more than two decades of history behind it and a simple core idea of generating a population of N individuals (concrete model parameters), each of which is evaluated with the fitness function. Then, some subset of top performers is used to produce the next generation of the population (this process is called mutation). This process is repeated until we’re satisfied with the performance of our population.
There are a lot of different methods in the GA family, for example, how to perform the mutation of the individuals for the next generation or how to rank the performers. Here, we will consider the simple GA method with some extensions, published in the paper by Such et al., called Deep neuroevolution: Genetic algorithms are a competitive alternative for training deep neural networks for reinforcement learning [Suc+17].
In this paper, the authors analyzed the simple GA method, which performs Gaussian noise perturbation of the parent’s weights to perform mutation. On every iteration, the top performer was copied without modification. In an algorithm form, the steps of a simple GA method can be written as follows:
- Initialize the mutation power, σ, the population size, N, the number of selected individuals, T, and the initial population, P 0, with N randomly initialized policies and their fitness: F 0 = {F(P i 0)|i = 1…N}
- For generation g = 1…G:
- Sort generation P n−1 in the descending order of the fitness function value F g−1
- Copy elite P 1 g = P 1 g−1,F 1 g = F 1 g−1
- For individual i = 2…N:
- Choose the k: random parent from 1…T
- Sample 𝜖 ∼𝒩(0,I)
- Mutate the parent: P i g = P i g−1 + σ𝜖
- Get its fitness: F i g = F(P i g)
There have been several improvements to this basic method from the paper [2], which we will discuss later. For now, let’s check the implementation of the core algorithm.
GA on CartPole
Section titled “GA on CartPole”The source code is in Chapter17/03_cartpole_ga.py, and it has a lot in common with our ES example. The difference is in the lack of the gradient ascent code, which was replaced by the network mutation function:
def mutate_parent(net: Net) -> Net: new_net = copy.deepcopy(net) for p in new_net.parameters(): noise = np.random.normal(size=p.data.size()) noise_t = torch.FloatTensor(noise) p.data += NOISE_STD * noise_t return new_netThe goal of the function is to create a mutated copy of the given policy by adding a random noise to all weights. The parent’s weights are kept untouched, as a random selection of the parent is performed with replacement, so this network could be used again later.
The count of hyperparameters is even smaller than with ES and includes the standard deviation of the noise added-on mutation, the population size, and the number of top performers used to produce the subsequent generation:
NOISE_STD = 0.01POPULATION_SIZE = 50PARENTS_COUNT = 10Before the training loop, we create the population of randomly initialized networks and obtain their fitness:
if __name__ == "__main__": env = gym.make("CartPole-v1") writer = SummaryWriter(comment="-cartpole-ga")
gen_idx = 0 nets = [ Net(env.observation_space.shape[0], env.action_space.n) for _ in range(POPULATION_SIZE) ] population = [ (net, common.evaluate(env, net)) for net in nets ]At the beginning of every generation, we sort the previous generation according to its fitness and record statistics about future parents:
while True: population.sort(key=lambda p: p[1], reverse=True) rewards = [p[1] for p in population[:PARENTS_COUNT]] reward_mean = np.mean(rewards) reward_max = np.max(rewards) reward_std = np.std(rewards)
writer.add_scalar("reward_mean", reward_mean, gen_idx) writer.add_scalar("reward_std", reward_std, gen_idx) writer.add_scalar("reward_max", reward_max, gen_idx) print("%d: reward_mean=%.2f, reward_max=%.2f, reward_std=%.2f" % ( gen_idx, reward_mean, reward_max, reward_std)) if reward_mean > 199: print("Solved in %d steps" % gen_idx) breakIn a separate loop over new individuals to be generated, we randomly sample a parent, mutate it, and evaluate its fitness score:
prev_population = populationpopulation = [population[0]]for _ in range(POPULATION_SIZE-1): parent_idx = np.random.randint(0, PARENTS_COUNT) parent = prev_population[parent_idx][0] net = mutate_parent(parent) fitness = common.evaluate(env, net) population.append((net, fitness))gen_idx += 1After starting the implementation, you should see the following (concrete output and count of steps might vary due to randomness in execution):
Chapter17$ ./03_cartpole_ga.py0: reward_mean=29.50, reward_max=109.00, reward_std=27.861: reward_mean=65.50, reward_max=111.00, reward_std=27.612: reward_mean=149.10, reward_max=305.00, reward_std=57.763: reward_mean=175.00, reward_max=305.00, reward_std=47.354: reward_mean=200.50, reward_max=305.00, reward_std=39.98Solved in 4 stepsAs you can see, the GA method is even more efficient than the ES method.
GA tweaks
Section titled “GA tweaks”Such et al. proposed two tweaks to the basic GA algorithm:
- The first, with the name deep GA, aimed to increase the scalability of the implementation. We will implement this later in the GA on HalfCheetah section.
- The second, called novelty search, was an attempt to replace the reward objective with a different metric of the episode. We’ve left this as an exercise for you to try out.
In the example used in the following GA on HalfCheetah section, we will implement the first improvement, whereas the second one is left as an optional exercise.
Deep GA
Section titled “Deep GA”Being a gradient-free method, GA is potentially even more scalable than ES methods in terms of speed, with more CPUs involved in the optimization. However, the simple GA algorithm that you have seen has a similar bottleneck to ES methods: the policy parameters have to be exchanged between the workers. Such et al. (the authors) proposed a trick similar to the shared seed approach but taken to an extreme (as we’re using seeds to track thousands of mutations). They called it deep GA, and at its core, the policy parameters are represented as a list of random seeds used to create this particular policy’s weights.
In fact, the initial network’s weights were generated randomly on the first population, so the first seed in the list defines this initialization. On every population, mutations are also fully specified by the random seed for every mutation. So, the only thing we need to reconstruct the weights is the seeds themselves. In this approach, we need to reconstruct the weights on every worker, but usually, this overhead is much less than the overhead of transferring full weights over the network.
GA on HalfCheetah
Section titled “GA on HalfCheetah”In our final example in this chapter, we will implement the parallelized deep GA on the HalfCheetah environment. The complete code is in 04_cheetah_ga.py. The architecture is very close to the parallel ES version, with one master process and several workers. The goal of every worker is to evaluate the batch of networks and return the result to the master, which merges partial results into the complete population, ranks the individuals according to the obtained reward, and generates the next population to be evaluated by the workers.
Every individual is encoded by a list of random seeds used to initialize the initial network weights and all subsequent mutations. This representation allows very compact encoding of the network, even when the number of parameters in the policy is not very large. For example, in our network with with one hidden layer of 64 neurons, we have 1,542 float values (the input is 17 values and the action is 6 floats, which gives 17 × 64 + 64 + 64 × 6 + 6 = 1542). Every float occupies 4 bytes, which is the same size used by the random seed. So, the deep GA representation proposed by the paper will be smaller up to 1,542 generations in the optimization.
Implementation
Section titled “Implementation”In our example, we will perform parallelization on local CPUs so the amount of data transferred back and forth doesn’t matter much; however, if you have a couple of hundred cores to utilize, the representation might become a significant issue.
The set of hyperparameters is the same as in the CartPole example, with the difference of a larger population size:
NOISE_STD = 0.01POPULATION_SIZE = 2000PARENTS_COUNT = 10WORKERS_COUNT = 6SEEDS_PER_WORKER = POPULATION_SIZE // WORKERS_COUNTMAX_SEED = 2**32 - 1There are two functions used to build the networks based on the seeds given. The first one performs one mutation on the already created policy network:
def mutate_net(net: Net, seed: int, copy_net: bool = True) -> Net: new_net = copy.deepcopy(net) if copy_net else net np.random.seed(seed) for p in new_net.parameters(): noise = np.random.normal(size=p.data.size()) noise_t = torch.FloatTensor(noise) p.data += NOISE_STD * noise_t return new_netThe preceding function can perform the mutation in place or by copying the target network based on arguments (copying is needed for the first generation).
The second function creates the network from scratch using the list of seeds:
def build_net(env: gym.Env, seeds: tt.List[int]) -> Net: torch.manual_seed(seeds[0]) net = Net(env.observation_space.shape[0], env.action_space.shape[0]) for seed in seeds[1:]: net = mutate_net(net, seed, copy_net=False) return netHere, the first seed is passed to PyTorch to influence the network initialization, and subsequent seeds are used to apply network mutations.
The worker function obtains the list of seeds to evaluate and outputs individual OutputItem dataclass items for every result obtained:
@dataclassclass OutputItem: seeds: tt.List[int] reward: float steps: int
def worker_func(input_queue: mp.Queue, output_queue: mp.Queue): env = gym.make("HalfCheetah-v4") cache = {}
while True: parents = input_queue.get() if parents is None: break new_cache = {} for net_seeds in parents: if len(net_seeds) > 1: net = cache.get(net_seeds[:-1]) if net is not None: net = mutate_net(net, net_seeds[-1]) else: net = build_net(env, net_seeds) else: net = build_net(env, net_seeds) new_cache[net_seeds] = net reward, steps = common.evaluate(env, net, get_max_action=False) output_queue.put(OutputItem(seeds=net_seeds, reward=reward, steps=steps)) cache = new_cacheThis function maintains the cache of networks to minimize the amount of time spent recreating the parameters from the list of seeds. This cache is cleared for every generation, as every new generation is created from the current generation winners, so there is only a tiny chance that old networks can be reused from the cache.
The code of the master process is also straightforward:
batch_steps = 0population = []while len(population) < SEEDS_PER_WORKER * WORKERS_COUNT: out_item = output_queue.get() population.append((out_item.seeds, out_item.reward)) batch_steps += out_item.stepsif elite is not None: population.append(elite)population.sort(key=lambda p: p[1], reverse=True)elite = population[0]for worker_queue in input_queues: seeds = [] for _ in range(SEEDS_PER_WORKER): parent = np.random.randint(PARENTS_COUNT) next_seed = np.random.randint(MAX_SEED) s = list(population[parent][0]) + [next_seed] seeds.append(tuple(s)For every generation, we send the current population’s seeds to workers for evaluation and wait for the results. Then, we sort the results and generate the next population based on the top performers. On the master’s side, the mutation is just a seed number generated randomly and appended to the list of seeds of the parent.
Results
Section titled “Results”In this example, we’re using the MuJoCo HalfCheetah environment, which doesn’t have any health checks internally, so every episode takes 2,000 steps. Because of this, every training step requires about a minute, so be patient. After 300 mutation rounds (which took about 7 hours), the best policy was able to get a reward of 6454, which is a great result. If you remember our experiments in the previous chapter, only the SAC method was able to get a higher reward of 7063 on MuJoCo HalfCheetah. Of course, HalfCheetah is not very challenging, but still — very good.
The plots are shown in Figure 17.5 and Figure 17.6.

Figure 17.5: The maximum (left) and mean rewards (right) for GA on HalfCheetah

Figure 17.6: Standard deviation of reward for GA on HalfCheetah
Summary
Section titled “Summary”In this chapter, you saw two examples of black-box optimization methods: evolution strategies and genetic algorithms, which can provide competition for other analytical gradient methods. Their strength lies in good parallelization on a large number of resources and the smaller number of assumptions that they have on the reward function.
In the next chapter, we will take a look at a very important aspect of RL: advanced exploration methods.
Get This Book’s PDF Version and Exclusive Extras
|