Исходный код СУБД RuDB — свободной СУБД с открытым исходным кодом на базе PostgreSQL
rudb
2 days ago bd039d1e92813358c5c5a1e346b49074baf513f2
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
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
#!/usr/bin/env python
# -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
from __future__ import annotations
 
import os
import tempfile
import unittest
 
import numpy as np
import onnx
from op_test_utils import TestDataFeeds, check_model_correctness, check_op_type_count
 
from onnxruntime.quantization import CalibrationMethod, QuantFormat, QuantType, get_qdq_config, quantize
from onnxruntime.quantization.quant_utils import get_opset_version
 
 
class TestGetQDQConfig(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        cls._tmp_model_dir = tempfile.TemporaryDirectory(prefix="ort.int_qdq_config_")
 
        # Note: swap with the commented line if you want to see the models in local test dir.
        cls._tmp_dir_path = cls._tmp_model_dir.name
        # cls._tmp_dir_path = "."
 
    @classmethod
    def tearDownClass(cls):
        cls._tmp_model_dir.cleanup()
 
    def build_add_model(
        self,
        shape: list[int],
        tensor_type: onnx.TensorProto.DataType,
        weight: onnx.TensorProto | None = None,
        opset: int = 21,
    ) -> onnx.ModelProto:
        """
        Returns an onnx.ModelProto with a single Add operator. The second input can be optionally made
        a static weight.
        """
        graph_inputs = [onnx.helper.make_tensor_value_info("input_0", tensor_type, shape)]
        graph_outputs = [onnx.helper.make_tensor_value_info("output_0", tensor_type, shape)]
        initializers = []
        add_input_names = ["input_0"]
 
        if weight is not None:
            initializers.append(weight)
            add_input_names.append(weight.name)
        else:
            graph_inputs.append(onnx.helper.make_tensor_value_info("input_1", tensor_type, shape))
            add_input_names.append("input_1")
 
        add_node = onnx.helper.make_node("Add", add_input_names, ["output_0"], name="Add0")
 
        graph = onnx.helper.make_graph(
            [add_node],
            "AddGraph",
            graph_inputs,
            graph_outputs,
            initializer=initializers,
        )
        opset_imports = [onnx.helper.make_opsetid("", opset)]
        model = onnx.helper.make_model(graph, opset_imports=opset_imports)
        model = onnx.shape_inference.infer_shapes(model)
        onnx.checker.check_model(model, True)
        return model
 
    def test_basic_args(self):
        """
        Test that get_qdq_config() returns a config that sets the basic args.
        """
 
        shape = [1, 8, 8]
        tensor_type = onnx.TensorProto.FLOAT
        np_dtype = onnx.helper.tensor_dtype_to_np_dtype(tensor_type)
        weight = onnx.numpy_helper.from_array(np.ones(shape, dtype=np_dtype), "weight")
        float_model = self.build_add_model(shape, tensor_type, weight, opset=21)
 
        input_data_list = [
            {"input_0": np.ones(shape, dtype=np_dtype) * np.array(-2, dtype=np_dtype)},
            {"input_0": np.ones(shape, dtype=np_dtype) * np.array(2, dtype=np_dtype)},
        ]
        data_reader = TestDataFeeds(input_data_list)
 
        qdq_config = get_qdq_config(
            float_model,
            data_reader,
            calibrate_method=CalibrationMethod.Percentile,
            calibrate_args={"percentile": 99.98},  # Converted to extra_options
            activation_type=QuantType.QUInt16,
            weight_type=QuantType.QInt16,
            per_channel=True,
            reduce_range=True,
            nodes_to_exclude=["Mul"],
            # Other options converted to extra_options:
            min_real_range=0.0001,
            keep_removable_activations=True,
            activation_symmetric=True,
            weight_symmetric=True,
        )
        self.assertEqual(qdq_config.calibrate_method, CalibrationMethod.Percentile)
        self.assertEqual(qdq_config.activation_type, QuantType.QUInt16)
        self.assertEqual(qdq_config.weight_type, QuantType.QInt16)
        self.assertTrue(qdq_config.per_channel)
        self.assertTrue(qdq_config.reduce_range)
        self.assertEqual(set(qdq_config.nodes_to_exclude), {"Mul"})
        self.assertEqual(set(qdq_config.op_types_to_quantize), {"Add"})
 
        # Check that calibration args are translated to extra_options.
        self.assertEqual(qdq_config.extra_options["CalibPercentile"], 99.98)
 
        # Check that other args are also translated to extra_options.
        self.assertEqual(qdq_config.extra_options["MinimumRealRange"], 0.0001)
        self.assertTrue(qdq_config.extra_options["QDQKeepRemovableActivations"])
        self.assertTrue(qdq_config.extra_options["ActivationSymmetric"])
        self.assertTrue(qdq_config.extra_options["WeightSymmetric"])
 
        # The following options should always be set to specific values.
        self.assertTrue(qdq_config.extra_options["ForceQuantizeNoInputCheck"])
        self.assertEqual(qdq_config.quant_format, QuantFormat.QDQ)
 
        # Should use onnx domain Q/DQ ops because onnx opset >= 21.
        self.assertFalse(qdq_config.extra_options.get("UseQDQContribOps", False))
 
    def test_exclude_nodes_callable(self):
        """
        Test passing a function/callable to exclude nodes from quantization.
        """
 
        shape = [1, 8, 8]
        tensor_type = onnx.TensorProto.FLOAT
        np_dtype = onnx.helper.tensor_dtype_to_np_dtype(tensor_type)
        weight = onnx.numpy_helper.from_array(np.ones(shape, dtype=np_dtype), "weight")
        float_model = self.build_add_model(shape, tensor_type, weight, opset=21)
 
        input_data_list = [
            {"input_0": np.ones(shape, dtype=np_dtype) * np.array(-2, dtype=np_dtype)},
            {"input_0": np.ones(shape, dtype=np_dtype) * np.array(2, dtype=np_dtype)},
        ]
        data_reader = TestDataFeeds(input_data_list)
 
        # Local function that excludes all "Add" nodes.
        def should_exclude_node_(model: onnx.ModelProto, node: onnx.NodeProto) -> bool:
            return node.op_type == "Add"
 
        qdq_config = get_qdq_config(
            float_model,
            data_reader,
            nodes_to_exclude=should_exclude_node_,
        )
 
        expected_excluded_nodes = {node.name for node in float_model.graph.node if node.op_type == "Add"}
        self.assertTrue(bool(expected_excluded_nodes))
        self.assertEqual(set(qdq_config.nodes_to_exclude), expected_excluded_nodes)
 
    def test_op_types_to_quantize(self):
        """
        Test that get_qdq_config() returns a config that sets the op_types_to_quantize arg.
        """
        shape = [1, 8, 8]
        tensor_type = onnx.TensorProto.FLOAT
        np_dtype = onnx.helper.tensor_dtype_to_np_dtype(tensor_type)
        weight = onnx.numpy_helper.from_array(np.ones(shape, dtype=np_dtype), "weight")
        float_model = self.build_add_model(shape, tensor_type, weight)
 
        input_data_list = [
            {"input_0": np.ones(shape, dtype=np_dtype) * np.array(-2, dtype=np_dtype)},
            {"input_0": np.ones(shape, dtype=np_dtype) * np.array(2, dtype=np_dtype)},
        ]
        data_reader = TestDataFeeds(input_data_list)
 
        # No op_types_to_quantize arg means all ops are quantized.
        qdq_config = get_qdq_config(float_model, data_reader, op_types_to_quantize=None)
        self.assertEqual(set(qdq_config.op_types_to_quantize), {"Add"})
 
        # specify custom op_types_to_quantize arg.
        qdq_config = get_qdq_config(float_model, data_reader, op_types_to_quantize=["Mul"])
        self.assertEqual(set(qdq_config.op_types_to_quantize), {"Mul"})
 
        # exclude op_type indirectly by specifying nodes_to_exclude arg.
        qdq_config = get_qdq_config(
            float_model,
            data_reader,
            nodes_to_exclude=[node.name for node in float_model.graph.node if node.op_type == "Add"],
        )
        self.assertEqual(set(qdq_config.op_types_to_quantize), set())
 
    def test_calibration_providers(self):
        """
        Test that get_qdq_config() returns a config that sets the calibration providers arg.
        """
 
        shape = [1, 8, 8]
        tensor_type = onnx.TensorProto.FLOAT
        np_dtype = onnx.helper.tensor_dtype_to_np_dtype(tensor_type)
        weight = onnx.numpy_helper.from_array(np.ones(shape, dtype=np_dtype), "weight")
        float_model = self.build_add_model(shape, tensor_type, weight)
 
        input_data_list = [
            {"input_0": np.ones(shape, dtype=np_dtype) * np.array(-2, dtype=np_dtype)},
            {"input_0": np.ones(shape, dtype=np_dtype) * np.array(2, dtype=np_dtype)},
        ]
        data_reader = TestDataFeeds(input_data_list)
 
        qdq_config = get_qdq_config(
            float_model,
            data_reader,
            calibration_providers=["CPUExecutionProvider"],
        )
        self.assertEqual(qdq_config.calibration_providers, ["CPUExecutionProvider"])
 
    def test_external_data(self):
        """
        Test that get_qdq_config() returns a config that enables external data
        if the input model has external data.
        """
 
        # Create model with a weight large enough (> 1024 bytes) to be stored externally.
        shape = [1, 32, 32]
        tensor_type = onnx.TensorProto.FLOAT
        np_dtype = onnx.helper.tensor_dtype_to_np_dtype(tensor_type)
        large_weight = onnx.numpy_helper.from_array(np.ones(shape, dtype=np_dtype), "weight")
        float_model = self.build_add_model(shape, tensor_type, large_weight)
        float_model_path = os.path.join(self._tmp_dir_path, "add_ext_data_int_qdq_config.onnx")
 
        onnx.save_model(
            float_model,
            float_model_path,
            save_as_external_data=True,
            all_tensors_to_one_file=True,
            location="add_ext_data_int_qdq_config.bin",
        )
 
        input_data_list = [
            {"input_0": np.ones(shape, dtype=np_dtype) * np.array(-2, dtype=np_dtype)},
            {"input_0": np.ones(shape, dtype=np_dtype) * np.array(0, dtype=np_dtype)},
            {"input_0": np.ones(shape, dtype=np_dtype) * np.array(2, dtype=np_dtype)},
        ]
        data_reader = TestDataFeeds(input_data_list)
 
        # Create a quantization config and check that it sets boolean to use external data
        qdq_config = get_qdq_config(
            float_model_path, data_reader, activation_type=QuantType.QUInt8, weight_type=QuantType.QInt8
        )
        self.assertEqual(set(qdq_config.op_types_to_quantize), {"Add"})
        self.assertTrue(qdq_config.use_external_data_format)
 
        # Quantize the model and check computational correctness against float model.
        qdq_model_path = os.path.join(self._tmp_dir_path, "add_ext_data_int_qdq_config.qdq.onnx")
        quantize(float_model_path, qdq_model_path, qdq_config)
 
        expected_op_counts = {"DequantizeLinear": 3, "QuantizeLinear": 2, "Add": 1}
        check_op_type_count(self, qdq_model_path, **expected_op_counts)
 
        data_reader.rewind()
        check_model_correctness(self, float_model_path, qdq_model_path, data_reader.get_next())
 
        # The quantized weight should still be stored in an external file.
        qdq_model = onnx.load_model(qdq_model_path, load_external_data=False)
        weight_quantized = next(
            (
                initializer
                for initializer in qdq_model.graph.initializer
                if initializer.name == f"{large_weight.name}_quantized"
            ),
            None,
        )
        self.assertIsNotNone(weight_quantized)
        self.assertEqual(weight_quantized.data_location, onnx.TensorProto.EXTERNAL)
 
    def test_no_qdq_contrib_ops_for_int16_opset_lt21(self):
        """
        Test that get_qdq_config() does NOT set UseQDQContribOps for int16 types even when
        the model opset is < 21.  quantize_static() will bump the opset to 21 automatically,
        where native ONNX QuantizeLinear/DequantizeLinear supports INT16/UINT16, so contrib-
        domain ops are not needed.
        """
 
        shape = [1, 8, 8]
        tensor_type = onnx.TensorProto.FLOAT
        np_dtype = onnx.helper.tensor_dtype_to_np_dtype(tensor_type)
        weight = onnx.numpy_helper.from_array(np.ones(shape, dtype=np_dtype), "weight")
        float_model = self.build_add_model(shape, tensor_type, weight, opset=19)
 
        input_data_list = [
            {"input_0": np.ones(shape, dtype=np_dtype) * np.array(-2, dtype=np_dtype)},
            {"input_0": np.ones(shape, dtype=np_dtype) * np.array(2, dtype=np_dtype)},
        ]
        data_reader = TestDataFeeds(input_data_list)
 
        qdq_config = get_qdq_config(
            float_model,
            data_reader,
            activation_type=QuantType.QUInt16,
            weight_type=QuantType.QInt8,
        )
 
        self.assertEqual(qdq_config.activation_type, QuantType.QUInt16)
        # UseQDQContribOps must NOT be auto-set for 16-bit types; the opset bump handles them.
        self.assertFalse(qdq_config.extra_options.get("UseQDQContribOps", False))
 
    def test_quantize_via_config_int16_opset_lt21_uses_native_qdq(self):
        """
        Test that the config-based quantize() path produces a model at opset 21 using native
        ONNX QuantizeLinear/DequantizeLinear (not com.microsoft domain) when int16 activation
        types are requested on a model whose original opset is < 21.
        """
 
        shape = [1, 8, 8]
        tensor_type = onnx.TensorProto.FLOAT
        np_dtype = onnx.helper.tensor_dtype_to_np_dtype(tensor_type)
        weight = onnx.numpy_helper.from_array(np.ones(shape, dtype=np_dtype), "weight")
        # Build a model at opset 20 (< 21) with int16 activation type
        float_model = self.build_add_model(shape, tensor_type, weight, opset=20)
 
        input_data_list = [
            {"input_0": np.ones(shape, dtype=np_dtype) * np.array(-2, dtype=np_dtype)},
            {"input_0": np.ones(shape, dtype=np_dtype) * np.array(2, dtype=np_dtype)},
        ]
        data_reader = TestDataFeeds(input_data_list)
 
        qdq_config = get_qdq_config(
            float_model,
            data_reader,
            activation_type=QuantType.QUInt16,
            weight_type=QuantType.QInt8,
        )
 
        qdq_model_path = os.path.join(self._tmp_dir_path, "add_int16_opset20_qdq.onnx")
        quantize(float_model, qdq_model_path, qdq_config)
 
        qdq_model = onnx.load_model(qdq_model_path)
 
        # The quantized model must have been bumped to opset 21.
        onnx_opset_version = get_opset_version(qdq_model)
        self.assertEqual(onnx_opset_version, 21)
 
        # All Q/DQ nodes must use the default ONNX domain (not com.microsoft).
        for node in qdq_model.graph.node:
            if node.op_type in ("QuantizeLinear", "DequantizeLinear"):
                self.assertEqual(
                    node.domain,
                    "",
                    f"Expected native ONNX domain for {node.op_type} but got '{node.domain}'",
                )
 
    def test_use_qdq_contrib_ops_for_int4_opset19(self):
        """
        Test that get_qdq_config() returns a config that forces 'com.microsoft' Q/DQ ops for
        use of int4 in opset < 21.
        """
 
        shape = [1, 8, 8]
        tensor_type = onnx.TensorProto.FLOAT
        np_dtype = onnx.helper.tensor_dtype_to_np_dtype(tensor_type)
        weight = onnx.numpy_helper.from_array(np.ones(shape, dtype=np_dtype), "weight")
        float_model = self.build_add_model(shape, tensor_type, weight, opset=19)
 
        input_data_list = [
            {"input_0": np.ones(shape, dtype=np_dtype) * np.array(-2, dtype=np_dtype)},
            {"input_0": np.ones(shape, dtype=np_dtype) * np.array(2, dtype=np_dtype)},
        ]
        data_reader = TestDataFeeds(input_data_list)
 
        # Use int4 in tensor quantization overrides. This should still force use of 'com.microsoft' Q/DQ ops.
        qdq_config = get_qdq_config(
            float_model,
            data_reader,
            activation_type=QuantType.QUInt8,
            weight_type=QuantType.QInt8,
            tensor_quant_overrides={"weight": [{"quant_type": QuantType.QInt4}]},
        )
 
        self.assertEqual(qdq_config.extra_options["TensorQuantOverrides"]["weight"][0]["quant_type"], QuantType.QInt4)
        self.assertTrue(qdq_config.extra_options["UseQDQContribOps"])
 
    def test_overrides_16bit_opset_lt21_bumps_opset_no_contrib_ops(self):
        """
        Regression test: when TensorQuantOverrides request a 16-bit type on a model whose opset is
        < 21, the quantized model must be bumped to opset 21 and UseQDQContribOps must NOT be set.
        """
 
        shape = [1, 8, 8]
        tensor_type = onnx.TensorProto.FLOAT
        np_dtype = onnx.helper.tensor_dtype_to_np_dtype(tensor_type)
        weight = onnx.numpy_helper.from_array(np.ones(shape, dtype=np_dtype), "weight")
        # Build a model at opset 18 (< 21) so the opset bump is required.
        float_model = self.build_add_model(shape, tensor_type, weight, opset=18)
 
        input_data_list = [
            {"input_0": np.ones(shape, dtype=np_dtype) * np.array(-2, dtype=np_dtype)},
            {"input_0": np.ones(shape, dtype=np_dtype) * np.array(2, dtype=np_dtype)},
        ]
        data_reader = TestDataFeeds(input_data_list)
 
        # Override the weight to use QUInt16 via TensorQuantOverrides; top-level types are 8-bit.
        qdq_config = get_qdq_config(
            float_model,
            data_reader,
            activation_type=QuantType.QUInt8,
            weight_type=QuantType.QInt8,
            tensor_quant_overrides={"weight": [{"quant_type": QuantType.QUInt16}]},
        )
 
        # UseQDQContribOps must NOT be set: the 16-bit override triggers an opset bump to 21,
        # where native ONNX Q/DQ ops handle all types.
        self.assertFalse(qdq_config.extra_options.get("UseQDQContribOps", False))
 
        qdq_model_path = os.path.join(self._tmp_dir_path, "add_override_uint16_opset18_qdq.onnx")
        quantize(float_model, qdq_model_path, qdq_config)
 
        qdq_model = onnx.load_model(qdq_model_path)
 
        # The quantized model must have been bumped to opset 21.
        onnx_opset_version = get_opset_version(qdq_model)
        self.assertEqual(onnx_opset_version, 21)
 
        # All Q/DQ nodes must use the default ONNX domain (not com.microsoft).
        for node in qdq_model.graph.node:
            if node.op_type in ("QuantizeLinear", "DequantizeLinear"):
                self.assertEqual(
                    node.domain,
                    "",
                    f"Expected native ONNX domain for {node.op_type} but got '{node.domain}'",
                )
 
    def test_overrides_mixed_16bit_4bit_opset_lt21_no_contrib_ops(self):
        """
        Regression test: when TensorQuantOverrides contain both a 16-bit type (for one tensor) and
        a 4-bit type (for another tensor) on a model whose opset is < 21, UseQDQContribOps must NOT
        be set because the 16-bit override triggers an opset bump to 21 where all types are native.
        """
 
        shape = [1, 8, 8]
        tensor_type = onnx.TensorProto.FLOAT
        np_dtype = onnx.helper.tensor_dtype_to_np_dtype(tensor_type)
        weight = onnx.numpy_helper.from_array(np.ones(shape, dtype=np_dtype), "weight")
        # Build a model at opset 18 (< 21).
        float_model = self.build_add_model(shape, tensor_type, weight, opset=18)
 
        input_data_list = [
            {"input_0": np.ones(shape, dtype=np_dtype) * np.array(-2, dtype=np_dtype)},
            {"input_0": np.ones(shape, dtype=np_dtype) * np.array(2, dtype=np_dtype)},
        ]
        data_reader = TestDataFeeds(input_data_list)
 
        # Override: weight uses QUInt16 (16-bit, triggers opset bump), input_0 uses QInt4 (4-bit).
        # The presence of the 16-bit override means the model is bumped to opset 21, so native
        # Q/DQ ops handle everything — UseQDQContribOps must NOT be set.
        qdq_config = get_qdq_config(
            float_model,
            data_reader,
            activation_type=QuantType.QUInt8,
            weight_type=QuantType.QInt8,
            tensor_quant_overrides={
                "weight": [{"quant_type": QuantType.QUInt16}],
                "input_0": [{"quant_type": QuantType.QInt4}],
            },
        )
 
        # UseQDQContribOps must NOT be set: the 16-bit override triggers an opset bump to 21,
        # making native Q/DQ ops sufficient for all types including the 4-bit one.
        self.assertFalse(qdq_config.extra_options.get("UseQDQContribOps", False))
 
        qdq_model_path = os.path.join(self._tmp_dir_path, "add_mixed_16bit_4bit_opset18_qdq.onnx")
        quantize(float_model, qdq_model_path, qdq_config)
 
        qdq_model = onnx.load_model(qdq_model_path)
 
        # The quantized model must have been bumped to opset 21.
        onnx_opset_version = get_opset_version(qdq_model)
        self.assertGreaterEqual(onnx_opset_version, 21)
 
        # All Q/DQ nodes must use the default ONNX domain (not com.microsoft).
        for node in qdq_model.graph.node:
            if node.op_type in ("QuantizeLinear", "DequantizeLinear"):
                self.assertEqual(
                    node.domain,
                    "",
                    f"Expected native ONNX domain for {node.op_type} but got '{node.domain}'",
                )
 
 
if __name__ == "__main__":
    unittest.main()