2021-05-22 20:19:24 +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-08-23 15:29:07 +00:00
|
|
|
import os
|
2022-06-21 13:49:57 +00:00
|
|
|
from datetime import timedelta
|
2021-06-28 20:08:10 +00:00
|
|
|
from unittest import mock
|
|
|
|
|
2021-08-23 15:29:07 +00:00
|
|
|
import pytest
|
2021-05-22 20:19:24 +00:00
|
|
|
import torch
|
2021-06-28 20:08:10 +00:00
|
|
|
from torch.nn.parallel import DistributedDataParallel
|
2021-05-22 20:19:24 +00:00
|
|
|
|
2022-09-12 10:20:08 +00:00
|
|
|
from lightning_lite.plugins.environments import ClusterEnvironment, LightningEnvironment
|
2022-09-29 16:45:27 +00:00
|
|
|
from lightning_lite.strategies.fairscale import _FAIRSCALE_AVAILABLE
|
2021-09-02 02:23:59 +00:00
|
|
|
from pytorch_lightning import LightningModule, Trainer
|
2022-06-14 23:53:54 +00:00
|
|
|
from pytorch_lightning.demos.boring_classes import BoringModel
|
2021-12-23 07:26:28 +00:00
|
|
|
from pytorch_lightning.strategies import DDPStrategy
|
2021-09-02 02:23:59 +00:00
|
|
|
from pytorch_lightning.trainer.states import TrainerFn
|
2022-09-01 16:08:40 +00:00
|
|
|
from pytorch_lightning.utilities.imports import _TORCH_GREATER_EQUAL_1_10
|
2022-06-15 22:10:49 +00:00
|
|
|
from tests_pytorch.helpers.runif import RunIf
|
2021-05-22 20:19:24 +00:00
|
|
|
|
2022-08-26 07:58:21 +00:00
|
|
|
if _FAIRSCALE_AVAILABLE:
|
|
|
|
from fairscale.optim import OSS
|
|
|
|
if _TORCH_GREATER_EQUAL_1_10:
|
|
|
|
from torch.distributed.optim import ZeroRedundancyOptimizer
|
|
|
|
|
2021-05-22 20:19:24 +00:00
|
|
|
|
|
|
|
class BoringModelGPU(BoringModel):
|
|
|
|
def on_train_start(self) -> None:
|
|
|
|
# make sure that the model is on GPU when training
|
2021-12-22 02:11:43 +00:00
|
|
|
assert self.device == torch.device(f"cuda:{self.trainer.strategy.local_rank}")
|
2021-05-22 20:19:24 +00:00
|
|
|
self.start_cuda_memory = torch.cuda.memory_allocated()
|
|
|
|
|
|
|
|
|
2022-05-24 12:54:05 +00:00
|
|
|
@RunIf(min_cuda_gpus=2, skip_windows=True, standalone=True)
|
2021-05-22 20:19:24 +00:00
|
|
|
def test_ddp_with_2_gpus():
|
2022-02-17 01:27:51 +00:00
|
|
|
"""Tests if device is set correctly when training and after teardown for DDPStrategy."""
|
2022-04-20 18:57:40 +00:00
|
|
|
trainer = Trainer(
|
|
|
|
accelerator="gpu",
|
|
|
|
devices=2,
|
|
|
|
strategy="ddp",
|
|
|
|
fast_dev_run=True,
|
|
|
|
enable_progress_bar=False,
|
|
|
|
enable_model_summary=False,
|
|
|
|
)
|
2022-03-29 12:09:41 +00:00
|
|
|
# assert strategy attributes for device setting
|
2021-12-22 02:11:43 +00:00
|
|
|
assert isinstance(trainer.strategy, DDPStrategy)
|
|
|
|
local_rank = trainer.strategy.local_rank
|
|
|
|
assert trainer.strategy.root_device == torch.device(f"cuda:{local_rank}")
|
2021-05-22 20:19:24 +00:00
|
|
|
|
|
|
|
model = BoringModelGPU()
|
|
|
|
|
|
|
|
trainer.fit(model)
|
|
|
|
|
|
|
|
# assert after training, model is moved to CPU and memory is deallocated
|
|
|
|
assert model.device == torch.device("cpu")
|
|
|
|
cuda_memory = torch.cuda.memory_allocated()
|
|
|
|
assert cuda_memory < model.start_cuda_memory
|
2021-06-28 20:08:10 +00:00
|
|
|
|
|
|
|
|
|
|
|
class BarrierModel(BoringModel):
|
|
|
|
def setup(self, stage=None):
|
2021-12-22 02:11:43 +00:00
|
|
|
assert not isinstance(self.trainer.strategy.model, DistributedDataParallel)
|
|
|
|
self.trainer.strategy.barrier("barrier before model is wrapped")
|
2021-06-28 20:08:10 +00:00
|
|
|
|
|
|
|
def on_train_start(self):
|
2021-12-22 02:11:43 +00:00
|
|
|
assert isinstance(self.trainer.strategy.model, DistributedDataParallel)
|
|
|
|
self.trainer.strategy.barrier("barrier after model is wrapped")
|
2021-06-28 20:08:10 +00:00
|
|
|
|
|
|
|
|
2022-05-24 12:54:05 +00:00
|
|
|
@RunIf(min_cuda_gpus=4, standalone=True)
|
2021-06-28 20:08:10 +00:00
|
|
|
@mock.patch("torch.distributed.barrier")
|
|
|
|
def test_ddp_barrier_non_consecutive_device_ids(barrier_mock, tmpdir):
|
2021-07-26 11:37:35 +00:00
|
|
|
"""Test correct usage of barriers when device ids do not start at 0 or are not consecutive."""
|
2021-06-28 20:08:10 +00:00
|
|
|
model = BoringModel()
|
|
|
|
gpus = [1, 3]
|
2022-04-20 18:57:40 +00:00
|
|
|
trainer = Trainer(
|
|
|
|
default_root_dir=tmpdir,
|
|
|
|
max_steps=1,
|
|
|
|
accelerator="gpu",
|
|
|
|
devices=gpus,
|
|
|
|
strategy="ddp",
|
|
|
|
enable_progress_bar=False,
|
|
|
|
enable_model_summary=False,
|
|
|
|
)
|
2021-06-28 20:08:10 +00:00
|
|
|
trainer.fit(model)
|
|
|
|
barrier_mock.assert_any_call(device_ids=[gpus[trainer.local_rank]])
|
2021-08-23 15:29:07 +00:00
|
|
|
|
|
|
|
|
|
|
|
@mock.patch.dict(os.environ, {"LOCAL_RANK": "1"})
|
|
|
|
def test_incorrect_ddp_script_spawning(tmpdir):
|
|
|
|
"""Test an error message when user accidentally instructs Lightning to spawn children processes on rank > 0."""
|
|
|
|
|
|
|
|
class WronglyImplementedEnvironment(LightningEnvironment):
|
2021-10-25 23:15:41 +00:00
|
|
|
@property
|
|
|
|
def creates_processes_externally(self):
|
2021-08-23 15:29:07 +00:00
|
|
|
# returning false no matter what means Lightning would spawn also on ranks > 0 new processes
|
|
|
|
return False
|
|
|
|
|
|
|
|
model = BoringModel()
|
|
|
|
trainer = Trainer(
|
|
|
|
default_root_dir=tmpdir,
|
2021-10-16 15:10:25 +00:00
|
|
|
strategy="ddp",
|
2022-03-27 16:13:48 +00:00
|
|
|
accelerator="cpu",
|
|
|
|
devices=2,
|
2021-10-16 15:10:25 +00:00
|
|
|
plugins=[WronglyImplementedEnvironment()],
|
2021-08-23 15:29:07 +00:00
|
|
|
)
|
|
|
|
with pytest.raises(
|
|
|
|
RuntimeError, match="Lightning attempted to launch new distributed processes with `local_rank > 0`."
|
|
|
|
):
|
|
|
|
trainer.fit(model)
|
2021-09-02 02:23:59 +00:00
|
|
|
|
|
|
|
|
|
|
|
@RunIf(skip_windows=True)
|
|
|
|
def test_ddp_configure_ddp():
|
2021-12-21 08:55:51 +00:00
|
|
|
"""Tests with ddp strategy."""
|
2021-09-02 02:23:59 +00:00
|
|
|
model = BoringModel()
|
2021-12-21 08:55:51 +00:00
|
|
|
ddp_strategy = DDPStrategy()
|
2021-09-02 02:23:59 +00:00
|
|
|
trainer = Trainer(
|
|
|
|
max_epochs=1,
|
2021-12-21 08:55:51 +00:00
|
|
|
strategy=ddp_strategy,
|
2021-09-02 02:23:59 +00:00
|
|
|
)
|
|
|
|
# test wrap the model if fitting
|
|
|
|
trainer.state.fn = TrainerFn.FITTING
|
2021-12-22 02:11:43 +00:00
|
|
|
trainer.strategy.connect(model)
|
2021-09-02 02:23:59 +00:00
|
|
|
trainer.lightning_module.trainer = trainer
|
2021-12-22 02:11:43 +00:00
|
|
|
trainer.strategy.setup_environment()
|
2021-09-02 02:23:59 +00:00
|
|
|
assert isinstance(trainer.model, LightningModule)
|
2021-12-22 02:11:43 +00:00
|
|
|
trainer.strategy.setup(trainer)
|
2021-12-21 08:55:51 +00:00
|
|
|
# in DDPStrategy configure_ddp(), model wrapped by DistributedDataParallel
|
2021-09-02 02:23:59 +00:00
|
|
|
assert isinstance(trainer.model, DistributedDataParallel)
|
|
|
|
|
2022-03-03 18:30:24 +00:00
|
|
|
ddp_strategy = DDPStrategy()
|
2021-09-02 02:23:59 +00:00
|
|
|
trainer = Trainer(
|
|
|
|
max_epochs=1,
|
2021-12-21 08:55:51 +00:00
|
|
|
strategy=ddp_strategy,
|
2021-09-02 02:23:59 +00:00
|
|
|
)
|
2022-03-12 03:52:59 +00:00
|
|
|
# test do not wrap the model if TrainerFn is not fitting
|
2021-12-20 16:41:22 +00:00
|
|
|
trainer.state.fn = TrainerFn.VALIDATING
|
2021-12-22 02:11:43 +00:00
|
|
|
trainer.strategy.connect(model)
|
2021-12-20 16:41:22 +00:00
|
|
|
trainer.lightning_module.trainer = trainer
|
2021-12-22 02:11:43 +00:00
|
|
|
trainer.strategy.setup_environment()
|
|
|
|
trainer.strategy.setup(trainer)
|
2021-12-21 08:55:51 +00:00
|
|
|
# in DDPStrategy configure_ddp(), model are still LightningModule
|
2021-09-02 02:23:59 +00:00
|
|
|
assert isinstance(trainer.model, LightningModule)
|
2022-03-12 03:52:59 +00:00
|
|
|
|
|
|
|
|
2022-05-24 12:54:05 +00:00
|
|
|
@RunIf(min_cuda_gpus=1)
|
2022-10-13 13:29:50 +00:00
|
|
|
@pytest.mark.parametrize("trainer_fn", (TrainerFn.VALIDATING, TrainerFn.TESTING, TrainerFn.PREDICTING))
|
2022-03-12 03:52:59 +00:00
|
|
|
def test_ddp_dont_configure_sync_batchnorm(trainer_fn):
|
|
|
|
model = BoringModelGPU()
|
|
|
|
model.layer = torch.nn.BatchNorm1d(10)
|
|
|
|
ddp_strategy = DDPStrategy()
|
2022-03-27 16:13:48 +00:00
|
|
|
trainer = Trainer(accelerator="gpu", devices=1, strategy=ddp_strategy, sync_batchnorm=True)
|
2022-03-12 03:52:59 +00:00
|
|
|
trainer.state.fn = trainer_fn
|
|
|
|
trainer.strategy.connect(model)
|
|
|
|
trainer.lightning_module.trainer = trainer
|
|
|
|
trainer.strategy.setup_environment()
|
|
|
|
assert isinstance(trainer.model, LightningModule)
|
|
|
|
trainer.strategy.setup(trainer)
|
|
|
|
# because TrainerFn is not FITTING, model is not configured with sync batchnorm
|
|
|
|
assert not isinstance(trainer.strategy.model.layer, torch.nn.modules.batchnorm.SyncBatchNorm)
|
2022-03-24 09:40:34 +00:00
|
|
|
|
|
|
|
|
2022-06-01 10:25:05 +00:00
|
|
|
class CheckOptimizerDeviceModel(BoringModel):
|
|
|
|
def configure_optimizers(self):
|
|
|
|
assert all(param.device.type == "cuda" for param in self.parameters())
|
|
|
|
super().configure_optimizers()
|
|
|
|
|
|
|
|
|
|
|
|
@RunIf(min_cuda_gpus=1)
|
|
|
|
@pytest.mark.parametrize("strategy", ("ddp", "ddp_spawn"))
|
|
|
|
def test_model_parameters_on_device_for_optimizer(strategy):
|
|
|
|
"""Test that the strategy has moved the parameters to the device by the time the optimizer gets created."""
|
|
|
|
model = CheckOptimizerDeviceModel()
|
|
|
|
trainer = Trainer(
|
|
|
|
default_root_dir=os.getcwd(),
|
|
|
|
fast_dev_run=1,
|
|
|
|
accelerator="gpu",
|
|
|
|
devices=1,
|
|
|
|
strategy=strategy,
|
|
|
|
)
|
|
|
|
trainer.fit(model)
|
|
|
|
|
|
|
|
|
2022-03-24 09:40:34 +00:00
|
|
|
def test_configure_launcher_create_processes_externally():
|
|
|
|
class MyClusterEnvironment(ClusterEnvironment):
|
|
|
|
@property
|
|
|
|
def creates_processes_externally(self):
|
|
|
|
return True
|
|
|
|
|
|
|
|
@property
|
|
|
|
def main_address(self):
|
|
|
|
return ""
|
|
|
|
|
|
|
|
@property
|
|
|
|
def main_port(self):
|
|
|
|
return 8080
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
def detect():
|
|
|
|
return True
|
|
|
|
|
|
|
|
def world_size(self):
|
|
|
|
return 1
|
|
|
|
|
|
|
|
def set_world_size(self):
|
|
|
|
pass
|
|
|
|
|
|
|
|
def global_rank(self):
|
|
|
|
return 0
|
|
|
|
|
|
|
|
def set_global_rank(self):
|
|
|
|
pass
|
|
|
|
|
|
|
|
def local_rank(self):
|
|
|
|
return 0
|
|
|
|
|
|
|
|
def node_rank(self):
|
|
|
|
return 0
|
|
|
|
|
|
|
|
ddp_strategy = DDPStrategy(cluster_environment=MyClusterEnvironment())
|
|
|
|
assert ddp_strategy.launcher is None
|
|
|
|
ddp_strategy._configure_launcher()
|
|
|
|
assert ddp_strategy.launcher is None
|
2022-06-21 13:49:57 +00:00
|
|
|
|
|
|
|
|
|
|
|
@mock.patch("torch.distributed.init_process_group")
|
|
|
|
def test_ddp_strategy_set_timeout(mock_init_process_group):
|
2022-09-29 17:30:09 +00:00
|
|
|
"""Test that the timeout gets passed to the ``torch.distributed.init_process_group`` function."""
|
2022-06-21 13:49:57 +00:00
|
|
|
test_timedelta = timedelta(seconds=30)
|
|
|
|
model = BoringModel()
|
|
|
|
ddp_strategy = DDPStrategy(timeout=test_timedelta)
|
|
|
|
trainer = Trainer(
|
|
|
|
max_epochs=1,
|
|
|
|
strategy=ddp_strategy,
|
|
|
|
)
|
|
|
|
# test wrap the model if fitting
|
|
|
|
trainer.state.fn = TrainerFn.FITTING
|
|
|
|
trainer.strategy.connect(model)
|
|
|
|
trainer.lightning_module.trainer = trainer
|
|
|
|
trainer.strategy.setup_environment()
|
|
|
|
|
|
|
|
process_group_backend = trainer.strategy._get_process_group_backend()
|
|
|
|
global_rank = trainer.strategy.cluster_environment.global_rank()
|
|
|
|
world_size = trainer.strategy.cluster_environment.world_size()
|
|
|
|
mock_init_process_group.assert_called_with(
|
|
|
|
process_group_backend, rank=global_rank, world_size=world_size, timeout=test_timedelta
|
|
|
|
)
|
2022-08-26 07:58:21 +00:00
|
|
|
|
|
|
|
|
|
|
|
class BoringFairScaleOptimizerModel(BoringModel):
|
|
|
|
def configure_optimizers(self):
|
|
|
|
base_optimizer = torch.optim.SGD(self.layer.parameters(), lr=0.1)
|
|
|
|
return OSS(params=base_optimizer.param_groups, optim=type(base_optimizer), **base_optimizer.defaults)
|
|
|
|
|
|
|
|
|
2022-09-01 16:08:40 +00:00
|
|
|
@RunIf(min_cuda_gpus=2, fairscale=True)
|
2022-08-26 07:58:21 +00:00
|
|
|
@pytest.mark.parametrize("strategy", (pytest.param("ddp", marks=RunIf(standalone=True)), "ddp_spawn"))
|
|
|
|
def test_ddp_strategy_checkpoint_multi_gpu_fairscale_optimizer(tmpdir, strategy):
|
2022-11-05 03:29:38 +00:00
|
|
|
"""Test to ensure that checkpoint is saved correctly when using fairscale optimizer."""
|
2022-08-26 07:58:21 +00:00
|
|
|
model = BoringFairScaleOptimizerModel()
|
|
|
|
trainer = Trainer(accelerator="gpu", devices=2, strategy=strategy, max_steps=1)
|
|
|
|
|
|
|
|
trainer.fit(model)
|
|
|
|
|
|
|
|
checkpoint_path = os.path.join(tmpdir, "model.pt")
|
2022-11-05 03:29:38 +00:00
|
|
|
# need to broadcast because tmpdir is different on each process
|
|
|
|
checkpoint_path = trainer.strategy.broadcast(checkpoint_path)
|
2022-08-26 07:58:21 +00:00
|
|
|
trainer.save_checkpoint(checkpoint_path)
|
2022-11-05 03:29:38 +00:00
|
|
|
trainer.strategy.barrier() # ensure the checkpoint is saved before load
|
2022-08-26 07:58:21 +00:00
|
|
|
saved_model = BoringModel.load_from_checkpoint(checkpoint_path)
|
|
|
|
|
|
|
|
# Assert model parameters are identical after loading
|
|
|
|
for trained_param, loaded_param in zip(model.parameters(), saved_model.parameters()):
|
|
|
|
assert torch.equal(trained_param.to("cpu"), loaded_param)
|
|
|
|
|
|
|
|
|
|
|
|
class BoringZeroRedundancyOptimizerModel(BoringModel):
|
|
|
|
def configure_optimizers(self):
|
|
|
|
return ZeroRedundancyOptimizer(self.layer.parameters(), optimizer_class=torch.optim.Adam, lr=0.1)
|
|
|
|
|
|
|
|
|
2022-11-10 13:59:13 +00:00
|
|
|
@RunIf(min_cuda_gpus=2, skip_windows=True)
|
2022-08-26 07:58:21 +00:00
|
|
|
@pytest.mark.parametrize("strategy", (pytest.param("ddp", marks=RunIf(standalone=True)), "ddp_spawn"))
|
|
|
|
def test_ddp_strategy_checkpoint_zero_redundancy_optimizer(tmpdir, strategy):
|
|
|
|
"""Test to ensure that checkpoint is saved correctly when using zero redundancy optimizer."""
|
|
|
|
model = BoringZeroRedundancyOptimizerModel()
|
|
|
|
trainer = Trainer(accelerator="gpu", devices=2, strategy=strategy, max_steps=1)
|
|
|
|
|
|
|
|
trainer.fit(model)
|
|
|
|
|
|
|
|
checkpoint_path = os.path.join(tmpdir, "model.pt")
|
2022-11-05 03:29:38 +00:00
|
|
|
# need to broadcast because tmpdir is different on each process
|
|
|
|
checkpoint_path = trainer.strategy.broadcast(checkpoint_path)
|
2022-08-26 07:58:21 +00:00
|
|
|
trainer.save_checkpoint(checkpoint_path)
|
2022-11-05 03:29:38 +00:00
|
|
|
trainer.strategy.barrier() # ensure the checkpoint is saved before load
|
2022-08-26 07:58:21 +00:00
|
|
|
saved_model = BoringModel.load_from_checkpoint(checkpoint_path)
|
|
|
|
|
|
|
|
# Assert model parameters are identical after loading
|
|
|
|
for trained_param, loaded_param in zip(model.parameters(), saved_model.parameters()):
|
|
|
|
assert torch.equal(trained_param.to("cpu"), loaded_param)
|