AI Logic

Hyperparameter Optimization

BOHB

Updated:

How BOHB works. On the left, one run of Successive Halving, the same as in Hyperband: from bottom to top, 81 candidates are each trained for 1 epoch and the top 27 are kept, and the epochs are tripled while the candidates are cut to a third. The only difference from Hyperband is that the 81 candidates at the bottom are chosen by a model. On the right, the procedure for choosing each candidate, from bottom to top: with probability ρ pick at random; otherwise pick the largest budget with enough observations, fit KDE densities l(x) and g(x) to the good and bad groups, draw N_s samples from l′(x), and return the candidate with the largest l(x)/g(x).

Background and Overview

BOHB is a hyperparameter search method that keeps Hyperband's mechanism of stopping bad candidates after short training, but chooses the initial candidates with a Bayesian optimization model instead of at random. The name comes from combining Bayesian Optimization (BO) and Hyperband (HB). It was proposed by Falkner, Klein, and Hutter in 2018 (ICML 2018).

Hyperband and Bayesian optimization each have their strengths and weaknesses.

  • Hyperband: it weeds out many candidates with short training, so it reaches reasonably good settings quickly with little compute. But because it picks candidates at random, it does not learn from earlier results, and as compute grows, its advantage over random search shrinks.
  • Bayesian optimization: it chooses the next candidate from past results, so given time, it approaches the best settings. But it trains every candidate to completion, so early on it is about as slow as random search.

BOHB gets the best of both. The paper reports that it found good solutions more than an order of magnitude faster than Bayesian optimization, and approached the best solutions orders of magnitude faster than Hyperband.

In the figure at the top of the article, the left side is the same early-stopping procedure as Hyperband (one bracket), and the right side is the procedure for choosing initial candidates one at a time (Algorithm 2 in the paper).

Theory (How Candidates Are Chosen)

BOHB's outer procedure is exactly the same as Hyperband's. It sets the minimum bmin⁔b_{\min} and maximum bmax⁔b_{\max} of the budget given to one candidate (such as the number of epochs) and the aggressiveness of stopping η\eta, then runs Successive Halving many times while varying the number of candidates and the initial budget. Successive Halving trains each candidate with budget bb, keeps only the top 1/η1/\eta by performance, and multiplies the budget by η\eta, repeating until it reaches bmax⁔b_{\max} (see the Hyperband article for details).

The only difference is how the initial candidates of each Successive Halving are chosen. Each time BOHB chooses a candidate, it takes the following steps (Algorithm 2 in the paper).

  1. With probability ρ\rho, pick at random and stop. Mixing in random candidates at a fixed rate keeps broad exploration and preserves Hyperband's theoretical guarantees.
  2. Choose the budget bb for building the model. It splits the observations so far by budget and, among budgets with at least Nmin⁔+2N_{\min} + 2 observations, picks the largest one. Nmin⁔N_{\min} is the number of hyperparameters dd plus 1. If no budget has enough, it picks at random.
  3. Fit densities to the good and bad groups. It sorts the NbN_b observations at budget bb by loss, splits them into a good group and a bad group, and builds a probability density for each with kernel density estimation (KDE). The density of candidates whose loss is better than a threshold α\alpha is l(x)l(x), and that of worse candidates is g(x)g(x) (Eq. (2)). l(x)=p(y<α∣x,D),g(x)=p(y>α∣x,D)l(x) = p(y < \alpha \mid x, D), \qquad g(x) = p(y > \alpha \mid x, D) The sizes of the good and bad groups are set with a fraction qq as follows (Eq. (3)). This ensures each group has at least Nmin⁔N_{\min} observations even when there are few. Nb,l=max⁔(Nmin⁔,qā‹…Nb),Nb,g=max⁔(Nmin⁔,Nbāˆ’Nb,l)N_{b,l} = \max(N_{\min}, q \cdot N_b), \qquad N_{b,g} = \max(N_{\min}, N_b - N_{b,l})
  4. Draw NsN_s candidates. They are drawn from l′(x)l'(x), which is l(x)l(x) with its kernel bandwidth widened by a factor of bwb_w. This explores the area around the good group a little more broadly.
  5. Return the candidate with the largest l(x)/g(x)l(x)/g(x). The more likely a candidate is under the good group and the less likely under the bad group, the larger this ratio.

