ai-edge-quantizer-nightly 0.0.1.dev20250302__py3-none-any.whl → 0.5.0.dev20260103__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 (69) hide show
  1. ai_edge_quantizer/algorithm_manager.py +224 -0
  2. ai_edge_quantizer/algorithm_manager_api_test.py +7 -0
  3. ai_edge_quantizer/algorithms/nonlinear_quantize/float_casting_test.py +2 -2
  4. ai_edge_quantizer/algorithms/uniform_quantize/common_quantize.py +643 -20
  5. ai_edge_quantizer/algorithms/uniform_quantize/common_quantize_test.py +29 -2
  6. ai_edge_quantizer/algorithms/uniform_quantize/dequantized_weight_recovery.py +29 -35
  7. ai_edge_quantizer/algorithms/uniform_quantize/dequantized_weight_recovery_test.py +35 -12
  8. ai_edge_quantizer/algorithms/uniform_quantize/hadamard_rotation.py +414 -0
  9. ai_edge_quantizer/algorithms/uniform_quantize/hadamard_rotation_test.py +440 -0
  10. ai_edge_quantizer/algorithms/uniform_quantize/mse.py +127 -0
  11. ai_edge_quantizer/algorithms/uniform_quantize/mse_test.py +195 -0
  12. ai_edge_quantizer/algorithms/uniform_quantize/naive_min_max_quantize.py +54 -168
  13. ai_edge_quantizer/algorithms/uniform_quantize/naive_min_max_quantize_test.py +54 -17
  14. ai_edge_quantizer/algorithms/uniform_quantize/octav.py +188 -0
  15. ai_edge_quantizer/algorithms/uniform_quantize/octav_test.py +240 -0
  16. ai_edge_quantizer/algorithms/uniform_quantize/uniform_quantize_tensor.py +260 -13
  17. ai_edge_quantizer/algorithms/uniform_quantize/uniform_quantize_tensor_test.py +152 -5
  18. ai_edge_quantizer/algorithms/utils/common_utils.py +142 -54
  19. ai_edge_quantizer/calibrator.py +58 -94
  20. ai_edge_quantizer/calibrator_test.py +5 -74
  21. ai_edge_quantizer/default_policy.py +108 -16
  22. ai_edge_quantizer/model_modifier.py +132 -8
  23. ai_edge_quantizer/model_modifier_test.py +81 -1
  24. ai_edge_quantizer/model_validator.py +38 -10
  25. ai_edge_quantizer/model_validator_test.py +2 -1
  26. ai_edge_quantizer/params_generator.py +230 -47
  27. ai_edge_quantizer/params_generator_test.py +366 -261
  28. ai_edge_quantizer/qtyping.py +92 -6
  29. ai_edge_quantizer/quantizer.py +167 -23
  30. ai_edge_quantizer/quantizer_test.py +288 -26
  31. ai_edge_quantizer/recipe.py +156 -21
  32. ai_edge_quantizer/recipe_manager.py +158 -1
  33. ai_edge_quantizer/recipe_manager_test.py +146 -32
  34. ai_edge_quantizer/recipe_test.py +93 -17
  35. ai_edge_quantizer/transformation_instruction_generator.py +313 -46
  36. ai_edge_quantizer/transformation_instruction_generator_test.py +449 -27
  37. ai_edge_quantizer/transformation_performer.py +112 -58
  38. ai_edge_quantizer/transformation_performer_test.py +176 -4
  39. ai_edge_quantizer/transformations/duplicate_buffer.py +46 -0
  40. ai_edge_quantizer/transformations/duplicate_buffer_test.py +106 -0
  41. ai_edge_quantizer/transformations/duplicate_tensor.py +62 -0
  42. ai_edge_quantizer/transformations/duplicate_tensor_test.py +131 -0
  43. ai_edge_quantizer/transformations/insert_decomposed_hadamard_rotation.py +299 -0
  44. ai_edge_quantizer/transformations/insert_decomposed_hadamard_rotation_test.py +244 -0
  45. ai_edge_quantizer/transformations/insert_hadamard_rotation.py +186 -0
  46. ai_edge_quantizer/transformations/insert_hadamard_rotation_test.py +200 -0
  47. ai_edge_quantizer/transformations/quantize_tensor.py +24 -44
  48. ai_edge_quantizer/transformations/quantize_tensor_test.py +3 -2
  49. ai_edge_quantizer/transformations/transformation_utils.py +157 -11
  50. ai_edge_quantizer/transformations/transformation_utils_test.py +96 -2
  51. ai_edge_quantizer/utils/calibration_utils.py +263 -1
  52. ai_edge_quantizer/utils/calibration_utils_test.py +173 -3
  53. ai_edge_quantizer/utils/constrained_ops_utils.py +111 -0
  54. ai_edge_quantizer/utils/constrained_ops_utils_test.py +50 -0
  55. ai_edge_quantizer/utils/test_utils.py +191 -58
  56. ai_edge_quantizer/utils/tfl_flatbuffer_utils.py +96 -50
  57. ai_edge_quantizer/utils/tfl_flatbuffer_utils_test.py +20 -0
  58. ai_edge_quantizer/utils/tfl_interpreter_utils.py +138 -5
  59. ai_edge_quantizer/utils/tfl_interpreter_utils_test.py +29 -2
  60. ai_edge_quantizer/utils/validation_utils.py +114 -4
  61. ai_edge_quantizer/utils/validation_utils_test.py +80 -0
  62. {ai_edge_quantizer_nightly-0.0.1.dev20250302.dist-info → ai_edge_quantizer_nightly-0.5.0.dev20260103.dist-info}/METADATA +13 -3
  63. ai_edge_quantizer_nightly-0.5.0.dev20260103.dist-info/RECORD +81 -0
  64. {ai_edge_quantizer_nightly-0.0.1.dev20250302.dist-info → ai_edge_quantizer_nightly-0.5.0.dev20260103.dist-info}/WHEEL +1 -1
  65. ai_edge_quantizer/transformations/emulated_subchannel.py +0 -363
  66. ai_edge_quantizer/transformations/emulated_subchannel_test.py +0 -212
  67. ai_edge_quantizer_nightly-0.0.1.dev20250302.dist-info/RECORD +0 -67
  68. {ai_edge_quantizer_nightly-0.0.1.dev20250302.dist-info → ai_edge_quantizer_nightly-0.5.0.dev20260103.dist-info/licenses}/LICENSE +0 -0
  69. {ai_edge_quantizer_nightly-0.0.1.dev20250302.dist-info → ai_edge_quantizer_nightly-0.5.0.dev20260103.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,188 @@
1
+ # Copyright 2024 The AI Edge Quantizer Authors.
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
+ """Implements the OCTAV quantization."""
17
+
18
+ import dataclasses
19
+ from typing import Any, Optional, Sequence, Union
20
+ import numpy as np
21
+ from ai_edge_quantizer import qtyping
22
+ from ai_edge_quantizer.algorithms.uniform_quantize import common_quantize
23
+ from ai_edge_quantizer.algorithms.uniform_quantize import naive_min_max_quantize
24
+ from ai_edge_quantizer.algorithms.uniform_quantize import uniform_quantize_tensor
25
+ from ai_edge_quantizer.algorithms.utils import common_utils
26
+
27
+ ALGORITHM_KEY = "OCTAV"
28
+
29
+
30
+ def _guess_clipping_with_octav(
31
+ x: np.ndarray,
32
+ bits: int,
33
+ axis: Union[int, Sequence[int]],
34
+ max_iterations: int,
35
+ exponent_divisor: float,
36
+ early_stop: bool = True,
37
+ ) -> np.ndarray:
38
+ """Returns a tensor of absolute clipping constants for a tensor using OCTAV.
39
+
40
+ This method implements equation (6) from the OCTAV paper:
41
+ https://arxiv.org/abs/2206.06501
42
+
43
+ Args:
44
+ x: Tensor data to return guesses for.
45
+ bits: Number of bits used during quantization.
46
+ axis: Axis to reduce the tensor along to get the guesses.
47
+ max_iterations: Number of Newton-Raphson iterations to use.
48
+ exponent_divisor: What factor to divide the 4^-bits term by. In the paper,
49
+ 3.0 is optimal for signed ints and 12.0 for unsigned ints.
50
+ early_stop: If True, stop the iteration if the guess doesn't change.
51
+
52
+ Returns:
53
+ A tensor of shape [num_channels] with clipping constant guesses.
54
+ """
55
+ magnitude = np.abs(x)
56
+ x_reduced = np.mean(x, axis=axis, keepdims=True)
57
+ old_guess = np.zeros(x_reduced.shape)
58
+ guess = np.ones(x_reduced.shape)
59
+ for _ in range(max_iterations):
60
+ if early_stop and np.allclose(guess, old_guess):
61
+ break
62
+ guess_broadcasted = np.broadcast_to(guess, magnitude.shape)
63
+ guess_mask = np.asarray(magnitude < guess_broadcasted, dtype=x.dtype)
64
+ numerator = np.sum(
65
+ magnitude * np.asarray(1.0 - guess_mask), axis=axis, keepdims=True
66
+ )
67
+ denominator1 = (4.0 ** (-bits) / exponent_divisor) * np.sum(
68
+ guess_mask, axis=axis, keepdims=True
69
+ )
70
+ denominator2 = np.sum(1.0 - guess_mask, axis=axis, keepdims=True)
71
+ old_guess = guess
72
+ guess = numerator / (denominator1 + denominator2)
73
+
74
+ return guess
75
+
76
+
77
+ def get_tensor_quant_params(
78
+ op_info: qtyping.OpInfo,
79
+ tensor_quant_config: qtyping.TensorQuantizationConfig,
80
+ tensor_content: Optional[np.ndarray] = None,
81
+ tensor_qsv: Optional[dict[str, Any]] = None,
82
+ ) -> qtyping.UniformQuantParams:
83
+ """Returns the quantization parameters for a tensor.
84
+
85
+ Args:
86
+ op_info: Aggregated information about the op (e.g., quantization config).
87
+ tensor_quant_config: The quantization config for the tensor.
88
+ tensor_content: The content of the tensor. When None, it means the tensor is
89
+ not a weight tensor (e.g. static quantization) so we fallback to using
90
+ naive_min_max_quantize.
91
+ tensor_qsv: A dictionary containing the min/max of the tensor.
92
+
93
+ Raises:
94
+ ValueError: If the blockwise quantization is requested.
95
+ ValueError: If the asymmetric quantization is requested.
96
+ ValueError: `tensor_qsv` must contain min/max values, or `tensor_content`
97
+ must be provided so that they can be inferred.
98
+ """
99
+ # Fallback to naive_min_max_quantize.py for non-weight tensors.
100
+ if tensor_content is None:
101
+ return naive_min_max_quantize.get_tensor_quant_params(
102
+ op_info, tensor_quant_config, tensor_content, tensor_qsv
103
+ )
104
+
105
+ if not tensor_quant_config.symmetric:
106
+ raise ValueError(
107
+ f"Unsupported symmetry: {tensor_quant_config.symmetric}. OCTAV"
108
+ " supports symmetric quantization only for now."
109
+ )
110
+
111
+ if not tensor_qsv:
112
+ # We need min/max to calculate quantization parameters, which
113
+ # should be collected during the calibration process. However,
114
+ # weight-only and DRQ do not require calibration, thus it is
115
+ # possible that this information is missing here. In that case we
116
+ # collect min/max on the spot.
117
+ tensor_min_max = common_quantize.init_tensor_min_max(
118
+ tensor_content,
119
+ op_info,
120
+ )
121
+ else:
122
+ tensor_min_max = tensor_qsv
123
+
124
+ if "min" not in tensor_min_max or "max" not in tensor_min_max:
125
+ raise ValueError(
126
+ "min and max must be provided to produce tensor quantization"
127
+ " parameters. Check if the correct calibration results are passed into"
128
+ " the ParamsGenerator."
129
+ )
130
+
131
+ quantized_dim = common_utils.get_weight_quantized_dim(
132
+ op_info, tensor_content, tensor_quant_config.granularity
133
+ )
134
+ if uniform_quantize_tensor.is_blockwise(tensor_quant_config.granularity):
135
+ reshaped_data, reduce_dims = (
136
+ uniform_quantize_tensor.reshape_data_for_blockwise(
137
+ tensor_content,
138
+ op_info.op_name,
139
+ tensor_quant_config.granularity,
140
+ )
141
+ )
142
+ else:
143
+ reshaped_data = tensor_content
144
+ reduce_dims = common_utils.get_reduce_dims(
145
+ quantized_dim, tensor_content.shape
146
+ )
147
+ clipping_constants = _guess_clipping_with_octav(
148
+ reshaped_data,
149
+ tensor_quant_config.num_bits,
150
+ reduce_dims,
151
+ max_iterations=10,
152
+ exponent_divisor=3.0 if tensor_quant_config.symmetric else 12.0,
153
+ )
154
+ # We created a new dimension in order to reduce properly for blockwise
155
+ # quantization, so we need to reshape the clipping constants back to the
156
+ # min/max shape for the next step.
157
+ if uniform_quantize_tensor.is_blockwise(tensor_quant_config.granularity):
158
+ clipping_constants = clipping_constants.reshape(tensor_min_max["min"].shape)
159
+
160
+ zp, scale = uniform_quantize_tensor.tensor_zp_scale_from_min_max(
161
+ tensor_min_max["min"],
162
+ tensor_min_max["max"],
163
+ tensor_quant_config.num_bits,
164
+ tensor_quant_config.symmetric,
165
+ tensor_quant_config.granularity,
166
+ clipping_constants,
167
+ )
168
+
169
+ quant_params = qtyping.UniformQuantParams(
170
+ scale=scale,
171
+ zero_point=zp,
172
+ num_bits=tensor_quant_config.num_bits,
173
+ symmetric=tensor_quant_config.symmetric,
174
+ quantized_dimension=quantized_dim,
175
+ block_size=uniform_quantize_tensor.extract_block_size_from_granularity(
176
+ tensor_quant_config.granularity
177
+ ),
178
+ )
179
+
180
+ quantized_vars = uniform_quantize_tensor.uniform_quantize(
181
+ tensor_content,
182
+ quant_params,
183
+ is_blockwise_quant=uniform_quantize_tensor.is_blockwise(
184
+ tensor_quant_config.granularity
185
+ ),
186
+ )
187
+
188
+ return dataclasses.replace(quant_params, quantized_data=quantized_vars)
@@ -0,0 +1,240 @@
1
+ # Copyright 2024 The AI Edge Quantizer Authors.
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 os
17
+ from typing import cast
18
+
19
+ from absl.testing import parameterized
20
+ import numpy as np
21
+
22
+ from tensorflow.python.platform import googletest
23
+ from ai_edge_quantizer import qtyping
24
+ from ai_edge_quantizer.algorithms.uniform_quantize import octav
25
+ from ai_edge_quantizer.utils import test_utils
26
+ from ai_edge_quantizer.utils import tfl_flatbuffer_utils
27
+
28
+
29
+ class OctavQuantizeTest(parameterized.TestCase):
30
+ """Tests for general functions for OCTAV."""
31
+
32
+ def setUp(self):
33
+ super().setUp()
34
+ np.random.seed(666)
35
+ self._test_model_path = os.path.join(
36
+ test_utils.get_path_to_datafile("../../tests/models"),
37
+ "conv_fc_mnist.tflite",
38
+ )
39
+ self._test_model = tfl_flatbuffer_utils.read_model(self._test_model_path)
40
+ # The test model has one subgraph for now.
41
+ self._graph_info = qtyping.GraphInfo(
42
+ subgraph_tensors=self._test_model.subgraphs[0].tensors,
43
+ buffers=self._test_model.buffers,
44
+ )
45
+ self._tensor_name_to_qsv = {}
46
+ subgraph0 = self._test_model.subgraphs[0]
47
+ self._subgraph_op_index = 3
48
+ self._fc_op = subgraph0.operators[self._subgraph_op_index]
49
+ self._fc_op_info = qtyping.OpInfo(
50
+ op=self._fc_op,
51
+ op_name=qtyping.TFLOperationName.FULLY_CONNECTED,
52
+ subgraph_op_index=self._subgraph_op_index,
53
+ op_quant_config=qtyping.OpQuantizationConfig(
54
+ weight_tensor_config=None,
55
+ ),
56
+ )
57
+
58
+ def test_get_tensor_quant_params_unsupported_symmetry(self):
59
+ err_msg = "Unsupported symmetry"
60
+ test_data = np.array([[-7, 7], [4, -4], [4, -4], [7, 7]])
61
+ with self.assertRaisesWithPredicateMatch(
62
+ ValueError, lambda err: err_msg in str(err)
63
+ ):
64
+ _ = octav.get_tensor_quant_params(
65
+ op_info=self._fc_op_info,
66
+ tensor_quant_config=qtyping.TensorQuantizationConfig(
67
+ num_bits=4,
68
+ symmetric=False,
69
+ granularity=qtyping.QuantGranularity.CHANNELWISE,
70
+ ),
71
+ tensor_content=test_data,
72
+ )
73
+
74
+ def test_get_tensor_quant_params_success_with_qsv(self):
75
+ # Fall back to naive_min_max_quantize.py for non-weight tensors.
76
+ tensor_quant_params = octav.get_tensor_quant_params(
77
+ op_info=self._fc_op_info,
78
+ tensor_quant_config=qtyping.TensorQuantizationConfig(
79
+ num_bits=8,
80
+ granularity=qtyping.QuantGranularity.TENSORWISE,
81
+ ),
82
+ tensor_qsv={
83
+ "min": np.array([-1]),
84
+ "max": np.array([1]),
85
+ },
86
+ )
87
+
88
+ self.assertIsNone(tensor_quant_params.quantized_dimension)
89
+ scale = tensor_quant_params.scale
90
+ self.assertEqual(scale.shape, (1,))
91
+ self.assertSequenceAlmostEqual(scale.flatten(), [1 / 127])
92
+
93
+ # Zero point should be zero for symmetric quantization.
94
+ zp = tensor_quant_params.zero_point
95
+ self.assertEqual(np.sum(zp), 0)
96
+ self.assertEqual(zp.shape, (1,))
97
+
98
+ def test_get_tensor_quant_params_sanity_tensorwise(self):
99
+ test_data = np.array([
100
+ [-1e5, 25, -50, 75, -100, 125],
101
+ [25, -30, 50, -75, 1e5, -125],
102
+ [50, -60, 70, -80, 90, -100],
103
+ ])
104
+ tensor_config = qtyping.TensorQuantizationConfig(
105
+ num_bits=4,
106
+ symmetric=True,
107
+ granularity=qtyping.QuantGranularity.TENSORWISE,
108
+ )
109
+ fc_op_info = qtyping.OpInfo(
110
+ op=self._fc_op,
111
+ op_name=qtyping.TFLOperationName.FULLY_CONNECTED,
112
+ subgraph_op_index=self._subgraph_op_index,
113
+ op_quant_config=qtyping.OpQuantizationConfig(
114
+ weight_tensor_config=tensor_config,
115
+ ),
116
+ )
117
+ quant_params = octav.get_tensor_quant_params(
118
+ op_info=fc_op_info,
119
+ tensor_quant_config=tensor_config,
120
+ tensor_content=test_data,
121
+ )
122
+ adjusted_test_data = quant_params.quantized_data * quant_params.scale
123
+ real_max = np.max(np.abs(test_data))
124
+ adjusted_max = np.max(np.abs(adjusted_test_data))
125
+
126
+ # Check that some clipping occurred.
127
+ with self.subTest(name="CheckClipping"):
128
+ self.assertLess(adjusted_max, real_max)
129
+
130
+ with self.subTest(name="CheckQuantParamsShapes"):
131
+ self.assertEqual(quant_params.zero_point.shape, (1, 1))
132
+ self.assertEqual(quant_params.scale.shape, (1, 1))
133
+ self.assertIsNone(quant_params.quantized_dimension)
134
+ self.assertIsNotNone(quant_params.quantized_data)
135
+ self.assertTupleEqual(
136
+ cast(np.ndarray, quant_params.quantized_data).shape, test_data.shape
137
+ )
138
+
139
+ with self.subTest(name="CheckQuantParamsValues"):
140
+ self.assertTrue(np.all(quant_params.zero_point == 0))
141
+
142
+ def test_get_tensor_quant_params_sanity_channelwise(self):
143
+ # Test that the call generates quant params that are appropriately shaped,
144
+ # have some clipping, and correct config values without checking the
145
+ # actual values numerically.
146
+ test_data = np.array([
147
+ [-1e5, 25, -50, 75, -100, 125],
148
+ [25, -30, 50, -75, 1e5, -125],
149
+ [50, -60, 70, -80, 90, -100],
150
+ ])
151
+ tensor_config = qtyping.TensorQuantizationConfig(
152
+ num_bits=4,
153
+ symmetric=True,
154
+ granularity=qtyping.QuantGranularity.CHANNELWISE,
155
+ )
156
+ fc_op_info = qtyping.OpInfo(
157
+ op=self._fc_op,
158
+ op_name=qtyping.TFLOperationName.FULLY_CONNECTED,
159
+ subgraph_op_index=self._subgraph_op_index,
160
+ op_quant_config=qtyping.OpQuantizationConfig(
161
+ weight_tensor_config=tensor_config,
162
+ ),
163
+ )
164
+ quant_params = octav.get_tensor_quant_params(
165
+ op_info=fc_op_info,
166
+ tensor_quant_config=tensor_config,
167
+ tensor_content=test_data,
168
+ )
169
+ # Dequantize output to compare with the original test data.
170
+ adjusted_test_data = quant_params.quantized_data * quant_params.scale
171
+
172
+ for i, row in enumerate(test_data):
173
+ real_max = np.max(np.abs(row))
174
+ adjusted_max = np.max(np.abs(adjusted_test_data[i]))
175
+ # Check that some clipping occurred.
176
+ with self.subTest(name="CheckClipping"):
177
+ self.assertLess(adjusted_max, real_max)
178
+
179
+ with self.subTest(name="CheckQuantParamsShapes"):
180
+ self.assertEqual(quant_params.zero_point.shape, (test_data.shape[0], 1))
181
+ self.assertEqual(quant_params.scale.shape, (test_data.shape[0], 1))
182
+ self.assertIsNotNone(quant_params.quantized_data)
183
+ self.assertTupleEqual(
184
+ cast(np.ndarray, quant_params.quantized_data).shape, test_data.shape
185
+ )
186
+
187
+ with self.subTest(name="CheckQuantParamsValues"):
188
+ self.assertTrue(np.all(quant_params.zero_point == 0))
189
+ self.assertEqual(quant_params.quantized_dimension, 0)
190
+
191
+ def test_get_tensor_quant_params_sanity_blockwise(self):
192
+ # Test that the call generates quant params that are appropriately shaped,
193
+ # have some clipping, and correct config values without checking the
194
+ # actual values numerically.
195
+ test_data = np.random.randint(0, 1024, size=(32, 128))
196
+ tensor_config = qtyping.TensorQuantizationConfig(
197
+ num_bits=4,
198
+ symmetric=True,
199
+ granularity=qtyping.QuantGranularity.BLOCKWISE_32,
200
+ )
201
+ fc_op_info = qtyping.OpInfo(
202
+ op=self._fc_op,
203
+ op_name=qtyping.TFLOperationName.FULLY_CONNECTED,
204
+ subgraph_op_index=self._subgraph_op_index,
205
+ op_quant_config=qtyping.OpQuantizationConfig(
206
+ weight_tensor_config=tensor_config,
207
+ ),
208
+ )
209
+ quant_params = octav.get_tensor_quant_params(
210
+ op_info=fc_op_info,
211
+ tensor_quant_config=tensor_config,
212
+ tensor_content=test_data,
213
+ )
214
+
215
+ with self.subTest(name="CheckQuantParamsShapes"):
216
+ # Check that quant params have appropriate shapes.
217
+ self.assertEqual(quant_params.zero_point.shape, (32, 4))
218
+ self.assertEqual(quant_params.scale.shape, (32, 4))
219
+ self.assertIsNotNone(quant_params.quantized_data)
220
+ self.assertTupleEqual(
221
+ cast(np.ndarray, quant_params.quantized_data).shape, test_data.shape
222
+ )
223
+
224
+ scales = np.repeat(quant_params.scale, 32, axis=1)
225
+ adjusted_test_data = quant_params.quantized_data * scales
226
+ for i, row in enumerate(test_data):
227
+ real_max = np.max(np.abs(row))
228
+ adjusted_max = np.max(np.abs(adjusted_test_data[i]))
229
+ # Check that some clipping occurred.
230
+ with self.subTest(name="CheckClipping"):
231
+ self.assertLess(adjusted_max, real_max)
232
+
233
+ with self.subTest(name="CheckQuantParamsValues"):
234
+ self.assertTrue(np.all(quant_params.zero_point == 0))
235
+ # See TFL_OP_TO_BLOCKWISE_WEIGHT_QUANTIZED_DIM.
236
+ self.assertEqual(quant_params.quantized_dimension, 1)
237
+
238
+
239
+ if __name__ == "__main__":
240
+ googletest.main()