|
| 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 | +r""" |
| 8 | +Ensemble posteriors. Used in conjunction with ensemble models. |
| 9 | +""" |
| 10 | + |
| 11 | +from __future__ import annotations |
| 12 | + |
| 13 | +from typing import Optional |
| 14 | + |
| 15 | +import torch |
| 16 | +from botorch.posteriors.posterior import Posterior |
| 17 | +from torch import Tensor |
| 18 | + |
| 19 | + |
| 20 | +class EnsemblePosterior(Posterior): |
| 21 | + r"""Ensemble posterior, that should be used for ensemble models that compute |
| 22 | + eagerly a finite number of samples per X value as for example a deep ensemble |
| 23 | + or a random forest.""" |
| 24 | + |
| 25 | + def __init__(self, values: Tensor) -> None: |
| 26 | + r""" |
| 27 | + Args: |
| 28 | + values: Values of the samples produced by this posterior as |
| 29 | + a `(b) x s x q x m` tensor where `m` is the output size of the |
| 30 | + model and `s` is the ensemble size. |
| 31 | + """ |
| 32 | + if values.ndim < 3: |
| 33 | + raise ValueError("Values has to be at least three-dimensional.") |
| 34 | + self.values = values |
| 35 | + |
| 36 | + @property |
| 37 | + def ensemble_size(self) -> int: |
| 38 | + r"""The size of the ensemble""" |
| 39 | + return self.values.shape[-3] |
| 40 | + |
| 41 | + @property |
| 42 | + def weights(self) -> Tensor: |
| 43 | + r"""The weights of the individual models in the ensemble. |
| 44 | + Equally weighted by default.""" |
| 45 | + return torch.ones(self.ensemble_size) / self.ensemble_size |
| 46 | + |
| 47 | + @property |
| 48 | + def device(self) -> torch.device: |
| 49 | + r"""The torch device of the posterior.""" |
| 50 | + return self.values.device |
| 51 | + |
| 52 | + @property |
| 53 | + def dtype(self) -> torch.dtype: |
| 54 | + r"""The torch dtype of the posterior.""" |
| 55 | + return self.values.dtype |
| 56 | + |
| 57 | + @property |
| 58 | + def mean(self) -> Tensor: |
| 59 | + r"""The mean of the posterior as a `(b) x n x m`-dim Tensor.""" |
| 60 | + return self.values.mean(dim=-3) |
| 61 | + |
| 62 | + @property |
| 63 | + def variance(self) -> Tensor: |
| 64 | + r"""The variance of the posterior as a `(b) x n x m`-dim Tensor. |
| 65 | +
|
| 66 | + Computed as the sample variance across the ensemble outputs. |
| 67 | + """ |
| 68 | + if self.ensemble_size == 1: |
| 69 | + return torch.zeros_like(self.values.squeeze(-3)) |
| 70 | + return self.values.var(dim=-3) |
| 71 | + |
| 72 | + def _extended_shape( |
| 73 | + self, sample_shape: torch.Size = torch.Size() # noqa: B008 |
| 74 | + ) -> torch.Size: |
| 75 | + r"""Returns the shape of the samples produced by the posterior with |
| 76 | + the given `sample_shape`. |
| 77 | + """ |
| 78 | + return sample_shape + self.values.shape[:-3] + self.values.shape[-2:] |
| 79 | + |
| 80 | + def rsample( |
| 81 | + self, |
| 82 | + sample_shape: Optional[torch.Size] = None, |
| 83 | + ) -> Tensor: |
| 84 | + r"""Sample from the posterior (with gradients). |
| 85 | +
|
| 86 | + Based on the sample shape, base samples are generated and passed to |
| 87 | + `rsample_from_base_samples`. |
| 88 | +
|
| 89 | + Args: |
| 90 | + sample_shape: A `torch.Size` object specifying the sample shape. To |
| 91 | + draw `n` samples, set to `torch.Size([n])`. To draw `b` batches |
| 92 | + of `n` samples each, set to `torch.Size([b, n])`. |
| 93 | +
|
| 94 | + Returns: |
| 95 | + Samples from the posterior, a tensor of shape |
| 96 | + `self._extended_shape(sample_shape=sample_shape)`. |
| 97 | + """ |
| 98 | + if sample_shape is None: |
| 99 | + sample_shape = torch.Size([1]) |
| 100 | + # get indices as base_samples |
| 101 | + base_samples = ( |
| 102 | + torch.multinomial( |
| 103 | + self.weights, |
| 104 | + num_samples=sample_shape.numel(), |
| 105 | + replacement=True, |
| 106 | + ) |
| 107 | + .reshape(sample_shape) |
| 108 | + .to(device=self.device) |
| 109 | + ) |
| 110 | + return self.rsample_from_base_samples( |
| 111 | + sample_shape=sample_shape, base_samples=base_samples |
| 112 | + ) |
| 113 | + |
| 114 | + def rsample_from_base_samples( |
| 115 | + self, sample_shape: torch.Size, base_samples: Tensor |
| 116 | + ) -> Tensor: |
| 117 | + r"""Sample from the posterior (with gradients) using base samples. |
| 118 | +
|
| 119 | + This is intended to be used with a sampler that produces the corresponding base |
| 120 | + samples, and enables acquisition optimization via Sample Average Approximation. |
| 121 | +
|
| 122 | + Args: |
| 123 | + sample_shape: A `torch.Size` object specifying the sample shape. To |
| 124 | + draw `n` samples, set to `torch.Size([n])`. To draw `b` batches |
| 125 | + of `n` samples each, set to `torch.Size([b, n])`. |
| 126 | + base_samples: A Tensor of indices as base samples of shape |
| 127 | + `sample_shape`, typically obtained from `IndexSampler`. |
| 128 | + This is used for deterministic optimization. The predictions of |
| 129 | + the ensemble corresponding to the indices are then sampled. |
| 130 | +
|
| 131 | +
|
| 132 | + Returns: |
| 133 | + Samples from the posterior, a tensor of shape |
| 134 | + `self._extended_shape(sample_shape=sample_shape)`. |
| 135 | + """ |
| 136 | + if base_samples.shape != sample_shape: |
| 137 | + raise ValueError("Base samples do not match sample shape.") |
| 138 | + # move sample axis to front |
| 139 | + values = self.values.movedim(-3, 0) |
| 140 | + # sample from the first dimension of values |
| 141 | + return values[base_samples, ...] |
0 commit comments