|
| 1 | +# Copyright The PyTorch Lightning 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 | +import os |
| 16 | + |
| 17 | +import torch |
| 18 | + |
| 19 | +import pytorch_lightning as pl |
| 20 | +from pytorch_lightning import seed_everything, Trainer |
| 21 | +from pytorch_lightning.callbacks import ModelCheckpoint |
| 22 | +from pytorch_lightning.utilities.cloud_io import load as pl_load |
| 23 | +from tests.base import BoringModel |
| 24 | + |
| 25 | + |
| 26 | +def test_finetuning_with_resume_from_checkpoint(tmpdir): |
| 27 | + """ |
| 28 | + This test validates that generated ModelCheckpoint is pointing to the right best_model_path during test |
| 29 | + """ |
| 30 | + |
| 31 | + seed_everything(3) |
| 32 | + |
| 33 | + checkpoint_callback = ModelCheckpoint(monitor='val_loss', dirpath=tmpdir, filename="{epoch:02d}", save_top_k=-1) |
| 34 | + |
| 35 | + class ExtendedBoringModel(BoringModel): |
| 36 | + |
| 37 | + def configure_optimizers(self): |
| 38 | + optimizer = torch.optim.SGD(self.layer.parameters(), lr=0.001) |
| 39 | + lr_scheduler = torch.optim.lr_scheduler.StepLR(optimizer, step_size=1) |
| 40 | + return [optimizer], [lr_scheduler] |
| 41 | + |
| 42 | + def validation_step(self, batch, batch_idx): |
| 43 | + output = self.layer(batch) |
| 44 | + loss = self.loss(batch, output) |
| 45 | + self.log("val_loss", loss, on_epoch=True, prog_bar=True) |
| 46 | + |
| 47 | + model = ExtendedBoringModel() |
| 48 | + model.validation_epoch_end = None |
| 49 | + trainer = Trainer( |
| 50 | + default_root_dir=tmpdir, |
| 51 | + max_epochs=1, |
| 52 | + limit_train_batches=12, |
| 53 | + limit_val_batches=6, |
| 54 | + limit_test_batches=12, |
| 55 | + callbacks=[checkpoint_callback], |
| 56 | + logger=False, |
| 57 | + ) |
| 58 | + trainer.fit(model) |
| 59 | + assert os.listdir(tmpdir) == ['epoch=00.ckpt'] |
| 60 | + |
| 61 | + best_model_paths = [checkpoint_callback.best_model_path] |
| 62 | + results = [] |
| 63 | + |
| 64 | + for idx in range(3, 6): |
| 65 | + # load from checkpoint |
| 66 | + trainer = pl.Trainer( |
| 67 | + default_root_dir=tmpdir, |
| 68 | + max_epochs=idx, |
| 69 | + limit_train_batches=12, |
| 70 | + limit_val_batches=12, |
| 71 | + limit_test_batches=12, |
| 72 | + resume_from_checkpoint=best_model_paths[-1], |
| 73 | + progress_bar_refresh_rate=0, |
| 74 | + ) |
| 75 | + trainer.fit(model) |
| 76 | + trainer.test() |
| 77 | + results.append(deepcopy(trainer.callback_metrics)) |
| 78 | + best_model_paths.append(trainer.checkpoint_callback.best_model_path) |
| 79 | + |
| 80 | + for idx in range(len(results) - 1): |
| 81 | + assert results[idx]["val_loss"] > results[idx + 1]["val_loss"] |
| 82 | + |
| 83 | + for idx, best_model_path in enumerate(best_model_paths): |
| 84 | + if idx == 0: |
| 85 | + assert best_model_path.endswith(f"epoch=0{idx}.ckpt") |
| 86 | + else: |
| 87 | + assert f"epoch={idx + 1}" in best_model_path |
0 commit comments