mct-nightly 2.1.0.20240801.515__py3-none-any.whl → 2.1.0.20240803.442__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 (33) hide show
  1. {mct_nightly-2.1.0.20240801.515.dist-info → mct_nightly-2.1.0.20240803.442.dist-info}/METADATA +1 -1
  2. {mct_nightly-2.1.0.20240801.515.dist-info → mct_nightly-2.1.0.20240803.442.dist-info}/RECORD +33 -29
  3. model_compression_toolkit/__init__.py +1 -1
  4. model_compression_toolkit/constants.py +2 -1
  5. model_compression_toolkit/core/common/graph/base_node.py +50 -5
  6. model_compression_toolkit/core/common/mixed_precision/resource_utilization_tools/resource_utilization_data.py +6 -6
  7. model_compression_toolkit/core/common/quantization/node_quantization_config.py +1 -0
  8. model_compression_toolkit/core/common/quantization/quantization_params_generation/lut_kmeans_params.py +6 -4
  9. model_compression_toolkit/core/common/quantization/quantization_params_generation/power_of_two_selection.py +19 -12
  10. model_compression_toolkit/core/common/quantization/quantization_params_generation/qparams_activations_computation.py +14 -14
  11. model_compression_toolkit/core/common/quantization/quantization_params_generation/qparams_search.py +14 -9
  12. model_compression_toolkit/core/common/quantization/quantization_params_generation/symmetric_selection.py +25 -17
  13. model_compression_toolkit/core/common/quantization/quantization_params_generation/uniform_selection.py +10 -6
  14. model_compression_toolkit/core/common/quantization/set_node_quantization_config.py +12 -5
  15. model_compression_toolkit/core/common/substitutions/shift_negative_activation.py +7 -5
  16. model_compression_toolkit/target_platform_capabilities/target_platform/op_quantization_config.py +25 -2
  17. model_compression_toolkit/target_platform_capabilities/tpc_models/imx500_tpc/target_platform_capabilities.py +5 -0
  18. model_compression_toolkit/target_platform_capabilities/tpc_models/imx500_tpc/v1/tp_model.py +2 -0
  19. model_compression_toolkit/target_platform_capabilities/tpc_models/imx500_tpc/v1_lut/tp_model.py +2 -0
  20. model_compression_toolkit/target_platform_capabilities/tpc_models/imx500_tpc/v1_pot/tp_model.py +2 -0
  21. model_compression_toolkit/target_platform_capabilities/tpc_models/imx500_tpc/v2/tp_model.py +2 -0
  22. model_compression_toolkit/target_platform_capabilities/tpc_models/imx500_tpc/v2_lut/tp_model.py +2 -0
  23. model_compression_toolkit/target_platform_capabilities/tpc_models/imx500_tpc/v3/tp_model.py +2 -0
  24. model_compression_toolkit/target_platform_capabilities/tpc_models/imx500_tpc/v3_lut/tp_model.py +2 -0
  25. model_compression_toolkit/target_platform_capabilities/tpc_models/imx500_tpc/v4/__init__.py +16 -0
  26. model_compression_toolkit/target_platform_capabilities/tpc_models/imx500_tpc/v4/tp_model.py +235 -0
  27. model_compression_toolkit/target_platform_capabilities/tpc_models/imx500_tpc/v4/tpc_keras.py +132 -0
  28. model_compression_toolkit/target_platform_capabilities/tpc_models/imx500_tpc/v4/tpc_pytorch.py +112 -0
  29. model_compression_toolkit/target_platform_capabilities/tpc_models/qnnpack_tpc/v1/tp_model.py +2 -0
  30. model_compression_toolkit/target_platform_capabilities/tpc_models/tflite_tpc/v1/tp_model.py +2 -0
  31. {mct_nightly-2.1.0.20240801.515.dist-info → mct_nightly-2.1.0.20240803.442.dist-info}/LICENSE.md +0 -0
  32. {mct_nightly-2.1.0.20240801.515.dist-info → mct_nightly-2.1.0.20240803.442.dist-info}/WHEEL +0 -0
  33. {mct_nightly-2.1.0.20240801.515.dist-info → mct_nightly-2.1.0.20240803.442.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,235 @@
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
+ from typing import List, Tuple
16
+
17
+ import model_compression_toolkit as mct
18
+ from model_compression_toolkit.constants import FLOAT_BITWIDTH
19
+ from model_compression_toolkit.target_platform_capabilities.constants import KERNEL_ATTR, BIAS_ATTR, WEIGHTS_N_BITS
20
+ from model_compression_toolkit.target_platform_capabilities.target_platform import OpQuantizationConfig, \
21
+ TargetPlatformModel
22
+ from model_compression_toolkit.target_platform_capabilities.target_platform.op_quantization_config import \
23
+ AttributeQuantizationConfig
24
+
25
+ tp = mct.target_platform
26
+
27
+
28
+ def get_tp_model() -> TargetPlatformModel:
29
+ """
30
+ A method that generates a default target platform model, with base 8-bit quantization configuration and 8, 4, 2
31
+ bits configuration list for mixed-precision quantization.
32
+ NOTE: in order to generate a target platform model with different configurations but with the same Operators Sets
33
+ (for tests, experiments, etc.), use this method implementation as a test-case, i.e., override the
34
+ 'get_op_quantization_configs' method and use its output to call 'generate_tp_model' with your configurations.
35
+ This version enables metadata by default.
36
+
37
+ Returns: A TargetPlatformModel object.
38
+
39
+ """
40
+ base_config, mixed_precision_cfg_list, default_config = get_op_quantization_configs()
41
+ return generate_tp_model(default_config=default_config,
42
+ base_config=base_config,
43
+ mixed_precision_cfg_list=mixed_precision_cfg_list,
44
+ name='imx500_tp_model')
45
+
46
+
47
+ def get_op_quantization_configs() -> \
48
+ Tuple[OpQuantizationConfig, List[OpQuantizationConfig], OpQuantizationConfig]:
49
+ """
50
+ Creates a default configuration object for 8-bit quantization, to be used to set a default TargetPlatformModel.
51
+ In addition, creates a default configuration objects list (with 8, 4 and 2 bit quantization) to be used as
52
+ default configuration for mixed-precision quantization.
53
+
54
+ Returns: An OpQuantizationConfig config object and a list of OpQuantizationConfig objects.
55
+
56
+ """
57
+
58
+ # TODO: currently, we don't want to quantize any attribute but the kernel by default,
59
+ # to preserve the current behavior of MCT, so quantization is disabled for all other attributes.
60
+ # Other quantization parameters are set to what we eventually want to quantize by default
61
+ # when we enable multi-attributes quantization - THIS NEED TO BE MODIFIED IN ALL TP MODELS!
62
+
63
+ # define a default quantization config for all non-specified weights attributes.
64
+ default_weight_attr_config = AttributeQuantizationConfig(
65
+ weights_quantization_method=tp.QuantizationMethod.POWER_OF_TWO,
66
+ weights_n_bits=8,
67
+ weights_per_channel_threshold=False,
68
+ enable_weights_quantization=False, # TODO: this will changed to True once implementing multi-attributes quantization
69
+ lut_values_bitwidth=None)
70
+
71
+ # define a quantization config to quantize the kernel (for layers where there is a kernel attribute).
72
+ kernel_base_config = AttributeQuantizationConfig(
73
+ weights_quantization_method=tp.QuantizationMethod.SYMMETRIC,
74
+ weights_n_bits=8,
75
+ weights_per_channel_threshold=True,
76
+ enable_weights_quantization=True,
77
+ lut_values_bitwidth=None)
78
+
79
+ # define a quantization config to quantize the bias (for layers where there is a bias attribute).
80
+ bias_config = AttributeQuantizationConfig(
81
+ weights_quantization_method=tp.QuantizationMethod.POWER_OF_TWO,
82
+ weights_n_bits=FLOAT_BITWIDTH,
83
+ weights_per_channel_threshold=False,
84
+ enable_weights_quantization=False,
85
+ lut_values_bitwidth=None)
86
+
87
+ # Create a quantization config.
88
+ # A quantization configuration defines how an operator
89
+ # should be quantized on the modeled hardware:
90
+
91
+ # We define a default config for operation without kernel attribute.
92
+ # This is the default config that should be used for non-linear operations.
93
+ eight_bits_default = tp.OpQuantizationConfig(
94
+ default_weight_attr_config=default_weight_attr_config,
95
+ attr_weights_configs_mapping={},
96
+ activation_quantization_method=tp.QuantizationMethod.POWER_OF_TWO,
97
+ activation_n_bits=8,
98
+ supported_input_activation_n_bits=8,
99
+ enable_activation_quantization=True,
100
+ quantization_preserving=False,
101
+ fixed_scale=None,
102
+ fixed_zero_point=None,
103
+ simd_size=32)
104
+
105
+ # We define an 8-bit config for linear operations quantization, that include a kernel and bias attributes.
106
+ linear_eight_bits = tp.OpQuantizationConfig(
107
+ default_weight_attr_config=default_weight_attr_config,
108
+ attr_weights_configs_mapping={KERNEL_ATTR: kernel_base_config, BIAS_ATTR: bias_config},
109
+ activation_quantization_method=tp.QuantizationMethod.POWER_OF_TWO,
110
+ activation_n_bits=8,
111
+ supported_input_activation_n_bits=8,
112
+ enable_activation_quantization=True,
113
+ quantization_preserving=False,
114
+ fixed_scale=None,
115
+ fixed_zero_point=None,
116
+ simd_size=32)
117
+
118
+ # To quantize a model using mixed-precision, create
119
+ # a list with more than one OpQuantizationConfig.
120
+ # In this example, we quantize some operations' weights
121
+ # using 2, 4 or 8 bits, and when using 2 or 4 bits, it's possible
122
+ # to quantize the operations' activations using LUT.
123
+ four_bits = linear_eight_bits.clone_and_edit(attr_to_edit={KERNEL_ATTR: {WEIGHTS_N_BITS: 4}},
124
+ simd_size=linear_eight_bits.simd_size * 2)
125
+ two_bits = linear_eight_bits.clone_and_edit(attr_to_edit={KERNEL_ATTR: {WEIGHTS_N_BITS: 2}},
126
+ simd_size=linear_eight_bits.simd_size * 4)
127
+
128
+ mixed_precision_cfg_list = [linear_eight_bits, four_bits, two_bits]
129
+
130
+ return linear_eight_bits, mixed_precision_cfg_list, eight_bits_default
131
+
132
+
133
+ def generate_tp_model(default_config: OpQuantizationConfig,
134
+ base_config: OpQuantizationConfig,
135
+ mixed_precision_cfg_list: List[OpQuantizationConfig],
136
+ name: str) -> TargetPlatformModel:
137
+ """
138
+ Generates TargetPlatformModel with default defined Operators Sets, based on the given base configuration and
139
+ mixed-precision configurations options list.
140
+
141
+ Args
142
+ default_config: A default OpQuantizationConfig to set as the TP model default configuration.
143
+ base_config: An OpQuantizationConfig to set as the TargetPlatformModel base configuration for mixed-precision purposes only.
144
+ mixed_precision_cfg_list: A list of OpQuantizationConfig to be used as the TP model mixed-precision
145
+ quantization configuration options.
146
+ name: The name of the TargetPlatformModel.
147
+
148
+ Returns: A TargetPlatformModel object.
149
+
150
+ """
151
+ # Create a QuantizationConfigOptions, which defines a set
152
+ # of possible configurations to consider when quantizing a set of operations (in mixed-precision, for example).
153
+ # If the QuantizationConfigOptions contains only one configuration,
154
+ # this configuration will be used for the operation quantization:
155
+ default_configuration_options = tp.QuantizationConfigOptions([default_config])
156
+
157
+ # Create a QuantizationConfigOptions for quantizing constants in functional ops.
158
+ # Constant configuration is similar to the default eight bit configuration except for PoT
159
+ # quantization method for the constant.
160
+ # Since the constants are not named attributes of the layer, we use the default_weight_attr_config to
161
+ # define the desired quantization properties for them.
162
+ const_config = default_config.clone_and_edit(
163
+ default_weight_attr_config=default_config.default_weight_attr_config.clone_and_edit(
164
+ enable_weights_quantization=True, weights_per_channel_threshold=True,
165
+ weights_quantization_method=tp.QuantizationMethod.POWER_OF_TWO))
166
+ const_configuration_options = tp.QuantizationConfigOptions([const_config])
167
+
168
+ # 16 bits inputs and outputs. Currently, only defined for consts since they are used in operators that
169
+ # support 16 bit as input and output.
170
+ const_config_input16 = const_config.clone_and_edit(
171
+ supported_input_activation_n_bits=(8, 16))
172
+ const_config_input16_output16 = const_config_input16.clone_and_edit(
173
+ activation_n_bits=16, is_signed=True)
174
+ const_configuration_options_inout16 = tp.QuantizationConfigOptions([const_config_input16_output16,
175
+ const_config_input16],
176
+ base_config=const_config_input16)
177
+
178
+ # Create a TargetPlatformModel and set its default quantization config.
179
+ # This default configuration will be used for all operations
180
+ # unless specified otherwise (see OperatorsSet, for example):
181
+ generated_tpm = tp.TargetPlatformModel(default_configuration_options, add_metadata=True, name=name)
182
+
183
+ # To start defining the model's components (such as operator sets, and fusing patterns),
184
+ # use 'with' the TargetPlatformModel instance, and create them as below:
185
+ with generated_tpm:
186
+ # Create an OperatorsSet to represent a set of operations.
187
+ # Each OperatorsSet has a unique label.
188
+ # If a quantization configuration options is passed, these options will
189
+ # be used for operations that will be attached to this set's label.
190
+ # Otherwise, it will be a configure-less set (used in fusing):
191
+
192
+ generated_tpm.set_simd_padding(is_simd_padding=True)
193
+
194
+ # May suit for operations like: Dropout, Reshape, etc.
195
+ default_qco = tp.get_default_quantization_config_options()
196
+ tp.OperatorsSet("NoQuantization",
197
+ default_qco.clone_and_edit(enable_activation_quantization=False,
198
+ supported_input_activation_n_bits=(8, 16))
199
+ .clone_and_edit_weight_attribute(enable_weights_quantization=False))
200
+
201
+ # Create Mixed-Precision quantization configuration options from the given list of OpQuantizationConfig objects
202
+ mixed_precision_configuration_options = tp.QuantizationConfigOptions(mixed_precision_cfg_list,
203
+ base_config=base_config)
204
+
205
+ # Define operator sets that use mixed_precision_configuration_options:
206
+ conv = tp.OperatorsSet("Conv", mixed_precision_configuration_options)
207
+ fc = tp.OperatorsSet("FullyConnected", mixed_precision_configuration_options)
208
+
209
+ # Define operations sets without quantization configuration
210
+ # options (useful for creating fusing patterns, for example):
211
+ any_relu = tp.OperatorsSet("AnyReLU")
212
+ add = tp.OperatorsSet("Add", const_configuration_options_inout16)
213
+ sub = tp.OperatorsSet("Sub", const_configuration_options_inout16)
214
+ mul = tp.OperatorsSet("Mul", const_configuration_options_inout16)
215
+ div = tp.OperatorsSet("Div", const_configuration_options)
216
+ prelu = tp.OperatorsSet("PReLU")
217
+ swish = tp.OperatorsSet("Swish")
218
+ sigmoid = tp.OperatorsSet("Sigmoid")
219
+ tanh = tp.OperatorsSet("Tanh")
220
+
221
+ # Combine multiple operators into a single operator to avoid quantization between
222
+ # them. To do this we define fusing patterns using the OperatorsSets that were created.
223
+ # To group multiple sets with regard to fusing, an OperatorSetConcat can be created
224
+ activations_after_conv_to_fuse = tp.OperatorSetConcat(any_relu, swish, prelu, sigmoid, tanh)
225
+ activations_after_fc_to_fuse = tp.OperatorSetConcat(any_relu, swish, sigmoid)
226
+ any_binary = tp.OperatorSetConcat(add, sub, mul, div)
227
+
228
+ # ------------------- #
229
+ # Fusions
230
+ # ------------------- #
231
+ tp.Fusing([conv, activations_after_conv_to_fuse])
232
+ tp.Fusing([fc, activations_after_fc_to_fuse])
233
+ tp.Fusing([any_binary, any_relu])
234
+
235
+ return generated_tpm
@@ -0,0 +1,132 @@
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
+ import tensorflow as tf
16
+ from packaging import version
17
+
18
+ from model_compression_toolkit.defaultdict import DefaultDict
19
+ from model_compression_toolkit.constants import FOUND_SONY_CUSTOM_LAYERS
20
+ from model_compression_toolkit.target_platform_capabilities.constants import KERNEL_ATTR, KERAS_DEPTHWISE_KERNEL, \
21
+ KERAS_KERNEL, BIAS_ATTR, BIAS
22
+
23
+ if FOUND_SONY_CUSTOM_LAYERS:
24
+ from sony_custom_layers.keras.object_detection.ssd_post_process import SSDPostProcess
25
+
26
+ if version.parse(tf.__version__) >= version.parse("2.13"):
27
+ from keras.src.layers import Conv2D, DepthwiseConv2D, Dense, Reshape, ZeroPadding2D, Dropout, \
28
+ MaxPooling2D, Activation, ReLU, Add, Subtract, Multiply, PReLU, Flatten, Cropping2D, LeakyReLU, Permute, \
29
+ Conv2DTranspose, Identity
30
+ else:
31
+ from keras.layers import Conv2D, DepthwiseConv2D, Dense, Reshape, ZeroPadding2D, Dropout, \
32
+ MaxPooling2D, Activation, ReLU, Add, Subtract, Multiply, PReLU, Flatten, Cropping2D, LeakyReLU, Permute, \
33
+ Conv2DTranspose, Identity
34
+
35
+ from model_compression_toolkit.target_platform_capabilities.tpc_models.imx500_tpc.v4.tp_model import get_tp_model
36
+ import model_compression_toolkit as mct
37
+ from model_compression_toolkit.target_platform_capabilities.tpc_models.imx500_tpc.v4 import __version__ as TPC_VERSION
38
+
39
+ tp = mct.target_platform
40
+
41
+
42
+ def get_keras_tpc() -> tp.TargetPlatformCapabilities:
43
+ """
44
+ get a Keras TargetPlatformCapabilities object with default operation sets to layers mapping.
45
+
46
+ Returns: a Keras TargetPlatformCapabilities object for the given TargetPlatformModel.
47
+ """
48
+ imx500_tpc_tp_model = get_tp_model()
49
+ return generate_keras_tpc(name='imx500_tpc_keras_tpc', tp_model=imx500_tpc_tp_model)
50
+
51
+
52
+ def generate_keras_tpc(name: str, tp_model: tp.TargetPlatformModel):
53
+ """
54
+ Generates a TargetPlatformCapabilities object with default operation sets to layers mapping.
55
+
56
+ Args:
57
+ name: Name of the TargetPlatformCapabilities.
58
+ tp_model: TargetPlatformModel object.
59
+
60
+ Returns: a TargetPlatformCapabilities object for the given TargetPlatformModel.
61
+ """
62
+
63
+ keras_tpc = tp.TargetPlatformCapabilities(tp_model, name=name, version=TPC_VERSION)
64
+
65
+ no_quant_list = [Identity,
66
+ tf.identity,
67
+ Reshape,
68
+ tf.reshape,
69
+ Permute,
70
+ tf.transpose,
71
+ Flatten,
72
+ Cropping2D,
73
+ ZeroPadding2D,
74
+ Dropout,
75
+ MaxPooling2D,
76
+ tf.split,
77
+ tf.quantization.fake_quant_with_min_max_vars,
78
+ tf.math.argmax,
79
+ tf.shape,
80
+ tf.math.equal,
81
+ tf.gather,
82
+ tf.cast,
83
+ tf.unstack,
84
+ tf.compat.v1.gather,
85
+ tf.nn.top_k,
86
+ tf.__operators__.getitem,
87
+ tf.strided_slice,
88
+ tf.image.combined_non_max_suppression,
89
+ tf.compat.v1.shape]
90
+
91
+ if FOUND_SONY_CUSTOM_LAYERS:
92
+ no_quant_list.append(SSDPostProcess)
93
+
94
+ with keras_tpc:
95
+ tp.OperationsSetToLayers("NoQuantization", no_quant_list)
96
+ tp.OperationsSetToLayers("Conv",
97
+ [Conv2D,
98
+ DepthwiseConv2D,
99
+ Conv2DTranspose,
100
+ tf.nn.conv2d,
101
+ tf.nn.depthwise_conv2d,
102
+ tf.nn.conv2d_transpose],
103
+ # we provide attributes mapping that maps each layer type in the operations set
104
+ # that has weights attributes with provided quantization config (in the tp model) to
105
+ # its framework-specific attribute name.
106
+ # note that a DefaultDict should be provided if not all the layer types in the
107
+ # operation set are provided separately in the mapping.
108
+ attr_mapping={
109
+ KERNEL_ATTR: DefaultDict({
110
+ DepthwiseConv2D: KERAS_DEPTHWISE_KERNEL,
111
+ tf.nn.depthwise_conv2d: KERAS_DEPTHWISE_KERNEL}, default_value=KERAS_KERNEL),
112
+ BIAS_ATTR: DefaultDict(default_value=BIAS)})
113
+ tp.OperationsSetToLayers("FullyConnected", [Dense],
114
+ attr_mapping={KERNEL_ATTR: DefaultDict(default_value=KERAS_KERNEL),
115
+ BIAS_ATTR: DefaultDict(default_value=BIAS)})
116
+ tp.OperationsSetToLayers("AnyReLU", [tf.nn.relu,
117
+ tf.nn.relu6,
118
+ tf.nn.leaky_relu,
119
+ ReLU,
120
+ LeakyReLU,
121
+ tp.LayerFilterParams(Activation, activation="relu"),
122
+ tp.LayerFilterParams(Activation, activation="leaky_relu")])
123
+ tp.OperationsSetToLayers("Add", [tf.add, Add])
124
+ tp.OperationsSetToLayers("Sub", [tf.subtract, Subtract])
125
+ tp.OperationsSetToLayers("Mul", [tf.math.multiply, Multiply])
126
+ tp.OperationsSetToLayers("Div", [tf.math.divide, tf.math.truediv])
127
+ tp.OperationsSetToLayers("PReLU", [PReLU])
128
+ tp.OperationsSetToLayers("Swish", [tf.nn.swish, tp.LayerFilterParams(Activation, activation="swish")])
129
+ tp.OperationsSetToLayers("Sigmoid", [tf.nn.sigmoid, tp.LayerFilterParams(Activation, activation="sigmoid")])
130
+ tp.OperationsSetToLayers("Tanh", [tf.nn.tanh, tp.LayerFilterParams(Activation, activation="tanh")])
131
+
132
+ return keras_tpc
@@ -0,0 +1,112 @@
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
+ import operator
17
+
18
+ import torch
19
+ from torch import add, sub, mul, div, flatten, reshape, split, unsqueeze, dropout, sigmoid, tanh, chunk, unbind, topk, \
20
+ gather, equal, transpose, permute, argmax, squeeze
21
+ from torch.nn import Conv2d, Linear, ConvTranspose2d, MaxPool2d
22
+ from torch.nn import Dropout, Flatten, Hardtanh, Identity
23
+ from torch.nn import ReLU, ReLU6, PReLU, SiLU, Sigmoid, Tanh, Hardswish, LeakyReLU
24
+ from torch.nn.functional import relu, relu6, prelu, silu, hardtanh, hardswish, leaky_relu
25
+
26
+ from model_compression_toolkit.defaultdict import DefaultDict
27
+ from model_compression_toolkit.target_platform_capabilities.constants import KERNEL_ATTR, BIAS_ATTR, PYTORCH_KERNEL, \
28
+ BIAS
29
+ from model_compression_toolkit.target_platform_capabilities.tpc_models.imx500_tpc.v4.tp_model import get_tp_model
30
+ import model_compression_toolkit as mct
31
+ from model_compression_toolkit.target_platform_capabilities.tpc_models.imx500_tpc.v4 import __version__ as TPC_VERSION
32
+
33
+ tp = mct.target_platform
34
+
35
+
36
+ def get_pytorch_tpc() -> tp.TargetPlatformCapabilities:
37
+ """
38
+ get a Pytorch TargetPlatformCapabilities object with default operation sets to layers mapping.
39
+
40
+ Returns: a Pytorch TargetPlatformCapabilities object for the given TargetPlatformModel.
41
+ """
42
+ imx500_tpc_tp_model = get_tp_model()
43
+ return generate_pytorch_tpc(name='imx500_tpc_pytorch_tpc', tp_model=imx500_tpc_tp_model)
44
+
45
+
46
+ def generate_pytorch_tpc(name: str, tp_model: tp.TargetPlatformModel):
47
+ """
48
+ Generates a TargetPlatformCapabilities object with default operation sets to layers mapping.
49
+ Args:
50
+ name: Name of the TargetPlatformModel.
51
+ tp_model: TargetPlatformModel object.
52
+ Returns: a TargetPlatformCapabilities object for the given TargetPlatformModel.
53
+ """
54
+
55
+ pytorch_tpc = tp.TargetPlatformCapabilities(tp_model,
56
+ name=name,
57
+ version=TPC_VERSION)
58
+
59
+ # we provide attributes mapping that maps each layer type in the operations set
60
+ # that has weights attributes with provided quantization config (in the tp model) to
61
+ # its framework-specific attribute name.
62
+ # note that a DefaultDict should be provided if not all the layer types in the
63
+ # operation set are provided separately in the mapping.
64
+ pytorch_linear_attr_mapping = {KERNEL_ATTR: DefaultDict(default_value=PYTORCH_KERNEL),
65
+ BIAS_ATTR: DefaultDict(default_value=BIAS)}
66
+
67
+ with pytorch_tpc:
68
+ tp.OperationsSetToLayers("NoQuantization", [Identity,
69
+ Dropout,
70
+ Flatten,
71
+ dropout,
72
+ flatten,
73
+ split,
74
+ operator.getitem,
75
+ reshape,
76
+ unsqueeze,
77
+ chunk,
78
+ unbind,
79
+ torch.Tensor.size,
80
+ permute,
81
+ transpose,
82
+ equal,
83
+ argmax,
84
+ gather,
85
+ topk,
86
+ squeeze,
87
+ MaxPool2d])
88
+
89
+ tp.OperationsSetToLayers("Conv", [Conv2d, ConvTranspose2d],
90
+ attr_mapping=pytorch_linear_attr_mapping)
91
+ tp.OperationsSetToLayers("FullyConnected", [Linear],
92
+ attr_mapping=pytorch_linear_attr_mapping)
93
+ tp.OperationsSetToLayers("AnyReLU", [torch.relu,
94
+ ReLU,
95
+ ReLU6,
96
+ LeakyReLU,
97
+ relu,
98
+ relu6,
99
+ leaky_relu,
100
+ tp.LayerFilterParams(Hardtanh, min_val=0),
101
+ tp.LayerFilterParams(hardtanh, min_val=0)])
102
+
103
+ tp.OperationsSetToLayers("Add", [operator.add, add])
104
+ tp.OperationsSetToLayers("Sub", [operator.sub, sub])
105
+ tp.OperationsSetToLayers("Mul", [operator.mul, mul])
106
+ tp.OperationsSetToLayers("Div", [operator.truediv, div])
107
+ tp.OperationsSetToLayers("PReLU", [PReLU, prelu])
108
+ tp.OperationsSetToLayers("Swish", [SiLU, silu, Hardswish, hardswish])
109
+ tp.OperationsSetToLayers("Sigmoid", [Sigmoid, sigmoid])
110
+ tp.OperationsSetToLayers("Tanh", [Tanh, tanh])
111
+
112
+ return pytorch_tpc
@@ -90,6 +90,7 @@ def get_op_quantization_configs() -> Tuple[OpQuantizationConfig, List[OpQuantiza
90
90
  attr_weights_configs_mapping={},
91
91
  activation_quantization_method=tp.QuantizationMethod.POWER_OF_TWO,
92
92
  activation_n_bits=8,
93
+ supported_input_activation_n_bits=8,
93
94
  enable_activation_quantization=True,
94
95
  quantization_preserving=False,
95
96
  fixed_scale=None,
@@ -102,6 +103,7 @@ def get_op_quantization_configs() -> Tuple[OpQuantizationConfig, List[OpQuantiza
102
103
  default_weight_attr_config=default_weight_attr_config,
103
104
  attr_weights_configs_mapping={KERNEL_ATTR: kernel_base_config, BIAS_ATTR: bias_config},
104
105
  activation_n_bits=8,
106
+ supported_input_activation_n_bits=8,
105
107
  enable_activation_quantization=True,
106
108
  quantization_preserving=False,
107
109
  fixed_scale=None,
@@ -88,6 +88,7 @@ def get_op_quantization_configs() -> Tuple[OpQuantizationConfig, List[OpQuantiza
88
88
  attr_weights_configs_mapping={},
89
89
  activation_quantization_method=tp.QuantizationMethod.POWER_OF_TWO,
90
90
  activation_n_bits=8,
91
+ supported_input_activation_n_bits=8,
91
92
  enable_activation_quantization=True,
92
93
  quantization_preserving=False,
93
94
  fixed_scale=None,
@@ -100,6 +101,7 @@ def get_op_quantization_configs() -> Tuple[OpQuantizationConfig, List[OpQuantiza
100
101
  default_weight_attr_config=default_weight_attr_config,
101
102
  attr_weights_configs_mapping={KERNEL_ATTR: kernel_base_config, BIAS_ATTR: bias_config},
102
103
  activation_n_bits=8,
104
+ supported_input_activation_n_bits=8,
103
105
  enable_activation_quantization=True,
104
106
  quantization_preserving=False,
105
107
  fixed_scale=None,