-
Notifications
You must be signed in to change notification settings - Fork 79
add support for custom metric function for mixed precision #1420
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
Idan-BenAmi
merged 6 commits into
SonySemiconductorSolutions:main
from
itai-berman:task_loss_api
Apr 28, 2025
Merged
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
eb7d615
add support for custom metric function for mixed precision
itai-berman 1ae808f
remove duplicate custom metric function and keep only single entry point
itai-berman 838d309
add custom_metric_fn description to docstring
itai-berman 85b0de7
add check that returned type is float
itai-berman b70bb65
add unit test to mp custom metric
itai-berman 0f9017c
move test to common and remove fixture
itai-berman 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
101 changes: 101 additions & 0 deletions
101
tests_pytest/common_tests/unit_tests/core/mixed_precision/test_custom_metric_function.py
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,101 @@ | ||
| # Copyright 2025 Sony Semiconductor Israel, 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 numpy as np | ||
|
|
||
| from unittest.mock import Mock | ||
|
|
||
| from model_compression_toolkit.core import MixedPrecisionQuantizationConfig | ||
| from model_compression_toolkit.core.common.mixed_precision.sensitivity_evaluation import SensitivityEvaluation | ||
| from model_compression_toolkit.core.common.model_builder_mode import ModelBuilderMode | ||
|
|
||
|
|
||
| def custom_float_metric(model_mp) -> float: | ||
| return 100.0 | ||
|
|
||
|
|
||
| def custom_np_float_metric(model_mp) -> np.floating: | ||
| return np.float64(100.0) | ||
|
|
||
|
|
||
| def custom_str_metric(model_mp) -> str: | ||
| return 'test' | ||
|
|
||
|
|
||
| def custom_none_metric(model_mp): | ||
| return None | ||
|
|
||
|
|
||
| def get_sensitivity_evaluator(custom_metric_fn): | ||
| mock_graph = Mock() | ||
| mock_graph.get_topo_sorted_nodes.return_value = ['test', 'this', 'is', 'reset'] | ||
| mock_graph.get_outputs.return_value = [] | ||
|
|
||
| def representative_data_gen() -> list: | ||
| for _ in range(5): | ||
| yield np.random.randn(2, 3, 248, 248) | ||
|
|
||
| mock_fw_info = Mock() | ||
|
|
||
| def custom_model_builder_return_value(*args, **kwargs): | ||
| mode = kwargs.get('mode') | ||
| if mode == ModelBuilderMode.FLOAT: | ||
| return (None, None) | ||
| else: | ||
| return (None, None, None) | ||
|
|
||
| def custom_to_tensor(img): | ||
| return img | ||
|
|
||
| mock_fw_impl = Mock() | ||
| mock_fw_impl.model_builder.side_effect = custom_model_builder_return_value | ||
| mock_fw_impl.to_tensor.side_effect = custom_to_tensor | ||
|
|
||
| mock_set_layer_to_bitwidth = Mock() | ||
|
|
||
| mp_cfg = MixedPrecisionQuantizationConfig(custom_metric_fn=custom_metric_fn) | ||
|
|
||
| sensitivity_eval = SensitivityEvaluation(graph=mock_graph, | ||
| quant_config=mp_cfg, | ||
| representative_data_gen=representative_data_gen, | ||
| fw_info=mock_fw_info, | ||
| fw_impl=mock_fw_impl, | ||
| set_layer_to_bitwidth=mock_set_layer_to_bitwidth | ||
| ) | ||
| sensitivity_eval._configure_bitwidths_model = lambda *args, **kwargs: None # Method does nothing | ||
| sensitivity_eval.model_mp = Mock() | ||
| return sensitivity_eval | ||
|
|
||
|
|
||
| class TestMPCustomMetricFunction: | ||
|
|
||
| @pytest.mark.parametrize("metric_fn, expected", [ | ||
| (custom_float_metric, 100.0), | ||
| (custom_np_float_metric, np.float64(100.0)), | ||
| ]) | ||
| def test_valid_metric_function(self, metric_fn, expected): | ||
| sensitivity_eval = get_sensitivity_evaluator(metric_fn) | ||
| assert len(sensitivity_eval.interest_points) == 0 | ||
| assert sensitivity_eval.compute_metric(Mock()) == expected | ||
|
|
||
| @pytest.mark.parametrize("metric_fn, expected", [ | ||
| (custom_str_metric, str.__name__), | ||
| (custom_none_metric, type(None).__name__), | ||
| ]) | ||
| def test_type_invalid_metric_function(self, metric_fn, expected): | ||
| sensitivity_eval = get_sensitivity_evaluator(metric_fn) | ||
| assert len(sensitivity_eval.interest_points) == 0 | ||
| with pytest.raises(TypeError, match=f'The custom_metric_fn is expected to return float or numpy float, got {expected}'): | ||
| sensitivity_metric = sensitivity_eval.compute_metric(Mock()) |
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.
Please add description to docstring, including the expected api of the function (args it accepts and what it should return).