-
Notifications
You must be signed in to change notification settings - Fork 372
Expand file tree
/
Copy pathtest_surrogate.py
More file actions
2360 lines (2239 loc) · 98.1 KB
/
test_surrogate.py
File metadata and controls
2360 lines (2239 loc) · 98.1 KB
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
#!/usr/bin/env python3
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
# pyre-strict
import dataclasses
import inspect
import math
import warnings
from contextlib import ExitStack
from copy import copy
from itertools import product
from typing import Any
from unittest.mock import MagicMock, Mock, patch
import numpy as np
import torch
from ax.core.search_space import SearchSpaceDigest
from ax.exceptions.core import UnsupportedError, UserInputError
from ax.exceptions.model import ModelError
from ax.generators.torch.botorch_modular.acquisition import Acquisition
from ax.generators.torch.botorch_modular.kernels import (
default_loc_and_scale_for_lognormal_lengthscale_prior,
DefaultRBFKernel,
ScaleMaternKernel,
)
from ax.generators.torch.botorch_modular.surrogate import (
_construct_default_input_transforms,
_construct_specified_input_transforms,
_extract_model_kwargs,
_make_botorch_input_transform,
_submodel_input_constructor_mtgp,
submodel_input_constructor,
Surrogate,
SurrogateSpec,
)
from ax.generators.torch.botorch_modular.utils import (
choose_model_class,
fit_botorch_model,
ModelConfig,
)
from ax.generators.torch.utils import predict_from_model
from ax.generators.torch_base import TorchOptConfig
from ax.generators.utils import best_in_sample_point
from ax.utils.common.constants import Keys
from ax.utils.common.testutils import TestCase
from ax.utils.stats.model_fit_stats import DIAGNOSTIC_FNS
from ax.utils.testing.mock import mock_botorch_optimize
from ax.utils.testing.torch_stubs import get_torch_test_data
from ax.utils.testing.utils import generic_equals
from botorch.exceptions.errors import ModelFittingError
from botorch.models import ModelListGP, SingleTaskGP
from botorch.models.deterministic import GenericDeterministicModel
from botorch.models.fully_bayesian import SaasFullyBayesianSingleTaskGP
from botorch.models.fully_bayesian_multitask import SaasFullyBayesianMultiTaskGP
from botorch.models.gp_regression_mixed import MixedSingleTaskGP
from botorch.models.model import Model, ModelList # noqa: F401 -- used in Mocks.
from botorch.models.multitask import MultiTaskGP
from botorch.models.pairwise_gp import PairwiseGP, PairwiseLaplaceMarginalLogLikelihood
from botorch.models.transforms.input import (
ChainedInputTransform,
LearnedFeatureImputation,
Log10,
Normalize,
)
from botorch.models.transforms.outcome import OutcomeTransform, Standardize
from botorch.utils.datasets import MultiTaskDataset, SupervisedDataset
from botorch.utils.evaluation import compute_in_sample_model_fit_metric
from botorch.utils.sampling import draw_sobol_samples
from botorch.utils.transforms import standardize
from botorch.utils.types import DEFAULT
from gpytorch.constraints import GreaterThan, Interval
from gpytorch.kernels import Kernel, LinearKernel, MaternKernel, RBFKernel, ScaleKernel
from gpytorch.likelihoods import FixedNoiseGaussianLikelihood, GaussianLikelihood
from gpytorch.likelihoods.noise_models import HomoskedasticNoise
from gpytorch.mlls import ExactMarginalLogLikelihood, LeaveOneOutPseudoLikelihood
from gpytorch.priors import LogNormalPrior
from pyre_extensions import assert_is_instance, none_throws
from torch import Tensor
from torch.nn import ModuleList # @manual -- autodeps can't figure it out.
ACQUISITION_PATH = f"{Acquisition.__module__}"
CURRENT_PATH = f"{__name__}"
SURROGATE_PATH = f"{Surrogate.__module__}"
UTILS_PATH = f"{ModelConfig.__module__}"
RANK = "rank"
class SingleTaskGPWithDifferentConstructor(SingleTaskGP):
def __init__(self, train_X: Tensor, train_Y: Tensor) -> None:
super().__init__(train_X=train_X, train_Y=train_Y)
class SurrogateInputConstructorsTest(TestCase):
def test__extract_model_kwargs(self) -> None:
feature_names = ["a", "b"]
bounds = [(0.0, 1.0), (0.0, 1.0)]
with self.subTest("Multi-fidelity with task features not supported"):
search_space_digest = SearchSpaceDigest(
feature_names=feature_names,
bounds=bounds,
task_features=[0],
fidelity_features=[0],
)
with self.assertRaisesRegex(
NotImplementedError, "Multi-Fidelity GP models with task_features"
):
_extract_model_kwargs(
search_space_digest=search_space_digest,
botorch_model_class=SingleTaskGP,
)
with self.subTest("Multiple task features not supported"):
search_space_digest = SearchSpaceDigest(
feature_names=feature_names,
bounds=bounds,
task_features=[0, 1],
)
with self.assertRaisesRegex(
NotImplementedError, "Multiple task features are not supported"
):
_extract_model_kwargs(
search_space_digest=search_space_digest,
botorch_model_class=SingleTaskGP,
)
with self.subTest("Cannot fit MultiTaskGP without task feature."):
search_space_digest = SearchSpaceDigest(
feature_names=feature_names,
bounds=bounds,
task_features=[],
)
with self.assertRaisesRegex(
ModelFittingError, "Cannot fit MultiTaskGP without task feature."
):
_extract_model_kwargs(
search_space_digest=search_space_digest,
botorch_model_class=MultiTaskGP,
)
with self.subTest("Task feature provided, fidelity and categorical not"):
search_space_digest = SearchSpaceDigest(
feature_names=feature_names,
bounds=bounds,
task_features=[1],
)
model_kwargs = _extract_model_kwargs(
search_space_digest=search_space_digest,
botorch_model_class=SingleTaskGP,
)
self.assertSetEqual(set(model_kwargs.keys()), {"task_feature"})
self.assertEqual(model_kwargs["task_feature"], -1)
with self.subTest("No feature info provided"):
search_space_digest = SearchSpaceDigest(
feature_names=feature_names,
bounds=bounds,
)
model_kwargs = _extract_model_kwargs(
search_space_digest=search_space_digest,
botorch_model_class=SingleTaskGP,
)
self.assertEqual(len(model_kwargs.keys()), 0)
with self.subTest("Fidelity and categorical features provided"):
search_space_digest = SearchSpaceDigest(
feature_names=feature_names,
bounds=bounds,
fidelity_features=[0],
categorical_features=[1],
)
model_kwargs = _extract_model_kwargs(
search_space_digest=search_space_digest,
botorch_model_class=SingleTaskGP,
)
self.assertSetEqual(
set(model_kwargs.keys()), {"fidelity_features", "categorical_features"}
)
self.assertEqual(model_kwargs["fidelity_features"], [0])
self.assertEqual(model_kwargs["categorical_features"], [1])
with self.subTest("MTGP without task feature input"):
search_space_digest = SearchSpaceDigest(
feature_names=feature_names, bounds=bounds
)
# Mock signature to remove task_feature.
with patch(
"ax.generators.torch.botorch_modular.surrogate.inspect.signature",
return_value=inspect.signature(SingleTaskGP),
):
model_kwargs = _extract_model_kwargs(
search_space_digest=search_space_digest,
botorch_model_class=MultiTaskGP,
)
self.assertEqual(len(model_kwargs.keys()), 0)
def test__make_botorch_input_transform(self) -> None:
feature_names = ["a", "b"]
bounds = [(0.0, 1.0), (0.0, 1.0)]
search_space_digest = SearchSpaceDigest(
feature_names=feature_names,
bounds=bounds,
)
dataset = SupervisedDataset(
X=torch.tensor([[1.0, 2.0], [3.0, 4.0]]),
Y=torch.tensor([[1.0], [2.0]]),
feature_names=feature_names,
outcome_names=["metric"],
)
with self.subTest("Empty list of specified input transforms"):
with patch(
f"{SURROGATE_PATH}._construct_specified_input_transforms",
wraps=_construct_specified_input_transforms,
) as mock_construct_specified_input_transforms:
transform = _make_botorch_input_transform(
input_transform_classes=[],
input_transform_options={},
search_space_digest=search_space_digest,
dataset=dataset,
)
mock_construct_specified_input_transforms.assert_called_once_with(
input_transform_classes=[],
input_transform_options={},
search_space_digest=search_space_digest,
dataset=dataset,
)
self.assertIsNone(transform)
with self.subTest("Empty set of default transforms"):
with patch(
f"{SURROGATE_PATH}._construct_default_input_transforms",
wraps=_construct_default_input_transforms,
) as mock_construct_default_input_transforms:
transform = _make_botorch_input_transform(
input_transform_classes=DEFAULT,
input_transform_options={},
search_space_digest=search_space_digest,
dataset=dataset,
)
mock_construct_default_input_transforms.assert_called_once_with(
search_space_digest=search_space_digest,
dataset=dataset,
)
self.assertIsNone(transform)
with self.subTest("Multiple specified transforms"):
transform = _make_botorch_input_transform(
input_transform_classes=[Normalize, Log10],
input_transform_options={"Log10": {"indices": [0]}},
search_space_digest=search_space_digest,
dataset=dataset,
)
transform = assert_is_instance(transform, ChainedInputTransform)
tf_values = list(transform.values())
self.assertEqual(len(tf_values), 2)
self.assertIsInstance(tf_values[0], Normalize)
self.assertIsInstance(tf_values[1], Log10)
self.assertEqual(
assert_is_instance(tf_values[1].indices, Tensor).tolist(), [0]
)
bounds = [(1.0, 5.0), (2.0, 10.0)]
search_space_digest = SearchSpaceDigest(
feature_names=feature_names,
bounds=bounds,
task_features=[1],
)
with self.subTest("Default Normalize transform"):
transform = _make_botorch_input_transform(
input_transform_classes=DEFAULT,
input_transform_options={},
search_space_digest=search_space_digest,
dataset=dataset,
)
transform = assert_is_instance(transform, Normalize)
self.assertEqual(transform.indices.tolist(), [0])
self.assertEqual(transform.bounds.tolist(), [[1.0], [5.0]])
def test_submodel_input_constructor_mtgp_map_heterogeneous(self) -> None:
"""_submodel_input_constructor_mtgp passes map_heterogeneous_to_full
to construct_inputs when LFI is configured, enabling zero-padded
heterogeneous datasets to be used with MultiTaskGP."""
ds_target = SupervisedDataset(
X=torch.tensor([[1.0, 0.0], [2.0, 0.0]]),
Y=torch.tensor([[1.0], [2.0]]),
feature_names=["x0", "task"],
outcome_names=["y_task_0"],
)
ds_source = SupervisedDataset(
X=torch.tensor([[3.0, 4.0, 1.0], [5.0, 6.0, 1.0]]),
Y=torch.tensor([[3.0], [4.0]]),
feature_names=["x0", "x1", "task"],
outcome_names=["y_task_1"],
)
mt_dataset = MultiTaskDataset(
datasets=[ds_target, ds_source],
target_outcome_name="y_task_0",
task_feature_index=-1,
)
self.assertTrue(mt_dataset.has_heterogeneous_features)
ssd = SearchSpaceDigest(
feature_names=["x0", "x1", "task"],
bounds=[(0.0, 5.0), (0.0, 6.0), (0.0, 1.0)],
task_features=[2],
target_values={2: 0.0},
)
surrogate = Surrogate(
surrogate_spec=SurrogateSpec(
model_configs=[ModelConfig(botorch_model_class=MultiTaskGP)]
)
)
with self.subTest("with LFI — construct_inputs succeeds"):
config_with_lfi = ModelConfig(
botorch_model_class=MultiTaskGP,
input_transform_classes=[Normalize, LearnedFeatureImputation],
)
result = _submodel_input_constructor_mtgp(
botorch_model_class=MultiTaskGP,
model_config=config_with_lfi,
dataset=mt_dataset,
search_space_digest=ssd,
surrogate=surrogate,
)
self.assertEqual(result["train_X"].shape[-1], 3)
with self.subTest("without LFI — construct_inputs raises"):
from botorch.exceptions.errors import (
UnsupportedError as BotorchUnsupportedError,
)
config_no_lfi = ModelConfig(
botorch_model_class=MultiTaskGP,
input_transform_classes=[Normalize],
)
with self.assertRaises(BotorchUnsupportedError):
_submodel_input_constructor_mtgp(
botorch_model_class=MultiTaskGP,
model_config=config_no_lfi,
dataset=mt_dataset,
search_space_digest=ssd,
surrogate=surrogate,
)
class SurrogateTest(TestCase):
def setUp(self, cuda: bool = False) -> None:
super().setUp()
self.device = torch.device("cuda" if cuda else "cpu")
self.dtype = torch.float
self.tkwargs = {"device": self.device, "dtype": self.dtype}
(
self.Xs,
self.Ys,
self.Yvars,
self.bounds,
_,
self.feature_names,
_,
) = get_torch_test_data(dtype=self.dtype, cuda=cuda)
self.metric_signatures = ["metric"]
self.training_data = [
SupervisedDataset(
X=self.Xs,
# Note: using 1d Y does not match the 2d TorchOptConfig
Y=self.Ys,
feature_names=self.feature_names,
outcome_names=self.metric_signatures,
)
]
self.training_data_standardized = [
SupervisedDataset(
X=self.Xs,
Y=standardize(self.Ys),
feature_names=self.feature_names,
outcome_names=self.metric_signatures,
)
]
self.mll_class = ExactMarginalLogLikelihood
self.search_space_digest = SearchSpaceDigest(
feature_names=self.feature_names,
bounds=self.bounds,
target_values={1: 1.0},
)
self.fixed_features = {1: 2.0}
self.refit = True
self.objective_weights = torch.tensor([[-1.0, 1.0]], **self.tkwargs)
# Note: these only work with 1 outcome
self.outcome_constraints = (
torch.tensor([[1.0]], **self.tkwargs),
torch.tensor([[0.5]], **self.tkwargs),
)
self.linear_constraints = (
torch.tensor([[0.0, 0.0, 0.0], [0.0, 1.0, 0.0]], **self.tkwargs),
torch.tensor([[0.5], [1.0]], **self.tkwargs),
)
self.options = {}
self.torch_opt_config = TorchOptConfig(
objective_weights=self.objective_weights,
outcome_constraints=self.outcome_constraints,
linear_constraints=self.linear_constraints,
fixed_features=self.fixed_features,
)
self.ds2 = SupervisedDataset(
# pyre-fixme[6]: For 1st argument expected `Union[BotorchContainer,
# Tensor]` but got `int`.
X=2 * self.Xs,
# pyre-fixme[6]: For 2nd argument expected `Union[BotorchContainer,
# Tensor]` but got `int`.
Y=2 * self.Ys,
feature_names=self.feature_names,
outcome_names=["m2"],
)
def _get_surrogate(
self,
botorch_model_class: type[Model],
use_outcome_transform: bool = True,
n_outcomes: int = 1,
) -> tuple[Surrogate, dict[str, Any]]:
if botorch_model_class is SaasFullyBayesianSingleTaskGP:
mll_options = {"jit_compile": True}
else:
mll_options = {}
if use_outcome_transform:
outcome_transform_classes: list[type[OutcomeTransform]] = [Standardize]
outcome_transform_options = {"Standardize": {"m": n_outcomes}}
else:
outcome_transform_classes = None
outcome_transform_options = {}
surrogate = Surrogate(
surrogate_spec=SurrogateSpec(
model_configs=[
ModelConfig(
botorch_model_class=botorch_model_class,
mll_class=self.mll_class,
mll_options=mll_options,
outcome_transform_classes=outcome_transform_classes,
outcome_transform_options=outcome_transform_options,
)
]
)
)
surrogate_kwargs = botorch_model_class.construct_inputs(self.training_data[0])
return surrogate, surrogate_kwargs
def test_init(self) -> None:
for botorch_model_class in [SaasFullyBayesianSingleTaskGP, SingleTaskGP]:
surrogate, _ = self._get_surrogate(botorch_model_class=botorch_model_class)
self.assertEqual(
surrogate.surrogate_spec.model_configs[0].botorch_model_class,
botorch_model_class,
)
self.assertEqual(
surrogate.surrogate_spec.model_configs[0].mll_class, self.mll_class
)
self.assertTrue(
surrogate.surrogate_spec.allow_batched_models
) # True by default
def test_clone_reset(self) -> None:
surrogate = self._get_surrogate(botorch_model_class=SingleTaskGP)[0]
self.assertEqual(surrogate, surrogate.clone_reset())
# This mock is needed since we are not using a real MLL
@patch(f"{UTILS_PATH}.fit_gpytorch_mll")
# Patch deepcopying model_config that contains mock_mll
# otherwise it will lose its callcounts
# pyre-ignore [56]: not able to infer the type of argument lambda
@patch(f"{UTILS_PATH}.deepcopy", side_effect=lambda x: x)
def test_mll_options(self, _, __) -> None:
mock_mll = MagicMock(self.mll_class)
surrogate = Surrogate(
surrogate_spec=SurrogateSpec(
model_configs=[
ModelConfig(
botorch_model_class=SingleTaskGP,
mll_class=mock_mll,
mll_options={"some_option": "some_value"},
)
]
)
)
surrogate.fit(
datasets=self.training_data,
search_space_digest=self.search_space_digest,
refit=self.refit,
)
self.assertEqual(mock_mll.call_args[1]["some_option"], "some_value")
@mock_botorch_optimize
def test_copy_options(self) -> None:
training_data = self.training_data + [self.ds2]
d = self.Xs.shape[-1]
surrogate = Surrogate(
surrogate_spec=SurrogateSpec(
model_configs=[
ModelConfig(
botorch_model_class=SingleTaskGP,
likelihood_class=GaussianLikelihood,
likelihood_options={"noise_constraint": GreaterThan(1e-3)},
mll_class=ExactMarginalLogLikelihood,
covar_module_class=ScaleKernel,
covar_module_options={
"base_kernel": MaternKernel(ard_num_dims=d)
},
input_transform_classes=[Normalize],
outcome_transform_classes=[Standardize],
outcome_transform_options={"Standardize": {"m": 1}},
)
]
),
allow_batched_models=False,
)
surrogate.fit(
datasets=training_data,
search_space_digest=self.search_space_digest,
refit=True,
)
models = assert_is_instance(surrogate.model.models, ModuleList)
model1_old_lengtscale = (
models[1].covar_module.base_kernel.lengthscale.detach().clone()
)
# Change the lengthscales of one model and make sure the other isn't changed
models[0].covar_module.base_kernel.lengthscale += 1
self.assertAllClose(
model1_old_lengtscale,
models[1].covar_module.base_kernel.lengthscale,
)
# Test the same thing with the likelihood noise constraint
models[0].likelihood.noise_covar.raw_noise_constraint.lower_bound.fill_(1e-4)
self.assertEqual(
models[0].likelihood.noise_covar.raw_noise_constraint.lower_bound, 1e-4
)
self.assertEqual(
models[1].likelihood.noise_covar.raw_noise_constraint.lower_bound, 1e-3
)
# Check input transform
# bounds will be taken from the search space digest
self.assertAllClose(
models[0].input_transform.offset,
torch.tensor([[0, 1, 2]], **self.tkwargs),
)
self.assertAllClose(
models[1].input_transform.offset,
torch.tensor([[0, 1, 2]], **self.tkwargs),
)
# Check outcome transform
self.assertAllClose(
models[0].outcome_transform.means, torch.tensor([[3.5]], **self.tkwargs)
)
self.assertAllClose(
models[1].outcome_transform.means, torch.tensor([[7]], **self.tkwargs)
)
def test_botorch_transforms(self) -> None:
# Successfully passing down the transforms
surrogate = Surrogate(
surrogate_spec=SurrogateSpec(
model_configs=[
ModelConfig(
botorch_model_class=SingleTaskGP,
outcome_transform_classes=[Standardize],
input_transform_classes=[Normalize],
)
]
)
)
surrogate.fit(
datasets=self.training_data,
search_space_digest=self.search_space_digest,
refit=self.refit,
)
botorch_model = surrogate.model
self.assertIsInstance(botorch_model.input_transform, Normalize)
self.assertIsInstance(botorch_model.outcome_transform, Standardize)
# pyre-fixme[16]: Item `Tensor` of `Tensor | Module` has no attribute `_m`.
self.assertEqual(botorch_model.outcome_transform._m, self.Ys.shape[-1])
# Error handling if the model does not support transforms.
surrogate = Surrogate(
surrogate_spec=SurrogateSpec(
model_configs=[
ModelConfig(
botorch_model_class=SingleTaskGPWithDifferentConstructor,
outcome_transform_classes=[Standardize],
outcome_transform_options={
"Standardize": {"m": self.Ys.shape[-1]}
},
input_transform_classes=[Normalize],
)
]
)
)
with self.assertRaisesRegex(UserInputError, "BoTorch model"):
surrogate.fit(
datasets=self.training_data,
search_space_digest=self.search_space_digest,
refit=self.refit,
)
def test_model_property(self) -> None:
for botorch_model_class in [SaasFullyBayesianSingleTaskGP, SingleTaskGP]:
surrogate, _ = self._get_surrogate(botorch_model_class=botorch_model_class)
with self.assertRaisesRegex(
ModelError, "BoTorch `Model` has not yet been constructed."
):
surrogate.model
def test_training_data_property(self) -> None:
for botorch_model_class in [SaasFullyBayesianSingleTaskGP, SingleTaskGP]:
surrogate, _ = self._get_surrogate(botorch_model_class=botorch_model_class)
with self.assertRaisesRegex(
ModelError,
"Underlying BoTorch `Model` has not yet received its training_data.",
):
surrogate.training_data
@mock_botorch_optimize
def test_dtype_and_device_properties(self) -> None:
for botorch_model_class in [SaasFullyBayesianSingleTaskGP, SingleTaskGP]:
surrogate, _ = self._get_surrogate(botorch_model_class=botorch_model_class)
surrogate.fit(
datasets=self.training_data,
search_space_digest=self.search_space_digest,
)
self.assertEqual(self.dtype, surrogate.dtype)
self.assertEqual(self.device, surrogate.device)
@mock_botorch_optimize
@patch(
f"{SURROGATE_PATH}.submodel_input_constructor",
wraps=submodel_input_constructor,
)
@patch(f"{SURROGATE_PATH}.fit_botorch_model", wraps=fit_botorch_model)
def test_fit_model_reuse(self, mock_fit: Mock, mock_constructor: Mock) -> None:
surrogate, _ = self._get_surrogate(
botorch_model_class=SingleTaskGP, use_outcome_transform=False
)
search_space_digest = SearchSpaceDigest(
feature_names=self.feature_names,
bounds=self.bounds,
)
surrogate.fit(
datasets=self.training_data,
search_space_digest=search_space_digest,
)
mock_fit.assert_called_once()
mock_constructor.assert_called_once()
key = tuple(self.training_data[0].outcome_names)
submodel = surrogate._submodels[key]
self.assertIs(surrogate._last_datasets[key], self.training_data[0])
self.assertIs(surrogate._last_search_space_digest, search_space_digest)
# Refit with same arguments.
surrogate.fit(
datasets=self.training_data,
search_space_digest=search_space_digest,
)
# Still only called once -- i.e. not fitted again:
mock_fit.assert_called_once()
mock_constructor.assert_called_once()
# Model is still the same object.
self.assertIs(submodel, surrogate._submodels[key])
# Change the search space digest.
bounds = self.bounds.copy()
bounds[0] = (999.0, 9999.0)
search_space_digest = SearchSpaceDigest(
feature_names=self.feature_names,
bounds=bounds,
)
with patch(f"{SURROGATE_PATH}.logger.debug") as mock_log:
surrogate.fit(
datasets=self.training_data,
search_space_digest=search_space_digest,
)
mock_log.assert_called_once()
self.assertIn(
"Discarding all previously trained models", mock_log.call_args[0][0]
)
self.assertIsNot(submodel, surrogate._submodels[key])
self.assertIs(surrogate._last_search_space_digest, search_space_digest)
@mock_botorch_optimize
def test_construct_model(self) -> None:
for botorch_model_class in (SaasFullyBayesianSingleTaskGP, SingleTaskGP):
# Don't use an outcome transform here because the
# botorch_model_class will change to one that is not compatible with
# outcome transforms below
surrogate, _ = self._get_surrogate(
botorch_model_class=botorch_model_class, use_outcome_transform=False
)
with self.subTest("Arguments passed through correctly"):
with (
patch.object(
botorch_model_class,
"construct_inputs",
wraps=botorch_model_class.construct_inputs,
) as mock_construct_inputs,
patch.object(
botorch_model_class,
"__init__",
return_value=None,
autospec=True,
) as mock_init,
patch(f"{SURROGATE_PATH}.fit_botorch_model") as mock_fit,
):
model = surrogate._construct_model(
dataset=self.training_data[0],
search_space_digest=self.search_space_digest,
model_config=surrogate.surrogate_spec.model_configs[0],
state_dict=None,
refit=True,
)
mock_init.assert_called_once()
mock_fit.assert_called_once()
call_kwargs = mock_init.call_args.kwargs
self.assertTrue(torch.equal(call_kwargs["train_X"], self.Xs))
self.assertTrue(torch.equal(call_kwargs["train_Y"], self.Ys))
self.assertIsInstance(call_kwargs["input_transform"], Normalize)
self.assertIsNone(call_kwargs["outcome_transform"])
self.assertEqual(
len(call_kwargs),
6 if botorch_model_class is SaasFullyBayesianSingleTaskGP else 4,
)
mock_construct_inputs.assert_called_with(
training_data=self.training_data[0],
)
# We can't use `wraps=fit_botorch_model` with the above code,
# because `_construct_submodules` relies on `inspect` and mocks seem
# to break that
with self.subTest("Model construction runs"):
model = surrogate._construct_model(
dataset=self.training_data[0],
search_space_digest=self.search_space_digest,
model_config=surrogate.surrogate_spec.model_configs[0],
state_dict=None,
refit=True,
)
# Cache the model & dataset as we would in `Surrogate.fit``.
outcomes = self.training_data[0].outcome_names
key = tuple(outcomes)
surrogate._submodels[key] = model
surrogate._last_datasets[key] = self.training_data[0]
surrogate.metric_to_best_model_config[outcomes[0]] = (
surrogate.surrogate_spec.model_configs[0]
)
# Attempt to re-fit the same model with the same data.
with patch(
f"{SURROGATE_PATH}.fit_botorch_model", wraps=fit_botorch_model
) as mock_fit:
new_model = surrogate._construct_model(
dataset=self.training_data[0],
search_space_digest=self.search_space_digest,
model_config=surrogate.surrogate_spec.model_configs[0],
state_dict=None,
refit=True,
)
mock_fit.assert_not_called()
self.assertIs(new_model, model)
# Model is not re-fit if we change the model config.
# The reason is that we cache the best model config.
# We only reset the best model config and cached models
# if the search space digest changes
with patch(
f"{SURROGATE_PATH}.fit_botorch_model", wraps=fit_botorch_model
) as mock_fit:
model = surrogate._construct_model(
dataset=self.training_data[0],
search_space_digest=self.search_space_digest,
model_config=ModelConfig(
botorch_model_class=SingleTaskGPWithDifferentConstructor
),
state_dict=None,
refit=True,
)
mock_fit.assert_not_called()
# Model is not re-fit if we change the model class.
search_space_digest = SearchSpaceDigest(
feature_names=self.feature_names,
bounds=self.bounds,
target_values={1: 2.0},
)
with patch(f"{SURROGATE_PATH}.fit_botorch_model") as mock_fit:
model = surrogate._construct_model(
dataset=self.training_data[0],
search_space_digest=search_space_digest,
model_config=ModelConfig(),
state_dict=None,
refit=True,
)
mock_fit.assert_not_called()
def test_construct_model_warm_start(self) -> None:
for warm_start_refit in (False, True):
surrogate = Surrogate(warm_start_refit=warm_start_refit)
with (
patch.object(
SingleTaskGP, "__init__", return_value=None, autospec=True
),
patch(f"{SURROGATE_PATH}.fit_botorch_model"),
patch.object(SingleTaskGP, "load_state_dict") as mock_load_state_dict,
):
surrogate._construct_model(
dataset=self.training_data[0],
search_space_digest=self.search_space_digest,
model_config=surrogate.surrogate_spec.model_configs[0],
state_dict={},
refit=True,
)
if warm_start_refit:
mock_load_state_dict.assert_called_once()
else:
mock_load_state_dict.assert_not_called()
@mock_botorch_optimize
def test_construct_custom_model(self) -> None:
# Test error for unsupported covar_module and likelihood.
surrogate = Surrogate(
surrogate_spec=SurrogateSpec(
model_configs=[
ModelConfig(
botorch_model_class=SingleTaskGPWithDifferentConstructor,
mll_class=self.mll_class,
covar_module_class=RBFKernel,
likelihood_class=FixedNoiseGaussianLikelihood,
)
]
)
)
with self.assertRaisesRegex(UserInputError, "does not support"):
surrogate.fit(
self.training_data,
search_space_digest=self.search_space_digest,
)
# Pass custom options to a SingleTaskGP and make sure they are used
noise_constraint = Interval(1e-6, 1e-1)
surrogate = Surrogate(
surrogate_spec=SurrogateSpec(
model_configs=[
ModelConfig(
botorch_model_class=SingleTaskGP,
mll_class=LeaveOneOutPseudoLikelihood,
covar_module_class=RBFKernel,
covar_module_options={"ard_num_dims": 3},
likelihood_class=GaussianLikelihood,
likelihood_options={"noise_constraint": noise_constraint},
)
]
)
)
surrogate.fit(
self.training_data,
search_space_digest=self.search_space_digest,
)
model = none_throws(surrogate._model)
self.assertEqual(type(model.likelihood), GaussianLikelihood)
noise_constraint.eval() # For the equality check.
self.assertEqual(
# Checking equality of __dict__'s since Interval does not define __eq__.
# pyre-fixme[16]: Item `Tensor` of `Tensor | Module` has no attribute
# `noise_covar`.
model.likelihood.noise_covar.raw_noise_constraint.__dict__,
noise_constraint.__dict__,
)
self.assertEqual(
surrogate.surrogate_spec.model_configs[0].mll_class,
LeaveOneOutPseudoLikelihood,
)
self.assertEqual(type(model.covar_module), RBFKernel)
# pyre-fixme[16]: Item `Tensor` of `Tensor | Module` has no attribute
# `ard_num_dims`.
self.assertEqual(model.covar_module.ard_num_dims, 3)
def test_construct_model_with_metric_to_model_configs(self) -> None:
surrogate = Surrogate(
surrogate_spec=SurrogateSpec(
metric_to_model_configs={
"metric": [ModelConfig()],
"metric2": [ModelConfig(covar_module_class=ScaleMaternKernel)],
},
model_configs=[ModelConfig(covar_module_class=LinearKernel)],
)
)
training_data = self.training_data + [
SupervisedDataset(
X=self.Xs,
# Note: using 1d Y does not match the 2d TorchOptConfig
Y=self.Ys,
feature_names=self.feature_names,
outcome_names=[f"metric{i}"],
)
for i in range(2, 5)
]
surrogate.fit(
datasets=training_data, search_space_digest=self.search_space_digest
)
# test model follows metric_to_model_configs for
# first two metrics
self.assertIsInstance(surrogate.model, ModelListGP)
submodels = surrogate.model.models
# pyre-fixme[6]: For 1st argument expected
# `pyre_extensions.PyreReadOnly[Sized]` but got `Union[Tensor, Module]`.
self.assertEqual(len(submodels), 4)
# pyre-fixme[29]: `Union[(self: Tensor) -> Any, Tensor, Module]` is not a
# function.
for m in submodels:
self.assertIsInstance(m, SingleTaskGP)
# pyre-fixme[29]: `Union[(self: TensorBase, indices: Union[None, slice[Any, A...
self.assertIsInstance(surrogate.model.models[1].covar_module, ScaleKernel)
self.assertIsInstance(
# pyre-fixme[29]: `Union[(self: TensorBase, indices: Union[None, slice[An...
surrogate.model.models[1].covar_module.base_kernel,
MaternKernel,
)
# pyre-fixme[29]: `Union[(self: TensorBase, indices: Union[None, slice[Any, A...
self.assertIsInstance(surrogate.model.models[0].covar_module, RBFKernel)
# test model use model_configs for the third metric
# pyre-fixme[29]: `Union[(self: TensorBase, indices: Union[None, slice[Any, A...
self.assertIsInstance(surrogate.model.models[2].covar_module, LinearKernel)
def test_construct_model_remove_task_features(self) -> None:
self.search_space_digest.task_features.append(-1)
self.search_space_digest.feature_names.append("task_feat")
self.search_space_digest.bounds.append((0.0, 1.0))
X = self.Xs
dataset = MultiTaskDataset(
datasets=[
SupervisedDataset(
X=torch.cat(
[
X,
torch.ones(X.shape[0], 1, dtype=X.dtype, device=X.device),
],
dim=-1,
),
# Note: using 1d Y does not match the 2d TorchOptConfig
Y=self.Ys,
feature_names=self.search_space_digest.feature_names,
outcome_names=self.metric_signatures,
)
],
target_outcome_name=self.metric_signatures[0],
task_feature_index=-1,
)
botorch_model_class = SingleTaskGP
for remove_task_features in (False, True):
# Don't use an outcome transform here because the
# botorch_model_class will change to one that is not compatible with
# outcome transforms below
surrogate, _ = self._get_surrogate(
botorch_model_class=botorch_model_class, use_outcome_transform=False
)
model_config = ModelConfig(
botorch_model_class=botorch_model_class,
covar_module_class=ScaleMaternKernel,
covar_module_options={"remove_task_features": remove_task_features},
)
with (
patch.object(
botorch_model_class,
"construct_inputs",
wraps=botorch_model_class.construct_inputs,
),
patch.object(
botorch_model_class, "__init__", return_value=None, autospec=True
) as mock_init,
patch(f"{SURROGATE_PATH}.fit_botorch_model") as mock_fit,
):
surrogate._construct_model(
dataset=dataset,
search_space_digest=self.search_space_digest,
model_config=model_config,
state_dict=None,
refit=True,
)
mock_init.assert_called_once()
mock_fit.assert_called_once()
call_kwargs = mock_init.call_args.kwargs
self.assertTrue(torch.equal(call_kwargs["train_X"], dataset.X))