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鈥檒l occasionally send you account related emails.

Already on GitHub? Sign in to your account

Ignore parameters causing ValueError when dumping to YAML #19804

Merged
merged 7 commits into from
Jun 6, 2024
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 2 additions & 0 deletions src/lightning/pytorch/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,8 @@ The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/).

- Fixed an issue with the LightningCLI not being able to set the `ModelCheckpoint(save_last=...)` argument ([#19808](https://github.com/Lightning-AI/pytorch-lightning/pull/19808))

- Fixed an issue causing ValueError for certain object such as TorchMetrics when dumping hyperparameters to YAML ([#19804](https://github.com/Lightning-AI/pytorch-lightning/pull/19804))


## [2.2.2] - 2024-04-11

Expand Down
2 changes: 1 addition & 1 deletion src/lightning/pytorch/core/saving.py
Original file line number Diff line number Diff line change
Expand Up @@ -359,7 +359,7 @@ def save_hparams_to_yaml(config_yaml: _PATH, hparams: Union[dict, Namespace], us
try:
v = v.name if isinstance(v, Enum) else v
yaml.dump(v)
except TypeError:
except (TypeError, ValueError):
warn(f"Skipping '{k}' parameter because it is not possible to safely dump to YAML.")
hparams[k] = type(v).__name__
else:
Expand Down
10 changes: 9 additions & 1 deletion tests/tests_pytorch/models/test_hparams.py
Original file line number Diff line number Diff line change
Expand Up @@ -552,7 +552,7 @@ def test_hparams_pickle_warning(tmp_path):
trainer.fit(model)


def test_hparams_save_yaml(tmp_path):
def test_save_hparams_to_yaml(tmp_path):
class Options(str, Enum):
option1name = "option1val"
option2name = "option2val"
Expand Down Expand Up @@ -590,6 +590,14 @@ def _compare_params(loaded_params, default_params: dict):
_compare_params(load_hparams_from_yaml(path_yaml), hparams)


def test_save_hparams_to_yaml_warning(tmp_path):
"""Test that we warn about unserializable parameters that need to be dropped."""
path_yaml = tmp_path / "hparams.yaml"
hparams = {"torch_type": torch.float32}
with pytest.warns(UserWarning, match="Skipping 'torch_type' parameter"):
save_hparams_to_yaml(path_yaml, hparams)


class NoArgsSubClassBoringModel(CustomBoringModel):
def __init__(self):
super().__init__()
Expand Down