mct-nightly 1.10.0.20231018.post358__py3-none-any.whl → 1.10.0.20231019.post424__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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: mct-nightly
3
- Version: 1.10.0.20231018.post358
3
+ Version: 1.10.0.20231019.post424
4
4
  Summary: A Model Compression Toolkit for neural networks
5
5
  Home-page: UNKNOWN
6
6
  License: UNKNOWN
@@ -373,10 +373,13 @@ model_compression_toolkit/qat/keras/quantizer/ste_rounding/symmetric_ste.py,sha2
373
373
  model_compression_toolkit/qat/keras/quantizer/ste_rounding/uniform_ste.py,sha256=EED6LfqhX_OhDRJ9e4GwbpgNC9vq7hoXyJS2VPvG2qc,10789
374
374
  model_compression_toolkit/qat/pytorch/__init__.py,sha256=cco4TmeIDIh32nj9ZZXVkws4dd9F2UDrmjKzTN8G0V0,697
375
375
  model_compression_toolkit/qat/pytorch/quantization_facade.py,sha256=LGIk_nbcQEOhSN8fe56u6QGGUtGOVhF7tlCwW2G-Ig4,12549
376
- model_compression_toolkit/qat/pytorch/quantizer/__init__.py,sha256=R4vwVcbg6QprCTNzibyF9PtbKKKBsfu9ffypKDNscJQ,859
376
+ model_compression_toolkit/qat/pytorch/quantizer/__init__.py,sha256=xYa4C8pr9cG1f3mQQcBXO_u3IdJN-zl7leZxuXDs86w,1003
377
377
  model_compression_toolkit/qat/pytorch/quantizer/base_pytorch_qat_quantizer.py,sha256=FnhuFCuQoSf78FM1z1UZgXXd3k-mKSM7i9dYOuJUmeA,2213
378
378
  model_compression_toolkit/qat/pytorch/quantizer/quantization_builder.py,sha256=GOYRDXvQSGe_iUFVmvDy5BqC952hu_-rQO06n8QCyw0,5491
379
- model_compression_toolkit/qat/pytorch/quantizer/quantizer_utils.py,sha256=5XswoF-5aaFangkHssWKAQTsk6lf_zzndzfCsBWBVMs,5004
379
+ model_compression_toolkit/qat/pytorch/quantizer/quantizer_utils.py,sha256=nO7IrDRo5b9Asf21WJacE4vf5voD3UzF_oGjBoGusD4,5335
380
+ model_compression_toolkit/qat/pytorch/quantizer/lsq/__init__.py,sha256=huHoBUcKNB6BnY6YaUCcFvdyBtBI172ZoUD8ZYeNc6o,696
381
+ model_compression_toolkit/qat/pytorch/quantizer/lsq/symmetric_lsq.py,sha256=HihuaMi0P0OQkNZlZAE-QeYlK_4AqcDKV6N405SdgI0,10712
382
+ model_compression_toolkit/qat/pytorch/quantizer/lsq/uniform_lsq.py,sha256=fqAI151SUo9OYN4UvQJIcdB6p1r7HVeteqPqHGxv-tI,10355
380
383
  model_compression_toolkit/qat/pytorch/quantizer/ste_rounding/__init__.py,sha256=Rf1RcYmelmdZmBV5qOKvKWF575ofc06JFQSq83Jz99A,696
381
384
  model_compression_toolkit/qat/pytorch/quantizer/ste_rounding/symmetric_ste.py,sha256=4xmLmg7yN2A7iKnifwkWddgJTWMUiIjFilIuorJeK1A,9657
382
385
  model_compression_toolkit/qat/pytorch/quantizer/ste_rounding/uniform_ste.py,sha256=HshW016iVAMx7iMkUwlONN2P3K4XgDIu-2AnJnBVSGo,8778
