|
1 | 1 | #!/usr/bin/env python3
|
2 | 2 |
|
| 3 | +import warnings |
| 4 | +from typing import Any, Optional |
| 5 | + |
3 | 6 | import torch
|
4 | 7 |
|
| 8 | +from ..constraints import Interval |
| 9 | +from ..priors import Prior |
5 | 10 | from ..utils.broadcasting import _mul_broadcast_shape
|
| 11 | +from ..utils.warnings import OldVersionWarning |
6 | 12 | from .mean import Mean
|
7 | 13 |
|
8 | 14 |
|
| 15 | +def _ensure_updated_strategy_flag_set( |
| 16 | + state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs |
| 17 | +): |
| 18 | + if prefix + "constant" in state_dict: |
| 19 | + constant = state_dict.pop(prefix + "constant") |
| 20 | + state_dict[prefix + "raw_constant"] = constant |
| 21 | + warnings.warn( |
| 22 | + "You have loaded a GP model with a ConstantMean from a previous version of " |
| 23 | + "GPyTorch. The mean module parameter `constant` has been renamed to `raw_constant`. " |
| 24 | + "We have updated the name of the parameter in your state dict, but we recommend that you " |
| 25 | + "re-save your model.", |
| 26 | + OldVersionWarning, |
| 27 | + ) |
| 28 | + |
| 29 | + |
9 | 30 | class ConstantMean(Mean):
|
10 |
| - def __init__(self, prior=None, batch_shape=torch.Size(), **kwargs): |
| 31 | + r""" |
| 32 | + A (non-zero) constant prior mean function, i.e.: |
| 33 | +
|
| 34 | + .. math:: |
| 35 | + \mu(\mathbf x) = C |
| 36 | +
|
| 37 | + where :math:`C` is a learned constant. |
| 38 | +
|
| 39 | + :param constant_prior: Prior for constant parameter :math:`C`. |
| 40 | + :type constant_prior: ~gpytorch.priors.Prior, optional |
| 41 | + :param constant_constraint: Constraint for constant parameter :math:`C`. |
| 42 | + :type constant_constraint: ~gpytorch.priors.Interval, optional |
| 43 | + :param batch_shape: The batch shape of the learned constant(s) (default: []). |
| 44 | + :type batch_shape: torch.Size, optional |
| 45 | +
|
| 46 | + :var torch.Tensor constant: :math:`C` parameter |
| 47 | + """ |
| 48 | + |
| 49 | + def __init__( |
| 50 | + self, |
| 51 | + constant_prior: Optional[Prior] = None, |
| 52 | + constant_constraint: Optional[Interval] = None, |
| 53 | + batch_shape: torch.Size = torch.Size(), |
| 54 | + **kwargs: Any, |
| 55 | + ): |
11 | 56 | super(ConstantMean, self).__init__()
|
| 57 | + |
| 58 | + # Deprecated kwarg |
| 59 | + constant_prior_deprecated = kwargs.get("prior") |
| 60 | + if constant_prior_deprecated is not None: |
| 61 | + if constant_prior is None: # Using the old kwarg for the constant_prior |
| 62 | + warnings.warn( |
| 63 | + "The kwarg `prior` for ConstantMean has been renamed to `constant_prior`, and will be deprecated.", |
| 64 | + DeprecationWarning, |
| 65 | + ) |
| 66 | + constant_prior = constant_prior_deprecated |
| 67 | + else: # Weird edge case where someone set both `prior` and `constant_prior` |
| 68 | + warnings.warn( |
| 69 | + "You have set both the `constant_prior` and the deprecated `prior` arguments for ConstantMean. " |
| 70 | + "`prior` is deprecated, and will be ignored.", |
| 71 | + DeprecationWarning, |
| 72 | + ) |
| 73 | + |
| 74 | + # Ensure that old versions of the model still load |
| 75 | + self._register_load_state_dict_pre_hook(_ensure_updated_strategy_flag_set) |
| 76 | + |
12 | 77 | self.batch_shape = batch_shape
|
13 |
| - self.register_parameter(name="constant", parameter=torch.nn.Parameter(torch.zeros(*batch_shape, 1))) |
14 |
| - if prior is not None: |
15 |
| - self.register_prior("mean_prior", prior, self._constant_param, self._constant_closure) |
| 78 | + self.register_parameter(name="raw_constant", parameter=torch.nn.Parameter(torch.zeros(*batch_shape, 1))) |
| 79 | + if constant_prior is not None: |
| 80 | + self.register_prior("mean_prior", constant_prior, self._constant_param, self._constant_closure) |
| 81 | + if constant_constraint is not None: |
| 82 | + self.register_constraint("raw_constant", constant_constraint) |
| 83 | + |
| 84 | + @property |
| 85 | + def constant(self): |
| 86 | + return self._constant_param(self) |
16 | 87 |
|
| 88 | + @constant.setter |
| 89 | + def constant(self, value): |
| 90 | + self._constant_closure(self, value) |
| 91 | + |
| 92 | + # We need a getter of this form so that we can pickle ConstantMean modules with a mean prior, see PR #1992 |
17 | 93 | def _constant_param(self, m):
|
18 |
| - return m.constant |
| 94 | + if hasattr(m, "raw_constant_constraint"): |
| 95 | + return m.raw_constant_constraint.transform(m.raw_constant) |
| 96 | + return m.raw_constant |
19 | 97 |
|
| 98 | + # We need a setter of this form so that we can pickle ConstantMean modules with a mean prior, see PR #1992 |
20 | 99 | def _constant_closure(self, m, value):
|
21 | 100 | if not torch.is_tensor(value):
|
22 |
| - value = torch.as_tensor(value).to(self.constant) |
23 |
| - m.initialize(constant=value.reshape(self.constant.shape)) |
| 101 | + value = torch.as_tensor(value).to(m.raw_constant) |
| 102 | + |
| 103 | + # Reshape the value so that it has a singleton dimension on the end |
| 104 | + if value.numel() != self.raw_constant.numel(): |
| 105 | + raise RuntimeError( |
| 106 | + f"Value of shape {value.shape} is incompatibile with ConstantMean of batch shape {m.batch_shape}" |
| 107 | + ) |
| 108 | + value = value.reshape(self.constant.shape) |
| 109 | + |
| 110 | + if hasattr(m, "raw_constant_constraint"): |
| 111 | + m.initialize(raw_constant=m.raw_constant_constraint.inverse_transform(value)) |
| 112 | + else: |
| 113 | + m.initialize(raw_constant=value) |
24 | 114 |
|
25 | 115 | def forward(self, input):
|
26 | 116 | if input.shape[:-2] == self.batch_shape:
|
27 | 117 | return self.constant.expand(input.shape[:-1])
|
28 | 118 | else:
|
29 |
| - return self.constant.expand(_mul_broadcast_shape(input.shape[:-1], self.constant.shape)) |
| 119 | + return self.constant.expand(_mul_broadcast_shape(input.shape[:-1], self.raw_constant.shape)) |
0 commit comments