model-compression-toolkit 2.3.0__py3-none-any.whl → 2.4.2__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- model_compression_toolkit/__init__.py +1 -1
- model_compression_toolkit/constants.py +9 -0
- model_compression_toolkit/core/__init__.py +2 -2
- model_compression_toolkit/core/common/collectors/histogram_collector.py +18 -19
- model_compression_toolkit/core/common/collectors/statistics_collector.py +7 -3
- model_compression_toolkit/core/common/collectors/weighted_histogram_collector.py +114 -0
- model_compression_toolkit/core/common/framework_implementation.py +26 -37
- model_compression_toolkit/core/common/framework_info.py +6 -0
- model_compression_toolkit/core/common/fusion/fusing_info.py +526 -0
- model_compression_toolkit/core/common/fusion/graph_fuser.py +52 -28
- model_compression_toolkit/core/common/graph/base_graph.py +125 -30
- model_compression_toolkit/core/common/graph/base_node.py +79 -57
- model_compression_toolkit/core/common/graph/memory_graph/compute_graph_max_cut.py +1 -1
- model_compression_toolkit/core/common/graph/memory_graph/cut.py +20 -12
- model_compression_toolkit/core/common/graph/memory_graph/max_cut_astar.py +2 -1
- model_compression_toolkit/core/common/graph/memory_graph/memory_graph.py +0 -3
- model_compression_toolkit/core/common/graph/virtual_activation_weights_node.py +67 -72
- model_compression_toolkit/core/common/hessian/hessian_info_service.py +31 -15
- model_compression_toolkit/core/common/hessian/hessian_scores_calculator.py +5 -3
- model_compression_toolkit/core/common/hessian/hessian_scores_request.py +7 -2
- model_compression_toolkit/core/common/mixed_precision/__init__.py +1 -0
- model_compression_toolkit/core/common/mixed_precision/bit_width_setter.py +2 -1
- model_compression_toolkit/core/common/mixed_precision/mixed_precision_candidates_filter.py +3 -12
- model_compression_toolkit/core/common/mixed_precision/mixed_precision_quantization_config.py +62 -5
- model_compression_toolkit/core/common/mixed_precision/mixed_precision_ru_helper.py +36 -131
- model_compression_toolkit/core/common/mixed_precision/mixed_precision_search_facade.py +35 -51
- model_compression_toolkit/core/common/mixed_precision/mixed_precision_search_manager.py +380 -424
- model_compression_toolkit/core/common/mixed_precision/resource_utilization_tools/resource_utilization.py +22 -10
- model_compression_toolkit/core/common/mixed_precision/resource_utilization_tools/resource_utilization_calculator.py +284 -167
- model_compression_toolkit/core/common/mixed_precision/resource_utilization_tools/resource_utilization_data.py +14 -94
- model_compression_toolkit/core/common/mixed_precision/search_methods/linear_programming.py +123 -307
- model_compression_toolkit/core/common/mixed_precision/sensitivity_eval/__init__.py +14 -0
- model_compression_toolkit/core/common/mixed_precision/sensitivity_eval/metric_calculators.py +424 -0
- model_compression_toolkit/core/common/mixed_precision/sensitivity_eval/sensitivity_evaluation.py +168 -0
- model_compression_toolkit/core/common/mixed_precision/sensitivity_eval/set_layer_to_bitwidth.py +56 -0
- model_compression_toolkit/core/common/mixed_precision/solution_refinement_procedure.py +92 -47
- model_compression_toolkit/core/common/model_collector.py +120 -20
- model_compression_toolkit/core/common/quantization/bit_width_config.py +181 -26
- model_compression_toolkit/core/common/quantization/candidate_node_quantization_config.py +8 -6
- model_compression_toolkit/core/common/quantization/debug_config.py +2 -0
- model_compression_toolkit/core/common/quantization/filter_nodes_candidates.py +2 -0
- model_compression_toolkit/core/common/quantization/node_quantization_config.py +89 -15
- model_compression_toolkit/core/common/quantization/quantization_params_generation/error_functions.py +2 -0
- model_compression_toolkit/core/common/quantization/quantization_params_generation/qparams_activations_computation.py +110 -33
- model_compression_toolkit/core/common/quantization/set_node_quantization_config.py +187 -33
- model_compression_toolkit/core/common/similarity_analyzer.py +1 -1
- model_compression_toolkit/core/common/statistics_correction/compute_activation_bias_correction_of_graph.py +3 -8
- model_compression_toolkit/core/common/statistics_correction/compute_bias_correction_of_graph.py +6 -4
- model_compression_toolkit/core/common/substitutions/batchnorm_reconstruction.py +19 -3
- model_compression_toolkit/core/common/substitutions/shift_negative_activation.py +94 -13
- model_compression_toolkit/core/common/substitutions/virtual_activation_weights_composition.py +35 -15
- model_compression_toolkit/core/common/substitutions/weights_activation_split.py +3 -3
- model_compression_toolkit/core/graph_prep_runner.py +5 -2
- model_compression_toolkit/core/keras/back2framework/mixed_precision_model_builder.py +38 -82
- model_compression_toolkit/core/keras/default_framework_info.py +2 -2
- model_compression_toolkit/core/keras/keras_implementation.py +57 -73
- model_compression_toolkit/core/keras/mixed_precision/configurable_activation_quantizer.py +8 -7
- model_compression_toolkit/core/keras/mixed_precision/configurable_weights_quantizer.py +6 -5
- model_compression_toolkit/core/pytorch/back2framework/mixed_precision_model_builder.py +50 -88
- model_compression_toolkit/core/pytorch/back2framework/pytorch_model_builder.py +52 -16
- model_compression_toolkit/core/pytorch/constants.py +1 -0
- model_compression_toolkit/core/pytorch/default_framework_info.py +2 -2
- model_compression_toolkit/core/pytorch/graph_substitutions/substitutions/convtranspose_dynamic_padding.py +77 -0
- model_compression_toolkit/core/pytorch/graph_substitutions/substitutions/scaled_dot_product_attention.py +1 -2
- model_compression_toolkit/core/pytorch/graph_substitutions/substitutions/shift_negative_activation.py +5 -5
- model_compression_toolkit/core/pytorch/hessian/activation_hessian_scores_calculator_pytorch.py +23 -61
- model_compression_toolkit/core/pytorch/mixed_precision/configurable_activation_quantizer.py +8 -11
- model_compression_toolkit/core/pytorch/mixed_precision/configurable_weights_quantizer.py +12 -10
- model_compression_toolkit/core/pytorch/pytorch_implementation.py +60 -63
- model_compression_toolkit/core/pytorch/reader/graph_builders.py +2 -0
- model_compression_toolkit/core/pytorch/reader/reader.py +31 -7
- model_compression_toolkit/core/pytorch/utils.py +2 -2
- model_compression_toolkit/core/quantization_prep_runner.py +1 -0
- model_compression_toolkit/core/runner.py +10 -24
- model_compression_toolkit/data_generation/pytorch/optimization_functions/image_initilization.py +3 -5
- model_compression_toolkit/exporter/model_exporter/pytorch/base_pytorch_exporter.py +62 -7
- model_compression_toolkit/exporter/model_exporter/pytorch/fakely_quant_onnx_pytorch_exporter.py +73 -15
- model_compression_toolkit/exporter/model_exporter/pytorch/fakely_quant_torchscript_pytorch_exporter.py +1 -1
- model_compression_toolkit/exporter/model_exporter/pytorch/pytorch_export_facade.py +26 -11
- model_compression_toolkit/exporter/model_wrapper/pytorch/builder/fully_quantized_model_builder.py +22 -10
- model_compression_toolkit/gptq/common/gptq_config.py +1 -1
- model_compression_toolkit/gptq/keras/quantization_facade.py +6 -2
- model_compression_toolkit/gptq/pytorch/gptq_training.py +3 -2
- model_compression_toolkit/gptq/pytorch/quantization_facade.py +7 -2
- model_compression_toolkit/logger.py +0 -2
- model_compression_toolkit/ptq/keras/quantization_facade.py +7 -2
- model_compression_toolkit/ptq/pytorch/quantization_facade.py +7 -2
- model_compression_toolkit/qat/pytorch/quantizer/quantization_builder.py +3 -2
- model_compression_toolkit/target_platform_capabilities/__init__.py +3 -2
- model_compression_toolkit/target_platform_capabilities/constants.py +1 -0
- model_compression_toolkit/target_platform_capabilities/schema/mct_current_schema.py +1 -1
- model_compression_toolkit/target_platform_capabilities/schema/schema_compatability.py +124 -0
- model_compression_toolkit/target_platform_capabilities/schema/v1.py +47 -67
- model_compression_toolkit/target_platform_capabilities/schema/v2.py +283 -0
- model_compression_toolkit/target_platform_capabilities/targetplatform2framework/attach2fw.py +2 -2
- model_compression_toolkit/target_platform_capabilities/targetplatform2framework/attach2keras.py +5 -10
- model_compression_toolkit/target_platform_capabilities/targetplatform2framework/attach2pytorch.py +6 -2
- model_compression_toolkit/target_platform_capabilities/targetplatform2framework/framework_quantization_capabilities.py +27 -7
- model_compression_toolkit/target_platform_capabilities/tpc_io_handler.py +64 -37
- model_compression_toolkit/target_platform_capabilities/tpc_models/tflite_tpc/v1/tpc.py +3 -2
- model_compression_toolkit/verify_packages.py +0 -1
- {model_compression_toolkit-2.3.0.dist-info → model_compression_toolkit-2.4.2.dist-info}/METADATA +31 -30
- {model_compression_toolkit-2.3.0.dist-info → model_compression_toolkit-2.4.2.dist-info}/RECORD +106 -101
- model_compression_toolkit/core/common/fusion/layer_fusing.py +0 -131
- model_compression_toolkit/core/common/mixed_precision/distance_weighting.py +0 -76
- model_compression_toolkit/core/common/mixed_precision/sensitivity_evaluation.py +0 -500
- model_compression_toolkit/core/common/mixed_precision/set_layer_to_bitwidth.py +0 -50
- {model_compression_toolkit-2.3.0.dist-info → model_compression_toolkit-2.4.2.dist-info}/LICENSE.md +0 -0
- {model_compression_toolkit-2.3.0.dist-info → model_compression_toolkit-2.4.2.dist-info}/WHEEL +0 -0
- {model_compression_toolkit-2.3.0.dist-info → model_compression_toolkit-2.4.2.dist-info}/top_level.txt +0 -0
|
@@ -57,10 +57,14 @@ FLOAT_BITWIDTH = 32
|
|
|
57
57
|
# In Mixed-Precision, a node can have multiple candidates for weights and activations quantization configuration.
|
|
58
58
|
# In order to display a single view of a node (for example, for logging in TensorBoard) we need to track the attributes
|
|
59
59
|
# that are shared among different candidates:
|
|
60
|
+
WEIGHTS_ATTRIBUTE = 'weights'
|
|
61
|
+
ACTIVATION_ATTRIBUTE = 'activation'
|
|
60
62
|
WEIGHTS_NBITS_ATTRIBUTE = 'weights_n_bits'
|
|
61
63
|
CORRECTED_BIAS_ATTRIBUTE = 'corrected_bias'
|
|
62
64
|
ACTIVATION_N_BITS_ATTRIBUTE = 'activation_n_bits'
|
|
63
65
|
SUPPORTED_INPUT_ACTIVATION_NBITS_ATTRIBUTE = 'supported_input_activation_n_bits'
|
|
66
|
+
WEIGHTS = 'weights'
|
|
67
|
+
ACTIVATION = 'activation'
|
|
64
68
|
|
|
65
69
|
# Quantization Parameters Iterative Search Defaults:
|
|
66
70
|
SYMMETRIC_TENSOR_N_ITER = 40
|
|
@@ -134,3 +138,8 @@ SHAPE = 'shape'
|
|
|
134
138
|
NODE_NAME = 'node_name'
|
|
135
139
|
TOTAL_SIZE = 'total_size'
|
|
136
140
|
NODE_OUTPUT_INDEX = 'node_output_index'
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
# Fusing Patterns constants
|
|
144
|
+
FUSED_LAYER_PATTERN = 'fused_layer_pattern'
|
|
145
|
+
FUSED_OP_QUANT_CONFIG = 'fused_op_quantization_config'
|
|
@@ -22,8 +22,8 @@ from model_compression_toolkit.core.common.quantization.quantization_config impo
|
|
|
22
22
|
from model_compression_toolkit.core.common.quantization.bit_width_config import BitWidthConfig
|
|
23
23
|
from model_compression_toolkit.core.common.quantization.core_config import CoreConfig
|
|
24
24
|
from model_compression_toolkit.core.common.mixed_precision.resource_utilization_tools.resource_utilization import ResourceUtilization
|
|
25
|
-
from model_compression_toolkit.core.common.mixed_precision.mixed_precision_quantization_config import
|
|
25
|
+
from model_compression_toolkit.core.common.mixed_precision.mixed_precision_quantization_config import (
|
|
26
|
+
MixedPrecisionQuantizationConfig, MpDistanceWeighting, MpMetricNormalization)
|
|
26
27
|
from model_compression_toolkit.core.keras.resource_utilization_data_facade import keras_resource_utilization_data
|
|
27
28
|
from model_compression_toolkit.core.pytorch.resource_utilization_data_facade import pytorch_resource_utilization_data
|
|
28
|
-
from model_compression_toolkit.core.common.mixed_precision.distance_weighting import MpDistanceWeighting
|
|
29
29
|
|
|
@@ -53,38 +53,37 @@ class HistogramCollector(BaseCollector):
|
|
|
53
53
|
"""
|
|
54
54
|
|
|
55
55
|
super().__init__()
|
|
56
|
-
self.
|
|
57
|
-
self.
|
|
58
|
-
self.
|
|
59
|
-
self.
|
|
56
|
+
self._n_bins = n_bins
|
|
57
|
+
self._bins = None
|
|
58
|
+
self._counts = None
|
|
59
|
+
self._histogram_per_iteration = []
|
|
60
60
|
|
|
61
|
-
def
|
|
61
|
+
def _merge_histograms(self):
|
|
62
62
|
"""
|
|
63
63
|
After collecting histogram per iteration, we merge these histograms to a single histogram
|
|
64
64
|
containing all samples from all iterations.
|
|
65
65
|
The merge is done in a lazy manner (is computed only when actually needed).
|
|
66
66
|
"""
|
|
67
|
-
if len(self.
|
|
67
|
+
if len(self._histogram_per_iteration) > 0:
|
|
68
68
|
# Stack all bins that were gathered during inference
|
|
69
|
-
bins_stack = np.vstack([hist[1] for hist in self.
|
|
69
|
+
bins_stack = np.vstack([hist[1] for hist in self._histogram_per_iteration])
|
|
70
70
|
|
|
71
71
|
# The combined histogram will be computed between new min/max (which is the min/max of all histograms).
|
|
72
72
|
# The bin width of the merged histogram is the minimal bin width among all histograms (to lose as less
|
|
73
73
|
# information as possible during the merge).
|
|
74
74
|
merged_histogram_min = np.min(bins_stack)
|
|
75
75
|
merged_histogram_max = np.max(bins_stack)
|
|
76
|
-
|
|
77
|
-
merged_histogram_bins = np.arange(merged_histogram_min, merged_histogram_max+merged_bin_width, merged_bin_width)
|
|
76
|
+
merged_histogram_bins = np.linspace(merged_histogram_min, merged_histogram_max, self._n_bins + 1)
|
|
78
77
|
|
|
79
78
|
merged_histogram_counts = None
|
|
80
|
-
for histogram in self.
|
|
79
|
+
for histogram in self._histogram_per_iteration: # Iterate all collected histograms and merge them
|
|
81
80
|
if merged_histogram_counts is None: # First histogram to consider
|
|
82
81
|
merged_histogram_counts = interpolate_histogram(merged_histogram_bins, histogram[1], histogram[0])
|
|
83
82
|
else: # Merge rest of histograms into existing final histogram
|
|
84
83
|
merged_histogram_counts += interpolate_histogram(merged_histogram_bins, histogram[1], histogram[0])
|
|
85
84
|
|
|
86
|
-
self.
|
|
87
|
-
self.
|
|
85
|
+
self._counts = merged_histogram_counts
|
|
86
|
+
self._bins = merged_histogram_bins
|
|
88
87
|
|
|
89
88
|
def scale(self, scale_factor: np.ndarray):
|
|
90
89
|
"""
|
|
@@ -102,7 +101,7 @@ class HistogramCollector(BaseCollector):
|
|
|
102
101
|
self.update_legal_status(is_illegal=True)
|
|
103
102
|
else:
|
|
104
103
|
bins, _ = self.get_histogram()
|
|
105
|
-
self.
|
|
104
|
+
self._bins = bins * scale_factor
|
|
106
105
|
|
|
107
106
|
def shift(self, shift_value: np.ndarray):
|
|
108
107
|
"""
|
|
@@ -120,7 +119,7 @@ class HistogramCollector(BaseCollector):
|
|
|
120
119
|
self.update_legal_status(is_illegal=True)
|
|
121
120
|
else:
|
|
122
121
|
bins, _ = self.get_histogram()
|
|
123
|
-
self.
|
|
122
|
+
self._bins = bins + shift_value
|
|
124
123
|
|
|
125
124
|
def get_histogram(self) -> Tuple[np.ndarray, np.ndarray]:
|
|
126
125
|
"""
|
|
@@ -130,9 +129,9 @@ class HistogramCollector(BaseCollector):
|
|
|
130
129
|
self.validate_data_correctness()
|
|
131
130
|
# If collected histograms (one per inference iteration) were not merged before, merge them and return the
|
|
132
131
|
# merged histogram.
|
|
133
|
-
if self.
|
|
134
|
-
self.
|
|
135
|
-
return self.
|
|
132
|
+
if self._bins is None or self._counts is None:
|
|
133
|
+
self._merge_histograms()
|
|
134
|
+
return self._bins, self._counts
|
|
136
135
|
|
|
137
136
|
def max(self):
|
|
138
137
|
"""
|
|
@@ -156,5 +155,5 @@ class HistogramCollector(BaseCollector):
|
|
|
156
155
|
Args:
|
|
157
156
|
x: Tensor going through the collector to update the histogram according to.
|
|
158
157
|
"""
|
|
159
|
-
count, bins = np.histogram(x, bins=self.
|
|
160
|
-
self.
|
|
158
|
+
count, bins = np.histogram(x, bins=self._n_bins)
|
|
159
|
+
self._histogram_per_iteration.append((count, bins))
|
|
@@ -17,13 +17,12 @@
|
|
|
17
17
|
import math
|
|
18
18
|
from copy import deepcopy
|
|
19
19
|
from typing import Any, Tuple
|
|
20
|
-
|
|
21
20
|
import numpy as np
|
|
22
21
|
|
|
23
|
-
from model_compression_toolkit.core.common.framework_info import FrameworkInfo, ChannelAxis
|
|
24
22
|
from model_compression_toolkit.core.common.collectors.histogram_collector import HistogramCollector
|
|
25
23
|
from model_compression_toolkit.core.common.collectors.mean_collector import MeanCollector
|
|
26
24
|
from model_compression_toolkit.core.common.collectors.min_max_per_channel_collector import MinMaxPerChannelCollector
|
|
25
|
+
from model_compression_toolkit.core.common.collectors.weighted_histogram_collector import WeightedHistogramCollector
|
|
27
26
|
|
|
28
27
|
|
|
29
28
|
class BaseStatsCollector(object):
|
|
@@ -71,21 +70,24 @@ class StatsCollector(BaseStatsCollector):
|
|
|
71
70
|
|
|
72
71
|
super().__init__()
|
|
73
72
|
self.hc = HistogramCollector()
|
|
73
|
+
self.weighted_hc = WeightedHistogramCollector()
|
|
74
74
|
self.mc = MeanCollector(axis=out_channel_axis)
|
|
75
75
|
self.mpcc = MinMaxPerChannelCollector(init_min_value=init_min_value,
|
|
76
76
|
init_max_value=init_max_value,
|
|
77
77
|
axis=out_channel_axis)
|
|
78
78
|
|
|
79
|
-
def update_statistics(self, x: Any):
|
|
79
|
+
def update_statistics(self, x: Any, weights: Any=None):
|
|
80
80
|
"""
|
|
81
81
|
Update statistics in all collectors with a new tensor to consider.
|
|
82
82
|
|
|
83
83
|
Args:
|
|
84
84
|
x: Tensor to consider when updating statistics.
|
|
85
|
+
weights: Weights tensor to consider when updating statistics.
|
|
85
86
|
"""
|
|
86
87
|
|
|
87
88
|
x = standardize_tensor(x)
|
|
88
89
|
self.hc.update(x)
|
|
90
|
+
self.weighted_hc.update(x, weights)
|
|
89
91
|
self.mc.update(x)
|
|
90
92
|
self.mpcc.update(x)
|
|
91
93
|
|
|
@@ -228,6 +230,7 @@ def shift_statistics(collector: BaseStatsCollector,
|
|
|
228
230
|
shifted_collector.mc.shift(shift_value)
|
|
229
231
|
if shifted_collector.require_collection():
|
|
230
232
|
shifted_collector.hc.shift(shift_value)
|
|
233
|
+
shifted_collector.weighted_hc.shift(shift_value)
|
|
231
234
|
|
|
232
235
|
return shifted_collector
|
|
233
236
|
|
|
@@ -253,5 +256,6 @@ def scale_statistics(collector: BaseStatsCollector,
|
|
|
253
256
|
scaled_collector.mc.scale(scale_value)
|
|
254
257
|
if scaled_collector.require_collection():
|
|
255
258
|
scaled_collector.hc.scale(scale_value)
|
|
259
|
+
scaled_collector.weighted_hc.scale(scale_value)
|
|
256
260
|
|
|
257
261
|
return scaled_collector
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
# Copyright 2025 Sony Semiconductor Israel, Inc. All rights reserved.
|
|
2
|
+
#
|
|
3
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
4
|
+
# you may not use this file except in compliance with the License.
|
|
5
|
+
# You may obtain a copy of the License at
|
|
6
|
+
#
|
|
7
|
+
# http://www.apache.org/licenses/LICENSE-2.0
|
|
8
|
+
#
|
|
9
|
+
# Unless required by applicable law or agreed to in writing, software
|
|
10
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
11
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
12
|
+
# See the License for the specific language governing permissions and
|
|
13
|
+
# limitations under the License.
|
|
14
|
+
# ==============================================================================
|
|
15
|
+
|
|
16
|
+
import numpy as np
|
|
17
|
+
from model_compression_toolkit.core.common.collectors.histogram_collector import HistogramCollector
|
|
18
|
+
from model_compression_toolkit.logger import Logger
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def check_broadcastable(x: np.ndarray, weights: np.ndarray) -> None:
|
|
22
|
+
"""
|
|
23
|
+
Checks if tensor 'weights' can be broadcasted to the shape of tensor 'x'.
|
|
24
|
+
|
|
25
|
+
Args:
|
|
26
|
+
x (np.ndarray): The target tensor.
|
|
27
|
+
weights (np.ndarray): The tensor to check broadcasting compatibility.
|
|
28
|
+
|
|
29
|
+
Raises:
|
|
30
|
+
Logger.critical: If 'weights' cannot be broadcasted to 'x'.
|
|
31
|
+
"""
|
|
32
|
+
# Get shapes
|
|
33
|
+
shape_x = x.shape
|
|
34
|
+
shape_w = weights.shape
|
|
35
|
+
|
|
36
|
+
# Ensure weights has less or equal dimensions than x
|
|
37
|
+
if len(shape_w) > len(shape_x):
|
|
38
|
+
Logger.critical(f"Tensor weights with shape {shape_w} has more dimensions than tensor a with shape {shape_x}.")
|
|
39
|
+
|
|
40
|
+
# Align shapes by padding weights' shape with leading ones
|
|
41
|
+
shape_w = (1,) * (len(shape_x) - len(shape_w)) + shape_w
|
|
42
|
+
|
|
43
|
+
# Check if each dimension is either equal or 1
|
|
44
|
+
for i, (sx, sw) in enumerate(zip(shape_x, shape_w)):
|
|
45
|
+
if not (sx == sw or sw == 1):
|
|
46
|
+
Logger.critical(f"Tensor weights with shape {shape_w} cannot be broadcasted to tensor a with shape {shape_x}. "
|
|
47
|
+
f"Dimension mismatch at index {i}: {sw} cannot be broadcasted to {sx}.")
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
class WeightedHistogramCollector(HistogramCollector):
|
|
51
|
+
"""
|
|
52
|
+
Collector for holding weighted histograms of tensors going through it.
|
|
53
|
+
Extends the functionality of the base HistogramCollector by incorporating weights
|
|
54
|
+
into the histogram calculation, allowing for weighted distributions.
|
|
55
|
+
"""
|
|
56
|
+
def __init__(self, n_bins: int = 2048):
|
|
57
|
+
"""
|
|
58
|
+
Args:
|
|
59
|
+
n_bins: Number of bins in the histogram.
|
|
60
|
+
"""
|
|
61
|
+
|
|
62
|
+
super().__init__(n_bins)
|
|
63
|
+
|
|
64
|
+
def update(self, x: np.ndarray, weights: np.ndarray = None):
|
|
65
|
+
"""
|
|
66
|
+
Update the current state of the histogram bins and counts based on a new
|
|
67
|
+
tensor that passes through the collector, taking weights into account.
|
|
68
|
+
|
|
69
|
+
Args:
|
|
70
|
+
x: Tensor that passes through the collector to update the histogram.
|
|
71
|
+
weights: Array of weights corresponding to the elements of the tensor `x`.
|
|
72
|
+
If not provided, uniform weights of 1 will be applied to all elements.
|
|
73
|
+
|
|
74
|
+
Details:
|
|
75
|
+
- The `weights` parameter allows each element of `x` to contribute a
|
|
76
|
+
weighted amount to the histogram bins, rather than contributing a simple count.
|
|
77
|
+
- This is particularly useful when the data being processed has an associated
|
|
78
|
+
importance, frequency, or probability value that should influence the histogram.
|
|
79
|
+
For example:
|
|
80
|
+
- Hessian values can serve as weights for each activation in `x`.
|
|
81
|
+
- Normalization of the histogram to reflect relative contributions.
|
|
82
|
+
- The method ensures that `x` and `weights` have matching shapes and logs
|
|
83
|
+
an error if this condition is not met.
|
|
84
|
+
"""
|
|
85
|
+
if weights is None or np.all(weights == 0):
|
|
86
|
+
weights = np.ones_like(x) # Assign uniform weights if none are provided.
|
|
87
|
+
|
|
88
|
+
# Checks if tensor 'weights' can be broadcasted to the shape of tensor 'x'.
|
|
89
|
+
check_broadcastable(x, weights)
|
|
90
|
+
|
|
91
|
+
# Get x's shape
|
|
92
|
+
x_shape = x.shape
|
|
93
|
+
|
|
94
|
+
# Get weight's shape
|
|
95
|
+
weights_shape = weights.shape
|
|
96
|
+
|
|
97
|
+
# Determine the correct shape for weights
|
|
98
|
+
weights_new_shape = list(weights_shape) # Convert to list for modification
|
|
99
|
+
|
|
100
|
+
# Ensure weights has the same number of dimensions as x
|
|
101
|
+
while len(weights_new_shape) < len(x_shape):
|
|
102
|
+
weights_new_shape.append(1) # Add singleton dimensions
|
|
103
|
+
|
|
104
|
+
# Reshape weights to the correct shape
|
|
105
|
+
weights = weights.reshape(weights_new_shape)
|
|
106
|
+
|
|
107
|
+
# Broadcast weights to match x's shape
|
|
108
|
+
weights = np.broadcast_to(weights, x_shape)
|
|
109
|
+
|
|
110
|
+
# Compute the weighted histogram.
|
|
111
|
+
count, bins = np.histogram(x, bins=self._n_bins, weights=weights)
|
|
112
|
+
|
|
113
|
+
# Store the weighted histogram (counts and bins) for this iteration.
|
|
114
|
+
self._histogram_per_iteration.append((count, bins))
|
|
@@ -13,24 +13,20 @@
|
|
|
13
13
|
# limitations under the License.
|
|
14
14
|
# ==============================================================================
|
|
15
15
|
from abc import ABC, abstractmethod
|
|
16
|
-
from typing import Callable, Any, List, Tuple,
|
|
16
|
+
from typing import Callable, Any, List, Tuple, Generator, Type
|
|
17
17
|
|
|
18
18
|
import numpy as np
|
|
19
19
|
|
|
20
20
|
from model_compression_toolkit.constants import HESSIAN_NUM_ITERATIONS
|
|
21
|
-
from model_compression_toolkit.core import MixedPrecisionQuantizationConfig
|
|
22
21
|
from model_compression_toolkit.core import common
|
|
23
22
|
from model_compression_toolkit.core.common import BaseNode
|
|
24
|
-
from model_compression_toolkit.core.common.collectors.statistics_collector import BaseStatsCollector
|
|
25
23
|
from model_compression_toolkit.core.common.framework_info import FrameworkInfo
|
|
26
24
|
from model_compression_toolkit.core.common.graph.base_graph import Graph
|
|
27
|
-
from model_compression_toolkit.core.common.hessian import HessianScoresRequest
|
|
28
|
-
from model_compression_toolkit.core.common.mixed_precision.sensitivity_evaluation import SensitivityEvaluation
|
|
25
|
+
from model_compression_toolkit.core.common.hessian import HessianScoresRequest
|
|
29
26
|
from model_compression_toolkit.core.common.model_builder_mode import ModelBuilderMode
|
|
30
27
|
from model_compression_toolkit.core.common.node_prior_info import NodePriorInfo
|
|
31
28
|
from model_compression_toolkit.core.common.quantization.core_config import CoreConfig
|
|
32
29
|
from model_compression_toolkit.core.common.quantization.quantization_config import QuantizationConfig
|
|
33
|
-
from model_compression_toolkit.core.common.user_info import UserInformation
|
|
34
30
|
|
|
35
31
|
|
|
36
32
|
class FrameworkImplementation(ABC):
|
|
@@ -38,6 +34,10 @@ class FrameworkImplementation(ABC):
|
|
|
38
34
|
An abstract class with abstract methods that should be implemented when supporting a new
|
|
39
35
|
framework in MCT.
|
|
40
36
|
"""
|
|
37
|
+
weights_quant_layer_cls: Type
|
|
38
|
+
activation_quant_layer_cls: Type
|
|
39
|
+
configurable_weights_quantizer_cls: Type
|
|
40
|
+
configurable_activation_quantizer_cls: Type
|
|
41
41
|
|
|
42
42
|
@property
|
|
43
43
|
def constants(self):
|
|
@@ -93,6 +93,17 @@ class FrameworkImplementation(ABC):
|
|
|
93
93
|
raise NotImplementedError(f'{self.__class__.__name__} has to implement the '
|
|
94
94
|
f'framework\'s to_tensor method.') # pragma: no cover
|
|
95
95
|
|
|
96
|
+
@abstractmethod
|
|
97
|
+
def is_tuple_of_tensors(self, obj: Any) -> bool:
|
|
98
|
+
"""
|
|
99
|
+
Check if a given object if a tuple of tensors
|
|
100
|
+
:param obj: Object to check its type
|
|
101
|
+
:return: True if obj is a tuple of tensors, False otherwise
|
|
102
|
+
"""
|
|
103
|
+
raise NotImplementedError(f'{self.__class__.__name__} has to implement the '
|
|
104
|
+
f'framework\'s is_tuple_of_tensors method.') # pragma: no cover
|
|
105
|
+
|
|
106
|
+
|
|
96
107
|
@abstractmethod
|
|
97
108
|
def model_reader(self,
|
|
98
109
|
model: Any,
|
|
@@ -137,13 +148,18 @@ class FrameworkImplementation(ABC):
|
|
|
137
148
|
@abstractmethod
|
|
138
149
|
def run_model_inference(self,
|
|
139
150
|
model: Any,
|
|
140
|
-
input_list: List[Any]
|
|
151
|
+
input_list: List[Any],
|
|
152
|
+
requires_grad: bool = False) -> Tuple[Any]:
|
|
141
153
|
"""
|
|
142
|
-
|
|
154
|
+
Executes the given model on the provided input data.
|
|
155
|
+
|
|
156
|
+
This method must be implemented by subclasses to provide framework-specific logic
|
|
157
|
+
for running inference (e.g., PyTorch, TensorFlow/Keras).
|
|
143
158
|
|
|
144
159
|
Args:
|
|
145
|
-
model:
|
|
146
|
-
input_list:
|
|
160
|
+
model: The framework-specific model instance.
|
|
161
|
+
input_list: A list of inputs for the model.
|
|
162
|
+
requires_grad: Whether to enable gradient computation. Defaults to `False`.
|
|
147
163
|
|
|
148
164
|
Returns:
|
|
149
165
|
The frameworks model's output.
|
|
@@ -311,33 +327,6 @@ class FrameworkImplementation(ABC):
|
|
|
311
327
|
f'framework\'s get_substitutions_after_second_moment_correction '
|
|
312
328
|
f'method.') # pragma: no cover
|
|
313
329
|
|
|
314
|
-
@abstractmethod
|
|
315
|
-
def get_sensitivity_evaluator(self,
|
|
316
|
-
graph: Graph,
|
|
317
|
-
quant_config: MixedPrecisionQuantizationConfig,
|
|
318
|
-
representative_data_gen: Callable,
|
|
319
|
-
fw_info: FrameworkInfo,
|
|
320
|
-
hessian_info_service: HessianInfoService = None,
|
|
321
|
-
disable_activation_for_metric: bool = False) -> SensitivityEvaluation:
|
|
322
|
-
"""
|
|
323
|
-
Creates and returns an object which handles the computation of a sensitivity metric for a mixed-precision
|
|
324
|
-
configuration (comparing to the float model).
|
|
325
|
-
|
|
326
|
-
Args:
|
|
327
|
-
graph: Graph to build its float and mixed-precision models.
|
|
328
|
-
quant_config: QuantizationConfig of how the model should be quantized.
|
|
329
|
-
representative_data_gen: Dataset to use for retrieving images for the models inputs.
|
|
330
|
-
fw_info: FrameworkInfo object with information about the specific framework's model.
|
|
331
|
-
disable_activation_for_metric: Whether to disable activation quantization when computing the MP metric.
|
|
332
|
-
hessian_info_service: HessianInfoService to fetch information based on Hessian-approximation.
|
|
333
|
-
|
|
334
|
-
Returns:
|
|
335
|
-
A function that computes the metric.
|
|
336
|
-
"""
|
|
337
|
-
|
|
338
|
-
raise NotImplementedError(f'{self.__class__.__name__} has to implement the '
|
|
339
|
-
f'framework\'s get_sensitivity_evaluator method.') # pragma: no cover
|
|
340
|
-
|
|
341
330
|
def get_node_prior_info(self, node: BaseNode,
|
|
342
331
|
fw_info: FrameworkInfo,
|
|
343
332
|
graph: Graph) -> NodePriorInfo:
|
|
@@ -22,6 +22,12 @@ from mct_quantizers import QuantizationMethod
|
|
|
22
22
|
from model_compression_toolkit.defaultdict import DefaultDict
|
|
23
23
|
|
|
24
24
|
|
|
25
|
+
# Default value to use for ops without kernel.
|
|
26
|
+
# This is a weird default, but it's used all over the place, so for now only extract it to const so that it can be
|
|
27
|
+
# referenced by variable instead of hard-coded.
|
|
28
|
+
DEFAULT_KERNEL_ATTRIBUTES = [None]
|
|
29
|
+
|
|
30
|
+
|
|
25
31
|
class ChannelAxis(Enum):
|
|
26
32
|
"""
|
|
27
33
|
|