@@ -445,8 +448,8 @@ model_compression_toolkit/trainable_infrastructure/keras/quantize_wrapper.py,sha
445
448
  model_compression_toolkit/trainable_infrastructure/keras/quantizer_utils.py,sha256=MVwXNymmFRB2NXIBx4e2mdJ1RfoHxRPYRgjb1MQP5kY,1797
446
449
  model_compression_toolkit/trainable_infrastructure/pytorch/__init__.py,sha256=huHoBUcKNB6BnY6YaUCcFvdyBtBI172ZoUD8ZYeNc6o,696
447
450
  model_compression_toolkit/trainable_infrastructure/pytorch/base_pytorch_quantizer.py,sha256=SbvRlIdE32PEBsINt1bhSqvrKL_zbM9V-aeSkOn-sw4,3083
448
- mct_nightly-1.10.0.20231018.post358.dist-info/LICENSE.md,sha256=aYSSIb-5AFPeITTvXm1UAoe0uYBiMmSS8flvXaaFUks,10174
449
- mct_nightly-1.10.0.20231018.post358.dist-info/METADATA,sha256=mVpOJhL0dYj3nqrs9owiW0nPowR7YwjXGpEF7c0vt2E,16303
450
- mct_nightly-1.10.0.20231018.post358.dist-info/WHEEL,sha256=yQN5g4mg4AybRjkgi-9yy4iQEFibGQmlz78Pik5Or-A,92
451
- mct_nightly-1.10.0.20231018.post358.dist-info/top_level.txt,sha256=gsYA8juk0Z-ZmQRKULkb3JLGdOdz8jW_cMRjisn9ga4,26
452
- mct_nightly-1.10.0.20231018.post358.dist-info/RECORD,,
451
+ mct_nightly-1.10.0.20231019.post424.dist-info/LICENSE.md,sha256=aYSSIb-5AFPeITTvXm1UAoe0uYBiMmSS8flvXaaFUks,10174
452
+ mct_nightly-1.10.0.20231019.post424.dist-info/METADATA,sha256=7KfKPP_oFOaieSu_3UTKRv1F3HaR5jiwMOP1DiBAiIg,16303
453
+ mct_nightly-1.10.0.20231019.post424.dist-info/WHEEL,sha256=yQN5g4mg4AybRjkgi-9yy4iQEFibGQmlz78Pik5Or-A,92
454
+ mct_nightly-1.10.0.20231019.post424.dist-info/top_level.txt,sha256=gsYA8juk0Z-ZmQRKULkb3JLGdOdz8jW_cMRjisn9ga4,26
455
+ mct_nightly-1.10.0.20231019.post424.dist-info/RECORD,,
@@ -14,4 +14,6 @@
14
14
  # ==============================================================================
15
15
 
16
16
  import model_compression_toolkit.qat.pytorch.quantizer.ste_rounding.symmetric_ste
