AI Logic

Hyperparameter Optimization

Hyperband

Updated:

How Hyperband works. On the left, one run of Successive Halving (bracket s = 4): from bottom to top, 81 candidates are each trained for 1 epoch and the top 27 are kept; then 27 candidates for 3 epochs, 9 for 9 epochs, and 3 for 27 epochs, tripling the epochs while cutting the candidates to a third, and the last one is trained for 81 epochs. On the right, a table of "number of candidates × epochs" for the 5 brackets (s = 4 to 0) that Hyperband runs; s = 0 trains 5 candidates for 81 epochs each, the same as random search.

What Is Hyperband?

Hyperband is a search method that trains randomly chosen hyperparameter candidates a little at a time, stops poorly performing candidates early, and gives more compute only to the survivors. It was proposed by Li et al. (posted on arXiv in 2016, published in JMLR in 2018).

It builds on Successive Halving by Jamieson and Talwalkar (2015). Successive Halving gives many candidates a small amount of training time (such as epochs; the paper calls this a "resource"), discards the worse half, and gives the remaining candidates more resource, repeating until one remains. The more promising a candidate, the exponentially more resource it receives (left side of the figure at the top).

However, Successive Halving has a problem: you must decide how many candidates to start with. Even with the same compute budget, the result depends on whether you try many candidates briefly or few candidates for longer, and which is better is not known in advance. Hyperband removes this choice by trying many combinations of "number of candidates" and "resource per candidate" (right side of the figure at the top).

Compared with random search, the way candidates are chosen (at random) is the same; only the way compute is allocated differs. In the paper's words, it is random search sped up by "adaptive resource allocation" and "early stopping".

Theory (Successive Halving and the Hyperband Procedure)

Hyperband has only two inputs: the maximum resource RR given to one candidate (e.g., 81 epochs), and η\eta (default 3), which sets the fraction kept in each round of selection. With η=3\eta = 3, each round keeps the top third and triples the resource of the survivors (this generalizes the "half" of the original Successive Halving to 1/η1/\eta).

Successive Halving (one bracket) takes the number of candidates nn and the initial resource rr, and repeats the following for i=0,1,…,si = 0, 1, \dots, s (lines 3–9 of Algorithm 1).

  1. Choose nn candidates at random (only the first time).
  2. Train each of the ni=⌊n η−i⌋n_i = \lfloor n\,\eta^{-i} \rfloor remaining candidates up to resource ri=r ηir_i = r\,\eta^{i}, and measure the validation loss.
  3. Keep only the top ⌊ni/η⌋\lfloor n_i / \eta \rfloor with the smallest loss.

Hyperband runs this Successive Halving smax⁡+1s_{\max} + 1 times with different combinations of the number of candidates and the initial resource (lines 1–2 of Algorithm 1).

smax⁡=⌊log⁡ηR⌋,B=(smax⁡+1) Rs_{\max} = \lfloor \log_\eta R \rfloor, \qquad B = (s_{\max} + 1)\,R n=⌈BR⋅ηss+1⌉,r=R η−s(s=smax⁡,smax⁡−1,…,0)n = \left\lceil \frac{B}{R} \cdot \frac{\eta^{s}}{s + 1} \right\rceil, \qquad r = R\,\eta^{-s} \qquad (s = s_{\max}, s_{\max} - 1, \dots, 0)

The larger ss is, the more candidates a bracket tries very briefly and the more aggressively it stops them. The bracket with s=0s = 0 trains a few candidates all the way to RR, so it is random search itself. Each bracket uses roughly the same resource BB. Finally, the candidate with the smallest loss seen so far is returned as the answer.

With R=81R = 81 and η=3\eta = 3, the brackets are as follows ("number of candidates × epochs per candidate"; lower rows are later rungs).

Rung iis=4s = 4s=3s = 3s=2s = 2s=1s = 1s=0s = 0
081 × 134 × 315 × 98 × 275 × 81
127 × 311 × 95 × 272 × 81
29 × 93 × 271 × 81
33 × 271 × 81
41 × 81

The table above shows values computed with the formulas of Algorithm 1. Table 1 of the paper (arXiv v4 and the JMLR version) lists the initial numbers of candidates for s=3,2,1s = 3, 2, 1 as 27, 9, and 6, which do not match the formula values (34, 15, 8). The values for s=4s = 4 and s=0s = 0 match.

How It Works and Why It Is Effective

Hyperband is fast because many bad candidates can be identified as bad after only brief training. Most randomly chosen candidates are poor settings, so training all of them to completion is very wasteful. Successive Halving weeds out unpromising candidates with little resource and gives the remaining promising ones exponentially more resource.

