-
Notifications
You must be signed in to change notification settings - Fork 362
Expand file tree
/
Copy pathtest_acquisition.py
More file actions
2343 lines (2179 loc) · 96.6 KB
/
test_acquisition.py
File metadata and controls
2343 lines (2179 loc) · 96.6 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
from __future__ import annotations
import dataclasses
import itertools
from contextlib import ExitStack
from copy import deepcopy
from typing import Any
from unittest import mock
from unittest.mock import Mock
import numpy as np
import torch
from ax.core.search_space import SearchSpaceDigest
from ax.exceptions.core import AxError, SearchSpaceExhausted
from ax.generators.torch.botorch_modular.acquisition import (
_expand_and_set_single_feature_to_target,
Acquisition,
logger,
)
from ax.generators.torch.botorch_modular.multi_acquisition import MultiAcquisition
from ax.generators.torch.botorch_modular.optimizer_argparse import optimizer_argparse
from ax.generators.torch.botorch_modular.optimizer_defaults import (
BATCH_LIMIT,
INIT_BATCH_LIMIT,
MAX_OPT_AGG_SIZE,
)
from ax.generators.torch.botorch_modular.surrogate import Surrogate
from ax.generators.torch.botorch_modular.utils import (
_objective_threshold_to_outcome_constraints,
)
from ax.generators.torch.utils import (
_get_X_pending_and_observed,
get_botorch_objective_and_transform,
subset_model,
SubsetModelData,
)
from ax.generators.torch_base import TorchOptConfig
from ax.utils.common.constants import Keys
from ax.utils.common.testutils import TestCase
from ax.utils.testing.mock import (
mock_botorch_optimize,
mock_botorch_optimize_context_manager,
)
from ax.utils.testing.utils import generic_equals
from botorch.acquisition.acquisition import AcquisitionFunction
from botorch.acquisition.input_constructors import (
_register_acqf_input_constructor,
ACQF_INPUT_CONSTRUCTOR_REGISTRY,
get_acqf_input_constructor,
)
from botorch.acquisition.knowledge_gradient import qKnowledgeGradient
from botorch.acquisition.logei import qLogProbabilityOfFeasibility
from botorch.acquisition.monte_carlo import qNoisyExpectedImprovement
from botorch.acquisition.multi_objective.monte_carlo import (
qNoisyExpectedHypervolumeImprovement,
)
from botorch.acquisition.objective import LinearMCObjective
from botorch.exceptions.warnings import OptimizationWarning
from botorch.optim.optimize import (
optimize_acqf,
optimize_acqf_discrete,
optimize_acqf_mixed,
)
from botorch.optim.optimize_mixed import optimize_acqf_mixed_alternating
from botorch.utils.constraints import get_outcome_constraint_transforms
from botorch.utils.datasets import SupervisedDataset
from botorch.utils.testing import MockPosterior, skip_if_import_error
from torch import Tensor
ACQUISITION_PATH: str = Acquisition.__module__
CURRENT_PATH: str = __name__
SURROGATE_PATH: str = Surrogate.__module__
# Used to avoid going through BoTorch `Acquisition.__init__` which
# requires valid kwargs (correct sizes and lengths of tensors, etc).
class DummyAcquisitionFunction(AcquisitionFunction):
X_pending: Tensor | None = None
def __init__(self, eta: float = 1e-3, model: Any = None, **kwargs: Any) -> None:
# pyre-ignore [6]
AcquisitionFunction.__init__(self, model=None)
self.eta = eta
self.model = model
def forward(self, X: Tensor) -> Tensor:
# take the norm and sum over the q-batch dim
if len(X.shape) > 2:
res = torch.linalg.norm(X, dim=-1).sum(-1)
else:
res = torch.linalg.norm(X, dim=-1).squeeze(-1)
# At least 1d is required for sequential optimize_acqf.
return torch.atleast_1d(res)
class DummyOneShotAcquisitionFunction(DummyAcquisitionFunction, qKnowledgeGradient):
def evaluate(self, X: Tensor, **kwargs: Any) -> Tensor:
return X.sum(dim=-1)
class AcquisitionTest(TestCase):
acquisition_class = Acquisition
def setUp(self) -> None:
super().setUp()
qNEI_input_constructor = get_acqf_input_constructor(qNoisyExpectedImprovement)
self.mock_input_constructor = mock.MagicMock(
qNEI_input_constructor, side_effect=qNEI_input_constructor
)
# Adding wrapping here to be able to count calls and inspect arguments.
_register_acqf_input_constructor(
acqf_cls=DummyAcquisitionFunction,
input_constructor=self.mock_input_constructor,
)
_register_acqf_input_constructor(
acqf_cls=DummyOneShotAcquisitionFunction,
input_constructor=self.mock_input_constructor,
)
self.tkwargs: dict[str, Any] = {"dtype": torch.double}
self.surrogate = Surrogate()
self.X = torch.tensor([[1.0, 2.0, 3.0], [2.0, 3.0, 4.0]], **self.tkwargs)
self.Y = torch.tensor([[3.0], [4.0]], **self.tkwargs)
self.Yvar = torch.tensor([[0.0], [2.0]], **self.tkwargs)
self.fidelity_features = [2]
self.feature_names = ["a", "b", "c"]
self.metric_signatures = ["metric"]
self.training_data = [
SupervisedDataset(
X=self.X,
Y=self.Y,
feature_names=self.feature_names,
outcome_names=self.metric_signatures,
)
]
self.search_space_digest = SearchSpaceDigest(
feature_names=self.feature_names,
bounds=[(0.0, 10.0), (0.0, 10.0), (0.0, 10.0)],
target_values={2: 1.0},
)
with mock_botorch_optimize_context_manager():
self.surrogate.fit(
datasets=self.training_data,
search_space_digest=SearchSpaceDigest(
feature_names=self.search_space_digest.feature_names,
bounds=self.search_space_digest.bounds,
target_values=self.search_space_digest.target_values,
),
)
self.botorch_acqf_class = DummyAcquisitionFunction
self.objective_weights = torch.tensor([[1.0]])
self.objective_thresholds = None
self.pending_observations = [torch.tensor([[1.0, 3.0, 4.0]], **self.tkwargs)]
self.outcome_constraints = (
torch.tensor([[1.0]], **self.tkwargs),
torch.tensor([[0.5]], **self.tkwargs),
)
self.constraints = get_outcome_constraint_transforms(
outcome_constraints=self.outcome_constraints
)
self.linear_constraints = None
self.fixed_features = {1: 2.0}
self.botorch_acqf_options = {"cache_root": False, "prune_baseline": False}
self.options = {}
self.inequality_constraints = [
(
torch.tensor([0, 1], dtype=torch.int),
torch.tensor([-1.0, 1.0], **self.tkwargs),
1,
)
]
self.rounding_func = lambda x: x
self.optimizer_options = {Keys.NUM_RESTARTS: 20, Keys.RAW_SAMPLES: 1024}
self.torch_opt_config = TorchOptConfig(
objective_weights=self.objective_weights,
objective_thresholds=self.objective_thresholds,
pending_observations=self.pending_observations,
outcome_constraints=self.outcome_constraints,
linear_constraints=self.linear_constraints,
fixed_features=self.fixed_features,
)
self.botorch_acqf_classes_with_options = None
def tearDown(self) -> None:
# Avoid polluting the registry for other tests.
ACQF_INPUT_CONSTRUCTOR_REGISTRY.pop(DummyAcquisitionFunction)
def get_acquisition_function(
self,
fixed_features: dict[int, float] | None = None,
one_shot: bool = False,
target_point: Tensor | None = None,
) -> Acquisition:
return self.acquisition_class(
botorch_acqf_class=(
DummyOneShotAcquisitionFunction if one_shot else self.botorch_acqf_class
),
surrogate=self.surrogate,
search_space_digest=self.search_space_digest,
torch_opt_config=dataclasses.replace(
self.torch_opt_config,
fixed_features=fixed_features or {},
pruning_target_point=target_point,
),
options=self.options,
botorch_acqf_options=self.botorch_acqf_options,
botorch_acqf_classes_with_options=self.botorch_acqf_classes_with_options,
)
def test_init_raises(self) -> None:
with self.assertRaisesRegex(
AxError,
"One of botorch_acqf_class or botorch_acqf_classes"
"_with_options is required.",
):
Acquisition(
surrogate=self.surrogate,
search_space_digest=self.search_space_digest,
torch_opt_config=self.torch_opt_config,
botorch_acqf_class=None,
botorch_acqf_options={},
)
@mock.patch(
f"{ACQUISITION_PATH}._get_X_pending_and_observed",
wraps=_get_X_pending_and_observed,
)
@mock.patch(f"{ACQUISITION_PATH}.subset_model", wraps=subset_model)
def test_init(
self,
mock_subset_model: Mock,
mock_get_X: Mock,
) -> None:
acquisition = self.acquisition_class(
surrogate=self.surrogate,
search_space_digest=self.search_space_digest,
torch_opt_config=self.torch_opt_config,
botorch_acqf_class=self.botorch_acqf_class,
options=self.options,
botorch_acqf_options=self.botorch_acqf_options,
botorch_acqf_classes_with_options=self.botorch_acqf_classes_with_options,
)
# Check `_get_X_pending_and_observed` kwargs
mock_get_X.assert_called_once()
_, ckwargs = mock_get_X.call_args
for X, dataset in zip(ckwargs["Xs"], self.training_data):
self.assertTrue(torch.equal(X, dataset.X))
for attr in (
"pending_observations",
"objective_weights",
"outcome_constraints",
"linear_constraints",
"fixed_features",
):
self.assertTrue(generic_equals(ckwargs[attr], getattr(self, attr)))
self.assertIs(ckwargs["bounds"], self.search_space_digest.bounds)
# Call `subset_model` only when needed
mock_subset_model.assert_called_with(
model=acquisition.surrogate.model,
objective_weights=self.objective_weights,
outcome_constraints=self.outcome_constraints,
objective_thresholds=self.objective_thresholds,
)
# Mock so that we can check that arguments are passed correctly.
@mock.patch(f"{ACQUISITION_PATH}._get_X_pending_and_observed")
@mock.patch(
f"{ACQUISITION_PATH}.subset_model",
# pyre-fixme[6]: For 1st param expected `Model` but got `None`.
# pyre-fixme[6]: For 5th param expected `Tensor` but got `None`.
return_value=SubsetModelData(None, torch.ones(1), None, None, None),
)
@mock.patch(
f"{ACQUISITION_PATH}.get_botorch_objective_and_transform",
wraps=get_botorch_objective_and_transform,
)
def test_init_with_subset_model_false(
self,
mock_get_objective_and_transform: Mock,
mock_subset_model: Mock,
mock_get_X: Mock,
) -> None:
botorch_objective = LinearMCObjective(weights=torch.tensor([1.0]))
mock_get_objective_and_transform.return_value = (botorch_objective, None)
mock_get_X.return_value = (self.pending_observations[0], self.X[:1])
self.options[Keys.SUBSET_MODEL] = False
with mock.patch(
f"{ACQUISITION_PATH}.get_outcome_constraint_transforms",
return_value=self.constraints,
) as mock_get_outcome_constraint_transforms:
acquisition = Acquisition(
surrogate=self.surrogate,
search_space_digest=self.search_space_digest,
torch_opt_config=self.torch_opt_config,
botorch_acqf_class=self.botorch_acqf_class,
options=self.options,
botorch_acqf_options=self.botorch_acqf_options,
)
mock_subset_model.assert_not_called()
# Check `get_botorch_objective_and_transform` kwargs
mock_get_objective_and_transform.assert_called_once()
_, ckwargs = mock_get_objective_and_transform.call_args
self.assertIs(ckwargs["model"], acquisition.surrogate.model)
self.assertIs(ckwargs["objective_weights"], self.objective_weights)
self.assertIs(ckwargs["outcome_constraints"], self.outcome_constraints)
self.assertTrue(torch.equal(ckwargs["X_observed"], self.X[:1]))
# Check final `acqf` creation
self.mock_input_constructor.assert_called_once()
_, ckwargs = self.mock_input_constructor.call_args
self.assertIs(ckwargs["model"], acquisition.surrogate.model)
self.assertIs(ckwargs["objective"], botorch_objective)
self.assertTrue(torch.equal(ckwargs["X_pending"], self.pending_observations[0]))
for k, v in self.botorch_acqf_options.items():
self.assertEqual(ckwargs[k], v)
self.assertIs(
ckwargs["constraints"],
self.constraints,
)
mock_get_outcome_constraint_transforms.assert_called_once_with(
outcome_constraints=self.outcome_constraints
)
@mock_botorch_optimize
def test_optimize(self) -> None:
for prune_irrelevant_parameters in (False, True):
if prune_irrelevant_parameters:
self.options = {
"prune_irrelevant_parameters": True,
}
else:
self.options = {}
acquisition = self.get_acquisition_function(
fixed_features=self.fixed_features,
target_point=torch.zeros(3, dtype=torch.double),
)
n = 5
with (
mock.patch(
f"{ACQUISITION_PATH}.optimizer_argparse", wraps=optimizer_argparse
) as mock_optimizer_argparse,
mock.patch(
f"{ACQUISITION_PATH}.optimize_acqf", wraps=optimize_acqf
) as mock_optimize_acqf,
mock.patch.object(
acquisition,
"_prune_irrelevant_parameters",
wraps=acquisition._prune_irrelevant_parameters,
) as mock_prune_irrelevant_parameters,
):
acquisition.optimize(
n=n,
search_space_digest=self.search_space_digest,
inequality_constraints=self.inequality_constraints,
fixed_features=self.fixed_features,
rounding_func=self.rounding_func,
optimizer_options=self.optimizer_options,
)
mock_optimizer_argparse.assert_called_once_with(
acquisition.acqf,
optimizer_options=self.optimizer_options,
optimizer="optimize_acqf",
)
mock_optimize_acqf.assert_called_with(
acq_function=acquisition.acqf,
sequential=True,
bounds=mock.ANY,
q=n,
options={
"init_batch_limit": INIT_BATCH_LIMIT,
"batch_limit": BATCH_LIMIT,
"max_optimization_problem_aggregation_size": MAX_OPT_AGG_SIZE,
},
inequality_constraints=self.inequality_constraints,
fixed_features=self.fixed_features,
post_processing_func=self.rounding_func,
acq_function_sequence=None,
**self.optimizer_options,
)
if prune_irrelevant_parameters:
mock_prune_irrelevant_parameters.assert_called_once()
call_kwargs = mock_prune_irrelevant_parameters.call_args_list[0][1]
for kw_name in (
"candidates",
"search_space_digest",
"inequality_constraints",
"fixed_features",
):
self.assertIsNotNone(call_kwargs[kw_name])
self.assertIsNotNone(acquisition.num_pruned_dims)
else:
mock_prune_irrelevant_parameters.assert_not_called()
self.assertIsNone(acquisition.num_pruned_dims)
# can't use assert_called_with on bounds due to ambiguous bool comparison
expected_bounds = torch.tensor(
self.search_space_digest.bounds,
dtype=acquisition.dtype,
device=acquisition.device,
).transpose(0, 1)
self.assertTrue(
torch.equal(mock_optimize_acqf.call_args[1]["bounds"], expected_bounds)
)
def test_optimize_discrete(self) -> None:
ssd1 = SearchSpaceDigest(
feature_names=["a", "b", "c"],
bounds=[(1, 2), (2, 3), (3, 4)],
categorical_features=[0, 1, 2],
discrete_choices={0: [1, 2], 1: [2, 3], 2: [3, 4]},
)
# check fixed_feature index validation
with self.assertRaisesRegex(ValueError, "Invalid fixed_feature index"):
acquisition = self.get_acquisition_function()
acquisition.optimize(
n=3,
search_space_digest=ssd1,
fixed_features={3: 2.0},
rounding_func=self.rounding_func,
)
# check that SearchSpaceExhausted is raised correctly
acquisition = self.get_acquisition_function()
all_possible_choices = list(itertools.product(*ssd1.discrete_choices.values()))
acquisition.X_observed = torch.tensor(all_possible_choices, **self.tkwargs)
with self.assertRaisesRegex(
SearchSpaceExhausted,
"No more feasible choices in a fully discrete search space.",
):
acquisition.optimize(
n=1,
search_space_digest=ssd1,
rounding_func=self.rounding_func,
)
acquisition = self.get_acquisition_function()
with self.assertWarnsRegex(
OptimizationWarning,
"only.*possible choices remain.",
):
acquisition.optimize(
n=8,
search_space_digest=ssd1,
rounding_func=self.rounding_func,
)
acquisition = self.get_acquisition_function()
n = 2
# Also check that it runs when optimizer options are provided, whether
# `raw_samples` or `num_restarts` is present or not.
for optimizer_options in [None, {"raw_samples": 8}, {"num_restarts": 8}]:
with self.subTest(optimizer_options=optimizer_options):
acquisition.optimize(
n=n,
search_space_digest=ssd1,
rounding_func=self.rounding_func,
optimizer_options=optimizer_options,
)
optimizer_options = {"batch_initial_conditions": None}
with (
self.subTest(optimizer_options=None),
self.assertRaisesRegex(ValueError, "Argument "),
):
acquisition.optimize(
n=n,
search_space_digest=ssd1,
rounding_func=self.rounding_func,
optimizer_options=optimizer_options,
)
# check this works without any fixed_feature specified
# 2 candidates have acqf value 8, but [1, 3, 4] is pending and thus should
# not be selected. [2, 3, 4] is the best point, but has already been picked
with (
mock.patch(
f"{ACQUISITION_PATH}.optimizer_argparse", wraps=optimizer_argparse
) as mock_optimizer_argparse,
mock.patch(
f"{ACQUISITION_PATH}.optimize_acqf_discrete",
wraps=optimize_acqf_discrete,
) as mock_optimize_acqf_discrete,
):
X_selected, _, weights = acquisition.optimize(
n=n,
search_space_digest=ssd1,
rounding_func=self.rounding_func,
)
mock_optimizer_argparse.assert_called_once_with(
acquisition.acqf,
optimizer_options=None,
optimizer="optimize_acqf_discrete",
)
mock_optimize_acqf_discrete.assert_called_once_with(
acq_function=acquisition.acqf,
q=n,
choices=mock.ANY,
max_batch_size=2048,
X_avoid=mock.ANY,
inequality_constraints=None,
)
expected_choices = torch.tensor(all_possible_choices)
expected_avoid = torch.cat([self.X, self.pending_observations[0]], dim=-2)
kwargs = mock_optimize_acqf_discrete.call_args.kwargs
self.assertTrue(torch.equal(expected_choices, kwargs["choices"]))
self.assertTrue(torch.equal(expected_avoid, kwargs["X_avoid"]))
expected = torch.tensor([[2, 2, 4], [2, 3, 3]]).to(self.X)
self.assertTrue(X_selected.shape == (2, 3))
self.assertTrue(
all((x.unsqueeze(0) == expected).all(dim=-1).any() for x in X_selected)
)
self.assertTrue(torch.equal(weights, torch.ones(2)))
# check with fixed feature
# Since parameter 1 is fixed to 2, the best 3 candidates are
# [4, 2, 4], [3, 2, 4], [4, 2, 3]
ssd2 = SearchSpaceDigest(
feature_names=["a", "b", "c"],
bounds=[(0, 4) for _ in range(3)],
categorical_features=[0, 1, 2],
discrete_choices={k: [0, 1, 2, 3, 4] for k in range(3)},
)
with (
mock.patch(
f"{ACQUISITION_PATH}.optimizer_argparse", wraps=optimizer_argparse
) as mock_optimizer_argparse,
mock.patch(
f"{ACQUISITION_PATH}.optimize_acqf_discrete",
wraps=optimize_acqf_discrete,
) as mock_optimize_acqf_discrete,
mock.patch(
"botorch.models.gp_regression.SingleTaskGP.batch_shape",
torch.Size([16]),
),
):
X_selected, _, weights = acquisition.optimize(
n=3,
search_space_digest=ssd2,
fixed_features=self.fixed_features,
rounding_func=self.rounding_func,
)
mock_optimizer_argparse.assert_called_once_with(
acquisition.acqf,
optimizer_options=None,
optimizer="optimize_acqf_discrete",
)
mock_optimize_acqf_discrete.assert_called_once_with(
acq_function=acquisition.acqf,
q=3,
choices=mock.ANY,
max_batch_size=128, # 2048 // 16 (mocked batch_shape).
X_avoid=mock.ANY,
inequality_constraints=None,
)
expected = torch.tensor([[4, 2, 4], [3, 2, 4], [4, 2, 3]]).to(self.X)
self.assertTrue(X_selected.shape == (3, 3))
self.assertTrue(
all((x.unsqueeze(0) == expected).all(dim=-1).any() for x in X_selected)
)
self.assertTrue(torch.equal(weights, torch.ones(3)))
# check with a constraint that -1 * x[0] -1 * x[1] >= 0 which should make
# [0, 0, 4] the best candidate.
X_selected, _, weights = acquisition.optimize(
n=1,
search_space_digest=ssd2,
rounding_func=self.rounding_func,
inequality_constraints=[
(torch.tensor([0, 1], dtype=torch.int64), -torch.ones(2), 0)
],
)
expected = torch.tensor([[0, 0, 4]]).to(self.X)
self.assertTrue(torch.equal(expected, X_selected))
self.assertTrue(torch.equal(weights, torch.tensor([1.0], dtype=self.X.dtype)))
# Same thing but use two constraints instead
X_selected, _, weights = acquisition.optimize(
n=1,
search_space_digest=ssd2,
rounding_func=self.rounding_func,
inequality_constraints=[
(torch.tensor([0], dtype=torch.int64), -torch.ones(1), 0),
(torch.tensor([1], dtype=torch.int64), -torch.ones(1), 0),
],
)
expected = torch.tensor([[0, 0, 4]]).to(self.X)
self.assertTrue(torch.equal(expected, X_selected))
self.assertTrue(torch.equal(weights, torch.tensor([1.0])))
# With no X_observed or X_pending.
acquisition = self.get_acquisition_function()
acquisition.X_observed, acquisition.X_pending = None, None
X_selected, _, weights = acquisition.optimize(
n=2,
search_space_digest=ssd1,
rounding_func=self.rounding_func,
)
self.assertTrue(torch.equal(weights, torch.ones(2)))
expected = torch.tensor([[1, 3, 4], [2, 3, 4]]).to(self.X)
self.assertTrue(X_selected.shape == (2, 3))
self.assertTrue(
all((x.unsqueeze(0) == expected).all(dim=-1).any() for x in X_selected)
)
def test_optimize_discrete_fewer_candidates(self) -> None:
"""Test that arm_weights and candidates have the same length when
optimize_acqf_discrete returns fewer than n candidates."""
# Search space with 2x2x2 = 8 total choices.
ssd = SearchSpaceDigest(
feature_names=["a", "b", "c"],
bounds=[(1, 2), (2, 3), (3, 4)],
categorical_features=[0, 1, 2],
discrete_choices={0: [1, 2], 1: [2, 3], 2: [3, 4]},
)
# Mark 6 of the 8 choices as observed so only 2 remain.
all_choices = list(itertools.product(*ssd.discrete_choices.values()))
acquisition = self.get_acquisition_function()
acquisition.X_observed = torch.tensor(all_choices[:6], **self.tkwargs)
acquisition.X_pending = None
# Request n=5 candidates but only 2 feasible choices remain.
with self.assertWarnsRegex(
OptimizationWarning,
"only.*possible choices remain.",
):
candidates, acqf_values, weights = acquisition.optimize(
n=5,
search_space_digest=ssd,
rounding_func=self.rounding_func,
)
# optimize_acqf_discrete returns only 2 candidates.
self.assertEqual(candidates.shape[0], 2)
# arm_weights must match the number of candidates, not n.
self.assertEqual(weights.shape[0], candidates.shape[0])
self.assertEqual(weights.shape[0], acqf_values.shape[0])
self.assertTrue(weights.sum().item(), 5)
def test_optimize_discrete_single_candidate(self) -> None:
"""Test arm_weights length when only 1 candidate remains in a
discrete search space and n > 1."""
ssd = SearchSpaceDigest(
feature_names=["a", "b", "c"],
bounds=[(1, 2), (2, 3), (3, 4)],
categorical_features=[0, 1, 2],
discrete_choices={0: [1, 2], 1: [2, 3], 2: [3, 4]},
)
# Mark 7 of 8 choices as observed so only 1 remains.
all_choices = list(itertools.product(*ssd.discrete_choices.values()))
acquisition = self.get_acquisition_function()
acquisition.X_observed = torch.tensor(all_choices[:7], **self.tkwargs)
acquisition.X_pending = None
with self.assertWarnsRegex(
OptimizationWarning,
"only.*possible choices remain.",
):
candidates, acqf_values, weights = acquisition.optimize(
n=3,
search_space_digest=ssd,
rounding_func=self.rounding_func,
)
self.assertEqual(candidates.shape[0], 1)
self.assertEqual(weights.shape[0], candidates.shape[0])
# The remaining choice is all_choices[7].
expected = torch.tensor([all_choices[7]], **self.tkwargs)
self.assertTrue(torch.equal(candidates, expected))
def test_select_from_candidate_set(self) -> None:
"""Test all select_from_candidate_set paths and optimize dispatch."""
from botorch.generation.sampling import SamplingStrategy
acquisition = self.get_acquisition_function()
with self.subTest("validation_too_few_candidates"):
with self.assertRaisesRegex(ValueError, "but 3 were requested"):
acquisition.select_from_candidate_set(
n=3,
candidate_set=torch.tensor([[1.0, 2.0, 3.0]], **self.tkwargs),
)
with self.subTest("validation_empty_candidate_set"):
with self.assertRaisesRegex(ValueError, "empty"):
acquisition.select_from_candidate_set(
n=1,
candidate_set=torch.empty(0, 3, **self.tkwargs),
)
with self.subTest("win_counting_normalized"):
candidate_set = torch.tensor(
[[1.0, 2.0, 3.0], [4.0, 5.0, 6.0], [7.0, 8.0, 9.0]],
**self.tkwargs,
)
class _AlternatingWinStrategy(SamplingStrategy):
"""Candidate 0 wins 75% of the time, candidate 1 wins 25%."""
num_samples: int = 0
def forward(self, X: Tensor, num_samples: int = 1) -> Tensor:
n_first = int(num_samples * 0.75)
n_second = num_samples - n_first
first = X[..., 0:1, :].expand(*X.shape[:-2], n_first, X.shape[-1])
second = X[..., 1:2, :].expand(*X.shape[:-2], n_second, X.shape[-1])
return torch.cat([first, second], dim=-2)
strategy = _AlternatingWinStrategy()
strategy.num_samples = 100
candidates, _, weights = acquisition.select_from_candidate_set(
n=2,
candidate_set=candidate_set,
sampling_strategy=strategy,
)
self.assertEqual(candidates.shape[0], 2)
self.assertAlmostEqual(weights.sum().item(), 1.0, places=4)
self.assertAlmostEqual(weights[0].item(), 0.75, places=4)
self.assertAlmostEqual(weights[1].item(), 0.25, places=4)
with self.subTest("direct_selection_without_num_samples"):
candidate_set = torch.tensor(
[[1.0, 2.0, 3.0], [4.0, 5.0, 6.0], [7.0, 8.0, 9.0]],
**self.tkwargs,
)
class _DirectStrategy(SamplingStrategy):
"""Always returns the first n candidates."""
def forward(self, X: Tensor, num_samples: int = 1) -> Tensor:
return X[..., :num_samples, :]
candidates, _, weights = acquisition.select_from_candidate_set(
n=2,
candidate_set=candidate_set,
sampling_strategy=_DirectStrategy(),
)
self.assertEqual(candidates.shape[0], 2)
self.assertTrue(torch.all(weights == 1.0))
self.assertEqual(weights.shape, (2,))
with self.subTest("greedy_via_optimize_acqf_discrete"):
candidate_set = torch.rand(10, 3, **self.tkwargs)
candidates, _, weights = acquisition.select_from_candidate_set(
n=1,
candidate_set=candidate_set,
)
self.assertEqual(candidates.shape, (1, 3))
self.assertEqual(weights.shape, (1,))
self.assertAlmostEqual(weights[0].item(), 1.0, places=6)
self.assertTrue((candidate_set == candidates[0]).all(dim=-1).any())
with self.subTest("optimize_raises_strategy_without_candidate_set"):
strategy = Mock(spec=SamplingStrategy)
with self.assertRaisesRegex(ValueError, "candidate_set.*required"):
acquisition.optimize(
n=1,
search_space_digest=self.search_space_digest,
sampling_strategy=strategy,
)
# mock `optimize_acqf_discrete_local_search` because it isn't handled by
# `mock_botorch_optimize`
@mock.patch(
f"{ACQUISITION_PATH}.optimize_acqf_discrete_local_search",
return_value=(torch.rand(3, 3), torch.rand(3)),
)
def test_optimize_acqf_discrete_local_search(
self,
mock_optimize_acqf_discrete_local_search: Mock,
) -> None:
ssd = SearchSpaceDigest(
feature_names=["a", "b", "c"],
bounds=[(0, 1) for _ in range(3)],
categorical_features=[0, 1, 2],
discrete_choices={ # 30 * 60 * 90 > 100,000
k: np.linspace(0, 1, 30 * (k + 1)).tolist() for k in range(3)
},
)
acquisition = self.get_acquisition_function()
with mock.patch(
f"{ACQUISITION_PATH}.optimizer_argparse", wraps=optimizer_argparse
) as mock_optimizer_argparse:
acquisition.optimize(
n=3,
search_space_digest=ssd,
inequality_constraints=self.inequality_constraints,
fixed_features=None,
rounding_func=self.rounding_func,
optimizer_options=self.optimizer_options,
)
mock_optimizer_argparse.assert_called_once_with(
acquisition.acqf,
optimizer_options=self.optimizer_options,
optimizer="optimize_acqf_discrete_local_search",
)
mock_optimize_acqf_discrete_local_search.assert_called_once()
args, kwargs = mock_optimize_acqf_discrete_local_search.call_args
self.assertEqual(len(args), 0)
self.assertSetEqual(
{
"acq_function",
"discrete_choices",
"q",
"num_restarts",
"raw_samples",
"inequality_constraints",
"X_avoid",
},
set(kwargs.keys()),
)
self.assertEqual(kwargs["acq_function"], acquisition.acqf)
self.assertEqual(kwargs["q"], 3)
self.assertEqual(kwargs["inequality_constraints"], self.inequality_constraints)
self.assertEqual(kwargs["num_restarts"], self.optimizer_options["num_restarts"])
self.assertEqual(kwargs["raw_samples"], self.optimizer_options["raw_samples"])
self.assertTrue(
all(
torch.allclose(torch.linspace(0, 1, 30 * (k + 1), **self.tkwargs), c)
for k, c in enumerate(kwargs["discrete_choices"])
)
)
X_avoid_true = torch.cat((self.X, self.pending_observations[0]), dim=0)
self.assertEqual(kwargs["X_avoid"].shape, X_avoid_true.shape)
self.assertTrue( # The order of the rows may not match
all((X_avoid_true == x).all(dim=-1).any().item() for x in kwargs["X_avoid"])
)
@mock_botorch_optimize
def test_optimize_acqf_discrete_too_many_choices(self) -> None:
# Check that mixed optimizer is used when there are too many choices.
# Otherwise, it should use local search.
ssd_ordinal_integer = SearchSpaceDigest(
feature_names=["a", "b", "c"],
bounds=[(0, 100 * (i + 1)) for i in range(3)],
ordinal_features=[0, 1, 2],
discrete_choices={i: list(range(100 * (i + 1) + 1)) for i in range(3)},
)
ssd_categorical_integer = SearchSpaceDigest(
feature_names=["a", "b", "c"],
bounds=[(0, 100 * (i + 1)) for i in range(3)],
categorical_features=[0, 1, 2],
discrete_choices={i: list(range(100 * (i + 1) + 1)) for i in range(3)},
)
ssd_ordinal_noninteger_small = SearchSpaceDigest(
feature_names=["a", "b", "c"],
bounds=[(0, 99) for i in range(3)],
ordinal_features=[0, 1, 2],
discrete_choices={
i: np.arange(0, 100, dtype=np.float64).tolist() for i in range(3)
},
)
ssd_ordinal_noninteger_large = SearchSpaceDigest(
feature_names=["a", "b", "c"],
bounds=[(0, 100) for i in range(3)],
ordinal_features=[0, 1, 2],
discrete_choices={
i: np.arange(0, 100 + 1, dtype=np.float64).tolist() for i in range(3)
},
)
acquisition = self.get_acquisition_function()
for ssd, expected_optimizer in [
(ssd_ordinal_integer, "optimize_acqf_mixed_alternating"),
(ssd_categorical_integer, "optimize_acqf_mixed_alternating"),
(ssd_ordinal_noninteger_small, "optimize_acqf_discrete_local_search"),
(ssd_ordinal_noninteger_large, "optimize_acqf_mixed_alternating"),
]:
# Mock optimize_acqf_discrete_local_search because it isn't handled
# by `mock_botorch_optimize`
with (
mock.patch(
f"{ACQUISITION_PATH}.optimizer_argparse", wraps=optimizer_argparse
) as mock_optimizer_argparse,
mock.patch(
f"{ACQUISITION_PATH}.optimize_acqf_discrete_local_search",
return_value=(torch.rand(3, 3), torch.rand(3)),
),
):
acquisition.optimize(
n=3,
search_space_digest=ssd,
inequality_constraints=self.inequality_constraints,
fixed_features=None,
rounding_func=self.rounding_func,
optimizer_options=self.optimizer_options,
)
mock_optimizer_argparse.assert_called_once_with(
acquisition.acqf,
optimizer_options=self.optimizer_options,
optimizer=expected_optimizer,
)
@mock_botorch_optimize
def test_optimize_mixed(self) -> None:
ssd = SearchSpaceDigest(
feature_names=["a", "b"],
bounds=[(0, 1), (0, 2)],
categorical_features=[1],
discrete_choices={1: [0, 1, 2]},
)
acquisition = self.get_acquisition_function()
with mock.patch(
f"{ACQUISITION_PATH}.optimize_acqf_mixed", wraps=optimize_acqf_mixed
) as mock_optimize_acqf_mixed:
acquisition.optimize(
n=3,
search_space_digest=ssd,
inequality_constraints=self.inequality_constraints,
fixed_features=None,
rounding_func=self.rounding_func,
optimizer_options=self.optimizer_options,
)
mock_optimize_acqf_mixed.assert_called_with(
acq_function=acquisition.acqf,
bounds=mock.ANY,
q=3,
options={"init_batch_limit": INIT_BATCH_LIMIT, "batch_limit": BATCH_LIMIT},
fixed_features_list=[{1: 0}, {1: 1}, {1: 2}],
inequality_constraints=self.inequality_constraints,
post_processing_func=self.rounding_func,
**self.optimizer_options,
)
# can't use assert_called_with on bounds due to ambiguous bool comparison
expected_bounds = torch.tensor(ssd.bounds, **self.tkwargs).transpose(0, 1)
self.assertTrue(
torch.equal(
mock_optimize_acqf_mixed.call_args[1]["bounds"], expected_bounds
)
)
@mock_botorch_optimize
def test_optimize_acqf_mixed_alternating(self) -> None:
b_upper_bound = 15
ssd = SearchSpaceDigest(
feature_names=["a", "b", "c"],
bounds=[(0, 1), (0, b_upper_bound), (0, 5)],
ordinal_features=[1],
discrete_choices={1: list(range(16))},
)
acquisition = self.get_acquisition_function()
# Check with ordinal discrete features.
with mock.patch(
f"{ACQUISITION_PATH}.optimize_acqf_mixed_alternating",
wraps=optimize_acqf_mixed_alternating,
) as mock_alternating:
acquisition.optimize(
n=3,
search_space_digest=ssd,
inequality_constraints=self.inequality_constraints,
fixed_features={0: 0.5},
rounding_func=self.rounding_func,
optimizer_options={
"options": {"maxiter_alternating": 2},
"num_restarts": 2,
"raw_samples": 4,
},
)
mock_alternating.assert_called_with(
acq_function=acquisition.acqf,
bounds=mock.ANY,
discrete_dims={1: list(range(16))},
cat_dims={},
q=3,
options={
"init_batch_limit": INIT_BATCH_LIMIT,
"batch_limit": BATCH_LIMIT,
"maxiter_alternating": 2,
},
inequality_constraints=self.inequality_constraints,
fixed_features={0: 0.5},
post_processing_func=self.rounding_func,
num_restarts=2,
raw_samples=4,
)
# Check with cateogrial features but no non-integer features.
ssd_categorical = dataclasses.replace(
ssd, ordinal_features=[], categorical_features=[1]
)
optimizer_options = {
"options": {"maxiter_alternating": 2},
"num_restarts": 2,
"raw_samples": 4,
}
with mock.patch(
f"{ACQUISITION_PATH}.optimize_acqf_mixed_alternating",
wraps=optimize_acqf_mixed_alternating,
) as mock_alternating:
candidates, acqf_values, arm_weights = acquisition.optimize(
n=3,
search_space_digest=ssd_categorical,
inequality_constraints=self.inequality_constraints,