|
16 | 16 | from abc import ABC, abstractmethod |
17 | 17 | from collections import defaultdict |
18 | 18 | from copy import deepcopy |
19 | | -from typing import Any, Callable, Dict, Hashable, List, Mapping, Optional, Union |
| 19 | +from typing import ( |
| 20 | + Any, |
| 21 | + Callable, |
| 22 | + Dict, |
| 23 | + Hashable, |
| 24 | + List, |
| 25 | + Mapping, |
| 26 | + Optional, |
| 27 | + TypeVar, |
| 28 | + Union, |
| 29 | +) |
20 | 30 |
|
21 | 31 | import numpy as np |
22 | 32 | import torch |
|
30 | 40 | from torch import Tensor |
31 | 41 | from torch.nn import Module, ModuleList |
32 | 42 |
|
| 43 | +TFantasizeMixin = TypeVar("TFantasizeMixin", bound="FantasizeMixin") |
| 44 | + |
33 | 45 |
|
34 | 46 | class Model(Module, ABC): |
35 | 47 | r"""Abstract base class for BoTorch models. |
@@ -138,42 +150,6 @@ def condition_on_observations(self, X: Tensor, Y: Tensor, **kwargs: Any) -> Mode |
138 | 150 | f"`condition_on_observations` not implemented for {self.__class__.__name__}" |
139 | 151 | ) |
140 | 152 |
|
141 | | - def fantasize( |
142 | | - self, |
143 | | - X: Tensor, |
144 | | - sampler: MCSampler, |
145 | | - observation_noise: bool = True, |
146 | | - **kwargs: Any, |
147 | | - ) -> Model: |
148 | | - r"""Construct a fantasy model. |
149 | | -
|
150 | | - Constructs a fantasy model in the following fashion: |
151 | | - (1) compute the model posterior at `X` (including observation noise if |
152 | | - `observation_noise=True`). |
153 | | - (2) sample from this posterior (using `sampler`) to generate "fake" |
154 | | - observations. |
155 | | - (3) condition the model on the new fake observations. |
156 | | -
|
157 | | - Args: |
158 | | - X: A `batch_shape x n' x d`-dim Tensor, where `d` is the dimension of |
159 | | - the feature space, `n'` is the number of points per batch, and |
160 | | - `batch_shape` is the batch shape (must be compatible with the |
161 | | - batch shape of the model). |
162 | | - sampler: The sampler used for sampling from the posterior at `X`. |
163 | | - observation_noise: If True, include observation noise. |
164 | | -
|
165 | | - Returns: |
166 | | - The constructed fantasy model. |
167 | | - """ |
168 | | - propagate_grads = kwargs.pop("propagate_grads", False) |
169 | | - with fantasize_flag(): |
170 | | - with settings.propagate_grads(propagate_grads): |
171 | | - post_X = self.posterior(X, observation_noise=observation_noise) |
172 | | - Y_fantasized = sampler(post_X) # num_fantasies x batch_shape x n' x m |
173 | | - return self.condition_on_observations( |
174 | | - X=self.transform_inputs(X), Y=Y_fantasized, **kwargs |
175 | | - ) |
176 | | - |
177 | 153 | @classmethod |
178 | 154 | def construct_inputs( |
179 | 155 | cls, |
@@ -252,6 +228,100 @@ def train(self, mode: bool = True) -> Model: |
252 | 228 | return super().train(mode=mode) |
253 | 229 |
|
254 | 230 |
|
| 231 | +class FantasizeMixin(ABC): |
| 232 | + """ |
| 233 | + Mixin to add a `fantasize` method to a `Model`. |
| 234 | +
|
| 235 | + Example: |
| 236 | + class BaseModel: |
| 237 | + def __init__(self, ...): |
| 238 | + def condition_on_observations(self, ...): |
| 239 | + def posterior(self, ...): |
| 240 | + def transform_inputs(self, ...): |
| 241 | +
|
| 242 | + class ModelThatCanFantasize(BaseModel, FantasizeMixin): |
| 243 | + def __init__(self, args): |
| 244 | + super().__init__(args) |
| 245 | +
|
| 246 | + model = ModelThatCanFantasize(...) |
| 247 | + model.fantasize(X) |
| 248 | + """ |
| 249 | + |
| 250 | + @abstractmethod |
| 251 | + def condition_on_observations( |
| 252 | + self: TFantasizeMixin, X: Tensor, Y: Tensor, **kwargs: Any |
| 253 | + ) -> TFantasizeMixin: |
| 254 | + """ |
| 255 | + Classes that inherit from `FantasizeMixin` must implement |
| 256 | + a `condition_on_observations` method. |
| 257 | + """ |
| 258 | + |
| 259 | + @abstractmethod |
| 260 | + def posterior( |
| 261 | + self, |
| 262 | + X: Tensor, |
| 263 | + *args, |
| 264 | + observation_noise: bool = False, |
| 265 | + **kwargs: Any, |
| 266 | + ) -> Posterior: |
| 267 | + """ |
| 268 | + Classes that inherit from `FantasizeMixin` must implement |
| 269 | + a `posterior` method. |
| 270 | + """ |
| 271 | + |
| 272 | + @abstractmethod |
| 273 | + def transform_inputs( |
| 274 | + self, |
| 275 | + X: Tensor, |
| 276 | + input_transform: Optional[Module] = None, |
| 277 | + ) -> Tensor: |
| 278 | + """ |
| 279 | + Classes that inherit from `FantasizeMixin` must implement |
| 280 | + a `transform_inputs` method. |
| 281 | + """ |
| 282 | + |
| 283 | + # When Python 3.11 arrives we can start annotating return types like |
| 284 | + # this as |
| 285 | + # 'Self', but at this point the verbose 'T...' syntax is needed. |
| 286 | + def fantasize( |
| 287 | + self: TFantasizeMixin, |
| 288 | + # TODO: see if any of these can be imported only if TYPE_CHECKING |
| 289 | + X: Tensor, |
| 290 | + sampler: MCSampler, |
| 291 | + observation_noise: bool = True, |
| 292 | + **kwargs: Any, |
| 293 | + ) -> TFantasizeMixin: |
| 294 | + r"""Construct a fantasy model. |
| 295 | +
|
| 296 | + Constructs a fantasy model in the following fashion: |
| 297 | + (1) compute the model posterior at `X` (including observation noise if |
| 298 | + `observation_noise=True`). |
| 299 | + (2) sample from this posterior (using `sampler`) to generate "fake" |
| 300 | + observations. |
| 301 | + (3) condition the model on the new fake observations. |
| 302 | +
|
| 303 | + Args: |
| 304 | + X: A `batch_shape x n' x d`-dim Tensor, where `d` is the dimension of |
| 305 | + the feature space, `n'` is the number of points per batch, and |
| 306 | + `batch_shape` is the batch shape (must be compatible with the |
| 307 | + batch shape of the model). |
| 308 | + sampler: The sampler used for sampling from the posterior at `X`. |
| 309 | + observation_noise: If True, include observation noise. |
| 310 | + kwargs: Will be passed to `model.condition_on_observations` |
| 311 | +
|
| 312 | + Returns: |
| 313 | + The constructed fantasy model. |
| 314 | + """ |
| 315 | + propagate_grads = kwargs.pop("propagate_grads", False) |
| 316 | + with fantasize_flag(): |
| 317 | + with settings.propagate_grads(propagate_grads): |
| 318 | + post_X = self.posterior(X, observation_noise=observation_noise) |
| 319 | + Y_fantasized = sampler(post_X) # num_fantasies x batch_shape x n' x m |
| 320 | + return self.condition_on_observations( |
| 321 | + X=self.transform_inputs(X), Y=Y_fantasized, **kwargs |
| 322 | + ) |
| 323 | + |
| 324 | + |
255 | 325 | class ModelList(Model): |
256 | 326 | r"""A multi-output Model represented by a list of independent models. |
257 | 327 |
|
|
0 commit comments