I have started using Genetic Algorithms (GA) in my PhD research. They are a very effective and simple tool used to solve optimisation problems. Using a “natural selection”-like process to explore the solution space, they can quickly arrive at a good candidate solution. The nice thing about GAs is that they are very easy to implement. However, a basic implementation can be a bit slow.

In deep learning (DL), to speed up the computation we make heavy use of GPUs (and in some cases TPUs). A lot of my work has been doing DL with JAX. If you don’t know, JAX is an autograd and XLA library for Python. It allows you to write Python code with the NumPy API that can be compiled, vectorised, and run on GPUs. Inspired by a blog post from Will Whitney outlining a neat way to use jax.vmap to train multiple models at once, I asked myself: could I use the same technique to speed up my GA and run it on the GPU? It turns out, with a few minor caveats, you can. Check out my code on GitHub.

  • What is a GA?
    • A quick overview of what a GA is and how it works
  • SIMD
  • Speeding up GAs with JAX

What is a GA?

A quick overview of what a GA is and how it works.

The GA is inspired by the biological method of evolution through natural selection, where fitter individuals are more likely to pass on their genetic material. There is an initial population of \(N\) candidates. During each iteration of the GA a new population is created by combining and mutating the existing members based on their fitness. An iteration of the algorithm is analogous to a generation.

Each candidate has a genetic representation, a set of “chromosomes” that make up a solution. A basic encoding is simply a binary string comprised of 1s and 0s for each solution variable. We also need a fitness function that can take a solution representation and evaluate how good it is. It will return a scalar value (a single number) to represent how good the solution is; lower is normally better.

With search-based optimisation methods there is a trade-off between exploration and exploitation. For the same “budget”, we can either explore more areas of the solution space in the hope of finding improvement, or we can exploit the local optima we have found and try to make them better. GAs can strike a good balance in the trade-off between exploration and exploitation.

Crossover and Mutation

This is how new members (candidate solutions) are added to the population. The process mimics that of reproduction: two members are selected, exchange genetic material, and create a new child solution. We then apply a mutate operator to the new child. Crossover is how we exploit the search space while mutation drives exploration.

In the case of a basic binary string encoding, the crossover operator just randomly chooses the value of each chromosome from one of the two parents.

Candidate = list[bool]
def crossover(p1: Candidate, p2: Candidate, threshold: float = 0.5) -> Candidate:
    c = p1[:] # Copy
    for i in range(len(p1)):
        if uniform(0, 1) < threshold:
            c[i] = p2[i]
    return c

While the mutate operator can simply randomly flip bits:

def mutate(s: Candidate, mutate_rate: float) -> Candidate:
    for i in range(len(s)):
        if uniform(0, 1) < mutate_rate:
            s[i] = not s[i]
    return s

Having taught undergrads GAs for a few years now, it’s always amusing how invested some of them get in the parent-child analogy; on more than one occasion I have seen code along the lines of crossover(mum, dad).

Parent Selection

This is where the selection part of “natural selection” happens. In a typical GA, parent selection is done so that each candidate is given a probability proportional to its fitness. That is to say, the fitter an individual, the more likely it is to be selected to be a parent. Note that the two parents could be the same.

However, there are alternative methods. For example, in each generation only the best \(n\%\) of solutions in the population can have children and are then sampled uniformly. In fact there are a lot of variations that can be made to a GA: you can adjust the parent selection criteria, scale gene selection based on fitness, decay the mutation rate with each generation, and so on.

Below is a basic implementation that takes the best half of the population and randomly samples from it to create a new generation, while preserving the top half of the previous generation.

population = init_pop()
pop_size = len(population)
mutate_rate = 0.3

