AI Logic

Hyperparameter Optimization

Population Based Training

Updated:

Exploit and explore in Population Based Training on a timeline. In the upper graph, the horizontal axis is training progress and the vertical axis is performance, with performance curves for four members; at each of ready 1, 2, and 3, the worst member copies the weights of the best member and its performance jumps up (dashed arrows). The lower table shows each member's learning rate per interval, with colored cells where a member that copied had its learning rate changed to 1.2× or 0.8× the source's value.

Background and Overview

Population Based Training (PBT) is a search method that trains many models with different hyperparameters in parallel; partway through, poorly performing models copy the weights and hyperparameters of better models (exploit), change the copied hyperparameters slightly (explore), and continue training. It was proposed by Jaderberg et al. at DeepMind in 2017.

There are two broad approaches to finding hyperparameters.

  • Parallel search (grid search and random search): train many settings at once and pick the best. It takes only the time of one training run, but the runs do not use each other's results.
  • Sequential optimization (manual tuning, Bayesian optimization): decide the next setting after seeing the previous run's results. It tends to reach good answers, but because training is repeated many times in sequence, it takes a long time.

PBT bridges the two. Like parallel search, it finishes in the same time as a single training run, yet it improves settings during training using information from the population. Moreover, instead of fixing each hyperparameter to a single value, it automatically finds schedules that change as training progresses (e.g., lowering the learning rate partway through).

In the figure at the top of the article, the upper part shows how the performance of four models (members) evolves, and the lower part shows each member's learning rate. At each ready, the worst member copies the best member (dashed arrows) and perturbs the copied learning rate (colored cells).

Theory (The PBT Procedure)

In PBT, a model being trained is called a member, and the set of members is called the population. Each member has weights θ\theta, hyperparameters hh, and its latest performance pp. Each member repeats the following steps until the end of training, without waiting for the other members (Algorithm 1 in the paper).

  1. step: update the weights by one step using the hyperparameters hh. θ←step(θ∣h)\theta \leftarrow \mathrm{step}(\theta \mid h)

  2. eval: measure the current model's performance. p←eval(θ)p \leftarrow \mathrm{eval}(\theta). The performance can be the metric you actually want to improve, such as validation accuracy or BLEU. It does not need to be differentiable.

  3. ready: if enough steps have passed since the last review (enough for gradient-based training to make real progress), go on to steps 4 and 5. Otherwise, return to step 1.

  4. exploit: compare with the performance of other members in the population, and if a member is better than itself, copy its weights and hyperparameters. The paper used two rules:

    • Truncation selection: rank all members by performance; if this member is in the bottom 20%, pick one from the top 20% and copy it.
    • Selection by t-test: pick another member, compare their last 10 performance values with Welch's t-test, and copy if the other is better.
  5. explore: only when a copy happened, change the hyperparameters to start a new exploration.

    • Perturb: multiply each hyperparameter by 1.2 or 0.8.
    • Resample: with some probability, redraw it from the initial distribution.

    After changing them, run eval again, then return to step 1.

  6. When training ends, return the best-performing model in the population.

Exploit and explore closely resemble "selection" and "mutation" in genetic algorithms. The difference is that the weights themselves are not evolved but trained by gradient descent. The result is learning on two timescales: the weights change quickly through gradients, and the hyperparameters change slowly at ready intervals.

How It Works and Why It Is Effective

From the paper's analysis, the reasons PBT works can be summarized in three points.

  • It does not keep spending compute on hopeless runs. Poorly performing members copy good members' weights partway through, so the machines assigned to them are used to continue promising settings. Bad settings that random search would train to the end can be switched out early.
  • Hyperparameters can change during training. The best learning rate or regularization strength can differ between the beginning and the end of training. PBT reviews hyperparameters at every ready, so schedules emerge as a result, such as a decreasing learning rate or dropout that is strengthened or weakened.
  • The gains of lucky members spread through the population. In reinforcement learning, a member that happened to explore its environment well can achieve good performance. By copying its weights, PBT spreads the benefit of that luck to other members.

In a simple example in the paper (Figure 2), two members solve a problem of maximizing a quadratic function; every 4 steps the weaker member copies the stronger one and perturbs it, reaching an optimum that random search could not. Here most of the benefit came from exploit (copying), and explore (perturbing) added only a small extra gain.

As an analogy, it is like several teams working on the same task who periodically show each other their results; a team that is behind takes over the work of the team that is furthest ahead and continues with a slightly different approach.

On the other hand, in the DeepMind Lab experiments (Figure 5 (c)), combining both gave the best results, better than copying only the weights or only reviewing the hyperparameters. Also, retraining from scratch with the hyperparameters PBT found at the end fixed did not match PBT's performance (Figure 5 (d)). The benefit comes not from "finding good fixed values" but from "being able to change them during training."

