|
| 1 | +# Copyright The Lightning AI team. |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | +from copy import deepcopy |
| 15 | + |
| 16 | +import pytest |
| 17 | +import torch |
| 18 | + |
| 19 | +from lightning.fabric import Fabric |
| 20 | +from tests_fabric.helpers.runif import RunIf |
| 21 | + |
| 22 | + |
| 23 | +@pytest.mark.parametrize( |
| 24 | + "accelerator", |
| 25 | + [ |
| 26 | + "cpu", |
| 27 | + pytest.param("cuda", marks=RunIf(min_cuda_gpus=2)), |
| 28 | + ], |
| 29 | +) |
| 30 | +def test_ddp_save_load(accelerator, tmp_path): |
| 31 | + """Test that DDP model checkpoints can be saved and loaded successfully.""" |
| 32 | + fabric = Fabric(devices=2, accelerator=accelerator, strategy="ddp_spawn") |
| 33 | + fabric.launch(_run_ddp_save_load, tmp_path) |
| 34 | + |
| 35 | + |
| 36 | +def _run_ddp_save_load(fabric, tmp_path): |
| 37 | + fabric.seed_everything(0) |
| 38 | + |
| 39 | + tmp_path = fabric.broadcast(tmp_path) |
| 40 | + |
| 41 | + model = torch.nn.Linear(2, 2) |
| 42 | + params_before = deepcopy(list(model.parameters())) |
| 43 | + |
| 44 | + # Save |
| 45 | + fabric.save(tmp_path / "saved_before_setup.ckpt", {"model": model}) |
| 46 | + wrapped_model = fabric.setup(model) |
| 47 | + fabric.save(tmp_path / "saved_after_setup.ckpt", {"model": wrapped_model}) |
| 48 | + |
| 49 | + def assert_params_equal(params0, params1): |
| 50 | + assert all(torch.equal(p0, p1.to(p0.device)) for p0, p1 in zip(params0, params1)) |
| 51 | + |
| 52 | + # Load |
| 53 | + model = torch.nn.Linear(2, 2) |
| 54 | + fabric.load(tmp_path / "saved_before_setup.ckpt", {"model": model}) |
| 55 | + assert_params_equal(params_before, model.parameters()) |
| 56 | + fabric.load(tmp_path / "saved_after_setup.ckpt", {"model": model}) |
| 57 | + assert_params_equal(params_before, model.parameters()) |
| 58 | + |
| 59 | + wrapped_model = fabric.setup(model) |
| 60 | + fabric.load(tmp_path / "saved_before_setup.ckpt", {"model": wrapped_model}) |
| 61 | + assert_params_equal(params_before, wrapped_model.parameters()) |
| 62 | + fabric.load(tmp_path / "saved_after_setup.ckpt", {"model": wrapped_model}) |
| 63 | + assert_params_equal(params_before, wrapped_model.parameters()) |
0 commit comments