eeipu 1.0.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- cost_aware_bo/__init__.py +17 -0
- cost_aware_bo/acquisition_funcs/EEIPU/EEIPU.py +213 -0
- cost_aware_bo/acquisition_funcs/EEIPU/EEIPU_iteration.py +83 -0
- cost_aware_bo/acquisition_funcs/EI/EI_iteration.py +49 -0
- cost_aware_bo/acquisition_funcs/LaMBO/LaMBO.py +191 -0
- cost_aware_bo/acquisition_funcs/LaMBO/LaMBO_iteration.py +46 -0
- cost_aware_bo/acquisition_funcs/LaMBO/MSET.py +159 -0
- cost_aware_bo/acquisition_funcs/MS_BO/MS_BO_iteration.py +81 -0
- cost_aware_bo/acquisition_funcs/__init__.py +0 -0
- cost_aware_bo/acquisition_funcs/cost_aware_acqf/CArBO.py +177 -0
- cost_aware_bo/acquisition_funcs/cost_aware_acqf/CArBO_iteration.py +89 -0
- cost_aware_bo/acquisition_funcs/cost_aware_acqf/EIPS.py +149 -0
- cost_aware_bo/acquisition_funcs/cost_aware_acqf/EIPS_iteration.py +80 -0
- cost_aware_bo/api.py +150 -0
- cost_aware_bo/functions/__init__.py +0 -0
- cost_aware_bo/functions/iteration_funcs.py +83 -0
- cost_aware_bo/functions/processing_funcs.py +198 -0
- cost_aware_bo/optimize_mem_acqf.py +79 -0
- cost_aware_bo/optimizer/__init__.py +0 -0
- cost_aware_bo/optimizer/optimize_acqf_funcs.py +25 -0
- cost_aware_bo/param_gen.py +672 -0
- eeipu/__init__.py +22 -0
- eeipu-1.0.0.dist-info/METADATA +171 -0
- eeipu-1.0.0.dist-info/RECORD +28 -0
- eeipu-1.0.0.dist-info/WHEEL +5 -0
- eeipu-1.0.0.dist-info/licenses/AUTHORS.md +20 -0
- eeipu-1.0.0.dist-info/licenses/LICENSE +199 -0
- eeipu-1.0.0.dist-info/top_level.txt +2 -0
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
"""Cost-Aware and Memoization-Aware Bayesian Optimization (EEIPU)."""
|
|
2
|
+
|
|
3
|
+
from .acquisition_funcs.EEIPU.EEIPU import EEIPU
|
|
4
|
+
from .api import EEIPUOptimizer
|
|
5
|
+
from .param_gen import generate_hps, log_metrics, read_json, update_dataset_new_run
|
|
6
|
+
|
|
7
|
+
__version__ = "1.0.0"
|
|
8
|
+
|
|
9
|
+
__all__ = [
|
|
10
|
+
"EEIPU",
|
|
11
|
+
"EEIPUOptimizer",
|
|
12
|
+
"generate_hps",
|
|
13
|
+
"update_dataset_new_run",
|
|
14
|
+
"log_metrics",
|
|
15
|
+
"read_json",
|
|
16
|
+
"__version__",
|
|
17
|
+
]
|
|
@@ -0,0 +1,213 @@
|
|
|
1
|
+
from typing import Any, Dict, Optional, Union
|
|
2
|
+
|
|
3
|
+
import torch
|
|
4
|
+
from botorch.acquisition.analytic import AnalyticAcquisitionFunction
|
|
5
|
+
from botorch.acquisition.objective import MCAcquisitionObjective, PosteriorTransform
|
|
6
|
+
from botorch.models.model import Model
|
|
7
|
+
from botorch.sampling import MCSampler
|
|
8
|
+
from botorch.utils import t_batch_mode_transform
|
|
9
|
+
from torch import Tensor
|
|
10
|
+
from torch.distributions import Normal
|
|
11
|
+
|
|
12
|
+
DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class EEIPU(AnalyticAcquisitionFunction):
|
|
16
|
+
r"""Modification of Standard Expected Improvement Class defined in BoTorch
|
|
17
|
+
See: https://botorch.org/api/_modules/botorch/acquisition/analytic.html#ExpectedImprovement
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
def __init__(
|
|
21
|
+
self,
|
|
22
|
+
model: Model,
|
|
23
|
+
cost_gp: Model,
|
|
24
|
+
best_f: Union[float, Tensor],
|
|
25
|
+
cost_sampler: Optional[MCSampler] = None,
|
|
26
|
+
acq_objective: Optional[MCAcquisitionObjective] = None,
|
|
27
|
+
posterior_transform: Optional[PosteriorTransform] = None,
|
|
28
|
+
maximize: bool = True,
|
|
29
|
+
acq_type: str = "",
|
|
30
|
+
unstandardizer=None,
|
|
31
|
+
normalizer=None,
|
|
32
|
+
unnormalizer=None,
|
|
33
|
+
bounds: Tensor = None,
|
|
34
|
+
iter: int = None,
|
|
35
|
+
params: Dict = None,
|
|
36
|
+
eta=None,
|
|
37
|
+
consumed_budget=None,
|
|
38
|
+
warmup_iters=None,
|
|
39
|
+
**kwargs: Any,
|
|
40
|
+
) -> None:
|
|
41
|
+
r"""q-Expected Improvement.
|
|
42
|
+
|
|
43
|
+
Args:
|
|
44
|
+
model: A fitted objective model.
|
|
45
|
+
cost_model: A fitted cost model.
|
|
46
|
+
best_f: The best objective value observed so far (assumed noiseless).
|
|
47
|
+
cost_sampler: The sampler used to draw base samples.
|
|
48
|
+
acq_objective: The MCAcquisitionObjective under which the samples are evaluated.
|
|
49
|
+
Defaults to `IdentityMCObjective()`.
|
|
50
|
+
posterior_transform: A PosteriorTransform (optional).
|
|
51
|
+
maximize: If True, consider the problem a maximization problem.
|
|
52
|
+
"""
|
|
53
|
+
super().__init__(model=model, posterior_transform=posterior_transform, **kwargs)
|
|
54
|
+
self.maximize = maximize
|
|
55
|
+
if not torch.is_tensor(best_f):
|
|
56
|
+
best_f = torch.tensor(best_f, device=DEVICE)
|
|
57
|
+
|
|
58
|
+
self.register_buffer("best_f", best_f)
|
|
59
|
+
self.cost_gp = cost_gp
|
|
60
|
+
self.cost_sampler = cost_sampler
|
|
61
|
+
self.acq_obj = acq_objective
|
|
62
|
+
self.acq_type = acq_type
|
|
63
|
+
self.unstandardizer = unstandardizer
|
|
64
|
+
self.normalizer = normalizer
|
|
65
|
+
self.unnormalizer = unnormalizer
|
|
66
|
+
self.bounds = bounds
|
|
67
|
+
self.params = params
|
|
68
|
+
self.iter = iter
|
|
69
|
+
self.eta = eta
|
|
70
|
+
self.consumed_budget = consumed_budget
|
|
71
|
+
self.warmup = True
|
|
72
|
+
|
|
73
|
+
def get_mc_samples(self, X: Tensor, gp_model, bounds):
|
|
74
|
+
cost_posterior = gp_model.posterior(X)
|
|
75
|
+
cost_samples = self.cost_sampler(cost_posterior)
|
|
76
|
+
cost_samples = cost_samples.to(DEVICE)
|
|
77
|
+
cost_samples = cost_samples.max(dim=2)[0]
|
|
78
|
+
|
|
79
|
+
cost_samples = self.unstandardizer(cost_samples, bounds=bounds)
|
|
80
|
+
cost_samples = torch.exp(cost_samples)
|
|
81
|
+
|
|
82
|
+
cost_samples = self.acq_obj(cost_samples)
|
|
83
|
+
|
|
84
|
+
cost_samples = cost_samples[:, :, None]
|
|
85
|
+
cost_samples = cost_samples.to(DEVICE)
|
|
86
|
+
|
|
87
|
+
return cost_samples
|
|
88
|
+
|
|
89
|
+
def get_memoized_costs(self, X, delta):
|
|
90
|
+
stage_costs = None
|
|
91
|
+
for i in range(delta):
|
|
92
|
+
cost_samples = torch.full(
|
|
93
|
+
(self.params["cost_samples"], X.shape[0]),
|
|
94
|
+
self.params["epsilon"],
|
|
95
|
+
device=DEVICE,
|
|
96
|
+
)
|
|
97
|
+
cost_samples = cost_samples[:, :, None]
|
|
98
|
+
cost_samples = cost_samples.to(DEVICE)
|
|
99
|
+
|
|
100
|
+
stage_costs = (
|
|
101
|
+
cost_samples
|
|
102
|
+
if (not torch.is_tensor(stage_costs))
|
|
103
|
+
else torch.cat([stage_costs, cost_samples], axis=2)
|
|
104
|
+
)
|
|
105
|
+
|
|
106
|
+
return stage_costs
|
|
107
|
+
|
|
108
|
+
def get_stagewise_expected_costs(self, X, delta):
|
|
109
|
+
# Discount Memoized stages by setting their costs to epsilon
|
|
110
|
+
stage_costs = self.get_memoized_costs(X, delta)
|
|
111
|
+
|
|
112
|
+
# Use MC Sampling to get the expected costs of unmemoized stages
|
|
113
|
+
for i in range(delta, len(self.cost_gp)):
|
|
114
|
+
cost_model = self.cost_gp[i]
|
|
115
|
+
hyp_indexes = self.params["h_ind"][i]
|
|
116
|
+
|
|
117
|
+
cost_samples = self.get_mc_samples(
|
|
118
|
+
X[:, :, hyp_indexes], cost_model, self.bounds["c"][:, i]
|
|
119
|
+
)
|
|
120
|
+
stage_costs = (
|
|
121
|
+
cost_samples
|
|
122
|
+
if (not torch.is_tensor(stage_costs))
|
|
123
|
+
else torch.cat([stage_costs, cost_samples], axis=2)
|
|
124
|
+
)
|
|
125
|
+
|
|
126
|
+
return stage_costs
|
|
127
|
+
|
|
128
|
+
def compute_expected_inverse_cost(
|
|
129
|
+
self, X: Tensor, delta: int = 0, alpha_epsilon=False
|
|
130
|
+
) -> Tensor:
|
|
131
|
+
stage_costs = self.get_stagewise_expected_costs(X, delta)
|
|
132
|
+
|
|
133
|
+
stage_costs = stage_costs.sum(dim=-1)
|
|
134
|
+
|
|
135
|
+
inv_cost = 1 / stage_costs
|
|
136
|
+
inv_cost = inv_cost.mean(dim=0)
|
|
137
|
+
|
|
138
|
+
return inv_cost
|
|
139
|
+
|
|
140
|
+
def compute_taylor_expansion(
|
|
141
|
+
self, X: Tensor, delta: int = 0, alpha_epsilon=False
|
|
142
|
+
) -> Tensor:
|
|
143
|
+
stage_costs = self.get_stagewise_expected_costs(X, delta)
|
|
144
|
+
|
|
145
|
+
stage_costs = stage_costs.sum(dim=-1)
|
|
146
|
+
|
|
147
|
+
sample_mean = stage_costs.mean(dim=0)
|
|
148
|
+
sample_var = stage_costs.var(dim=0)
|
|
149
|
+
|
|
150
|
+
inv_cost = 1 / sample_mean + sample_var / sample_mean**3
|
|
151
|
+
return inv_cost
|
|
152
|
+
|
|
153
|
+
# def compute_ground_truth(self, X: Tensor, alpha_epsilon=False) -> Tensor:
|
|
154
|
+
# stage_costs = self.get_mc_samples(X, self.inv_cost_gp, self.bounds['1/c'])
|
|
155
|
+
|
|
156
|
+
# ground_truth = stage_costs.mean(dim=0)
|
|
157
|
+
# return ground_truth
|
|
158
|
+
|
|
159
|
+
def compute_expected_cost(self, X: Tensor) -> Tensor:
|
|
160
|
+
# Check on GPT if this is the proper sampling method
|
|
161
|
+
# Also, test the accuracy of cost expectation
|
|
162
|
+
all_cost_obj = []
|
|
163
|
+
for i, cost_model in enumerate(self.cost_gp):
|
|
164
|
+
hyp_indexes = self.params["h_ind"][i]
|
|
165
|
+
cost_posterior = cost_model.posterior(X[:, hyp_indexes])
|
|
166
|
+
cost_samples = self.cost_sampler(cost_posterior)
|
|
167
|
+
cost_samples = cost_samples.to(DEVICE)
|
|
168
|
+
cost_samples = cost_samples.max(dim=2)[0]
|
|
169
|
+
|
|
170
|
+
# cost_samples = self.unstandardizer(cost_samples, bounds=self.bounds['c'][:,i])
|
|
171
|
+
# cost_samples = torch.exp(cost_samples)
|
|
172
|
+
cost_obj = self.acq_obj(cost_samples)
|
|
173
|
+
all_cost_obj.append(cost_obj.mean(dim=0).item())
|
|
174
|
+
return all_cost_obj
|
|
175
|
+
|
|
176
|
+
def custom_EI(self, X):
|
|
177
|
+
self.best_f = self.best_f.to(X)
|
|
178
|
+
posterior = self.model.posterior(
|
|
179
|
+
X=X, posterior_transform=self.posterior_transform
|
|
180
|
+
)
|
|
181
|
+
|
|
182
|
+
mean = posterior.mean
|
|
183
|
+
view_shape = mean.shape[:-2] if mean.shape[-2] == 1 else mean.shape[:-1]
|
|
184
|
+
mean = mean.view(view_shape)
|
|
185
|
+
sigma = posterior.variance.clamp_min(1e-9).sqrt().view(view_shape)
|
|
186
|
+
|
|
187
|
+
u = (mean - self.best_f.expand_as(mean)) / sigma
|
|
188
|
+
if not self.maximize:
|
|
189
|
+
u = -u
|
|
190
|
+
|
|
191
|
+
normal = Normal(torch.zeros_like(u), torch.ones_like(u))
|
|
192
|
+
ucdf = normal.cdf(u)
|
|
193
|
+
updf = torch.exp(normal.log_prob(u))
|
|
194
|
+
|
|
195
|
+
ei = sigma * (updf + u * ucdf)
|
|
196
|
+
|
|
197
|
+
return ei
|
|
198
|
+
|
|
199
|
+
@t_batch_mode_transform(expected_q=1, assert_output_shape=False)
|
|
200
|
+
def forward(self, X: Tensor, delta: int = 0, curr_iter: int = -1) -> Tensor:
|
|
201
|
+
ei_x = self.custom_EI(X)
|
|
202
|
+
|
|
203
|
+
total_budget = self.params["total_budget"] + 0
|
|
204
|
+
budget_0 = self.params.get("budget_0", 0)
|
|
205
|
+
|
|
206
|
+
remaining = max(0.0, total_budget - (self.consumed_budget or 0.0))
|
|
207
|
+
init_budget = total_budget - budget_0
|
|
208
|
+
|
|
209
|
+
cost_cool = remaining / init_budget if init_budget > 0 else 0.0
|
|
210
|
+
|
|
211
|
+
inv_cost = self.compute_expected_inverse_cost(X, delta=delta)
|
|
212
|
+
|
|
213
|
+
return ei_x * (inv_cost**cost_cool)
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import torch
|
|
2
|
+
from botorch.acquisition.objective import IdentityMCObjective
|
|
3
|
+
from botorch.sampling import SobolQMCNormalSampler
|
|
4
|
+
|
|
5
|
+
from cost_aware_bo.functions.iteration_funcs import (
|
|
6
|
+
get_gp_models,
|
|
7
|
+
get_multistage_cost_models,
|
|
8
|
+
)
|
|
9
|
+
from cost_aware_bo.functions.processing_funcs import (
|
|
10
|
+
generate_prefix_pool,
|
|
11
|
+
get_gen_bounds,
|
|
12
|
+
normalize,
|
|
13
|
+
standardize,
|
|
14
|
+
unnormalize,
|
|
15
|
+
unstandardize,
|
|
16
|
+
)
|
|
17
|
+
from cost_aware_bo.optimize_mem_acqf import optimize_acqf_by_mem
|
|
18
|
+
|
|
19
|
+
from .EEIPU import EEIPU
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def eeipu_iteration(
|
|
23
|
+
X,
|
|
24
|
+
y,
|
|
25
|
+
c,
|
|
26
|
+
bounds=None,
|
|
27
|
+
acqf_str="",
|
|
28
|
+
decay=None,
|
|
29
|
+
iter=None,
|
|
30
|
+
consumed_budget=None,
|
|
31
|
+
params=None,
|
|
32
|
+
):
|
|
33
|
+
# Next test: try bounds['x'] again and make sure prefix pooling works with normalized data
|
|
34
|
+
train_x = normalize(X, bounds=bounds["x_cube"])
|
|
35
|
+
train_y = standardize(y, bounds["y"])
|
|
36
|
+
|
|
37
|
+
prefix_pool = None
|
|
38
|
+
if params["use_pref_pool"]:
|
|
39
|
+
prefix_pool = generate_prefix_pool(train_x, y, acqf_str, params)
|
|
40
|
+
|
|
41
|
+
norm_bounds = get_gen_bounds(
|
|
42
|
+
params["h_ind"], params["normalization_bounds"], bound_type="norm"
|
|
43
|
+
)
|
|
44
|
+
|
|
45
|
+
mll, gp_model = get_gp_models(train_x, train_y, iter, params=params)
|
|
46
|
+
|
|
47
|
+
cost_mll, cost_gp = get_multistage_cost_models(
|
|
48
|
+
train_x, c, iter, params["h_ind"], bounds, acqf_str
|
|
49
|
+
)
|
|
50
|
+
|
|
51
|
+
cost_sampler = SobolQMCNormalSampler(
|
|
52
|
+
sample_shape=torch.Size([params["cost_samples"]]), seed=iter
|
|
53
|
+
)
|
|
54
|
+
acqf = EEIPU(
|
|
55
|
+
acq_type=acqf_str,
|
|
56
|
+
model=gp_model,
|
|
57
|
+
cost_gp=cost_gp,
|
|
58
|
+
best_f=train_y.max(),
|
|
59
|
+
cost_sampler=cost_sampler,
|
|
60
|
+
acq_objective=IdentityMCObjective(),
|
|
61
|
+
unstandardizer=unstandardize,
|
|
62
|
+
normalizer=normalize,
|
|
63
|
+
unnormalizer=unnormalize,
|
|
64
|
+
bounds=bounds,
|
|
65
|
+
eta=decay,
|
|
66
|
+
consumed_budget=consumed_budget,
|
|
67
|
+
iter=iter,
|
|
68
|
+
params=params,
|
|
69
|
+
)
|
|
70
|
+
|
|
71
|
+
new_x, n_memoised, acq_value = optimize_acqf_by_mem(
|
|
72
|
+
acqf=acqf,
|
|
73
|
+
acqf_str=acqf_str,
|
|
74
|
+
bounds=norm_bounds,
|
|
75
|
+
iter=iter,
|
|
76
|
+
prefix_pool=prefix_pool,
|
|
77
|
+
params=params,
|
|
78
|
+
seed=iter,
|
|
79
|
+
)
|
|
80
|
+
|
|
81
|
+
new_x = unnormalize(new_x, bounds["x_cube"])
|
|
82
|
+
|
|
83
|
+
return new_x, n_memoised, acq_value
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
try:
|
|
2
|
+
from botorch.acquisition import LogExpectedImprovement as ExpectedImprovement
|
|
3
|
+
except ImportError:
|
|
4
|
+
from botorch.acquisition import ExpectedImprovement
|
|
5
|
+
|
|
6
|
+
from cost_aware_bo.functions.iteration_funcs import get_gp_models
|
|
7
|
+
from cost_aware_bo.functions.processing_funcs import (
|
|
8
|
+
get_gen_bounds,
|
|
9
|
+
normalize,
|
|
10
|
+
standardize,
|
|
11
|
+
unnormalize,
|
|
12
|
+
)
|
|
13
|
+
from cost_aware_bo.optimize_mem_acqf import optimize_acqf_by_mem
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def ei_iteration(
|
|
17
|
+
X,
|
|
18
|
+
y,
|
|
19
|
+
c,
|
|
20
|
+
bounds=None,
|
|
21
|
+
acqf_str="",
|
|
22
|
+
decay=None,
|
|
23
|
+
iter=None,
|
|
24
|
+
consumed_budget=None,
|
|
25
|
+
params=None,
|
|
26
|
+
):
|
|
27
|
+
train_x = normalize(X, bounds=bounds["x_cube"])
|
|
28
|
+
train_y = standardize(y, bounds["y"])
|
|
29
|
+
|
|
30
|
+
mll, gp_model = get_gp_models(train_x, train_y, iter, params=params)
|
|
31
|
+
|
|
32
|
+
norm_bounds = get_gen_bounds(
|
|
33
|
+
params["h_ind"], params["normalization_bounds"], bound_type="norm"
|
|
34
|
+
)
|
|
35
|
+
|
|
36
|
+
acqf = ExpectedImprovement(model=gp_model, best_f=train_y.max())
|
|
37
|
+
|
|
38
|
+
new_x, n_memoised, acq_value = optimize_acqf_by_mem(
|
|
39
|
+
acqf=acqf,
|
|
40
|
+
acqf_str=acqf_str,
|
|
41
|
+
bounds=norm_bounds,
|
|
42
|
+
iter=iter,
|
|
43
|
+
params=params,
|
|
44
|
+
seed=iter,
|
|
45
|
+
)
|
|
46
|
+
|
|
47
|
+
new_x = unnormalize(new_x, bounds=bounds["x_cube"])
|
|
48
|
+
|
|
49
|
+
return new_x, n_memoised, acq_value
|
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
import copy
|
|
2
|
+
import random
|
|
3
|
+
|
|
4
|
+
import numpy as np
|
|
5
|
+
import torch
|
|
6
|
+
|
|
7
|
+
from cost_aware_bo.functions.processing_funcs import get_initial_data
|
|
8
|
+
|
|
9
|
+
from .MSET import MSET, Node
|
|
10
|
+
|
|
11
|
+
DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def build_partitions(input_bounds, h_ind, n_stages):
|
|
15
|
+
partitions = []
|
|
16
|
+
for i in range(n_stages - 1):
|
|
17
|
+
stage_partition = []
|
|
18
|
+
for stage_idx in h_ind[i]:
|
|
19
|
+
lo, hi = input_bounds[0][stage_idx], input_bounds[1][stage_idx]
|
|
20
|
+
mid = (lo + hi) / 2.0
|
|
21
|
+
p = [[lo, mid], [mid, hi]]
|
|
22
|
+
stage_partition.append(p)
|
|
23
|
+
partitions.append(stage_partition)
|
|
24
|
+
|
|
25
|
+
last_stage_partition = []
|
|
26
|
+
for stage_idx in h_ind[-1]:
|
|
27
|
+
lo, hi = input_bounds[0][stage_idx], input_bounds[1][stage_idx]
|
|
28
|
+
p = [lo, hi]
|
|
29
|
+
last_stage_partition.append(p)
|
|
30
|
+
|
|
31
|
+
return partitions, last_stage_partition
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def get_pdf(n_leaves):
|
|
35
|
+
unif_prob = 1.0 / n_leaves
|
|
36
|
+
probs = np.array([unif_prob for i in range(n_leaves)])
|
|
37
|
+
return probs
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def build_tree(partitions, depths, last_stage_partition):
|
|
41
|
+
root = Node(None, 0, 0)
|
|
42
|
+
mset = MSET(partitions, depths, last_stage_partition)
|
|
43
|
+
|
|
44
|
+
left = mset.ConstructMSET(root, 0, 0, 1, [], [[], []])
|
|
45
|
+
right = mset.ConstructMSET(root, 0, 1, 2, [], [[], []])
|
|
46
|
+
root.add_child(left, right)
|
|
47
|
+
|
|
48
|
+
mset.assign_leaf_ranges(root)
|
|
49
|
+
|
|
50
|
+
return mset, root
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def get_subtree_arms(root, prev_h, prev_arm_idx):
|
|
54
|
+
node = copy.deepcopy(root)
|
|
55
|
+
curr_depth = 0
|
|
56
|
+
|
|
57
|
+
while curr_depth < prev_h:
|
|
58
|
+
if node.left.leaf_ranges[0] <= prev_arm_idx <= node.left.leaf_ranges[1]:
|
|
59
|
+
node = node.left
|
|
60
|
+
elif node.right.leaf_ranges[0] <= prev_arm_idx <= node.right.leaf_ranges[1]:
|
|
61
|
+
node = node.right
|
|
62
|
+
|
|
63
|
+
curr_depth += 1
|
|
64
|
+
|
|
65
|
+
return node.leaf_ranges
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def select_arm(root, leaves, probs, prev_h, prev_arm_idx, n_leaves):
|
|
69
|
+
arm_choices = np.array([i for i in range(n_leaves)])
|
|
70
|
+
valid_arm_idx = get_subtree_arms(root, prev_h, prev_arm_idx)
|
|
71
|
+
|
|
72
|
+
valid_arm_choices = arm_choices[valid_arm_idx[0] : valid_arm_idx[1] + 1]
|
|
73
|
+
valid_probs = probs[valid_arm_idx[0] : valid_arm_idx[1] + 1]
|
|
74
|
+
|
|
75
|
+
arm_idx = random.choices(valid_arm_choices, weights=valid_probs)[0]
|
|
76
|
+
|
|
77
|
+
return torch.tensor(leaves[arm_idx], device=DEVICE), arm_idx
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def update_loss_estimators(loss, root, probs, arm_idx, sigma, H, acq_value, eta=1):
|
|
81
|
+
loss[arm_idx][0] = acq_value
|
|
82
|
+
node = copy.deepcopy(root)
|
|
83
|
+
|
|
84
|
+
for height in range(1, H):
|
|
85
|
+
# Move to the child that has the current arm as a leaf
|
|
86
|
+
if node.left.leaf_ranges[0] <= arm_idx <= node.left.leaf_ranges[1]:
|
|
87
|
+
node = node.left
|
|
88
|
+
elif node.right.leaf_ranges[0] <= arm_idx <= node.right.leaf_ranges[1]:
|
|
89
|
+
node = node.right
|
|
90
|
+
|
|
91
|
+
nominator = 0
|
|
92
|
+
for leaf_idx in range(node.leaf_ranges[0], node.leaf_ranges[1]):
|
|
93
|
+
nominator += probs[leaf_idx] * np.exp(
|
|
94
|
+
-eta * (1 + sigma[height - 1]) * loss[leaf_idx][height - 1]
|
|
95
|
+
)
|
|
96
|
+
|
|
97
|
+
denominator = probs[node.leaf_ranges[0] : node.leaf_ranges[1] + 1].sum()
|
|
98
|
+
|
|
99
|
+
# print(f'To update losses, the nominator is {nominator} and the denominator is {denominator}')
|
|
100
|
+
|
|
101
|
+
loss_i = np.log(nominator / denominator) ** (-1 / eta)
|
|
102
|
+
|
|
103
|
+
loss[arm_idx][height] = sigma[height] * loss_i
|
|
104
|
+
|
|
105
|
+
return loss
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def update_arm_probability(loss, probs, arm_idx, n_leaves, eta=1):
|
|
109
|
+
nominator = probs[arm_idx] * np.exp(-eta * loss[arm_idx, :].sum())
|
|
110
|
+
|
|
111
|
+
denominator = 0
|
|
112
|
+
for leaf_idx in range(n_leaves):
|
|
113
|
+
denominator += probs[leaf_idx] * np.exp(-eta * loss[leaf_idx, :].sum())
|
|
114
|
+
|
|
115
|
+
return nominator / denominator
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def update_all_probabilities(loss, probs, arm_idx, n_leaves):
|
|
119
|
+
# We update the probability of the current arm first
|
|
120
|
+
probs[arm_idx] = update_arm_probability(loss, probs, arm_idx, n_leaves)
|
|
121
|
+
|
|
122
|
+
# We then update the probabilities of all remaining arms
|
|
123
|
+
for idx in range(n_leaves):
|
|
124
|
+
if idx == arm_idx:
|
|
125
|
+
continue
|
|
126
|
+
probs[idx] = update_arm_probability(loss, probs, idx, n_leaves)
|
|
127
|
+
|
|
128
|
+
return probs
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def remove_invalid_partitions(
|
|
132
|
+
input_bounds, probs, loss, h_ind, n_leaves, H, n_stages, leaf_partitions
|
|
133
|
+
):
|
|
134
|
+
prob_thres = 1e-6
|
|
135
|
+
|
|
136
|
+
invalid_partitions = np.where(probs < prob_thres)[0]
|
|
137
|
+
if invalid_partitions.shape[0] > 0:
|
|
138
|
+
first_invalid_idx = invalid_partitions[0]
|
|
139
|
+
invalid_partition = leaf_partitions[first_invalid_idx]
|
|
140
|
+
|
|
141
|
+
for i in range(n_stages - 1):
|
|
142
|
+
for stage_idx in h_ind[i]:
|
|
143
|
+
if invalid_partition[i] == 0:
|
|
144
|
+
input_bounds[0][stage_idx] = (
|
|
145
|
+
input_bounds[0][stage_idx] + input_bounds[1][stage_idx]
|
|
146
|
+
) / 2.0
|
|
147
|
+
else:
|
|
148
|
+
input_bounds[1][stage_idx] = (
|
|
149
|
+
input_bounds[0][stage_idx] + input_bounds[1][stage_idx]
|
|
150
|
+
) / 2.0
|
|
151
|
+
|
|
152
|
+
probs = get_pdf(n_leaves)
|
|
153
|
+
loss = np.zeros([n_leaves, H])
|
|
154
|
+
|
|
155
|
+
return input_bounds, probs, loss
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
# def build_datasets(self, acqf, leaf_bounds, trial_number, n_leaves, arm_idx, params):
|
|
159
|
+
|
|
160
|
+
# X_tree, Y_tree, C_tree, C_inv_tree = [], [], [], []
|
|
161
|
+
# best_f = -1e9
|
|
162
|
+
# init_cost = 0
|
|
163
|
+
# for leaf in range(n_leaves):
|
|
164
|
+
# x, y, c, c_inv, cost0 = get_initial_data(
|
|
165
|
+
# params['n_init_data'], bounds=leaf_bounds[leaf],
|
|
166
|
+
# seed=trial_number*10000, acqf=acqf, params=params)
|
|
167
|
+
|
|
168
|
+
# X_tree.append(x)
|
|
169
|
+
# Y_tree.append(y)
|
|
170
|
+
# C_tree.append(c)
|
|
171
|
+
# C_inv_tree.append(c_inv)
|
|
172
|
+
|
|
173
|
+
# if leaf == arm_idx:
|
|
174
|
+
# init_cost = cost0
|
|
175
|
+
# best_f = max(best_f, y.max().item())
|
|
176
|
+
|
|
177
|
+
# return X_tree, Y_tree, C_tree, C_inv_tree, init_cost, best_f
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def build_datasets(acqf, bounds, trial_number, n_leaves, arm_idx, params):
|
|
181
|
+
X, Y, C, C_inv, cost0 = get_initial_data(
|
|
182
|
+
params["n_init_data"],
|
|
183
|
+
bounds=bounds,
|
|
184
|
+
seed=trial_number * 10000,
|
|
185
|
+
acqf=acqf,
|
|
186
|
+
params=params,
|
|
187
|
+
)
|
|
188
|
+
|
|
189
|
+
best_f = Y.max().item()
|
|
190
|
+
|
|
191
|
+
return X, Y, C, C_inv, cost0, best_f
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
from botorch.acquisition import UpperConfidenceBound
|
|
2
|
+
|
|
3
|
+
from cost_aware_bo.functions.iteration_funcs import get_gp_models
|
|
4
|
+
from cost_aware_bo.functions.processing_funcs import (
|
|
5
|
+
get_gen_bounds,
|
|
6
|
+
normalize,
|
|
7
|
+
standardize,
|
|
8
|
+
unnormalize,
|
|
9
|
+
)
|
|
10
|
+
from cost_aware_bo.optimize_mem_acqf import optimize_acqf_by_mem
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def lambo_iteration(
|
|
14
|
+
X,
|
|
15
|
+
y,
|
|
16
|
+
c,
|
|
17
|
+
bounds=None,
|
|
18
|
+
acqf_str="",
|
|
19
|
+
decay=None,
|
|
20
|
+
iter=None,
|
|
21
|
+
consumed_budget=None,
|
|
22
|
+
params=None,
|
|
23
|
+
):
|
|
24
|
+
train_x = normalize(X, bounds=bounds["x_cube"])
|
|
25
|
+
train_y = standardize(y, bounds["y"])
|
|
26
|
+
|
|
27
|
+
mll, gp_model = get_gp_models(train_x, train_y, iter, params=params)
|
|
28
|
+
|
|
29
|
+
norm_bounds = get_gen_bounds(
|
|
30
|
+
params["h_ind"], params["normalization_bounds"], bound_type="norm"
|
|
31
|
+
)
|
|
32
|
+
|
|
33
|
+
acqf = UpperConfidenceBound(model=gp_model, beta=0.2, maximize=True)
|
|
34
|
+
|
|
35
|
+
new_x, n_memoised, acq_value = optimize_acqf_by_mem(
|
|
36
|
+
acqf=acqf,
|
|
37
|
+
acqf_str=acqf_str,
|
|
38
|
+
bounds=norm_bounds,
|
|
39
|
+
iter=iter,
|
|
40
|
+
params=params,
|
|
41
|
+
seed=iter,
|
|
42
|
+
)
|
|
43
|
+
|
|
44
|
+
new_x = unnormalize(new_x, bounds=bounds["x_cube"])
|
|
45
|
+
|
|
46
|
+
return new_x, n_memoised, acq_value
|