-
Notifications
You must be signed in to change notification settings - Fork 3.5k
Introduce CheckpointIO Plugin #8743
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
Changes from 37 commits
Commits
Show all changes
40 commits
Select commit
Hold shift + click to select a range
a93e452
poc API
72f4dfd
Merge branch 'master' into feat/ckpt_plugin
e7d2b66
Fix up the API, unsure on connection
b41e794
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] 9161980
Example API
7aa4e8c
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] dffe088
Update all constructors
cacf0e5
Move towards having the checkpoint plugin not require the plugin, and…
028ac38
Remove import
99c7a46
Fix tests
3adc486
Change name
b7d5b55
Cleanups
0a0a068
Fixes/Cleanups
97fb2a2
Use property
402156e
Fixes to signature
5310a7f
Merge branch 'master' into feat/ckpt_plugin
d7f567a
Add warning for TPU plugins that they do not support custom checkpoin…
fcc24b4
Cleanup API, introduce storage options
4421276
Update signature to be more general
d84cce1
Address feedback, add test for support check
38c22a2
Merge branch 'master' into feat/ckpt_plugin
b7f37ee
Add CHANGELOG.md
49086cc
fix tests
936f65a
change name
049a676
Fix mypy
1ff0912
Reviews
1841d3b
Add ability to pass checkpoint plugin through the trainer
b909dfe
Add constraints
50b11b5
Match signature to see if mypy works
9e16e34
Address review points
642e6fa
Revert changes to typing
5c9e973
Add docs/doc strings and API
6361c87
Address feedback
c921dbb
Update pytorch_lightning/plugins/training_type/training_type_plugin.py
fd82276
Address reviews
2fc3558
Update typing
21783f6
Refactor name
3b8c3f5
Clear up signature of function; checkpoint_plugin -> checkpoint_io
9cfe98f
Slightly cleaner
8f234e0
Address reviews
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 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,52 @@ | ||
Custom Checkpointing IO | ||
======================= | ||
|
||
.. warning:: The Checkpoint IO API is experimental and subject to change. | ||
|
||
Lightning supports modifying the checkpointing save/load functionality through the ``CheckpointIO``. This encapsulates the save/load logic | ||
that is managed by the ``TrainingTypePlugin``. | ||
|
||
``CheckpointIO`` can be extended to include your custom save/load functionality to and from a path, with the object being passed to either a `Trainer`` object or a``TrainingTypePlugin`` as shown below. | ||
|
||
.. code-block:: python | ||
|
||
from pathlib import Path | ||
from typing import Any, Dict, Optional, Union | ||
|
||
from pytorch_lightning import Trainer | ||
from pytorch_lightning.callbacks import ModelCheckpoint | ||
from pytorch_lightning.plugins import CheckpointIO, SingleDevicePlugin | ||
|
||
|
||
class CustomCheckpointPlugin(CheckpointIO): | ||
def save_checkpoint( | ||
self, checkpoint: Dict[str, Any], path: Union[str, Path], storage_options: Optional[Any] = None | ||
) -> None: | ||
... | ||
|
||
def load_checkpoint(self, path: Union[str, Path], storage_options: Optional[Any] = None) -> Dict[str, Any]: | ||
... | ||
|
||
|
||
checkpoint_plugin = CustomCheckpointPlugin() | ||
|
||
# Pass into the Trainer object | ||
model = MyModel() | ||
trainer = Trainer( | ||
plugins=[checkpoint_plugin], | ||
callbacks=ModelCheckpoint(save_last=True), | ||
) | ||
trainer.fit(model) | ||
|
||
# pass into TrainingTypePlugin | ||
model = MyModel() | ||
device = torch.device("cpu") | ||
trainer = Trainer( | ||
plugins=SingleDevicePlugin(device, checkpoint_plugin=checkpoint_plugin), | ||
callbacks=ModelCheckpoint(save_last=True), | ||
) | ||
trainer.fit(model) | ||
|
||
.. note:: | ||
|
||
Some ``TrainingTypePlugins`` do not support custom ``CheckpointIO`` as as checkpointing logic is not modifiable. |
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,15 @@ | ||
# 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 pytorch_lightning.plugins.io.checkpoint_plugin import CheckpointIO # noqa: F401 | ||
from pytorch_lightning.plugins.io.torch_plugin import TorchCheckpointIO # noqa: F401 |
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,57 @@ | ||
# 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 abc import ABC, abstractmethod | ||
from typing import Any, Dict, Optional | ||
|
||
from pytorch_lightning.utilities.types import _PATH | ||
|
||
|
||
class CheckpointIO(ABC): | ||
""" | ||
Interface to save/load checkpoints as they are saved through the ``TrainingTypePlugin``. | ||
|
||
Typically most plugins either use the Torch based IO Plugin; ``TorchCheckpointIO`` but may | ||
require particular handling depending on the plugin. | ||
|
||
In addition, you can pass a custom ``CheckpointIO`` by extending this class and passing it | ||
to the Trainer, i.e ``Trainer(plugins=[MyCustomCheckpointIO()])``. | ||
|
||
.. note:: | ||
|
||
For some plugins, it is not possible to use a custom checkpoint plugin as checkpointing logic is not | ||
modifiable. | ||
|
||
""" | ||
|
||
@abstractmethod | ||
def save_checkpoint(self, checkpoint: Dict[str, Any], path: _PATH, storage_options: Optional[Any] = None) -> None: | ||
"""Save model/training states as a checkpoint file through state-dump and file-write. | ||
|
||
Args: | ||
checkpoint: dict containing model and trainer state | ||
path: write-target path | ||
storage_options: Optional parameters when saving the model/training states. | ||
""" | ||
|
||
@abstractmethod | ||
def load_checkpoint(self, path: _PATH, storage_options: Optional[Any] = None) -> Dict[str, Any]: | ||
""" | ||
Load checkpoint from a path when resuming or loading ckpt for test/validate/predict stages. | ||
|
||
Args: | ||
path: Path to checkpoint | ||
storage_options: Optional parameters when loading the model/training states. | ||
|
||
Returns: The loaded checkpoint. | ||
""" |
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,55 @@ | ||
# 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 Any, Callable, Dict, Optional | ||
|
||
import pytorch_lightning as pl | ||
from pytorch_lightning.plugins.io.checkpoint_plugin import CheckpointIO | ||
from pytorch_lightning.utilities import rank_zero_warn | ||
from pytorch_lightning.utilities.cloud_io import atomic_save | ||
from pytorch_lightning.utilities.cloud_io import load as pl_load | ||
from pytorch_lightning.utilities.types import _PATH | ||
|
||
|
||
class TorchCheckpointIO(CheckpointIO): | ||
""" | ||
CheckpointIO that utilizes :func:`torch.save` and :func:`torch.load` | ||
to save and load checkpoints respectively, common for most use cases. | ||
""" | ||
|
||
def save_checkpoint(self, checkpoint: Dict[str, Any], path: _PATH, storage_options: Optional[Any] = None) -> None: | ||
try: | ||
# write the checkpoint dictionary on the file | ||
atomic_save(checkpoint, path) | ||
except AttributeError as err: | ||
# todo (sean): is this try catch necessary still? | ||
# https://github.com/PyTorchLightning/pytorch-lightning/pull/431 | ||
key = pl.LightningModule.CHECKPOINT_HYPER_PARAMS_KEY | ||
checkpoint.pop(key, None) | ||
rank_zero_warn(f"Warning, `{key}` dropped from checkpoint. An attribute is not picklable: {err}") | ||
atomic_save(checkpoint, path) | ||
|
||
def load_checkpoint( | ||
self, path: _PATH, map_location: Optional[Callable] = lambda storage, loc: storage | ||
) -> Dict[str, Any]: | ||
""" | ||
Loads checkpoint using torch.load, with additional handling for fsspec remote loading of files. | ||
SeanNaren marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
Args: | ||
path: Path to checkpoint | ||
map_location: a function, :class:`torch.device`, string or a dict specifying how to remap storage | ||
locations. | ||
|
||
Returns: The loaded checkpoint. | ||
""" | ||
return pl_load(path, map_location=map_location) |
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
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.