-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLangermann_Random_EI_UCB_cEI_cUCB.py
344 lines (272 loc) · 10.2 KB
/
Langermann_Random_EI_UCB_cEI_cUCB.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
from botorch.acquisition import objective
import torch
import os
import time
import sys
import gpytorch.settings as gpt_settings
from botorch.acquisition import qUpperConfidenceBound, qExpectedImprovement
from botorch.acquisition.objective import GenericMCObjective
from botorch.models import HigherOrderGP, SingleTaskGP, ModelList
from botorch.models.higher_order_gp import FlattenedStandardize
from botorch.models.transforms import Normalize, Standardize
from botorch.optim import optimize_acqf
from botorch.sampling import IIDNormalSampler
from botorch.optim.fit import fit_gpytorch_torch
from gpytorch.mlls import ExactMarginalLogLikelihood
SMOKE_TEST = os.environ.get("SMOKE_TEST")
filename = sys.argv[1]
regret_file = f"./outputs/regret_{filename}.txt"
runtime_file = f"./outputs/runtime_{filename}.txt"
Langermann = {
"A_T": torch.tensor([[3., 5., 2., 1., 7.], [5., 2., 1., 4., 9.]]),
"d": 2,
"c": torch.tensor([1., 2., 5., 2., 3.]),
"m": 5,
"range_lower": 0.0,
"range_upper": 4.0
}
Langermann["A"] = torch.transpose(Langermann["A_T"], 0, 1)
def f1(x, i):
val = 0
for j in range(Langermann["d"]):
val += (x[j] - Langermann["A"][i][j]) ** 2
return torch.exp(-val/torch.pi)
def f2(x, i):
val = 0
for j in range(Langermann["d"]):
val += (x[j] - Langermann["A"][i][j]) ** 2
return torch.cos(val * torch.pi)
def fi(x, i):
return Langermann["c"][i] * f1(x, i) * f2(x, i)
def env_cfun(x):
return torch.tensor([fi(x, i) for i in range(Langermann["m"])])
def gen_rand_points(bounds, num_samples):
points_nlzd = torch.rand(num_samples, bounds.shape[-1]).to(bounds)
return bounds[0] + (bounds[1] - bounds[0]) * points_nlzd
def optimize_ei(qEI, bounds, **options):
with gpt_settings.fast_computations(covar_root_decomposition=False):
cands_nlzd, _ = optimize_acqf(
qEI, bounds, **options,
)
return cands_nlzd
def optimize_ucb(qUCB, bounds, **options):
with gpt_settings.fast_computations(covar_root_decomposition=False):
cands_nlzd, _ = optimize_acqf(
qUCB, bounds, **options,
)
return cands_nlzd
torch.manual_seed(time.time())
device = torch.device(
"cpu") if not torch.cuda.is_available() else torch.device("cuda:4")
dtype = torch.float
def prepare_data(device=device, dtype=dtype):
bounds = torch.tensor(
[[0.0, 0.0], [4.0, 4.0]],
device=device,
dtype=dtype
)
X0 = torch.tensor([2.00299219, 1.006096], device=device, dtype=dtype)
def c_batched(X):
return torch.stack([env_cfun(x) for x in X])
c_true = env_cfun(X0)
global_minima = -torch.sum(c_true)
def neq_sum_squared_diff(samples):
vals = -torch.sum(samples, -1)
vals = vals.sub(global_minima).square().mul(-1.0)
return vals
objective = GenericMCObjective(neq_sum_squared_diff)
num_samples = 32
return c_batched, objective, bounds, num_samples, global_minima
n_init = 30
beta = 1.0
if SMOKE_TEST:
n_batches = 1
batch_size = 2
n_trials = 1
else:
n_batches = 70
batch_size = 1
n_trials = 3
models_used = (
"rnd",
"ei",
"ucb",
# "ei_hogp_cf",
"comp-ucb",
"bomcf"
)
with gpt_settings.cholesky_jitter(1e-4):
c_batched, objective, bounds, num_samples, global_minima = prepare_data()
train_X_init = gen_rand_points(bounds, n_init)
train_Y_init = c_batched(train_X_init)
train_X = {k: train_X_init.clone() for k in models_used}
train_Y = {k: train_Y_init.clone() for k in train_X}
for i in range(n_batches):
runtimes = {}
# get best observations, log status
best_f = {k: objective(v).max().detach() for k, v in train_Y.items()}
print(
f"It {i+1:>2}/{n_batches}, best obs.: "
", ".join([f"{k}: {v:.3f}" for k, v in best_f.items()])
)
# generate random candidates
tic = time.monotonic()
cands = {}
cands["rnd"] = gen_rand_points(bounds, batch_size)
runtimes["rnd"] = time.monotonic() - tic
# hyperparameters for LBFGS
optimize_acqf_kwargs = {
"q": batch_size,
"num_restarts": 50,
"raw_samples": 1024,
"dtype": torch.double
}
sampler = IIDNormalSampler(128)
# Vanilla EI
tic = time.monotonic()
train_Y_ei = objective(train_Y["ei"]).unsqueeze(-1)
model_ei = SingleTaskGP(
train_X["ei"],
train_Y_ei,
input_transform=Normalize(train_X["ei"].shape[-1]),
outcome_transform=Standardize(train_Y_ei.shape[-1]),
)
mll = ExactMarginalLogLikelihood(model_ei.likelihood, model_ei)
fit_gpytorch_torch(
mll, options={"lr": 0.01, "maxiter": 3000, "disp": False})
# generate qEI candidate (single output modeling)
qEI = qExpectedImprovement(
model_ei, best_f=best_f["ei"], sampler=sampler)
try:
cands["ei"] = optimize_ei(qEI, bounds, **optimize_acqf_kwargs)
except:
# if LBFGS doesn't converge, no new attempt
cands["ei"] = None
runtimes["ei"] = time.monotonic() - tic
# Vanilla UCB
tic = time.monotonic()
train_Y_ucb = objective(train_Y["ucb"]).unsqueeze(-1)
model_ucb = SingleTaskGP(
train_X["ucb"],
train_Y_ucb,
input_transform=Normalize(train_X["ucb"].shape[-1]),
outcome_transform=Standardize(train_Y_ucb.shape[-1]),
)
mll = ExactMarginalLogLikelihood(model_ucb.likelihood, model_ucb)
fit_gpytorch_torch(
mll, options={"lr": 0.01, "maxiter": 3000, "disp": False})
# generate qEI candidate (single output modeling)
qUCB = qUpperConfidenceBound(model_ucb, beta=beta, sampler=sampler)
try:
cands["ucb"] = optimize_ucb(qUCB, bounds, **optimize_acqf_kwargs)
except:
cands["ucb"] = None
runtimes["ucb"] = time.monotonic() - tic
# Comp-UCB
tic = time.monotonic()
models_comp_ucb = []
for itr in range(Langermann["m"]):
gp = SingleTaskGP(
train_X["comp-ucb"],
train_Y["comp-ucb"][:, itr:itr+1],
input_transform=Normalize(train_X["comp-ucb"].shape[-1]),
outcome_transform=Standardize(
train_Y["comp-ucb"][:, itr:itr+1].shape[-1])
)
mll = ExactMarginalLogLikelihood(gp.likelihood, gp)
fit_gpytorch_torch(
mll, options={"lr": 0.01, "maxiter": 3000, "disp": False})
models_comp_ucb.append(gp)
final_model_comp_ucb = ModelList(*models_comp_ucb)
qUCB_comp_ucb = qUpperConfidenceBound(
final_model_comp_ucb,
beta=beta,
sampler=sampler,
objective=objective
)
try:
cands["comp-ucb"] = optimize_ucb(qUCB_comp_ucb,
bounds, **optimize_acqf_kwargs)
except:
cands["comp-ucb"] = None
runtimes["comp-ucb"] = time.monotonic() - tic
# BOMCF
tic = time.monotonic()
models_bomcf = []
for itr in range(Langermann["m"]):
gp = SingleTaskGP(
train_X["bomcf"],
train_Y["bomcf"][:, itr:itr+1],
input_transform=Normalize(train_X["bomcf"].shape[-1]),
outcome_transform=Standardize(
train_Y["bomcf"][:, itr:itr+1].shape[-1])
)
mll = ExactMarginalLogLikelihood(gp.likelihood, gp)
fit_gpytorch_torch(
mll, options={"lr": 0.01, "maxiter": 3000, "disp": False})
models_bomcf.append(gp)
final_model_bomcf = ModelList(*models_bomcf)
qEI_bomcf = qExpectedImprovement(
final_model_bomcf,
best_f=best_f["bomcf"],
sampler=sampler,
objective=objective
)
try:
cands["bomcf"] = optimize_ei(
qEI_bomcf, bounds, **optimize_acqf_kwargs)
except:
cands["bomcf"] = None
runtimes["bomcf"] = time.monotonic() - tic
# HOGP
# tic = time.monotonic()
# model_ei_hogp_cf = HigherOrderGP(
# train_X["ei_hogp_cf"],
# train_Y["ei_hogp_cf"],
# outcome_transform=FlattenedStandardize(train_Y["ei_hogp_cf"].shape[1:]),
# input_transform=Normalize(train_X["ei_hogp_cf"].shape[-1]),
# latent_init="gp",
# )
# mll = ExactMarginalLogLikelihood(model_ei_hogp_cf.likelihood, model_ei_hogp_cf)
# fit_gpytorch_torch(mll, options={"lr": 0.01, "maxiter": 3000, "disp": False})
# # generate qEI candidate (multi-output modeling)
# qEI_hogp_cf = qExpectedImprovement(
# model_ei_hogp_cf,
# best_f=best_f["ei_hogp_cf"],
# sampler=sampler,
# objective=objective,
# )
# cands["ei_hogp_cf"] = optimize_ei(qEI_hogp_cf, bounds, **optimize_acqf_kwargs)
# runtimes["ei_hogp_cf"] = time.monotonic() - tic
# make observations and update data
regrets = {}
for k, Xold in train_X.items():
if cands[k] == None:
continue
Xnew = cands[k]
if Xnew.shape[0] > 0:
train_X[k] = torch.cat([Xold, Xnew])
train_Y[k] = torch.cat([train_Y[k], c_batched(Xnew)])
vals = -torch.sum(c_batched(Xnew), -1)
regrets[k] = vals - global_minima
beta = beta * (0.999 ** batch_size)
# Log outputs
# run times
with open(runtime_file, "a+") as f:
f.write(f"Iteration {i}\n")
for method in models_used:
f.write(f"{method} -- {runtimes[method]}\n")
f.close()
# regret
with open(regret_file, "a+") as f:
f.write(f"Iteration {i}\n")
for method in models_used:
if method in regrets:
f.write(f"{method} -- {regrets[method]}\n")
else:
f.write(f"{method} -- None\n")
f.close()
# output
print(f"{i}")
print(f"Runtimes: {runtimes}")
print(f"Regrets: {regrets}")