-
Notifications
You must be signed in to change notification settings - Fork 31
Expand file tree
/
Copy pathfloat_casting.py
More file actions
340 lines (303 loc) · 11.6 KB
/
Copy pathfloat_casting.py
File metadata and controls
340 lines (303 loc) · 11.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
# Copyright 2024 The AI Edge Quantizer Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Performs float casting quantization."""
from typing import Any, Optional
import numpy as np
from ai_edge_quantizer import qtyping
from ai_edge_quantizer.algorithms.utils import common_utils
from ai_edge_quantizer.utils import tfl_flatbuffer_utils
ALGORITHM_KEY = "float_casting"
_TFLOpName = qtyping.TFLOperationName
_QuantTransformation = qtyping.QuantTransformation
# "Fake" quantization config for float casting.
_FP16_QUANT_CONFIG = qtyping.TensorQuantizationConfig(
num_bits=16, dtype=qtyping.TensorDataType.FLOAT
)
# Ops that support weight quantization config (e.g., support Weight-only).
SUPPORTED_WEIGHT_QUANT_OPS = frozenset([
_TFLOpName.FULLY_CONNECTED,
_TFLOpName.CONV_2D,
_TFLOpName.DEPTHWISE_CONV_2D,
_TFLOpName.CONV_2D_TRANSPOSE,
_TFLOpName.EMBEDDING_LOOKUP,
])
def check_op_quantization_config(
op_name: _TFLOpName,
op_quant_config: qtyping.OpQuantizationConfig,
config_check_policy: Optional[qtyping.ConfigCheckPolicyDict] = None,
) -> None:
"""Checks if the op is valid for float casting quantization.
Args:
op_name: The name of the op.
op_quant_config: The quantization config for the op.
config_check_policy: The policy to check the quantization config.
Raises:
ValueError: If the op is not supported or the compute_precision is not
FLOAT.
"""
# TODO: b/353780772 - Add config check policy for float casting quantization.
if config_check_policy is not None and config_check_policy:
raise ValueError(f"Config check isn't implemented yet for op: {op_name}.")
# Check if WEIGHT_ONLY.
if op_quant_config.compute_precision != qtyping.ComputePrecision.FLOAT:
raise ValueError(
"Currently, only Weight-Only is supported for float casting"
" quantization. Got unsupported execution mode:"
f" {op_quant_config.compute_precision} for op: {op_name}"
)
if op_quant_config.activation_tensor_config is not None:
raise ValueError(
"Activation tensor quantization is not supported for float casting"
" quantization."
)
if op_name not in SUPPORTED_WEIGHT_QUANT_OPS:
raise ValueError(
f"Unsupported op: {op_name} for float casting quantization."
)
if op_quant_config.weight_tensor_config is None:
raise ValueError(
"Weight tensor quantization config is required for float casting"
" quantization."
)
if (
op_quant_config.weight_tensor_config.num_bits != 16
or op_quant_config.weight_tensor_config.dtype
!= qtyping.TensorDataType.FLOAT
):
raise ValueError(
"Currently, float casting quantization config requires number of bits"
" to be set as 16, dtype as float, got"
f" {op_quant_config.weight_tensor_config.num_bits} and"
f" {op_quant_config.weight_tensor_config.dtype} ."
)
def materialize_fc_conv(
op_info: qtyping.OpInfo,
graph_info: qtyping.GraphInfo,
tensor_name_to_qsv: dict[str, Any], # pylint: disable=unused-argument
tensor_quant_params_cache: common_utils.TensorQuantParamsCache,
) -> list[qtyping.TensorTransformationParams]:
"""Materialize tensors in fully_connected, conv_2d and depthwise_conv_2d ops.
This function is called by the quantization pipeline to materialize
quantization parameters for the weight tensor of the op.
Args:
op_info: Aggregated information about the op (e.g., quantization config).
graph_info: Graph information needed to perform quantization for the op.
tensor_name_to_qsv: A map of tensor name to quantization parameters
(unused).
tensor_quant_params_cache: Cache of already computed
`UniformQuantParams|NonLinearQuantParams` objects keyed on a tuple of the
buffer ID and the `TensorQuantizationConfig` used to compute it.
Returns:
Quantization configuration for the weight tensor of the op.
Raises:
ValueError: If the op is not supported or the compute precision is not
FLOAT.
"""
input_tensor, weight_tensor, bias_tensor, output_tensor = (
tfl_flatbuffer_utils.parse_fc_bmm_conv_tensors(
op_info.op, graph_info.subgraph_tensors
)
)
op_tensor_params = []
# Input tensor.
input_quant_params = _config_no_quantize_tensor(
op_info, input_tensor, is_inbounding_tensor=True
)
op_tensor_params.append(input_quant_params)
# Weight tensor.
weight_content = tfl_flatbuffer_utils.get_tensor_data(
weight_tensor,
graph_info.buffers,
)
if weight_content is None:
# If the weight data is not stored in the flatbuffer (e.g. dynamic weights),
# skip quantization for this tensor.
op2weight_params = qtyping.OpToTensorParams(
subgraph_op_id=op_info.subgraph_op_index,
transformations=[_QuantTransformation.NO_QUANTIZE],
)
else:
if not (
quant_params := tensor_quant_params_cache.lookup(
weight_tensor.buffer, _FP16_QUANT_CONFIG
)
):
quant_params = qtyping.NonLinearQuantParams(
num_bits=16, quantized_data=weight_content.astype(np.float16)
)
tensor_quant_params_cache.insert(
weight_tensor.buffer, _FP16_QUANT_CONFIG, quant_params
)
op2weight_params = qtyping.OpToTensorParams(
subgraph_op_id=op_info.subgraph_op_index,
parameters=quant_params,
transformations=[_QuantTransformation.ADD_DEQUANTIZE],
)
quant_params = qtyping.NonLinearQuantParams(
num_bits=16, quantized_data=weight_content.astype(np.float16) # pytype: disable=attribute-error
)
op2weight_params = qtyping.OpToTensorParams(
subgraph_op_id=op_info.subgraph_op_index,
parameters=quant_params,
transformations=[_QuantTransformation.ADD_DEQUANTIZE],
)
op_tensor_params.append(
qtyping.TensorTransformationParams(
tensor_name=tfl_flatbuffer_utils.get_tensor_name(weight_tensor),
consumers=[op2weight_params],
)
)
# Output tensor.
output_quant_params = _config_no_quantize_tensor(
op_info, output_tensor, is_inbounding_tensor=False
)
op_tensor_params.append(output_quant_params)
# Bias tensor.
if bias_tensor is not None:
bias_quant_params = _config_no_quantize_tensor(
op_info, bias_tensor, is_inbounding_tensor=True
)
op_tensor_params.append(bias_quant_params)
return op_tensor_params
def materialize_embedding_lookup(
op_info: qtyping.OpInfo,
graph_info: qtyping.GraphInfo,
tensor_name_to_qsv: dict[str, Any],
tensor_quant_params_cache: common_utils.TensorQuantParamsCache,
) -> list[qtyping.TensorTransformationParams]:
return materialize_fc_conv(
op_info,
graph_info,
tensor_name_to_qsv,
tensor_quant_params_cache=tensor_quant_params_cache,
)
def materialize_conv2d_transpose(
op_info: qtyping.OpInfo,
graph_info: qtyping.GraphInfo,
tensor_name_to_qsv: dict[str, Any], # pylint: disable=unused-argument
tensor_quant_params_cache: common_utils.TensorQuantParamsCache,
) -> list[qtyping.TensorTransformationParams]:
"""Materialize tensors in fully_connected, conv_2d and depthwise_conv_2d ops.
This function is called by the quantization pipeline to materialize
quantization parameters for the weight tensor of the op.
Args:
op_info: Aggregated information about the op (e.g., quantization config).
graph_info: Graph information needed to perform quantization for the op.
tensor_name_to_qsv: A map of tensor name to quantization parameters
(unused).
tensor_quant_params_cache: Cache of already computed
`UniformQuantParams|NonLinearQuantParams` objects keyed on a tuple of the
buffer ID and the `TensorQuantizationConfig` used to compute it.
Returns:
Quantization configuration for the weight tensor of the op.
Raises:
ValueError: If the op is not supported or the execution mode is not
WEIGHT_ONLY.
"""
input_tensor, weight_tensor, bias_tensor, output_tensor = (
tfl_flatbuffer_utils.parse_fc_bmm_conv_tensors(
op_info.op,
graph_info.subgraph_tensors,
input_index=2,
weight_index=1,
bias_index=3,
output_index=0,
)
)
op_tensor_params = []
# Input tensor.
input_quant_params = _config_no_quantize_tensor(
op_info, input_tensor, is_inbounding_tensor=True
)
op_tensor_params.append(input_quant_params)
# Weight tensor.
weight_content = tfl_flatbuffer_utils.get_tensor_data(
weight_tensor,
graph_info.buffers,
)
if weight_content is None:
# If the weight data is not stored in the flatbuffer (e.g. dynamic weights),
# skip quantization for this tensor.
op2weight_params = qtyping.OpToTensorParams(
subgraph_op_id=op_info.subgraph_op_index,
transformations=[_QuantTransformation.NO_QUANTIZE],
)
else:
if not (
quant_params := tensor_quant_params_cache.lookup(
weight_tensor.buffer, _FP16_QUANT_CONFIG
)
):
quant_params = qtyping.NonLinearQuantParams(
num_bits=16, quantized_data=weight_content.astype(np.float16)
)
tensor_quant_params_cache.insert(
weight_tensor.buffer, _FP16_QUANT_CONFIG, quant_params
)
op2weight_params = qtyping.OpToTensorParams(
subgraph_op_id=op_info.subgraph_op_index,
parameters=quant_params,
transformations=[_QuantTransformation.ADD_DEQUANTIZE],
)
op_tensor_params.append(
qtyping.TensorTransformationParams(
tensor_name=tfl_flatbuffer_utils.get_tensor_name(weight_tensor),
consumers=[op2weight_params],
)
)
# Output tensor.
output_quant_params = _config_no_quantize_tensor(
op_info, output_tensor, is_inbounding_tensor=False
)
op_tensor_params.append(output_quant_params)
# Bias tensor.
if bias_tensor is not None:
bias_quant_params = _config_no_quantize_tensor(
op_info, bias_tensor, is_inbounding_tensor=True
)
op_tensor_params.append(bias_quant_params)
return op_tensor_params
def _config_no_quantize_tensor(
op_info: qtyping.OpInfo,
tensor: Any,
is_inbounding_tensor: bool,
) -> qtyping.TensorTransformationParams:
"""Configures a tensor to be not quantized.
Args:
op_info: Aggregated information about the op (e.g., quantization config).
tensor: The tensor to be configured.
is_inbounding_tensor: Whether the tensor is an inbounding tensor.
Returns:
TensorTransformationParams for the tensor.
"""
tensor_name = tfl_flatbuffer_utils.get_tensor_name(tensor)
op2tensor_params = qtyping.OpToTensorParams(
subgraph_op_id=op_info.subgraph_op_index,
transformations=[_QuantTransformation.NO_QUANTIZE],
)
if is_inbounding_tensor:
return qtyping.TensorTransformationParams(
tensor_name=tensor_name,
consumers=[op2tensor_params],
)
return qtyping.TensorTransformationParams(
tensor_name=tensor_name, producer=op2tensor_params
)
def init_qsvs(*_) -> qtyping.QSV:
"""Currently calibration free. Placeholder for AlgorithmManager."""
return {}
def calibrate(*_) -> dict[str, qtyping.QSV]:
"""Currently calibration free. Placeholder for AlgorithmManager."""
return {}