-
Notifications
You must be signed in to change notification settings - Fork 144
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
[Export Refactor][Image Classification] create_dummy_input
function
#1880
Merged
dbogunowicz
merged 16 commits into
feature/damian/feature_branch_export
from
feature/damian/create_dummy_inputs_ic
Dec 11, 2023
Merged
Changes from 15 commits
Commits
Show all changes
16 commits
Select commit
Hold shift + click to select a range
6d8991c
initial commit
dbogunowicz 059ceab
looking good, time to cleanup
dbogunowicz b390c2e
Delete src/sparseml/export/helpers.py
dbogunowicz c2c8444
Delete tests/sparseml/export/test_helpers.py
dbogunowicz 6ce6ba5
ready for review
dbogunowicz 6f3e5e7
Merge branch 'feature/damian/create_model_ic' of github.com:neuralmag…
dbogunowicz 5dfbdcd
improve design
dbogunowicz 042c193
tests pass
dbogunowicz 29cfa1d
reuse _validate_dataset_num_classes
dbogunowicz ab73aec
initial commit
dbogunowicz f628532
Update src/sparseml/pytorch/image_classification/integration_helper_f…
dbogunowicz b93b634
Update src/sparseml/pytorch/image_classification/integration_helper_f…
dbogunowicz e7606cd
ready for review
dbogunowicz ea9cb61
Update src/sparseml/export/export.py
dbogunowicz 9572e0b
Update src/sparseml/integration_helper_functions.py
dbogunowicz 6e5f575
Merge remote-tracking branch 'origin/feature/damian/feature_branch_ex…
dbogunowicz 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
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 |
---|---|---|
@@ -0,0 +1,13 @@ | ||
# Copyright (c) 2021 - present / Neuralmagic, Inc. 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. |
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
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 |
---|---|---|
@@ -0,0 +1,105 @@ | ||
# Copyright (c) 2021 - present / Neuralmagic, Inc. 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 enum import Enum | ||
from pathlib import Path | ||
from typing import Any, Callable, Dict, Optional, Union | ||
|
||
from pydantic import BaseModel, Field | ||
|
||
from sparsezoo.utils.registry import RegistryMixin | ||
|
||
|
||
__all__ = ["IntegrationHelperFunctions", "infer_integration"] | ||
|
||
|
||
class Integrations(Enum): | ||
""" | ||
Holds the names of the available integrations. | ||
""" | ||
|
||
image_classification = "image-classification" | ||
|
||
|
||
class IntegrationHelperFunctions(RegistryMixin, BaseModel): | ||
""" | ||
Registry that maps names to helper functions | ||
for creation/export/manipulation of models for a specific | ||
integration. | ||
""" | ||
|
||
create_model: Optional[ | ||
Callable[ | ||
[Union[str, Path], Optional[Dict[str, Any]]][ | ||
"torch.nn.Module", Optional[Dict[str, Any]] # noqa F821 | ||
] | ||
] | ||
] = Field( | ||
description="A function that takes: " | ||
"- a source path to a PyTorch model " | ||
"- (optionally) a dictionary of additional arguments" | ||
"and returns: " | ||
"- a (sparse) PyTorch model " | ||
"- (optionally) a dictionary of additional arguments" | ||
) | ||
create_dummy_input: Optional[ | ||
Callable[Any]["torch.Tensor"] # noqa F821 | ||
] = Field( # noqa: F82 | ||
description="A function that takes: " | ||
"- a dictionary of arguments" | ||
"and returns: " | ||
"- a dummy input for the model (a torch.Tensor) " | ||
) | ||
export_model: Optional[Callable] = Field( | ||
description="A function that exports a (sparse) PyTorch " | ||
"model to an ONNX format appropriate for a " | ||
"deployment target." | ||
) | ||
apply_optimizations: Optional[Callable] = Field( | ||
description="A function that takes a set of " | ||
"optimizations and applies them to an ONNX model." | ||
) | ||
export_sample_inputs_outputs: Optional[Callable] = Field( | ||
description="A function that exports input/output samples given " | ||
"a (sparse) PyTorch model." | ||
) | ||
create_deployment_folder: Optional[Callable] = Field( | ||
description="A function that creates a " | ||
"deployment folder for the exporter ONNX model" | ||
"with the appropriate structure." | ||
) | ||
|
||
|
||
def infer_integration(source_path: Union[Path, str]) -> str: | ||
""" | ||
Infer the integration to use for exporting the model from the source_path. | ||
|
||
:param source_path: The path to the PyTorch model to export. | ||
:return: The name of the integration to use for exporting the model. | ||
""" | ||
from sparseml.pytorch.image_classification.utils.helpers import ( | ||
is_image_classification_model, | ||
) | ||
|
||
if is_image_classification_model(source_path): | ||
# import to register the image_classification integration helper functions | ||
import sparseml.pytorch.image_classification.integration_helper_functions # noqa F401 | ||
|
||
return Integrations.image_classification.value | ||
else: | ||
raise ValueError( | ||
f"Could not infer integration from source_path: {source_path}." | ||
f"Please specify an argument `integration` from one of" | ||
f"the available integrations: {list(Integrations)}." | ||
) |
72 changes: 72 additions & 0 deletions
72
src/sparseml/pytorch/image_classification/integration_helper_functions.py
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 |
---|---|---|
@@ -0,0 +1,72 @@ | ||
# Copyright (c) 2021 - present / Neuralmagic, Inc. 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 pathlib import Path | ||
from typing import Any, Callable, Dict, Optional, Tuple, Union | ||
|
||
import torch | ||
from pydantic import Field | ||
|
||
from src.sparseml.integration_helper_functions import ( | ||
IntegrationHelperFunctions, | ||
Integrations, | ||
) | ||
from src.sparseml.pytorch.image_classification.utils.helpers import ( | ||
create_model as create_image_classification_model, | ||
) | ||
|
||
|
||
def create_model( | ||
source_path: Union[Path, str], **kwargs | ||
) -> Tuple[torch.nn.Module, Dict[str, Any]]: | ||
""" | ||
A contract to create a model from a source path | ||
|
||
:param source_path: The path to the model | ||
:param kwargs: Additional kwargs to pass to the model creation function | ||
:return: A tuple of the | ||
- torch model | ||
- additional dictionary of useful objects created during model creation | ||
""" | ||
model, *_, validation_loader = create_image_classification_model( | ||
checkpoint_path=source_path, **kwargs | ||
) | ||
return model, dict(validation_loader=validation_loader) | ||
|
||
|
||
def create_dummy_input( | ||
validation_loader: Optional[torch.utils.data.DataLoader] = None, | ||
image_size: Optional[int] = 224, | ||
) -> torch.Tensor: | ||
""" | ||
A contract to create a dummy input for a model | ||
|
||
:param validation_loader: The validation loader to get a batch from. | ||
If None, a fake batch will be created | ||
:param image_size: The image size to use for the dummy input. Defaults to 224 | ||
:return: The dummy input as a torch tensor | ||
""" | ||
|
||
if not validation_loader: | ||
# create fake data for export | ||
validation_loader = [[torch.randn(1, 3, image_size, image_size)]] | ||
return next(iter(validation_loader))[0] | ||
|
||
|
||
@IntegrationHelperFunctions.register(name=Integrations.image_classification.value) | ||
class ImageClassification(IntegrationHelperFunctions): | ||
create_model: Callable[..., Tuple[torch.nn.Module, Dict[str, Any]]] = Field( | ||
default=create_model | ||
) | ||
create_dummy_input: Callable[..., torch.Tensor] = Field(default=create_dummy_input) |
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.
how do we expect this optional value to flow from the create model function? thinking we need to accept
**kwargs
in this signature to avoid edge cases for extra kwargs (ie arch key that we'll need)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.
I think that the flow is quite elegant and well-designed:
Maybe i'd call the variable more generically, i.e.
data_loader
instead ofvalidation_loader