-
Notifications
You must be signed in to change notification settings - Fork 37
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
auto save model in lightning #613
Closed
Closed
Changes from 7 commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
74f0609
auto save model in lightning
dbd354b
lightning: save model at each checkpoint if save_top_k == -1
15932a8
add type: model to lightning artifact
3c77b75
Merge branch 'main' into lightning-model
110b9aa
lightning: drop unused checkpoints
48309f5
lightning: add tests for log_model
a9e4587
merge
09d9f80
Merge branch 'main' into lightning-model
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 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 |
---|---|---|
@@ -1,22 +1,27 @@ | ||
# ruff: noqa: ARG002 | ||
import inspect | ||
from typing import Any, Dict, Optional | ||
from pathlib import Path | ||
from typing import Any, Dict, List, Optional, Union | ||
|
||
try: | ||
from lightning.fabric.utilities.logger import ( | ||
_convert_params, | ||
_sanitize_callable_params, | ||
_sanitize_params, | ||
) | ||
from lightning.pytorch.callbacks.model_checkpoint import ModelCheckpoint | ||
from lightning.pytorch.loggers.logger import Logger, rank_zero_experiment | ||
from lightning.pytorch.loggers.utilities import _scan_checkpoints | ||
from lightning.pytorch.utilities import rank_zero_only | ||
except ImportError: | ||
from lightning_fabric.utilities.logger import ( | ||
_convert_params, | ||
_sanitize_callable_params, | ||
_sanitize_params, | ||
) | ||
from pytorch_lightning.callbacks import ModelCheckpoint | ||
from pytorch_lightning.loggers.logger import Logger, rank_zero_experiment | ||
from pytorch_lightning.utilities.logger import _scan_checkpoints | ||
from pytorch_lightning.utilities import rank_zero_only | ||
|
||
from torch import is_tensor | ||
|
@@ -44,10 +49,11 @@ def _should_call_next_step(): | |
|
||
|
||
class DVCLiveLogger(Logger): | ||
def __init__( | ||
def __init__( # noqa: PLR0913 | ||
self, | ||
run_name: Optional[str] = "dvclive_run", | ||
prefix="", | ||
log_model: Union[str, bool] = False, | ||
experiment=None, | ||
dir: Optional[str] = None, # noqa: A002 | ||
resume: bool = False, | ||
|
@@ -72,6 +78,10 @@ def __init__( | |
if report == "notebook": | ||
# Force Live instantiation | ||
self.experiment # noqa: B018 | ||
self._log_model = log_model | ||
self._logged_model_time: Dict[str, float] = {} | ||
self._checkpoint_callback: Optional[ModelCheckpoint] = None | ||
self._all_checkpoint_paths: List[str] = [] | ||
|
||
@property | ||
def name(self): | ||
|
@@ -131,6 +141,42 @@ def log_metrics(self, metrics: Dict[str, Any], step: Optional[int] = None): | |
self.experiment._latest_studio_step -= 1 # noqa: SLF001 | ||
self.experiment.next_step() | ||
|
||
def after_save_checkpoint(self, checkpoint_callback: ModelCheckpoint) -> None: | ||
if self._log_model in [True, "all"]: | ||
self._checkpoint_callback = checkpoint_callback | ||
self._scan_checkpoints(checkpoint_callback) | ||
if self._log_model == "all" or ( | ||
self._log_model is True and checkpoint_callback.save_top_k == -1 | ||
): | ||
self._save_checkpoints(checkpoint_callback) | ||
|
||
@rank_zero_only | ||
def finalize(self, status: str) -> None: | ||
# Log best model. | ||
if self._checkpoint_callback: | ||
self._scan_checkpoints(self._checkpoint_callback) | ||
self._save_checkpoints(self._checkpoint_callback) | ||
best_model_path = self._checkpoint_callback.best_model_path | ||
self.experiment.log_artifact( | ||
best_model_path, name="best", type="model", cache=False | ||
) | ||
self.experiment.end() | ||
|
||
def _scan_checkpoints(self, checkpoint_callback: ModelCheckpoint) -> None: | ||
# get checkpoints to be saved with associated score | ||
checkpoints = _scan_checkpoints(checkpoint_callback, self._logged_model_time) | ||
|
||
# update model time and append path to list of all checkpoints | ||
for t, p, _, _ in checkpoints: | ||
self._logged_model_time[p] = t | ||
self._all_checkpoint_paths.append(p) | ||
|
||
def _save_checkpoints(self, checkpoint_callback: ModelCheckpoint) -> None: | ||
# drop unused checkpoints | ||
if not self._experiment._resume: # noqa: SLF001 | ||
for p in Path(checkpoint_callback.dirpath).iterdir(): | ||
if str(p) not in self._all_checkpoint_paths: | ||
p.unlink(missing_ok=True) | ||
Comment on lines
+178
to
+179
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. Let's be clear about this in the docs |
||
|
||
# save directory | ||
self.experiment.log_artifact(checkpoint_callback.dirpath) |
This file contains 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
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.
WDYT of creating a copy in "dvclive" folder (or in the checkpoints folder itself), at least for the best?
It seems that we would be changing the path of the registered model between experiments in the current behavior
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.
Yes, which I guess is also what other trackers do AFAICT? Do you think the path matters? Maybe it makes it easier to
dvc get
later, although we could make that work by the artifact name. No strong opinion from me.