As an analogy, it is like an audition where the first round looks at everyone for one minute each, the second round looks at the survivors for three minutes each, and the final round looks at a few people at length. Compared with watching everyone at length from the start, many more people can be judged in the same time.

However, how well brief training reveals good and bad differs by problem (Figure 2 in the paper).

  • Problems where differences show up quickly even with brief training: trying many candidates briefly and stopping aggressively (brackets with large ss) pays off.
  • Problems where differences only show up after long training: trying few candidates for longer (brackets with small ss) is safer.

Since you cannot know in advance which case applies, Hyperband runs all brackets as "insurance." The paper's theoretical analysis shows that the extra resource paid for this insurance is only a logarithmic factor compared with Successive Halving using the single best bracket (Section 5.3.3).

Experimental Results

The paper compares Hyperband with the Bayesian optimization methods SMAC, TPE, and Spearmint, with random search, and with random search using twice the budget (random 2×).

LeNet on MNIST (Section 3.3): running the 5 brackets with R=81R = 81 epochs and η=3\eta = 3 separately, the best was s=3s = 3; neither s=4s = 4, which stops most aggressively, nor s=0s = 0 (random search), which does not stop at all, was the best. Hyperband performed almost as well as the best bracket and beat random search.

Convolutional networks for image classification (Section 4.1): on CIFAR-10, MRBI, and SVHN, the number of training iterations was used as the resource (1 unit = 100 mini-batches, R=300R = 300 or 600, η=4\eta = 4), and each method was given a budget of 50R50R.

DatasetResult
CIFAR-10Hyperband reached good settings more than 10× faster than the other methods compared
MRBIMore than 10× faster than the standard methods and 5× faster than SMAC with early stopping
SVHNHyperband found good settings quickly, but Bayesian optimization was on par, and SMAC with early stopping did better

Across the three datasets, only Hyperband and SMAC with early stopping consistently beat random search with twice the budget. Hyperband was reported to be more than 20× faster than random search, and its first result at a budget of 5R5R often matched the other methods' results at 50R50R.

Kernel-based classification on CIFAR-10 (Section 4.2.2): in an experiment using the amount of training data as the resource (1 unit = 100 samples, R=400R = 400, η=4\eta = 4), Hyperband evaluated more than 250 candidates in its first bracket (about 20 minutes) and was more than 30× faster than Bayesian optimization and 70× faster than random search. The paper explains that because training time grows with the square of the data size, reducing the resource saved a great deal.

The speedup over random search ranged from 6× to 70× across all experiments. The paper explains this range by three factors: how training time scales with the resource, the setup overhead per candidate, and how hard good settings are to find (the number of dimensions searched).

Caveats

It is less effective on problems where performance after brief training disagrees with performance after long training. For example, settings with slow learning rate decay or networks with many layers may perform poorly at first but well at the end. Such candidates tend to be stopped in early rungs, and the paper also lists fairly comparing candidates with very different convergence speeds as future work.

It does not speed things up if the per-candidate setup overhead is large relative to training time. Time for initializing, loading, and validating a model does not shrink when training is shortened. In the paper's experiment on 117 datasets, many datasets finished training in seconds, so initialization overhead was relatively large and there was no notable speedup.

Also keep the following in mind.

  • Set the maximum resource RR to fit the problem: for neural networks, the number of epochs you would normally train is a good guide. A small RR gives results quickly but weakens the ability to tell good candidates from bad.
  • Use η\eta = 3 or 4: the paper says results are not very sensitive to η\eta and recommends 3 or 4 in practice. In the paper's experiments, the guideline is to choose it so that there are about 5 brackets (at least 3).
  • Avoid hyperparameters whose optimum should change with the resource: when the amount of data is the resource, hyperparameters whose optimum depends on the data size, such as the maximum depth of a decision tree, make performance at small resources unreliable (Section 4.4.3).
  • Make training resumable across rungs: saving the models trained in the previous rung and continuing from there in the next rung reduces waste.

Comparison with Other Search Methods

The table compares Hyperband 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
Successive HalvingStops runs early based on intermediate results (points chosen at random)EasyThe right aggressiveness of stopping is roughly known
HyperbandStops runs early based on intermediate results (tries many levels of aggressiveness)Easy (can be split by bracket)A 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 Bayesian optimization are less competitors than methods that improve different parts. Bayesian optimization improves "which candidate to try next," while Hyperband improves "how much compute to give each candidate." The paper also says there is value in combining early stopping with smart candidate selection, and BOHB is one such combination.

