2020-10-13 11:18:07 +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.
|
2020-10-04 03:39:17 +00:00
|
|
|
import os
|
2020-09-30 12:33:01 +00:00
|
|
|
from enum import Enum
|
2020-11-05 17:52:02 +00:00
|
|
|
from typing import Any, Optional, Union
|
2020-09-28 23:09:04 +00:00
|
|
|
|
|
|
|
import torch
|
2020-11-12 17:18:09 +00:00
|
|
|
from torch.optim import Optimizer
|
2020-09-28 23:09:04 +00:00
|
|
|
|
2020-11-12 17:18:09 +00:00
|
|
|
from pytorch_lightning.utilities import AMPType
|
2020-09-28 23:09:04 +00:00
|
|
|
from pytorch_lightning.utilities.apply_func import move_data_to_device
|
2020-09-05 21:01:46 +00:00
|
|
|
from pytorch_lightning.utilities.exceptions import MisconfigurationException
|
2020-10-01 05:21:38 +00:00
|
|
|
from pytorch_lightning.utilities.parsing import AttributeDict
|
2020-10-04 03:39:17 +00:00
|
|
|
import torch.distributed as torch_distrib
|
|
|
|
from pytorch_lightning import _logger as log
|
2020-09-05 22:27:28 +00:00
|
|
|
|
2020-11-05 17:52:02 +00:00
|
|
|
if torch.distributed.is_available():
|
|
|
|
from torch.distributed import ReduceOp
|
|
|
|
else:
|
|
|
|
class ReduceOp:
|
|
|
|
SUM = None
|
|
|
|
|
2020-08-24 11:02:06 +00:00
|
|
|
|
|
|
|
class Accelerator(object):
|
|
|
|
|
2020-10-22 09:15:51 +00:00
|
|
|
def __init__(self, trainer=None, cluster_environment=None, ddp_plugin=None):
|
2020-08-24 11:02:06 +00:00
|
|
|
self.trainer = trainer
|
2020-10-10 13:21:08 +00:00
|
|
|
self.nickname = None
|
2020-10-04 12:48:46 +00:00
|
|
|
self.cluster_environment = cluster_environment
|
2020-10-01 05:21:38 +00:00
|
|
|
self.dist = AttributeDict(rank=0, device=None)
|
2020-10-22 09:15:51 +00:00
|
|
|
self.ddp_plugin = ddp_plugin
|
2020-10-10 13:21:08 +00:00
|
|
|
|
|
|
|
if trainer is not None:
|
|
|
|
self.train_loop = self.trainer.train
|
|
|
|
self.validation_loop = self.trainer.run_evaluation
|
|
|
|
self.test_loop = self.trainer.run_evaluation
|
2020-08-24 11:02:06 +00:00
|
|
|
|
2020-08-26 23:10:24 +00:00
|
|
|
def setup(self, model):
|
2020-08-26 22:43:28 +00:00
|
|
|
pass
|
|
|
|
|
2020-08-26 18:20:38 +00:00
|
|
|
def teardown(self):
|
2020-10-24 20:55:49 +00:00
|
|
|
# Ensure if necessary all processes are finished
|
|
|
|
self.barrier()
|
2020-08-26 18:20:38 +00:00
|
|
|
|
2020-10-15 21:02:50 +00:00
|
|
|
def barrier(self, name: Optional[str] = None):
|
2020-09-11 01:58:47 +00:00
|
|
|
pass
|
|
|
|
|
2020-10-01 05:21:38 +00:00
|
|
|
def broadcast(self, obj, src=0):
|
|
|
|
return obj
|
|
|
|
|
2020-09-11 01:58:47 +00:00
|
|
|
def train_or_test(self):
|
|
|
|
if self.trainer.testing:
|
|
|
|
results = self.trainer.run_test()
|
|
|
|
else:
|
|
|
|
results = self.trainer.train()
|
|
|
|
return results
|
|
|
|
|
2020-08-24 11:02:06 +00:00
|
|
|
def batch_to_device(self, batch: Any, device: torch.device):
|
|
|
|
model = self.trainer.get_model()
|
|
|
|
if model is not None:
|
|
|
|
return model.transfer_batch_to_device(batch, device)
|
|
|
|
return move_data_to_device(batch, device)
|
2020-08-24 21:50:47 +00:00
|
|
|
|
|
|
|
def training_step_end(self, output):
|
|
|
|
return output
|
|
|
|
|
|
|
|
def test_step_end(self, output):
|
|
|
|
return output
|
|
|
|
|
|
|
|
def validation_step_end(self, output):
|
|
|
|
return output
|
2020-08-25 01:53:56 +00:00
|
|
|
|
|
|
|
def process_dataloader(self, dataloader):
|
|
|
|
return dataloader
|
2020-09-05 12:55:22 +00:00
|
|
|
|
2020-10-11 00:05:05 +00:00
|
|
|
def backward(self, closure_loss, optimizer, opt_idx, *args, **kwargs):
|
2020-09-05 12:55:22 +00:00
|
|
|
if self.trainer.precision == 16:
|
2020-10-11 00:05:05 +00:00
|
|
|
closure_loss = self.trainer.precision_connector.backend.backward(
|
|
|
|
closure_loss, optimizer, opt_idx, *args, **kwargs
|
|
|
|
)
|
2020-10-10 15:05:57 +00:00
|
|
|
else:
|
|
|
|
# do backward pass
|
2020-10-21 18:34:29 +00:00
|
|
|
model = self.trainer.get_model()
|
|
|
|
model.backward(closure_loss, optimizer, opt_idx, *args, **kwargs)
|
2020-10-10 15:05:57 +00:00
|
|
|
|
|
|
|
# once backward has been applied, release graph
|
|
|
|
closure_loss = closure_loss.detach()
|
2020-09-05 12:55:22 +00:00
|
|
|
return closure_loss
|
2020-09-05 21:01:46 +00:00
|
|
|
|
2020-11-12 19:22:06 +00:00
|
|
|
def optimizer_step(self, optimizer, batch_idx, opt_idx, lambda_closure, *args, **kwargs):
|
2020-09-05 21:01:46 +00:00
|
|
|
model_ref = self.trainer.get_model()
|
|
|
|
is_lbfgs = isinstance(optimizer, torch.optim.LBFGS)
|
2020-11-10 19:44:51 +00:00
|
|
|
using_native_amp = self.trainer.amp_backend == AMPType.NATIVE
|
|
|
|
automatic_optimization = self.trainer.train_loop.automatic_optimization
|
2020-09-05 21:01:46 +00:00
|
|
|
|
|
|
|
# native amp + lbfgs is a no go right now
|
2020-11-10 19:44:51 +00:00
|
|
|
if using_native_amp and is_lbfgs:
|
2020-09-05 21:01:46 +00:00
|
|
|
raise MisconfigurationException(
|
|
|
|
'native PyTorch amp and lbfgs are not compatible.'
|
|
|
|
' To request, please file a Github issue in PyTorch and tag @mcarilli')
|
|
|
|
|
|
|
|
# model hook
|
|
|
|
model_ref.optimizer_step(
|
2020-11-02 22:13:34 +00:00
|
|
|
epoch=self.trainer.current_epoch,
|
|
|
|
batch_idx=batch_idx,
|
|
|
|
optimizer=optimizer,
|
|
|
|
optimizer_idx=opt_idx,
|
|
|
|
optimizer_closure=lambda_closure,
|
|
|
|
on_tpu=False, # TPUAccelerator class sets this as True
|
2020-11-10 19:44:51 +00:00
|
|
|
using_native_amp=using_native_amp,
|
2020-11-12 19:22:06 +00:00
|
|
|
using_lbfgs=is_lbfgs,
|
|
|
|
*args,
|
|
|
|
**kwargs,
|
2020-09-05 21:01:46 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
# scale when native amp
|
2020-11-10 19:44:51 +00:00
|
|
|
if automatic_optimization and using_native_amp:
|
2020-09-05 21:01:46 +00:00
|
|
|
self.trainer.scaler.update()
|
|
|
|
|
|
|
|
def optimizer_zero_grad(self, batch_idx, optimizer, opt_idx):
|
|
|
|
model_ref = self.trainer.get_model()
|
|
|
|
model_ref.optimizer_zero_grad(self.trainer.current_epoch, batch_idx, optimizer, opt_idx)
|
2020-09-05 22:27:28 +00:00
|
|
|
|
2020-10-11 17:12:35 +00:00
|
|
|
def clip_gradients(self, optimizer, clip_val=None):
|
|
|
|
# use the trainer's clip val if none passed
|
|
|
|
grad_clip_val = self.trainer.gradient_clip_val
|
|
|
|
if clip_val is not None:
|
|
|
|
grad_clip_val = clip_val
|
|
|
|
grad_clip_val = float(grad_clip_val)
|
2020-09-05 22:27:28 +00:00
|
|
|
|
2020-10-11 17:12:35 +00:00
|
|
|
if grad_clip_val <= 0:
|
2020-09-05 22:27:28 +00:00
|
|
|
return
|
2020-11-12 17:18:09 +00:00
|
|
|
self._clip_gradients(optimizer, grad_clip_val)
|
2020-09-05 22:27:28 +00:00
|
|
|
|
2020-11-12 17:18:09 +00:00
|
|
|
def _clip_gradients(self, optimizer: Optimizer, grad_clip_val: Union[float, int], norm_type: float = 2.0):
|
|
|
|
if self.trainer.amp_backend:
|
|
|
|
self.trainer.precision_connector.backend.clip_gradients(grad_clip_val, optimizer, norm_type)
|
2020-09-05 22:27:28 +00:00
|
|
|
else:
|
2020-11-12 17:18:09 +00:00
|
|
|
model = self.trainer.get_model()
|
|
|
|
torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=grad_clip_val, norm_type=norm_type)
|
2020-09-06 21:50:47 +00:00
|
|
|
|
2020-10-08 02:27:36 +00:00
|
|
|
def on_train_epoch_end(self, outputs):
|
2020-09-06 21:50:47 +00:00
|
|
|
pass
|
2020-09-11 14:56:21 +00:00
|
|
|
|
2020-10-01 12:15:23 +00:00
|
|
|
def on_train_end(self):
|
|
|
|
pass
|
|
|
|
|
2020-09-11 14:56:21 +00:00
|
|
|
def early_stopping_should_stop(self, pl_module):
|
|
|
|
return self.trainer.should_stop
|
2020-09-28 23:09:04 +00:00
|
|
|
|
|
|
|
def setup_optimizers(self, model):
|
|
|
|
if self.trainer.testing is True:
|
|
|
|
return
|
|
|
|
|
|
|
|
optimizers, lr_schedulers, optimizer_frequencies = self.trainer.init_optimizers(model)
|
|
|
|
self.trainer.optimizers = optimizers
|
|
|
|
self.trainer.lr_schedulers = lr_schedulers
|
|
|
|
self.trainer.optimizer_frequencies = optimizer_frequencies
|
2020-09-30 12:33:01 +00:00
|
|
|
|
2020-10-04 03:39:17 +00:00
|
|
|
def init_ddp_connection(
|
2020-11-12 17:18:09 +00:00
|
|
|
self, global_rank: int, world_size: int, is_slurm_managing_tasks: bool = True
|
2020-10-04 03:39:17 +00:00
|
|
|
) -> None:
|
2020-10-10 12:09:29 +00:00
|
|
|
os.environ["MASTER_ADDR"] = str(self.cluster_environment.master_address())
|
|
|
|
os.environ["MASTER_PORT"] = str(self.cluster_environment.master_port())
|
|
|
|
os.environ["WORLD_SIZE"] = str(self.cluster_environment.world_size())
|
2020-10-04 03:39:17 +00:00
|
|
|
torch_backend = "nccl" if self.trainer.on_gpu else "gloo"
|
|
|
|
|
|
|
|
if not torch.distributed.is_initialized():
|
|
|
|
log.info(
|
|
|
|
f"initializing ddp: GLOBAL_RANK: {global_rank}, MEMBER: {global_rank + 1}/{world_size}"
|
|
|
|
)
|
|
|
|
torch_distrib.init_process_group(
|
|
|
|
torch_backend, rank=global_rank, world_size=world_size
|
|
|
|
)
|
|
|
|
|
2020-11-05 17:52:02 +00:00
|
|
|
def sync_tensor(self,
|
|
|
|
tensor: Union[torch.Tensor],
|
|
|
|
group: Optional[Any] = None,
|
|
|
|
reduce_op: Optional[Union[ReduceOp, str]] = None) -> torch.Tensor:
|
|
|
|
"""
|
|
|
|
Function to reduce a tensor from several distributed processes to one aggregated tensor.
|
2020-11-08 22:24:41 +00:00
|
|
|
|
2020-11-05 17:52:02 +00:00
|
|
|
Args:
|
|
|
|
tensor: the tensor to sync and reduce
|
|
|
|
group: the process group to gather results from. Defaults to all processes (world)
|
|
|
|
reduce_op: the reduction operation. Defaults to sum.
|
|
|
|
Can also be a string of 'avg', 'mean' to calculate the mean during reduction.
|
2020-11-08 22:24:41 +00:00
|
|
|
|
2020-11-05 17:52:02 +00:00
|
|
|
Return:
|
|
|
|
reduced value
|
|
|
|
"""
|
|
|
|
raise NotImplementedError()
|
|
|
|
|
2020-10-13 20:47:23 +00:00
|
|
|
def __getstate__(self):
|
|
|
|
return {
|
|
|
|
'trainer': self.trainer,
|
|
|
|
'nickname': self.nickname,
|
|
|
|
'cluster_environment': self.cluster_environment,
|
2020-10-22 09:15:51 +00:00
|
|
|
'dist': self.dist,
|
|
|
|
'ddp_plugin': self.ddp_plugin
|
2020-10-13 20:47:23 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
def __setstate__(self, d):
|
|
|
|
self.trainer = d['trainer']
|
|
|
|
self.nickname = d['nickname']
|
|
|
|
self.cluster_environment = d['cluster_environment']
|
|
|
|
self.dist = d['dist']
|
2020-10-22 09:15:51 +00:00
|
|
|
self.ddp_plugin = d['ddp_plugin']
|
2020-10-13 20:47:23 +00:00
|
|
|
|
2020-09-30 12:33:01 +00:00
|
|
|
|
2020-10-02 10:18:44 +00:00
|
|
|
# TODO: allow user to compare with string even internaly we shall use these Enum to prevent typos...
|
2020-09-30 12:33:01 +00:00
|
|
|
class BackendType(Enum):
|
|
|
|
DP = 'dp'
|
|
|
|
DDP = 'ddp'
|
|
|
|
DDP2 = 'ddp2'
|
|
|
|
DDP_SPAWN = 'ddp_spawn'
|
2020-10-02 10:18:44 +00:00
|
|
|
# decuple distrib and device
|
2020-09-30 12:33:01 +00:00
|
|
|
DDP_CPU = 'ddp_cpu'
|
|
|
|
HOROVOD = 'horovod'
|
2020-10-02 10:18:44 +00:00
|
|
|
# this is rather device
|
|
|
|
TPU = 'tpu'
|