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 2 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 `is_restarting` attribute to base `Loop` ([#8247](https://github.com/PyTorchLightning/pytorch-lightning/pull/8247))


### Changed


Expand Down
25 changes: 24 additions & 1 deletion pytorch_lightning/loops/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,12 @@ class Loop(ABC):

.. codeblock:: python

if is_restarting:
restore()
is_restarting = False
else:
reset()

tchaton marked this conversation as resolved.
Show resolved Hide resolved
on_run_start()

while not done:
Expand All @@ -46,6 +52,15 @@ class Loop(ABC):
def __init__(self) -> None:
self.iteration_count: int = 0
self.trainer: Optional['pl.Trainer'] = None
self._is_restarting = False

@property
def is_restarting(self) -> bool:
tchaton marked this conversation as resolved.
Show resolved Hide resolved
return self._is_restarting

@is_restarting.setter
def is_restarting(self, is_restarting: bool) -> None:
self._is_restarting = is_restarting

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

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

self.on_run_start(*args, **kwargs)

while not self.done:
Expand All @@ -103,6 +123,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
76 changes: 76 additions & 0 deletions tests/loops/test_loops.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
# 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)
print(value, self.iteration_count)
tchaton marked this conversation as resolved.
Show resolved Hide resolved

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"]

state_dict = {}

data = range(10)
loop = Simple(data)
try:
loop.run()
tchaton marked this conversation as resolved.
Show resolved Hide resolved
except CustomExpection:
state_dict = loop.state_dict()

loop = Simple(data)
loop.load_state_dict(state_dict)
loop.is_restarting = True
tchaton marked this conversation as resolved.
Show resolved Hide resolved
loop.run()

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