Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add ModelCheckpoint.to_yaml method #3048

Merged
merged 9 commits into from
Sep 27, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 13 additions & 1 deletion pytorch_lightning/callbacks/model_checkpoint.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,10 @@

import os
import re
import yaml
from copy import deepcopy
from typing import Any, Dict, Optional
from typing import Any, Dict, Optional, Union
from pathlib import Path

import numpy as np
import torch
Expand Down Expand Up @@ -531,3 +533,13 @@ def _do_check_save(
if cur_path != filepath:
self._del_model(cur_path)

def to_yaml(self, filepath: Optional[Union[str, Path]] = None):
"""
Saves the `best_k_models` dict containing the checkpoint
paths with the corresponding scores to a YAML file.
"""
best_k = {k: v.item() for k, v in self.best_k_models.items()}
if filepath is None:
filepath = os.path.join(self.dirpath, "best_k_models.yaml")
with open(filepath, "w") as fp:
yaml.dump(best_k, fp)
19 changes: 19 additions & 0 deletions tests/callbacks/test_model_checkpoint.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import os
import yaml
import pickle
import platform
import re
Expand Down Expand Up @@ -36,6 +37,24 @@ def test_model_checkpoint_with_non_string_input(tmpdir, save_top_k):
)


@pytest.mark.parametrize('save_top_k', [-1, 0, 1, 2])
def test_model_checkpoint_to_yaml(tmpdir, save_top_k):
""" Test that None in checkpoint callback is valid and that chkp_path is set correctly """
tutils.reset_seed()
model = EvalModelTemplate()

checkpoint = ModelCheckpoint(filepath=tmpdir, monitor='val_loss', save_top_k=save_top_k)

trainer = Trainer(default_root_dir=tmpdir, checkpoint_callback=checkpoint, overfit_batches=0.20, max_epochs=2)
trainer.fit(model)

path_yaml = os.path.join(tmpdir, 'best_k_models.yaml')
checkpoint.to_yaml(path_yaml)
d = yaml.full_load(open(path_yaml, 'r'))
best_k = {k: v.item() for k, v in checkpoint.best_k_models.items()}
assert d == best_k


@pytest.mark.parametrize(
"logger_version,expected",
[(None, "version_0"), (1, "version_1"), ("awesome", "awesome")],
Expand Down