Исходный код СУБД 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
#!/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.
# --------------------------------------------------------------------------
 
import tempfile
import unittest
from pathlib import Path
 
import numpy
import onnx
from ml_dtypes import int4, uint4
from onnx import TensorProto, helper, numpy_helper
 
from onnxruntime.quantization.quant_utils import (
    QuantType,
    compute_scale_zp,
    compute_scale_zp_float8,
    load_model_with_shape_infer,
    model_has_infer_metadata,
    pack_bytes_to_4bit,
    quantize_data,
    update_opset_version,
)
 
 
class TestQuantUtil(unittest.TestCase):
    def test_compute_scale_zp(self):
        def _compute_scale_zp(rmin, rmax, qmin, qmax, qtype, symmetric=False, min_real_range=None):
            zp, scale = compute_scale_zp(
                numpy.array(rmin, dtype=numpy.float32),
                numpy.array(rmax, dtype=numpy.float32),
                numpy.array(qmin, dtype=qtype),
                numpy.array(qmax, dtype=qtype),
                symmetric=symmetric,
                min_real_range=min_real_range,
            )
            assert isinstance(zp, numpy.ndarray)
            assert isinstance(scale, numpy.ndarray)
            return [float(zp), float(scale)]
 
        numpy.testing.assert_allclose(_compute_scale_zp(0.0, 0.0, -127, 127, numpy.int8, symmetric=True), [0, 1.0])
        numpy.testing.assert_allclose(_compute_scale_zp(1.0, -1.0, -127, 127, numpy.int8, symmetric=True), [0, 1.0])
        numpy.testing.assert_allclose(_compute_scale_zp(0.0, 0.0, 0, 255, numpy.uint8, symmetric=True), [0, 1.0])
        numpy.testing.assert_allclose(_compute_scale_zp(1.0, -1.0, 0, 255, numpy.uint8, symmetric=True), [0, 1.0])
 
        numpy.testing.assert_allclose(
            _compute_scale_zp(-1.0, 2.0, -127, 127, numpy.int8, symmetric=True), [0, numpy.float32(2.0 / 127)]
        )
        numpy.testing.assert_allclose(
            _compute_scale_zp(-1.0, 2.0, -127, 127, numpy.int8, symmetric=False), [-42, numpy.float32(3.0 / 254)]
        )
 
        numpy.testing.assert_allclose(
            _compute_scale_zp(-1.0, 2.0, 0, 255, numpy.uint8, symmetric=True), [128, numpy.float32(4.0 / 255)]
        )
        numpy.testing.assert_allclose(
            _compute_scale_zp(-1.0, 2.0, 0, 255, numpy.uint8, symmetric=False), [85, numpy.float32(3.0 / 255)]
        )
 
        tiny_float = numpy.float32(numpy.finfo(numpy.float32).tiny * 0.1)
        numpy.testing.assert_allclose(
            _compute_scale_zp(-tiny_float, tiny_float, 0, 255, numpy.uint8, symmetric=True), [0, 1.0]
        )
        numpy.testing.assert_allclose(
            _compute_scale_zp(-tiny_float, 0.0, 0, 255, numpy.uint8, symmetric=False), [0, 1.0]
        )
 
        # Test enforcing a minimum floatint-point range.
        numpy.testing.assert_allclose(
            _compute_scale_zp(0.0, 0.0, 0, 255, numpy.uint8, symmetric=False, min_real_range=0.0001), [0, 0.0001 / 255]
        )
        numpy.testing.assert_allclose(
            _compute_scale_zp(0.0, 0.0, -128, 127, numpy.int8, symmetric=True, min_real_range=0.0001), [0, 0.0002 / 255]
        )
        numpy.testing.assert_allclose(
            _compute_scale_zp(0.0, 0.0, 0, 65535, numpy.uint16, symmetric=False, min_real_range=0.0001),
            [0, 0.0001 / 65535],
        )
        numpy.testing.assert_allclose(
            _compute_scale_zp(0.0, 0.0, -32768, 32767, numpy.int16, symmetric=True, min_real_range=0.0001),
            [0, 0.0002 / 65535],
        )
 
    def test_compute_scale_zp_large_finite_range(self):
        for dtype, magnitude in ((numpy.float16, 40000), (numpy.float32, 3e38)):
            for qtype in (numpy.int8, numpy.uint8, numpy.int16, numpy.uint16):
                for symmetric in (False, True):
                    with self.subTest(dtype=dtype, qtype=qtype, symmetric=symmetric):
                        rmin = numpy.array(-0.75 * magnitude, dtype=dtype)
                        rmax = numpy.array(magnitude, dtype=dtype)
                        qmin = numpy.array(numpy.iinfo(qtype).min, dtype=qtype)
                        qmax = numpy.array(numpy.iinfo(qtype).max, dtype=qtype)
                        zero_point, scale = compute_scale_zp(rmin, rmax, qmin, qmax, symmetric=symmetric)
 
                        # Use Python floats so the reference range does not overflow the input dtype.
                        real_min = -float(rmax) if symmetric else float(rmin)
                        expected_scale = (float(rmax) - real_min) / (int(qmax) - int(qmin))
                        expected_zero = (
                            round((int(qmax) + int(qmin)) / 2)
                            if symmetric
                            else round(int(qmin) - real_min / expected_scale)
                        )
                        self.assertTrue(numpy.isfinite(scale))
                        self.assertEqual(scale.dtype, dtype)
                        self.assertEqual(zero_point.dtype, qtype)
                        numpy.testing.assert_array_equal(scale, numpy.array(expected_scale, dtype=dtype))
                        self.assertEqual(int(zero_point), expected_zero)
 
    def test_compute_scale_zp_float8(self):
        # The FLOAT8E4M3FN reference distribution must be the 254 finite float8
        # values (std ~= 100.0577), not the integers 0..255 (std ~= 73.9). With
        # std=1 the scale is therefore 1 / 100.0577, not 1 / 73.9.
        zero, scale = compute_scale_zp_float8(TensorProto.FLOAT8E4M3FN, numpy.float32(1.0))
        numpy.testing.assert_allclose(float(scale), 1.0 / 100.05772, rtol=1e-5)
        # Scale is linear in the input std.
        _, scale2 = compute_scale_zp_float8(TensorProto.FLOAT8E4M3FN, numpy.float32(2.0))
        numpy.testing.assert_allclose(float(scale2), 2.0 / 100.05772, rtol=1e-5)
 
    def test_load_external_model(self):
        input_name = "input"
        output_name = "output"
        add_shape = [1024, 1024]
 
        initializers = []
        weight_name = "weight"
        weight_data = numpy.random.normal(0, 0.1, add_shape).astype(numpy.float32)
        initializers.append(numpy_helper.from_array(weight_data, name=weight_name))
        add_node = helper.make_node("Add", [input_name, weight_name], [output_name], name="add_node")
 
        # make graph
        input_tensor = helper.make_tensor_value_info(input_name, TensorProto.FLOAT, add_shape)
        output_tensor = helper.make_tensor_value_info(output_name, TensorProto.FLOAT, add_shape)
        graph_name = "test_load_external_model"
        graph = helper.make_graph(
            [add_node],
            graph_name,
            [input_tensor],
            [output_tensor],
            initializer=initializers,
        )
        model = helper.make_model(graph, opset_imports=[helper.make_opsetid("", 13)])
 
        with tempfile.TemporaryDirectory() as temp_dir:
            self.assertFalse(model_has_infer_metadata(model))
            model_file_path = temp_dir + "/test_load_external_model.onnx"
            onnx.save(model, model_file_path, save_as_external_data=True)
            model_reloaded = load_model_with_shape_infer(Path(model_file_path))
            self.assertTrue(model_has_infer_metadata(model_reloaded))
 
    def test_pack_bytes_to_4bit(self):
        """
        Tests the pack_bytes_to_4bit() utility.
        """
        subtest_configs = [
            (-8, 6, True),  # Odd num elems, signed
            (-8, 7, True),  # Even num elems, signed
            (0, 14, False),  # Odd num elems, unsigned
            (0, 15, False),  # Even num elems, unsigned
        ]
        for min_val, max_val, signed in subtest_configs:
            with self.subTest(min_val=min_val, max_val=max_val, signed=signed):
                src_float = numpy.arange(min_val, max_val + 1).astype(numpy.float32)
                src_int = src_float.astype(numpy.int8 if signed else numpy.uint8)
 
                actual_packed_vals = bytes(pack_bytes_to_4bit(src_int.tobytes()))
                src_4bit = src_float.astype(int4 if signed else uint4)
                expected_packed_vals = bytes(pack_bytes_to_4bit(src_4bit.tobytes()))
                self.assertEqual(actual_packed_vals, expected_packed_vals)
 
    def test_quantize_data_4bit(self):
        """
        Test that calling quantize_data for int4 quantization returns data of the correct type and range.
        """
        data_float = numpy.arange(-20, 17).astype(numpy.float32)
 
        subtest_configs = [
            (onnx.TensorProto.INT4, True),  # int4, symmetric quant
            (onnx.TensorProto.INT4, False),  # int4, symmetric quant
            (onnx.TensorProto.UINT4, True),  # uint4, symmetric quant
            (onnx.TensorProto.UINT4, False),  # uint4, symmetric quant
        ]
 
        for onnx_type, symmetric in subtest_configs:
            with self.subTest(onnx_type=onnx_type, symmetric=symmetric):
                zero_point, scale, data_quant = quantize_data(data_float, onnx_type, symmetric)
                is_signed = onnx_type == onnx.TensorProto.INT4
                np_int_type = int4 if is_signed else uint4
                qmin = numpy.array(-8 if is_signed else 0, dtype=np_int_type)
                qmax = numpy.array(7 if is_signed else 15, dtype=np_int_type)
                self.assertEqual(zero_point.dtype, np_int_type)
                self.assertEqual(scale.dtype, data_float.dtype)
 
                expected_zp, expected_scale = compute_scale_zp(
                    data_float.min(), data_float.max(), qmin, qmax, symmetric=symmetric
                )
                self.assertEqual(zero_point, expected_zp)
                self.assertEqual(scale, expected_scale)
 
                # Even int4 quantization generates 8-bit numpy values.
                self.assertEqual(data_quant.dtype, np_int_type)
                for index, actual_quant_val in enumerate(data_quant.flatten()):
                    self.assertTrue(actual_quant_val >= qmin and actual_quant_val <= qmax)
 
                    expected_quant_val = numpy.asarray((data_float[index] / scale).round() + zero_point).astype(
                        np_int_type
                    )
                    numpy.clip(expected_quant_val, qmin, qmax, out=expected_quant_val)
 
                    self.assertEqual(numpy.array(actual_quant_val), expected_quant_val)
 
    def test_update_opset_version_16bit(self):
        graph = helper.make_graph([], "test_graph", [], [])
 
        # 16-bit weight type alone should auto-bump opset < 21 -> 21
        for weight_type, label in (
            (QuantType.QUInt16, "QUInt16"),
            (QuantType.QInt16, "QInt16"),
        ):
            with self.subTest(weight_type=label, opset=20):
                model = helper.make_model(graph, opset_imports=[helper.make_opsetid("", 20)])
                result = update_opset_version(model, weight_type)
                result_opset = result.opset_import[0].version
                self.assertEqual(result_opset, 21)
 
        # Already at opset 21 - should stay at 21
        for weight_type, label in (
            (QuantType.QUInt16, "QUInt16"),
            (QuantType.QInt16, "QInt16"),
        ):
            with self.subTest(weight_type=label, opset=21):
                model = helper.make_model(graph, opset_imports=[helper.make_opsetid("", 21)])
                result = update_opset_version(model, weight_type)
                result_opset = result.opset_import[0].version
                self.assertEqual(result_opset, 21)
 
        # 16-bit activation type with 8-bit weight should also bump opset < 21 -> 21
        for activation_type, label in (
            (QuantType.QUInt16, "QUInt16"),
            (QuantType.QInt16, "QInt16"),
        ):
            with self.subTest(activation_type=label, weight_type="QInt8", opset=20):
                model = helper.make_model(graph, opset_imports=[helper.make_opsetid("", 20)])
                result = update_opset_version(model, QuantType.QInt8, activation_type)
                result_opset = result.opset_import[0].version
                self.assertEqual(result_opset, 21)
 
        # Both 8-bit should NOT bump to 21; opset stays at 20
        with self.subTest(weight_type="QInt8", activation_type="QUInt8", opset=20):
            model = helper.make_model(graph, opset_imports=[helper.make_opsetid("", 20)])
            result = update_opset_version(model, QuantType.QInt8, QuantType.QUInt8)
            result_opset = result.opset_import[0].version
            self.assertEqual(result_opset, 20)
 
 
if __name__ == "__main__":
    unittest.main()