-
Notifications
You must be signed in to change notification settings - Fork 77
Botorch preset #757
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
Botorch preset #757
Changes from all commits
Commits
Show all changes
22 commits
Select commit
Hold shift + click to select a range
316251d
Enable multitask mode for surrogate streamlit
AdrianSosic 805d680
Add BOTORCH preset
AdrianSosic 45d4a62
Extend BoTorch preset test to multitask case
AdrianSosic 6dfa935
Add custom GPyTorch components to replicate BoTorch logic
AdrianSosic 781515b
Extend BoTorch factories to multitask case
AdrianSosic fca6ac8
Add kernel active dimension validation to ICMKernelFactory
AdrianSosic 15b10be
Fix KernelFactory return types
AdrianSosic 46b96a4
Make BotorchKernelFactory support parameter selection
AdrianSosic 994e1a8
Fix active dimensions validation
AdrianSosic 5b312d9
Bypass kernel warning for presets
AdrianSosic 95f2305
Update CHANGELOG.md
AdrianSosic 472d597
Rename on-task/off-task to target/source in streamlit
AdrianSosic 5be27f3
Fix missing fit_criterion_factory renamings
AdrianSosic 3050a6f
Fix dimension handling in BotorchKernelFactory
AdrianSosic 9c54d20
Add temporary ignore to pytest.ini
AdrianSosic 873b8f6
Fix deprecated .evaluate() call in test_kernels.py
AdrianSosic fbe2440
Fix lazy imports
AdrianSosic fbe87ec
Fix dimension validation in ICMKernelFactory
AdrianSosic 0609e92
Fix kernel factory return types
AdrianSosic f6f42a7
Drop duplicated kernel creation
AdrianSosic 7996e1e
Fix vlines argument in streamlit script
AdrianSosic 2deed6c
Hardwire MLL as criterion for BoTorch preset
AdrianSosic 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
Some comments aren't visible on the classic Files Changed page.
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
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 |
|---|---|---|
| @@ -0,0 +1,71 @@ | ||
| """Custom GPyTorch components.""" | ||
|
|
||
| import torch | ||
| from botorch.models.multitask import _compute_multitask_mean | ||
| from botorch.models.utils.gpytorch_modules import MIN_INFERRED_NOISE_LEVEL | ||
| from gpytorch.constraints import GreaterThan | ||
| from gpytorch.likelihoods.hadamard_gaussian_likelihood import HadamardGaussianLikelihood | ||
| from gpytorch.means import MultitaskMean | ||
| from gpytorch.means.multitask_mean import Mean | ||
| from gpytorch.priors import LogNormalPrior | ||
| from torch import Tensor | ||
|
AdrianSosic marked this conversation as resolved.
|
||
| from torch.nn import Module | ||
|
|
||
|
|
||
| class HadamardConstantMean(Mean): | ||
| """A GPyTorch mean function implementing BoTorch's multitask mean logic. | ||
|
|
||
| While GPyTorch already provides a :class:`~gpytorch.means.MultitaskMean` class, it | ||
| computes mean values for all (input, task)-pairs (where input means all parameters | ||
| except the task parameter), i.e. it intrinsically applies a Cartesian expansion. | ||
| However, for the regular transfer learning setting, we only need the means for the | ||
| pairs that are actually observed/requested. BoTorch subselects the relevant means | ||
| from the GPyTorch output in `MultiTaskGP.forward`, i.e. it uses a class-based | ||
| approach to define its special logic for the multitask case. In contrast, BayBE uses | ||
| a composition approach, which is more flexible but requires that the logic is | ||
| injected via a self-contained `Mean` object, which is what this class provides. | ||
|
|
||
| Note: | ||
| Analogous to GPyTorch's | ||
| https://github.com/cornellius-gp/gpytorch/blob/main/gpytorch/likelihoods/hadamard_gaussian_likelihood.py | ||
| but where the logic is applied to the mean function, i.e. we learn a different | ||
| (constant) mean for each task. | ||
| """ | ||
|
|
||
| def __init__(self, mean_module: Module, num_tasks: int, task_feature: int): | ||
| super().__init__() | ||
| self.multitask_mean = MultitaskMean(mean_module, num_tasks=num_tasks) | ||
| self.task_feature = task_feature | ||
|
|
||
| def forward(self, x: Tensor) -> Tensor: | ||
| # Adapted from https://github.com/meta-pytorch/botorch/blob/e0f4f5b941b5949a4a1171bf8d4ee9f74f146f3a/botorch/models/multitask.py#L397 | ||
|
|
||
| # Convert task feature to positive index | ||
| task_feature = self.task_feature % x.shape[-1] | ||
|
|
||
| # Split input into task and non-task components | ||
| x_before = x[..., :task_feature] | ||
| task_idcs = x[..., task_feature : task_feature + 1] | ||
| x_after = x[..., task_feature + 1 :] | ||
|
|
||
| return _compute_multitask_mean( | ||
| self.multitask_mean, x_before, task_idcs, x_after | ||
| ) | ||
|
|
||
|
|
||
| def make_botorch_multitask_likelihood( | ||
| num_tasks: int, task_feature: int | ||
| ) -> HadamardGaussianLikelihood: | ||
| """Adapted from :class:`botorch.models.multitask.MultiTaskGP`.""" | ||
| noise_prior = LogNormalPrior(loc=-4.0, scale=1.0) | ||
| return HadamardGaussianLikelihood( | ||
| num_tasks=num_tasks, | ||
| batch_shape=torch.Size(), | ||
| noise_prior=noise_prior, | ||
| noise_constraint=GreaterThan( | ||
| MIN_INFERRED_NOISE_LEVEL, | ||
| transform=None, | ||
| initial_value=noise_prior.mode, | ||
| ), | ||
| task_feature_index=task_feature, | ||
| ) | ||
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
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
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
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 |
|---|---|---|
| @@ -0,0 +1,140 @@ | ||
| """BoTorch preset for Gaussian process surrogates.""" | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import gc | ||
| from itertools import chain | ||
| from typing import TYPE_CHECKING, ClassVar | ||
|
|
||
| from attrs import define | ||
| from typing_extensions import override | ||
|
|
||
| from baybe.kernels.base import Kernel | ||
| from baybe.parameters.enum import _ParameterKind | ||
| from baybe.searchspace.core import SearchSpace | ||
| from baybe.surrogates.gaussian_process.components import LikelihoodFactoryProtocol | ||
| from baybe.surrogates.gaussian_process.components.fit_criterion import ( | ||
| FitCriterion, | ||
| PlainFitCriterionFactory, | ||
| ) | ||
| from baybe.surrogates.gaussian_process.components.kernel import ( | ||
| ICMKernelFactory, | ||
| _PureKernelFactory, | ||
| ) | ||
| from baybe.surrogates.gaussian_process.components.mean import MeanFactoryProtocol | ||
|
|
||
| if TYPE_CHECKING: | ||
| from gpytorch.kernels import Kernel as GPyTorchKernel | ||
| from gpytorch.likelihoods import Likelihood as GPyTorchLikelihood | ||
| from gpytorch.means import Mean as GPyTorchMean | ||
| from torch import Tensor | ||
|
|
||
|
|
||
| @define | ||
| class BotorchKernelFactory(_PureKernelFactory): | ||
| """A factory providing BoTorch kernels.""" | ||
|
|
||
| _uses_parameter_names: ClassVar[bool] = True | ||
| # See base class. | ||
|
AVHopp marked this conversation as resolved.
|
||
|
|
||
| _supported_parameter_kinds: ClassVar[_ParameterKind] = ( | ||
| _ParameterKind.REGULAR | _ParameterKind.TASK | ||
| ) | ||
| # See base class. | ||
|
|
||
| @override | ||
| def _make( | ||
| self, searchspace: SearchSpace, train_x: Tensor, train_y: Tensor | ||
| ) -> Kernel | GPyTorchKernel: | ||
| from botorch.models.kernels.positive_index import PositiveIndexKernel | ||
| from botorch.models.utils.gpytorch_modules import ( | ||
| get_covar_module_with_dim_scaled_prior, | ||
| ) | ||
|
|
||
| parameter_names = self.get_parameter_names(searchspace) | ||
|
|
||
| # For regular parameters, resolve parameter names to active dimension indices | ||
| active_dims = list( | ||
| chain.from_iterable( | ||
| searchspace.get_comp_rep_parameter_indices(name) | ||
| for name in parameter_names | ||
| if searchspace.get_parameters_by_name([name])[0]._kind | ||
| is _ParameterKind.REGULAR | ||
|
AdrianSosic marked this conversation as resolved.
|
||
| ) | ||
| ) | ||
| ard_num_dims = len(active_dims) | ||
|
|
||
| # Create the base kernel for the regular parameters | ||
| base_kernel = get_covar_module_with_dim_scaled_prior( | ||
| ard_num_dims=ard_num_dims, active_dims=active_dims | ||
| ) | ||
|
|
||
| # Single-task case | ||
| if (task_idx := searchspace.task_idx) is None: | ||
| return base_kernel | ||
|
|
||
| index_kernel = PositiveIndexKernel( | ||
| num_tasks=searchspace.n_tasks, | ||
| rank=searchspace.n_tasks, | ||
| active_dims=[task_idx], | ||
| ) | ||
| return ICMKernelFactory(base_kernel, index_kernel)( | ||
| searchspace, train_x, train_y | ||
| ) | ||
|
|
||
|
|
||
| class BotorchMeanFactory(MeanFactoryProtocol): | ||
| """A factory providing BoTorch mean functions.""" | ||
|
|
||
| @override | ||
| def __call__( | ||
| self, searchspace: SearchSpace, train_x: Tensor, train_y: Tensor | ||
| ) -> GPyTorchMean: | ||
| from gpytorch.means import ConstantMean | ||
|
|
||
| from baybe.surrogates.gaussian_process.components._gpytorch import ( | ||
| HadamardConstantMean, | ||
| ) | ||
|
|
||
| if searchspace.n_tasks == 1: | ||
| return ConstantMean() | ||
|
|
||
| assert searchspace.task_idx is not None | ||
| return HadamardConstantMean( | ||
| ConstantMean(), searchspace.n_tasks, searchspace.task_idx | ||
| ) | ||
|
|
||
|
|
||
| class BotorchLikelihoodFactory(LikelihoodFactoryProtocol): | ||
| """A factory providing BoTorch likelihoods.""" | ||
|
|
||
| @override | ||
| def __call__( | ||
| self, searchspace: SearchSpace, train_x: Tensor, train_y: Tensor | ||
| ) -> GPyTorchLikelihood: | ||
|
|
||
| if searchspace.n_tasks == 1: | ||
| from botorch.models.utils.gpytorch_modules import ( | ||
| get_gaussian_likelihood_with_lognormal_prior, | ||
| ) | ||
|
|
||
| return get_gaussian_likelihood_with_lognormal_prior() | ||
|
|
||
| from baybe.surrogates.gaussian_process.components._gpytorch import ( | ||
| make_botorch_multitask_likelihood, | ||
| ) | ||
|
|
||
| assert searchspace.task_idx is not None | ||
| return make_botorch_multitask_likelihood( | ||
| num_tasks=searchspace.n_tasks, task_feature=searchspace.task_idx | ||
| ) | ||
|
|
||
|
|
||
| # Collect leftover original slotted classes processed by `attrs.define` | ||
| gc.collect() | ||
|
|
||
| # Aliases for generic preset imports | ||
| KERNEL_FACTORY = BotorchKernelFactory() | ||
| MEAN_FACTORY = BotorchMeanFactory() | ||
| LIKELIHOOD_FACTORY = BotorchLikelihoodFactory() | ||
| FIT_CRITERION_FACTORY = PlainFitCriterionFactory(FitCriterion.MARGINAL_LOG_LIKELIHOOD) | ||
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
Oops, something went wrong.
Oops, something went wrong.
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.
Uh oh!
There was an error while loading. Please reload this page.