for n in NUM_GENERATIONS:
    fitness = [fit_fn(p) for p in population]
    candidates = population[fitness.argsort()[:pop_size // 2]]

    new_sols = []
    for _ in range(pop_size // 2):
        p1, p2 = randint(pop_size // 2), randint(pop_size // 2)
        child = mutate(crossover(candidates[p1], candidates[p2]), mutate_rate)
        new_sols.append(child)

    population = candidates + new_sols

SIMD

Have you ever wondered why deep learning runs on GPUs? It’s all thanks to SIMD. SIMD stands for “single instruction, multiple data” and is one of the four types of parallel processing. SIMD is distinct from the typical way we think about parallel code, i.e. a multi-processor architecture where each core runs its own set of instructions on its own data: “multiple instruction, multiple data (MIMD)”. In the case of SIMD we want to apply the same operation to lots of data. This is normally done through vectorisation of the program: using specific instructions that leverage specialised hardware, we can apply the same instruction to a vector (an array) of data.

Imagine we have a vector and we want to add 1 to every element. In a classic loop we would iterate over every element:

for i in range(len(vector)):
    vector[i] += 1

In this case the processor updates each element in the vector one after the other. Using jax.vmap we can vectorise this operation:

jax.vmap(lambda x: x + 1)(vector)

By using SIMD, rather than the operation taking len(vector) cycles, the hardware can execute it in parallel across vector lanes. Modern CPUs have support for vector operations with their AVX instruction set, and GPUs scale this much further. Thanks to libraries like JAX, it is often straightforward to vectorise code to target SIMD execution.

How does this relate to deep learning? Those neural network layers are mostly made up of operations that look like \(X \cdot W + b\) over very big matrices, which is something GPUs parallelise very well.

Speeding up GAs

So what does all this have to do with GAs? In short, we can use JAX to offload the work to the GPU and jax.vmap to maximise GPU utilisation.

My first step was to jax.jit compile the GA so that it ran on the GPU. Doing so gave only a minimal improvement in performance. After running performance analysis, I could see that overall GPU utilisation was low. Based on Will Whitney’s blog post and my previous experience training multiple models at once, the solution was to use jax.vmap. Looking at the code for the GA above, there are two key places where we can apply vectorisation: the call to the fitness function and the crossover-mutate loop. Applying vmap to the fitness function was an easy update: fitness = jax.vmap(fit_fn)(population). For crossover and mutation it’s a little more involved because of JAX’s functional PRNG handling. I wrote a new function that performs both crossover and mutation so that it can be vectorised:

def mix_and_mutate(mix_key: PRNGKeyArray, mutate_key: PRNGKeyArray, twist: Array, parent):
    # Some JAX tricks to deal with randomness
    mix_key = jax.random.fold_in(mix_key, twist)
    mutate_key = jax.random.fold_in(mutate_key, twist)
    # Mix and mutate step
    child = mix(mix_key, parent[0], parent[1])
    child = mutate(mutate_key, child, rate=self.mutate_rate)
    return child

Putting it all together, the main loop of the GA now looks something like:

for n in NUM_GENERATIONS:
    # Parallel call to fitness function
    fitness = jax.vmap(fit_fn)(population)

    # Select and sample
    candidates = population[fitness.argsort()[:pop_size // 2]]
    parents = jax.random.choice(key, candidates, replace=True, shape=(population_size // 2, 2))

    # Parallel call to mix and mutate
    twists = jnp.arange(population_size // 2, dtype=int) # Needed for per-child PRNG keys
    new_pop = jax.vmap(mix_and_mutate, in_axes=(None, None, 0, 0))(mix_key, mutate_key, twists, parents)

    # Make the new generation
    population = jnp.concatenate([candidates, new_pop])

With these changes, the GA runs on GPU and makes much better use of it. There is still compilation overhead with jax.jit, in part because JAX will unroll the outer Python generation loop. A way around this is to use jax.lax.scan, which compiles the loop into a single XLA step. scan functions similarly to Haskell’s fold or Python’s reduce operator. Per the docs, its Haskell type signature is (c -> a -> (c, b)) -> c -> [a] -> (c, [b]). In plain terms, scan takes as input:

  • A function that accepts a carry object, c, and an element a, returning a new carry and an output b.
  • An initial carry object.
  • A sequence of a values.

It returns a tuple of the final carry and the stacked sequence of b values.

scan applies the function sequentially to every element in the list of a values to produce b values; each time it calls the function it also passes in the carry object returned by the previous call. This allows the function to maintain state across iterations. To use it in our GA, we can update the loop to:

def run_generation(population, _):
    # The same loop body for the GA
    ...
    return new_population, None

population, _ = jax.lax.scan(run_generation, init=population, length=self.generations, xs=None)

Since we are using scan purely to iterate generations, we don’t need per-step outputs (the b values) and return None. The final carry value is the last generation’s population, containing the fittest solutions found.

The Caveats

As I alluded to, there are a few limitations to this approach:

  1. The objective function must be jax.jit compilable. While JAX is expressive and NumPy-style numerical code usually works cleanly, interfacing with existing external solvers or complex non-JAX simulations can be difficult.
  2. Because of how jax.vmap and jax.scan allocate memory, there are limits on population size and generation counts on a single device, though batching or sharding can mitigate this.

For my research I was able to express the fitness function directly in JAX, conditioned on instance input parameters. Adding another layer of jax.vmap over problem instances, I ran 10,000 samples for 1,000 generations with a population of 256 in roughly five minutes.