Repository: Lightning-AI/pytorch-lightning
File: tests/checkpointing/test_model_checkpoint.py (Python)

Code before:
    )
    trainer.fit(TestModel())
    assert model_checkpoint.current_score == 0.3
    ckpts = [torch.load(str(ckpt)) for ckpt in tmpdir.listdir()]
    ckpts = [ckpt["callbacks"][type(model_checkpoint)] for ckpt in ckpts]
    assert sorted(ckpt["current_score"] for ckpt in ckpts) == [0.1, 0.2, 0.3]


@pytest.mark.parametrize("mode", ["min", "max"])
def test_current_score_when_nan(tmpdir, mode):
    """ Check that ModelCheckpoint handles NaN values correctly """
    class TestModel(BoringModel):
        def training_step(self, *args):
            self.log("foo", float("nan"))
            return super().training_step(*args)

    model_checkpoint = ModelCheckpoint(
        dirpath=tmpdir,
        save_top_k=1,
        monitor="foo",
        mode=mode,
    )
    trainer = Trainer(
        default_root_dir=tmpdir,
        fast_dev_run=True,
        callbacks=[model_checkpoint],
        logger=False,
        weights_summary=None,
        progress_bar_refresh_rate=0,
    )
    trainer.fit(TestModel())
    expected = float("inf" if mode == "min" else "-inf")
    assert model_checkpoint.best_model_score == expected
    assert model_checkpoint.current_score == expected


@pytest.mark.parametrize("hparams_type", [dict, Container])
def test_hparams_type(tmpdir, hparams_type):
    class TestModel(BoringModel):
        def __init__(self, hparams):
            super().__init__()
            self.save_hyperparameters(hparams)

    model_checkpoint = ModelCheckpoint(
        dirpath=tmpdir,
        save_top_k=1,
        monitor="foo",
    )
    trainer = Trainer(
        default_root_dir=tmpdir,
        fast_dev_run=True,

Review comment (suggestion):
I am thinking if in such case we shall rename the previous one
```suggestion
        (2, ['curr_epoch-v0.ckpt', 'curr_epoch-v1.ckpt']),
```
cc: @PyTorchLightning/core-contributors 

Code after:
    trainer = Trainer(
        default_root_dir=tmpdir,
        fast_dev_run=True,
        callbacks=[model_checkpoint],
        logger=False,
        weights_summary=None,
        progress_bar_refresh_rate=0,
    )
    hp = {"test_hp_0": 1, "test_hp_1": 2}
    hp = OmegaConf.create(hp) if hparams_type == Container else Namespace(**hp)
    model = TestModel(hp)
    trainer.fit(model)
    ckpt = trainer.checkpoint_connector.dump_checkpoint()
    if hparams_type == Container:
        assert isinstance(ckpt[model.CHECKPOINT_HYPER_PARAMS_KEY], hparams_type)
    else:
        # make sure it's not AttributeDict
        assert type(ckpt[model.CHECKPOINT_HYPER_PARAMS_KEY]) == hparams_type


@pytest.mark.parametrize('max_epochs', [3, 4])
@pytest.mark.parametrize(
    'save_top_k, expected',
    [
        (1, ['curr_epoch.ckpt']),
        (2, ['curr_epoch.ckpt', 'curr_epoch-v0.ckpt']),
    ]
)
def test_model_checkpoint_file_already_exists(tmpdir, max_epochs, save_top_k, expected):
    """
    Test that version is added to filename if required and it already exists in dirpath.
    """
    model_checkpoint = ModelCheckpoint(
        dirpath=tmpdir,
        filename='curr_epoch',
        save_top_k=save_top_k,
        monitor='epoch',
        mode='max',
    )
    trainer = Trainer(
        default_root_dir=tmpdir,
        callbacks=[model_checkpoint],
        max_epochs=max_epochs,
        limit_train_batches=2,
        limit_val_batches=2,
        logger=None,
        weights_summary=None,
        progress_bar_refresh_rate=0,
    )

    model = BoringModel()