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-11-20 10:17:46 +00:00
|
|
|
import os
|
2021-03-18 21:33:39 +00:00
|
|
|
from typing import Optional
|
|
|
|
from unittest import mock
|
2021-02-17 16:37:39 +00:00
|
|
|
from unittest.mock import patch
|
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
|
|
|
|
2021-04-27 17:49:32 +00:00
|
|
|
import pytorch_lightning as pl
|
2021-02-17 16:37:39 +00:00
|
|
|
from pytorch_lightning import Trainer
|
2021-04-27 17:49:32 +00:00
|
|
|
from pytorch_lightning.callbacks import Callback
|
2022-03-18 06:38:03 +00:00
|
|
|
from pytorch_lightning.strategies import DDPStrategy
|
2021-02-17 16:37:39 +00:00
|
|
|
from tests.helpers.boring_model import BoringModel
|
2021-03-02 09:36:01 +00:00
|
|
|
from tests.helpers.runif import RunIf
|
2022-02-22 05:14:18 +00:00
|
|
|
from tests.strategies import ddp_model
|
2020-11-26 22:45:52 +00:00
|
|
|
from tests.utilities.distributed import call_training_script
|
2020-10-01 16:34:12 +00:00
|
|
|
|
2022-03-23 19:52:12 +00:00
|
|
|
CLI_ARGS = "--max_epochs 1 --accelerator gpu --devices 2 --strategy ddp"
|
2021-02-23 22:08:46 +00:00
|
|
|
|
2020-10-01 16:34:12 +00:00
|
|
|
|
2022-05-24 12:54:05 +00:00
|
|
|
@RunIf(min_cuda_gpus=2)
|
2021-06-23 02:42:04 +00:00
|
|
|
@pytest.mark.parametrize("as_module", [True, False])
|
|
|
|
def test_multi_gpu_model_ddp_fit_only(tmpdir, as_module):
|
2020-10-01 16:34:12 +00:00
|
|
|
# call the script
|
2021-07-26 11:37:35 +00:00
|
|
|
call_training_script(ddp_model, CLI_ARGS, "fit", tmpdir, timeout=120, as_module=as_module)
|
2020-10-01 16:34:12 +00:00
|
|
|
|
|
|
|
# load the results of the script
|
2021-07-26 11:37:35 +00:00
|
|
|
result_path = os.path.join(tmpdir, "ddp.result")
|
2020-10-01 16:34:12 +00:00
|
|
|
result = torch.load(result_path)
|
|
|
|
|
|
|
|
# verify the file wrote the expected outputs
|
2021-07-26 11:37:35 +00:00
|
|
|
assert result["status"] == "complete"
|
2020-10-01 16:34:12 +00:00
|
|
|
|
|
|
|
|
2022-05-24 12:54:05 +00:00
|
|
|
@RunIf(min_cuda_gpus=2)
|
2021-06-23 02:42:04 +00:00
|
|
|
@pytest.mark.parametrize("as_module", [True, False])
|
|
|
|
def test_multi_gpu_model_ddp_test_only(tmpdir, as_module):
|
2020-10-01 16:34:12 +00:00
|
|
|
# call the script
|
2021-07-26 11:37:35 +00:00
|
|
|
call_training_script(ddp_model, CLI_ARGS, "test", tmpdir, as_module=as_module)
|
2020-10-01 16:34:12 +00:00
|
|
|
|
|
|
|
# load the results of the script
|
2021-07-26 11:37:35 +00:00
|
|
|
result_path = os.path.join(tmpdir, "ddp.result")
|
2020-10-01 16:34:12 +00:00
|
|
|
result = torch.load(result_path)
|
|
|
|
|
|
|
|
# verify the file wrote the expected outputs
|
2021-07-26 11:37:35 +00:00
|
|
|
assert result["status"] == "complete"
|
2020-10-01 16:34:12 +00:00
|
|
|
|
|
|
|
|
2022-05-24 12:54:05 +00:00
|
|
|
@RunIf(min_cuda_gpus=2)
|
2021-06-23 02:42:04 +00:00
|
|
|
@pytest.mark.parametrize("as_module", [True, False])
|
|
|
|
def test_multi_gpu_model_ddp_fit_test(tmpdir, as_module):
|
2020-10-03 18:05:31 +00:00
|
|
|
# call the script
|
2021-07-26 11:37:35 +00:00
|
|
|
call_training_script(ddp_model, CLI_ARGS, "fit_test", tmpdir, timeout=20, as_module=as_module)
|
2020-10-03 18:05:31 +00:00
|
|
|
|
|
|
|
# load the results of the script
|
2021-07-26 11:37:35 +00:00
|
|
|
result_path = os.path.join(tmpdir, "ddp.result")
|
2020-10-03 18:05:31 +00:00
|
|
|
result = torch.load(result_path)
|
|
|
|
|
|
|
|
# verify the file wrote the expected outputs
|
2021-07-26 11:37:35 +00:00
|
|
|
assert result["status"] == "complete"
|
2020-10-03 18:05:31 +00:00
|
|
|
|
2021-07-26 11:37:35 +00:00
|
|
|
model_outs = result["result"]
|
2020-10-03 18:05:31 +00:00
|
|
|
for out in model_outs:
|
2021-07-26 11:37:35 +00:00
|
|
|
assert out["test_acc"] > 0.7
|
2020-11-20 10:17:46 +00:00
|
|
|
|
|
|
|
|
2021-03-02 09:36:01 +00:00
|
|
|
@RunIf(skip_windows=True)
|
2021-02-17 16:37:39 +00:00
|
|
|
@pytest.mark.skipif(torch.cuda.is_available(), reason="test doesn't requires GPU machine")
|
2022-02-09 23:11:27 +00:00
|
|
|
@mock.patch("torch.cuda.is_available", return_value=True)
|
2021-02-17 16:37:39 +00:00
|
|
|
def test_torch_distributed_backend_env_variables(tmpdir):
|
2021-09-06 12:49:09 +00:00
|
|
|
"""This test set `undefined` as torch backend and should raise an `Backend.UNDEFINED` ValueError."""
|
2021-02-17 16:37:39 +00:00
|
|
|
_environ = {"PL_TORCH_DISTRIBUTED_BACKEND": "undefined", "CUDA_VISIBLE_DEVICES": "0,1", "WORLD_SIZE": "2"}
|
2021-07-26 11:37:35 +00:00
|
|
|
with patch.dict(os.environ, _environ), patch("torch.cuda.device_count", return_value=2):
|
2022-03-18 06:38:03 +00:00
|
|
|
with pytest.deprecated_call(match="Environment variable `PL_TORCH_DISTRIBUTED_BACKEND` was deprecated in v1.6"):
|
|
|
|
with pytest.raises(ValueError, match="Invalid backend: 'undefined'"):
|
|
|
|
model = BoringModel()
|
2022-04-10 17:10:05 +00:00
|
|
|
trainer = Trainer(
|
|
|
|
default_root_dir=tmpdir,
|
|
|
|
fast_dev_run=True,
|
|
|
|
strategy="ddp",
|
|
|
|
accelerator="gpu",
|
|
|
|
devices=2,
|
|
|
|
logger=False,
|
|
|
|
)
|
2022-03-18 06:38:03 +00:00
|
|
|
trainer.fit(model)
|
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")
|
2022-02-09 23:11:27 +00:00
|
|
|
@mock.patch("torch.cuda.is_available", return_value=True)
|
|
|
|
@mock.patch("torch.cuda.device_count", return_value=1)
|
|
|
|
@mock.patch("pytorch_lightning.accelerators.gpu.GPUAccelerator.is_available", return_value=True)
|
2021-07-26 11:37:35 +00:00
|
|
|
@mock.patch.dict(os.environ, {"PL_TORCH_DISTRIBUTED_BACKEND": "gloo"}, clear=True)
|
2022-02-09 23:11:27 +00:00
|
|
|
def test_ddp_torch_dist_is_available_in_setup(
|
|
|
|
mock_gpu_is_available, mock_device_count, mock_cuda_available, mock_set_device, 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):
|
|
|
|
def setup(self, stage: Optional[str] = None) -> None:
|
|
|
|
assert torch.distributed.is_initialized()
|
|
|
|
raise SystemExit()
|
|
|
|
|
|
|
|
model = TestModel()
|
2022-03-27 16:13:48 +00:00
|
|
|
trainer = Trainer(default_root_dir=tmpdir, fast_dev_run=True, strategy="ddp", accelerator="gpu", devices=1)
|
2022-03-18 06:38:03 +00:00
|
|
|
with pytest.deprecated_call(match="Environment variable `PL_TORCH_DISTRIBUTED_BACKEND` was deprecated in v1.6"):
|
|
|
|
with pytest.raises(SystemExit):
|
|
|
|
trainer.fit(model)
|
2021-04-27 17:49:32 +00:00
|
|
|
|
|
|
|
|
2022-05-24 12:54:05 +00:00
|
|
|
@RunIf(min_cuda_gpus=2, min_torch="1.8.1", standalone=True)
|
2021-11-17 15:46:14 +00:00
|
|
|
@pytest.mark.parametrize("precision", (16, 32))
|
|
|
|
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)
|
2022-02-24 17:22:48 +00:00
|
|
|
assert trainer.strategy.model.parameters_to_ignore == ["module.something"]
|
|
|
|
assert trainer.strategy.model.module._ddp_params_and_buffers_to_ignore == ["module.something"]
|
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(
|
|
|
|
["process_group_backend", "env_var", "device_str", "expected_process_group_backend"],
|
|
|
|
[
|
|
|
|
pytest.param("foo", None, "cpu", "foo"),
|
|
|
|
pytest.param("foo", "BAR", "cpu", "foo"),
|
|
|
|
pytest.param("foo", "BAR", "cuda:0", "foo"),
|
|
|
|
pytest.param(None, "BAR", "cuda:0", "BAR"),
|
|
|
|
pytest.param(None, None, "cuda:0", "nccl"),
|
|
|
|
pytest.param(None, None, "cpu", "gloo"),
|
|
|
|
],
|
|
|
|
)
|
|
|
|
def test_ddp_process_group_backend(process_group_backend, env_var, device_str, expected_process_group_backend):
|
|
|
|
"""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))
|
|
|
|
if not process_group_backend and env_var:
|
|
|
|
with mock.patch.dict(os.environ, {"PL_TORCH_DISTRIBUTED_BACKEND": env_var}):
|
|
|
|
with pytest.deprecated_call(
|
|
|
|
match="Environment variable `PL_TORCH_DISTRIBUTED_BACKEND` was deprecated in v1.6"
|
|
|
|
):
|
|
|
|
assert strategy._get_process_group_backend() == expected_process_group_backend
|
|
|
|
else:
|
|
|
|
assert strategy._get_process_group_backend() == expected_process_group_backend
|