-
Notifications
You must be signed in to change notification settings - Fork 36
[WIP] Test time deep method #305
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
base: main
Are you sure you want to change the base?
Changes from 8 commits
6b8ee39
cd13eed
d0ee0a3
32aec72
c23e8f2
a3c0ced
28ce3f3
e81a62e
4c76ba4
aab0c09
44b2df9
616cc29
26840fd
b4c1841
8bacda4
1f52a1b
bc37c6e
5a71c1d
6d34ed8
0c0dfae
1e501b8
7b17529
62d86db
d29d299
65c60d3
d103ef8
96717f7
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,155 @@ | ||
| # Author : Maxence Barneche | ||
| # | ||
| # License: BSD-3-Clause | ||
|
|
||
| import torch | ||
|
|
||
| from skada.deep.base import BaseDALoss, DomainAwareModule, DomainAwareNet | ||
|
|
||
|
|
||
| class TestTimeCriterion(torch.nn.Module): | ||
| def __init__( | ||
| self, | ||
| base_criterion, | ||
| adapt_criterion, | ||
| reg=1, | ||
| reduction="mean", | ||
| train_on_target=False, | ||
| ): | ||
| super().__init__() | ||
| self.base_criterion = base_criterion | ||
| self.adapt_criterion = adapt_criterion | ||
| self.reg = reg | ||
| self.train_on_target = train_on_target | ||
|
|
||
| # Update the reduce parameter for both criteria if specified | ||
| if hasattr(self.base_criterion, "reduction"): | ||
| self.base_criterion.reduction = reduction | ||
|
|
||
| # TODO: implement losses between source and target | ||
| # that are sum of the losses of each sample | ||
| # if hasattr(self.adapt_criterion, 'reduction'): | ||
| # self.adapt_criterion.reduction = reduction | ||
|
|
||
| def forward( | ||
| self, | ||
| y_pred, | ||
| y_true, | ||
| ): | ||
| """ | ||
| Parameters | ||
| ---------- | ||
| y_pred : | ||
| Prediction of the labels. | ||
| y_true : | ||
| The true labels. Available for source, masked for target. | ||
| """ | ||
| if self.train_on_target: | ||
| # In finetune mode, we only compute the base loss | ||
| return self.adapt_criterion( | ||
| y_s=y_true, | ||
| y_pred=y_pred, | ||
| ) | ||
| else: | ||
| # In adapt mode, we compute the adaptation loss | ||
| return self.base_criterion(y_pred, y_true) | ||
|
|
||
|
|
||
| class TestTimeNet(DomainAwareNet): | ||
| def __init__( | ||
| self, | ||
| module, | ||
| criterion: "TestTimeCriterion", | ||
| optimizer_adapt=None, | ||
| epochs_adapt=None, | ||
| **kwargs, | ||
| ): | ||
| super().__init__(module, criterion=criterion, **kwargs) | ||
| self.optimizer_adapt = optimizer_adapt | ||
| self.epochs_adapt = epochs_adapt | ||
|
|
||
| def fit_source( | ||
| self, X, y=None, sample_domain=None, sample_weight=None, **fit_params | ||
| ): | ||
| print("Training model on source domain...") | ||
| X = self._prepare_input(X, y, sample_domain, sample_weight) | ||
| X = X.select_source() | ||
| self.criterion.train_on_target = False | ||
| self.partial_fit(X, None, **fit_params) | ||
| return self | ||
|
|
||
| def fit_adapt(self, X, sample_domain, sample_weight=None, **fit_params): | ||
| print("Adapting model to target domain...") | ||
| if self.optimizer_adapt is not None: | ||
| self.initialize_adapt_optimizer() | ||
| X = self._prepare_input(X, None, sample_domain, sample_weight) | ||
| X = X.select_target() | ||
| self.criterion.train_on_target = True | ||
| self.partial_fit(X, None, epochs=self.epochs_adapt, **fit_params) | ||
| return self | ||
|
|
||
| def fit(self, X, y=None, sample_domain=None, sample_weight=None, **fit_params): | ||
| self.fit_source(X, y, sample_domain, sample_weight, **fit_params) | ||
| self.fit_adapt(X, sample_domain, sample_weight, **fit_params) | ||
| return self | ||
|
|
||
| def initialize_adapt_optimizer(self): | ||
| named_parameters = self.get_all_learnable_params() | ||
| args, kwargs = self.get_params_for_optimizer( | ||
| "adapt_optimizer", named_parameters | ||
| ) | ||
| self.optimizer_ = self.optimizer_adapt(*args, **kwargs) | ||
| return self | ||
|
|
||
|
|
||
| class TentNet(TestTimeNet): | ||
| def __init__(self, module, criterion, **kwargs): | ||
| super().__init__(module, criterion=criterion, **kwargs) | ||
|
|
||
| def forward(self, X, sample_domain=None, sample_weight=None): | ||
| """Forward pass of the model.""" | ||
| X = self._prepare_input(X, None, sample_domain, sample_weight) | ||
| # Note: we are supposed to freeze some attributes of the model | ||
|
Collaborator
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 we should be able to choose what to freeze in the TestTimeNet. We don't need a TentNet I think |
||
| # during the adaptation phase, but we do not do it here. | ||
| return self.module(X) | ||
|
|
||
|
|
||
| class TentLoss(BaseDALoss): | ||
|
Collaborator
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. don't forget the docstring |
||
| def __init__( | ||
| self, reg_dist=1, reg_cl=1, base_criterion=None, target_criterion=None | ||
| ): | ||
| super().__init__() | ||
| self.reg_dist = reg_dist | ||
| self.reg_cl = reg_cl | ||
| self.base_criterion = base_criterion | ||
| self.target_criterion = target_criterion | ||
|
|
||
| def forward(self, y_s, y_t): | ||
|
Collaborator
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. what is y_s and y_t ? You should have only y_t no ? |
||
| loss = self.target_criterion(y_t, y_s) | ||
| return loss + self.reg_dist * torch.mean(y_t) + self.reg_cl * torch.mean(y_s) | ||
|
|
||
|
|
||
| def Tent( | ||
| module, | ||
| layer_name, | ||
| reg_dist=1, | ||
| reg_cl=1, | ||
| base_criterion=None, | ||
| target_criterion=None, | ||
| **kwargs, | ||
| ): | ||
| if base_criterion is None: | ||
| base_criterion = torch.nn.CrossEntropyLoss() | ||
|
|
||
| net = TentNet( | ||
| module=DomainAwareModule, | ||
| module__base_module=module, | ||
| module__layer_name=layer_name, | ||
| criterion=TestTimeCriterion, | ||
| criterion__base_criterion=base_criterion, | ||
| criterion__adapt_criterion=TentLoss(reg_dist, reg_cl, target_criterion), | ||
| criterion__reg=1, | ||
| **kwargs, | ||
| ) | ||
|
|
||
| return net | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,60 @@ | ||
| # Author : Maxence Barneche | ||
| # | ||
| # License: BSD-3-Clause | ||
|
|
||
| import pytest | ||
|
|
||
| torch = pytest.importorskip("torch") | ||
|
|
||
| import numpy as np | ||
| from torch.optim import Adam | ||
| from torch.utils.data import DataLoader | ||
|
|
||
| from skada.datasets import make_shifted_datasets | ||
| from skada.deep._test_time import TestTimeCriterion, TestTimeNet | ||
| from skada.deep.base import DomainAwareModule | ||
| from skada.deep.losses import TestLoss | ||
| from skada.deep.modules import ToyModule2D | ||
|
|
||
|
|
||
| @pytest.mark.parametrize( | ||
| "epochs_adapt, optimizer_adapt", | ||
| [ | ||
| (None, None), # Default test | ||
| (3, None), # Test with specific adaptation epochs given | ||
| (None, Adam), | ||
| ], # Test with Adam optimizer for adaptation | ||
| ) | ||
| def test_test_time_criterion(epochs_adapt, optimizer_adapt): | ||
| num_features = 10 | ||
| module = ToyModule2D(num_features=num_features) | ||
| criterion = TestTimeCriterion(torch.nn.CrossEntropyLoss(), TestLoss()) | ||
|
|
||
| n_samples = 20 | ||
| dataset = make_shifted_datasets( | ||
| n_samples_source=n_samples, | ||
| n_samples_target=n_samples, | ||
| shift="conditional_shift", | ||
| noise=0.1, | ||
| random_state=42, | ||
| ) | ||
| X, y, sample_domain = dataset | ||
| X = X.astype(np.float32) | ||
|
|
||
| method = TestTimeNet( | ||
| DomainAwareModule(module, "dropout"), | ||
| epochs_adapt=epochs_adapt, | ||
| iterator_train=DataLoader, | ||
| criterion=criterion, | ||
| batch_size=10, | ||
| max_epochs=2, | ||
| train_split=None, | ||
| optimizer_adapt=optimizer_adapt, | ||
| ) | ||
|
|
||
| method.fit(X, y, sample_domain) | ||
|
|
||
| # If the adaptation optimizer is specified, the net's optimizer should have changed | ||
| # during the fit_adapt method called inside the fit method | ||
| if optimizer_adapt is not None: | ||
| assert isinstance(method.optimizer_, optimizer_adapt) |
Uh oh!
There was an error while loading. Please reload this page.