-
Notifications
You must be signed in to change notification settings - Fork 0
/
run.py
335 lines (286 loc) · 12.1 KB
/
run.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
#!/usr/bin/env python
import os
import sys
import argparse
import datetime
import uuid
import pandas
import GPy
import numpy as np
import matplotlib.pyplot as plt
import hpolib.benchmarks.synthetic_functions as hpolib_funcs
import hpolib.benchmarks.ml.conv_net
import hpolib.benchmarks.ml.fully_connected_network
import hpolib.benchmarks.ml.logistic_regression
import hpolib.benchmarks.ml.svm_benchmark
import evalset.test_funcs as stratified
from src.environments.embedding import embed
from src.utils import accumulate_immediate_regret, prepare_stratified_benchmark, prepare_benchmark
from src.algorithm import AcquisitionAlgorithm, RandomSearch
from src.acquisition_functions import EI, UCB
from src.models.regression import BayesianLinearRegression
from src.models.models import DNGOModel, GPModel
from src.models.neural_network import FeatureExtractorNetwork
from src.environments.logistic_regression import LogisticRegression
from src.environments.rosenbrock_benchmark import Rosenbrock
import config
parser = argparse.ArgumentParser()
parser.add_argument("-s", "--seed", type=int, default=None)
parser.add_argument("-m", "--model", type=str, default="dngo", choices=["dngo", "gp", "rand", "test"])
parser.add_argument("-g", "--group", type=str, default="standard")
ard_parser = parser.add_mutually_exclusive_group(required=False)
ard_parser.add_argument('--ard', dest='ard', action='store_true')
ard_parser.add_argument('--no-ard', dest='ard', action='store_false')
parser.set_defaults(ard=False)
# nn
parser.add_argument("-la", "--activations", type=str, default=["relu", "relu", "tanh"], nargs="+")
parser.add_argument("-nnt", "--nn_training", type=str, default="fixed", choices=["fixed", "retrain", "retrain-reset"])
parser.add_argument("-b", "--dim_basis", type=int, default=50)
parser.add_argument("-h1", "--dim_h1", type=int, default=50)
parser.add_argument("-h2", "--dim_h2", type=int, default=50)
parser.add_argument("-nn", "--num_nn", type=int, default=1)
parser.add_argument("-bs", "--batch_size", type=int, default=1000)
parser.add_argument("-e", "--epochs", type=int, default=1000)
parser.add_argument("-lr", "--lr", type=float, default=0.01)
parser.add_argument("-l2", "--weight_decay", type=float, default=0)
nn_aggregators = {
"median": np.median,
"max": np.max,
"average": np.average,
}
parser.add_argument("-agg", "--nn_aggregator", type=str, default="median", choices=nn_aggregators.keys())
# gp
parser.add_argument("-mcmc", "--num_mcmc", type=int, default=0)
# bo
obj_functions = {
'branin': hpolib_funcs.Branin(),
'hartmann3': hpolib_funcs.Hartmann3(),
'hartmann6': hpolib_funcs.Hartmann6(),
'camelback': hpolib_funcs.Camelback(),
'forrester': hpolib_funcs.Forrester(),
'bohachevsky': hpolib_funcs.Bohachevsky(),
'goldsteinprice': hpolib_funcs.GoldsteinPrice(),
'levy': hpolib_funcs.Levy(),
'rosenbrock': hpolib_funcs.Rosenbrock(),
'sinone': hpolib_funcs.SinOne(),
'sintwo': hpolib_funcs.SinTwo(),
'cnn_cifar10': hpolib.benchmarks.ml.conv_net.ConvolutionalNeuralNetworkOnCIFAR10(max_num_epochs=40),
'fcnet_mnist': hpolib.benchmarks.ml.fully_connected_network.FCNetOnMnist(max_num_epochs=100),
'lr_mnist': hpolib.benchmarks.ml.logistic_regression.LogisticRegressionOnMnist(),
'svm_mnist': hpolib.benchmarks.ml.svm_benchmark.SvmOnMnist(),
'logistic_regression_mnist': LogisticRegression(num_epochs=100),
'rosenbrock10D': Rosenbrock(d=10),
'rosenbrock8D': Rosenbrock(d=8),
}
stratified_obj_functions = {
'cube': stratified.Cube(),
'lennardjones6': stratified.LennardJones6(),
'alpine01': stratified.Alpine01(),
'corana': stratified.Corana(),
'plateau': stratified.Plateau(),
'gear': stratified.Gear(),
'griewank': stratified.Griewank(),
'dolan': stratified.Dolan(),
'jennrichsampson': stratified.JennrichSampson(),
}
stratified_obj_functions = {k: prepare_stratified_benchmark(func) for (k, func) in stratified_obj_functions.items()}
obj_functions = {k: prepare_benchmark(func) for (k, func) in obj_functions.items()}
obj_functions.update(stratified_obj_functions)
parser.add_argument("-f", "--obj_func", type=str, choices=obj_functions.keys(), default="branin")
parser.add_argument("-em", "--embedding", nargs='+', type=float, default=None)
acquisition_functions = {'EI': EI,
'UCB': UCB,}
parser.add_argument("-a", "--acq", type=str, choices=acquisition_functions.keys(), default="UCB")
parser.add_argument("-k", "--n_iter", type=int, default=100)
parser.add_argument("-init", "--n_init", type=int, default=2)
parser.add_argument("-iuuid", "--init_src", type=str, default=None)
# Constructing model
def create_model(args, init_data=None):
args_dict = vars(args)
seed = args_dict.get('seed', None)
rng = np.random.RandomState(seed)
# Support function parsed directly
if type(args.obj_func) == tuple:
f, bounds, f_opt = args.obj_func
else:
f, bounds, f_opt = obj_functions[args.obj_func]
input_dim = bounds.shape[0]
# nn training type
if args.nn_training == "fixed":
retrain_nn = False
reset_weights = False
elif args.nn_training == "retrain":
retrain_nn = True
reset_weights = False
elif args.nn_training == "retrain-reset":
retrain_nn = True
reset_weights = True
else:
retrain_nn = True
reset_weights = True
# Embedding
embedding = args_dict.get('embedding')
if type(embedding) is tuple:
embedding = list(embedding)
if type(embedding) is list and len(embedding) > 0:
embedded_dims = len(embedding)
A = np.array(embedding)
bounds = np.concatenate([bounds, [[0,1]] * embedded_dims])
f = embed(f, A, f_dim=input_dim)
f_opt = f_opt + np.sum(A)
input_dim = bounds.shape[0]
else:
embedded_dims = None
if args.model == "dngo":
nn = FeatureExtractorNetwork(
activations=args_dict.get('activations', ['relu', 'relu', 'tanh']),
input_dim=input_dim,
dim_basis=args.dim_basis,
dim_h1=args.dim_h1,
dim_h2=args.dim_h2,
epochs=args.epochs,
batch_size=args.batch_size,
lr=args.lr,
weight_decay=args.weight_decay)
# kernel = GPy.kern.Linear(args.dim_basis)
# kernel.variances.set_prior(GPy.priors.LogGaussian(0, 1))
# reg = GPyRegression(kernel=kernel, num_mcmc=args.num_mcmc, GPy.priors.Gamma.from_EV(1,4))
reg = BayesianLinearRegression(num_mcmc=args.num_mcmc)
model = DNGOModel(nn,
regressor=reg,
num_nn=args.num_nn,
ensemble_aggregator=nn_aggregators[args.nn_aggregator],
retrain_nn=retrain_nn,
reset_weights=reset_weights, )
elif args.model == "gp":
kernel = GPy.kern.RBF(input_dim, ARD=args.ard)
kernel.lengthscale.set_prior(GPy.priors.LogGaussian(0, 1))
kernel.variance.set_prior(GPy.priors.LogGaussian(0, 1))
model = GPModel(kernel=kernel, num_mcmc=args.num_mcmc, noise_prior=GPy.priors.LogGaussian(0, 1))
#model = GPyBOModel(kernel=kernel, num_mcmc=args.num_mcmc, noise_prior=GPyHorseshoePrior(0.1))
elif args.model == "rand":
bo = RandomSearch(f,
n_iter=args.n_iter,
bounds=bounds,
f_opt=f_opt,
rng=rng)
return bo
else:
raise Exception("`dngo` and `gp` should be the only two options")
acq = acquisition_functions[args.acq](model)
bo = AcquisitionAlgorithm(f, model,
acquisition_function=acq,
n_init=args_dict.get('n_init', 2),
n_iter=args.n_iter,
bounds=bounds,
embedded_dims=embedded_dims,
f_opt=f_opt,
init_data=init_data,
rng=rng)
return bo
if __name__ == '__main__':
plt.switch_backend('agg')
args = parser.parse_args()
if args.model == 'test':
import torch
import torch.cuda
if torch.cuda.is_available():
device = torch.device("cuda")
else:
device = torch.device("cpu")
print(device)
exit(0)
# outputs/{model_shortname}/
# command.txt
# immediate_regret.png
# obs.npy
# plots/
# i-{i}.png
def get_shorthand(k):
"""Transform e.g. `batch_size` into `bs` for
registered argparse argument `-bs` `--batch_size`
"""
for action in parser._actions:
if action.dest == k:
s = action.option_strings[0]
return remove_start_dash(s)
# fallback
return k
def generate_uuid():
return str(uuid.uuid4()).split('-')[0]
def remove_start_dash(s):
if s[:2] == "--":
return s[2:]
elif s[:1] == "-":
return s[1:]
else:
return s
uid = generate_uuid()
date = datetime.datetime.utcnow()
model_shortname = map(remove_start_dash, sys.argv[1:])
model_shortname = map(get_shorthand, model_shortname)
model_shortname = "-".join(model_shortname)
model_shortname = uid + "--" + model_shortname
print(model_shortname)
conf = config.get_config()
model_conf = config.get_model_config(uid, model_shortname, conf)
row = vars(args)
row['uuid'] = uid
row['date'] = date
row['name'] = model_shortname
os.makedirs(model_conf['folder'], exist_ok=True)
os.makedirs(model_conf['plot_folder'], exist_ok=True)
# log command to rerun easily
command = " ".join(sys.argv)
command_full = "python run.py " + " ".join(["--{} {}".format(k, v) for k, v in vars(args).items()])
with open(model_conf['command_path'], 'w') as file:
file.writelines([command, "\n", command_full])
if args.init_src:
import pandas as pd
df = pd.read_csv(conf['database'])
df = df.set_index('uuid')
name = df.loc[args.init_src]['name']
init_src_conf = config.get_model_config(args.init_src, name, conf)
X = np.load(init_src_conf['obs_X_path'])
Y = np.load(init_src_conf['obs_Y_path'])
init_data = (X,Y)
else:
init_data = None
bo = create_model(args, init_data=init_data)
has_quick_eval = bo.f_opt is not None
def backup(bo, i, x_new):
# Update row data
row['incumbent'] = bo.model.get_incumbent()[1]
row['num_steps'] = i
if has_quick_eval:
# Plot step
# path = os.path.join(model_conf['plot_folder'], "i-{}.png".format(i))
# bo.plot_prediction(x_new=x_new, save_dist=path)
# if args.embedding is not None:
# path = os.path.join(model_conf['plot_folder'], "i-embedding-{}.png".format(i))
# bo.plot_prediction(x_new=x_new, save_dist=path, plot_embedded_subspace=True)
# # Plot regret
ir = accumulate_immediate_regret(bo.model.Y, bo.f_opt)
# plot_ir([ir])
# plt.savefig(model_conf['regret_plot_path'])
# plt.close()
row['immediate_regret'] = ir[-1]
else:
row['immediate_regret'] = row['incumbent']
# Update observation record
np.save(model_conf['obs_X_path'], bo.model.X)
np.save(model_conf['obs_Y_path'], bo.model.Y)
try:
df = pandas.read_csv(conf['database'])
# Add missing columns (in case a new parameter was introduced)
missing_columns = set(row.keys()) - set(df.columns.values)
for col in missing_columns:
df[col] = pandas.Series(None, index=df.index)
df = df.set_index('uuid')
df.loc[uid] = pandas.Series(row)
df = df.reset_index()
except FileNotFoundError:
df = pandas.DataFrame([row])
df.to_csv(conf['database'], index=False)
bo.run(do_plot=False, periodic_interval=10, periodic_callback=backup)
backup(bo, args.n_iter, None)