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,440 @@
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
+ """Test Hadamard rotation materialization."""
17
+
18
+ import os
19
+
20
+ from absl.testing import parameterized
21
+ import numpy as np
22
+
23
+ from tensorflow.python.platform import googletest
24
+ from ai_edge_quantizer import qtyping
25
+ from ai_edge_quantizer.algorithms.uniform_quantize import hadamard_rotation
26
+ from ai_edge_quantizer.utils import test_utils
27
+ from ai_edge_quantizer.utils import tfl_flatbuffer_utils
28
+
29
+ _TEST_DATA_PREFIX_PATH = test_utils.get_path_to_datafile("../../tests/models")
30
+ _TFLOpName = qtyping.TFLOperationName
31
+ _TensorQuantConfig = qtyping.TensorQuantizationConfig
32
+
33
+
34
+ class HadamardRotationFullyConnectedTest(parameterized.TestCase):
35
+
36
+ def setUp(self):
37
+ super().setUp()
38
+ np.random.seed(888)
39
+ self._test_model_path = os.path.join(
40
+ _TEST_DATA_PREFIX_PATH, "conv_fc_mnist.tflite"
41
+ )
42
+ self._test_model = tfl_flatbuffer_utils.read_model(self._test_model_path)
43
+ self._graph_info = qtyping.GraphInfo(
44
+ subgraph_tensors=self._test_model.subgraphs[0].tensors,
45
+ buffers=self._test_model.buffers,
46
+ )
47
+ self._tensor_name_to_qsv = None
48
+ self._subgraph = self._test_model.subgraphs[0]
49
+ self._fc_subgraph_op_index = 3
50
+ self._fc_op = self._subgraph.operators[self._fc_subgraph_op_index]
51
+ self._fc_buffer_id = self._subgraph.tensors[self._fc_op.inputs[1]].buffer
52
+ self._op_info = qtyping.OpInfo(
53
+ op=self._fc_op,
54
+ op_name=_TFLOpName.FULLY_CONNECTED,
55
+ subgraph_op_index=self._fc_subgraph_op_index,
56
+ op_quant_config=qtyping.OpQuantizationConfig(
57
+ weight_tensor_config=_TensorQuantConfig(
58
+ num_bits=8,
59
+ symmetric=True,
60
+ granularity=qtyping.QuantGranularity.CHANNELWISE,
61
+ ),
62
+ ),
63
+ )
64
+
65
+ def test_materialize_fully_connected_basic(self):
66
+ params = hadamard_rotation.materialize_fully_connected_custom_op(
67
+ self._op_info, self._graph_info, self._tensor_name_to_qsv
68
+ )
69
+ fc_input = params[0]
70
+ weight = params[1]
71
+ bias = params[2]
72
+ output = params[3]
73
+
74
+ self.assertLen(params, 4)
75
+ self.assertIsNone(fc_input.producer)
76
+ self.assertIsNotNone(fc_input.consumers)
77
+ self.assertIsNone(weight.producer)
78
+ self.assertIsNotNone(weight.consumers)
79
+ self.assertIsNone(bias.producer)
80
+ self.assertIsNotNone(bias.consumers)
81
+ self.assertIsNotNone(output.producer)
82
+ self.assertIsNone(output.consumers)
83
+ self.assertEqual(
84
+ fc_input.consumers[0].transformations,
85
+ [qtyping.QuantTransformation.INSERT_HADAMARD_ROTATION],
86
+ )
87
+ self.assertEqual(
88
+ weight.consumers[0].transformations,
89
+ [qtyping.QuantTransformation.QUANTIZE_TENSOR],
90
+ )
91
+ self.assertEqual(
92
+ bias.consumers[0].transformations,
93
+ [qtyping.QuantTransformation.NO_QUANTIZE],
94
+ )
95
+ if output.producer is not None:
96
+ self.assertEqual(
97
+ output.producer.transformations,
98
+ [qtyping.QuantTransformation.NO_QUANTIZE],
99
+ )
100
+
101
+ def test_fully_connected_tensorwise_supported(self):
102
+ self._op_info = qtyping.OpInfo(
103
+ op=self._fc_op,
104
+ op_name=_TFLOpName.FULLY_CONNECTED,
105
+ subgraph_op_index=self._fc_subgraph_op_index,
106
+ op_quant_config=qtyping.OpQuantizationConfig(
107
+ weight_tensor_config=_TensorQuantConfig(
108
+ num_bits=8,
109
+ symmetric=True,
110
+ granularity=qtyping.QuantGranularity.TENSORWISE,
111
+ ),
112
+ ),
113
+ )
114
+ params = hadamard_rotation.materialize_fully_connected_custom_op(
115
+ self._op_info, self._graph_info, self._tensor_name_to_qsv
116
+ )
117
+ self.assertLen(params, 4)
118
+ fc_input = params[0]
119
+ self.assertIsNotNone(fc_input)
120
+ self.assertIsNotNone(fc_input.consumers)
121
+ self.assertIsNotNone(fc_input.consumers[0].parameters)
122
+ self.assertIsInstance(
123
+ fc_input.consumers[0].parameters, qtyping.UniformQuantParams
124
+ )
125
+ if isinstance(
126
+ fc_input.consumers[0].parameters, qtyping.UniformQuantParams
127
+ ):
128
+ self.assertIsNone(fc_input.consumers[0].parameters.quantized_dimension)
129
+ weight = params[1]
130
+ self.assertIsNotNone(weight)
131
+ self.assertIsNotNone(weight.consumers)
132
+ self.assertIsNotNone(weight.consumers[0].parameters)
133
+ self.assertIsInstance(
134
+ weight.consumers[0].parameters, qtyping.UniformQuantParams
135
+ )
136
+ if isinstance(
137
+ weight.consumers[0].parameters, qtyping.UniformQuantParams
138
+ ):
139
+ self.assertIsNone(weight.consumers[0].parameters.quantized_dimension)
140
+
141
+ def test_fully_connected_blockwise_supported(self):
142
+ self._op_info = qtyping.OpInfo(
143
+ op=self._fc_op,
144
+ op_name=_TFLOpName.FULLY_CONNECTED,
145
+ subgraph_op_index=self._fc_subgraph_op_index,
146
+ op_quant_config=qtyping.OpQuantizationConfig(
147
+ weight_tensor_config=_TensorQuantConfig(
148
+ num_bits=8,
149
+ symmetric=True,
150
+ granularity=qtyping.QuantGranularity.BLOCKWISE_32,
151
+ ),
152
+ ),
153
+ )
154
+ params = hadamard_rotation.materialize_fully_connected_custom_op(
155
+ self._op_info, self._graph_info, self._tensor_name_to_qsv
156
+ )
157
+ self.assertLen(params, 4)
158
+ fc_input = params[0]
159
+ self.assertIsNotNone(fc_input)
160
+ self.assertIsNotNone(fc_input.consumers)
161
+ self.assertIsNotNone(fc_input.consumers[0].parameters)
162
+ self.assertIsInstance(
163
+ fc_input.consumers[0].parameters, qtyping.UniformQuantParams
164
+ )
165
+ if isinstance(
166
+ fc_input.consumers[0].parameters, qtyping.UniformQuantParams
167
+ ):
168
+ self.assertEqual(fc_input.consumers[0].parameters.quantized_dimension, 1)
169
+ weight = params[1]
170
+ self.assertIsNotNone(weight)
171
+ self.assertIsNotNone(weight.consumers)
172
+ self.assertIsNotNone(weight.consumers[0].parameters)
173
+ self.assertIsInstance(
174
+ weight.consumers[0].parameters, qtyping.UniformQuantParams
175
+ )
176
+ if isinstance(
177
+ weight.consumers[0].parameters, qtyping.UniformQuantParams
178
+ ):
179
+ self.assertEqual(weight.consumers[0].parameters.quantized_dimension, 1)
180
+
181
+ def test_materialize_fully_connected_decomposed(self):
182
+ params = hadamard_rotation.materialize_fully_connected_decomposed(
183
+ self._op_info, self._graph_info, self._tensor_name_to_qsv
184
+ )
185
+ fc_input = params[0]
186
+ weight = params[1]
187
+ bias = params[2]
188
+ output = params[3]
189
+
190
+ self.assertLen(params, 4)
191
+ self.assertEqual(
192
+ fc_input.consumers[0].transformations,
193
+ [qtyping.QuantTransformation.INSERT_DECOMPOSED_HADAMARD_ROTATION],
194
+ )
195
+ self.assertEqual(
196
+ weight.consumers[0].transformations,
197
+ [qtyping.QuantTransformation.QUANTIZE_TENSOR],
198
+ )
199
+ self.assertEqual(
200
+ bias.consumers[0].transformations,
201
+ [qtyping.QuantTransformation.NO_QUANTIZE],
202
+ )
203
+ if output.producer is not None:
204
+ self.assertEqual(
205
+ output.producer.transformations,
206
+ [qtyping.QuantTransformation.NO_QUANTIZE],
207
+ )
208
+
209
+ def test_get_tensor_quant_params_basic(self):
210
+ input_tensor = self._subgraph.tensors[self._fc_op.inputs[1]]
211
+ buffer = self._graph_info.buffers[self._fc_buffer_id]
212
+ np_buffer = np.frombuffer(buffer.data, dtype=np.float32).reshape(
213
+ input_tensor.shape
214
+ )
215
+ qparams = hadamard_rotation.get_tensor_quant_params(
216
+ self._op_info,
217
+ self._op_info.op_quant_config.weight_tensor_config,
218
+ np_buffer,
219
+ self._tensor_name_to_qsv,
220
+ )
221
+ self.assertEqual(qparams.num_bits, 8)
222
+ self.assertEqual(qparams.zero_point.all(), 0)
223
+ self.assertEqual(qparams.symmetric, True)
224
+ self.assertIsNotNone(qparams.quantized_data)
225
+ self.assertEqual(qparams.block_size, 0)
226
+ self.assertIsNotNone(qparams.hadamard)
227
+ if qparams.hadamard is not None:
228
+ self.assertEqual(qparams.hadamard.hadamard_size, 32)
229
+
230
+ def test_get_tensor_quant_params_golden_1(self):
231
+ test_data = np.ones((6, 6))
232
+ # expected:
233
+ # [[127 0 127 0 127 0]
234
+ # [127 0 127 0 127 0]
235
+ # [127 0 127 0 127 0]
236
+ # [127 0 127 0 127 0]
237
+ # [127 0 127 0 127 0]
238
+ # [127 0 127 0 127 0]]
239
+ expected = np.tile([127, 0], [6, 3])
240
+ qparams = hadamard_rotation.get_tensor_quant_params(
241
+ self._op_info,
242
+ self._op_info.op_quant_config.weight_tensor_config,
243
+ test_data,
244
+ self._tensor_name_to_qsv,
245
+ )
246
+ self.assertIsNotNone(qparams.quantized_data)
247
+ np.testing.assert_array_equal(
248
+ np.array(qparams.quantized_data), expected
249
+ )
250
+
251
+ def test_get_tensor_quant_params_golden_2(self):
252
+ # test_data:
253
+ # [[1 2 1 2 1 2]
254
+ # [3 4 3 4 3 4]
255
+ # [1 2 1 2 1 2]
256
+ # [3 4 3 4 3 4]
257
+ # [1 2 1 2 1 2]
258
+ # [3 4 3 4 3 4]]
259
+ test_data = np.tile([[1, 2], [3, 4]], [3, 3])
260
+ # expected:
261
+ # [[127 -42 127 -42 127 -42]
262
+ # [127 -18 127 -18 127 -18]
263
+ # [127 -42 127 -42 127 -42]
264
+ # [127 -18 127 -18 127 -18]
265
+ # [127 -42 127 -42 127 -42]
266
+ # [127 -18 127 -18 127 -18]]
267
+ expected = np.tile([[127, -42], [127, -18]], [3, 3])
268
+ qparams = hadamard_rotation.get_tensor_quant_params(
269
+ self._op_info,
270
+ self._op_info.op_quant_config.weight_tensor_config,
271
+ test_data,
272
+ self._tensor_name_to_qsv,
273
+ )
274
+ self.assertIsNotNone(qparams.quantized_data)
275
+ np.testing.assert_array_equal(
276
+ np.array(qparams.quantized_data), expected
277
+ )
278
+
279
+ def test_get_tensor_quant_params_golden_3(self):
280
+ # test_data:
281
+ # [[[1 2 1 2 1 2]
282
+ # [3 4 3 4 3 4]
283
+ # [1 2 1 2 1 2]]
284
+ # [[3 4 3 4 3 4]
285
+ # [1 2 1 2 1 2]
286
+ # [3 4 3 4 3 4]]]
287
+ test_data = np.tile([[1, 2], [3, 4]], [3, 3])
288
+ test_data = np.reshape(test_data, (2, 3, 6))
289
+ # expected:
290
+ # [[[ 54 -18 54 -18 54 -18]
291
+ # [127 -18 127 -18 127 -18]
292
+ # [ 54 -18 54 -18 54 -18]]
293
+ # [[127 -18 127 -18 127 -18]
294
+ # [ 54 -18 54 -18 54 -18]
295
+ # [127 -18 127 -18 127 -18]]]
296
+ expected = np.tile([[54, -18], [127, -18]], [3, 3])
297
+ expected = np.reshape(expected, (2, 3, 6))
298
+ qparams = hadamard_rotation.get_tensor_quant_params(
299
+ self._op_info,
300
+ self._op_info.op_quant_config.weight_tensor_config,
301
+ test_data,
302
+ self._tensor_name_to_qsv,
303
+ )
304
+ self.assertIsNotNone(qparams.quantized_data)
305
+ np.testing.assert_array_equal(
306
+ np.array(qparams.quantized_data), expected
307
+ )
308
+
309
+ def test_raise_missing_tensor_content(self):
310
+ with self.assertRaisesWithPredicateMatch(
311
+ ValueError, lambda err: "weight tensor" in str(err)
312
+ ):
313
+ hadamard_rotation.get_tensor_quant_params(
314
+ self._op_info,
315
+ self._op_info.op_quant_config.weight_tensor_config,
316
+ None,
317
+ self._tensor_name_to_qsv,
318
+ )
319
+
320
+ def test_raise_qsv_set(self):
321
+ with self.assertRaisesWithPredicateMatch(
322
+ ValueError, lambda err: "static quantization" in str(err)
323
+ ):
324
+ hadamard_rotation.get_tensor_quant_params(
325
+ self._op_info,
326
+ self._op_info.op_quant_config.weight_tensor_config,
327
+ self._graph_info.buffers[self._fc_buffer_id],
328
+ self._graph_info.buffers[self._fc_buffer_id],
329
+ )
330
+
331
+ def test_raise_1d_constant(self):
332
+ with self.assertRaisesWithPredicateMatch(
333
+ ValueError, lambda err: "rank >= 2" in str(err)
334
+ ):
335
+ hadamard_rotation.get_tensor_quant_params(
336
+ self._op_info,
337
+ self._op_info.op_quant_config.weight_tensor_config,
338
+ np.array([1.0, 2.0, 3.0]),
339
+ self._tensor_name_to_qsv,
340
+ )
341
+
342
+
343
+ class HadamardRotationEmbeddingLookupTest(parameterized.TestCase):
344
+
345
+ def setUp(self):
346
+ super().setUp()
347
+ np.random.seed(888)
348
+ self._test_model_path = os.path.join(
349
+ _TEST_DATA_PREFIX_PATH, "embedding_lookup.tflite"
350
+ )
351
+ self._test_model = tfl_flatbuffer_utils.read_model(self._test_model_path)
352
+ self._graph_info = qtyping.GraphInfo(
353
+ subgraph_tensors=self._test_model.subgraphs[0].tensors,
354
+ buffers=self._test_model.buffers,
355
+ )
356
+ self._tensor_name_to_qsv = None
357
+
358
+ def test_materialize_embedding_lookup_basic(self):
359
+ subgraph = self._test_model.subgraphs[0]
360
+ embedding_subgraph_op_index = 0
361
+ embedding_op = subgraph.operators[embedding_subgraph_op_index]
362
+ op_info = qtyping.OpInfo(
363
+ op=embedding_op,
364
+ op_name=_TFLOpName.EMBEDDING_LOOKUP,
365
+ subgraph_op_index=embedding_subgraph_op_index,
366
+ op_quant_config=qtyping.OpQuantizationConfig(
367
+ weight_tensor_config=_TensorQuantConfig(
368
+ num_bits=8,
369
+ symmetric=True,
370
+ granularity=qtyping.QuantGranularity.CHANNELWISE,
371
+ ),
372
+ ),
373
+ )
374
+ params = hadamard_rotation.materialize_embedding_lookup_custom_op(
375
+ op_info, self._graph_info, self._tensor_name_to_qsv
376
+ )
377
+ self.assertLen(params, 3)
378
+ lookup = params[0]
379
+ value = params[1]
380
+ output = params[2]
381
+ self.assertIsNone(lookup.producer)
382
+ self.assertIsNotNone(lookup.consumers)
383
+ self.assertIsNone(value.producer)
384
+ self.assertIsNotNone(value.consumers)
385
+ self.assertIsNotNone(output.producer)
386
+ self.assertIsNone(output.consumers)
387
+ self.assertEqual(
388
+ lookup.consumers[0].transformations,
389
+ [qtyping.QuantTransformation.NO_QUANTIZE],
390
+ )
391
+ self.assertEqual(
392
+ value.consumers[0].transformations,
393
+ [qtyping.QuantTransformation.QUANTIZE_TENSOR],
394
+ )
395
+ if output.producer is not None:
396
+ self.assertEqual(
397
+ output.producer.transformations,
398
+ [qtyping.QuantTransformation.INSERT_HADAMARD_ROTATION],
399
+ )
400
+
401
+ def test_materialize_embedding_lookup_decomposed(self):
402
+ subgraph = self._test_model.subgraphs[0]
403
+ embedding_subgraph_op_index = 0
404
+ embedding_op = subgraph.operators[embedding_subgraph_op_index]
405
+ op_info = qtyping.OpInfo(
406
+ op=embedding_op,
407
+ op_name=_TFLOpName.EMBEDDING_LOOKUP,
408
+ subgraph_op_index=embedding_subgraph_op_index,
409
+ op_quant_config=qtyping.OpQuantizationConfig(
410
+ weight_tensor_config=_TensorQuantConfig(
411
+ num_bits=8,
412
+ symmetric=True,
413
+ granularity=qtyping.QuantGranularity.CHANNELWISE,
414
+ ),
415
+ ),
416
+ )
417
+ params = hadamard_rotation.materialize_embedding_lookup_decomposed(
418
+ op_info, self._graph_info, self._tensor_name_to_qsv
419
+ )
420
+ self.assertLen(params, 3)
421
+ lookup = params[0]
422
+ value = params[1]
423
+ output = params[2]
424
+ self.assertEqual(
425
+ lookup.consumers[0].transformations,
426
+ [qtyping.QuantTransformation.NO_QUANTIZE],
427
+ )
428
+ self.assertEqual(
429
+ value.consumers[0].transformations,
430
+ [qtyping.QuantTransformation.QUANTIZE_TENSOR],
431
+ )
432
+ if output.producer is not None:
433
+ self.assertEqual(
434
+ output.producer.transformations,
435
+ [qtyping.QuantTransformation.INSERT_DECOMPOSED_HADAMARD_ROTATION],
436
+ )
437
+
438
+
439
+ if __name__ == "__main__":
440
+ googletest.main()
@@ -0,0 +1,127 @@
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 MSE quantization."""
17
+
18
+ import dataclasses
19
+ from typing import Any, Optional
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 = "MSE"
28
+
29
+ # Coefficients from offline numeric analysis.
30
+ _MSE_QUANT_MULS = {
31
+ 8: 0.05408,
32
+ 4: 0.37755,
33
+ }
34
+
35
+
36
+ def get_tensor_quant_params(
37
+ op_info: qtyping.OpInfo,
38
+ tensor_quant_config: qtyping.TensorQuantizationConfig,
39
+ tensor_content: Optional[np.ndarray] = None,
40
+ tensor_qsv: Optional[dict[str, Any]] = None,
41
+ ) -> qtyping.UniformQuantParams:
42
+ """Returns the quantization parameters for a tensor.
43
+
44
+ Args:
45
+ op_info: Aggregated information about the op (e.g., quantization config).
46
+ tensor_quant_config: The quantization config for the tensor.
47
+ tensor_content: The content of the tensor. When None, it means the tensor is
48
+ not a weight tensor (e.g. static quantization) so we fallback to using
49
+ naive_min_max_quantize.
50
+ tensor_qsv: A dictionary containing the min/max of the tensor.
51
+
52
+ Raises:
53
+ ValueError: If the blockwise quantization is requested.
54
+ ValueError: If the asymmetric quantization is requested.
55
+ ValueError: `tensor_qsv` must contain min/max values, or `tensor_content`
56
+ must be provided so that they can be inferred.
57
+ """
58
+ if uniform_quantize_tensor.is_blockwise(tensor_quant_config.granularity):
59
+ raise ValueError(
60
+ "Blockwise quantization is not supported for MSE quantization."
61
+ )
62
+
63
+ # Fallback to naive_min_max_quantize.py for non-weight tensors.
64
+ if tensor_content is None:
65
+ return naive_min_max_quantize.get_tensor_quant_params(
66
+ op_info, tensor_quant_config, tensor_content, tensor_qsv
67
+ )
68
+
69
+ if not tensor_quant_config.symmetric:
70
+ raise ValueError(
71
+ f"Unsupported symmetry: {tensor_quant_config.symmetric}. MSE"
72
+ " supports symmetric quantization only for now."
73
+ )
74
+
75
+ if not tensor_qsv:
76
+ # We need min/max to calculate quantization parameters, which
77
+ # should be collected during the calibration process. However,
78
+ # weight-only and DRQ do not require calibration, thus it is
79
+ # possible that this information is missing here. In that case we
80
+ # collect min/max on the spot.
81
+ tensor_min_max = common_quantize.init_tensor_min_max(
82
+ tensor_content,
83
+ op_info,
84
+ )
85
+ else:
86
+ tensor_min_max = tensor_qsv
87
+
88
+ if "min" not in tensor_min_max or "max" not in tensor_min_max:
89
+ raise ValueError(
90
+ "min and max must be provided to produce tensor quantization"
91
+ " parameters. Check if the correct calibration results are passed into"
92
+ " the ParamsGenerator."
93
+ )
94
+
95
+ quantized_dim = common_utils.get_weight_quantized_dim(
96
+ op_info, tensor_content, tensor_quant_config.granularity
97
+ )
98
+
99
+ reshaped_data = tensor_content
100
+ reduce_dims = common_utils.get_reduce_dims(
101
+ quantized_dim, tensor_content.shape
102
+ )
103
+
104
+ multiplier = _MSE_QUANT_MULS[tensor_quant_config.num_bits]
105
+ scale = multiplier * np.sqrt(
106
+ np.mean(reshaped_data**2, axis=reduce_dims, keepdims=True)
107
+ )
108
+ zp = np.zeros_like(scale, dtype=np.int32)
109
+
110
+ quant_params = qtyping.UniformQuantParams(
111
+ scale=scale,
112
+ zero_point=zp,
113
+ num_bits=tensor_quant_config.num_bits,
114
+ symmetric=tensor_quant_config.symmetric,
115
+ quantized_dimension=quantized_dim,
116
+ block_size=uniform_quantize_tensor.extract_block_size_from_granularity(
117
+ tensor_quant_config.granularity
118
+ ),
119
+ )
120
+
121
+ quantized_vars = uniform_quantize_tensor.uniform_quantize(
122
+ tensor_content,
123
+ quant_params,
124
+ uniform_quantize_tensor.is_blockwise(tensor_quant_config.granularity),
125
+ )
126
+
127
+ return dataclasses.replace(quant_params, quantized_data=quantized_vars)