mct-nightly 2.0.0.20240417.406__py3-none-any.whl → 2.0.0.20240419.358__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.
Files changed (60) hide show
  1. {mct_nightly-2.0.0.20240417.406.dist-info → mct_nightly-2.0.0.20240419.358.dist-info}/METADATA +1 -1
  2. {mct_nightly-2.0.0.20240417.406.dist-info → mct_nightly-2.0.0.20240419.358.dist-info}/RECORD +60 -57
  3. model_compression_toolkit/__init__.py +1 -1
  4. model_compression_toolkit/constants.py +2 -0
  5. model_compression_toolkit/core/common/graph/base_graph.py +2 -2
  6. model_compression_toolkit/core/common/graph/base_node.py +26 -9
  7. model_compression_toolkit/core/common/graph/functional_node.py +18 -1
  8. model_compression_toolkit/core/common/hessian/hessian_info_service.py +2 -3
  9. model_compression_toolkit/core/common/hessian/trace_hessian_request.py +1 -3
  10. model_compression_toolkit/core/common/network_editors/node_filters.py +4 -3
  11. model_compression_toolkit/core/common/quantization/node_quantization_config.py +0 -5
  12. model_compression_toolkit/core/common/quantization/quantization_config.py +5 -2
  13. model_compression_toolkit/core/common/quantization/quantization_params_generation/error_functions.py +67 -4
  14. model_compression_toolkit/core/common/quantization/quantization_params_generation/lut_kmeans_params.py +12 -4
  15. model_compression_toolkit/core/common/quantization/quantization_params_generation/power_of_two_selection.py +14 -4
  16. model_compression_toolkit/core/common/quantization/quantization_params_generation/qparams_computation.py +30 -3
  17. model_compression_toolkit/core/common/quantization/quantization_params_generation/qparams_weights_computation.py +17 -7
  18. model_compression_toolkit/core/common/quantization/quantization_params_generation/symmetric_selection.py +14 -3
  19. model_compression_toolkit/core/common/quantization/quantization_params_generation/uniform_selection.py +13 -3
  20. model_compression_toolkit/core/common/quantization/set_node_quantization_config.py +16 -3
  21. model_compression_toolkit/core/common/similarity_analyzer.py +16 -4
  22. model_compression_toolkit/core/common/substitutions/remove_identity.py +48 -0
  23. model_compression_toolkit/core/graph_prep_runner.py +10 -4
  24. model_compression_toolkit/core/keras/back2framework/keras_model_builder.py +4 -1
  25. model_compression_toolkit/core/keras/graph_substitutions/substitutions/batchnorm_folding.py +7 -7
  26. model_compression_toolkit/core/keras/graph_substitutions/substitutions/linear_collapsing.py +1 -1
  27. model_compression_toolkit/core/keras/graph_substitutions/substitutions/remove_identity.py +51 -0
  28. model_compression_toolkit/core/keras/graph_substitutions/substitutions/residual_collapsing.py +1 -1
  29. model_compression_toolkit/core/keras/keras_implementation.py +13 -11
  30. model_compression_toolkit/core/keras/keras_node_prior_info.py +4 -4
  31. model_compression_toolkit/core/keras/pruning/pruning_keras_implementation.py +4 -5
  32. model_compression_toolkit/core/keras/reader/common.py +2 -2
  33. model_compression_toolkit/core/keras/reader/node_builder.py +28 -9
  34. model_compression_toolkit/core/keras/tf_tensor_numpy.py +5 -2
  35. model_compression_toolkit/core/pytorch/back2framework/pytorch_model_builder.py +34 -21
  36. model_compression_toolkit/core/pytorch/graph_substitutions/substitutions/batchnorm_folding.py +8 -8
  37. model_compression_toolkit/core/pytorch/graph_substitutions/substitutions/const_holder_conv.py +2 -2
  38. model_compression_toolkit/core/pytorch/graph_substitutions/substitutions/linear_collapsing.py +1 -1
  39. model_compression_toolkit/core/pytorch/graph_substitutions/substitutions/relu_bound_to_power_of_2.py +4 -4
  40. model_compression_toolkit/core/pytorch/graph_substitutions/substitutions/remove_identity.py +50 -0
  41. model_compression_toolkit/core/pytorch/graph_substitutions/substitutions/residual_collapsing.py +1 -1
  42. model_compression_toolkit/core/pytorch/pruning/pruning_pytorch_implementation.py +8 -8
  43. model_compression_toolkit/core/pytorch/pytorch_implementation.py +7 -6
  44. model_compression_toolkit/core/pytorch/pytorch_node_prior_info.py +2 -2
  45. model_compression_toolkit/core/quantization_prep_runner.py +6 -2
  46. model_compression_toolkit/core/runner.py +5 -2
  47. model_compression_toolkit/exporter/model_wrapper/keras/builder/fully_quantized_model_builder.py +5 -1
  48. model_compression_toolkit/exporter/model_wrapper/pytorch/builder/fully_quantized_model_builder.py +9 -2
  49. model_compression_toolkit/gptq/keras/quantization_facade.py +2 -1
  50. model_compression_toolkit/gptq/pytorch/quantization_facade.py +3 -1
  51. model_compression_toolkit/gptq/runner.py +1 -0
  52. model_compression_toolkit/target_platform_capabilities/tpc_models/imx500_tpc/latest/__init__.py +5 -5
  53. model_compression_toolkit/target_platform_capabilities/tpc_models/imx500_tpc/v1_lut/tp_model.py +1 -1
  54. model_compression_toolkit/target_platform_capabilities/tpc_models/imx500_tpc/v2/tp_model.py +20 -6
  55. model_compression_toolkit/target_platform_capabilities/tpc_models/imx500_tpc/v2/tpc_keras.py +1 -1
  56. model_compression_toolkit/target_platform_capabilities/tpc_models/imx500_tpc/v2_lut/tp_model.py +22 -8
  57. model_compression_toolkit/target_platform_capabilities/tpc_models/imx500_tpc/v2_lut/tpc_keras.py +1 -1
  58. {mct_nightly-2.0.0.20240417.406.dist-info → mct_nightly-2.0.0.20240419.358.dist-info}/LICENSE.md +0 -0
  59. {mct_nightly-2.0.0.20240417.406.dist-info → mct_nightly-2.0.0.20240419.358.dist-info}/WHEEL +0 -0
  60. {mct_nightly-2.0.0.20240417.406.dist-info → mct_nightly-2.0.0.20240419.358.dist-info}/top_level.txt +0 -0
