tutorials/discrete_multi_fidelity_bo.ipynb (473 lines of code) (raw):
{
"metadata": {
"kernelspec": {
"name": "python3",
"display_name": "python3"
}
},
"nbformat": 4,
"nbformat_minor": 2,
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Multi-Fidelity BO with Discrete Fidelities using KG\n",
"\n",
"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](https://botorch.org/tutorials/multi_fidelity_bo), except with discrete fidelity parameters that are interpreted as multiple information sources.\n",
"\n",
"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.\n",
"\n",
"[1] [M. Poloczek, J. Wang, P.I. Frazier. Multi-Information Source Optimization. NeurIPS, 2017](https://papers.nips.cc/paper/2017/file/df1f1d20ee86704251795841e6a9405a-Paper.pdf)\n",
"\n",
"[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](https://arxiv.org/pdf/1903.04703.pdf)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Set dtype and device"
]
},
{
"cell_type": "code",
"metadata": {},
"source": [
"import os\n",
"import torch\n",
"\n",
"\n",
"tkwargs = {\n",
" \"dtype\": torch.double,\n",
" \"device\": torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\"),\n",
"}\n",
"SMOKE_TEST = os.environ.get(\"SMOKE_TEST\")"
],
"execution_count": 1,
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Problem setup\n",
"\n",
"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)$ where $x \\in [0,1]^6$ and $s \\in \\{0.5, 0.75, 1\\}$. The target fidelity is 1.0, which means that our goal is to solve $\\max_x f(x,1.0)$ by making use of cheaper evaluations $f(x,s)$ for $s \\in \\{0.5, 0.75\\}$. In this example, we'll assume that the cost function takes the form $5.0 + s$, illustrating a situation where the fixed cost is $5.0$."
]
},
{
"cell_type": "code",
"metadata": {},
"source": [
"from botorch.test_functions.multi_fidelity import AugmentedHartmann\n",
"\n",
"\n",
"problem = AugmentedHartmann(negate=True).to(**tkwargs)\n",
"fidelities = torch.tensor([0.5, 0.75, 1.0], **tkwargs)"
],
"execution_count": 2,
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Model initialization\n",
"\n",
"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$."
]
},
{
"cell_type": "code",
"metadata": {},
"source": [
"from botorch.models.gp_regression_fidelity import SingleTaskMultiFidelityGP\n",
"from botorch.models.transforms.outcome import Standardize\n",
"from gpytorch.mlls.exact_marginal_log_likelihood import ExactMarginalLogLikelihood\n",
"\n",
"\n",
"def generate_initial_data(n=16):\n",
" # generate training data\n",
" train_x = torch.rand(n, 6, **tkwargs)\n",
" train_f = fidelities[torch.randint(3, (n, 1))]\n",
" train_x_full = torch.cat((train_x, train_f), dim=1)\n",
" train_obj = problem(train_x_full).unsqueeze(-1) # add output dimension\n",
" return train_x_full, train_obj\n",
"\n",
"\n",
"def initialize_model(train_x, train_obj):\n",
" # define a surrogate model suited for a \"training data\"-like fidelity parameter\n",
" # in dimension 6, as in [2]\n",
" model = SingleTaskMultiFidelityGP(train_x, train_obj, outcome_transform=Standardize(m=1), data_fidelity=6)\n",
" mll = ExactMarginalLogLikelihood(model.likelihood, model)\n",
" return mll, model"
],
"execution_count": 3,
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {
"originalKey": "8add142b-e32b-4f27-8f22-4386879512f6",
"showInput": false
},
"source": [
"#### Define a helper function to construct the MFKG acquisition function\n",
"The helper function illustrates how one can initialize an $q$MFKG 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`.\n",
"\n",
"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.\n",
"\n",
"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`."
]
},
{
"cell_type": "code",
"metadata": {},
"source": [
"from botorch import fit_gpytorch_model\n",
"from botorch.models.cost import AffineFidelityCostModel\n",
"from botorch.acquisition.cost_aware import InverseCostWeightedUtility\n",
"from botorch.acquisition import PosteriorMean\n",
"from botorch.acquisition.knowledge_gradient import qMultiFidelityKnowledgeGradient\n",
"from botorch.acquisition.fixed_feature import FixedFeatureAcquisitionFunction\n",
"from botorch.optim.optimize import optimize_acqf\n",
"from botorch.acquisition.utils import project_to_target_fidelity\n",
"\n",
"bounds = torch.tensor([[0.0] * problem.dim, [1.0] * problem.dim], **tkwargs)\n",
"target_fidelities = {6: 1.0}\n",
"\n",
"cost_model = AffineFidelityCostModel(fidelity_weights={6: 1.0}, fixed_cost=5.0)\n",
"cost_aware_utility = InverseCostWeightedUtility(cost_model=cost_model)\n",
"\n",
"\n",
"def project(X):\n",
" return project_to_target_fidelity(X=X, target_fidelities=target_fidelities)\n",
"\n",
"def get_mfkg(model):\n",
" \n",
" curr_val_acqf = FixedFeatureAcquisitionFunction(\n",
" acq_function=PosteriorMean(model),\n",
" d=7,\n",
" columns=[6],\n",
" values=[1],\n",
" )\n",
" \n",
" _, current_value = optimize_acqf(\n",
" acq_function=curr_val_acqf,\n",
" bounds=bounds[:,:-1],\n",
" q=1,\n",
" num_restarts=10 if not SMOKE_TEST else 2,\n",
" raw_samples=1024 if not SMOKE_TEST else 4,\n",
" options={\"batch_limit\": 10, \"maxiter\": 200},\n",
" )\n",
" \n",
" return qMultiFidelityKnowledgeGradient(\n",
" model=model,\n",
" num_fantasies=128 if not SMOKE_TEST else 2,\n",
" current_value=current_value,\n",
" cost_aware_utility=cost_aware_utility,\n",
" project=project,\n",
" )"
],
"execution_count": 4,
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Define a helper function that performs the essential BO step\n",
"This helper function optimizes the acquisition function and returns the batch $\\{x_1, x_2, \\ldots x_q\\}$ along with the observed function values. The function `optimize_acqf_mixed` sequentially optimizes the acquisition function over $x$ for each value of the fidelity $s \\in \\{0, 0.5, 1.0\\}$."
]
},
{
"cell_type": "code",
"metadata": {},
"source": [
"from botorch.optim.optimize import optimize_acqf_mixed\n",
"\n",
"\n",
"torch.set_printoptions(precision=3, sci_mode=False)\n",
"\n",
"NUM_RESTARTS = 5 if not SMOKE_TEST else 2\n",
"RAW_SAMPLES = 128 if not SMOKE_TEST else 4\n",
"BATCH_SIZE = 4\n",
"\n",
"\n",
"def optimize_mfkg_and_get_observation(mfkg_acqf):\n",
" \"\"\"Optimizes MFKG and returns a new candidate, observation, and cost.\"\"\"\n",
"\n",
" # generate new candidates\n",
" candidates, _ = optimize_acqf_mixed(\n",
" acq_function=mfkg_acqf,\n",
" bounds=bounds,\n",
" fixed_features_list=[{6: 0.5}, {6: 0.75}, {6: 1.0}],\n",
" q=BATCH_SIZE,\n",
" num_restarts=NUM_RESTARTS,\n",
" raw_samples=RAW_SAMPLES,\n",
" # batch_initial_conditions=X_init,\n",
" options={\"batch_limit\": 5, \"maxiter\": 200},\n",
" )\n",
"\n",
" # observe new values\n",
" cost = cost_model(candidates).sum()\n",
" new_x = candidates.detach()\n",
" new_obj = problem(new_x).unsqueeze(-1)\n",
" print(f\"candidates:\\n{new_x}\\n\")\n",
" print(f\"observations:\\n{new_obj}\\n\\n\")\n",
" return new_x, new_obj, cost"
],
"execution_count": 5,
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Perform a few steps of multi-fidelity BO\n",
"First, let's generate some initial random data and fit a surrogate model."
]
},
{
"cell_type": "code",
"metadata": {},
"source": [
"train_x, train_obj = generate_initial_data(n=16)"
],
"execution_count": 6,
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We can now use the helper functions above to run a few iterations of BO."
]
},
{
"cell_type": "code",
"metadata": {},
"source": [
"cumulative_cost = 0.0\n",
"N_ITER = 3 if not SMOKE_TEST else 1\n",
"\n",
"for i in range(N_ITER):\n",
" mll, model = initialize_model(train_x, train_obj)\n",
" fit_gpytorch_model(mll)\n",
" mfkg_acqf = get_mfkg(model)\n",
" new_x, new_obj, cost = optimize_mfkg_and_get_observation(mfkg_acqf)\n",
" train_x = torch.cat([train_x, new_x])\n",
" train_obj = torch.cat([train_obj, new_obj])\n",
" cumulative_cost += cost"
],
"execution_count": 7,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"candidates:\ntensor([[0.199, 0.101, 0.436, 0.433, 0.197, 0.421, 0.750],\n [0.142, 0.274, 0.308, 0.413, 0.298, 0.570, 0.750],\n [0.097, 0.141, 0.417, 0.453, 0.477, 0.536, 0.500],\n [0.123, 0.022, 0.328, 0.430, 0.270, 0.689, 0.500]], device='cuda:0',\n dtype=torch.float64)\n\nobservations:\ntensor([[1.369],\n [2.308],\n [1.404],\n [2.297]], device='cuda:0', dtype=torch.float64)\n\n\n"
]
},
{
"output_type": "stream",
"name": "stdout",
"text": [
"candidates:\ntensor([[0.276, 0.159, 0.231, 0.462, 0.295, 0.633, 1.000],\n [0.213, 0.163, 0.297, 0.336, 0.276, 0.671, 0.750],\n [0.029, 0.235, 0.236, 0.405, 0.290, 0.709, 0.500],\n [0.159, 0.205, 0.360, 0.397, 0.361, 0.717, 1.000]], device='cuda:0',\n dtype=torch.float64)\n\nobservations:\ntensor([[2.170],\n [2.984],\n [2.197],\n [2.588]], device='cuda:0', dtype=torch.float64)\n\n\n"
]
},
{
"output_type": "stream",
"name": "stdout",
"text": [
"candidates:\ntensor([[0.268, 0.224, 0.340, 0.334, 0.230, 0.751, 0.500],\n [0.263, 0.181, 0.242, 0.307, 0.335, 0.735, 0.500],\n [0.166, 0.163, 0.345, 0.260, 0.278, 0.711, 0.500],\n [0.257, 0.238, 0.337, 0.311, 0.316, 0.639, 0.750]], device='cuda:0',\n dtype=torch.float64)\n\nobservations:\ntensor([[2.565],\n [2.818],\n [3.036],\n [3.036]], device='cuda:0', dtype=torch.float64)\n\n\n"
]
}
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Make a final recommendation\n",
"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."
]
},
{
"cell_type": "code",
"metadata": {},
"source": [
"def get_recommendation(model):\n",
" rec_acqf = FixedFeatureAcquisitionFunction(\n",
" acq_function=PosteriorMean(model),\n",
" d=7,\n",
" columns=[6],\n",
" values=[1],\n",
" )\n",
"\n",
" final_rec, _ = optimize_acqf(\n",
" acq_function=rec_acqf,\n",
" bounds=bounds[:,:-1],\n",
" q=1,\n",
" num_restarts=10,\n",
" raw_samples=512,\n",
" options={\"batch_limit\": 5, \"maxiter\": 200},\n",
" )\n",
" \n",
" final_rec = rec_acqf._construct_X_full(final_rec)\n",
" \n",
" objective_value = problem(final_rec)\n",
" print(f\"recommended point:\\n{final_rec}\\n\\nobjective value:\\n{objective_value}\")\n",
" return final_rec"
],
"execution_count": 8,
"outputs": []
},
{
"cell_type": "code",
"metadata": {},
"source": [
"final_rec = get_recommendation(model)\n",
"print(f\"\\ntotal cost: {cumulative_cost}\\n\")"
],
"execution_count": 9,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"recommended point:\ntensor([[0.213, 0.164, 0.302, 0.327, 0.283, 0.689, 1.000]], device='cuda:0',\n dtype=torch.float64)\n\nobjective value:\ntensor([3.021], device='cuda:0', dtype=torch.float64)\n\ntotal cost: 68.0\n\n"
]
}
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Comparison to standard EI (always use target fidelity)\n",
"Let's now repeat the same steps using a standard EI 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)."
]
},
{
"cell_type": "code",
"metadata": {},
"source": [
"from botorch.acquisition import qExpectedImprovement\n",
"\n",
"\n",
"def get_ei(model, best_f):\n",
"\n",
" return FixedFeatureAcquisitionFunction(\n",
" acq_function=qExpectedImprovement(model=model, best_f=best_f),\n",
" d=7,\n",
" columns=[6],\n",
" values=[1],\n",
" )\n",
"\n",
"\n",
"def optimize_ei_and_get_observation(ei_acqf):\n",
" \"\"\"Optimizes EI and returns a new candidate, observation, and cost.\"\"\"\n",
"\n",
" candidates, _ = optimize_acqf(\n",
" acq_function=ei_acqf,\n",
" bounds=bounds[:, :-1],\n",
" q=BATCH_SIZE,\n",
" num_restarts=10,\n",
" raw_samples=512,\n",
" options={\"batch_limit\": 5, \"maxiter\": 200},\n",
" )\n",
"\n",
" # add the fidelity parameter\n",
" candidates = ei_acqf._construct_X_full(candidates)\n",
"\n",
" # observe new values\n",
" cost = cost_model(candidates).sum()\n",
" new_x = candidates.detach()\n",
" new_obj = problem(new_x).unsqueeze(-1)\n",
" print(f\"candidates:\\n{new_x}\\n\")\n",
" print(f\"observations:\\n{new_obj}\\n\\n\")\n",
" return new_x, new_obj, cost"
],
"execution_count": 10,
"outputs": []
},
{
"cell_type": "code",
"metadata": {},
"source": [
"cumulative_cost = 0.0\n",
"\n",
"train_x, train_obj = generate_initial_data(n=16)\n",
"\n",
"for _ in range(N_ITER):\n",
" mll, model = initialize_model(train_x, train_obj)\n",
" fit_gpytorch_model(mll)\n",
" ei_acqf = get_ei(model, best_f=train_obj.max())\n",
" new_x, new_obj, cost = optimize_ei_and_get_observation(ei_acqf)\n",
" train_x = torch.cat([train_x, new_x])\n",
" train_obj = torch.cat([train_obj, new_obj])\n",
" cumulative_cost += cost"
],
"execution_count": 11,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"candidates:\ntensor([[0.247, 0.687, 0.581, 0.760, 0.093, 0.132, 1.000],\n [0.319, 0.850, 0.639, 0.865, 0.000, 0.120, 1.000],\n [0.349, 0.666, 0.555, 0.986, 0.000, 0.126, 1.000],\n [0.297, 0.792, 0.450, 0.889, 0.034, 0.028, 1.000]], device='cuda:0',\n dtype=torch.float64)\n\nobservations:\ntensor([[0.973],\n [1.091],\n [0.340],\n [0.902]], device='cuda:0', dtype=torch.float64)\n\n\n"
]
},
{
"output_type": "stream",
"name": "stdout",
"text": [
"candidates:\ntensor([[0.194, 0.858, 0.622, 0.799, 0.000, 0.095, 1.000],\n [0.341, 0.854, 0.590, 0.767, 0.000, 0.085, 1.000],\n [0.999, 0.439, 0.828, 0.975, 0.633, 0.176, 1.000],\n [0.296, 0.859, 0.677, 0.806, 0.119, 0.054, 1.000]], device='cuda:0',\n dtype=torch.float64)\n\nobservations:\ntensor([[ 0.862],\n [ 1.975],\n [ 0.000],\n [ 1.514]], device='cuda:0', dtype=torch.float64)\n\n\n"
]
},
{
"output_type": "stream",
"name": "stderr",
"text": [
"/data/sandcastle/boxes/fbsource/fbcode/buck-out/opt/gen/bento/kernels/bento_kernel_ae#link-tree/gpytorch/utils/cholesky.py:40: NumericalWarning:\n\nA not p.d., added jitter of 1.0e-08 to the diagonal\n\n"
]
},
{
"output_type": "stream",
"name": "stdout",
"text": [
"candidates:\ntensor([[0.360, 0.891, 0.588, 0.749, 0.019, 0.036, 1.000],\n [0.049, 0.894, 0.345, 0.210, 0.482, 0.463, 1.000],\n [0.398, 0.970, 0.504, 0.213, 0.814, 0.724, 1.000],\n [0.817, 0.879, 0.691, 0.842, 0.455, 0.937, 1.000]], device='cuda:0',\n dtype=torch.float64)\n\nobservations:\ntensor([[2.271],\n [0.216],\n [0.055],\n [0.036]], device='cuda:0', dtype=torch.float64)\n\n\n"
]
}
]
},
{
"cell_type": "code",
"metadata": {},
"source": [
"final_rec = get_recommendation(model)\n",
"print(f\"\\ntotal cost: {cumulative_cost}\\n\")"
],
"execution_count": 12,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"recommended point:\ntensor([[0.352, 0.874, 0.589, 0.756, 0.008, 0.060, 1.000]], device='cuda:0',\n dtype=torch.float64)\n\nobjective value:\ntensor([2.166], device='cuda:0', dtype=torch.float64)\n\ntotal cost: 72.0\n\n"
]
}
]
},
{
"cell_type": "code",
"metadata": {},
"source": [
""
],
"execution_count": 12,
"outputs": []
}
]
}