17
- import model_compression_toolkit.qat.pytorch.quantizer.ste_rounding.uniform_ste
17
+ import model_compression_toolkit.qat.pytorch.quantizer.ste_rounding.uniform_ste
18
+ import model_compression_toolkit.qat.pytorch.quantizer.lsq.symmetric_lsq
19
+ import model_compression_toolkit.qat.pytorch.quantizer.lsq.uniform_lsq
@@ -0,0 +1,14 @@
1
+ # Copyright 2023 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
+ # ==============================================================================
@@ -0,0 +1,228 @@
1
+ # Copyright 2023 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 Union
16
+
17
+ import numpy as np
18
+ import torch
19
+ import torch.nn as nn
20
+
21
+ from model_compression_toolkit.qat import TrainingMethod
22
+ from model_compression_toolkit.target_platform_capabilities.target_platform import QuantizationMethod
23
+ from mct_quantizers import PytorchQuantizationWrapper
24
+ from model_compression_toolkit.qat.common import THRESHOLD_TENSOR
25
+ from model_compression_toolkit import constants as C
26
+ from model_compression_toolkit.qat.pytorch.quantizer.base_pytorch_qat_quantizer import BasePytorchQATTrainableQuantizer
27
+ from mct_quantizers.common.base_inferable_quantizer import mark_quantizer, QuantizationTarget
28
+
29
+ from model_compression_toolkit.core.pytorch.utils import to_torch_tensor
30
+ from model_compression_toolkit.qat.pytorch.quantizer.quantizer_utils import ste_round, grad_scale
31
+ from mct_quantizers.pytorch.quantizers import \
32
+ WeightsPOTInferableQuantizer, WeightsSymmetricInferableQuantizer, ActivationPOTInferableQuantizer, \
33
+ ActivationSymmetricInferableQuantizer
34
+ from model_compression_toolkit.trainable_infrastructure.common.trainable_quantizer_config import \
35
+ TrainableQuantizerWeightsConfig, TrainableQuantizerActivationConfig
36
+ from model_compression_toolkit.trainable_infrastructure.common.base_trainable_quantizer import VariableGroup
37
+
38
+
39
+ def symmetric_lsq_quantizer(x: nn.Parameter,
40
+ thresholds: nn.Parameter,
41
+ num_bits: int,
42
+ sign: bool,
43
+ min_int: int,
44
+ max_int: int,
45
+ scale_factor: float) -> Union[nn.Parameter, torch.Tensor]:
46
+ """
47
+ Symmetric quantizer according to LSQ algorithm: https://arxiv.org/pdf/1902.08153.pdf
48
+ Args:
49
+ x: input to quantize
50
+ thresholds: thresholds of quantization levels
51
+ num_bits: number of bits for quantization
52
+ sign: whether x is signed or not
53
+ min_int: min clipping integer value
54
+ max_int: max clipping integer value
55
+ scale_factor: grad scale of LSQ algorithm
56
+ Returns:
57
+ A quantized tensor
58
+ """
59
+ delta = thresholds / (2 ** (num_bits - int(sign)))
60
+ delta_scaled = grad_scale(delta, scale_factor)
61
+ rounded = ste_round(x / delta_scaled)
62
+ clipped = torch.clip(rounded, min=min_int, max=max_int)
63
+ quantized = delta_scaled * clipped
64
+ return quantized
65
+
66
+
67
+ @mark_quantizer(quantization_target=QuantizationTarget.Weights,
68
+ quantization_method=[QuantizationMethod.POWER_OF_TWO, QuantizationMethod.SYMMETRIC],
69
+ identifier=TrainingMethod.LSQ)
70
+ class LSQWeightQATQuantizer(BasePytorchQATTrainableQuantizer):
71
+ """
72
+ Trainable constrained quantizer to quantize layer's weights.
73
+ """
74
+
75
+ def __init__(self, quantization_config: TrainableQuantizerWeightsConfig):
76
+ """
77
+ Initialize a LSQWeightQATQuantizer object with parameters to use
78
+ for the quantization.
79
+
80
+ Args:
81
+ quantization_config: trainable quantizer config class
82
+ """
83
+ super().__init__(quantization_config)
84
+ self.power_of_two = quantization_config.weights_quantization_method == QuantizationMethod.POWER_OF_TWO
85
+ self.threshold_values = np.array(quantization_config.weights_quantization_params[C.THRESHOLD])
86
+ if self.power_of_two:
87
+ self.threshold_values = np.power(2.0, np.ceil(np.log2(np.maximum(self.threshold_values, C.MIN_THRESHOLD))))
88
+ self.num_bits = self.quantization_config.weights_n_bits
89
+ n_pos_bits = self.num_bits - int(C.WEIGHTS_SIGNED)
90
+ self.min_int = -int(C.WEIGHTS_SIGNED) * (2 ** n_pos_bits)
91
+ self.max_int = 2 ** n_pos_bits - 1
92
+ self.scale_factor = 1.0 / np.sqrt(self.max_int * self.threshold_values.size)
93
+
94
+ def initialize_quantization(self,
95
+ tensor_shape: torch.Size,
96
+ name: str,
97
+ layer: PytorchQuantizationWrapper):
98
+ """
99
+ Add quantizer parameters to the quantizer parameters dictionary
100
+
101
+ Args:
102
+ tensor_shape: tensor shape of the quantized tensor.
103
+ name: Tensor name.
104
+ layer: Layer to quantize.
105
+ """
106
+
107
+ # Add threshold variables to layer.
108
+ layer.register_parameter(name + "_" + THRESHOLD_TENSOR, nn.Parameter(to_torch_tensor(self.threshold_values), requires_grad=True))
109
+
110
+ # save the quantizer added parameters for later calculations
111
+ self.add_quantizer_variable(THRESHOLD_TENSOR, layer.get_parameter(name + "_" + THRESHOLD_TENSOR), VariableGroup.QPARAMS)
112
+
113
+
114
+ def __call__(self,
115
+ inputs: nn.Parameter,
116
+ training: bool) -> nn.Parameter:
117
+ """
118
+ Quantize a tensor
119
+ Args:
120
+ inputs: Input tensor to quantize.
121
+ training: whether in training mode or not
122
+ Returns:
123
+ quantized tensor
124
+ """
125
+ thresholds = self.get_quantizer_variable(THRESHOLD_TENSOR)
126
+ weight_quantized = symmetric_lsq_quantizer(inputs, thresholds, self.num_bits, C.WEIGHTS_SIGNED, self.min_int, self.max_int, self.scale_factor)
127
+ return weight_quantized
128
+
129
+ def convert2inferable(self) -> Union[WeightsPOTInferableQuantizer, WeightsSymmetricInferableQuantizer]:
130
+ """
131
+ Convert quantizer to inferable quantizer.
132
+
133
+ Returns:
134
+ A pytorch inferable quanizer object.
135
+ """
136
+ threshold_values = self.get_quantizer_variable(THRESHOLD_TENSOR).cpu().detach().numpy().flatten()
137
+ if self.power_of_two:
138
+ pot_threshold = 2 ** np.ceil(np.log2(threshold_values))
139
+ return WeightsPOTInferableQuantizer(num_bits=self.num_bits,
140
+ threshold=pot_threshold.tolist(),
141
+ per_channel=self.quantization_config.weights_per_channel_threshold,
142
+ channel_axis=self.quantization_config.weights_channels_axis)
143
+ else:
144
+ return WeightsSymmetricInferableQuantizer(num_bits=self.num_bits,
145
+ threshold=threshold_values.tolist(),
146
+ per_channel=self.quantization_config.weights_per_channel_threshold,
147
+ channel_axis=self.quantization_config.weights_channels_axis)
148
+
149
+
150
+
151
+ @mark_quantizer(quantization_target=QuantizationTarget.Activation,
152
+ quantization_method=[QuantizationMethod.POWER_OF_TWO, QuantizationMethod.SYMMETRIC],
153
+ identifier=TrainingMethod.LSQ)
154
+ class LSQActivationQATQuantizer(BasePytorchQATTrainableQuantizer):
155
+ """
156
+ Trainable constrained quantizer to quantize layer activations.
157
+ """
158
+
159
+ def __init__(self, quantization_config: TrainableQuantizerActivationConfig):
160
+ """
161
+ Initialize a LSQActivationQATQuantizer object with parameters to use
162
+ for symmetric or power of two quantization.
163
+
164
+ Args:
165
+ quantization_config: trainable quantizer config class
166
+ """
167
+ super().__init__(quantization_config)
168
+ self.power_of_two = quantization_config.activation_quantization_method == QuantizationMethod.POWER_OF_TWO
169
+ self.sign = quantization_config.activation_quantization_params['is_signed']
170
+ self.threshold_values = np.array([quantization_config.activation_quantization_params[C.THRESHOLD]])
171
+ self.num_bits = quantization_config.activation_n_bits
172
+ n_pos_bits = self.num_bits - int(self.sign)
173
+ self.min_int = -int(self.sign) * (2 ** n_pos_bits)
174
+ self.max_int = (2 ** n_pos_bits) - 1
175
+
176
+ def initialize_quantization(self,
177
+ tensor_shape: torch.Size,
178
+ name: str,
179
+ layer: PytorchQuantizationWrapper):
180
+ """
181
+ Add quantizer parameters to the quantizer parameters dictionary
182
+
183
+ Args:
184
+ tensor_shape: tensor shape of the quantized tensor.
185
+ name: Tensor name.
186
+ layer: Layer to quantize.
187
+ """
188
+ layer.register_parameter(name, nn.Parameter(to_torch_tensor(self.threshold_values), requires_grad=True))
189
+
190
+ # save the quantizer added parameters for later calculations
191
+ self.add_quantizer_variable(THRESHOLD_TENSOR, layer.get_parameter(name), VariableGroup.QPARAMS)
192
+
193
+ def __call__(self,
194
+ inputs: torch.Tensor,
195
+ training: bool = True) -> torch.Tensor:
196
+ """
197
+ Quantize a tensor.
198
+ Args:
199
+ inputs: Input tensor to quantize.
200
+ training: Whether the graph is in training mode.
201
+
202
+ Returns:
203
+ The quantized tensor.
204
+ """
205
+
206
+ thresholds = self.get_quantizer_variable(THRESHOLD_TENSOR)
207
+ n_channels = inputs.shape[1]
208
+ scale_factor = 1.0 / np.sqrt(self.max_int * n_channels)
209
+ inputs_quantized = symmetric_lsq_quantizer(inputs, thresholds, self.num_bits, self.sign, self.min_int, self.max_int, scale_factor)
210
+ return inputs_quantized
211
+
212
+ def convert2inferable(self) -> Union[ActivationPOTInferableQuantizer, ActivationSymmetricInferableQuantizer]:
213
+ """
214
+ Convert quantizer to inferable quantizer.
215
+
216
+ Returns:
217
+ A pytorch inferable quanizer object.
218
+ """
219
+ threshold_values = self.get_quantizer_variable(THRESHOLD_TENSOR).cpu().detach().numpy()
220
+ if self.power_of_two:
221
+ pot_threshold = np.power(2.0, np.ceil(np.log2(threshold_values)))
222
+ return ActivationPOTInferableQuantizer(num_bits=self.num_bits,
223
+ threshold=pot_threshold.tolist(),
224
+ signed=self.sign)
225
+ else:
226
+ return ActivationSymmetricInferableQuantizer(num_bits=self.num_bits,
227
+ threshold=threshold_values.tolist(),
228
+ signed=self.sign)
@@ -0,0 +1,223 @@
1
+ # Copyright 2023 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 Union
16
+ import numpy as np
17
+ import torch
18
+ import torch.nn as nn
19
+
20
+ from model_compression_toolkit.constants import RANGE_MAX, RANGE_MIN
21
+ from model_compression_toolkit.trainable_infrastructure.common.constants import FQ_MIN, FQ_MAX
22
+
23
+ from model_compression_toolkit.qat import TrainingMethod
24
+ from model_compression_toolkit.target_platform_capabilities.target_platform import QuantizationMethod
25
+ from mct_quantizers import QuantizationTarget, PytorchQuantizationWrapper
26
+ from model_compression_toolkit import constants as C
27
+
28
+ from model_compression_toolkit.qat.pytorch.quantizer.base_pytorch_qat_quantizer import BasePytorchQATTrainableQuantizer
29
+ from mct_quantizers import mark_quantizer
30
+ from model_compression_toolkit.qat.pytorch.quantizer.quantizer_utils import ste_round, grad_scale
31
+ from model_compression_toolkit.core.pytorch.utils import to_torch_tensor
32
+ from mct_quantizers.pytorch.quantizers import \
33
+ WeightsUniformInferableQuantizer, ActivationUniformInferableQuantizer
34
+ from model_compression_toolkit.trainable_infrastructure.common.trainable_quantizer_config import \
35
+ TrainableQuantizerWeightsConfig, TrainableQuantizerActivationConfig
36
+ from model_compression_toolkit.trainable_infrastructure.common.base_trainable_quantizer import VariableGroup
37
+ from model_compression_toolkit.qat.pytorch.quantizer.quantizer_utils import adjust_range_to_include_zero
38
+ from model_compression_toolkit.core.common.quantization.quantizers.quantizers_helpers import fix_range_to_include_zero
39
+
40
+
41
+
42
+ def uniform_lsq_quantizer(x: nn.Parameter,
43
+ min_range: nn.Parameter,
44
+ max_range: nn.Parameter,
45
+ num_bits: int,
46
+ min_int: int,
47
+ max_int: int,
48
+ scale_factor: float) -> Union[nn.Parameter, torch.Tensor]:
49
+ """
50
+ Uniform quantizer according to LSQ algorithm: https://arxiv.org/pdf/1902.08153.pdf
51
+ Args:
52
+ x: input to quantize
53
+ min_range: min range of quantization values
54
+ max_range: min range of quantization values
55
+ num_bits: number of bits for quantization
56
+ min_int: min clipping integer value
57
+ max_int: max clipping integer value
58
+ scale_factor: grad scale of LSQ algorithm
59
+ Returns:
60
+ A quantized tensor
61
+ """
62
+ a, b = adjust_range_to_include_zero(min_range, max_range, num_bits)
63
+ delta = (b - a) / (2 ** num_bits - 1)
64
+ delta_scaled = grad_scale(delta, scale_factor)
65
+ rounded = ste_round((x - a) / delta_scaled)
66
+ clipped = torch.clip(rounded, min=min_int, max=max_int)
67
+ quantized = delta_scaled * clipped + a
68
+ return quantized
69
+
70
+
71
+ @mark_quantizer(quantization_target=QuantizationTarget.Weights,
72
+ quantization_method=[QuantizationMethod.UNIFORM],
73
+ identifier=TrainingMethod.LSQ)
74
+ class LSQUniformWeightQATQuantizer(BasePytorchQATTrainableQuantizer):
75
+ """
76
+ Trainable constrained quantizer to quantize layer's weights.
77
+ """
78
+
79
+ def __init__(self, quantization_config: TrainableQuantizerWeightsConfig):
80
+ """
81
+ Initialize a LSQUniformWeightQATQuantizer object with parameters to use
82
+ for the quantization.
83
+
84
+ Args:
85
+ quantization_config: trainable quantizer config class
86
+ """
87
+ super().__init__(quantization_config)
88
+ self.num_bits = self.quantization_config.weights_n_bits
89
+ self.min_int = 0
90
+ self.max_int = 2 ** self.num_bits - 1
91
+ self.min_values = np.array(quantization_config.weights_quantization_params[RANGE_MIN])
92
+ self.max_values = np.array(quantization_config.weights_quantization_params[RANGE_MAX])
93
+ self.scale_factor = 1.0 / np.sqrt(self.max_int * self.min_values.size)
94
+
95
+ def initialize_quantization(self,
96
+ tensor_shape: torch.Size,
97
+ name: str,
98
+ layer: PytorchQuantizationWrapper):
99
+ """
100
+ Add quantizer parameters to the quantizer parameters dictionary
101
+
102
+ Args:
103
+ tensor_shape: tensor shape of the quantized tensor.
104
+ name: Tensor name.
105
+ layer: Layer to quantize.
106
+ """
107
+
108
+ # Add min and max variables to layer.
109
+ layer.register_parameter(name+"_"+FQ_MIN, nn.Parameter(to_torch_tensor(self.min_values), requires_grad=True))
110
+ layer.register_parameter(name+"_"+FQ_MAX, nn.Parameter(to_torch_tensor(self.max_values), requires_grad=True))
111
+
112
+ # Save the quantizer parameters for later calculations
113
+ self.add_quantizer_variable(FQ_MIN, layer.get_parameter(name+"_"+FQ_MIN), VariableGroup.QPARAMS)
114
+ self.add_quantizer_variable(FQ_MAX, layer.get_parameter(name+"_"+FQ_MAX), VariableGroup.QPARAMS)
115
+
116
+
117
+ def __call__(self,
118
+ inputs: nn.Parameter,
119
+ training: bool) -> torch.Tensor:
120
+ """
121
+ Quantize a tensor
122
+ Args:
123
+ inputs: Input tensor to quantize.
124
+ training: whether in training mode or not
125
+ Returns:
126
+ quantized tensor
127
+ """
128
+ min_range = self.get_quantizer_variable(FQ_MIN)
129
+ max_range = self.get_quantizer_variable(FQ_MAX)
130
+ weight_quantized = uniform_lsq_quantizer(inputs, min_range, max_range, self.num_bits, self.min_int, self.max_int, self.scale_factor)
131
+ return weight_quantized
132
+
133
+ def convert2inferable(self) -> WeightsUniformInferableQuantizer:
134
+ """
135
+ Convert quantizer to inferable quantizer.
136
+
137
+ Returns:
138
+ A pytorch inferable quanizer object.
139
+ """
140
+ min_range = self.get_quantizer_variable(FQ_MIN).cpu().detach().numpy()
141
+ max_range = self.get_quantizer_variable(FQ_MAX).cpu().detach().numpy()
142
+ min_range, max_range = fix_range_to_include_zero(min_range, max_range, self.num_bits)
143
+ return WeightsUniformInferableQuantizer(num_bits=self.num_bits,
144
+ min_range=min_range.tolist(),
145
+ max_range=max_range.tolist(),
146
+ per_channel=self.quantization_config.weights_per_channel_threshold,
147
+ channel_axis=self.quantization_config.weights_channels_axis)
148
+
149
+
150
+ @mark_quantizer(quantization_target=QuantizationTarget.Activation,
151
+ quantization_method=[QuantizationMethod.UNIFORM],
152
+ identifier=TrainingMethod.LSQ)
153
+ class LSQUniformActivationQATQuantizer(BasePytorchQATTrainableQuantizer):
154
+ """
155
+ Trainable constrained quantizer to quantize layer activations.
156
+ """
157
+
158
+ def __init__(self, quantization_config: TrainableQuantizerActivationConfig):
159
+ """
160
+ Initialize a LSQUniformActivationQATQuantizer object with parameters to use
161
+ for uniform quantization.
162
+
163
+ Args:
164
+ quantization_config: trainable quantizer config class
165
+ """
166
+ super().__init__(quantization_config)
167
+ self.num_bits = self.quantization_config.activation_n_bits
168
+ self.min_int = 0
169
+ self.max_int = 2 ** self.num_bits - 1
170
+ self.min_range = np.array([quantization_config.activation_quantization_params[C.RANGE_MIN]])
171
+ self.max_range = np.array([quantization_config.activation_quantization_params[C.RANGE_MAX]])
172
+
173
+ def initialize_quantization(self,
174
+ tensor_shape: torch.Size,
175
+ name: str,
176
+ layer: PytorchQuantizationWrapper):
177
+ """
178
+ Add quantizer parameters to the quantizer parameters dictionary
179
+
180
+ Args:
181
+ tensor_shape: tensor shape of the quantized tensor.
182
+ name: Tensor name.
183
+ layer: Layer to quantize.
184
+ """
185
+ layer.register_parameter(name+"_"+FQ_MIN, nn.Parameter(to_torch_tensor(self.min_range), requires_grad=True))
186
+ layer.register_parameter(name+"_"+FQ_MAX, nn.Parameter(to_torch_tensor(self.max_range), requires_grad=True))
187
+
188
+ # Save the quantizer parameters for later calculations
189
+ self.add_quantizer_variable(FQ_MIN, layer.get_parameter(name+"_"+FQ_MIN), VariableGroup.QPARAMS)
190
+ self.add_quantizer_variable(FQ_MAX, layer.get_parameter(name+"_"+FQ_MAX), VariableGroup.QPARAMS)
191
+
192
+ def __call__(self,
193
+ inputs: torch.Tensor,
194
+ training: bool = True) -> torch.Tensor:
195
+ """
196
+ Quantize a tensor.
197
+ Args:
198
+ inputs: Input tensor to quantize.
199
+ training: Whether the graph is in training mode.
200
+
201
+ Returns:
202
+ The quantized tensor.
203
+ """
204
+ min_range = self.get_quantizer_variable(FQ_MIN)
205
+ max_range = self.get_quantizer_variable(FQ_MAX)
206
+ n_channels = inputs.shape[1]
207
+ scale_factor = 1.0 / np.sqrt(self.max_int * n_channels)
208
+ inputs_quantized = uniform_lsq_quantizer(inputs, min_range, max_range, self.num_bits, self.min_int, self.max_int, scale_factor)
209
+ return inputs_quantized
210
+
211
+ def convert2inferable(self) -> ActivationUniformInferableQuantizer:
212
+ """
213
+ Convert quantizer to inferable quantizer.
214
+
215
+ Returns:
216
+ A pytorch inferable quanizer object.
217
+ """
218
+ min_range = self.get_quantizer_variable(FQ_MIN).cpu().detach().numpy()
219
+ max_range = self.get_quantizer_variable(FQ_MAX).cpu().detach().numpy()
220
+ min_range, max_range = fix_range_to_include_zero(min_range, max_range, self.num_bits)
221
+ return ActivationUniformInferableQuantizer(num_bits=self.num_bits,
222
+ min_range=min_range.tolist(),
223
+ max_range=max_range.tolist())
@@ -40,9 +40,22 @@ def ste_clip(x: torch.Tensor, min_val=-1.0, max_val=1.0) -> torch.Tensor:
40
40
  return (torch.clip(x, min=min_val, max=max_val) - x).detach() + x