@@ -13,13 +13,16 @@
13
13
  # limitations under the License.
14
14
  # ==============================================================================
15
15
  from copy import deepcopy
16
- from typing import Tuple, Callable
16
+ from typing import Tuple, Callable, List
17
17
  import numpy as np
18
18
  import model_compression_toolkit.core.common.quantization.quantization_config as qc
19
+ from model_compression_toolkit.core.common.hessian import TraceHessianRequest, HessianMode, HessianInfoGranularity, \
20
+ HessianInfoService
19
21
  from model_compression_toolkit.core.common.similarity_analyzer import compute_mse, compute_mae, compute_lp_norm
20
22
  from model_compression_toolkit.target_platform_capabilities.target_platform import QuantizationMethod
21
- from model_compression_toolkit.constants import FLOAT_32
22
- from model_compression_toolkit.core.common.quantization.quantizers.quantizers_helpers import uniform_quantize_tensor
23
+ from model_compression_toolkit.constants import FLOAT_32, NUM_QPARAM_HESSIAN_SAMPLES
24
+ from model_compression_toolkit.core.common.quantization.quantizers.quantizers_helpers import uniform_quantize_tensor, \
25
+ reshape_tensor_for_per_channel_search
23
26
 
24
27
 
25
28
  def _mse_error_histogram(q_bins: np.ndarray,
@@ -371,13 +374,63 @@ def _get_sliced_histogram(bins: np.ndarray,
371
374
  return bins_subset, counts_subset
372
375
 
373
376
 
377
+ def _compute_hessian_for_hmse(node,
378
+ hessian_info_service: HessianInfoService,
379
+ num_hessian_samples: int = NUM_QPARAM_HESSIAN_SAMPLES) -> List[np.ndarray]:
380
+ """
381
+ Compute and retrieve Hessian-based scores for using during HMSE error computation.
382
+
383
+ Args:
384
+ node: The node to compute Hessian-based scores for.
385
+ hessian_info_service: HessianInfoService object for retrieving Hessian-based scores.
386
+ num_hessian_samples: Number of samples to approximate Hessian-based scores on.
387
+
388
+ Returns: A list with computed Hessian-based scores tensors for the given node.
389
+
390
+ """
391
+ _request = TraceHessianRequest(mode=HessianMode.WEIGHTS,
392
+ granularity=HessianInfoGranularity.PER_ELEMENT,
393
+ target_node=node)
394
+ _scores_for_node = hessian_info_service.fetch_hessian(_request,
395
+ required_size=num_hessian_samples)
396
+
397
+ return _scores_for_node
398
+
399
+
400
+ def _hmse_error_function_wrapper(float_tensor: np.ndarray,
401
+ fxp_tensor: np.ndarray,
402
+ axis: int,
403
+ norm: bool,
404
+ hessian_scores: np.ndarray):
405
+ """
406
+ This function wraps the HMSE error method to enable using it during parameters selection.
407
+
408
+ Args:
409
+ float_tensor: Float tensor.
410
+ fxp_tensor: Quantized tensor.
411
+ axis: Axis along which the operation has been performed. If not None, then per-channel computation is expected.
412
+ norm: Indicates whether to normalize the result of the error function.
413
+ hessian_scores: A tensor with Hessian-based scores to use for Hessian-based MSE (HMSE) error computation.
414
+
415
+ Returns: The HMSE error between the float and fixed-point tensors.
416
+
417
+ """
418
+ if axis is not None:
419
+ hessian_scores = reshape_tensor_for_per_channel_search(hessian_scores, 0)
420
+
421
+ return compute_mse(float_tensor, fxp_tensor, axis, norm, weights=hessian_scores)
422
+
423
+
374
424
  def get_threshold_selection_tensor_error_function(quantization_method: QuantizationMethod,
375
425
  quant_error_method: qc.QuantizationErrorMethod,
376
426
  p: int,
377
427
  axis: int = None,
378
428
  norm: bool = False,
379
429
  n_bits: int = 8,
380
- signed: bool = True) -> Callable:
430
+ signed: bool = True,
431
+ node=None,
432
+ hessian_info_service: HessianInfoService = None,
433
+ num_hessian_samples: int = NUM_QPARAM_HESSIAN_SAMPLES) -> Callable:
381
434
  """
382
435
  Returns the error function compatible to the provided threshold method,
383
436
  to be used in the threshold optimization search for tensor quantization.
@@ -389,6 +442,9 @@ def get_threshold_selection_tensor_error_function(quantization_method: Quantizat
389
442
  norm: Indicates whether to normalize the result of the error function.
390
443
  n_bits: Number of bits used to quantize the tensor.
391
444
  signed: Indicates whether the input is signed.
445
+ node: The node for which the quantization error is computed (used only with HMSE error method).
446
+ hessian_info_service: HessianInfoService object for retrieving Hessian-based scores (used only with HMSE error method).
447
+ num_hessian_samples: Number of samples to approximate Hessian-based scores on (used only with HMSE error method).
392
448
 
393
449
  Returns: a Callable method that calculates the error between a tensor and a quantized tensor.
394
450
  """
@@ -418,6 +474,13 @@ def get_threshold_selection_tensor_error_function(quantization_method: Quantizat
418
474
  n_bits=n_bits,
419
475
  per_channel=True)
420
476
 
477
+ if quant_error_method == qc.QuantizationErrorMethod.HMSE:
478
+ node_hessian_scores = _compute_hessian_for_hmse(node, hessian_info_service, num_hessian_samples)
479
+ node_hessian_scores = np.sqrt(np.mean(node_hessian_scores, axis=0))
480
+
481
+ return lambda x, y, threshold: _hmse_error_function_wrapper(x, y, norm=norm, axis=axis,
482
+ hessian_scores=node_hessian_scores)
483
+
421
484
  quant_method_error_function_mapping = {
422
485
  qc.QuantizationErrorMethod.MSE: lambda x, y, threshold: compute_mse(x, y, norm=norm, axis=axis),
423
486
  qc.QuantizationErrorMethod.MAE: lambda x, y, threshold: compute_mae(x, y, norm=norm, axis=axis),
@@ -13,12 +13,14 @@
13
13
  # limitations under the License.
14
14
  # ==============================================================================
15
15
 
16
+ from typing import Dict
16
17
  import numpy as np
17
18
  from sklearn.cluster import KMeans
18
19
 
19
20
  import model_compression_toolkit.core.common.quantization.quantization_config as qc
20
21
  from model_compression_toolkit.constants import LUT_VALUES, MIN_THRESHOLD, SCALE_PER_CHANNEL, \
21
- LUT_VALUES_BITWIDTH, THRESHOLD
22
+ LUT_VALUES_BITWIDTH, THRESHOLD, NUM_QPARAM_HESSIAN_SAMPLES
23
+ from model_compression_toolkit.core.common.hessian import HessianInfoService
22
24
  from model_compression_toolkit.core.common.quantization.quantizers.quantizers_helpers import \
23
25
  max_power_of_two, int_quantization_with_threshold
24
26
  from model_compression_toolkit.core.common.quantization.quantization_params_generation.symmetric_selection import \
@@ -37,7 +39,10 @@ def lut_kmeans_tensor(tensor_data: np.ndarray,
37
39
  n_iter: int = 10,
38
40
  min_threshold: float = MIN_THRESHOLD,
39
41
  quant_error_method: qc.QuantizationErrorMethod = None,
40
- is_symmetric=False) -> dict:
42
+ is_symmetric: bool = False,
43
+ node=None,
44
+ hessian_info_service: HessianInfoService = None,
45
+ num_hessian_samples: int = NUM_QPARAM_HESSIAN_SAMPLES) -> Dict:
41
46
  """
42
47
  The quantizer first finds the closest max value per channel of tensor_data.
43
48
  Now, we divide tensor_data with the threshold vector per channel. In addition, we scale the result to the range
@@ -53,7 +58,10 @@ def lut_kmeans_tensor(tensor_data: np.ndarray,
53
58
  n_iter: Number of iterations to search_methods for the optimal threshold.
54
59
  min_threshold: Minimal threshold to chose when the computed one is smaller.
55
60
  quant_error_method: an error function to optimize the parameters' selection accordingly (not used for this method).
56
- is_symmetric (bool): Whether to apply symmetric weight quantization (default is False, meaning power of 2 quantization)
61
+ is_symmetric (bool): Whether to apply symmetric weight quantization (default is False, meaning power of 2 quantization).
62
+ node: The node for which the quantization error is computed (not used for this method).
63
+ hessian_info_service: HessianInfoService object for retrieving Hessian-based scores (not used for this method).
64
+ num_hessian_samples: Number of samples to approximate Hessian-based scores on (not used for this method).
57
65
 
58
66
  Returns:
59
67
  A dictionary containing the cluster assignments according to the k-means algorithm,
@@ -94,7 +102,7 @@ def lut_kmeans_histogram(bins: np.ndarray,
94
102
  constrained: bool = True,
95
103
  n_iter: int = 20,
96
104
  min_threshold: float = MIN_THRESHOLD,
97
- quant_error_method: qc.QuantizationErrorMethod = qc.QuantizationErrorMethod.MSE) -> dict:
105
+ quant_error_method: qc.QuantizationErrorMethod = qc.QuantizationErrorMethod.MSE) -> Dict:
98
106
  """
99
107
  Finds quantization cluster points for non-uniform activation quantization.
100
108
  The quantizer first finds the closest power-of-two number to the max value of the given histogram,
@@ -15,7 +15,8 @@
15
15
  import numpy as np
16
16
 
17
17
  import model_compression_toolkit.core.common.quantization.quantization_config as qc
18
- from model_compression_toolkit.constants import MIN_THRESHOLD, THRESHOLD
18
+ from model_compression_toolkit.constants import MIN_THRESHOLD, THRESHOLD, NUM_QPARAM_HESSIAN_SAMPLES
19
+ from model_compression_toolkit.core.common.hessian import HessianInfoService
19
20
  from model_compression_toolkit.core.common.quantization.quantization_params_generation.qparams_search import \
20
21
  qparams_selection_tensor_search, qparams_selection_histogram_search
21
22
  from model_compression_toolkit.core.common.quantization.quantizers.quantizers_helpers import max_power_of_two, get_tensor_max
@@ -31,7 +32,11 @@ def power_of_two_selection_tensor(tensor_data: np.ndarray,
31
32
  channel_axis: int = 1,
32
33
  n_iter: int = 10,
33
34
  min_threshold: float = MIN_THRESHOLD,
34
- quant_error_method: qc.QuantizationErrorMethod = qc.QuantizationErrorMethod.MSE) -> dict:
35
+ quant_error_method: qc.QuantizationErrorMethod = qc.QuantizationErrorMethod.MSE,
36
+ node=None,
37
+ hessian_info_service: HessianInfoService = None,
38
+ num_hessian_samples: int = NUM_QPARAM_HESSIAN_SAMPLES,
39
+ ) -> dict:
35
40
  """
36
41
  Compute the power of two threshold based on the provided QuantizationErrorMethod to quantize the tensor.
37
42
  Different search is applied, depends on the value of the selected QuantizationErrorMethod.
@@ -45,6 +50,9 @@ def power_of_two_selection_tensor(tensor_data: np.ndarray,
45
50
  n_iter: Number of iterations to search for the optimal threshold (not used for this method).
46
51
  min_threshold: Minimal threshold to use if threshold is too small (not used for this method).
47
52
  quant_error_method: an error function to optimize the parameters' selection accordingly.
53
+ node: The node for which the quantization error is computed (used only with HMSE error method).
54
+ hessian_info_service: HessianInfoService object for retrieving Hessian-based scores (used only with HMSE error method).
55
+ num_hessian_samples: Number of samples to approximate Hessian-based scores on (used only with HMSE error method).
48
56
 
49
57
  Returns:
50
58
  Power of two threshold to quantize the tensor in a power of 2 manner.
@@ -57,8 +65,10 @@ def power_of_two_selection_tensor(tensor_data: np.ndarray,
57
65
  signed = True # weights are always signed
58
66
  axis = -1 if per_channel else None
59
67
  error_function = get_threshold_selection_tensor_error_function(QuantizationMethod.POWER_OF_TWO,
60
- quant_error_method, p, axis=axis, norm=False, n_bits=n_bits,
61
- signed=signed)
68
+ quant_error_method, p, axis=axis, norm=False,
69
+ n_bits=n_bits, signed=signed, node=node,
70
+ hessian_info_service=hessian_info_service,
71
+ num_hessian_samples=num_hessian_samples)
62
72
  threshold = qparams_selection_tensor_search(error_function,
63
73
  tensor_data,
64
74
  n_bits,
@@ -12,10 +12,15 @@
12
12
  # See the License for the specific language governing permissions and
13
13
  # limitations under the License.
14
14
  # ==============================================================================
15
+ import copy
16
+
15
17
  from tqdm import tqdm
16
18
  from typing import List
17
19
 
20
+ from model_compression_toolkit.constants import NUM_QPARAM_HESSIAN_SAMPLES
21
+ from model_compression_toolkit.core import QuantizationErrorMethod
18
22
  from model_compression_toolkit.core.common import Graph, BaseNode
23
+ from model_compression_toolkit.core.common.hessian import HessianInfoService
19
24
  from model_compression_toolkit.core.common.quantization.quantization_params_generation.qparams_activations_computation \
20
25
  import get_activations_qparams
21
26
  from model_compression_toolkit.core.common.quantization.quantization_params_generation.qparams_weights_computation import \
@@ -25,7 +30,9 @@ from model_compression_toolkit.logger import Logger
25
30
 
26
31
  def calculate_quantization_params(graph: Graph,
27
32
  nodes: List[BaseNode] = [],
28
- specific_nodes: bool = False):
33
+ specific_nodes: bool = False,
34
+ hessian_info_service: HessianInfoService = None,
35
+ num_hessian_samples: int = NUM_QPARAM_HESSIAN_SAMPLES):
29
36
  """
