Skip to main content
Version: Next

Multi-fidelity Bayesian optimization with discrete fidelities using KG

Multi-Fidelity BO with Discrete Fidelities using KG

In this tutorial, we show how to do multi-fidelity BO with discrete fidelities based on [1], where each fidelity is a different "information source." This tutorial uses the same setup as the continuous multi-fidelity BO tutorial, except with discrete fidelity parameters that are interpreted as multiple information sources.

We use a GP model with a single task that models the design and fidelity parameters jointly. In some cases, where there is not a natural ordering in the fidelity space, it may be more appropriate to use a multi-task model (with, say, an ICM kernel). We will provide a tutorial once this functionality is in place.

[1] M. Poloczek, J. Wang, P.I. Frazier. Multi-Information Source Optimization. NeurIPS, 2017

[2] J. Wu, S. Toscano-Palmerin, P.I. Frazier, A.G. Wilson. Practical Multi-fidelity Bayesian Optimization for Hyperparameter Tuning. Conference on Uncertainty in Artificial Intelligence (UAI), 2019

Set dtype and device

# Install dependencies if we are running in colab
import sys
if 'google.colab' in sys.modules:
%pip install botorch
import os
import torch


tkwargs = {
"dtype": torch.double,
"device": torch.device("cuda" if torch.cuda.is_available() else "cpu"),
}
SMOKE_TEST = os.environ.get("SMOKE_TEST")

Problem setup

We'll consider the Augmented Hartmann multi-fidelity synthetic test problem. This function is a version of the Hartmann6 test function with an additional dimension representing the fidelity parameter; details are in [2]. The function takes the form f(x,s)f(x,s) where x[0,1]6x \in [0,1]^6 and s0.5,0.75,1s \in {0.5, 0.75, 1}. The target fidelity is 1.0, which means that our goal is to solve maxxf(x,1.0)\max_x f(x,1.0) by making use of cheaper evaluations f(x,s)f(x,s) for s0.5,0.75s \in {0.5, 0.75}. In this example, we'll assume that the cost function takes the form 0.25+s0.25 + s, illustrating a situation where the fixed cost is 0.250.25.

from botorch.test_functions.multi_fidelity import AugmentedHartmann


problem = AugmentedHartmann(negate=True).to(**tkwargs)
fidelities = torch.tensor([0.5, 0.75, 1.0], **tkwargs)

Model initialization

We use a SingleTaskMultiFidelityGP as the surrogate model, which uses a kernel from [2] that is well-suited for multi-fidelity applications. The SingleTaskMultiFidelityGP models the design and fidelity parameters jointly, so its domain is [0,1]7[0,1]^7.

from botorch.models.gp_regression_fidelity import SingleTaskMultiFidelityGP
from botorch.models.transforms.outcome import Standardize
from gpytorch.mlls.exact_marginal_log_likelihood import ExactMarginalLogLikelihood


def generate_initial_data(n=16):
# generate training data
train_x = torch.rand(n, 6, **tkwargs)
train_f = fidelities[torch.randint(3, (n, 1))]
train_x_full = torch.cat((train_x, train_f), dim=1)
train_obj = problem(train_x_full).unsqueeze(-1) # add output dimension
return train_x_full, train_obj


def initialize_model(train_x, train_obj):
# define a surrogate model suited for a "training data"-like fidelity parameter
# in dimension 6, as in [2]
model = SingleTaskMultiFidelityGP(
train_x, train_obj, outcome_transform=Standardize(m=1), data_fidelities=[6]
)
mll = ExactMarginalLogLikelihood(model.likelihood, model)
return mll, model

Define a helper function to construct the MFKG acquisition function

The helper function illustrates how one can initialize an qqMFKG acquisition function. In this example, we assume that the affine cost is known. We then use the notion of a CostAwareUtility in BoTorch to scalarize the "competing objectives" of information gain and cost. The MFKG acquisition function optimizes the ratio of information gain to cost, which is captured by the InverseCostWeightedUtility.

In order for MFKG to evaluate the information gain, it uses the model to predict the function value at the highest fidelity after conditioning on the observation. This is handled by the project argument, which specifies how to transform a tensor X to its target fidelity. We use a default helper function called project_to_target_fidelity to achieve this.

An important point to keep in mind: in the case of standard KG, one can ignore the current value and simply optimize the expected maximum posterior mean of the next stage. However, for MFKG, since the goal is optimize information gain per cost, it is important to first compute the current value (i.e., maximum of the posterior mean at the target fidelity). To accomplish this, we use a FixedFeatureAcquisitionFunction on top of a PosteriorMean.

from botorch import fit_gpytorch_mll
from botorch.models.cost import AffineFidelityCostModel
from botorch.acquisition.cost_aware import InverseCostWeightedUtility
from botorch.acquisition import PosteriorMean
from botorch.acquisition.knowledge_gradient import qMultiFidelityKnowledgeGradient
from botorch.acquisition.fixed_feature import FixedFeatureAcquisitionFunction
from botorch.optim.optimize import optimize_acqf
from botorch.acquisition.utils import project_to_target_fidelity

