-
Notifications
You must be signed in to change notification settings - Fork 563
Add constant_constraint to ConstantMean #2082
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 1 commit
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change | ||||
---|---|---|---|---|---|---|
@@ -1,29 +1,111 @@ | ||||||
#!/usr/bin/env python3 | ||||||
|
||||||
import warnings | ||||||
from typing import Any, Optional | ||||||
|
||||||
import torch | ||||||
|
||||||
from ..utils.broadcasting import _mul_broadcast_shape | ||||||
from ..constraints import Interval | ||||||
from ..priors import Prior | ||||||
from ..utils.warnings import OldVersionWarning | ||||||
from .mean import Mean | ||||||
|
||||||
|
||||||
def _ensure_updated_strategy_flag_set( | ||||||
state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs | ||||||
): | ||||||
if prefix + "constant" in state_dict: | ||||||
constant = state_dict.pop(prefix + "constant").squeeze(-1) # Remove deprecated singleton dimension | ||||||
state_dict[prefix + "raw_constant"] = constant | ||||||
warnings.warn( | ||||||
"You have loaded a GP model with a ConstantMean from a previous version of " | ||||||
"GPyTorch. The mean module parameter `constant` has been renamed to `raw_constant`. " | ||||||
"Additionally, the shape of `raw_constant` is now *batch_shape, whereas the shape of " | ||||||
"`constant` was *batch_shape x 1. " | ||||||
"We have updated the name/shape of the parameter in your state dict, but we recommend that you " | ||||||
"re-save your model.", | ||||||
OldVersionWarning, | ||||||
) | ||||||
|
||||||
|
||||||
class ConstantMean(Mean): | ||||||
def __init__(self, prior=None, batch_shape=torch.Size(), **kwargs): | ||||||
r""" | ||||||
A (non-zero) constant prior mean function, i.e.: | ||||||
|
||||||
.. math:: | ||||||
\mu(\mathbf x) = C | ||||||
|
||||||
where :math:`C` is a learned constant. | ||||||
|
||||||
:param constant_prior: Prior for constant parameter :math:`C`. | ||||||
:type constant_prior: ~gpytorch.priors.Prior, optional | ||||||
:param constant_constraint: Constraint for constant parameter :math:`C`. | ||||||
:type constant_constraint: ~gpytorch.priors.Interval, optional | ||||||
:param batch_shape: The batch shape of the learned constant(s) (default: []). | ||||||
:type batch_shape: torch.Size, optional | ||||||
|
||||||
:var torch.Tensor constant: :math:`C` parameter | ||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
|
||||||
""" | ||||||
|
||||||
def __init__( | ||||||
self, | ||||||
constant_prior: Optional[Prior] = None, | ||||||
constant_constraint: Optional[Interval] = None, | ||||||
batch_shape: torch.Size = torch.Size(), | ||||||
**kwargs: Any, | ||||||
): | ||||||
super(ConstantMean, self).__init__() | ||||||
|
||||||
# Deprecated kwarg | ||||||
constant_prior_deprecated = kwargs.get("prior") | ||||||
if constant_prior_deprecated is not None: | ||||||
if constant_prior is None: # Using the old kwarg for the constant_prior | ||||||
warnings.warn( | ||||||
"The kwarg `prior` for ConstantMean has been renamed to `constant_prior`, and will be deprecated.", | ||||||
DeprecationWarning, | ||||||
) | ||||||
constant_prior = constant_prior_deprecated | ||||||
else: # Weird edge case where someone set both `prior` and `constant_prior` | ||||||
warnings.warn( | ||||||
"You have set both the `constant_prior` and the deprecated `prior` arguments for ConstantMean. " | ||||||
"`prior` is deprecated, and will be ignored.", | ||||||
DeprecationWarning, | ||||||
) | ||||||
Comment on lines
+68
to
+73
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I think this is weird enough that we may just want to throw an error here? |
||||||
|
||||||
# Ensure that old versions of the model still load | ||||||
self._register_load_state_dict_pre_hook(_ensure_updated_strategy_flag_set) | ||||||
|
||||||
self.batch_shape = batch_shape | ||||||
self.register_parameter(name="constant", parameter=torch.nn.Parameter(torch.zeros(*batch_shape, 1))) | ||||||
if prior is not None: | ||||||
self.register_prior("mean_prior", prior, self._constant_param, self._constant_closure) | ||||||
self.register_parameter(name="raw_constant", parameter=torch.nn.Parameter(torch.zeros(batch_shape))) | ||||||
if constant_prior is not None: | ||||||
self.register_prior("mean_prior", constant_prior, self._constant_param, self._constant_closure) | ||||||
if constant_constraint is not None: | ||||||
self.register_constraint("raw_constant", constant_constraint) | ||||||
|
||||||
@property | ||||||
def constant(self): | ||||||
return self._constant_param(self) | ||||||
|
||||||
@constant.setter | ||||||
def constant(self, value): | ||||||
self._constant_closure(self, value) | ||||||
|
||||||
# We need a getter of this form so that we can pickle ConstantMean modules with a mean prior, see PR #1992 | ||||||
def _constant_param(self, m): | ||||||
return m.constant | ||||||
if hasattr(m, "raw_constant_constraint"): | ||||||
return m.raw_constant_constraint.transform(m.raw_constant) | ||||||
return m.raw_constant | ||||||
|
||||||
# We need a setter of this form so that we can pickle ConstantMean modules with a mean prior, see PR #1992 | ||||||
def _constant_closure(self, m, value): | ||||||
if not torch.is_tensor(value): | ||||||
value = torch.as_tensor(value).to(self.constant) | ||||||
m.initialize(constant=value.reshape(self.constant.shape)) | ||||||
value = torch.as_tensor(value).to(m.raw_constant) | ||||||
|
||||||
def forward(self, input): | ||||||
if input.shape[:-2] == self.batch_shape: | ||||||
return self.constant.expand(input.shape[:-1]) | ||||||
if hasattr(m, "raw_constant_constraint"): | ||||||
m.initialize(raw_constant=m.raw_constant_constraint.inverse_transform(value)) | ||||||
else: | ||||||
return self.constant.expand(_mul_broadcast_shape(input.shape[:-1], self.constant.shape)) | ||||||
m.initialize(raw_constant=value) | ||||||
|
||||||
def forward(self, input): | ||||||
constant = self.constant.unsqueeze(-1) # *batch_shape x 1 | ||||||
return constant.expand(torch.broadcast_shapes(constant.shape, input.shape[:-1])) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
consistency nit