ai-edge-quantizer-nightly 0.0.1.dev20250115__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 (63) hide show
  1. ai_edge_quantizer/__init__.py +19 -0
  2. ai_edge_quantizer/algorithm_manager.py +167 -0
  3. ai_edge_quantizer/algorithm_manager_api.py +271 -0
  4. ai_edge_quantizer/algorithm_manager_api_test.py +210 -0
  5. ai_edge_quantizer/algorithms/__init__.py +15 -0
  6. ai_edge_quantizer/algorithms/nonlinear_quantize/__init__.py +15 -0
  7. ai_edge_quantizer/algorithms/nonlinear_quantize/float_casting.py +273 -0
  8. ai_edge_quantizer/algorithms/nonlinear_quantize/float_casting_test.py +664 -0
  9. ai_edge_quantizer/algorithms/uniform_quantize/__init__.py +15 -0
  10. ai_edge_quantizer/algorithms/uniform_quantize/naive_min_max_quantize.py +666 -0
  11. ai_edge_quantizer/algorithms/uniform_quantize/naive_min_max_quantize_test.py +184 -0
  12. ai_edge_quantizer/algorithms/uniform_quantize/uniform_quantize_tensor.py +371 -0
  13. ai_edge_quantizer/algorithms/uniform_quantize/uniform_quantize_tensor_test.py +357 -0
  14. ai_edge_quantizer/algorithms/utils/__init__.py +15 -0
  15. ai_edge_quantizer/algorithms/utils/min_max_quantize_utils.py +1067 -0
  16. ai_edge_quantizer/algorithms/utils/min_max_quantize_utils_test.py +512 -0
  17. ai_edge_quantizer/calibrator.py +288 -0
  18. ai_edge_quantizer/calibrator_test.py +297 -0
  19. ai_edge_quantizer/conftest.py +22 -0
  20. ai_edge_quantizer/default_policy.py +310 -0
  21. ai_edge_quantizer/model_modifier.py +176 -0
  22. ai_edge_quantizer/model_modifier_test.py +130 -0
  23. ai_edge_quantizer/model_validator.py +357 -0
  24. ai_edge_quantizer/model_validator_test.py +354 -0
  25. ai_edge_quantizer/params_generator.py +361 -0
  26. ai_edge_quantizer/params_generator_test.py +1041 -0
  27. ai_edge_quantizer/qtyping.py +483 -0
  28. ai_edge_quantizer/quantizer.py +372 -0
  29. ai_edge_quantizer/quantizer_test.py +532 -0
  30. ai_edge_quantizer/recipe.py +67 -0
  31. ai_edge_quantizer/recipe_manager.py +245 -0
  32. ai_edge_quantizer/recipe_manager_test.py +815 -0
  33. ai_edge_quantizer/recipe_test.py +97 -0
  34. ai_edge_quantizer/transformation_instruction_generator.py +584 -0
  35. ai_edge_quantizer/transformation_instruction_generator_test.py +1082 -0
  36. ai_edge_quantizer/transformation_performer.py +278 -0
  37. ai_edge_quantizer/transformation_performer_test.py +344 -0
  38. ai_edge_quantizer/transformations/__init__.py +15 -0
  39. ai_edge_quantizer/transformations/dequant_insert.py +87 -0
  40. ai_edge_quantizer/transformations/dequant_insert_test.py +304 -0
  41. ai_edge_quantizer/transformations/emulated_subchannel.py +363 -0
  42. ai_edge_quantizer/transformations/emulated_subchannel_test.py +212 -0
  43. ai_edge_quantizer/transformations/quant_insert.py +100 -0
  44. ai_edge_quantizer/transformations/quant_insert_test.py +284 -0
  45. ai_edge_quantizer/transformations/quantize_tensor.py +156 -0
  46. ai_edge_quantizer/transformations/quantize_tensor_test.py +227 -0
  47. ai_edge_quantizer/transformations/transformation_utils.py +132 -0
  48. ai_edge_quantizer/transformations/transformation_utils_test.py +162 -0
  49. ai_edge_quantizer/utils/__init__.py +15 -0
  50. ai_edge_quantizer/utils/calibration_utils.py +86 -0
  51. ai_edge_quantizer/utils/calibration_utils_test.py +77 -0
  52. ai_edge_quantizer/utils/test_utils.py +107 -0
  53. ai_edge_quantizer/utils/tfl_flatbuffer_utils.py +317 -0
  54. ai_edge_quantizer/utils/tfl_flatbuffer_utils_test.py +200 -0
  55. ai_edge_quantizer/utils/tfl_interpreter_utils.py +312 -0
  56. ai_edge_quantizer/utils/tfl_interpreter_utils_test.py +332 -0
  57. ai_edge_quantizer/utils/validation_utils.py +125 -0
  58. ai_edge_quantizer/utils/validation_utils_test.py +87 -0
  59. ai_edge_quantizer_nightly-0.0.1.dev20250115.dist-info/LICENSE +201 -0
  60. ai_edge_quantizer_nightly-0.0.1.dev20250115.dist-info/METADATA +32 -0
  61. ai_edge_quantizer_nightly-0.0.1.dev20250115.dist-info/RECORD +63 -0
  62. ai_edge_quantizer_nightly-0.0.1.dev20250115.dist-info/WHEEL +5 -0
  63. ai_edge_quantizer_nightly-0.0.1.dev20250115.dist-info/top_level.txt +1 -0
