-
Notifications
You must be signed in to change notification settings - Fork 3.6k
Add adapt_checkpoint_hparams hook for customizing checkpoint hyperparameter loading #21408
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
Open
arrdel
wants to merge
9
commits into
Lightning-AI:master
Choose a base branch
from
arrdel:add-adapt-checkpoint-hparams-hook-21255
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
910a712
Add adapt_checkpoint_hparams hook for customizing checkpoint hyperpar…
arrdel ad1a028
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] 998ea3e
refactor(cli): Add subcommand parameter to adapt_checkpoint_hparams h…
arrdel 00e7032
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] b3b1025
fix: Break long line in adapt_checkpoint_hparams docstring example
arrdel fc8cc3a
fix: Replace BoringCkptPathModel with AdaptHparamsModel to fix tensor…
arrdel a0f0d77
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] 17d3b30
fix: Change AdaptHparamsModel to inherit from BoringModel
arrdel 204afb7
fix: Pass hidden_dim explicitly in test to fix assertion
arrdel File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -495,6 +495,21 @@ def __init__(self, out_dim: int = 2, hidden_dim: int = 2) -> None: | |
| self.layer = torch.nn.Linear(32, out_dim) | ||
|
|
||
|
|
||
| class AdaptHparamsModel(BoringModel): | ||
| """Simple model for testing adapt_checkpoint_hparams hook without dynamic neural network layers. | ||
|
|
||
| This model stores hyperparameters as attributes without creating layers that would cause size mismatches when | ||
| hyperparameters are changed between fit and predict phases. | ||
|
|
||
| """ | ||
|
|
||
| def __init__(self, out_dim: int = 8, hidden_dim: int = 16) -> None: | ||
| super().__init__() | ||
| self.save_hyperparameters() | ||
| self.out_dim = out_dim | ||
| self.hidden_dim = hidden_dim | ||
|
|
||
|
|
||
| def test_lightning_cli_ckpt_path_argument_hparams(cleandir): | ||
| class CkptPathCLI(LightningCLI): | ||
| def add_arguments_to_parser(self, parser): | ||
|
|
@@ -562,6 +577,62 @@ def add_arguments_to_parser(self, parser): | |
| assert cli.model.layer.out_features == 4 | ||
|
|
||
|
|
||
| def test_adapt_checkpoint_hparams_hook_pop_keys(cleandir): | ||
| """Test that the adapt_checkpoint_hparams hook is called and modifications are applied.""" | ||
|
|
||
| class AdaptHparamsCLI(LightningCLI): | ||
| def adapt_checkpoint_hparams(self, subcommand: str, checkpoint_hparams: dict) -> dict: | ||
| """Remove out_dim and hidden_dim for non-fit subcommands.""" | ||
| if subcommand != "fit": | ||
| checkpoint_hparams.pop("out_dim", None) | ||
| checkpoint_hparams.pop("hidden_dim", None) | ||
|
Comment on lines
+587
to
+588
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. From a testing perspective there is no difference between |
||
| return checkpoint_hparams | ||
|
|
||
| # First, create a checkpoint by running fit | ||
| cli_args = ["fit", "--model.out_dim=3", "--model.hidden_dim=6", "--trainer.max_epochs=1"] | ||
| with mock.patch("sys.argv", ["any.py"] + cli_args): | ||
| cli = AdaptHparamsCLI(AdaptHparamsModel) | ||
|
|
||
| assert cli.config.fit.model.out_dim == 3 | ||
| assert cli.config.fit.model.hidden_dim == 6 | ||
|
|
||
| checkpoint_path = next(Path(cli.trainer.log_dir, "checkpoints").glob("*.ckpt")) | ||
|
|
||
| # Test that predict uses adapted hparams (without out_dim and hidden_dim) | ||
| cli_args = ["predict", f"--ckpt_path={checkpoint_path}", "--model.out_dim=5", "--model.hidden_dim=10"] | ||
| with mock.patch("sys.argv", ["any.py"] + cli_args): | ||
| cli = AdaptHparamsCLI(AdaptHparamsModel) | ||
|
|
||
| # Since we removed out_dim and hidden_dim for predict, the CLI values should be used | ||
| assert cli.config.predict.model.out_dim == 5 | ||
| assert cli.config.predict.model.hidden_dim == 10 | ||
|
|
||
|
|
||
| def test_adapt_checkpoint_hparams_hook_empty_dict(cleandir): | ||
| """Test that returning empty dict from adapt_checkpoint_hparams disables checkpoint hyperparameter loading.""" | ||
|
|
||
| class AdaptHparamsEmptyCLI(LightningCLI): | ||
| def adapt_checkpoint_hparams(self, subcommand: str, checkpoint_hparams: dict) -> dict: | ||
| """Disable checkpoint hyperparameter loading.""" | ||
| return {} | ||
|
|
||
| # First, create a checkpoint | ||
| cli_args = ["fit", "--model.out_dim=3", "--trainer.max_epochs=1"] | ||
| with mock.patch("sys.argv", ["any.py"] + cli_args): | ||
| cli = AdaptHparamsEmptyCLI(AdaptHparamsModel) | ||
|
|
||
| checkpoint_path = next(Path(cli.trainer.log_dir, "checkpoints").glob("*.ckpt")) | ||
|
|
||
| # Test that predict uses default values when hook returns empty dict | ||
| cli_args = ["predict", f"--ckpt_path={checkpoint_path}"] | ||
| with mock.patch("sys.argv", ["any.py"] + cli_args): | ||
| cli = AdaptHparamsEmptyCLI(AdaptHparamsModel) | ||
|
|
||
| # Model should use default values (out_dim=8, hidden_dim=16) | ||
| assert cli.config_init.predict.model.out_dim == 8 | ||
| assert cli.config_init.predict.model.hidden_dim == 16 | ||
|
|
||
|
|
||
| def test_lightning_cli_submodules(cleandir): | ||
| class MainModule(BoringModel): | ||
| def __init__(self, submodule1: LightningModule, submodule2: LightningModule, main_param: int = 1): | ||
|
|
||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Not really related to this new feature, but there is also my comment in #21116 (comment). Nobody responded to it. Maybe by default
fitshould not use the hparams from the checkpoint?Also this could be related #21255 (comment)
I am not really sure what to do here.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@arrdel any comment on this?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actually, it seems #21455 would fix this comment, I think.