-
Notifications
You must be signed in to change notification settings - Fork 3.4k
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
[PoC] Add KFold - External Loop. #8715
Closed
Closed
Changes from 11 commits
Commits
Show all changes
19 commits
Select commit
Hold shift + click to select a range
c7a1fe5
update
tchaton 210bd51
update
tchaton 91a9dff
update
tchaton 2fb8496
update
tchaton 6ac569f
Merge branch 'master' into poc_loop_customization
tchaton 626525e
simplify code
tchaton 480744e
break if new trainer is attached
tchaton 7cca34d
update
tchaton 40089ae
changelog
tchaton d6d30fd
add warning
tchaton dd56081
update
tchaton d209d53
resolve bug
tchaton 615ab30
update
tchaton de5da36
update tests
tchaton d86e7af
add some typing
tchaton 4b42c07
update
tchaton 8a03ea1
Merge branch 'master' into poc_loop_customization
tchaton f853b60
update on comments
tchaton 8d667f1
update
tchaton 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 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 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,162 @@ | ||
# Copyright The PyTorch Lightning team. | ||
# | ||
# Licensed under the Apache License, Version 2.0 (the "License"); | ||
# you may not use this file except in compliance with the License. | ||
# You may obtain a copy of the License at | ||
# | ||
# http://www.apache.org/licenses/LICENSE-2.0 | ||
# | ||
# Unless required by applicable law or agreed to in writing, software | ||
# distributed under the License is distributed on an "AS IS" BASIS, | ||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
# See the License for the specific language governing permissions and | ||
# limitations under the License. | ||
|
||
""" | ||
WARNING: Loop customization is in `pre-alpha release` and the API is likely to change quite a lot ! | ||
Please, open issues with your own particular requests, so the Lightning Team can progressively converge to a great API. | ||
""" | ||
|
||
from dataclasses import dataclass, field | ||
from typing import Any, Dict, List, Type | ||
|
||
import numpy as np | ||
from sklearn.model_selection import KFold | ||
from torch.utils.data import Dataset | ||
|
||
from pytorch_lightning import _logger as log | ||
from pytorch_lightning import seed_everything, Trainer | ||
from pytorch_lightning.callbacks.base import Callback | ||
from pytorch_lightning.loops.base import ExternalLoop | ||
from pytorch_lightning.utilities import rank_zero_only | ||
from pytorch_lightning.utilities.boring_model import BoringDataModule, BoringModel | ||
from pytorch_lightning.utilities.exceptions import MisconfigurationException | ||
|
||
seed_everything(42) | ||
|
||
|
||
class SplitDataset(Dataset): | ||
tchaton marked this conversation as resolved.
Show resolved
Hide resolved
|
||
"""SplitDataset is used to create Dataset Subset using indices. | ||
Args: | ||
dataset: A dataset to be splitted | ||
indices: List of indices to expose from the dataset | ||
use_duplicated_indices: Whether to allow duplicated indices. | ||
Example:: | ||
split_ds = SplitDataset(dataset, indices=[10, 14, 25]) | ||
split_ds = SplitDataset(dataset, indices=[10, 10, 10, 14, 25], use_duplicated_indices=True) | ||
""" | ||
|
||
_INTERNAL_KEYS = ("dataset", "indices", "data") | ||
|
||
def __init__(self, dataset: Any, indices: List[int] = None, use_duplicated_indices: bool = False) -> None: | ||
if indices is None: | ||
indices = [] | ||
if not isinstance(indices, list): | ||
raise MisconfigurationException("indices should be a list") | ||
|
||
if use_duplicated_indices: | ||
indices = list(indices) | ||
else: | ||
indices = list(np.unique(indices)) | ||
|
||
if np.max(indices) >= len(dataset) or np.min(indices) < 0: | ||
raise MisconfigurationException(f"`indices` should be within [0, {len(dataset) -1}].") | ||
|
||
self.dataset = dataset | ||
tchaton marked this conversation as resolved.
Show resolved
Hide resolved
|
||
self.indices = indices | ||
|
||
def __getattr__(self, key: str): | ||
if key not in self._INTERNAL_KEYS: | ||
return self.dataset.__getattribute__(key) | ||
tchaton marked this conversation as resolved.
Show resolved
Hide resolved
|
||
raise AttributeError | ||
|
||
def __setattr__(self, name: str, value: Any) -> None: | ||
if name in self._INTERNAL_KEYS: | ||
self.__dict__[name] = value | ||
else: | ||
setattr(self.dataset, name, value) | ||
|
||
def __getitem__(self, index: int) -> Any: | ||
return self.dataset[self.indices[index]] | ||
|
||
def __len__(self) -> int: | ||
return len(self.indices) - 1 | ||
tchaton marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
|
||
@dataclass | ||
class KFoldLoop(ExternalLoop): | ||
|
||
num_folds: int | ||
num_epochs: int = 10 | ||
best_model_paths: List[str] = field(default_factory=lambda: []) | ||
restarting: bool = False | ||
|
||
@staticmethod | ||
def loop_base_callback() -> Type[Callback]: | ||
class BaseKFoldCallback(Callback): | ||
@rank_zero_only | ||
def on_fold_start(self, trainer, pl_module, counter): | ||
"""Override with your own logic""" | ||
|
||
return BaseKFoldCallback | ||
Comment on lines
+148
to
+154
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. can't we define this outside this class but in the file namespace? |
||
|
||
@property | ||
def done(self) -> bool: | ||
return self.current_fold >= self.num_folds | ||
|
||
def reset(self) -> None: | ||
if not self.restarting: | ||
self.current_fold = 0 | ||
self.set_max_epochs(self.num_epochs) | ||
|
||
def generate_fold(self, dataloader_kwargs: Dict[str, Any], stage: str): | ||
dataset = dataloader_kwargs["dataset"] | ||
kfold = KFold(self.num_folds, random_state=42, shuffle=True) | ||
train_indices, validation_indices = list(kfold.split(range(len(dataset))))[self.current_fold] | ||
if stage == "train": | ||
dataloader_kwargs["dataset"] = SplitDataset(dataset, train_indices.tolist()) | ||
else: | ||
dataloader_kwargs["dataset"] = SplitDataset(dataset, validation_indices.tolist()) | ||
dataloader_kwargs["sampler"].data_source = dataloader_kwargs["dataset"] | ||
return dataloader_kwargs | ||
|
||
def on_run_start(self, *args: Any, **kwargs: Any) -> None: | ||
# temporary hack | ||
self.trainer.datamodule.setup("fit") | ||
|
||
def on_advance_start(self): | ||
self.reload_train_dataloader(self.generate_fold) | ||
self.reload_val_dataloaders(self.generate_fold) | ||
self.trainer.call_hook("on_fold_start", self.current_fold) | ||
self.lightning_module.reset_parameters() | ||
|
||
def advance(self): | ||
return self.trainer.fit(self.lightning_module, train_dataloader=self.train_dataloader) | ||
|
||
def on_advance_end(self) -> None: | ||
self.current_fold += 1 | ||
self.increment_max_epochs(self.num_epochs) | ||
# stored best weight path for this fold | ||
self.best_model_paths.append(self.trainer.checkpoint_callback.best_model_path) | ||
|
||
def on_save_checkpoint(self) -> Dict: | ||
return {"current_fold": self.current_fold} | ||
|
||
def on_load_checkpoint(self, state_dict) -> None: | ||
self.current_fold = state_dict["current_fold"] | ||
|
||
|
||
class KFoldCallback(KFoldLoop.loop_base_callback()): | ||
|
||
"""This callback demonstrates how to implement your own callback API.""" | ||
|
||
@rank_zero_only | ||
def on_fold_start(self, trainer, pl_module, counter): | ||
log.info(f"Starting to train on fold {counter}") | ||
|
||
|
||
loop = KFoldLoop(5) | ||
model = BoringModel() | ||
datamodule = BoringDataModule() | ||
trainer = Trainer(callbacks=KFoldCallback()) | ||
trainer.run_loop(model, datamodule=datamodule, loop=loop) | ||
tchaton marked this conversation as resolved.
Show resolved
Hide resolved
|
This file contains 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 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 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.
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.
rather not seed anything globally