@@ -0,0 +1,664 @@
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 absl.testing import parameterized
18
+ import numpy as np
19
+ from tensorflow.python.platform import googletest
20
+ from ai_edge_quantizer import qtyping
21
+ from ai_edge_quantizer.algorithms.nonlinear_quantize import float_casting
22
+ from ai_edge_quantizer.utils import test_utils
23
+ from ai_edge_quantizer.utils import tfl_flatbuffer_utils
24
+
25
+ _TEST_DATA_PREFIX_PATH = test_utils.get_path_to_datafile("../../tests/models")
26
+ _TFLOpName = qtyping.TFLOperationName
27
+ _ComputePrecision = qtyping.ComputePrecision
28
+ _TensorQuantConfig = qtyping.TensorQuantizationConfig
29
+ _QuantTransformation = qtyping.QuantTransformation
30
+
31
+
32
+ class Fp16QuantizeTest(parameterized.TestCase):
33
+
34
+ def setUp(self):
35
+ super().setUp()
36
+ np.random.seed(666)
37
+ self._test_model_path = os.path.join(
38
+ _TEST_DATA_PREFIX_PATH, "conv_fc_mnist.tflite"
39
+ )
40
+ self._test_model = tfl_flatbuffer_utils.read_model(self._test_model_path)
41
+ # The test model has one subgraph for now.
42
+ self._graph_info = qtyping.GraphInfo(
43
+ subgraph_tensors=self._test_model.subgraphs[0].tensors,
44
+ buffers=self._test_model.buffers,
45
+ )
46
+ self._tensor_name_to_qsv = {}
47
+
48
+ @parameterized.named_parameters(
49
+ dict(
50
+ testcase_name="fc",
51
+ op_name=_TFLOpName.FULLY_CONNECTED,
52
+ ),
53
+ dict(
54
+ testcase_name="conv2d",
55
+ op_name=_TFLOpName.CONV_2D,
56
+ ),
57
+ dict(
58
+ testcase_name="embedding_lookup",
59
+ op_name=_TFLOpName.EMBEDDING_LOOKUP,
60
+ ),
61
+ )
62
+ def test_check_op_quantization_config_succeeds(self, op_name):
63
+ float_casting.check_op_quantization_config(
64
+ op_name,
65
+ qtyping.OpQuantizationConfig(
66
+ weight_tensor_config=_TensorQuantConfig(
67
+ num_bits=16, dtype=qtyping.TensorDataType.FLOAT
68
+ ),
69
+ compute_precision=_ComputePrecision.FLOAT, # WEIGHT_ONLY.
70
+ explicit_dequantize=True,
71
+ ),
72
+ )
73
+
74
+ @parameterized.named_parameters(
75
+ dict(
76
+ testcase_name="invalid_fc",
77
+ op_name=_TFLOpName.FULLY_CONNECTED,
78
+ ),
79
+ dict(
80
+ testcase_name="invalid_conv2d",
81
+ op_name=_TFLOpName.CONV_2D,
82
+ ),
83
+ dict(
84
+ testcase_name="invalid_embedding_lookup",
85
+ op_name=_TFLOpName.EMBEDDING_LOOKUP,
86
+ ),
87
+ )
88
+ def test_check_op_quantization_config_invalid_activation_tensor_config_raises_exception(
89
+ self, op_name
90
+ ):
91
+ # With activation tensor config.
92
+ error_message = (
93
+ "Activation tensor quantization is not supported for float casting"
94
+ " quantization."
95
+ )
96
+ with self.assertRaisesWithPredicateMatch(
97
+ ValueError, lambda err: error_message in str(err)
98
+ ):
99
+ float_casting.check_op_quantization_config(
100
+ op_name,
101
+ qtyping.OpQuantizationConfig(
102
+ activation_tensor_config=_TensorQuantConfig(
103
+ num_bits=16, dtype=qtyping.TensorDataType.FLOAT
104
+ ),
105
+ weight_tensor_config=_TensorQuantConfig(
106
+ num_bits=16, dtype=qtyping.TensorDataType.FLOAT
107
+ ),
108
+ compute_precision=_ComputePrecision.FLOAT, # WEIGHT_ONLY.
109
+ explicit_dequantize=True,
110
+ ),
111
+ )
112
+
113
+ @parameterized.named_parameters(
114
+ dict(
115
+ testcase_name="invalid_fc",
116
+ op_name=_TFLOpName.FULLY_CONNECTED,
117
+ ),
118
+ dict(
119
+ testcase_name="invalid_conv2d",
120
+ op_name=_TFLOpName.CONV_2D,
121
+ ),
122
+ dict(
123
+ testcase_name="invalid_embedding_lookup",
124
+ op_name=_TFLOpName.EMBEDDING_LOOKUP,
125
+ ),
126
+ )
127
+ def test_check_op_quantization_config_invalid_bit_width_raises_exception(
128
+ self, op_name
129
+ ):
130
+ error_message = (
131
+ "float casting quantization config requires number of bits to be set as"
132
+ " 16, dtype as float"
133
+ )
134
+ # Wrong bit width.
135
+ with self.assertRaisesWithPredicateMatch(
136
+ ValueError, lambda err: error_message in str(err)
137
+ ):
138
+ float_casting.check_op_quantization_config(
139
+ op_name,
140
+ qtyping.OpQuantizationConfig(
141
+ activation_tensor_config=None,
142
+ weight_tensor_config=_TensorQuantConfig(
143
+ num_bits=8, dtype=qtyping.TensorDataType.FLOAT
144
+ ),
145
+ compute_precision=_ComputePrecision.FLOAT, # WEIGHT_ONLY.
146
+ explicit_dequantize=True,
147
+ ),
148
+ )
149
+
150
+ @parameterized.named_parameters(
151
+ dict(
152
+ testcase_name="invalid_fc",
153
+ op_name=_TFLOpName.FULLY_CONNECTED,
154
+ ),
155
+ dict(
156
+ testcase_name="invalid_conv2d",
157
+ op_name=_TFLOpName.CONV_2D,
158
+ ),
159
+ dict(
160
+ testcase_name="invalid_embedding_lookup",
161
+ op_name=_TFLOpName.EMBEDDING_LOOKUP,
162
+ ),
163
+ )
164
+ def test_check_op_quantization_config_invalid_dtype_raises_exception(
165
+ self, op_name
166
+ ):
167
+ error_message = (
168
+ "float casting quantization config requires number of bits to be set as"
169
+ " 16, dtype as float"
170
+ )
171
+ # Wrong dtype.
172
+ with self.assertRaisesWithPredicateMatch(
173
+ ValueError, lambda err: error_message in str(err)
174
+ ):
175
+ float_casting.check_op_quantization_config(
176
+ op_name,
177
+ qtyping.OpQuantizationConfig(
178
+ activation_tensor_config=None,
179
+ weight_tensor_config=_TensorQuantConfig(
180
+ num_bits=16, dtype=qtyping.TensorDataType.INT
181
+ ),
182
+ compute_precision=_ComputePrecision.FLOAT, # WEIGHT_ONLY.
183
+ explicit_dequantize=True,
184
+ ),
185
+ )
186
+
187
+ @parameterized.named_parameters(
188
+ dict(
189
+ testcase_name="invalid_fc",
190
+ op_name=_TFLOpName.FULLY_CONNECTED,
191
+ ),
192
+ dict(
193
+ testcase_name="invalid_conv2d",
194
+ op_name=_TFLOpName.CONV_2D,
195
+ ),
196
+ dict(
197
+ testcase_name="invalid_embedding_lookup",
198
+ op_name=_TFLOpName.EMBEDDING_LOOKUP,
199
+ ),
200
+ )
201
+ def test_check_op_quantization_config_no_weight_config_raises_exception(
202
+ self, op_name
203
+ ):
204
+ error_message = (
205
+ "Weight tensor quantization config is required for float casting"
206
+ " quantization."
207
+ )
208
+ # No weight quantization config.
209
+ with self.assertRaisesWithPredicateMatch(
210
+ ValueError, lambda err: error_message in str(err)
211
+ ):
212
+ float_casting.check_op_quantization_config(
213
+ op_name,
214
+ qtyping.OpQuantizationConfig(
215
+ activation_tensor_config=None,
216
+ compute_precision=_ComputePrecision.FLOAT, # WEIGHT_ONLY.
217
+ explicit_dequantize=True,
218
+ ),
219
+ )
220
+
221
+ @parameterized.named_parameters(
222
+ dict(
223
+ testcase_name="averagepool2D",
224
+ op_name=_TFLOpName.AVERAGE_POOL_2D,
225
+ ),
226
+ dict(
227
+ testcase_name="reshape",
228
+ op_name=_TFLOpName.RESHAPE,
229
+ ),
230
+ )
231
+ def test_check_op_quantization_config_invalid_ops_raises_exception(
232
+ self, op_name
233
+ ):
234
+ error_message = "Unsupported op"
235
+ with self.assertRaisesWithPredicateMatch(
236
+ ValueError, lambda err: error_message in str(err)
237
+ ):
238
+ float_casting.check_op_quantization_config(
239
+ op_name=op_name,
240
+ op_quant_config=qtyping.OpQuantizationConfig(
241
+ activation_tensor_config=None,
242
+ weight_tensor_config=_TensorQuantConfig(
243
+ num_bits=16, dtype=qtyping.TensorDataType.FLOAT
244
+ ),
245
+ compute_precision=_ComputePrecision.FLOAT, # WEIGHT_ONLY.
246
+ explicit_dequantize=True,
247
+ ),
248
+ )
249
+
250
+ @parameterized.named_parameters(
251
+ dict(
252
+ testcase_name="fc_with_bias",
253
+ subgraph_op_id=3,
254
+ op_tensor_names={
255
+ "weight": "arith.constant1",
256
+ "bias": "arith.constant2",
257
+ "input": "sequential/flatten/Reshape",
258
+ "output": "sequential/dense/MatMul;sequential/dense/Relu;sequential/dense/BiasAdd",
259
+ },
260
+ ),
261
+ dict(
262
+ testcase_name="fc_with_no_bias",
263
+ subgraph_op_id=4,
264
+ op_tensor_names={
265
+ "weight": "arith.constant",
266
+ "input": "sequential/dense/MatMul;sequential/dense/Relu;sequential/dense/BiasAdd",
267
+ "output": "sequential/dense_1/MatMul",
268
+ },
269
+ ),
270
+ )
271
+ def test_fully_connected_weight_only_succeeds(
272
+ self, subgraph_op_id, op_tensor_names
273
+ ):
274
+ subgraph0 = self._test_model.subgraphs[0]
275
+ fc_op = subgraph0.operators[subgraph_op_id]
276
+ op_info = qtyping.OpInfo(
277
+ op=fc_op,
278
+ op_name=_TFLOpName.FULLY_CONNECTED,
279
+ subgraph_op_index=subgraph_op_id,
280
+ op_quant_config=qtyping.OpQuantizationConfig(
281
+ weight_tensor_config=_TensorQuantConfig(
282
+ num_bits=16, dtype=qtyping.TensorDataType.FLOAT
283
+ ),
284
+ compute_precision=_ComputePrecision.FLOAT, # WEIGHT_ONLY.
285
+ explicit_dequantize=True,
286
+ ),
287
+ )
288
+
289
+ self._test_fc_conv(
290
+ op_info,
291
+ self._graph_info,
292
+ op_tensor_names,
293
+ float_casting.materialize_fc_conv,
294
+ )
295
+
296
+ def test_conv2d_weight_only_succeeds(self):
297
+ # Read from Model Explorer.
298
+ subgraph0 = self._test_model.subgraphs[0]
299
+ subgraph_op_id = 0
300
+ op = subgraph0.operators[subgraph_op_id]
301
+
302
+ op_info = qtyping.OpInfo(
303
+ op=op,
304
+ op_name=_TFLOpName.CONV_2D,
305
+ subgraph_op_index=subgraph_op_id,
306
+ op_quant_config=qtyping.OpQuantizationConfig(
307
+ weight_tensor_config=_TensorQuantConfig(
308
+ num_bits=16, dtype=qtyping.TensorDataType.FLOAT
309
+ ),
310
+ compute_precision=_ComputePrecision.FLOAT, # WEIGHT_ONLY.
311
+ explicit_dequantize=True,
312
+ ),
313
+ )
314
+
315
+ op_tensor_names = {}
316
+ op_tensor_names["weight"] = "sequential/conv2d/Conv2D"
317
+ op_tensor_names["bias"] = (
318
+ "sequential/conv2d/Relu;sequential/conv2d/BiasAdd;sequential/conv2d/Conv2D;sequential/conv2d/BiasAdd/ReadVariableOp"
319
+ )
320
+ op_tensor_names["input"] = "serving_default_conv2d_input:0"
321
+ op_tensor_names["output"] = (
322
+ "sequential/conv2d/Relu;sequential/conv2d/BiasAdd;sequential/conv2d/Conv2D;sequential/conv2d/BiasAdd/ReadVariableOp1"
323
+ )
324
+ self._test_fc_conv(
325
+ op_info,
326
+ self._graph_info,
327
+ op_tensor_names,
328
+ float_casting.materialize_fc_conv,
329
+ )
330
+
331
+ @parameterized.named_parameters(
332
+ dict(
333
+ testcase_name="invalid_fc",
334
+ op_name=_TFLOpName.FULLY_CONNECTED,
335
+ ),
336
+ dict(
337
+ testcase_name="invalid_conv2d",
338
+ op_name=_TFLOpName.CONV_2D,
339
+ ),
340
+ dict(
341
+ testcase_name="invalid_embedding_lookup",
342
+ op_name=_TFLOpName.EMBEDDING_LOOKUP,
343
+ ),
344
+ )
345
+ def test_check_op_quantization_config_invalid_execution_mode_raises_exception(
346
+ self, op_name
347
+ ):
348
+ # Use DRQ instead of WEIGHT-ONLY.
349
+ error_message = (
350
+ "Currently, only Weight-Only is supported for float casting"
351
+ " quantization."
352
+ )
353
+ with self.assertRaisesWithPredicateMatch(
354
+ ValueError, lambda err: error_message in str(err)
355
+ ):
356
+ float_casting.check_op_quantization_config(
357
+ op_name,
358
+ qtyping.OpQuantizationConfig(
359
+ activation_tensor_config=None,
360
+ weight_tensor_config=_TensorQuantConfig(
361
+ num_bits=16, dtype=qtyping.TensorDataType.FLOAT
362
+ ),
363
+ compute_precision=_ComputePrecision.INTEGER, # DRQ.
364
+ ),
365
+ )
366
+
367
+ def test_conv2d_transpose_weight_only_succeeds(self):
368
+ # Read from Model Explorer.
369
+ test_model_path = os.path.join(
370
+ _TEST_DATA_PREFIX_PATH, "single_conv2d_transpose_bias.tflite"
371
+ )
372
+
373
+ test_model = tfl_flatbuffer_utils.read_model(test_model_path)
374
+ # The test model has one subgraph for now.
375
+ graph_info = qtyping.GraphInfo(
376
+ subgraph_tensors=test_model.subgraphs[0].tensors,
377
+ buffers=test_model.buffers,
378
+ )
379
+
380
+ subgraph0 = test_model.subgraphs[0]
381
+ subgraph_op_id = 0
382
+ op = subgraph0.operators[subgraph_op_id]
383
+
384
+ op_info = qtyping.OpInfo(
385
+ op=op,
386
+ op_name=_TFLOpName.CONV_2D_TRANSPOSE,
387
+ subgraph_op_index=subgraph_op_id,
388
+ op_quant_config=qtyping.OpQuantizationConfig(
389
+ weight_tensor_config=_TensorQuantConfig(
390
+ num_bits=16, dtype=qtyping.TensorDataType.FLOAT
391
+ ),
392
+ compute_precision=_ComputePrecision.FLOAT, # WEIGHT_ONLY.
393
+ explicit_dequantize=True,
394
+ ),
395
+ )
396
+
397
+ op_tensor_names = {}
398
+ op_tensor_names["weight"] = (
399
+ "sequential_5/conv2d_transpose_3/conv2d_transpose"
400
+ )
401
+ op_tensor_names["bias"] = (
402
+ "sequential_5/conv2d_transpose_3/BiasAdd;sequential_5/conv2d_transpose_3/conv2d_transpose;sequential_5/conv2d_transpose_3/BiasAdd/ReadVariableOp"
403
+ )
404
+ op_tensor_names["input"] = "serving_default_input_6:0"
405
+ op_tensor_names["output"] = "StatefulPartitionedCall:0"
406
+
407
+ tensor_quant_params = float_casting.materialize_conv2d_transpose(
408
+ op_info, graph_info, self._tensor_name_to_qsv
409
+ )
410
+ _, weight_tensor, bias_tensor, _ = (
411
+ tfl_flatbuffer_utils.parse_fc_bmm_conv_tensors(
412
+ op_info.op, graph_info.subgraph_tensors
413
+ )
414
+ )
415
+
416
+ num_configs = 4 if bias_tensor is not None else 3
417
+ self.assertLen(tensor_quant_params, num_configs)
418
+
419
+ # Test input tensor params.
420
+ self._test_fp16_nonweight_tensor_transformation_params(
421
+ op_tensor_names["input"],
422
+ op_info.subgraph_op_index,
423
+ transformation_params=tensor_quant_params[0],
424
+ desired_transformations=[_QuantTransformation.NO_QUANTIZE],
425
+ is_inbounding_tensor=True,
426
+ )
427
+
428
+ # Test weight tensor params.
429
+ weight_tensor_data = tfl_flatbuffer_utils.get_tensor_data(
430
+ weight_tensor,
431
+ graph_info.buffers,
432
+ )
433
+ self._test_fp16_weight_tensor_transformation_params(
434
+ op_tensor_names["weight"],
435
+ op_info.subgraph_op_index,
436
+ tensor_quant_config=op_info.op_quant_config.weight_tensor_config,
437
+ transformation_params=tensor_quant_params[1],
438
+ desired_transformations=[_QuantTransformation.ADD_DEQUANTIZE],
439
+ tensor_data=weight_tensor_data,
440
+ )
441
+ # Test output tensor params.
442
+ self._test_fp16_nonweight_tensor_transformation_params(
443
+ op_tensor_names["output"],
444
+ op_info.subgraph_op_index,
445
+ transformation_params=tensor_quant_params[2],
446
+ desired_transformations=[_QuantTransformation.NO_QUANTIZE],
447
+ is_inbounding_tensor=False,
448
+ )
449
+
450
+ # Test bias tensor params.
451
+ if bias_tensor is not None:
452
+ self._test_fp16_nonweight_tensor_transformation_params(
453
+ op_tensor_names["bias"],
454
+ op_info.subgraph_op_index,
455
+ transformation_params=tensor_quant_params[3],
456
+ desired_transformations=[_QuantTransformation.NO_QUANTIZE],
457
+ is_inbounding_tensor=True,
458
+ )
459
+
460
+ def test_depthwise_conv2d_weight_only_succeeds(self):
461
+ # Read from Model Explorer.
462
+ test_model_path = os.path.join(
463
+ _TEST_DATA_PREFIX_PATH, "single_depthwise_conv2d_bias.tflite"
464
+ )
465
+
466
+ test_model = tfl_flatbuffer_utils.read_model(test_model_path)
467
+ # The test model has one subgraph for now.
468
+ graph_info = qtyping.GraphInfo(
469
+ subgraph_tensors=test_model.subgraphs[0].tensors,
470
+ buffers=test_model.buffers,
471
+ )
472
+
473
+ subgraph0 = test_model.subgraphs[0]
474
+ subgraph_op_id = 0
475
+ op = subgraph0.operators[subgraph_op_id]
476
+
477
+ op_info = qtyping.OpInfo(
478
+ op=op,
479
+ op_name=_TFLOpName.DEPTHWISE_CONV_2D,
480
+ subgraph_op_index=subgraph_op_id,
481
+ op_quant_config=qtyping.OpQuantizationConfig(
482
+ weight_tensor_config=_TensorQuantConfig(
483
+ num_bits=16, dtype=qtyping.TensorDataType.FLOAT
484
+ ),
485
+ compute_precision=_ComputePrecision.FLOAT, # WEIGHT_ONLY.
486
+ explicit_dequantize=True,
487
+ ),
488
+ )
489
+
490
+ op_tensor_names = {}
491
+ op_tensor_names["weight"] = "sequential/depthwise_conv2d/depthwise"
492
+ op_tensor_names["bias"] = (
493
+ "sequential/depthwise_conv2d/BiasAdd;sequential/depthwise_conv2d/depthwise;sequential/depthwise_conv2d/BiasAdd/ReadVariableOp"
494
+ )
495
+ op_tensor_names["input"] = "serving_default_input_1:0"
496
+ op_tensor_names["output"] = "StatefulPartitionedCall:0"
497
+ self._test_fc_conv(
498
+ op_info,
499
+ graph_info,
500
+ op_tensor_names,
501
+ float_casting.materialize_fc_conv,
502
+ )
503
+
504
+ def test_embedding_lookup_weight_only_succeeds(self):
505
+ test_model_path = os.path.join(
506
+ _TEST_DATA_PREFIX_PATH, "embedding_lookup.tflite"
507
+ )
508
+
509
+ test_model = tfl_flatbuffer_utils.read_model(test_model_path)
510
+ graph_info = qtyping.GraphInfo(
511
+ subgraph_tensors=test_model.subgraphs[0].tensors,
512
+ buffers=test_model.buffers,
513
+ )
514
+
515
+ subgraph0 = test_model.subgraphs[0]
516
+ subgraph_op_id = 0
517
+ op = subgraph0.operators[subgraph_op_id]
518
+
519
+ op_info = qtyping.OpInfo(
520
+ op=op,
521
+ op_name=_TFLOpName.EMBEDDING_LOOKUP,
522
+ subgraph_op_index=subgraph_op_id,
523
+ op_quant_config=qtyping.OpQuantizationConfig(
524
+ weight_tensor_config=_TensorQuantConfig(
525
+ num_bits=16, dtype=qtyping.TensorDataType.FLOAT
526
+ ),
527
+ compute_precision=_ComputePrecision.FLOAT, # WEIGHT_ONLY.
528
+ explicit_dequantize=True,
529
+ ),
530
+ )
531
+
532
+ op_tensor_names = {}
533
+ op_tensor_names["weight"] = (
534
+ "jax2tf_export_func_/...y_yz-_...z/pjit__einsum_/MatMul;jax2tf_export_func_/pjit__one_hot_/Equal;jax2tf_export_func_/pjit__one_hot_/Cast_1"
535
+ )
536
+ op_tensor_names["input"] = "inputs"
537
+ op_tensor_names["output"] = "Identity_1"
538
+
539
+ # TODO: b/335913710 - Rename the test function.
540
+ self._test_fc_conv(
541
+ op_info,
542
+ graph_info,
543
+ op_tensor_names,
544
+ float_casting.materialize_fc_conv,
545
+ )
546
+
547
+ def _test_fc_conv(
548
+ self,
549
+ op_info,
550
+ graph_info,
551
+ op_tensor_names,
552
+ materialization_func,
553
+ ):
554
+
555
+ tensor_quant_params = materialization_func(
556
+ op_info, graph_info, self._tensor_name_to_qsv
557
+ )
558
+ _, weight_tensor, bias_tensor, _ = (
559
+ tfl_flatbuffer_utils.parse_fc_bmm_conv_tensors(
560
+ op_info.op, graph_info.subgraph_tensors
561
+ )
562
+ )
563
+
564
+ num_configs = 4 if bias_tensor is not None else 3
565
+ self.assertLen(tensor_quant_params, num_configs)
566
+
567
+ # Test input tensor params.
568
+ self._test_fp16_nonweight_tensor_transformation_params(
569
+ op_tensor_names["input"],
570
+ op_info.subgraph_op_index,
571
+ transformation_params=tensor_quant_params[0],
572
+ desired_transformations=[_QuantTransformation.NO_QUANTIZE],
573
+ is_inbounding_tensor=True,
574
+ )
575
+
576
+ # Test weight tensor params.
577
+ weight_tensor_data = tfl_flatbuffer_utils.get_tensor_data(
578
+ weight_tensor,
579
+ graph_info.buffers,
580
+ )
581
+
582
+ self._test_fp16_weight_tensor_transformation_params(
583
+ op_tensor_names["weight"],
584
+ op_info.subgraph_op_index,
585
+ tensor_quant_config=op_info.op_quant_config.weight_tensor_config,
586
+ transformation_params=tensor_quant_params[1],
587
+ desired_transformations=[_QuantTransformation.ADD_DEQUANTIZE],
588
+ tensor_data=weight_tensor_data,
589
+ )
590
+ # Test output tensor params.
591
+ self._test_fp16_nonweight_tensor_transformation_params(
592
+ op_tensor_names["output"],
593
+ op_info.subgraph_op_index,
594
+ transformation_params=tensor_quant_params[2],
595
+ desired_transformations=[_QuantTransformation.NO_QUANTIZE],
596
+ is_inbounding_tensor=False,
597
+ )
598
+
599
+ # Test bias tensor params.
600
+ if bias_tensor is not None:
601
+ self._test_fp16_nonweight_tensor_transformation_params(
602
+ op_tensor_names["bias"],
603
+ op_info.subgraph_op_index,
604
+ transformation_params=tensor_quant_params[3],
605
+ desired_transformations=[_QuantTransformation.NO_QUANTIZE],
606
+ is_inbounding_tensor=True,
607
+ )
608
+
609
+ def _test_fp16_weight_tensor_transformation_params(
610
+ self,
611
+ tensor_name,
612
+ subgraph_op_id,
613
+ tensor_quant_config,
614
+ transformation_params,
615
+ desired_transformations,
616
+ tensor_data,
617
+ ):
618
+ self.assertEqual(transformation_params.tensor_name, tensor_name)
619
+ # Weight-only means the transformation is added from the consumer.
620
+ self.assertIsNone(transformation_params.producer)
621
+ self.assertLen(transformation_params.consumers, 1)
622
+ # Check op params.
623
+ op_params = transformation_params.consumers[0]
624
+ self.assertEqual(op_params.subgraph_op_id, subgraph_op_id)
625
+ self.assertSequenceEqual(op_params.transformations, desired_transformations)
626
+ # Check quantization params.
627
+ quantization_params = op_params.parameters
628
+ self.assertIsNotNone(quantization_params)
629
+ self.assertIsNotNone(tensor_quant_config)
630
+ self.assertEqual(quantization_params.num_bits, tensor_quant_config.num_bits)
631
+ quantized_data = quantization_params.quantized_data
632
+ self.assertIsNotNone(quantized_data)
633
+ self.assertEqual(quantized_data.dtype, "float16")
634
+ # fp16 quantization implies very small error.
635
+ self.assertSequenceAlmostEqual(
636
+ list(tensor_data.flatten()), # pytype: disable=attribute-error
637
+ list(quantization_params.quantized_data.flatten()), # pytype: disable=attribute-error
638
+ delta=5,
639
+ )
640
+
641
+ def _test_fp16_nonweight_tensor_transformation_params(
642
+ self,
643
+ tensor_name,
644
+ subgraph_op_id,
645
+ transformation_params,
646
+ desired_transformations,
647
+ is_inbounding_tensor,
648
+ ):
649
+ self.assertEqual(transformation_params.tensor_name, tensor_name)
650
+ if is_inbounding_tensor:
651
+ self.assertIsNone(transformation_params.producer)
652
+ self.assertLen(transformation_params.consumers, 1)
653
+ op_params = transformation_params.consumers[0]
654
+ else:
655
+ self.assertIsNone(transformation_params.consumers)
656
+ op_params = transformation_params.producer
657
+ self.assertIsNotNone(op_params)
658
+ self.assertEqual(op_params.subgraph_op_id, subgraph_op_id)
659
+ self.assertSequenceEqual(op_params.transformations, desired_transformations)
660
+ self.assertIsNone(op_params.parameters)
661
+
662
+
663
+ if __name__ == "__main__":
664
+ googletest.main()
@@ -0,0 +1,15 @@
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
+