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

Lightning Lite core and tests #10175

Merged
merged 60 commits into from
Oct 29, 2021
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
Show all changes
60 commits
Select commit Hold shift + click to select a range
782c70f
lightning lite package and tests
awaelchli Oct 27, 2021
be39098
update changelog
awaelchli Oct 27, 2021
34b0e89
Merge branch 'master' into lightning-lite/lite-core
tchaton Oct 27, 2021
e45f736
update
tchaton Oct 27, 2021
0deceba
Docstrings and CHANGELOG
carmocca Oct 27, 2021
5d14e83
Fixes to previous commit. Mention devices=auto (not yet implemented).…
carmocca Oct 27, 2021
11862e8
Fix test
carmocca Oct 27, 2021
ffed5ce
Fix test
carmocca Oct 27, 2021
538b969
Merge branch 'lightning-lite/lite-core' of https://github.com/PyTorch…
carmocca Oct 27, 2021
93b7940
update
tchaton Oct 28, 2021
13587df
Merge branch 'master' into lightning-lite/lite-core
awaelchli Oct 28, 2021
cf34e7b
Merge branch 'master' into lightning-lite/lite-core
awaelchli Oct 28, 2021
a6414a2
update access to deepspeed internal vars
awaelchli Oct 28, 2021
5e1aeb8
fix check for multiple models in deepspeed
awaelchli Oct 28, 2021
f885b35
fix deepspeed precision
awaelchli Oct 28, 2021
5546084
Merge branch 'master' into lightning-lite/lite-core
awaelchli Oct 28, 2021
db34e09
fix line too long
awaelchli Oct 28, 2021
992fd45
Minor changes
carmocca Oct 28, 2021
b8d44ce
remove identity wrapper
awaelchli Oct 28, 2021
732de7a
Merge remote-tracking branch 'origin/lightning-lite/lite-core' into l…
awaelchli Oct 28, 2021
04094c3
Same annotations as Lightning which are identical to those in torch
carmocca Oct 28, 2021
1d9920a
Add comment
carmocca Oct 28, 2021
a6df052
Simplify _LiteOptimizer
carmocca Oct 28, 2021
5208e19
Didn't mean to remove this :)
carmocca Oct 28, 2021
31406ae
rename cast to autocast
awaelchli Oct 28, 2021
bda0f8a
test: Remove unused parametrization
carmocca Oct 28, 2021
c34d006
rename save_checkpoint to save
awaelchli Oct 28, 2021
f45c2c8
update docstring
awaelchli Oct 28, 2021
c84acb1
update comment
awaelchli Oct 28, 2021
ddd7c4f
Merge remote-tracking branch 'origin/lightning-lite/lite-core' into l…
awaelchli Oct 28, 2021
92752e6
add load
awaelchli Oct 28, 2021
c0ffc71
tests: update autocast use
carmocca Oct 28, 2021
af40009
add test for autocast
awaelchli Oct 28, 2021
eb9b92e
simplify test
awaelchli Oct 28, 2021
3e261e1
add test description
awaelchli Oct 28, 2021
5754ad7
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Oct 28, 2021
85fe0cf
remove "mixed" string support
awaelchli Oct 28, 2021
91a6b3c
More mixed references
carmocca Oct 28, 2021
f45a97a
Implement `seed_everything`
carmocca Oct 28, 2021
b543655
Merge branch 'master' into lightning-lite/lite-core
awaelchli Oct 28, 2021
ba7ac5f
add isinstance check
awaelchli Oct 28, 2021
f04b398
add bfloat16
awaelchli Oct 28, 2021
229b024
rename params_on_cpu
awaelchli Oct 28, 2021
95db246
Pass down the barrier name
carmocca Oct 28, 2021
0c8e914
Add back __del__
carmocca Oct 28, 2021
a93278d
Fix mypy
carmocca Oct 28, 2021
65e289b
Fix test
carmocca Oct 28, 2021
d408228
Add worker init fn
carmocca Oct 28, 2021
952e11c
Forgot to pass the global rank
carmocca Oct 28, 2021
50d5124
add back skip of expensive spawn test
awaelchli Oct 28, 2021
13fb58a
resolve todo in _LiteModule
awaelchli Oct 28, 2021
2e92fe1
Merge remote-tracking branch 'origin/lightning-lite/lite-core' into l…
awaelchli Oct 28, 2021
9a1e93f
Add seed everything test
carmocca Oct 28, 2021
f47c2ad
fix type error
awaelchli Oct 28, 2021
5baffe6
Merge branch 'master' into lightning-lite/lite-core
awaelchli Oct 29, 2021
280dd4d
update
tchaton Oct 29, 2021
46070bc
Merge branch 'lightning-lite/lite-core' of https://github.com/PyTorch…
tchaton Oct 29, 2021
947f9ca
update lambda_closure -> closure
awaelchli Oct 29, 2021
05ea78d
Merge branch 'master' into lightning-lite/lite-core
awaelchli Oct 29, 2021
015051a
update
tchaton Oct 29, 2021
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
2 changes: 1 addition & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -220,7 +220,7 @@ The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/).
* Implemented `DeepSpeedPlugin._setup_model_and_optimizers` ([#10009](https://github.com/PyTorchLightning/pytorch-lightning/pull/10009), [#10064](https://github.com/PyTorchLightning/pytorch-lightning/pull/10064))
* Implemented `{DDPShardedPlugin,DDPShardedSpawnPlugin}._setup_model_and_optimizers` ([#10028](https://github.com/PyTorchLightning/pytorch-lightning/pull/10028), [#10064](https://github.com/PyTorchLightning/pytorch-lightning/pull/10064))
* Added optional `model` argument to the `optimizer_step` methods in accelerators and plugins ([#10023](https://github.com/PyTorchLightning/pytorch-lightning/pull/10023))

* Added `pytorch_lightning.lite` package ([#?](https://github.com/PyTorchLightning/pytorch-lightning/pull/?))


- Added `XLACheckpointIO` plugin ([#9972](https://github.com/PyTorchLightning/pytorch-lightning/pull/9972))
Expand Down
17 changes: 17 additions & 0 deletions pytorch_lightning/lite/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
# 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.lite.lite import LightningLite

__all__ = ["LightningLite"]
470 changes: 470 additions & 0 deletions pytorch_lightning/lite/lite.py

Large diffs are not rendered by default.

151 changes: 151 additions & 0 deletions pytorch_lightning/lite/wrappers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,151 @@
# 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, Generator, Iterator, List, Optional, Union

import torch
from torch import nn as nn
from torch import Tensor
from torch.optim import Optimizer
from torch.utils.data import DataLoader

from pytorch_lightning.accelerators import Accelerator
from pytorch_lightning.utilities.apply_func import apply_to_collection, move_data_to_device


def _do_nothing_closure() -> None:
return None


class _LiteOptimizer:
def __init__(self, optimizer: Optimizer, accelerator: Accelerator) -> None:
"""LiteOptimizer is a thin wrapper around the :class:`~torch.optim.Optimizer` that delegates the optimizer
step calls to the accelerator/strategy plugin.

The underlying wrapped optimizer object can be accessed via the property :attr:`optimizer`.

Args:
optimizer: The optimizer to wrap
accelerator: Reference to the accelerator for handling the optimizer step
"""
self.__dict__ = {k: v for k, v in optimizer.__dict__.items() if k not in ("step", "__del__")}
carmocca marked this conversation as resolved.
Show resolved Hide resolved
self.__class__ = type("Lite" + optimizer.__class__.__name__, (self.__class__, optimizer.__class__), {})
self._optimizer = optimizer
self._accelerator = accelerator

@property
def optimizer(self) -> Optimizer:
return self._optimizer

@property
def state(self) -> Dict[str, torch.Tensor]:
return self._optimizer.state

@state.setter
def state(self, state: Dict[str, torch.Tensor]) -> None:
self._optimizer.state = state

@property
def defaults(self) -> Dict[str, Any]:
return self._optimizer.defaults

@defaults.setter
def defaults(self, defaults: Dict[str, Any]) -> None:
self._optimizer.defaults = defaults

@property
def param_groups(self) -> List[Dict[str, torch.Tensor]]:
return self._optimizer.param_groups

@param_groups.setter
def param_groups(self, param_groups: List[Dict[str, torch.Tensor]]) -> None:
self._optimizer.param_groups = param_groups

def step(self, closure: Optional[Callable] = None) -> None:
closure = closure or _do_nothing_closure
self._accelerator.optimizer_step(
self._optimizer,
opt_idx=0,
lambda_closure=closure,
model=self._accelerator.model,
)

def zero_grad(self, *args: Any, **kwargs: Any) -> None:
awaelchli marked this conversation as resolved.
Show resolved Hide resolved
self._optimizer.zero_grad(*args, **kwargs)


class _LiteModule(nn.Module):
# TODO: Pass in the precision plugin instead of accelerator
carmocca marked this conversation as resolved.
Show resolved Hide resolved
def __init__(self, module: nn.Module, accelerator: Accelerator) -> None:
"""The LiteModule is a thin wrapper around the :class:`torch.nn.Module` and handles precision / autocast
automatically for the forward pass.

The underlying wrapped module can be accessed via the property :attr:`module`.

Args:
module: The module to wrap
accelerator: Reference to the accelerator for handling precision context
"""
super().__init__()
self._module = module
self._accelerator = accelerator

@property
def module(self) -> nn.Module:
return self._module

def forward(self, *args: Any, **kwargs: Any) -> Any:
carmocca marked this conversation as resolved.
Show resolved Hide resolved
"""Casts all inputs to the right precision and handles autocast for operations in the module forward
method."""
precision = self._accelerator.precision_plugin.precision
precision_to_type = {
"mixed": torch.float16,
awaelchli marked this conversation as resolved.
Show resolved Hide resolved
16: torch.float16,
32: torch.float32,
64: torch.float64,
}
# TODO (@awaelchli): let the precision plugin handle the conversion
to_type = precision_to_type[precision]
args, kwargs = apply_to_collection([args, kwargs], function=lambda t: t.to(to_type), dtype=Tensor)

with self._accelerator.precision_plugin.forward_context():
output = self.module(*args, **kwargs)

output = apply_to_collection(output, function=lambda t: t.to(torch.get_default_dtype()), dtype=Tensor)
return output


class _LiteDataLoader(DataLoader):
def __init__(self, device: Optional[torch.device] = None, **dl_kwargs: Any) -> None:
"""The LiteDataLoader is an extension of the PyTorch :class:`~torch.utils.data.DataLoader` that adds
additional features such as moving the data to the device automatically.

Args:
device: The device to which the data should be moved. By default the device is `None` and no data
transfers will be made (identical behavior as :class:`~torch.utils.data.DataLoader`).
**dl_kwargs: Accepts all arguments that the PyTorch :class:`~torch.utils.data.DataLoader` accepts.
"""
super().__init__(**dl_kwargs)
self._device = device

@property
def device(self) -> Optional[torch.device]:
return self._device

def __iter__(self) -> Union[Iterator[Any], Generator[Any, None, None]]:
iterator = super().__iter__()
if self._device is None:
return iterator

for item in iterator:
yield move_data_to_device(item, self._device)
Empty file added tests/lite/__init__.py
Empty file.
Loading