30
37
  For a graph, go over its nodes, compute quantization params (for both weights and activations according
31
38
  to the given framework info), and create and attach a NodeQuantizationConfig to each node (containing the
@@ -39,6 +46,8 @@ def calculate_quantization_params(graph: Graph,
39
46
  graph: Graph to compute its nodes' thresholds.
40
47
  nodes: List of nodes to compute their thresholds instead of computing it for all nodes in the graph.
41
48
  specific_nodes: Flag to compute thresholds for only specific nodes.
49
+ hessian_info_service: HessianInfoService object for retrieving Hessian-based scores (used only with HMSE error method).
50
+ num_hessian_samples: Number of samples to approximate Hessian-based scores on (used only with HMSE error method).
42
51
 
43
52
  """
44
53
 
@@ -60,10 +69,28 @@ def calculate_quantization_params(graph: Graph,
60
69
  output_channels_axis = channels_axis[0]
61
70
  else:
62
71
  output_channels_axis = None
72
+
73
+ mod_attr_cfg = attr_cfg
74
+
75
+ if attr_cfg.weights_error_method == QuantizationErrorMethod.HMSE:
76
+ kernel_attr_name = graph.fw_info.get_kernel_op_attributes(n.type)
77
+ if len(kernel_attr_name) > 0:
78
+ kernel_attr_name = kernel_attr_name[0]
79
+
80
+ if kernel_attr_name is None or kernel_attr_name not in attr:
81
+ Logger.warning(f"The HMSE error method for parameters selection is only supported for "
82
+ f"kernel weights attributes. Running parameters selection for attribute "
83
+ f"'{attr}' in node '{n.name}' with the default MSE error method instead.")
84
+ mod_attr_cfg = copy.deepcopy(attr_cfg)
85
+ mod_attr_cfg.weights_error_method = QuantizationErrorMethod.MSE
86
+
63
87
  weights_params = get_weights_qparams(n.get_weights_by_keys(attr),
64
88
  candidate_qc.weights_quantization_cfg,
65
- attr_cfg,
66
- output_channels_axis)
89
+ mod_attr_cfg,
90
+ output_channels_axis,
91
+ node=n,
92
+ hessian_info_service=hessian_info_service,
93
+ num_hessian_samples=num_hessian_samples)
67
94
  attr_cfg.set_weights_quantization_param(weights_params)
68
95
 
69
96
  if n.is_activation_quantization_enabled():
@@ -12,11 +12,12 @@
12
12
  # See the License for the specific language governing permissions and
13
13
  # limitations under the License.
14
14
  # ==============================================================================
15
- from typing import Dict, Any, Tuple
15
+ from typing import Dict, Any
16
16
 
17
17
  import numpy as np
18
18
 
19
- from model_compression_toolkit.logger import Logger
19
+ from model_compression_toolkit.constants import NUM_QPARAM_HESSIAN_SAMPLES
20
+ from model_compression_toolkit.core.common.hessian import HessianInfoService
20
21
  from model_compression_toolkit.defaultdict import DefaultDict
21
22
  from model_compression_toolkit.core.common.framework_info import FrameworkInfo
22
23
  from model_compression_toolkit.core.common.quantization.node_quantization_config import NodeWeightsQuantizationConfig, \
@@ -27,31 +28,40 @@ from model_compression_toolkit.core.common.quantization.node_quantization_config
27
28
  dummy_channel_mapping = DefaultDict(default_value=(None, None))
28
29
 
29
30
 
30
- def get_weights_qparams(kernel: np.ndarray,
31
+ def get_weights_qparams(weights_attr_values: np.ndarray,
31
32
  weights_quant_config: NodeWeightsQuantizationConfig,
32
33
  attr_quant_config: WeightsAttrQuantizationConfig,
33
- output_channels_axis: int) -> Dict[Any, Any]:
34
+ output_channels_axis: int,
35
+ node=None,
36
+ hessian_info_service: HessianInfoService = None,
37
+ num_hessian_samples: int = NUM_QPARAM_HESSIAN_SAMPLES) -> Dict[Any, Any]:
34
38
  """
35
39
  Compute thresholds to quantize a kernel according to a NodeWeightsQuantizationConfig
36
40
  instance.
37
41
 
38
42
  Args:
39
- kernel: Kernel to compute the quantization thresholds to.
43
+ weights_attr_values: Weights attribute parameter to compute the quantization thresholds for.
40
44
  weights_quant_config: Weights quantization configuration to define how the thresholds are computed.
41
45
  attr_quant_config: A specific weights attribute quantization configuration to get its params.
42
46
  output_channels_axis: Index of the kernel output channels dimension.
47
+ node: The node for which the quantization error is computed (used only with HMSE error method).
48
+ hessian_info_service: HessianInfoService object for retrieving Hessian-based scores (used only with HMSE error method).
49
+ num_hessian_samples: Number of samples to approximate Hessian-based scores on (used only with HMSE error method).
43
50
 
44
51
  Returns:
45
52
  A dictionary with the quantization threshold of the kernel.
46
53
  """
47
54
  if attr_quant_config.weights_quantization_params_fn is not None:
48
- weights_params = attr_quant_config.weights_quantization_params_fn(kernel,
55
+ weights_params = attr_quant_config.weights_quantization_params_fn(weights_attr_values,
49
56
  p=attr_quant_config.l_p_value,
50
57
  n_bits=attr_quant_config.weights_n_bits,
51
58
  per_channel=attr_quant_config.weights_per_channel_threshold and output_channels_axis is not None,
52
59
  channel_axis=output_channels_axis,
53
60
  min_threshold=weights_quant_config.min_threshold,
54
- quant_error_method=attr_quant_config.weights_error_method)
61
+ quant_error_method=attr_quant_config.weights_error_method,
62
+ node=node,
63
+ hessian_info_service=hessian_info_service,
64
+ num_hessian_samples=num_hessian_samples)
55
65
  else:
56
66
  weights_params = {}
57
67
 
@@ -15,7 +15,8 @@
15
15
  import numpy as np
16
16
 
17
17
  import model_compression_toolkit.core.common.quantization.quantization_config as qc
18
- from model_compression_toolkit.constants import MIN_THRESHOLD, THRESHOLD
18
+ from model_compression_toolkit.constants import MIN_THRESHOLD, THRESHOLD, NUM_QPARAM_HESSIAN_SAMPLES
19
+ from model_compression_toolkit.core.common.hessian import HessianInfoService
19
20
  from model_compression_toolkit.core.common.quantization.quantization_params_generation.error_functions import \
20
21
  get_threshold_selection_tensor_error_function, get_threshold_selection_histogram_error_function, _kl_error_histogram
21
22
  from model_compression_toolkit.core.common.quantization.quantization_params_generation.qparams_search import \
@@ -33,7 +34,10 @@ def symmetric_selection_tensor(tensor_data: np.ndarray,
33
34
  channel_axis: int = 1,
34
35
  n_iter: int = 10,
35
36
  min_threshold: float = MIN_THRESHOLD,
36
- quant_error_method: qc.QuantizationErrorMethod = qc.QuantizationErrorMethod.MSE) -> dict:
37
+ quant_error_method: qc.QuantizationErrorMethod = qc.QuantizationErrorMethod.MSE,
38
+ node=None,
39
+ hessian_info_service: HessianInfoService = None,
40
+ num_hessian_samples: int = NUM_QPARAM_HESSIAN_SAMPLES) -> dict:
37
41
  """
38
42
  Compute the optimal threshold based on the provided QuantizationErrorMethod to quantize the tensor.
39
43
  Different search is applied, depends on the value of the selected QuantizationErrorMethod.
@@ -47,6 +51,9 @@ def symmetric_selection_tensor(tensor_data: np.ndarray,
47
51
  n_iter: Number of iterations to search for the optimal threshold (not used for this method).
48
52
  min_threshold: Minimal threshold to use if threshold is too small (not used for this method).
49
53
  quant_error_method: an error function to optimize the parameters' selection accordingly.
54
+ node: The node for which the quantization error is computed (used only with HMSE error method).
55
+ hessian_info_service: HessianInfoService object for retrieving Hessian-based scores (used only with HMSE error method).
56
+ num_hessian_samples: Number of samples to approximate Hessian-based scores on (used only with HMSE error method).
50
57
 
51
58
  Returns:
52
59
  Optimal threshold to quantize the tensor in a symmetric manner.
@@ -59,7 +66,11 @@ def symmetric_selection_tensor(tensor_data: np.ndarray,
59
66
  else:
60
67
  signed = True # weights are always signed
61
68
  axis = -1 if per_channel else None
62
- error_function = get_threshold_selection_tensor_error_function(QuantizationMethod.SYMMETRIC, quant_error_method, p, axis=axis, norm=False, n_bits=n_bits, signed=signed)
69
+ error_function = get_threshold_selection_tensor_error_function(QuantizationMethod.SYMMETRIC, quant_error_method,
70
+ p, axis=axis, norm=False, n_bits=n_bits,
71
+ signed=signed, node=node,
72
+ hessian_info_service=hessian_info_service,
73
+ num_hessian_samples=num_hessian_samples)
63
74
  threshold = qparams_symmetric_selection_tensor_search(error_function,
64
75
  tensor_data,
65
76
  tensor_max,
@@ -15,7 +15,8 @@
15
15
  import numpy as np
16
16
 
17
17
  import model_compression_toolkit.core.common.quantization.quantization_config as qc
18
- from model_compression_toolkit.constants import MIN_THRESHOLD, RANGE_MIN, RANGE_MAX
18
+ from model_compression_toolkit.constants import MIN_THRESHOLD, RANGE_MIN, RANGE_MAX, NUM_QPARAM_HESSIAN_SAMPLES
19
+ from model_compression_toolkit.core.common.hessian import HessianInfoService
19
20
  from model_compression_toolkit.core.common.quantization.quantization_params_generation.qparams_search import \
20
21
  qparams_uniform_selection_tensor_search, qparams_uniform_selection_histogram_search
21
22
  from model_compression_toolkit.core.common.quantization.quantization_params_generation.error_functions import \
@@ -31,7 +32,10 @@ def uniform_selection_tensor(tensor_data: np.ndarray,
31
32
  channel_axis: int = 1,
32
33
  n_iter: int = 10,
33
34
  min_threshold: float = MIN_THRESHOLD,
34
- quant_error_method: qc.QuantizationErrorMethod = qc.QuantizationErrorMethod.MSE) -> dict:
35
+ quant_error_method: qc.QuantizationErrorMethod = qc.QuantizationErrorMethod.MSE,
36
+ node=None,
37
+ hessian_info_service: HessianInfoService = None,
38
+ num_hessian_samples: int = NUM_QPARAM_HESSIAN_SAMPLES) -> dict:
35
39
  """
36
40
  Compute the optimal quantization range based on the provided QuantizationErrorMethod
37
41
  to uniformly quantize the tensor.
@@ -46,6 +50,9 @@ def uniform_selection_tensor(tensor_data: np.ndarray,
46
50
  n_iter: Number of iterations to search for the optimal threshold (not used for this method).
47
51
  min_threshold: Minimal threshold to use if threshold is too small (not used for this method).
48
52
  quant_error_method: an error function to optimize the range parameters' selection accordingly.
53
+ node: The node for which the quantization error is computed (used only with HMSE error method).
54
+ hessian_info_service: HessianInfoService object for retrieving Hessian-based scores (used only with HMSE error method).
55
+ num_hessian_samples: Number of samples to approximate Hessian-based scores on (used only with HMSE error method).
49
56
 
50
57
  Returns:
51
58
  Optimal quantization range to quantize the tensor uniformly.
@@ -57,7 +64,10 @@ def uniform_selection_tensor(tensor_data: np.ndarray,
57
64
  mm = tensor_min, tensor_max
58
65
  else:
59
66
  axis = -1 if per_channel else None
60
- error_function = get_threshold_selection_tensor_error_function(QuantizationMethod.UNIFORM, quant_error_method, p, axis=axis, norm=False)
67
+ error_function = get_threshold_selection_tensor_error_function(QuantizationMethod.UNIFORM, quant_error_method,
68
+ p, axis=axis, norm=False, node=node,
69
+ hessian_info_service=hessian_info_service,
70
+ num_hessian_samples=num_hessian_samples)
61
71
  mm = qparams_uniform_selection_tensor_search(error_function,
62
72
  tensor_data,
63
73
  tensor_min,
@@ -24,7 +24,8 @@ from model_compression_toolkit.core.common.graph.base_graph import Graph
24
24
  from model_compression_toolkit.core.common.quantization.candidate_node_quantization_config import \
25
25
  CandidateNodeQuantizationConfig
26
26
  from model_compression_toolkit.core.common.quantization.node_quantization_config import NodeActivationQuantizationConfig
27
- from model_compression_toolkit.core.common.quantization.quantization_config import QuantizationConfig
27
+ from model_compression_toolkit.core.common.quantization.quantization_config import QuantizationConfig, \
28
+ QuantizationErrorMethod
28
29
  from model_compression_toolkit.core.common.quantization.quantization_params_fn_selection import \
29
30
  get_activation_quantization_params_fn, get_weights_quantization_params_fn
30
31
  from model_compression_toolkit.core.common.quantization.quantization_fn_selection import \
@@ -36,19 +37,31 @@ from model_compression_toolkit.target_platform_capabilities.target_platform.op_q
36
37
 
37
38
  def set_quantization_configuration_to_graph(graph: Graph,
38
39
  quant_config: QuantizationConfig,
39
- mixed_precision_enable: bool = False) -> Graph:
40
+ mixed_precision_enable: bool = False,
41
+ running_gptq: bool = False) -> Graph:
40
42
  """
41
43
  Add quantization configuration for each graph node.
42
44
 
43
45
  Args:
44
46
  graph: Graph for which to add quantization info to each node.
45
47
  quant_config: Quantization configuration containing parameters for how the graph should be quantized.
46
- mixed_precision_enable: is mixed precision enabled
48
+ mixed_precision_enable: is mixed precision enabled.
49
+ running_gptq: Whether or not a GPTQ optimization is planned to run after the PTQ process.
47
50
 
48
51
  Returns:
49
52
  The graph with quantization configurations attached to each node in it.
50
53
  """
51
54
 
55
+ if quant_config.weights_error_method == QuantizationErrorMethod.HMSE:
56
+ if not running_gptq:
57
+ Logger.warning(f"The HMSE error method for parameters selection is only supported when running GPTQ "
58
+ f"optimization due to long execution time that is not suitable for basic PTQ. "
59
+ f"Using the default MSE error method instead.")
60
+ quant_config.weights_error_method = QuantizationErrorMethod.MSE
61
+ else:
62
+ Logger.warning("Using the HMSE error method for weights quantization parameters search. "
63
+ "Note: This method may significantly increase runtime during the parameter search process.")
64
+
52
65
  for n in graph.nodes:
53
66
  set_quantization_configs_to_node(node=n,
54
67
  quant_config=quant_config,
@@ -18,6 +18,8 @@ from typing import Any
18
18
  import numpy as np
19
19
 
20
20
  from model_compression_toolkit.constants import EPS
21
+ from model_compression_toolkit.logger import Logger
22
+
21
23
 
22
24
  #########################
23
25
  # Helpful functions
@@ -87,7 +89,8 @@ def compute_mse(float_tensor: np.ndarray,
87
89
  norm: bool = False,
88
90
  norm_eps: float = 1e-8,
89
91
  batch: bool = False,
90
- axis: int = None) -> float:
92
+ axis: int = None,
93
+ weights: np.ndarray = None) -> float:
91
94
  """
92
95
  Compute the mean square error between two numpy arrays.
93
96
 
@@ -98,6 +101,7 @@ def compute_mse(float_tensor: np.ndarray,
98
101
  norm_eps: epsilon value for error normalization stability.
99
102
  batch: Whether to run batch similarity analysis or not.
100
103
  axis: Axis along which the operator has been computed.
104
+ weights: Weights tensor to use for computing Weighted-MSE error computation.
101
105
 
102
106
  Returns:
103
107
  The MSE distance between the two tensors.
@@ -107,7 +111,15 @@ def compute_mse(float_tensor: np.ndarray,
107
111
  float_flat = flatten_tensor(float_tensor, batch, axis)
108
112
  fxp_flat = flatten_tensor(fxp_tensor, batch, axis)
109
113
 
110
- error = ((float_flat - fxp_flat) ** 2).mean(axis=-1)
114
+ if weights is not None:
115
+ w_flat = flatten_tensor(weights, batch, axis)
116
+ if w_flat.shape != float_flat.shape:
117
+ Logger.critical(f"Shape mismatch: The shape of the weights tensor {weights.shape} does not match the shape "
118
+ f"of the input tensors {float_flat.shape} for Weighted-MSE computation.") # pragma: no cover
119
+ error = ((w_flat * (float_flat - fxp_flat)) ** 2).mean(axis=-1)
120
+ else:
121
+ error = ((float_flat - fxp_flat) ** 2).mean(axis=-1)
122
+
111
123
  if norm:
112
124
  error /= ((float_flat ** 2).mean(axis=-1) + norm_eps)
113
125
 
@@ -223,7 +235,7 @@ def compute_kl_divergence(float_tensor: np.ndarray, fxp_tensor: np.ndarray, batc
223
235
  axis: int = None) -> float:
224
236
  """
225
237
  Compute the similarity between two tensor using KL-divergence.
226
- The returned values is between 0 to 1: the smaller returned value,
238
+ The returned values is between 0 and 1: the smaller returned value,
227
239
  the greater similarity there is between the two tensors.
228
240
 
229
241
  Args:
@@ -245,6 +257,6 @@ def compute_kl_divergence(float_tensor: np.ndarray, fxp_tensor: np.ndarray, batc
245
257
  non_zero_fxp_tensor[non_zero_fxp_tensor == 0] = EPS
246
258
 
247
259
  prob_distance = np.where(float_flat != 0, float_flat * np.log(float_flat / non_zero_fxp_tensor), 0)
248
- # The sum is part of the KL-Divergance function.
260
+ # The sum is part of the KL-Divergence function.
249
261
  # The mean is to aggregate the distance between each output probability vectors.
250
262
  return np.mean(np.sum(prob_distance, axis=-1), axis=-1)
@@ -0,0 +1,48 @@
1
+ # Copyright 2024 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
+ from model_compression_toolkit.core.common.graph.base_graph import Graph
17
+ from model_compression_toolkit.core.common.graph.base_node import BaseNode
18
+
19
+
20
+ def remove_identity_node(graph: Graph,
21
+ node: BaseNode) -> Graph:
22
+ """
23
+ The method to perform the substitution of the identity node by
24
+ reconnecting its input directly to its output, effectively removing the node
25
+ from the graph.
26
+
27
+ Args:
28
+ graph: The current graph of operations where the node resides.
29
+ node: The specific `BaseNode` that is matched to be an Identity operation.
30
+
31
+ Returns:
32
+ Graph: The updated graph after removing the identity node.
33
+ """
34
+ # Retrieve the predecessor nodes of the identity node.
35
+ prev_identity_nodes = graph.get_prev_nodes(node)
36
+ # Ensure there is exactly one predecessor; otherwise, do nothing.
37
+ if len(prev_identity_nodes) != 1:
38
+ return graph
39
+
40
+ # Reconnect the output edges of the identity node to its predecessor,
41
+ # effectively bypassing the identity node.
42
+ graph.reconnect_out_edges(current_node=node, new_node=prev_identity_nodes[0])
43
+ # Remove the edge from the predecessor to the identity node.
44
+ graph.remove_edge(prev_identity_nodes[0], node)
45
+ # Remove the identity node from the graph.
46
+ graph.remove_node(node_to_remove=node)
47
+
48
+ return graph
@@ -39,7 +39,8 @@ def graph_preparation_runner(in_model: Any,
39
39
  fw_impl: FrameworkImplementation,
40
40
  tpc: TargetPlatformCapabilities,
41
41
  tb_w: TensorboardWriter = None,
42
- mixed_precision_enable: bool = False) -> Graph:
42
+ mixed_precision_enable: bool = False,
43
+ running_gptq: bool = False) -> Graph:
43
44
  """
44
45
  Runs all required preparations in order to build a quantization graph from the given model,
45
46
  quantization configuration and target platform specifications.
@@ -59,6 +60,7 @@ def graph_preparation_runner(in_model: Any,
59
60
  the attached framework operator's information.
60
61
  tb_w: TensorboardWriter object for logging.
61
62
  mixed_precision_enable: is mixed precision enabled.
63
+ running_gptq: Whether or not a GPTQ optimization is planned to run after the PTQ process.
62
64
 
63
65
  Returns:
64
66
  An internal graph representation of the input model.
@@ -79,7 +81,8 @@ def graph_preparation_runner(in_model: Any,
79
81
  fw_info,
80
82
  tb_w,
81
83
  fw_impl,
82
- mixed_precision_enable=mixed_precision_enable)
84
+ mixed_precision_enable=mixed_precision_enable,
85
+ running_gptq=running_gptq)
83
86
 
84
87
  return transformed_graph
85
88
 
@@ -90,7 +93,8 @@ def get_finalized_graph(initial_graph: Graph,
90
93
  fw_info: FrameworkInfo = None,
91
94
  tb_w: TensorboardWriter = None,
92
95
  fw_impl: FrameworkImplementation = None,
93
- mixed_precision_enable: bool = False) -> Graph:
96
+ mixed_precision_enable: bool = False,
97
+ running_gptq: bool = False) -> Graph:
94
98
  """
95
99
  Applies all edit operation (edit, substitutions, etc.) on the model's graph, to prepare it for the quantization
96
100
  process. All future graph substitutions and operations that change the graph should be added to this method.
@@ -105,6 +109,7 @@ def get_finalized_graph(initial_graph: Graph,
105
109
  tb_w (TensorboardWriter): TensorboardWriter object to use for logging events such as graphs, histograms, etc.
106
110
  fw_impl (FrameworkImplementation): FrameworkImplementation object with a specific framework methods implementation.
107
111
  mixed_precision_enable: is mixed precision enabled.
112
+ running_gptq: Whether or not a GPTQ optimization is planned to run after the PTQ process.
108
113
 
109
114
  Returns: Graph object that represents the model, after applying all required modifications to it.
110
115
  """
@@ -142,7 +147,8 @@ def get_finalized_graph(initial_graph: Graph,
142
147
  ######################################
143
148
  transformed_graph = set_quantization_configuration_to_graph(graph=transformed_graph,
144
149
  quant_config=quant_config,
145
- mixed_precision_enable=mixed_precision_enable)
150
+ mixed_precision_enable=mixed_precision_enable,
151
+ running_gptq=running_gptq)
146
152
 
147
153
  ######################################
148
154
  # Layer fusing