bounds = torch.tensor([[0.0] * problem.dim, [1.0] * problem.dim], **tkwargs)
target_fidelities = {6: 1.0}

cost_model = AffineFidelityCostModel(fidelity_weights={6: 1.0}, fixed_cost=0.25)
cost_aware_utility = InverseCostWeightedUtility(cost_model=cost_model)


def project(X):
return project_to_target_fidelity(X=X, target_fidelities=target_fidelities)


def get_mfkg(model):

curr_val_acqf = FixedFeatureAcquisitionFunction(
acq_function=PosteriorMean(model),
d=7,
columns=[6],
values=[1],
)

_, current_value = optimize_acqf(
acq_function=curr_val_acqf,
bounds=bounds[:, :-1],
q=1,
num_restarts=10 if not SMOKE_TEST else 2,
raw_samples=1024 if not SMOKE_TEST else 4,
options={"batch_limit": 10, "maxiter": 200},
)

return qMultiFidelityKnowledgeGradient(
model=model,
num_fantasies=128 if not SMOKE_TEST else 2,
current_value=current_value,
cost_aware_utility=cost_aware_utility,
project=project,
)

Define a helper function that performs the essential BO step

This helper function optimizes the acquisition function and returns the batch x1,x2,xq{x_1, x_2, \ldots x_q} along with the observed function values. The function optimize_acqf_mixed sequentially optimizes the acquisition function over xx for each value of the fidelity s0,0.5,1.0s \in {0, 0.5, 1.0}.

from botorch.optim.optimize import optimize_acqf_mixed


torch.set_printoptions(precision=3, sci_mode=False)

NUM_RESTARTS = 5 if not SMOKE_TEST else 2
RAW_SAMPLES = 128 if not SMOKE_TEST else 4
BATCH_SIZE = 4


def optimize_mfkg_and_get_observation(mfkg_acqf):
"""Optimizes MFKG and returns a new candidate, observation, and cost."""

# generate new candidates
candidates, _ = optimize_acqf_mixed(
acq_function=mfkg_acqf,
bounds=bounds,
fixed_features_list=[{6: 0.5}, {6: 0.75}, {6: 1.0}],
q=BATCH_SIZE,
num_restarts=NUM_RESTARTS,
raw_samples=RAW_SAMPLES,
# batch_initial_conditions=X_init,
options={"batch_limit": 5, "maxiter": 200},
)

# observe new values
cost = cost_model(candidates).sum()
new_x = candidates.detach()
new_obj = problem(new_x).unsqueeze(-1)
print(f"candidates:\n{new_x}\n")
print(f"observations:\n{new_obj}\n\n")
return new_x, new_obj, cost

Perform a few steps of multi-fidelity BO

First, let's generate some initial random data and fit a surrogate model.

train_x, train_obj = generate_initial_data(n=16)

We can now use the helper functions above to run a few iterations of BO.

cumulative_cost = 0.0
N_ITER = 3 if not SMOKE_TEST else 1

for i in range(N_ITER):
mll, model = initialize_model(train_x, train_obj)
fit_gpytorch_mll(mll)
mfkg_acqf = get_mfkg(model)
new_x, new_obj, cost = optimize_mfkg_and_get_observation(mfkg_acqf)
train_x = torch.cat([train_x, new_x])
train_obj = torch.cat([train_obj, new_obj])
cumulative_cost += cost
Out:

candidates:

tensor([[0.288, 0.652, 0.749, 0.370, 0.264, 0.292, 0.500],

[0.391, 0.791, 0.665, 0.446, 0.274, 0.257, 0.500],

[0.293, 0.762, 0.743, 0.554, 0.354, 0.340, 0.500],

[0.374, 0.751, 0.898, 0.410, 0.410, 0.327, 0.500]],

dtype=torch.float64)

observations:

tensor([[0.755],

[1.417],

[0.782],

[0.788]], dtype=torch.float64)

candidates:

tensor([[0.277, 0.836, 0.908, 0.448, 0.129, 0.214, 0.500],

[0.783, 0.235, 0.616, 0.450, 0.208, 0.001, 0.500],

[0.417, 0.777, 0.740, 0.561, 0.228, 0.157, 0.500],

[0.456, 0.805, 0.952, 0.430, 0.277, 0.185, 0.500]],

dtype=torch.float64)

observations:

tensor([[1.351],

[0.029],

[2.414],

[1.783]], dtype=torch.float64)

candidates:

tensor([[0.418, 0.712, 0.254, 0.348, 0.754, 0.148, 0.500],

[0.431, 0.828, 0.731, 0.635, 0.324, 0.148, 0.500],

[0.433, 0.733, 0.750, 0.602, 0.342, 0.117, 0.500],

[0.443, 0.802, 0.630, 0.556, 0.175, 0.098, 0.500]],

dtype=torch.float64)

