2020-10-13 11:18:07 +00:00
|
|
|
# Copyright The Lightning AI 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.
|
2023-07-14 17:15:05 +00:00
|
|
|
import os
|
2021-03-18 21:33:39 +00:00
|
|
|
from unittest import mock
|
2020-11-20 10:17:46 +00:00
|
|
|
|
2020-10-01 16:34:12 +00:00
|
|
|
import pytest
|
|
|
|
import torch
|
2021-04-27 17:49:32 +00:00
|
|
|
from torch.nn.parallel.distributed import DistributedDataParallel
|
2020-11-20 10:17:46 +00:00
|
|
|
|
2023-02-02 10:06:45 +00:00
|
|
|
import lightning.pytorch as pl
|
2023-07-14 17:15:05 +00:00
|
|
|
from lightning.fabric.plugins.environments import LightningEnvironment
|
2023-02-28 17:38:40 +00:00
|
|
|
from lightning.fabric.utilities.imports import _TORCH_GREATER_EQUAL_2_0
|
2023-02-02 10:06:45 +00:00
|
|
|
from lightning.pytorch import seed_everything, Trainer
|
|
|
|
from lightning.pytorch.callbacks import Callback
|
|
|
|
from lightning.pytorch.demos.boring_classes import BoringModel
|
2023-07-14 17:15:05 +00:00
|
|
|
from lightning.pytorch.plugins import DoublePrecisionPlugin, PrecisionPlugin
|
2023-02-02 10:06:45 +00:00
|
|
|
from lightning.pytorch.strategies import DDPStrategy
|
2022-08-10 21:15:12 +00:00
|
|
|
from tests_pytorch.helpers.datamodules import ClassifDataModule
|
2022-06-15 22:10:49 +00:00
|
|
|
from tests_pytorch.helpers.runif import RunIf
|
2022-08-10 21:15:12 +00:00
|
|
|
from tests_pytorch.helpers.simple_models import ClassificationModel
|
2020-10-01 16:34:12 +00:00
|
|
|
|
2021-02-23 22:08:46 +00:00
|
|
|
|
2022-11-01 11:40:32 +00:00
|
|
|
@RunIf(min_cuda_gpus=2, standalone=True, sklearn=True)
|
2022-08-10 21:15:12 +00:00
|
|
|
def test_multi_gpu_model_ddp_fit_only(tmpdir):
|
|
|
|
dm = ClassifDataModule()
|
|
|
|
model = ClassificationModel()
|
|
|
|
trainer = Trainer(default_root_dir=tmpdir, max_epochs=1, accelerator="gpu", devices=2, strategy="ddp")
|
|
|
|
trainer.fit(model, datamodule=dm)
|
2020-10-01 16:34:12 +00:00
|
|
|
|
|
|
|
|
2022-11-01 11:40:32 +00:00
|
|
|
@RunIf(min_cuda_gpus=2, standalone=True, sklearn=True)
|
2022-08-10 21:15:12 +00:00
|
|
|
def test_multi_gpu_model_ddp_test_only(tmpdir):
|
|
|
|
dm = ClassifDataModule()
|
|
|
|
model = ClassificationModel()
|
|
|
|
trainer = Trainer(default_root_dir=tmpdir, max_epochs=1, accelerator="gpu", devices=2, strategy="ddp")
|
|
|
|
trainer.test(model, datamodule=dm)
|
2020-10-01 16:34:12 +00:00
|
|
|
|
|
|
|
|
2022-11-01 11:40:32 +00:00
|
|
|
@RunIf(min_cuda_gpus=2, standalone=True, sklearn=True)
|
2022-08-10 21:15:12 +00:00
|
|
|
def test_multi_gpu_model_ddp_fit_test(tmpdir):
|
|
|
|
seed_everything(4321)
|
|
|
|
dm = ClassifDataModule()
|
|
|
|
model = ClassificationModel()
|
|
|
|
trainer = Trainer(default_root_dir=tmpdir, max_epochs=1, accelerator="gpu", devices=2, strategy="ddp")
|
|
|
|
trainer.fit(model, datamodule=dm)
|
|
|
|
result = trainer.test(model, datamodule=dm)
|
2020-10-01 16:34:12 +00:00
|
|
|
|
2022-08-10 21:15:12 +00:00
|
|
|
for out in result:
|
2021-07-26 11:37:35 +00:00
|
|
|
assert out["test_acc"] > 0.7
|
2020-11-20 10:17:46 +00:00
|
|
|
|
|
|
|
|
2021-03-18 21:33:39 +00:00
|
|
|
@RunIf(skip_windows=True)
|
2021-07-26 11:37:35 +00:00
|
|
|
@mock.patch("torch.cuda.set_device")
|
2023-02-02 10:06:45 +00:00
|
|
|
@mock.patch("lightning.pytorch.accelerators.cuda._check_cuda_matmul_precision")
|
2023-03-06 16:52:02 +00:00
|
|
|
@mock.patch("lightning.pytorch.accelerators.cuda._clear_cuda_memory")
|
|
|
|
def test_ddp_torch_dist_is_available_in_setup(_, __, ___, cuda_count_1, mps_count_0, tmpdir):
|
2021-09-06 12:49:09 +00:00
|
|
|
"""Test to ensure torch distributed is available within the setup hook using ddp."""
|
2021-03-18 21:33:39 +00:00
|
|
|
|
|
|
|
class TestModel(BoringModel):
|
2022-09-01 13:47:40 +00:00
|
|
|
def setup(self, stage: str) -> None:
|
2021-03-18 21:33:39 +00:00
|
|
|
assert torch.distributed.is_initialized()
|
|
|
|
raise SystemExit()
|
|
|
|
|
|
|
|
model = TestModel()
|
2022-09-16 15:27:36 +00:00
|
|
|
trainer = Trainer(
|
|
|
|
default_root_dir=tmpdir,
|
|
|
|
fast_dev_run=True,
|
|
|
|
strategy=DDPStrategy(process_group_backend="gloo"),
|
|
|
|
accelerator="gpu",
|
|
|
|
devices=1,
|
|
|
|
)
|
|
|
|
with pytest.raises(SystemExit):
|
|
|
|
trainer.fit(model)
|
2021-04-27 17:49:32 +00:00
|
|
|
|
|
|
|
|
2023-02-01 19:09:12 +00:00
|
|
|
@RunIf(min_cuda_gpus=2, standalone=True)
|
2023-05-05 06:25:15 +00:00
|
|
|
@pytest.mark.parametrize("precision", ["16-mixed", "32-true"])
|
2021-11-17 15:46:14 +00:00
|
|
|
def test_ddp_wrapper(tmpdir, precision):
|
2021-09-06 12:49:09 +00:00
|
|
|
"""Test parameters to ignore are carried over for DDP."""
|
2021-04-27 17:49:32 +00:00
|
|
|
|
|
|
|
class WeirdModule(torch.nn.Module):
|
|
|
|
def _save_to_state_dict(self, destination, prefix, keep_vars):
|
|
|
|
return {"something": "something"}
|
|
|
|
|
|
|
|
class CustomModel(BoringModel):
|
|
|
|
def __init__(self):
|
|
|
|
super().__init__()
|
|
|
|
self.weird_module = WeirdModule()
|
|
|
|
|
|
|
|
# should be skip.
|
2022-02-24 17:22:48 +00:00
|
|
|
self._ddp_params_and_buffers_to_ignore = ["something"]
|
2021-04-27 17:49:32 +00:00
|
|
|
|
|
|
|
class CustomCallback(Callback):
|
2021-07-26 11:37:35 +00:00
|
|
|
def on_train_start(self, trainer: "pl.Trainer", pl_module: "pl.LightningModule") -> None:
|
2021-12-22 02:11:43 +00:00
|
|
|
assert isinstance(trainer.strategy.model, DistributedDataParallel)
|
2023-06-05 11:38:56 +00:00
|
|
|
expected = ["something"]
|
2023-02-28 17:38:40 +00:00
|
|
|
assert (
|
|
|
|
trainer.strategy.model.parameters_to_ignore == set(expected) if _TORCH_GREATER_EQUAL_2_0 else expected
|
|
|
|
)
|
|
|
|
assert trainer.strategy.model.module._ddp_params_and_buffers_to_ignore == expected
|
2021-04-27 17:49:32 +00:00
|
|
|
|
|
|
|
model = CustomModel()
|
2021-06-01 15:21:17 +00:00
|
|
|
trainer = Trainer(
|
|
|
|
default_root_dir=tmpdir,
|
|
|
|
fast_dev_run=True,
|
|
|
|
precision=precision,
|
2021-10-16 15:10:25 +00:00
|
|
|
strategy="ddp",
|
2022-03-24 14:09:39 +00:00
|
|
|
accelerator="gpu",
|
|
|
|
devices=2,
|
2021-06-01 15:21:17 +00:00
|
|
|
callbacks=CustomCallback(),
|
2022-04-20 18:57:40 +00:00
|
|
|
enable_progress_bar=False,
|
|
|
|
enable_model_summary=False,
|
2021-06-01 15:21:17 +00:00
|
|
|
)
|
2021-04-27 17:49:32 +00:00
|
|
|
trainer.fit(model)
|
2022-03-18 06:38:03 +00:00
|
|
|
|
|
|
|
|
|
|
|
@pytest.mark.parametrize(
|
2023-05-04 15:50:39 +00:00
|
|
|
("process_group_backend", "device_str", "expected_process_group_backend"),
|
2022-03-18 06:38:03 +00:00
|
|
|
[
|
2022-09-16 15:27:36 +00:00
|
|
|
pytest.param("foo", "cpu", "foo"),
|
|
|
|
pytest.param("foo", "cuda:0", "foo"),
|
|
|
|
pytest.param(None, "cuda:0", "nccl"),
|
|
|
|
pytest.param(None, "cpu", "gloo"),
|
2022-03-18 06:38:03 +00:00
|
|
|
],
|
|
|
|
)
|
2022-09-16 15:27:36 +00:00
|
|
|
def test_ddp_process_group_backend(process_group_backend, device_str, expected_process_group_backend):
|
2022-03-18 06:38:03 +00:00
|
|
|
"""Test settings for process group backend."""
|
|
|
|
|
|
|
|
class MockDDPStrategy(DDPStrategy):
|
|
|
|
def __init__(self, root_device, process_group_backend):
|
|
|
|
self._root_device = root_device
|
|
|
|
super().__init__(process_group_backend=process_group_backend)
|
|
|
|
|
|
|
|
@property
|
|
|
|
def root_device(self):
|
|
|
|
return self._root_device
|
|
|
|
|
|
|
|
strategy = MockDDPStrategy(process_group_backend=process_group_backend, root_device=torch.device(device_str))
|
2022-09-16 15:27:36 +00:00
|
|
|
assert strategy._get_process_group_backend() == expected_process_group_backend
|
2022-08-09 08:26:02 +00:00
|
|
|
|
|
|
|
|
|
|
|
@pytest.mark.parametrize(
|
2023-05-04 15:50:39 +00:00
|
|
|
("strategy_name", "expected_ddp_kwargs"),
|
2022-08-09 08:26:02 +00:00
|
|
|
[
|
|
|
|
("ddp", {}),
|
|
|
|
("ddp_find_unused_parameters_false", {"find_unused_parameters": False}),
|
2023-02-06 15:51:21 +00:00
|
|
|
("ddp_find_unused_parameters_true", {"find_unused_parameters": True}),
|
2022-08-09 08:26:02 +00:00
|
|
|
],
|
|
|
|
)
|
2023-02-06 15:51:21 +00:00
|
|
|
def test_ddp_kwargs_from_registry(strategy_name, expected_ddp_kwargs, mps_count_0):
|
2022-08-09 08:26:02 +00:00
|
|
|
trainer = Trainer(strategy=strategy_name)
|
|
|
|
assert trainer.strategy._ddp_kwargs == expected_ddp_kwargs
|
2023-07-14 17:15:05 +00:00
|
|
|
|
|
|
|
|
|
|
|
@RunIf(min_cuda_gpus=2)
|
|
|
|
@pytest.mark.parametrize(
|
|
|
|
("precision_plugin", "expected_dtype"),
|
|
|
|
[
|
|
|
|
(PrecisionPlugin(), torch.float32),
|
|
|
|
(DoublePrecisionPlugin(), torch.float64),
|
|
|
|
],
|
|
|
|
)
|
|
|
|
@mock.patch.dict(os.environ, {"LOCAL_RANK": "1"})
|
|
|
|
def test_tensor_init_context(precision_plugin, expected_dtype):
|
|
|
|
"""Test that the module under the init-context gets moved to the right device and dtype."""
|
|
|
|
parallel_devices = [torch.device("cuda", 0), torch.device("cuda", 1)]
|
|
|
|
expected_device = parallel_devices[1] if _TORCH_GREATER_EQUAL_2_0 else torch.device("cpu")
|
|
|
|
|
|
|
|
strategy = DDPStrategy(
|
|
|
|
parallel_devices=parallel_devices, precision_plugin=precision_plugin, cluster_environment=LightningEnvironment()
|
|
|
|
)
|
|
|
|
assert strategy.local_rank == 1
|
|
|
|
with strategy.tensor_init_context():
|
|
|
|
module = torch.nn.Linear(2, 2)
|
|
|
|
assert module.weight.device == module.bias.device == expected_device
|
|
|
|
assert module.weight.dtype == module.bias.dtype == expected_dtype
|