2021-01-30 19:55:28 +00:00
|
|
|
# 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.
|
2021-03-29 20:50:51 +00:00
|
|
|
import contextlib
|
2021-10-29 20:31:32 +00:00
|
|
|
from abc import abstractmethod
|
2021-11-08 17:36:37 +00:00
|
|
|
from typing import Any, Callable, Dict, Generator, List, Optional, Union
|
2021-01-30 19:55:28 +00:00
|
|
|
|
|
|
|
import torch
|
2021-04-15 16:48:16 +00:00
|
|
|
from torch import Tensor
|
2021-09-29 13:34:26 +00:00
|
|
|
from torch.cuda.amp import GradScaler
|
2021-04-15 16:48:16 +00:00
|
|
|
from torch.nn import Module
|
2021-01-30 19:55:28 +00:00
|
|
|
from torch.optim import Optimizer
|
|
|
|
|
2021-04-10 06:55:07 +00:00
|
|
|
import pytorch_lightning as pl
|
2021-02-18 18:28:23 +00:00
|
|
|
from pytorch_lightning.plugins.precision import ApexMixedPrecisionPlugin, NativeMixedPrecisionPlugin, PrecisionPlugin
|
2021-09-10 20:58:02 +00:00
|
|
|
from pytorch_lightning.plugins.training_type import DataParallelPlugin, TrainingTypePlugin
|
2021-05-04 10:50:56 +00:00
|
|
|
from pytorch_lightning.trainer.states import TrainerFn
|
2021-05-02 22:27:17 +00:00
|
|
|
from pytorch_lightning.utilities.apply_func import apply_to_collection, move_data_to_device
|
2021-10-26 15:26:26 +00:00
|
|
|
from pytorch_lightning.utilities.enums import AMPType, LightningEnum
|
2021-11-10 07:28:24 +00:00
|
|
|
from pytorch_lightning.utilities.types import STEP_OUTPUT
|
2021-01-30 19:55:28 +00:00
|
|
|
|
|
|
|
|
2021-04-15 16:48:16 +00:00
|
|
|
class Accelerator:
|
2021-09-06 12:49:09 +00:00
|
|
|
"""The Accelerator Base Class. An Accelerator is meant to deal with one type of Hardware.
|
2021-01-30 19:55:28 +00:00
|
|
|
|
|
|
|
Currently there are accelerators for:
|
2021-04-10 06:55:07 +00:00
|
|
|
|
2021-01-30 19:55:28 +00:00
|
|
|
- CPU
|
|
|
|
- GPU
|
|
|
|
- TPU
|
2021-09-27 04:09:16 +00:00
|
|
|
- IPU
|
2021-01-30 19:55:28 +00:00
|
|
|
|
|
|
|
Each Accelerator gets two plugins upon initialization:
|
|
|
|
One to handle differences from the training routine and one to handle different precisions.
|
|
|
|
"""
|
|
|
|
|
2021-07-26 11:37:35 +00:00
|
|
|
def __init__(self, precision_plugin: PrecisionPlugin, training_type_plugin: TrainingTypePlugin) -> None:
|
2021-01-30 19:55:28 +00:00
|
|
|
"""
|
|
|
|
Args:
|
|
|
|
precision_plugin: the plugin to handle precision-specific parts
|
|
|
|
training_type_plugin: the plugin to handle different training routines
|
|
|
|
"""
|
|
|
|
self.precision_plugin = precision_plugin
|
|
|
|
self.training_type_plugin = training_type_plugin
|
|
|
|
|
2021-04-19 12:43:16 +00:00
|
|
|
self.optimizers: List = []
|
|
|
|
self.lr_schedulers: List = []
|
|
|
|
self.optimizer_frequencies: List = []
|
2021-01-30 19:55:28 +00:00
|
|
|
|
2021-03-18 21:33:39 +00:00
|
|
|
def setup_environment(self) -> None:
|
2021-09-06 12:49:09 +00:00
|
|
|
"""Setup any processes or distributed connections.
|
|
|
|
|
|
|
|
This is called before the LightningModule/DataModule setup hook which allows the user to access the accelerator
|
|
|
|
environment before setup is complete.
|
2021-03-18 21:33:39 +00:00
|
|
|
"""
|
|
|
|
self.training_type_plugin.setup_environment()
|
2021-01-30 19:55:28 +00:00
|
|
|
|
2021-08-04 15:43:34 +00:00
|
|
|
def setup(self, trainer: "pl.Trainer") -> None:
|
2021-09-06 12:49:09 +00:00
|
|
|
"""Setup plugins for the trainer fit and creates optimizers.
|
2021-04-10 06:55:07 +00:00
|
|
|
|
2021-01-30 19:55:28 +00:00
|
|
|
Args:
|
2021-03-18 21:33:39 +00:00
|
|
|
trainer: the trainer instance
|
2021-01-30 19:55:28 +00:00
|
|
|
"""
|
2021-08-04 15:43:34 +00:00
|
|
|
self.setup_training_type_plugin()
|
2021-03-22 11:43:53 +00:00
|
|
|
if not self.training_type_plugin.setup_optimizers_in_pre_dispatch:
|
|
|
|
self.setup_optimizers(trainer)
|
2021-05-13 17:33:55 +00:00
|
|
|
self.setup_precision_plugin()
|
2021-01-30 19:55:28 +00:00
|
|
|
|
2021-07-26 11:37:35 +00:00
|
|
|
def pre_dispatch(self, trainer: "pl.Trainer") -> None:
|
2021-02-17 20:41:18 +00:00
|
|
|
"""Hook to do something before the training/evaluation/prediction starts."""
|
2021-05-02 22:27:17 +00:00
|
|
|
self._move_optimizer_state()
|
|
|
|
|
2021-02-17 20:41:18 +00:00
|
|
|
self.training_type_plugin.pre_dispatch()
|
2021-03-22 11:43:53 +00:00
|
|
|
if self.training_type_plugin.setup_optimizers_in_pre_dispatch:
|
|
|
|
self.setup_optimizers(trainer)
|
2021-05-02 22:27:17 +00:00
|
|
|
|
2021-02-17 20:41:18 +00:00
|
|
|
self.precision_plugin.pre_dispatch()
|
|
|
|
|
2021-07-21 09:37:05 +00:00
|
|
|
def _move_optimizer_state(self, device: Optional[torch.device] = None) -> None:
|
2021-07-26 11:37:35 +00:00
|
|
|
"""Moves the state of the optimizers to the GPU if needed."""
|
2021-07-21 09:37:05 +00:00
|
|
|
device = device or self.root_device
|
2021-05-02 22:27:17 +00:00
|
|
|
for opt in self.optimizers:
|
|
|
|
for p, v in opt.state.items():
|
2021-07-21 09:37:05 +00:00
|
|
|
opt.state[p] = apply_to_collection(v, torch.Tensor, move_data_to_device, device)
|
2021-05-02 22:27:17 +00:00
|
|
|
|
2021-07-26 11:37:35 +00:00
|
|
|
def dispatch(self, trainer: "pl.Trainer") -> None:
|
2021-04-30 17:16:28 +00:00
|
|
|
"""Hook to do something before the training/evaluation/prediction starts."""
|
|
|
|
self.training_type_plugin.dispatch(trainer)
|
|
|
|
self.precision_plugin.dispatch(trainer)
|
|
|
|
|
2021-07-26 11:37:35 +00:00
|
|
|
def post_dispatch(self, trainer: "pl.Trainer") -> None:
|
2021-04-13 08:47:15 +00:00
|
|
|
"""Hook to do something after the training/evaluation/prediction starts."""
|
2021-09-10 20:58:02 +00:00
|
|
|
self.training_type_plugin.post_dispatch(trainer)
|
2021-02-17 20:41:18 +00:00
|
|
|
self.precision_plugin.post_dispatch()
|
|
|
|
|
2021-01-30 19:55:28 +00:00
|
|
|
@property
|
2021-04-15 16:48:16 +00:00
|
|
|
def model(self) -> Module:
|
2021-09-06 12:49:09 +00:00
|
|
|
"""Returns the model.
|
|
|
|
|
|
|
|
This can also be a wrapped LightningModule. For retrieving the pure LightningModule use
|
|
|
|
:attr:`Accelerator.lightning_module`
|
2021-01-30 19:55:28 +00:00
|
|
|
"""
|
|
|
|
return self.training_type_plugin.model
|
|
|
|
|
|
|
|
@model.setter
|
2021-04-15 16:48:16 +00:00
|
|
|
def model(self, new_model: Module) -> None:
|
2021-01-30 19:55:28 +00:00
|
|
|
self.training_type_plugin.model = new_model
|
|
|
|
|
|
|
|
@property
|
2021-07-26 11:37:35 +00:00
|
|
|
def lightning_module(self) -> "pl.LightningModule":
|
2021-09-06 12:49:09 +00:00
|
|
|
"""Returns the pure LightningModule.
|
|
|
|
|
2021-01-30 19:55:28 +00:00
|
|
|
To get the potentially wrapped model use :attr:`Accelerator.model`
|
|
|
|
"""
|
|
|
|
return self.training_type_plugin.lightning_module
|
|
|
|
|
|
|
|
@property
|
|
|
|
def root_device(self) -> torch.device:
|
2021-09-06 12:49:09 +00:00
|
|
|
"""Returns the root device."""
|
2021-01-30 19:55:28 +00:00
|
|
|
return self.training_type_plugin.root_device
|
|
|
|
|
2021-02-25 06:42:23 +00:00
|
|
|
def teardown(self) -> None:
|
2021-09-06 12:49:09 +00:00
|
|
|
"""This method is called to teardown the training process.
|
|
|
|
|
2021-05-22 20:19:24 +00:00
|
|
|
It is the right place to release memory and free other resources.
|
2021-01-30 19:55:28 +00:00
|
|
|
"""
|
2021-05-22 20:19:24 +00:00
|
|
|
self.training_type_plugin.teardown()
|
2021-01-30 19:55:28 +00:00
|
|
|
|
2021-08-16 11:34:42 +00:00
|
|
|
def batch_to_device(self, batch: Any, device: Optional[torch.device] = None, dataloader_idx: int = 0) -> Any:
|
2021-09-06 12:49:09 +00:00
|
|
|
"""Moves the batch to the correct device. The returned batch is of the same type as the input batch, just
|
|
|
|
having all tensors on the correct device.
|
2021-01-30 19:55:28 +00:00
|
|
|
|
|
|
|
Args:
|
|
|
|
batch: The batch of samples to move to the correct device
|
|
|
|
device: The target device
|
2021-05-13 17:33:55 +00:00
|
|
|
dataloader_idx: The index of the dataloader to which the batch belongs.
|
2021-01-30 19:55:28 +00:00
|
|
|
"""
|
|
|
|
model = self.lightning_module
|
2021-07-13 06:23:36 +00:00
|
|
|
device = device or self.root_device
|
|
|
|
|
2021-07-05 08:31:39 +00:00
|
|
|
if model is not None and not isinstance(self.training_type_plugin, DataParallelPlugin):
|
|
|
|
# no need to transfer batch to device in DP mode
|
2021-08-16 11:34:42 +00:00
|
|
|
return model._apply_batch_transfer_handler(batch, device=device, dataloader_idx=dataloader_idx)
|
2021-02-18 11:58:12 +00:00
|
|
|
|
2021-01-30 19:55:28 +00:00
|
|
|
return move_data_to_device(batch, device)
|
|
|
|
|
2021-07-26 11:37:35 +00:00
|
|
|
def training_step(self, step_kwargs: Dict[str, Union[Any, int]]) -> STEP_OUTPUT:
|
2021-01-30 19:55:28 +00:00
|
|
|
"""The actual training step.
|
|
|
|
|
2021-09-09 07:45:52 +00:00
|
|
|
See :meth:`~pytorch_lightning.core.lightning.LightningModule.training_step` for more details
|
2021-01-30 19:55:28 +00:00
|
|
|
"""
|
2021-08-25 19:10:28 +00:00
|
|
|
with self.precision_plugin.train_step_context():
|
2021-05-13 17:33:55 +00:00
|
|
|
return self.training_type_plugin.training_step(*step_kwargs.values())
|
2021-01-30 19:55:28 +00:00
|
|
|
|
2021-05-13 17:33:55 +00:00
|
|
|
def validation_step(self, step_kwargs: Dict[str, Union[Any, int]]) -> Optional[STEP_OUTPUT]:
|
2021-01-30 19:55:28 +00:00
|
|
|
"""The actual validation step.
|
|
|
|
|
2021-09-09 07:45:52 +00:00
|
|
|
See :meth:`~pytorch_lightning.core.lightning.LightningModule.validation_step` for more details
|
2021-01-30 19:55:28 +00:00
|
|
|
"""
|
2021-08-25 19:10:28 +00:00
|
|
|
with self.precision_plugin.val_step_context():
|
2021-05-13 17:33:55 +00:00
|
|
|
return self.training_type_plugin.validation_step(*step_kwargs.values())
|
2021-01-30 19:55:28 +00:00
|
|
|
|
2021-05-13 17:33:55 +00:00
|
|
|
def test_step(self, step_kwargs: Dict[str, Union[Any, int]]) -> Optional[STEP_OUTPUT]:
|
2021-01-30 19:55:28 +00:00
|
|
|
"""The actual test step.
|
|
|
|
|
2021-09-09 07:45:52 +00:00
|
|
|
See :meth:`~pytorch_lightning.core.lightning.LightningModule.test_step` for more details
|
2021-01-30 19:55:28 +00:00
|
|
|
"""
|
2021-08-25 19:10:28 +00:00
|
|
|
with self.precision_plugin.test_step_context():
|
2021-05-13 17:33:55 +00:00
|
|
|
return self.training_type_plugin.test_step(*step_kwargs.values())
|
2021-02-16 22:11:56 +00:00
|
|
|
|
2021-05-13 17:33:55 +00:00
|
|
|
def predict_step(self, step_kwargs: Dict[str, Union[Any, int]]) -> STEP_OUTPUT:
|
2021-02-16 22:11:56 +00:00
|
|
|
"""The actual predict step.
|
|
|
|
|
2021-09-09 07:45:52 +00:00
|
|
|
See :meth:`~pytorch_lightning.core.lightning.LightningModule.predict_step` for more details
|
2021-02-16 22:11:56 +00:00
|
|
|
"""
|
2021-08-25 19:10:28 +00:00
|
|
|
with self.precision_plugin.predict_step_context():
|
2021-05-13 17:33:55 +00:00
|
|
|
return self.training_type_plugin.predict_step(*step_kwargs.values())
|
2021-01-30 19:55:28 +00:00
|
|
|
|
2021-07-26 11:37:35 +00:00
|
|
|
def backward(self, closure_loss: Tensor, *args: Any, **kwargs: Any) -> Tensor:
|
2021-01-30 19:55:28 +00:00
|
|
|
"""Forwards backward-calls to the precision plugin.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
closure_loss: a tensor holding the loss value to backpropagate
|
|
|
|
"""
|
2021-07-08 14:02:09 +00:00
|
|
|
self.training_type_plugin.pre_backward(closure_loss)
|
|
|
|
closure_loss = self.precision_plugin.pre_backward(self.lightning_module, closure_loss)
|
PoC: Accelerator refactor (#5743)
* restoring the result from subprocess
* fix queue.get() order for results
* add missing "block_backward_sync" context manager
* add missing "block_backward_sync" context manager
* fix sync_batchnorm
* fix supported gpu-ids for tuple
* fix clip gradients and inf recursion
* accelerator selection: added cluster_environment plugin
* fix torchelastic test
* fix reduce early stopping decision for DDP
* fix tests: callbacks, conversion to lightning optimizer
* fix lightning optimizer does not pickle
* fix setting benchmark and deterministic option
* fix slurm amp test
* fix prepare_data test and determine node_rank
* fix retrieving last path when testing
* remove obsolete plugin argument
* fix test: test_trainer_config
* fix torchscript tests
* fix trainer.model access
* move properties
* fix test_transfer_batch_hook
* fix auto_select_gpus
* fix omegaconf test
* fix test that needs to simulate slurm ddp
* add horovod plugin
* fix test with named arguments
* clean up whitespace
* fix datamodules test
* remove old accelerators
* fix naming
* move old plugins
* move to plugins
* create precision subpackage
* create training_type subpackage
* fix all new import errors
* fix wrong arguments order passed to test
* fix LR finder
* Added sharded training type and amp plugin
* Move clip grad to precision plugin
* Added sharded spawn, select accelerators based on distributed_backend + enable custom fp16 plugin automatically
* Fix import issue, attempting to fix tests
* Fix initial test
* Reflect hook logic from master, should wrap model after move to device
* Optional state consolidation, since master has optimizers not wrapped
* change attribute for instance test
* reset optimizers
optimizers are not used in main process, so state would be wrong.
* legacy
* imports in accel
* legacy2
* trainer imports
* fix import errors after rebase
* move hook to new setup location
* provide unwrapping logic
* fix trainer callback system
* added ddp2 implementation
* fix imports .legacy
* move plugins
* restore legacy
* drop test.py from root
* add tpu accelerator and plugins
* fixes
* fix lightning optimizer merge
* reset bugreportmodel
* unwrapping
* step routing forward
* model access
* unwrap
* opt
* integrate distrib_type
* sync changes
* sync
* fixes
* add forgotten generators
* add missing logic
* update
* import
* missed imports
* import fixes
* isort
* mv f
* changelog
* format
* move helper to parallel plugin
* d
* add world size
* clean up
* duplicate
* activate ddp_sharded and tpu
* set nvidia flags
* remove unused colab var
* use_tpu <-> on_tpu attrs
* make some ddp_cpu and clusterplugin tests pass
* Ref/accelerator connector (#5742)
* final cleanup
Co-authored-by: Adrian Wälchli <aedu.waelchli@gmail.com>
* connector cleanup
Co-authored-by: Adrian Wälchli <aedu.waelchli@gmail.com>
* trainer cleanup
Co-authored-by: Adrian Wälchli <aedu.waelchli@gmail.com>
* accelerator cleanup + missing logic in accelerator connector
Co-authored-by: Adrian Wälchli <aedu.waelchli@gmail.com>
* add missing changes to callbacks
Co-authored-by: Adrian Wälchli <aedu.waelchli@gmail.com>
* reflect accelerator changes to lightning module
Co-authored-by: Adrian Wälchli <aedu.waelchli@gmail.com>
* clean cluster envs
Co-authored-by: Adrian Wälchli <aedu.waelchli@gmail.com>
* cleanup plugins
Co-authored-by: Adrian Wälchli <aedu.waelchli@gmail.com>
* add broadcasting
Co-authored-by: Adrian Wälchli <aedu.waelchli@gmail.com>
* yapf
* remove plugin connector
Co-authored-by: Adrian Wälchli <aedu.waelchli@gmail.com>
* plugins
* manual optimization
* update optimizer routing
* add rank to torchelastic
* fix memory mixed precision
* setstate on trainer for pickling in ddp spawn
* add predict method
* add back commented accelerator code
* adapt test for sync_batch_norm to new plugin
* fix deprecated tests
* fix ddp cpu choice when no num_processes are given
* yapf format
* skip a memory test that cannot pass anymore
* fix pickle error in spawn plugin
* x
* avoid
* x
* fix cyclic import in docs build
* add support for sharded
* update typing
* add sharded and sharded_spawn to distributed types
* make unwrap model default
* refactor LightningShardedDataParallel similar to LightningDistributedDataParallel
* update sharded spawn to reflect changes
* update sharded to reflect changes
* Merge 1.1.5 changes
* fix merge
* fix merge
* yapf isort
* fix merge
* yapf isort
* fix indentation in test
* copy over reinit scheduler implementation from dev1.2
* fix apex tracking calls with dev_debugger
* reduce diff to dev1.2, clean up
* fix trainer config test when gpus>0 and num_processes >0 and ddp_cpu
* sort plugin tests legacy/new
* fix error handling for amp on cpu
* fix merge
fix merge
fix merge
* [Feat] Resolve manual_backward (#5837)
* resolve manual_backward
* resolve flake8
* update
* resolve for ddp_spawn
* resolve flake8
* resolve flake8
* resolve flake8
Co-authored-by: Ubuntu <ubuntu@ip-172-31-88-60.ec2.internal>
* fix tests/accelerator tests on cpu
* [BugFix] Resolve manual optimization (#5852)
* resolve manual_optimization
* update
* update
Co-authored-by: Ubuntu <ubuntu@ip-172-31-88-60.ec2.internal>
* Remove copy trainer parameters to happen earlier within the loop and add safe guard to get ref model (#5856)
* resovle a bug
* Accelerator refactor sharded rpc (#5854)
* rpc branch
* merge
* update handling of rpc
* make devices etc. Optional in RPC
* set devices etc. later if necessary
* remove devices from sequential
* make devices optional in rpc
* fix import
* uncomment everything
* fix cluster selection
Co-authored-by: Ubuntu <ubuntu@ip-172-31-88-60.ec2.internal>
* resolve bug
* fix assert in rpc test
* resolve a test
* fix docs compilation
* accelerator refactor - fix for sharded parity test (#5866)
* fix memory issue with ddp_spawn
* x
x
x
x
x
x
x
x
x
* x
* Remove DDP2 as this does not apply
* Add missing pre optimizer hook to ensure lambda closure is called
* fix apex docstring
* [accelerator][BugFix] Resolve some test for 1 gpu (#5863)
* update
* revert init
* resolve a bug
* update
* resolve flake8
* update
* update
* update
* revert init
* resolve a bug
* update
* resolve flake8
* update
* update
* update
* update
* update
* revert init
* resolve a bug
* update
* resolve flake8
* update
* update
* update
* revert init
* update
* resolve flake8
* update
* update
* update
* update
* update
* all_gather
* update
* make plugins work, add misconfig for RPC
* update
* update
* remove breaking test
* resolve some tests
* resolve flake8
* revert to ddp_spawn
Co-authored-by: root <root@ip-172-31-88-60.ec2.internal>
Co-authored-by: Ubuntu <ubuntu@ip-172-31-88-60.ec2.internal>
Co-authored-by: Justus Schock <justus.schock@rwth-aachen.de>
* yapf isort
* resolve flake8
* fix apex doctests
* fix apex doctests 2
* resolve docs
* update drone
* clean env
* update
* update
* update
* update
* merge
* Fix RPC related tests, clean out old API, update for new accelerator API [skip ci] (#5881)
* Fix RPC related tests, clean out old API, update for new accelerator API
* Move tests out of legacy folder, update paths and names
* Update test_remove_1-4.py
* Expose properties for tpu cores/gpus/num_gpus
* Add root GPU property
* Move properties to properties.py
* move tests that were previously in drone
* Fix root GPU property (#5908)
* Move root GPU to property, remove horovod set as this is handled in horovod plugin, ensure we mock correctly to set GPU accelerator
* Add missing tests back
* fix best model path transfer when no checkpoint callback available
* Fix setup hook order [wip] (#5858)
* Call trainer setup hook before accelerator setup
* Add test case
* add new test
* typo
* fix callback order in test
Co-authored-by: tchaton <thomas@grid.ai>
Co-authored-by: Adrian Wälchli <aedu.waelchli@gmail.com>
* rename ddp sequential -> rpc sequential for special test
* revert
* fix stupid merge problem
* Use property in connector for sampler (#5913)
* merge the import conflicts
* fix spawning of processes in slurm
* [wip] Fix some bugs for TPU [skip ci] (#5878)
* fixed for single tpu
* fixed spawn
* fixed spawn
* update
* update
* wip
* resolve bugs
* resolve bug
* update on comment
* removed decorator
* resolve comments
* set to 4
* update
* update
* need cleaning
* update
* update
* update
* resolve flake8
* resolve bugs
* exclude broadcast
* resolve bugs
* change test
* update
* update
* skip if meet fails
* properly raise trace
* update
* add catch
* wrap test
* resolve typo
* update
* typo
Co-authored-by: Lezwon Castelino <lezwon@gmail.com>
Co-authored-by: Your Name <you@example.com>
* resolve some tests
* update
* fix imports
* update
* resolve flake8
* update azure pipeline
* skip a sharded test on cpu that requires a gpu
* resolve tpus
* resolve bug
* resolve flake8
* update
* updat utils
* revert permission change on files
* suggestions from carlos
Co-authored-by: Carlos Mocholí <carlossmocholi@gmail.com>
* remove unrelated formatting changes
* remove incomplete comment
* Update pytorch_lightning/accelerators/__init__.py
Co-authored-by: Carlos Mocholí <carlossmocholi@gmail.com>
* remove unrelated formatting change
* add types
* warn 1.7 ddp manual backward only if ddp kwarg unset
* yapf + isort
* pep8 unused imports
* fix cyclic import in docs
* Apply suggestions from code review
* typer in accelerator.py
* typo
* Apply suggestions from code review
* formatting
* update on comments
* update typo
* Update pytorch_lightning/trainer/properties.py
Co-authored-by: Adrian Wälchli <aedu.waelchli@gmail.com>
* update
* suggestion from code review
* suggestion from code review
Co-authored-by: Adrian Wälchli <aedu.waelchli@gmail.com>
Co-authored-by: SeanNaren <sean@grid.ai>
Co-authored-by: Jirka Borovec <jirka.borovec@seznam.cz>
Co-authored-by: chaton <thomas@grid.ai>
Co-authored-by: Ubuntu <ubuntu@ip-172-31-88-60.ec2.internal>
Co-authored-by: Sean Naren <sean.narenthiran@gmail.com>
Co-authored-by: root <root@ip-172-31-88-60.ec2.internal>
Co-authored-by: Lezwon Castelino <lezwon@gmail.com>
Co-authored-by: Your Name <you@example.com>
Co-authored-by: Carlos Mocholí <carlossmocholi@gmail.com>
Co-authored-by: Jirka Borovec <Borda@users.noreply.github.com>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2021-02-12 20:48:56 +00:00
|
|
|
|
2021-07-08 14:02:09 +00:00
|
|
|
self.precision_plugin.backward(self.lightning_module, closure_loss, *args, **kwargs)
|
2021-01-30 19:55:28 +00:00
|
|
|
|
2021-07-08 14:02:09 +00:00
|
|
|
closure_loss = self.precision_plugin.post_backward(self.lightning_module, closure_loss)
|
|
|
|
self.training_type_plugin.post_backward(closure_loss)
|
2021-01-30 19:55:28 +00:00
|
|
|
|
2021-07-08 14:02:09 +00:00
|
|
|
return closure_loss
|
2021-01-30 19:55:28 +00:00
|
|
|
|
2021-10-20 20:36:27 +00:00
|
|
|
def optimizer_step(
|
|
|
|
self,
|
|
|
|
optimizer: Optimizer,
|
|
|
|
opt_idx: int,
|
2021-10-29 13:03:04 +00:00
|
|
|
closure: Callable[[], Any],
|
2021-10-20 20:36:27 +00:00
|
|
|
model: Optional[Union["pl.LightningModule", Module]] = None,
|
|
|
|
**kwargs: Any
|
|
|
|
) -> None:
|
2021-01-30 19:55:28 +00:00
|
|
|
"""performs the actual optimizer step.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
optimizer: the optimizer performing the step
|
|
|
|
opt_idx: index of the current optimizer
|
2021-10-29 13:03:04 +00:00
|
|
|
closure: closure calculating the loss value
|
2021-10-20 20:36:27 +00:00
|
|
|
model: reference to the model, optionally defining optimizer step related hooks
|
2021-10-25 16:40:22 +00:00
|
|
|
**kwargs: Any extra arguments to ``optimizer.step``
|
2021-01-30 19:55:28 +00:00
|
|
|
"""
|
2021-10-20 20:36:27 +00:00
|
|
|
model = model or self.lightning_module
|
2021-10-29 13:03:04 +00:00
|
|
|
self.precision_plugin.optimizer_step(model, optimizer, opt_idx, closure, **kwargs)
|
|
|
|
|
PoC: Accelerator refactor (#5743)
* restoring the result from subprocess
* fix queue.get() order for results
* add missing "block_backward_sync" context manager
* add missing "block_backward_sync" context manager
* fix sync_batchnorm
* fix supported gpu-ids for tuple
* fix clip gradients and inf recursion
* accelerator selection: added cluster_environment plugin
* fix torchelastic test
* fix reduce early stopping decision for DDP
* fix tests: callbacks, conversion to lightning optimizer
* fix lightning optimizer does not pickle
* fix setting benchmark and deterministic option
* fix slurm amp test
* fix prepare_data test and determine node_rank
* fix retrieving last path when testing
* remove obsolete plugin argument
* fix test: test_trainer_config
* fix torchscript tests
* fix trainer.model access
* move properties
* fix test_transfer_batch_hook
* fix auto_select_gpus
* fix omegaconf test
* fix test that needs to simulate slurm ddp
* add horovod plugin
* fix test with named arguments
* clean up whitespace
* fix datamodules test
* remove old accelerators
* fix naming
* move old plugins
* move to plugins
* create precision subpackage
* create training_type subpackage
* fix all new import errors
* fix wrong arguments order passed to test
* fix LR finder
* Added sharded training type and amp plugin
* Move clip grad to precision plugin
* Added sharded spawn, select accelerators based on distributed_backend + enable custom fp16 plugin automatically
* Fix import issue, attempting to fix tests
* Fix initial test
* Reflect hook logic from master, should wrap model after move to device
* Optional state consolidation, since master has optimizers not wrapped
* change attribute for instance test
* reset optimizers
optimizers are not used in main process, so state would be wrong.
* legacy
* imports in accel
* legacy2
* trainer imports
* fix import errors after rebase
* move hook to new setup location
* provide unwrapping logic
* fix trainer callback system
* added ddp2 implementation
* fix imports .legacy
* move plugins
* restore legacy
* drop test.py from root
* add tpu accelerator and plugins
* fixes
* fix lightning optimizer merge
* reset bugreportmodel
* unwrapping
* step routing forward
* model access
* unwrap
* opt
* integrate distrib_type
* sync changes
* sync
* fixes
* add forgotten generators
* add missing logic
* update
* import
* missed imports
* import fixes
* isort
* mv f
* changelog
* format
* move helper to parallel plugin
* d
* add world size
* clean up
* duplicate
* activate ddp_sharded and tpu
* set nvidia flags
* remove unused colab var
* use_tpu <-> on_tpu attrs
* make some ddp_cpu and clusterplugin tests pass
* Ref/accelerator connector (#5742)
* final cleanup
Co-authored-by: Adrian Wälchli <aedu.waelchli@gmail.com>
* connector cleanup
Co-authored-by: Adrian Wälchli <aedu.waelchli@gmail.com>
* trainer cleanup
Co-authored-by: Adrian Wälchli <aedu.waelchli@gmail.com>
* accelerator cleanup + missing logic in accelerator connector
Co-authored-by: Adrian Wälchli <aedu.waelchli@gmail.com>
* add missing changes to callbacks
Co-authored-by: Adrian Wälchli <aedu.waelchli@gmail.com>
* reflect accelerator changes to lightning module
Co-authored-by: Adrian Wälchli <aedu.waelchli@gmail.com>
* clean cluster envs
Co-authored-by: Adrian Wälchli <aedu.waelchli@gmail.com>
* cleanup plugins
Co-authored-by: Adrian Wälchli <aedu.waelchli@gmail.com>
* add broadcasting
Co-authored-by: Adrian Wälchli <aedu.waelchli@gmail.com>
* yapf
* remove plugin connector
Co-authored-by: Adrian Wälchli <aedu.waelchli@gmail.com>
* plugins
* manual optimization
* update optimizer routing
* add rank to torchelastic
* fix memory mixed precision
* setstate on trainer for pickling in ddp spawn
* add predict method
* add back commented accelerator code
* adapt test for sync_batch_norm to new plugin
* fix deprecated tests
* fix ddp cpu choice when no num_processes are given
* yapf format
* skip a memory test that cannot pass anymore
* fix pickle error in spawn plugin
* x
* avoid
* x
* fix cyclic import in docs build
* add support for sharded
* update typing
* add sharded and sharded_spawn to distributed types
* make unwrap model default
* refactor LightningShardedDataParallel similar to LightningDistributedDataParallel
* update sharded spawn to reflect changes
* update sharded to reflect changes
* Merge 1.1.5 changes
* fix merge
* fix merge
* yapf isort
* fix merge
* yapf isort
* fix indentation in test
* copy over reinit scheduler implementation from dev1.2
* fix apex tracking calls with dev_debugger
* reduce diff to dev1.2, clean up
* fix trainer config test when gpus>0 and num_processes >0 and ddp_cpu
* sort plugin tests legacy/new
* fix error handling for amp on cpu
* fix merge
fix merge
fix merge
* [Feat] Resolve manual_backward (#5837)
* resolve manual_backward
* resolve flake8
* update
* resolve for ddp_spawn
* resolve flake8
* resolve flake8
* resolve flake8
Co-authored-by: Ubuntu <ubuntu@ip-172-31-88-60.ec2.internal>
* fix tests/accelerator tests on cpu
* [BugFix] Resolve manual optimization (#5852)
* resolve manual_optimization
* update
* update
Co-authored-by: Ubuntu <ubuntu@ip-172-31-88-60.ec2.internal>
* Remove copy trainer parameters to happen earlier within the loop and add safe guard to get ref model (#5856)
* resovle a bug
* Accelerator refactor sharded rpc (#5854)
* rpc branch
* merge
* update handling of rpc
* make devices etc. Optional in RPC
* set devices etc. later if necessary
* remove devices from sequential
* make devices optional in rpc
* fix import
* uncomment everything
* fix cluster selection
Co-authored-by: Ubuntu <ubuntu@ip-172-31-88-60.ec2.internal>
* resolve bug
* fix assert in rpc test
* resolve a test
* fix docs compilation
* accelerator refactor - fix for sharded parity test (#5866)
* fix memory issue with ddp_spawn
* x
x
x
x
x
x
x
x
x
* x
* Remove DDP2 as this does not apply
* Add missing pre optimizer hook to ensure lambda closure is called
* fix apex docstring
* [accelerator][BugFix] Resolve some test for 1 gpu (#5863)
* update
* revert init
* resolve a bug
* update
* resolve flake8
* update
* update
* update
* revert init
* resolve a bug
* update
* resolve flake8
* update
* update
* update
* update
* update
* revert init
* resolve a bug
* update
* resolve flake8
* update
* update
* update
* revert init
* update
* resolve flake8
* update
* update
* update
* update
* update
* all_gather
* update
* make plugins work, add misconfig for RPC
* update
* update
* remove breaking test
* resolve some tests
* resolve flake8
* revert to ddp_spawn
Co-authored-by: root <root@ip-172-31-88-60.ec2.internal>
Co-authored-by: Ubuntu <ubuntu@ip-172-31-88-60.ec2.internal>
Co-authored-by: Justus Schock <justus.schock@rwth-aachen.de>
* yapf isort
* resolve flake8
* fix apex doctests
* fix apex doctests 2
* resolve docs
* update drone
* clean env
* update
* update
* update
* update
* merge
* Fix RPC related tests, clean out old API, update for new accelerator API [skip ci] (#5881)
* Fix RPC related tests, clean out old API, update for new accelerator API
* Move tests out of legacy folder, update paths and names
* Update test_remove_1-4.py
* Expose properties for tpu cores/gpus/num_gpus
* Add root GPU property
* Move properties to properties.py
* move tests that were previously in drone
* Fix root GPU property (#5908)
* Move root GPU to property, remove horovod set as this is handled in horovod plugin, ensure we mock correctly to set GPU accelerator
* Add missing tests back
* fix best model path transfer when no checkpoint callback available
* Fix setup hook order [wip] (#5858)
* Call trainer setup hook before accelerator setup
* Add test case
* add new test
* typo
* fix callback order in test
Co-authored-by: tchaton <thomas@grid.ai>
Co-authored-by: Adrian Wälchli <aedu.waelchli@gmail.com>
* rename ddp sequential -> rpc sequential for special test
* revert
* fix stupid merge problem
* Use property in connector for sampler (#5913)
* merge the import conflicts
* fix spawning of processes in slurm
* [wip] Fix some bugs for TPU [skip ci] (#5878)
* fixed for single tpu
* fixed spawn
* fixed spawn
* update
* update
* wip
* resolve bugs
* resolve bug
* update on comment
* removed decorator
* resolve comments
* set to 4
* update
* update
* need cleaning
* update
* update
* update
* resolve flake8
* resolve bugs
* exclude broadcast
* resolve bugs
* change test
* update
* update
* skip if meet fails
* properly raise trace
* update
* add catch
* wrap test
* resolve typo
* update
* typo
Co-authored-by: Lezwon Castelino <lezwon@gmail.com>
Co-authored-by: Your Name <you@example.com>
* resolve some tests
* update
* fix imports
* update
* resolve flake8
* update azure pipeline
* skip a sharded test on cpu that requires a gpu
* resolve tpus
* resolve bug
* resolve flake8
* update
* updat utils
* revert permission change on files
* suggestions from carlos
Co-authored-by: Carlos Mocholí <carlossmocholi@gmail.com>
* remove unrelated formatting changes
* remove incomplete comment
* Update pytorch_lightning/accelerators/__init__.py
Co-authored-by: Carlos Mocholí <carlossmocholi@gmail.com>
* remove unrelated formatting change
* add types
* warn 1.7 ddp manual backward only if ddp kwarg unset
* yapf + isort
* pep8 unused imports
* fix cyclic import in docs
* Apply suggestions from code review
* typer in accelerator.py
* typo
* Apply suggestions from code review
* formatting
* update on comments
* update typo
* Update pytorch_lightning/trainer/properties.py
Co-authored-by: Adrian Wälchli <aedu.waelchli@gmail.com>
* update
* suggestion from code review
* suggestion from code review
Co-authored-by: Adrian Wälchli <aedu.waelchli@gmail.com>
Co-authored-by: SeanNaren <sean@grid.ai>
Co-authored-by: Jirka Borovec <jirka.borovec@seznam.cz>
Co-authored-by: chaton <thomas@grid.ai>
Co-authored-by: Ubuntu <ubuntu@ip-172-31-88-60.ec2.internal>
Co-authored-by: Sean Naren <sean.narenthiran@gmail.com>
Co-authored-by: root <root@ip-172-31-88-60.ec2.internal>
Co-authored-by: Lezwon Castelino <lezwon@gmail.com>
Co-authored-by: Your Name <you@example.com>
Co-authored-by: Carlos Mocholí <carlossmocholi@gmail.com>
Co-authored-by: Jirka Borovec <Borda@users.noreply.github.com>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2021-02-12 20:48:56 +00:00
|
|
|
def optimizer_zero_grad(self, current_epoch: int, batch_idx: int, optimizer: Optimizer, opt_idx: int) -> None:
|
2021-09-06 12:49:09 +00:00
|
|
|
"""Zeros all model parameter's gradients."""
|
2021-01-30 19:55:28 +00:00
|
|
|
model_ref = self.lightning_module
|
|
|
|
model_ref.optimizer_zero_grad(current_epoch, batch_idx, optimizer, opt_idx)
|
|
|
|
|
2021-07-26 11:37:35 +00:00
|
|
|
def setup_optimizers(self, trainer: "pl.Trainer") -> None:
|
2021-09-06 12:49:09 +00:00
|
|
|
"""Creates optimizers and schedulers.
|
2021-01-30 19:55:28 +00:00
|
|
|
|
|
|
|
Args:
|
|
|
|
trainer: the Trainer, these optimizers should be connected to
|
|
|
|
"""
|
2021-05-04 10:50:56 +00:00
|
|
|
if trainer.state.fn not in (TrainerFn.FITTING, TrainerFn.TUNING):
|
2021-01-30 19:55:28 +00:00
|
|
|
return
|
2021-02-17 20:23:42 +00:00
|
|
|
optimizers, lr_schedulers, optimizer_frequencies = self.training_type_plugin.init_optimizers(
|
|
|
|
trainer=trainer, model=self.lightning_module
|
|
|
|
)
|
2021-01-30 19:55:28 +00:00
|
|
|
self.optimizers = optimizers
|
|
|
|
self.lr_schedulers = lr_schedulers
|
|
|
|
self.optimizer_frequencies = optimizer_frequencies
|
|
|
|
|
2021-08-04 15:43:34 +00:00
|
|
|
def setup_training_type_plugin(self) -> None:
|
2021-03-18 21:33:39 +00:00
|
|
|
"""Attaches the training type plugin to the accelerator."""
|
2021-08-04 15:43:34 +00:00
|
|
|
self.training_type_plugin.setup()
|
2021-01-30 19:55:28 +00:00
|
|
|
|
2021-05-13 17:33:55 +00:00
|
|
|
def setup_precision_plugin(self) -> None:
|
2021-09-06 12:49:09 +00:00
|
|
|
"""Attaches the precision plugin to the accelerator."""
|
2021-05-13 17:33:55 +00:00
|
|
|
model, optimizers, schedulers = self.precision_plugin.connect(self.model, self.optimizers, self.lr_schedulers)
|
2021-01-30 19:55:28 +00:00
|
|
|
self.model = model
|
|
|
|
self.optimizers = optimizers
|
2021-07-08 14:02:09 +00:00
|
|
|
self.lr_schedulers = schedulers
|
2021-01-30 19:55:28 +00:00
|
|
|
|
|
|
|
@property
|
|
|
|
def amp_backend(self) -> Optional[LightningEnum]:
|
2021-01-31 18:12:02 +00:00
|
|
|
if isinstance(self.precision_plugin, ApexMixedPrecisionPlugin):
|
|
|
|
return AMPType.APEX
|
2021-06-28 09:57:41 +00:00
|
|
|
if isinstance(self.precision_plugin, NativeMixedPrecisionPlugin):
|
2021-01-31 18:12:02 +00:00
|
|
|
return AMPType.NATIVE
|
2021-02-01 13:34:59 +00:00
|
|
|
return None
|
2021-01-30 19:55:28 +00:00
|
|
|
|
|
|
|
@property
|
2021-02-26 13:27:16 +00:00
|
|
|
def precision(self) -> Union[str, int]:
|
2021-01-30 19:55:28 +00:00
|
|
|
return self.precision_plugin.precision
|
|
|
|
|
|
|
|
@property
|
2021-07-26 11:37:35 +00:00
|
|
|
def scaler(self) -> Optional["GradScaler"]:
|
|
|
|
return getattr(self.precision_plugin, "scaler", None)
|
2021-01-30 19:55:28 +00:00
|
|
|
|
2021-04-15 16:48:16 +00:00
|
|
|
def optimizer_state(self, optimizer: Optimizer) -> Dict[str, Tensor]:
|
2021-09-06 12:49:09 +00:00
|
|
|
"""Returns state of an optimizer.
|
|
|
|
|
|
|
|
Allows for syncing/collating optimizer state from processes in custom plugins.
|
2021-01-30 19:55:28 +00:00
|
|
|
"""
|
2021-07-26 11:37:35 +00:00
|
|
|
return getattr(self.training_type_plugin, "optimizer_state", lambda x: x.state_dict())(optimizer)
|
2021-01-30 19:55:28 +00:00
|
|
|
|
2021-03-29 20:50:51 +00:00
|
|
|
@contextlib.contextmanager
|
2021-03-30 17:39:02 +00:00
|
|
|
def model_sharded_context(self) -> Generator[None, None, None]:
|
2021-09-06 12:49:09 +00:00
|
|
|
"""Provide hook to create modules in a distributed aware context. This is useful for when we'd like to.
|
|
|
|
|
2021-03-29 20:50:51 +00:00
|
|
|
shard the model instantly - useful for extremely large models. Can save memory and
|
|
|
|
initialization time.
|
|
|
|
|
2021-04-10 06:55:07 +00:00
|
|
|
Returns:
|
|
|
|
Model parallel context.
|
2021-03-29 20:50:51 +00:00
|
|
|
"""
|
|
|
|
with self.training_type_plugin.model_sharded_context():
|
|
|
|
yield
|
|
|
|
|
2021-09-27 04:09:16 +00:00
|
|
|
def get_device_stats(self, device: Union[str, torch.device]) -> Dict[str, Any]:
|
|
|
|
"""Gets stats for a given device.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
device: device for which to get stats
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
Dictionary of device stats
|
|
|
|
"""
|
|
|
|
raise NotImplementedError
|
|
|
|
|
2021-06-07 12:06:41 +00:00
|
|
|
def on_train_start(self) -> None:
|
|
|
|
"""Called when train begins."""
|
|
|
|
return self.training_type_plugin.on_train_start()
|
|
|
|
|
2021-10-29 20:31:32 +00:00
|
|
|
@staticmethod
|
|
|
|
@abstractmethod
|
|
|
|
def auto_device_count() -> int:
|
|
|
|
"""Get the devices when set to auto."""
|