observations:

tensor([[1.211],

[2.512],

[2.407],

[2.816]], dtype=torch.float64)

Make a final recommendation

In multi-fidelity BO, there are usually fewer observations of the function at the target fidelity, so it is important to use a recommendation function that uses the correct fidelity. Here, we maximize the posterior mean with the fidelity dimension fixed to the target fidelity of 1.0.

def get_recommendation(model):
rec_acqf = FixedFeatureAcquisitionFunction(
acq_function=PosteriorMean(model),
d=7,
columns=[6],
values=[1],
)

final_rec, _ = optimize_acqf(
acq_function=rec_acqf,
bounds=bounds[:, :-1],
q=1,
num_restarts=10,
raw_samples=512,
options={"batch_limit": 5, "maxiter": 200},
)

final_rec = rec_acqf._construct_X_full(final_rec)

objective_value = problem(final_rec)
print(f"recommended point:\n{final_rec}\n\nobjective value:\n{objective_value}")
return final_rec
final_rec = get_recommendation(model)
print(f"\ntotal cost: {cumulative_cost}\n")
Out:

recommended point:

tensor([[0.426, 0.776, 0.721, 0.580, 0.239, 0.139, 1.000]],

dtype=torch.float64)

objective value:

tensor([2.530], dtype=torch.float64)

total cost: 9.0

Comparison to standard (log)EI (always use target fidelity)

Let's now repeat the same steps using a standard qLogExpectedImprovement acquisition function (note that this is not a rigorous comparison as we are only looking at one trial in order to keep computational requirements low).

from botorch.acquisition import qLogExpectedImprovement


def get_ei(model, best_f):

return FixedFeatureAcquisitionFunction(
acq_function=qLogExpectedImprovement(model=model, best_f=best_f), d=7, columns=[6], values=[1],
)


def optimize_ei_and_get_observation(ei_acqf):
"""Optimizes EI and returns a new candidate, observation, and cost."""

candidates, _ = optimize_acqf(
acq_function=ei_acqf,
bounds=bounds[:, :-1],
q=BATCH_SIZE,
num_restarts=10,
raw_samples=512,
options={"batch_limit": 5, "maxiter": 200},
)

# add the fidelity parameter
candidates = ei_acqf._construct_X_full(candidates)

# observe new values
cost = cost_model(candidates).sum()
new_x = candidates.detach()
new_obj = problem(new_x).unsqueeze(-1)
print(f"candidates:\n{new_x}\n")
print(f"observations:\n{new_obj}\n\n")
return new_x, new_obj, cost
cumulative_cost = 0.0

train_x, train_obj = generate_initial_data(n=16)

for _ in range(N_ITER):
mll, model = initialize_model(train_x, train_obj)
fit_gpytorch_mll(mll)
ei_acqf = get_ei(model, best_f=train_obj.max())
new_x, new_obj, cost = optimize_ei_and_get_observation(ei_acqf)
train_x = torch.cat([train_x, new_x])
train_obj = torch.cat([train_obj, new_obj])
cumulative_cost += cost
Out:

candidates:

tensor([[0.094, 0.141, 0.634, 0.353, 0.180, 0.597, 1.000],

[0.007, 0.306, 0.598, 0.332, 0.193, 0.608, 1.000],

[0.165, 0.256, 0.601, 0.341, 0.210, 0.759, 1.000],

[0.151, 0.236, 0.512, 0.427, 0.067, 0.686, 1.000]],

dtype=torch.float64)

observations:

tensor([[2.069],

[1.959],

[2.400],

[1.075]], dtype=torch.float64)

candidates:

tensor([[0.149, 0.240, 0.661, 0.305, 0.221, 0.787, 1.000],

[0.137, 0.496, 0.271, 0.591, 0.253, 0.628, 1.000],

[0.158, 0.192, 0.601, 0.298, 0.259, 0.744, 1.000],

[0.482, 0.586, 0.901, 0.094, 0.009, 0.307, 1.000]],

dtype=torch.float64)

observations:

tensor([[2.394],

[0.740],

[2.854],

[0.098]], dtype=torch.float64)

candidates:

tensor([[0.227, 0.783, 0.444, 0.154, 0.699, 0.328, 1.000],

[0.073, 0.907, 0.478, 0.442, 0.373, 0.133, 1.000],

[0.154, 0.153, 0.560, 0.270, 0.285, 0.730, 1.000],

[0.614, 0.621, 0.801, 0.116, 0.505, 0.647, 1.000]],

dtype=torch.float64)

observations:

tensor([[0.229],

[0.399],

[3.072],

[0.286]], dtype=torch.float64)

final_rec = get_recommendation(model)
print(f"\ntotal cost: {cumulative_cost}\n")
Out:

recommended point:

tensor([[0.159, 0.170, 0.580, 0.284, 0.277, 0.731, 1.000]],

dtype=torch.float64)

objective value:

tensor([3.018], dtype=torch.float64)

total cost: 15.0