-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy path_sober_wrapper.py
1051 lines (988 loc) · 42.2 KB
/
_sober_wrapper.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
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from botorch.fit import fit_gpytorch_mll
from botorch.models import SingleTaskGP
from copy import deepcopy
from gpytorch.constraints import Interval
from gpytorch.kernels import ScaleKernel, RBFKernel
from gpytorch.likelihoods import GaussianLikelihood
from gpytorch.mlls import ExactMarginalLogLikelihood
from math import exp, log
from .BOLFI._botorch_acquisition import SOBERUCB
from .BOLFI._gpytorch_bolfi_model import BOLFIModel
from multiprocessing import Pool
from scipy.stats import chi2
from ._prior import Uniform, Gaussian, TruncatedGaussian
from ._sober import Sober
from ._utils import TensorManager
from BASQ._basq import BASQ
from BASQ._scale_mmlt import ScaleMmltGP
import time
import torch
import warnings
class SoberWrapper:
def __init__(
self,
model=None,
data=None,
model_initial_samples=0,
mean=None,
covariance=None,
bounds=None,
prior='Uniform',
maximize=False,
use_bolfi=False,
weights=None,
custom_objective_and_loglikelihood=None,
transforms=None,
seed=None,
disable_numpy_mode=False,
parallelization=True,
visualizations=False,
true_optimum=None,
standalone=True,
**kwargs
):
"""
:param model:
A method that takes an array of numbers and returns an array
of numbers. These are intended to be parameters and
model evaluation, respectively. If not set,
`custom_objective_and_loglikelihood` needs to be used.
:param data:
The data that `model` will be fitted to. Has to have the
same shape as the return value of `model`. If not set,
`custom_objective_and_loglikelihood` needs to be used.
:param model_initial_samples:
Number of parameter samples from the prior, that get used as
initial training data together with their model evaluations.
:param mean:
A torch.Tensor of size n, where n is the number of model
parameters. The mean used for a Gaussian prior.
This will be internally modified with `transforms`.
:param covariance:
A torch.Tensor of size n x n, where n is the number of model
parameter. The covariance used for a Gaussian prior.
This will NOT be internally modified with `transforms`.
:param bounds:
A torch.Tensor of size 2 x n, where n is the number of model
parameters. Entry 0/1 is the list of lower/upper bounds.
This will be internally modified with `transforms`.
:param prior:
Defaults to the 'Uniform' prior within `bounds`.
May be set to 'Gaussian' using `mean` and `covariance` or
'TruncatedGaussian' using all three.
:param maximize:
If set to True, the model distance to data will be maximized
instead of minimized. Has no effect with custom objectives.
:param use_bolfi:
By default, use a simple RBF (Radial Basis Function) kernel.
This describes the surrogate model that will be trained.
If set to True, the surrogate model will get additional
structure that prepares it for optimization tasks. It will
be more inclined to have a parabolic shape, for instance.
For information, see https://doi.org/10.1002/batt.202200374,
or for the details, http://jmlr.org/papers/v17/15-017.html.
Recommended for optimization tasks that would otherwise
overwhelm the capabilities of the machine this runs on.
:param weights:
An optional list of weights that will be applied to the
distance between `model` and `data`. Defaults to 1.0.
:param custom_objective_and_loglikelihood:
To use SOBER directly through this wrapper, set this to a
function that returns a two-tuple, given the input of
'model'. First entry of the tuple is the objective value
that will be maximized, and second entry is the
Log-Likelihood.
:param transforms:
An optional list of 2-tuples, where the first entries will
be used to transform the model parameters before
parameterization, and the second entries will be used to
reverse that transformation to get the parameterization
results out of the calculations done in transformed space.
:param seed:
An optional seed to fix Random Number Generation.
:param disable_numpy_mode:
When set to True, the cast of parameter sets to NumPy arrays
will be disabled. Use this to use your torch-compatible
model in high-performance mode.
:param parallelization:
By default, `model` will get called on as many CPUs in
parallel as the system provides. If set to off, `model` will
be called on batch input and expected to parallelize itself.
:param visualizations:
If set to True, visualizations of the parameterization
process get plotted alongside it. Note that the plot windows
need to be closed then for the algorithm to progress.
:param true_optimum:
Will be used for visualizations if set. Has to have the same
shape as one parameter set.
:param standalone:
By default, when initializing an object of this class
directly, this is True and will initialize SOBER.
Will be set to False by inheriting classes if necessary.
:param **kwargs:
Additional keyword arguments will be passed to the `model`.
"""
if visualizations:
import matplotlib.pyplot as plt
from pandas import DataFrame
from seaborn import pairplot
self.tm = TensorManager()
self.model = model
self.model_kwargs = kwargs
self.data = data
if bounds is not None:
self.input_dim = len(bounds[0])
elif mean is not None:
self.input_dim = len(mean)
else:
raise ValueError(
"Either 'mean' and 'covariance' or 'bounds' needs to be set."
)
self.transforms = (
transforms or [(None, None) for _ in range(self.input_dim)]
)
for i in range(len(self.transforms)):
if not self.transforms[i][0] or not self.transforms[i][1]:
self.transforms[i] = (lambda x: x, lambda x: x)
if mean is not None:
self.mean = mean
batched_and_transformed_mean = self.apply_transform(
torch.atleast_2d(deepcopy(mean))
)
if bounds is not None:
self.bounds = bounds.to(device=self.tm.device, dtype=self.tm.dtype)
self.bounds[0] = self.apply_transform(
torch.atleast_2d(self.bounds[0])
)[0]
self.bounds[1] = self.apply_transform(
torch.atleast_2d(self.bounds[1])
)[0]
if mean is None:
self.mean = self.reverse_transform(torch.atleast_2d(
(self.bounds[0] + self.bounds[1]) / 2
))
elif mean is not None and covariance is not None:
self.bounds = torch.stack([
(
batched_and_transformed_mean
- 4 * torch.sqrt(torch.diag(covariance))
),
(
batched_and_transformed_mean
+ 4 * torch.sqrt(torch.diag(covariance))
),
]).to(device=self.tm.device, dtype=self.tm.dtype)
else:
raise ValueError(
"Either 'mean' and 'covariance' or 'bounds' needs to be set."
)
if 'Gaussian' in prior:
if covariance is None:
if bounds is None:
raise ValueError(
"Either 'covariance' or 'bounds' needs to be set."
)
covariance = torch.diag(
(self.bounds[1] - self.bounds[0])
/ (2 * chi2(self.input_dim).ppf(0.95)**0.5)
)
if prior == 'Uniform':
self.diagonalization = torch.diag(torch.ones(self.input_dim))
self.diagonalization = self.diagonalization.to(
device=self.tm.device, dtype=self.tm.dtype
)
self.prior = Uniform(torch.stack([
torch.zeros(self.input_dim), torch.ones(self.input_dim)
]))
elif prior == 'Gaussian':
_, self.diagonalization = torch.linalg.eigh(covariance)
self.prior = Gaussian(
self.normalize_input(batched_and_transformed_mean)[0],
(0.5 / 4)**2 * torch.diag(torch.ones(self.input_dim))
)
elif prior == 'TruncatedGaussian':
_, self.diagonalization = torch.linalg.eigh(covariance)
self.diagonalization = self.diagonalization.to(
device=self.tm.device, dtype=self.tm.dtype
)
self.prior = TruncatedGaussian(
self.normalize_input(batched_and_transformed_mean)[0],
(0.5 / 4)**2 * torch.diag(torch.ones(self.input_dim)),
torch.stack([
torch.zeros(self.input_dim), torch.ones(self.input_dim)
])
)
else:
raise ValueError(
"'prior' must be one of 'Uniform', 'Gaussian', or "
"'TruncatedGaussian'."
)
self.back_diagonalization = self.diagonalization.T
# Match eigenvalue order with parameter order.
# This will be only used for visualization, and even then it
# is only correct in the case of a diagonal prior covariance.
self.diag_order = [-1 for _ in range(self.input_dim)]
for i in range(self.input_dim):
result_orig = self.normalize_input(
self.apply_transform(torch.atleast_2d(deepcopy(self.mean)))
)
test_vector = self.apply_transform(
torch.atleast_2d(deepcopy(self.mean))
)
test_vector[0][i] = self.bounds[0][i]
result_eval = self.normalize_input(test_vector)
comparison = (result_orig - result_eval).abs()[0]
self.diag_order[i] = int(comparison.argmax())
self.current_MAP = self.mean
self.maximize = maximize
self.use_bolfi = use_bolfi
if weights is None and data is not None:
self.weights = 1.0
else:
self.weights = weights
self.custom_objective_and_loglikelihood = (
custom_objective_and_loglikelihood
)
self.disable_numpy_mode = disable_numpy_mode
self.parallelization = parallelization
if seed:
torch.manual_seed(seed)
self.true_optimum = true_optimum
if self.true_optimum is not None:
self.normalized_true_optimum = self.normalize_input(
self.apply_transform(
torch.atleast_2d(torch.Tensor(self.true_optimum))
)
)[0]
else:
self.normalized_true_optimum = None
self.X_all = self.prior.sample(model_initial_samples).to(
device=self.tm.device, dtype=self.tm.dtype
)
if visualizations:
pairgrid = pairplot(DataFrame(self.tm.numpy(self.X_all)))
pairgrid.figure.suptitle("correlation plot of prior sampling")
if self.normalized_true_optimum is not None:
for i in range(len(self.true_optimum)):
pairgrid.axes[i][i].scatter(
self.normalized_true_optimum[i],
0, s=100, marker='*', color='C1'
)
plt.show()
# To store and then check against the MAP samples
self.sober_iterations = 0
self.surrogate_effective_samples = 0
self.standalone = standalone
if self.standalone:
self.initialize_sober(visualizations)
def initialize_sober(self, visualizations=False):
if visualizations:
import matplotlib.pyplot as plt
self.Y_all, self.LL_all = self.objective_and_loglikelihood_function(
self.X_all, sober_batch=True
)
# Normalize Y_all and store the normalization parameters.
# For applying Y_batch later, de-normalization is needed.
self.Y_all_mean = self.Y_all.mean()
self.Y_all_std = self.Y_all.std()
self.Y_all = (self.Y_all - self.Y_all_mean) / self.Y_all_std
if visualizations:
_, ax = plt.subplots(1, 2, tight_layout=True, figsize=(8, 4))
ax[0].hist(self.tm.numpy(
self.Y_all_mean + self.Y_all_std * self.Y_all
), 50)
if self.custom_objective_and_loglikelihood is None:
ax[0].set_title("log distances histogram")
ax[0].set_xlabel("log distance values")
else:
ax[0].set_title("custom objective histogram")
ax[0].set_xlabel("custom objective values")
ax[0].set_ylabel("occurrences")
ax[1].hist(self.tm.numpy(self.LL_all), 50)
ax[1].set_title("log likelihoods histogram")
ax[1].set_xlabel("log likelihood values")
plt.show()
# Sets self.surrogate_model.
self.set_rbf_model(self.X_all, self.Y_all, use_bolfi=self.use_bolfi)
self.sober = Sober(self.prior, self.surrogate_model)
self.results = []
self.total_sober_iterations = 0
self.total_model_samples = []
def process_evaluations(self, evaluations, sober_batch):
"""
Gets called after model evaluation if standalone is False.
:param evaulations:
Evaluations of ``self.model``.
:param sober_batch: bool
Used to mark whether the evaluations to be processed are
part of a batch or not. If not, usually skip processing.
"""
pass
def normalize_input(self, x):
"""
Normalizes transformed parameter values to the unit cube.
:param x:
An array of numbers that are valid model parameters.
:returns:
An array of numbers that are between 0 and 1.
"""
return torch.matmul(
self.diagonalization,
(
(x - self.bounds[0]) / (self.bounds[1] - self.bounds[0])
)[..., None]
).squeeze(2)
def denormalize_input(self, x):
"""
Maps the unit cube onto the transformed parameter space.
:param x:
An array of numbers that are between 0 and 1.
:returns:
An array of numbers inside the parameter bounds.
"""
return self.bounds[0] + (self.bounds[1] - self.bounds[0]) * (
torch.matmul(self.back_diagonalization, x[..., None])
).squeeze(2)
def apply_transform(self, x):
"""
Transforms from parameter space to transformed space.
:param x:
An array of numbers from parameter space.
:returns:
An array of numbers, transformed with ``self.transforms``.
"""
if x.dim() > 1:
for i, transform in enumerate(self.transforms):
x.T[i] = transform[0](x.T[i])
else:
for i, transform in enumerate(self.transforms):
x[i] = transform[0](x[i])
return x
def reverse_transform(self, x):
"""
Reverses transformed space into parameter space.
:param x:
An array of numbers from transformed space.
:returns:
An array of numbers that are valid model parameters.
"""
if x.dim() > 1:
for i, transform in enumerate(self.transforms):
x.T[i] = transform[1](x.T[i])
else:
for i, transform in enumerate(self.transforms):
x[i] = transform[1](x[i])
return x
def apply_transform_and_normalize_one_variable(self, var, index):
"""
Translates one variable from parameter space to unit cube.
:param var:
The value of the variable.
:param index:
The index of the variable.
:returns:
A Python float in the unit cube.
"""
x = deepcopy(self.current_MAP)
x[index] = var
return float(self.normalize_input(self.apply_transform(
torch.atleast_2d(x)
))[0][self.diag_order[index]])
def denormalize_and_reverse_transform_one_variable(self, var, index):
"""
Translates one variable from unit cube to parameter space.
:param var:
The value of the variable.
:param index:
The index of the variable.
:returns:
A Python float in parameter space.
"""
x = deepcopy(self.current_MAP)
x = self.normalize_input(self.apply_transform(torch.atleast_2d(x)))[0]
x[self.diag_order[index]] = var
return float(self.reverse_transform(self.denormalize_input(
torch.atleast_2d(x)
))[0][index])
def model_wrapper(self, x):
"""
Calls ``self.model``, with or without NumPy conversion.
:param x:
An array of numbers that are valid model parameters.
:returns:
A torch.Tensor of the model results.
"""
if self.disable_numpy_mode:
return self.model(x, **self.model_kwargs)
else:
return torch.Tensor(self.model(
x.cpu().detach().numpy(), **self.model_kwargs
)).to(device=self.tm.device, dtype=self.tm.dtype)
@staticmethod
def parallelizable_model_wrapper(
x, model, disable_numpy_mode, device, dtype, model_kwargs
):
if disable_numpy_mode:
return model(x, **model_kwargs)
else:
result = torch.tensor(
model(x.cpu().detach().numpy(), **model_kwargs)
)
if result.dtype == torch.cfloat or result.dtype == torch.cdouble:
return result.to(device=device)
else:
return result.to(device=device, dtype=dtype)
def distance_function(self, observations):
"""
The distance between ``self.data`` and model evaluation.
:param observations:
A ``self.model`` evaulation.
:returns:
The 2-norm weighted distance between model and data.
"""
return (
(observations - self.data) * self.weights
).view(observations.shape[0], -1).norm(dim=1).to(
device=self.tm.device, dtype=self.tm.dtype
)
def default_objective_function(self, observations):
"""
Takes the negative logarithm of distance for maximization.
:param observations:
A ``self.model`` evaluation.
:returns:
The negative of the logarithm of ``self.distance_function``.
"""
if isinstance(observations, list):
try:
observations = torch.stack(observations)
except RuntimeError: # inhomogeneous observation shape
return torch.tensor([
-self.distance_function(obs.unsqueeze(0)).log()
for obs in observations
]).to(device=self.tm.device, dtype=self.tm.dtype)
return -self.distance_function(observations).log()
def evaluate_model(self, x):
"""
Calls the model in parallel and produces batch output.
:param x:
An array of numbers after transformation and normalization.
May be batched, where the batch-dimension is the first one.
:returns:
An array of cost function values at x.
"""
randomness = 'different'
transformed_batch = self.denormalize_input(torch.atleast_2d(x))
# torch.vmap works with in-place operations only.
batch = torch.vmap(
self.reverse_transform, randomness=randomness
)(transformed_batch)
# Since this calls the model, use multiprocessing instead.
if self.parallelization:
parallel_input = [
(
batch_entry,
self.model,
self.disable_numpy_mode,
self.tm.device,
self.tm.dtype,
self.model_kwargs,
)
for batch_entry in batch
]
try:
with Pool() as p:
evaluations = p.starmap(
SoberWrapper.parallelizable_model_wrapper,
parallel_input
)
except AttributeError as e:
raise AttributeError(
"The 'model' must be defined in a global scope, else "
"calculating multiple instances in parallel can't work. "
"Original error message: " + str(e)
)
else:
evaluations = SoberWrapper.parallelizable_model_wrapper(
batch,
self.model,
self.disable_numpy_mode,
self.tm.device,
self.tm.dtype,
self.model_kwargs
)
return evaluations
def objective_and_loglikelihood_function(self, x, sober_batch=True):
"""
Simplest choice for a Log-Likelihood, basically a rescaling.
:param x:
An array of numbers after transformation and normalization.
May be batched, where the batch-dimension is the first one.
:param sober_batch:
Gets passed to ``self.process_evaluations``.
:returns:
2-tuple: an array of objective values at x, and an array of
Log-Likelihood values at x.
"""
if self.custom_objective_and_loglikelihood is not None:
randomness = 'different'
transformed_batch = self.denormalize_input(torch.atleast_2d(x))
# torch.vmap works with in-place operations only.
batch = torch.vmap(
self.reverse_transform, randomness=randomness
)(transformed_batch)
return self.custom_objective_and_loglikelihood(batch)
evaluations = self.evaluate_model(x)
if not self.standalone:
self.process_evaluations(evaluations, sober_batch)
N = self.input_dim
objective = self.default_objective_function(evaluations)
if self.maximize:
objective = -objective
loglikelihood = -0.5 * (1 + log(2 * torch.pi / N) - objective) * N
return objective, loglikelihood
def set_rbf_model(self, x, y, use_bolfi=False):
"""
Sets up a simple RBF or advanced BOLFI surrogate.
:param x:
The independent variables.
:param y:
The dependent variables.
:param use_bolfi:
Whether or not to use the BOLFI surrogate. Recommended for
optimization tasks that would otherwise overwhelm the PC.
"""
base_kernel = RBFKernel(ard_num_dims=x.shape[-1])
covar_module = ScaleKernel(base_kernel)
train_y = y.view(-1).unsqueeze(1)
likelihood = GaussianLikelihood(noise_constraint=Interval(1e-2, 10))
if use_bolfi:
surrogate_model = BOLFIModel(
x, train_y, likelihood=likelihood, bounds=self.bounds
)
else:
surrogate_model = SingleTaskGP(
x, train_y, likelihood=likelihood, covar_module=covar_module
)
if self.tm.is_cuda():
self.surrogate_model = surrogate_model.cuda()
else:
self.surrogate_model = surrogate_model
def optimize_model(self):
"""Trains the (RBF) surrogate model on the new data."""
self.surrogate_model.train()
self.surrogate_model.likelihood.train()
self.surrogate_model.set_train_data(
self.X_all, self.Y_all, strict=False
)
mll = ExactMarginalLogLikelihood(
self.surrogate_model.likelihood, self.surrogate_model
)
fit_gpytorch_mll(mll)
self.surrogate_model.eval()
self.surrogate_model.likelihood.eval()
def visualize_results(self):
"""Visualizes convergence of SOBER (call 'run' first)."""
import matplotlib.pyplot as plt
_, ax = plt.subplots(1, 2, tight_layout=True, figsize=(8, 4))
ax[0].plot(
self.total_model_samples,
[entry[1] for entry in self.results],
'bo-',
label="observed maximum"
)
ax[0].legend()
ax[0].set_xlabel("index of batches")
ax[0].set_ylabel("objective")
ax[1].plot(
self.total_model_samples,
[entry[0] for entry in self.results],
'bo-'
)
ax[1].set_xlabel("index of batches")
ax[1].set_ylabel("overhead [s]")
plt.show()
def results_to_dict(self):
"""Collects results in basic Python objects (lists, dicts)."""
return {
"parameters evaluations": [
list(entry) for entry in self.X_all.cpu().detach().numpy()
],
"objective evaluations": list((
self.Y_all_mean + self.Y_all_std * self.Y_all
).cpu().detach().numpy()),
"Log-Likelihood evaluations": list(
self.LL_all.cpu().detach().numpy()
),
"results": {
"duration [s]": [res[0] for res in self.results],
"best observed": [res[1] for res in self.results],
},
}
def run_SOBER(
self,
sober_iterations,
model_samples_per_iteration,
surrogate_samples=None,
surrogate_effective_samples=None,
acquisition_function=None,
visualizations=False,
verbose=True,
**kwargs
):
"""
Calls the basic SOBER routines in order.
:param sober_iterations:
The number of SOBER loops. In each loop,
`model_samples_per_iteration` samples are taken from the
current SOBER surrogate. At the end of each loop, this
surrogate gets re-trained with those new samples.
:param model_samples_per_iteration:
The batch size, i.e., how many samples get taken from the
current SOBER surrogate model before the surrogate gets
updated by the new samples (with the model evaluations).
:param surrogate_samples:
Number of random samples taken from the surrogate at the
beginning of each loop. These form the basis for a
surrogate-surrogate, which will be used to select the
model evaluation points. This number can be very high, as
the surrogate is very performant; the reason for the
surrogate-surrogate is that it's tractable for the
non-random model sample selection calculations.
Defaults to 4 times `model_samples_per_iteration`.
:param surrogate_effective_samples:
The number of effective samples the surrogate gets reduced
to before it gets used for sample selection calculations.
This is intended to reduce the internal complexity of the
surrogate-surrogate, as its number of "kernels" would
correspond to `surrogate_samples` elsewise. Usually, the
number of samples needed to cover the parameter space is way
higher than the number of "kernels" a surrogate-surrogate
needs. So to speed up calculations, the surrogate-surrogate
gets reduced to this number of "kernels".
Defaults to 2 times `model_samples_per_iteration`.
:param acquisition_function:
The heuristic tacked on to the sample selection
calculations. If None, but use_bolfi=True at initialization,
the Upper Confidence Bound (UCB) acquisition function will
be set up and used, as it is part of the BOLFI formula.
Note: the original BOLFI minimizes, so it uses Lower CB.
:param visualizations:
If set to True, visualizations of the parameterization
process get plotted alongside it. Note that the plot windows
need to be closed then for the algorithm to progress.
:param verbose:
If set to True, status updates of the parameterization get
logged to stdout.
:param kwargs:
Please ignore; it is an implementation detail that makes
``run_SOBER_adaptively`` easier to maintain.
"""
surrogate_effective_samples = (
surrogate_effective_samples or 2 * model_samples_per_iteration
)
if model_samples_per_iteration >= surrogate_effective_samples:
raise ValueError(
"Number of model evaluations must be lower than number "
"of surrogate evaluations."
)
surrogate_samples = (
surrogate_samples or 4 * model_samples_per_iteration
)
for _ in range(1, sober_iterations + 1):
self.sober_iterations += 1
time_start = time.monotonic()
self.optimize_model()
# For some reason, calling this too early would not get rid
# of the superfluous "input matches training data" error.
warnings.simplefilter("ignore")
self.sober.update_model(self.surrogate_model)
if acquisition_function is None and self.use_bolfi:
acquisition_function = SOBERUCB(
self.surrogate_model, sample_size=len(self.X_all)
)
X_batch = self.sober.next_batch(
surrogate_samples,
surrogate_effective_samples,
model_samples_per_iteration,
calc_obj=acquisition_function,
verbose=verbose
)
self.surrogate_effective_samples = surrogate_effective_samples
time_end = time.monotonic()
time_interval = time_end - time_start
self.X_all = torch.cat((self.X_all, X_batch), dim=0)
Y_batch, LL_batch = self.objective_and_loglikelihood_function(
X_batch, sober_batch=True
)
# De-normalize Y_all before mixing it with Y_batch.
self.Y_all = self.Y_all_mean + self.Y_all_std * self.Y_all
self.Y_all = torch.cat((self.Y_all, Y_batch), dim=0)
# Now normalize the new Y_all.
self.Y_all_mean = self.Y_all.mean()
self.Y_all_std = self.Y_all.std()
self.Y_all = (self.Y_all - self.Y_all_mean) / self.Y_all_std
self.LL_all = torch.cat((self.LL_all, LL_batch), dim=0)
Y_all_denorm = self.Y_all_mean + self.Y_all_std * self.Y_all
if verbose:
print(
f"{len(self.X_all)}) "
f"Best objective: {Y_all_denorm.max().item():.5e} "
f"Best Log-Likelihood: {self.LL_all.max().item():.5e}"
)
mspersample = time_interval / model_samples_per_iteration * 1e3
print(
f"Acquisition time [s]: {time_interval:.5e}, "
f"per sample [ms]: {mspersample:.5e}"
)
self.results.append([time_interval, Y_all_denorm.max().item()])
self.total_sober_iterations += 1
if self.total_model_samples:
self.total_model_samples.append(
self.total_model_samples[-1] + model_samples_per_iteration
)
else:
self.total_model_samples.append(model_samples_per_iteration)
if visualizations:
self.visualize_results()
def run_BASQ(
self,
integration_nodes,
basq_samples=None,
basq_effective_samples=None,
basq_posterior_samples=None,
map_samples=None,
dampening=0,
visualizations=False,
return_raw_samples=False,
verbose=True,
**kwargs
):
"""
Performs BASQ (use 'run_SOBER' first).
:param integration_nodes:
Number of nodes for the numerical integration, i.e.,
quadrature. These will be optimally chosen. May be thought
of as the BASQ equivalent of the model samples in SOBER.
:param basq_samples:
Number of random samples taken from the BASQ model as the
basis for the computation of the integration nodes.
Defaults to 4 times `integration_nodes`.
:param basq_effective_samples:
The number of effective samples the `basq_samples`
evaluations get reduced to. These will form the set of nodes
to choose from for the integration nodes.
Defaults to 2 times `integration_nodes`.
:param basq_posterior_samples:
Number of samples to draw from the BASQ posterior for
visualization purposes. Defaults to `integration_nodes`.
:param ratio_wkde:
The dampening factor used when sampling the BASQ posterior.
Defaults to 0, i.e., only the posterior. Any value between
this and 1 will include that fraction of the prior.
:param map_samples:
Number of samples to draw from the BASQ posterior in search
of the Maximum A Posteriori location (MAP). Defaults to the
'surrogate_effective_samples' used in the SOBER call,
multiplied by the total amount of SOBER iterations.
:param visualizations:
If set to True, visualizations of the parameterization
process get plotted alongside it. Note that the plot windows
need to be closed then for the algorithm to progress.
:param return_raw_samples:
Set to True if you want to get the samples taken from the
normalized posterior. Else, parameter values will be given.
:param verbose:
If set to True, status updates of the quadrature get logged
to stdout.
:param **kwargs:
Please ignore; it is an implementation detail that makes
``run_SOBER_adaptively`` easier to maintain.
:returns:
A 5-tuple of the posterior samples, the MAP, the best
observed model sample, the expected log marginal likelihood,
and the variance of the log marginal likelihood.
"""
map_samples = map_samples or (
self.sober_iterations * self.surrogate_effective_samples
)
if map_samples < self.surrogate_effective_samples:
raise ValueError(
"Number of MAP samples must be higher than number of "
"surrogate effective samples."
)
basq_samples = basq_samples or 4 * integration_nodes
basq_effective_samples = (
basq_effective_samples or 2 * integration_nodes
)
basq_posterior_samples = basq_posterior_samples or integration_nodes
if visualizations:
import matplotlib.pyplot as plt
from pandas import DataFrame
from seaborn import pairplot
if verbose:
from tabulate import tabulate
time_start = time.monotonic()
basq_base_kernel = RBFKernel(ard_num_dims=self.X_all.shape[-1])
basq_covar_module = ScaleKernel(basq_base_kernel)
basq_surrogate_model = ScaleMmltGP(
self.X_all, self.LL_all, basq_covar_module
)
time_setup = time.monotonic()
basq = BASQ(
self.prior,
basq_surrogate_model,
self.sober,
ratio_wkde=1 - dampening,
)
time_init = time.monotonic()
(
log_expected_marginal_likelihood,
log_approx_variance_marginal_likelihood
) = basq.quadrature(
basq_samples, basq_effective_samples, integration_nodes
)
time_quad = time.monotonic()
taken_samples = basq.sampling_posterior(basq_posterior_samples)
time_samples = time.monotonic()
MAP_normalized = basq.MAP(map_samples)
time_map = time.monotonic()
if verbose:
print(
"BASQ: setup", time_setup - time_start,
"init", time_init - time_setup,
"quad", time_quad - time_init,
"samples", time_samples - time_quad,
"MAP", time_map - time_samples,
)
MAP = self.reverse_transform(self.denormalize_input(
torch.atleast_2d(deepcopy(MAP_normalized))
)[0])
self.current_MAP = MAP
best_observed_normalized = self.X_all[(
self.Y_all_mean + self.Y_all_std * self.Y_all
).argmax()]
best_observed = self.reverse_transform(self.denormalize_input(
torch.atleast_2d(deepcopy(best_observed_normalized))
)[0])
if verbose:
table = [
["Location", "Parameters", "Posterior", "Log-Likelihood"],
[
"MAP",
MAP,
basq.posterior(MAP_normalized.unsqueeze(0)).cpu().detach(),
self.objective_and_loglikelihood_function(
MAP_normalized.unsqueeze(0), sober_batch=False
)[1].cpu().detach()
],
[
"best observed",
best_observed,
basq.posterior(
best_observed_normalized.unsqueeze(0)
).cpu().detach(),
self.objective_and_loglikelihood_function(
best_observed_normalized.unsqueeze(0),
sober_batch=False
)[1].cpu().detach()
]
]
print(tabulate(table, headers='firstrow', tablefmt='pretty'))
if visualizations:
# Minimal necessary transformation: re-ordering.
# This would be most succinctly be done by applying the
# back_diagonalization matrix, but that would also skew
# the covariances. So just use diag_order instead.
orig_order_samples = torch.zeros_like(taken_samples)
for par_index, raw_index in enumerate(self.diag_order):
orig_order_samples.T[par_index] = taken_samples.T[raw_index]
df = DataFrame(orig_order_samples.numpy())
if verbose:
df.describe()
pairgrid = pairplot(df, kind='kde')
# Rotate the labels for better readability.
for i in range(self.input_dim):
plt.setp(
pairgrid.axes[i][0].get_yticklabels(),
rotation=45,
ha='right',
rotation_mode='anchor'
)
plt.setp(
pairgrid.axes[self.input_dim - 1][i].get_xticklabels(),
rotation=45,
ha='right',
rotation_mode='anchor'
)
for i in range(self.input_dim):
for axis in (
pairgrid.axes[self.input_dim - 1][i].xaxis,
pairgrid.axes[i][0].yaxis,
):
fmt = "{:.3g}"
axis.set_major_formatter(lambda x, _, index=i: fmt.format(
self.denormalize_and_reverse_transform_one_variable(
x, index
)
))
if self.normalized_true_optimum is not None:
for i in range(len(self.true_optimum)):
pairgrid.axes[i][i].scatter(
self.normalized_true_optimum[i],
0, s=100, marker='*', color='tab:orange'
)
pairgrid.tight_layout()
plt.show()
return (
taken_samples
if return_raw_samples else