The idea behind steps 3–5 is the same as the Tree-structured Parzen Estimator (TPE, Bergstra et al. 2011). TPE showed that maximizing l(x)/g(x)l(x)/g(x) is equivalent to maximizing expected improvement (EI), the acquisition function of Bayesian optimization. The difference is that TPE builds a 1-D KDE for each hyperparameter, whereas BOHB builds a single multidimensional KDE. This makes it easier to capture interaction effects between hyperparameters.

How It Works and Why It Is Effective

BOHB works well because the Hyperband part and the Bayesian optimization part cover each other's weaknesses.

  • Results at small budgets let it build a model early. Hyperband tries many candidates at small budgets in its first rung. BOHB stores these results as observations too, so it can choose candidates with a small-budget model while large-budget results are still scarce.
  • In the end, it relies on the large-budget model. Rankings at small budgets can disagree with those at large budgets. BOHB uses the model for the largest budget with enough observations, so as the search progresses it can overcome wrong conclusions drawn at small budgets.
  • Mixing in random candidates guarantees convergence even in the worst case. Because random candidates are mixed in at rate ρ\rho, even in the worst case where small-budget results are completely unreliable, BOHB is at most (smax⁔+1)/ρ(s_{\max} + 1)/\rho times slower than random search and is guaranteed to eventually approach the best setting (Section 4.1).
  • KDE is cheap and handles many kinds of values. The cost of a Gaussian process grows with the cube of the number of observations, whereas KDE grows only linearly. Hyperband produces many observations at small budgets, so this cheapness matters. KDE also handles spaces that mix continuous values and categorical choices.

As an analogy, Hyperband is hiring by "giving everyone a short interview and screening them out," while BOHB is hiring by "using past interview records to invite likely hires first." The interview process is the same, but choosing whom to invite more wisely leads to good people sooner.

Parallelization: BOHB pools all machines into one group and assigns free machines to the waiting training jobs with the smallest budgets first. If the current Successive Halving leaves machines idle, it starts the next Successive Halving in parallel. Observations are shared across all Successive Halving runs, so candidates chosen in parallel also benefit from the model. And because the number NsN_s of candidates drawn from the KDE is limited, successively chosen candidates are spread out, reducing the waste of trying similar candidates at the same time.

Experimental Results

The paper compared BOHB with random search, TPE, Gaussian process Bayesian optimization (GP-BO), Hyperband, and others. In all experiments, Ī·\eta for Hyperband and BOHB is 3.

Experiment (section of the paper)What was comparedResult
6 hyperparameters of a fully connected network, 6 OpenML datasets (Section 5.2.2)Time to the best settingHyperband was about 3Ɨ faster than random search. BOHB reached Hyperband's final performance 100Ɨ faster, and its final performance was better than the other Bayesian optimization methods
2 hyperparameters of an SVM (Section 5.2.1)Low-dimensional, continuous problemBOHB was on par with Fabolas and slightly better than Hyperband
Bayesian neural network (Section 5.3)MCMC steps as the budgetBOHB converged faster than Hyperband and TPE, and found better settings on Boston housing
Reinforcement learning (8 PPO hyperparameters, cartpole, Section 5.4)Number of trials as the budgetIt started out the same as Hyperband and finally converged to better settings
16-dimensional synthetic function (Section 5.1)8 continuous, 8 categoricalIt started as fast as Hyperband, and only BOHB converged within the time limit

Image classification on CIFAR-10 (Section 5.5): the search covered four hyperparameters — learning rate, momentum, weight decay, and batch size — of a depth-20 residual network (about 8.5 million parameters) using Shake-Shake and Cutout. With budgets of 22, 66, 200, and 600 epochs, 16 iterations on 19 machines (2 GPUs each), and 33 GPU-days in total, the test error was 2.78% ± 0.09%.