Experimental Results

The paper compared PBT with training the same number of members without exploit and explore (random search, in the case of reinforcement learning).

Task (section of the paper)MembersHyperparameters searchedWithout PBTWith PBT
15 DeepMind Lab tasks, UNREAL (Section 4.1)40Learning rate, entropy cost, unroll length93% of human106%
4 Atari games, FuN (Section 4.1)80Learning rate, entropy cost, intrinsic reward cost147%181%
6 StarCraft II tasks, A3C (Section 4.1)30Learning rate36%39%
Machine translation WMT 2014 En–De, Transformer (Section 4.2)32Learning rate, rates of 3 kinds of dropoutBLEU 22.3022.65
GAN on CIFAR-10 (Section 4.3)45Learning rates of the discriminator and generatorInception Score 6.456.89

The reinforcement learning values are the average performance of the best member in the population, with human performance as 100%. The machine translation values are BLEU on the WMT 2014 test data (from 23.71 to 24.23 on the validation data newstest2012), and the baseline is a learning rate schedule carefully tuned by hand and with Bayesian optimization. The GAN values are Inception Scores computed with an ImageNet classifier, and the baseline is the best hand-designed schedule, which decays the learning rate exponentially.

Schedules found:

  • In machine translation, it found a learning rate that starts small, jumps up by 3 orders of magnitude, and then decays exponentially, a shape closely resembling human-designed schedules. The dropout rates rose by nearly an order of magnitude, returned to their original values, and then slowly rose by an order of magnitude again — a shape humans would not think of.
  • For the GAN, it found schedules that decrease the learning rate, but the discriminator's decayed more steeply than the human one, and the generator's somewhat more gently.
  • In a DeepMind Lab maze task, the RNN unroll length gradually grew, letting the agent use memory and exceed human performance.

Caveats

It does not work well with a small population. PBT is a greedy method that picks whom to copy based on current performance, so with few members it loses diversity and is easily trapped in local solutions. In the paper's Atari experiments, with 10 or fewer members the variance was large and performance was worse, and it worked stably with 20–40 members. Going larger improved results further, but with diminishing returns.

It only applies to hyperparameters that can change during training. Because exploit copies weights, it cannot target things like the number or width of layers, where a change would make the weights unusable as they are. The paper searched things that can change while training continues, such as the learning rate, entropy cost, dropout rate, and unroll length.

Also keep the following in mind.

  • Make the ready interval long enough for performance differences to mean something. If the interval is too short, comparisons happen before gradient-based training has made enough progress, and noise in performance decides whom to copy. The paper used every 10610^6–10710^7 steps for reinforcement learning, 2,000 steps for machine translation, and 5,000 steps for GANs.
  • Start with truncation selection for copying. In the paper's GAN experiments, truncation selection was slightly better than the method that just compares two members, and preliminary Atari experiments showed the same trend. The paper describes truncation selection as a robust choice.
  • It tends to converge to a single ancestor in the end. In the paper's phylogenetic tree (Figure 6), all final members were descendants of a single initial member. Several promising lineages survived for a long time along the way, but enlarge the population if you want to preserve diversity.
  • The result is a schedule, not fixed hyperparameters. To reproduce the result or use it for another model, trace the lineage and record the whole schedule, not just the final values.

Comparison with Other Search Methods

The table compares PBT with other commonly compared hyperparameter search methods from the same viewpoints.

