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ā and maximum bmaxā of the budget given to one candidate (such as the number of epochs) and the aggressiveness of stopping Ī·, then runs Successive Halving many times while varying the number of candidates and the initial budget. Successive Halving trains each candidate with budget b, keeps only the top 1/Ī· by performance, and multiplies the budget by Ī·, repeating until it reaches bmaxā (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).
With probability Ļ, pick at random and stop. Mixing in random candidates at a fixed rate keeps broad exploration and preserves Hyperband's theoretical guarantees.
Choose the budget b for building the model. It splits the observations so far by budget and, among budgets with at least Nminā+2 observations, picks the largest one. Nminā is the number of hyperparameters d plus 1. If no budget has enough, it picks at random.
Fit densities to the good and bad groups. It sorts the Nbā observations at budget b 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 α is l(x), and that of worse candidates is g(x) (Eq. (2)).
l(x)=p(y<αā£x,D),g(x)=p(y>αā£x,D)
The sizes of the good and bad groups are set with a fraction q as follows (Eq. (3)). This ensures each group has at least Nminā observations even when there are few.
Nb,lā=max(Nminā,qā Nbā),Nb,gā=max(Nminā,NbāāNb,lā)
Draw Nsā candidates. They are drawn from lā²(x), which is l(x) with its kernel bandwidth widened by a factor of bwā. This explores the area around the good group a little more broadly.
Return the candidate with the largest 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) 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 Ļ, even in the worst case where small-budget results are completely unreliable, BOHB is at most (smaxā+1)/Ļ 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 Nsā 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, Ī· for Hyperband and BOHB is 3.
Experiment (section of the paper)
What was compared
Result
6 hyperparameters of a fully connected network, 6 OpenML datasets (Section 5.2.2)
Time to the best setting
Hyperband 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 problem
BOHB was on par with Fabolas and slightly better than Hyperband
Bayesian neural network (Section 5.3)
MCMC steps as the budget
BOHB converged faster than Hyperband and TPE, and found better settings on Boston housing
It started out the same as Hyperband and finally converged to better settings
16-dimensional synthetic function (Section 5.1)
8 continuous, 8 categorical
It 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%.
Method
Test error
Compute
Residual network with hyperparameters found by BOHB
2.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ā give a clue about performance at large budgets. The paper also states that bminā and bmaxā 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 Ī·. Appendix G of the paper reports that varying the random fraction Ļ, the number of samples Nsā, the bandwidth factor bwā, and Ī· 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ā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.
Many 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ā+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.