|
| 1 | +import logging |
| 2 | +import os |
| 3 | +import sys |
| 4 | +from pathlib import Path |
| 5 | + |
| 6 | +import pytest |
| 7 | +from lightning_utilities.core.imports import RequirementCache |
| 8 | + |
| 9 | +from pytorch_lightning.strategies.launchers.subprocess_script import _HYDRA_AVAILABLE |
| 10 | +from tests_pytorch.helpers.runif import RunIf |
| 11 | + |
| 12 | +_HYDRA_WITH_RERUN = RequirementCache("hydra-core>=1.2") |
| 13 | +_HYDRA_WITH_RUN_PROCESS = RequirementCache("hydra-core>=1.0.7") |
| 14 | + |
| 15 | +if _HYDRA_AVAILABLE: |
| 16 | + from omegaconf import OmegaConf |
| 17 | +if _HYDRA_WITH_RUN_PROCESS: |
| 18 | + from hydra.test_utils.test_utils import run_process |
| 19 | + |
| 20 | + |
| 21 | +# fixture to run hydra jobs in a clean temporary directory |
| 22 | +# Hydra creates its own output directories and logs |
| 23 | +@pytest.fixture |
| 24 | +def cleandir(tmp_path): |
| 25 | + """Run function in a temporary directory.""" |
| 26 | + old_dir = os.getcwd() # get current working directory (cwd) |
| 27 | + os.chdir(tmp_path) # change cwd to the temp-directory |
| 28 | + yield tmp_path # yields control to the test to be run |
| 29 | + os.chdir(old_dir) |
| 30 | + logging.shutdown() |
| 31 | + |
| 32 | + |
| 33 | +# Script to run from command line |
| 34 | +script = """ |
| 35 | +import hydra |
| 36 | +import os |
| 37 | +import torch |
| 38 | +
|
| 39 | +from pytorch_lightning import Trainer |
| 40 | +from pytorch_lightning.demos.boring_classes import BoringModel |
| 41 | +
|
| 42 | +class BoringModelGPU(BoringModel): |
| 43 | + def on_train_start(self) -> None: |
| 44 | + # make sure that the model is on GPU when training |
| 45 | + assert self.device == torch.device(f"cuda:{self.trainer.strategy.local_rank}") |
| 46 | +
|
| 47 | +@hydra.main(config_path=None, version_base="1.1") |
| 48 | +def task_fn(cfg): |
| 49 | + trainer = Trainer(accelerator="auto", devices=cfg.devices, strategy=cfg.strategy, fast_dev_run=True) |
| 50 | + model = BoringModelGPU() |
| 51 | + trainer.fit(model) |
| 52 | + trainer.test(model) |
| 53 | +
|
| 54 | + if torch.distributed.is_initialized(): |
| 55 | + torch.distributed.destroy_process_group() |
| 56 | +
|
| 57 | + os.environ.pop("LOCAL_RANK", None) |
| 58 | +
|
| 59 | +if __name__ == "__main__": |
| 60 | + task_fn() |
| 61 | +""" |
| 62 | + |
| 63 | + |
| 64 | +@RunIf(min_cuda_gpus=2, skip_windows=True, standalone=True) |
| 65 | +@pytest.mark.skipif(not _HYDRA_WITH_RUN_PROCESS, reason=str(_HYDRA_WITH_RUN_PROCESS)) |
| 66 | +@pytest.mark.parametrize("subdir", [None, "dksa", ".hello"]) |
| 67 | +def test_ddp_with_hydra_runjob(cleandir, subdir): |
| 68 | + # Save script locally |
| 69 | + with open("temp.py", "w") as fn: |
| 70 | + fn.write(script) |
| 71 | + |
| 72 | + # Run CLI |
| 73 | + devices = 2 |
| 74 | + cmd = [sys.executable, "temp.py", f"+devices={devices}", '+strategy="ddp"'] |
| 75 | + if subdir is not None: |
| 76 | + cmd += [f"hydra.output_subdir={subdir}"] |
| 77 | + run_process(cmd) |
| 78 | + |
| 79 | + # Make sure config.yaml was created for additional |
| 80 | + # processes. |
| 81 | + logs = list(Path.cwd().glob("**/config.yaml")) |
| 82 | + assert len(logs) == devices |
| 83 | + |
| 84 | + # Make sure the parameter was set and used |
| 85 | + cfg = OmegaConf.load(logs[0]) |
| 86 | + assert cfg.devices == devices |
| 87 | + |
| 88 | + # Make sure PL spawned a job that is logged by Hydra |
| 89 | + logs = list(Path.cwd().glob("**/*.log")) |
| 90 | + assert len(logs) == 1 |
| 91 | + |
| 92 | + |
| 93 | +@RunIf(min_cuda_gpus=2, skip_windows=True, standalone=True) |
| 94 | +@pytest.mark.skipif(not _HYDRA_WITH_RUN_PROCESS, reason=str(_HYDRA_WITH_RUN_PROCESS)) |
| 95 | +@pytest.mark.parametrize("num_jobs", [1, 2]) |
| 96 | +def test_ddp_with_hydra_multirunjob(cleandir, num_jobs): |
| 97 | + # Save script locally |
| 98 | + with open("temp.py", "w") as fn: |
| 99 | + fn.write(script) |
| 100 | + |
| 101 | + # create fake multirun params based on `num_jobs` |
| 102 | + fake_param = "+foo=" + ",".join(str(i) for i in range(num_jobs)) |
| 103 | + |
| 104 | + # Run CLI |
| 105 | + run_process([sys.executable, "temp.py", "+devices=2", '+strategy="ddp"', fake_param, "--multirun"]) |
| 106 | + |
| 107 | + # Make sure config.yaml was created for each job |
| 108 | + configs = sorted(Path.cwd().glob("**/.pl_ddp_hydra_*/config.yaml")) |
| 109 | + assert len(configs) == num_jobs |
| 110 | + |
| 111 | + # Make sure the parameter was set and used for each job |
| 112 | + for i, config in enumerate(configs): |
| 113 | + cfg = OmegaConf.load(config) |
| 114 | + local_rank = int(config.parent.parent.parts[-1]) |
| 115 | + assert cfg.devices == 2 |
| 116 | + assert cfg.foo == local_rank |
| 117 | + |
| 118 | + logs = list(Path.cwd().glob("**/*.log")) |
| 119 | + assert len(logs) == num_jobs |
| 120 | + |
| 121 | + |
| 122 | +yaml_file = """ |
| 123 | +hydra: |
| 124 | + callbacks: |
| 125 | + save_job_info: |
| 126 | + _target_: hydra.experimental.callbacks.PickleJobInfoCallback |
| 127 | +""" |
| 128 | + |
| 129 | + |
| 130 | +@RunIf(min_cuda_gpus=2, skip_windows=True, standalone=True) |
| 131 | +@pytest.mark.skipif(not _HYDRA_WITH_RERUN, reason=str(_HYDRA_WITH_RERUN)) |
| 132 | +@pytest.mark.parametrize("num_jobs", [1, 2]) |
| 133 | +def test_ddp_with_hydra_multirunjob_rerun(cleandir, num_jobs): |
| 134 | + # Save script locally |
| 135 | + with open("temp.py", "w") as fn: |
| 136 | + fn.write(script) |
| 137 | + |
| 138 | + with open("config.yaml", "w") as fn: |
| 139 | + fn.write(yaml_file) |
| 140 | + |
| 141 | + # create fake multirun params based on `num_jobs` |
| 142 | + fake_param = "+foo=" + ",".join(str(i) for i in range(num_jobs)) |
| 143 | + |
| 144 | + # Run CLI |
| 145 | + run_process( |
| 146 | + [ |
| 147 | + sys.executable, |
| 148 | + "temp.py", |
| 149 | + "-cp", |
| 150 | + ".", |
| 151 | + "-cn", |
| 152 | + "config.yaml", |
| 153 | + "+devices=2", |
| 154 | + '+strategy="ddp"', |
| 155 | + fake_param, |
| 156 | + "--multirun", |
| 157 | + ] |
| 158 | + ) |
| 159 | + |
| 160 | + pickles = sorted(Path.cwd().glob("**/.hydra/config.pickle")) |
| 161 | + assert len(pickles) == num_jobs |
0 commit comments