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.
- ai_edge_quantizer/__init__.py +19 -0
- ai_edge_quantizer/algorithm_manager.py +167 -0
- ai_edge_quantizer/algorithm_manager_api.py +271 -0
- ai_edge_quantizer/algorithm_manager_api_test.py +210 -0
- ai_edge_quantizer/algorithms/__init__.py +15 -0
- ai_edge_quantizer/algorithms/nonlinear_quantize/__init__.py +15 -0
- ai_edge_quantizer/algorithms/nonlinear_quantize/float_casting.py +273 -0
- ai_edge_quantizer/algorithms/nonlinear_quantize/float_casting_test.py +664 -0
- ai_edge_quantizer/algorithms/uniform_quantize/__init__.py +15 -0
- ai_edge_quantizer/algorithms/uniform_quantize/naive_min_max_quantize.py +666 -0
- ai_edge_quantizer/algorithms/uniform_quantize/naive_min_max_quantize_test.py +184 -0
- ai_edge_quantizer/algorithms/uniform_quantize/uniform_quantize_tensor.py +371 -0
- ai_edge_quantizer/algorithms/uniform_quantize/uniform_quantize_tensor_test.py +357 -0
- ai_edge_quantizer/algorithms/utils/__init__.py +15 -0
- ai_edge_quantizer/algorithms/utils/min_max_quantize_utils.py +1067 -0
- ai_edge_quantizer/algorithms/utils/min_max_quantize_utils_test.py +512 -0
- ai_edge_quantizer/calibrator.py +288 -0
- ai_edge_quantizer/calibrator_test.py +297 -0
- ai_edge_quantizer/conftest.py +22 -0
- ai_edge_quantizer/default_policy.py +310 -0
- ai_edge_quantizer/model_modifier.py +176 -0
- ai_edge_quantizer/model_modifier_test.py +130 -0
- ai_edge_quantizer/model_validator.py +357 -0
- ai_edge_quantizer/model_validator_test.py +354 -0
- ai_edge_quantizer/params_generator.py +361 -0
- ai_edge_quantizer/params_generator_test.py +1041 -0
- ai_edge_quantizer/qtyping.py +483 -0
- ai_edge_quantizer/quantizer.py +372 -0
- ai_edge_quantizer/quantizer_test.py +532 -0
- ai_edge_quantizer/recipe.py +67 -0
- ai_edge_quantizer/recipe_manager.py +245 -0
- ai_edge_quantizer/recipe_manager_test.py +815 -0
- ai_edge_quantizer/recipe_test.py +97 -0
- ai_edge_quantizer/transformation_instruction_generator.py +584 -0
- ai_edge_quantizer/transformation_instruction_generator_test.py +1082 -0
- ai_edge_quantizer/transformation_performer.py +278 -0
- ai_edge_quantizer/transformation_performer_test.py +344 -0
- ai_edge_quantizer/transformations/__init__.py +15 -0
- ai_edge_quantizer/transformations/dequant_insert.py +87 -0
- ai_edge_quantizer/transformations/dequant_insert_test.py +304 -0
- ai_edge_quantizer/transformations/emulated_subchannel.py +363 -0
- ai_edge_quantizer/transformations/emulated_subchannel_test.py +212 -0
- ai_edge_quantizer/transformations/quant_insert.py +100 -0
- ai_edge_quantizer/transformations/quant_insert_test.py +284 -0
- ai_edge_quantizer/transformations/quantize_tensor.py +156 -0
- ai_edge_quantizer/transformations/quantize_tensor_test.py +227 -0
- ai_edge_quantizer/transformations/transformation_utils.py +132 -0
- ai_edge_quantizer/transformations/transformation_utils_test.py +162 -0
- ai_edge_quantizer/utils/__init__.py +15 -0
- ai_edge_quantizer/utils/calibration_utils.py +86 -0
- ai_edge_quantizer/utils/calibration_utils_test.py +77 -0
- ai_edge_quantizer/utils/test_utils.py +107 -0
- ai_edge_quantizer/utils/tfl_flatbuffer_utils.py +317 -0
- ai_edge_quantizer/utils/tfl_flatbuffer_utils_test.py +200 -0
- ai_edge_quantizer/utils/tfl_interpreter_utils.py +312 -0
- ai_edge_quantizer/utils/tfl_interpreter_utils_test.py +332 -0
- ai_edge_quantizer/utils/validation_utils.py +125 -0
- ai_edge_quantizer/utils/validation_utils_test.py +87 -0
- ai_edge_quantizer_nightly-0.0.1.dev20250115.dist-info/LICENSE +201 -0
- ai_edge_quantizer_nightly-0.0.1.dev20250115.dist-info/METADATA +32 -0
- ai_edge_quantizer_nightly-0.0.1.dev20250115.dist-info/RECORD +63 -0
- ai_edge_quantizer_nightly-0.0.1.dev20250115.dist-info/WHEEL +5 -0
- ai_edge_quantizer_nightly-0.0.1.dev20250115.dist-info/top_level.txt +1 -0
@@ -0,0 +1,372 @@
|
|
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
|
+
"""AI Edge Quantizer API."""
|
17
|
+
|
18
|
+
from collections.abc import Iterable
|
19
|
+
import dataclasses
|
20
|
+
import json
|
21
|
+
import os
|
22
|
+
from typing import Any, Optional, Union
|
23
|
+
from ai_edge_quantizer import algorithm_manager
|
24
|
+
from ai_edge_quantizer import calibrator
|
25
|
+
from ai_edge_quantizer import default_policy
|
26
|
+
from ai_edge_quantizer import model_modifier
|
27
|
+
from ai_edge_quantizer import model_validator
|
28
|
+
from ai_edge_quantizer import params_generator
|
29
|
+
from ai_edge_quantizer import qtyping
|
30
|
+
from ai_edge_quantizer import recipe_manager
|
31
|
+
from ai_edge_quantizer.utils import test_utils
|
32
|
+
from ai_edge_quantizer.utils import tfl_flatbuffer_utils
|
33
|
+
from ai_edge_quantizer.utils import tfl_interpreter_utils
|
34
|
+
from ai_edge_quantizer.utils import validation_utils
|
35
|
+
from tensorflow.python.platform import gfile # pylint: disable=g-direct-tensorflow-import
|
36
|
+
|
37
|
+
# Expose algorithm names to users.
|
38
|
+
AlgorithmName = algorithm_manager.AlgorithmName
|
39
|
+
|
40
|
+
_QuantRecipe = recipe_manager.ModelQuantizationRecipe
|
41
|
+
_TFLOpName = qtyping.TFLOperationName
|
42
|
+
_OpQuantizationConfig = qtyping.OpQuantizationConfig
|
43
|
+
_TensorQuantizationConfig = qtyping.TensorQuantizationConfig
|
44
|
+
_TensorTransformationParams = dict[str, qtyping.TensorTransformationParams]
|
45
|
+
_SignatureInput = dict[str, Any] # input_argument_name -> tensor_value.
|
46
|
+
_CalibrationResult = dict[str, qtyping.QSV]
|
47
|
+
|
48
|
+
|
49
|
+
@dataclasses.dataclass(frozen=True)
|
50
|
+
class QuantizationResult:
|
51
|
+
"""Quantization result.
|
52
|
+
|
53
|
+
Attributes:
|
54
|
+
recipe: Quantization recipe.
|
55
|
+
quantized_model: Quantized model.
|
56
|
+
"""
|
57
|
+
|
58
|
+
recipe: _QuantRecipe
|
59
|
+
quantized_model: Optional[bytearray]
|
60
|
+
|
61
|
+
def save(self, save_folder: str, model_name: str) -> None:
|
62
|
+
"""Saves the quantized model and the quantization recipe.
|
63
|
+
|
64
|
+
Args:
|
65
|
+
save_folder: Path to the folder to save the quantized model and the
|
66
|
+
quantization recipe.
|
67
|
+
model_name: Name of the model.
|
68
|
+
|
69
|
+
Raises:
|
70
|
+
RuntimeError: If no quantized model is available.
|
71
|
+
FileExistsError: If the model already exists in the folder.
|
72
|
+
"""
|
73
|
+
if self.quantized_model is None:
|
74
|
+
raise RuntimeError(
|
75
|
+
'No quantized model to save. Make sure .quantize() is called.'
|
76
|
+
)
|
77
|
+
model_save_path = os.path.join(save_folder, f'{model_name}.tflite')
|
78
|
+
if gfile.Exists(model_save_path):
|
79
|
+
raise FileExistsError(
|
80
|
+
f'The model {model_save_path} already exists in the folder.'
|
81
|
+
)
|
82
|
+
with gfile.GFile(model_save_path, 'wb') as output_file_handle:
|
83
|
+
output_file_handle.write(self.quantized_model)
|
84
|
+
|
85
|
+
recipe = json.dumps(self.recipe)
|
86
|
+
recipe_save_path = os.path.join(save_folder, model_name + '_recipe.json')
|
87
|
+
with gfile.GFile(recipe_save_path, 'w') as output_file_handle:
|
88
|
+
output_file_handle.write(recipe)
|
89
|
+
|
90
|
+
def export_model(self, filepath: str) -> None:
|
91
|
+
"""Exports the quantized model to a .tflite flatbuffer.
|
92
|
+
|
93
|
+
Args:
|
94
|
+
filepath: Path (including file name) that the exported model should be
|
95
|
+
serialized to.
|
96
|
+
|
97
|
+
Raises:
|
98
|
+
RuntimeError: If no quantized model is available.
|
99
|
+
"""
|
100
|
+
if self.quantized_model is None:
|
101
|
+
raise RuntimeError(
|
102
|
+
'No quantized model to save. Make sure .quantize() is called.'
|
103
|
+
)
|
104
|
+
with gfile.GFile(filepath, 'wb') as output_file_handle:
|
105
|
+
output_file_handle.write(self.quantized_model)
|
106
|
+
|
107
|
+
|
108
|
+
class Quantizer:
|
109
|
+
"""AI Edge Quantizer API.
|
110
|
+
|
111
|
+
Attributes:
|
112
|
+
float_model: TFLite model file path or bytearray.
|
113
|
+
quantization_recipe: Quantization recipe .json filepath or in loaded json
|
114
|
+
format.
|
115
|
+
"""
|
116
|
+
|
117
|
+
def __init__(
|
118
|
+
self,
|
119
|
+
float_model: Union[str, bytearray],
|
120
|
+
quantization_recipe: Optional[Union[str, _QuantRecipe]] = None,
|
121
|
+
):
|
122
|
+
"""Initializes the quantizer.
|
123
|
+
|
124
|
+
Args:
|
125
|
+
float_model: Path to the float tflite model.
|
126
|
+
quantization_recipe: Quantization recipe in .json filepath or loaded json
|
127
|
+
format.
|
128
|
+
"""
|
129
|
+
# Use `float model` as bytes for memory efficiency.
|
130
|
+
self.float_model: bytes = (
|
131
|
+
tfl_flatbuffer_utils.get_model_content(float_model)
|
132
|
+
if isinstance(float_model, str)
|
133
|
+
else float_model
|
134
|
+
)
|
135
|
+
|
136
|
+
self._recipe_manager: recipe_manager.RecipeManager = (
|
137
|
+
recipe_manager.RecipeManager()
|
138
|
+
)
|
139
|
+
if quantization_recipe is not None:
|
140
|
+
self.load_quantization_recipe(quantization_recipe)
|
141
|
+
self._result: QuantizationResult = QuantizationResult([{}], None)
|
142
|
+
|
143
|
+
def load_quantization_recipe(self, recipe: Union[str, _QuantRecipe]) -> None:
|
144
|
+
"""Loads a quantization recipe.
|
145
|
+
|
146
|
+
The existing recipe will be overwritten.
|
147
|
+
|
148
|
+
Args:
|
149
|
+
recipe: Quantization recipe in json format.
|
150
|
+
"""
|
151
|
+
if isinstance(recipe, str):
|
152
|
+
with gfile.Open(recipe) as json_file:
|
153
|
+
recipe = json.load(json_file)
|
154
|
+
self._recipe_manager.load_quantization_recipe(recipe)
|
155
|
+
|
156
|
+
def load_config_policy(self, filename: str) -> None:
|
157
|
+
"""Loads a JSON policy.
|
158
|
+
|
159
|
+
The existing policy will be overwritten.
|
160
|
+
|
161
|
+
Args:
|
162
|
+
filename: Config policy filename.
|
163
|
+
"""
|
164
|
+
with gfile.Open(filename, 'r') as f:
|
165
|
+
policy = default_policy.update_default_config_policy(f.read())
|
166
|
+
|
167
|
+
# Register the policy for MIN_MAX_UNIFORM_QUANT algorithm.
|
168
|
+
algorithm_manager.register_config_check_policy_func(
|
169
|
+
AlgorithmName.MIN_MAX_UNIFORM_QUANT, policy
|
170
|
+
)
|
171
|
+
|
172
|
+
def get_quantization_recipe(self) -> _QuantRecipe:
|
173
|
+
"""Gets the quantization recipe.
|
174
|
+
|
175
|
+
Returns:
|
176
|
+
A quantization recipe.
|
177
|
+
"""
|
178
|
+
return self._recipe_manager.get_quantization_recipe()
|
179
|
+
|
180
|
+
def update_quantization_recipe(
|
181
|
+
self,
|
182
|
+
regex: str,
|
183
|
+
operation_name: _TFLOpName,
|
184
|
+
op_config: Optional[_OpQuantizationConfig] = None,
|
185
|
+
algorithm_key: str = algorithm_manager.AlgorithmName.MIN_MAX_UNIFORM_QUANT,
|
186
|
+
):
|
187
|
+
"""Adds a quantization configuration to the recipe.
|
188
|
+
|
189
|
+
Conflict arises when we are trying to set an operation under a certain regex
|
190
|
+
which is already existed in the config dictionary. Under such circumstance,
|
191
|
+
the new config is used to replace the previous one.
|
192
|
+
|
193
|
+
We also have special treatment for _TFLOperationKey.ALL. If the new config
|
194
|
+
is on _TFLOperationKey.ALL and there are existing op configs inside the same
|
195
|
+
scope, we clear the previous configs and use _TFLOperationKey.ALL.
|
196
|
+
|
197
|
+
Args:
|
198
|
+
regex: Regular expression for layer name matching.
|
199
|
+
operation_name: Target TFLite operation. * for all supported TFLite
|
200
|
+
operation.
|
201
|
+
op_config: Quantization configuration which will be used to update the
|
202
|
+
default configuration. None or empty dict means the default
|
203
|
+
configuration will be used.
|
204
|
+
algorithm_key: Algorithm key to be applied.
|
205
|
+
"""
|
206
|
+
self._recipe_manager.add_quantization_config(
|
207
|
+
regex, operation_name, op_config, algorithm_key
|
208
|
+
)
|
209
|
+
|
210
|
+
@property
|
211
|
+
def need_calibration(self) -> bool:
|
212
|
+
"""Checks if the current recipe needs calibration."""
|
213
|
+
return self._recipe_manager.need_calibration()
|
214
|
+
|
215
|
+
def calibrate(
|
216
|
+
self,
|
217
|
+
calibration_data: dict[str, Iterable[_SignatureInput]],
|
218
|
+
previous_calibration_result: Optional[_CalibrationResult] = None,
|
219
|
+
num_threads: int = 16,
|
220
|
+
) -> _CalibrationResult:
|
221
|
+
"""Calibrates the float model (required by static range quantization).
|
222
|
+
|
223
|
+
Args:
|
224
|
+
calibration_data: Calibration data for a model signature.
|
225
|
+
previous_calibration_result: Previous calibration result to be loaded. The
|
226
|
+
calibration process will be resumed from the previous result.
|
227
|
+
num_threads: Number of threads to use for calibration.
|
228
|
+
|
229
|
+
Returns:
|
230
|
+
Calibration result ({tensor_name: tensor QSVs (e.g.,min/max)}).
|
231
|
+
|
232
|
+
Raises:
|
233
|
+
ValueError: If the calibration result is insufficient.
|
234
|
+
"""
|
235
|
+
if not self.need_calibration:
|
236
|
+
return {}
|
237
|
+
|
238
|
+
calib = calibrator.Calibrator(self.float_model, num_threads=num_threads)
|
239
|
+
if previous_calibration_result is not None:
|
240
|
+
calib.load_model_qsvs(previous_calibration_result)
|
241
|
+
calib.calibrate(calibration_data, self._recipe_manager)
|
242
|
+
return calib.get_model_qsvs()
|
243
|
+
|
244
|
+
def _ensure_model_qsv_sufficient(
|
245
|
+
self, calibration_result: _CalibrationResult
|
246
|
+
):
|
247
|
+
"""Checks if the calibration result has sufficient QSV."""
|
248
|
+
|
249
|
+
# Find all tensor names with empty entries.
|
250
|
+
empty_qsvs = [key for key, value in calibration_result.items() if not value]
|
251
|
+
|
252
|
+
# Go over every signature and check if empty entry tensor belongs to it.
|
253
|
+
tfl_interpreter = tfl_interpreter_utils.create_tfl_interpreter(
|
254
|
+
self.float_model
|
255
|
+
)
|
256
|
+
for signature_key in tfl_interpreter.get_signature_list():
|
257
|
+
subgraph_idx = tfl_interpreter_utils.get_signature_main_subgraph_index(
|
258
|
+
tfl_interpreter, signature_key
|
259
|
+
)
|
260
|
+
|
261
|
+
for tensor_detail in tfl_interpreter.get_tensor_details(subgraph_idx):
|
262
|
+
tensor_name = tensor_detail['name']
|
263
|
+
if tensor_name in empty_qsvs:
|
264
|
+
raise ValueError(
|
265
|
+
f'Missing QSVs (min/max) for tensor {tensor_name} in Signature'
|
266
|
+
f" '{signature_key}'. Please check if Signature"
|
267
|
+
f' {signature_key} has been calibrated.'
|
268
|
+
)
|
269
|
+
|
270
|
+
def quantize(
|
271
|
+
self, calibration_result: Optional[_CalibrationResult] = None
|
272
|
+
) -> QuantizationResult:
|
273
|
+
"""Quantizes the float model.
|
274
|
+
|
275
|
+
Args:
|
276
|
+
calibration_result: Calibration result to be used for quantization (if
|
277
|
+
needed, check with self.need_calibration).
|
278
|
+
|
279
|
+
Returns:
|
280
|
+
Quantization result.
|
281
|
+
|
282
|
+
Raises:
|
283
|
+
RuntimeError: If quantization recipe is empty.
|
284
|
+
"""
|
285
|
+
|
286
|
+
if calibration_result is not None:
|
287
|
+
self._ensure_model_qsv_sufficient(calibration_result)
|
288
|
+
|
289
|
+
if not self.get_quantization_recipe():
|
290
|
+
raise RuntimeError('Can not quantize without a quantization recipe.')
|
291
|
+
quant_params = self._get_quantization_params(calibration_result)
|
292
|
+
quantized_model = self._get_quantized_model(quant_params)
|
293
|
+
self._result = QuantizationResult(
|
294
|
+
self.get_quantization_recipe(), quantized_model
|
295
|
+
)
|
296
|
+
return self._result
|
297
|
+
|
298
|
+
def validate(
|
299
|
+
self,
|
300
|
+
test_data: Optional[dict[str, Iterable[_SignatureInput]]] = None,
|
301
|
+
error_metrics: str = 'mse',
|
302
|
+
use_xnnpack: bool = True,
|
303
|
+
num_threads: int = 16,
|
304
|
+
) -> model_validator.ComparisonResult:
|
305
|
+
"""Numerical validation of the quantized model for a model signature.
|
306
|
+
|
307
|
+
Side by side numerical comparison will be performed on all tensors in the
|
308
|
+
quantized model against ones from the float model. If no test data is
|
309
|
+
provided, random normal distributed data will be used. This test is intended
|
310
|
+
to be SANITY check for the quality of the quantized model. End to end task
|
311
|
+
specific test should be performed as the golden standard of the quantized
|
312
|
+
model quality. The comparison result will be saved in json format if
|
313
|
+
json_save_path is provided.
|
314
|
+
|
315
|
+
Args:
|
316
|
+
test_data: A dictionary of signature key and its correspending test input
|
317
|
+
data that will be used for validation. If set to None, random normal
|
318
|
+
distributed data will be used for all signatures in the model.
|
319
|
+
error_metrics: Error metrics to be used for comparison.
|
320
|
+
use_xnnpack: Whether to use the xnnpack library for validation.
|
321
|
+
num_threads: Number of threads to use for validation.
|
322
|
+
|
323
|
+
Returns:
|
324
|
+
The comparison result.
|
325
|
+
"""
|
326
|
+
if test_data is None:
|
327
|
+
# Create test data for all signatures in the model.
|
328
|
+
test_data = test_utils.create_random_normal_input_data(
|
329
|
+
self.float_model, num_samples=1
|
330
|
+
)
|
331
|
+
return model_validator.compare_model(
|
332
|
+
self.float_model,
|
333
|
+
self._result.quantized_model,
|
334
|
+
test_data,
|
335
|
+
error_metrics,
|
336
|
+
validation_utils.get_validation_func(error_metrics),
|
337
|
+
use_xnnpack=use_xnnpack,
|
338
|
+
num_threads=num_threads,
|
339
|
+
)
|
340
|
+
|
341
|
+
def _get_quantization_params(
|
342
|
+
self, calibration_result: Optional[_CalibrationResult] = None
|
343
|
+
) -> _TensorTransformationParams:
|
344
|
+
"""Gets the quantization parameters.
|
345
|
+
|
346
|
+
Args:
|
347
|
+
calibration_result: Calibration result to be used for quantization (if
|
348
|
+
needed, check with self.need_calibration).
|
349
|
+
|
350
|
+
Returns:
|
351
|
+
A dictionary containing the quantization parameters.
|
352
|
+
"""
|
353
|
+
params_generator_instance = params_generator.ParamsGenerator(
|
354
|
+
self.float_model
|
355
|
+
)
|
356
|
+
return params_generator_instance.generate_quantization_parameters(
|
357
|
+
self._recipe_manager, calibration_result
|
358
|
+
)
|
359
|
+
|
360
|
+
def _get_quantized_model(
|
361
|
+
self, quant_params: _TensorTransformationParams
|
362
|
+
) -> bytearray:
|
363
|
+
"""Gets the quantized model.
|
364
|
+
|
365
|
+
Args:
|
366
|
+
quant_params: A dictionary containing the quantization parameters.
|
367
|
+
|
368
|
+
Returns:
|
369
|
+
The quantized model.
|
370
|
+
"""
|
371
|
+
model_modifier_instance = model_modifier.ModelModifier(self.float_model)
|
372
|
+
return model_modifier_instance.modify_model(quant_params)
|