-
Notifications
You must be signed in to change notification settings - Fork 78
refactor: formalize artifact saving #492
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
gsprochette
wants to merge
8
commits into
main
Choose a base branch
from
refactor/formalize-artifact-saving
base: main
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.
+307
−60
Open
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
cebc8c4
refactor: formalize artifact saving
gsprochette 6d452d4
fix: load artifacts docstring
gsprochette 6994cdc
fix: register torch compile save as save artifacts
gsprochette b87307b
fix: address bugbot comments
gsprochette 0697d1a
fix: make typing tighter for artifact loading
gsprochette 4595a41
fix: circular import
gsprochette 033ca4b
docs: add deprecation warning to torch_artifact save/load and save fi…
gsprochette 88821bb
docs: fix enum docstring
gsprochette 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
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 |
|---|---|---|
|
|
@@ -30,6 +30,7 @@ | |
| from transformers import pipeline | ||
|
|
||
| from pruna import SmashConfig | ||
| from pruna.engine.load_artifacts import load_artifacts | ||
| from pruna.engine.utils import load_json_config, move_to_device, set_to_best_available_device | ||
| from pruna.logging.logger import pruna_logger | ||
|
|
||
|
|
@@ -56,6 +57,8 @@ def load_pruna_model(model_path: str | Path, **kwargs) -> tuple[Any, SmashConfig | |
| """ | ||
| smash_config = SmashConfig() | ||
| smash_config.load_from_json(model_path) | ||
| if "torch_artifacts" in smash_config.load_fns: | ||
| _convert_to_artifact(smash_config, model_path) | ||
|
Collaborator
Author
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. @simlang in response to your comment I removed the logic in save.py and added this function:
Let me know if that's to your liking |
||
| # since the model was just loaded from a file, we do not need to prepare saving anymore | ||
| smash_config._prepare_saving = False | ||
|
|
||
|
|
@@ -64,11 +67,6 @@ def load_pruna_model(model_path: str | Path, **kwargs) -> tuple[Any, SmashConfig | |
| if len(smash_config.load_fns) == 0: | ||
| raise ValueError("Load function has not been set.") | ||
|
|
||
| # load torch artifacts if they exist | ||
| if LOAD_FUNCTIONS.torch_artifacts.name in smash_config.load_fns: | ||
| load_torch_artifacts(model_path, **kwargs) | ||
| smash_config.load_fns.remove(LOAD_FUNCTIONS.torch_artifacts.name) | ||
|
|
||
gsprochette marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| if len(smash_config.load_fns) > 1: | ||
| pruna_logger.error(f"Load functions not used: {smash_config.load_fns[1:]}") | ||
|
|
||
|
|
@@ -78,9 +76,41 @@ def load_pruna_model(model_path: str | Path, **kwargs) -> tuple[Any, SmashConfig | |
| if any(algorithm is not None for algorithm in smash_config.reapply_after_load.values()): | ||
| model = resmash_fn(model, smash_config) | ||
|
|
||
| # load artifacts (e.g. speed up the warmup or make it more consistent) | ||
| load_artifacts(model, model_path, smash_config) | ||
|
|
||
| return model, smash_config | ||
|
|
||
|
|
||
| def _convert_to_artifact(smash_config: SmashConfig, model_path: str | Path) -> None: | ||
| """Convert legacy 'torch_artifacts' entries to the new artifact-based fields. | ||
|
|
||
| This handles older configs that still store 'torch_artifacts' under | ||
| 'save_fns' or 'load_fns' instead of the corresponding '*_artifacts_fns' | ||
| fields. | ||
| """ | ||
| updated = False | ||
|
|
||
| if "torch_artifacts" in smash_config.save_fns: | ||
| smash_config.save_fns.remove("torch_artifacts") | ||
| smash_config.save_artifacts_fns.append("torch_artifacts") | ||
| updated = True | ||
|
|
||
| if "torch_artifacts" in smash_config.load_fns: | ||
| smash_config.load_fns.remove("torch_artifacts") | ||
| smash_config.load_artifacts_fns.append("torch_artifacts") | ||
| updated = True | ||
|
|
||
| if updated: | ||
| pruna_logger.warning( | ||
| "The legacy 'torch_artifacts' save/load function entry in your SmashConfig is deprecated; " | ||
| "your config file has been updated automatically. If you downloaded this smashed model, " | ||
| "please ask the provider to update their model by loading it once with a recent version " | ||
| "of Pruna and re-uploading it." | ||
| ) | ||
| smash_config.save_to_json(model_path) | ||
|
|
||
|
|
||
| def load_pruna_model_from_pretrained( | ||
| repo_id: str, | ||
| revision: Optional[str] = None, | ||
|
|
@@ -440,23 +470,6 @@ def load_quantized_model(quantized_path: str | Path) -> Any: | |
| ) | ||
|
|
||
|
|
||
| def load_torch_artifacts(model_path: str | Path, **kwargs) -> None: | ||
| """ | ||
| Load a torch artifacts from the given model path. | ||
|
|
||
| Parameters | ||
| ---------- | ||
| model_path : str | Path | ||
| The path to the model directory. | ||
| **kwargs : Any | ||
| Additional keyword arguments to pass to the model loading function. | ||
| """ | ||
| artifact_path = Path(model_path) / "artifact_bytes.bin" | ||
| artifact_bytes = artifact_path.read_bytes() | ||
|
|
||
| torch.compiler.load_cache_artifacts(artifact_bytes) | ||
|
|
||
|
|
||
| def load_hqq_diffusers(path: str | Path, smash_config: SmashConfig, **kwargs) -> Any: | ||
| """ | ||
| Load a diffusers model from the given model path. | ||
|
|
@@ -580,7 +593,6 @@ class LOAD_FUNCTIONS(Enum): # noqa: N801 | |
| pickled = partial(load_pickled) | ||
| hqq = partial(load_hqq) | ||
| hqq_diffusers = partial(load_hqq_diffusers) | ||
| torch_artifacts = partial(load_torch_artifacts) | ||
|
|
||
| def __call__(self, *args, **kwargs) -> Any: | ||
| """ | ||
|
|
||
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 |
|---|---|---|
| @@ -0,0 +1,123 @@ | ||
| # Copyright 2025 - Pruna AI GmbH. All rights reserved. | ||
| # | ||
| # Licensed under the Apache License, Version 2.0 (the "License"); | ||
| # you may not use this file except in compliance with the License. | ||
| # You may obtain a copy of the License at | ||
| # | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. | ||
| from __future__ import annotations | ||
|
|
||
| from enum import Enum | ||
| from functools import partial | ||
| from pathlib import Path | ||
| from typing import Any | ||
|
|
||
| import torch | ||
|
|
||
| from pruna.config.smash_config import SmashConfig | ||
| from pruna.logging.logger import pruna_logger | ||
|
|
||
|
|
||
| def load_artifacts(model: Any, model_path: str | Path, smash_config: SmashConfig) -> None: | ||
| """ | ||
| Load available artifacts. | ||
|
|
||
| This function is intended to be called after the main model load function. | ||
| It loads artifacts specific to different algorithms into the pre-loaded model. | ||
|
|
||
| Parameters | ||
| ---------- | ||
| model : Any | ||
| The model to load the artifacts for. | ||
| model_path : str | Path | ||
| The directory to load the artifacts from. | ||
| smash_config : SmashConfig | ||
| The SmashConfig object containing the load and save functions. | ||
|
|
||
| Returns | ||
| ------- | ||
| None | ||
| The function does not return anything. | ||
| """ | ||
| artifact_fns = getattr(smash_config, "load_artifacts_fns", []) | ||
| if not artifact_fns: | ||
| return | ||
|
|
||
| for fn_name in artifact_fns: | ||
| # Only handle artifact loaders we explicitly know about here. | ||
| if fn_name not in LOAD_ARTIFACTS_FUNCTIONS.__members__: | ||
| continue | ||
|
|
||
| LOAD_ARTIFACTS_FUNCTIONS[fn_name](model, model_path, smash_config) | ||
|
|
||
|
|
||
| def load_torch_artifacts(model: Any, model_path: str | Path, smash_config: SmashConfig) -> None: | ||
| """ | ||
| Load torch artifacts from the given model path. | ||
|
|
||
| Parameters | ||
| ---------- | ||
| model : Any | ||
| The model to load the artifacts for. | ||
| model_path : str | Path | ||
| The directory to load the artifacts from. | ||
| smash_config : SmashConfig | ||
| The SmashConfig object containing the load and save functions. | ||
| """ | ||
| artifact_path = Path(model_path) / "artifact_bytes.bin" | ||
| if not artifact_path.exists(): | ||
| pruna_logger.error(f"No torch artifacts found at {artifact_path}; skipping torch artifact loading.") | ||
| return | ||
|
|
||
| pruna_logger.info(f"Loading torch artifacts from {artifact_path}") | ||
| artifact_bytes = artifact_path.read_bytes() | ||
|
|
||
| torch.compiler.load_cache_artifacts(artifact_bytes) | ||
|
|
||
|
|
||
| class LOAD_ARTIFACTS_FUNCTIONS(Enum): # noqa: N801 | ||
| """ | ||
| Enumeration of *artifact* load functions. | ||
|
|
||
| Artifact loaders are functions that are called after the main model load | ||
| has completed. They attach additional runtime state to the already-loaded | ||
| model (e.g. compilation cache). | ||
|
|
||
| This enum provides callable functions for loading such artifacts. | ||
|
|
||
| Parameters | ||
| ---------- | ||
| value : callable | ||
| The artifact load function to be called. | ||
| names : str | ||
| The name of the enum member. | ||
| module : str | ||
| The module where the enum is defined. | ||
| qualname : str | ||
| The qualified name of the enum. | ||
| type : type | ||
| The type of the enum. | ||
| start : int | ||
| The start index for auto-numbering enum values. | ||
| boundary : enum.FlagBoundary or None | ||
| Boundary handling mode used by the Enum functional API for Flag and | ||
| IntFlag enums. | ||
|
|
||
| Examples | ||
| -------- | ||
| >>> LOAD_ARTIFACTS_FUNCTIONS.torch_artifacts(model, model_path, smash_config) | ||
| # Torch artifacts loaded into the current runtime | ||
| """ | ||
|
|
||
| torch_artifacts = partial(load_torch_artifacts) | ||
|
|
||
| def __call__(self, *args, **kwargs) -> None: | ||
| """Call the underlying load function.""" | ||
| if self.value is not None: | ||
| self.value(*args, **kwargs) |
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
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.
Uh oh!
There was an error while loading. Please reload this page.