Rough guidelines for choosing:

  • If a few epochs give a rough idea of good and bad, use Hyperband rather than random search: with the same budget, it can try far more candidates.
  • If aggressive stopping is known to be safe, Successive Halving with only the most aggressive bracket is enough: in many of the paper's experiments, repeating only the s=4s = 4 bracket gave better results than Hyperband. But which bracket is best is not known in advance, so use Hyperband when unsure.
  • If one training run is expensive and intermediate results are unreliable, consider Bayesian optimization.

PyTorch example

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

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


def get_hyperparameter_configuration(n, rng):
    """Draw n candidates independently at random (learning rate uniform on a log scale)"""
    return [{"lr": math.exp(rng.uniform(math.log(1e-4), math.log(1e-1))),
             "hidden": rng.choice([32, 64, 128, 256])} for _ in range(n)]


def run_then_return_val_loss(state, epochs):
    """Train the candidate up to epoch `epochs` (resuming from the previous rung) and return the validation loss"""
    if "model" not in state:
        state["model"] = nn.Sequential(nn.Linear(20, state["cfg"]["hidden"]), nn.ReLU(), nn.Linear(state["cfg"]["hidden"], 2))
        state["opt"] = torch.optim.SGD(state["model"].parameters(), lr=state["cfg"]["lr"], momentum=0.9)
        state["done"] = 0
    model, opt, loss_fn = state["model"], state["opt"], nn.CrossEntropyLoss()
    model.train()
    for _ in range(int(epochs) - state["done"]):                 # Train only the missing epochs
        for xb, yb in zip(X_train.split(64), y_train.split(64)):
            opt.zero_grad()
            loss_fn(model(xb), yb).backward()
            opt.step()
    state["done"] = int(epochs)
    model.eval()
    with torch.no_grad():
        return loss_fn(model(X_val), y_val).item()


def hyperband(R=27, eta=3, seed=0):
    """Algorithm 1 of Li et al. (2018)"""
    rng = random.Random(seed)
    s_max = int(math.log(R) / math.log(eta) + 1e-9)
    B = (s_max + 1) * R
    best = (float("inf"), None)
    for s in range(s_max, -1, -1):                                 # Outer loop: vary the bracket (aggressiveness of stopping)
        n = math.ceil(B / R * eta ** s / (s + 1))
        r = R * eta ** (-s)
        T = [{"cfg": c} for c in get_hyperparameter_configuration(n, rng)]
        for i in range(s + 1):                                     # Inner loop: Successive Halving
            n_i = math.floor(n * eta ** (-i))
            r_i = r * eta ** i
            losses = [run_then_return_val_loss(t, r_i) for t in T]
            for loss, t in zip(losses, T):
                if loss < best[0]:
                    best = (loss, t["cfg"])
            k = max(1, n_i // eta)
            T = [t for _, t in sorted(zip(losses, T), key=lambda p: p[0])[:k]]   # Keep the top 1/η
    return best


print(hyperband())

FAQ

Q. Can only the number of epochs be used as the resource?
A.

No. Besides the number of training iterations (epochs), the paper gives examples using training time, the fraction of the data used, and the number of features as the resource. Anything works as long as performance after short (small) training gives a clue about how good a candidate is after full training.

Q. How does it differ from using Successive Halving alone?
A.

Successive Halving fixes a single initial number of candidates (that is, a single aggressiveness of stopping). Hyperband repeats Successive Halving with many such numbers, so it can be used without knowing in advance which aggressiveness is best. In exchange, compared with the case where the best aggressiveness is known, the required compute grows by about a logarithmic factor.

Q. What value should η be?
A.

The paper recommends 3 or 4. A larger η\eta discards more candidates per round, so results come sooner, but the number of brackets decreases. In the paper's experiments, η\eta is chosen so that there are about 5 brackets.

References

  1. L. Li, K. Jamieson, G. DeSalvo, A. Rostamizadeh and A. Talwalkar, "Hyperband: A Novel Bandit-Based Approach to Hyperparameter Optimization," Journal of Machine Learning Research, 18(185):1–52, 2018. arXiv:1603.06560.
  2. K. Jamieson and A. Talwalkar, "Non-stochastic Best Arm Identification and Hyperparameter Optimization," arXiv:1502.07943, 2015.
  3. J. Bergstra and Y. Bengio, "Random Search for Hyper-Parameter Optimization," Journal of Machine Learning Research, vol. 13, pp. 281–305, 2012.