MethodUses past results?Easy to parallelize?Best suited for
Random searchNoVery easyMany machines; an initial rough search
Bayesian optimizationYes (a surrogate model picks the next point)Needs extra workEach training run is expensive and only a few trials are possible
HyperbandStops runs early based on intermediate resultsEasyA few epochs give a rough idea of good and bad
BOHBYes (a model picks Hyperband's points)EasyWanting the strengths of both Hyperband and Bayesian optimization
PBTCopies good models during trainingParallel by designMany machines, and hyperparameters may change during training

Hyperband and PBT both change how compute is allocated based on intermediate results, but they think differently. Hyperband stops and discards bad candidates, whereas PBT replaces bad members with continuations of good members, keeping the number of machines constant while training continues. And because PBT changes hyperparameters during training, its answer is a schedule.

Rough guidelines for choosing:

  • 20 or more machines can run side by side, and the learning rate and similar settings may change during training: PBT. Its effect has been reported to be especially strong on tasks such as reinforcement learning and GANs, where training is unstable and the optimal hyperparameters change along the way.
  • Few machines, and training can be repeated a few times: Bayesian optimization or BOHB.
  • You want to search architecture such as the number of layers: PBT cannot do this, so use Hyperband, BOHB, or Bayesian optimization.

The PBT framework has also been used to search data augmentation policies (Population Based Augmentation).

PyTorch example

Show code
python
import copy
import random
import torch
import torch.nn as nn

torch.manual_seed(0)
X_train, y_train = torch.randn(2048, 20), torch.randint(0, 2, (2048,))
X_val, y_val = torch.randn(512, 20), torch.randint(0, 2, (512,))


class Member:
    """One member of the population: weights θ, hyperparameters h, performance p"""
    def __init__(self, rng):
        self.h = {"lr": 10 ** rng.uniform(-4, -1), "weight_decay": 10 ** rng.uniform(-6, -3)}
        self.model = nn.Sequential(nn.Linear(20, 64), nn.ReLU(), nn.Dropout(0.1), nn.Linear(64, 2))
        self.opt = torch.optim.SGD(self.model.parameters(), lr=self.h["lr"], momentum=0.9,
                                   weight_decay=self.h["weight_decay"])
        self.p = float("-inf")

    def apply_h(self):
        for g in self.opt.param_groups:          # Swap hyperparameters without stopping training
            g["lr"], g["weight_decay"] = self.h["lr"], self.h["weight_decay"]


def step(m, n_steps=50):
    """θ ← step(θ | h), n_steps times"""
    m.model.train()
    loss_fn = nn.CrossEntropyLoss()
    for _ in range(n_steps):
        idx = torch.randint(0, len(X_train), (64,))
        m.opt.zero_grad()
        loss_fn(m.model(X_train[idx]), y_train[idx]).backward()
        m.opt.step()


def evaluate(m):
    """p ← eval(θ): validation accuracy (need not be differentiable)"""
    m.model.eval()                               # Measure with dropout disabled
    with torch.no_grad():
        return (m.model(X_val).argmax(1) == y_val).float().mean().item()


def exploit_and_explore(population, rng, frac=0.2):
    """Truncation selection (bottom 20% copy the top 20%) + perturb (multiply each h by 1.2 or 0.8)"""
    ranked = sorted(population, key=lambda m: m.p)
    k = max(1, int(len(population) * frac))
    for loser in ranked[:k]:
        winner = rng.choice(ranked[-k:])
        loser.model.load_state_dict(winner.model.state_dict())   # exploit: copy the weights
        loser.opt.load_state_dict(winner.opt.state_dict())       # Also copy the optimizer state
        loser.h = copy.deepcopy(winner.h)                        #          and the hyperparameters
        for name in loser.h:                                     # explore: perturb
            loser.h[name] *= rng.choice([0.8, 1.2])
        loser.apply_h()
        loser.p = evaluate(loser)


def pbt(population_size=20, n_ready=30, seed=0):
    rng = random.Random(seed)
    population = [Member(rng) for _ in range(population_size)]
    for _ in range(n_ready):                     # The paper is asynchronous; here all members run in lockstep for simplicity
        for m in population:
            step(m)
            m.p = evaluate(m)
        exploit_and_explore(population, rng)
    best = max(population, key=lambda m: m.p)
    return best.p, best.h


print(pbt())

FAQ

Q. Does PBT use more machines than random search?
A.

No. They can be compared with the same number of machines. The paper's experiments also compare against random search with the same number of members (machines). PBT just reassigns the machines given to poorly performing members to continue training good members, so the compute and training time are the same as random search, and the results are better.

Q. Do members need to wait for each other?
A.

No. PBT in the paper is asynchronous: at its own ready timing, each member simply reads the other members' latest performance, weights, and hyperparameters. No central coordinating process is needed either. All that is required is to keep each member's performance, weights, and hyperparameters somewhere the other members can read them.

Q. Can it be used together with a learning rate schedule (such as cosine)?
A.

Yes, but PBT is itself a method for finding learning rate schedules. In the paper's machine translation and GAN experiments, the learning rate decay PBT found resembled human-designed schedules or was steeper than them. Whether to rely on a fixed shape such as cosine annealing or leave it to PBT is, in practice, best decided by the number of machines available.

References

  1. M. Jaderberg, V. Dalibard, S. Osindero, W. M. Czarnecki, J. Donahue, A. Razavi, O. Vinyals, T. Green, I. Dunning, K. Simonyan, C. Fernando, and K. Kavukcuoglu, "Population Based Training of Neural Networks," arXiv:1711.09846, 2017.
  2. J. Bergstra and Y. Bengio, "Random Search for Hyper-Parameter Optimization," Journal of Machine Learning Research, vol. 13, pp. 281–305, 2012.