|
| 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 | +Dummy classes and other helpers that are used in multiple test files |
| 9 | +should be defined here to avoid relative imports. |
| 10 | +""" |
| 11 | + |
| 12 | +from __future__ import annotations |
| 13 | + |
| 14 | +import math |
| 15 | +from typing import Optional, Tuple |
| 16 | + |
| 17 | +import torch |
| 18 | +from botorch.acquisition.objective import PosteriorTransform |
| 19 | +from botorch.models.gpytorch import GPyTorchModel |
| 20 | +from botorch.models.model import FantasizeMixin, Model |
| 21 | +from botorch.models.transforms.outcome import Standardize |
| 22 | +from botorch.models.utils import add_output_dim |
| 23 | +from botorch.models.utils.assorted import fantasize |
| 24 | +from botorch.posteriors.posterior import Posterior |
| 25 | +from botorch.utils.datasets import MultiTaskDataset, SupervisedDataset |
| 26 | +from gpytorch.distributions.multivariate_normal import MultivariateNormal |
| 27 | +from gpytorch.kernels import RBFKernel, ScaleKernel |
| 28 | +from gpytorch.likelihoods.gaussian_likelihood import ( |
| 29 | + FixedNoiseGaussianLikelihood, |
| 30 | + GaussianLikelihood, |
| 31 | +) |
| 32 | +from gpytorch.means import ConstantMean |
| 33 | +from gpytorch.models.exact_gp import ExactGP |
| 34 | +from torch import Size, Tensor |
| 35 | +from torch.nn.functional import pad |
| 36 | + |
| 37 | + |
| 38 | +def get_sample_moments(samples: Tensor, sample_shape: Size) -> Tuple[Tensor, Tensor]: |
| 39 | + """Computes the mean and covariance of a set of samples. |
| 40 | +
|
| 41 | + Args: |
| 42 | + samples: A tensor of shape `sample_shape x batch_shape x q`. |
| 43 | + sample_shape: The sample_shape input used while generating the samples using |
| 44 | + the pathwise sampling API. |
| 45 | + """ |
| 46 | + sample_dim = len(sample_shape) |
| 47 | + samples = samples.view(-1, *samples.shape[sample_dim:]) |
| 48 | + loc = samples.mean(dim=0) |
| 49 | + residuals = (samples - loc).permute(*range(1, samples.ndim), 0) |
| 50 | + return loc, (residuals @ residuals.transpose(-2, -1)) / sample_shape.numel() |
| 51 | + |
| 52 | + |
| 53 | +def standardize_moments( |
| 54 | + transform: Standardize, |
| 55 | + loc: Tensor, |
| 56 | + covariance_matrix: Tensor, |
| 57 | +) -> Tuple[Tensor, Tensor]: |
| 58 | + """Standardizes the loc and covariance_matrix using the mean and standard |
| 59 | + deviations from a Standardize transform. |
| 60 | + """ |
| 61 | + m = transform.means.squeeze().unsqueeze(-1) |
| 62 | + s = transform.stdvs.squeeze().reciprocal().unsqueeze(-1) |
| 63 | + loc = s * (loc - m) |
| 64 | + correlation_matrix = s.unsqueeze(-1) * covariance_matrix * s.unsqueeze(-2) |
| 65 | + return loc, correlation_matrix |
| 66 | + |
| 67 | + |
| 68 | +def gen_multi_task_dataset( |
| 69 | + yvar: Optional[float] = None, **tkwargs |
| 70 | +) -> Tuple[MultiTaskDataset, Tuple[Tensor, Tensor, Tensor]]: |
| 71 | + """Constructs a multi-task dataset with two tasks, each with 10 data points.""" |
| 72 | + X = torch.linspace(0, 0.95, 10, **tkwargs) + 0.05 * torch.rand(10, **tkwargs) |
| 73 | + X = X.unsqueeze(dim=-1) |
| 74 | + Y1 = torch.sin(X * (2 * math.pi)) + torch.randn_like(X) * 0.2 |
| 75 | + Y2 = torch.cos(X * (2 * math.pi)) + torch.randn_like(X) * 0.2 |
| 76 | + train_X = torch.cat([pad(X, (1, 0), value=i) for i in range(2)]) |
| 77 | + train_Y = torch.cat([Y1, Y2]) |
| 78 | + |
| 79 | + Yvar1 = None if yvar is None else torch.full_like(Y1, yvar) |
| 80 | + Yvar2 = None if yvar is None else torch.full_like(Y2, yvar) |
| 81 | + train_Yvar = None if yvar is None else torch.cat([Yvar1, Yvar2]) |
| 82 | + datasets = [ |
| 83 | + SupervisedDataset( |
| 84 | + X=train_X[:10], |
| 85 | + Y=Y1, |
| 86 | + Yvar=Yvar1, |
| 87 | + feature_names=["task", "X"], |
| 88 | + outcome_names=["y"], |
| 89 | + ), |
| 90 | + SupervisedDataset( |
| 91 | + X=train_X[10:], |
| 92 | + Y=Y2, |
| 93 | + Yvar=Yvar2, |
| 94 | + feature_names=["task", "X"], |
| 95 | + outcome_names=["y1"], |
| 96 | + ), |
| 97 | + ] |
| 98 | + dataset = MultiTaskDataset( |
| 99 | + datasets=datasets, target_outcome_name="y", task_feature_index=0 |
| 100 | + ) |
| 101 | + return dataset, (train_X, train_Y, train_Yvar) |
| 102 | + |
| 103 | + |
| 104 | +def get_pvar_expected(posterior: Posterior, model: Model, X: Tensor, m: int) -> Tensor: |
| 105 | + """Computes the expected variance of a posterior after adding the |
| 106 | + predictive noise from the likelihood. |
| 107 | + """ |
| 108 | + X = model.transform_inputs(X) |
| 109 | + lh_kwargs = {} |
| 110 | + if isinstance(model.likelihood, FixedNoiseGaussianLikelihood): |
| 111 | + lh_kwargs["noise"] = model.likelihood.noise.mean().expand(X.shape[:-1]) |
| 112 | + if m == 1: |
| 113 | + return model.likelihood( |
| 114 | + posterior.distribution, X, **lh_kwargs |
| 115 | + ).variance.unsqueeze(-1) |
| 116 | + X_, odi = add_output_dim(X=X, original_batch_shape=model._input_batch_shape) |
| 117 | + pvar_exp = model.likelihood(model(X_), X_, **lh_kwargs).variance |
| 118 | + return torch.stack([pvar_exp.select(dim=odi, index=i) for i in range(m)], dim=-1) |
| 119 | + |
| 120 | + |
| 121 | +class DummyNonScalarizingPosteriorTransform(PosteriorTransform): |
| 122 | + scalarize = False |
| 123 | + |
| 124 | + def evaluate(self, Y): |
| 125 | + pass # pragma: no cover |
| 126 | + |
| 127 | + def forward(self, posterior): |
| 128 | + pass # pragma: no cover |
| 129 | + |
| 130 | + |
| 131 | +class SimpleGPyTorchModel(GPyTorchModel, ExactGP, FantasizeMixin): |
| 132 | + last_fantasize_flag: bool = False |
| 133 | + |
| 134 | + def __init__(self, train_X, train_Y, outcome_transform=None, input_transform=None): |
| 135 | + r""" |
| 136 | + Args: |
| 137 | + train_X: A tensor of inputs, passed to self.transform_inputs. |
| 138 | + train_Y: Passed to outcome_transform. |
| 139 | + outcome_transform: Transform applied to train_Y. |
| 140 | + input_transform: A Module that performs the input transformation, passed to |
| 141 | + self.transform_inputs. |
| 142 | + """ |
| 143 | + with torch.no_grad(): |
| 144 | + transformed_X = self.transform_inputs( |
| 145 | + X=train_X, input_transform=input_transform |
| 146 | + ) |
| 147 | + if outcome_transform is not None: |
| 148 | + train_Y, _ = outcome_transform(train_Y) |
| 149 | + self._validate_tensor_args(transformed_X, train_Y) |
| 150 | + train_Y = train_Y.squeeze(-1) |
| 151 | + likelihood = GaussianLikelihood() |
| 152 | + super().__init__(train_X, train_Y, likelihood) |
| 153 | + self.mean_module = ConstantMean() |
| 154 | + self.covar_module = ScaleKernel(RBFKernel()) |
| 155 | + if outcome_transform is not None: |
| 156 | + self.outcome_transform = outcome_transform |
| 157 | + if input_transform is not None: |
| 158 | + self.input_transform = input_transform |
| 159 | + self._num_outputs = 1 |
| 160 | + self.to(train_X) |
| 161 | + self.transformed_call_args = [] |
| 162 | + |
| 163 | + def forward(self, x): |
| 164 | + self.last_fantasize_flag = fantasize.on() |
| 165 | + if self.training: |
| 166 | + x = self.transform_inputs(x) |
| 167 | + self.transformed_call_args.append(x) |
| 168 | + mean_x = self.mean_module(x) |
| 169 | + covar_x = self.covar_module(x) |
| 170 | + return MultivariateNormal(mean_x, covar_x) |
0 commit comments