Skip to content
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

[feat] Add restore to base loop #8247

Merged
merged 3 commits into from
Jul 2, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,9 @@ The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/).
- Added `max_depth` parameter in `ModelSummary` ([#8062](https://github.com/PyTorchLightning/pytorch-lightning/pull/8062))


- Added `restore` function and `restarting` attribute to base `Loop` ([#8247](https://github.com/PyTorchLightning/pytorch-lightning/pull/8247))


### Changed


Expand Down
19 changes: 18 additions & 1 deletion pytorch_lightning/loops/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,15 @@ class Loop(ABC):
def __init__(self) -> None:
self.iteration_count: int = 0
self.trainer: Optional['pl.Trainer'] = None
self._restarting = False

@property
def restarting(self) -> bool:
return self._restarting

@restarting.setter
def restarting(self, restarting: bool) -> None:
self._restarting = restarting
Comment on lines +49 to +57
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is there a reason why you added a getter/setter considering they don't do anything custom?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not a strong need for them right now. Can be removed later on.


@property
@abstractmethod
Expand Down Expand Up @@ -87,7 +96,12 @@ def run(self, *args: Any, **kwargs: Any) -> Optional[Any]:
if self.skip:
return self.on_skip()

self.reset()
if self.restarting:
self.restore()
self.restarting = False
else:
self.reset()

self.on_run_start(*args, **kwargs)

while not self.done:
Expand All @@ -103,6 +117,9 @@ def run(self, *args: Any, **kwargs: Any) -> Optional[Any]:
self.teardown()
return output

def restore(self) -> None:
"""Restore the internal state of the loop the beginning of run if restarting is ``True``."""

@abstractmethod
def reset(self) -> None:
"""Resets the internal state of the loop at the beginning of each call to :attr:`run`."""
Expand Down
74 changes: 74 additions & 0 deletions tests/loops/test_loops.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
# 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.

from typing import Dict, Iterator

from pytorch_lightning.loops.base import Loop


def test_loop_restore():

class CustomExpection(Exception):
pass

class Simple(Loop):
tchaton marked this conversation as resolved.
Show resolved Hide resolved

def __init__(self, dataset: Iterator):
super().__init__()
self.dataset = dataset

def restore(self) -> None:
self.iter_dataset = iter(self.dataset)
for _ in range(self.iteration_count):
next(self.iter_dataset)
self.iteration_count += 1

@property
def done(self) -> bool:
return self.iteration_count > len(self.dataset)

def reset(self) -> None:
self.iter_dataset = iter(self.dataset)
self.outputs = []

def advance(self) -> None:
value = next(self.iter_dataset)

if self.iteration_count == 5:
raise CustomExpection

self.outputs.append(value)

def state_dict(self) -> Dict:
return {"iteration_count": self.iteration_count, "outputs": self.outputs}

def load_state_dict(self, state_dict: Dict) -> None:
self.iteration_count = state_dict["iteration_count"]
self.outputs = state_dict["outputs"]

data = range(10)
loop = Simple(data)
try:
loop.run()
state_dict = {}
except CustomExpection:
state_dict = loop.state_dict()

loop = Simple(data)
loop.load_state_dict(state_dict)
loop.restarting = True
loop.run()

assert not loop.restarting
assert loop.outputs == list(range(10))