MethodTest errorCompute
Residual network with hyperparameters found by BOHB2.78%33 GPU-days
NAS with reinforcement learning (Zoph & Le 2017)3.65%—
Progressive NAS (Liu et al. 2017)3.41%—
Reinforcement learning (Zoph et al. 2017), evolutionary search (Real et al. 2018)2.4%, 2.1%2,000, 3,150 GPU-days

As the paper itself notes, the networks and regularization differ, so the numbers are not directly comparable, but the result shows how far BOHB gets with little compute.

Caveats

It does not speed things up unless results at the minimum budget bmin⁔b_{\min} give a clue about performance at large budgets. The paper also states that bmin⁔b_{\min} and bmax⁔b_{\max} are the most important inputs and must be set to fit the problem. For example, when training on a subset of the data, the minimum budget should not be "one data point" but enough data to build a meaningful model.

Other methods can win on problems with very many hyperparameters, or on low-dimensional continuous problems. On the paper's synthetic function, at 64 dimensions the noise grew so large that small-budget results stopped helping the model, and TPE and SMAC outperformed BOHB. The paper also notes that on low-dimensional continuous problems such as the 2-D SVM, Gaussian process Bayesian optimization generally does better than KDE.

Also keep the following in mind.

  • It is not very sensitive to its own hyperparameters such as Ī·\eta. Appendix G of the paper reports that varying the random fraction ρ\rho, the number of samples NsN_s, the bandwidth factor bwb_w, and Ī·\eta one at a time, the defaults worked stably on every problem.
  • Adding too many machines yields diminishing returns. On the paper's letter dataset, speed scaled almost linearly with 2–4 machines, and with 32 machines it reached a loss of 10āˆ’210^{-2} about 15Ɨ faster than with 1 machine. With many machines, many random candidates are tried before the first model is built.
  • In later rungs, resuming training from the previous rung reduces waste. As with Hyperband, save the models and add budget to them.
  • A public implementation exists. The paper's authors released it as HpBandSter (the code example below is a small implementation for seeing how the method works).

Comparison with Other Search Methods

The table compares BOHB 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 results (points chosen at random)EasyA 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

Rough guidelines for choosing:

  • A few epochs give a rough idea of good and bad, and a fair amount of compute is available: BOHB. It returns good settings as fast as Hyperband at first, and the more time it gets, the closer it gets to settings better than Hyperband's.
  • The budget is small and a rough result is needed quickly: Hyperband is nearly as good as BOHB. The two differ only when the budget grows.
  • Short-training results are unreliable, very few trials are possible, or the problem is low-dimensional and continuous: Gaussian process Bayesian optimization.
  • Many machines, and hyperparameters may change during training: PBT.

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,))

# Search space: learning rate (log) and hidden width. Both are kept in [0, 1] so a KDE fits easily
def decode(u):
    return {"lr": 10 ** (-4 + 3 * u[0]), "hidden": int(16 + u[1] * 240)}


