|
| 1 | +import pytest |
| 2 | +import torch |
| 3 | + |
| 4 | +import lightning.pytorch as pl |
| 5 | +from lightning.pytorch.callbacks import ModelCheckpoint |
| 6 | +from lightning.pytorch.demos.boring_classes import BoringModel |
| 7 | +from tests_pytorch.helpers.runif import RunIf |
| 8 | + |
| 9 | + |
| 10 | +def create_boring_checkpoint(tmp_path, model, accelerator="cuda"): |
| 11 | + checkpoint_callback = ModelCheckpoint(dirpath=tmp_path, filename="checkpoint") |
| 12 | + trainer = pl.Trainer( |
| 13 | + devices=1, |
| 14 | + accelerator=accelerator, |
| 15 | + max_epochs=1, |
| 16 | + enable_model_summary=False, |
| 17 | + enable_progress_bar=False, |
| 18 | + callbacks=[checkpoint_callback], |
| 19 | + ) |
| 20 | + trainer.fit(model) |
| 21 | + |
| 22 | + |
| 23 | +@pytest.mark.parametrize( |
| 24 | + "map_location", (None, "cpu", torch.device("cpu"), lambda storage, loc: storage, {"cpu": "cpu"}) |
| 25 | +) |
| 26 | +def test_load_from_checkpoint_map_location_cpu(tmp_path, map_location): |
| 27 | + create_boring_checkpoint(tmp_path, BoringModel(), accelerator="cpu") |
| 28 | + model = BoringModel.load_from_checkpoint(f"{tmp_path}/checkpoint.ckpt", map_location=map_location) |
| 29 | + assert model.device.type == "cpu" |
| 30 | + |
| 31 | + |
| 32 | +@RunIf(min_cuda_gpus=1) |
| 33 | +@pytest.mark.parametrize( |
| 34 | + "map_location", (None, "cuda", torch.device("cuda"), lambda storage, loc: storage.cuda(), {"cpu": "cuda"}) |
| 35 | +) |
| 36 | +def test_load_from_checkpoint_map_location_gpu(tmp_path, map_location): |
| 37 | + create_boring_checkpoint(tmp_path, BoringModel(), accelerator="cuda") |
| 38 | + model = BoringModel.load_from_checkpoint(f"{tmp_path}/checkpoint.ckpt", map_location=map_location) |
| 39 | + assert model.device.type == "cuda" |
| 40 | + |
| 41 | + |
| 42 | +@RunIf(min_cuda_gpus=1) |
| 43 | +@pytest.mark.parametrize("map_location", ("cpu", torch.device("cpu"), lambda storage, loc: storage, {"cuda": "cpu"})) |
| 44 | +def test_load_from_checkpoint_map_location_gpu_to_cpu(tmp_path, map_location): |
| 45 | + create_boring_checkpoint(tmp_path, BoringModel(), accelerator="cpu") |
| 46 | + model = BoringModel.load_from_checkpoint(f"{tmp_path}/checkpoint.ckpt", map_location=map_location) |
| 47 | + assert model.device.type == "cpu" |
| 48 | + |
| 49 | + |
| 50 | +@RunIf(min_cuda_gpus=1) |
| 51 | +@pytest.mark.parametrize( |
| 52 | + "map_location", ("cuda", torch.device("cuda"), lambda storage, loc: storage.cuda(), {"cpu": "cuda"}) |
| 53 | +) |
| 54 | +def test_load_from_checkpoint_map_location_cpu_to_gpu(tmp_path, map_location): |
| 55 | + create_boring_checkpoint(tmp_path, BoringModel(), accelerator="cpu") |
| 56 | + model = BoringModel.load_from_checkpoint(f"{tmp_path}/checkpoint.ckpt", map_location=map_location) |
| 57 | + assert model.device.type == "cuda" |
0 commit comments