-
Notifications
You must be signed in to change notification settings - Fork 19
[Transform] [Utils] Support precision, add torch dtype validation #414
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
Merged
Merged
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
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
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
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,74 @@ | ||
# 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 typing import Annotated, Any | ||
|
||
import torch | ||
from pydantic import GetCoreSchemaHandler, GetJsonSchemaHandler | ||
from pydantic.json_schema import JsonSchemaValue | ||
from pydantic_core import core_schema | ||
|
||
|
||
__all__ = ["TorchDtype"] | ||
|
||
|
||
class _TorchDtypeAnnotation: | ||
@classmethod | ||
def __get_pydantic_core_schema__( | ||
cls, | ||
_source_type: Any, | ||
_handler: GetCoreSchemaHandler, | ||
) -> core_schema.CoreSchema: | ||
# support strings of the form `torch.xxx` or `xxx` | ||
def validate_from_str(name: str) -> torch.dtype: | ||
name = name.removeprefix("torch.") | ||
try: | ||
value = getattr(torch, name) | ||
assert isinstance(value, torch.dtype) | ||
except Exception: | ||
raise ValueError(f"No such torch dtype `torch.{name}`") | ||
|
||
return value | ||
|
||
# package validation into a schema (which also validates str type) | ||
from_str_schema = core_schema.chain_schema( | ||
[ | ||
core_schema.str_schema(), | ||
core_schema.no_info_plain_validator_function(validate_from_str), | ||
] | ||
) | ||
|
||
return core_schema.json_or_python_schema( | ||
json_schema=from_str_schema, | ||
python_schema=core_schema.union_schema( | ||
[ | ||
# support both torch.dtype or strings | ||
core_schema.is_instance_schema(torch.dtype), | ||
from_str_schema, | ||
] | ||
), | ||
# serialize as `torch.xxx` | ||
serialization=core_schema.plain_serializer_function_ser_schema( | ||
lambda instance: str(instance) | ||
), | ||
) | ||
|
||
@classmethod | ||
def __get_pydantic_json_schema__( | ||
cls, _core_schema: core_schema.CoreSchema, handler: GetJsonSchemaHandler | ||
) -> JsonSchemaValue: | ||
return handler(core_schema.str_schema()) | ||
|
||
|
||
TorchDtype = Annotated[torch.dtype, _TorchDtypeAnnotation] |
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 |
---|---|---|
@@ -0,0 +1,79 @@ | ||
# 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. | ||
|
||
import pytest | ||
import torch | ||
from compressed_tensors.utils.type import TorchDtype | ||
from pydantic import BaseModel, Field | ||
from pydantic_core._pydantic_core import ValidationError | ||
|
||
|
||
class DummyModel(BaseModel): | ||
dtype: TorchDtype = Field(default=torch.float32) | ||
|
||
|
||
@pytest.mark.unit | ||
def test_default_value(): | ||
model = DummyModel() | ||
assert model.dtype == torch.float32 | ||
|
||
|
||
@pytest.mark.unit | ||
def test_value_override(): | ||
model = DummyModel() | ||
model.dtype = torch.float16 | ||
assert model.dtype == torch.float16 | ||
|
||
|
||
@pytest.mark.unit | ||
def test_validation(): | ||
DummyModel(dtype=torch.float16) | ||
DummyModel(dtype="torch.float16") | ||
DummyModel(dtype="float16") | ||
|
||
with pytest.raises(ValidationError): | ||
model = DummyModel(dtype="notatype") | ||
|
||
|
||
@pytest.mark.unit | ||
def test_serialization(): | ||
model = DummyModel() | ||
assert model.model_dump()["dtype"] == "torch.float32" | ||
assert DummyModel.model_validate(model.model_dump()) == model | ||
|
||
model = DummyModel(dtype=torch.float16) | ||
assert model.model_dump()["dtype"] == "torch.float16" | ||
assert DummyModel.model_validate(model.model_dump()) == model | ||
|
||
model = DummyModel() | ||
model.dtype = torch.float16 | ||
assert model.model_dump()["dtype"] == "torch.float16" | ||
assert DummyModel.model_validate(model.model_dump()) == model | ||
|
||
|
||
@pytest.mark.unit | ||
def test_deserialization(): | ||
dummy_dict = {"dtype": "torch.float16"} | ||
assert DummyModel.model_validate(dummy_dict).dtype == torch.float16 | ||
|
||
dummy_dict = {"dtype": "float16"} | ||
assert DummyModel.model_validate(dummy_dict).dtype == torch.float16 | ||
|
||
with pytest.raises(ValueError): | ||
dummy_dict = {"dtype": "notatype"} | ||
DummyModel.model_validate(dummy_dict) | ||
|
||
with pytest.raises(ValueError): | ||
dummy_dict = {"dtype": "torch.notatype"} | ||
DummyModel.model_validate(dummy_dict) |
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.