|
| 1 | +#!/usr/bin/env python3 |
| 2 | +# Copyright (c) Meta Platforms, Inc. and affiliates. |
| 3 | +# |
| 4 | +# This source code is licensed under the MIT license found in the |
| 5 | +# LICENSE file in the root directory of this source tree. |
| 6 | + |
| 7 | + |
| 8 | +import warnings |
| 9 | +from unittest.mock import patch |
| 10 | + |
| 11 | +import torch |
| 12 | +from botorch.acquisition.knowledge_gradient import qKnowledgeGradient |
| 13 | +from botorch.exceptions.warnings import BadInitialCandidatesWarning |
| 14 | +from botorch.generation.gen import gen_candidates_scipy |
| 15 | +from botorch.models.gp_regression import SingleTaskGP |
| 16 | +from botorch.optim.core import scipy_minimize |
| 17 | +from botorch.optim.initializers import gen_batch_initial_conditions, initialize_q_batch |
| 18 | +from botorch.optim.optimize import optimize_acqf |
| 19 | + |
| 20 | +from botorch.test_utils.mock import fast_optimize, fast_optimize_context_manager |
| 21 | +from botorch.utils.testing import BotorchTestCase, MockAcquisitionFunction |
| 22 | + |
| 23 | + |
| 24 | +class SinAcqusitionFunction(MockAcquisitionFunction): |
| 25 | + """Simple acquisition function with known numerical properties.""" |
| 26 | + |
| 27 | + def __init__(self, *args, **kwargs): # noqa: D107 |
| 28 | + return |
| 29 | + |
| 30 | + def __call__(self, X): |
| 31 | + return torch.sin(X[..., 0].max(dim=-1).values) |
| 32 | + |
| 33 | + |
| 34 | +class TestMock(BotorchTestCase): |
| 35 | + def test_fast_optimize_context_manager(self): |
| 36 | + with self.subTest("gen_candidates_scipy"): |
| 37 | + with fast_optimize_context_manager(): |
| 38 | + cand, value = gen_candidates_scipy( |
| 39 | + initial_conditions=torch.tensor([[0.0]]), |
| 40 | + acquisition_function=SinAcqusitionFunction(), |
| 41 | + ) |
| 42 | + # When not using `fast_optimize`, the value is 1.0. With it, the value is |
| 43 | + # around 0.84 |
| 44 | + self.assertLess(value.item(), 0.99) |
| 45 | + |
| 46 | + with self.subTest("scipy_minimize"): |
| 47 | + x = torch.tensor([0.0]) |
| 48 | + |
| 49 | + def closure(): |
| 50 | + return torch.sin(x), [torch.cos(x)] |
| 51 | + |
| 52 | + with fast_optimize_context_manager(): |
| 53 | + result = scipy_minimize(closure=closure, parameters={"x": x}) |
| 54 | + self.assertEqual( |
| 55 | + result.message, "STOP: TOTAL NO. of ITERATIONS REACHED LIMIT" |
| 56 | + ) |
| 57 | + |
| 58 | + with self.subTest("optimize_acqf"): |
| 59 | + with fast_optimize_context_manager(): |
| 60 | + cand, value = optimize_acqf( |
| 61 | + acq_function=SinAcqusitionFunction(), |
| 62 | + bounds=torch.tensor([[-2.0], [2.0]]), |
| 63 | + q=1, |
| 64 | + num_restarts=32, |
| 65 | + batch_initial_conditions=torch.tensor([[0.0]]), |
| 66 | + ) |
| 67 | + self.assertLess(value.item(), 0.99) |
| 68 | + |
| 69 | + with self.subTest("gen_batch_initial_conditions"): |
| 70 | + with fast_optimize_context_manager(), patch( |
| 71 | + "botorch.optim.initializers.initialize_q_batch", |
| 72 | + wraps=initialize_q_batch, |
| 73 | + ) as mock_init_q_batch: |
| 74 | + cand, value = optimize_acqf( |
| 75 | + acq_function=SinAcqusitionFunction(), |
| 76 | + bounds=torch.tensor([[-2.0], [2.0]]), |
| 77 | + q=1, |
| 78 | + num_restarts=32, |
| 79 | + raw_samples=16, |
| 80 | + ) |
| 81 | + self.assertEqual(mock_init_q_batch.call_args[1]["n"], 2) |
| 82 | + |
| 83 | + @fast_optimize |
| 84 | + def test_decorator(self) -> None: |
| 85 | + model = SingleTaskGP( |
| 86 | + train_X=torch.tensor([[0.0]], dtype=torch.double), |
| 87 | + train_Y=torch.tensor([[0.0]], dtype=torch.double), |
| 88 | + ) |
| 89 | + acqf = qKnowledgeGradient(model=model, num_fantasies=64) |
| 90 | + # this is called within gen_one_shot_kg_initial_conditions |
| 91 | + with patch( |
| 92 | + "botorch.optim.initializers.gen_batch_initial_conditions", |
| 93 | + wraps=gen_batch_initial_conditions, |
| 94 | + ) as mock_gen_batch_ics, warnings.catch_warnings(): |
| 95 | + warnings.simplefilter("ignore", category=BadInitialCandidatesWarning) |
| 96 | + cand, value = optimize_acqf( |
| 97 | + acq_function=acqf, |
| 98 | + bounds=torch.tensor([[-2.0], [2.0]]), |
| 99 | + q=1, |
| 100 | + num_restarts=32, |
| 101 | + raw_samples=16, |
| 102 | + ) |
| 103 | + |
| 104 | + called_with = mock_gen_batch_ics.call_args[1] |
| 105 | + self.assertEqual(called_with["num_restarts"], 2) |
| 106 | + self.assertEqual(called_with["raw_samples"], 4) |
| 107 | + |
| 108 | + def test_raises_when_unused(self) -> None: |
| 109 | + with self.assertRaisesRegex(AssertionError, "No mocks were called"): |
| 110 | + with fast_optimize_context_manager(): |
| 111 | + pass |
0 commit comments