Исходный код СУБД 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
#!/usr/bin/env python
"""
Softmax quantization test case
"""
# coding: utf-8
# -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
 
import unittest
from pathlib import Path
 
import numpy as np
import onnx
from onnx import TensorProto, helper, numpy_helper
from op_test_utils import TestDataFeeds, check_model_correctness, check_op_type_count, check_qtype_by_node_type
 
from onnxruntime.quantization import QuantFormat, QuantType, quantize_static
 
 
class TestOpSoftmax(unittest.TestCase):
    """_summary_
    unittest (softmax): quantization of QDQ and Qop with u8 and s8
    """
 
    def input_feeds(self, n_repeat, name2shape):
        input_data_list = []
        for _ in range(n_repeat):
            inputs = {}
            for name, shape in name2shape.items():
                inputs.update({name: np.random.randint(-1, 2, shape).astype(np.float32)})
            input_data_list.extend([inputs])
        data_r = TestDataFeeds(input_data_list)
        return data_r
 
    def construct_model_conv_softmax(
        self,
        output_model_path,
        conv_input_shape,
        conv_weight_shape,
        softmax_input_shape,
        softmax_attributes,
        output_shape,
        add_ms_domain_opset=False,
    ):
        #      (input)
        #          \
        #         Conv
        #        /    \
        #   Identity  Softmax
        #    /            \
        # (identity_out)  (output)
        input_tensor = helper.make_tensor_value_info("input", TensorProto.FLOAT, conv_input_shape)
 
        conv_weight_arr = np.random.randint(-1, 2, conv_weight_shape).astype(np.float32)
        conv_weight_initializer = onnx.numpy_helper.from_array(conv_weight_arr, name="conv1_weight")
        conv_node = onnx.helper.make_node("Conv", ["input", "conv1_weight"], ["conv_output"], name="conv_node")
 
        identity_out = helper.make_tensor_value_info("identity_out", TensorProto.FLOAT, softmax_input_shape)
        identity_node = helper.make_node("Identity", ["conv_output"], ["identity_out"], name="IdentityNode")
 
        initializers = [conv_weight_initializer]
 
        output_tensor = helper.make_tensor_value_info("output", TensorProto.FLOAT, output_shape)
        softmax_node = helper.make_node(
            "Softmax", ["conv_output"], ["output"], name="softmax_node", **softmax_attributes
        )
 
        graph = helper.make_graph(
            [conv_node, identity_node, softmax_node],
            "TestOpQuantizersoftmax_test_model",
            [input_tensor],
            [identity_out, output_tensor],
            initializer=initializers,
        )
 
        opset_imports = [helper.make_opsetid("", 13)]
        if add_ms_domain_opset:
            opset_imports.append(helper.make_opsetid("com.microsoft", 1))
 
        model = helper.make_model(graph, opset_imports=opset_imports)
        model.ir_version = 7  # use stable onnx ir version
        onnx.save(model, output_model_path)
 
    def quantize_softmax_test_qop(self, activation_type, weight_type, extra_options={}):  # noqa: B006
        np.random.seed(1)
        model_fp32_path = "softmax_fp32.onnx"
        self.construct_model_conv_softmax(
            model_fp32_path,
            [1, 2, 26, 42],
            [3, 2, 3, 3],
            [1, 3, 24, 40],
            {"axis": -2},
            [1, 3, 24, 40],
        )
        data_reader = self.input_feeds(1, {"input": [1, 2, 26, 42]})
 
        activation_proto_qtype = activation_type.tensor_type
        activation_type_str = str(activation_type)
        weight_type_str = str(weight_type)
        model_q8_path = f"softmax_{activation_type_str}{weight_type_str}.onnx"
 
        # Verify QOperator mode
        data_reader.rewind()
        quantize_static(
            model_fp32_path,
            model_q8_path,
            data_reader,
            quant_format=QuantFormat.QOperator,
            activation_type=activation_type,
            weight_type=weight_type,
            extra_options=extra_options,
        )
        qnode_counts = {
            "QLinearConv": 1,
            "QuantizeLinear": 1,
            "DequantizeLinear": 2,
            "QLinearSoftmax": 1,
            "Softmax": 0,
        }
        check_op_type_count(self, model_q8_path, **qnode_counts)
        qnode_io_qtypes = {
            "QuantizeLinear": [
                ["i", 2, activation_proto_qtype],
                ["o", 0, activation_proto_qtype],
            ]
        }
        qnode_io_qtypes.update(
            {
                "QLinearConv": [
                    ["i", 2, activation_proto_qtype],
                    ["i", 7, activation_proto_qtype],
                    ["o", 0, activation_proto_qtype],
                ]
            }
        )
        qnode_io_qtypes.update(
            {"QLinearSoftmax": [["i", 4, activation_proto_qtype]]}
        )  # shape info note workig on custome ops
        check_qtype_by_node_type(self, model_q8_path, qnode_io_qtypes)
        data_reader.rewind()
        check_model_correctness(self, model_fp32_path, model_q8_path, data_reader.get_next())
 
    def quantize_softmax_test_qdq(self, activation_type, weight_type, extra_options={}):  # noqa: B006
        np.random.seed(1)
        model_fp32_path = "softmax_fp32.onnx"
        self.construct_model_conv_softmax(
            model_fp32_path,
            [1, 2, 26, 42],
            [3, 2, 3, 3],
            [1, 3, 24, 40],
            {"axis": -2},
            [1, 3, 24, 40],
            add_ms_domain_opset=extra_options.get("UseQDQContribOps", False),
        )
        data_reader = self.input_feeds(1, {"input": [1, 2, 26, 42]})
 
        activation_proto_qtype = activation_type.tensor_type
        activation_type_str = str(activation_type)
        weight_type_str = str(weight_type)
        model_qdq_path = f"softmax_qdq_{activation_type_str}{weight_type_str}.onnx"
 
        # Verify QDQ mode
        data_reader.rewind()
        quantize_static(
            model_fp32_path,
            model_qdq_path,
            data_reader,
            quant_format=QuantFormat.QDQ,
            activation_type=activation_type,
            weight_type=weight_type,
            extra_options=extra_options,
        )
 
        result_model = onnx.load(Path(model_qdq_path))
        qnode_cnt = 0
        dqnode_cnt = 0
        softmax_cnt = 0
        qnode_zeropoints = []
        for node in result_model.graph.node:
            if node.op_type == "QuantizeLinear":
                qnode_cnt += 1
                qnode_zeropoints.append(node.input[2])
            elif node.op_type == "DequantizeLinear":
                dqnode_cnt += 1
            elif node.op_type == "Softmax":
                softmax_cnt += 1
        self.assertEqual(3, qnode_cnt, f"Expected 3 QuantizeLinear nodes, found {qnode_cnt}")
        self.assertEqual(4, dqnode_cnt, f"Expected 4 DequantizeLinear nodes, found {dqnode_cnt}")
        self.assertEqual(1, softmax_cnt, f"Expected 1 Softmax node, found {softmax_cnt}")
        for tensor in result_model.graph.initializer:
            if tensor.name in qnode_zeropoints:
                self.assertEqual(
                    tensor.data_type,
                    activation_proto_qtype,
                    f"QuantizeLinear zero-point must be of proto type {activation_proto_qtype}, "
                    f"but found {tensor.data_type} instead.",
                )
                if extra_options.get("ActivationSymmetric", False):
                    np_value = numpy_helper.to_array(tensor)
                    self.assertEqual(
                        0,
                        np_value,
                        f"QuantizeLinear node zero point value must be 0, found {np_value} instead!",
                    )
 
        data_reader.rewind()
        check_model_correctness(self, model_fp32_path, model_qdq_path, data_reader.get_next())
 
    def test_quantize_softmax(self):
        self.quantize_softmax_test_qop(QuantType.QUInt8, QuantType.QUInt8)
        self.quantize_softmax_test_qdq(QuantType.QUInt8, QuantType.QUInt8)
 
    def test_bug_fix_exclude_softmax(self):
        """
        Test fix to bug that happens when softmax is excluded from quantization, but
        the quantization tool still tries to assign it a tensor range of [0.0, 1.0].
        """
        np.random.seed(1)
        model_fp32_path = "softmax_fp32.onnx"
        model_qdq_path = "softmax_bug_exclude_softmax.qdq.onnx"
        self.construct_model_conv_softmax(
            model_fp32_path,
            [1, 2, 26, 42],
            [3, 2, 3, 3],
            [1, 3, 24, 40],
            {"axis": -2},
            [1, 3, 24, 40],
            add_ms_domain_opset=False,
        )
        data_reader = self.input_feeds(1, {"input": [1, 2, 26, 42]})
        data_reader.rewind()
 
        # Bug would cause an exception during quantization.
        quantize_static(
            model_fp32_path,
            model_qdq_path,
            data_reader,
            quant_format=QuantFormat.QDQ,
            activation_type=QuantType.QUInt8,
            weight_type=QuantType.QInt8,
            nodes_to_exclude=["Softmax"],
        )
 
        qdq_model = onnx.load(Path(model_qdq_path))
        self.assertIn("Softmax", {node.op_type for node in qdq_model.graph.node})
 
    def test_quantize_softmax_s8s8(self):
        self.quantize_softmax_test_qop(
            QuantType.QInt8,
            QuantType.QInt8,
        )
        self.quantize_softmax_test_qdq(
            QuantType.QInt8,
            QuantType.QInt8,
        )
        self.quantize_softmax_test_qop(
            QuantType.QInt8,
            QuantType.QInt8,
            extra_options={"ActivationSymmetric": True},
        )
        self.quantize_softmax_test_qdq(
            QuantType.QInt8,
            QuantType.QInt8,
            extra_options={"ActivationSymmetric": True},
        )
 
    def test_quantize_softmax_qdq_u16u16(self):
        self.quantize_softmax_test_qdq(
            QuantType.QUInt16,
            QuantType.QUInt16,
            extra_options={"UseQDQContribOps": True},
        )
 
    def test_quantize_softmax_qdq_s16s16(self):
        self.quantize_softmax_test_qdq(
            QuantType.QInt16,
            QuantType.QInt16,
            extra_options={"UseQDQContribOps": True},
        )
        self.quantize_softmax_test_qdq(
            QuantType.QInt16,
            QuantType.QInt16,
            extra_options={"UseQDQContribOps": True, "ActivationSymmetric": True},
        )
 
 
if __name__ == "__main__":
    unittest.main()