41
41
 
42
42
 
43
- def fix_range_to_include_zero(range_min: torch.Tensor,
44
- range_max: torch.Tensor,
45
- n_bits: int) -> Tuple[torch.Tensor, torch.Tensor]:
43
+ def grad_scale(x: torch.Tensor, scale=1.0) -> torch.Tensor:
44
+ """
45
+ Gradient scale
46
+ Args:
47
+ x: input variable
48
+ scale: scale factor
49
+ Returns:
50
+ x in forward and x*scale in backward (for scaling the gradients).
51
+ """
52
+ x_scaled = x * scale
53
+ return (x - x_scaled).detach() + x_scaled
54
+
55
+
56
+ def adjust_range_to_include_zero(range_min: torch.Tensor,
57
+ range_max: torch.Tensor,
58
+ n_bits: int) -> Tuple[torch.Tensor, torch.Tensor]:
46
59
  """
47
60
  Adjusting the quantization range to include representation of 0.0 in the quantization grid.
48
61
  If quantization per-channel, then range_min and range_max should be tensors in the specific shape that allows
@@ -120,7 +133,7 @@ def uniform_quantizer(tensor_data: torch.Tensor,
120
133
  Quantized data.
121
134
  """
122
135
  # adjusts the quantization range so the quantization grid includes zero.
123
- a, b = fix_range_to_include_zero(range_min, range_max, n_bits)
136
+ a, b = adjust_range_to_include_zero(range_min, range_max, n_bits)
124
137
 
125
138
  # Compute the step size of quantized values.
126
139
  delta_tensor = (b - a) / (2 ** n_bits - 1)