|
9 | 9 | from botorch.acquisition.objective import PosteriorTransform |
10 | 10 | from botorch.exceptions.errors import InputDataError |
11 | 11 | from botorch.models.deterministic import GenericDeterministicModel |
| 12 | +from botorch.models.gp_regression import SingleTaskGP |
12 | 13 | from botorch.models.model import Model, ModelDict, ModelList |
| 14 | +from botorch.models.transforms.input import Normalize, Round |
| 15 | +from botorch.models.transforms.outcome import Standardize |
13 | 16 | from botorch.posteriors.ensemble import EnsemblePosterior |
14 | 17 | from botorch.posteriors.posterior_list import PosteriorList |
15 | 18 | from botorch.utils.datasets import SupervisedDataset |
16 | 19 | from botorch.utils.testing import BotorchTestCase, MockModel, MockPosterior |
17 | 20 | from torch import rand |
| 21 | +from torch.nn import Module |
| 22 | + |
| 23 | + |
| 24 | +class NonUntransformableOutcomeTransform(Standardize): |
| 25 | + def untransform(self, **kwargs): |
| 26 | + raise NotImplementedError |
18 | 27 |
|
19 | 28 |
|
20 | 29 | class NotSoAbstractBaseModel(Model): |
@@ -138,6 +147,211 @@ def test_posterior_transform(self): |
138 | 147 | ) |
139 | 148 |
|
140 | 149 |
|
| 150 | +def _get_input_output_transform( |
| 151 | + d: int, m: int, use_transforms: bool = True |
| 152 | +) -> dict[str, Module]: |
| 153 | + return { |
| 154 | + "input_transform": Normalize(d=d) if use_transforms else None, |
| 155 | + "outcome_transform": Standardize(m=m) if use_transforms else None, |
| 156 | + } |
| 157 | + |
| 158 | + |
| 159 | +class TestTransformWarnings(BotorchTestCase): |
| 160 | + def test_set_transformed_inputs_warning_no_train_inputs(self): |
| 161 | + """Test warning when model has input_transform but no train_inputs.""" |
| 162 | + # Setup: Create a model with input_transform but without train_inputs attribute |
| 163 | + model = NotSoAbstractBaseModel() |
| 164 | + model.input_transform = Normalize(d=2) |
| 165 | + |
| 166 | + # Execute: Call _set_transformed_inputs which should trigger warning |
| 167 | + # Assert: Verify warning is raised |
| 168 | + with self.assertWarnsRegex( |
| 169 | + RuntimeWarning, |
| 170 | + "Could not update `train_inputs` with transformed inputs " |
| 171 | + "since NotSoAbstractBaseModel does not have a `train_inputs` " |
| 172 | + "attribute. Make sure that the `input_transform` is applied to " |
| 173 | + "both the train inputs and test inputs.", |
| 174 | + ): |
| 175 | + model._set_transformed_inputs() |
| 176 | + |
| 177 | + def test_load_state_dict_output_warnings(self): |
| 178 | + """Test warning when outcome transform doesn't support untransforming.""" |
| 179 | + tkwargs = {"device": self.device, "dtype": torch.double} |
| 180 | + |
| 181 | + train_X = torch.rand(3, 2, **tkwargs) |
| 182 | + train_Y = torch.rand(3, 1, **tkwargs) |
| 183 | + |
| 184 | + # Setup: Create model with untransformable outcome transform |
| 185 | + model = SingleTaskGP( |
| 186 | + train_X=train_X, |
| 187 | + train_Y=train_Y, |
| 188 | + input_transform=Normalize(d=2), |
| 189 | + outcome_transform=NonUntransformableOutcomeTransform(m=1), |
| 190 | + ) |
| 191 | + state_dict = model.state_dict() |
| 192 | + |
| 193 | + # Assert: Verify warning is raised for untransformable outcome transform |
| 194 | + with self.assertWarnsRegex( |
| 195 | + UserWarning, |
| 196 | + "Outcome transform does not support untransforming.*", |
| 197 | + ): |
| 198 | + model.load_state_dict(state_dict, keep_transforms=True) |
| 199 | + |
| 200 | + |
| 201 | +class TestLoadStateDict(BotorchTestCase): |
| 202 | + def _test_load_state_dict_base( |
| 203 | + self, num_outputs: int, include_yvar: bool = True |
| 204 | + ) -> None: |
| 205 | + """Base test helper for load_state_dict with transforms.""" |
| 206 | + tkwargs = {"device": self.device, "dtype": torch.double} |
| 207 | + from botorch.models.gp_regression import SingleTaskGP |
| 208 | + |
| 209 | + train_X = torch.rand(3, 2, **tkwargs) |
| 210 | + train_X = torch.cat( |
| 211 | + [train_X, torch.tensor([[-0.02, 11.1], [17.1, -2.5]], **tkwargs)], dim=0 |
| 212 | + ) |
| 213 | + train_Y = torch.sin(train_X).sum(dim=1, keepdim=True).repeat(1, num_outputs) |
| 214 | + |
| 215 | + model_kwargs = { |
| 216 | + "train_X": train_X, |
| 217 | + "train_Y": train_Y, |
| 218 | + } |
| 219 | + |
| 220 | + if include_yvar: |
| 221 | + train_Yvar = 0.1 * torch.rand_like(train_Y) |
| 222 | + model_kwargs["train_Yvar"] = train_Yvar |
| 223 | + |
| 224 | + base_model = SingleTaskGP( |
| 225 | + **model_kwargs, **_get_input_output_transform(d=2, m=num_outputs) |
| 226 | + ) |
| 227 | + |
| 228 | + original_train_inputs = base_model.input_transform(base_model.train_inputs[0]) |
| 229 | + original_train_targets = base_model.train_targets.clone() |
| 230 | + original_train_yvar = base_model.likelihood.noise_covar.noise.clone() |
| 231 | + |
| 232 | + state_dict = base_model.state_dict() |
| 233 | + |
| 234 | + cv_model_kwargs = model_kwargs.copy() |
| 235 | + cv_model_kwargs["train_X"] = train_X[:-1] |
| 236 | + cv_model_kwargs["train_Y"] = train_Y[:-1] |
| 237 | + if include_yvar: |
| 238 | + cv_model_kwargs["train_Yvar"] = train_Yvar[:-1] |
| 239 | + cv_model = SingleTaskGP( |
| 240 | + **cv_model_kwargs, **_get_input_output_transform(d=2, m=num_outputs) |
| 241 | + ) |
| 242 | + |
| 243 | + # Test keep_transforms=True |
| 244 | + cv_model.load_state_dict(state_dict, keep_transforms=True) |
| 245 | + |
| 246 | + # Ensure outcome transform is in eval mode and doesn't change parameters |
| 247 | + sd_mean = cv_model.outcome_transform.means |
| 248 | + cv_model.outcome_transform(train_Y[:-1]) |
| 249 | + self.assertTrue(torch.all(cv_model.outcome_transform.means == sd_mean)) |
| 250 | + |
| 251 | + # Check that transform parameters match state_dict |
| 252 | + self.assertTrue( |
| 253 | + torch.allclose( |
| 254 | + cv_model.input_transform._offset, |
| 255 | + state_dict["input_transform._offset"], |
| 256 | + ) |
| 257 | + ) |
| 258 | + self.assertTrue( |
| 259 | + torch.allclose( |
| 260 | + cv_model.outcome_transform.means, |
| 261 | + state_dict["outcome_transform.means"], |
| 262 | + ) |
| 263 | + ) |
| 264 | + |
| 265 | + # Verify train data preservation in transformed space |
| 266 | + self.assertAllClose(cv_model.train_targets, original_train_targets[..., :-1]) |
| 267 | + self.assertTrue( |
| 268 | + torch.equal( |
| 269 | + cv_model.input_transform(cv_model.train_inputs[0]), |
| 270 | + original_train_inputs[..., :-1, :], |
| 271 | + ) |
| 272 | + ) |
| 273 | + if include_yvar: |
| 274 | + self.assertAllClose( |
| 275 | + cv_model.likelihood.noise_covar.noise, original_train_yvar[..., :-1] |
| 276 | + ) |
| 277 | + |
| 278 | + # Test keep_transforms=False (allows refitting) |
| 279 | + cv_model = SingleTaskGP( |
| 280 | + **cv_model_kwargs, **_get_input_output_transform(d=2, m=num_outputs) |
| 281 | + ) |
| 282 | + cv_model.load_state_dict(state_dict, keep_transforms=False) |
| 283 | + |
| 284 | + # Transforms should refit on new data |
| 285 | + sd_mean = cv_model.outcome_transform.means |
| 286 | + cv_model.outcome_transform(train_Y[:-1]) |
| 287 | + self.assertTrue(torch.all(cv_model.outcome_transform.means != sd_mean)) |
| 288 | + |
| 289 | + self.assertFalse( |
| 290 | + torch.equal( |
| 291 | + cv_model.input_transform(cv_model.train_inputs[0]), |
| 292 | + original_train_inputs[..., :-1, :], |
| 293 | + ) |
| 294 | + ) |
| 295 | + self.assertFalse( |
| 296 | + torch.equal(cv_model.train_targets, original_train_targets[..., :-1]) |
| 297 | + ) |
| 298 | + self.assertFalse( |
| 299 | + torch.equal( |
| 300 | + cv_model.input_transform._offset, |
| 301 | + state_dict["input_transform._offset"], |
| 302 | + ) |
| 303 | + ) |
| 304 | + self.assertFalse( |
| 305 | + torch.equal( |
| 306 | + cv_model.outcome_transform.means, |
| 307 | + state_dict["outcome_transform.means"], |
| 308 | + ) |
| 309 | + ) |
| 310 | + |
| 311 | + def test_load_state_dict_with_transforms(self): |
| 312 | + """Test load_state_dict with input and outcome transforms.""" |
| 313 | + self._test_load_state_dict_base(num_outputs=1, include_yvar=True) |
| 314 | + |
| 315 | + def test_load_state_dict_with_transforms_no_yvar(self): |
| 316 | + """Test load_state_dict with input and outcome transforms without Yvar.""" |
| 317 | + self._test_load_state_dict_base(num_outputs=1, include_yvar=False) |
| 318 | + |
| 319 | + def test_load_state_dict_multi_output_with_transforms(self): |
| 320 | + """Test load_state_dict with multi-output model and transforms.""" |
| 321 | + self._test_load_state_dict_base(num_outputs=3, include_yvar=True) |
| 322 | + |
| 323 | + def test_load_state_dict_multi_output_with_transforms_no_yvar(self): |
| 324 | + """Test load_state_dict with multi-output model and transforms without Yvar.""" |
| 325 | + self._test_load_state_dict_base(num_outputs=3, include_yvar=False) |
| 326 | + |
| 327 | + def test_load_state_dict_no_transforms(self): |
| 328 | + """Test load_state_dict without any transforms.""" |
| 329 | + tkwargs = {"device": self.device, "dtype": torch.double} |
| 330 | + from botorch.models.gp_regression import SingleTaskGP |
| 331 | + |
| 332 | + train_X = torch.rand(3, 2, **tkwargs) |
| 333 | + train_X = torch.cat( |
| 334 | + [train_X, torch.tensor([[-0.02, 11.1], [17.1, -2.5]], **tkwargs)], dim=0 |
| 335 | + ) |
| 336 | + train_Y = torch.sin(train_X).sum(dim=1, keepdim=True) |
| 337 | + |
| 338 | + base_model = SingleTaskGP( |
| 339 | + train_X=train_X, train_Y=train_Y, outcome_transform=None |
| 340 | + ) |
| 341 | + original_train_targets = base_model.train_targets.clone() |
| 342 | + state_dict = base_model.state_dict() |
| 343 | + |
| 344 | + cv_model = SingleTaskGP( |
| 345 | + train_X=train_X[:-1], train_Y=train_Y[:-1], outcome_transform=None |
| 346 | + ) |
| 347 | + cv_model.load_state_dict(state_dict, keep_transforms=False) |
| 348 | + |
| 349 | + # Verify train targets are preserved |
| 350 | + self.assertTrue( |
| 351 | + torch.equal(cv_model.train_targets, original_train_targets[:-1]) |
| 352 | + ) |
| 353 | + |
| 354 | + |
141 | 355 | class TestModelDict(BotorchTestCase): |
142 | 356 | def test_model_dict(self): |
143 | 357 | models = {"m1": MockModel(MockPosterior()), "m2": MockModel(MockPosterior())} |
|
0 commit comments