def train_and_eval(state, epochs):
    """Train the candidate up to epoch `epochs` (resuming from the previous rung) and return the validation loss"""
    if "model" not in state:
        cfg = decode(state["u"])
        state["model"] = nn.Sequential(nn.Linear(20, cfg["hidden"]), nn.ReLU(), nn.Linear(cfg["hidden"], 2))
        state["opt"] = torch.optim.SGD(state["model"].parameters(), lr=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"]):
        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 kde(points):
    """Multivariate Gaussian-kernel KDE (bandwidth by Scott's rule). Returns the density function and bandwidth"""
    pts = torch.tensor(points)
    n, d = pts.shape
    bw = (pts.std(0, unbiased=True).clamp_min(1e-3)) * n ** (-1.0 / (d + 4))
    def pdf(x):
        z = (x[None, :] - pts) / bw
        return torch.exp(-0.5 * (z ** 2).sum(1)).mean() / bw.prod()
    return pdf, pts, bw


def sample_config(D, d, rng, rho=1/3, q=0.15, n_samples=64, bw_factor=3.0):
    """Algorithm 2 of the paper (the values of ρ, q, N_s, b_w are chosen for this example)"""
    n_min = d + 1
    if rng.random() < rho:                                        # Line 1: random with probability ρ
        return [rng.random() for _ in range(d)]
    budgets = [b for b, obs in D.items() if len(obs) >= n_min + 2]
    if not budgets:                                               # Line 3: random if not enough observations
        return [rng.random() for _ in range(d)]
    obs = sorted(D[max(budgets)], key=lambda t: t[1])             # Line 2: largest budget with enough observations
    n_l = max(n_min, int(q * len(obs)))                           # Eq. (3)
    n_g = max(n_min, len(obs) - n_l)
    l, l_pts, l_bw = kde([u for u, _ in obs[:n_l]])               # Line 4: density of the good group l(x)
    g, _, _ = kde([u for u, _ in obs[-n_g:]])                     #         density of the bad group g(x)
    best, best_ratio = None, -1.0
    for _ in range(n_samples):                                    # Line 5: draw from l'(x) (bandwidth Ɨ b_w)
        center = l_pts[rng.randrange(len(l_pts))]
        x = (center + torch.randn(len(center)) * l_bw * bw_factor).clamp(0, 1)
        ratio = (l(x) / g(x).clamp_min(1e-32)).item()
        if ratio > best_ratio:                                    # Line 6: the one maximizing l(x)/g(x)
            best, best_ratio = x.tolist(), ratio
    return best


def bohb(b_max=27, eta=3, d=2, n_iter=2, seed=0):
    rng = random.Random(seed)
    D = {}                                                        # Observations per budget [(u, loss), ...]
    s_max = int(math.log(b_max) / math.log(eta) + 1e-9)
    best = (float("inf"), None)
    for _ in range(n_iter):
        for s in range(s_max, -1, -1):                            # Brackets run the same way as Hyperband
            n = math.ceil((s_max + 1) / (s + 1) * eta ** s)
            T = [{"u": sample_config(D, d, rng)} for _ in range(n)]   # The only difference from Hyperband
            for i in range(s + 1):                                # Successive Halving
                b = b_max * eta ** (i - s)
                losses = [train_and_eval(t, b) for t in T]
                for t, loss in zip(T, losses):
                    D.setdefault(b, []).append((t["u"], loss))
                    if loss < best[0]:
                        best = (loss, decode(t["u"]))
                T = [t for _, t in sorted(zip(losses, T), key=lambda p: p[0])[:max(1, len(T) // eta)]]
    return best


print(bohb())

FAQ

Q. Do BOHB and Hyperband differ when only a little compute is available?
A.

Not much. In the paper's experiments, Hyperband and BOHB found good settings at about the same speed at first. Until enough observations accumulate to build a model (Nmin⁔+2N_{\min} + 2 per budget), BOHB also picks candidates at random. The difference shows when the budget grows: from there, BOHB approaches the best settings faster than Hyperband.

Q. Why use KDE (TPE) instead of a Gaussian process?
A.

The paper cites simplicity and low computational cost. The Hyperband part produces many observations at small budgets, so a Gaussian process, whose cost grows with the cube of the number of observations, becomes heavy. KDE needs only computation linear in the number of observations and easily handles spaces that mix continuous and categorical values, as well as high-dimensional spaces. The paper also states that TPE could be replaced by a Gaussian process method that meets the requirements.

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

No. Besides the number of epochs, the paper's experiments use the amount of training data, the number of MCMC steps, and the number of reinforcement learning trials as budgets. Anything works as long as performance at a small budget gives a clue about how good a setting is at the maximum budget.

References

  1. S. Falkner, A. Klein, and F. Hutter, "BOHB: Robust and Efficient Hyperparameter Optimization at Scale," ICML, 2018.
  2. L. Li, K. Jamieson, G. DeSalvo, A. Rostamizadeh, and A. Talwalkar, "Hyperband: A Novel Bandit-Based Approach to Hyperparameter Optimization," JMLR, 2018.
  3. J. Bergstra, R. Bardenet, Y. Bengio, and B. KƩgl, "Algorithms for Hyper-Parameter Optimization," NeurIPS, 2011.
  4. HpBandSter (public code by the paper's authors)