DaniAffCH commited on
Commit
6911e5d
·
1 Parent(s): 84c8121

[GSoC] Blockwise Quantization Tool (#265)

Browse files

* Blockwise quantization tool

* add missing type hints

* add min python version check

* refactoring

tools/quantize/README.md CHANGED
@@ -7,7 +7,7 @@ Install dependencies before trying quantization:
7
  pip install -r requirements.txt
8
  ```
9
 
10
- ## Usage
11
 
12
  Quantize all models in the Zoo:
13
  ```shell
@@ -52,6 +52,16 @@ models = dict(
52
  python quantize-inc.py model1
53
  ```
54
 
 
 
 
 
 
 
 
 
 
 
55
  ## Dataset
56
  Some models are quantized with extra datasets.
57
  - [MP-PalmDet](../../models/palm_detection_mediapipe) and [MP-HandPose](../../models/handpose_estimation_mediapipe) are quantized with evaluation set of [FreiHAND](https://lmb.informatik.uni-freiburg.de/resources/datasets/FreihandDataset.en.html). Download the dataset from [this link](https://lmb.informatik.uni-freiburg.de/data/freihand/FreiHAND_pub_v2_eval.zip). Unpack it and replace `path/to/dataset` with the path to `FreiHAND_pub_v2_eval/evaluation/rgb`.
 
7
  pip install -r requirements.txt
8
  ```
9
 
10
+ ## Quantization Usage
11
 
12
  Quantize all models in the Zoo:
13
  ```shell
 
52
  python quantize-inc.py model1
53
  ```
54
 
55
+ ## Blockwise quantization usage
56
+
57
+ `block_quantize.py` requires Python>=3.7
58
+
59
+ To perform weight-only blockwise quantization:
60
+
61
+ ```shell
62
+ python block_quantize.py --input_model INPUT_MODEL.onnx --output_model OUTPUT_MODEL.onnx --block_size {block size} --bits {8,16}
63
+ ```
64
+
65
  ## Dataset
66
  Some models are quantized with extra datasets.
67
  - [MP-PalmDet](../../models/palm_detection_mediapipe) and [MP-HandPose](../../models/handpose_estimation_mediapipe) are quantized with evaluation set of [FreiHAND](https://lmb.informatik.uni-freiburg.de/resources/datasets/FreihandDataset.en.html). Download the dataset from [this link](https://lmb.informatik.uni-freiburg.de/data/freihand/FreiHAND_pub_v2_eval.zip). Unpack it and replace `path/to/dataset` with the path to `FreiHAND_pub_v2_eval/evaluation/rgb`.
tools/quantize/block_quantize.py ADDED
@@ -0,0 +1,419 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+
3
+ MIN_PYTHON_VERSION = (3, 7)
4
+
5
+ if sys.version_info < MIN_PYTHON_VERSION:
6
+ raise ImportError("This script requires Python 3.7 or higher!")
7
+
8
+ import argparse
9
+ import os
10
+ from dataclasses import dataclass, field
11
+ from typing import List, Optional, Tuple
12
+
13
+ import numpy as np
14
+ import onnx
15
+ from onnx import helper
16
+
17
+ BITS_TO_NUMPY_TYPE = {8: np.uint8, 16: np.uint16}
18
+
19
+
20
+ SUPPORTED_OPS = {
21
+ "Conv"
22
+ }
23
+
24
+ ONNX_OPSET = 21
25
+
26
+
27
+ @dataclass
28
+ class BlockQuantizeConfig:
29
+ input_model_path: str
30
+ output_model_path: str
31
+ block_size: int
32
+ bits: int
33
+
34
+
35
+ @dataclass
36
+ class BlockQuantizeResult:
37
+ quantized_weights: np.ndarray = field(default_factory=lambda: np.array([]))
38
+ scales: np.ndarray = field(default_factory=lambda: np.array([]))
39
+ zero_point: np.ndarray = field(default_factory=lambda: np.array([]))
40
+ block_size: int = 1
41
+ axis: int = 1
42
+ original_shape: Tuple = field(default_factory=tuple)
43
+ quantization_error: np.ndarray = field(default_factory=lambda: np.array([]))
44
+
45
+
46
+ @dataclass
47
+ class LayerParams:
48
+ weights: np.ndarray = field(default_factory=lambda: np.array([]))
49
+ bias: Optional[np.ndarray] = None
50
+
51
+
52
+ def closest_divisor(number: int, divisor: int) -> int:
53
+ for d in range(divisor, 0, -1):
54
+ if number % d == 0:
55
+ return d
56
+ return 1
57
+
58
+
59
+ def block_dequantize_tensor(
60
+ x: np.ndarray, block_axis: int, scale: np.ndarray, zero_point: np.ndarray
61
+ ) -> np.ndarray:
62
+ repeats = x.shape[block_axis] // scale.shape[block_axis]
63
+
64
+ x_scale_elementwise = np.repeat(scale, repeats=repeats, axis=block_axis)
65
+ x_zero_point_elementwise = np.repeat(zero_point, repeats=repeats, axis=block_axis)
66
+
67
+ y = (
68
+ x.astype(np.float32) - x_zero_point_elementwise.astype(np.float32)
69
+ ) * x_scale_elementwise
70
+
71
+ return y
72
+
73
+
74
+ def block_quantize_tensor(
75
+ x: np.ndarray,
76
+ block_axis: int,
77
+ scale: np.ndarray,
78
+ zero_point: np.ndarray,
79
+ n_bits: int,
80
+ ) -> np.ndarray:
81
+ repeats = x.shape[block_axis] // scale.shape[block_axis]
82
+
83
+ y_scale_elementwise = np.repeat(scale, repeats=repeats, axis=block_axis)
84
+ y_zero_point_elementwise = np.repeat(zero_point, repeats=repeats, axis=block_axis)
85
+
86
+ y = np.rint(x / y_scale_elementwise + y_zero_point_elementwise).astype(
87
+ BITS_TO_NUMPY_TYPE[n_bits]
88
+ )
89
+
90
+ return y
91
+
92
+
93
+ def create_dequantize_node(
94
+ node_name,
95
+ quantized_weights,
96
+ scales,
97
+ zero_point,
98
+ dequantized_weights,
99
+ block_size,
100
+ axis,
101
+ ) -> onnx.NodeProto:
102
+ block_size_attr = helper.make_attribute("block_size", block_size)
103
+ axis_attr = helper.make_attribute("axis", axis)
104
+
105
+ n = helper.make_node(
106
+ "DequantizeLinear",
107
+ inputs=[quantized_weights, scales, zero_point],
108
+ outputs=[dequantized_weights],
109
+ name=node_name,
110
+ )
111
+ n.attribute.extend([block_size_attr, axis_attr])
112
+ return n
113
+
114
+
115
+ def create_reshape_node(
116
+ node_name, dequantized_weights, shape_tensor, reshaped_weights_name
117
+ ) -> onnx.NodeProto:
118
+ return helper.make_node(
119
+ "Reshape",
120
+ inputs=[dequantized_weights, shape_tensor],
121
+ outputs=[reshaped_weights_name],
122
+ name=node_name,
123
+ )
124
+
125
+
126
+ class BlockQuantizer:
127
+ def __init__(self, conf: BlockQuantizeConfig) -> None:
128
+ self.conf = conf
129
+ self.validate_conf()
130
+
131
+ self.model = onnx.load(conf.input_model_path)
132
+
133
+ if self.model.opset_import[0].version != ONNX_OPSET:
134
+ self.model = onnx.version_converter.convert_version(self.model, ONNX_OPSET)
135
+
136
+ self.graph = self.model.graph
137
+ self.initializers_map = {
138
+ init.name: init for init in self.model.graph.initializer
139
+ }
140
+
141
+ def validate_conf(self):
142
+ if not os.path.isfile(self.conf.input_model_path):
143
+ raise ValueError(
144
+ f"Input model path '{self.conf.input_model_path}' does not exist or is not a file."
145
+ )
146
+
147
+ if not self.conf.input_model_path.lower().endswith(".onnx"):
148
+ raise ValueError(
149
+ f"Input model path '{self.conf.input_model_path}' must have a .onnx extension."
150
+ )
151
+
152
+ if not self.conf.output_model_path.lower().endswith(".onnx"):
153
+ raise ValueError(
154
+ f"Output model path '{self.conf.output_model_path}' must have a .onnx extension."
155
+ )
156
+
157
+ if self.conf.block_size <= 0:
158
+ raise ValueError("Block size must be a positive integer.")
159
+
160
+ if self.conf.bits not in BITS_TO_NUMPY_TYPE:
161
+ allowed_values = ", ".join([str(k) for k in BITS_TO_NUMPY_TYPE.keys()])
162
+ raise ValueError(
163
+ f"Bits must be one of the following values: [{allowed_values}]."
164
+ )
165
+
166
+ def get_initializer_tensor(self, name: str) -> Optional[np.ndarray]:
167
+ if name in self.initializers_map:
168
+ return onnx.numpy_helper.to_array(self.initializers_map[name])
169
+
170
+ return None
171
+
172
+ def get_layer_params(self, node: onnx.NodeProto) -> LayerParams:
173
+ params = LayerParams()
174
+
175
+ weights_name = node.input[1]
176
+ params.weights = self.get_initializer_tensor(weights_name)
177
+
178
+ if len(node.input) > 2:
179
+ bias_name = node.input[2]
180
+ params.bias = self.get_initializer_tensor(bias_name)
181
+
182
+ return params
183
+
184
+ def compute_scale_zeropoint(
185
+ self, b_min: np.ndarray, b_max: np.ndarray
186
+ ) -> Tuple[np.ndarray, np.ndarray]:
187
+ assert (
188
+ b_min < b_max
189
+ ).all(), (
190
+ "minimum must be lower than maximum when computing scale and zero point"
191
+ )
192
+
193
+ # zero must be present in the range, this enforces qmin <= zero_point <= qmax
194
+ b_min = np.minimum(b_min, np.zeros_like(b_min, dtype=b_min.dtype))
195
+ b_max = np.maximum(b_max, np.zeros_like(b_max, dtype=b_max.dtype))
196
+
197
+ qmin = np.iinfo(BITS_TO_NUMPY_TYPE[self.conf.bits]).min
198
+ qmax = np.iinfo(BITS_TO_NUMPY_TYPE[self.conf.bits]).max
199
+
200
+ dq = qmax - qmin
201
+
202
+ scales = (b_max - b_min) / dq
203
+ zeropoints = np.rint(qmin - b_min / scales).astype(
204
+ BITS_TO_NUMPY_TYPE[self.conf.bits]
205
+ )
206
+
207
+ return (scales, zeropoints)
208
+
209
+ def block_quantize(self, weight: np.ndarray) -> BlockQuantizeResult:
210
+ original_shape = weight.shape
211
+ weight = weight.reshape((weight.shape[0], -1))
212
+
213
+ quantization_axis = 1
214
+
215
+ block_size = closest_divisor(weight.shape[1], self.conf.block_size)
216
+
217
+ assert (
218
+ weight.shape[1] % block_size == 0
219
+ ), f"weight shape ({weight.shape[1]}) must be divisible by block size ({block_size})"
220
+
221
+ # Warning, axis = 1 specific instruction!
222
+ blocked_weight = weight.reshape(
223
+ (weight.shape[0], weight.shape[1] // block_size, -1)
224
+ )
225
+
226
+ # Warning, axis = 1 specific instruction!
227
+ blocked_max = np.max(blocked_weight, -1)
228
+ # Warning, axis = 1 specific instruction!
229
+ blocked_min = np.min(blocked_weight, -1)
230
+
231
+ scales, zeropoints = self.compute_scale_zeropoint(blocked_min, blocked_max)
232
+
233
+ quantized_weight = block_quantize_tensor(
234
+ weight, quantization_axis, scales, zeropoints, self.conf.bits
235
+ )
236
+ reconstructed_mat = block_dequantize_tensor(
237
+ quantized_weight, quantization_axis, scales, zeropoints
238
+ )
239
+
240
+ qerror = np.linalg.norm(reconstructed_mat - weight)
241
+
242
+ res = BlockQuantizeResult(
243
+ quantized_weight,
244
+ scales,
245
+ zeropoints,
246
+ block_size,
247
+ quantization_axis,
248
+ original_shape,
249
+ qerror,
250
+ )
251
+
252
+ return res
253
+
254
+ def get_model_size(self, model_path: str) -> float:
255
+ size_bytes = os.path.getsize(model_path)
256
+ size_mb = size_bytes / 1024
257
+
258
+ return size_mb
259
+
260
+ def display_summary(self, sqe: List):
261
+ mse = sum(sqe) / len(sqe)
262
+ original_model_size = self.get_model_size(self.conf.input_model_path)
263
+ quantized_model_size = self.get_model_size(self.conf.output_model_path)
264
+
265
+ print("Done! Results saved in", self.conf.output_model_path)
266
+ print("\nSummary of Results:\n")
267
+ print(f"{'Metric':<30} {'Value':<10}")
268
+ print(f"{'-'*40}")
269
+ print(f"{'Mean Squared Quantization Error':<30} {mse:.6f}")
270
+ print(f"{'Original Model Size (KB)':<31} {original_model_size:,.2f}")
271
+ print(f"{'Block-Quantized Model Size (KB)':<30} {quantized_model_size:,.2f}")
272
+
273
+ def run(self):
274
+ print("Quantizing the model...")
275
+
276
+ visited_nodes = []
277
+ sqe = []
278
+
279
+ for node in self.model.graph.node:
280
+ if node.name in visited_nodes:
281
+ continue
282
+ if node.op_type in SUPPORTED_OPS:
283
+ conv_params = self.get_layer_params(node)
284
+ block_quantize_res = self.block_quantize(conv_params.weights)
285
+
286
+ quantized_weights_name = f"{node.name}_quantized_weights"
287
+ quantized_node_name = f"{node.name}_quantized_node"
288
+ dequantized_weights_name = f"{node.name}_dequantized_weights"
289
+ scales_name = f"{node.name}_scales"
290
+ zero_point_name = f"{node.name}_zero_point"
291
+
292
+ shape_node_name = f"{node.name}_shape_node"
293
+ shape_name = f"{node.name}_shape"
294
+ reshaped_weights_name = f"{node.name}_reshaped_weights"
295
+
296
+ dequantize_node = create_dequantize_node(
297
+ quantized_node_name,
298
+ quantized_weights_name,
299
+ scales_name,
300
+ zero_point_name,
301
+ dequantized_weights_name,
302
+ block_quantize_res.block_size,
303
+ block_quantize_res.axis,
304
+ )
305
+ reshape_node = create_reshape_node(
306
+ shape_node_name,
307
+ dequantized_weights_name,
308
+ shape_name,
309
+ reshaped_weights_name,
310
+ )
311
+
312
+ shape_tensor = onnx.numpy_helper.from_array(
313
+ np.array(block_quantize_res.original_shape), name=shape_name
314
+ )
315
+ scale_initializer = onnx.numpy_helper.from_array(
316
+ block_quantize_res.scales, name=scales_name
317
+ )
318
+ zero_point_initializer = onnx.numpy_helper.from_array(
319
+ block_quantize_res.zero_point, name=zero_point_name
320
+ )
321
+ quantized_weights_initializer = onnx.numpy_helper.from_array(
322
+ block_quantize_res.quantized_weights, name=quantized_weights_name
323
+ )
324
+
325
+ dequantized_weights_info = helper.make_tensor_value_info(
326
+ dequantized_weights_name,
327
+ onnx.TensorProto.FLOAT,
328
+ block_quantize_res.quantized_weights.shape,
329
+ )
330
+ shape_info = helper.make_tensor_value_info(
331
+ reshaped_weights_name,
332
+ onnx.TensorProto.FLOAT,
333
+ block_quantize_res.original_shape,
334
+ )
335
+
336
+ self.graph.initializer.extend(
337
+ [
338
+ scale_initializer,
339
+ zero_point_initializer,
340
+ shape_tensor,
341
+ quantized_weights_initializer,
342
+ ]
343
+ )
344
+
345
+ # Removing fp32 weights
346
+ self.graph.initializer.remove(
347
+ next(
348
+ init
349
+ for init in self.graph.initializer
350
+ if init.name == node.input[1]
351
+ )
352
+ )
353
+ node.input[1] = reshaped_weights_name
354
+
355
+ # Preserving the topological order of graph nodes
356
+ self.graph.node.insert(0, reshape_node)
357
+ self.graph.node.insert(0, dequantize_node)
358
+ self.graph.value_info.insert(0, shape_info)
359
+ self.graph.value_info.insert(0, dequantized_weights_info)
360
+
361
+ sqe.append(block_quantize_res.quantization_error**2)
362
+ visited_nodes.append(node.name)
363
+
364
+ onnx.checker.check_model(self.model, full_check=True)
365
+ onnx.save(self.model, self.conf.output_model_path)
366
+
367
+ self.display_summary(sqe)
368
+
369
+
370
+ def setup_args() -> argparse.Namespace:
371
+ parser = argparse.ArgumentParser(description="Blockwise quantization tool")
372
+
373
+ parser.add_argument(
374
+ "-i",
375
+ "--input_model",
376
+ type=str,
377
+ help="The path of onnx model to quantize",
378
+ required=True,
379
+ )
380
+ parser.add_argument(
381
+ "-bs",
382
+ "--block_size",
383
+ type=int,
384
+ help="The maximum size of quantization block",
385
+ required=True,
386
+ )
387
+ parser.add_argument(
388
+ "-b",
389
+ "--bits",
390
+ type=int,
391
+ help="Quantization bits",
392
+ choices=[8, 16],
393
+ default=8,
394
+ required=False,
395
+ )
396
+ parser.add_argument(
397
+ "-o",
398
+ "--output_model",
399
+ type=str,
400
+ help="The output model path",
401
+ default="block_quantized_model.onnx",
402
+ required=False,
403
+ )
404
+
405
+ return parser.parse_args()
406
+
407
+
408
+ if __name__ == "__main__":
409
+ args = setup_args()
410
+
411
+ quantization_config = BlockQuantizeConfig(
412
+ input_model_path=args.input_model,
413
+ output_model_path=args.output_model,
414
+ block_size=args.block_size,
415
+ bits=args.bits,
416
+ )
417
+
418
+ quantizer = BlockQuantizer(quantization_config)
419
+ quantizer.run()
tools/quantize/requirements.txt CHANGED
@@ -1,4 +1,5 @@
1
  opencv-python>=4.10.0
 
2
  onnx
3
  onnxruntime
4
  onnxruntime-extensions
 
1
  opencv-python>=4.10.0
2
+ numpy
3
  onnx
4
  onnxruntime
5
  onnxruntime-extensions