VideoUFO commited on
Commit
50be9b7
·
verified ·
1 Parent(s): b554a07

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. ScaleDF_rebuttal/python_dedup_pkgs/onnx-1.22.0.dist-info/entry_points.txt +5 -0
  2. ScaleDF_rebuttal/python_dedup_pkgs/onnx-1.22.0.dist-info/licenses/LICENSE +202 -0
  3. ScaleDF_rebuttal/python_dedup_pkgs/onnx-1.22.0.dist-info/licenses/NOTICE +59 -0
  4. ScaleDF_rebuttal/python_dedup_pkgs/onnx-1.22.0.dist-info/sboms/sbom.cdx.json +75 -0
  5. ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/LICENSE +21 -0
  6. ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/Privacy.md +21 -0
  7. ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/ThirdPartyNotices.txt +0 -0
  8. ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/__init__.py +500 -0
  9. ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/backend/__init__.py +6 -0
  10. ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/backend/backend.py +214 -0
  11. ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/backend/backend_rep.py +76 -0
  12. ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/capi/__init__.py +4 -0
  13. ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/capi/_ld_preload.py +7 -0
  14. ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/capi/_pybind_state.py +33 -0
  15. ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/capi/build_and_package_info.py +3 -0
  16. ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/capi/convert_npz_to_onnx_adapter.py +48 -0
  17. ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/capi/libonnxruntime_providers_shared.so +0 -0
  18. ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/capi/onnxruntime_collect_build_info.py +47 -0
  19. ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/capi/onnxruntime_inference_collection.py +1627 -0
  20. ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/capi/onnxruntime_validation.py +154 -0
  21. ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/datasets/__init__.py +18 -0
  22. ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/quantization/CalTableFlatBuffers/KeyValue.py +78 -0
  23. ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/quantization/CalTableFlatBuffers/TrtTable.py +90 -0
  24. ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/quantization/CalTableFlatBuffers/__init__.py +0 -0
  25. ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/quantization/__init__.py +24 -0
  26. ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/quantization/base_quantizer.py +530 -0
  27. ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/quantization/calibrate.py +1353 -0
  28. ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/quantization/cuda_quantizer.py +643 -0
  29. ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/quantization/execution_providers/qnn/__init__.py +2 -0
  30. ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/quantization/execution_providers/qnn/fusion_lpnorm.py +132 -0
  31. ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/quantization/execution_providers/qnn/fusion_spacetodepth.py +162 -0
  32. ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/quantization/execution_providers/qnn/mixed_precision_overrides_utils.py +413 -0
  33. ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/quantization/execution_providers/qnn/preprocess.py +353 -0
  34. ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/quantization/execution_providers/qnn/quant_config.py +389 -0
  35. ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/quantization/fusions/__init__.py +4 -0
  36. ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/quantization/fusions/fusion.py +311 -0
  37. ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/quantization/fusions/fusion_gelu.py +272 -0
  38. ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/quantization/fusions/fusion_layernorm.py +146 -0
  39. ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/quantization/fusions/replace_upsample_with_resize.py +96 -0
  40. ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/quantization/matmul_bnb4_quantizer.py +239 -0
  41. ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/quantization/matmul_nbits_quantizer.py +1874 -0
  42. ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/quantization/neural_compressor/__init__.py +1 -0
  43. ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/quantization/neural_compressor/onnx_model.py +1236 -0
  44. ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/quantization/neural_compressor/util.py +80 -0
  45. ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/quantization/neural_compressor/weight_only.py +932 -0
  46. ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/quantization/onnx_model.py +600 -0
  47. ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/quantization/onnx_quantizer.py +1174 -0
  48. ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/quantization/operators/__init__.py +2 -0
  49. ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/quantization/operators/activation.py +119 -0
  50. ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/quantization/operators/argmax.py +18 -0
ScaleDF_rebuttal/python_dedup_pkgs/onnx-1.22.0.dist-info/entry_points.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ [console_scripts]
2
+ backend-test-tools = onnx.backend.test.cmd_tools:main
3
+ check-model = onnx.bin.checker:check_model
4
+ check-node = onnx.bin.checker:check_node
5
+
ScaleDF_rebuttal/python_dedup_pkgs/onnx-1.22.0.dist-info/licenses/LICENSE ADDED
@@ -0,0 +1,202 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
ScaleDF_rebuttal/python_dedup_pkgs/onnx-1.22.0.dist-info/licenses/NOTICE ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ONNX is licensed under the Apache License, Version 2.0 (see LICENSE).
2
+
3
+ This product includes software from the following third-party projects, which
4
+ are linked into ONNX wheel builds. Their copyright notices are reproduced below.
5
+
6
+ ---
7
+
8
+ ## abseil-cpp
9
+
10
+ Copyright 2017 The Abseil Authors.
11
+
12
+ Version: 20250127.0
13
+ Source: https://github.com/abseil/abseil-cpp
14
+ License: Apache-2.0 (see LICENSE)
15
+
16
+ ---
17
+
18
+ ## protobuf
19
+
20
+ Copyright 2008 Google Inc.
21
+
22
+ Version: 25.1
23
+ Source: https://github.com/protocolbuffers/protobuf
24
+ License: Apache-2.0 (see LICENSE)
25
+
26
+ ---
27
+
28
+ ## nanobind
29
+
30
+ Copyright (c) 2022 Wenzel Jakob <wenzel.jakob@epfl.ch>
31
+
32
+ Version: 2.12.0
33
+ Source: https://github.com/wjakob/nanobind
34
+ License: BSD-3-Clause
35
+
36
+ Redistribution and use in source and binary forms, with or without
37
+ modification, are permitted provided that the following conditions are met:
38
+
39
+ 1. Redistributions of source code must retain the above copyright notice,
40
+ this list of conditions and the following disclaimer.
41
+
42
+ 2. Redistributions in binary form must reproduce the above copyright notice,
43
+ this list of conditions and the following disclaimer in the documentation
44
+ and/or other materials provided with the distribution.
45
+
46
+ 3. Neither the name of the copyright holder nor the names of its contributors
47
+ may be used to endorse or promote products derived from this software
48
+ without specific prior written permission.
49
+
50
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
51
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
52
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
53
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
54
+ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
55
+ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
56
+ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
57
+ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
58
+ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
59
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
ScaleDF_rebuttal/python_dedup_pkgs/onnx-1.22.0.dist-info/sboms/sbom.cdx.json ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "$schema": "https://cyclonedx.org/schema/bom-1.7.schema.json",
3
+ "bomFormat": "CycloneDX",
4
+ "specVersion": "1.7",
5
+ "version": 1,
6
+ "metadata": {
7
+ "lifecycles": [{"phase": "build"}],
8
+ "component": {
9
+ "type": "library",
10
+ "name": "onnx",
11
+ "description": "Open Neural Network Exchange — open format for AI/ML models",
12
+ "purl": "pkg:pypi/onnx",
13
+ "bom-ref": "onnx"
14
+ }
15
+ },
16
+ "components": [
17
+ {
18
+ "type": "library",
19
+ "name": "abseil-cpp",
20
+ "version": "20250127.0",
21
+ "bom-ref": "abseil-cpp",
22
+ "purl": "pkg:github/abseil/abseil-cpp@v20250127.0",
23
+ "externalReferences": [
24
+ {
25
+ "type": "distribution",
26
+ "url": "https://github.com/abseil/abseil-cpp/releases/download/20250127.0/abseil-cpp-20250127.0.tar.gz"
27
+ }
28
+ ],
29
+ "hashes": [
30
+ {"alg": "SHA-256", "content": "16242f394245627e508ec6bb296b433c90f8d914f73b9c026fddb905e27276e8"}
31
+ ],
32
+ "licenses": [{"license": {"id": "Apache-2.0"}}]
33
+ },
34
+ {
35
+ "type": "library",
36
+ "name": "protobuf",
37
+ "version": "25.1",
38
+ "bom-ref": "protobuf",
39
+ "purl": "pkg:github/protocolbuffers/protobuf@v25.1",
40
+ "externalReferences": [
41
+ {
42
+ "type": "distribution",
43
+ "url": "https://github.com/protocolbuffers/protobuf/releases/download/v25.1/protobuf-25.1.tar.gz"
44
+ }
45
+ ],
46
+ "hashes": [
47
+ {"alg": "SHA-256", "content": "9bd87b8280ef720d3240514f884e56a712f2218f0d693b48050c836028940a42"}
48
+ ],
49
+ "licenses": [{"license": {"id": "BSD-3-Clause"}}]
50
+ },
51
+ {
52
+ "type": "library",
53
+ "name": "nanobind",
54
+ "version": "2.12.0",
55
+ "bom-ref": "nanobind",
56
+ "purl": "pkg:github/wjakob/nanobind@v2.12.0",
57
+ "externalReferences": [
58
+ {
59
+ "type": "vcs",
60
+ "url": "https://github.com/wjakob/nanobind.git"
61
+ }
62
+ ],
63
+ "licenses": [{"license": {"id": "BSD-3-Clause"}}]
64
+ }
65
+ ],
66
+ "dependencies": [
67
+ {
68
+ "ref": "onnx",
69
+ "dependsOn": ["abseil-cpp", "protobuf", "nanobind"]
70
+ },
71
+ {"ref": "abseil-cpp"},
72
+ {"ref": "protobuf"},
73
+ {"ref": "nanobind"}
74
+ ]
75
+ }
ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/LICENSE ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MIT License
2
+
3
+ Copyright (c) Microsoft Corporation
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/Privacy.md ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Privacy
2
+
3
+ ## Data Collection
4
+ The software may collect information about you and your use of the software and send it to Microsoft. Microsoft may use this information to provide services and improve our products and services. You may turn off the telemetry as described in the repository. There are also some features in the software that may enable you and Microsoft to collect data from users of your applications. If you use these features, you must comply with applicable law, including providing appropriate notices to users of your applications together with a copy of Microsoft's privacy statement. Our privacy statement is located at https://go.microsoft.com/fwlink/?LinkID=824704. You can learn more about data collection and use in the help documentation and our privacy statement. Your use of the software operates as your consent to these practices.
5
+
6
+ ***
7
+
8
+ ### Private Builds
9
+ No data collection is performed when using your private builds built from source code.
10
+
11
+ ### Official Builds
12
+ ONNX Runtime does not maintain any independent telemetry collection mechanisms outside of what is provided by the platforms it supports. However, where applicable, ONNX Runtime will take advantage of platform-supported telemetry systems to collect trace events with the goal of improving product quality.
13
+
14
+ Currently telemetry is only implemented for Windows builds and is turned **ON** by default in the official builds distributed in their respective package management repositories ([see here](../README.md#binaries)). This may be expanded to cover other platforms in the future. Data collection is implemented via 'Platform Telemetry' per vendor platform providers (see [telemetry.h](../onnxruntime/core/platform/telemetry.h)).
15
+
16
+ #### Technical Details
17
+ The Windows provider uses the [TraceLogging](https://docs.microsoft.com/en-us/windows/win32/tracelogging/trace-logging-about) API for its implementation. This enables ONNX Runtime trace events to be collected by the operating system, and based on user consent, this data may be periodically sent to Microsoft servers following GDPR and privacy regulations for anonymity and data access controls.
18
+
19
+ Windows ML and onnxruntime C APIs allow Trace Logging to be turned on/off (see [API pages](../README.md#api-documentation) for details).
20
+ For information on how to enable and disable telemetry, see [C API: Telemetry](./C_API.md#telemetry).
21
+ There are equivalent APIs in the C#, Python, and Java language bindings as well.
ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/ThirdPartyNotices.txt ADDED
The diff for this file is too large to render. See raw diff
 
ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/__init__.py ADDED
@@ -0,0 +1,500 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -------------------------------------------------------------------------
2
+ # Copyright (c) Microsoft Corporation. All rights reserved.
3
+ # Licensed under the MIT License.
4
+ # --------------------------------------------------------------------------
5
+ """
6
+ ONNX Runtime is a performance-focused scoring engine for Open Neural Network Exchange (ONNX) models.
7
+ For more information on ONNX Runtime, please see `aka.ms/onnxruntime <https://aka.ms/onnxruntime/>`_
8
+ or the `Github project <https://github.com/microsoft/onnxruntime/>`_.
9
+ """
10
+
11
+ import contextlib
12
+
13
+ __version__ = "1.28.0"
14
+ __author__ = "Microsoft"
15
+
16
+ # we need to do device version validation (for example to check Cuda version for an onnxruntime-training package).
17
+ # in order to know whether the onnxruntime package is for training it needs
18
+ # to do import onnxruntime.training.ortmodule first.
19
+ # onnxruntime.capi._pybind_state is required before import onnxruntime.training.ortmodule.
20
+ # however, import onnxruntime.capi._pybind_state will already raise an exception if a required Cuda version
21
+ # is not found.
22
+ # here we need to save the exception and continue with Cuda version validation in order to post
23
+ # meaningful messages to the user.
24
+ # the saved exception is raised after device version validation.
25
+ try:
26
+ from onnxruntime.capi._pybind_state import (
27
+ ExecutionMode, # noqa: F401
28
+ ExecutionOrder, # noqa: F401
29
+ GraphOptimizationLevel, # noqa: F401
30
+ LoraAdapter, # noqa: F401
31
+ ModelMetadata, # noqa: F401
32
+ NodeArg, # noqa: F401
33
+ OrtAllocatorType, # noqa: F401
34
+ OrtArenaCfg, # noqa: F401
35
+ OrtCompileApiFlags, # noqa: F401
36
+ OrtDeviceMemoryType, # noqa: F401
37
+ OrtEpAssignedNode, # noqa: F401
38
+ OrtEpAssignedSubgraph, # noqa: F401
39
+ OrtEpDevice, # noqa: F401
40
+ OrtExecutionProviderDevicePolicy, # noqa: F401
41
+ OrtExternalInitializerInfo, # noqa: F401
42
+ OrtHardwareDevice, # noqa: F401
43
+ OrtHardwareDeviceType, # noqa: F401
44
+ OrtMemoryInfo, # noqa: F401
45
+ OrtMemoryInfoDeviceType, # noqa: F401
46
+ OrtMemType, # noqa: F401
47
+ OrtSparseFormat, # noqa: F401
48
+ OrtSyncStream, # noqa: F401
49
+ RunOptions, # noqa: F401
50
+ SessionIOBinding, # noqa: F401
51
+ SessionOptions, # noqa: F401
52
+ create_and_register_allocator, # noqa: F401
53
+ create_and_register_allocator_v2, # noqa: F401
54
+ disable_telemetry_events, # noqa: F401
55
+ enable_telemetry_events, # noqa: F401
56
+ get_all_providers, # noqa: F401
57
+ get_available_providers, # noqa: F401
58
+ get_build_info,
59
+ get_device, # noqa: F401
60
+ get_ep_devices, # noqa: F401
61
+ get_version_string, # noqa: F401
62
+ has_collective_ops, # noqa: F401
63
+ register_execution_provider_library,
64
+ set_default_logger_severity, # noqa: F401
65
+ set_default_logger_verbosity, # noqa: F401
66
+ set_global_thread_pool_sizes, # noqa: F401
67
+ set_seed, # noqa: F401
68
+ unregister_execution_provider_library, # noqa: F401
69
+ )
70
+
71
+ import_capi_exception = None
72
+ except Exception as e:
73
+ import_capi_exception = e
74
+
75
+ from onnxruntime.capi import onnxruntime_validation
76
+
77
+ if import_capi_exception:
78
+ raise import_capi_exception
79
+
80
+ from onnxruntime.capi.onnxruntime_inference_collection import (
81
+ AdapterFormat, # noqa: F401
82
+ InferenceSession, # noqa: F401
83
+ IOBinding, # noqa: F401
84
+ ModelCompiler, # noqa: F401
85
+ OrtDevice, # noqa: F401
86
+ OrtDeviceVendorId, # noqa: F401
87
+ OrtValue, # noqa: F401
88
+ SparseTensor, # noqa: F401
89
+ copy_tensors, # noqa: F401
90
+ )
91
+
92
+ # TODO: thiagofc: Temporary experimental namespace for new PyTorch front-end
93
+ try: # noqa: SIM105
94
+ from . import experimental # noqa: F401
95
+ except ImportError:
96
+ pass
97
+
98
+
99
+ package_name, version, cuda_version = onnxruntime_validation.get_package_name_and_version_info()
100
+
101
+ if version:
102
+ __version__ = version
103
+
104
+ onnxruntime_validation.check_distro_info()
105
+
106
+
107
+ def _get_cuda_plugin_ep_library_path() -> str | None:
108
+ import os # noqa: PLC0415
109
+ import sys # noqa: PLC0415
110
+
111
+ if ", cuda-plugin-ep=" not in get_build_info():
112
+ return None
113
+
114
+ if sys.platform == "win32":
115
+ library_name = "onnxruntime_providers_cuda.dll"
116
+ elif sys.platform == "darwin":
117
+ library_name = "libonnxruntime_providers_cuda.dylib"
118
+ else:
119
+ library_name = "libonnxruntime_providers_cuda.so"
120
+
121
+ library_path = os.path.join(os.path.dirname(__file__), "capi", library_name)
122
+ return library_path if os.path.isfile(library_path) else None
123
+
124
+
125
+ def _register_bundled_cuda_plugin_ep(warn_on_failure: bool = False):
126
+ library_path = _get_cuda_plugin_ep_library_path()
127
+ if not library_path:
128
+ return
129
+
130
+ try:
131
+ register_execution_provider_library("CUDAExecutionProvider", library_path)
132
+ except Exception as e:
133
+ if "already registered" not in str(e).lower():
134
+ if warn_on_failure:
135
+ import warnings # noqa: PLC0415
136
+
137
+ warnings.warn(f"Failed to register bundled CUDA plugin EP from {library_path}: {e}")
138
+
139
+
140
+ _register_bundled_cuda_plugin_ep(warn_on_failure=True)
141
+
142
+
143
+ def _get_package_version(package_name: str):
144
+ from importlib.metadata import PackageNotFoundError, version # noqa: PLC0415
145
+
146
+ try:
147
+ package_version = version(package_name)
148
+ except PackageNotFoundError:
149
+ package_version = None
150
+ return package_version
151
+
152
+
153
+ def _get_package_root(package_name: str, directory_name: str | None = None):
154
+ from importlib.metadata import PackageNotFoundError, distribution # noqa: PLC0415
155
+
156
+ root_directory_name = directory_name or package_name
157
+ try:
158
+ dist = distribution(package_name)
159
+ files = dist.files or []
160
+
161
+ for file in files:
162
+ if file.name.endswith("__init__.py") and root_directory_name in file.parts:
163
+ return file.locate().parent
164
+
165
+ # Fallback to the first __init__.py
166
+ if not directory_name:
167
+ for file in files:
168
+ if file.name.endswith("__init__.py"):
169
+ return file.locate().parent
170
+ except PackageNotFoundError:
171
+ # package not found, do nothing
172
+ pass
173
+
174
+ return None
175
+
176
+
177
+ def _extract_cuda_major_version(version_str: str) -> str:
178
+ """Extract CUDA major version from version string (e.g., '12.1' -> '12').
179
+
180
+ Args:
181
+ version_str: CUDA version string to parse
182
+
183
+ Returns:
184
+ Major version as string, or "12" if parsing fails
185
+ """
186
+ return version_str.split(".", maxsplit=1)[0] if version_str else "12"
187
+
188
+
189
+ def _get_cufft_version(cuda_major_version: str) -> str:
190
+ """Get cufft library version based on CUDA major version.
191
+
192
+ Args:
193
+ cuda_major_version: CUDA major version as string (e.g., "12", "13")
194
+
195
+ Returns:
196
+ cufft version as string
197
+ """
198
+ # cufft versions: CUDA 12.x -> 11, CUDA 13.x -> 12
199
+ return "12" if int(cuda_major_version) >= 13 else "11"
200
+
201
+
202
+ def _get_nvidia_dll_paths(is_windows: bool, cuda: bool = True, cudnn: bool = True):
203
+ # Dynamically determine CUDA major version from build info.
204
+ # build_cuda_version defaults to the version this package was built with; it is a parameter for testability.
205
+ cuda_major_version = _extract_cuda_major_version(cuda_version)
206
+ cufft_version = _get_cufft_version(cuda_major_version)
207
+
208
+ # Starting with CUDA 13, NVIDIA consolidated the per-component CUDA Toolkit wheels
209
+ # (cublas, cufft, cuda_runtime, cuda_nvrtc, curand, ...) into a single "nvidia/cu{major}"
210
+ # package and dropped the "-cuNN" suffix from those package names. On Windows the DLLs
211
+ # moved into an architecture sub-folder ("bin/<arch>", e.g. "bin/x86_64"); on Linux the
212
+ # libraries are placed directly in "lib" (the wheel itself is architecture specific, so
213
+ # there is no arch sub-folder). cuDNN keeps its own "nvidia/cudnn" package and layout.
214
+ use_consolidated_layout = cuda_major_version.isdigit() and int(cuda_major_version) >= 13
215
+
216
+ if use_consolidated_layout:
217
+ cuda_dir = f"cu{cuda_major_version}"
218
+ if is_windows:
219
+ import platform # noqa: PLC0415
220
+
221
+ arch = "arm64" if platform.machine().lower() in ("arm64", "aarch64") else "x86_64"
222
+ cuda_dll_paths = [
223
+ ("nvidia", cuda_dir, "bin", arch, f"cublasLt64_{cuda_major_version}.dll"),
224
+ ("nvidia", cuda_dir, "bin", arch, f"cublas64_{cuda_major_version}.dll"),
225
+ ("nvidia", cuda_dir, "bin", arch, f"cufft64_{cufft_version}.dll"),
226
+ ("nvidia", cuda_dir, "bin", arch, f"cudart64_{cuda_major_version}.dll"),
227
+ ]
228
+ else: # Linux
229
+ # cublas64 depends on cublasLt64, so cublasLt64 should be loaded first.
230
+ cuda_dll_paths = [
231
+ ("nvidia", cuda_dir, "lib", f"libcublasLt.so.{cuda_major_version}"),
232
+ ("nvidia", cuda_dir, "lib", f"libcublas.so.{cuda_major_version}"),
233
+ ("nvidia", cuda_dir, "lib", f"libnvrtc.so.{cuda_major_version}"),
234
+ ("nvidia", cuda_dir, "lib", "libcurand.so.10"),
235
+ ("nvidia", cuda_dir, "lib", f"libcufft.so.{cufft_version}"),
236
+ ("nvidia", cuda_dir, "lib", f"libcudart.so.{cuda_major_version}"),
237
+ ]
238
+ elif is_windows:
239
+ # CUDA 12 and earlier: each component ships its own "nvidia/<component>" package.
240
+ # Path is relative to site-packages directory.
241
+ cuda_dll_paths = [
242
+ ("nvidia", "cublas", "bin", f"cublasLt64_{cuda_major_version}.dll"),
243
+ ("nvidia", "cublas", "bin", f"cublas64_{cuda_major_version}.dll"),
244
+ ("nvidia", "cufft", "bin", f"cufft64_{cufft_version}.dll"),
245
+ ("nvidia", "cuda_runtime", "bin", f"cudart64_{cuda_major_version}.dll"),
246
+ ]
247
+ else: # Linux
248
+ # cublas64 depends on cublasLt64, so cublasLt64 should be loaded first.
249
+ cuda_dll_paths = [
250
+ ("nvidia", "cublas", "lib", f"libcublasLt.so.{cuda_major_version}"),
251
+ ("nvidia", "cublas", "lib", f"libcublas.so.{cuda_major_version}"),
252
+ ("nvidia", "cuda_nvrtc", "lib", f"libnvrtc.so.{cuda_major_version}"),
253
+ ("nvidia", "curand", "lib", "libcurand.so.10"),
254
+ ("nvidia", "cufft", "lib", f"libcufft.so.{cufft_version}"),
255
+ ("nvidia", "cuda_runtime", "lib", f"libcudart.so.{cuda_major_version}"),
256
+ ]
257
+
258
+ # cuDNN keeps its own "nvidia/cudnn" package layout in both old and consolidated schemes.
259
+ if is_windows:
260
+ cudnn_dll_paths = [
261
+ ("nvidia", "cudnn", "bin", "cudnn_engines_runtime_compiled64_9.dll"),
262
+ ("nvidia", "cudnn", "bin", "cudnn_engines_precompiled64_9.dll"),
263
+ ("nvidia", "cudnn", "bin", "cudnn_heuristic64_9.dll"),
264
+ ("nvidia", "cudnn", "bin", "cudnn_ops64_9.dll"),
265
+ ("nvidia", "cudnn", "bin", "cudnn_adv64_9.dll"),
266
+ ("nvidia", "cudnn", "bin", "cudnn_graph64_9.dll"),
267
+ ("nvidia", "cudnn", "bin", "cudnn64_9.dll"),
268
+ ("nvidia", "cudnn", "bin", "cudnn_engines_tensor_ir64_9.dll"),
269
+ ]
270
+ else: # Linux
271
+ # Do not load cudnn sub DLLs (they will be dynamically loaded later) to be consistent with PyTorch in Linux.
272
+ cudnn_dll_paths = [
273
+ ("nvidia", "cudnn", "lib", "libcudnn.so.9"),
274
+ ]
275
+
276
+ return (cuda_dll_paths if cuda else []) + (cudnn_dll_paths if cudnn else [])
277
+
278
+
279
+ def print_debug_info():
280
+ """Print information to help debugging."""
281
+ import importlib.util # noqa: PLC0415
282
+ import os # noqa: PLC0415
283
+ import platform # noqa: PLC0415
284
+ from importlib.metadata import distributions # noqa: PLC0415
285
+
286
+ print(f"{package_name} version: {__version__}")
287
+ if cuda_version:
288
+ print(f"CUDA version used in build: {cuda_version}")
289
+ print("platform:", platform.platform())
290
+
291
+ print("\nPython package, version and location:")
292
+ ort_packages = []
293
+ for dist in distributions():
294
+ package = dist.metadata["Name"]
295
+ if package == "onnxruntime" or package.startswith(("onnxruntime-", "ort-")):
296
+ # Exclude packages whose root directory name is not onnxruntime.
297
+ location = _get_package_root(package, "onnxruntime")
298
+ if location and (package not in ort_packages):
299
+ ort_packages.append(package)
300
+ print(f"{package}=={dist.version} at {location}")
301
+
302
+ if len(ort_packages) > 1:
303
+ print(
304
+ "\033[33mWARNING: multiple onnxruntime packages are installed to the same location. "
305
+ "Please 'pip uninstall` all above packages, then `pip install` only one of them.\033[0m"
306
+ )
307
+
308
+ if cuda_version:
309
+ # Print version of installed packages that is related to CUDA or cuDNN DLLs.
310
+ cuda_major = _extract_cuda_major_version(cuda_version)
311
+
312
+ # Starting with CUDA 13, NVIDIA dropped the "-cuNN" suffix from the per-component
313
+ # CUDA Toolkit packages (cuDNN keeps its suffixed package name).
314
+ cuda_pkg_suffix = "" if (cuda_major.isdigit() and int(cuda_major) >= 13) else f"-cu{cuda_major}"
315
+
316
+ packages = [
317
+ "torch",
318
+ f"nvidia-cuda-runtime{cuda_pkg_suffix}",
319
+ f"nvidia-cudnn-cu{cuda_major}",
320
+ f"nvidia-cublas{cuda_pkg_suffix}",
321
+ f"nvidia-cufft{cuda_pkg_suffix}",
322
+ f"nvidia-curand{cuda_pkg_suffix}",
323
+ f"nvidia-cuda-nvrtc{cuda_pkg_suffix}",
324
+ f"nvidia-nvjitlink{cuda_pkg_suffix}",
325
+ ]
326
+ for package in packages:
327
+ directory_name = "nvidia" if package.startswith("nvidia-") else None
328
+ version = _get_package_version(package)
329
+ if version:
330
+ print(f"{package}=={version} at {_get_package_root(package, directory_name)}")
331
+ else:
332
+ print(f"{package} not installed")
333
+
334
+ if platform.system() == "Windows":
335
+ print(f"\nEnvironment variable:\nPATH={os.environ.get('PATH', '(unset)')}")
336
+ elif platform.system() == "Linux":
337
+ print(f"\nEnvironment variable:\nLD_LIBRARY_PATH={os.environ.get('LD_LIBRARY_PATH', '(unset)')}")
338
+
339
+ if importlib.util.find_spec("psutil"):
340
+
341
+ def is_target_dll(path: str):
342
+ target_keywords = ["vcruntime140", "msvcp140"]
343
+ if cuda_version:
344
+ target_keywords = ["cufft", "cublas", "cudart", "nvrtc", "curand", "cudnn", *target_keywords]
345
+ return any(keyword in path for keyword in target_keywords)
346
+
347
+ import psutil # noqa: PLC0415
348
+
349
+ p = psutil.Process(os.getpid())
350
+
351
+ print("\nList of loaded DLLs:")
352
+ for lib in p.memory_maps():
353
+ if is_target_dll(lib.path.lower()):
354
+ print(lib.path)
355
+
356
+ if cuda_version:
357
+ if importlib.util.find_spec("cpuinfo") and importlib.util.find_spec("py3nvml"):
358
+ from .transformers.machine_info import get_device_info # noqa: PLC0415
359
+
360
+ print("\nDevice information:")
361
+ print(get_device_info())
362
+ else:
363
+ print("please `pip install py-cpuinfo py3nvml` to show device information.")
364
+ else:
365
+ print("please `pip install psutil` to show loaded DLLs.")
366
+
367
+
368
+ def preload_dlls(cuda: bool = True, cudnn: bool = True, msvc: bool = True, directory=None):
369
+ """Preload CUDA 12.x+ and optional cuDNN 9.x DLLs in Windows or Linux, and MSVC runtime DLLs in Windows.
370
+
371
+ When the installed PyTorch is compatible (using same major version of CUDA and cuDNN),
372
+ there is no need to call this function if `import torch` is done before `import onnxruntime`.
373
+
374
+ Args:
375
+ cuda (bool, optional): enable loading CUDA DLLs. Defaults to True.
376
+ cudnn (bool, optional): enable loading cuDNN DLLs. Defaults to True. Missing cuDNN DLLs are ignored.
377
+ msvc (bool, optional): enable loading MSVC DLLs in Windows. Defaults to True.
378
+ directory(str, optional): a directory contains CUDA or cuDNN DLLs. It can be an absolute path,
379
+ or a path relative to the directory of this file.
380
+ If directory is None (default value), the search order: the lib directory of compatible PyTorch in Windows,
381
+ nvidia site packages, default DLL loading paths.
382
+ If directory is empty string (""), the search order: nvidia site packages, default DLL loading paths.
383
+ If directory is a path, the search order: the directory, default DLL loading paths.
384
+ """
385
+ import ctypes # noqa: PLC0415
386
+ import os # noqa: PLC0415
387
+ import platform # noqa: PLC0415
388
+ import sys # noqa: PLC0415
389
+
390
+ if platform.system() not in ["Windows", "Linux"]:
391
+ return
392
+
393
+ is_windows = platform.system() == "Windows"
394
+ if is_windows and msvc:
395
+ try:
396
+ ctypes.CDLL("vcruntime140.dll")
397
+ ctypes.CDLL("msvcp140.dll")
398
+ if platform.machine() != "ARM64":
399
+ ctypes.CDLL("vcruntime140_1.dll")
400
+ except OSError:
401
+ print("Microsoft Visual C++ Redistributable is not installed, this may lead to the DLL load failure.")
402
+ print("It can be downloaded at https://aka.ms/vs/17/release/vc_redist.x64.exe.")
403
+
404
+ # Check if CUDA version is supported (12.x or 13.x+)
405
+ ort_cuda_major = None
406
+ if cuda_version:
407
+ try:
408
+ ort_cuda_major = int(cuda_version.split(".")[0])
409
+ if ort_cuda_major < 12 and (cuda or cudnn):
410
+ print(
411
+ f"\033[33mWARNING: {package_name} is built with CUDA {cuda_version}, which is not supported for preloading. "
412
+ f"CUDA 12.x or newer is required. Call preload_dlls with cuda=False and cudnn=False.\033[0m"
413
+ )
414
+ return
415
+ except ValueError:
416
+ print(
417
+ f"\033[33mWARNING: Unable to parse CUDA version '{cuda_version}'. "
418
+ "Skipping DLL preloading. Call preload_dlls with cuda=False and cudnn=False.\033[0m"
419
+ )
420
+ return
421
+ elif cuda or cudnn:
422
+ # No CUDA version info available but CUDA/cuDNN preloading requested
423
+ return
424
+
425
+ is_cuda_cudnn_imported_by_torch = False
426
+
427
+ if is_windows:
428
+ torch_version = _get_package_version("torch")
429
+ # Check if torch CUDA version matches onnxruntime CUDA version
430
+ torch_cuda_major = None
431
+ if torch_version and "+cu" in torch_version:
432
+ with contextlib.suppress(ValueError):
433
+ # Extract CUDA version from torch (e.g., "2.0.0+cu121" -> 12)
434
+ cu_part = torch_version.split("+cu")[1]
435
+ torch_cuda_major = int(cu_part[:2]) # First 2 digits are major version
436
+
437
+ is_torch_cuda_compatible = (
438
+ torch_cuda_major == ort_cuda_major if (torch_cuda_major and ort_cuda_major) else False
439
+ )
440
+
441
+ if "torch" in sys.modules:
442
+ is_cuda_cudnn_imported_by_torch = is_torch_cuda_compatible
443
+ if torch_cuda_major and ort_cuda_major and torch_cuda_major != ort_cuda_major:
444
+ print(
445
+ f"\033[33mWARNING: The installed PyTorch {torch_version} uses CUDA {torch_cuda_major}.x, "
446
+ f"but {package_name} is built with CUDA {ort_cuda_major}.x. "
447
+ f"Please install PyTorch for CUDA {ort_cuda_major}.x to be compatible.\033[0m"
448
+ )
449
+
450
+ if is_torch_cuda_compatible and directory is None:
451
+ torch_root = _get_package_root("torch", "torch")
452
+ if torch_root:
453
+ directory = os.path.join(torch_root, "lib")
454
+
455
+ base_directory = directory or ".."
456
+ if not os.path.isabs(base_directory):
457
+ base_directory = os.path.join(os.path.dirname(__file__), base_directory)
458
+ base_directory = os.path.normpath(base_directory)
459
+ if not os.path.isdir(base_directory):
460
+ raise RuntimeError(f"Invalid parameter of directory={directory}. The directory does not exist!")
461
+
462
+ if is_cuda_cudnn_imported_by_torch:
463
+ # In Windows, PyTorch has loaded CUDA and cuDNN DLLs during `import torch`, no need to load them again.
464
+ print("Skip loading CUDA and cuDNN DLLs since torch is imported.")
465
+ return
466
+
467
+ # Try load DLLs from nvidia site packages.
468
+ dll_paths = _get_nvidia_dll_paths(is_windows, cuda, cudnn)
469
+ optional_dll_filenames = {relative_path[-1] for relative_path in _get_nvidia_dll_paths(is_windows, False, cudnn)}
470
+ loaded_dlls = []
471
+ for relative_path in dll_paths:
472
+ dll_path = (
473
+ os.path.join(base_directory, relative_path[-1])
474
+ if directory
475
+ else os.path.join(base_directory, *relative_path)
476
+ )
477
+ if os.path.isfile(dll_path):
478
+ try:
479
+ _ = ctypes.CDLL(dll_path)
480
+ loaded_dlls.append(relative_path[-1])
481
+ except Exception as e:
482
+ if relative_path[-1] not in optional_dll_filenames:
483
+ print(f"Failed to load {dll_path}: {e}")
484
+
485
+ # Try load DLLs with default path settings.
486
+ has_failure = False
487
+ for relative_path in dll_paths:
488
+ dll_filename = relative_path[-1]
489
+ if dll_filename not in loaded_dlls:
490
+ try:
491
+ _ = ctypes.CDLL(dll_filename)
492
+ except Exception as e:
493
+ if dll_filename not in optional_dll_filenames:
494
+ has_failure = True
495
+ print(f"Failed to load {dll_filename}: {e}")
496
+
497
+ if has_failure:
498
+ print("Please follow https://onnxruntime.ai/docs/install/#cuda-and-cudnn to install CUDA.")
499
+
500
+ _register_bundled_cuda_plugin_ep(warn_on_failure=True)
ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/backend/__init__.py ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ # -------------------------------------------------------------------------
2
+ # Copyright (c) Microsoft Corporation. All rights reserved.
3
+ # Licensed under the MIT License.
4
+ # --------------------------------------------------------------------------
5
+
6
+ from .backend import is_compatible, prepare, run, supports_device # noqa: F401
ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/backend/backend.py ADDED
@@ -0,0 +1,214 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -------------------------------------------------------------------------
2
+ # Copyright (c) Microsoft Corporation. All rights reserved.
3
+ # Licensed under the MIT License.
4
+ # --------------------------------------------------------------------------
5
+ """
6
+ Implements ONNX's backend API.
7
+ """
8
+
9
+ import os
10
+ import unittest
11
+
12
+ import packaging.version
13
+ from onnx import ModelProto, helper, version # noqa: F401
14
+ from onnx.backend.base import Backend
15
+ from onnx.checker import check_model
16
+
17
+ from onnxruntime import InferenceSession, SessionOptions, get_available_providers, get_device
18
+ from onnxruntime.backend.backend_rep import OnnxRuntimeBackendRep
19
+
20
+ # Allowlist of SessionOptions attributes that are safe to set via the backend API.
21
+ # Dangerous attributes intentionally excluded:
22
+ # optimized_model_filepath — triggers Model::Save(), overwrites arbitrary files
23
+ # profile_file_prefix — writes profiling JSON to arbitrary path
24
+ # enable_profiling — causes uncontrolled file writes to cwd
25
+ _ALLOWED_SESSION_OPTIONS = frozenset(
26
+ {
27
+ "enable_cpu_mem_arena",
28
+ "enable_mem_pattern",
29
+ "enable_mem_reuse",
30
+ "execution_mode",
31
+ "execution_order",
32
+ "graph_optimization_level",
33
+ "inter_op_num_threads",
34
+ "intra_op_num_threads",
35
+ "log_severity_level",
36
+ "log_verbosity_level",
37
+ "logid",
38
+ "use_deterministic_compute",
39
+ "use_per_session_threads",
40
+ }
41
+ )
42
+
43
+
44
+ class OnnxRuntimeBackend(Backend):
45
+ """
46
+ Implements
47
+ `ONNX's backend API <https://github.com/onnx/onnx/blob/main/docs/ImplementingAnOnnxBackend.md>`_
48
+ with *ONNX Runtime*.
49
+ The backend is mostly used when you need to switch between
50
+ multiple runtimes with the same API.
51
+ `Importing models from ONNX to Caffe2 <https://github.com/onnx/tutorials/blob/master/tutorials/OnnxCaffe2Import.ipynb>`_
52
+ shows how to use *caffe2* as a backend for a converted model.
53
+ Note: This is not the official Python API.
54
+ """
55
+
56
+ allowReleasedOpsetsOnly = bool(os.getenv("ALLOW_RELEASED_ONNX_OPSET_ONLY", "1") == "1") # noqa: N815
57
+
58
+ @classmethod
59
+ def is_compatible(cls, model, device=None, **kwargs):
60
+ """
61
+ Return whether the model is compatible with the backend.
62
+
63
+ :param model: unused
64
+ :param device: None to use the default device or a string (ex: `'CPU'`)
65
+ :return: boolean
66
+ """
67
+ if device is None:
68
+ device = get_device()
69
+ return cls.supports_device(device)
70
+
71
+ @classmethod
72
+ def is_opset_supported(cls, model):
73
+ """
74
+ Return whether the opset for the model is supported by the backend.
75
+ When By default only released onnx opsets are allowed by the backend
76
+ To test new opsets env variable ALLOW_RELEASED_ONNX_OPSET_ONLY should be set to 0
77
+
78
+ :param model: Model whose opsets needed to be verified.
79
+ :return: boolean and error message if opset is not supported.
80
+ """
81
+ if cls.allowReleasedOpsetsOnly:
82
+ for opset in model.opset_import:
83
+ domain = opset.domain if opset.domain else "ai.onnx"
84
+ try:
85
+ key = (domain, opset.version)
86
+ if key not in helper.OP_SET_ID_VERSION_MAP:
87
+ error_message = (
88
+ "Skipping this test as only released onnx opsets are supported."
89
+ "To run this test set env variable ALLOW_RELEASED_ONNX_OPSET_ONLY to 0."
90
+ f" Got Domain '{domain}' version '{opset.version}'."
91
+ )
92
+ return False, error_message
93
+ except AttributeError:
94
+ # for some CI pipelines accessing helper.OP_SET_ID_VERSION_MAP
95
+ # is generating attribute error. TODO investigate the pipelines to
96
+ # fix this error. Falling back to a simple version check when this error is encountered
97
+ if (domain == "ai.onnx" and opset.version > 12) or (domain == "ai.ommx.ml" and opset.version > 2):
98
+ error_message = (
99
+ "Skipping this test as only released onnx opsets are supported."
100
+ "To run this test set env variable ALLOW_RELEASED_ONNX_OPSET_ONLY to 0."
101
+ f" Got Domain '{domain}' version '{opset.version}'."
102
+ )
103
+ return False, error_message
104
+ return True, ""
105
+
106
+ @classmethod
107
+ def supports_device(cls, device):
108
+ """
109
+ Check whether the backend is compiled with particular device support.
110
+ In particular it's used in the testing suite.
111
+ """
112
+ if device == "CUDA":
113
+ device = "GPU"
114
+ return "-" + device in get_device() or device + "-" in get_device() or device == get_device()
115
+
116
+ @classmethod
117
+ def prepare(cls, model, device=None, **kwargs):
118
+ """
119
+ Load the model and creates an :class:`onnxruntime.backend.backend_rep.OnnxRuntimeBackendRep`
120
+ ready to be used as a backend.
121
+
122
+ :param model: the model to prepare — accepts a file path (str), serialized
123
+ model (bytes), :class:`onnx.ModelProto`, :class:`onnxruntime.InferenceSession`,
124
+ or :class:`onnxruntime.backend.backend_rep.OnnxRuntimeBackendRep` (returned as-is)
125
+ :param device: requested device for the computation,
126
+ None means the default one which depends on
127
+ the compilation settings
128
+ :param kwargs: only a safe subset of :class:`onnxruntime.SessionOptions` attributes are
129
+ accepted; see ``_ALLOWED_SESSION_OPTIONS`` for the list
130
+ :return: :class:`onnxruntime.backend.backend_rep.OnnxRuntimeBackendRep`
131
+ """
132
+ if isinstance(model, OnnxRuntimeBackendRep):
133
+ return model
134
+ elif isinstance(model, InferenceSession):
135
+ return OnnxRuntimeBackendRep(model)
136
+ elif isinstance(model, (str, bytes)):
137
+ options = SessionOptions()
138
+ for k, v in kwargs.items():
139
+ if k in _ALLOWED_SESSION_OPTIONS:
140
+ setattr(options, k, v)
141
+ elif hasattr(options, k):
142
+ raise RuntimeError(
143
+ f"SessionOptions attribute '{k}' is not permitted via the backend API. "
144
+ f"Allowed attributes: {', '.join(sorted(_ALLOWED_SESSION_OPTIONS))}"
145
+ )
146
+ # else: silently ignore unknown keys
147
+
148
+ excluded_providers = os.getenv("ORT_ONNX_BACKEND_EXCLUDE_PROVIDERS", default="").split(",")
149
+ providers = [x for x in get_available_providers() if (x not in excluded_providers)]
150
+
151
+ inf = InferenceSession(model, sess_options=options, providers=providers)
152
+ # backend API is primarily used for ONNX test/validation. As such, we should disable session.run() fallback
153
+ # which may hide test failures.
154
+ inf.disable_fallback()
155
+ if device is not None and not cls.supports_device(device):
156
+ raise RuntimeError(f"Incompatible device expected '{device}', got '{get_device()}'")
157
+ return cls.prepare(inf, device, **kwargs)
158
+ else:
159
+ # type: ModelProto
160
+ # check_model serializes the model anyways, so serialize the model once here
161
+ # and reuse it below in the cls.prepare call to avoid an additional serialization
162
+ # only works with onnx >= 1.10.0 hence the version check
163
+ onnx_version = packaging.version.parse(version.version) or packaging.version.Version("0")
164
+ onnx_supports_serialized_model_check = onnx_version.release >= (1, 10, 0)
165
+ bin_or_model = model.SerializeToString() if onnx_supports_serialized_model_check else model
166
+ check_model(bin_or_model)
167
+ opset_supported, error_message = cls.is_opset_supported(model)
168
+ if not opset_supported:
169
+ raise unittest.SkipTest(error_message)
170
+ # Now bin might be serialized, if it's not we need to serialize it otherwise we'll have
171
+ # an infinite recursive call
172
+ bin = bin_or_model
173
+ if not isinstance(bin, (str, bytes)):
174
+ bin = bin.SerializeToString()
175
+ return cls.prepare(bin, device, **kwargs)
176
+
177
+ @classmethod
178
+ def run_model(cls, model, inputs, device=None, **kwargs):
179
+ """
180
+ Compute the prediction.
181
+
182
+ :param model: the model to run — accepts a file path (str), serialized
183
+ model (bytes), :class:`onnx.ModelProto`, :class:`onnxruntime.InferenceSession`,
184
+ or :class:`onnxruntime.backend.backend_rep.OnnxRuntimeBackendRep`
185
+ :param inputs: inputs
186
+ :param device: requested device for the computation,
187
+ None means the default one which depends on
188
+ the compilation settings
189
+ :param kwargs: ``run_model()`` forwards kwargs to both ``prepare()`` and ``rep.run()``.
190
+ ``prepare()`` validates and applies ``_ALLOWED_SESSION_OPTIONS`` only when creating
191
+ a new session from a model path or bytes; if ``model`` is already an
192
+ ``InferenceSession`` or ``OnnxRuntimeBackendRep``, session-option kwargs are
193
+ silently ignored. ``rep.run()`` always validates against ``_ALLOWED_RUN_OPTIONS``
194
+ and raises ``RuntimeError`` for known-but-blocked run attributes.
195
+ Logging-related kwargs (``log_severity_level``, ``log_verbosity_level``, ``logid``)
196
+ appear in both allowlists.
197
+ :return: predictions
198
+ """
199
+ rep = cls.prepare(model, device, **kwargs)
200
+ return rep.run(inputs, **kwargs)
201
+
202
+ @classmethod
203
+ def run_node(cls, node, inputs, device=None, outputs_info=None, **kwargs):
204
+ """
205
+ This method is not implemented as it is much more efficient
206
+ to run a whole model than every node independently.
207
+ """
208
+ raise NotImplementedError("It is much more efficient to run a whole model than every node independently.")
209
+
210
+
211
+ is_compatible = OnnxRuntimeBackend.is_compatible
212
+ prepare = OnnxRuntimeBackend.prepare
213
+ run = OnnxRuntimeBackend.run_model
214
+ supports_device = OnnxRuntimeBackend.supports_device
ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/backend/backend_rep.py ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -------------------------------------------------------------------------
2
+ # Copyright (c) Microsoft Corporation. All rights reserved.
3
+ # Licensed under the MIT License.
4
+ # --------------------------------------------------------------------------
5
+ """
6
+ Implements ONNX's backend API.
7
+ """
8
+
9
+ from onnx.backend.base import BackendRep
10
+
11
+ from onnxruntime import RunOptions
12
+
13
+ # Allowlist of RunOptions attributes that are safe to set via the backend API.
14
+ # 'terminate' excluded: setting it True would deny the current inference call.
15
+ # 'training_mode' excluded: silently switches inference behavior in training builds.
16
+ _ALLOWED_RUN_OPTIONS = frozenset(
17
+ {
18
+ "log_severity_level",
19
+ "log_verbosity_level",
20
+ "logid",
21
+ "only_execute_path_to_fetches",
22
+ }
23
+ )
24
+
25
+
26
+ class OnnxRuntimeBackendRep(BackendRep):
27
+ """
28
+ Wraps an :class:`onnxruntime.InferenceSession` to implement ONNX's
29
+ :class:`onnx.backend.base.BackendRep` interface for running predictions.
30
+ """
31
+
32
+ def __init__(self, session):
33
+ """
34
+ :param session: :class:`onnxruntime.InferenceSession`
35
+ """
36
+ self._session = session
37
+
38
+ def run(self, inputs, **kwargs): # type: (Any, **Any) -> Tuple[Any, ...]
39
+ """
40
+ Computes the prediction.
41
+ See :meth:`onnxruntime.InferenceSession.run`.
42
+
43
+ :param inputs: a list of input arrays (one per model input) or a single
44
+ array when the model has exactly one input
45
+ :param kwargs: only a safe subset of :class:`onnxruntime.RunOptions` attributes are
46
+ accepted; see ``_ALLOWED_RUN_OPTIONS`` for the list
47
+ :return: list of output arrays
48
+ """
49
+
50
+ options = RunOptions()
51
+ for k, v in kwargs.items():
52
+ if k in _ALLOWED_RUN_OPTIONS:
53
+ setattr(options, k, v)
54
+ elif hasattr(options, k):
55
+ raise RuntimeError(
56
+ f"RunOptions attribute '{k}' is not permitted via the backend API. "
57
+ f"Allowed attributes: {', '.join(sorted(_ALLOWED_RUN_OPTIONS))}"
58
+ )
59
+ # else: silently ignore unknown keys
60
+
61
+ if isinstance(inputs, list):
62
+ inps = {}
63
+ for i, inp in enumerate(self._session.get_inputs()):
64
+ inps[inp.name] = inputs[i]
65
+ outs = self._session.run(None, inps, options)
66
+ if isinstance(outs, list):
67
+ return outs
68
+ else:
69
+ output_names = [o.name for o in self._session.get_outputs()]
70
+ return [outs[name] for name in output_names]
71
+ else:
72
+ inp = self._session.get_inputs()
73
+ if len(inp) != 1:
74
+ raise RuntimeError(f"Model expect {len(inp)} inputs")
75
+ inps = {inp[0].name: inputs}
76
+ return self._session.run(None, inps, options)
ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/capi/__init__.py ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ # -------------------------------------------------------------------------
2
+ # Copyright (c) Microsoft Corporation. All rights reserved.
3
+ # Licensed under the MIT License.
4
+ # --------------------------------------------------------------------------
ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/capi/_ld_preload.py ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ # -------------------------------------------------------------------------
2
+ # Copyright (c) Microsoft Corporation. All rights reserved.
3
+ # Licensed under the MIT License.
4
+ # --------------------------------------------------------------------------
5
+
6
+ # This file can be modified by setup.py when building a manylinux2010 wheel
7
+ # When modified, it will preload some libraries needed for the python C extension
ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/capi/_pybind_state.py ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -------------------------------------------------------------------------
2
+ # Copyright (c) Microsoft Corporation. All rights reserved.
3
+ # Licensed under the MIT License.
4
+ # --------------------------------------------------------------------------
5
+ """
6
+ Ensure that dependencies are available and then load the extension module.
7
+ """
8
+ import os
9
+ import platform
10
+ import warnings
11
+
12
+ from . import _ld_preload # noqa: F401
13
+
14
+ if platform.system() == "Windows":
15
+ from . import version_info
16
+
17
+ # If on Windows, check if this import error is caused by the user not installing the 2019 VC Runtime
18
+ # The VC Redist installer usually puts the VC Runtime dlls in the System32 folder, but it may also be found
19
+ # in some other locations.
20
+ # TODO, we may want to try to load the VC Runtime dlls instead of checking if the hardcoded file path
21
+ # is valid, and raise ImportError if the load fails
22
+ if version_info.vs2019 and platform.architecture()[0] == "64bit":
23
+ system_root = os.getenv("SystemRoot") or "C:\\Windows"
24
+ if not os.path.isfile(os.path.join(system_root, "System32", "vcruntime140_1.dll")):
25
+ warnings.warn("Please install the 2019 Visual C++ runtime and then try again. "
26
+ "If you've installed the runtime in a non-standard location "
27
+ "(other than %SystemRoot%\\System32), "
28
+ "make sure it can be found by setting the correct path.")
29
+
30
+
31
+
32
+ from .onnxruntime_pybind11_state import * # noqa
33
+
ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/capi/build_and_package_info.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ package_name = 'onnxruntime-gpu'
2
+ __version__ = '1.28.0'
3
+ cuda_version = '13.0'
ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/capi/convert_npz_to_onnx_adapter.py ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Microsoft Corporation. All rights reserved.
2
+ # Licensed under the MIT License.
3
+
4
+ # This script helps converting .npz files to .onnx_adapter files
5
+
6
+ import argparse
7
+ import os
8
+ import sys
9
+
10
+ import numpy as np
11
+
12
+ import onnxruntime as ort
13
+
14
+
15
+ def get_args() -> argparse:
16
+ parser = argparse.ArgumentParser()
17
+ parser.add_argument("--npz_file_path", type=str, required=True)
18
+ parser.add_argument("--output_file_path", type=str, required=True)
19
+ parser.add_argument("--adapter_version", type=int, required=True)
20
+ parser.add_argument("--model_version", type=int, required=True)
21
+ return parser.parse_args()
22
+
23
+
24
+ def export_lora_parameters(
25
+ npz_file_path: os.PathLike, adapter_version: int, model_version: int, output_file_path: os.PathLike
26
+ ):
27
+ """The function converts lora parameters in npz to onnx_adapter format"""
28
+ adapter_format = ort.AdapterFormat()
29
+ adapter_format.set_adapter_version(adapter_version)
30
+ adapter_format.set_model_version(model_version)
31
+ name_to_ort_value = {}
32
+ with np.load(npz_file_path) as data:
33
+ for name, np_arr in data.items():
34
+ ort_value = ort.OrtValue.ortvalue_from_numpy(np_arr)
35
+ name_to_ort_value[name] = ort_value
36
+
37
+ adapter_format.set_parameters(name_to_ort_value)
38
+ adapter_format.export_adapter(output_file_path)
39
+
40
+
41
+ def main() -> int:
42
+ args = get_args()
43
+ export_lora_parameters(args.npz_file_path, args.adapter_version, args.model_version, args.output_file_path)
44
+ return 0
45
+
46
+
47
+ if __name__ == "__main__":
48
+ sys.exit(main())
ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/capi/libonnxruntime_providers_shared.so ADDED
Binary file (14.6 kB). View file
 
ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/capi/onnxruntime_collect_build_info.py ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -------------------------------------------------------------------------
2
+ # Copyright (c) Microsoft Corporation. All rights reserved.
3
+ # Licensed under the MIT License.
4
+ # --------------------------------------------------------------------------
5
+ import ctypes
6
+ import sys
7
+ import warnings
8
+
9
+
10
+ def find_cudart_versions(build_env=False, build_cuda_version=None):
11
+ # ctypes.CDLL and ctypes.util.find_library load the latest installed library.
12
+ # it may not the the library that would be loaded by onnxruntime.
13
+ # for example, in an environment with Cuda 11.1 and subsequently
14
+ # conda cudatoolkit 10.2.89 installed. ctypes will find cudart 10.2. however,
15
+ # onnxruntime built with Cuda 11.1 will find and load cudart for Cuda 11.1.
16
+ # for the above reason, we need find all versions in the environment and
17
+ # only give warnings if the expected cuda version is not found.
18
+ # in onnxruntime build environment, we expected only one Cuda version.
19
+ if not sys.platform.startswith("linux"):
20
+ warnings.warn("find_cudart_versions only works on Linux")
21
+ return None
22
+
23
+ cudart_possible_versions = {None, build_cuda_version}
24
+
25
+ def get_cudart_version(find_cudart_version=None):
26
+ cudart_lib_filename = "libcudart.so"
27
+ if find_cudart_version:
28
+ cudart_lib_filename = cudart_lib_filename + "." + find_cudart_version
29
+
30
+ try:
31
+ cudart = ctypes.CDLL(cudart_lib_filename)
32
+ cudart.cudaRuntimeGetVersion.restype = int
33
+ cudart.cudaRuntimeGetVersion.argtypes = [ctypes.POINTER(ctypes.c_int)]
34
+ version = ctypes.c_int()
35
+ status = cudart.cudaRuntimeGetVersion(ctypes.byref(version))
36
+ if status != 0:
37
+ return None
38
+ except Exception:
39
+ return None
40
+
41
+ return version.value
42
+
43
+ # use set to avoid duplications
44
+ cudart_found_versions = {get_cudart_version(cudart_version) for cudart_version in cudart_possible_versions}
45
+
46
+ # convert to list and remove None
47
+ return [ver for ver in cudart_found_versions if ver]
ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/capi/onnxruntime_inference_collection.py ADDED
@@ -0,0 +1,1627 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -------------------------------------------------------------------------
2
+ # Copyright (c) Microsoft Corporation. All rights reserved.
3
+ # Licensed under the MIT License.
4
+ # --------------------------------------------------------------------------
5
+ from __future__ import annotations
6
+
7
+ import collections
8
+ import collections.abc
9
+ import os
10
+ import typing
11
+ import warnings
12
+ from collections.abc import Callable, Sequence
13
+ from enum import IntEnum
14
+ from typing import Any
15
+
16
+ import numpy as np
17
+
18
+ from onnxruntime.capi import _pybind_state as C
19
+
20
+ if typing.TYPE_CHECKING:
21
+ import numpy.typing as npt
22
+
23
+
24
+ def get_ort_device_type(device_type: str) -> int:
25
+ if device_type == "cuda":
26
+ return C.OrtDevice.cuda()
27
+ elif device_type == "cann":
28
+ return C.OrtDevice.cann()
29
+ elif device_type == "cpu":
30
+ return C.OrtDevice.cpu()
31
+ elif device_type == "dml":
32
+ return C.OrtDevice.dml()
33
+ elif device_type == "webgpu":
34
+ return C.OrtDevice.webgpu()
35
+ elif device_type == "gpu":
36
+ return C.OrtDevice.gpu()
37
+ elif device_type == "npu":
38
+ return C.OrtDevice.npu()
39
+ else:
40
+ raise Exception("Unsupported device type: " + device_type)
41
+
42
+
43
+ class OrtDeviceVendorId(IntEnum):
44
+ """Vendor IDs aligned with OrtDevice::VendorIds in ortdevice.h."""
45
+
46
+ NONE = 0x0000
47
+ AMD = 0x1002
48
+ NVIDIA = 0x10DE
49
+ ARM = 0x13B5
50
+ MICROSOFT = 0x1414
51
+ HUAWEI = 0x19E5
52
+ QUALCOMM = 0x5143
53
+ INTEL = 0x8086
54
+
55
+
56
+ def get_vendor_id_for_device_type(device_type: str) -> OrtDeviceVendorId | None:
57
+ if device_type == "cuda":
58
+ return OrtDeviceVendorId.NVIDIA
59
+ elif device_type == "dml":
60
+ return OrtDeviceVendorId.MICROSOFT
61
+ elif device_type == "cann":
62
+ return OrtDeviceVendorId.HUAWEI
63
+ else:
64
+ return None
65
+
66
+
67
+ class AdapterFormat:
68
+ """
69
+ This class is used to create adapter files from python structures
70
+ """
71
+
72
+ def __init__(self, adapter=None) -> None:
73
+ if adapter is None:
74
+ self._adapter = C.AdapterFormat()
75
+ else:
76
+ self._adapter = adapter
77
+
78
+ @staticmethod
79
+ def read_adapter(file_path: os.PathLike) -> AdapterFormat:
80
+ return AdapterFormat(C.AdapterFormat.read_adapter(file_path))
81
+
82
+ def export_adapter(self, file_path: os.PathLike):
83
+ """
84
+ This function writes a file at the specified location
85
+ in onnxrunitme adapter format containing Lora parameters.
86
+
87
+ :param file_path: absolute path for the adapter
88
+ """
89
+ self._adapter.export_adapter(file_path)
90
+
91
+ def get_format_version(self) -> int:
92
+ return self._adapter.format_version
93
+
94
+ def set_adapter_version(self, adapter_version: int) -> None:
95
+ self._adapter.adapter_version = adapter_version
96
+
97
+ def get_adapter_version(self) -> int:
98
+ return self._adapter.adapter_version
99
+
100
+ def set_model_version(self, model_version: int) -> None:
101
+ self._adapter.model_version = model_version
102
+
103
+ def get_model_version(self) -> int:
104
+ return self._adapter.model_version
105
+
106
+ def set_parameters(self, params: dict[str, OrtValue]) -> None:
107
+ """Set adapter parameters for export."""
108
+ self._adapter.parameters = {k: v._ortvalue for k, v in params.items()}
109
+
110
+ def get_parameters(self) -> dict[str, OrtValue]:
111
+ """Get adapter parameters as a dict of name -> OrtValue.
112
+
113
+ On read instances, the returned OrtValues are zero-copy views; the
114
+ backing memory stays alive as long as any returned OrtValue is referenced.
115
+ """
116
+ return {k: OrtValue(v) for k, v in self._adapter.parameters.items()}
117
+
118
+
119
+ def check_and_normalize_provider_args(
120
+ providers: Sequence[str | tuple[str, dict[Any, Any]]] | None,
121
+ provider_options: Sequence[dict[Any, Any]] | None,
122
+ available_provider_names: Sequence[str],
123
+ ):
124
+ """
125
+ Validates the 'providers' and 'provider_options' arguments and returns a
126
+ normalized version.
127
+
128
+ :param providers: Optional sequence of providers in order of decreasing
129
+ precedence. Values can either be provider names or tuples of
130
+ (provider name, options dict).
131
+ :param provider_options: Optional sequence of options dicts corresponding
132
+ to the providers listed in 'providers'.
133
+ :param available_provider_names: The available provider names.
134
+
135
+ :return: Tuple of (normalized 'providers' sequence, normalized
136
+ 'provider_options' sequence).
137
+
138
+ 'providers' can contain either names or names and options. When any options
139
+ are given in 'providers', 'provider_options' should not be used.
140
+
141
+ The normalized result is a tuple of:
142
+ 1. Sequence of provider names in the same order as 'providers'.
143
+ 2. Sequence of corresponding provider options dicts with string keys and
144
+ values. Unspecified provider options yield empty dicts.
145
+ """
146
+ if providers is None:
147
+ return [], []
148
+
149
+ provider_name_to_options = collections.OrderedDict()
150
+
151
+ def set_provider_options(name, options):
152
+ if name not in available_provider_names:
153
+ warnings.warn(
154
+ "Specified provider '{}' is not in available provider names.Available providers: '{}'".format(
155
+ name, ", ".join(available_provider_names)
156
+ )
157
+ )
158
+
159
+ if name in provider_name_to_options:
160
+ warnings.warn(f"Duplicate provider '{name}' encountered, ignoring.")
161
+ return
162
+
163
+ normalized_options = {str(key): str(value) for key, value in options.items()}
164
+ provider_name_to_options[name] = normalized_options
165
+
166
+ if not isinstance(providers, collections.abc.Sequence):
167
+ raise ValueError("'providers' should be a sequence.")
168
+
169
+ if provider_options is not None:
170
+ if not isinstance(provider_options, collections.abc.Sequence):
171
+ raise ValueError("'provider_options' should be a sequence.")
172
+
173
+ if len(providers) != len(provider_options):
174
+ raise ValueError("'providers' and 'provider_options' should be the same length if both are given.")
175
+
176
+ if not all(isinstance(provider, str) for provider in providers):
177
+ raise ValueError("Only string values for 'providers' are supported if 'provider_options' is given.")
178
+
179
+ if not all(isinstance(options_for_provider, dict) for options_for_provider in provider_options):
180
+ raise ValueError("'provider_options' values must be dicts.")
181
+
182
+ for name, options in zip(providers, provider_options, strict=False):
183
+ set_provider_options(name, options)
184
+
185
+ else:
186
+ for provider in providers:
187
+ if isinstance(provider, str):
188
+ set_provider_options(provider, {})
189
+ elif (
190
+ isinstance(provider, tuple)
191
+ and len(provider) == 2
192
+ and isinstance(provider[0], str)
193
+ and isinstance(provider[1], dict)
194
+ ):
195
+ set_provider_options(provider[0], provider[1])
196
+ else:
197
+ raise ValueError("'providers' values must be either strings or (string, dict) tuples.")
198
+
199
+ return list(provider_name_to_options.keys()), list(provider_name_to_options.values())
200
+
201
+
202
+ class Session:
203
+ """
204
+ This is the main class used to run a model.
205
+ """
206
+
207
+ def __init__(self, enable_fallback: bool = True):
208
+ # self._sess is managed by the derived class and relies on bindings from C.InferenceSession
209
+ self._sess = None
210
+ self._enable_fallback = enable_fallback
211
+
212
+ def get_session_options(self) -> C.SessionOptions:
213
+ "Return the session options. See :class:`onnxruntime.SessionOptions`."
214
+ return self._sess_options
215
+
216
+ def get_inputs(self) -> Sequence[C.NodeArg]:
217
+ "Return the inputs metadata as a list of :class:`onnxruntime.NodeArg`."
218
+ return self._inputs_meta
219
+
220
+ def get_outputs(self) -> Sequence[C.NodeArg]:
221
+ "Return the outputs metadata as a list of :class:`onnxruntime.NodeArg`."
222
+ return self._outputs_meta
223
+
224
+ def get_overridable_initializers(self) -> Sequence[C.NodeArg]:
225
+ "Return the inputs (including initializers) metadata as a list of :class:`onnxruntime.NodeArg`."
226
+ return self._overridable_initializers
227
+
228
+ def get_modelmeta(self) -> C.ModelMetadata:
229
+ "Return the metadata. See :class:`onnxruntime.ModelMetadata`."
230
+ return self._model_meta
231
+
232
+ def get_input_memory_infos(self) -> Sequence[C.OrtMemoryInfo]:
233
+ "Return the memory info for the inputs."
234
+ return self._input_meminfos
235
+
236
+ def get_output_memory_infos(self) -> Sequence[C.OrtMemoryInfo]:
237
+ "Return the memory info for the outputs."
238
+ return self._output_meminfos
239
+
240
+ def get_input_epdevices(self) -> Sequence[C.OrtEpDevice]:
241
+ "Return the execution providers for the inputs."
242
+ return self._input_epdevices
243
+
244
+ def get_providers(self) -> Sequence[str]:
245
+ "Return list of registered execution providers."
246
+ return self._providers
247
+
248
+ def get_provider_options(self):
249
+ "Return registered execution providers' configurations."
250
+ return self._provider_options
251
+
252
+ def get_provider_graph_assignment_info(self) -> Sequence[C.OrtEpAssignedSubgraph]:
253
+ """
254
+ Get information about the subgraphs assigned to each execution provider and the nodes within.
255
+
256
+ Application must enable the recording of graph assignment information by setting the session configuration
257
+ for the key "session.record_ep_graph_assignment_info" to "1".
258
+ """
259
+ return self._sess.get_provider_graph_assignment_info()
260
+
261
+ def set_providers(self, providers=None, provider_options=None) -> None:
262
+ """
263
+ Register the input list of execution providers. The underlying session is re-created.
264
+
265
+ :param providers: Optional sequence of providers in order of decreasing
266
+ precedence. Values can either be provider names or tuples of
267
+ (provider name, options dict). If not provided, then all available
268
+ providers are used with the default precedence.
269
+ :param provider_options: Optional sequence of options dicts corresponding
270
+ to the providers listed in 'providers'.
271
+
272
+ 'providers' can contain either names or names and options. When any options
273
+ are given in 'providers', 'provider_options' should not be used.
274
+
275
+ The list of providers is ordered by precedence. For example
276
+ `['CUDAExecutionProvider', 'CPUExecutionProvider']`
277
+ means execute a node using CUDAExecutionProvider if capable,
278
+ otherwise execute using CPUExecutionProvider.
279
+ """
280
+ # recreate the underlying C.InferenceSession
281
+ self._reset_session(providers, provider_options)
282
+
283
+ def disable_fallback(self) -> None:
284
+ """
285
+ Disable session.run() fallback mechanism.
286
+ """
287
+ self._enable_fallback = False
288
+
289
+ def enable_fallback(self) -> None:
290
+ """
291
+ Enable session.Run() fallback mechanism. If session.Run() fails due to an internal Execution Provider failure,
292
+ reset the Execution Providers enabled for this session.
293
+ If GPU is enabled, fall back to CUDAExecutionProvider.
294
+ otherwise fall back to CPUExecutionProvider.
295
+ """
296
+ self._enable_fallback = True
297
+
298
+ def _validate_input(self, feed_input_names):
299
+ missing_input_names = []
300
+ for input in self._inputs_meta:
301
+ if input.name not in feed_input_names and not input.type.startswith("optional"):
302
+ missing_input_names.append(input.name)
303
+ if missing_input_names:
304
+ raise ValueError(
305
+ f"Required inputs ({missing_input_names}) are missing from input feed ({feed_input_names})."
306
+ )
307
+
308
+ def run(self, output_names, input_feed, run_options=None) -> Sequence[np.ndarray | SparseTensor | list | dict]:
309
+ """
310
+ Compute the predictions.
311
+
312
+ :param output_names: name of the outputs
313
+ :param input_feed: dictionary ``{ input_name: input_value }``
314
+ :param run_options: See :class:`onnxruntime.RunOptions`.
315
+ :return: list of results, every result is either a numpy array,
316
+ a sparse tensor, a list or a dictionary.
317
+
318
+ ::
319
+
320
+ sess.run([output_name], {input_name: x})
321
+ """
322
+ self._validate_input(list(input_feed.keys()))
323
+ if not output_names:
324
+ output_names = [output.name for output in self._outputs_meta]
325
+ try:
326
+ return self._sess.run(output_names, input_feed, run_options)
327
+ except C.EPFail as err:
328
+ if self._enable_fallback:
329
+ print(f"EP Error: {err!s} using {self._providers}")
330
+ print(f"Falling back to {self._fallback_providers} and retrying.")
331
+ self.set_providers(self._fallback_providers)
332
+ # Fallback only once.
333
+ self.disable_fallback()
334
+ return self._sess.run(output_names, input_feed, run_options)
335
+ raise
336
+
337
+ def run_async(self, output_names, input_feed, callback, user_data, run_options=None):
338
+ """
339
+ Compute the predictions asynchronously in a separate cxx thread from ort intra-op threadpool.
340
+
341
+ :param output_names: name of the outputs
342
+ :param input_feed: dictionary ``{ input_name: input_value }``
343
+ :param callback: python function that accept array of results, and a status string on error.
344
+ The callback will be invoked by a cxx thread from ort intra-op threadpool.
345
+ :param run_options: See :class:`onnxruntime.RunOptions`.
346
+
347
+ ::
348
+ class MyData:
349
+ def __init__(self):
350
+ # ...
351
+ def save_results(self, results):
352
+ # ...
353
+
354
+ def callback(results: np.ndarray, user_data: MyData, err: str) -> None:
355
+ if err:
356
+ print (err)
357
+ else:
358
+ # save results to user_data
359
+
360
+ sess.run_async([output_name], {input_name: x}, callback)
361
+ """
362
+ self._validate_input(list(input_feed.keys()))
363
+ if not output_names:
364
+ output_names = [output.name for output in self._outputs_meta]
365
+ return self._sess.run_async(output_names, input_feed, callback, user_data, run_options)
366
+
367
+ def run_with_ort_values(self, output_names, input_dict_ort_values, run_options=None) -> Sequence[OrtValue]:
368
+ """
369
+ Compute the predictions.
370
+
371
+ :param output_names: name of the outputs
372
+ :param input_dict_ort_values: dictionary ``{ input_name: input_ort_value }``
373
+ See ``OrtValue`` class how to create `OrtValue`
374
+ from numpy array or `SparseTensor`
375
+ :param run_options: See :class:`onnxruntime.RunOptions`.
376
+ :return: an array of `OrtValue`
377
+
378
+ ::
379
+
380
+ sess.run([output_name], {input_name: x})
381
+ """
382
+
383
+ def invoke(sess, output_names, input_dict_ort_values, run_options):
384
+ input_dict = {}
385
+ for n, v in input_dict_ort_values.items():
386
+ input_dict[n] = v._get_c_value()
387
+ result = sess.run_with_ort_values(input_dict, output_names, run_options)
388
+ if not isinstance(result, C.OrtValueVector):
389
+ raise TypeError("run_with_ort_values() must return a instance of type 'OrtValueVector'.")
390
+ ort_values = [OrtValue(v) for v in result]
391
+ return ort_values
392
+
393
+ self._validate_input(list(input_dict_ort_values.keys()))
394
+ if not output_names:
395
+ output_names = [output.name for output in self._outputs_meta]
396
+ try:
397
+ return invoke(self._sess, output_names, input_dict_ort_values, run_options)
398
+ except C.EPFail as err:
399
+ if self._enable_fallback:
400
+ print(f"EP Error: {err!s} using {self._providers}")
401
+ print(f"Falling back to {self._fallback_providers} and retrying.")
402
+ self.set_providers(self._fallback_providers)
403
+ # Fallback only once.
404
+ self.disable_fallback()
405
+ return invoke(self._sess, output_names, input_dict_ort_values, run_options)
406
+ raise
407
+
408
+ def end_profiling(self):
409
+ """
410
+ End profiling and return results in a file.
411
+
412
+ The results are stored in a filename if the option
413
+ :meth:`onnxruntime.SessionOptions.enable_profiling`.
414
+ """
415
+ return self._sess.end_profiling()
416
+
417
+ def get_profiling_start_time_ns(self):
418
+ """
419
+ Return the nanoseconds of profiling's start time
420
+ Comparable to time.monotonic_ns() after Python 3.3
421
+ On some platforms, this timer may not be as precise as nanoseconds
422
+ For instance, on Windows and MacOS, the precision will be ~100ns
423
+ """
424
+ return self._sess.get_profiling_start_time_ns
425
+
426
+ def io_binding(self) -> IOBinding:
427
+ "Return an onnxruntime.IOBinding object`."
428
+ return IOBinding(self)
429
+
430
+ def run_with_iobinding(self, iobinding, run_options=None):
431
+ """
432
+ Compute the predictions.
433
+
434
+ :param iobinding: the iobinding object that has graph inputs/outputs bind.
435
+ :param run_options: See :class:`onnxruntime.RunOptions`.
436
+ """
437
+ self._sess.run_with_iobinding(iobinding._iobinding, run_options)
438
+
439
+ def set_ep_dynamic_options(self, options: dict[str, str]):
440
+ """
441
+ Set dynamic options for execution providers.
442
+
443
+ :param options: Dictionary of key-value pairs where both keys and values are strings.
444
+ These options will be passed to the execution providers to modify
445
+ their runtime behavior.
446
+ """
447
+ self._sess.set_ep_dynamic_options(options)
448
+
449
+ def get_tuning_results(self):
450
+ return self._sess.get_tuning_results()
451
+
452
+ def set_tuning_results(self, results, *, error_on_invalid=False):
453
+ return self._sess.set_tuning_results(results, error_on_invalid)
454
+
455
+ def run_with_ortvaluevector(self, run_options, feed_names, feeds, fetch_names, fetches, fetch_devices):
456
+ """
457
+ Compute the predictions similar to other run_*() methods but with minimal C++/Python conversion overhead.
458
+
459
+ :param run_options: See :class:`onnxruntime.RunOptions`.
460
+ :param feed_names: list of input names.
461
+ :param feeds: list of input OrtValue.
462
+ :param fetch_names: list of output names.
463
+ :param fetches: list of output OrtValue.
464
+ :param fetch_devices: list of output devices.
465
+ """
466
+ self._sess.run_with_ortvaluevector(run_options, feed_names, feeds, fetch_names, fetches, fetch_devices)
467
+
468
+
469
+ class InferenceSession(Session):
470
+ """
471
+ This is the main class used to run a model.
472
+ """
473
+
474
+ def __init__(
475
+ self,
476
+ path_or_bytes: str | bytes | os.PathLike,
477
+ sess_options: C.SessionOptions | None = None,
478
+ providers: Sequence[str | tuple[str, dict[Any, Any]]] | None = None,
479
+ provider_options: Sequence[dict[Any, Any]] | None = None,
480
+ **kwargs,
481
+ ) -> None:
482
+ """
483
+ :param path_or_bytes: Filename or serialized ONNX or ORT format model in a byte string.
484
+ :param sess_options: Session options.
485
+ :param providers: Optional sequence of providers in order of decreasing
486
+ precedence. Values can either be provider names or tuples of
487
+ (provider name, options dict). If not provided, then all available
488
+ providers are used with the default precedence.
489
+ :param provider_options: Optional sequence of options dicts corresponding
490
+ to the providers listed in 'providers'.
491
+
492
+ The model type will be inferred unless explicitly set in the SessionOptions.
493
+ To explicitly set:
494
+
495
+ ::
496
+
497
+ so = onnxruntime.SessionOptions()
498
+ # so.add_session_config_entry('session.load_model_format', 'ONNX') or
499
+ so.add_session_config_entry('session.load_model_format', 'ORT')
500
+
501
+ A file extension of '.ort' will be inferred as an ORT format model.
502
+ All other filenames are assumed to be ONNX format models.
503
+
504
+ 'providers' can contain either names or names and options. When any options
505
+ are given in 'providers', 'provider_options' should not be used.
506
+
507
+ The list of providers is ordered by precedence. For example
508
+ `['CUDAExecutionProvider', 'CPUExecutionProvider']`
509
+ means execute a node using `CUDAExecutionProvider`
510
+ if capable, otherwise execute using `CPUExecutionProvider`.
511
+ """
512
+ super().__init__(enable_fallback=int(kwargs.get("enable_fallback", 1)) == 1)
513
+
514
+ if isinstance(path_or_bytes, (str, os.PathLike)):
515
+ self._model_path = os.fspath(path_or_bytes)
516
+ self._model_bytes = None
517
+ elif isinstance(path_or_bytes, bytes):
518
+ self._model_path = None
519
+ self._model_bytes = path_or_bytes # TODO: This is bad as we're holding the memory indefinitely
520
+ else:
521
+ raise TypeError(f"Unable to load from type '{type(path_or_bytes)}'")
522
+
523
+ self._sess_options = sess_options
524
+ self._sess_options_initial = sess_options
525
+ if "read_config_from_model" in kwargs:
526
+ self._read_config_from_model = int(kwargs["read_config_from_model"]) == 1
527
+ else:
528
+ self._read_config_from_model = os.environ.get("ORT_LOAD_CONFIG_FROM_MODEL") == "1"
529
+
530
+ # internal parameters that we don't expect to be used in general so aren't documented
531
+ disabled_optimizers = kwargs.get("disabled_optimizers")
532
+
533
+ try:
534
+ self._create_inference_session(providers, provider_options, disabled_optimizers)
535
+ except (ValueError, RuntimeError) as e:
536
+ if self._enable_fallback:
537
+ try:
538
+ print("*************** EP Error ***************")
539
+ print(f"EP Error {e} when using {providers}")
540
+ print(f"Falling back to {self._fallback_providers} and retrying.")
541
+ print("****************************************")
542
+ self._create_inference_session(self._fallback_providers, None)
543
+ # Fallback only once.
544
+ self.disable_fallback()
545
+ return
546
+ except Exception as fallback_error:
547
+ raise fallback_error from e
548
+ # Fallback is disabled. Raise the original error.
549
+ raise e
550
+
551
+ def _create_inference_session(self, providers, provider_options, disabled_optimizers=None):
552
+ available_providers = C.get_available_providers()
553
+
554
+ # Validate that TensorrtExecutionProvider and NvTensorRTRTXExecutionProvider are not both specified
555
+ if providers:
556
+ has_tensorrt = any(
557
+ provider == "TensorrtExecutionProvider"
558
+ or (isinstance(provider, tuple) and provider[0] == "TensorrtExecutionProvider")
559
+ for provider in providers
560
+ )
561
+ has_tensorrt_rtx = any(
562
+ provider == "NvTensorRTRTXExecutionProvider"
563
+ or (isinstance(provider, tuple) and provider[0] == "NvTensorRTRTXExecutionProvider")
564
+ for provider in providers
565
+ )
566
+ if has_tensorrt and has_tensorrt_rtx:
567
+ raise ValueError(
568
+ "Cannot enable both 'TensorrtExecutionProvider' and 'NvTensorRTRTXExecutionProvider' "
569
+ "in the same session."
570
+ )
571
+ # Tensorrt and TensorRT RTX can fall back to CUDA if it's explicitly assigned. All others fall back to CPU.
572
+ if "NvTensorRTRTXExecutionProvider" in available_providers:
573
+ if (
574
+ providers
575
+ and any(
576
+ provider == "CUDAExecutionProvider"
577
+ or (isinstance(provider, tuple) and provider[0] == "CUDAExecutionProvider")
578
+ for provider in providers
579
+ )
580
+ and any(
581
+ provider == "NvTensorRTRTXExecutionProvider"
582
+ or (isinstance(provider, tuple) and provider[0] == "NvTensorRTRTXExecutionProvider")
583
+ for provider in providers
584
+ )
585
+ ):
586
+ self._fallback_providers = ["CUDAExecutionProvider", "CPUExecutionProvider"]
587
+ else:
588
+ self._fallback_providers = ["CPUExecutionProvider"]
589
+ elif "TensorrtExecutionProvider" in available_providers:
590
+ if (
591
+ providers
592
+ and any(
593
+ provider == "CUDAExecutionProvider"
594
+ or (isinstance(provider, tuple) and provider[0] == "CUDAExecutionProvider")
595
+ for provider in providers
596
+ )
597
+ and any(
598
+ provider == "TensorrtExecutionProvider"
599
+ or (isinstance(provider, tuple) and provider[0] == "TensorrtExecutionProvider")
600
+ for provider in providers
601
+ )
602
+ ):
603
+ self._fallback_providers = ["CUDAExecutionProvider", "CPUExecutionProvider"]
604
+ else:
605
+ self._fallback_providers = ["CPUExecutionProvider"]
606
+ else:
607
+ self._fallback_providers = ["CPUExecutionProvider"]
608
+
609
+ # validate providers and provider_options before other initialization
610
+ providers, provider_options = check_and_normalize_provider_args(
611
+ providers, provider_options, available_providers
612
+ )
613
+
614
+ # Print a warning if user passed providers to InferenceSession() but the SessionOptions instance
615
+ # already has provider information (e.g., via add_provider_for_devices()). The providers specified
616
+ # here will take precedence.
617
+ if self._sess_options is not None and (providers or provider_options) and self._sess_options.has_providers():
618
+ warnings.warn(
619
+ "Specified 'providers'/'provider_options' when creating InferenceSession but SessionOptions has "
620
+ "already been configured with providers. InferenceSession will only use the providers "
621
+ "passed to InferenceSession()."
622
+ )
623
+
624
+ session_options = self._sess_options if self._sess_options else C.get_default_session_options()
625
+
626
+ self._register_ep_custom_ops(session_options, providers, provider_options, available_providers)
627
+
628
+ if self._model_path:
629
+ sess = C.InferenceSession(session_options, self._model_path, True, self._read_config_from_model)
630
+ else:
631
+ sess = C.InferenceSession(session_options, self._model_bytes, False, self._read_config_from_model)
632
+
633
+ if disabled_optimizers is None:
634
+ disabled_optimizers = set()
635
+ elif not isinstance(disabled_optimizers, set):
636
+ # convert to set. assumes iterable
637
+ disabled_optimizers = set(disabled_optimizers)
638
+
639
+ # initialize the C++ InferenceSession
640
+ sess.initialize_session(providers, provider_options, disabled_optimizers)
641
+
642
+ self._sess = sess
643
+ self._sess_options = self._sess.session_options
644
+ self._inputs_meta = self._sess.inputs_meta
645
+ self._outputs_meta = self._sess.outputs_meta
646
+ self._overridable_initializers = self._sess.overridable_initializers
647
+ self._input_meminfos = self._sess.input_meminfos
648
+ self._output_meminfos = self._sess.output_meminfos
649
+ self._input_epdevices = self._sess.input_epdevices
650
+ self._model_meta = self._sess.model_meta
651
+ self._providers = self._sess.get_providers()
652
+ self._provider_options = self._sess.get_provider_options()
653
+ self._profiling_start_time_ns = self._sess.get_profiling_start_time_ns
654
+
655
+ def _reset_session(self, providers, provider_options) -> None:
656
+ "release underlying session object."
657
+ # meta data references session internal structures
658
+ # so they must be set to None to decrement _sess reference count.
659
+ self._sess_options = None
660
+ self._inputs_meta = None
661
+ self._outputs_meta = None
662
+ self._overridable_initializers = None
663
+ self._input_meminfos = None
664
+ self._output_meminfos = None
665
+ self._input_epdevices = None
666
+ self._model_meta = None
667
+ self._providers = None
668
+ self._provider_options = None
669
+ self._profiling_start_time_ns = None
670
+
671
+ # create a new C.InferenceSession
672
+ self._sess = None
673
+ self._sess_options = self._sess_options_initial
674
+ self._create_inference_session(providers, provider_options)
675
+
676
+ def _register_ep_custom_ops(self, session_options, providers, provider_options, available_providers):
677
+ for i in range(len(providers)):
678
+ if providers[i] in available_providers and providers[i] == "TensorrtExecutionProvider":
679
+ C.register_tensorrt_plugins_as_custom_ops(session_options, provider_options[i])
680
+ elif (
681
+ isinstance(providers[i], tuple)
682
+ and providers[i][0] in available_providers
683
+ and providers[i][0] == "TensorrtExecutionProvider"
684
+ ):
685
+ C.register_tensorrt_plugins_as_custom_ops(session_options, providers[i][1])
686
+
687
+ if providers[i] in available_providers and providers[i] == "NvTensorRTRTXExecutionProvider":
688
+ C.register_nv_tensorrt_rtx_plugins_as_custom_ops(session_options, provider_options[i])
689
+ elif (
690
+ isinstance(providers[i], tuple)
691
+ and providers[i][0] in available_providers
692
+ and providers[i][0] == "NvTensorrtRTXExecutionProvider"
693
+ ):
694
+ C.register_nv_tensorrt_rtx_plugins_as_custom_ops(session_options, providers[i][1])
695
+
696
+
697
+ def make_get_initializer_location_func_wrapper(
698
+ get_initializer_location_func: GetInitializerLocationFunc,
699
+ ) -> GetInitializerLocationWrapperFunc:
700
+ """
701
+ Wraps a user's "get initializer location" function. The returned wrapper function adheres to the
702
+ signature expected by ORT.
703
+
704
+ Need this wrapper to:
705
+ - Convert the `initializer_value` parameter from `C.OrtValue` to `onnxruntime.OrtValue`, which is more
706
+ convenient for the user's function to use.
707
+ - Allow the user's function to return the original `external_info` parameter (this wrapper makes a copy)
708
+ """
709
+
710
+ def get_initializer_location_func_wrapper(
711
+ initializer_name: str,
712
+ initializer_value: C.OrtValue,
713
+ external_info: C.OrtExternalInitializerInfo | None,
714
+ ) -> C.OrtExternalInitializerInfo | None:
715
+ ret_val: C.OrtExternalInitializerInfo | None = get_initializer_location_func(
716
+ initializer_name, OrtValue(initializer_value), external_info
717
+ )
718
+ if ret_val is not None and ret_val == external_info:
719
+ # User returned `external_info` (const and owned by ORT). ORT expects the returned value to be
720
+ # a new instance (that it deletes), so make a copy.
721
+ ret_val = C.OrtExternalInitializerInfo(ret_val.filepath, ret_val.file_offset, ret_val.byte_size)
722
+ return ret_val
723
+
724
+ return get_initializer_location_func_wrapper
725
+
726
+
727
+ class ModelCompiler:
728
+ """
729
+ This class is used to compile an ONNX model. A compiled ONNX model has EPContext nodes that each
730
+ encapsulates a subgraph compiled/optimized for a specific execution provider.
731
+
732
+ Refer to the EPContext design document for more information about EPContext models:
733
+ https://onnxruntime.ai/docs/execution-providers/EP-Context-Design.html
734
+
735
+ ::
736
+
737
+ sess_options = onnxruntime.SessionOptions()
738
+ sess_options.add_provider("SomeExecutionProvider", {"option1": "value1"})
739
+ # Alternatively, allow ONNX Runtime to select the provider automatically given a policy:
740
+ # sess_options.set_provider_selection_policy(onnxrt.OrtExecutionProviderDevicePolicy.PREFER_NPU)
741
+
742
+ model_compiler = onnxruntime.ModelCompiler(sess_options, "input_model.onnx")
743
+ model_compiler.compile_to_file("output_model.onnx")
744
+ """
745
+
746
+ def __init__(
747
+ self,
748
+ sess_options: C.SessionOptions,
749
+ input_model_path_or_bytes: str | os.PathLike | bytes,
750
+ embed_compiled_data_into_model: bool = False,
751
+ external_initializers_file_path: str | os.PathLike | None = None,
752
+ external_initializers_size_threshold: int = 1024,
753
+ flags: int = C.OrtCompileApiFlags.NONE,
754
+ graph_optimization_level: C.GraphOptimizationLevel = C.GraphOptimizationLevel.ORT_DISABLE_ALL,
755
+ get_initializer_location_func: GetInitializerLocationFunc | None = None,
756
+ ):
757
+ """
758
+ Creates a ModelCompiler instance.
759
+
760
+ :param sess_options: Session options containing the providers for which the model will be compiled.
761
+ Refer to SessionOptions.add_provider() and SessionOptions.set_provider_selection_policy().
762
+ :param input_model_path_or_bytes: The path to the input model file or bytes representing a serialized
763
+ ONNX model.
764
+ :param embed_compiled_data_into_model: Defaults to False. Set to True to embed compiled binary data into
765
+ EPContext nodes in the compiled model.
766
+ :param external_initializers_file_path: Defaults to None. Set to a path for a file that will store the
767
+ initializers for non-compiled nodes.
768
+ :param external_initializers_size_threshold: Defaults to 1024. Ignored if `external_initializers_file_path`
769
+ is None or empty. Initializers larger than this threshold are stored in the external initializers file.
770
+ :param flags: Additional boolean options to enable. Set this parameter to a bitwise OR of
771
+ flags in onnxruntime.OrtCompileApiFlags.
772
+ :param graph_optimization_level: The graph optimization level.
773
+ Defaults to onnxruntime.GraphOptimizationLevel.ORT_DISABLE_ALL.
774
+ :param get_initializer_location_func: Optional function called for every initializer to allow user to specify
775
+ whether an initializer should be stored within the model or externally. Example:
776
+ ```
777
+ def get_initializer_location(
778
+ initializer_name: str,
779
+ initializer_value: onnxrt.OrtValue,
780
+ external_info: onnxrt.OrtExternalInitializerInfo | None,
781
+ ) -> onnxrt.OrtExternalInitializerInfo | None:
782
+ byte_size = initializer_value.tensor_size_in_bytes()
783
+
784
+ if byte_size < 64:
785
+ return None # Store small initializer within compiled model.
786
+
787
+ # Else, write initializer to new external file.
788
+ value_np = initializer_value.numpy()
789
+ file_offset = ext_init_file.tell()
790
+ ext_init_file.write(value_np.tobytes())
791
+ return onnxrt.OrtExternalInitializerInfo(initializer_file_path, file_offset, byte_size)
792
+ ```
793
+ """
794
+ input_model_path: str | os.PathLike | None = None
795
+ input_model_bytes: bytes | None = None
796
+ if isinstance(input_model_path_or_bytes, (str, os.PathLike)):
797
+ if not input_model_path_or_bytes:
798
+ raise ValueError("Input model path is empty")
799
+ input_model_path = os.fspath(input_model_path_or_bytes)
800
+ elif isinstance(input_model_path_or_bytes, bytes):
801
+ if len(input_model_path_or_bytes) == 0:
802
+ raise ValueError("Input model bytes array is empty")
803
+ input_model_bytes = input_model_path_or_bytes
804
+ else:
805
+ raise TypeError(f"Unable to load from type '{type(input_model_path_or_bytes)}'")
806
+
807
+ if external_initializers_file_path:
808
+ if not isinstance(external_initializers_file_path, (str, os.PathLike)):
809
+ arg_type = type(external_initializers_file_path)
810
+ raise TypeError(f"Output external initializer filepath is of unexpected type '{arg_type}'")
811
+ external_initializers_file_path = os.fspath(external_initializers_file_path)
812
+ else:
813
+ external_initializers_file_path = ""
814
+
815
+ if get_initializer_location_func is not None:
816
+ if external_initializers_file_path:
817
+ raise ValueError(
818
+ "Cannot initialize ModelCompiler with both `external_initializers_file_path` "
819
+ "and `get_initializer_location_func`"
820
+ )
821
+ self.get_initializer_location_func_wrapper = make_get_initializer_location_func_wrapper(
822
+ get_initializer_location_func
823
+ )
824
+ else:
825
+ self.get_initializer_location_func_wrapper = None
826
+
827
+ if input_model_path:
828
+ self._model_compiler = C.ModelCompiler(
829
+ sess_options,
830
+ input_model_path,
831
+ True, # is path
832
+ embed_compiled_data_into_model,
833
+ external_initializers_file_path,
834
+ external_initializers_size_threshold,
835
+ flags,
836
+ graph_optimization_level,
837
+ self.get_initializer_location_func_wrapper,
838
+ )
839
+ else:
840
+ self._model_compiler = C.ModelCompiler(
841
+ sess_options,
842
+ input_model_bytes,
843
+ False, # is bytes
844
+ embed_compiled_data_into_model,
845
+ external_initializers_file_path,
846
+ external_initializers_size_threshold,
847
+ flags,
848
+ graph_optimization_level,
849
+ self.get_initializer_location_func_wrapper,
850
+ )
851
+
852
+ def compile_to_file(self, output_model_path: str | None = None):
853
+ """
854
+ Compiles to an output file. If an output file path is not provided,
855
+ the output file path is generated based on the input model path by replacing
856
+ '.onnx' with '_ctx.onnx'. Ex: The generated output file is 'model_ctx.onnx' for
857
+ an input model with path 'model.onnx'.
858
+
859
+ Raises an 'InvalidArgument' exception if the compilation options are invalid.
860
+
861
+ :param output_model_path: Defaults to None. The path for the output/compiled model.
862
+ """
863
+ if output_model_path:
864
+ if not isinstance(output_model_path, (str, os.PathLike)):
865
+ raise TypeError(f"Output model's filepath is of unexpected type '{type(output_model_path)}'")
866
+ output_model_path = os.fspath(output_model_path)
867
+ self._model_compiler.compile_to_file(output_model_path)
868
+
869
+ def compile_to_bytes(self) -> bytes:
870
+ """
871
+ Compiles to bytes representing the serialized compiled ONNX model.
872
+
873
+ Raises an 'InvalidArgument' exception if the compilation options are invalid.
874
+
875
+ :return: A bytes object representing the compiled ONNX model.
876
+ """
877
+ return self._model_compiler.compile_to_bytes()
878
+
879
+ def compile_to_stream(self, write_function: Callable[[bytes], None]):
880
+ """
881
+ Compiles the input model and writes the serialized ONNX bytes to a stream using the provided write function.
882
+ Raises an 'InvalidArgument' exception if the compilation options are invalid.
883
+ :param write_function: A callable that accepts a bytes buffer to write.
884
+ """
885
+ self._model_compiler.compile_to_stream(write_function)
886
+
887
+
888
+ class IOBinding:
889
+ """
890
+ This class provides API to bind input/output to a specified device, e.g. GPU.
891
+ """
892
+
893
+ def __init__(self, session: Session):
894
+ self._iobinding = C.SessionIOBinding(session._sess)
895
+ self._numpy_obj_references = {}
896
+
897
+ def bind_cpu_input(self, name, arr_on_cpu):
898
+ """
899
+ bind an input to array on CPU
900
+ :param name: input name
901
+ :param arr_on_cpu: input values as a python array on CPU
902
+ """
903
+ # Hold a reference to the numpy object as the bound OrtValue is backed
904
+ # directly by the data buffer of the numpy object and so the numpy object
905
+ # must be around until this IOBinding instance is around
906
+ self._numpy_obj_references[name] = arr_on_cpu
907
+ self._iobinding.bind_input(name, arr_on_cpu)
908
+
909
+ def bind_input(self, name, device_type, device_id, element_type, shape, buffer_ptr):
910
+ """
911
+ :param name: input name
912
+ :param device_type: e.g. cpu, cuda, cann
913
+ :param device_id: device id, e.g. 0
914
+ :param element_type: input element type. It can be either numpy type (like numpy.float32) or an integer for onnx type (like onnx.TensorProto.BFLOAT16)
915
+ :param shape: input shape
916
+ :param buffer_ptr: memory pointer to input data
917
+ """
918
+ self._iobinding.bind_input(
919
+ name,
920
+ C.OrtDevice(
921
+ get_ort_device_type(device_type),
922
+ C.OrtDevice.default_memory(),
923
+ device_id,
924
+ ),
925
+ element_type,
926
+ shape,
927
+ buffer_ptr,
928
+ )
929
+
930
+ def bind_ortvalue_input(self, name, ortvalue):
931
+ """
932
+ :param name: input name
933
+ :param ortvalue: OrtValue instance to bind
934
+ """
935
+ self._iobinding.bind_ortvalue_input(name, ortvalue._ortvalue)
936
+
937
+ def synchronize_inputs(self):
938
+ self._iobinding.synchronize_inputs()
939
+
940
+ def bind_output(
941
+ self,
942
+ name,
943
+ device_type="cpu",
944
+ device_id=0,
945
+ element_type=None,
946
+ shape=None,
947
+ buffer_ptr=None,
948
+ ):
949
+ """
950
+ :param name: output name
951
+ :param device_type: e.g. cpu, cuda, cann, cpu by default
952
+ :param device_id: device id, e.g. 0
953
+ :param element_type: output element type. It can be either numpy type (like numpy.float32) or an integer for onnx type (like onnx.TensorProto.BFLOAT16)
954
+ :param shape: output shape
955
+ :param buffer_ptr: memory pointer to output data
956
+ """
957
+
958
+ # Follow the `if` path when the user has not provided any pre-allocated buffer but still
959
+ # would like to bind an output to a specific device (e.g. cuda).
960
+ # Pre-allocating an output buffer may not be an option for the user as :
961
+ # (1) They may not want to use a custom allocator specific to the device they want to bind the output to,
962
+ # in which case ORT will allocate the memory for the user
963
+ # (2) The output has a dynamic shape and hence the size of the buffer may not be fixed across runs
964
+ if buffer_ptr is None:
965
+ self._iobinding.bind_output(
966
+ name,
967
+ C.OrtDevice(
968
+ get_ort_device_type(device_type),
969
+ C.OrtDevice.default_memory(),
970
+ device_id,
971
+ ),
972
+ )
973
+ else:
974
+ if element_type is None or shape is None:
975
+ raise ValueError("`element_type` and `shape` are to be provided if pre-allocated memory is provided")
976
+ self._iobinding.bind_output(
977
+ name,
978
+ C.OrtDevice(
979
+ get_ort_device_type(device_type),
980
+ C.OrtDevice.default_memory(),
981
+ device_id,
982
+ ),
983
+ element_type,
984
+ shape,
985
+ buffer_ptr,
986
+ )
987
+
988
+ def bind_ortvalue_output(self, name, ortvalue):
989
+ """
990
+ :param name: output name
991
+ :param ortvalue: OrtValue instance to bind
992
+ """
993
+ self._iobinding.bind_ortvalue_output(name, ortvalue._ortvalue)
994
+
995
+ def synchronize_outputs(self):
996
+ self._iobinding.synchronize_outputs()
997
+
998
+ def get_outputs(self):
999
+ """
1000
+ Returns the output OrtValues from the Run() that preceded the call.
1001
+ The data buffer of the obtained OrtValues may not reside on CPU memory
1002
+ """
1003
+ outputs = self._iobinding.get_outputs()
1004
+ if not isinstance(outputs, C.OrtValueVector):
1005
+ raise TypeError("get_outputs() must return an instance of type 'OrtValueVector'.")
1006
+ return [OrtValue(ortvalue) for ortvalue in outputs]
1007
+
1008
+ def get_outputs_as_ortvaluevector(self):
1009
+ return self._iobinding.get_outputs()
1010
+
1011
+ def copy_outputs_to_cpu(self):
1012
+ """Copy output contents to CPU."""
1013
+ return self._iobinding.copy_outputs_to_cpu()
1014
+
1015
+ def clear_binding_inputs(self):
1016
+ self._iobinding.clear_binding_inputs()
1017
+
1018
+ def clear_binding_outputs(self):
1019
+ self._iobinding.clear_binding_outputs()
1020
+
1021
+
1022
+ class OrtValue:
1023
+ """
1024
+ A data structure that supports all ONNX data formats (tensors and non-tensors) that allows users
1025
+ to place the data backing these on a device, for example, on a CUDA supported device.
1026
+ This class provides APIs to construct and deal with OrtValues.
1027
+ """
1028
+
1029
+ def __init__(self, ortvalue: C.OrtValue, numpy_obj: np.ndarray | None = None):
1030
+ if isinstance(ortvalue, C.OrtValue):
1031
+ self._ortvalue = ortvalue
1032
+ # Hold a ref count to the numpy object if the OrtValue is backed directly
1033
+ # by its data buffer so that it isn't destroyed when the OrtValue is in use
1034
+ self._numpy_obj = numpy_obj
1035
+ else:
1036
+ # An end user won't hit this error
1037
+ raise ValueError(
1038
+ "`Provided ortvalue` needs to be of type `onnxruntime.capi.onnxruntime_pybind11_state.OrtValue`"
1039
+ )
1040
+
1041
+ def _get_c_value(self) -> C.OrtValue:
1042
+ return self._ortvalue
1043
+
1044
+ @classmethod
1045
+ def ortvalue_from_numpy(
1046
+ cls, numpy_obj: np.ndarray, /, device_type="cpu", device_id=0, vendor_id: int | OrtDeviceVendorId = -1
1047
+ ) -> OrtValue:
1048
+ """
1049
+ Factory method to construct an OrtValue (which holds a Tensor) from a given Numpy object
1050
+ A copy of the data in the Numpy object is held by the OrtValue only if the device is NOT cpu
1051
+
1052
+ :param numpy_obj: The Numpy object to construct the OrtValue from
1053
+ :param device_type: e.g. cpu, cuda, cann, cpu by default
1054
+ :param device_id: device id, e.g. 0
1055
+ :param vendor_id: The device's PCI vendor id as an int or OrtDeviceVendorId. If provided, the device_type should be "gpu" or "npu".
1056
+ """
1057
+ # Hold a reference to the numpy object (if device_type is 'cpu') as the OrtValue
1058
+ # is backed directly by the data buffer of the numpy object and so the numpy object
1059
+ # must be around until this OrtValue instance is around
1060
+ return cls(
1061
+ C.OrtValue.ortvalue_from_numpy(
1062
+ numpy_obj,
1063
+ OrtDevice.make(device_type, device_id, vendor_id)._get_c_device(),
1064
+ ),
1065
+ numpy_obj if device_type.lower() == "cpu" else None,
1066
+ )
1067
+
1068
+ @classmethod
1069
+ def ortvalue_from_numpy_with_onnx_type(cls, data: np.ndarray, /, onnx_element_type: int) -> OrtValue:
1070
+ """
1071
+ This method creates an instance of OrtValue on top of the numpy array.
1072
+ No data copy is made and the lifespan of the resulting OrtValue should never
1073
+ exceed the lifespan of bytes object. The API attempts to reinterpret
1074
+ the data type which is expected to be the same size. This is useful
1075
+ when we want to use an ONNX data type that is not supported by numpy.
1076
+
1077
+ :param data: numpy.ndarray.
1078
+ :param onnx_element_type: a valid onnx TensorProto::DataType enum value
1079
+ """
1080
+ return cls(C.OrtValue.ortvalue_from_numpy_with_onnx_type(data, onnx_element_type), data)
1081
+
1082
+ @classmethod
1083
+ def ortvalue_from_shape_and_type(
1084
+ cls,
1085
+ shape: Sequence[int],
1086
+ element_type,
1087
+ device_type: str = "cpu",
1088
+ device_id: int = 0,
1089
+ vendor_id: int | OrtDeviceVendorId = -1,
1090
+ memory_info: C.OrtMemoryInfo | None = None,
1091
+ ) -> OrtValue:
1092
+ """
1093
+ Factory method to construct an OrtValue (which holds a Tensor) from given shape and element_type
1094
+
1095
+ :param shape: List of integers indicating the shape of the OrtValue
1096
+ :param element_type: The data type of the elements. It can be either numpy type (like numpy.float32) or an integer for onnx type (like onnx.TensorProto.BFLOAT16).
1097
+ :param device_type: e.g. cpu, cuda, cann, cpu by default
1098
+ :param device_id: device id, e.g. 0
1099
+ :param vendor_id: The device's PCI vendor id as an int or OrtDeviceVendorId. If provided, the device type should be "gpu" or "npu".
1100
+ :param memory_info: An OrtMemoryInfo from an OrtEpDevice (e.g. via ep_device.memory_info(OrtDeviceMemoryType.HOST_ACCESSIBLE)). When provided, the allocator matching this memory info is used directly, which allows allocating HOST_ACCESSIBLE memory for zero-copy numpy interop. The device_type, device_id, and vendor_id parameters are ignored when memory_info is provided.
1101
+ """
1102
+
1103
+ if memory_info is not None:
1104
+ if device_type != "cpu" or device_id != 0 or vendor_id != -1:
1105
+ warnings.warn(
1106
+ "device_type, device_id, and vendor_id are ignored when memory_info is provided.",
1107
+ stacklevel=2,
1108
+ )
1109
+ if isinstance(element_type, int):
1110
+ return cls(
1111
+ C.OrtValue.ortvalue_from_shape_and_onnx_type_for_memory_info(
1112
+ shape,
1113
+ element_type,
1114
+ memory_info,
1115
+ )
1116
+ )
1117
+ return cls(
1118
+ C.OrtValue.ortvalue_from_shape_and_type_for_memory_info(
1119
+ shape,
1120
+ element_type,
1121
+ memory_info,
1122
+ )
1123
+ )
1124
+
1125
+ device = OrtDevice.make(device_type, device_id, vendor_id)._get_c_device()
1126
+
1127
+ # Integer for onnx element type (see https://onnx.ai/onnx/api/mapping.html).
1128
+ # This is helpful for some data type (like TensorProto.BFLOAT16) that is not available in numpy.
1129
+ if isinstance(element_type, int):
1130
+ return cls(
1131
+ C.OrtValue.ortvalue_from_shape_and_onnx_type(
1132
+ shape,
1133
+ element_type,
1134
+ device,
1135
+ )
1136
+ )
1137
+
1138
+ return cls(
1139
+ C.OrtValue.ortvalue_from_shape_and_type(
1140
+ shape,
1141
+ element_type,
1142
+ device,
1143
+ )
1144
+ )
1145
+
1146
+ @classmethod
1147
+ def ort_value_from_sparse_tensor(cls, sparse_tensor: SparseTensor) -> OrtValue:
1148
+ """
1149
+ The function will construct an OrtValue instance from a valid SparseTensor
1150
+ The new instance of OrtValue will assume the ownership of sparse_tensor
1151
+ """
1152
+ return cls(C.OrtValue.ort_value_from_sparse_tensor(sparse_tensor._get_c_tensor()))
1153
+
1154
+ def as_sparse_tensor(self) -> SparseTensor:
1155
+ """
1156
+ The function will return SparseTensor contained in this OrtValue
1157
+ """
1158
+ return SparseTensor(self._ortvalue.as_sparse_tensor())
1159
+
1160
+ def data_ptr(self) -> int:
1161
+ """
1162
+ Returns the address of the first element in the OrtValue's data buffer
1163
+ """
1164
+ return self._ortvalue.data_ptr()
1165
+
1166
+ def device_name(self) -> str:
1167
+ """
1168
+ Returns the name of the device where the OrtValue's data buffer resides e.g. cpu, cuda, cann
1169
+ """
1170
+ return self._ortvalue.device_name().lower()
1171
+
1172
+ def shape(self) -> Sequence[int]:
1173
+ """
1174
+ Returns the shape of the data in the OrtValue
1175
+ """
1176
+ return self._ortvalue.shape()
1177
+
1178
+ def data_type(self) -> str:
1179
+ """
1180
+ Returns the data type of the data in the OrtValue. E.g. 'tensor(int64)'
1181
+ """
1182
+ return self._ortvalue.data_type()
1183
+
1184
+ def element_type(self) -> int:
1185
+ """
1186
+ Returns the proto type of the data in the OrtValue
1187
+ if the OrtValue is a tensor.
1188
+ """
1189
+ return self._ortvalue.element_type()
1190
+
1191
+ def tensor_size_in_bytes(self) -> int:
1192
+ """
1193
+ Returns the size of the data in the OrtValue in bytes
1194
+ if the OrtValue is a tensor.
1195
+ """
1196
+ return self._ortvalue.tensor_size_in_bytes()
1197
+
1198
+ def has_value(self) -> bool:
1199
+ """
1200
+ Returns True if the OrtValue corresponding to an
1201
+ optional type contains data, else returns False
1202
+ """
1203
+ return self._ortvalue.has_value()
1204
+
1205
+ def is_tensor(self) -> bool:
1206
+ """
1207
+ Returns True if the OrtValue contains a Tensor, else returns False
1208
+ """
1209
+ return self._ortvalue.is_tensor()
1210
+
1211
+ def is_sparse_tensor(self) -> bool:
1212
+ """
1213
+ Returns True if the OrtValue contains a SparseTensor, else returns False
1214
+ """
1215
+ return self._ortvalue.is_sparse_tensor()
1216
+
1217
+ def is_tensor_sequence(self) -> bool:
1218
+ """
1219
+ Returns True if the OrtValue contains a Tensor Sequence, else returns False
1220
+ """
1221
+ return self._ortvalue.is_tensor_sequence()
1222
+
1223
+ def numpy(self) -> np.ndarray:
1224
+ """
1225
+ Returns a Numpy object from the OrtValue.
1226
+ Valid only for OrtValues holding Tensors. Throws for OrtValues holding non-Tensors.
1227
+ Use accessors to gain a reference to non-Tensor objects such as SparseTensor
1228
+ """
1229
+ return self._ortvalue.numpy()
1230
+
1231
+ def __array__(self, dtype=None, copy=None) -> np.ndarray:
1232
+ """
1233
+ Supports ``numpy.asarray(ortvalue)`` and ``numpy.array(ortvalue)`` via the
1234
+ `numpy __array__ protocol <https://numpy.org/devdocs/user/basics.interoperability.html>`_.
1235
+
1236
+ Valid only for OrtValues holding Tensors on CPU.
1237
+
1238
+ :param dtype: Optional numpy dtype to cast the result to.
1239
+ :param copy: Optional bool (numpy >= 2.0). If ``False``, a copy will
1240
+ only be made if necessary. If ``True``, a copy is always forced.
1241
+ If ``None`` (default), a copy will be made only if needed.
1242
+ :return: A numpy array with the same data as the OrtValue.
1243
+ """
1244
+ arr = self.numpy()
1245
+
1246
+ if copy is not None:
1247
+ # numpy >= 2.0 added the copy kwarg to np.asarray;
1248
+ # np.array has always accepted it but with weaker semantics pre-2.0.
1249
+ arr = np.array(arr, dtype=dtype, copy=copy)
1250
+ elif dtype is not None:
1251
+ # np.asarray avoids a copy when the dtype already matches,
1252
+ # preserving memory sharing with the underlying OrtValue.
1253
+ arr = np.asarray(arr, dtype=dtype)
1254
+
1255
+ return arr
1256
+
1257
+ def __dlpack__(self, *, stream=None):
1258
+ """
1259
+ Returns a DLPack capsule representing the tensor (part of the
1260
+ `DLPack protocol <https://dmlc.github.io/dlpack/latest/>`_).
1261
+
1262
+ This enables interoperability with other frameworks via
1263
+ ``from_dlpack(ortvalue)`` (e.g. ``torch.from_dlpack``,
1264
+ ``jax.dlpack.from_dlpack``, ``numpy.from_dlpack``).
1265
+
1266
+ The OrtValue must hold a contiguous tensor. No data is copied;
1267
+ the consumer shares memory with this OrtValue, which must remain
1268
+ alive while the capsule is in use.
1269
+
1270
+ :param stream: Optional stream on which the tensor data is accessible.
1271
+ Currently unused; included for protocol compliance.
1272
+ :return: A PyCapsule holding a DLManagedTensor.
1273
+ """
1274
+ return self._ortvalue.__dlpack__(stream=stream)
1275
+
1276
+ def __dlpack_device__(self) -> tuple[int, int]:
1277
+ """
1278
+ Returns ``(device_type, device_id)`` indicating where the tensor data
1279
+ resides (part of the `DLPack protocol
1280
+ <https://dmlc.github.io/dlpack/latest/>`_).
1281
+
1282
+ :return: Tuple of ``(device_type, device_id)`` as ints following DLPack
1283
+ ``DLDeviceType`` enum values.
1284
+ """
1285
+ return self._ortvalue.__dlpack_device__()
1286
+
1287
+ @classmethod
1288
+ def from_dlpack(cls, data, /) -> OrtValue:
1289
+ """
1290
+ Construct an OrtValue from an object that implements the DLPack protocol.
1291
+
1292
+ Accepts either:
1293
+
1294
+ * An object with ``__dlpack__`` / ``__dlpack_device__`` methods
1295
+ (e.g. a PyTorch tensor, JAX array, or numpy array).
1296
+ * A raw DLPack PyCapsule (legacy path).
1297
+
1298
+ Boolean tensors are automatically detected when the source object
1299
+ exposes a ``dtype`` attribute (numpy, PyTorch, etc.) or is an
1300
+ ``OrtValue``. For raw DLPack capsules where the original dtype cannot
1301
+ be inspected, bool tensors encoded as uint8 by older DLPack versions
1302
+ are not distinguishable from true uint8 tensors and will be imported
1303
+ as uint8.
1304
+
1305
+ No data is copied; the new OrtValue shares memory with the source.
1306
+
1307
+ :param data: A tensor object supporting the DLPack protocol, or a raw
1308
+ DLPack PyCapsule.
1309
+ :return: An OrtValue wrapping the tensor data.
1310
+ """
1311
+ # Detect boolean dtype from the source object before consuming it,
1312
+ # because DLPack encodes bool as uint8 and the capsule alone cannot
1313
+ # distinguish between the two.
1314
+ is_bool = False
1315
+ if isinstance(data, OrtValue):
1316
+ is_bool = data.data_type() == "tensor(bool)"
1317
+ elif hasattr(data, "dtype"):
1318
+ dtype_obj = data.dtype
1319
+ # Use .name when available (numpy, cupy, tensorflow all expose it).
1320
+ # Fall back to str() for frameworks that don't (e.g. PyTorch).
1321
+ dtype_name = getattr(dtype_obj, "name", str(dtype_obj))
1322
+ is_bool = dtype_name in ("bool", "bool_", "torch.bool")
1323
+
1324
+ # If the input supports the __dlpack__ protocol, call it to get the capsule.
1325
+ if hasattr(data, "__dlpack__"):
1326
+ capsule = data.__dlpack__()
1327
+ else:
1328
+ capsule = data
1329
+
1330
+ return cls(C.OrtValue.from_dlpack(capsule, is_bool))
1331
+
1332
+ def update_inplace(self, data) -> None:
1333
+ """
1334
+ Update the OrtValue in place. The source data is copied over to the device
1335
+ memory backing the OrtValue. It can be used to update the input values for
1336
+ an InferenceSession with CUDA graph enabled or other scenarios where the
1337
+ OrtValue needs to be updated while the memory address can not be changed.
1338
+
1339
+ :param data: The source data, which can be a Numpy array or another OrtValue.
1340
+ When an OrtValue is provided, data can be copied between devices (e.g.,
1341
+ GPU to GPU) without going through the CPU.
1342
+ """
1343
+ if isinstance(data, OrtValue):
1344
+ self._ortvalue.update_inplace(data._ortvalue)
1345
+ return
1346
+
1347
+ if not isinstance(data, np.ndarray):
1348
+ raise TypeError("data must be a numpy.ndarray or an OrtValue.")
1349
+
1350
+ self._ortvalue.update_inplace(data)
1351
+
1352
+
1353
+ def copy_tensors(src: Sequence[OrtValue], dst: Sequence[OrtValue], stream=None) -> None:
1354
+ """
1355
+ Copy tensor data from source OrtValue sequence to destination OrtValue sequence.
1356
+ """
1357
+ c_sources = [s._get_c_value() for s in src]
1358
+ c_dsts = [d._get_c_value() for d in dst]
1359
+ C.copy_tensors(c_sources, c_dsts, stream)
1360
+
1361
+
1362
+ class OrtDevice:
1363
+ """
1364
+ A data structure that exposes the underlying C++ OrtDevice
1365
+ """
1366
+
1367
+ def __init__(self, c_ort_device):
1368
+ """
1369
+ Internal constructor
1370
+ """
1371
+ if isinstance(c_ort_device, C.OrtDevice):
1372
+ self._ort_device = c_ort_device
1373
+ else:
1374
+ # An end user won't hit this error
1375
+ raise ValueError(
1376
+ "`Provided object` needs to be of type `onnxruntime.capi.onnxruntime_pybind11_state.OrtDevice`"
1377
+ )
1378
+
1379
+ def _get_c_device(self):
1380
+ """
1381
+ Internal accessor to underlying object
1382
+ """
1383
+ return self._ort_device
1384
+
1385
+ @staticmethod
1386
+ def make(ort_device_name, device_id, vendor_id: int | OrtDeviceVendorId = -1):
1387
+ if vendor_id < 0:
1388
+ # Preserve the historical convenience aliases ("cuda", "dml", "cann")
1389
+ # while making them work with plugin EP shared allocators. Those
1390
+ # allocators are keyed by vendor-specific OrtDevice values even when the
1391
+ # Python package itself was built without the corresponding built-in EP.
1392
+ alias_vendor_id = get_vendor_id_for_device_type(ort_device_name)
1393
+ if alias_vendor_id is not None:
1394
+ return OrtDevice(
1395
+ C.OrtDevice(
1396
+ get_ort_device_type(ort_device_name),
1397
+ C.OrtDevice.default_memory(),
1398
+ int(alias_vendor_id),
1399
+ device_id,
1400
+ )
1401
+ )
1402
+
1403
+ # backwards compatibility with generic predefined OrtDevice names
1404
+ return OrtDevice(
1405
+ C.OrtDevice(
1406
+ get_ort_device_type(ort_device_name),
1407
+ C.OrtDevice.default_memory(),
1408
+ device_id,
1409
+ )
1410
+ )
1411
+ else:
1412
+ # generic. use GPU or NPU for ort_device_name and provide a vendor id.
1413
+ # vendor id of 0 is valid in some cases (e.g. webgpu is generic and does not have a vendor id)
1414
+ return OrtDevice(
1415
+ C.OrtDevice(
1416
+ get_ort_device_type(ort_device_name),
1417
+ C.OrtDevice.default_memory(),
1418
+ int(vendor_id),
1419
+ device_id,
1420
+ )
1421
+ )
1422
+
1423
+ def device_id(self):
1424
+ return self._ort_device.device_id()
1425
+
1426
+ def device_type(self):
1427
+ return self._ort_device.device_type()
1428
+
1429
+ def device_vendor_id(self):
1430
+ return self._ort_device.vendor_id()
1431
+
1432
+ def device_mem_type(self):
1433
+ return self._ort_device.mem_type()
1434
+
1435
+
1436
+ class SparseTensor:
1437
+ """
1438
+ A data structure that project the C++ SparseTensor object
1439
+ The class provides API to work with the object.
1440
+ Depending on the format, the class will hold more than one buffer
1441
+ depending on the format
1442
+ """
1443
+
1444
+ def __init__(self, sparse_tensor: C.SparseTensor):
1445
+ """
1446
+ Internal constructor
1447
+ """
1448
+ if isinstance(sparse_tensor, C.SparseTensor):
1449
+ self._tensor = sparse_tensor
1450
+ else:
1451
+ # An end user won't hit this error
1452
+ raise ValueError(
1453
+ "`Provided object` needs to be of type `onnxruntime.capi.onnxruntime_pybind11_state.SparseTensor`"
1454
+ )
1455
+
1456
+ def _get_c_tensor(self) -> C.SparseTensor:
1457
+ return self._tensor
1458
+
1459
+ @classmethod
1460
+ def sparse_coo_from_numpy(
1461
+ cls,
1462
+ dense_shape: npt.NDArray[np.int64],
1463
+ values: np.ndarray,
1464
+ coo_indices: npt.NDArray[np.int64],
1465
+ ort_device: OrtDevice,
1466
+ ) -> SparseTensor:
1467
+ """
1468
+ Factory method to construct a SparseTensor in COO format from given arguments
1469
+
1470
+ :param dense_shape: 1-D numpy array(int64) or a python list that contains a dense_shape of the sparse tensor
1471
+ must be on cpu memory
1472
+ :param values: a homogeneous, contiguous 1-D numpy array that contains non-zero elements of the tensor
1473
+ of a type.
1474
+ :param coo_indices: contiguous numpy array(int64) that contains COO indices for the tensor. coo_indices may
1475
+ have a 1-D shape when it contains a linear index of non-zero values and its length must be equal to
1476
+ that of the values. It can also be of 2-D shape, in which has it contains pairs of coordinates for
1477
+ each of the nnz values and its length must be exactly twice of the values length.
1478
+ :param ort_device: - describes the backing memory owned by the supplied nummpy arrays. Only CPU memory is
1479
+ suppored for non-numeric data types.
1480
+
1481
+ For primitive types, the method will map values and coo_indices arrays into native memory and will use
1482
+ them as backing storage. It will increment the reference count for numpy arrays and it will decrement it
1483
+ on GC. The buffers may reside in any storage either CPU or GPU.
1484
+ For strings and objects, it will create a copy of the arrays in CPU memory as ORT does not support those
1485
+ on other devices and their memory can not be mapped.
1486
+ """
1487
+ return cls(C.SparseTensor.sparse_coo_from_numpy(dense_shape, values, coo_indices, ort_device._get_c_device()))
1488
+
1489
+ @classmethod
1490
+ def sparse_csr_from_numpy(
1491
+ cls,
1492
+ dense_shape: npt.NDArray[np.int64],
1493
+ values: np.ndarray,
1494
+ inner_indices: npt.NDArray[np.int64],
1495
+ outer_indices: npt.NDArray[np.int64],
1496
+ ort_device: OrtDevice,
1497
+ ) -> SparseTensor:
1498
+ """
1499
+ Factory method to construct a SparseTensor in CSR format from given arguments
1500
+
1501
+ :param dense_shape: 1-D numpy array(int64) or a python list that contains a dense_shape of the
1502
+ sparse tensor (rows, cols) must be on cpu memory
1503
+ :param values: a contiguous, homogeneous 1-D numpy array that contains non-zero elements of the tensor
1504
+ of a type.
1505
+ :param inner_indices: contiguous 1-D numpy array(int64) that contains CSR inner indices for the tensor.
1506
+ Its length must be equal to that of the values.
1507
+ :param outer_indices: contiguous 1-D numpy array(int64) that contains CSR outer indices for the tensor.
1508
+ Its length must be equal to the number of rows + 1.
1509
+ :param ort_device: - describes the backing memory owned by the supplied nummpy arrays. Only CPU memory is
1510
+ suppored for non-numeric data types.
1511
+
1512
+ For primitive types, the method will map values and indices arrays into native memory and will use them as
1513
+ backing storage. It will increment the reference count and it will decrement then count when it is GCed.
1514
+ The buffers may reside in any storage either CPU or GPU.
1515
+ For strings and objects, it will create a copy of the arrays in CPU memory as ORT does not support those
1516
+ on other devices and their memory can not be mapped.
1517
+ """
1518
+ return cls(
1519
+ C.SparseTensor.sparse_csr_from_numpy(
1520
+ dense_shape,
1521
+ values,
1522
+ inner_indices,
1523
+ outer_indices,
1524
+ ort_device._get_c_device(),
1525
+ )
1526
+ )
1527
+
1528
+ def values(self) -> np.ndarray:
1529
+ """
1530
+ The method returns a numpy array that is backed by the native memory
1531
+ if the data type is numeric. Otherwise, the returned numpy array that contains
1532
+ copies of the strings.
1533
+ """
1534
+ return self._tensor.values()
1535
+
1536
+ def as_coo_view(self):
1537
+ """
1538
+ The method will return coo representation of the sparse tensor which will enable
1539
+ querying COO indices. If the instance did not contain COO format, it would throw.
1540
+ You can query coo indices as:
1541
+
1542
+ ::
1543
+
1544
+ coo_indices = sparse_tensor.as_coo_view().indices()
1545
+
1546
+ which will return a numpy array that is backed by the native memory.
1547
+ """
1548
+ return self._tensor.get_coo_data()
1549
+
1550
+ def as_csrc_view(self):
1551
+ """
1552
+ The method will return CSR(C) representation of the sparse tensor which will enable
1553
+ querying CRS(C) indices. If the instance dit not contain CSR(C) format, it would throw.
1554
+ You can query indices as:
1555
+
1556
+ ::
1557
+
1558
+ inner_ndices = sparse_tensor.as_csrc_view().inner()
1559
+ outer_ndices = sparse_tensor.as_csrc_view().outer()
1560
+
1561
+ returning numpy arrays backed by the native memory.
1562
+ """
1563
+ return self._tensor.get_csrc_data()
1564
+
1565
+ def as_blocksparse_view(self):
1566
+ """
1567
+ The method will return coo representation of the sparse tensor which will enable
1568
+ querying BlockSparse indices. If the instance did not contain BlockSparse format, it would throw.
1569
+ You can query coo indices as:
1570
+
1571
+ ::
1572
+
1573
+ block_sparse_indices = sparse_tensor.as_blocksparse_view().indices()
1574
+
1575
+ which will return a numpy array that is backed by the native memory
1576
+ """
1577
+ return self._tensor.get_blocksparse_data()
1578
+
1579
+ def to_cuda(self, ort_device):
1580
+ """
1581
+ Returns a copy of this instance on the specified cuda device
1582
+
1583
+ :param ort_device: with name 'cuda' and valid gpu device id
1584
+
1585
+ The method will throw if:
1586
+
1587
+ - this instance contains strings
1588
+ - this instance is already on GPU. Cross GPU copy is not supported
1589
+ - CUDA is not present in this build
1590
+ - if the specified device is not valid
1591
+ """
1592
+ return SparseTensor(self._tensor.to_cuda(ort_device._get_c_device()))
1593
+
1594
+ def format(self):
1595
+ """
1596
+ Returns a OrtSparseFormat enumeration
1597
+ """
1598
+ return self._tensor.format
1599
+
1600
+ def dense_shape(self) -> npt.NDArray[np.int64]:
1601
+ """
1602
+ Returns a numpy array(int64) containing a dense shape of a sparse tensor
1603
+ """
1604
+ return self._tensor.dense_shape()
1605
+
1606
+ def data_type(self) -> str:
1607
+ """
1608
+ Returns a string data type of the data in the OrtValue
1609
+ """
1610
+ return self._tensor.data_type()
1611
+
1612
+ def device_name(self) -> str:
1613
+ """
1614
+ Returns the name of the device where the SparseTensor data buffers reside e.g. cpu, cuda
1615
+ """
1616
+ return self._tensor.device_name().lower()
1617
+
1618
+
1619
+ # Type hint for user-specified function that allows the user to specify initializer locations when compiling a model.
1620
+ GetInitializerLocationFunc = Callable[
1621
+ [str, OrtValue, C.OrtExternalInitializerInfo | None], C.OrtExternalInitializerInfo | None
1622
+ ]
1623
+
1624
+ # Type hint that adheres to the signature expected by ORT.
1625
+ GetInitializerLocationWrapperFunc = Callable[
1626
+ [str, C.OrtValue, C.OrtExternalInitializerInfo | None], C.OrtExternalInitializerInfo | None
1627
+ ]
ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/capi/onnxruntime_validation.py ADDED
@@ -0,0 +1,154 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -------------------------------------------------------------------------
2
+ # Copyright (c) Microsoft Corporation. All rights reserved.
3
+ # Licensed under the MIT License.
4
+ # --------------------------------------------------------------------------
5
+ """
6
+ Check OS requirements for ONNX Runtime Python Bindings.
7
+ """
8
+
9
+ import linecache
10
+ import platform
11
+ import warnings
12
+
13
+
14
+ def check_distro_info():
15
+ __my_distro__ = ""
16
+ __my_distro_ver__ = ""
17
+ __my_system__ = platform.system().lower()
18
+
19
+ __OS_RELEASE_FILE__ = "/etc/os-release" # noqa: N806
20
+ __LSB_RELEASE_FILE__ = "/etc/lsb-release" # noqa: N806
21
+
22
+ if __my_system__ == "windows":
23
+ __my_distro__ = __my_system__
24
+ __my_distro_ver__ = platform.release().lower()
25
+
26
+ if __my_distro_ver__ not in ["10", "11", "2016server", "2019server", "2022server", "2025server"]:
27
+ warnings.warn(
28
+ f"Unsupported Windows version ({__my_distro_ver__}). ONNX Runtime supports Windows 10 and above, or Windows Server 2016 and above."
29
+ )
30
+ elif __my_system__ == "linux":
31
+ """Although the 'platform' python module for getting Distro information works well on standard OS images
32
+ running on real hardware, it is not accurate when running on Azure VMs, Git Bash, Cygwin, etc.
33
+ The returned values for release and version are unpredictable for virtualized or emulated environments.
34
+ /etc/os-release and /etc/lsb_release files, on the other hand, are guaranteed to exist and have standard values
35
+ in all OSes supported by onnxruntime. The former is the current standard file to check OS info and the latter
36
+ is its predecessor.
37
+ """
38
+ # Newer systems have /etc/os-release with relevant distro info
39
+ __my_distro__ = linecache.getline(__OS_RELEASE_FILE__, 3)[3:-1]
40
+ __my_distro_ver__ = linecache.getline(__OS_RELEASE_FILE__, 6)[12:-2]
41
+
42
+ # Older systems may have /etc/os-release instead
43
+ if not __my_distro__:
44
+ __my_distro__ = linecache.getline(__LSB_RELEASE_FILE__, 1)[11:-1]
45
+ __my_distro_ver__ = linecache.getline(__LSB_RELEASE_FILE__, 2)[16:-1]
46
+
47
+ # Instead of trying to parse distro specific files,
48
+ # warn the user ONNX Runtime may not work out of the box
49
+ __my_distro__ = __my_distro__.lower()
50
+ __my_distro_ver__ = __my_distro_ver__.lower()
51
+ elif __my_system__ == "darwin":
52
+ __my_distro__ = __my_system__
53
+ __my_distro_ver__ = platform.release().lower()
54
+
55
+ if int(__my_distro_ver__.split(".")[0]) < 11:
56
+ warnings.warn(
57
+ f"Unsupported macOS version ({__my_distro_ver__}). ONNX Runtime supports macOS 11.0 or later."
58
+ )
59
+ elif __my_system__ == "aix":
60
+ import subprocess # noqa: PLC0415
61
+
62
+ returned_output = subprocess.check_output("oslevel")
63
+ __my_distro_ver__str = returned_output.decode("utf-8")
64
+ __my_distro_ver = __my_distro_ver__str[:3]
65
+ else:
66
+ warnings.warn(
67
+ f"Unsupported platform ({__my_system__}). ONNX Runtime supports Linux, macOS, AIX and Windows platforms, only."
68
+ )
69
+
70
+
71
+ def get_package_name_and_version_info():
72
+ package_name = ""
73
+ version = ""
74
+ cuda_version = ""
75
+
76
+ try:
77
+ from .build_and_package_info import __version__ as version # noqa: PLC0415
78
+ from .build_and_package_info import package_name # noqa: PLC0415
79
+
80
+ try: # noqa: SIM105
81
+ from .build_and_package_info import cuda_version # noqa: PLC0415
82
+ except ImportError:
83
+ # cuda_version is optional. For example, cpu only package does not have the attribute.
84
+ pass
85
+ except Exception as e:
86
+ warnings.warn("WARNING: failed to collect package name and version info")
87
+ print(e)
88
+
89
+ return package_name, version, cuda_version
90
+
91
+
92
+ def check_training_module():
93
+ import_ortmodule_exception = None
94
+
95
+ has_ortmodule = False
96
+ try:
97
+ from onnxruntime.training.ortmodule import ORTModule # noqa: F401, PLC0415
98
+
99
+ has_ortmodule = True
100
+ except ImportError:
101
+ # ORTModule not present
102
+ has_ortmodule = False
103
+ except Exception as e:
104
+ # this may happen if Cuda is not installed, we want to raise it after
105
+ # for any exception other than not having ortmodule, we want to continue
106
+ # device version validation and raise the exception after.
107
+ try:
108
+ from onnxruntime.training.ortmodule._fallback import ORTModuleInitException # noqa: PLC0415
109
+
110
+ if isinstance(e, ORTModuleInitException):
111
+ # ORTModule is present but not ready to run yet
112
+ has_ortmodule = True
113
+ except Exception:
114
+ # ORTModule not present
115
+ has_ortmodule = False
116
+
117
+ if not has_ortmodule:
118
+ import_ortmodule_exception = e
119
+
120
+ # collect onnxruntime package name, version, and cuda version
121
+ package_name, version, cuda_version = get_package_name_and_version_info()
122
+
123
+ if has_ortmodule and cuda_version:
124
+ try:
125
+ # collect cuda library build info. the library info may not be available
126
+ # when the build environment has none or multiple libraries installed
127
+ try:
128
+ from .build_and_package_info import cudart_version # noqa: PLC0415
129
+ except ImportError:
130
+ warnings.warn("WARNING: failed to get cudart_version from onnxruntime build info.")
131
+ cudart_version = None
132
+
133
+ def print_build_package_info():
134
+ warnings.warn(f"onnxruntime training package info: package_name: {package_name}")
135
+ warnings.warn(f"onnxruntime training package info: __version__: {version}")
136
+ warnings.warn(f"onnxruntime training package info: cuda_version: {cuda_version}")
137
+ warnings.warn(f"onnxruntime build info: cudart_version: {cudart_version}")
138
+
139
+ # collection cuda library info from current environment.
140
+ from onnxruntime.capi.onnxruntime_collect_build_info import find_cudart_versions # noqa: PLC0415
141
+
142
+ local_cudart_versions = find_cudart_versions(build_env=False, build_cuda_version=cuda_version)
143
+ if cudart_version and local_cudart_versions and cudart_version not in local_cudart_versions:
144
+ print_build_package_info()
145
+ warnings.warn("WARNING: failed to find cudart version that matches onnxruntime build info")
146
+ warnings.warn(f"WARNING: found cudart versions: {local_cudart_versions}")
147
+ except Exception as e:
148
+ warnings.warn("WARNING: failed to collect onnxruntime version and build info")
149
+ print(e)
150
+
151
+ if import_ortmodule_exception:
152
+ raise import_ortmodule_exception
153
+
154
+ return has_ortmodule, package_name, version, cuda_version
ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/datasets/__init__.py ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Microsoft Corporation. All rights reserved.
2
+ # Licensed under the MIT License.
3
+ """
4
+ Short examples used in the documentation.
5
+ """
6
+
7
+ import os
8
+
9
+
10
+ def get_example(name):
11
+ """
12
+ Retrieves the absolute file name of an example.
13
+ """
14
+ this = os.path.abspath(os.path.dirname(__file__))
15
+ full = os.path.join(this, name)
16
+ if not os.path.exists(full):
17
+ raise FileNotFoundError(f"Unable to find example '{name}'")
18
+ return full
ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/quantization/CalTableFlatBuffers/KeyValue.py ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # automatically generated by the FlatBuffers compiler, do not modify
2
+
3
+ # namespace: CalTableFlatBuffers
4
+
5
+ import flatbuffers
6
+ from flatbuffers.compat import import_numpy
7
+
8
+ np = import_numpy()
9
+
10
+
11
+ class KeyValue:
12
+ __slots__ = ["_tab"]
13
+
14
+ @classmethod
15
+ def GetRootAs(cls, buf, offset=0): # noqa: N802
16
+ n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset)
17
+ x = KeyValue()
18
+ x.Init(buf, n + offset)
19
+ return x
20
+
21
+ @classmethod
22
+ def GetRootAsKeyValue(cls, buf, offset=0): # noqa: N802
23
+ """This method is deprecated. Please switch to GetRootAs."""
24
+ return cls.GetRootAs(buf, offset)
25
+
26
+ # KeyValue
27
+ def Init(self, buf, pos): # noqa: N802
28
+ self._tab = flatbuffers.table.Table(buf, pos)
29
+
30
+ # KeyValue
31
+ def Key(self): # noqa: N802
32
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4))
33
+ if o != 0:
34
+ return self._tab.String(o + self._tab.Pos)
35
+ return None
36
+
37
+ # KeyValue
38
+ def Value(self): # noqa: N802
39
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6))
40
+ if o != 0:
41
+ return self._tab.String(o + self._tab.Pos)
42
+ return None
43
+
44
+
45
+ def Start(builder): # noqa: N802
46
+ builder.StartObject(2)
47
+
48
+
49
+ def KeyValueStart(builder): # noqa: N802
50
+ """This method is deprecated. Please switch to Start."""
51
+ return Start(builder)
52
+
53
+
54
+ def AddKey(builder, key): # noqa: N802
55
+ builder.PrependUOffsetTRelativeSlot(0, flatbuffers.number_types.UOffsetTFlags.py_type(key), 0)
56
+
57
+
58
+ def KeyValueAddKey(builder, key): # noqa: N802
59
+ """This method is deprecated. Please switch to AddKey."""
60
+ return AddKey(builder, key)
61
+
62
+
63
+ def AddValue(builder, value): # noqa: N802
64
+ builder.PrependUOffsetTRelativeSlot(1, flatbuffers.number_types.UOffsetTFlags.py_type(value), 0)
65
+
66
+
67
+ def KeyValueAddValue(builder, value): # noqa: N802
68
+ """This method is deprecated. Please switch to AddValue."""
69
+ return AddValue(builder, value)
70
+
71
+
72
+ def End(builder): # noqa: N802
73
+ return builder.EndObject()
74
+
75
+
76
+ def KeyValueEnd(builder): # noqa: N802
77
+ """This method is deprecated. Please switch to End."""
78
+ return End(builder)
ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/quantization/CalTableFlatBuffers/TrtTable.py ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # automatically generated by the FlatBuffers compiler, do not modify
2
+
3
+ # namespace: CalTableFlatBuffers
4
+
5
+ import flatbuffers
6
+ from flatbuffers.compat import import_numpy
7
+
8
+ np = import_numpy()
9
+
10
+
11
+ class TrtTable:
12
+ __slots__ = ["_tab"]
13
+
14
+ @classmethod
15
+ def GetRootAs(cls, buf, offset=0): # noqa: N802
16
+ n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset)
17
+ x = TrtTable()
18
+ x.Init(buf, n + offset)
19
+ return x
20
+
21
+ @classmethod
22
+ def GetRootAsTrtTable(cls, buf, offset=0): # noqa: N802
23
+ """This method is deprecated. Please switch to GetRootAs."""
24
+ return cls.GetRootAs(buf, offset)
25
+
26
+ # TrtTable
27
+ def Init(self, buf, pos): # noqa: N802
28
+ self._tab = flatbuffers.table.Table(buf, pos)
29
+
30
+ # TrtTable
31
+ def Dict(self, j): # noqa: N802
32
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4))
33
+ if o != 0:
34
+ x = self._tab.Vector(o)
35
+ x += flatbuffers.number_types.UOffsetTFlags.py_type(j) * 4
36
+ x = self._tab.Indirect(x)
37
+ from onnxruntime.quantization.CalTableFlatBuffers.KeyValue import KeyValue # noqa: PLC0415
38
+
39
+ obj = KeyValue()
40
+ obj.Init(self._tab.Bytes, x)
41
+ return obj
42
+ return None
43
+
44
+ # TrtTable
45
+ def DictLength(self): # noqa: N802
46
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4))
47
+ if o != 0:
48
+ return self._tab.VectorLen(o)
49
+ return 0
50
+
51
+ # TrtTable
52
+ def DictIsNone(self): # noqa: N802
53
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4))
54
+ return o == 0
55
+
56
+
57
+ def Start(builder): # noqa: N802
58
+ builder.StartObject(1)
59
+
60
+
61
+ def TrtTableStart(builder): # noqa: N802
62
+ """This method is deprecated. Please switch to Start."""
63
+ return Start(builder)
64
+
65
+
66
+ def AddDict(builder, dict): # noqa: N802
67
+ builder.PrependUOffsetTRelativeSlot(0, flatbuffers.number_types.UOffsetTFlags.py_type(dict), 0)
68
+
69
+
70
+ def TrtTableAddDict(builder, dict): # noqa: N802
71
+ """This method is deprecated. Please switch to AddDict."""
72
+ return AddDict(builder, dict)
73
+
74
+
75
+ def StartDictVector(builder, numElems): # noqa: N802
76
+ return builder.StartVector(4, numElems, 4)
77
+
78
+
79
+ def TrtTableStartDictVector(builder, numElems): # noqa: N802
80
+ """This method is deprecated. Please switch to Start."""
81
+ return StartDictVector(builder, numElems)
82
+
83
+
84
+ def End(builder): # noqa: N802
85
+ return builder.EndObject()
86
+
87
+
88
+ def TrtTableEnd(builder): # noqa: N802
89
+ """This method is deprecated. Please switch to End."""
90
+ return End(builder)
ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/quantization/CalTableFlatBuffers/__init__.py ADDED
File without changes
ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/quantization/__init__.py ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .calibrate import ( # noqa: F401
2
+ CalibraterBase,
3
+ CalibrationDataReader,
4
+ CalibrationMethod,
5
+ MinMaxCalibrater,
6
+ TensorData,
7
+ TensorsData,
8
+ create_calibrator,
9
+ load_tensors_data,
10
+ save_tensors_data,
11
+ )
12
+ from .cuda_quantizer import CudaQuantizer # noqa: F401
13
+ from .qdq_quantizer import QDQQuantizer # noqa: F401
14
+ from .quant_utils import QuantFormat, QuantType, write_calibration_table # noqa: F401
15
+ from .quantize import (
16
+ DynamicQuantConfig, # noqa: F401
17
+ QuantizationMode, # noqa: F401
18
+ StaticQuantConfig, # noqa: F401
19
+ get_qdq_config, # noqa: F401
20
+ quantize, # noqa: F401
21
+ quantize_dynamic, # noqa: F401
22
+ quantize_static, # noqa: F401
23
+ )
24
+ from .shape_inference import quant_pre_process # noqa: F401
ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/quantization/base_quantizer.py ADDED
@@ -0,0 +1,530 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -------------------------------------------------------------------------
2
+ # Copyright (c) Microsoft Corporation. All rights reserved.
3
+ # Licensed under the MIT License. See License.txt in the project root for
4
+ # license information.
5
+ # --------------------------------------------------------------------------
6
+ import logging
7
+ from typing import Any
8
+
9
+ import numpy as np
10
+ import onnx
11
+ import onnx.numpy_helper
12
+
13
+ try:
14
+ from onnx.reference.op_run import to_array_extended
15
+ except ImportError:
16
+ # old version of onnx.
17
+ to_array_extended = None
18
+
19
+ from .calibrate import TensorData
20
+ from .onnx_model import ONNXModel
21
+ from .quant_utils import (
22
+ DEQUANT_OP_NAME,
23
+ ONNX_TYPE_TO_NP_TYPE,
24
+ QUANT_OP_NAME,
25
+ TENSOR_NAME_QUANT_SUFFIX,
26
+ find_by_name,
27
+ get_opset_version,
28
+ model_has_infer_metadata,
29
+ normalize_axis,
30
+ pack_bytes_to_4bit,
31
+ quantize_data,
32
+ quantize_nparray,
33
+ save_and_reload_model_with_shape_infer,
34
+ tensor_proto_to_array,
35
+ )
36
+ from .tensor_quant_overrides import TensorQuantOverridesHelper
37
+
38
+
39
+ class QuantizationParams:
40
+ def __init__(self, **data: dict[str, Any]):
41
+ self.data = {}
42
+ for k, v in data.items():
43
+ if not isinstance(k, str):
44
+ raise TypeError(f"Keys must be strings not {type(k)} for k={k!r}.")
45
+ if k != "axis" and not isinstance(v, (int, str, np.ndarray, float)):
46
+ raise TypeError(f"Values must be numpy arrays, int, float, str not {type(v)} for k={k!r}.")
47
+ if k == "axis" and not isinstance(v, int) and v is not None:
48
+ raise TypeError(f"Axis value must be an int or None, not {type(v)}.")
49
+ if k == "scale" and v.dtype not in (np.float32, np.float16):
50
+ raise ValueError(f"scale must a float32 or float16 numpy element but is {v.dtype} for k={k!r}")
51
+ self.data[k] = v
52
+
53
+ def get(self, key, default_value=None):
54
+ return self.data.get(key, default_value)
55
+
56
+ def __iter__(self):
57
+ yield from self.data
58
+
59
+ def __getitem__(self, key):
60
+ return self.data[key]
61
+
62
+ def __setitem__(self, key, value):
63
+ self.data[key] = value
64
+
65
+ def __len__(self):
66
+ return len(self.data)
67
+
68
+
69
+ class BaseQuantizer:
70
+ def __init__(
71
+ self,
72
+ model,
73
+ per_channel,
74
+ reduce_range,
75
+ weight_qType,
76
+ activation_qType,
77
+ tensors_range,
78
+ nodes_to_quantize,
79
+ nodes_to_exclude,
80
+ op_types_to_quantize,
81
+ extra_options=None,
82
+ ):
83
+ if not model_has_infer_metadata(model):
84
+ model = save_and_reload_model_with_shape_infer(model)
85
+ self.value_infos = {vi.name: vi for vi in model.graph.value_info}
86
+ self.value_infos.update({ot.name: ot for ot in model.graph.output})
87
+ self.value_infos.update({it.name: it for it in model.graph.input})
88
+
89
+ self.model = ONNXModel(model)
90
+ self.opset_version = get_opset_version(model)
91
+ self.per_channel = per_channel # weight-pack per channel
92
+ self.reduce_range = reduce_range
93
+
94
+ self.extra_options = extra_options if extra_options else {}
95
+ self.enable_subgraph_quantization = (
96
+ "EnableSubgraph" in self.extra_options and self.extra_options["EnableSubgraph"]
97
+ )
98
+ self.parent = None
99
+ self.force_quantize_no_input_check = (
100
+ "ForceQuantizeNoInputCheck" in self.extra_options and self.extra_options["ForceQuantizeNoInputCheck"]
101
+ )
102
+
103
+ # If user does not explicitly set "WeightSymmetric", then the weight's quantization type determines
104
+ # the symmetry (i.e., signed integer types will use symmetric quantization). See `def is_weight_symmetric()`
105
+ self._is_weight_symmetric: bool | None = self.extra_options.get("WeightSymmetric", None)
106
+ self.is_activation_symmetric = self.extra_options.get("ActivationSymmetric", False)
107
+ self.is_activation_restricted_asymmetric = self.extra_options.get("ActivationRestrictedAsymmetric", False)
108
+ self.min_real_range = self.extra_options.get("MinimumRealRange")
109
+
110
+ self.activation_qType = getattr(activation_qType, "tensor_type", activation_qType)
111
+ self.weight_qType = getattr(weight_qType, "tensor_type", weight_qType)
112
+
113
+ """
114
+ Dictionary specifying the min and max values for tensors. It has following format:
115
+ {
116
+ "param_name": [min, max]
117
+ }
118
+ example:
119
+ {
120
+ 'Conv_3:0': [np.float32(0), np.float32(0.5)],
121
+ 'Conv_4:0': [np.float32(1), np.float32(3.5)]
122
+ }
123
+ """
124
+ if tensors_range is not None and any(not isinstance(t, TensorData) for t in tensors_range.values()):
125
+ raise TypeError(
126
+ f"tensors_range contains unexpected types { {type(v) for v in tensors_range.values()} }, not TensorData."
127
+ )
128
+ self.tensors_range = tensors_range
129
+ self.nodes_to_quantize = nodes_to_quantize # specific nodes to quantize
130
+ self.nodes_to_exclude = nodes_to_exclude # specific nodes to exclude
131
+ self.op_types_to_quantize = op_types_to_quantize
132
+
133
+ # Get tensor-level quantization overrides and ensure they are valid.
134
+ self.tensor_quant_overrides = TensorQuantOverridesHelper(self.extra_options.get("TensorQuantOverrides", {}))
135
+
136
+ self.initializers = {initzer.name: initzer for initzer in self.model.initializer()}
137
+ overrides_valid, overrides_err = self.tensor_quant_overrides.is_valid(
138
+ self.initializers, self.value_infos.keys(), activation_qType
139
+ )
140
+ if not overrides_valid:
141
+ raise ValueError(overrides_err)
142
+
143
+ self.tensor_quant_override_qtypes = self.tensor_quant_overrides.get_quant_types()
144
+
145
+ def is_weight_symmetric(self, weight_quant_type: onnx.TensorProto.DataType) -> bool:
146
+ if self._is_weight_symmetric is not None:
147
+ return self._is_weight_symmetric # Return value explicitly set by user.
148
+ return weight_quant_type in (
149
+ onnx.TensorProto.INT4,
150
+ onnx.TensorProto.INT8,
151
+ onnx.TensorProto.INT16,
152
+ onnx.TensorProto.FLOAT8E4M3FN,
153
+ )
154
+
155
+ def quantize_model(self):
156
+ raise NotImplementedError
157
+
158
+ def is_input_a_initializer(self, input_name):
159
+ initializer = find_by_name(input_name, self.model.initializer())
160
+ return initializer is not None
161
+
162
+ def is_per_channel(self):
163
+ return self.per_channel
164
+
165
+ def is_valid_quantize_weight(self, weight_name):
166
+ weight = find_by_name(weight_name, self.model.initializer())
167
+ if weight is not None:
168
+ return weight.data_type in (onnx.TensorProto.FLOAT, onnx.TensorProto.FLOAT16)
169
+ if (not self.enable_subgraph_quantization) or (self.parent is None):
170
+ return False
171
+ return self.parent.is_valid_quantize_weight(weight_name)
172
+
173
+ def should_quantize_node(self, node):
174
+ if (
175
+ self.nodes_to_quantize is not None
176
+ and len(self.nodes_to_quantize) != 0
177
+ and node.name not in self.nodes_to_quantize
178
+ ):
179
+ return False
180
+
181
+ if node.op_type not in self.op_types_to_quantize:
182
+ return False
183
+
184
+ if node.op_type in (DEQUANT_OP_NAME, QUANT_OP_NAME):
185
+ return False
186
+
187
+ if self.nodes_to_exclude is not None and node.name in self.nodes_to_exclude:
188
+ return False
189
+
190
+ return True
191
+
192
+ def quantize_bias_static_impl(self, bias_name, input_scale, weight_scale, beta=1.0):
193
+ """
194
+ Quantized the bias. Zero Point == 0 and Scale == Input_Scale * Weight_Scale
195
+ """
196
+
197
+ # get bias
198
+ bias_initializer = find_by_name(bias_name, self.model.initializer())
199
+ bias_data = tensor_proto_to_array(bias_initializer)
200
+ quantized_bias_name = bias_name + TENSOR_NAME_QUANT_SUFFIX
201
+
202
+ # quantize bias
203
+ if self.weight_qType == onnx.TensorProto.FLOAT8E4M3FN:
204
+ data = np.asarray(bias_data)
205
+ if data.dtype == np.float16:
206
+ node_qtype = onnx.TensorProto.FLOAT16
207
+ elif data.dtype == np.float32:
208
+ node_qtype = onnx.TensorProto.FLOAT
209
+ else:
210
+ raise TypeError(f"Only float16 or float32 are supported with float 8 but bias dtype is {data.dtype}.")
211
+ quantized_data = data.astype(np.float32)
212
+ bias_scale = np.array([1], dtype=quantized_data.dtype)
213
+ bias_scale_data = bias_scale.reshape(-1)
214
+ packed_bias_initializer = onnx.numpy_helper.from_array(quantized_data, quantized_bias_name)
215
+ self.model.initializer_extend([packed_bias_initializer])
216
+ node_type = "Cast"
217
+ else:
218
+ # calculate scale for bias
219
+ # TODO: This formula should be explained including why the scale is not estimated for the bias as well.
220
+ bias_scale = input_scale * weight_scale * beta
221
+
222
+ # Quantize by dividing by bias_scale
223
+ quantized_data = np.asarray(bias_data, dtype=np.float64) / np.asarray(bias_scale, dtype=np.float64)
224
+ quantized_data = quantized_data.round()
225
+
226
+ # Clip quantized data to the range of a int32
227
+ int32_min = np.float64(np.iinfo(np.int32).min)
228
+ int32_max = np.float64(np.iinfo(np.int32).max)
229
+ if np.any(quantized_data < int32_min) or np.any(quantized_data > int32_max):
230
+ logging.warning(
231
+ f"Quantized bias `{bias_name}` exceeds the range of a int32. The bias scale is too small."
232
+ )
233
+
234
+ quantized_data = np.clip(quantized_data, int32_min, int32_max).astype(np.int32)
235
+
236
+ # update bias initializer
237
+ bias_np_data = np.asarray(quantized_data, dtype=np.int32).reshape(bias_initializer.dims)
238
+ packed_bias_initializer = onnx.numpy_helper.from_array(bias_np_data, quantized_bias_name)
239
+ self.model.initializer_extend([packed_bias_initializer])
240
+
241
+ # Bias's scale dtype should match the original bias data's unquantized type (float32 or float16).
242
+ bias_scale_data = np.asarray(bias_scale, dtype=bias_data.dtype).reshape(-1)
243
+ node_type = "DequantizeLinear"
244
+ node_qtype = self.weight_qType
245
+
246
+ # update scale initializer
247
+ quantized_bias_scale_name = quantized_bias_name + "_scale"
248
+ packed_bias_scale_initializer = onnx.numpy_helper.from_array(bias_scale_data, quantized_bias_scale_name)
249
+ self.model.initializer_extend([packed_bias_scale_initializer])
250
+
251
+ # update zero initializer
252
+ if self.weight_qType == onnx.TensorProto.FLOAT8E4M3FN:
253
+ tensor_type = self.weight_qType
254
+ else:
255
+ tensor_type = onnx.TensorProto.INT32
256
+
257
+ quantized_bias_zp_name = quantized_bias_name + "_zero_point"
258
+ if self.weight_qType == onnx.TensorProto.FLOAT8E4M3FN:
259
+ packed_bias_zp_initializer = onnx.helper.make_tensor(quantized_bias_zp_name, self.weight_qType, [1], [0.0])
260
+ elif bias_scale.size > 1:
261
+ bias_zp_data = np.zeros(bias_scale.shape, dtype=np.int32).reshape(-1)
262
+ packed_bias_zp_initializer = onnx.numpy_helper.from_array(bias_zp_data, quantized_bias_zp_name)
263
+ else:
264
+ packed_bias_zp_initializer = onnx.helper.make_tensor(quantized_bias_zp_name, tensor_type, [], [0])
265
+ self.model.initializer_extend([packed_bias_zp_initializer])
266
+
267
+ return (
268
+ quantized_bias_name,
269
+ quantized_bias_scale_name,
270
+ quantized_bias_zp_name,
271
+ bias_scale_data,
272
+ node_type,
273
+ node_qtype,
274
+ )
275
+
276
+ def quantize_initializer_impl(self, weight, qType, reduce_range=False, keep_float_weight=False):
277
+ """
278
+ :param weight: TensorProto initializer
279
+ :param qType: type to quantize to
280
+ :param keep_float_weight: Whether to quantize the weight. In some cases, we only want to qunatize scale and zero point.
281
+ If keep_float_weight is False, quantize the weight, or don't quantize the weight.
282
+ :return: quantized weight name, zero point name, scale name
283
+ """
284
+ # TODO(adrianlizarraga): This function is now only used by onnx_quantizer.py, so move it there.
285
+ q_weight_name = weight.name + TENSOR_NAME_QUANT_SUFFIX
286
+ zp_name = weight.name + "_zero_point"
287
+ scale_name = weight.name + "_scale"
288
+
289
+ # Quantize weight data. Use quantization overrides if provided by the user.
290
+ weight_data = tensor_proto_to_array(weight)
291
+ quant_overrides = self.tensor_quant_overrides.get_per_tensor_overrides(weight.name, default_val={})
292
+ if "quant_type" in quant_overrides:
293
+ qType = quant_overrides["quant_type"].tensor_type # noqa: N806
294
+
295
+ if "scale" in quant_overrides and "zero_point" in quant_overrides:
296
+ zero_point = np.array(quant_overrides["zero_point"], dtype=ONNX_TYPE_TO_NP_TYPE[qType])
297
+ scale = np.array(quant_overrides["scale"])
298
+ q_weight_data = quantize_nparray(qType, weight_data.flatten(), scale, zero_point)
299
+ assert isinstance(zero_point, np.ndarray), f"Unexpected type {type(zero_point)}"
300
+ assert zero_point.dtype != np.float32 and zero_point.dtype != np.float16, (
301
+ f"Unexpected dtype {zero_point.dtype}"
302
+ )
303
+ assert isinstance(scale, np.ndarray), f"Unexpected type {type(scale)}"
304
+
305
+ else:
306
+ symmetric = self.is_weight_symmetric(qType) if qType == self.weight_qType else self.is_activation_symmetric
307
+ zero_point, scale, q_weight_data = quantize_data(
308
+ weight_data.flatten(),
309
+ qType,
310
+ quant_overrides.get("symmetric", symmetric),
311
+ reduce_range=quant_overrides.get("reduce_range", self.reduce_range and reduce_range),
312
+ min_real_range=self.min_real_range,
313
+ rmin_override=quant_overrides.get("rmin"),
314
+ rmax_override=quant_overrides.get("rmax"),
315
+ )
316
+
317
+ assert isinstance(zero_point, np.ndarray), f"Unexpected type {type(zero_point)}"
318
+ assert zero_point.dtype != np.float32 and zero_point.dtype != np.float16, (
319
+ f"Unexpected dtype {zero_point.dtype}"
320
+ )
321
+ assert isinstance(scale, np.ndarray), f"Unexpected type {type(scale)}"
322
+
323
+ scale_dtype = weight.data_type
324
+ scale_initializer = onnx.helper.make_tensor(scale_name, scale_dtype, [], scale.reshape((-1,)).tolist())
325
+ zero_initializer = onnx.helper.make_tensor(zp_name, qType, [], zero_point.reshape((-1,)).tolist())
326
+ self.model.initializer_extend([scale_initializer, zero_initializer])
327
+
328
+ if not keep_float_weight:
329
+ if self.weight_qType == onnx.TensorProto.FLOAT8E4M3FN:
330
+ q_weight_initializer = onnx.TensorProto()
331
+ q_weight_initializer.data_type = self.weight_qType
332
+ q_weight_initializer.dims.extend(weight.dims)
333
+ q_weight_initializer.name = q_weight_name
334
+ # Do not remove .flatten().copy() numpy is not clear about data persistence.
335
+ q_weight_initializer.raw_data = q_weight_data.flatten().copy().tobytes()
336
+ if to_array_extended is not None:
337
+ # This test should not be needed but it helped catch some issues
338
+ # with data persistence and tobytes.
339
+ check = to_array_extended(q_weight_initializer)
340
+ if check.shape != weight_data.shape or check.tobytes() != q_weight_data.tobytes():
341
+ raise RuntimeError(
342
+ f"The initializer of shape {weight_data.shape} could not be created, expecting "
343
+ f"{q_weight_data.tobytes()[:10]}, got {check.tobytes()[:10]} and shape={weight.shape}"
344
+ f"\nraw={str(q_weight_initializer)[:200]}."
345
+ )
346
+ elif qType in (onnx.TensorProto.INT4, onnx.TensorProto.UINT4):
347
+ if q_weight_data.dtype not in (np.int8, np.uint8):
348
+ raise RuntimeError(
349
+ f"Quantized weights for {q_weight_name} must be 8-bit before packing as 4-bit values."
350
+ )
351
+
352
+ # We do not use onnx.helper.pack_float32_to_4bit() due to performance.
353
+ # This can be the difference between a large model taking 30 minutes to quantize vs 5 minutes.
354
+ packed_data = bytes(pack_bytes_to_4bit(q_weight_data.tobytes()))
355
+
356
+ # We only use onnx.helper.make_tensor with raw data due to bug: https://github.com/onnx/onnx/pull/6161
357
+ q_weight_initializer = onnx.helper.make_tensor(q_weight_name, qType, weight.dims, packed_data, raw=True)
358
+ else:
359
+ q_weight_data = np.asarray(q_weight_data, dtype=onnx.helper.tensor_dtype_to_np_dtype(qType)).reshape(
360
+ weight.dims
361
+ )
362
+ q_weight_initializer = onnx.numpy_helper.from_array(q_weight_data, q_weight_name)
363
+ self.model.initializer_extend([q_weight_initializer])
364
+
365
+ return q_weight_name, zp_name, scale_name
366
+
367
+ def quantize_weight_per_channel_impl(
368
+ self,
369
+ weight_name,
370
+ weight_qType,
371
+ channel_axis,
372
+ reduce_range=True,
373
+ keep_float_weight=False,
374
+ ):
375
+ # TODO(adrianlizarraga): This function is now only used by onnx_quantizer.py, so move it there.
376
+ initializer = find_by_name(weight_name, self.model.initializer())
377
+ if initializer is None:
378
+ raise ValueError("{} is not an initializer", weight_name)
379
+
380
+ weights = tensor_proto_to_array(initializer)
381
+ weights_rank = len(weights.shape)
382
+ is_axis_valid, axis_norm = normalize_axis(channel_axis, weights_rank)
383
+ if not is_axis_valid:
384
+ raise ValueError(
385
+ f"Weight {weight_name} has a per-channel axis with value {channel_axis} that is "
386
+ f"out-of-bounds for rank {weights_rank}"
387
+ )
388
+
389
+ channel_axis = axis_norm
390
+ channel_count = weights.shape[channel_axis]
391
+ quant_overrides_for_channels = self.tensor_quant_overrides.get_per_channel_overrides(
392
+ weight_name, default_val=[{"axis": channel_axis}]
393
+ )
394
+
395
+ num_channel_overrides = len(quant_overrides_for_channels)
396
+ if num_channel_overrides != 1 and num_channel_overrides != channel_count:
397
+ raise ValueError(
398
+ f"Per-channel tensor quantization overrides for {weight_name} must have "
399
+ f"either 1 or {channel_count} elements in the list of dictionaries."
400
+ )
401
+
402
+ is_axis_override_valid, axis_override = normalize_axis(quant_overrides_for_channels[0]["axis"], weights_rank)
403
+ if not is_axis_override_valid or axis_override != channel_axis:
404
+ raise ValueError(
405
+ f"Tensor quantization overrides for {weight_name} specify an unexpected axis. "
406
+ f"Expected {channel_axis}, but got {quant_overrides_for_channels[0]['axis']}."
407
+ )
408
+
409
+ # If user provides per-channel quantization overrides, all channels must use the same quant_type,
410
+ # axis, symmetric, and reduce_range values. So, just use the first channel's values.
411
+ if "quant_type" in quant_overrides_for_channels[0]:
412
+ weight_qType = quant_overrides_for_channels[0]["quant_type"].tensor_type # noqa: N806
413
+
414
+ symmetric = quant_overrides_for_channels[0].get("symmetric", self.is_weight_symmetric(weight_qType))
415
+ reduce_range = quant_overrides_for_channels[0].get("reduce_range", self.reduce_range and reduce_range)
416
+ zero_point_list = []
417
+ scale_list = []
418
+ quantized_per_channel_data_list = []
419
+ weights_shape = list(weights.shape)
420
+ reshape_dims = list(weights_shape) # deep copy
421
+ reshape_dims[channel_axis] = 1 # only one per channel for reshape
422
+ for i in range(channel_count):
423
+ per_channel_data = weights.take(i, channel_axis)
424
+ channel_override_index = i if i < num_channel_overrides else 0
425
+ channel_quant_overrides = quant_overrides_for_channels[channel_override_index]
426
+
427
+ if "scale" in channel_quant_overrides and "zero_point" in channel_quant_overrides:
428
+ zero_point = np.array(channel_quant_overrides["zero_point"], dtype=ONNX_TYPE_TO_NP_TYPE[weight_qType])
429
+ scale = np.array(channel_quant_overrides["scale"])
430
+ quantized_per_channel_data = quantize_nparray(
431
+ weight_qType, per_channel_data.flatten(), scale, zero_point
432
+ )
433
+ assert isinstance(zero_point, np.ndarray), f"Unexpected type {type(zero_point)}"
434
+ assert zero_point.dtype != np.float32 and zero_point.dtype != np.float16, (
435
+ f"Unexpected dtype {zero_point.dtype}"
436
+ )
437
+ assert isinstance(scale, np.ndarray), f"Unexpected type {type(scale)}"
438
+ assert isinstance(quantized_per_channel_data, np.ndarray), (
439
+ f"Unexpected type {type(quantized_per_channel_data)}"
440
+ )
441
+
442
+ else:
443
+ zero_point, scale, quantized_per_channel_data = quantize_data(
444
+ per_channel_data.flatten(),
445
+ weight_qType,
446
+ symmetric,
447
+ reduce_range=reduce_range,
448
+ min_real_range=self.min_real_range,
449
+ rmin_override=channel_quant_overrides.get("rmin"),
450
+ rmax_override=channel_quant_overrides.get("rmax"),
451
+ )
452
+
453
+ assert isinstance(zero_point, np.ndarray), f"Unexpected type {type(zero_point)}"
454
+ assert zero_point.dtype != np.float32 and zero_point.dtype != np.float16, (
455
+ f"Unexpected dtype {zero_point.dtype}"
456
+ )
457
+ assert isinstance(scale, np.ndarray), f"Unexpected type {type(scale)}"
458
+ assert isinstance(quantized_per_channel_data, np.ndarray), (
459
+ f"Unexpected type {type(quantized_per_channel_data)}"
460
+ )
461
+
462
+ zero_point_list.append(zero_point)
463
+ scale_list.append(scale)
464
+ quantized_per_channel_data_list.append(np.asarray(quantized_per_channel_data).reshape(reshape_dims))
465
+
466
+ # combine per_channel_data into one
467
+ quantized_weights = np.concatenate(quantized_per_channel_data_list, channel_axis)
468
+ q_weight_name = weight_name + TENSOR_NAME_QUANT_SUFFIX
469
+ zp_name = weight_name + "_zero_point"
470
+ scale_name = weight_name + "_scale"
471
+
472
+ # Update packed weight, zero point, and scale initializers
473
+ zero_scale_shape = [initializer.dims[channel_axis]]
474
+ scale_initializer = onnx.helper.make_tensor(
475
+ scale_name, initializer.data_type, zero_scale_shape, np.hstack(scale_list).tolist()
476
+ )
477
+ zero_initializer = onnx.helper.make_tensor(
478
+ zp_name, weight_qType, zero_scale_shape, np.hstack(zero_point_list).tolist()
479
+ )
480
+
481
+ self.model.initializer_extend([scale_initializer, zero_initializer])
482
+
483
+ if not keep_float_weight:
484
+ if weight_qType in (onnx.TensorProto.INT4, onnx.TensorProto.UINT4):
485
+ if quantized_weights.dtype not in (np.int8, np.uint8):
486
+ raise RuntimeError(
487
+ f"Quantized weights for {q_weight_name} must be 8-bit before packing as 4-bit values."
488
+ )
489
+
490
+ # We do not use onnx.helper.pack_float32_to_4bit() due to performance.
491
+ # This can be the difference between a large model taking 30 minutes to quantize vs 5 minutes.
492
+ packed_data = bytes(pack_bytes_to_4bit(quantized_weights.tobytes()))
493
+
494
+ # We only use onnx.helper.make_tensor with raw data due to bug: https://github.com/onnx/onnx/pull/6161
495
+ q_weight_initializer = onnx.helper.make_tensor(
496
+ q_weight_name, weight_qType, weights_shape, packed_data, raw=True
497
+ )
498
+ self.model.initializer_extend([q_weight_initializer])
499
+ else:
500
+ quantized_weights = np.asarray(
501
+ quantized_weights,
502
+ dtype=onnx.helper.tensor_dtype_to_np_dtype(weight_qType),
503
+ ).reshape(initializer.dims)
504
+ q_weight_initializer = onnx.numpy_helper.from_array(quantized_weights, q_weight_name)
505
+ self.model.initializer_extend([q_weight_initializer])
506
+
507
+ return q_weight_name, zp_name, scale_name
508
+
509
+ def adjust_tensor_ranges(self):
510
+ if self.tensors_range is None:
511
+ return
512
+
513
+ for node in self.model.nodes():
514
+ # adjust tensor_ranges for input of Clip and Relu node
515
+ if node.op_type in ["Clip", "Relu"]:
516
+ if not self.should_quantize_node(node):
517
+ continue
518
+ if len(self.model.input_name_to_nodes()[node.input[0]]) != 1:
519
+ continue
520
+ if node.input[0] not in self.tensors_range or node.output[0] not in self.tensors_range:
521
+ continue
522
+ td = self.tensors_range[node.output[0]]
523
+ if not isinstance(td, TensorData):
524
+ raise TypeError(f"Unexpected type {type(td)} for {node.output[0]!r}.")
525
+ self.tensors_range[node.input[0]] = td
526
+ # Adjust Softmax to range from 0.0 to 1.0
527
+ elif node.op_type == "Softmax":
528
+ if not self.should_quantize_node(node):
529
+ continue
530
+ self.tensors_range[node.output[0]] = TensorData(lowest=np.float32(0.0), highest=np.float32(1.0))
ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/quantization/calibrate.py ADDED
@@ -0,0 +1,1353 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # -------------------------------------------------------------------------
3
+ # Copyright (c) Microsoft, Intel Corporation. All rights reserved.
4
+ # Licensed under the MIT License. See License.txt in the project root for
5
+ # license information.
6
+ # --------------------------------------------------------------------------
7
+ import abc
8
+ import contextlib
9
+ import copy
10
+ import itertools
11
+ import json
12
+ import os
13
+ import tempfile
14
+ import uuid
15
+ from collections.abc import Sequence
16
+ from enum import Enum
17
+ from pathlib import Path
18
+
19
+ import numpy as np
20
+ import onnx
21
+ from onnx import ModelProto, TensorProto, helper, numpy_helper
22
+
23
+ import onnxruntime
24
+
25
+ from .quant_utils import apply_plot, load_model_with_shape_infer, smooth_distribution
26
+
27
+
28
+ def rel_entr(pk: np.ndarray, qk: np.ndarray) -> np.ndarray:
29
+ """
30
+ See https://docs.scipy.org/doc/scipy/reference/generated/scipy.special.rel_entr.html#scipy.special.rel_entr.
31
+ Python implementation.
32
+ """
33
+ res = np.empty(pk.shape, dtype=pk.dtype)
34
+ res[:] = pk[:] * np.log(pk[:] / qk[:])
35
+ c2 = (pk == 0) & (qk >= 0)
36
+ res[c2] = 0
37
+ c1 = (pk > 0) & (qk > 0)
38
+ res[~c1] = np.inf
39
+ return res
40
+
41
+
42
+ def entropy(
43
+ pk: np.ndarray,
44
+ qk: np.ndarray,
45
+ base: float | None = None,
46
+ axis: int = 0,
47
+ ) -> np.ndarray:
48
+ """
49
+ Simplifeied version of entropy.
50
+ Source: https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.entropy.html.
51
+ This avoids taking a dependency on scipy just for this function.
52
+ """
53
+ assert base is None or base > 0, "base={base} must be a positive number or `None`."
54
+ assert qk is not None, "qk is None"
55
+
56
+ pk = np.asarray(pk).astype(np.float32)
57
+ pk = 1.0 * pk / np.sum(pk, axis=axis, keepdims=True)
58
+
59
+ qk = np.asarray(qk).astype(np.float32)
60
+ pk, qk = np.broadcast_arrays(pk, qk)
61
+ qk = 1.0 * qk / np.sum(qk, axis=axis, keepdims=True)
62
+ vec = rel_entr(pk, qk)
63
+
64
+ s = np.sum(vec, axis=axis)
65
+ if base is not None:
66
+ s /= np.log(base)
67
+ return s.astype(pk.dtype)
68
+
69
+
70
+ class TensorData:
71
+ _allowed = frozenset(["avg", "std", "lowest", "highest", "hist", "hist_edges", "bins"])
72
+ _floats = frozenset(["avg", "std", "lowest", "highest", "hist_edges"])
73
+
74
+ def __init__(self, **kwargs):
75
+ self._attrs = list(kwargs.keys())
76
+ for k, v in kwargs.items():
77
+ if k not in TensorData._allowed:
78
+ raise ValueError(f"Unexpected value {k!r} not in {TensorData._allowed}.")
79
+ if k in TensorData._floats:
80
+ if not hasattr(v, "dtype"):
81
+ raise ValueError(f"Unexpected type {type(v)} for k={k!r}")
82
+ if v.dtype not in (np.float16, np.float32):
83
+ raise ValueError(f"Unexpected dtype {v.dtype} for k={k!r}")
84
+ setattr(self, k, v)
85
+
86
+ @property
87
+ def range_value(self):
88
+ if not hasattr(self, "lowest") or not hasattr(self, "highest"):
89
+ raise AttributeError(f"Attributes 'lowest' and/or 'highest' missing in {dir(self)}.")
90
+ return (self.lowest, self.highest)
91
+
92
+ @property
93
+ def avg_std(self):
94
+ if not hasattr(self, "avg") or not hasattr(self, "std"):
95
+ raise AttributeError(f"Attributes 'avg' and/or 'std' missing in {dir(self)}.")
96
+ return (self.avg, self.std)
97
+
98
+ def to_dict(self):
99
+ # This is needed to serialize the data into JSON.
100
+ data = {k: getattr(self, k) for k in self._attrs}
101
+ data["CLS"] = self.__class__.__name__
102
+ return data
103
+
104
+ @classmethod
105
+ def from_dict(cls, d: dict) -> "TensorData":
106
+ """Reconstruct a TensorData from a dict produced by to_dict()."""
107
+ kwargs = {}
108
+ for k, v in d.items():
109
+ if k == "CLS":
110
+ continue
111
+ value = v
112
+ if isinstance(value, dict) and value.get("CLS") == "numpy.array":
113
+ value = np.array(value["data"], dtype=np.dtype(value["dtype"]))
114
+ elif k in cls._floats and isinstance(value, (int, float)):
115
+ value = np.array(value, dtype=np.float32)
116
+ kwargs[k] = value
117
+ return cls(**kwargs)
118
+
119
+
120
+ class TensorsData:
121
+ def __init__(self, calibration_method, data: dict[str, TensorData | tuple]):
122
+ self.calibration_method = calibration_method
123
+ self.data = {}
124
+ for k, v in data.items():
125
+ if not isinstance(k, str):
126
+ raise TypeError(f"Keys must be strings not {type(k)}.")
127
+ if isinstance(v, tuple):
128
+ if calibration_method == CalibrationMethod.MinMax and len(v) == 2:
129
+ self.data[k] = TensorData(lowest=v[0], highest=v[1])
130
+ continue
131
+ if len(v) == 4:
132
+ self.data[k] = TensorData(lowest=v[0], highest=v[1], hist=v[2], bins=v[3])
133
+ continue
134
+ raise TypeError(f"Unexpected tuple for {k:r}, it has {len(v)} elements: {v}.")
135
+ if not isinstance(v, TensorData):
136
+ raise TypeError(f"Values must be TensorData not {type(v)}.")
137
+ self.data[k] = v
138
+
139
+ def __iter__(self):
140
+ yield from self.data
141
+
142
+ def __contains__(self, key):
143
+ return key in self.data
144
+
145
+ def __getitem__(self, key):
146
+ return self.data[key]
147
+
148
+ def __setitem__(self, key, value):
149
+ if key not in self.data:
150
+ raise RuntimeError(f"Only an existing tensor can be modified, {key!r} is not.")
151
+ self.data[key] = value
152
+
153
+ def keys(self):
154
+ return self.data.keys()
155
+
156
+ def values(self):
157
+ return self.data.values()
158
+
159
+ def items(self):
160
+ return self.data.items()
161
+
162
+ def to_dict(self):
163
+ # This is needed to serialize the data into JSON.
164
+ data = {
165
+ "CLS": self.__class__.__name__,
166
+ "data": self.data,
167
+ "calibration_method": self.calibration_method,
168
+ }
169
+ return data
170
+
171
+ @classmethod
172
+ def from_dict(cls, d: dict) -> "TensorsData":
173
+ """Reconstruct a TensorsData from a dict produced by to_dict()."""
174
+ method_val = d["calibration_method"]
175
+ if isinstance(method_val, dict) and method_val.get("CLS") == "CalibrationMethod":
176
+ name = method_val["value"].split(".")[-1]
177
+ method = CalibrationMethod[name]
178
+ else:
179
+ method = method_val
180
+ reconstructed = {k: TensorData.from_dict(v) for k, v in d["data"].items()}
181
+ return cls(method, reconstructed)
182
+
183
+
184
+ class CalibrationMethod(Enum):
185
+ MinMax = 0
186
+ Entropy = 1
187
+ Percentile = 2
188
+ Distribution = 3
189
+
190
+
191
+ class CalibrationDataReader(metaclass=abc.ABCMeta):
192
+ @classmethod
193
+ def __subclasshook__(cls, subclass):
194
+ return (hasattr(subclass, "get_next") and callable(subclass.get_next)) or NotImplemented
195
+
196
+ @abc.abstractmethod
197
+ def get_next(self) -> dict:
198
+ """generate the input data dict for ONNXinferenceSession run"""
199
+ raise NotImplementedError
200
+
201
+ def __iter__(self):
202
+ return self
203
+
204
+ def __next__(self):
205
+ result = self.get_next()
206
+ if result is None:
207
+ raise StopIteration
208
+ return result
209
+
210
+ def __len__(self):
211
+ raise NotImplementedError
212
+
213
+ def set_range(self, start_index: int, end_index: int):
214
+ raise NotImplementedError
215
+
216
+
217
+ class CalibrationCacheEncoder(json.JSONEncoder):
218
+ """Shared JSON encoder for calibration caches.
219
+
220
+ Handles numpy ndarrays and numpy scalar types (integer/floating) so
221
+ calibration JSON output is consistent across ``save_tensors_data`` and
222
+ ``quant_utils.write_calibration_table``.
223
+ """
224
+
225
+ def default(self, obj):
226
+ if isinstance(obj, (TensorData, TensorsData)):
227
+ return obj.to_dict()
228
+ if isinstance(obj, np.ndarray):
229
+ return {"data": obj.tolist(), "dtype": str(obj.dtype), "CLS": "numpy.array"}
230
+ if isinstance(obj, CalibrationMethod):
231
+ return {"CLS": obj.__class__.__name__, "value": str(obj)}
232
+ if isinstance(obj, np.integer):
233
+ return int(obj)
234
+ if isinstance(obj, np.floating):
235
+ return float(obj)
236
+ return json.JSONEncoder.default(self, obj)
237
+
238
+
239
+ def save_tensors_data(tensors_data: "TensorsData", path: "str | Path", *, smooth_quant: bool = False) -> None:
240
+ """Serialize calibration tensor ranges to a JSON file at *path*.
241
+
242
+ :param smooth_quant: whether the producing run used SmoothQuant. Stored in
243
+ the cache so a later load can detect a mismatch and recompute.
244
+ """
245
+ path = Path(path)
246
+ path.parent.mkdir(parents=True, exist_ok=True)
247
+ fd, tmp_name = tempfile.mkstemp(dir=path.parent, prefix=".calibcache_", suffix=".tmp")
248
+ try:
249
+ with os.fdopen(fd, "w") as f:
250
+ payload = tensors_data.to_dict()
251
+ payload["smooth_quant"] = smooth_quant
252
+ json.dump(payload, f, cls=CalibrationCacheEncoder)
253
+ f.flush()
254
+ os.replace(tmp_name, path)
255
+ except BaseException:
256
+ with contextlib.suppress(FileNotFoundError):
257
+ os.unlink(tmp_name)
258
+ raise
259
+
260
+
261
+ def load_tensors_data(path: "str | Path") -> "TensorsData":
262
+ """Load calibration tensor ranges from a JSON file written by save_tensors_data()."""
263
+ path = Path(path)
264
+ if not path.exists():
265
+ raise FileNotFoundError(f"Calibration cache not found: {path}")
266
+ if not path.is_file():
267
+ raise ValueError(f"Calibration cache path is not a file: {path}")
268
+ with path.open("r") as f:
269
+ d = json.load(f)
270
+ return TensorsData.from_dict(d)
271
+
272
+
273
+ class CalibraterBase:
274
+ def __init__(
275
+ self,
276
+ model_path: str | Path,
277
+ op_types_to_calibrate: Sequence[str] | None = None,
278
+ augmented_model_path="augmented_model.onnx",
279
+ symmetric=False,
280
+ use_external_data_format=False,
281
+ per_channel=False,
282
+ ):
283
+ """
284
+ :param model_path: ONNX model to calibrate. It should be a model file path
285
+ :param op_types_to_calibrate: operator types to calibrate. By default, calibrate all the float32/float16 tensors.
286
+ :param augmented_model_path: save augmented model to this path.
287
+ :param symmetric: make range of tensor symmetric (central point is 0).
288
+ :param use_external_data_format: use external data format to store model which size is >= 2Gb.
289
+ :param per_channel: whether to compute ranges per each channel.
290
+ """
291
+ if isinstance(model_path, str):
292
+ self.model = load_model_with_shape_infer(Path(model_path))
293
+ elif isinstance(model_path, Path):
294
+ self.model = load_model_with_shape_infer(model_path)
295
+ else:
296
+ raise ValueError("model_path should be model path.")
297
+
298
+ self.op_types_to_calibrate = op_types_to_calibrate
299
+ self.augmented_model_path = augmented_model_path
300
+ self.symmetric = symmetric
301
+ self.use_external_data_format = use_external_data_format
302
+ self.per_channel = per_channel
303
+
304
+ self.augment_model = None
305
+ self.infer_session = None
306
+ self.execution_providers = ["CPUExecutionProvider"]
307
+
308
+ def set_execution_providers(self, execution_providers=["CPUExecutionProvider"]): # noqa: B006
309
+ """
310
+ reset the execution providers to execute the collect_data. It triggers to re-creating inference session.
311
+ """
312
+ self.execution_providers = execution_providers
313
+ self.create_inference_session()
314
+
315
+ def create_inference_session(self):
316
+ """
317
+ create an OnnxRuntime InferenceSession.
318
+ """
319
+ sess_options = onnxruntime.SessionOptions()
320
+ sess_options.graph_optimization_level = onnxruntime.GraphOptimizationLevel.ORT_DISABLE_ALL
321
+ self.infer_session = onnxruntime.InferenceSession(
322
+ self.augmented_model_path,
323
+ sess_options=sess_options,
324
+ providers=self.execution_providers,
325
+ )
326
+
327
+ def select_tensors_to_calibrate(self, model: ModelProto):
328
+ """
329
+ select input/output tensors of candidate nodes to calibrate.
330
+ returns:
331
+ tensors (set): set of tensor name.
332
+ value_infos (dict): tensor name to value info.
333
+ """
334
+ value_infos = {vi.name: vi for vi in model.graph.value_info}
335
+ value_infos.update({ot.name: ot for ot in model.graph.output})
336
+ value_infos.update({it.name: it for it in model.graph.input})
337
+ initializer = {init.name for init in model.graph.initializer}
338
+
339
+ tensors_to_calibrate = set()
340
+ tensor_type_to_calibrate = {TensorProto.FLOAT, TensorProto.FLOAT16}
341
+
342
+ for node in model.graph.node:
343
+ if not self.op_types_to_calibrate or node.op_type in self.op_types_to_calibrate:
344
+ for tensor_name in itertools.chain(node.input, node.output):
345
+ if tensor_name in value_infos:
346
+ vi = value_infos[tensor_name]
347
+ if (
348
+ vi.type.HasField("tensor_type")
349
+ and (vi.type.tensor_type.elem_type in tensor_type_to_calibrate)
350
+ and (tensor_name not in initializer)
351
+ ):
352
+ tensors_to_calibrate.add(tensor_name)
353
+
354
+ return tensors_to_calibrate, value_infos
355
+
356
+ def get_augment_model(self):
357
+ """
358
+ return: augmented onnx model. Call after calling augment_graph
359
+ """
360
+ return self.model
361
+
362
+ def augment_graph(self):
363
+ """
364
+ abstract method: augment the input model to prepare for collecting data. It will:
365
+ 1. augment the model to be able to collect desired statistics data
366
+ 2. save augmented model to augmented_model_paths
367
+ """
368
+ raise NotImplementedError
369
+
370
+ def collect_data(self, data_reader: CalibrationDataReader):
371
+ """
372
+ abstract method: collect the tensors that will be used for range computation. It can be called multiple times.
373
+ """
374
+ raise NotImplementedError
375
+
376
+ def compute_data(self) -> TensorsData:
377
+ """
378
+ abstract method: compute data based on the calibration method stored in TensorsData
379
+ """
380
+ raise NotImplementedError
381
+
382
+
383
+ class MinMaxCalibrater(CalibraterBase):
384
+ def __init__(
385
+ self,
386
+ model_path: str | Path,
387
+ op_types_to_calibrate: Sequence[str] | None = None,
388
+ augmented_model_path="augmented_model.onnx",
389
+ symmetric=False,
390
+ use_external_data_format=False,
391
+ moving_average=False,
392
+ averaging_constant=0.01,
393
+ max_intermediate_outputs=None,
394
+ per_channel=False,
395
+ ):
396
+ """
397
+ :param model_path: ONNX model to calibrate. It is a model path
398
+ :param op_types_to_calibrate: operator types to calibrate. By default, calibrate all the float32/float16 tensors.
399
+ :param augmented_model_path: save augmented model to this path.
400
+ :param symmetric: make range of tensor symmetric (central point is 0).
401
+ :param use_external_data_format: use external data format to store model which size is >= 2Gb
402
+ :param moving_average: compute the moving average of the minimum and maximum values instead of the global minimum and maximum.
403
+ :param averaging_constant: constant smoothing factor to use when computing the moving average.
404
+ :param max_intermediate_outputs: maximum number of intermediate outputs before an intermediate range is computed.
405
+ :param per_channel: whether to compute ranges per each channel.
406
+ """
407
+ super().__init__(
408
+ model_path,
409
+ op_types_to_calibrate=op_types_to_calibrate,
410
+ augmented_model_path=augmented_model_path,
411
+ symmetric=symmetric,
412
+ use_external_data_format=use_external_data_format,
413
+ per_channel=per_channel,
414
+ )
415
+ self.intermediate_outputs = []
416
+ self.calibrate_tensors_range = None
417
+ self.num_model_outputs = len(self.model.graph.output)
418
+ self.model_original_outputs = {output.name for output in self.model.graph.output}
419
+ self.moving_average = moving_average
420
+ if moving_average and (averaging_constant < 0 or averaging_constant > 1):
421
+ raise ValueError("Invalid averaging constant, which should not be < 0 or > 1.")
422
+ self.averaging_constant = averaging_constant
423
+ self.max_intermediate_outputs = max_intermediate_outputs
424
+
425
+ def augment_graph(self):
426
+ """
427
+ Adds ReduceMin and ReduceMax nodes to all quantization_candidates op type nodes in
428
+ model and ensures their outputs are stored as part of the graph output
429
+ :return: augmented ONNX model
430
+ """
431
+ tensors, _ = self.select_tensors_to_calibrate(self.model)
432
+ reshape_shape_name = str(uuid.uuid4())
433
+ reshape_shape = numpy_helper.from_array(np.array([-1], dtype=np.int64), reshape_shape_name)
434
+ self.model.graph.initializer.append(reshape_shape)
435
+
436
+ def get_op_version(op_type, model):
437
+ for opset_import in model.opset_import:
438
+ if onnx.defs.has(op_type, opset_import.domain):
439
+ return opset_import.version
440
+ raise RuntimeError(f"Model does not contain a version for '{op_type}'.")
441
+
442
+ def insert_nodes(tensor_name, new_nodes):
443
+ index = next(
444
+ (i for i, x in enumerate(self.model.graph.node) if tensor_name in x.input), len(self.model.graph.node)
445
+ )
446
+ for node in new_nodes:
447
+ self.model.graph.node.insert(index, node)
448
+ index += 1
449
+
450
+ def add_reduce_min_max(tensor_name, reduce_op_name):
451
+ # When doing ReduceMax/ReduceMin, ORT can't reduce on dim with value of 0 if 'keepdims' is false.
452
+ # To make the code simple, we always let keepdims to be 1.
453
+ keepdims = 1
454
+
455
+ # Adding ReduceMin/ReduceMax nodes: ReduceMin/ReduceMax -> Reshape-> (output)
456
+ reduce_output = tensor_name + "_" + reduce_op_name
457
+ intermediate_output = reduce_output + "_Reshape"
458
+ reduce_node = onnx.helper.make_node(
459
+ reduce_op_name, [tensor_name], [intermediate_output], keepdims=keepdims, name=reduce_output
460
+ )
461
+
462
+ reshape_node = onnx.helper.make_node(
463
+ "Reshape",
464
+ inputs=[intermediate_output, reshape_shape_name],
465
+ outputs=[reduce_output],
466
+ name=intermediate_output,
467
+ )
468
+
469
+ value_infos = {vi.name: vi for vi in self.model.graph.value_info}
470
+ value_infos.update({o.name: o for o in self.model.graph.output})
471
+ value_infos.update({i.name: i for i in self.model.graph.input})
472
+ if tensor_name in value_infos:
473
+ onnx_type = value_infos[tensor_name].type.tensor_type.elem_type
474
+ else:
475
+ raise ValueError(
476
+ f"Unable to guess tensor type for tensor {tensor_name!r}, "
477
+ "running shape inference before quantization may resolve this issue."
478
+ )
479
+
480
+ # Include axes in reduce_op when per_channel, always keeping axis=1
481
+ if self.per_channel:
482
+ tensor_rank = len(value_infos[tensor_name].type.tensor_type.shape.dim)
483
+ reduced_axes = [0, *range(2, tensor_rank)]
484
+ # Depending on opset version, axes in ReduceMin/ReduceMax are in attribute or inputs
485
+ if get_op_version(reduce_op_name, self.model) < 18:
486
+ reduce_node.attribute.append(helper.make_attribute("axes", reduced_axes))
487
+ else:
488
+ reduce_axes_name = str(uuid.uuid4())
489
+ reduce_axes = numpy_helper.from_array(np.array(reduced_axes, dtype=np.int64), reduce_axes_name)
490
+ reduce_node.input.append(reduce_axes_name)
491
+ self.model.graph.initializer.append(reduce_axes)
492
+
493
+ insert_nodes(tensor_name, [reduce_node, reshape_node])
494
+ self.model.graph.output.append(helper.make_tensor_value_info(reduce_output, onnx_type, [None]))
495
+
496
+ for tensor in tensors:
497
+ add_reduce_min_max(tensor, "ReduceMin")
498
+ add_reduce_min_max(tensor, "ReduceMax")
499
+
500
+ onnx.save(
501
+ self.model,
502
+ self.augmented_model_path,
503
+ save_as_external_data=self.use_external_data_format,
504
+ )
505
+
506
+ def clear_collected_data(self):
507
+ self.intermediate_outputs = []
508
+
509
+ def collect_data(self, data_reader: CalibrationDataReader):
510
+ while True:
511
+ inputs = data_reader.get_next()
512
+ if not inputs:
513
+ break
514
+ self.intermediate_outputs.append(
515
+ [
516
+ value if sess_o.name not in self.model_original_outputs else None
517
+ for sess_o, value in zip(
518
+ self.infer_session.get_outputs(), self.infer_session.run(None, inputs), strict=False
519
+ )
520
+ ]
521
+ )
522
+ if (
523
+ self.max_intermediate_outputs is not None
524
+ and len(self.intermediate_outputs) == self.max_intermediate_outputs
525
+ ):
526
+ self.clear_collected_data()
527
+
528
+ if len(self.intermediate_outputs) == 0 and self.calibrate_tensors_range is None:
529
+ raise ValueError("No data is collected.")
530
+
531
+ t = self.compute_data()
532
+ if not isinstance(t, TensorsData):
533
+ raise TypeError(f"compute_data must return a TensorsData not {type(t)}.")
534
+ self.clear_collected_data()
535
+
536
+ def merge_range(self, old_range, new_range):
537
+ if not old_range:
538
+ return new_range
539
+
540
+ for key, value in old_range.items():
541
+ # Handling for structured data types with TensorData
542
+ if isinstance(value, TensorData):
543
+ old_min = value.range_value[0]
544
+ old_max = value.range_value[1]
545
+ else:
546
+ old_min, old_max = value
547
+
548
+ if isinstance(new_range[key], TensorData):
549
+ new_min = new_range[key].range_value[0]
550
+ new_max = new_range[key].range_value[1]
551
+ else:
552
+ new_min, new_max = new_range[key]
553
+
554
+ if self.moving_average:
555
+ min_value = old_min + self.averaging_constant * (new_min - old_min)
556
+ max_value = old_max + self.averaging_constant * (new_max - old_max)
557
+ else:
558
+ min_value = min(old_min, new_min)
559
+ max_value = max(old_max, new_max)
560
+
561
+ # If structured as TensorData, wrap the result accordingly
562
+ if isinstance(value, TensorData) or isinstance(new_range[key], TensorData):
563
+ new_range[key] = TensorData(lowest=min_value, highest=max_value)
564
+ else:
565
+ new_range[key] = (min_value, max_value)
566
+
567
+ return new_range
568
+
569
+ def compute_data(self) -> TensorsData:
570
+ """
571
+ Compute the min-max range of tensor
572
+ :return: dictionary mapping: {added node names: (ReduceMin, ReduceMax) pairs }
573
+ """
574
+
575
+ if len(self.intermediate_outputs) == 0:
576
+ return self.calibrate_tensors_range
577
+
578
+ output_names = [self.infer_session.get_outputs()[i].name for i in range(len(self.intermediate_outputs[0]))]
579
+ output_dicts_list = [
580
+ dict(zip(output_names, intermediate_output, strict=False))
581
+ for intermediate_output in self.intermediate_outputs
582
+ ]
583
+
584
+ merged_output_dict = {}
585
+ for d in output_dicts_list:
586
+ for k, v in d.items():
587
+ merged_output_dict.setdefault(k, []).append(v)
588
+ added_output_names = output_names[self.num_model_outputs :]
589
+ calibrate_tensor_names = [
590
+ added_output_names[i].rpartition("_")[0] for i in range(0, len(added_output_names), 2)
591
+ ] # output names
592
+
593
+ merged_added_output_dict = {
594
+ i: merged_output_dict[i] for i in merged_output_dict if i not in self.model_original_outputs
595
+ }
596
+
597
+ pairs = []
598
+ for i in range(0, len(added_output_names), 2):
599
+ if self.moving_average:
600
+ min_value_array = np.nanmean(merged_added_output_dict[added_output_names[i]], axis=0)
601
+ max_value_array = np.nanmean(merged_added_output_dict[added_output_names[i + 1]], axis=0)
602
+ else:
603
+ min_value_array = np.nanmin(merged_added_output_dict[added_output_names[i]], axis=0)
604
+ max_value_array = np.nanmax(merged_added_output_dict[added_output_names[i + 1]], axis=0)
605
+
606
+ if self.symmetric:
607
+ max_absolute_value = np.nanmax([np.abs(min_value_array), np.abs(max_value_array)], axis=0)
608
+ pairs.append((-max_absolute_value, max_absolute_value))
609
+ else:
610
+ pairs.append((min_value_array, max_value_array))
611
+
612
+ new_calibrate_tensors_range = TensorsData(
613
+ CalibrationMethod.MinMax, dict(zip(calibrate_tensor_names, pairs, strict=False))
614
+ )
615
+ if self.calibrate_tensors_range:
616
+ self.calibrate_tensors_range = self.merge_range(self.calibrate_tensors_range, new_calibrate_tensors_range)
617
+ else:
618
+ self.calibrate_tensors_range = new_calibrate_tensors_range
619
+
620
+ return self.calibrate_tensors_range
621
+
622
+
623
+ class HistogramCalibrater(CalibraterBase):
624
+ def __init__(
625
+ self,
626
+ model_path: str | Path,
627
+ op_types_to_calibrate: Sequence[str] | None = None,
628
+ augmented_model_path="augmented_model.onnx",
629
+ use_external_data_format=False,
630
+ method="percentile",
631
+ symmetric=False,
632
+ num_bins=128,
633
+ num_quantized_bins=2048,
634
+ percentile=99.999,
635
+ scenario="same",
636
+ ):
637
+ """
638
+ :param model_path: ONNX model to calibrate. It is a model path.
639
+ :param op_types_to_calibrate: operator types to calibrate. By default, calibrate all the float32/float16 tensors.
640
+ :param augmented_model_path: save augmented model to this path.
641
+ :param use_external_data_format: use external data format to store model which size is >= 2Gb
642
+ :param method: A string. One of ['entropy', 'percentile'].
643
+ :param symmetric: make range of tensor symmetric (central point is 0).
644
+ :param num_bins: number of bins to create a new histogram for collecting tensor values.
645
+ :param num_quantized_bins: number of quantized bins. Default 128.
646
+ :param percentile: A float number between [0, 100]. Default 99.99.
647
+ :param scenario: see :class:`DistributionCalibrater`
648
+ """
649
+ super().__init__(
650
+ model_path,
651
+ op_types_to_calibrate=op_types_to_calibrate,
652
+ augmented_model_path=augmented_model_path,
653
+ symmetric=symmetric,
654
+ use_external_data_format=use_external_data_format,
655
+ )
656
+ self.intermediate_outputs = []
657
+ self.calibrate_tensors_range = None
658
+ self.num_model_outputs = len(self.model.graph.output)
659
+ self.model_original_outputs = {output.name for output in self.model.graph.output}
660
+ self.collector = None
661
+ self.method = method
662
+ self.num_bins = num_bins
663
+ self.num_quantized_bins = num_quantized_bins
664
+ self.percentile = percentile
665
+ self.tensors_to_calibrate = None
666
+ self.scenario = scenario
667
+
668
+ def augment_graph(self):
669
+ """
670
+ make all quantization_candidates op type nodes as part of the graph output.
671
+ :return: augmented ONNX model
672
+ """
673
+ self.tensors_to_calibrate, value_infos = self.select_tensors_to_calibrate(self.model)
674
+ for tensor in self.tensors_to_calibrate:
675
+ if tensor not in self.model_original_outputs:
676
+ self.model.graph.output.append(value_infos[tensor])
677
+
678
+ onnx.save(
679
+ self.model,
680
+ self.augmented_model_path,
681
+ save_as_external_data=self.use_external_data_format,
682
+ )
683
+
684
+ def clear_collected_data(self):
685
+ self.intermediate_outputs = []
686
+
687
+ def collect_data(self, data_reader: CalibrationDataReader):
688
+ """
689
+ Entropy Calibrator collects operators' tensors as well as generates tensor histogram for each operator.
690
+ """
691
+ input_names_set = {node_arg.name for node_arg in self.infer_session.get_inputs()}
692
+ output_names = [node_arg.name for node_arg in self.infer_session.get_outputs()]
693
+
694
+ while True:
695
+ inputs = data_reader.get_next()
696
+ if not inputs:
697
+ break
698
+ outputs = self.infer_session.run(None, inputs)
699
+
700
+ # Copy np.ndarray only for graph outputs that are also graph inputs to workaround bug:
701
+ # https://github.com/microsoft/onnxruntime/issues/21922
702
+ fixed_outputs = []
703
+ for output_index, output in enumerate(outputs):
704
+ if output_names[output_index] in input_names_set:
705
+ fixed_outputs.append(copy.copy(output))
706
+ else:
707
+ fixed_outputs.append(output)
708
+
709
+ self.intermediate_outputs.append(fixed_outputs)
710
+
711
+ if len(self.intermediate_outputs) == 0:
712
+ raise ValueError("No data is collected.")
713
+
714
+ output_dicts_list = [
715
+ dict(zip(output_names, intermediate_output, strict=False))
716
+ for intermediate_output in self.intermediate_outputs
717
+ ]
718
+
719
+ merged_dict = {}
720
+ for d in output_dicts_list:
721
+ for k, v in d.items():
722
+ merged_dict.setdefault(k, []).append(v)
723
+
724
+ clean_merged_dict = {i: merged_dict[i] for i in merged_dict if i in self.tensors_to_calibrate}
725
+
726
+ if not self.collector:
727
+ self.collector = HistogramCollector(
728
+ method=self.method,
729
+ symmetric=self.symmetric,
730
+ num_bins=self.num_bins,
731
+ num_quantized_bins=self.num_quantized_bins,
732
+ percentile=self.percentile,
733
+ scenario=self.scenario,
734
+ )
735
+ self.collector.collect(clean_merged_dict)
736
+
737
+ self.clear_collected_data()
738
+
739
+ def compute_data(self) -> TensorsData:
740
+ """
741
+ Compute the min-max range of tensor
742
+ :return: dictionary mapping: {tensor name: (min value, max value)}
743
+ """
744
+ if not self.collector:
745
+ raise ValueError("No collector created and can't generate calibration data.")
746
+
747
+ if isinstance(self, EntropyCalibrater):
748
+ cal = CalibrationMethod.Entropy
749
+ elif isinstance(self, PercentileCalibrater):
750
+ cal = CalibrationMethod.Percentile
751
+ elif isinstance(self, DistributionCalibrater):
752
+ cal = CalibrationMethod.Distribution
753
+ else:
754
+ raise TypeError(f"Unknown calibrater {type(self)}. This method must be overwritten.")
755
+ return TensorsData(cal, self.collector.compute_collection_result())
756
+
757
+
758
+ class EntropyCalibrater(HistogramCalibrater):
759
+ def __init__(
760
+ self,
761
+ model_path: str | Path,
762
+ op_types_to_calibrate: Sequence[str] | None = None,
763
+ augmented_model_path="augmented_model.onnx",
764
+ use_external_data_format=False,
765
+ method="entropy",
766
+ symmetric=False,
767
+ num_bins=128,
768
+ num_quantized_bins=128,
769
+ ):
770
+ """
771
+ :param model_path: ONNX model to calibrate. It is a model path
772
+ :param op_types_to_calibrate: operator types to calibrate. By default, calibrate all the float32/float16 tensors.
773
+ :param augmented_model_path: save augmented model to this path.
774
+ :param use_external_data_format: use external data format to store model which size is >= 2Gb
775
+ :param method: A string. One of ['entropy', 'percentile', 'distribution'].
776
+ :param symmetric: make range of tensor symmetric (central point is 0).
777
+ :param num_bins: number of bins to create a new histogram for collecting tensor values.
778
+ :param num_quantized_bins: number of quantized bins. Default 128.
779
+ """
780
+ super().__init__(
781
+ model_path,
782
+ op_types_to_calibrate,
783
+ augmented_model_path,
784
+ use_external_data_format,
785
+ method=method,
786
+ symmetric=symmetric,
787
+ num_bins=num_bins,
788
+ num_quantized_bins=num_quantized_bins,
789
+ )
790
+
791
+
792
+ class PercentileCalibrater(HistogramCalibrater):
793
+ def __init__(
794
+ self,
795
+ model_path: str | Path,
796
+ op_types_to_calibrate: Sequence[str] | None = None,
797
+ augmented_model_path="augmented_model.onnx",
798
+ use_external_data_format=False,
799
+ method="percentile",
800
+ symmetric=False,
801
+ num_bins=2048,
802
+ percentile=99.999,
803
+ ):
804
+ """
805
+ :param model_path: ONNX model to calibrate. It is a model path
806
+ :param op_types_to_calibrate: operator types to calibrate. By default, calibrate all the float32/float16 tensors.
807
+ :param augmented_model_path: save augmented model to this path.
808
+ :param use_external_data_format: use external data format to store model which size is >= 2Gb
809
+ :param method: A string. One of ['entropy', 'percentile', 'distribution'].
810
+ :param symmetric: make range of tensor symmetric (central point is 0).
811
+ :param num_quantized_bins: number of quantized bins. Default 128.
812
+ :param percentile: A float number between [0, 100]. Default 99.99.
813
+ """
814
+ super().__init__(
815
+ model_path,
816
+ op_types_to_calibrate,
817
+ augmented_model_path,
818
+ use_external_data_format,
819
+ method=method,
820
+ symmetric=symmetric,
821
+ num_bins=num_bins,
822
+ percentile=percentile,
823
+ )
824
+
825
+
826
+ class DistributionCalibrater(HistogramCalibrater):
827
+ def __init__(
828
+ self,
829
+ model_path: str | Path,
830
+ op_types_to_calibrate: Sequence[str] | None = None,
831
+ augmented_model_path="augmented_model.onnx",
832
+ use_external_data_format=False,
833
+ method="distribution",
834
+ num_bins=128,
835
+ scenario="same",
836
+ ):
837
+ """
838
+ :param model_path: ONNX model to calibrate. It is a model path
839
+ :param op_types_to_calibrate: operator types to calibrate. By default, calibrate all the float32/float16 tensors.
840
+ :param augmented_model_path: save augmented model to this path.
841
+ :param use_external_data_format: use external data format to store model which size is >= 2Gb
842
+ :param method: A string. One of ['entropy', 'percentile', 'distribution'].
843
+ :param symmetric: make range of tensor symmetric (central point is 0).
844
+ :param num_bins: number of bins to create a new histogram for collecting tensor values.
845
+ :param scenario: for float 8 only, if `scenario="same"`,
846
+ the algorithm weights and float 8 follow the same distribution,
847
+ if `scenario="p3"`, it assumes the weights follow
848
+ a gaussian law and float 8 ~ X^3 where X is a gaussian law
849
+ """
850
+ super().__init__(
851
+ model_path,
852
+ op_types_to_calibrate,
853
+ augmented_model_path,
854
+ use_external_data_format,
855
+ method=method,
856
+ num_bins=num_bins,
857
+ scenario=scenario,
858
+ )
859
+
860
+
861
+ class CalibrationDataCollector(metaclass=abc.ABCMeta):
862
+ """
863
+ Base class for collecting data for calibration-based quantization.
864
+ """
865
+
866
+ @abc.abstractmethod
867
+ def collect(self, name_to_arr):
868
+ """
869
+ Generate informative data based on given data.
870
+ name_to_arr : dict
871
+ tensor name to NDArray data
872
+ """
873
+ raise NotImplementedError
874
+
875
+ @abc.abstractmethod
876
+ def compute_collection_result(self):
877
+ """
878
+ Get the optimal result among collection data.
879
+ """
880
+ raise NotImplementedError
881
+
882
+
883
+ class HistogramCollector(CalibrationDataCollector):
884
+ """
885
+ Collecting histogram for each tensor. Percentile and Entropy method are supported.
886
+
887
+ ref: https://github.com//apache/incubator-mxnet/blob/master/python/mxnet/contrib/quantization.py
888
+ ref: https://docs.nvidia.com/deeplearning/tensorrt/pytorch-quantization-toolkit/docs/_modules/
889
+ pytorch_quantization/calib/histogram.html
890
+ """
891
+
892
+ def __init__(self, method, symmetric, num_bins, num_quantized_bins, percentile, scenario):
893
+ self.histogram_dict = {}
894
+ self.method = method
895
+ self.symmetric = symmetric
896
+ self.num_bins = num_bins
897
+ self.num_quantized_bins = num_quantized_bins
898
+ self.percentile = percentile
899
+ self.scenario = scenario
900
+
901
+ def get_histogram_dict(self):
902
+ return self.histogram_dict
903
+
904
+ def collect(self, name_to_arr):
905
+ print("Collecting tensor data and making histogram ...")
906
+
907
+ # TODO: Currently we have different collect() for entropy and percentile method respectively.
908
+ # Need unified collect in the future.
909
+ if self.method in {"distribution", "entropy"}:
910
+ return self.collect_value(name_to_arr)
911
+ elif self.method == "percentile":
912
+ if self.symmetric:
913
+ return self.collect_absolute_value(name_to_arr)
914
+ else:
915
+ return self.collect_value(name_to_arr)
916
+ else:
917
+ raise ValueError("Only 'entropy', 'percentile' or 'distribution' methods are supported")
918
+
919
+ def collect_absolute_value(self, name_to_arr):
920
+ """
921
+ Collect histogram on absolute value
922
+ """
923
+ for tensor, data_arr in name_to_arr.items():
924
+ if isinstance(data_arr, list):
925
+ for arr in data_arr:
926
+ assert isinstance(arr, np.ndarray), f"Unexpected type {type(arr)} for tensor={tensor!r}"
927
+ dtypes = {a.dtype for a in data_arr}
928
+ assert len(dtypes) == 1, (
929
+ f"The calibration expects only one element type but got {dtypes} for tensor={tensor!r}"
930
+ )
931
+ data_arr_np = np.asarray(data_arr)
932
+ elif not isinstance(data_arr, np.ndarray):
933
+ raise ValueError(f"Unexpected type {type(data_arr)} for tensor={tensor!r}")
934
+ else:
935
+ data_arr_np = data_arr
936
+ data_arr_np = data_arr_np.flatten()
937
+ if data_arr_np.size > 0:
938
+ min_value = np.nanmin(data_arr_np)
939
+ max_value = np.nanmax(data_arr_np)
940
+ else:
941
+ min_value = np.array(0, dtype=data_arr_np.dtype)
942
+ max_value = np.array(0, dtype=data_arr_np.dtype)
943
+
944
+ data_arr_np = np.absolute(data_arr_np) # only consider absolute value
945
+
946
+ if tensor not in self.histogram_dict:
947
+ # first time it uses num_bins to compute histogram.
948
+ hist, hist_edges = np.histogram(data_arr_np, bins=self.num_bins)
949
+ hist_edges = hist_edges.astype(data_arr_np.dtype)
950
+ assert data_arr_np.dtype != np.float64, (
951
+ "only float32 or float16 is supported, every constant must be explicitly typed"
952
+ )
953
+ self.histogram_dict[tensor] = (hist, hist_edges, min_value, max_value)
954
+ else:
955
+ old_histogram = self.histogram_dict[tensor]
956
+ old_min = old_histogram[2]
957
+ old_max = old_histogram[3]
958
+ assert hasattr(old_min, "dtype"), f"old_min should be a numpy array but is {type(old_min)}"
959
+ assert hasattr(old_max, "dtype"), f"old_min should be a numpy array but is {type(old_max)}"
960
+ old_hist = old_histogram[0]
961
+ old_hist_edges = old_histogram[1]
962
+ temp_amax = np.nanmax(data_arr_np)
963
+ if temp_amax > old_hist_edges[-1]:
964
+ # increase the number of bins
965
+ width = old_hist_edges[1] - old_hist_edges[0]
966
+ # NOTE: np.arange may create an extra bin after the one containing temp_amax
967
+ new_bin_edges = np.arange(old_hist_edges[-1] + width, temp_amax + width, width)
968
+ old_hist_edges = np.hstack((old_hist_edges, new_bin_edges))
969
+ hist, hist_edges = np.histogram(data_arr_np, bins=old_hist_edges)
970
+ hist_edges = hist_edges.astype(data_arr_np.dtype)
971
+ hist[: len(old_hist)] += old_hist
972
+ assert data_arr_np.dtype != np.float64, (
973
+ "only float32 or float16 is supported, every constant must be explicitly typed"
974
+ )
975
+ self.histogram_dict[tensor] = (hist, hist_edges, min(old_min, min_value), max(old_max, max_value))
976
+
977
+ def collect_value(self, name_to_arr):
978
+ """
979
+ Collect histogram on real value
980
+ """
981
+ for tensor, data_arr in name_to_arr.items():
982
+ data_arr = np.asarray(data_arr) # noqa: PLW2901
983
+ data_arr = data_arr.flatten() # noqa: PLW2901
984
+
985
+ if data_arr.size > 0:
986
+ min_value = np.nanmin(data_arr)
987
+ max_value = np.nanmax(data_arr)
988
+ else:
989
+ min_value = np.array(0, dtype=data_arr.dtype)
990
+ max_value = np.array(0, dtype=data_arr.dtype)
991
+
992
+ threshold = np.array(max(abs(min_value), abs(max_value)), dtype=data_arr.dtype)
993
+
994
+ if tensor in self.histogram_dict:
995
+ old_histogram = self.histogram_dict[tensor]
996
+ self.histogram_dict[tensor] = self.merge_histogram(
997
+ old_histogram, data_arr, min_value, max_value, threshold
998
+ )
999
+ else:
1000
+ hist, hist_edges = np.histogram(data_arr, self.num_bins, range=(-threshold, threshold))
1001
+ self.histogram_dict[tensor] = (
1002
+ hist,
1003
+ hist_edges,
1004
+ min_value,
1005
+ max_value,
1006
+ threshold,
1007
+ )
1008
+
1009
+ def merge_histogram(self, old_histogram, data_arr, new_min, new_max, new_threshold):
1010
+ (old_hist, old_hist_edges, old_min, old_max, old_threshold) = old_histogram
1011
+
1012
+ if new_threshold <= old_threshold:
1013
+ new_hist, _ = np.histogram(data_arr, len(old_hist), range=(-old_threshold, old_threshold))
1014
+ return (
1015
+ new_hist + old_hist,
1016
+ old_hist_edges,
1017
+ min(old_min, new_min),
1018
+ max(old_max, new_max),
1019
+ old_threshold,
1020
+ )
1021
+ else:
1022
+ if old_threshold == 0:
1023
+ hist, hist_edges = np.histogram(data_arr, len(old_hist), range=(-new_threshold, new_threshold))
1024
+ hist += old_hist
1025
+ else:
1026
+ old_num_bins = len(old_hist)
1027
+ old_stride = 2 * old_threshold / old_num_bins
1028
+ half_increased_bins = int((new_threshold - old_threshold) // old_stride + 1)
1029
+ new_num_bins = old_num_bins + 2 * half_increased_bins
1030
+ new_threshold = half_increased_bins * old_stride + old_threshold
1031
+ hist, hist_edges = np.histogram(data_arr, new_num_bins, range=(-new_threshold, new_threshold))
1032
+ hist[half_increased_bins : new_num_bins - half_increased_bins] += old_hist
1033
+ return (
1034
+ hist,
1035
+ hist_edges,
1036
+ min(old_min, new_min),
1037
+ max(old_max, new_max),
1038
+ new_threshold,
1039
+ )
1040
+
1041
+ def compute_collection_result(self):
1042
+ if not self.histogram_dict or len(self.histogram_dict) == 0:
1043
+ raise ValueError("Histogram has not been collected. Please run collect() first.")
1044
+ print(f"Finding optimal threshold for each tensor using {self.method!r} algorithm ...")
1045
+
1046
+ if self.method == "entropy":
1047
+ return self.compute_entropy()
1048
+ elif self.method == "percentile":
1049
+ return self.compute_percentile()
1050
+ elif self.method == "distribution":
1051
+ return self.compute_distribution()
1052
+ else:
1053
+ raise ValueError("Only 'entropy', 'percentile' or 'distribution' methods are supported")
1054
+
1055
+ def compute_percentile(self):
1056
+ if self.percentile < 0 or self.percentile > 100:
1057
+ raise ValueError("Invalid percentile. Must be in range 0 <= percentile <= 100.")
1058
+
1059
+ histogram_dict = self.histogram_dict
1060
+ percentile = self.percentile
1061
+
1062
+ thresholds_dict = {} # per tensor thresholds
1063
+
1064
+ print(f"Number of tensors : {len(histogram_dict)}")
1065
+ print(f"Number of histogram bins : {self.num_bins}")
1066
+ print(f"Percentile : ({100.0 - percentile},{percentile})")
1067
+
1068
+ for tensor, histogram in histogram_dict.items():
1069
+ hist = histogram[0]
1070
+ hist_edges = histogram[1]
1071
+ total = hist.sum()
1072
+ cdf = np.cumsum(hist / total)
1073
+ if self.symmetric:
1074
+ idx_right = np.searchsorted(cdf, percentile / 100.0)
1075
+
1076
+ thresholds_dict[tensor] = (
1077
+ -np.array(hist_edges[idx_right], dtype=hist_edges.dtype),
1078
+ np.array(hist_edges[idx_right], dtype=hist_edges.dtype),
1079
+ )
1080
+ else:
1081
+ percent_to_cut_one_side = (100.0 - percentile) / 200.0
1082
+ idx_right = np.searchsorted(cdf, 1.0 - percent_to_cut_one_side)
1083
+ idx_left = np.searchsorted(cdf, percent_to_cut_one_side)
1084
+ thresholds_dict[tensor] = (
1085
+ np.array(hist_edges[idx_left], dtype=hist_edges.dtype),
1086
+ np.array(hist_edges[idx_right], dtype=hist_edges.dtype),
1087
+ )
1088
+ min_value = histogram[2]
1089
+ max_value = histogram[3]
1090
+ if thresholds_dict[tensor][0] < min_value:
1091
+ thresholds_dict[tensor] = (min_value, thresholds_dict[tensor][1])
1092
+ if thresholds_dict[tensor][1] > max_value:
1093
+ thresholds_dict[tensor] = (thresholds_dict[tensor][0], max_value)
1094
+ thresholds_dict[tensor] = (*thresholds_dict[tensor], *hist[:2])
1095
+ # Plot histogram for debug only
1096
+ if os.environ.get("QUANTIZATION_DEBUG", "0") in (1, "1"):
1097
+ apply_plot(hist, hist_edges)
1098
+
1099
+ return thresholds_dict
1100
+
1101
+ def compute_entropy(self):
1102
+ histogram_dict = self.histogram_dict
1103
+ num_quantized_bins = self.num_quantized_bins
1104
+
1105
+ thresholds_dict = {} # per tensor thresholds
1106
+
1107
+ print(f"Number of tensors : {len(histogram_dict)}")
1108
+ print(f"Number of histogram bins : {self.num_bins} (The number may increase depends on the data it collects)")
1109
+ print(f"Number of quantized bins : {self.num_quantized_bins}")
1110
+
1111
+ for tensor, histogram in histogram_dict.items():
1112
+ optimal_threshold = self.get_entropy_threshold(histogram, num_quantized_bins)
1113
+ thresholds_dict[tensor] = optimal_threshold
1114
+ thresholds_dict[tensor] = (*optimal_threshold, *histogram[:2])
1115
+
1116
+ # Plot histogram for debug only
1117
+ if os.environ.get("QUANTIZATION_DEBUG", "0") in (1, "1"):
1118
+ apply_plot(histogram[0], histogram[1])
1119
+
1120
+ return thresholds_dict
1121
+
1122
+ @staticmethod
1123
+ def _avg_std(hist, hist_edges, power=1):
1124
+ if power <= 0:
1125
+ raise ValueError(f"power={power} <= 0 is invalid.")
1126
+ values = (hist_edges[:-1] + hist_edges[1:]) * 0.5
1127
+ if power == 1:
1128
+ avg = (hist * values).sum() / hist.sum()
1129
+ std = ((hist * values**2).sum() / hist.sum() - avg**2) ** 0.5
1130
+ return np.array(avg, dtype=hist_edges.dtype), np.array(std, dtype=hist_edges.dtype)
1131
+ if int(power) == power and int(power) % 2 == 1:
1132
+ avg = (hist * values**power).sum() / hist.sum()
1133
+ std = ((hist * (values**power - avg) ** 2).sum() / hist.sum()) ** 0.5
1134
+ return np.array(avg, dtype=hist_edges.dtype), np.array(std, dtype=hist_edges.dtype)
1135
+
1136
+ fact = np.abs(values) / values
1137
+ fact[np.isnan(fact)] = 1
1138
+ fact[np.isinf(fact)] = 1
1139
+ values = np.abs(values) ** power * fact
1140
+ avg = (hist * values).sum() / hist.sum()
1141
+ std = ((hist * values**2).sum() / hist.sum() - avg**2) ** 0.5
1142
+ return np.array(avg, dtype=hist_edges.dtype), np.array(std, dtype=hist_edges.dtype)
1143
+
1144
+ def compute_distribution(self):
1145
+ if self.num_bins < 512:
1146
+ raise ValueError("Invalid num_bins. Must be in range 512 <= num_bins.")
1147
+
1148
+ histogram_dict = self.histogram_dict
1149
+ thresholds_dict = {} # per tensor thresholds
1150
+
1151
+ print(f"Number of tensors : {len(histogram_dict)}")
1152
+ print(f"Number of histogram bins : {self.num_bins}")
1153
+ print(f"Scenario : {self.scenario!r})")
1154
+
1155
+ for tensor, histogram in histogram_dict.items():
1156
+ hist = histogram[0]
1157
+ hist_edges = histogram[1]
1158
+
1159
+ assert hist_edges.dtype != np.float64
1160
+ if self.scenario == "same":
1161
+ avg_coef, std_coef = self._avg_std(hist, hist_edges, power=1)
1162
+ elif self.scenario == "p3":
1163
+ avg_coef, std_coef = self._avg_std(hist, hist_edges, power=1.0 / 3.0)
1164
+ else:
1165
+ raise ValueError("Invalid scenario. Must be in {'same', 'p3'}.")
1166
+ assert avg_coef.dtype != np.float64
1167
+ assert std_coef.dtype != np.float64
1168
+ assert hist_edges.dtype != np.float64
1169
+ thresholds_dict[tensor] = TensorData(
1170
+ avg=avg_coef,
1171
+ std=std_coef,
1172
+ hist=hist,
1173
+ hist_edges=hist_edges,
1174
+ lowest=hist_edges.min(),
1175
+ highest=hist_edges.max(),
1176
+ )
1177
+
1178
+ # Plot histogram for debug only
1179
+ if os.environ.get("QUANTIZATION_DEBUG", "0") in (1, "1"):
1180
+ apply_plot(hist, hist_edges)
1181
+
1182
+ return thresholds_dict
1183
+
1184
+ def get_entropy_threshold(self, histogram, num_quantized_bins):
1185
+ """Given a dataset, find the optimal threshold for quantizing it.
1186
+ The reference distribution is `q`, and the candidate distribution is `p`.
1187
+ `q` is a truncated version of the original distribution.
1188
+ Ref: http://on-demand.gputechconf.com/gtc/2017/presentation/s7310-8-bit-inference-with-tensorrt.pdf
1189
+ """
1190
+ hist = histogram[0]
1191
+ hist_edges = histogram[1]
1192
+ num_bins = hist.size
1193
+ zero_bin_index = num_bins // 2
1194
+ num_half_quantized_bin = num_quantized_bins // 2
1195
+
1196
+ dtype = histogram[1].dtype
1197
+ kl_divergence = np.zeros(zero_bin_index - num_half_quantized_bin + 1)
1198
+ thresholds = [(np.array(0, dtype=dtype), np.array(0, dtype=dtype)) for i in range(kl_divergence.size)]
1199
+
1200
+ # <------------ num bins ---------------->
1201
+ # <--- quantized bins ---->
1202
+ # |======|===========|===========|=======|
1203
+ # zero bin index
1204
+ # ^ ^
1205
+ # | |
1206
+ # start index end index (start of iteration)
1207
+ # ^ ^
1208
+ # | |
1209
+ # start index end index ...
1210
+ # ^ ^
1211
+ # | |
1212
+ # start index end index (end of iteration)
1213
+
1214
+ for i in range(num_half_quantized_bin, zero_bin_index + 1, 1):
1215
+ start_index = zero_bin_index - i
1216
+ end_index = min(zero_bin_index + i + 1, num_bins)
1217
+
1218
+ thresholds[i - num_half_quantized_bin] = (hist_edges[start_index], hist_edges[end_index])
1219
+
1220
+ sliced_distribution = copy.deepcopy(hist[start_index:end_index])
1221
+
1222
+ # reference distribution p
1223
+ p = sliced_distribution.copy() # a copy of np array
1224
+ left_outliers_count = sum(hist[:start_index])
1225
+ right_outliers_count = sum(hist[end_index:])
1226
+ p[0] += left_outliers_count
1227
+ p[-1] += right_outliers_count
1228
+
1229
+ # nonzeros[i] incidates whether p[i] is non-zero
1230
+ nonzeros = (p != 0).astype(np.int64)
1231
+
1232
+ # quantize p.size bins into quantized bins (default 128 bins)
1233
+ quantized_bins = np.zeros(num_quantized_bins, dtype=np.int64)
1234
+ num_merged_bins = sliced_distribution.size // num_quantized_bins
1235
+
1236
+ # merge bins into quantized bins
1237
+ for index in range(num_quantized_bins):
1238
+ start = index * num_merged_bins
1239
+ end = start + num_merged_bins
1240
+ quantized_bins[index] = sum(sliced_distribution[start:end])
1241
+ quantized_bins[-1] += sum(sliced_distribution[num_quantized_bins * num_merged_bins :])
1242
+
1243
+ # in order to compare p and q, we need to make length of q equals to length of p
1244
+ # expand quantized bins into p.size bins
1245
+ q = np.zeros(p.size, dtype=np.int64)
1246
+ for index in range(num_quantized_bins):
1247
+ start = index * num_merged_bins
1248
+ end = start + num_merged_bins
1249
+
1250
+ norm = sum(nonzeros[start:end])
1251
+ if norm != 0:
1252
+ q[start:end] = quantized_bins[index] / norm
1253
+
1254
+ p = smooth_distribution(p)
1255
+ q = smooth_distribution(q)
1256
+ if p is None or q is None:
1257
+ div = np.array(np.inf, dtype=dtype)
1258
+ else:
1259
+ div = np.array(entropy(p, q), dtype=dtype)
1260
+ kl_divergence[i - num_half_quantized_bin] = div
1261
+
1262
+ min_kl_divergence_idx = np.argmin(kl_divergence)
1263
+ optimal_threshold = thresholds[min_kl_divergence_idx]
1264
+ min_value = histogram[2]
1265
+ max_value = histogram[3]
1266
+ if optimal_threshold[0] < min_value:
1267
+ optimal_threshold = (min_value, optimal_threshold[1])
1268
+ if optimal_threshold[1] > max_value:
1269
+ optimal_threshold = (optimal_threshold[0], max_value)
1270
+ assert hasattr(optimal_threshold[0], "dtype")
1271
+ assert hasattr(optimal_threshold[1], "dtype")
1272
+ return optimal_threshold
1273
+
1274
+
1275
+ def create_calibrator(
1276
+ model: str | Path,
1277
+ op_types_to_calibrate: Sequence[str] | None = None,
1278
+ augmented_model_path="augmented_model.onnx",
1279
+ calibrate_method=CalibrationMethod.MinMax,
1280
+ use_external_data_format=False,
1281
+ providers=None,
1282
+ extra_options={}, # noqa: B006
1283
+ ):
1284
+ calibrator = None
1285
+ if calibrate_method == CalibrationMethod.MinMax:
1286
+ # default settings for min-max algorithm
1287
+ symmetric = extra_options.get("symmetric", False)
1288
+ moving_average = extra_options.get("moving_average", False)
1289
+ averaging_constant = extra_options.get("averaging_constant", 0.01)
1290
+ max_intermediate_outputs = extra_options.get("max_intermediate_outputs", None)
1291
+ per_channel = extra_options.get("per_channel", False)
1292
+ calibrator = MinMaxCalibrater(
1293
+ model,
1294
+ op_types_to_calibrate,
1295
+ augmented_model_path,
1296
+ use_external_data_format=use_external_data_format,
1297
+ symmetric=symmetric,
1298
+ moving_average=moving_average,
1299
+ averaging_constant=averaging_constant,
1300
+ max_intermediate_outputs=max_intermediate_outputs,
1301
+ per_channel=per_channel,
1302
+ )
1303
+ elif calibrate_method == CalibrationMethod.Entropy:
1304
+ # default settings for entropy algorithm
1305
+ num_bins = extra_options.get("num_bins", 128)
1306
+ num_quantized_bins = extra_options.get("num_quantized_bins", 128)
1307
+ symmetric = extra_options.get("symmetric", False)
1308
+ calibrator = EntropyCalibrater(
1309
+ model,
1310
+ op_types_to_calibrate,
1311
+ augmented_model_path,
1312
+ use_external_data_format=use_external_data_format,
1313
+ symmetric=symmetric,
1314
+ num_bins=num_bins,
1315
+ num_quantized_bins=num_quantized_bins,
1316
+ )
1317
+ elif calibrate_method == CalibrationMethod.Percentile:
1318
+ # default settings for percentile algorithm
1319
+ num_bins = extra_options.get("num_bins", 2048)
1320
+ percentile = extra_options.get("percentile", 99.999)
1321
+ symmetric = extra_options.get("symmetric", True)
1322
+ calibrator = PercentileCalibrater(
1323
+ model,
1324
+ op_types_to_calibrate,
1325
+ augmented_model_path,
1326
+ use_external_data_format=use_external_data_format,
1327
+ symmetric=symmetric,
1328
+ num_bins=num_bins,
1329
+ percentile=percentile,
1330
+ )
1331
+
1332
+ elif calibrate_method == CalibrationMethod.Distribution:
1333
+ # default settings for percentile algorithm
1334
+ num_bins = extra_options.get("num_bins", 2048)
1335
+ scenario = extra_options.get("scenario", "same")
1336
+
1337
+ calibrator = DistributionCalibrater(
1338
+ model,
1339
+ op_types_to_calibrate,
1340
+ augmented_model_path,
1341
+ use_external_data_format=use_external_data_format,
1342
+ num_bins=num_bins,
1343
+ scenario=scenario,
1344
+ )
1345
+
1346
+ if calibrator:
1347
+ calibrator.augment_graph()
1348
+ if providers:
1349
+ calibrator.execution_providers = providers
1350
+ calibrator.create_inference_session()
1351
+ return calibrator
1352
+
1353
+ raise ValueError(f"Unsupported calibration method {calibrate_method}")
ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/quantization/cuda_quantizer.py ADDED
@@ -0,0 +1,643 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -------------------------------------------------------------------------
2
+ # Copyright (c) Microsoft Corporation. All rights reserved.
3
+ # Licensed under the MIT License. See License.txt in the project root for
4
+ # license information.
5
+ # --------------------------------------------------------------------------
6
+
7
+ """CUDA weight-only quantization helpers.
8
+
9
+ This module contains small Python utilities for producing the weight layouts
10
+ consumed by CUDA weight-only kernels. The blockwise quantizers wrap the same C++
11
+ pybind entry points used by runtime prepacking, and the mixed-GEMM weight packer
12
+ is a PyTorch reimplementation of the runtime CUDA packing, so tests and model
13
+ builders can generate byte-identical quantized weights. The PyTorch packer runs
14
+ on CUDA when a device is available and falls back to CPU otherwise, which is the
15
+ only option on platforms where the standalone CUDA packer is not built (Windows).
16
+ A GPU-gated parity test validates it against that standalone CUDA packer.
17
+
18
+ Two storage families are exposed:
19
+
20
+ * raw MatMulNBits blockwise storage, laid out by output channel as ``[N, K/pack]``;
21
+ * CUDA mixed-GEMM prepacked storage. MatMulNBits prepacked initializers keep the
22
+ schema shape ``[N, K/block_size, block_size*bits/8]`` and require the node
23
+ attribute ``weight_prepacked=1``. QMoE/CUTLASS callers use the kernel-facing
24
+ shape ``[K, N/pack]``.
25
+
26
+ All public helpers take one logical expert weight matrix with shape ``[N, K]``.
27
+ """
28
+
29
+ from __future__ import annotations
30
+
31
+ import functools
32
+ import logging
33
+ from typing import TYPE_CHECKING
34
+
35
+ import numpy as np
36
+
37
+ _logger = logging.getLogger(__name__)
38
+
39
+ if TYPE_CHECKING:
40
+ import torch
41
+
42
+
43
+ def _get_torch():
44
+ """Import torch lazily so importing onnxruntime.quantization does not require torch."""
45
+ try:
46
+ import torch # noqa: PLC0415
47
+ except ImportError as e:
48
+ raise ImportError("CUDA weight-only quantization requires torch. Please install torch to use it.") from e
49
+
50
+ return torch
51
+
52
+
53
+ def _get_pack_weights_for_cuda_mixed_gemm():
54
+ """Return the standalone CUDA mixed-GEMM weight packer (parity oracle).
55
+
56
+ Production packing uses the PyTorch implementation (``_pack_weights_for_cuda_mixed_gemm``).
57
+ This standalone packer lives in ``onnxruntime.capi.onnxruntime_cuda_quant_preprocess``, a
58
+ separate extension module that links the CUDA runtime (built only on non-Windows CUDA
59
+ builds). It is imported lazily here (never at ``import onnxruntime`` time) and is used by
60
+ the parity test to validate the PyTorch packer byte-for-byte.
61
+ """
62
+ try:
63
+ from onnxruntime.capi import onnxruntime_cuda_quant_preprocess as _cuda_quant # noqa: PLC0415
64
+ except ImportError as e:
65
+ raise ImportError(
66
+ "The standalone CUDA weight packer (onnxruntime_cuda_quant_preprocess) is unavailable; "
67
+ "it is built only on non-Windows onnxruntime-gpu CUDA builds."
68
+ ) from e
69
+
70
+ try:
71
+ return _cuda_quant.pack_weights_for_cuda_mixed_gemm
72
+ except AttributeError as e:
73
+ raise ImportError("onnxruntime_cuda_quant_preprocess is missing pack_weights_for_cuda_mixed_gemm.") from e
74
+
75
+
76
+ def has_cuda_weight_prepacking() -> bool:
77
+ """Return True if mixed-GEMM weight prepacking is available.
78
+
79
+ Prepacking is implemented with PyTorch (CUDA when available, CPU otherwise), so it is
80
+ available whenever torch is importable. Callers use this to skip prepack code paths
81
+ (and tests) when torch is unavailable.
82
+ """
83
+ try:
84
+ _get_torch()
85
+ except ImportError:
86
+ return False
87
+ return True
88
+
89
+
90
+ @functools.lru_cache(maxsize=1)
91
+ def _warn_cpu_prepack_once() -> None:
92
+ _logger.warning(
93
+ "CUDA device is not available; packing mixed-GEMM weights on CPU with PyTorch. "
94
+ "This is correct but significantly slower for large Mixture-of-Experts models. "
95
+ "Pack on a CUDA-enabled machine for best performance."
96
+ )
97
+
98
+
99
+ def _prepack_device():
100
+ """Pick the torch device for mixed-GEMM weight packing (CUDA if available, else CPU)."""
101
+ torch = _get_torch()
102
+ if torch.cuda.is_available():
103
+ return torch.device("cuda")
104
+ _warn_cpu_prepack_once()
105
+ return torch.device("cpu")
106
+
107
+
108
+ def _preprocess_weights_for_mixed_gemm_torch(tensor, bits: int, sm: int):
109
+ """PyTorch port of the runtime CUDA ``preprocess_weights_for_mixed_gemm``.
110
+
111
+ ``tensor`` is a signed int8 weight in ``(K, N/pack)`` packed row-major layout on any
112
+ device. Returns the CUTLASS mixed-GEMM layout with the same shape/dtype/device. This
113
+ mirrors ``preprocess_weights_for_mixed_gemm_cuda`` (permute_B_rows -> subbyte_transpose
114
+ -> interleave_column_major -> add_bias_and_interleave) so its output is byte-identical
115
+ to the standalone CUDA packer, for both the SM80 (Ampere) and SM90 (Hopper) layouts.
116
+ """
117
+ torch = _get_torch()
118
+ bits_a = 16 # fp16/bf16 activations
119
+ bits_b = 4 if bits == 4 else 8
120
+
121
+ if tensor.dim() == 2:
122
+ tensor = tensor.unsqueeze(0)
123
+
124
+ permutation_map = {
125
+ "16_8": [0, 1, 8, 9, 2, 3, 10, 11, 4, 5, 12, 13, 6, 7, 14, 15],
126
+ "16_4": [
127
+ 0,
128
+ 1,
129
+ 8,
130
+ 9,
131
+ 16,
132
+ 17,
133
+ 24,
134
+ 25,
135
+ 2,
136
+ 3,
137
+ 10,
138
+ 11,
139
+ 18,
140
+ 19,
141
+ 26,
142
+ 27,
143
+ 4,
144
+ 5,
145
+ 12,
146
+ 13,
147
+ 20,
148
+ 21,
149
+ 28,
150
+ 29,
151
+ 6,
152
+ 7,
153
+ 14,
154
+ 15,
155
+ 22,
156
+ 23,
157
+ 30,
158
+ 31,
159
+ ],
160
+ }
161
+ mma_shape_n = 8
162
+ b_rows_per_mma = 8 * 16 // bits_b
163
+
164
+ num_experts, num_rows, num_cols = tensor.shape[0], tensor.shape[1], tensor.shape[2]
165
+ if num_rows % b_rows_per_mma != 0 or num_cols % mma_shape_n != 0:
166
+ raise ValueError(
167
+ f"weight shape (rows={num_rows}, packed_cols={num_cols}) is incompatible with mixed-GEMM "
168
+ f"packing (rows must be a multiple of {b_rows_per_mma}, packed cols a multiple of {mma_shape_n})."
169
+ )
170
+
171
+ # permute_B_rows_for_mixed_gemm
172
+ if sm < 100:
173
+ pmap = permutation_map[f"{bits_a}_{bits_b}"]
174
+ row_idx = [(r // b_rows_per_mma) * b_rows_per_mma + pmap[r % b_rows_per_mma] for r in range(num_rows)]
175
+ tensor = tensor[:, row_idx, :]
176
+
177
+ # subbyte_transpose
178
+ original_shape = tensor.shape
179
+ if bits_b == 4:
180
+ u = tensor.view(torch.uint8)
181
+ high = (u >> 4).permute(0, 2, 1).unsqueeze(2)
182
+ low = ((u << 4) >> 4).permute(0, 2, 1).unsqueeze(2)
183
+ merged = torch.cat([low, high], dim=2).reshape(u.shape[0], -1, u.shape[1])
184
+ merged = merged[:, :, 0::2] + merged[:, :, 1::2] * 16
185
+ tensor = merged.view(torch.int8).reshape(original_shape)
186
+ else:
187
+ tensor = tensor.permute(0, 2, 1).reshape(original_shape)
188
+
189
+ # interleave_column_major_tensor
190
+ interleave = bits_a // bits_b
191
+ if interleave > 1 and sm < 90:
192
+ rows_per_tile = 128 * 8 // bits_a
193
+ elts_in_int32 = 32 // bits_b
194
+ if num_rows % elts_in_int32 != 0 or num_rows % rows_per_tile != 0:
195
+ raise ValueError(f"num_rows ({num_rows}) is incompatible with column-interleave tiling.")
196
+ tensor = tensor.reshape(
197
+ num_experts, -1, interleave, num_rows // rows_per_tile, rows_per_tile * 4 // elts_in_int32
198
+ )
199
+ tensor = tensor.permute(0, 1, 3, 2, 4).reshape(original_shape)
200
+
201
+ # add_bias_and_interleave_quantized_tensor_inplace
202
+ if bits_b == 8:
203
+ t = tensor.to(torch.int64) # widen so the +128 rebias cannot overflow int8
204
+ t += -256 * (t > 127).to(torch.int64) + 128
205
+ t = t.reshape(-1, 4)[:, [0, 2, 1, 3]].reshape(original_shape)
206
+ tensor = t.to(torch.uint8).view(torch.int8)
207
+ else:
208
+ u = tensor.view(torch.uint8)
209
+ high = (u >> 4).unsqueeze(-1)
210
+ low = ((u << 4) >> 4).unsqueeze(-1)
211
+ merged = torch.cat([low, high], dim=-1).reshape(u.shape[0], u.shape[1], -1)
212
+ merged = merged.reshape(-1, 8)[:, [0, 2, 4, 6, 1, 3, 5, 7]].reshape(merged.shape)
213
+ merged = merged.to(torch.int16)
214
+ merged += -16 * (merged > 7).to(torch.int16) + 8
215
+ merged = merged[:, :, 0::2] + merged[:, :, 1::2] * 16
216
+ tensor = merged.to(torch.uint8).view(torch.int8)
217
+
218
+ return tensor.squeeze(0).contiguous()
219
+
220
+
221
+ def _pack_weights_for_cuda_mixed_gemm(q_weights, n: int, k: int, bits: int, force_arch: int = 80) -> np.ndarray:
222
+ """PyTorch implementation of the CUDA ``pack_weights_for_cuda_mixed_gemm``.
223
+
224
+ ``q_weights`` is ORT's unsigned MatMulNBits/QMoE storage ``(N, K/pack)`` (uint8). Returns
225
+ a flat ``int8`` numpy array with the CUTLASS mixed-GEMM layout, byte-identical to the
226
+ standalone CUDA packer. Runs on CUDA when available, otherwise on CPU.
227
+ """
228
+ torch = _get_torch()
229
+ bits = int(bits)
230
+ force_arch = int(force_arch)
231
+ if bits not in (4, 8):
232
+ raise ValueError(f"bits must be 4 or 8, got {bits}.")
233
+ if force_arch not in (80, 90):
234
+ raise ValueError(f"force_arch must be 80 (SM80) or 90 (SM90), got {force_arch}.")
235
+ pack = 8 // bits
236
+ device = _prepack_device()
237
+
238
+ q = torch.as_tensor(np.ascontiguousarray(q_weights)).view(torch.uint8).reshape(n, k // pack).to(device)
239
+
240
+ # Front-end adaptor: transpose ORT (N, K) -> (K, N) and convert unsigned -> signed int8.
241
+ if bits == 4:
242
+ low = (q & 0x0F).to(torch.int16)
243
+ high = (q >> 4).to(torch.int16)
244
+ unpacked = torch.empty((n, k), dtype=torch.int16, device=device)
245
+ unpacked[:, 0::2] = low
246
+ unpacked[:, 1::2] = high
247
+ signed_t = (unpacked - 8).transpose(0, 1).contiguous() # (K, N), zero point 8
248
+ packed_t = ((signed_t[:, 0::2] & 0x0F) | ((signed_t[:, 1::2] & 0x0F) << 4)).to(torch.uint8).view(torch.int8)
249
+ else:
250
+ signed_t = (q.to(torch.int16) - 128).transpose(0, 1).contiguous() # (K, N), zero point 128
251
+ packed_t = signed_t.to(torch.uint8).view(torch.int8)
252
+
253
+ out = _preprocess_weights_for_mixed_gemm_torch(packed_t.contiguous(), bits, force_arch)
254
+ return out.reshape(-1).cpu().numpy()
255
+
256
+
257
+ def _get_quantize_matmul_nbits():
258
+ """Return MatMulNBits blockwise quantizers from the ORT pybind module."""
259
+ try:
260
+ from onnxruntime.capi._pybind_state import ( # noqa: PLC0415
261
+ quantize_matmul_4bits,
262
+ quantize_matmul_8bits,
263
+ )
264
+ except ImportError as e:
265
+ raise ImportError(
266
+ "CUDA blockwise quantization requires quantize_matmul_4bits and quantize_matmul_8bits from onnxruntime."
267
+ ) from e
268
+
269
+ return quantize_matmul_4bits, quantize_matmul_8bits
270
+
271
+
272
+ class CudaQuantizer:
273
+ """CUDA quantizer utilities for MoE/QMoE and MatMulNBits-style weight-only kernels.
274
+
275
+ The methods are stateless; callers may use the class directly without
276
+ constructing an object.
277
+ """
278
+
279
+ @staticmethod
280
+ def qmoe_symmetric_per_channel_quantize(
281
+ weights: torch.Tensor,
282
+ bits: int,
283
+ *,
284
+ unsigned_full_range: bool = True,
285
+ ) -> tuple[torch.Tensor, torch.Tensor]:
286
+ """Quantize one QMoE expert with symmetric per-channel storage.
287
+
288
+ ``weights`` has logical shape ``[N, K]``. Returns raw QMoE storage
289
+ ``[N, K/pack]`` and scales ``[N]``. By default, this emits the ORT CUDA
290
+ QMoE storage contract: unsigned bytes/nibbles with an implicit zero-point
291
+ offset, so each stored value is ``q + zero_point`` even though the numeric
292
+ quantization is symmetric. By default it uses the full ``[-8, 7]`` /
293
+ ``[-128, 127]`` range. Set ``unsigned_full_range=False`` to use the legacy
294
+ ``[-7, 7]`` / ``[-127, 127]`` range.
295
+ """
296
+ torch = _get_torch()
297
+
298
+ weights = weights.detach().cpu().to(torch.float32).contiguous()
299
+ bits = int(bits)
300
+ if bits not in (4, 8):
301
+ raise ValueError(f"QMoE per-channel quantization only supports 4 or 8 bits, got {bits}.")
302
+
303
+ n, k = weights.shape
304
+ pack = 8 // bits
305
+ if k % pack != 0:
306
+ raise ValueError(f"K ({k}) must be divisible by {pack} for QMoE per-channel quantization.")
307
+
308
+ if bits == 4:
309
+ if unsigned_full_range:
310
+ qmin, qmax, scale_divisor, zero_point = -8, 7, 8, 8
311
+ else:
312
+ qmin, qmax, scale_divisor, zero_point = -7, 7, 7, 8
313
+ else: # bits == 8, already validated above
314
+ if unsigned_full_range:
315
+ qmin, qmax, scale_divisor, zero_point = -128, 127, 128, 128
316
+ else:
317
+ qmin, qmax, scale_divisor, zero_point = -127, 127, 127, 128
318
+ scales = weights.abs().amax(dim=1, keepdim=True) / float(scale_divisor)
319
+ scales = torch.clamp(scales, min=torch.finfo(torch.float32).eps)
320
+ quantized = torch.clamp(torch.round(weights / scales), qmin, qmax).to(torch.int16).contiguous()
321
+ quantized = (quantized + zero_point).to(torch.uint8)
322
+
323
+ if bits == 4:
324
+ qweight = (quantized[:, 0::2] & 0xF) | ((quantized[:, 1::2] & 0xF) << 4)
325
+ qweight = qweight.to(torch.uint8)
326
+ else:
327
+ qweight = quantized
328
+
329
+ return qweight.contiguous(), scales.squeeze(-1).contiguous()
330
+
331
+ @staticmethod
332
+ def qmoe_per_channel_quantize(
333
+ weights: torch.Tensor,
334
+ bits: int,
335
+ prepack: bool,
336
+ force_arch: int = 80,
337
+ *,
338
+ unsigned_full_range: bool = True,
339
+ ) -> tuple[torch.Tensor, torch.Tensor]:
340
+ """Quantize per-channel QMoE weights and optionally CUTLASS-prepack them.
341
+
342
+ When ``prepack`` is true, returned weights have shape ``[K, N/pack]``.
343
+ Otherwise, returned weights keep raw per-channel storage ``[N, K/pack]``.
344
+ Prepacking uses PyTorch (CUDA when available, CPU otherwise).
345
+ """
346
+ torch = _get_torch()
347
+
348
+ qweight, scales = CudaQuantizer.qmoe_symmetric_per_channel_quantize(
349
+ weights,
350
+ bits,
351
+ unsigned_full_range=unsigned_full_range,
352
+ )
353
+ if not prepack:
354
+ return qweight, scales
355
+
356
+ n, k = weights.shape
357
+ pack = 8 // int(bits)
358
+ if n % pack != 0:
359
+ raise ValueError(f"N ({n}) must be divisible by {pack} for CUDA QMoE prepacked weights.")
360
+
361
+ packed = _pack_weights_for_cuda_mixed_gemm(qweight.numpy(), n, k, int(bits), force_arch)
362
+ packed = np.asarray(packed).view(np.uint8).reshape(k, n // pack)
363
+ return torch.from_numpy(np.ascontiguousarray(packed)), scales
364
+
365
+ @staticmethod
366
+ def _matmulnbits_blockwise_quantize_impl(
367
+ weights: torch.Tensor,
368
+ bits: int,
369
+ block_size: int,
370
+ *,
371
+ symmetric: bool,
372
+ abs_scales: bool,
373
+ unsigned_full_range: bool,
374
+ ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
375
+ """Quantize ``weights`` with MatMulNBits pybinds and return unflattened storage."""
376
+ torch = _get_torch()
377
+
378
+ bits = int(bits)
379
+ block_size = int(block_size)
380
+ w = weights.detach().cpu().to(torch.float32).contiguous().numpy()
381
+ n, k = w.shape
382
+ if bits not in (4, 8):
383
+ raise ValueError(f"Blockwise quantization only supports 4 or 8 bits, got {bits}.")
384
+ if block_size <= 0:
385
+ raise ValueError(f"Blockwise quantization requires a positive block_size, got {block_size}.")
386
+
387
+ num_blocks = (k + block_size - 1) // block_size
388
+ pack = 8 // bits
389
+ blob_size = (block_size + pack - 1) // pack
390
+
391
+ if symmetric:
392
+ if bits == 4:
393
+ qmin, qmax, scale_divisor, zero_point = (-8, 7, 8, 8) if unsigned_full_range else (-7, 7, 7, 8)
394
+ else:
395
+ qmin, qmax, scale_divisor, zero_point = (
396
+ (-128, 127, 128, 128) if unsigned_full_range else (-127, 127, 127, 128)
397
+ )
398
+
399
+ padded_k = num_blocks * block_size
400
+ if padded_k != k:
401
+ w = np.pad(w, ((0, 0), (0, padded_k - k)), "constant")
402
+
403
+ blocked = w.reshape(n, num_blocks, block_size)
404
+ scales = np.max(np.abs(blocked), axis=2).astype(np.float32) / np.float32(scale_divisor)
405
+ scales = np.maximum(scales, np.finfo(np.float32).eps)
406
+ quantized = np.clip(np.rint(blocked / scales[:, :, np.newaxis]), qmin, qmax).astype(np.int16)
407
+ quantized = (quantized + zero_point).astype(np.uint8)
408
+
409
+ if bits == 4:
410
+ qweight = np.zeros((n, num_blocks, blob_size), dtype=np.uint8)
411
+ qweight[:, :, : quantized[:, :, 0::2].shape[2]] = quantized[:, :, 0::2] & 0xF
412
+ qweight[:, :, : quantized[:, :, 1::2].shape[2]] |= (quantized[:, :, 1::2] & 0xF) << 4
413
+ else:
414
+ qweight = quantized
415
+
416
+ zero_points = np.zeros((n, (num_blocks + 1) // 2 if bits == 4 else num_blocks), dtype=np.uint8)
417
+ return torch.from_numpy(qweight), torch.from_numpy(scales), torch.from_numpy(zero_points)
418
+
419
+ w_t = np.ascontiguousarray(w.T)
420
+ qweight = np.zeros((n, num_blocks, blob_size), dtype=np.uint8)
421
+ scales = np.zeros((n, num_blocks), dtype=np.float32)
422
+ zero_points = np.zeros((n, (num_blocks + 1) // 2 if bits == 4 else num_blocks), dtype=np.uint8)
423
+
424
+ quantize_matmul_4bits, quantize_matmul_8bits = _get_quantize_matmul_nbits()
425
+ quantize = quantize_matmul_4bits if bits == 4 else quantize_matmul_8bits
426
+ quantize(qweight, w_t, scales, zero_points, block_size, n, k, symmetric)
427
+
428
+ if abs_scales:
429
+ scales = np.abs(scales)
430
+
431
+ return torch.from_numpy(qweight), torch.from_numpy(scales), torch.from_numpy(zero_points)
432
+
433
+ @staticmethod
434
+ def matmulnbits_blockwise_quantize(
435
+ weights: torch.Tensor,
436
+ bits: int,
437
+ block_size: int,
438
+ *,
439
+ symmetric: bool = True,
440
+ return_zero_points: bool = False,
441
+ abs_scales: bool = True,
442
+ flatten_qweight: bool = True,
443
+ unsigned_full_range: bool = True,
444
+ ) -> tuple[torch.Tensor, torch.Tensor] | tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
445
+ """Quantize one expert with ONNX Runtime's MatMulNBits blockwise encoding.
446
+
447
+ ``weights`` has logical shape ``[N, K]``. Returns raw flattened storage
448
+ ``[N, ceil(K/block_size)*ceil(block_size/pack)]`` and block scales
449
+ ``[N, ceil(K/block_size)]`` by default. Set ``flatten_qweight=False`` for
450
+ the MatMulNBits initializer shape
451
+ ``[N, ceil(K/block_size), ceil(block_size/pack)]``.
452
+ Set ``return_zero_points=True`` to also return packed block zero-points.
453
+ Symmetric quantization uses the full ``[-8, 7]`` / ``[-128, 127]`` range
454
+ by default. Set ``unsigned_full_range=False`` to use the legacy
455
+ ``[-7, 7]`` / ``[-127, 127]`` range.
456
+ """
457
+ qweight, scales, zero_points = CudaQuantizer._matmulnbits_blockwise_quantize_impl(
458
+ weights,
459
+ bits,
460
+ block_size,
461
+ symmetric=symmetric,
462
+ abs_scales=abs_scales,
463
+ unsigned_full_range=unsigned_full_range,
464
+ )
465
+ if flatten_qweight:
466
+ qweight = qweight.reshape(qweight.shape[0], -1).contiguous()
467
+ if return_zero_points:
468
+ return qweight, scales, zero_points
469
+
470
+ return qweight, scales
471
+
472
+ @staticmethod
473
+ def matmulnbits_prepacked_blockwise_quantize(
474
+ weights: torch.Tensor,
475
+ bits: int,
476
+ block_size: int,
477
+ force_arch: int = 80,
478
+ *,
479
+ symmetric: bool = True,
480
+ return_zero_points: bool = False,
481
+ abs_scales: bool = True,
482
+ unsigned_full_range: bool = True,
483
+ ) -> tuple[torch.Tensor, torch.Tensor] | tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
484
+ """Quantize and CUDA-prepack one MatMulNBits weight initializer.
485
+
486
+ ``weights`` has logical shape ``[N, K]``. Returns ``B`` with the standard
487
+ MatMulNBits initializer shape ``[N, K/block_size, block_size*bits/8]``
488
+ and scales with shape ``[N, K/block_size]``.
489
+
490
+ The ``force_arch`` value selects the mixed-GEMM weight layout and must match
491
+ the ``weight_prepacked`` attribute set on the MatMulNBits node:
492
+
493
+ * ``force_arch=80`` (default): SM80/Ampere layout, consumed by the SM80 kernel
494
+ (also used on newer GPUs via the compatibility path). Use ``weight_prepacked=1``.
495
+ * ``force_arch=90``: SM90/Hopper layout, consumed by the native SM90 TMA/WGMMA
496
+ kernel. Use ``weight_prepacked=2``. Requires ``block_size`` in {64, 128}.
497
+ """
498
+ torch = _get_torch()
499
+
500
+ bits = int(bits)
501
+ block_size = int(block_size)
502
+ force_arch = int(force_arch)
503
+ if force_arch not in (80, 90):
504
+ raise ValueError(f"force_arch must be 80 (SM80) or 90 (SM90), but got {force_arch}.")
505
+ # The native SM90 kernel needs group_size to be a multiple of the 64-element Hopper K tile,
506
+ # so block_size=32 is only supported by the SM80/Ampere-class kernel.
507
+ allowed_block_sizes = (32, 64, 128) if force_arch == 80 else (64, 128)
508
+ if block_size not in allowed_block_sizes:
509
+ raise ValueError(
510
+ f"block_size must be one of {allowed_block_sizes} for force_arch={force_arch}, but got {block_size}."
511
+ )
512
+ n, k = weights.shape
513
+ if k % block_size != 0:
514
+ raise ValueError(f"K ({k}) must be divisible by block_size ({block_size}) for CUDA-prepacked weights.")
515
+
516
+ qweight, scales, zero_points = CudaQuantizer._matmulnbits_blockwise_quantize_impl(
517
+ weights,
518
+ bits,
519
+ block_size,
520
+ symmetric=symmetric,
521
+ abs_scales=abs_scales,
522
+ unsigned_full_range=unsigned_full_range,
523
+ )
524
+
525
+ pack_weights_for_cuda_mixed_gemm = _pack_weights_for_cuda_mixed_gemm
526
+ packed = pack_weights_for_cuda_mixed_gemm(qweight.reshape(n, -1).numpy(), n, k, bits, force_arch)
527
+ packed = np.asarray(packed).view(np.uint8).reshape(qweight.shape)
528
+ packed = torch.from_numpy(np.ascontiguousarray(packed))
529
+ if return_zero_points:
530
+ return packed, scales, zero_points
531
+
532
+ return packed, scales
533
+
534
+ @staticmethod
535
+ def qmoe_prepacked_blockwise_quantize(
536
+ weights: torch.Tensor,
537
+ bits: int,
538
+ block_size: int,
539
+ force_arch: int = 80,
540
+ *,
541
+ symmetric: bool = True,
542
+ return_zero_points: bool = False,
543
+ abs_scales: bool = False,
544
+ unsigned_full_range: bool = True,
545
+ ) -> tuple[torch.Tensor, torch.Tensor] | tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
546
+ """Quantize one expert and CUTLASS-prepack it for CUDA QMoE fpA_intB GEMM.
547
+
548
+ ``weights`` has logical shape ``[N, K]``. Returns ``qweight`` with shape
549
+ ``[K, N/pack]`` and block scales with shape ``[N, K/block_size]``.
550
+ Set ``return_zero_points=True`` to also return packed block zero-points.
551
+ """
552
+ bits = int(bits)
553
+ block_size = int(block_size)
554
+ n, k = weights.shape
555
+ pack = 8 // bits
556
+ if k % block_size != 0:
557
+ raise ValueError(f"K ({k}) must be divisible by block_size ({block_size}) for CUDA-prepacked weights.")
558
+ if n % pack != 0:
559
+ raise ValueError(f"N ({n}) must be divisible by {pack} for QMoE blockwise quantization.")
560
+
561
+ qweight, scales, zero_points = CudaQuantizer._matmulnbits_blockwise_quantize_impl(
562
+ weights,
563
+ bits,
564
+ block_size,
565
+ symmetric=symmetric,
566
+ abs_scales=abs_scales,
567
+ unsigned_full_range=unsigned_full_range,
568
+ )
569
+
570
+ pack_weights_for_cuda_mixed_gemm = _pack_weights_for_cuda_mixed_gemm
571
+ packed = pack_weights_for_cuda_mixed_gemm(qweight.reshape(n, -1).numpy(), n, k, bits, force_arch)
572
+ packed = np.asarray(packed).view(np.uint8).reshape(k, n // pack)
573
+ torch = _get_torch()
574
+ packed = torch.from_numpy(np.ascontiguousarray(packed))
575
+ if return_zero_points:
576
+ return packed, scales, zero_points
577
+
578
+ return packed, scales
579
+
580
+ @staticmethod
581
+ def symmetric_blockwise_quantize(
582
+ weights: torch.Tensor,
583
+ bits: int,
584
+ block_size: int,
585
+ *,
586
+ unsigned_full_range: bool = True,
587
+ ) -> tuple[torch.Tensor, torch.Tensor]:
588
+ """Quantize one expert with a pure-PyTorch symmetric blockwise encoding.
589
+
590
+ This helper is useful for non-CUDA reference paths. Unlike the pybind-backed
591
+ helpers above, it pads the last dimension when it is not divisible by
592
+ ``block_size`` and returns storage with the same leading shape as ``weights``.
593
+ """
594
+ torch = _get_torch()
595
+
596
+ weights = weights.detach().cpu().contiguous()
597
+ original_shape = weights.shape
598
+ bits = int(bits)
599
+ block_size = int(block_size)
600
+ if bits == 4:
601
+ qmin, qmax, scale_divisor = (-8, 7, 8) if unsigned_full_range else (-7, 7, 7)
602
+ elif bits == 8:
603
+ qmin, qmax, scale_divisor = (-128, 127, 128) if unsigned_full_range else (-127, 127, 127)
604
+ else:
605
+ raise ValueError(f"CUDA blockwise quantization only supports 4 or 8 bits, got {bits}.")
606
+
607
+ last_dim = original_shape[-1]
608
+ num_blocks = (last_dim + block_size - 1) // block_size
609
+ pad_size = num_blocks * block_size - last_dim
610
+ if pad_size > 0:
611
+ pad_shape = list(original_shape)
612
+ pad_shape[-1] = pad_size
613
+ padding = torch.zeros(pad_shape, dtype=weights.dtype, device=weights.device)
614
+ weights_padded = torch.cat([weights, padding], dim=-1)
615
+ else:
616
+ weights_padded = weights
617
+
618
+ reshaped_weights = weights_padded.view(*original_shape[:-1], num_blocks, block_size)
619
+ block_max_abs = torch.max(torch.abs(reshaped_weights), dim=-1)[0]
620
+ scales = torch.clamp(block_max_abs / scale_divisor, min=1e-8)
621
+
622
+ quantized = torch.round(reshaped_weights / scales.unsqueeze(-1))
623
+ quantized = torch.clamp(quantized, qmin, qmax)
624
+
625
+ if bits == 4:
626
+ quantized_flat = quantized.to(torch.int8).view(*original_shape[:-1], num_blocks * block_size)
627
+ if pad_size > 0:
628
+ quantized_flat = quantized_flat[..., :-pad_size]
629
+
630
+ quantized_uint4 = (quantized_flat + 8).to(torch.uint8)
631
+ packed_shape = list(original_shape)
632
+ packed_shape[-1] = (original_shape[-1] + 1) // 2
633
+ qweight = torch.zeros(packed_shape, dtype=torch.uint8, device=weights.device)
634
+ qweight[..., :] = quantized_uint4[..., 0::2] & 0xF
635
+ if quantized_uint4.shape[-1] > 1:
636
+ qweight[..., : quantized_uint4[..., 1::2].shape[-1]] |= (quantized_uint4[..., 1::2] & 0xF) << 4
637
+ else:
638
+ qweight = quantized.to(torch.int8).view(*original_shape[:-1], num_blocks * block_size)
639
+ if pad_size > 0:
640
+ qweight = qweight[..., :-pad_size]
641
+ qweight = qweight.view(original_shape)
642
+
643
+ return qweight.cpu(), scales.cpu()
ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/quantization/execution_providers/qnn/__init__.py ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ from .preprocess import qnn_preprocess_model # noqa: F401
2
+ from .quant_config import get_qnn_qdq_config # noqa: F401
ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/quantization/execution_providers/qnn/fusion_lpnorm.py ADDED
@@ -0,0 +1,132 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -------------------------------------------------------------------------
2
+ # Copyright (c) Microsoft Corporation. All rights reserved.
3
+ # Licensed under the MIT License. See License.txt in the project root for
4
+ # license information.
5
+ # --------------------------------------------------------------------------
6
+ from __future__ import annotations
7
+
8
+ import onnx
9
+
10
+ from ...fusions import Fusion
11
+ from ...onnx_model import ONNXModel
12
+
13
+
14
+ class FusionLpNormalization(Fusion):
15
+ def __init__(self, model: ONNXModel, epsilon: float = 1e-12):
16
+ super().__init__(model, "LpNormalization", "ReduceL2")
17
+ self.epsilon = epsilon
18
+
19
+ def fuse(
20
+ self,
21
+ reduce_node: onnx.NodeProto,
22
+ input_name_to_nodes: dict[str, list[onnx.NodeProto]],
23
+ output_name_to_node: dict[str, onnx.NodeProto],
24
+ ):
25
+ """
26
+ Interface function that tries to fuse a node sequence containing a ReduceL2 node into a single
27
+ LpNormalization node.
28
+
29
+ Pattern 1:
30
+ [root] --> ReduceL2 -----> Clip --> Expand ----> Div -->
31
+ | (axis=-1) (min=epsilon) (shape=root) ^
32
+ | (keepdims=True) |
33
+ | |
34
+ +-----------------------------------------------+
35
+ Notes:
36
+ - ReduceL2 must use the last axis, and keepdims == True
37
+ - Clip must only have a min attribute that is ~1e-12
38
+ - Expand must restore the shape to root.shape
39
+ - The output of Expand must be the second input to Div.
40
+ """
41
+ if reduce_node.output[0] not in input_name_to_nodes:
42
+ return
43
+
44
+ # ReduceL2 must have one Clip child
45
+ children = input_name_to_nodes[reduce_node.output[0]]
46
+ if len(children) != 1 or children[0].op_type != "Clip":
47
+ return
48
+
49
+ # ReduceL2 must have keepdims == True
50
+ keepdims = self.get_node_attribute(reduce_node, "keepdims")
51
+ if not keepdims:
52
+ return
53
+
54
+ # ReduceL2 axes must refer only to the last dimension.
55
+ # Axes became an input in opset 18. Before then, axes was an attribute
56
+ reduce_input_ttype = self.model.get_tensor_type(reduce_node.input[0])
57
+ if not reduce_input_ttype:
58
+ return
59
+
60
+ reduce_input_shape = self.tensor_shape_to_list(reduce_input_ttype)
61
+ if not reduce_input_shape:
62
+ return
63
+
64
+ axes = self.get_node_attribute(reduce_node, "axes")
65
+ if not axes and len(reduce_node.input) > 1:
66
+ axes = self.model.get_constant_value(reduce_node.input[1])
67
+
68
+ if not axes or len(axes) != 1:
69
+ return
70
+
71
+ last_dim = len(reduce_input_shape) - 1
72
+ if axes[0] != -1 and axes[0] != last_dim:
73
+ return
74
+
75
+ # Clip node must have a min attribute approximately equal to 1e-12
76
+ clip_node = children[0]
77
+ clip_min = self.get_node_attribute(clip_node, "min")
78
+ if clip_min is None and len(clip_node.input) > 1:
79
+ clip_min = self.model.get_constant_value(clip_node.input[1])
80
+
81
+ clip_max = self.get_node_attribute(clip_node, "max") # TODO: clip_max could be FLOAT_MAX
82
+ if clip_max is None and len(clip_node.input) > 2:
83
+ clip_max = self.model.get_constant_value(clip_node.input[2])
84
+
85
+ if not (clip_max is None and clip_min is not None and clip_min > 0 and abs(clip_min - self.epsilon) < 1e-13):
86
+ return
87
+
88
+ if clip_node.output[0] not in input_name_to_nodes:
89
+ return
90
+
91
+ # Clip must have a single Expand child.
92
+ children = input_name_to_nodes[clip_node.output[0]]
93
+ if len(children) != 1 or children[0].op_type != "Expand":
94
+ return
95
+
96
+ expand_node = children[0]
97
+ if expand_node.output[0] not in input_name_to_nodes:
98
+ return
99
+
100
+ # Expand must have a single Div child
101
+ children = input_name_to_nodes[expand_node.output[0]]
102
+ if len(children) != 1 or children[0].op_type != "Div":
103
+ return
104
+
105
+ div_node = children[0]
106
+
107
+ # The first input to Div must be the root of the subgraph (i.e., reduce_node.input[0])
108
+ # The second input to Div must be the output of the Expand.
109
+ # As long as these two inputs go to the same Div node, then ONNX validation will ensure that
110
+ # their shapes match.
111
+ if div_node.input[0] != reduce_node.input[0]:
112
+ return
113
+ if div_node.input[1] != expand_node.output[0]:
114
+ return
115
+
116
+ subgraph_input = reduce_node.input[0]
117
+ subgraph_output = div_node.output[0]
118
+
119
+ subgraph_nodes = [reduce_node, clip_node, expand_node, div_node]
120
+ if not self.is_safe_to_fuse_nodes(subgraph_nodes, [subgraph_output], input_name_to_nodes, output_name_to_node):
121
+ return
122
+
123
+ self.nodes_to_remove.extend(subgraph_nodes)
124
+ fused_node = onnx.helper.make_node(
125
+ self.fused_op_type,
126
+ name=self.create_unique_node_name(),
127
+ inputs=[subgraph_input],
128
+ outputs=[subgraph_output],
129
+ p=2,
130
+ axis=-1,
131
+ )
132
+ self.nodes_to_add.append(fused_node)
ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/quantization/execution_providers/qnn/fusion_spacetodepth.py ADDED
@@ -0,0 +1,162 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -------------------------------------------------------------------------
2
+ # Copyright (c) Microsoft Corporation. All rights reserved.
3
+ # Licensed under the MIT License. See License.txt in the project root for
4
+ # license information.
5
+ # --------------------------------------------------------------------------
6
+ """Define SpaceToDepth fusion."""
7
+
8
+ import onnx
9
+
10
+ from ... import fusions, onnx_model
11
+
12
+
13
+ class FusionSpaceToDepth(fusions.Fusion):
14
+ """Fusion for SpaceToDepth."""
15
+
16
+ def __init__(self, model: onnx_model.ONNXModel):
17
+ """Initialize.
18
+
19
+ Args:
20
+ model: An onnx_model.ONNXModel instance.
21
+ """
22
+ super().__init__(model, "SpaceToDepth", "Reshape")
23
+
24
+ def _fuse_yolo(
25
+ self,
26
+ node: onnx.NodeProto,
27
+ input_name_to_nodes: dict[str, list[onnx.NodeProto]],
28
+ output_name_to_node: dict[str, onnx.NodeProto],
29
+ ):
30
+ """Fuse for early version of YOLO.
31
+
32
+ Pattern:
33
+
34
+ | [N, C, H, W]
35
+ Reshape
36
+ | [N, C, H/blk, blk, W/blk, blk]
37
+ Transpose
38
+ | [N, C, H/blk, W/blk, blk, blk]
39
+ Reshape
40
+ | [N, C, H/blk * W/blk, blk * blk]
41
+ Transpose
42
+ | [N, C, blk * blk, H/blk * W/blk]
43
+ Reshape
44
+ | [N, C, blk * blk, H/blk, W/blk]
45
+ Transpose
46
+ | [N, blk * blk, C, H/blk, W/blk]
47
+ Reshape
48
+ | [N, blk * blk * C, H/blk, W/blk]
49
+
50
+ This sequence can be fused into a single SpaceToDepth with blocksize `blk`. Note that unlike DepthToSpace
51
+ supporting DCR or CRD mode, SpaceToDepth only supports DCR mode in its latest opset version (13), which matches
52
+ the pattern here.
53
+ """
54
+ reshape_node1 = node
55
+
56
+ def get_target_child(parent_node, target_op_type):
57
+ """Get target child of given node."""
58
+ if parent_node.output[0] not in input_name_to_nodes:
59
+ return None
60
+
61
+ children = input_name_to_nodes[parent_node.output[0]]
62
+ if len(children) > 1 or children[0].op_type != target_op_type:
63
+ return None
64
+
65
+ return children[0]
66
+
67
+ if (
68
+ (transpose_node1 := get_target_child(reshape_node1, "Transpose")) is None
69
+ or (reshape_node2 := get_target_child(transpose_node1, "Reshape")) is None
70
+ or (transpose_node2 := get_target_child(reshape_node2, "Transpose")) is None
71
+ or (reshape_node3 := get_target_child(transpose_node2, "Reshape")) is None
72
+ or (transpose_node3 := get_target_child(reshape_node3, "Transpose")) is None
73
+ or (reshape_node4 := get_target_child(transpose_node3, "Reshape")) is None
74
+ ):
75
+ return False
76
+
77
+ def get_tensor_shape(tensor_name):
78
+ """Get shape for given tensor name."""
79
+ tensor_type = self.model.get_tensor_type(tensor_name)
80
+ if not tensor_type:
81
+ return None
82
+
83
+ tensor_shape = self.tensor_shape_to_list(tensor_type)
84
+ if not tensor_shape:
85
+ return None
86
+
87
+ return tensor_shape
88
+
89
+ if (
90
+ (input_shape := get_tensor_shape(reshape_node1.input[0])) is None
91
+ or (reshape_shape1 := get_tensor_shape(reshape_node1.output[0])) is None
92
+ or (reshape_shape2 := get_tensor_shape(reshape_node2.output[0])) is None
93
+ or (reshape_shape3 := get_tensor_shape(reshape_node3.output[0])) is None
94
+ or (reshape_shape4 := get_tensor_shape(reshape_node4.output[0])) is None
95
+ ):
96
+ return False
97
+
98
+ transpose_perm1 = self.get_node_attribute(transpose_node1, "perm")
99
+ transpose_perm2 = self.get_node_attribute(transpose_node2, "perm")
100
+ transpose_perm3 = self.get_node_attribute(transpose_node3, "perm")
101
+
102
+ # Check rank.
103
+ if (
104
+ len(input_shape) != 4
105
+ or len(reshape_shape1) != 6
106
+ or len(reshape_shape2) != 4
107
+ or len(reshape_shape3) != 5
108
+ or len(reshape_shape4) != 4
109
+ ):
110
+ return False
111
+
112
+ # Check shape and perm.
113
+ batch, channel, height, width = input_shape
114
+ blocksize = reshape_shape1[3]
115
+ if (
116
+ reshape_shape1 != [batch, channel, height // blocksize, blocksize, width // blocksize, blocksize]
117
+ or transpose_perm1 != [0, 1, 2, 4, 3, 5]
118
+ or reshape_shape2 != [batch, channel, (height // blocksize) * (width // blocksize), blocksize**2]
119
+ or transpose_perm2 != [0, 1, 3, 2]
120
+ or reshape_shape3 != [batch, channel, blocksize**2, height // blocksize, width // blocksize]
121
+ or transpose_perm3 != [0, 2, 1, 3, 4]
122
+ or reshape_shape4 != [batch, blocksize**2 * channel, height // blocksize, width // blocksize]
123
+ ):
124
+ return False
125
+
126
+ self.nodes_to_remove.extend(
127
+ [
128
+ reshape_node1,
129
+ transpose_node1,
130
+ reshape_node2,
131
+ transpose_node2,
132
+ reshape_node3,
133
+ transpose_node3,
134
+ reshape_node4,
135
+ ]
136
+ )
137
+
138
+ s2d_node = onnx.helper.make_node(
139
+ self.fused_op_type,
140
+ name=self.create_unique_node_name(),
141
+ inputs=[reshape_node1.input[0]],
142
+ outputs=[reshape_node4.output[0]],
143
+ blocksize=blocksize,
144
+ )
145
+ self.nodes_to_add.append(s2d_node)
146
+
147
+ return True
148
+
149
+ def fuse(
150
+ self,
151
+ node: onnx.NodeProto,
152
+ input_name_to_nodes: dict[str, list[onnx.NodeProto]],
153
+ output_name_to_node: dict[str, onnx.NodeProto],
154
+ ):
155
+ """Fuse a sequence of Reshape and Transpose nodes into a single SpaceToDepth node.
156
+
157
+ Args:
158
+ node: An onnx.NodeProto matching the specified search type (i.e., Reshape).
159
+ input_name_to_nodes: A dict mapping tensor name to consumed nodes.
160
+ output_name_to_node: A dict mapping tensor name to produced node.
161
+ """
162
+ self._fuse_yolo(node, input_name_to_nodes, output_name_to_node)
ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/quantization/execution_providers/qnn/mixed_precision_overrides_utils.py ADDED
@@ -0,0 +1,413 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -------------------------------------------------------------------------
2
+ # Copyright (c) Microsoft Corporation. All rights reserved.
3
+ # Licensed under the MIT License. See License.txt in the project root for
4
+ # license information.
5
+ # --------------------------------------------------------------------------
6
+ from __future__ import annotations
7
+
8
+ import logging
9
+ from dataclasses import dataclass
10
+
11
+ import onnx
12
+
13
+ from ...quant_utils import QuantType
14
+ from ...tensor_quant_overrides import QuantTypeInfo, TensorQuantOverridesHelper
15
+
16
+
17
+ @dataclass
18
+ class TensorTypeRequest:
19
+ """
20
+ Bundles desired quantization type requests for a tensor. A distinction is made between the
21
+ produced type and the consumed type.
22
+ """
23
+
24
+ # The tensor's quant type at the producer end. If None, assumed to be the default activation quant type.
25
+ producer: QuantTypeInfo | None
26
+
27
+ # The tensor's quant type received by a set of consumer nodes.
28
+ # If None, assumed to be the default activation quant type for all consumers.
29
+ # consumers[1] is a set of consumer node names.
30
+ consumers: tuple[QuantTypeInfo, set[str]] | None
31
+
32
+
33
+ class MixedPrecisionTensorQuantOverridesFixer:
34
+ """
35
+ Helper that generates tensor quantization overrides for mixed-precision QDQ models.
36
+
37
+ Specifically, this helper fixes an initial set of quantization overrides that assign a non-default
38
+ activation quantization type to one or more tensors by doing the following:
39
+ - Inferring which other tensors need to be overridden to the non-default activation quantization type.
40
+ - Inserting quantization data type conversions.
41
+
42
+ Example:
43
+ --------
44
+
45
+ Float model:
46
+
47
+ input_0 --> Op1 --> Op3 --> Op5 --> Op6 --> output_0
48
+ ^
49
+ |
50
+ input_1 --> Op2 -+-> Op4 ----+
51
+ |
52
+ +-> Op7 --> output_1
53
+ |
54
+ +-> Op8 --> output_2
55
+
56
+ If we'd like to quantize this model to uint8 precision, but would like to make sure tensor "Op4_out"
57
+ is quantized to 16-bit, then we would specify the following initial tensor quantization overrides:
58
+
59
+ ```
60
+ init_overrides = {"Op4_out": [{"quant_type": QuantType.QUInt16}]}
61
+ ```
62
+
63
+ These initial overrides may not create a valid model because Op4 and Op5 may require both the input and output
64
+ to be the same type (e.g., uint16). This helper fixes the overrides so that input/output data types
65
+ are valid:
66
+
67
+ ```
68
+ overrides = TensorQuantOverridesHelper(init_overrides)
69
+
70
+ fixer = MixedPrecisionTensorQuantOverridesFixer.create_from_model(overrides, model, QuantType.QUInt8)
71
+ fixer.apply(
72
+ default_activation_qtype=QuantType.QUInt8,
73
+ default_activation_symmetric=False,
74
+ )
75
+ ```
76
+
77
+ The above snippet generates the following "fixed" overrides (get via overrides.get_dict()):
78
+
79
+ {
80
+ "Op2_out": [{"quant_type": QUInt8, "convert": {"quant_type": QUInt16, "recv_nodes": {"Op4"}}}],
81
+ "Op3_out": [{"quant_type": QUInt8, "convert": {"quant_type": QUInt16, "recv_nodes": {"Op5"}}}],
82
+ "Op4_out": [{"quant_type": QUInt16}],
83
+ "Op5_out": [{"quant_type": QUInt16, "convert": {"quant_type": QUInt8, "recv_nodes": {"Op6"}}}]
84
+ }
85
+
86
+ How to interpret the fixed overrides:
87
+ - Op2's output is consumed by Op4, Op7, and Op8. Op4 consumes the converted u16 type,
88
+ but Op7 and Op8 consume the original u8 type.
89
+ - Op3's output is converted from u8 to u16. Op5 consumes the converted u16 type.
90
+ - Op4's output is just u16 (not converted). All consumers of Op4_out get the u16 type.
91
+ - Op5's output is converted from u16 to u8. Op6 consumes the u8 type.
92
+ """
93
+
94
+ def __init__(
95
+ self,
96
+ overrides: TensorQuantOverridesHelper,
97
+ producers: dict[str, onnx.NodeProto],
98
+ consumers: dict[str, list[onnx.NodeProto]],
99
+ value_infos: dict[str, onnx.ValueInfoProto],
100
+ initializers: dict[str, onnx.TensorProto],
101
+ ):
102
+ """
103
+ Params:
104
+ overrides: The initial tensor quantization overrides to fix.
105
+ producers: Dictionary that maps a tensor name to the producer node that generates the tensor.
106
+ consumers: Dictionary that maps a tensor name to the consumer nodes that take the tensor as input.
107
+ value_infos: Dictionary that maps a tensor name to its onnx.ValueInfoProto.
108
+ initializers: Dictionary that maps an initializer name to its onnx.TensorProto.
109
+ """
110
+ self.overrides = overrides
111
+ self.consumers = consumers
112
+ self.producers = producers
113
+ self.value_infos = value_infos
114
+ self.initializers = initializers
115
+
116
+ @staticmethod
117
+ def create_from_model(
118
+ overrides: TensorQuantOverridesHelper, model: onnx.ModelProto, default_activation_qtype: QuantType
119
+ ) -> MixedPrecisionTensorQuantOverridesFixer:
120
+ """
121
+ Helper function that creates an instance of this class from a loaded ONNX model.
122
+
123
+ Params:
124
+ overrides: The initial tensor quantization overrides to fix.
125
+ model: Loaded ONNX model
126
+ default_activation_qtype: The intended default activation quantization type.
127
+ Used to validate the initial overrides.
128
+
129
+ Returns:
130
+ Initialized MixedPrecisionTensorQuantOverridesFixer object
131
+ """
132
+ model = onnx.shape_inference.infer_shapes(model) # Need to infer shapes to get value_infos
133
+
134
+ # Build dictionaries that enable convenient lookups of initializers and value_infos by name.
135
+ initializers = {initializer.name: initializer for initializer in model.graph.initializer}
136
+ value_infos = {vi.name: vi for vi in model.graph.value_info}
137
+ value_infos.update({ot.name: ot for ot in model.graph.output})
138
+ value_infos.update({it.name: it for it in model.graph.input})
139
+
140
+ # Ensure that the user-provided initial overrides are actually valid.
141
+ valid, err = overrides.is_valid(initializers, set(value_infos), default_activation_qtype)
142
+ if not valid:
143
+ pprint_overrides = overrides.pprint_str(indent=4)
144
+ logging.error(f"Provided invalid tensor quantization overrides:\n{pprint_overrides}")
145
+ raise ValueError(err)
146
+
147
+ consumers = {}
148
+ producers = {}
149
+
150
+ # Build dictionaries that map a tensor name to the consumer or producer nodes.
151
+ for node in model.graph.node:
152
+ for input_name in node.input:
153
+ if input_name:
154
+ if input_name not in consumers:
155
+ consumers[input_name] = []
156
+
157
+ consumers[input_name].append(node)
158
+
159
+ for output_name in node.output:
160
+ producers[output_name] = node
161
+
162
+ return MixedPrecisionTensorQuantOverridesFixer(overrides, producers, consumers, value_infos, initializers)
163
+
164
+ def apply(
165
+ self,
166
+ default_activation_qtype: QuantType,
167
+ default_activation_symmetric: bool,
168
+ ):
169
+ """
170
+ Fixes the initial tensor quantization overrides (in-place) for use in mixed-precision QDQ models.
171
+
172
+ Params:
173
+ default_activation_qtype: The intended default activation quantization type.
174
+ default_activation_symmetric: The intended default symmetry used to quantize activations.
175
+ """
176
+ type_requests = self.get_desired_tensor_types(default_activation_qtype, default_activation_symmetric)
177
+
178
+ # Use type requests to "fix" tensor quantization overrides by adding
179
+ # quantization type conversions where necessary.
180
+ for tensor_name, type_req in type_requests.items():
181
+ all_consumers = {node.name for node in self.consumers.get(tensor_name, [])}
182
+ has_producer_req = type_req.producer is not None
183
+ has_consumer_req = bool(type_req.consumers)
184
+
185
+ # Only producer type: Add conversion back to default activation type
186
+ if has_producer_req and not has_consumer_req:
187
+ self._update_converted_tensor(
188
+ tensor_name, type_req.producer, QuantTypeInfo(default_activation_qtype), all_consumers
189
+ )
190
+ # Only consumers
191
+ elif not has_producer_req and has_consumer_req:
192
+ prod_type_info = self.overrides.get_node_output_qtype_info(tensor_name, default_activation_qtype)
193
+ consumer_type_info = type_req.consumers[0]
194
+
195
+ if prod_type_info != consumer_type_info:
196
+ self._update_converted_tensor(
197
+ tensor_name, prod_type_info, consumer_type_info, type_req.consumers[1]
198
+ )
199
+ else:
200
+ if not self._check_nodes_are_not_convert_consumers(tensor_name, type_req.consumers[1]):
201
+ raise ValueError(
202
+ f"Tensor override for '{tensor_name}' converts the type for consumers that need the original type."
203
+ )
204
+ # Both producer and consumers
205
+ elif has_producer_req and has_consumer_req:
206
+ prod_type_info = type_req.producer
207
+ consumer_type_info = type_req.consumers[0]
208
+
209
+ if prod_type_info != consumer_type_info:
210
+ self._update_converted_tensor(
211
+ tensor_name, prod_type_info, consumer_type_info, type_req.consumers[1]
212
+ )
213
+ else:
214
+ consumers_for_original_type = all_consumers.difference(type_req.consumers[1])
215
+
216
+ if len(consumers_for_original_type) == 0:
217
+ # All consumers want the overridden type, so no need for convert nodes!
218
+ # Just add the override to the new new if not already present.
219
+ if tensor_name not in self.overrides:
220
+ self.overrides[tensor_name] = [{}]
221
+ prod_type_info.save_to_dict(self.overrides[tensor_name][0])
222
+
223
+ assert "convert" not in self.overrides[tensor_name][0]
224
+ else:
225
+ # Some consumers don't want the overridden type.
226
+ self._update_converted_tensor(
227
+ tensor_name,
228
+ prod_type_info,
229
+ QuantTypeInfo(default_activation_qtype),
230
+ consumers_for_original_type,
231
+ )
232
+ else:
233
+ raise ValueError(f"TypeRequest for tensor {tensor_name} has no producer or consumers.")
234
+
235
+ # Done. Check if the overrides are valid.
236
+ valid, err = self.overrides.is_valid(self.initializers, set(self.value_infos), default_activation_qtype)
237
+ if not valid:
238
+ pprint_overrides = self.overrides.pprint_str(indent=4)
239
+ logging.error(
240
+ f"Generated invalid tensor quantization overrides for mixed-precision QDQ model:\n{pprint_overrides}"
241
+ )
242
+ raise ValueError(err)
243
+
244
+ def get_desired_tensor_types(
245
+ self,
246
+ default_activation_qtype: QuantType,
247
+ default_activation_symmetric: bool,
248
+ ) -> dict[str, TensorTypeRequest]:
249
+ """
250
+ Iterates through the initial tensor quantization overrides and builds a set of TensorTypeRequests objects
251
+ that describe the quantization types required at each tensor. These TensorTypeRequests objects are ultimately
252
+ used to generated the "fixed" overrides.
253
+
254
+ Params:
255
+ default_activation_qtype: The intended default activation quantization type.
256
+ default_activation_symmetric: The intended default symmetry used to quantize activations.
257
+
258
+ Returns:
259
+ TensorTypeRequest objects as a dict that maps a tensor name to its requested types.
260
+ """
261
+ type_requests = {}
262
+ default_activation_type_info = QuantTypeInfo(default_activation_qtype, default_activation_symmetric)
263
+
264
+ # Scan tensor overrides for type conversion requests.
265
+ for tensor_name, override_list in self.overrides.items():
266
+ if not self.__is_tensor_quantizable(tensor_name):
267
+ continue # Skip non-quantizable tensors (e.g., not a float)
268
+
269
+ if tensor_name in self.initializers:
270
+ continue # Skip initializers
271
+
272
+ if not override_list or len(override_list) > 1:
273
+ continue # Skip per-channel stuff
274
+
275
+ override_dict = override_list[0]
276
+ quant_type_info = QuantTypeInfo.load_from_dict(override_dict, default_activation_type_info.quant_type)
277
+ producer_node = self.producers.get(tensor_name) # None if this is a model input
278
+
279
+ if quant_type_info != default_activation_type_info and "convert" not in override_dict:
280
+ if producer_node is not None:
281
+ self._add_type_requests_for_node(type_requests, quant_type_info, producer_node)
282
+
283
+ # Find all consumer nodes of `tensor_name` and update their inputs/outputs to the new type.
284
+ for consumer_node in self.consumers.get(tensor_name, []):
285
+ self._add_type_requests_for_node(type_requests, quant_type_info, consumer_node)
286
+
287
+ return type_requests
288
+
289
+ def _add_type_requests_for_node(
290
+ self,
291
+ type_requests: dict[str, TensorTypeRequest],
292
+ quant_type_info: QuantTypeInfo,
293
+ node: onnx.NodeProto,
294
+ ):
295
+ """
296
+ Adds TensorTypeRequest objects for a given node, assuming that we want all its inputs and outputs
297
+ to have the same quantization type (as specified by the `quant_type_info` parameter).
298
+
299
+ Params:
300
+ type_requests: Dictionary of type requests to append to for this node.
301
+ quant_type_info: The quantization type to use for inputs and outputs.
302
+ node: The node for which the TensorTypeRequest objects are created and added to type_requests.
303
+ """
304
+ # Add output side
305
+ for output_name in node.output:
306
+ if not self.__is_tensor_quantizable(output_name):
307
+ continue
308
+
309
+ if output_name not in type_requests:
310
+ type_requests[output_name] = TensorTypeRequest(quant_type_info, None)
311
+ else:
312
+ if (
313
+ type_requests[output_name].producer is not None
314
+ and type_requests[output_name].producer != quant_type_info
315
+ ):
316
+ raise ValueError(f"Tensor {output_name} has multiple types.")
317
+
318
+ type_requests[output_name].producer = quant_type_info
319
+
320
+ # Add the consumer side
321
+ for input_name in node.input:
322
+ if input_name and input_name not in self.initializers and self.__is_tensor_quantizable(input_name):
323
+ if input_name not in type_requests:
324
+ type_requests[input_name] = TensorTypeRequest(None, None)
325
+
326
+ if type_requests[input_name].consumers is None:
327
+ type_requests[input_name].consumers = (quant_type_info, set())
328
+
329
+ if type_requests[input_name].consumers[0] != quant_type_info:
330
+ raise ValueError(f"Tensor {input_name} has consumers requesting different types.")
331
+
332
+ if not node.name:
333
+ raise ValueError(
334
+ f"Node of type {node.op_type} with output 0 {node.output[0]} does not have a name!"
335
+ )
336
+
337
+ type_requests[input_name].consumers[1].add(node.name)
338
+
339
+ def _update_converted_tensor(
340
+ self,
341
+ tensor_name: str,
342
+ producer_type_info: QuantTypeInfo,
343
+ consumer_type_info: QuantTypeInfo,
344
+ consumer_names: set[str],
345
+ ):
346
+ """
347
+ Updates the tensor quantization overrides for a tensor that is converted from one type to another.
348
+
349
+ Params:
350
+ tensor_name: The name of the tensor for which to update overrides.
351
+ producer_type_info: Info for the tensor's produced type.
352
+ consumer_type_info: Info for the tensor's consumed (i.e., converted) type.
353
+ consumer_names: Nodes names of consumers that consume the converted type.
354
+ """
355
+ if tensor_name not in self.overrides or not self.overrides[tensor_name]:
356
+ self.overrides[tensor_name] = [{}]
357
+ producer_type_info.save_to_dict(self.overrides[tensor_name][0])
358
+
359
+ overrides = self.overrides[tensor_name][0]
360
+ if producer_type_info != QuantTypeInfo.load_from_dict(overrides):
361
+ raise ValueError(f"Desired producer quant_type for {tensor_name} doesn't match existing type.")
362
+
363
+ if consumer_names:
364
+ if "convert" not in overrides:
365
+ overrides["convert"] = {}
366
+ consumer_type_info.save_to_dict(overrides["convert"])
367
+
368
+ convert_dict = overrides["convert"]
369
+ if consumer_type_info != QuantTypeInfo.load_from_dict(convert_dict):
370
+ raise ValueError(f"Desired consumer quant_type for {tensor_name} doesn't match existing type.")
371
+
372
+ if "recv_nodes" not in convert_dict:
373
+ convert_dict["recv_nodes"] = set()
374
+
375
+ convert_dict["recv_nodes"].update(consumer_names)
376
+
377
+ def _check_nodes_are_not_convert_consumers(self, tensor_name: str, node_names: set[str]):
378
+ """
379
+ Returns true if the given nodes do not consume/receive a converted quantization type.
380
+
381
+ Params:
382
+ tensor_name: The name of the tensor to check.
383
+ node_names: Set of node names that should not be consumers of the converted type.
384
+ """
385
+ if tensor_name not in self.overrides or not self.overrides[tensor_name]:
386
+ return True
387
+
388
+ overrides = self.overrides[tensor_name][0]
389
+
390
+ if "convert" not in overrides:
391
+ return True
392
+
393
+ convert_dict = overrides["convert"]
394
+
395
+ if "recv_nodes" not in convert_dict:
396
+ return False
397
+
398
+ return not convert_dict["recv_nodes"].intersection(node_names)
399
+
400
+ def __is_tensor_quantizable(self, tensor_name):
401
+ weight = self.initializers.get(tensor_name)
402
+ if weight is not None:
403
+ if weight.data_type in (onnx.TensorProto.FLOAT, onnx.TensorProto.FLOAT16):
404
+ return True
405
+ elif tensor_name in self.value_infos:
406
+ vi = self.value_infos[tensor_name]
407
+ if vi.type.HasField("tensor_type") and vi.type.tensor_type.elem_type in (
408
+ onnx.TensorProto.FLOAT,
409
+ onnx.TensorProto.FLOAT16,
410
+ ):
411
+ return True
412
+
413
+ return False
ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/quantization/execution_providers/qnn/preprocess.py ADDED
@@ -0,0 +1,353 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -------------------------------------------------------------------------
2
+ # Copyright (c) Microsoft Corporation. All rights reserved.
3
+ # Licensed under the MIT License. See License.txt in the project root for
4
+ # license information.
5
+ # --------------------------------------------------------------------------
6
+ from __future__ import annotations
7
+
8
+ import logging
9
+ import tempfile
10
+ from pathlib import Path
11
+
12
+ import onnx
13
+
14
+ from ....tools.onnx_model_utils import fix_output_shapes, make_input_shape_fixed, optimize_model
15
+ from ....tools.remove_initializer_from_input import remove_initializer_from_input
16
+ from ...fusions import FusionGelu, FusionLayerNormalization
17
+ from ...onnx_model import ONNXModel
18
+ from .fusion_lpnorm import FusionLpNormalization
19
+ from .fusion_spacetodepth import FusionSpaceToDepth
20
+
21
+
22
+ def qnn_preprocess_model(
23
+ model_input: str | Path | onnx.ModelProto,
24
+ model_output: str | Path,
25
+ exclude_initializer_from_input: bool = False,
26
+ fuse_layernorm: bool = False,
27
+ save_as_external_data: bool = False,
28
+ all_tensors_to_one_file: bool = False,
29
+ external_data_location: str | None = None,
30
+ external_data_size_threshold: int = 1024,
31
+ external_data_convert_attribute: bool = False,
32
+ inputs_to_make_channel_last: list[str] | None = None,
33
+ outputs_to_make_channel_last: list[str] | None = None,
34
+ dynamic_input_shapes: list[tuple[str, str]] | None = None,
35
+ ) -> bool:
36
+ """
37
+ If necessary, this method creates a new "pre-processed" model in preparation for
38
+ quantization of a model to be used in QNN EP. Returns true if a new model was created.
39
+
40
+ This method perfoms the following operations:
41
+ - Fuse Erf sequence into a single Gelu node.
42
+ - Fuse ReduceL2 sequence into a single LpNormalization node (p == 2).
43
+ - (Optional) Fuse ReduceMean sequence into a single LayerNormalization node.
44
+
45
+ Args:
46
+ model_input: Path to the input model file or ModelProto.
47
+ model_output: Path the output model file, which is only created if this method returns True.
48
+ exclude_initializer_from_input: A bool specifying whether to exclude initializer from input.
49
+ Defaults to False.
50
+ fuse_layernorm: True if ReduceMean sequences should be fused into LayerNormalization nodes.
51
+ Defaults to False.
52
+ save_as_external_data: True if output model should be saved with external data. Defaults to false.
53
+ all_tensors_to_one_file: Effective only if save_as_external_data is true. Defaults to false.
54
+ If true, save all tensors to one external file specified by external_data_location.
55
+ If false, save each tensor to a file named with the tensor name.
56
+ external_data_location: Effective only if save_as_external_data is true. Defaults to None.
57
+ Specify the external file to which all tensors are saved. Path is relative
58
+ to the model path. If not specified, the model's name is used.
59
+ external_data_size_threshold: Effective only if save_as_external_data is true. Defaults to 1024.
60
+ Tensors with a data size >= external_data_size_threshold are converted to external data.
61
+ To convert every tensor with raw data to external data, set to 0.
62
+ external_data_convert_attribute: Effective only if save_as_external_data is true. Defaults to false.
63
+ If true, convert all tensors to external data.
64
+ If false, convert only non-attribute tensors to external data.
65
+ inputs_to_make_channel_last: List of graph input names to transpose to be "channel-last". For example,
66
+ if "input0" originally has the shape (N, C, D1, D2, ..., Dn), the resulting model will change input0's
67
+ shape to (N, D1, D2, ..., Dn, C) and add a transpose node after it.
68
+
69
+ Original:
70
+ input0 (N, C, D1, D2, ..., Dn) --> <Nodes>
71
+
72
+ Updated:
73
+ input0 (N, D1, D2, ..., Dn, C) --> Transpose --> input0_chanfirst (N, C, D1, D2, ..., Dn) --> <Nodes>
74
+
75
+ This can potentially improve inference latency for QDQ models running on QNN EP because the
76
+ additional transpose node may allow other transpose nodes inserted during ORT layout transformation
77
+ to cancel out.
78
+ outputs_to_make_channel_last: List of graph output names to transpose to be "channel-last". For example,
79
+ if "output0" originally has the shape (N, C, D1, D2, ..., Dn), the resulting model will change output0's
80
+ shape to (N, D1, D2, ..., Dn, C) and add a transpose node before it.
81
+
82
+ Original:
83
+ <Nodes> --> output0 (N, C, D1, D2, ..., Dn)
84
+
85
+ Updated:
86
+ <Nodes> --> output0_chanfirst (N, C, D1, D2, ..., Dn) --> Transpose --> output0 (N, D1, D2, ..., Dn, C)
87
+
88
+ This can potentially improve inference latency for QDQ models running on QNN EP because the
89
+ additional transpose node may allow other transpose nodes inserted during ORT layout transformation
90
+ to cancel out.
91
+ dynamic_input_shapes: A list of tuples specifying model input name to and its static shape in comma seprated
92
+ format, for example: [('input', '1,3,256,256')]. Defaults to None.
93
+ """
94
+ modified = False
95
+ model = model_input if isinstance(model_input, onnx.ModelProto) else onnx.load_model(model_input)
96
+ model = save_and_reload_optimize_model(model, shape_infer=True)
97
+ onnx_model = ONNXModel(model)
98
+
99
+ # Optionally, fix the dynamic input shapes.
100
+ if dynamic_input_shapes:
101
+ for input_name, input_shape_str in dynamic_input_shapes:
102
+ input_shape = [int(i) for i in input_shape_str.split(",")]
103
+ make_input_shape_fixed(onnx_model.graph(), input_name, input_shape)
104
+ fix_output_shapes(onnx_model.model)
105
+ modified = True
106
+
107
+ # Exclude initializer from input if model.ir_version >= 4
108
+ if exclude_initializer_from_input:
109
+ modified |= remove_initializer_from_input(onnx_model.model)
110
+
111
+ # Fuse Erf sequence into a single Gelu
112
+ fusion_gelu = FusionGelu(onnx_model)
113
+ if fusion_gelu.apply():
114
+ modified = True
115
+
116
+ # Fuse ReduceL2 sequence into a single LpNormalization node with p == 2.
117
+ fusion_lpnorm = FusionLpNormalization(onnx_model)
118
+ if fusion_lpnorm.apply():
119
+ modified = True
120
+
121
+ # Fuse Reshape/Transpose sequence into a single SpaceToDepth.
122
+ fusion_s2d = FusionSpaceToDepth(onnx_model)
123
+ if fusion_s2d.apply():
124
+ modified = True
125
+
126
+ # Optionally, fuse ReduceMean sequence into a single LayerNormalization node.
127
+ if fuse_layernorm:
128
+ onnx_opset = next(x for x in model.opset_import if x.domain == "" or x.domain == "ai.onnx")
129
+
130
+ # Need opset >= 17 to use LayerNormalization.
131
+ if onnx_opset.version < 17:
132
+ logging.warning(
133
+ "Unable to fuse ReduceMean sequence into a LayerNormalization node. "
134
+ "ONNX model must use an opset >= 17 in order to use LayerNormalization, "
135
+ f"but found version {onnx_opset.version}. Please use onnx.version_converter to update your model."
136
+ )
137
+ else:
138
+ fusion_layernorm = FusionLayerNormalization(onnx_model)
139
+ if fusion_layernorm.apply():
140
+ modified = True
141
+
142
+ # Optionally, transpose inputs and/or outputs to make them "channel-last".
143
+ if inputs_to_make_channel_last or outputs_to_make_channel_last:
144
+ transpose_node_prefix = "Transpose_channel_"
145
+ transpose_node_suffix: int = onnx_model.get_largest_node_name_suffix(transpose_node_prefix) + 1
146
+ update_io_to_channel_last(
147
+ onnx_model.model,
148
+ inputs_to_make_channel_last,
149
+ outputs_to_make_channel_last,
150
+ transpose_node_name_prefix=transpose_node_prefix,
151
+ transpose_node_name_start_suffix=transpose_node_suffix,
152
+ )
153
+ modified = True
154
+
155
+ # Make sure all nodes have a name.
156
+ unnamed_node_prefix = "qnn_preproc_node_"
157
+ available_suffix = onnx_model.get_largest_node_name_suffix(unnamed_node_prefix) + 1
158
+ for node in onnx_model.model.graph.node:
159
+ if node.op_type != "Constant" and not node.name:
160
+ new_node_name = f"{unnamed_node_prefix}{available_suffix!s}"
161
+ available_suffix += 1
162
+ node.name = new_node_name
163
+ modified = True
164
+ logging.warning(f"Node of type {node.op_type} does not have a name. Renamed to {new_node_name}.")
165
+
166
+ if modified:
167
+ onnx_model.topological_sort()
168
+ onnx.save_model(
169
+ model,
170
+ model_output,
171
+ save_as_external_data=save_as_external_data,
172
+ all_tensors_to_one_file=all_tensors_to_one_file,
173
+ location=external_data_location,
174
+ size_threshold=external_data_size_threshold,
175
+ convert_attribute=external_data_convert_attribute,
176
+ )
177
+
178
+ return modified
179
+
180
+
181
+ def save_and_reload_optimize_model(model: onnx.ModelProto, shape_infer: bool) -> onnx.ModelProto:
182
+ with tempfile.TemporaryDirectory(prefix="ort.qnn_preproc.") as qnn_preproc_tmp_dir:
183
+ model_in_path = Path(qnn_preproc_tmp_dir).joinpath("qnn_proc_input.onnx")
184
+ onnx.save_model(model, model_in_path, save_as_external_data=True)
185
+ if shape_infer:
186
+ model_infer_path = Path(qnn_preproc_tmp_dir).joinpath("qnn_proc_infer.onnx")
187
+ onnx.shape_inference.infer_shapes_path(str(model_in_path), str(model_infer_path))
188
+ model_in_path = model_infer_path
189
+ model_out_path = Path(qnn_preproc_tmp_dir).joinpath("qnn_proc_output.onnx")
190
+ optimize_model(model_in_path, model_out_path)
191
+ ret_model = onnx.load_model(model_out_path)
192
+ ret_metaprops = {"onnx.infer": "onnxruntime.tools.qnn.preprocess"}
193
+ if ret_model.metadata_props:
194
+ ret_metaprops.update(ret_model.metadata_props)
195
+ onnx.helper.set_model_props(ret_model, ret_metaprops)
196
+ return ret_model
197
+
198
+
199
+ class InputOutputNameMap:
200
+ def __init__(
201
+ self,
202
+ orig_tensor_names: set[str],
203
+ orig_graph_inputs: dict[str, onnx.ValueInfoProto],
204
+ orig_graph_outputs: dict[str, onnx.ValueInfoProto],
205
+ ):
206
+ self.orig_tensor_names = orig_tensor_names
207
+ self.orig_graph_inputs = orig_graph_inputs
208
+ self.orig_graph_outputs = orig_graph_outputs
209
+ self.updated_io_names = {}
210
+ self.new_value_infos = []
211
+
212
+ def get_new_name(self, orig_name: str):
213
+ if orig_name in self.updated_io_names:
214
+ return self.updated_io_names[orig_name]
215
+
216
+ # Make a new tensor name that is unique among all tensors in the graph.
217
+ prefix: str = f"{orig_name}_channel_first_"
218
+ suffix: int = -1
219
+ for tensor_name in self.orig_tensor_names:
220
+ if tensor_name.startswith(prefix) and tensor_name[len(prefix) :].isdigit():
221
+ index = int(tensor_name[len(prefix) :])
222
+ suffix = max(suffix, index)
223
+
224
+ suffix += 1 # This is the first available suffix.
225
+ new_name = f"{prefix}{suffix!s}"
226
+
227
+ # Add new value_info objects for these new tensors.
228
+ orig_value_info = self.orig_graph_inputs.get(orig_name) or self.orig_graph_outputs[orig_name]
229
+ value_info_proto = onnx.ValueInfoProto()
230
+ value_info_proto.CopyFrom(orig_value_info)
231
+ value_info_proto.name = new_name
232
+ self.new_value_infos.append(value_info_proto)
233
+
234
+ self.updated_io_names[orig_name] = new_name
235
+ return self.updated_io_names[orig_name]
236
+
237
+
238
+ def update_io_to_channel_last(
239
+ model: onnx.ModelProto,
240
+ inputs_to_update: list[str] | None,
241
+ outputs_to_update: list[str] | None,
242
+ transpose_node_name_prefix: str = "Transpose_channel_",
243
+ transpose_node_name_start_suffix: int = 0,
244
+ ):
245
+ inputs_to_update = set(inputs_to_update or [])
246
+ outputs_to_update = set(outputs_to_update or [])
247
+
248
+ if not inputs_to_update and not outputs_to_update:
249
+ return
250
+
251
+ graph = model.graph
252
+ orig_graph_inputs = {ginput.name: ginput for ginput in graph.input}
253
+ orig_graph_outputs = {goutput.name: goutput for goutput in graph.output}
254
+
255
+ # Check that the user passed in actual input and output names.
256
+ for input_name in inputs_to_update:
257
+ if input_name not in orig_graph_inputs:
258
+ raise ValueError(f"{input_name} is not a graph input")
259
+
260
+ for output_name in outputs_to_update:
261
+ if output_name not in orig_graph_outputs:
262
+ raise ValueError(f"{output_name} is not a graph output")
263
+
264
+ orig_tensor_names = set()
265
+ orig_tensor_names.update(set(orig_graph_inputs))
266
+ orig_tensor_names.update(set(orig_graph_outputs))
267
+ orig_tensor_names.update(input_name for node in graph.node for input_name in node.input if input_name)
268
+
269
+ # Maps original input (or output) name to its updated name used within the graph.
270
+ io_map = InputOutputNameMap(orig_tensor_names, orig_graph_inputs, orig_graph_outputs)
271
+
272
+ # Update each node's inputs/outputs to use the transposed versions.
273
+ for node in graph.node:
274
+ for i in range(len(node.input)):
275
+ if node.input[i] and node.input[i] in inputs_to_update:
276
+ node.input[i] = io_map.get_new_name(node.input[i])
277
+ elif node.input[i] and node.input[i] in outputs_to_update:
278
+ node.input[i] = io_map.get_new_name(node.input[i])
279
+
280
+ for i in range(len(node.output)):
281
+ if node.output[i] in outputs_to_update:
282
+ node.output[i] = io_map.get_new_name(node.output[i])
283
+
284
+ # Update graph inputs to channel-last and a Transpose (to channel-first) after each.
285
+ for g_input_name in inputs_to_update:
286
+ g_input = orig_graph_inputs[g_input_name]
287
+
288
+ if not g_input.type.HasField("tensor_type") or not g_input.type.tensor_type.HasField("shape"):
289
+ raise ValueError(f"Expected input {g_input.name} to have a tensor_type with a shape")
290
+
291
+ input_shape = g_input.type.tensor_type.shape
292
+ input_rank = len(input_shape.dim)
293
+
294
+ if input_rank < 3:
295
+ raise ValueError(f"Expected input {g_input.name} to be of rank >= 3")
296
+
297
+ channel_dim = onnx.TensorShapeProto.Dimension()
298
+ channel_dim.CopyFrom(input_shape.dim[1])
299
+ for i in range(1, input_rank - 1):
300
+ input_shape.dim[i].CopyFrom(input_shape.dim[i + 1])
301
+ input_shape.dim[input_rank - 1].CopyFrom(channel_dim)
302
+
303
+ transpose_perm = list(range(input_rank))
304
+ for i in range(input_rank):
305
+ transpose_perm[i] = i if i < 1 else i - 1
306
+ transpose_perm[1] = input_rank - 1
307
+
308
+ transpose_node = onnx.helper.make_node(
309
+ "Transpose",
310
+ name=f"{transpose_node_name_prefix}{transpose_node_name_start_suffix!s}",
311
+ inputs=[g_input.name],
312
+ outputs=[io_map.get_new_name(g_input.name)],
313
+ perm=transpose_perm,
314
+ )
315
+ transpose_node_name_start_suffix += 1
316
+
317
+ graph.node.extend([transpose_node])
318
+
319
+ # Update graph outputs to channel-last and a Transpose (from channel-first) before each.
320
+ for g_output_name in outputs_to_update:
321
+ g_output = orig_graph_outputs[g_output_name]
322
+ if not g_output.type.HasField("tensor_type") or not g_output.type.tensor_type.HasField("shape"):
323
+ raise ValueError(f"Expected output {g_output.name} to have a tensor_type with a shape")
324
+
325
+ output_shape = g_output.type.tensor_type.shape
326
+ output_rank = len(output_shape.dim)
327
+
328
+ if output_rank < 3:
329
+ raise ValueError(f"Expected output {g_output.name} to be of rank >= 3")
330
+
331
+ channel_dim = onnx.TensorShapeProto.Dimension()
332
+ channel_dim.CopyFrom(output_shape.dim[1])
333
+ for i in range(1, output_rank - 1):
334
+ output_shape.dim[i].CopyFrom(output_shape.dim[i + 1])
335
+ output_shape.dim[output_rank - 1].CopyFrom(channel_dim)
336
+
337
+ transpose_perm = list(range(output_rank))
338
+ for i in range(output_rank):
339
+ transpose_perm[i] = i if i == 0 else i + 1
340
+ transpose_perm[output_rank - 1] = 1
341
+
342
+ transpose_node = onnx.helper.make_node(
343
+ "Transpose",
344
+ name=f"{transpose_node_name_prefix}{transpose_node_name_start_suffix!s}",
345
+ inputs=[io_map.get_new_name(g_output.name)],
346
+ outputs=[g_output.name],
347
+ perm=transpose_perm,
348
+ )
349
+ transpose_node_name_start_suffix += 1
350
+
351
+ graph.node.extend([transpose_node])
352
+
353
+ graph.value_info.extend(io_map.new_value_infos)
ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/quantization/execution_providers/qnn/quant_config.py ADDED
@@ -0,0 +1,389 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -------------------------------------------------------------------------
2
+ # Copyright (c) Microsoft Corporation. All rights reserved.
3
+ # Licensed under the MIT License. See License.txt in the project root for
4
+ # license information.
5
+ # --------------------------------------------------------------------------
6
+ from __future__ import annotations
7
+
8
+ import copy
9
+ import logging
10
+ from pathlib import Path
11
+ from typing import Any
12
+
13
+ import numpy as np
14
+ import onnx
15
+
16
+ from ...calibrate import CalibrationDataReader, CalibrationMethod
17
+ from ...quant_utils import QuantType
18
+ from ...quantize import StaticQuantConfig
19
+ from ...tensor_quant_overrides import TensorQuantOverridesHelper
20
+ from .mixed_precision_overrides_utils import MixedPrecisionTensorQuantOverridesFixer
21
+
22
+ Q16_TYPES = {QuantType.QInt16, QuantType.QUInt16}
23
+ Q8_TYPES = {QuantType.QInt8, QuantType.QUInt8}
24
+ Q4_TYPES = {QuantType.QInt4, QuantType.QUInt4}
25
+ OP_TYPES_TO_EXCLUDE = {"Cast"}
26
+ MODEL_SIZE_THRESHOLD = 2147483648 # Quant model should use external data if >= 2GB
27
+
28
+
29
+ def warn_unable_to_override(
30
+ node: onnx.NodeProto,
31
+ what_str: str,
32
+ tensor_name: str,
33
+ io_kind: str,
34
+ ):
35
+ logging.warning(
36
+ f"Unable to override {what_str} for {node.op_type} node's {io_kind} "
37
+ "because it has already been overridden! Check the initial quantization overrides provided "
38
+ "to get_qnn_qdq_config() if the generated QDQ model does not run on QNN EP. "
39
+ f"Node name: {node.name}, {io_kind} name: {tensor_name}"
40
+ )
41
+
42
+
43
+ def get_qnn_qdq_config(
44
+ model_input: str | Path | onnx.ModelProto,
45
+ calibration_data_reader: CalibrationDataReader,
46
+ calibrate_method: CalibrationMethod = CalibrationMethod.MinMax,
47
+ activation_type: QuantType = QuantType.QUInt8,
48
+ weight_type: QuantType = QuantType.QUInt8,
49
+ per_channel: bool = False,
50
+ init_overrides: dict[str, list[dict[str, Any]]] | None = None,
51
+ add_qtype_converts: bool = True,
52
+ activation_symmetric: bool = False,
53
+ weight_symmetric: bool | None = None,
54
+ keep_removable_activations: bool = False,
55
+ stride: int | None = None,
56
+ calibration_providers: list[str] | None = None,
57
+ op_types_to_quantize: list[str] | None = None,
58
+ nodes_to_exclude: list[str] | None = None,
59
+ ) -> StaticQuantConfig:
60
+ """
61
+ Returns a static quantization configuration suitable for running QDQ models on QNN EP.
62
+ This is done primarily by setting tensor-level quantization overrides.
63
+
64
+ Params:
65
+ model_input: Path to the input model file or ModelProto.
66
+ calibration_data_reader: Calibration data reader.
67
+ calibrate_methode: The calibration method. Defaults to MinMax.
68
+ activation_type: The default activation quantization type. Defaults to QUInt8.
69
+ weight_type: The default weight quantization type. Defaults to QUInt8.
70
+ per_channel: Global option that determines if a fixed set of operator types should be quantized per-channel.
71
+ Defaults to false. Alternatively, use the tensor-level `init_overrides` to select individual operators
72
+ and their quantization axes.
73
+
74
+ If set, the quantization tool uses per-channel quantization for the following operator types and inputs:
75
+ - Conv:
76
+ - input[1] on axis 0
77
+ - input[2] (bias) on axis 0
78
+ - ConvTranspose:
79
+ - input[1] on axis 1
80
+ - input[2] (bias) on axis 0
81
+ init_overrides: Initial tensor-level quantization overrides. Defaults to None. This function updates of a copy
82
+ of these overrides with any necessary adjustments and includes them in the returned
83
+ configuration object (i.e., config.extra_options['TensorQuantOverrides']).
84
+
85
+ The key is a tensor name and the value is a list of dictionaries. For per-tensor quantization, the list
86
+ contains a single dictionary. For per-channel quantization, the list contains either a dictionary for
87
+ each channel in the tensor or a single dictionary that is assumed to apply to all channels. An 'axis'
88
+ key must be present in the first dictionary for per-channel quantization.
89
+
90
+ Each dictionary contains optional overrides with the following keys and values.
91
+ 'quant_type' = QuantType : The tensor's quantization data type.
92
+ 'axis' = Int : The per-channel axis. Must be present for per-channel weights.
93
+ 'scale' = Float : The scale value to use. Must also specify `zero_point` if set.
94
+ 'zero_point' = Int : The zero-point value to use. Must also specify `scale` is set.
95
+ 'symmetric' = Bool : If the tensor should use symmetric quantization. Invalid if also
96
+ set `scale` or `zero_point`.
97
+ 'reduce_range' = Bool : If the quantization range should be reduced. Invalid if also
98
+ set `scale` or `zero_point`. Only valid for initializers.
99
+ 'rmax' = Float : Override the maximum real tensor value in calibration data.
100
+ Invalid if also set `scale` or `zero_point`.
101
+ 'rmin' = Float : Override the minimum real tensor value in calibration data.
102
+ Invalid if also set `scale` or `zero_point`.
103
+ 'convert' = Dict : A nested dictionary with the same keys for an activation
104
+ tensor that should be converted to another quantization type.
105
+ 'convert["recv_nodes"] = Set : Set of node names that consume the converted activation,
106
+ other nodes get the original type. If not specified,
107
+ assume all consumer nodes get the converted type.
108
+ add_qtype_converts: True if this function should automatically add "convert" entries to the provided
109
+ `init_overrides` to ensure that operators use valid input/output types (activations only).
110
+ Ex: if you override the output of an Add to 16-bit, this option ensures that the activation inputs
111
+ of the Add are also up-converted to 16-bit and that data types for surrounding ops are converted
112
+ appropriately. Refer to the documentation in mixed_precision_overrides_utils.py for additional details.
113
+ activation_symmetric: True if activations should be quantized symmetrically (i.e, rmax == -rmin) by default.
114
+ Defaults to false. For int8 and int16, this results in zero-point values of 0. For uint8 and uin16,
115
+ the zero-point values are 128 and 32,768, respectively.
116
+ weight_symmetric: True if weights should be quantized symmetrically (i.e., rmax == -rmin) by default.
117
+ Defaults to None. If set to None, weight_symmetric is assumed true if the weight_type is a signed int.
118
+ keep_removable_activations: Defaults to false. If true, "removable" activations (e.g., Clip or Relu) will not
119
+ be removed, and will be explicitly represented in the QDQ model. If false, these activations
120
+ are automatically removed if activations are asymmetrically quantized. Keeping these activations
121
+ is necessary if optimizations or EP transformations will later remove
122
+ QuantizeLinear/DequantizeLinear operators from the model.
123
+ calibration_providers: Execution providers to run the session during calibration. Default is None which uses
124
+ [ "CPUExecutionProvider" ].
125
+ op_types_to_quantize: If set to None, all operator types will be quantized except for OP_TYPES_TO_EXCLUDE
126
+ nodes_to_exclude: List of nodes names to exclude from quantization. The nodes in this list will be excluded from
127
+ quantization when it is not None.
128
+
129
+ Returns:
130
+ A StaticQuantConfig object
131
+ """
132
+ if weight_symmetric is None:
133
+ weight_symmetric = weight_type in {QuantType.QInt8, QuantType.QInt16}
134
+
135
+ model = (
136
+ model_input
137
+ if isinstance(model_input, onnx.ModelProto)
138
+ else onnx.load_model(model_input, load_external_data=False)
139
+ )
140
+
141
+ op_types = set()
142
+ model_has_external_data = False
143
+ name_to_initializer = {}
144
+
145
+ # Build map of initializers (name -> initializer) and
146
+ # check if the model has external data.
147
+ for initializer in model.graph.initializer:
148
+ name_to_initializer[initializer.name] = initializer
149
+ if onnx.external_data_helper.uses_external_data(initializer):
150
+ model_has_external_data = True
151
+
152
+ overrides_helper = TensorQuantOverridesHelper(copy.deepcopy(init_overrides) if init_overrides else {})
153
+
154
+ if not overrides_helper.empty() and add_qtype_converts:
155
+ # Fix mixed-precision overrides.
156
+ overrides_fixer = MixedPrecisionTensorQuantOverridesFixer.create_from_model(
157
+ overrides_helper, model, activation_type
158
+ )
159
+ overrides_fixer.apply(activation_type, activation_symmetric)
160
+
161
+ # Setup quantization overrides for specific operator types to ensure compatibility with QNN EP.
162
+ qnn_compat = QnnCompatibilityOverrides(
163
+ activation_type,
164
+ weight_type,
165
+ activation_symmetric,
166
+ weight_symmetric,
167
+ per_channel,
168
+ overrides_helper,
169
+ name_to_initializer,
170
+ )
171
+
172
+ op_types_to_quantize_set = set(op_types_to_quantize) if op_types_to_quantize else None
173
+ nodes_to_exclude_set = set(nodes_to_exclude) if nodes_to_exclude else None
174
+
175
+ for node in model.graph.node:
176
+ if op_types_to_quantize_set and node.op_type not in op_types_to_quantize_set:
177
+ continue
178
+ if nodes_to_exclude_set and node.name in nodes_to_exclude_set:
179
+ continue
180
+ op_types.add(node.op_type)
181
+ qnn_compat.process_node(node)
182
+
183
+ extra_options = {
184
+ "MinimumRealRange": 0.0001,
185
+ "DedicatedQDQPair": False, # Let ORT optimizer duplicate DQ nodes
186
+ "QDQKeepRemovableActivations": keep_removable_activations,
187
+ "TensorQuantOverrides": overrides_helper.get_dict(),
188
+ "ActivationSymmetric": activation_symmetric,
189
+ "WeightSymmetric": weight_symmetric,
190
+ "CalibStridedMinMax": stride,
191
+ }
192
+
193
+ # ONNX opset < 21 does not support 16-bit quantization, so must use 'com.microsoft' domain
194
+ # on Q/DQ operators if using 16-bit or 4-bit quantization.
195
+ onnx_opset = next(x for x in model.opset_import if x.domain == "" or x.domain == "ai.onnx")
196
+ if onnx_opset.version < 21:
197
+ opset21_types = Q16_TYPES.union(Q4_TYPES)
198
+ overrides_have_opset21_types = any(t in opset21_types for t in overrides_helper.get_quant_types())
199
+ if activation_type in opset21_types or weight_type in opset21_types or overrides_have_opset21_types:
200
+ extra_options["UseQDQContribOps"] = True
201
+
202
+ return StaticQuantConfig(
203
+ calibration_data_reader,
204
+ calibrate_method=calibrate_method,
205
+ activation_type=activation_type,
206
+ weight_type=weight_type,
207
+ op_types_to_quantize=(
208
+ op_types_to_quantize if op_types_to_quantize else list(op_types.difference(OP_TYPES_TO_EXCLUDE))
209
+ ),
210
+ nodes_to_exclude=nodes_to_exclude,
211
+ per_channel=per_channel,
212
+ use_external_data_format=(model_has_external_data or model.ByteSize() >= MODEL_SIZE_THRESHOLD),
213
+ calibration_providers=calibration_providers,
214
+ extra_options=extra_options,
215
+ )
216
+
217
+
218
+ class QnnCompatibilityOverrides:
219
+ """
220
+ Helper that processes nodes to generate quantization overrides that make the resulting QDQ model
221
+ compatible with QNN EP.
222
+ """
223
+
224
+ def __init__(
225
+ self,
226
+ default_activation_qtype: QuantType,
227
+ default_weight_qtype: QuantType,
228
+ activation_symmetric: bool,
229
+ weight_symmetric: bool,
230
+ per_channel: bool,
231
+ overrides: TensorQuantOverridesHelper,
232
+ initializers: dict[str, onnx.TensorProto],
233
+ ):
234
+ self.default_activation_qtype = default_activation_qtype
235
+ self.default_weight_qtype = default_weight_qtype
236
+ self.activation_symmetric = activation_symmetric
237
+ self.weight_symmetric = weight_symmetric
238
+ self.per_channel = per_channel
239
+ self.overrides = overrides
240
+ self.initializers = initializers
241
+
242
+ self.process_fns = {
243
+ "MatMul": self._process_matmul,
244
+ "LayerNormalization": self._process_layernorm,
245
+ "Sigmoid": self._process_sigmoid,
246
+ "Tanh": self._process_tanh,
247
+ }
248
+
249
+ def process_node(self, node: onnx.NodeProto):
250
+ process_fn = self.process_fns.get(node.op_type)
251
+
252
+ if process_fn is not None:
253
+ process_fn(node)
254
+
255
+ def _make_static_inputs_use_default_weight_type(self, node: onnx.NodeProto):
256
+ """
257
+ Overrides initializer input(s) to use the default weight type if:
258
+ - The default weight type is 8-bit
259
+ - One of the inputs is a 16-bit activation
260
+ - The other input is an initializer (per-tensor quantized)
261
+
262
+ This is necessary because the quantization tool does not assign MatMul or LayerNorm initializer
263
+ inputs the default weight type. Instead, it assigns the default activation type.
264
+ """
265
+ if self.default_weight_qtype not in Q8_TYPES:
266
+ return
267
+
268
+ input_16bit_act_name = None
269
+ input_weight_name = None
270
+
271
+ # Loop through first 2 inputs to find a 16-bit activation and a (per-tensor) weight.
272
+ for i in range(2):
273
+ input_name = node.input[i]
274
+ if not input_name:
275
+ continue
276
+
277
+ is_weight = input_name in self.initializers
278
+ qtype_info = self.overrides.get_node_input_qtype_info(
279
+ input_name,
280
+ node.name,
281
+ default_qtype=None if is_weight else self.default_activation_qtype,
282
+ )
283
+
284
+ if qtype_info.axis is not None:
285
+ return # Don't process MatMul with a per-channel quantized input.
286
+
287
+ if (
288
+ is_weight
289
+ and qtype_info.quant_type == self.default_weight_qtype
290
+ and qtype_info.symmetric == self.weight_symmetric
291
+ ):
292
+ return # Return. Weight is already overridden to use the desired weight type.
293
+
294
+ if is_weight:
295
+ input_weight_name = input_name
296
+ elif qtype_info.quant_type in Q16_TYPES:
297
+ input_16bit_act_name = input_name
298
+
299
+ # Override initializer input to use the default weight type.
300
+ if input_16bit_act_name and input_weight_name:
301
+ did_update = self.overrides.update_tensor_overrides(
302
+ input_weight_name,
303
+ {"quant_type": self.default_weight_qtype, "symmetric": self.weight_symmetric},
304
+ overwrite=False,
305
+ )
306
+
307
+ if not did_update:
308
+ warn_unable_to_override(node, "quant_type/symmetric", input_weight_name, "input weight")
309
+
310
+ def _process_matmul(self, node: onnx.NodeProto):
311
+ assert node.op_type == "MatMul", f"Expected MatMul, but got {node.op_type}"
312
+
313
+ if not self.per_channel:
314
+ self._make_static_inputs_use_default_weight_type(node)
315
+ return
316
+
317
+ # QNN does not support per-channel MatMul. However, the ORT quantization tool attempts to use per-channel
318
+ # quantization for MatMul by default *if* the global per_channel setting is enabled. So, we need to
319
+ # provide explicit per-tensor quantization overrides for MatMul if per_channel is enabled and
320
+ # the user did not provide any other overrides.
321
+ for input_name in node.input:
322
+ is_weight_no_overrides = input_name in self.initializers and input_name not in self.overrides
323
+ if is_weight_no_overrides:
324
+ self.overrides.update_tensor_overrides(
325
+ input_name,
326
+ {"quant_type": self.default_weight_qtype, "symmetric": self.weight_symmetric},
327
+ )
328
+
329
+ def _process_layernorm(self, node: onnx.NodeProto):
330
+ assert node.op_type == "LayerNormalization", f"Expected LayerNormalization, but got {node.op_type}"
331
+
332
+ if not self.per_channel:
333
+ self._make_static_inputs_use_default_weight_type(node)
334
+
335
+ def _process_sigmoid(self, node: onnx.NodeProto):
336
+ """
337
+ Overrides 16-bit Sigmoid's output scale and zero-point as per QNN requirements.
338
+ """
339
+ assert node.op_type == "Sigmoid", f"Expected Sigmoid, but got {node.op_type}"
340
+ output_type = self.overrides.get_node_output_qtype_info(
341
+ node.output[0], self.default_activation_qtype
342
+ ).quant_type
343
+
344
+ if output_type == QuantType.QUInt16:
345
+ self.overrides.update_tensor_overrides(
346
+ node.output[0],
347
+ {
348
+ "quant_type": output_type,
349
+ "scale": np.array(1.0 / 65536.0, dtype=np.float32),
350
+ "zero_point": np.array(0, dtype=np.uint16),
351
+ },
352
+ )
353
+ elif output_type == QuantType.QInt16:
354
+ self.overrides.update_tensor_overrides(
355
+ node.output[0],
356
+ {
357
+ "quant_type": output_type,
358
+ "scale": np.array(1.0 / 32768.0, dtype=np.float32),
359
+ "zero_point": np.array(0, dtype=np.int16),
360
+ },
361
+ )
362
+
363
+ def _process_tanh(self, node: onnx.NodeProto):
364
+ """
365
+ Overrides 16-bit Tanh's output scale and zero-point as per QNN requirements.
366
+ """
367
+ assert node.op_type == "Tanh", f"Expected Tanh, but got {node.op_type}"
368
+ output_type = self.overrides.get_node_output_qtype_info(
369
+ node.output[0], self.default_activation_qtype
370
+ ).quant_type
371
+
372
+ if output_type == QuantType.QUInt16:
373
+ self.overrides.update_tensor_overrides(
374
+ node.output[0],
375
+ {
376
+ "quant_type": output_type,
377
+ "scale": np.array(1.0 / 32768.0, dtype=np.float32),
378
+ "zero_point": np.array(32768, dtype=np.uint16),
379
+ },
380
+ )
381
+ elif output_type == QuantType.QInt16:
382
+ self.overrides.update_tensor_overrides(
383
+ node.output[0],
384
+ {
385
+ "quant_type": output_type,
386
+ "scale": np.array(1.0 / 32768.0, dtype=np.float32),
387
+ "zero_point": np.array(0, dtype=np.int16),
388
+ },
389
+ )
ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/quantization/fusions/__init__.py ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ from .fusion import Fusion # noqa: F401
2
+ from .fusion_gelu import FusionGelu # noqa: F401
3
+ from .fusion_layernorm import FusionLayerNormalization # noqa: F401
4
+ from .replace_upsample_with_resize import ReplaceUpsampleWithResize # noqa: F401
ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/quantization/fusions/fusion.py ADDED
@@ -0,0 +1,311 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -------------------------------------------------------------------------
2
+ # Copyright (c) Microsoft Corporation. All rights reserved.
3
+ # Licensed under the MIT License. See License.txt in the project root for
4
+ # license information.
5
+ # --------------------------------------------------------------------------
6
+ from __future__ import annotations
7
+
8
+ from collections import deque
9
+
10
+ import onnx
11
+
12
+ from ..onnx_model import ONNXModel
13
+
14
+
15
+ class Fusion:
16
+ """
17
+ Base class for fusions.
18
+ """
19
+
20
+ def __init__(self, model: ONNXModel, fused_op_type: str, search_op_type: str):
21
+ self.search_op_type: str = search_op_type
22
+ self.fused_op_type: str = fused_op_type
23
+ self.model: ONNXModel = model
24
+ self.nodes_to_remove: list = []
25
+ self.nodes_to_add: list = []
26
+
27
+ self._new_node_name_prefix = self.fused_op_type + "_fused_" + self.search_op_type + "_"
28
+ self._new_node_name_suffix = None # int|None used to create unique node names for the fused ops.
29
+
30
+ def fuse(
31
+ self,
32
+ node: onnx.NodeProto,
33
+ input_name_to_nodes: dict[str, list[onnx.NodeProto]],
34
+ output_name_to_node: dict[str, onnx.NodeProto],
35
+ ):
36
+ """
37
+ Interface function for derived fusion classes. Tries to fuse a node sequence containing
38
+ the specified node.
39
+ """
40
+ raise NotImplementedError
41
+
42
+ def apply(self) -> bool:
43
+ """
44
+ Apply graph fusion on the entire model graph.
45
+ """
46
+ input_name_to_nodes = self.model.input_name_to_nodes()
47
+ output_name_to_node = self.model.output_name_to_node()
48
+
49
+ for node in self.model.nodes():
50
+ if node.op_type == self.search_op_type:
51
+ self.fuse(node, input_name_to_nodes, output_name_to_node)
52
+
53
+ self.model.remove_nodes(self.nodes_to_remove)
54
+ self.model.add_nodes(self.nodes_to_add)
55
+
56
+ graph_updated = bool(self.nodes_to_remove or self.nodes_to_add)
57
+
58
+ if graph_updated:
59
+ self.model.remove_unused_constant()
60
+
61
+ return graph_updated
62
+
63
+ def create_unique_node_name(self):
64
+ prefix = self._new_node_name_prefix
65
+
66
+ if self._new_node_name_suffix is None:
67
+ largest_suffix: int = self.model.get_largest_node_name_suffix(prefix)
68
+ self._new_node_name_suffix = largest_suffix + 1
69
+
70
+ new_name = f"{prefix}{self._new_node_name_suffix!s}"
71
+ self._new_node_name_suffix += 1
72
+
73
+ return new_name
74
+
75
+ @staticmethod
76
+ def is_safe_to_fuse_nodes(
77
+ nodes_to_remove: list[onnx.NodeProto],
78
+ keep_outputs: list[str],
79
+ input_name_to_nodes: dict[str, list[onnx.NodeProto]],
80
+ output_name_to_node: dict[str, onnx.NodeProto],
81
+ ) -> bool:
82
+ for node_to_remove in nodes_to_remove:
83
+ for output_to_remove in node_to_remove.output:
84
+ if output_to_remove in keep_outputs:
85
+ continue
86
+
87
+ if output_to_remove in input_name_to_nodes:
88
+ for impacted_node in input_name_to_nodes[output_to_remove]:
89
+ if impacted_node not in nodes_to_remove:
90
+ # Not safe to remove nodes since output is used by impacted_node
91
+ return False
92
+ return True
93
+
94
+ @staticmethod
95
+ def get_node_attribute(node: onnx.NodeProto, attribute_name: str):
96
+ for attr in node.attribute:
97
+ if attr.name == attribute_name:
98
+ value = onnx.helper.get_attribute_value(attr)
99
+ return value
100
+ return None
101
+
102
+ @staticmethod
103
+ def input_index(node_output: str, child_node: onnx.NodeProto) -> int:
104
+ for index, input_name in enumerate(child_node.input):
105
+ if input_name == node_output:
106
+ return index
107
+ return -1
108
+
109
+ @staticmethod
110
+ def tensor_shape_to_list(tensor_type) -> list[int]:
111
+ shape_list = []
112
+ for d in tensor_type.shape.dim:
113
+ if d.HasField("dim_value"):
114
+ shape_list.append(d.dim_value) # known dimension
115
+ elif d.HasField("dim_param"):
116
+ shape_list.append(d.dim_param) # unknown dimension with symbolic name
117
+ else:
118
+ shape_list.append("?") # shall not happen
119
+ return shape_list
120
+
121
+ def get_constant_input(self, node: onnx.NodeProto):
122
+ for i, inp in enumerate(node.input):
123
+ value = self.model.get_constant_value(inp)
124
+ if value is not None:
125
+ return i, value
126
+
127
+ return None, None
128
+
129
+ def find_constant_input(self, node: onnx.NodeProto, expected_value: float, delta: float = 0.000001) -> int:
130
+ i, value = self.get_constant_input(node)
131
+ if value is not None and value.size == 1 and abs(value - expected_value) < delta:
132
+ return i
133
+
134
+ return -1
135
+
136
+ def has_constant_input(self, node: onnx.NodeProto, expected_value: float, delta: float = 0.000001) -> bool:
137
+ return self.find_constant_input(node, expected_value, delta) >= 0
138
+
139
+ def is_constant_with_specified_rank(self, output_name: str, rank: int) -> bool:
140
+ value = self.model.get_constant_value(output_name)
141
+ if value is None:
142
+ return False # Not an initializer
143
+
144
+ if len(value.shape) != rank:
145
+ return False # Wrong dimensions
146
+
147
+ return True
148
+
149
+ def match_first_parent(
150
+ self,
151
+ node: onnx.NodeProto,
152
+ parent_op_type: str,
153
+ output_name_to_node: dict[str, onnx.NodeProto] | None = None,
154
+ exclude: list[onnx.NodeProto] = [], # noqa: B006
155
+ ) -> tuple[onnx.NodeProto | None, int | None]:
156
+ """
157
+ Find parent node based on constraints on op_type.
158
+
159
+ Args:
160
+ node: current node.
161
+ parent_op_type (str): constraint of parent node op_type.
162
+ output_name_to_node (dict): dictionary with output name as key, and node as value.
163
+ exclude (list): list of nodes that are excluded (not allowed to match as parent).
164
+
165
+ Returns:
166
+ parent: The matched parent node. None if not found.
167
+ index: The input index of matched parent node. None if not found.
168
+ """
169
+ if output_name_to_node is None:
170
+ output_name_to_node = self.model.output_name_to_node()
171
+
172
+ for i, inp in enumerate(node.input):
173
+ if inp in output_name_to_node:
174
+ parent = output_name_to_node[inp]
175
+ if parent.op_type == parent_op_type and parent not in exclude:
176
+ return parent, i
177
+
178
+ return None, None
179
+
180
+ def match_parent(
181
+ self,
182
+ node: onnx.NodeProto,
183
+ parent_op_type: str,
184
+ input_index: int | None = None,
185
+ output_name_to_node: dict[str, onnx.NodeProto] | None = None,
186
+ exclude: list[onnx.NodeProto] = [], # noqa: B006
187
+ return_indice: list[int] | None = None,
188
+ ) -> onnx.NodeProto | None:
189
+ """
190
+ Find parent node based on constraints on op_type and index.
191
+ When input_index is None, we will find the first parent node based on constraints,
192
+ and return_indice will be appended the corresponding input index.
193
+
194
+ Args:
195
+ node (str): current node name.
196
+ parent_op_type (str): constraint of parent node op_type.
197
+ input_index (int or None): only check the parent given input index of current node.
198
+ output_name_to_node (dict): dictionary with output name as key, and node as value.
199
+ exclude (list): list of nodes that are excluded (not allowed to match as parent).
200
+ return_indice (list): a list to append the input index when input_index is None.
201
+
202
+ Returns:
203
+ parent: The matched parent node.
204
+ """
205
+ assert node is not None
206
+ assert input_index is None or input_index >= 0
207
+
208
+ if output_name_to_node is None:
209
+ output_name_to_node = self.model.output_name_to_node()
210
+
211
+ if input_index is None:
212
+ parent, index = self.match_first_parent(node, parent_op_type, output_name_to_node, exclude)
213
+ if return_indice is not None:
214
+ return_indice.append(index)
215
+ return parent
216
+
217
+ if input_index >= len(node.input):
218
+ # Input index out of bounds.
219
+ return None
220
+
221
+ parent = self.model.get_parent(node, input_index, output_name_to_node)
222
+ if parent is not None and parent.op_type == parent_op_type and parent not in exclude:
223
+ return parent
224
+
225
+ return None
226
+
227
+ def match_parent_path(
228
+ self,
229
+ node: onnx.NodeProto,
230
+ parent_op_types: list[str],
231
+ parent_input_index: list[int] | None = None,
232
+ output_name_to_node: dict[str, onnx.NodeProto] | None = None,
233
+ return_indice: list[int] | None = None,
234
+ ) -> list[onnx.NodeProto] | None:
235
+ """
236
+ Find a sequence of input edges based on constraints on parent op_type and index.
237
+ When input_index is None, we will find the first parent node based on constraints,
238
+ and return_indice will be appended the corresponding input index.
239
+
240
+ Args:
241
+ node (str): current node name.
242
+ parent_op_types (str): constraint of parent node op_type of each input edge.
243
+ parent_input_index (list): constraint of input index of each input edge. None means no constraint.
244
+ output_name_to_node (dict): dictionary with output name as key, and node as value.
245
+ return_indice (list): a list to append the input index
246
+ When there is no constraint on input index of an edge.
247
+
248
+ Returns:
249
+ parents: a list of matched parent node.
250
+ """
251
+ if parent_input_index is not None:
252
+ assert len(parent_input_index) == len(parent_op_types)
253
+
254
+ if output_name_to_node is None:
255
+ output_name_to_node = self.model.output_name_to_node()
256
+
257
+ current_node = node
258
+ matched_parents = []
259
+ for i, op_type in enumerate(parent_op_types):
260
+ matched_parent = self.match_parent(
261
+ current_node,
262
+ op_type,
263
+ parent_input_index[i] if parent_input_index is not None else None,
264
+ output_name_to_node,
265
+ exclude=[],
266
+ return_indice=return_indice,
267
+ )
268
+ if matched_parent is None:
269
+ return None
270
+
271
+ matched_parents.append(matched_parent)
272
+ current_node = matched_parent
273
+
274
+ return matched_parents
275
+
276
+ def match_parent_paths(
277
+ self,
278
+ node: onnx.NodeProto,
279
+ paths: list[tuple[list[str], list[int]]],
280
+ output_name_to_node: dict[str, onnx.NodeProto],
281
+ ) -> tuple[int, list[onnx.NodeProto] | None, list[int] | None]:
282
+ """
283
+ Find a matching parent path to the given node.
284
+ """
285
+ for i, path in enumerate(paths):
286
+ return_indice = []
287
+ matched = self.match_parent_path(node, path[0], path[1], output_name_to_node, return_indice)
288
+ if matched:
289
+ return i, matched, return_indice
290
+ return -1, None, None
291
+
292
+ def find_first_child_by_type(
293
+ self,
294
+ node: onnx.NodeProto,
295
+ child_type: str,
296
+ input_name_to_nodes: dict[str, list[onnx.NodeProto]] | None = None,
297
+ recursive: bool = True,
298
+ ) -> onnx.NodeProto | None:
299
+ children = self.model.get_children(node, input_name_to_nodes)
300
+ dq = deque(children)
301
+ while len(dq) > 0:
302
+ current_node = dq.pop()
303
+ if current_node.op_type == child_type:
304
+ return current_node
305
+
306
+ if recursive:
307
+ children = self.model.get_children(current_node, input_name_to_nodes)
308
+ for child in children:
309
+ dq.appendleft(child)
310
+
311
+ return None
ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/quantization/fusions/fusion_gelu.py ADDED
@@ -0,0 +1,272 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -------------------------------------------------------------------------
2
+ # Copyright (c) Microsoft Corporation. All rights reserved.
3
+ # Licensed under the MIT License. See License.txt in the project root for
4
+ # license information.
5
+ # --------------------------------------------------------------------------
6
+ from __future__ import annotations
7
+
8
+ import onnx
9
+
10
+ from ..onnx_model import ONNXModel
11
+ from .fusion import Fusion
12
+
13
+
14
+ class FusionGelu(Fusion):
15
+ def __init__(self, model: ONNXModel):
16
+ super().__init__(model, "Gelu", "Erf")
17
+
18
+ def fuse(
19
+ self,
20
+ erf_node: onnx.NodeProto,
21
+ input_name_to_nodes: dict[str, list[onnx.NodeProto]],
22
+ output_name_to_node: dict[str, onnx.NodeProto],
23
+ ):
24
+ """
25
+ Interface function that tries to fuse a node sequence containing an Erf node into a single
26
+ Gelu node.
27
+ """
28
+ if (
29
+ self.fuse_1(erf_node, input_name_to_nodes, output_name_to_node)
30
+ or self.fuse_2(erf_node, input_name_to_nodes, output_name_to_node)
31
+ or self.fuse_3(erf_node, input_name_to_nodes, output_name_to_node)
32
+ ):
33
+ self.model.set_opset_import("com.microsoft", 1)
34
+
35
+ def fuse_1(
36
+ self,
37
+ erf_node: onnx.NodeProto,
38
+ input_name_to_nodes: dict[str, list[onnx.NodeProto]],
39
+ output_name_to_node: dict[str, onnx.NodeProto],
40
+ ) -> bool:
41
+ """
42
+ This pattern is from PyTorch model
43
+ Fuse Gelu with Erf into one node:
44
+ Pattern 1:
45
+ +-------Mul(0.5)---------------------+
46
+ | |
47
+ | v
48
+ [root] --> Div -----> Erf --> Add --> Mul -->
49
+ (B=1.4142...) (1)
50
+
51
+ Pattern 2:
52
+ +------------------------------------+
53
+ | |
54
+ | v
55
+ [root] --> Div -----> Erf --> Add --> Mul -->Mul -->
56
+ (B=1.4142...) (1) (0.5)
57
+
58
+ Note that constant input for Add and Mul could be first or second input: like either A=0.5 or B=0.5 is fine.
59
+ """
60
+ if erf_node.output[0] not in input_name_to_nodes:
61
+ return False
62
+ children = input_name_to_nodes[erf_node.output[0]]
63
+ if len(children) != 1 or children[0].op_type != "Add":
64
+ return False
65
+ add_after_erf = children[0]
66
+
67
+ if not self.has_constant_input(add_after_erf, 1):
68
+ return False
69
+
70
+ if add_after_erf.output[0] not in input_name_to_nodes:
71
+ return False
72
+
73
+ children = input_name_to_nodes[add_after_erf.output[0]]
74
+ if len(children) != 1 or children[0].op_type != "Mul":
75
+ return False
76
+
77
+ mul_after_erf = children[0]
78
+
79
+ div = self.match_parent(erf_node, "Div", 0, output_name_to_node)
80
+ if div is None:
81
+ return False
82
+
83
+ if self.find_constant_input(div, 1.4142, delta=0.001) != 1:
84
+ return False
85
+
86
+ subgraph_input = div.input[0]
87
+
88
+ another = 1 if mul_after_erf.input[0] == add_after_erf.output[0] else 0
89
+ if subgraph_input == mul_after_erf.input[another]: # pattern 2
90
+ children = input_name_to_nodes[mul_after_erf.output[0]]
91
+ if len(children) != 1 or children[0].op_type != "Mul":
92
+ return False
93
+ mul_half = children[0]
94
+ if not self.has_constant_input(mul_half, 0.5):
95
+ return False
96
+ subgraph_output = mul_half.output[0]
97
+ else: # pattern 1
98
+ mul_half = self.match_parent(mul_after_erf, "Mul", another, output_name_to_node)
99
+ if mul_half is None:
100
+ return False
101
+
102
+ if not self.has_constant_input(mul_half, 0.5):
103
+ return False
104
+
105
+ if subgraph_input not in mul_half.input:
106
+ return False
107
+
108
+ subgraph_output = mul_after_erf.output[0]
109
+
110
+ subgraph_nodes = [div, erf_node, add_after_erf, mul_after_erf, mul_half]
111
+ if not self.is_safe_to_fuse_nodes(subgraph_nodes, [subgraph_output], input_name_to_nodes, output_name_to_node):
112
+ return False
113
+
114
+ self.nodes_to_remove.extend(subgraph_nodes)
115
+ fused_node = onnx.helper.make_node(
116
+ "Gelu", name=self.create_unique_node_name(), inputs=[subgraph_input], outputs=[subgraph_output]
117
+ )
118
+ fused_node.domain = "com.microsoft"
119
+ self.nodes_to_add.append(fused_node)
120
+ return True
121
+
122
+ def fuse_2(
123
+ self,
124
+ erf_node: onnx.NodeProto,
125
+ input_name_to_nodes: dict[str, list[onnx.NodeProto]],
126
+ output_name_to_node: dict[str, onnx.NodeProto],
127
+ ) -> bool:
128
+ """
129
+ This pattern is from Keras model
130
+ Fuse Gelu with Erf into one node:
131
+ +------------------------------------------+
132
+ | |
133
+ | v
134
+ [root] --> Div -----> Erf --> Add --> Mul -->Mul
135
+ (B=1.4142...) (A=1) (A=0.5)
136
+
137
+ Note that constant input for Add and Mul could be first or second input: like either A=0.5 or B=0.5 is fine.
138
+ """
139
+ if erf_node.output[0] not in input_name_to_nodes:
140
+ return False
141
+ children = input_name_to_nodes[erf_node.output[0]]
142
+ if len(children) != 1 or children[0].op_type != "Add":
143
+ return False
144
+ add_after_erf = children[0]
145
+
146
+ if not self.has_constant_input(add_after_erf, 1):
147
+ return False
148
+
149
+ if add_after_erf.output[0] not in input_name_to_nodes:
150
+ return False
151
+ children = input_name_to_nodes[add_after_erf.output[0]]
152
+ if len(children) != 1 or children[0].op_type != "Mul":
153
+ return False
154
+ mul_after_erf = children[0]
155
+
156
+ if not self.has_constant_input(mul_after_erf, 0.5):
157
+ return False
158
+
159
+ if mul_after_erf.output[0] not in input_name_to_nodes:
160
+ return False
161
+ children = input_name_to_nodes[mul_after_erf.output[0]]
162
+ if len(children) != 1 or children[0].op_type != "Mul":
163
+ return False
164
+ mul = children[0]
165
+
166
+ div = self.match_parent(erf_node, "Div", 0, output_name_to_node)
167
+ if div is None:
168
+ return False
169
+
170
+ sqrt_node = None
171
+ if self.find_constant_input(div, 1.4142, delta=0.001) != 1:
172
+ sqrt_node = self.match_parent(div, "Sqrt", 1, output_name_to_node)
173
+ if sqrt_node is None:
174
+ return False
175
+ if not self.has_constant_input(sqrt_node, 2.0):
176
+ return False
177
+
178
+ subgraph_input = div.input[0]
179
+
180
+ if subgraph_input not in mul.input:
181
+ return False
182
+
183
+ subgraph_nodes = [div, erf_node, add_after_erf, mul_after_erf, mul]
184
+ if sqrt_node:
185
+ subgraph_nodes.append(sqrt_node)
186
+
187
+ if not self.is_safe_to_fuse_nodes(subgraph_nodes, [mul.output[0]], input_name_to_nodes, output_name_to_node):
188
+ return False
189
+
190
+ self.nodes_to_remove.extend(subgraph_nodes)
191
+ fused_node = onnx.helper.make_node(
192
+ "Gelu", name=self.create_unique_node_name(), inputs=[subgraph_input], outputs=[mul.output[0]]
193
+ )
194
+ fused_node.domain = "com.microsoft"
195
+ self.nodes_to_add.append(fused_node)
196
+ return True
197
+
198
+ def fuse_3(
199
+ self,
200
+ erf_node: onnx.NodeProto,
201
+ input_name_to_nodes: dict[str, list[onnx.NodeProto]],
202
+ output_name_to_node: dict[str, onnx.NodeProto],
203
+ ) -> bool:
204
+ """
205
+ This pattern is from TensorFlow model
206
+ Fuse Gelu with Erf into one node:
207
+ +----------------------------------------------+
208
+ | |
209
+ | v
210
+ [root] --> Mul -----> Erf --> Add --> Mul -->Mul
211
+ (A=0.7071067690849304) (B=1) (B=0.5)
212
+
213
+ Note that constant input for Add and Mul could be first or second input: like either A=0.5 or B=0.5 is fine.
214
+ """
215
+
216
+ if erf_node.output[0] not in input_name_to_nodes:
217
+ return False
218
+ children = input_name_to_nodes[erf_node.output[0]]
219
+ if len(children) != 1 or children[0].op_type != "Add":
220
+ return False
221
+ add_after_erf = children[0]
222
+
223
+ if not self.has_constant_input(add_after_erf, 1):
224
+ return False
225
+
226
+ if add_after_erf.output[0] not in input_name_to_nodes:
227
+ return False
228
+ children = input_name_to_nodes[add_after_erf.output[0]]
229
+ if len(children) != 1 or children[0].op_type != "Mul":
230
+ return False
231
+ mul_half = children[0]
232
+
233
+ if not self.has_constant_input(mul_half, 0.5):
234
+ return False
235
+
236
+ first_mul = self.match_parent(erf_node, "Mul", 0, output_name_to_node)
237
+ if first_mul is None:
238
+ return False
239
+
240
+ i = self.find_constant_input(first_mul, 0.7071067690849304, delta=0.001)
241
+ if i < 0:
242
+ return False
243
+
244
+ root_input_index = 1 - i
245
+ subgraph_input = first_mul.input[root_input_index]
246
+
247
+ if mul_half.output[0] not in input_name_to_nodes:
248
+ return False
249
+ children = input_name_to_nodes[mul_half.output[0]]
250
+ if len(children) != 1 or children[0].op_type != "Mul":
251
+ return False
252
+ last_mul = children[0]
253
+
254
+ if not (last_mul.input[0] == subgraph_input or last_mul.input[1] == subgraph_input):
255
+ return False
256
+
257
+ subgraph_nodes = [first_mul, erf_node, add_after_erf, mul_half, last_mul]
258
+ if not self.is_safe_to_fuse_nodes(
259
+ subgraph_nodes,
260
+ [last_mul.output[0]],
261
+ input_name_to_nodes,
262
+ output_name_to_node,
263
+ ):
264
+ return False
265
+
266
+ self.nodes_to_remove.extend(subgraph_nodes)
267
+ fused_node = onnx.helper.make_node(
268
+ "Gelu", name=self.create_unique_node_name(), inputs=[subgraph_input], outputs=[last_mul.output[0]]
269
+ )
270
+ fused_node.domain = "com.microsoft"
271
+ self.nodes_to_add.append(fused_node)
272
+ return True
ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/quantization/fusions/fusion_layernorm.py ADDED
@@ -0,0 +1,146 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -------------------------------------------------------------------------
2
+ # Copyright (c) Microsoft Corporation. All rights reserved.
3
+ # Licensed under the MIT License. See License.txt in the project root for
4
+ # license information.
5
+ # --------------------------------------------------------------------------
6
+ from __future__ import annotations
7
+
8
+ import onnx
9
+
10
+ from ..onnx_model import ONNXModel
11
+ from .fusion import Fusion
12
+
13
+
14
+ class FusionLayerNormalization(Fusion):
15
+ def __init__(self, model: ONNXModel):
16
+ super().__init__(model, "LayerNormalization", "ReduceMean")
17
+
18
+ def fuse(
19
+ self,
20
+ reduce_mean_node: onnx.NodeProto,
21
+ input_name_to_nodes: dict[str, list[onnx.NodeProto]],
22
+ output_name_to_node: dict[str, onnx.NodeProto],
23
+ ):
24
+ """
25
+ Interface function that tries to fuse a node sequence containing a ReduceMean node into a single
26
+ LayerNormalization node.
27
+
28
+ +----------------------+
29
+ | |
30
+ | v
31
+ [Root] --> ReduceMean --> Sub --> Pow --> ReduceMean --> Add --> Sqrt --> Div --> Mul --> Add
32
+ (axis=2 or -1) | (Y=2) (axis=2 or -1) (E-6 or E-12 or 0) ^
33
+ | |
34
+ +-------------------------------------------------+
35
+
36
+ Or, using Mul instead of Pow:
37
+
38
+ +----------------------+
39
+ | |
40
+ | v
41
+ [Root] --> ReduceMean --> Sub --> Mul --> ReduceMean --> Add --> Sqrt --> Div --> Mul --> Add
42
+ (axis=2 or -1) | (in0=in1) (axis=2 or -1) (E-6 or E-12 or 0) ^
43
+ | |
44
+ +-------------------------------------------------+
45
+
46
+ It also handles cases of duplicated sub nodes exported from older version of PyTorch:
47
+
48
+ +----------------------+
49
+ | v
50
+ | +-------> Sub-----------------------------------------------+
51
+ | | |
52
+ | | v
53
+ [Root] --> ReduceMean --> Sub --> (Pow or Mul) --> ReduceMean --> Add --> Sqrt --> Div --> Mul --> Add
54
+ | ^
55
+ | |
56
+ +----------------------+
57
+ """
58
+ children = self.model.get_children(reduce_mean_node, input_name_to_nodes)
59
+ if len(children) == 0 or len(children) > 2:
60
+ return
61
+
62
+ root_input = reduce_mean_node.input[0]
63
+
64
+ if children[0].op_type != "Sub" or children[0].input[0] != root_input:
65
+ return
66
+
67
+ if len(children) == 2:
68
+ if children[1].op_type != "Sub" or children[1].input[0] != root_input:
69
+ return
70
+
71
+ div_node = None
72
+ for child in children:
73
+ div_node = self.find_first_child_by_type(child, "Div", input_name_to_nodes, recursive=False)
74
+ if div_node is not None:
75
+ break
76
+ if div_node is None:
77
+ return
78
+
79
+ path_id, parent_nodes, _ = self.match_parent_paths(
80
+ div_node,
81
+ [
82
+ (["Sqrt", "Add", "ReduceMean", "Pow", "Sub"], [1, 0, 0, 0, 0]),
83
+ (["Sqrt", "Add", "ReduceMean", "Pow", "Cast", "Sub"], [1, 0, 0, 0, 0, 0]),
84
+ (["Sqrt", "Add", "ReduceMean", "Mul", "Sub"], [1, 0, 0, 0, 0]),
85
+ (["Sqrt", "Add", "ReduceMean", "Mul", "Cast", "Sub"], [1, 0, 0, 0, 0, 0]),
86
+ ],
87
+ output_name_to_node,
88
+ )
89
+ if path_id < 0:
90
+ return
91
+
92
+ sub_node = parent_nodes[-1]
93
+ if sub_node not in children:
94
+ return
95
+
96
+ second_add_node = parent_nodes[1]
97
+ i, add_weight = self.get_constant_input(second_add_node)
98
+ if add_weight is None or add_weight <= 0 or add_weight > 1.0e-4:
99
+ # Skip fusion since epsilon value is not expected.
100
+ return
101
+
102
+ pow_or_mul_node = parent_nodes[3]
103
+ if pow_or_mul_node.op_type == "Pow" and self.find_constant_input(pow_or_mul_node, 2.0) != 1:
104
+ return
105
+ elif pow_or_mul_node.op_type == "Mul" and pow_or_mul_node.input[0] != pow_or_mul_node.input[1]:
106
+ return
107
+
108
+ mul_node = input_name_to_nodes[div_node.output[0]][0]
109
+ if mul_node.op_type != "Mul":
110
+ return
111
+
112
+ last_add_node = input_name_to_nodes[mul_node.output[0]][0]
113
+ if last_add_node.op_type != "Add":
114
+ return
115
+
116
+ subgraph_nodes = [reduce_mean_node]
117
+ subgraph_nodes.extend(children)
118
+ subgraph_nodes.extend(parent_nodes[:-1])
119
+
120
+ subgraph_nodes.extend([last_add_node, mul_node, div_node])
121
+ if not self.is_safe_to_fuse_nodes(
122
+ subgraph_nodes,
123
+ last_add_node.output,
124
+ input_name_to_nodes,
125
+ output_name_to_node,
126
+ ):
127
+ return
128
+
129
+ weight_input = mul_node.input[1 - self.input_index(div_node.output[0], mul_node)]
130
+ if not self.is_constant_with_specified_rank(weight_input, 1):
131
+ return
132
+
133
+ bias_input = last_add_node.input[1 - self.input_index(mul_node.output[0], last_add_node)]
134
+ if not self.is_constant_with_specified_rank(bias_input, 1):
135
+ return
136
+
137
+ self.nodes_to_remove.extend(subgraph_nodes)
138
+
139
+ normalize_node = onnx.helper.make_node(
140
+ "LayerNormalization",
141
+ name=self.create_unique_node_name(),
142
+ inputs=[reduce_mean_node.input[0], weight_input, bias_input],
143
+ outputs=[last_add_node.output[0]],
144
+ )
145
+ normalize_node.attribute.extend([onnx.helper.make_attribute("epsilon", float(add_weight))])
146
+ self.nodes_to_add.append(normalize_node)
ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/quantization/fusions/replace_upsample_with_resize.py ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -------------------------------------------------------------------------
2
+ # Copyright (c) Microsoft Corporation. All rights reserved.
3
+ # Licensed under the MIT License. See License.txt in the project root for
4
+ # license information.
5
+ # --------------------------------------------------------------------------
6
+ from __future__ import annotations
7
+
8
+ import numpy as np
9
+ import onnx
10
+
11
+ from ..onnx_model import ONNXModel
12
+ from .fusion import Fusion
13
+
14
+
15
+ class ReplaceUpsampleWithResize(Fusion):
16
+ """Replace Upsample with Resize."""
17
+
18
+ def __init__(self, model: ONNXModel, opset):
19
+ """Initialize."""
20
+ super().__init__(model, "Resize", "Upsample")
21
+ self.opset = opset
22
+
23
+ def fuse(
24
+ self,
25
+ node: onnx.NodeProto,
26
+ input_name_to_nodes: dict[str, list[onnx.NodeProto]],
27
+ output_name_to_node: dict[str, onnx.NodeProto],
28
+ ):
29
+ """Replace Upsample with Resize."""
30
+ mode = None
31
+ for attr in node.attribute:
32
+ if attr.name == "mode":
33
+ mode = attr.s.decode("utf-8")
34
+ break
35
+
36
+ scales_input = None
37
+ if self.opset > 7:
38
+ scales_input = node.input[1] if len(node.input) > 1 else ""
39
+ resize_inputs = [node.input[0], node.name + "_roi", scales_input]
40
+ else:
41
+ if self.opset == 7:
42
+ for attr in node.attribute:
43
+ if attr.name == "scales":
44
+ scales_input = attr.floats
45
+ break
46
+
47
+ scales_input = np.array(list(scales_input), np.float32)
48
+ else:
49
+ h_scale = 1
50
+ w_scale = 1
51
+ for attr in node.attribute:
52
+ if attr.name == "height_scale":
53
+ h_scale = attr.float
54
+ elif attr.name == "width_scale":
55
+ w_scale = attr.float
56
+
57
+ scales_input = np.array([1, 1, h_scale, w_scale], np.float32)
58
+
59
+ scales_tensor = onnx.helper.make_tensor(
60
+ name=node.name + "_scales",
61
+ data_type=onnx.TensorProto.FLOAT,
62
+ dims=scales_input.shape,
63
+ vals=scales_input.flatten().tolist(),
64
+ )
65
+
66
+ scales_node = onnx.helper.make_node(
67
+ "Constant", inputs=[], outputs=[node.name + "_scales"], value=scales_tensor
68
+ )
69
+
70
+ self.nodes_to_add.append(scales_node)
71
+
72
+ resize_inputs = [node.input[0], node.name + "_roi", node.name + "_scales"]
73
+
74
+ roi_tensor = onnx.helper.make_tensor(
75
+ name=node.name + "_roi",
76
+ data_type=onnx.TensorProto.FLOAT,
77
+ dims=(len(scales_input) * 2,),
78
+ vals=[0] * len(scales_input) + [1] * len(scales_input),
79
+ )
80
+
81
+ roi_node = onnx.helper.make_node("Constant", inputs=[], outputs=[node.name + "_roi"], value=roi_tensor)
82
+
83
+ resize_node = onnx.helper.make_node(
84
+ op_type="Resize", inputs=resize_inputs, outputs=node.output, mode=mode, nearest_mode="floor"
85
+ )
86
+
87
+ self.nodes_to_remove.append(node)
88
+ self.nodes_to_add.append(roi_node)
89
+ self.nodes_to_add.append(resize_node)
90
+
91
+ def apply(self) -> bool:
92
+ """Apply."""
93
+ if super().apply():
94
+ self.model.topological_sort()
95
+ return True
96
+ return False
ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/quantization/matmul_bnb4_quantizer.py ADDED
@@ -0,0 +1,239 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -------------------------------------------------------------------------
2
+ # Copyright (c) Microsoft Corporation. All rights reserved.
3
+ # Licensed under the MIT License. See License.txt in the project root for
4
+ # license information.
5
+ # --------------------------------------------------------------------------
6
+
7
+ import argparse
8
+ import logging
9
+ import os
10
+
11
+ import numpy as np
12
+ import numpy.typing as npt
13
+ import onnx
14
+ from onnx.onnx_pb import GraphProto, ModelProto, NodeProto, TensorProto
15
+
16
+ from onnxruntime.capi._pybind_state import quantize_matmul_bnb4
17
+
18
+ from .onnx_model import ONNXModel
19
+ from .quant_utils import attribute_to_kwarg
20
+
21
+ logger = logging.getLogger(__name__)
22
+
23
+
24
+ class MatMulBnb4Quantizer:
25
+ """Perform 4b quantization of constant MatMul weights using FP4 or NF4 data type"""
26
+
27
+ ##################
28
+ # quantization types, must be consistent with native code type
29
+ # Bnb_DataType_t defined in blockwise_quant_block_bnb4.h
30
+
31
+ # 4b floating point with bias of 3
32
+ FP4 = 0
33
+
34
+ # 4b NormalFloat
35
+ NF4 = 1
36
+
37
+ def __init__(self, model: ModelProto, quant_type: int, block_size: int, nodes_to_exclude=None):
38
+ nodes_to_exclude = nodes_to_exclude or []
39
+ assert quant_type in [MatMulBnb4Quantizer.FP4, MatMulBnb4Quantizer.NF4]
40
+ self.model = ONNXModel(model)
41
+ self.quant_type = quant_type
42
+ self.block_size = block_size
43
+ self.nodes_to_exclude = set(nodes_to_exclude)
44
+
45
+ @staticmethod
46
+ def __get_initializer(name, graph_path: list[GraphProto]) -> tuple[TensorProto, GraphProto]:
47
+ for gid in range(len(graph_path) - 1, -1, -1):
48
+ graph = graph_path[gid]
49
+ for tensor in graph.initializer:
50
+ if tensor.name == name:
51
+ return tensor, graph
52
+ return None, None
53
+
54
+ def bnb4_block_quant(self, fpweight: npt.ArrayLike) -> np.ndarray:
55
+ """4b quantize fp32/fp16 weight"""
56
+
57
+ if len(fpweight.shape) != 2:
58
+ raise ValueError("Current bnb4 block quantization only supports 2D tensors!")
59
+ # need to copy since the transposed weight still has the original memory layout
60
+ # Linear4bit quantizes its weight data which is the transposed weight
61
+ fpweight_t = fpweight.transpose().copy()
62
+
63
+ rows, cols = fpweight.shape
64
+ numel = rows * cols
65
+ block_size = self.block_size
66
+ num_blocks = (numel + block_size - 1) // block_size
67
+ quantized_numel = (numel + 1) // 2
68
+
69
+ packed = np.zeros(quantized_numel, dtype="uint8")
70
+ absmax = np.zeros(num_blocks, dtype=fpweight.dtype)
71
+ # block wise quantization, fpweight_t is flattened and divided into blocks
72
+ quantize_matmul_bnb4(packed, fpweight_t, absmax, block_size, self.quant_type, cols, rows)
73
+
74
+ return (packed, absmax)
75
+
76
+ def _bnb4_matmul_node_weight(self, node: NodeProto, graph_stack: list[GraphProto]) -> NodeProto:
77
+ """If the node is MatMul with fp32 const weight, quantize the weight with int4, and return the new node"""
78
+
79
+ if node.op_type != "MatMul":
80
+ return node # only care about MatMul for now
81
+
82
+ logger.debug(f"start to quantize {node.name} ...")
83
+ if node.name in self.nodes_to_exclude:
84
+ logger.debug(f"exclude to quantize {node.name} as specified by nodes_to_exclude...")
85
+ return node
86
+
87
+ inputB = node.input[1] # noqa: N806
88
+ B, Bs_graph = MatMulBnb4Quantizer.__get_initializer(inputB, graph_stack) # noqa: N806
89
+ if B is None:
90
+ logger.debug("MatMul doesn't have const weight. Skip to quantize")
91
+ return node # only care about constant weight
92
+
93
+ B_array = onnx.numpy_helper.to_array(B) # noqa: N806
94
+ if len(B_array.shape) != 2:
95
+ logger.debug("MatMul weight is not 2D. Skip to quantize")
96
+ return node # can only process 2-D matrix
97
+
98
+ packed, absmax = self.bnb4_block_quant(B_array)
99
+ B_quant = onnx.numpy_helper.from_array(packed) # noqa: N806
100
+ B_quant.name = B.name + "_Bnb4"
101
+ for input in Bs_graph.input:
102
+ if input.name == inputB:
103
+ Bs_graph.input.remove(input)
104
+ break
105
+
106
+ absmax_tensor = onnx.numpy_helper.from_array(absmax)
107
+ absmax_tensor.name = B.name + "_absmax"
108
+
109
+ Bs_graph.initializer.extend([B_quant, absmax_tensor])
110
+
111
+ kwargs = {}
112
+ rows, cols = B_array.shape
113
+ kwargs["K"] = rows
114
+ kwargs["N"] = cols
115
+ kwargs["block_size"] = self.block_size
116
+ kwargs["quant_type"] = self.quant_type
117
+
118
+ matmul_bnb4_node = onnx.helper.make_node(
119
+ "MatMulBnb4",
120
+ inputs=[node.input[0], B_quant.name, absmax_tensor.name],
121
+ outputs=[node.output[0]],
122
+ name=node.name + "_Bnb4" if node.name else "",
123
+ domain="com.microsoft",
124
+ **kwargs,
125
+ )
126
+
127
+ logger.debug(f"complete quantization of {node.name} ...")
128
+
129
+ return matmul_bnb4_node
130
+
131
+ def _process_subgraph(self, graph_stack: list[GraphProto]):
132
+ new_nodes = []
133
+ graph = graph_stack[-1]
134
+
135
+ for node in graph.node:
136
+ graph_attrs = [
137
+ attr
138
+ for attr in node.attribute
139
+ if attr.type == onnx.AttributeProto.GRAPH or attr.type == onnx.AttributeProto.GRAPHS
140
+ ]
141
+ if graph_attrs:
142
+ kwargs = {}
143
+ for attr in node.attribute:
144
+ if attr.type == onnx.AttributeProto.GRAPH:
145
+ # recursive call to take care of sub-graph
146
+ graph_stack.append(attr.g)
147
+ kv = {attr.name: self._process_subgraph(graph_stack)}
148
+ elif attr.type == onnx.AttributeProto.GRAPHS:
149
+ value = []
150
+ for subgraph in attr.graphs:
151
+ # recursive call to take care of sub-graph
152
+ graph_stack.append(subgraph)
153
+ value.extend([self._process_subgraph(graph_stack)])
154
+ kv = {attr.name: value}
155
+ else:
156
+ kv = attribute_to_kwarg(attr)
157
+ kwargs.update(kv)
158
+ node = onnx.helper.make_node( # noqa: PLW2901
159
+ node.op_type, node.input, node.output, name=node.name, **kwargs
160
+ )
161
+
162
+ new_nodes.append(self._bnb4_matmul_node_weight(node, graph_stack))
163
+
164
+ graph.ClearField("node")
165
+ graph.node.extend(new_nodes)
166
+ graph_stack.pop()
167
+ return graph
168
+
169
+ def process(self):
170
+ # use a stack to keep track of sub-graphs
171
+ graph_stack = [self.model.graph()]
172
+ opset_import = self.model.opset_import()
173
+
174
+ has_ms_domain = False
175
+ for opset in opset_import:
176
+ if opset.domain == "com.microsoft":
177
+ has_ms_domain = True
178
+ if not has_ms_domain:
179
+ opset_import.extend([onnx.helper.make_opsetid("com.microsoft", 1)])
180
+
181
+ self._process_subgraph(graph_stack)
182
+ self.model.clean_initializers()
183
+
184
+
185
+ def parse_args():
186
+ parser = argparse.ArgumentParser(
187
+ description="""Blockwise FP4/NF4 quantization for MatMul 2D weight matrices.
188
+
189
+ A weight matrix is partitioned into blocks, where each block is a contiguous
190
+ subset inside the flattened transposed weight matrix. Each block is quantized
191
+ into a set of 4b integers with an absolute value scaling factor.
192
+ """
193
+ )
194
+
195
+ parser.add_argument("--input_model", required=True, help="Path to the input model file")
196
+ parser.add_argument("--output_model", required=True, help="Path to the output model file")
197
+ parser.add_argument(
198
+ "--quant_type",
199
+ required=False,
200
+ default=1,
201
+ choices=[MatMulBnb4Quantizer.FP4, MatMulBnb4Quantizer.NF4],
202
+ help="Quantization data type. 0: FP4, 1: NF4",
203
+ )
204
+ parser.add_argument(
205
+ "--block_size",
206
+ required=False,
207
+ default=64,
208
+ help="Block size for blockwise quantization. Note: bnb.nn.Linear4bit only uses block_size=64",
209
+ )
210
+ parser.add_argument("-v", "--verbose", required=False, action="store_true")
211
+ parser.set_defaults(verbose=False)
212
+ parser.add_argument(
213
+ "--nodes_to_exclude",
214
+ nargs="+",
215
+ type=str,
216
+ required=False,
217
+ default=[],
218
+ help="Specify the nodes to be excluded from quantization with node names",
219
+ )
220
+
221
+ return parser.parse_args()
222
+
223
+
224
+ if __name__ == "__main__":
225
+ args = parse_args()
226
+ if args.verbose:
227
+ logger.setLevel(logging.DEBUG)
228
+
229
+ input_model_path = args.input_model
230
+ output_model_path = args.output_model
231
+
232
+ if os.path.exists(output_model_path):
233
+ logger.error(f"file {output_model_path} already exists")
234
+ raise Exception(f"file {output_model_path} already exists")
235
+
236
+ model = onnx.load(input_model_path)
237
+ quant = MatMulBnb4Quantizer(model, args.quant_type, args.block_size, nodes_to_exclude=args.nodes_to_exclude)
238
+ quant.process()
239
+ quant.model.save_model_to_file(output_model_path, True)
ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/quantization/matmul_nbits_quantizer.py ADDED
@@ -0,0 +1,1874 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -------------------------------------------------------------------------
2
+ # Copyright (c) Microsoft Corporation. All rights reserved.
3
+ # Licensed under the MIT License. See License.txt in the project root for
4
+ # license information.
5
+ # --------------------------------------------------------------------------
6
+
7
+ from __future__ import annotations
8
+
9
+ import argparse
10
+ import copy
11
+ import logging
12
+ import os
13
+
14
+ import ml_dtypes
15
+ import numpy as np
16
+ import numpy.typing as npt
17
+ import onnx
18
+ import onnx_ir as ir
19
+ from onnx.onnx_pb import GraphProto, ModelProto, NodeProto, TensorProto
20
+
21
+ from onnxruntime.capi._pybind_state import (
22
+ quantize_matmul_2bits,
23
+ quantize_matmul_4bits,
24
+ quantize_matmul_8bits,
25
+ quantize_qdq_matmul_4bits,
26
+ )
27
+
28
+ from .calibrate import CalibrationDataReader
29
+ from .neural_compressor import gptq_quantize, rtn_quantize
30
+ from .onnx_model import ONNXModel
31
+ from .quant_utils import QuantFormat, attribute_to_kwarg
32
+
33
+ logging.basicConfig(format="%(asctime)s %(name)s [%(levelname)s] - %(message)s", level=logging.INFO)
34
+ logger = logging.getLogger(__name__)
35
+
36
+
37
+ class WeightOnlyQuantConfig:
38
+ def __init__(
39
+ self,
40
+ algorithm: str,
41
+ quant_format: QuantFormat,
42
+ op_types_to_quantize: tuple[str, ...] | None = None,
43
+ quant_axes: tuple[tuple[str, int], ...] | None = None,
44
+ customized_weight_config: dict | None = None,
45
+ ):
46
+ """This is the Base class for Weight Only blockwise quantization Configuration.
47
+
48
+ Args:
49
+ algorithm:
50
+ weight only quantize algorithm name.
51
+ quant_format: QuantFormat{QOperator, QDQ}.
52
+ QOperator format quantizes the model with quantized operators directly.
53
+ QDQ format quantize the model by inserting QuantizeLinear/DeQuantizeLinear on the tensor.
54
+ op_types_to_quantize (optional):
55
+ set of operator types to quantize. Default {MatMul}
56
+ quant_axes (dict[str, int], optional):
57
+ op:axis, which axis to quantize for an op. Default {MatMul: 0, Gather: 1}
58
+ customized_weight_config:
59
+ customized weight config for nodes if needed. It is dictionary with node name as key,
60
+ and the value is a dict of customized config.
61
+ """
62
+ self.algorithm = algorithm
63
+ self.quant_format = quant_format
64
+ self.op_types_to_quantize = set(op_types_to_quantize) if op_types_to_quantize else {"MatMul"}
65
+ self.quant_axes = dict(quant_axes) if quant_axes else {"MatMul": 0, "Gather": 1}
66
+ self.customized_weight_config = customized_weight_config
67
+
68
+
69
+ class RTNWeightOnlyQuantConfig(WeightOnlyQuantConfig):
70
+ def __init__(
71
+ self,
72
+ ratios=None,
73
+ quant_format=QuantFormat.QOperator,
74
+ op_types_to_quantize: tuple[str, ...] | None = None,
75
+ customized_weight_config: dict | None = None,
76
+ ):
77
+ """
78
+ This is a class for round-to-nearest (RTN) algorithm Weight Only Quant Configuration.
79
+ RTN is the most straightforward way to quantize weight using scale maps.
80
+
81
+ Args:
82
+ ratios:
83
+ percentile of clip. Defaults to {}.
84
+ quant_format (QuantFormat{QOperator, QDQ}, optional):
85
+ QOperator format quantizes the model with quantized operators directly.
86
+ QDQ format quantize the model by inserting QuantizeLinear/DeQuantizeLinear on the tensor.
87
+ Defaults to QuantFormat.QOperator.
88
+ op_types_to_quantize (optional):
89
+ set of operator types to quantize.
90
+ customized_weight_config:
91
+ customized weight config for nodes if needed. It is dictionary with node name as key,
92
+ and the value is a dict of customized config.
93
+ """
94
+ assert quant_format == QuantFormat.QOperator, "RTN only supports QOperator format"
95
+
96
+ if ratios is None:
97
+ ratios = {}
98
+ super().__init__(
99
+ algorithm="RTN",
100
+ quant_format=quant_format,
101
+ op_types_to_quantize=op_types_to_quantize,
102
+ customized_weight_config=customized_weight_config,
103
+ )
104
+ self.ratios = ratios
105
+
106
+
107
+ class KQuantWeightOnlyQuantConfig(WeightOnlyQuantConfig):
108
+ def __init__(
109
+ self,
110
+ ratios=None,
111
+ quant_format=QuantFormat.QOperator,
112
+ op_types_to_quantize: tuple[str, ...] | None = None,
113
+ customized_weight_config: dict | None = None,
114
+ ):
115
+ """
116
+ This is a class for k-quant algorithm Weight Only Quant Configuration.
117
+
118
+ Args:
119
+ ratios:
120
+ percentile of clip. Defaults to {}.
121
+ quant_format (QuantFormat{QOperator, QDQ}, optional):
122
+ QOperator format quantizes the model with quantized operators directly.
123
+ QDQ format quantize the model by inserting QuantizeLinear/DeQuantizeLinear on the tensor.
124
+ Defaults to QuantFormat.QOperator.
125
+ op_types_to_quantize (optional):
126
+ set of operator types to quantize.
127
+ """
128
+ assert quant_format == QuantFormat.QOperator, "k-quant only supports QOperator format"
129
+
130
+ if ratios is None:
131
+ ratios = {}
132
+ super().__init__(
133
+ algorithm="k_quant",
134
+ quant_format=quant_format,
135
+ op_types_to_quantize=op_types_to_quantize,
136
+ customized_weight_config=customized_weight_config,
137
+ )
138
+ self.ratios = ratios
139
+
140
+
141
+ class GPTQWeightOnlyQuantConfig(WeightOnlyQuantConfig):
142
+ def __init__(
143
+ self,
144
+ calibration_data_reader: CalibrationDataReader | None = None,
145
+ percdamp=0.01,
146
+ block_size=128,
147
+ actorder=False,
148
+ mse=False,
149
+ perchannel=True,
150
+ quant_format=QuantFormat.QOperator,
151
+ op_types_to_quantize: tuple[str, ...] | None = None,
152
+ ):
153
+ """
154
+ This is a class for GPTQ algorithm Weight Only Quant Configuration.
155
+ GPTQ algorithm provides more accurate quantization but requires more computational resources.
156
+
157
+ Args:
158
+ calibration_data_reader:
159
+ a calibration data reader. It enumerates calibration data and generates inputs for the original model.
160
+ percdamp:
161
+ percent of the average Hessian diagonal to use for dampening.
162
+ block_size (int, optional):
163
+ channel number in one block to execute a GPTQ quantization iteration.
164
+ actorder (bool, optional):
165
+ whether rearrange Hessian matrix considering the diag's value.
166
+ mse (bool, optional):
167
+ whether get scale and zero point with mse error.
168
+ perchannel (bool, optional):
169
+ whether quantize weight per-channel.
170
+ quant_format (QuantFormat{QOperator, QDQ}, optional):
171
+ QOperator format quantizes the model with quantized operators directly.
172
+ QDQ format quantize the model by inserting QuantizeLinear/DeQuantizeLinear on the tensor.
173
+ Defaults to QuantFormat.QOperator.
174
+ op_types_to_quantize (optional):
175
+ set of operator types to quantize.
176
+ """
177
+ assert quant_format == QuantFormat.QOperator, "GPTQ only supports QOperator format"
178
+
179
+ super().__init__(
180
+ algorithm="GPTQ",
181
+ quant_format=quant_format,
182
+ op_types_to_quantize=op_types_to_quantize,
183
+ )
184
+ self.calibration_data_reader = calibration_data_reader
185
+ self.percdamp = percdamp
186
+ self.block_size = block_size
187
+ self.actorder = actorder
188
+ self.mse = mse
189
+ self.perchannel = perchannel
190
+
191
+
192
+ class HQQWeightOnlyQuantConfig(WeightOnlyQuantConfig):
193
+ def __init__(
194
+ self,
195
+ block_size=128,
196
+ bits=4,
197
+ axis=1,
198
+ quant_format=QuantFormat.QOperator,
199
+ op_types_to_quantize: tuple[str, ...] | None = None,
200
+ quant_axes: tuple[tuple[str, int], ...] | None = None,
201
+ ):
202
+ """
203
+ This is a class for HQQ algorithm Weight Only Quant Configuration.
204
+ HQQ algorithm quant weight without needing calibrate data.
205
+
206
+ Args:
207
+ block_size (int, optional):
208
+ channel number in one block to execute a HQQ quantization iteration.
209
+ bits (int, optional):
210
+ how many bits to represent weight.
211
+ axis (int, optional):
212
+ 0 or 1. which axis to quantize. https://arxiv.org/pdf/2309.15531.pdf
213
+ quant_format (QuantFormat{QOperator, QDQ}, optional):
214
+ QOperator format quantizes the model with quantized operators directly.
215
+ QDQ format quantize the model by inserting QuantizeLinear/DeQuantizeLinear on the tensor.
216
+ Defaults to QuantFormat.QOperator.
217
+ op_types_to_quantize (optional):
218
+ set of operator types to quantize.
219
+ quant_axes (dict[str, int], optional):
220
+ op:axis, which axis to quantize for an op. Default {MatMul: 0, Gather: 1}
221
+ """
222
+ assert quant_format == QuantFormat.QOperator, "HQQ only supports QOperator format"
223
+
224
+ super().__init__(
225
+ algorithm="HQQ",
226
+ quant_format=quant_format,
227
+ op_types_to_quantize=op_types_to_quantize,
228
+ quant_axes=quant_axes,
229
+ )
230
+ self.block_size = block_size
231
+ self.bits = bits
232
+ self.axis = axis
233
+
234
+
235
+ class DefaultWeightOnlyQuantConfig(WeightOnlyQuantConfig):
236
+ def __init__(
237
+ self,
238
+ block_size: int = 128,
239
+ is_symmetric: bool = False,
240
+ accuracy_level: int | None = None,
241
+ quant_format=QuantFormat.QOperator,
242
+ op_types_to_quantize: tuple[str, ...] | None = None,
243
+ quant_axes: tuple[tuple[str, int], ...] | None = None,
244
+ bits: int = 4,
245
+ channel_wised_quantize: bool = False,
246
+ ):
247
+ """
248
+ This is a class for weight only affine quantization configuration.
249
+
250
+ Args:
251
+ block_size (int, optional):
252
+ channel number in one block to execute an affine quantization iteration.
253
+ is_symmetric (bool, optional):
254
+ whether quantize weight symmetrically.
255
+ accuracy_level (int, optional):
256
+ Accuracy level of the 4-bit quantized MatMul computation.
257
+ Refer to the MatMulNBits contrib op's 'accuracy_level' attribute for details.
258
+ (https://github.com/microsoft/onnxruntime/blob/main/docs/ContribOperators.md#commicrosoftmatmulnbits)
259
+ quant_format (QuantFormat{QOperator, QDQ}, optional):
260
+ QOperator format quantizes the model with quantized operators directly.
261
+ QDQ format quantize the model by inserting QuantizeLinear/DeQuantizeLinear on the tensor.
262
+ Defaults to QuantFormat.QOperator.
263
+ op_types_to_quantize (optional):
264
+ set of operator types to quantize.
265
+ quant_axes (dict[str, int], optional):
266
+ op:axis, which axis to quantize for an op. Default {MatMul: 0, Gather: 1}
267
+ bits (int, optional):
268
+ number of bits per element after quantization. Default 4.
269
+ """
270
+ super().__init__(
271
+ algorithm="DEFAULT",
272
+ quant_format=quant_format,
273
+ op_types_to_quantize=op_types_to_quantize,
274
+ quant_axes=quant_axes,
275
+ )
276
+ self.block_size = block_size
277
+ self.is_symmetric = is_symmetric
278
+ self.bits = bits
279
+ self.accuracy_level = accuracy_level
280
+ self.channel_wised_quantize = channel_wised_quantize
281
+ if channel_wised_quantize and quant_format == QuantFormat.QOperator:
282
+ raise NotImplementedError("QuantFormat.QOperator is not supported channel_wised_quantize yet")
283
+
284
+
285
+ class NVAWQWeightOnlyQuantConfig(WeightOnlyQuantConfig):
286
+ def __init__(
287
+ self,
288
+ tokenizer_dir,
289
+ dataset_name="cnn",
290
+ cache_dir="./cache",
291
+ calibration_method="awq_lite",
292
+ ):
293
+ """
294
+ Configuration for the nvidia_awq quantization method.
295
+
296
+ Args:
297
+ tokenizer_dir (str): pathof the tokenizer dir.
298
+ dataset_name (str): Name of the dataset.
299
+ cache_dir (str): Directory for caching.
300
+ calibration_method (str): calib method for nvidia_awq.
301
+ """
302
+ # Import torch and DataLoader
303
+ try:
304
+ import torch # noqa: PLC0415
305
+ from torch.utils.data import DataLoader # noqa: PLC0415
306
+
307
+ self.torch = torch
308
+ self.DataLoader = DataLoader
309
+ except ImportError:
310
+ print(
311
+ "Error: The 'torch' library is required but not installed. Please install it using 'pip install torch'."
312
+ )
313
+ raise ImportError("torch is not installed. Exiting.") from None
314
+
315
+ # Import datasets
316
+ try:
317
+ from datasets import load_dataset # noqa: PLC0415
318
+
319
+ self.load_dataset = load_dataset
320
+ except ImportError:
321
+ print(
322
+ "Error: The 'datasets' library is required but not installed. Please install it using 'pip install datasets'."
323
+ )
324
+ raise ImportError("datasets is not installed. Exiting.") from None
325
+
326
+ # Import transformers
327
+ try:
328
+ from transformers import AutoConfig, AutoTokenizer # noqa: PLC0415
329
+
330
+ self.AutoConfig = AutoConfig
331
+ self.AutoTokenizer = AutoTokenizer
332
+ except ImportError:
333
+ print(
334
+ "Error: The 'transformers' library is required but not installed. Please install it using 'pip install transformers'."
335
+ )
336
+ raise ImportError("transformers is not installed. Exiting.") from None
337
+
338
+ super().__init__(
339
+ algorithm="nvidia_awq",
340
+ quant_format=QuantFormat.QDQ,
341
+ op_types_to_quantize=None, # Assuming op_types_to_quantize is handled elsewhere
342
+ quant_axes=None, # Assuming quant_axes is handled elsewhere
343
+ )
344
+
345
+ # Determine the device
346
+ device = self.torch.device("cuda" if self.torch.cuda.is_available() else "cpu")
347
+
348
+ calib_inputs = self.get_calib_inputs(
349
+ dataset_name=dataset_name,
350
+ model_name=tokenizer_dir,
351
+ cache_dir=cache_dir,
352
+ calib_size=32,
353
+ batch_size=1,
354
+ block_size=512,
355
+ device=device,
356
+ use_fp16=True,
357
+ use_buffer_share=False,
358
+ add_past_kv_inputs=True,
359
+ max_calib_rows_to_load=128,
360
+ add_position_ids=True,
361
+ )
362
+
363
+ self.calibration_data_reader = calib_inputs
364
+ self.calibration_method = calibration_method
365
+
366
+ def make_model_input(
367
+ self,
368
+ config,
369
+ input_ids_arg,
370
+ attention_mask_arg,
371
+ add_past_kv_inputs,
372
+ device,
373
+ use_fp16,
374
+ use_buffer_share,
375
+ add_position_ids,
376
+ ):
377
+ # Access torch from the instance variable
378
+ torch = self.torch
379
+
380
+ input_ids = input_ids_arg
381
+ attention_mask = attention_mask_arg
382
+
383
+ if isinstance(input_ids_arg, list):
384
+ input_ids = torch.tensor(input_ids_arg, device=device, dtype=torch.int64)
385
+ attention_mask = torch.tensor(attention_mask_arg, device=device, dtype=torch.int64)
386
+
387
+ inputs = {
388
+ "input_ids": input_ids.contiguous(),
389
+ "attention_mask": attention_mask.contiguous(),
390
+ }
391
+
392
+ if add_position_ids:
393
+ position_ids = attention_mask.long().cumsum(-1) - 1
394
+ position_ids.masked_fill_(attention_mask == 0, 1)
395
+ inputs["position_ids"] = position_ids.contiguous()
396
+
397
+ if add_past_kv_inputs:
398
+ torch_dtype = torch.float16 if use_fp16 else torch.float32
399
+ batch_size, sequence_length = input_ids.shape
400
+ max_sequence_length = config.max_position_embeddings
401
+ num_heads, head_size = (
402
+ config.num_key_value_heads,
403
+ config.hidden_size // config.num_attention_heads,
404
+ )
405
+ for i in range(config.num_hidden_layers):
406
+ past_key = torch.zeros(
407
+ batch_size,
408
+ num_heads,
409
+ max_sequence_length if use_buffer_share else 0,
410
+ head_size,
411
+ device=device,
412
+ dtype=torch_dtype,
413
+ )
414
+ past_value = torch.zeros(
415
+ batch_size,
416
+ num_heads,
417
+ max_sequence_length if use_buffer_share else 0,
418
+ head_size,
419
+ device=device,
420
+ dtype=torch_dtype,
421
+ )
422
+ inputs.update(
423
+ {
424
+ f"past_key_values.{i}.key": past_key.contiguous(),
425
+ f"past_key_values.{i}.value": past_value.contiguous(),
426
+ }
427
+ )
428
+
429
+ return inputs
430
+
431
+ def get_calib_inputs(
432
+ self,
433
+ dataset_name,
434
+ model_name,
435
+ cache_dir,
436
+ calib_size,
437
+ batch_size,
438
+ block_size,
439
+ device,
440
+ use_fp16,
441
+ use_buffer_share,
442
+ add_past_kv_inputs,
443
+ max_calib_rows_to_load,
444
+ add_position_ids,
445
+ ):
446
+ # Access transformers and datasets from the instance variables
447
+ auto_config = self.AutoConfig
448
+ auto_tokenizer = self.AutoTokenizer
449
+ load_dataset = self.load_dataset
450
+
451
+ config = auto_config.from_pretrained(
452
+ model_name, use_auth_token=True, cache_dir=cache_dir, trust_remote_code=True
453
+ )
454
+ tokenizer = auto_tokenizer.from_pretrained(
455
+ model_name, use_auth_token=True, cache_dir=cache_dir, trust_remote_code=True
456
+ )
457
+ tokenizer.add_special_tokens({"pad_token": "[PAD]"})
458
+ tokenizer.pad_token = tokenizer.eos_token
459
+
460
+ assert calib_size <= max_calib_rows_to_load, "calib size should be no more than max_calib_rows_to_load"
461
+
462
+ if "cnn" in dataset_name:
463
+ dataset2 = load_dataset("cnn_dailymail", name="3.0.0", split="train").select(range(max_calib_rows_to_load))
464
+ column = "article"
465
+ elif "pile" in dataset_name:
466
+ dataset2 = load_dataset("mit-han-lab/pile-val-backup", split="validation")
467
+ column = "text"
468
+ else:
469
+ raise ValueError(f'dataset "{dataset_name}" not supported')
470
+
471
+ dataset2 = dataset2[column][:calib_size]
472
+ batch_encoded = tokenizer.batch_encode_plus(
473
+ dataset2, return_tensors="pt", padding=True, truncation=True, max_length=block_size
474
+ )
475
+ batch_encoded = batch_encoded.to(device)
476
+ batch_encoded_input_ids = batch_encoded["input_ids"]
477
+ batch_encoded_attention_mask = batch_encoded["attention_mask"]
478
+
479
+ # Access DataLoader from the instance variable
480
+ data_loader = self.DataLoader
481
+
482
+ calib_dataloader_input_ids = data_loader(batch_encoded_input_ids, batch_size=batch_size, shuffle=False)
483
+ calib_dataloader_attention_mask = data_loader(
484
+ batch_encoded_attention_mask, batch_size=batch_size, shuffle=False
485
+ )
486
+
487
+ assert len(calib_dataloader_input_ids.dataset) == len(calib_dataloader_attention_mask.dataset)
488
+ assert len(calib_dataloader_input_ids) == len(calib_dataloader_attention_mask)
489
+
490
+ number_of_batched_samples = calib_size // batch_size
491
+
492
+ batched_input_ids = []
493
+ for idx, data in enumerate(calib_dataloader_input_ids):
494
+ batched_input_ids.append(data)
495
+ if idx == (number_of_batched_samples - 1):
496
+ break
497
+
498
+ batched_attention_mask = []
499
+ for idx, data in enumerate(calib_dataloader_attention_mask):
500
+ batched_attention_mask.append(data)
501
+ if idx == (number_of_batched_samples - 1):
502
+ break
503
+
504
+ print(
505
+ f"\n--Quantize-Script-- number_of_batched_samples={number_of_batched_samples}, "
506
+ f"batch-input-ids-list-len={len(batched_input_ids)}, batched_attention_mask={len(batched_attention_mask)}\n"
507
+ )
508
+
509
+ batched_inputs_list = []
510
+ for i in range(number_of_batched_samples):
511
+ input_ids = batched_input_ids[i]
512
+ attention_mask = batched_attention_mask[i]
513
+
514
+ inputs = self.make_model_input(
515
+ config,
516
+ input_ids,
517
+ attention_mask,
518
+ add_past_kv_inputs,
519
+ device,
520
+ use_fp16,
521
+ use_buffer_share,
522
+ add_position_ids,
523
+ )
524
+ inputs = {input_name: torch_tensor.cpu().numpy() for input_name, torch_tensor in inputs.items()}
525
+ batched_inputs_list.append(inputs)
526
+
527
+ print(f"\n--Quantize-Script-- number of batched inputs = {len(batched_inputs_list)}\n")
528
+ return batched_inputs_list
529
+
530
+
531
+ def is_divisible(val1, val2):
532
+ return int(val2 * np.ceil(val1 / val2)) == val1
533
+
534
+
535
+ class HQQWeightOnlyQuantizer:
536
+ def __init__(
537
+ self,
538
+ config: HQQWeightOnlyQuantConfig,
539
+ ):
540
+ self.config = config
541
+
542
+ # Proximal solver || weight - dequantize(quantize(weight))||_p^p
543
+ @staticmethod
544
+ def optimize_weights(
545
+ tensor,
546
+ scale,
547
+ zero,
548
+ min_max: list[int],
549
+ axis: int = 0,
550
+ opt_params: dict | None = None,
551
+ verbose=False,
552
+ ):
553
+ import torch # noqa: PLC0415
554
+
555
+ opt_params = {"lp_norm": 0.7, "beta": 1e1, "kappa": 1.01, "iters": 20} if opt_params is None else opt_params
556
+ lp_norm, beta, kappa, iters = (
557
+ opt_params["lp_norm"],
558
+ opt_params["beta"],
559
+ opt_params["kappa"],
560
+ opt_params["iters"],
561
+ )
562
+
563
+ dtype = torch.float16 if tensor.is_cuda else torch.float32
564
+ w_f = tensor.to(dtype)
565
+ scale = scale.to(dtype)
566
+ zero = zero.to(dtype)
567
+
568
+ def shrink_op(x, beta, p=lp_norm):
569
+ if p == 1:
570
+ return torch.sign(x) * torch.nn.functional.relu(torch.abs(x) - 1.0 / beta)
571
+ else:
572
+ return torch.sign(x) * torch.nn.functional.relu(
573
+ torch.abs(x) - (1.0 / beta) * torch.pow(torch.abs(x) + 1e-8, p - 1)
574
+ )
575
+
576
+ best_error = 1e4
577
+ for i in range(iters):
578
+ w_q = torch.round(w_f * scale + zero).clamp(min_max[0], min_max[1])
579
+ w_r = (w_q - zero) / scale
580
+ w_e = shrink_op(w_f - w_r, beta)
581
+ zero = torch.mean(w_q - (w_f - w_e) * scale, axis=axis, keepdim=True)
582
+ beta *= kappa
583
+
584
+ current_error = float(torch.abs(w_f - w_r).mean())
585
+ if verbose:
586
+ print(i, np.round(current_error, 6))
587
+ if current_error < best_error:
588
+ best_error = current_error
589
+ else:
590
+ break
591
+
592
+ del w_f, w_q, w_r, w_e
593
+
594
+ return scale, zero
595
+
596
+ @staticmethod
597
+ def pack_on_row_fast_248bit(pack_tensor, ori_int_tensor, bits):
598
+ if pack_tensor.shape[0] == ori_int_tensor.shape[0]:
599
+ ori_int_tensor = ori_int_tensor.T
600
+ pack_tensor = pack_tensor.T
601
+ if bits in [2, 4, 8]:
602
+ compress_ratio = pack_tensor.element_size() * 8 // bits
603
+ for j in range(compress_ratio):
604
+ pack_tensor[0:] |= ori_int_tensor[j::compress_ratio] << (bits * (j))
605
+ else:
606
+ raise NotImplementedError("Only 2,4,8 bits are supported.")
607
+
608
+ # from Official implementation of Half-Quadratic Quantization (HQQ)
609
+ def quantize_internal(
610
+ self, tensor, bits=4, channel_wise=True, group_size=64, optimize=True, round_zero=True, axis=1
611
+ ):
612
+ import torch # noqa: PLC0415
613
+
614
+ weight = tensor.float()
615
+ ori_shape = weight.shape
616
+
617
+ pad_len = (group_size - ori_shape[axis] % group_size) % group_size
618
+ if axis == 1:
619
+ weight = torch.nn.functional.pad(weight, (0, pad_len), "constant", 0)
620
+ else:
621
+ weight = torch.nn.functional.pad(weight, (0, 0, 0, pad_len), "constant", 0)
622
+ shape = weight.shape
623
+
624
+ # Reshape for grouping
625
+ if (group_size is not None) and channel_wise:
626
+ weight = weight.reshape([-1, group_size]) if (axis == 1) else weight.reshape([group_size, -1])
627
+
628
+ # Get min/max values
629
+ if channel_wise is False:
630
+ _min, _max = weight.min(), weight.max()
631
+ optimize = False
632
+ else:
633
+ _min = weight.min(axis=axis, keepdim=True)[0]
634
+ _max = weight.max(axis=axis, keepdim=True)[0]
635
+
636
+ max_v = 2**bits - 1
637
+ min_v = 0
638
+ min_max = [min_v, max_v]
639
+
640
+ # Note: here we work with the inverse of the scale to avoid division and quantize instead via weight*scale + zero, the scale is inverted later on.
641
+ # clamp to avoid half-precision problems
642
+ scale = (max_v / (_max - _min)).clamp(max=2e4)
643
+ #!!!!!!!!!!!!!!!
644
+ min_max_axis = _max - _min
645
+ if (min_max_axis == 0).sum().item() > 0:
646
+ min_max_axis[min_max_axis == 0] = max_v
647
+ scale = (max_v / min_max_axis).clamp(max=2e4)
648
+ zero = -_min * scale
649
+
650
+ if round_zero:
651
+ zero = torch.round(zero)
652
+
653
+ # Fine-tune weights
654
+ if optimize:
655
+ scale, zero = self.optimize_weights(tensor=weight, scale=scale, zero=zero, min_max=min_max, axis=axis)
656
+
657
+ # Quantize
658
+ # Necessary for fake quantization backprop
659
+ w_q = torch.round(weight * scale + zero).clamp(min_max[0], min_max[1])
660
+ w_q = w_q.reshape(shape).int()
661
+
662
+ scale = 1.0 / scale
663
+ if axis == 1:
664
+ scale = scale.reshape(shape[0], -1)
665
+ zero = zero.reshape(shape[0], -1)
666
+ else:
667
+ scale = scale.reshape(-1, shape[-1])
668
+ zero = zero.reshape(-1, shape[-1])
669
+ # cleanup
670
+ del weight, _min, _max
671
+
672
+ return w_q, scale.to(tensor.dtype), zero.to(tensor.dtype)
673
+
674
+ def quantize(self, node: NodeProto, graph_stack: list[GraphProto]) -> list[NodeProto]:
675
+ """
676
+ Target node: QOperator node: QDQ nodes:
677
+ MatMul MatMulNBits DeQuantizeLinear -> MatMul
678
+ Gather GatherBlockQuantized Gather, Gather, Gather (optional) -> DequantizeLinear
679
+ If the node is target node with fp32 or fp16 const weight, quantize the weight to int4 and
680
+ return the new nodes.
681
+ If QOperator format, return the corresponding QOperator nodes.
682
+ If QDQ format, return the corresdponging QDQ nodes.
683
+ Gather (quantized data) + Gather (scales) + Gather (optional, zero points) -> DequantizeLinear is
684
+ not supported yet because Gather does not support int4 data.
685
+ """
686
+ # With HQQ, zero points are in float. Current GatherBlockQuantized does not support float zero points.
687
+ if node.op_type == "Gather":
688
+ raise NotImplementedError("Gather quantization is not supported yet in HQQ")
689
+
690
+ import torch # noqa: PLC0415
691
+
692
+ logger.info(f"start to quantize {node.name} ...")
693
+ input_b = node.input[1]
694
+ b_pb, bs_graph = get_initializer(input_b, graph_stack)
695
+ if b_pb is None:
696
+ logger.info("MatMul doesn't have const weight. Skip to quantize")
697
+ return [node] # only care about constant weight
698
+
699
+ b_array = onnx.numpy_helper.to_array(b_pb)
700
+ b_original_shape = b_array.shape
701
+ if len(b_original_shape) != 2:
702
+ if len(b_original_shape) < 2:
703
+ logger.info("MatMul weight has fewer than 2 dimensions. Skip to quantize.")
704
+ return [node]
705
+ leading = b_original_shape[:-2]
706
+ if any(d != 1 for d in leading):
707
+ logger.info(
708
+ "MatMul weight has non-unit batch dims %s; N-D batched quantization not supported. "
709
+ "Skip to quantize.",
710
+ list(leading),
711
+ )
712
+ return [node]
713
+ # Squeeze all unit leading dims to obtain a 2-D weight [K, N]
714
+ b_array = b_array.reshape(b_original_shape[-2], b_original_shape[-1])
715
+ else:
716
+ b_original_shape = None # already 2-D, no reshape needed
717
+ b_array_torch = torch.from_numpy(b_array)
718
+ if torch.cuda.is_available():
719
+ b_array_torch = b_array_torch.cuda()
720
+
721
+ bits = self.config.bits
722
+ quant_weight_torch, scales_torch, zero_points_torch = self.quantize_internal(
723
+ b_array_torch.T, bits=bits, group_size=self.config.block_size
724
+ )
725
+ quant_weight_torch = quant_weight_torch.contiguous()
726
+ scales_torch = scales_torch.contiguous()
727
+ zero_points_torch = zero_points_torch.contiguous()
728
+
729
+ packed_size = 8 // bits # number of elements packed into one byte
730
+
731
+ packed_torch = torch.zeros(
732
+ (quant_weight_torch.shape[0], quant_weight_torch.shape[1] // packed_size),
733
+ dtype=torch.uint8,
734
+ device=quant_weight_torch.device,
735
+ )
736
+ self.pack_on_row_fast_248bit(packed_torch, quant_weight_torch, bits)
737
+ scales = scales_torch.cpu().numpy()
738
+ zero_points = zero_points_torch.cpu().numpy()
739
+ # reshape to the predefined shape in MatmulNbits
740
+ scales = scales.reshape(-1)
741
+ zero_points = zero_points.reshape(-1)
742
+ rows, cols = b_array_torch.shape
743
+ block_size = self.config.block_size
744
+ blob_size = block_size // packed_size
745
+ k_blocks = (rows + block_size - 1) // block_size
746
+ packed_torch = packed_torch.reshape(cols, k_blocks, blob_size)
747
+
748
+ b_quant = onnx.numpy_helper.from_array(packed_torch.cpu().numpy())
749
+ b_quant.name = b_pb.name + "_Q" + str(bits)
750
+ for input in bs_graph.input:
751
+ if input.name == input_b:
752
+ bs_graph.input.remove(input)
753
+ break
754
+
755
+ scales_tensor = onnx.numpy_helper.from_array(scales)
756
+ scales_tensor.name = b_pb.name + "_scales"
757
+ bs_graph.initializer.extend([b_quant, scales_tensor])
758
+
759
+ input_names = [node.input[0], b_quant.name, scales_tensor.name]
760
+ zp_tensor = onnx.numpy_helper.from_array(zero_points)
761
+ zp_tensor.name = b_pb.name + "_zero_points"
762
+ bs_graph.initializer.extend([zp_tensor])
763
+ input_names.append(zp_tensor.name)
764
+
765
+ kwargs = {}
766
+ rows, cols = b_array.shape
767
+ kwargs["K"] = rows
768
+ kwargs["N"] = cols
769
+ kwargs["bits"] = bits
770
+ kwargs["block_size"] = self.config.block_size
771
+
772
+ # When rank(A) >= rank_b_orig, the reshape would be a no-op since MatMulNBits
773
+ # already produces the correct output shape.
774
+ a_static_rank = _get_static_rank(node.input[0], graph_stack)
775
+ rank_b_orig = len(b_original_shape) if b_original_shape is not None else 0
776
+ needs_reshape = b_original_shape is not None and (a_static_rank is None or a_static_rank < rank_b_orig)
777
+ matmul_q_output = node.output[0] if not needs_reshape else node.output[0] + "_pre_reshape"
778
+ matmul_q_node = onnx.helper.make_node(
779
+ "MatMulNBits",
780
+ inputs=input_names,
781
+ outputs=[matmul_q_output],
782
+ name=node.name + "_Q" + str(bits) if node.name else "",
783
+ domain="com.microsoft",
784
+ **kwargs,
785
+ )
786
+
787
+ output_nodes = [matmul_q_node]
788
+ if needs_reshape:
789
+ # Restore ONNX MatMul broadcast shape on the output.
790
+ # MatMul(A, B_orig) output shape (with B_orig leading dims all 1) is:
791
+ # [1] * max(rank(B_orig) - rank(A), 0) + A.shape[:-1] + [N]
792
+ # MatMulNBits with squeezed B produces [...A.shape[:-1], N] (rank=rank(A)),
793
+ # so we only need to prepend leading 1s when rank(B_orig) > rank(A).
794
+ output_nodes.extend(
795
+ _build_nbits_output_reshape(
796
+ a_input_name=node.input[0],
797
+ b_original_shape=b_original_shape,
798
+ target_graph=bs_graph,
799
+ name_prefix=(node.name + "_Q" + str(bits)) if node.name else (b_pb.name + "_Q" + str(bits)),
800
+ pre_reshape_output=matmul_q_output,
801
+ final_output=node.output[0],
802
+ )
803
+ )
804
+
805
+ logger.info(f"complete quantization of {node.name} ...")
806
+
807
+ return output_nodes
808
+
809
+
810
+ def get_initializer(name, graph_path: list[GraphProto]) -> tuple[TensorProto, GraphProto]:
811
+ for gid in range(len(graph_path) - 1, -1, -1):
812
+ graph = graph_path[gid]
813
+ for tensor in graph.initializer:
814
+ if tensor.name == name:
815
+ return tensor, graph
816
+ return None, None
817
+
818
+
819
+ def _get_static_rank(tensor_name: str, graph_path: list[GraphProto]) -> int | None:
820
+ """Return the static rank of a tensor if its shape is known, else None.
821
+
822
+ Searches graph inputs, value_info, and outputs in the graph stack (inner-most
823
+ graph first). A known shape requires ``HasField('shape')`` to be true on the
824
+ tensor_type; the rank is then ``len(shape.dim)``. Individual dim sizes may
825
+ still be symbolic — only the rank (dimension count) matters here.
826
+ """
827
+ for gid in range(len(graph_path) - 1, -1, -1):
828
+ graph = graph_path[gid]
829
+ for vi in list(graph.input) + list(graph.value_info) + list(graph.output):
830
+ if vi.name == tensor_name:
831
+ tt = vi.type.tensor_type
832
+ if tt.HasField("shape"):
833
+ return len(tt.shape.dim)
834
+ return None
835
+ return None
836
+
837
+
838
+ def _build_nbits_output_reshape(
839
+ a_input_name: str,
840
+ b_original_shape: tuple,
841
+ target_graph: GraphProto,
842
+ name_prefix: str,
843
+ pre_reshape_output: str,
844
+ final_output: str,
845
+ ) -> list[NodeProto]:
846
+ """Build the reshape chain that restores the ONNX MatMul-broadcast output shape.
847
+
848
+ MatMulNBits produces shape ``[...A_batch_dims, M, N]`` (rank = rank(A)). To match
849
+ the original ``MatMul(A, B_orig)`` output, where B_orig has all-unit leading
850
+ dims, we need:
851
+
852
+ a_rank_eff = max(rank(A), 2) # ONNX promotes 1-D A to rank-2
853
+ out_shape = [1] * max(rank(B_orig) - a_rank_eff, 0) + A.shape[:-1] + [N]
854
+
855
+ This is built dynamically via Shape/Gather/Max/Sub/Max/ConstantOfShape/Slice/Concat
856
+ so it works regardless of A's static rank (handles rank(A) == 1, rank(A) == 2
857
+ — the common transformer case — as well as rank(A) >= rank(B_orig) where no
858
+ leading-1 prepending is needed). All ops used are valid from opset 11 onward.
859
+
860
+ Args:
861
+ a_input_name: name of the activation input edge (A) feeding MatMulNBits.
862
+ b_original_shape: the original (pre-squeeze) shape of B, e.g. ``(1, K, N)``.
863
+ target_graph: graph proto to append helper initializers into.
864
+ name_prefix: unique prefix for generated node/initializer names.
865
+ pre_reshape_output: name of the MatMulNBits output edge (the input of the
866
+ generated Reshape).
867
+ final_output: name of the final edge produced by the generated Reshape
868
+ (must match the original MatMul output edge).
869
+
870
+ Returns:
871
+ List of nodes to append to the consumer's ``output_nodes`` after the
872
+ MatMulNBits node. Initializers are appended to ``target_graph`` in place.
873
+ """
874
+ rank_b_orig = len(b_original_shape)
875
+ n_dim = b_original_shape[-1]
876
+
877
+ # Incorporate the unique output tensor name so initializer names are unique
878
+ # even when multiple MatMul nodes share the same node.name (Fix 2).
879
+ p = name_prefix + "_" + final_output
880
+ init_zero = p + "_zero"
881
+ init_one = p + "_one"
882
+ init_two = p + "_two"
883
+ init_one_vec = p + "_one_vec"
884
+ init_rank_b = p + "_rank_b"
885
+ init_n_vec = p + "_n_vec"
886
+ init_zero_vec = p + "_zero_vec"
887
+ init_one_value_template = p + "_one_value"
888
+
889
+ target_graph.initializer.extend(
890
+ [
891
+ onnx.numpy_helper.from_array(np.array(0, dtype=np.int64), name=init_zero),
892
+ onnx.numpy_helper.from_array(np.array(1, dtype=np.int64), name=init_one),
893
+ onnx.numpy_helper.from_array(np.array(2, dtype=np.int64), name=init_two),
894
+ onnx.numpy_helper.from_array(np.array([1], dtype=np.int64), name=init_one_vec),
895
+ onnx.numpy_helper.from_array(np.array(rank_b_orig, dtype=np.int64), name=init_rank_b),
896
+ onnx.numpy_helper.from_array(np.array([n_dim], dtype=np.int64), name=init_n_vec),
897
+ onnx.numpy_helper.from_array(np.array([0], dtype=np.int64), name=init_zero_vec),
898
+ ]
899
+ )
900
+
901
+ a_shape = p + "_a_shape"
902
+ a_shape_of_shape = p + "_a_shape_of_shape"
903
+ a_rank = p + "_a_rank"
904
+ a_rank_eff = p + "_a_rank_eff"
905
+ extra_raw = p + "_extra_raw"
906
+ extra_count = p + "_extra_count"
907
+ extra_count_vec = p + "_extra_count_vec"
908
+ extra_ones = p + "_extra_ones"
909
+ a_rank_minus_one = p + "_a_rank_m1"
910
+ a_rank_minus_one_vec = p + "_a_rank_m1_vec"
911
+ a_prefix_shape = p + "_a_prefix_shape"
912
+ target_shape = p + "_target_shape"
913
+
914
+ nodes = [
915
+ onnx.helper.make_node("Shape", [a_input_name], [a_shape], name=p + "_shape_a"),
916
+ # Use Shape(shape) + Gather instead of Size to stay within opset 11
917
+ # (Size requires opset >= 13 when applied to a shape tensor).
918
+ # Shape applied to the 1-D shape vector yields [rank_a] as a 1-element
919
+ # tensor; Gather with scalar index 0 extracts it as a scalar int64.
920
+ onnx.helper.make_node("Shape", [a_shape], [a_shape_of_shape], name=p + "_shape_of_a_shape"),
921
+ onnx.helper.make_node("Gather", [a_shape_of_shape, init_zero], [a_rank], name=p + "_gather_rank"),
922
+ # ONNX MatMul promotes a 1-D activation to rank-2 before computing the
923
+ # output shape, so use Max(a_rank, 2) as the effective rank when
924
+ # computing how many leading 1s to prepend.
925
+ onnx.helper.make_node("Max", [a_rank, init_two], [a_rank_eff], name=p + "_max_rank_eff"),
926
+ onnx.helper.make_node("Sub", [init_rank_b, a_rank_eff], [extra_raw], name=p + "_sub"),
927
+ onnx.helper.make_node("Max", [extra_raw, init_zero], [extra_count], name=p + "_max"),
928
+ onnx.helper.make_node("Reshape", [extra_count, init_one_vec], [extra_count_vec], name=p + "_reshape_extra"),
929
+ onnx.helper.make_node(
930
+ "ConstantOfShape",
931
+ [extra_count_vec],
932
+ [extra_ones],
933
+ name=p + "_const_ones",
934
+ value=onnx.helper.make_tensor(
935
+ name=init_one_value_template,
936
+ data_type=TensorProto.INT64,
937
+ dims=[1],
938
+ vals=[1],
939
+ ),
940
+ ),
941
+ onnx.helper.make_node("Sub", [a_rank, init_one], [a_rank_minus_one], name=p + "_sub_one"),
942
+ onnx.helper.make_node(
943
+ "Reshape", [a_rank_minus_one, init_one_vec], [a_rank_minus_one_vec], name=p + "_reshape_rank_m1"
944
+ ),
945
+ onnx.helper.make_node(
946
+ "Slice",
947
+ [a_shape, init_zero_vec, a_rank_minus_one_vec, init_zero_vec],
948
+ [a_prefix_shape],
949
+ name=p + "_slice_a_prefix",
950
+ ),
951
+ onnx.helper.make_node(
952
+ "Concat",
953
+ [extra_ones, a_prefix_shape, init_n_vec],
954
+ [target_shape],
955
+ name=p + "_concat_target",
956
+ axis=0,
957
+ ),
958
+ onnx.helper.make_node(
959
+ "Reshape",
960
+ [pre_reshape_output, target_shape],
961
+ [final_output],
962
+ name=p + "_reshape_out",
963
+ ),
964
+ ]
965
+ return nodes
966
+
967
+
968
+ # transpose int4 matrix (packed as uint8)
969
+ def transpose_packed_int4_matrix(packed, rows, cols):
970
+ # unpack to int4 matrix
971
+ total = rows * cols
972
+ high = (packed >> 4) & 0x0F
973
+ low = packed & 0x0F
974
+ int4_vals = np.empty(total, dtype=np.uint8)
975
+ int4_vals[0::2] = low
976
+ int4_vals[1::2] = high
977
+ int4_matrix = int4_vals.reshape((rows, cols))
978
+
979
+ # transpose int4 matrix
980
+ int4_matrix_transposed = int4_matrix.T
981
+
982
+ # pack to uint8
983
+ flat = int4_matrix_transposed.reshape(-1)
984
+ packed = ((flat[1::2] << 4) & 0xF0) | (flat[0::2] & 0x0F)
985
+ return packed.astype(np.uint8)
986
+
987
+
988
+ class DefaultWeightOnlyQuantizer:
989
+ def __init__(self, config: DefaultWeightOnlyQuantConfig):
990
+ self.config = config
991
+
992
+ def qbits_block_quant(self, fp32weight: npt.ArrayLike) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
993
+ """4b/8b quantize fp32 weight to int4 using C++ kernels."""
994
+
995
+ qbits = self.config.bits
996
+ kpack = 8 // qbits
997
+ if len(fp32weight.shape) != 2:
998
+ raise ValueError("Current int4 block quantization only supports 2D tensors!")
999
+ rows, cols = fp32weight.shape
1000
+
1001
+ block_size = self.config.block_size
1002
+ k_blocks = (rows + block_size - 1) // block_size
1003
+
1004
+ if self.config.quant_format == QuantFormat.QOperator:
1005
+ blob_size = (block_size + kpack - 1) // kpack
1006
+ padded_rows = k_blocks * block_size
1007
+ pad_len = padded_rows - rows
1008
+ if pad_len > 0:
1009
+ fp32weight = np.pad(fp32weight, ((0, pad_len), (0, 0)), "constant")
1010
+
1011
+ # block wise quantization, each block comes from a single column
1012
+ packed = np.zeros((cols, k_blocks, blob_size), dtype="uint8")
1013
+ zero_point = np.zeros((cols, ((k_blocks + kpack - 1) // kpack)), dtype="uint8")
1014
+ scales = np.zeros((cols, k_blocks), dtype=fp32weight.dtype)
1015
+ if qbits == 2:
1016
+ quantize_matmul_2bits(
1017
+ packed, fp32weight, scales, zero_point, block_size, cols, rows, self.config.is_symmetric
1018
+ )
1019
+ elif qbits == 8:
1020
+ quantize_matmul_8bits(
1021
+ packed, fp32weight, scales, zero_point, block_size, cols, rows, self.config.is_symmetric
1022
+ )
1023
+ else:
1024
+ quantize_matmul_4bits(
1025
+ packed, fp32weight, scales, zero_point, block_size, cols, rows, self.config.is_symmetric
1026
+ )
1027
+ else:
1028
+ # block size equal to rows (K) if channel wised quantize enabled
1029
+ block_size = rows if self.config.channel_wised_quantize else self.config.block_size
1030
+ k_blocks = (rows + block_size - 1) // block_size
1031
+
1032
+ assert qbits == 4, "QDQ format only support 4 bits quantization"
1033
+ packed = np.zeros((rows * cols + 1) // 2, dtype="uint8")
1034
+ zero_point = np.zeros((cols * k_blocks + 1) // 2, dtype="uint8")
1035
+ scales = np.zeros((k_blocks, cols), dtype=fp32weight.dtype)
1036
+ quantize_qdq_matmul_4bits(
1037
+ packed, fp32weight, scales, zero_point, block_size, cols, rows, self.config.is_symmetric
1038
+ )
1039
+
1040
+ return (packed, scales, zero_point)
1041
+
1042
+ def quantize_matmul(self, node: NodeProto, graph_stack: list[GraphProto]) -> list[NodeProto]:
1043
+ """
1044
+ Quantize weight B of MatMul node to int4 or int8.
1045
+ Supports 2D constant matrix, and N-D constant matrices whose leading dimensions are all 1
1046
+ (which are squeezed to 2D before quantization). Axis 0 blockwise quantization only.
1047
+ """
1048
+ bits = self.config.bits
1049
+ if bits == 8:
1050
+ qtype = TensorProto.INT8 if self.config.is_symmetric else TensorProto.UINT8
1051
+ else:
1052
+ qtype = TensorProto.INT4 if self.config.is_symmetric else TensorProto.UINT4
1053
+ input_b = node.input[1]
1054
+ b_tensor, b_graph = get_initializer(input_b, graph_stack)
1055
+ if b_tensor is None:
1056
+ logger.info("MatMul doesn't have const weight. Skip to quantize")
1057
+ return [node] # only care about constant weight
1058
+
1059
+ b_ndarray = ir.from_proto(b_tensor).numpy()
1060
+ b_original_shape = b_ndarray.shape
1061
+ if len(b_original_shape) != 2:
1062
+ if len(b_original_shape) < 2:
1063
+ logger.info("MatMul weight has fewer than 2 dimensions. Skip to quantize.")
1064
+ return [node]
1065
+ leading = b_original_shape[:-2]
1066
+ if any(d != 1 for d in leading):
1067
+ logger.info(
1068
+ "MatMul weight has non-unit batch dims %s; N-D batched quantization not supported. "
1069
+ "Skip to quantize.",
1070
+ list(leading),
1071
+ )
1072
+ return [node]
1073
+ # Squeeze all unit leading dims to obtain a 2-D weight [K, N]
1074
+ b_ndarray = b_ndarray.reshape(b_original_shape[-2], b_original_shape[-1])
1075
+ else:
1076
+ b_original_shape = None # already 2-D, no reshape needed
1077
+
1078
+ bfloat16 = b_ndarray.dtype == "bfloat16"
1079
+ if bfloat16:
1080
+ b_ndarray = b_ndarray.astype(np.float32)
1081
+
1082
+ packed, scales, zero_points = self.qbits_block_quant(b_ndarray)
1083
+ if bfloat16:
1084
+ scales = scales.astype(ml_dtypes.bfloat16)
1085
+
1086
+ if self.config.quant_format == QuantFormat.QOperator:
1087
+ b_quant = ir.serde.serialize_tensor(ir.Tensor(packed, name=b_tensor.name + f"_Q{bits}"))
1088
+ scales_tensor = ir.serde.serialize_tensor(ir.Tensor(scales, name=b_tensor.name + "_scales"))
1089
+ else:
1090
+ b_quant = onnx.helper.make_tensor(
1091
+ b_tensor.name + f"_DQ_Q{bits}", qtype, b_ndarray.shape, packed.tobytes(), True
1092
+ )
1093
+ scales_tensor = ir.serde.serialize_tensor(ir.Tensor(scales, name=b_tensor.name + "_DQ_scales"))
1094
+
1095
+ # if QDQ, CW and SYM enabled, optimize for Intel NPU, tranpose the weight to NHWC format will increase performance
1096
+ qdq_opt_for_intel_npu_enabled = (
1097
+ self.config.quant_format == QuantFormat.QDQ
1098
+ and self.config.channel_wised_quantize
1099
+ and self.config.is_symmetric
1100
+ )
1101
+ if qdq_opt_for_intel_npu_enabled:
1102
+ rows, cols = b_ndarray.shape
1103
+ packed = transpose_packed_int4_matrix(packed, rows, cols)
1104
+ scales = scales.reshape((cols, 1)) # (cols, 1)
1105
+ b_quant = onnx.helper.make_tensor(
1106
+ b_tensor.name + f"_DQ_Q{bits}", qtype, [cols, rows], packed.tobytes(), True
1107
+ )
1108
+ scales_tensor = ir.serde.serialize_tensor(ir.Tensor(scales, name=b_tensor.name + "_DQ_scales"))
1109
+
1110
+ for input in b_graph.input:
1111
+ if input.name == input_b:
1112
+ b_graph.input.remove(input)
1113
+ break
1114
+
1115
+ b_graph.initializer.extend([b_quant, scales_tensor])
1116
+
1117
+ output_nodes = []
1118
+
1119
+ if self.config.quant_format == QuantFormat.QOperator:
1120
+ input_names = [node.input[0], b_quant.name, scales_tensor.name]
1121
+ if not self.config.is_symmetric:
1122
+ zp_tensor = onnx.numpy_helper.from_array(zero_points, b_tensor.name + "_zero_points")
1123
+ input_names.append(zp_tensor.name)
1124
+ b_graph.initializer.extend([zp_tensor])
1125
+ kwargs = {}
1126
+ rows, cols = b_ndarray.shape
1127
+ kwargs["K"] = rows
1128
+ kwargs["N"] = cols
1129
+ kwargs["bits"] = bits
1130
+ kwargs["block_size"] = self.config.block_size
1131
+
1132
+ # Do not output accuracy_level if it is 0 since the attribute is optional and is not supported by most EPs.
1133
+ if self.config.accuracy_level:
1134
+ kwargs["accuracy_level"] = self.config.accuracy_level
1135
+
1136
+ # When rank(A) >= rank_b_orig, the reshape would be a no-op since MatMulNBits
1137
+ # already produces the correct output shape.
1138
+ a_static_rank = _get_static_rank(node.input[0], graph_stack)
1139
+ rank_b_orig = len(b_original_shape) if b_original_shape is not None else 0
1140
+ needs_reshape = b_original_shape is not None and (a_static_rank is None or a_static_rank < rank_b_orig)
1141
+ qop_output = node.output[0] if not needs_reshape else node.output[0] + "_pre_reshape"
1142
+ matmul_qbit_node = onnx.helper.make_node(
1143
+ "MatMulNBits",
1144
+ inputs=input_names,
1145
+ outputs=[qop_output],
1146
+ name=node.name + f"_Q{bits}" if node.name else "",
1147
+ domain="com.microsoft",
1148
+ **kwargs,
1149
+ )
1150
+
1151
+ output_nodes.append(matmul_qbit_node)
1152
+ if needs_reshape:
1153
+ output_nodes.extend(
1154
+ _build_nbits_output_reshape(
1155
+ a_input_name=node.input[0],
1156
+ b_original_shape=b_original_shape,
1157
+ target_graph=b_graph,
1158
+ name_prefix=(node.name + f"_Q{bits}") if node.name else (b_tensor.name + f"_Q{bits}"),
1159
+ pre_reshape_output=qop_output,
1160
+ final_output=node.output[0],
1161
+ )
1162
+ )
1163
+ else:
1164
+ dq_input_names = [b_quant.name, scales_tensor.name]
1165
+ dq_output_names = [b_quant.name + "_output"]
1166
+ tp_input_names = [dq_output_names[0]]
1167
+ tp_output_names = [dq_output_names[0] + "_transposed"]
1168
+ matmul_input_names = [
1169
+ node.input[0],
1170
+ tp_output_names[0] if qdq_opt_for_intel_npu_enabled else dq_output_names[0],
1171
+ ]
1172
+ # When rank(A) >= rank_b_orig, the reshape would be a no-op since MatMul
1173
+ # already produces the correct output shape.
1174
+ a_static_rank = _get_static_rank(node.input[0], graph_stack)
1175
+ rank_b_orig = len(b_original_shape) if b_original_shape is not None else 0
1176
+ needs_reshape = b_original_shape is not None and (a_static_rank is None or a_static_rank < rank_b_orig)
1177
+ qdq_matmul_out = node.output[0] if not needs_reshape else node.output[0] + "_pre_reshape"
1178
+ matmul_output_names = [qdq_matmul_out]
1179
+ if not self.config.is_symmetric:
1180
+ zp_tensor = onnx.helper.make_tensor(
1181
+ b_tensor.name + "_DQ_zero_points", qtype, scales.shape, zero_points.tobytes(), True
1182
+ )
1183
+ dq_input_names.append(zp_tensor.name)
1184
+ b_graph.initializer.extend([zp_tensor])
1185
+ rows, cols = b_ndarray.shape
1186
+ dq_kwargs = {
1187
+ "axis": 1 if qdq_opt_for_intel_npu_enabled else 0,
1188
+ "block_size": rows if self.config.channel_wised_quantize else self.config.block_size,
1189
+ }
1190
+ dq_node = onnx.helper.make_node(
1191
+ "DequantizeLinear",
1192
+ inputs=dq_input_names,
1193
+ outputs=dq_output_names,
1194
+ name=node.name + f"_DQ_Q{bits}" if node.name else "",
1195
+ **dq_kwargs,
1196
+ )
1197
+ matmul_node = onnx.helper.make_node(
1198
+ "MatMul",
1199
+ inputs=matmul_input_names,
1200
+ outputs=matmul_output_names,
1201
+ name=node.name + f"_matmul_Q{bits}" if node.name else "",
1202
+ )
1203
+ if qdq_opt_for_intel_npu_enabled:
1204
+ tp_node = onnx.helper.make_node(
1205
+ "Transpose",
1206
+ inputs=tp_input_names,
1207
+ outputs=tp_output_names,
1208
+ perm=[1, 0],
1209
+ )
1210
+ output_nodes.extend([dq_node, tp_node, matmul_node])
1211
+ else:
1212
+ output_nodes.extend([dq_node, matmul_node])
1213
+ if needs_reshape:
1214
+ output_nodes.extend(
1215
+ _build_nbits_output_reshape(
1216
+ a_input_name=node.input[0],
1217
+ b_original_shape=b_original_shape,
1218
+ target_graph=b_graph,
1219
+ name_prefix=(node.name + f"_DQ_Q{bits}") if node.name else (b_tensor.name + f"_DQ_Q{bits}"),
1220
+ pre_reshape_output=qdq_matmul_out,
1221
+ final_output=node.output[0],
1222
+ )
1223
+ )
1224
+
1225
+ return output_nodes
1226
+
1227
+ @staticmethod
1228
+ def quant_slice_symmetric(data: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
1229
+ max_val = np.max(data, axis=1, keepdims=True)
1230
+ min_val = np.min(data, axis=1, keepdims=True)
1231
+ abs_max = np.where(np.abs(max_val) > np.abs(min_val), max_val, min_val)
1232
+
1233
+ scale = abs_max / -8.0 # if max == min, max may be clipped
1234
+ quantized_slice = np.where(scale == 0, 0, data / scale).round().clip(-8, 7).astype(np.int8)
1235
+
1236
+ return quantized_slice, scale
1237
+
1238
+ @staticmethod
1239
+ def quant_slice_asymmetric(data: np.ndarray) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
1240
+ min_val = np.minimum(data.min(axis=1, keepdims=True), 0)
1241
+ max_val = np.maximum(data.max(axis=1, keepdims=True), 0)
1242
+
1243
+ scale = (max_val - min_val) / 15.0
1244
+ zero_point = np.where(scale == 0, 8, -min_val / scale).round().clip(0, 15).astype(np.uint8)
1245
+ quantized_slice = np.where(scale == 0, 8, data / scale + zero_point).round().clip(0, 15).astype(np.uint8)
1246
+
1247
+ return quantized_slice, scale, zero_point
1248
+
1249
+ @staticmethod
1250
+ def pack_int8_to_int4(data: np.ndarray) -> np.ndarray:
1251
+ """Pack int8 data to int4 and store in uint8 ndarray."""
1252
+ data_flat = data.reshape(-1)
1253
+ if len(data_flat) % 2 != 0:
1254
+ data_flat = np.append(data_flat, 0)
1255
+ quant_data_int4 = (data_flat[::2] & 0xF) | ((data_flat[1::2] & 0xF) << 4)
1256
+
1257
+ return quant_data_int4.astype("uint8")
1258
+
1259
+ @staticmethod
1260
+ def quantize_ndarray(
1261
+ data: np.ndarray,
1262
+ quantize_axis: int,
1263
+ block_size: int,
1264
+ is_symmetric: bool,
1265
+ ) -> tuple[np.ndarray, np.ndarray, np.ndarray | None]:
1266
+ """Quantize ndarray data to int4 using numpy, return (quantized data, scales, zero points)."""
1267
+ # Get the shape of the matrix
1268
+ m = 1 # dimension of the matrix before the quantize axis
1269
+ k = data.shape[quantize_axis] # dimension of the matrix along the quantize axis
1270
+ n = 1 # dimension of the matrix after the quantize axis
1271
+ for i, dim in enumerate(data.shape):
1272
+ if i < quantize_axis:
1273
+ m *= dim
1274
+ elif i > quantize_axis:
1275
+ n *= dim
1276
+
1277
+ k_blocks = (k + block_size - 1) // block_size
1278
+ scales_shape = list(data.shape)
1279
+ scales_shape[quantize_axis] = k_blocks
1280
+
1281
+ data_reshape = data.reshape((m, k, n))
1282
+ scales = np.zeros((m, k_blocks, n), dtype=data.dtype)
1283
+ if is_symmetric:
1284
+ quant_data_int8 = np.zeros((m, k, n), dtype="int8")
1285
+ else:
1286
+ quant_data_int8 = np.zeros((m, k, n), dtype="uint8")
1287
+ zero_point_int8 = np.zeros((m, k_blocks, n), dtype="uint8")
1288
+
1289
+ # slice and quantize
1290
+ for i in range(0, k, block_size):
1291
+ end_idx = min(i + block_size, k)
1292
+ slice = data_reshape[:, i:end_idx, :]
1293
+
1294
+ if is_symmetric:
1295
+ quantized_slice_int8, scale_slice = DefaultWeightOnlyQuantizer.quant_slice_symmetric(slice)
1296
+ else:
1297
+ quantized_slice_int8, scale_slice, zero_point_slice_int8 = (
1298
+ DefaultWeightOnlyQuantizer.quant_slice_asymmetric(slice)
1299
+ )
1300
+
1301
+ quant_data_int8[:, i:end_idx, :] = quantized_slice_int8
1302
+ j = i // block_size
1303
+ scales[:, j : (j + 1), :] = scale_slice
1304
+ if not is_symmetric:
1305
+ zero_point_int8[:, j : (j + 1), :] = zero_point_slice_int8
1306
+
1307
+ # pack int8 to int4
1308
+ quant_data_int4 = DefaultWeightOnlyQuantizer.pack_int8_to_int4(quant_data_int8)
1309
+ zero_point_int4 = None
1310
+ if not is_symmetric:
1311
+ zero_point_int4 = DefaultWeightOnlyQuantizer.pack_int8_to_int4(zero_point_int8)
1312
+ scales = scales.reshape(scales_shape)
1313
+ return quant_data_int4, scales, zero_point_int4
1314
+
1315
+ def quantize_gather(self, node: NodeProto, graph_stack: list[GraphProto]) -> list[NodeProto]:
1316
+ """Quantize weight data of Gather node to int4."""
1317
+ assert self.config.quant_format == QuantFormat.QOperator, "Gather only supports QOperator format currently."
1318
+
1319
+ qtype = TensorProto.INT4 if self.config.is_symmetric else TensorProto.UINT4
1320
+ data_arg = node.input[0]
1321
+ data_tensorproto, data_graphproto = get_initializer(data_arg, graph_stack)
1322
+ if data_tensorproto is None:
1323
+ logger.info("Gather doesn't have const weight. Skip quantization.")
1324
+ return [node] # only care about constant weight
1325
+
1326
+ data_ndarray = onnx.numpy_helper.to_array(data_tensorproto)
1327
+ data_rank = len(data_ndarray.shape)
1328
+ quantize_axis = self.config.quant_axes.get("Gather", 1)
1329
+ block_size = self.config.block_size
1330
+
1331
+ assert quantize_axis < data_rank and quantize_axis >= -data_rank, "Invalid quantize axis for Gather node."
1332
+ assert block_size >= 16 and ((block_size - 1) & block_size == 0), "Invalid block size for Gather node."
1333
+
1334
+ quantize_axis = (quantize_axis + data_rank) % data_rank
1335
+ quantized_data, scales, zero_points = self.quantize_ndarray(
1336
+ data_ndarray, quantize_axis, block_size, self.config.is_symmetric
1337
+ )
1338
+
1339
+ for input in data_graphproto.input:
1340
+ if input.name == data_arg:
1341
+ data_graphproto.input.remove(input)
1342
+ break
1343
+
1344
+ quantized_data_tensorproto = onnx.helper.make_tensor(
1345
+ data_tensorproto.name + "_Q4", qtype, data_ndarray.shape, quantized_data.tobytes(), True
1346
+ )
1347
+ scales_tensorproto = onnx.numpy_helper.from_array(scales, data_tensorproto.name + "_scales")
1348
+ input_names = [quantized_data_tensorproto.name, node.input[1], scales_tensorproto.name]
1349
+ data_graphproto.initializer.extend([quantized_data_tensorproto, scales_tensorproto])
1350
+ if not self.config.is_symmetric:
1351
+ zp_tensorproto = onnx.helper.make_tensor(
1352
+ data_tensorproto.name + "_zero_points", qtype, scales.shape, zero_points.tobytes(), True
1353
+ )
1354
+ input_names.append(zp_tensorproto.name)
1355
+ data_graphproto.initializer.extend([zp_tensorproto])
1356
+
1357
+ try:
1358
+ gather_axis = onnx.helper.get_node_attr_value(node, "axis")
1359
+ except ValueError:
1360
+ gather_axis = 0
1361
+
1362
+ kwargs = {
1363
+ "gather_axis": gather_axis,
1364
+ "quantize_axis": quantize_axis,
1365
+ "block_size": block_size,
1366
+ }
1367
+
1368
+ gather_q4_node = onnx.helper.make_node(
1369
+ "GatherBlockQuantized",
1370
+ inputs=input_names,
1371
+ outputs=[node.output[0]],
1372
+ name=node.name + "_Q4" if node.name else "",
1373
+ domain="com.microsoft",
1374
+ **kwargs,
1375
+ )
1376
+
1377
+ return [gather_q4_node]
1378
+
1379
+ def quantize(self, node: NodeProto, graph_stack: list[GraphProto]) -> list[NodeProto]:
1380
+ """
1381
+ Target node: QOperator node: QDQ nodes:
1382
+ MatMul MatMulNBits DeQuantizeLinear -> MatMul
1383
+ Gather GatherBlockQuantized Gather, Gather, Gather (optional) -> DequantizeLinear
1384
+ If the node is target node with fp32 or fp16 const weight, quantize the weight to int4 and
1385
+ return the new nodes.
1386
+ If QOperator format, return the corresponding QOperator nodes.
1387
+ If QDQ format, return the corresdponging QDQ nodes.
1388
+ Gather (quantized data) + Gather (scales) + Gather (optional, zero points) -> DequantizeLinear is
1389
+ not supported yet because Gather does not support int4 data.
1390
+ """
1391
+ logger.info(f"start to quantize {node.name} ...")
1392
+
1393
+ bits = self.config.bits
1394
+ if node.op_type == "MatMul":
1395
+ if bits == 8 and self.config.quant_format == QuantFormat.QDQ:
1396
+ logger.error("MatMul only supports QOperator format for 8 bits quantization.")
1397
+ return [node]
1398
+ results = self.quantize_matmul(node, graph_stack)
1399
+ elif node.op_type == "Gather":
1400
+ if self.config.bits != 4:
1401
+ logger.error("Gather only supports 4 bits quantization.")
1402
+ return [node]
1403
+
1404
+ results = self.quantize_gather(node, graph_stack)
1405
+ else:
1406
+ logger.error(f"Unsupported operator {node.op_type} for weight only quantization. Skip quantization.")
1407
+ return [node]
1408
+
1409
+ logger.info(f"complete quantization of {node.name} with {self.config.bits} bits ...")
1410
+ return results
1411
+
1412
+
1413
+ class NVAWQWeightOnlyQuantizer:
1414
+ def __init__(
1415
+ self,
1416
+ config: NVAWQWeightOnlyQuantConfig,
1417
+ ):
1418
+ self.config = config
1419
+
1420
+ def quantize_awq(self, model: ModelProto | str) -> ModelProto:
1421
+ """
1422
+ Perform nvidia_awq quantization using ModelOpt's int4 quantize function.
1423
+
1424
+ Args:
1425
+ model (ModelProto): The ONNX model to quantize.
1426
+
1427
+ Returns:
1428
+ ModelProto: The quantized ONNX model.
1429
+ """
1430
+ try:
1431
+ from modelopt.onnx.quantization.int4 import quantize as quantize_int4 # noqa: PLC0415
1432
+ except ImportError:
1433
+ print(
1434
+ "Please ensure that the 'modelopt' package is installed. Please install it using pip install nvidia_modelopt."
1435
+ )
1436
+ raise ImportError(
1437
+ "modelopt is not installed. Please install it using pip install nvidia_modelopt. Exiting."
1438
+ ) from None
1439
+
1440
+ logger.info("Starting nvidia_awq quantization...")
1441
+
1442
+ # Prepare calibration inputs
1443
+ calib_inputs = self.config.calibration_data_reader
1444
+
1445
+ # Perform quantization using ModelOpt's int4 quantize function
1446
+ quantized_model = quantize_int4(
1447
+ model,
1448
+ calibration_method=self.config.calibration_method,
1449
+ calibration_data_reader=calib_inputs,
1450
+ )
1451
+
1452
+ logger.info("Completed nvidia_awq quantization.")
1453
+ return quantized_model
1454
+
1455
+
1456
+ class MatMulNBitsQuantizer:
1457
+ """
1458
+ Target node: QOperator node: QDQ nodes:
1459
+ MatMul MatMulNBits DeQuantizeLinear -> MatMul
1460
+ Gather GatherBlockQuantized Gather, Gather, Gather (optional) -> DequantizeLinear
1461
+
1462
+ Perform 2/4/8 bits quantization of constant weights for target nodes.
1463
+ If algo_config.quant_format is QOperator:
1464
+ - nodes are replaced by the corresponding QOperator nodes.
1465
+ - quantized weights are stored in the contrib ops.
1466
+ If algo_config.quant_format is QDQ:
1467
+ - the quantized weight is stored in a standard onnx node. For MatMul, it is DequantizeLinear. For Gather,
1468
+ it is the three Gathers, one for quantized data, one for scales and one for optional zero points.
1469
+ - The nodes are replaced by the corresponding QDQ nodes.
1470
+ - currently Gather is not supported in QDQ because Gather does not support int4 yet.
1471
+ Note:
1472
+ - for quantized gather, the memory usage of "DequantizeLinear + Gather" is the same as the original Gather
1473
+ during runtime. Therefor it is not recommended.
1474
+ - when a node is in nodes_to_exclude, and the node configuration in algo_config.customized_weight_config will be ignored.
1475
+ """
1476
+
1477
+ def __init__(
1478
+ self,
1479
+ model: ModelProto | str,
1480
+ bits: int = 4, # default to 4bit
1481
+ block_size: int = 128,
1482
+ is_symmetric: bool = False,
1483
+ accuracy_level: int | None = None,
1484
+ nodes_to_exclude=None,
1485
+ nodes_to_include: list[str] | None = None,
1486
+ quant_format=QuantFormat.QOperator,
1487
+ op_types_to_quantize: tuple[str, ...] | None = None,
1488
+ quant_axes: tuple[tuple[str, int], ...] | None = None,
1489
+ channel_wised_quantize: bool = False,
1490
+ algo_config: WeightOnlyQuantConfig | None = None,
1491
+ ):
1492
+ if nodes_to_exclude is None:
1493
+ nodes_to_exclude = []
1494
+ self.model = ONNXModel(onnx.load(model)) if isinstance(model, str) else ONNXModel(model)
1495
+ self.model_path = model if isinstance(model, str) else None
1496
+ self.bits = bits
1497
+ self.block_size = block_size
1498
+ self.is_symmetric = is_symmetric
1499
+ self.accuracy_level = accuracy_level
1500
+ self.nodes_to_exclude = set(nodes_to_exclude)
1501
+ self.nodes_to_include = set(nodes_to_include) if nodes_to_include else None
1502
+ self.node_quantizer = None
1503
+
1504
+ if algo_config is None:
1505
+ algo_config = DefaultWeightOnlyQuantConfig(
1506
+ block_size=block_size,
1507
+ is_symmetric=is_symmetric,
1508
+ accuracy_level=accuracy_level,
1509
+ quant_format=quant_format,
1510
+ op_types_to_quantize=op_types_to_quantize,
1511
+ quant_axes=quant_axes,
1512
+ bits=bits,
1513
+ channel_wised_quantize=channel_wised_quantize,
1514
+ )
1515
+
1516
+ self.algo_config = algo_config
1517
+ if hasattr(self.algo_config, "bits"):
1518
+ assert self.algo_config.bits in [2, 4, 8], "Only support 2, 4 or 8 bits quantization"
1519
+
1520
+ if algo_config.algorithm == "HQQ":
1521
+ self.node_quantizer = HQQWeightOnlyQuantizer(self.algo_config)
1522
+ elif algo_config.algorithm == "DEFAULT":
1523
+ self.node_quantizer = DefaultWeightOnlyQuantizer(self.algo_config)
1524
+ elif algo_config.algorithm == "nvidia_awq":
1525
+ self.node_quantizer = NVAWQWeightOnlyQuantizer(self.algo_config)
1526
+
1527
+ def _process_subgraph(self, graph_stack: list[GraphProto]):
1528
+ new_nodes = []
1529
+ graph = graph_stack[-1]
1530
+
1531
+ for node in graph.node:
1532
+ graph_attrs = [
1533
+ attr
1534
+ for attr in node.attribute
1535
+ if attr.type == onnx.AttributeProto.GRAPH or attr.type == onnx.AttributeProto.GRAPHS
1536
+ ]
1537
+ if graph_attrs:
1538
+ kwargs = {}
1539
+ for attr in node.attribute:
1540
+ if attr.type == onnx.AttributeProto.GRAPH:
1541
+ # recursive call to take care of sub-graph
1542
+ graph_stack.append(attr.g)
1543
+ kv = {attr.name: self._process_subgraph(graph_stack)}
1544
+ elif attr.type == onnx.AttributeProto.GRAPHS:
1545
+ value = []
1546
+ for subgraph in attr.graphs:
1547
+ # recursive call to take care of sub-graph
1548
+ graph_stack.append(subgraph)
1549
+ value.extend([self._process_subgraph(graph_stack)])
1550
+ kv = {attr.name: value}
1551
+ else:
1552
+ kv = attribute_to_kwarg(attr)
1553
+ kwargs.update(kv)
1554
+ node = onnx.helper.make_node( # noqa: PLW2901
1555
+ node.op_type, node.input, node.output, name=node.name, **kwargs
1556
+ )
1557
+ out_nodes = []
1558
+ if node.name in self.nodes_to_exclude:
1559
+ logger.info(f"exclude to quantize {node.name} as specified by nodes_to_exclude...")
1560
+ out_nodes = [node]
1561
+ elif (self.nodes_to_include and node.name in self.nodes_to_include) or (
1562
+ node.op_type in self.algo_config.op_types_to_quantize
1563
+ ):
1564
+ out_nodes = self.node_quantizer.quantize(node, graph_stack)
1565
+ else:
1566
+ logger.info(f"skip to quantize {node.name} ...")
1567
+ out_nodes = [node]
1568
+ new_nodes.extend(out_nodes)
1569
+
1570
+ graph.ClearField("node")
1571
+ graph.node.extend(new_nodes)
1572
+ graph_stack.pop()
1573
+ return graph
1574
+
1575
+ def _generate_q4_node_config(self):
1576
+ """Generate weight only quant configuration for nodes."""
1577
+ q4_node_config = {}
1578
+ for node in self.model.model.graph.node:
1579
+ if node.op_type in ["MatMul"]:
1580
+ if not all(self.model.get_initializer(i) is None for i in node.input):
1581
+ template_config_q4 = {
1582
+ "bits": 4,
1583
+ "group_size": self.block_size,
1584
+ "scheme": "sym" if self.is_symmetric else "asym",
1585
+ }
1586
+ if (
1587
+ self.algo_config.customized_weight_config
1588
+ and node.name in self.algo_config.customized_weight_config
1589
+ ):
1590
+ for key, value in self.algo_config.customized_weight_config[node.name].items():
1591
+ if key in template_config_q4:
1592
+ template_config_q4[key] = value
1593
+ q4_node_config[node.name] = template_config_q4
1594
+ return q4_node_config
1595
+
1596
+ def int4_quant_algo(self):
1597
+ """4b quantize a model with RTN or GPTQ algorithm. Please refer to
1598
+ https://github.com/intel/neural-compressor/blob/master/docs/source/quantization_weight_only.md
1599
+ for more details on weight only quantization using Intel® Neural Compressor.
1600
+ """
1601
+
1602
+ def inc_dataloader():
1603
+ data_reader = copy.deepcopy(self.algo_config.calibration_data_reader)
1604
+ for data in data_reader:
1605
+ yield data, None
1606
+
1607
+ kwargs = {}
1608
+ if self.accuracy_level is not None:
1609
+ kwargs["accuracy_level"] = self.accuracy_level
1610
+ weight_only_node_config = self._generate_q4_node_config()
1611
+
1612
+ algorithm = self.algo_config.algorithm
1613
+ logger.info(f"start to quantize model with {algorithm} algorithm...")
1614
+ if algorithm in ["RTN", "k_quant"]:
1615
+ kwargs["ratios"] = self.algo_config.ratios
1616
+ kwargs["algorithm"] = algorithm
1617
+
1618
+ """
1619
+ We uses fp32 to represent the node that skip quantization, it does not mean this node is fp32 type though.
1620
+ """
1621
+ for n in self.nodes_to_exclude:
1622
+ weight_only_node_config[n] = "fp32"
1623
+
1624
+ self.model = rtn_quantize(
1625
+ model=self.model_path if self.model_path is not None else self.model.model,
1626
+ weight_config=weight_only_node_config,
1627
+ **kwargs,
1628
+ )
1629
+ elif algorithm == "GPTQ":
1630
+ kwargs["percdamp"] = self.algo_config.percdamp
1631
+ kwargs["blocksize"] = self.algo_config.block_size
1632
+ kwargs["actorder"] = self.algo_config.actorder
1633
+ kwargs["mse"] = self.algo_config.mse
1634
+ kwargs["perchannel"] = self.algo_config.perchannel
1635
+ kwargs["n_samples"] = -1
1636
+ dataloader = inc_dataloader()
1637
+
1638
+ self.model = gptq_quantize(
1639
+ model=self.model_path if self.model_path is not None else self.model.model,
1640
+ weight_config=weight_only_node_config,
1641
+ dataloader=dataloader,
1642
+ **kwargs,
1643
+ )
1644
+ logger.info(f"complete quantization of model with {algorithm} algorithm.")
1645
+
1646
+ def process(self):
1647
+ if self.algo_config.algorithm in ["HQQ", "DEFAULT"]:
1648
+ # use a stack to keep track of sub-graphs
1649
+ graph_stack = [self.model.graph()]
1650
+
1651
+ # Update domain opset
1652
+ if self.algo_config.quant_format == QuantFormat.QOperator:
1653
+ self.model.set_opset_import("com.microsoft", 1)
1654
+
1655
+ if self.algo_config.quant_format == QuantFormat.QDQ or "Gather" in self.algo_config.op_types_to_quantize:
1656
+ opset_import = self.model.opset_import()
1657
+ for opset in opset_import:
1658
+ if opset.domain in [None, "ai.onnx", ""] and opset.version < 21:
1659
+ logger.warning(
1660
+ "The opset of the input model is under 21 and doesn't support int4 data type. "
1661
+ "Force to update it to opset 21, but the generated model may not be a valid model."
1662
+ )
1663
+ self.model.set_opset_import(opset.domain, 21)
1664
+
1665
+ self._process_subgraph(graph_stack)
1666
+ self.model.clean_initializers()
1667
+ elif self.algo_config.algorithm == "nvidia_awq":
1668
+ # Handle nvidia_awq quantization
1669
+ logger.info("Processing nvidia_awq quantization...")
1670
+ self.model = self.node_quantizer.quantize_awq(
1671
+ self.model.model if self.model_path is None else self.model_path
1672
+ )
1673
+ logger.info("Completed nvidia_awq quantization.")
1674
+ self.model = ONNXModel(self.model) # Ensure the model is wrapped back into ONNXModel
1675
+ self.model.clean_initializers()
1676
+ else:
1677
+ # RTN or GPTQ weight-only quantize algorithm
1678
+ self.int4_quant_algo()
1679
+
1680
+
1681
+ def ort_convert_str_to_bool(value):
1682
+ return value.lower() in ("true", "1")
1683
+
1684
+
1685
+ # Custom function to parse str:int pairs
1686
+ def parse_key_value_pair(s):
1687
+ key, value = s.split(":")
1688
+ return key, int(value)
1689
+
1690
+
1691
+ def parse_args():
1692
+ parser = argparse.ArgumentParser(
1693
+ description="""Blockwise int4 quantization for MatMul 2D weight matrices.
1694
+
1695
+ A weight matrix is partitioned into into blocks, where each block is a
1696
+ continguous subset inside each column. Each block is quantized into a
1697
+ set of 4b integers with a scaling factor and an optional offset.
1698
+ """
1699
+ )
1700
+
1701
+ parser.add_argument("--input_model", required=True, help="Path to the input model file")
1702
+ parser.add_argument("--output_model", required=True, help="Path to the output model file")
1703
+ parser.add_argument("--block_size", required=False, default=32, type=int, help="Block size for quantization")
1704
+ parser.add_argument(
1705
+ "--quant_method",
1706
+ default="default",
1707
+ type=str,
1708
+ choices=["default", "hqq", "rtn", "k_quant", "gptq", "nvidia_awq"],
1709
+ help="the algorithm used to quantize weight, \nrtn and gptq leverage Intel® Neural Compressor",
1710
+ )
1711
+ parser.add_argument("--bits", default=4, type=int, help="the target bits to represent weight")
1712
+ parser.add_argument(
1713
+ "--symmetric",
1714
+ required=False,
1715
+ default=True,
1716
+ const=True,
1717
+ nargs="?",
1718
+ type=ort_convert_str_to_bool,
1719
+ choices=[True, False],
1720
+ help="Indicate whether to quantize the model symmetrically, symmetric is not supported by hqq",
1721
+ )
1722
+ parser.add_argument(
1723
+ "--accuracy_level",
1724
+ required=False,
1725
+ type=int,
1726
+ help="Accuracy level of the 4-bit quantized MatMul computation. "
1727
+ "Refer to the MatMulNBits contrib op's 'accuracy_level' attribute for details "
1728
+ "(https://github.com/microsoft/onnxruntime/blob/main/docs/ContribOperators.md#commicrosoftmatmulnbits).",
1729
+ )
1730
+ parser.add_argument("-v", "--verbose", required=False, action="store_true")
1731
+ parser.set_defaults(verbose=False)
1732
+ parser.add_argument(
1733
+ "--nodes_to_exclude",
1734
+ nargs="+",
1735
+ type=str,
1736
+ required=False,
1737
+ default=[],
1738
+ help="Specify the nodes to be excluded from quantization with node names",
1739
+ )
1740
+ parser.add_argument(
1741
+ "--nodes_to_include",
1742
+ nargs="+",
1743
+ type=str,
1744
+ required=False,
1745
+ help="Specify the specific nodes to be included from quantization with node names",
1746
+ )
1747
+ parser.add_argument(
1748
+ "--quant_format",
1749
+ default="QOperator",
1750
+ type=str,
1751
+ choices=["QOperator", "QDQ"],
1752
+ help="QuantFormat {QOperator, QDQ}"
1753
+ "QOperator format quantizes the model with quantized operators directly."
1754
+ "QDQ format quantize the model by inserting DeQuantizeLinear before the MatMul.",
1755
+ )
1756
+ parser.add_argument(
1757
+ "--op_types_to_quantize",
1758
+ type=str,
1759
+ nargs="+",
1760
+ choices=["MatMul", "Gather"],
1761
+ help="op_types_to_quantize {MatMul, Gather}. Operators to quantize. Default is MatMul.",
1762
+ )
1763
+ parser.add_argument(
1764
+ "--quant_axes",
1765
+ type=parse_key_value_pair,
1766
+ nargs="+",
1767
+ required=False,
1768
+ help="Key-value pairs in op_type:axis_to_quantize separated by space."
1769
+ "Specify the axis to quantize for an op. Default {MatMul:0, Gather:1}"
1770
+ "Example: --quant_axes MatMul:0 Gather:1",
1771
+ )
1772
+ # Group arguments specific to nvidia_awq
1773
+ nv_awq_config = parser.add_argument_group("nvidia_awq", "Arguments specific to nvidia_awq quantization")
1774
+ nv_awq_config.add_argument(
1775
+ "--calib_dataset_name",
1776
+ type=str,
1777
+ default="cnn",
1778
+ help="Name of the calibration dataset for nvidia_awq.",
1779
+ )
1780
+ nv_awq_config.add_argument(
1781
+ "--tokenizer_dir",
1782
+ type=str,
1783
+ required=False,
1784
+ help="Path of the tokenizer dir.",
1785
+ )
1786
+ nv_awq_config.add_argument(
1787
+ "--calibration_method",
1788
+ type=str,
1789
+ required=False,
1790
+ choices=["awq", "awq_clip"],
1791
+ help="Support two options, awq implementation and weight clipping.",
1792
+ )
1793
+ nv_awq_config.add_argument(
1794
+ "--cache_dir",
1795
+ type=str,
1796
+ default="./cache",
1797
+ help="Cache directory for calibration data.",
1798
+ )
1799
+ return parser.parse_args()
1800
+
1801
+
1802
+ if __name__ == "__main__":
1803
+ args = parse_args()
1804
+ if args.verbose:
1805
+ logger.setLevel(logging.DEBUG)
1806
+
1807
+ input_model_path = args.input_model
1808
+ output_model_path = args.output_model
1809
+ quant_format = QuantFormat[args.quant_format]
1810
+ op_types_to_quantize = tuple(args.op_types_to_quantize) if args.op_types_to_quantize else ("MatMul",)
1811
+ quant_axes = tuple(args.quant_axes) if args.quant_axes else None
1812
+
1813
+ if os.path.exists(output_model_path):
1814
+ logger.error(f"file {output_model_path} already exists")
1815
+ raise Exception(f"file {output_model_path} already exists")
1816
+
1817
+ if args.symmetric and args.quant_method == "hqq":
1818
+ logger.warning("symmetric is not supportted by hqq, will force to symmetric=False")
1819
+ args.symmetric = False
1820
+
1821
+ model = onnx.load(input_model_path)
1822
+ if args.quant_method == "hqq":
1823
+ quant_config = HQQWeightOnlyQuantConfig(
1824
+ block_size=args.block_size, bits=args.bits, op_types_to_quantize=op_types_to_quantize, quant_axes=quant_axes
1825
+ )
1826
+ elif args.quant_method == "default":
1827
+ quant_config = DefaultWeightOnlyQuantConfig(
1828
+ block_size=args.block_size,
1829
+ is_symmetric=args.symmetric,
1830
+ accuracy_level=args.accuracy_level,
1831
+ quant_format=quant_format,
1832
+ op_types_to_quantize=op_types_to_quantize,
1833
+ quant_axes=quant_axes,
1834
+ bits=args.bits,
1835
+ )
1836
+ elif args.quant_method == "rtn":
1837
+ quant_config = RTNWeightOnlyQuantConfig(op_types_to_quantize=op_types_to_quantize)
1838
+ elif args.quant_method == "k_quant":
1839
+ quant_config = KQuantWeightOnlyQuantConfig(op_types_to_quantize=op_types_to_quantize)
1840
+ elif args.quant_method == "gptq":
1841
+ quant_config = GPTQWeightOnlyQuantConfig(block_size=args.block_size, op_types_to_quantize=op_types_to_quantize)
1842
+ elif args.quant_method == "nvidia_awq":
1843
+ if quant_format == QuantFormat.QOperator:
1844
+ logger.warning("QOperator is not applicable to nvidia_awq. overriding the value to QDQ")
1845
+ quant_format = QuantFormat.QDQ
1846
+
1847
+ model = input_model_path
1848
+ if args.calibration_method is not None:
1849
+ if args.calibration_method == "awq":
1850
+ calibration_method = "awq_lite"
1851
+ else:
1852
+ calibration_method = "awq_clip"
1853
+ else:
1854
+ calibration_method = "awq_lite"
1855
+
1856
+ quant_config = NVAWQWeightOnlyQuantConfig(
1857
+ dataset_name=args.calib_dataset_name,
1858
+ tokenizer_dir=args.tokenizer_dir,
1859
+ cache_dir=args.cache_dir,
1860
+ calibration_method=calibration_method,
1861
+ )
1862
+ else:
1863
+ raise ValueError(f"Unsupported quantization method: {args.quant_method}")
1864
+
1865
+ quant = MatMulNBitsQuantizer(
1866
+ model=model,
1867
+ bits=args.bits,
1868
+ accuracy_level=args.accuracy_level,
1869
+ nodes_to_exclude=args.nodes_to_exclude,
1870
+ nodes_to_include=args.nodes_to_include,
1871
+ algo_config=quant_config,
1872
+ )
1873
+ quant.process()
1874
+ quant.model.save_model_to_file(output_model_path, True)
ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/quantization/neural_compressor/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ from .weight_only import gptq_quantize, rtn_quantize # noqa: F401
ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/quantization/neural_compressor/onnx_model.py ADDED
@@ -0,0 +1,1236 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # The implementation of this file is based on:
3
+ # https://github.com/intel/neural-compressor/tree/master/neural_compressor
4
+ #
5
+ # Copyright (c) 2023 Intel Corporation
6
+ #
7
+ # Licensed under the Apache License, Version 2.0 (the "License");
8
+ # you may not use this file except in compliance with the License.
9
+ # You may obtain a copy of the License at
10
+ #
11
+ # http://www.apache.org/licenses/LICENSE-2.0
12
+ #
13
+ # Unless required by applicable law or agreed to in writing, software
14
+ # distributed under the License is distributed on an "AS IS" BASIS,
15
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16
+ # See the License for the specific language governing permissions and
17
+ # limitations under the License.
18
+
19
+ """Class for ONNX model."""
20
+
21
+ import copy
22
+ import logging
23
+ import os
24
+ from collections import deque
25
+ from pathlib import Path
26
+
27
+ import onnx
28
+ import onnx.external_data_helper
29
+ import onnx_ir as ir
30
+
31
+ from .util import MAXIMUM_PROTOBUF, find_by_name
32
+
33
+ logger = logging.getLogger("neural_compressor")
34
+
35
+ # TODO: Check https://github.com/microsoft/onnxruntime/blob/main/onnxruntime/python/tools/quantization/onnx_model.py to see if we can integrate with it.
36
+
37
+
38
+ class ONNXModel:
39
+ """Build ONNX model."""
40
+
41
+ def __init__(self, model, **kwargs):
42
+ """Initialize an ONNX model.
43
+
44
+ Args:
45
+ model (str or ModelProto): path to onnx model or loaded ModelProto model object.
46
+ ignore_warning (bool): ignore large model warning. Default is False.
47
+ load_external_data (bool): load external data for large model. Default is True.
48
+ """
49
+ self._model = model if not isinstance(model, str) else onnx.load(model, load_external_data=False)
50
+ self._model_path = None if not isinstance(model, str) else model
51
+
52
+ self.check_is_large_model()
53
+ if self._is_large_model and self._model_path is None and not kwargs.get("ignore_warning", False):
54
+ logger.warning("Model size > 2GB. Please use model path instead of onnx model object to quantize")
55
+
56
+ if self._is_large_model and isinstance(model, str) and kwargs.get("load_external_data", True):
57
+ onnx.external_data_helper.load_external_data_for_model(self._model, os.path.dirname(self._model_path))
58
+
59
+ self._config = None
60
+ if isinstance(model, str) and os.path.exists(Path(model).parent.joinpath("config.json").as_posix()):
61
+ from transformers import AutoConfig # noqa: PLC0415
62
+
63
+ self._config = AutoConfig.from_pretrained(Path(model).parent.as_posix())
64
+
65
+ self.node_name_counter = {}
66
+ self._output_name_to_node = {}
67
+ self._input_name_to_nodes = {}
68
+ self._get_input_name_to_nodes(self._model.graph.node)
69
+ self._get_output_name_to_node(self._model.graph.node)
70
+ self._graph_info = {}
71
+ self._get_graph_info()
72
+ self._q_config = None
73
+
74
+ def check_is_large_model(self):
75
+ """Check model > 2GB."""
76
+ ir_graph = ir.from_proto(self._model.graph)
77
+ initializer_size = sum(
78
+ v.const_value.nbytes for v in ir_graph.initializers.values() if v.const_value is not None
79
+ )
80
+ self._is_large_model = initializer_size > MAXIMUM_PROTOBUF
81
+
82
+ @property
83
+ def is_large_model(self):
84
+ """Check the onnx model is over 2GB."""
85
+ return self._is_large_model
86
+
87
+ @property
88
+ def model_path(self):
89
+ """Return model path."""
90
+ return self._model_path
91
+
92
+ @model_path.setter
93
+ def model_path(self, path):
94
+ """Set model path."""
95
+ self._model_path = path
96
+
97
+ def framework(self):
98
+ """Return framework."""
99
+ return "onnxruntime"
100
+
101
+ @property
102
+ def q_config(self):
103
+ """Return q_config."""
104
+ return self._q_config
105
+
106
+ @q_config.setter
107
+ def q_config(self, q_config):
108
+ """Set q_config."""
109
+ self._q_config = q_config
110
+
111
+ @property
112
+ def hf_config(self):
113
+ """Return huggingface config if model is Transformer-based."""
114
+ return self._config
115
+
116
+ @property
117
+ def model(self):
118
+ """Return model itself."""
119
+ return self._model
120
+
121
+ @model.setter
122
+ def model(self, model):
123
+ """Set model itself."""
124
+ self._model = model
125
+ self._graph_info = {}
126
+ self._get_graph_info()
127
+ self._output_name_to_node = {}
128
+ self._input_name_to_nodes = {}
129
+ self._get_input_name_to_nodes(self._model.graph.node)
130
+ self._get_output_name_to_node(self._model.graph.node)
131
+
132
+ def input(self):
133
+ """Return input of model."""
134
+ return [i.name for i in self._model.graph.input]
135
+
136
+ def output(self):
137
+ """Return output of model."""
138
+ return [i.name for i in self._model.graph.output]
139
+
140
+ def update(self):
141
+ """Update model info."""
142
+ self._graph_info = {}
143
+ self._get_graph_info()
144
+ self._output_name_to_node = {}
145
+ self._input_name_to_nodes = {}
146
+ self._get_input_name_to_nodes(self._model.graph.node)
147
+ self._get_output_name_to_node(self._model.graph.node)
148
+
149
+ @property
150
+ def graph_info(self):
151
+ """Return ORT Graph Info object holding information about backend graph."""
152
+ return self._graph_info
153
+
154
+ def _get_graph_info(self):
155
+ """Update graph info."""
156
+ for node in self._model.graph.node:
157
+ self.graph_info.update({node.name: node.op_type})
158
+
159
+ def save(self, root):
160
+ """Save ONNX model."""
161
+ if os.path.split(root)[0] != "" and not os.path.exists(os.path.split(root)[0]):
162
+ raise ValueError('"root" directory does not exists.')
163
+ if self.is_large_model:
164
+ onnx.external_data_helper.load_external_data_for_model(self._model, os.path.split(self._model_path)[0])
165
+ onnx.save_model(
166
+ self._model,
167
+ root,
168
+ save_as_external_data=True,
169
+ all_tensors_to_one_file=True,
170
+ location=root.split("/")[-1] + "_data",
171
+ size_threshold=1024,
172
+ convert_attribute=False,
173
+ )
174
+ else:
175
+ onnx.save(self._model, root)
176
+
177
+ if self._config is not None:
178
+ model_type = "" if not hasattr(self._config, "model_type") else self._config.model_type
179
+ self._config.__class__.model_type = model_type
180
+ output_config_file = Path(root).parent.joinpath("config.json").as_posix()
181
+ self._config.to_json_file(output_config_file, use_diff=False)
182
+
183
+ def nodes(self):
184
+ """Return model nodes."""
185
+ return self._model.graph.node
186
+
187
+ def initializer(self):
188
+ """Return model initializer."""
189
+ return self._model.graph.initializer
190
+
191
+ def graph(self):
192
+ """Return model graph."""
193
+ return self._model.graph
194
+
195
+ def ir_version(self):
196
+ """Return model ir_version."""
197
+ return self._model.ir_version
198
+
199
+ def opset_import(self):
200
+ """Return model opset_import."""
201
+ return self._model.opset_import
202
+
203
+ def remove_node(self, node):
204
+ """Remove a node from model."""
205
+ if node in self._model.graph.node:
206
+ self._model.graph.node.remove(node)
207
+
208
+ def remove_nodes(self, nodes_to_remove):
209
+ """Remove nodes from model."""
210
+ for node in nodes_to_remove:
211
+ self.remove_node(node)
212
+
213
+ def add_node(self, node):
214
+ """Add a node to model."""
215
+ self._model.graph.node.extend([node])
216
+
217
+ def add_nodes(self, nodes_to_add):
218
+ """Add nodes to model."""
219
+ self._model.graph.node.extend(nodes_to_add)
220
+
221
+ def add_initializer(self, tensor):
222
+ """Add a initializer to model."""
223
+ if find_by_name(tensor.name, self._model.graph.initializer) is None:
224
+ self._model.graph.initializer.extend([tensor])
225
+
226
+ def add_initializers(self, tensors):
227
+ """Add initializers to model."""
228
+ for tensor in tensors:
229
+ self.add_initializer(tensor)
230
+
231
+ def get_initializer(self, name):
232
+ """Get an initializer by name."""
233
+ for tensor in self._model.graph.initializer:
234
+ if tensor.name == name:
235
+ return tensor
236
+ return None
237
+
238
+ def get_initializer_share_num(self, name):
239
+ """Get the number of shares of initializer."""
240
+ num = 0
241
+ if self.get_initializer(name) is None:
242
+ return num
243
+
244
+ for node in self.nodes():
245
+ if name in node.input:
246
+ num += 1
247
+ return num
248
+
249
+ def get_node(self, name):
250
+ """Get a node by name."""
251
+ for node in self._model.graph.node:
252
+ if node.name == name:
253
+ return node
254
+ return None
255
+
256
+ def remove_initializer(self, tensor):
257
+ """Remove an initializer from model."""
258
+ if tensor in self._model.graph.initializer:
259
+ self._model.graph.initializer.remove(tensor)
260
+
261
+ def remove_initializers(self, init_to_remove):
262
+ """Remove initializers from model."""
263
+ for initializer in init_to_remove:
264
+ self.remove_initializer(initializer)
265
+
266
+ def set_initializer(self, tensor, array, raw=False):
267
+ """Update initializer."""
268
+ old_tensor = self.get_initializer(tensor)
269
+ self.remove_initializer(old_tensor)
270
+ dims = old_tensor.dims
271
+ data_type = old_tensor.data_type
272
+ new_tensor = (
273
+ onnx.helper.make_tensor(tensor, data_type, dims, array.flatten().tolist())
274
+ if not raw
275
+ else onnx.helper.make_tensor(tensor, data_type, dims, array.tostring(), raw=raw)
276
+ )
277
+ self.add_initializer(new_tensor)
278
+
279
+ @property
280
+ def input_name_to_nodes(self):
281
+ """Return input names of nodes."""
282
+ return self._input_name_to_nodes
283
+
284
+ def _get_input_name_to_nodes(self, nodes):
285
+ """Get input names of nodes."""
286
+ for node in nodes:
287
+ attrs = [
288
+ attr
289
+ for attr in node.attribute
290
+ if attr.type == onnx.AttributeProto.GRAPH or attr.type == onnx.AttributeProto.GRAPHS
291
+ ]
292
+ if len(attrs) > 0:
293
+ for attr in attrs:
294
+ self._get_input_name_to_nodes(attr.g.node)
295
+ for input_name in node.input:
296
+ if len(input_name.strip()) != 0:
297
+ if input_name not in self._input_name_to_nodes:
298
+ self._input_name_to_nodes[input_name] = [node]
299
+ else:
300
+ self._input_name_to_nodes[input_name].append(node)
301
+
302
+ @property
303
+ def output_name_to_node(self):
304
+ """Return output names of nodes."""
305
+ return self._output_name_to_node
306
+
307
+ def _get_output_name_to_node(self, nodes):
308
+ """Get output names of nodes."""
309
+ for node in nodes:
310
+ attrs = [
311
+ attr
312
+ for attr in node.attribute
313
+ if attr.type == onnx.AttributeProto.GRAPH or attr.type == onnx.AttributeProto.GRAPHS
314
+ ]
315
+ if len(attrs) > 0:
316
+ for attr in attrs:
317
+ self._get_output_name_to_node(attr.g.node)
318
+ for output_name in node.output:
319
+ if len(output_name.strip()) != 0:
320
+ self._output_name_to_node[output_name] = node
321
+
322
+ def get_siblings(self, node):
323
+ """Get siblings nodes."""
324
+ siblings = []
325
+ for parent in self.get_parents(node):
326
+ for child in self.get_children(parent):
327
+ if child.name != node.name:
328
+ siblings.append(child)
329
+ return siblings
330
+
331
+ def get_children(self, node, input_name_to_nodes=None):
332
+ """Get children nodes."""
333
+ if input_name_to_nodes is None:
334
+ input_name_to_nodes = self._input_name_to_nodes
335
+
336
+ children = []
337
+ for output in node.output:
338
+ if output in input_name_to_nodes:
339
+ for child in input_name_to_nodes[output]:
340
+ children.append(child) # noqa: PERF402
341
+ return children
342
+
343
+ def get_parents(self, node, output_name_to_node=None):
344
+ """Get parents nodes."""
345
+ if output_name_to_node is None:
346
+ output_name_to_node = self._output_name_to_node
347
+
348
+ parents = []
349
+ for input in node.input:
350
+ if input in output_name_to_node:
351
+ parents.append(output_name_to_node[input])
352
+ return parents
353
+
354
+ def get_parent(self, node, idx, output_name_to_node=None):
355
+ """Get parent node by idx."""
356
+ if output_name_to_node is None:
357
+ output_name_to_node = self._output_name_to_node
358
+
359
+ if len(node.input) <= idx:
360
+ return None
361
+
362
+ input = node.input[idx]
363
+ if input not in output_name_to_node:
364
+ return None
365
+
366
+ return output_name_to_node[input]
367
+
368
+ def find_node_by_name(self, node_name, new_nodes_list, graph):
369
+ """Find out node by name."""
370
+ graph_nodes_list = list(graph.node) # deep copy
371
+ graph_nodes_list.extend(new_nodes_list)
372
+ node = find_by_name(node_name, graph_nodes_list)
373
+ return node
374
+
375
+ def find_nodes_by_initializer(self, graph, initializer):
376
+ """Find all nodes with given initializer as an input."""
377
+ nodes = []
378
+ for node in graph.node:
379
+ for node_input in node.input:
380
+ if node_input == initializer.name:
381
+ nodes.append(node)
382
+ return nodes
383
+
384
+ def get_scale_zero(self, tensor):
385
+ """Help function to get scale and zero_point."""
386
+ if not tensor.endswith("_quantized"):
387
+ logger.debug(f"Find {tensor} in the quantized graph is not quantized.")
388
+ return None, None
389
+
390
+ def _searcher(tensor_name):
391
+ """Search scale and zero point tensor recursively."""
392
+ node = self._input_name_to_nodes[tensor_name][0]
393
+ parent = self._output_name_to_node.get(tensor_name, None)
394
+ direct_int8 = ["Reshape", "Transpose", "Squeeze", "Unsqueeze", "MaxPool", "Pad", "Split"]
395
+ if parent is not None and parent.op_type in direct_int8:
396
+ fp32_tensor_name = (
397
+ parent.input[0]
398
+ .replace("_quantized", "")
399
+ .replace("_QuantizeLinear", "")
400
+ .replace("_QuantizeInput", "")
401
+ )
402
+ elif node.op_type in ["Gather"]: # pragma: no cover
403
+ fp32_tensor_name = (
404
+ node.output[0]
405
+ .replace("_quantized", "")
406
+ .replace("_QuantizeLinear", "")
407
+ .replace("_QuantizeInput", "")
408
+ )
409
+ else:
410
+ fp32_tensor_name = (
411
+ tensor_name.replace("_quantized", "").replace("_QuantizeLinear", "").replace("_QuantizeInput", "")
412
+ )
413
+ scale = fp32_tensor_name + "_scale"
414
+ scale_tensor = self.get_initializer(scale)
415
+ zo = fp32_tensor_name + "_zero_point"
416
+ zo_tensor = self.get_initializer(zo)
417
+
418
+ if scale_tensor is None or zo_tensor is None:
419
+ if parent is not None:
420
+ scale_tensor, zo_tensor = _searcher(parent.input[0])
421
+ return scale_tensor, zo_tensor
422
+
423
+ node = self._input_name_to_nodes[tensor][0]
424
+ # TODO check if scale_tensor and zero_point is needed
425
+ # for bias of qlinearconv, scale and zero_point is not needed
426
+ if (node.op_type == "QLinearConv" and tensor == node.input[-1]) or (
427
+ node.op_type == "QGemm" and tensor == node.input[-3]
428
+ ):
429
+ return None, None
430
+ else:
431
+ scale_tensor, zo_tensor = _searcher(tensor)
432
+ assert scale_tensor, f"missing scale for tensor {tensor}"
433
+ assert zo_tensor, f"missing zero point for tensor {tensor}"
434
+ return scale_tensor, zo_tensor
435
+
436
+ def save_model_to_file(self, output_path, use_external_data_format=False):
437
+ """Save model to external data, which is needed for model size > 2GB."""
438
+ if use_external_data_format:
439
+ onnx.external_data_helper.convert_model_to_external_data(
440
+ self._model, all_tensors_to_one_file=True, location=Path(output_path).name + ".data"
441
+ )
442
+ onnx.save_model(self._model, output_path)
443
+
444
+ @staticmethod
445
+ def replace_node_input(node, old_input_name, new_input_name):
446
+ """Replace input of a node."""
447
+ assert isinstance(old_input_name, str) and isinstance(new_input_name, str)
448
+ for j in range(len(node.input)):
449
+ if node.input[j] == old_input_name:
450
+ node.input[j] = new_input_name
451
+
452
+ def replace_input_of_all_nodes(self, old_input_name, new_input_name, white_optype=None, black_optype=None):
453
+ """Replace inputs of all nodes."""
454
+ if white_optype is None:
455
+ white_optype = []
456
+ if black_optype is None:
457
+ black_optype = []
458
+ if len(white_optype) > 0:
459
+ for node in self.model.graph.node:
460
+ if node.op_type in white_optype:
461
+ ONNXModel.replace_node_input(node, old_input_name, new_input_name)
462
+ else:
463
+ for node in self.model.graph.node:
464
+ if node.op_type not in black_optype:
465
+ ONNXModel.replace_node_input(node, old_input_name, new_input_name)
466
+
467
+ @staticmethod
468
+ def replace_node_output(node, old_output_name, new_output_name):
469
+ """Replace output of a node."""
470
+ assert isinstance(old_output_name, str) and isinstance(new_output_name, str)
471
+ for j in range(len(node.output)):
472
+ if node.output[j] == old_output_name:
473
+ node.output[j] = new_output_name
474
+
475
+ def replace_output_of_all_nodes(self, old_output_name, new_output_name, white_optype=None, black_optype=None):
476
+ """Replace outputs of all nodes."""
477
+ if white_optype is None:
478
+ white_optype = []
479
+ if black_optype is None:
480
+ black_optype = []
481
+ if len(white_optype) > 0:
482
+ for node in self.model.graph.node:
483
+ if node.op_type in white_optype:
484
+ ONNXModel.replace_node_output(node, old_output_name, new_output_name)
485
+ else:
486
+ for node in self.model.graph.node:
487
+ if node.op_type not in black_optype:
488
+ ONNXModel.replace_node_output(node, old_output_name, new_output_name)
489
+
490
+ def remove_unused_nodes(self):
491
+ """Remove unused nodes."""
492
+ unused_nodes = []
493
+ nodes = self.nodes()
494
+ for node in nodes:
495
+ if (
496
+ node.op_type == "Constant"
497
+ and node.output[0] not in self._model.graph.output
498
+ and node.output[0] not in self._input_name_to_nodes
499
+ ):
500
+ unused_nodes.append(node)
501
+ elif (
502
+ node.op_type == "QuantizeLinear"
503
+ and len(self.get_children(node)) == 1
504
+ and self.get_children(node)[0].op_type == "DequantizeLinear"
505
+ and node.input[0] not in self._output_name_to_node
506
+ and self.get_children(node)[0].output[0] not in self._input_name_to_nodes
507
+ ):
508
+ unused_nodes.append(node)
509
+ unused_nodes.extend(self.get_children(node))
510
+ else:
511
+ # remove the node if it does not serve as the input or output of any other nodes
512
+ unused = True
513
+ for output in node.output:
514
+ if output in self._input_name_to_nodes or output in self.output():
515
+ unused = False
516
+ break
517
+ for input in node.input:
518
+ if self.get_initializer(input) is not None:
519
+ continue
520
+ elif input in self._output_name_to_node or input in self.input():
521
+ unused = False
522
+ break
523
+ if unused:
524
+ unused_nodes.append(node)
525
+ self.remove_nodes(unused_nodes)
526
+
527
+ ununsed_weights = []
528
+ for w in self._model.graph.initializer:
529
+ if w.name not in self._input_name_to_nodes and w.name not in self._model.graph.output:
530
+ ununsed_weights.append(w)
531
+ # Remove from graph.input
532
+ for graph_input in self.graph().input:
533
+ if graph_input.name == w.name:
534
+ self.graph().input.remove(graph_input)
535
+
536
+ self.remove_initializers(ununsed_weights)
537
+ self.update()
538
+
539
+ def topological_sort(self, enable_subgraph=False):
540
+ """Topological sort the model."""
541
+
542
+ if not enable_subgraph:
543
+ input_name_to_nodes = {}
544
+ output_name_to_node = {}
545
+ for node in self.model.graph.node:
546
+ for input_name in node.input:
547
+ if len(input_name.strip()) != 0:
548
+ if input_name not in input_name_to_nodes:
549
+ input_name_to_nodes[input_name] = [node]
550
+ else:
551
+ input_name_to_nodes[input_name].append(node)
552
+ for output_name in node.output:
553
+ if len(output_name.strip()) != 0:
554
+ output_name_to_node[output_name] = node
555
+ else: # pragma: no cover
556
+ input_name_to_nodes = self._input_name_to_nodes
557
+ output_name_to_node = self._output_name_to_node
558
+
559
+ all_nodes = {}
560
+ q = deque()
561
+ wait = deque()
562
+ for inp in self.model.graph.input:
563
+ q.extend(input_name_to_nodes[inp.name])
564
+ for n in self.model.graph.node:
565
+ if all(i not in output_name_to_node and i not in self.input() for i in n.input):
566
+ q.append(n)
567
+
568
+ while q:
569
+ n = q.popleft()
570
+ if not all(output_name_to_node[i].name in all_nodes for i in n.input if i in output_name_to_node):
571
+ if n not in wait:
572
+ wait.append(n)
573
+ continue
574
+
575
+ all_nodes[n.name] = n
576
+ for out in n.output:
577
+ if out in input_name_to_nodes:
578
+ q.extend([i for i in input_name_to_nodes[out] if i.name not in all_nodes and i not in q])
579
+ if len(q) == 0 and len(wait) != 0:
580
+ q = copy.deepcopy(wait)
581
+ wait.clear()
582
+ nodes = [i[1] for i in all_nodes.items()]
583
+ assert len(list({n.name for n in nodes})) == len(list({n.name for n in self.model.graph.node}))
584
+ self.model.graph.ClearField("node")
585
+ self.model.graph.node.extend(nodes)
586
+
587
+ def get_nodes_chain(self, start, stop, result_chain=None):
588
+ """Get nodes chain with given start node and stop node."""
589
+ if result_chain is None:
590
+ result_chain = []
591
+ # process start node list
592
+ start_node = deque()
593
+ for node in start:
594
+ if isinstance(node, str):
595
+ start_node.append(node)
596
+ elif isinstance(node, onnx.NodeProto):
597
+ start_node.append(node.name)
598
+ else:
599
+ assert False, "'get_nodes_chain' function only support list[string]or list[NodeProto] params" # noqa: B011
600
+
601
+ # process stop node list
602
+ stop_node = []
603
+ for node in stop:
604
+ if isinstance(node, str):
605
+ stop_node.append(node)
606
+ elif isinstance(node, onnx.NodeProto):
607
+ stop_node.append(node.name)
608
+ else:
609
+ assert False, "'get_nodes_chain' function only support list[string]or list[NodeProto] params" # noqa: B011
610
+
611
+ while start_node:
612
+ node_name = start_node.popleft()
613
+ if node_name in stop_node:
614
+ continue
615
+ if node_name not in result_chain:
616
+ result_chain.append(node_name)
617
+ else:
618
+ continue
619
+
620
+ node = find_by_name(node_name, list(self.model.graph.node))
621
+ for parent in self.get_parents(node):
622
+ start_node.append(parent.name)
623
+
624
+ return result_chain
625
+
626
+ def find_split_node_for_layer_wise_quantization(self):
627
+ """Find split node for layer wise quantization."""
628
+ # find split nodes of decoder blocks
629
+ # embed -> decoder.0 -(split_node)-> ... -(split_node)-> decoder.n -(split_node)-> norm -> head
630
+ # after split: embed -> decoder.0,
631
+ # decoder.1,
632
+ # decoder.2,
633
+ # ...,
634
+ # decoder.n,
635
+ # norm -> head
636
+ start_nodes = []
637
+ for node in self._model.graph.node:
638
+ start_node, qkv_nodes_list = None, None
639
+ if node.op_type == "SkipLayerNormalization":
640
+ start_node = node
641
+ qkv_nodes_list = [
642
+ self.match_parent_path(
643
+ start_node,
644
+ ["MatMul", "Reshape", "Transpose", "Reshape", "MatMul"],
645
+ [None, 0, 0, 0, 0],
646
+ ),
647
+ self.match_parent_path(
648
+ start_node,
649
+ ["Add", "MatMul", "Reshape", "Transpose", "MatMul"],
650
+ [1, 1, 0, 0, 0],
651
+ ),
652
+ ]
653
+ if node.op_type == "Add":
654
+ start_node = node
655
+ qkv_nodes_list = [
656
+ # match base attention structure
657
+ self.match_parent_path(
658
+ start_node,
659
+ ["Add", "MatMul", "Reshape", "Transpose", "MatMul"],
660
+ [0, None, 0, 0, 0],
661
+ ),
662
+ self.match_parent_path(
663
+ start_node, ["Add", "MatMul", "Reshape", "Transpose", "MatMul"], [1, None, 0, 0, 0]
664
+ ),
665
+ # match gpt attention no past structure
666
+ self.match_parent_path(
667
+ start_node,
668
+ ["Reshape", "Gemm", "Reshape", "Reshape", "Transpose", "MatMul"],
669
+ [None, 0, 0, 0, 0, 0],
670
+ output_name_to_node=self.output_name_to_node,
671
+ return_indice=[],
672
+ ),
673
+ # match bart attention structure
674
+ self.match_parent_path(
675
+ start_node,
676
+ ["Add", "MatMul", "Reshape", "Transpose", "Reshape", "MatMul"],
677
+ [0, None, 0, 0, 0, 0],
678
+ ),
679
+ self.match_parent_path(
680
+ start_node,
681
+ ["Add", "MatMul", "Reshape", "Transpose", "Reshape", "MatMul"],
682
+ [1, None, 0, 0, 0, 0],
683
+ ),
684
+ self.match_parent_path(
685
+ start_node,
686
+ ["MatMul", "Mul", "MatMul", "Mul", "Div", "Add"],
687
+ [None, 0, None, 0, None, 0],
688
+ ),
689
+ self.match_parent_path(
690
+ start_node,
691
+ ["MatMul", "Mul", "MatMul", "SimplifiedLayerNormalization", "Add"],
692
+ [None, 0, None, 0, 0],
693
+ ),
694
+ ]
695
+ if not start_node:
696
+ continue
697
+ if not any(qkv_nodes_list):
698
+ continue
699
+ start_nodes.append(start_node)
700
+ return start_nodes
701
+
702
+ def find_qkv_in_attention(self, find_all=False):
703
+ """Find qkv MatMul in Attention.
704
+
705
+ Args:
706
+ find_all (bool, optional): find all qkv MatMul. Defaults to False
707
+
708
+ Returns:
709
+ qkv (list): qkv MatMul list
710
+ """
711
+ qkv = []
712
+ for node in self._model.graph.node:
713
+ if node.op_type == "Attention":
714
+ qkv.append([node.name])
715
+ continue
716
+ start_node, qkv_nodes_list = None, None
717
+ if node.op_type == "SkipLayerNormalization":
718
+ start_node = node
719
+ qkv_nodes_list = [
720
+ self.match_parent_path(
721
+ start_node,
722
+ ["MatMul", "Reshape", "Transpose", "Reshape", "MatMul"],
723
+ [None, 0, 0, 0, 0],
724
+ ),
725
+ self.match_parent_path(
726
+ start_node,
727
+ ["Add", "MatMul", "Reshape", "Transpose", "MatMul"],
728
+ [1, 1, 0, 0, 0],
729
+ ),
730
+ ]
731
+ if node.op_type == "Add":
732
+ start_node = node
733
+ qkv_nodes_list = [
734
+ # match base attention structure
735
+ self.match_parent_path(
736
+ start_node,
737
+ ["Add", "MatMul", "Reshape", "Transpose", "MatMul"],
738
+ [0, None, 0, 0, 0],
739
+ ),
740
+ self.match_parent_path(
741
+ start_node, ["Add", "MatMul", "Reshape", "Transpose", "MatMul"], [1, None, 0, 0, 0]
742
+ ),
743
+ # match gpt attention no past structure
744
+ self.match_parent_path(
745
+ start_node,
746
+ ["Reshape", "Gemm", "Reshape", "Reshape", "Transpose", "MatMul"],
747
+ [None, 0, 0, 0, 0, 0],
748
+ output_name_to_node=self.output_name_to_node,
749
+ return_indice=[],
750
+ ),
751
+ # match bart attention structure
752
+ self.match_parent_path(
753
+ start_node,
754
+ ["Add", "MatMul", "Reshape", "Transpose", "Reshape", "MatMul"],
755
+ [0, None, 0, 0, 0, 0],
756
+ ),
757
+ self.match_parent_path(
758
+ start_node,
759
+ ["Add", "MatMul", "Reshape", "Transpose", "Reshape", "MatMul"],
760
+ [1, None, 0, 0, 0, 0],
761
+ ),
762
+ ]
763
+ if not start_node:
764
+ continue
765
+ if not any(qkv_nodes_list):
766
+ continue
767
+ qkv_nodes = [qkv for qkv in qkv_nodes_list if qkv is not None][-1]
768
+ other_inputs = []
769
+ for input in start_node.input:
770
+ if input not in self.output_name_to_node:
771
+ continue
772
+ if input == qkv_nodes[0].output[0]:
773
+ continue
774
+ other_inputs.append(input)
775
+ if len(other_inputs) != 1:
776
+ continue
777
+ root_input = other_inputs[0]
778
+ input_name_to_nodes = self.input_name_to_nodes
779
+ children = input_name_to_nodes[root_input]
780
+ children_types = [child.op_type for child in children]
781
+ if children_types.count("MatMul") == 3:
782
+ qkv.append([child.name for child in children if child.op_type == "MatMul"])
783
+ if not find_all:
784
+ break
785
+ return qkv
786
+
787
+ def find_ffn_matmul(self, attention_index, attention_matmul_list, block_len):
788
+ """Find MatMul in FFN.
789
+
790
+ Args:
791
+ attention_index (list): index of Attention
792
+ attention_matmul_list (list): list of Attention and MatMul nodes
793
+ block_len (int): block length
794
+
795
+ Returns:
796
+ list: list of MatMul in FFN
797
+ """
798
+ ffn_matmul = []
799
+ for idx in range(len(attention_index)):
800
+ if idx != len(attention_index) - 1:
801
+ index = attention_index[idx + 1]
802
+ if index - 2 >= 0:
803
+ ffn_matmul.append([attention_matmul_list[index - 2], attention_matmul_list[index - 1]])
804
+ else:
805
+ index = attention_index[idx]
806
+ if index + block_len - 1 < len(attention_matmul_list):
807
+ ffn_matmul.append(
808
+ [attention_matmul_list[index + block_len - 2], attention_matmul_list[index + block_len - 1]]
809
+ )
810
+ return ffn_matmul
811
+
812
+ def export(self, save_path, conf):
813
+ """Export Qlinear to QDQ model."""
814
+ from neural_compressor.config import ONNXQlinear2QDQConfig # noqa: PLC0415
815
+ from neural_compressor.utils.export import onnx_qlinear_to_qdq # noqa: PLC0415
816
+
817
+ if isinstance(conf, ONNXQlinear2QDQConfig):
818
+ add_nodes, remove_nodes, inits = onnx_qlinear_to_qdq(self._model, self._input_name_to_nodes)
819
+ self.add_nodes(add_nodes)
820
+ self.remove_nodes(remove_nodes)
821
+ self.add_initializers(inits)
822
+ self.update()
823
+ self.remove_unused_nodes()
824
+ self.topological_sort()
825
+ self.save(save_path)
826
+ else:
827
+ logger.warning("Unsupported config for export, only ONNXQlinear2QDQConfig is supported!")
828
+ exit(0)
829
+
830
+ def add_tensors_to_outputs(self, tensor_names):
831
+ """Add the tensors to the model outputs to gets their values.
832
+
833
+ Args:
834
+ tensor_names: The names of tensors to be dumped.
835
+ """
836
+ added_outputs = []
837
+ for tensor in tensor_names:
838
+ if tensor not in self.output():
839
+ added_tensor = onnx.helper.ValueInfoProto()
840
+ added_tensor.name = tensor
841
+ added_outputs.append(added_tensor)
842
+ self._model.graph.output.extend(added_outputs) # pylint: disable=no-member
843
+
844
+ def remove_tensors_from_outputs(self, tensor_names):
845
+ """Remove the tensors from the model outputs.
846
+
847
+ Args:
848
+ tensor_names: The names of tensors to be removed.
849
+ """
850
+ removed_outputs = []
851
+ for tensor in tensor_names:
852
+ if tensor in self.output():
853
+ removed_outputs.append(self._model.graph.output[self.output().index(tensor)])
854
+ for output in removed_outputs:
855
+ self._model.graph.output.remove(output)
856
+
857
+ def match_first_parent(self, node, parent_op_type, output_name_to_node, exclude=None):
858
+ """Find parent node based on constraints on op_type.
859
+
860
+ Args:
861
+ node (str): current node name.
862
+ parent_op_type (str): constraint of parent node op_type.
863
+ output_name_to_node (dict): dictionary with output name as key, and node as value.
864
+ exclude (list): list of nodes that are excluded (not allowed to match as parent).
865
+
866
+ Returns:
867
+ parent: The matched parent node. None if not found.
868
+ index: The input index of matched parent node. None if not found.
869
+ """
870
+ if exclude is None:
871
+ exclude = []
872
+ for i, input in enumerate(node.input):
873
+ if input in output_name_to_node:
874
+ parent = output_name_to_node[input]
875
+ if parent.op_type == parent_op_type and parent not in exclude:
876
+ return parent, i
877
+ return None, None
878
+
879
+ def match_parent(
880
+ self,
881
+ node,
882
+ parent_op_type,
883
+ input_index=None,
884
+ output_name_to_node=None,
885
+ exclude=None,
886
+ return_indice=None,
887
+ ):
888
+ """Find parent node based on constraints on op_type and index.
889
+
890
+ Args:
891
+ node (str): current node name.
892
+ parent_op_type (str): constraint of parent node op_type.
893
+ input_index (int or None): only check the parent given input index of current node.
894
+ output_name_to_node (dict): dictionary with output name as key, and node as value.
895
+ exclude (list): list of nodes that are excluded (not allowed to match as parent).
896
+ return_indice (list): a list to append the input index when input_index is None.
897
+
898
+ Returns:
899
+ parent: The matched parent node.
900
+ """
901
+ assert node is not None
902
+ assert input_index is None or input_index >= 0
903
+ if exclude is None:
904
+ exclude = []
905
+ if output_name_to_node is None:
906
+ output_name_to_node = self._output_name_to_node
907
+
908
+ if input_index is None:
909
+ parent, index = self.match_first_parent(node, parent_op_type, output_name_to_node, exclude)
910
+ if return_indice is not None:
911
+ return_indice.append(index)
912
+ return parent
913
+
914
+ if input_index >= len(node.input):
915
+ return None
916
+
917
+ parent = self.get_parent(node, input_index, output_name_to_node)
918
+ if parent is not None and parent.op_type == parent_op_type and parent not in exclude:
919
+ return parent
920
+
921
+ return None
922
+
923
+ def match_parent_path(
924
+ self,
925
+ node,
926
+ parent_op_types,
927
+ parent_input_index,
928
+ output_name_to_node=None,
929
+ return_indice=None,
930
+ ):
931
+ """Find a sequence of input edges based on constraints on parent op_type and index.
932
+
933
+ Args:
934
+ node (str): current node name.
935
+ parent_op_types (str): constraint of parent node op_type of each input edge.
936
+ parent_input_index (list): constraint of input index of each input edge.
937
+ None means no constraint.
938
+ output_name_to_node (dict): dictionary with output name as key, and node as value.
939
+ return_indice (list): a list to append the input index when there is
940
+ no constraint on input index of an edge.
941
+
942
+ Returns:
943
+ parents: a list of matched parent node.
944
+ """
945
+ assert len(parent_input_index) == len(parent_op_types)
946
+
947
+ if output_name_to_node is None:
948
+ output_name_to_node = self._output_name_to_node
949
+
950
+ current_node = node
951
+ matched_parents = []
952
+ for i, op_type in enumerate(parent_op_types):
953
+ matched_parent = self.match_parent(
954
+ current_node,
955
+ op_type,
956
+ parent_input_index[i],
957
+ output_name_to_node,
958
+ exclude=[],
959
+ return_indice=return_indice,
960
+ )
961
+ if matched_parent is None:
962
+ return None
963
+
964
+ matched_parents.append(matched_parent)
965
+ current_node = matched_parent
966
+
967
+ return matched_parents
968
+
969
+ def is_smoothquant_model(self):
970
+ """Check the model is smooth quantized or not.
971
+
972
+ Returns:
973
+ bool: the model is smooth quantized or not.
974
+ """
975
+ for init in self.model.graph.initializer: # noqa: SIM110
976
+ if "_smooth_scale" in init.name:
977
+ return True
978
+ return False
979
+
980
+ def find_split_nodes(self):
981
+ """Find split nodes for layer-wise quantization."""
982
+ split_nodes = self.find_split_node_for_layer_wise_quantization()
983
+ return split_nodes
984
+
985
+ def split_model_with_node(
986
+ self, split_node_name, path_of_model_to_split, shape_infer=True, save_both_split_models=True
987
+ ):
988
+ """Split model into two parts at a given node.
989
+
990
+ Args:
991
+ split_node_name (str): name of the node where the model is split at>
992
+ path_of_model_to_split (str): path of model to be split.
993
+ shape_infer (bool): do shape inference. Default is True.
994
+ save_both_split_models (bool): whether to save the two split models.
995
+ False means only save the first split model.
996
+ True means save both the two split models.
997
+ Default id True.
998
+
999
+ Returns:
1000
+ tuple: the first split model, the second split model
1001
+ """
1002
+ # origin model : ... -> node_1 -> split_node -> node_2 -> ...
1003
+ # split model 1: ... -> node_1 -> split_node
1004
+ # split model 2: node_2 -> ...
1005
+
1006
+ split_model_part_1 = onnx.ModelProto()
1007
+ split_model_part_1.CopyFrom(self._model)
1008
+ split_model_part_1.graph.ClearField("node")
1009
+
1010
+ split_model_part_2 = onnx.ModelProto()
1011
+ split_model_part_2.CopyFrom(self._model)
1012
+ split_model_part_2.graph.ClearField("node")
1013
+
1014
+ split_node_output = None
1015
+ part_idx = 1
1016
+ for node in self._model.graph.node:
1017
+ if part_idx == 1:
1018
+ split_model_part_1.graph.node.append(node)
1019
+ elif part_idx == 2:
1020
+ split_model_part_2.graph.node.append(node)
1021
+
1022
+ if node.name == split_node_name:
1023
+ split_node_output = node.output
1024
+ part_idx = 2
1025
+
1026
+ assert len(split_node_output) == 1, (
1027
+ f"Only support split at node with 1 output tensor, while current split node {split_node_name} has {len(split_node_output)} output tensors"
1028
+ )
1029
+ split_tensor_name = split_node_output[0]
1030
+
1031
+ # infer shape of the model to be split
1032
+ if shape_infer:
1033
+ try:
1034
+ from neural_compressor.adaptor.ox_utils.util import infer_shapes # noqa: PLC0415
1035
+
1036
+ self._model = infer_shapes(self._model, auto_merge=True, base_dir=os.path.dirname(self._model_path))
1037
+ except Exception as e: # pragma: no cover
1038
+ logger.error(
1039
+ "Shape infer fails for layer-wise quantization. "
1040
+ "We would recommend checking the graph optimization level of your model "
1041
+ "and setting it to 'DISABLE_ALL' or 'ENABLE_BASIC', "
1042
+ "as this may help avoid this error."
1043
+ )
1044
+ raise e
1045
+
1046
+ split_tensor_type, split_tensor_shape = self._get_output_type_shape_by_tensor_name(split_tensor_name)
1047
+ split_tensor = onnx.helper.make_tensor_value_info(split_tensor_name, split_tensor_type, split_tensor_shape)
1048
+
1049
+ split_model_part_1 = ONNXModel(split_model_part_1, ignore_warning=True)
1050
+ split_model_part_2 = ONNXModel(split_model_part_2, ignore_warning=True)
1051
+
1052
+ # remove unused input & output
1053
+ split_model_part_1._remove_unused_input_output()
1054
+ split_model_part_2._remove_unused_input_output()
1055
+
1056
+ split_model_part_1.model.graph.output.append(split_tensor)
1057
+ split_model_part_2.model.graph.input.append(split_tensor)
1058
+
1059
+ insert_output_for_model_1 = []
1060
+ insert_input_for_model_2 = []
1061
+ for output in split_model_part_1.output_name_to_node:
1062
+ if output in split_model_part_2.input_name_to_nodes:
1063
+ output_type, output_shape = self._get_output_type_shape_by_tensor_name(output)
1064
+ output_tensor = onnx.helper.make_tensor_value_info(output, output_type, output_shape)
1065
+ if output_tensor not in split_model_part_1.model.graph.output:
1066
+ insert_output_for_model_1.append(output_tensor)
1067
+ if output_tensor not in split_model_part_2.model.graph.input:
1068
+ insert_input_for_model_2.append(output_tensor)
1069
+
1070
+ # insert model 1 output
1071
+ for output in insert_output_for_model_1:
1072
+ split_model_part_1.model.graph.output.append(output)
1073
+
1074
+ # insert model 2 input
1075
+ for input in insert_input_for_model_2:
1076
+ split_model_part_2.model.graph.input.append(input)
1077
+
1078
+ # remove unused init
1079
+ split_model_part_1.remove_unused_init()
1080
+ split_model_part_2.remove_unused_init()
1081
+
1082
+ split_model_part_1.update()
1083
+ split_model_part_2.update()
1084
+
1085
+ dir_of_model_to_split = os.path.dirname(path_of_model_to_split)
1086
+
1087
+ split_model_part_1.load_model_initializer_by_tensor(dir_of_model_to_split)
1088
+ split_model_part_1_path = os.path.join(dir_of_model_to_split, "split_model_part_1.onnx")
1089
+ split_model_part_1.model_path = split_model_part_1_path
1090
+ split_model_part_1._save_split_model(split_model_part_1_path)
1091
+ split_model_part_1.check_is_large_model()
1092
+ logger.debug(f"save split model part 1 to {split_model_part_1_path} for layer wise quantization")
1093
+
1094
+ if save_both_split_models:
1095
+ split_model_part_2.load_model_initializer_by_tensor(dir_of_model_to_split)
1096
+ split_model_part_2_path = os.path.join(dir_of_model_to_split, "split_model_part_2.onnx")
1097
+ split_model_part_2.model_path = split_model_part_2_path
1098
+ split_model_part_2._save_split_model(split_model_part_2_path)
1099
+ split_model_part_2.check_is_large_model()
1100
+ logger.debug(f"save split model part 2 to {split_model_part_2_path} for layer wise quantization")
1101
+ return split_model_part_1, split_model_part_2
1102
+ else:
1103
+ return split_model_part_1, split_model_part_2
1104
+
1105
+ def _save_split_model(self, save_path):
1106
+ """Save split model as external data for layer wise quantization.
1107
+
1108
+ Args:
1109
+ save_path (str): the path to save the split model
1110
+ """
1111
+ if os.path.exists(save_path + "_data"):
1112
+ os.remove(save_path + "_data")
1113
+ onnx.save_model(
1114
+ self._model,
1115
+ save_path,
1116
+ save_as_external_data=True,
1117
+ all_tensors_to_one_file=True,
1118
+ location=save_path.split("/")[-1] + "_data",
1119
+ size_threshold=1024,
1120
+ convert_attribute=False,
1121
+ )
1122
+
1123
+ def _get_output_type_shape_by_tensor_name(self, tensor_name):
1124
+ """Get output type and shape with a tensor name.
1125
+
1126
+ Args:
1127
+ tensor_name (str): name of a tensor
1128
+
1129
+ Returns:
1130
+ tuple: output type and shape
1131
+ """
1132
+ elem_type = onnx.TensorProto.FLOAT
1133
+ shape = None
1134
+ for output in self._model.graph.value_info:
1135
+ if output.name == tensor_name:
1136
+ elem_type = output.type.tensor_type.elem_type
1137
+ shape = [
1138
+ dim.dim_value if dim.HasField("dim_value") else -1 for dim in output.type.tensor_type.shape.dim
1139
+ ]
1140
+ break
1141
+ return elem_type, shape
1142
+
1143
+ def _remove_unused_input_output(self):
1144
+ """Remove unused input & output for split model."""
1145
+ remove_outputs = []
1146
+ remove_inputs = []
1147
+ for output in self._model.graph.output:
1148
+ if output.name not in self.output_name_to_node:
1149
+ remove_outputs.append(output)
1150
+
1151
+ for input in self._model.graph.input:
1152
+ if input.name not in self.input_name_to_nodes:
1153
+ remove_inputs.append(input)
1154
+
1155
+ for output in remove_outputs:
1156
+ self._model.graph.output.remove(output)
1157
+ for input in remove_inputs:
1158
+ self._model.graph.input.remove(input)
1159
+
1160
+ def remove_unused_init(self):
1161
+ """Remove unused init."""
1162
+ remov_inits = []
1163
+ for init in self._model.graph.initializer:
1164
+ if init.name not in self.input_name_to_nodes:
1165
+ remov_inits.append(init)
1166
+ self.remove_initializers(remov_inits)
1167
+
1168
+ def load_model_initializer_by_tensor(self, data_path=None):
1169
+ """Load model initializer by tensor.
1170
+
1171
+ Args:
1172
+ data_path (str, optional): the directory of saved initializer. Defaults to None.
1173
+ """
1174
+ if data_path is None:
1175
+ data_path = os.path.dirname(self._model_path)
1176
+ for init in self._model.graph.initializer:
1177
+ if init.HasField("data_location") and init.data_location == onnx.TensorProto.EXTERNAL:
1178
+ onnx.external_data_helper.load_external_data_for_tensor(init, data_path)
1179
+
1180
+ def write_external_data_to_new_location(self, external_data_location="external.data", overwrite=False):
1181
+ """Write external data of merged quantized model to new location to save memory.
1182
+
1183
+ Args:
1184
+ external_data_location (str, optional): external data location of merged quantized model.
1185
+ Defaults to "external.data".
1186
+ overwrite (bool, optional): if True, remove existed externa data. Defaults to False.
1187
+ """
1188
+ if overwrite and os.path.exists(os.path.join(os.path.dirname(self._model_path), external_data_location)):
1189
+ os.remove(os.path.join(os.path.dirname(self._model_path), external_data_location))
1190
+ self.load_model_initializer_by_tensor()
1191
+ onnx.external_data_helper.convert_model_to_external_data(self._model, location=external_data_location)
1192
+ # TODO : if init is already saved, skip write it
1193
+ onnx.external_data_helper.write_external_data_tensors(self._model, filepath=os.path.dirname(self._model_path))
1194
+
1195
+ def merge_split_models(self, to_merge_model):
1196
+ """Merge two split model into final model."""
1197
+ to_merge_model.write_external_data_to_new_location()
1198
+ self.add_nodes(list(to_merge_model.nodes()))
1199
+ self.add_initializers(list(to_merge_model.initializer()))
1200
+ self.update()
1201
+
1202
+ # add new output
1203
+ for output in to_merge_model.graph().output:
1204
+ if output.name not in self.output():
1205
+ self._model.graph.output.append(output)
1206
+
1207
+ # remove unused output
1208
+ remove_output = []
1209
+ for output in self._model.graph.output:
1210
+ if output.name in to_merge_model.input():
1211
+ remove_output.append(output)
1212
+ for output in remove_output:
1213
+ self._model.graph.output.remove(output)
1214
+
1215
+ # add new input
1216
+ for input in to_merge_model.graph().input:
1217
+ if (
1218
+ input.name not in self.input()
1219
+ and input.name not in self.output()
1220
+ and input.name not in self.output_name_to_node
1221
+ ):
1222
+ self._model.graph.input.append(input)
1223
+
1224
+ def re_org_output(self, origin_output):
1225
+ """Re-org output of merged model for layer-wise quantization."""
1226
+ outputs = {}
1227
+ tmp_remove = []
1228
+ for output in self._model.graph.output:
1229
+ outputs[output.name] = output
1230
+ tmp_remove.append(output)
1231
+
1232
+ for output in tmp_remove:
1233
+ self._model.graph.output.remove(output)
1234
+
1235
+ for out_name in origin_output:
1236
+ self._model.graph.output.append(outputs[out_name])
ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/quantization/neural_compressor/util.py ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # The implementation of this file is based on:
3
+ # https://github.com/intel/neural-compressor/tree/master/neural_compressor
4
+ #
5
+ # Copyright (c) 2023 Intel Corporation
6
+ #
7
+ # Licensed under the Apache License, Version 2.0 (the "License");
8
+ # you may not use this file except in compliance with the License.
9
+ # You may obtain a copy of the License at
10
+ #
11
+ # http://www.apache.org/licenses/LICENSE-2.0
12
+ #
13
+ # Unless required by applicable law or agreed to in writing, software
14
+ # distributed under the License is distributed on an "AS IS" BASIS,
15
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16
+ # See the License for the specific language governing permissions and
17
+ # limitations under the License.
18
+
19
+ """Helper classes or functions for onnxrt adaptor."""
20
+
21
+ import importlib
22
+ import logging
23
+
24
+ import numpy as np
25
+
26
+ logger = logging.getLogger("neural_compressor")
27
+
28
+
29
+ MAXIMUM_PROTOBUF = 2147483648
30
+
31
+
32
+ def simple_progress_bar(total, i):
33
+ """Progress bar for cases where tqdm can't be used."""
34
+ progress = i / total
35
+ bar_length = 20
36
+ bar = "#" * int(bar_length * progress)
37
+ spaces = " " * (bar_length - len(bar))
38
+ percentage = progress * 100
39
+ print(f"\rProgress: [{bar}{spaces}] {percentage:.2f}%", end="")
40
+
41
+
42
+ def find_by_name(name, item_list):
43
+ """Helper function to find item by name in a list."""
44
+ items = []
45
+ for item in item_list:
46
+ assert hasattr(item, "name"), f"{item} should have a 'name' attribute defined" # pragma: no cover
47
+ if item.name == name:
48
+ items.append(item)
49
+ if len(items) > 0:
50
+ return items[0]
51
+ else:
52
+ return None
53
+
54
+
55
+ def to_numpy(data):
56
+ """Convert to numpy ndarrays."""
57
+ import torch # noqa: PLC0415
58
+
59
+ if not isinstance(data, np.ndarray):
60
+ if not importlib.util.find_spec("torch"):
61
+ logger.error(
62
+ "Please install torch to enable subsequent data type check and conversion, "
63
+ "or reorganize your data format to numpy array."
64
+ )
65
+ exit(0)
66
+ if isinstance(data, torch.Tensor):
67
+ if data.dtype is torch.bfloat16: # pragma: no cover
68
+ return data.detach().cpu().to(torch.float32).numpy()
69
+ if data.dtype is torch.chalf: # pragma: no cover
70
+ return data.detach().cpu().to(torch.cfloat).numpy()
71
+ return data.detach().cpu().numpy()
72
+ else:
73
+ try:
74
+ return np.array(data)
75
+ except Exception:
76
+ assert False, ( # noqa: B011
77
+ f"The input data for onnx model is {type(data)}, which is not supported to convert to numpy ndarrays."
78
+ )
79
+ else:
80
+ return data
ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/quantization/neural_compressor/weight_only.py ADDED
@@ -0,0 +1,932 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # The implementation of this file is based on:
3
+ # https://github.com/intel/neural-compressor/tree/master/neural_compressor
4
+ #
5
+ # Copyright (c) 2023 Intel Corporation
6
+ #
7
+ # Licensed under the Apache License, Version 2.0 (the "License");
8
+ # you may not use this file except in compliance with the License.
9
+ # You may obtain a copy of the License at
10
+ #
11
+ # http://www.apache.org/licenses/LICENSE-2.0
12
+ #
13
+ # Unless required by applicable law or agreed to in writing, software
14
+ # distributed under the License is distributed on an "AS IS" BASIS,
15
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16
+ # See the License for the specific language governing permissions and
17
+ # limitations under the License.
18
+ #
19
+ # Modifications:
20
+ # Add k-quant quantization method.
21
+ # Copyright (c) Microsoft Corporation. All rights reserved.
22
+ # Licensed under the MIT License.
23
+
24
+ """WeightOnly for onnxrt adaptor."""
25
+
26
+ import copy
27
+ import logging
28
+ import os
29
+ import sys
30
+
31
+ import numpy as np
32
+ import onnx
33
+ from onnx import numpy_helper
34
+ from onnx.helper import np_dtype_to_tensor_dtype
35
+
36
+ import onnxruntime as ort
37
+
38
+ from .onnx_model import ONNXModel
39
+ from .util import simple_progress_bar
40
+
41
+ logger = logging.getLogger("neural_compressor")
42
+
43
+
44
+ def make_matmul_weight_only_node(
45
+ node,
46
+ weight_shape,
47
+ num_bits,
48
+ group_size,
49
+ k_blocks,
50
+ q_weight,
51
+ scale,
52
+ zero_point,
53
+ accuracy_level=0,
54
+ ): # pragma: no cover
55
+ """Build MatMulNBits node.
56
+
57
+ Args:
58
+ node: original matmul node
59
+ weight_shape: original weight shape
60
+ num_bits (int): num_bits
61
+ group_size (int): how many elements share one scale/zp
62
+ k_blocks (int): block number
63
+ q_weight (array): quantized weight
64
+ scale (array): scale
65
+ zero_point (array): zero point
66
+ accuracy_level (int): accuracy level. Support 0 (unset), 1(fp32), 2(fp16), 3(bf16), or 4(int8).
67
+
68
+ Returns:
69
+ matmul_weight_only_node: MatMulNBits node
70
+ new_inits: initializers of the new node
71
+ """
72
+ blob_size = group_size * num_bits // 8
73
+ packed = np.zeros((q_weight.shape[0], blob_size), dtype="uint8")
74
+ q_weight_name = node.input[1] + f"_Q{num_bits!s}G{group_size!s}"
75
+ input_names = [node.input[0], q_weight_name]
76
+ new_inits = []
77
+ kwargs = {}
78
+
79
+ op_type = "MatMulNBits"
80
+
81
+ # pack quantized weight
82
+ if num_bits == 4:
83
+ q_weight_pairs = q_weight[:, ::2] | q_weight[:, 1::2] << 4
84
+ packed[:, :] = q_weight_pairs[:, :blob_size]
85
+ elif num_bits == 8:
86
+ packed = q_weight
87
+ else:
88
+ logger.error(f"MatMulNBits does not have kernel support for num_bits = {num_bits}.")
89
+
90
+ packed = np.reshape(packed, (-1, k_blocks, blob_size))
91
+
92
+ # build scale tensor
93
+ scale = np.reshape(scale, (-1, k_blocks))
94
+ assert scale.dtype == np.float32 or scale.dtype == np.float16
95
+ scale_tensor = onnx.helper.make_tensor(
96
+ name=node.input[1] + "_scale",
97
+ data_type=np_dtype_to_tensor_dtype(scale.dtype),
98
+ dims=scale.shape,
99
+ vals=scale.tobytes(),
100
+ raw=True,
101
+ )
102
+ input_names.append(scale_tensor.name)
103
+ new_inits.append(scale_tensor)
104
+
105
+ # build zero_point tensor
106
+ if zero_point is not None:
107
+ if num_bits == 8:
108
+ packed_zp = zero_point.astype("uint8")
109
+ elif num_bits == 4:
110
+ # For 4-bit case, the default zeros is 0x8. So it is 0x88 = 136 if we fill lower/higher 4 bits with 0x8.
111
+ packed_zp = np.full((zero_point.shape[0] + 1) // 2, 136, dtype="uint8")
112
+ # create an index array
113
+ idx = np.arange(zero_point.shape[0] // k_blocks * k_blocks).reshape(-1)
114
+ # separate odd and even indices
115
+ even_idx = idx[::2]
116
+ odd_idx = idx[1::2]
117
+ # vectorized operation for even and odd indices
118
+ packed_zp[even_idx // 2] = (packed_zp[even_idx // 2] & 0xF0) | zero_point[even_idx].ravel()
119
+ packed_zp[odd_idx // 2] = (packed_zp[odd_idx // 2] & 0x0F) | (zero_point[odd_idx].ravel() << 4)
120
+ else:
121
+ raise ValueError(f"MatMulNBits does not have kernel support for num_bits = {num_bits}.")
122
+
123
+ packed_zp = np.reshape(packed_zp, (weight_shape[1], -1))
124
+ zp_tensor = onnx.helper.make_tensor(
125
+ name=node.input[1] + "_zp", data_type=2, dims=packed_zp.shape, vals=packed_zp.tobytes(), raw=True
126
+ )
127
+ input_names.append(zp_tensor.name)
128
+ new_inits.append(zp_tensor)
129
+
130
+ # set kwargs
131
+ kwargs["K"] = weight_shape[0]
132
+ kwargs["N"] = weight_shape[1]
133
+ kwargs["bits"] = num_bits
134
+ kwargs["block_size"] = group_size
135
+ if accuracy_level > 0:
136
+ # require onnxruntime > 1.16.3
137
+ kwargs["accuracy_level"] = accuracy_level
138
+
139
+ q_weight_tensor = onnx.helper.make_tensor(
140
+ name=q_weight_name,
141
+ data_type=2,
142
+ dims=packed.shape,
143
+ vals=packed.tobytes(),
144
+ raw=True,
145
+ )
146
+ new_inits.append(q_weight_tensor)
147
+
148
+ matmul_weight_only_node = onnx.helper.make_node(
149
+ op_type,
150
+ inputs=input_names,
151
+ outputs=node.output,
152
+ name=node.name + "_Q" + str(num_bits) if node.name else "_Q" + str(num_bits),
153
+ domain="com.microsoft",
154
+ **kwargs,
155
+ )
156
+ return matmul_weight_only_node, new_inits
157
+
158
+
159
+ def quant_tensor(data, num_bits=4, group_size=32, scheme="asym", dtype="int", ratio=1.0):
160
+ """Quantize tensor per group.
161
+
162
+ Args:
163
+ data : input weight
164
+ num_bits (int, optional): num_bits. Defaults to 4.
165
+ group_size (int, optional): how many elements share one scale/zp. Defaults to 4.
166
+ scheme (str, optional): quantization scheme. Defaults to "asym".
167
+ dtype (str, optional): data type. Defaults to "int".
168
+ ratio (float, optional): percentile of clip. Defaults to 1.0.
169
+
170
+ Returns:
171
+ output: quantized weight
172
+ scale: scale
173
+ zero_point: zero point
174
+ """
175
+ data = np.reshape(data, (-1, group_size))
176
+ if scheme == "asym" or dtype == "uint":
177
+ maxq = 2**num_bits - 1
178
+ minq = 0
179
+ elif scheme == "sym":
180
+ maxq = 2 ** (num_bits - 1) - 1 if num_bits != 1 else 0
181
+ minq = -(2 ** (num_bits - 1)) if num_bits != 1 else -1
182
+
183
+ rmin = np.min(data, axis=1, keepdims=True) * ratio
184
+ rmax = np.max(data, axis=1, keepdims=True) * ratio
185
+ if scheme == "sym":
186
+ max_range = np.maximum(np.abs(rmin), np.abs(rmax))
187
+ scale = np.ones(rmax.shape)
188
+ mask = max_range > 0
189
+ scale[mask] = (max_range[mask] * 2.0).astype(np.float64) / (maxq - minq)
190
+ zero_point = (
191
+ np.zeros(scale.shape) if dtype == "int" else np.ones(rmax.shape, dtype="uint8") * (1 << (num_bits - 1))
192
+ )
193
+ else:
194
+ scale = np.ones(rmax.shape)
195
+ scale[rmin != rmax] = np.array(
196
+ [float(i) / (maxq - minq) for i in (rmax - rmin)[rmin != rmax].flatten().tolist()]
197
+ )
198
+ zero_point = (
199
+ ((np.zeros(scale.shape) - rmin) / scale).round()
200
+ if dtype == "int"
201
+ else np.maximum(0, np.minimum(maxq, ((np.zeros(scale.shape) - rmin) / scale).round())).astype("uint8")
202
+ )
203
+
204
+ q_weight = np.empty_like(data, dtype=scale.dtype)
205
+ np.divide(data, scale, out=q_weight)
206
+ np.add(q_weight, zero_point, out=q_weight)
207
+ np.round(q_weight, out=q_weight)
208
+ np.clip(q_weight, minq, maxq, out=q_weight)
209
+
210
+ return q_weight, scale, zero_point
211
+
212
+
213
+ def quant_tensor_k_quant_cpu(data, num_bits=4, group_size=32):
214
+ """Quantize tensor per group based on k quant.
215
+
216
+ Ref: https://github.com/ggml-org/llama.cpp/blob/64eda5deb9859e87a020e56bab5d2f9ca956f1de/ggml/src/ggml-quants.c
217
+
218
+ Args:
219
+ data : input weight
220
+ num_bits (int, optional): num_bits. Defaults to 4.
221
+ group_size (int, optional): how many elements share one scale/zp. Defaults to 32.
222
+
223
+ Returns:
224
+ output: quantized weight
225
+ scale: scale
226
+ zero_point: zero point
227
+ """
228
+ data = np.reshape(data, (-1, group_size)).astype(np.float32) # nb = data.shape[0], (nb, group_size)
229
+ maxq = 2**num_bits - 1
230
+ minq = 0
231
+ sum_x2 = np.sum(data**2, axis=1, keepdims=True) # (nb, 1)
232
+ av_x = np.sqrt(sum_x2 / group_size) # (nb, 1)
233
+ weights = np.add(av_x, np.abs(data)) # (nb, group_size)
234
+ rmin = np.min(data, axis=1, keepdims=True) # (nb, 1)
235
+ rmax = np.max(data, axis=1, keepdims=True) # (nb, 1)
236
+ sum_w = np.sum(weights, axis=1, keepdims=True) # (nb, 1)
237
+ sum_x = np.sum(weights * data, axis=1, keepdims=True) # (nb, group_size)
238
+ iscale = np.ones(rmax.shape, dtype=data.dtype) # (nb, 1)
239
+ mask = rmin != rmax
240
+ iscale[mask] = (maxq - minq) / (rmax[mask] - rmin[mask])
241
+ scale = 1 / iscale
242
+ quant_data = np.clip(np.round(iscale * (data - rmin)), minq, maxq) # (nb, group_size)
243
+ diff = scale * quant_data + rmin - data # (nb, group_size)
244
+ best_mad = np.sum(weights * diff**2, axis=1, keepdims=True) # (nb, 1)
245
+ nstep = 20
246
+ rdelta = 0.1
247
+ # nstep * rdelta = -2 * rrmin, maxq - minq = 2**num_bits - 1
248
+ rrmin = -1
249
+ for is_ in range(nstep):
250
+ iscale_new = np.ones(rmax.shape, dtype=data.dtype) # (nb, 1)
251
+ factor = np.array([rrmin + rdelta * is_ + maxq - minq]).astype(data.dtype)[0]
252
+ mask = rmin != rmax
253
+ iscale_new[mask] = factor / (rmax[mask] - rmin[mask])
254
+ quant_data_new = np.clip(np.round(iscale_new * (data - rmin)), minq, maxq) # (nb, group_size)
255
+ mul_weights_quant_data_new = weights * quant_data_new
256
+ sum_l = np.sum(mul_weights_quant_data_new, axis=1, keepdims=True) # (nb, 1)
257
+ sum_l2 = np.sum(mul_weights_quant_data_new * quant_data_new, axis=1, keepdims=True) # (nb, 1)
258
+ sum_xl = np.sum(mul_weights_quant_data_new * data, axis=1, keepdims=True) # (nb, 1)
259
+ D = np.subtract(sum_w * sum_l2, sum_l**2) # noqa: N806
260
+
261
+ this_scale = (sum_w * sum_xl - sum_x * sum_l) / D # (nb, 1)
262
+ this_min = (sum_l2 * sum_x - sum_l * sum_xl) / D # (nb, 1)
263
+
264
+ diff = this_scale * quant_data_new + this_min - data # (nb, group_size)
265
+ mad = np.sum(weights * diff**2, axis=1, keepdims=True) # (nb, 1)
266
+
267
+ mad_1 = np.array(mad)
268
+ best_mad_1 = np.array(best_mad)
269
+ idx_to_replace = np.where(mad_1 < best_mad_1)[0]
270
+ quant_data[idx_to_replace, :] = quant_data_new[idx_to_replace, :]
271
+ best_mad[idx_to_replace] = mad[idx_to_replace]
272
+ scale[idx_to_replace] = this_scale[idx_to_replace]
273
+ rmin[idx_to_replace] = this_min[idx_to_replace]
274
+
275
+ zero_point = np.clip(((-rmin) / scale).round(), 0, maxq).astype("uint8")
276
+ scale = scale.astype(np.float64)
277
+ q_weight = np.empty_like(data, dtype=scale.dtype)
278
+ np.divide(data, scale, out=q_weight)
279
+ np.add(q_weight, zero_point, out=q_weight)
280
+ np.round(q_weight, out=q_weight)
281
+ np.clip(q_weight, minq, maxq, out=q_weight)
282
+
283
+ return q_weight, scale, zero_point
284
+
285
+
286
+ def quant_tensor_k_quant_cuda(data, num_bits=4, group_size=32):
287
+ """Quantize tensor per group based on k quant.
288
+
289
+ Ref: https://github.com/ggml-org/llama.cpp/blob/64eda5deb9859e87a020e56bab5d2f9ca956f1de/ggml/src/ggml-quants.c
290
+
291
+ Args:
292
+ data : input weight
293
+ num_bits (int, optional): num_bits. Defaults to 4.
294
+ group_size (int, optional): how many elements share one scale/zp. Defaults to 4.
295
+
296
+ Returns:
297
+ output: quantized weight
298
+ scale: scale
299
+ zero_point: zero point
300
+ """
301
+ try:
302
+ import cupy as cp # noqa: PLC0415
303
+ import torch # noqa: PLC0415
304
+
305
+ if torch.cuda.is_available():
306
+ data = cp.asarray(data)
307
+ data = data.reshape((-1, group_size)).astype(cp.float32) # nb = data.shape[0], (nb, group_size)
308
+ maxq = 2**num_bits - 1
309
+ minq = 0
310
+ sum_x2 = cp.sum(data**2, axis=1, keepdims=True) # (nb, 1)
311
+ av_x = cp.sqrt(sum_x2 / group_size) # (nb, 1)
312
+ weights = cp.add(av_x, cp.abs(data)) # (nb, group_size)
313
+ rmin = cp.min(data, axis=1, keepdims=True) # (nb, 1)
314
+ rmax = cp.max(data, axis=1, keepdims=True) # (nb, 1)
315
+ sum_w = cp.sum(weights, axis=1, keepdims=True) # (nb, 1)
316
+ sum_x = cp.sum(weights * data, axis=1, keepdims=True) # (nb, group_size)
317
+ iscale = cp.ones(rmax.shape, dtype=data.dtype) # (nb, 1)
318
+ mask = rmin != rmax
319
+ iscale[mask] = (maxq - minq) / (rmax[mask] - rmin[mask])
320
+ scale = 1 / iscale
321
+ quant_data = cp.clip(cp.round(iscale * (data - rmin)), minq, maxq) # (nb, group_size)
322
+ diff = scale * quant_data + rmin - data # (nb, group_size)
323
+ best_mad = cp.sum(weights * diff**2, axis=1, keepdims=True) # (nb, 1)
324
+ nstep = 20
325
+ rdelta = 0.1
326
+ rrmin = -1
327
+ for is_ in range(nstep):
328
+ iscale_new = cp.ones(rmax.shape, dtype=data.dtype) # (nb, 1)
329
+ factor = cp.array([rrmin + rdelta * is_ + maxq - minq]).astype(data.dtype)[0]
330
+ mask = rmin != rmax
331
+ iscale_new[mask] = factor / (rmax[mask] - rmin[mask])
332
+ quant_data_new = cp.clip(cp.round(iscale_new * (data - rmin)), minq, maxq) # (nb, group_size)
333
+ mul_weights_quant_data_new = weights * quant_data_new
334
+ sum_l = cp.sum(mul_weights_quant_data_new, axis=1, keepdims=True) # (nb, 1)
335
+ sum_l2 = cp.sum(mul_weights_quant_data_new * quant_data_new, axis=1, keepdims=True) # (nb, 1)
336
+ sum_xl = cp.sum(mul_weights_quant_data_new * data, axis=1, keepdims=True) # (nb, 1)
337
+ D = cp.subtract(sum_w * sum_l2, sum_l**2) # noqa: N806
338
+
339
+ this_scale = (sum_w * sum_xl - sum_x * sum_l) / D # (nb, 1)
340
+ this_min = (sum_l2 * sum_x - sum_l * sum_xl) / D # (nb, 1)
341
+
342
+ diff = this_scale * quant_data_new + this_min - data # (nb, group_size)
343
+ mad = cp.sum(weights * diff**2, axis=1, keepdims=True) # (nb, 1)
344
+
345
+ mad_1 = cp.array(mad)
346
+ best_mad_1 = cp.array(best_mad)
347
+ idx_to_replace = cp.where(mad_1 < best_mad_1)[0]
348
+ quant_data[idx_to_replace, :] = quant_data_new[idx_to_replace, :]
349
+ best_mad[idx_to_replace] = mad[idx_to_replace]
350
+ scale[idx_to_replace] = this_scale[idx_to_replace]
351
+ rmin[idx_to_replace] = this_min[idx_to_replace]
352
+
353
+ zero_point = cp.clip(((-rmin) / scale).round(), 0, maxq).astype("uint8")
354
+ scale = scale.astype(cp.float64)
355
+ q_weight = cp.empty_like(data, dtype=scale.dtype)
356
+ cp.divide(data, scale, out=q_weight)
357
+ cp.add(q_weight, zero_point, out=q_weight)
358
+ cp.round(q_weight, out=q_weight)
359
+ cp.clip(q_weight, minq, maxq, out=q_weight)
360
+
361
+ return q_weight.get(), scale.get(), zero_point.get()
362
+ else:
363
+ logger.warning(
364
+ "Try to use k-quant quantization on CUDA. However, CUDA is not available."
365
+ "Fall back to k-quant quantization on CPU."
366
+ )
367
+ return quant_tensor_k_quant_cpu(data, num_bits, group_size)
368
+ except ImportError:
369
+ logger.info(
370
+ "Now we are using k-quant quantization on cpu, which is time consuming."
371
+ "Please consider install cupy to speed up on CUDA. See https://cupy.dev/"
372
+ "Please also install torch to check CUDA availability."
373
+ )
374
+ return quant_tensor_k_quant_cpu(data, num_bits, group_size)
375
+
376
+
377
+ def qdq_tensor(data, num_bits=4, group_size=32, scheme="asym", dtype="int", ratio=1.0):
378
+ """Quant dequant tensor per group.
379
+
380
+ Args:
381
+ data : input weight
382
+ num_bits (int, optional): num_bits. Defaults to 4.
383
+ group_size (int, optional): how many elements share one scale/zp. Defaults to 4.
384
+ scheme (str, optional): quantization scheme. Defaults to "asym".
385
+ dtype (str, optional): data type. Defaults to "int".
386
+ ratio (float, optional): percentile of clip. Defaults to 1.0.
387
+
388
+ Returns:
389
+ output: quant-dequant weight
390
+ """
391
+ org_shape = data.shape
392
+ weight, scale, zp = quant_tensor(data, num_bits, group_size, scheme, dtype, ratio)
393
+ return np.reshape(scale * (weight - zp), org_shape)
394
+
395
+
396
+ def pad_tensor(weight, group_size, k_blocks):
397
+ """Pad tensor rowi so that it can be is divisible by group_size.
398
+
399
+ Args:
400
+ weight (array): weight
401
+ group_size (int): how many elements share one scale/zp
402
+ k_blocks (int): the number of block
403
+
404
+ Returns:
405
+ weight: paded weight
406
+ """
407
+ if group_size == -1:
408
+ return weight
409
+
410
+ org_w_shape = weight.shape
411
+ padded_rows = k_blocks * group_size
412
+ pad_len = padded_rows - org_w_shape[0]
413
+
414
+ if pad_len > 0:
415
+ weight = np.pad(weight, ((0, pad_len), (0, 0)), "constant")
416
+
417
+ return weight
418
+
419
+
420
+ def rtn_quantize(
421
+ model,
422
+ weight_config={}, # noqa: B006
423
+ num_bits=4,
424
+ group_size=32,
425
+ scheme="asym",
426
+ ratios={}, # noqa: B006
427
+ accuracy_level=0,
428
+ providers=["CPUExecutionProvider"], # noqa: B006
429
+ algorithm="k_quant",
430
+ ):
431
+ """Quant the model with round to nearst method.
432
+
433
+ Args:
434
+ model (ModelProto or ONNXModel): onnx model
435
+ weight_config (dict): quantization config
436
+ For example,
437
+ weight_config = {
438
+ 'fc2':
439
+ {
440
+ 'bits': 4,
441
+ 'group_size': 32,
442
+ 'scheme': 'sym',
443
+ 'algorithm': 'RTN'
444
+ }
445
+ }
446
+ num_bits (int, optional): num_bits. Default is 4.
447
+ group_size (int, optional): how many elements share one scale/zp. Default is 32.
448
+ scheme (str, optional): sym or asym. Defaults to "asym".
449
+ ratios (dict, optional): percentile of clip. Defaults to {}.
450
+ accuracy_level (int): accuracy level. Support 0 (unset),1(fp32), 2(fp16), 3(bf16), or 4(int8).
451
+ providers (list): providers to use
452
+
453
+ Returns:
454
+ model: fake quantized ONNXModel
455
+ """
456
+ model = ONNXModel(model)
457
+ base_dir = os.path.dirname(model.model_path) if model.model_path is not None else ""
458
+ new_nodes = []
459
+ remove_nodes = []
460
+ total_num = len([i for i in model.nodes() if i.op_type in ["MatMul"]])
461
+ curr_id = 0
462
+ for node in model.nodes():
463
+ if node.op_type in ["MatMul"]:
464
+ curr_id += 1
465
+ simple_progress_bar(total_num, curr_id)
466
+ if (
467
+ node.op_type in ["MatMul"]
468
+ and model.get_initializer(node.input[1]) is not None
469
+ and weight_config.get(node.name, {}) != "fp32"
470
+ ):
471
+ weight_tensor = model.get_initializer(node.input[1])
472
+ weight = numpy_helper.to_array(weight_tensor, base_dir=base_dir).copy()
473
+ if len(weight.shape) != 2:
474
+ continue
475
+
476
+ dtype = weight.dtype
477
+
478
+ if node.name in weight_config:
479
+ num_bits = weight_config[node.name]["bits"]
480
+ group_size = weight_config[node.name]["group_size"]
481
+ scheme = weight_config[node.name]["scheme"]
482
+
483
+ org_w_shape = weight.shape # ic, oc
484
+ group_size = group_size if group_size != -1 else org_w_shape[0]
485
+
486
+ k_blocks = (org_w_shape[0] - 1) // group_size + 1
487
+ init_share_num = model.get_initializer_share_num(node.input[1])
488
+
489
+ weight = pad_tensor(weight, group_size, k_blocks)
490
+
491
+ satisfy_MatMulNBits_condition = num_bits == 4 or num_bits == 8 # noqa: N806
492
+
493
+ if satisfy_MatMulNBits_condition: # pragma: no cover
494
+ if algorithm == "k_quant":
495
+ q_weight, scale, zp = quant_tensor_k_quant_cuda(weight.T, num_bits, group_size)
496
+ else:
497
+ q_weight, scale, zp = quant_tensor(
498
+ weight.T, num_bits, group_size, scheme, "uint", ratios.get(node.input[1], 1)
499
+ )
500
+
501
+ q_matmul_node, new_inits = make_matmul_weight_only_node(
502
+ node=node,
503
+ weight_shape=org_w_shape,
504
+ num_bits=num_bits,
505
+ group_size=group_size,
506
+ k_blocks=k_blocks,
507
+ q_weight=q_weight.astype("uint8"),
508
+ scale=scale.astype(dtype),
509
+ zero_point=zp if scheme == "asym" or algorithm == "k_quant" else None,
510
+ accuracy_level=accuracy_level,
511
+ )
512
+
513
+ model.add_initializers(new_inits)
514
+ remove_nodes.append(node)
515
+ new_nodes.append(q_matmul_node)
516
+ else:
517
+ q_weight = qdq_tensor(weight.T, num_bits, group_size, scheme, "int", ratios.get(node.input[1], 1))
518
+ q_weight = np.reshape(q_weight, (org_w_shape[1], -1))
519
+ q_weight = np.transpose(q_weight)
520
+ q_weight = q_weight[: org_w_shape[0], :].astype(dtype)
521
+ q_weight_tensor = onnx.helper.make_tensor(
522
+ name=node.input[1] + f"_Q{num_bits!s}G{group_size!s}",
523
+ data_type=np_dtype_to_tensor_dtype(dtype),
524
+ dims=weight.shape,
525
+ vals=q_weight.tobytes(),
526
+ raw=True,
527
+ )
528
+ model.add_initializer(q_weight_tensor)
529
+ node.input[1] = q_weight_tensor.name
530
+ if init_share_num == 1:
531
+ model.remove_initializer(weight_tensor)
532
+
533
+ model.add_nodes(new_nodes)
534
+ model.remove_nodes(remove_nodes)
535
+ model.topological_sort()
536
+ return model
537
+
538
+
539
+ def get_weight_scale(weight, group_size):
540
+ """Get the scale of weight."""
541
+ org_shape = weight.shape
542
+ weight = np.reshape(weight, (-1, group_size)) if group_size != -1 else weight
543
+ scale = np.mean(np.reshape(np.abs(weight) / np.max(np.abs(weight), axis=1, keepdims=True), org_shape), axis=0)
544
+ return scale
545
+
546
+
547
+ def prepare_inputs(model, n_samples, dataloader, providers):
548
+ """Prepare inputs for weight only quantization.
549
+
550
+ Args:
551
+ model (ModelProto or ONNXModel): onnx model
552
+ n_samples (int, optional): calibration sample number. -1 means all samples.
553
+ dataloader (object): dataloader for calibration.
554
+ providers (list): providers to use
555
+
556
+ Returns:
557
+ inputs: prepared inputs.
558
+ so: session options
559
+ """
560
+ from importlib.util import find_spec # noqa: PLC0415
561
+
562
+ from .util import to_numpy # noqa: PLC0415
563
+
564
+ so = ort.SessionOptions()
565
+ if sys.version_info < (3, 11) and find_spec("onnxruntime_extensions"): # pragma: no cover
566
+ from onnxruntime_extensions import get_library_path # noqa: PLC0415
567
+
568
+ so.register_custom_ops_library(get_library_path())
569
+ if model.is_large_model:
570
+ onnx.save_model(
571
+ model.model,
572
+ model.model_path + "_augment.onnx",
573
+ save_as_external_data=True,
574
+ all_tensors_to_one_file=True,
575
+ convert_attribute=False,
576
+ )
577
+
578
+ session = (
579
+ ort.InferenceSession(model.model.SerializeToString(), so, providers=providers)
580
+ if not model.is_large_model
581
+ else ort.InferenceSession(model.model_path + "_augment.onnx", so, providers=providers)
582
+ )
583
+ inputs_names = [i.name for i in session.get_inputs()]
584
+ del session
585
+
586
+ inputs = []
587
+ for i, data in enumerate(dataloader):
588
+ if n_samples != -1 and ((i + 1) * dataloader.batch_size) > n_samples:
589
+ break
590
+ if len(inputs_names) != 1 or isinstance(data[0], dict):
591
+ assert len(data[0]) == len(inputs_names), (
592
+ f"Input number mismatch, require {len(inputs_names)} but get {len(data[0])}"
593
+ )
594
+
595
+ if isinstance(data[0], dict):
596
+ inputs.append(dict([(name, to_numpy(inp_data)) for name, inp_data in data[0].items()])) # noqa: C404
597
+ elif isinstance(data[0], np.ndarray): # pragma: no cover
598
+ inputs.append(dict([(name, inp) for name, inp in zip(inputs_names, [data[0]], strict=False)])) # noqa: C404
599
+ else: # pragma: no cover
600
+ inputs.append(dict([(name, to_numpy(inp)) for name, inp in zip(inputs_names, data[0], strict=False)])) # noqa: C404
601
+ return inputs, so
602
+
603
+
604
+ def gptq(
605
+ W,
606
+ H,
607
+ num_bits=4,
608
+ group_size=32,
609
+ scheme="asym",
610
+ blocksize=128,
611
+ percdamp=0.01,
612
+ actorder=False,
613
+ mse=False,
614
+ perchannel=True,
615
+ ):
616
+ """Quant the weight with GPTQ method.
617
+
618
+ Args:
619
+ W (array): weight.
620
+ H (array): Hessian matrix.
621
+ num_bits (int, optional): num_bits. Default is 4.
622
+ group_size (int, optional): how many elements share one scale/zp. Default is 32.
623
+ scheme (str, optional): sym or asym. Defaults to "asym".
624
+ blocksize (int, optional): blocksize to quantize weight.
625
+ percdamp (float, optional): percent of the average Hessian diagonal to use for dampening.
626
+ actorder (bool, optional): whether rearrange Hessian matrix considering the diag's value.
627
+ mse (bool, optional): whether get scale and zero point with mse error.
628
+ perchannel (bool, optional): whether quantize weight per-channel.
629
+
630
+ Returns:
631
+ Q: fake quantized weight
632
+ """
633
+ maxq = 2**num_bits - 1
634
+ grid = 100
635
+ maxshrink = 0.8
636
+ norm = 2.4
637
+
638
+ def find_params(weight):
639
+ org_shape = weight.shape
640
+ # find zp, scale
641
+ if not perchannel:
642
+ weight = np.expand_dims(weight.flatten(), axis=1)
643
+ tmp = np.zeros(weight.shape[1])
644
+ xmin = np.minimum(np.min(weight, axis=0), tmp)
645
+ xmax = np.maximum(np.max(weight, axis=0), tmp)
646
+ if scheme == "sym":
647
+ xmax = np.maximum(np.abs(xmin), xmax)
648
+ tmp = xmin < 0
649
+ if np.any(tmp):
650
+ xmin[tmp] = -xmax[tmp]
651
+ tmp = (xmin == 0) & (xmax == 0)
652
+ xmin[tmp] = -1
653
+ xmax[tmp] = +1
654
+
655
+ scale = (xmax - xmin) / maxq
656
+ if scheme == "sym":
657
+ zero = np.ones(scale.shape) * (maxq + 1) / 2
658
+ else:
659
+ zero = np.round(-xmin / scale)
660
+ if mse:
661
+ best = np.ones([weight.shape[1]]) * float("inf")
662
+ for i in range(int(maxshrink * grid)):
663
+ p = 1 - i / grid
664
+ xmin1 = p * xmin
665
+ xmax1 = p * xmax
666
+ scale1 = (xmax1 - xmin1) / maxq
667
+ zero1 = np.round(-xmin1 / scale1) if scheme != "sym" else zero
668
+ q = np.clip(np.round(weight / scale1) + zero1, 0, maxq)
669
+ q -= weight
670
+ q = np.power(np.abs(q), norm)
671
+ err = np.sum(q, 0)
672
+ tmp = err < best
673
+ if np.any(tmp):
674
+ best[tmp] = err[tmp]
675
+ scale[tmp] = scale1[tmp]
676
+ zero[tmp] = zero1[tmp]
677
+ if not perchannel:
678
+ tmp = org_shape[1]
679
+ scale = np.repeat(scale, tmp)
680
+ zero = np.repeat(zero, tmp)
681
+ shape = [-1] + [1] * (len(org_shape) - 1)
682
+ scale = np.reshape(scale, shape)
683
+ zero = np.reshape(zero, shape)
684
+ return scale, zero
685
+
686
+ shape = W.shape
687
+ scale, zp = find_params(W)
688
+ dead = np.diag(H) == 0
689
+ H[dead, dead] = 1
690
+ W[dead, :] = 0 # such channel makes no contribution to quantization computation
691
+
692
+ # rearrange considering the diag's value
693
+ if actorder:
694
+ perm = np.argsort(np.diag(H))[::-1]
695
+ W = W[perm, :] # noqa: N806
696
+ H = H[perm, :][:, perm] # noqa: N806
697
+ Losses = np.zeros_like(W) # noqa: N806
698
+ Q = np.zeros_like(W) # noqa: N806
699
+ damp = percdamp * np.mean(np.diag(H))
700
+ diag = np.arange(shape[0])
701
+ H[diag, diag] += damp # add a average value of
702
+ H = np.linalg.cholesky(np.linalg.inv(H)).T # noqa: N806
703
+ Hinv = H # noqa: N806
704
+ for i1 in range(0, shape[0], blocksize):
705
+ i2 = min(i1 + blocksize, shape[0])
706
+ count = i2 - i1
707
+
708
+ W1 = copy.deepcopy(W[i1:i2, :]) # noqa: N806
709
+ Q1 = np.zeros_like(W1) # noqa: N806
710
+ Err1 = np.zeros_like(W1) # noqa: N806
711
+ Losses1 = np.zeros_like(W1) # noqa: N806
712
+ Hinv1 = Hinv[i1:i2, i1:i2] # noqa: N806
713
+
714
+ for i in range(count): # within a block, channel wise
715
+ w = W1[i, :]
716
+ d = Hinv1[i, i]
717
+
718
+ if group_size != -1:
719
+ if (i1 + i) % group_size == 0:
720
+ scale, zp = find_params(W[(i1 + i) : (i1 + i + group_size), :])
721
+
722
+ q = (scale * (np.clip(np.round(w[:, np.newaxis] / scale) + zp, 0, maxq) - zp)).flatten()
723
+ Q1[i, :] = q
724
+ Losses1[i, :] = (w - q) ** 2 / d**2
725
+
726
+ err1 = (w - q) / d
727
+ W1[i:, :] -= np.matmul(np.expand_dims(Hinv1[i:, i], axis=1), np.expand_dims(err1, axis=0))
728
+ Err1[i, :] = err1
729
+
730
+ Q[i1:i2, :] = Q1
731
+ Losses[i1:i2, :] = Losses1 / 2
732
+
733
+ W[i2:, :] -= np.matmul(Hinv[i2:, i1:i2], Err1)
734
+
735
+ if actorder:
736
+ invperm = np.argsort(perm)
737
+ Q = Q[invperm, :] # noqa: N806
738
+
739
+ Q = np.reshape(Q, W.shape) # noqa: N806
740
+ del W
741
+ return Q
742
+
743
+
744
+ def gptq_quantize(
745
+ model,
746
+ dataloader,
747
+ weight_config={}, # noqa: B006
748
+ num_bits=4,
749
+ group_size=32,
750
+ scheme="asym",
751
+ n_samples=128,
752
+ percdamp=0.01,
753
+ blocksize=128,
754
+ actorder=False,
755
+ mse=False,
756
+ perchannel=True,
757
+ accuracy_level=0,
758
+ providers=["CPUExecutionProvider"], # noqa: B006
759
+ ):
760
+ """Quant the model with GPTQ method.
761
+
762
+ Args:
763
+ model (ModelProto or ONNXModel): onnx model
764
+ dataloader (object): dataloader for calibration.
765
+ weight_config (dict): quantization config
766
+ For example,
767
+ weight_config = {
768
+ 'fc2':
769
+ {
770
+ 'bits': 4,
771
+ 'group_size': 32,
772
+ 'scheme': 'sym',
773
+ 'algorithm': 'GPTQ'
774
+ }
775
+ }
776
+ num_bits (int, optional): num_bits. Default is 4.
777
+ group_size (int, optional): how many elements share one scale/zp. Default is 32.
778
+ scheme (str, optional): sym or asym. Defaults to "asym".
779
+ n_samples (int, optional): calibration sample number.
780
+ percdamp (float, optional): percent of the average Hessian diagonal to use for dampening.
781
+ blocksize (int, optional): blocksize to quantize weight.
782
+ actorder (bool, optional): whether rearrange Hessian matrix considering the diag's value.
783
+ mse (bool, optional): whether get scale and zero point with mse error.
784
+ perchannel (bool, optional): whether quantize weight per-channel.
785
+ accuracy_level (int): accuracy level. Support 0 (unset), 1(fp32), 2(fp16), 3(bf16), or 4(int8).
786
+ providers (list): providers to use
787
+
788
+ Returns:
789
+ model: fake quantized ONNXModel
790
+ """
791
+ model = ONNXModel(model)
792
+ base_dir = os.path.dirname(model.model_path) if model.model_path is not None else ""
793
+
794
+ inputs, so = prepare_inputs(model, n_samples, dataloader, providers)
795
+ del dataloader
796
+ org_output = copy.deepcopy(model.model.graph.output)
797
+ model.remove_tensors_from_outputs([i.name for i in org_output])
798
+ output_names = []
799
+ for node in model.nodes():
800
+ if (
801
+ node.op_type in ["MatMul"]
802
+ and weight_config.get(node.name, {}) != "fp32"
803
+ and weight_config.get(node.name, {}).get("algorithm", "GPTQ") == "GPTQ"
804
+ ):
805
+ output_names.append(node.input[0])
806
+ output_names = list(set(output_names))
807
+ model.add_tensors_to_outputs(output_names)
808
+ if model.is_large_model:
809
+ onnx.save_model(
810
+ model.model,
811
+ model.model_path + "_augment.onnx",
812
+ save_as_external_data=True,
813
+ all_tensors_to_one_file=True,
814
+ convert_attribute=False,
815
+ )
816
+
817
+ session = (
818
+ ort.InferenceSession(model.model.SerializeToString(), so, providers=providers)
819
+ if not model.is_large_model
820
+ else ort.InferenceSession(model.model_path + "_augment.onnx", so, providers=providers)
821
+ )
822
+
823
+ for idx, input_name in enumerate(output_names):
824
+ simple_progress_bar(len(output_names), idx + 1)
825
+ node_list = []
826
+ weights = []
827
+
828
+ for node in model.input_name_to_nodes[input_name]:
829
+ if (
830
+ node.op_type in ["MatMul"]
831
+ and weight_config.get(node.name, {}) != "fp32"
832
+ and weight_config.get(node.name, {}).get("algorithm", "GPTQ") == "GPTQ"
833
+ and model.get_initializer(node.input[1]) is not None
834
+ ):
835
+ weight = numpy_helper.to_array(
836
+ model.get_initializer(model.get_node(node.name).input[1]), base_dir
837
+ ).copy()
838
+ if len(weight.shape) != 2:
839
+ continue
840
+
841
+ weights.append(weight)
842
+ node_list.append(model.get_node(node.name))
843
+
844
+ if len(weights) == 0:
845
+ continue
846
+
847
+ Hs = [np.zeros((i.shape[0], i.shape[0])) for i in weights] # noqa: N806
848
+ nsamples = 0
849
+ for data in inputs:
850
+ inp = session.run([input_name], data)[0]
851
+ tmp = inp.shape[0]
852
+ inp = np.reshape(inp, (-1, inp.shape[-1]))
853
+ Hs = [i * (nsamples / (nsamples + tmp)) for i in Hs] # noqa: N806
854
+ nsamples += tmp
855
+ inp = np.sqrt(2 / nsamples) * inp
856
+ Hs = [i + np.matmul(inp.T, inp) for i in Hs] # noqa: N806
857
+
858
+ for (
859
+ node,
860
+ weight,
861
+ H, # noqa: N806
862
+ ) in zip(node_list, weights, Hs, strict=False):
863
+ if node.name in weight_config:
864
+ num_bits = weight_config[node.name]["bits"]
865
+ group_size = weight_config[node.name]["group_size"]
866
+ scheme = weight_config[node.name]["scheme"]
867
+ group_size = group_size if group_size != -1 else weight.shape[0]
868
+ dtype = weight.dtype
869
+
870
+ q_weight = gptq(
871
+ weight,
872
+ H,
873
+ num_bits=num_bits,
874
+ group_size=group_size,
875
+ scheme=scheme,
876
+ blocksize=blocksize,
877
+ percdamp=percdamp,
878
+ actorder=actorder,
879
+ mse=mse,
880
+ perchannel=perchannel,
881
+ )
882
+
883
+ weight_tensor = model.get_initializer(node.input[1])
884
+ init_share_num = model.get_initializer_share_num(node.input[1])
885
+
886
+ satisfy_MatMulNBits_condition = num_bits == 4 # noqa: N806
887
+
888
+ if satisfy_MatMulNBits_condition: # pragma: no cover
889
+ org_shape = weight.shape
890
+ k_blocks = (org_shape[0] + group_size - 1) // group_size
891
+ q_weight = pad_tensor(q_weight, group_size, k_blocks)
892
+ q_weight, scale, zp = quant_tensor(q_weight.T, num_bits, group_size, scheme, "uint")
893
+ q_matmul_node, new_inits = make_matmul_weight_only_node(
894
+ node=node,
895
+ weight_shape=org_shape,
896
+ num_bits=num_bits,
897
+ group_size=group_size,
898
+ k_blocks=k_blocks,
899
+ q_weight=q_weight.astype("uint8"),
900
+ scale=scale.astype(dtype),
901
+ zero_point=zp if scheme == "asym" else None,
902
+ accuracy_level=accuracy_level,
903
+ )
904
+
905
+ model.add_initializers(new_inits)
906
+ model.remove_node(node)
907
+ model.add_node(q_matmul_node)
908
+ else:
909
+ q_weight_tensor = onnx.helper.make_tensor(
910
+ name=node.input[1] + f"_Q{num_bits!s}G{group_size!s}",
911
+ data_type=np_dtype_to_tensor_dtype(dtype),
912
+ dims=q_weight.shape,
913
+ vals=q_weight.astype(dtype).tobytes(),
914
+ raw=True,
915
+ )
916
+ model.add_initializer(q_weight_tensor)
917
+ node.input[1] = q_weight_tensor.name
918
+ if init_share_num == 1:
919
+ model.remove_initializer(weight_tensor)
920
+
921
+ model.remove_tensors_from_outputs(output_names)
922
+ model.model.graph.output.MergeFrom(org_output)
923
+
924
+ model.topological_sort()
925
+
926
+ # reload external data to prevent external data file path errors
927
+ if model.is_large_model:
928
+ from onnx.external_data_helper import load_external_data_for_model # noqa: PLC0415
929
+
930
+ load_external_data_for_model(model.model, os.path.split(model.model_path)[0])
931
+
932
+ return model
ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/quantization/onnx_model.py ADDED
@@ -0,0 +1,600 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # --------------------------------------------------------------------------
2
+ # Copyright (c) Microsoft Corporation. All rights reserved.
3
+ # Licensed under the MIT License.
4
+ # --------------------------------------------------------------------------
5
+ from pathlib import Path
6
+
7
+ import onnx
8
+ import onnx.helper as onnx_helper
9
+ import onnx.numpy_helper as onnx_numpy_helper
10
+ from onnx.onnx_pb import ModelProto
11
+
12
+ from .quant_utils import attribute_to_kwarg, find_by_name
13
+
14
+
15
+ def _clean_initializers_helper(graph, model):
16
+ """Clean unused initializers from graph.
17
+
18
+ Returns:
19
+ A cleaned graph without unused initializers
20
+ A list of tensor names, which are not produced by this graph and its subgraphes
21
+ """
22
+ requesting_tensor_names = set()
23
+ requesting_tensor_names.update(input_name for node in graph.node for input_name in node.input if input_name)
24
+ requesting_tensor_names.update(g_out.name for g_out in graph.output if g_out.name)
25
+
26
+ new_nodes = []
27
+ for node in graph.node:
28
+ new_node = node
29
+ graph_attrs = [
30
+ attr
31
+ for attr in node.attribute
32
+ if attr.type == onnx.AttributeProto.GRAPH or attr.type == onnx.AttributeProto.GRAPHS
33
+ ]
34
+ if graph_attrs:
35
+ kwargs = {}
36
+ for attr in node.attribute:
37
+ new_attribute = {}
38
+ if attr.type == onnx.AttributeProto.GRAPH:
39
+ (
40
+ cleaned_sub_graph,
41
+ sub_requesting_tensor_names,
42
+ ) = _clean_initializers_helper(attr.g, model)
43
+ new_attribute = {attr.name: cleaned_sub_graph}
44
+ requesting_tensor_names.update(sub_requesting_tensor_names)
45
+ elif attr.type == onnx.AttributeProto.GRAPHS:
46
+ cleaned_graphes = []
47
+ for subgraph in attr.graphs:
48
+ (
49
+ cleaned_sub_graph,
50
+ sub_requesting_tensor_names,
51
+ ) = _clean_initializers_helper(subgraph, model)
52
+ cleaned_graphes.append(cleaned_sub_graph)
53
+ requesting_tensor_names.update(sub_requesting_tensor_names)
54
+ new_attribute = {attr.name: cleaned_graphes}
55
+ else:
56
+ new_attribute = attribute_to_kwarg(attr)
57
+ kwargs.update(new_attribute)
58
+ new_node = onnx_helper.make_node(node.op_type, node.input, node.output, name=node.name, **kwargs)
59
+ new_nodes.append(new_node)
60
+
61
+ graph.ClearField("node")
62
+ graph.node.extend(new_nodes)
63
+
64
+ requesting_tensor_names.difference_update(output for node in graph.node for output in node.output)
65
+
66
+ unused_initializer = []
67
+ for initializer in graph.initializer:
68
+ if initializer.name in requesting_tensor_names:
69
+ requesting_tensor_names.remove(initializer.name)
70
+ else:
71
+ # mark it to remove, remove here directly will cause mis-behavier
72
+ unused_initializer.append(initializer)
73
+
74
+ name_to_input = {input.name: input for input in graph.input}
75
+ for initializer in unused_initializer:
76
+ graph.initializer.remove(initializer)
77
+ if initializer.name in name_to_input:
78
+ try:
79
+ graph.input.remove(name_to_input[initializer.name])
80
+ except StopIteration:
81
+ if model.ir_version < 4:
82
+ print(f"Warning: invalid weight name {initializer.name} found in the graph (not a graph input)")
83
+
84
+ requesting_tensor_names.difference_update(input.name for input in graph.input)
85
+
86
+ return graph, requesting_tensor_names
87
+
88
+
89
+ class ONNXModel:
90
+ def __init__(self, model: ModelProto):
91
+ self.model = model
92
+
93
+ def nodes(self):
94
+ return self.model.graph.node
95
+
96
+ def initializer(self):
97
+ return self.model.graph.initializer
98
+
99
+ def initializer_extend(self, inits):
100
+ if len(inits) == 0:
101
+ raise ValueError("Can add an empty list.")
102
+ for init in self.initializer():
103
+ self._check_init(init, "gain")
104
+ for init in inits:
105
+ self._check_init(init)
106
+ self.model.graph.initializer.append(init)
107
+
108
+ def graph(self):
109
+ return self.model.graph
110
+
111
+ def ir_version(self):
112
+ return self.model.ir_version
113
+
114
+ def opset_import(self):
115
+ return self.model.opset_import
116
+
117
+ def set_opset_import(self, domain, version):
118
+ for opset in self.model.opset_import:
119
+ if opset.domain == domain:
120
+ opset.version = version
121
+ return
122
+
123
+ self.model.opset_import.extend([onnx_helper.make_opsetid(domain, version)])
124
+
125
+ def remove_node(self, node):
126
+ if node in self.model.graph.node:
127
+ self.model.graph.node.remove(node)
128
+
129
+ def remove_nodes(self, nodes_to_remove):
130
+ for node in nodes_to_remove:
131
+ self.remove_node(node)
132
+
133
+ def add_node(self, node):
134
+ self.model.graph.node.extend([self._check_node(node)])
135
+
136
+ def add_nodes(self, nodes_to_add):
137
+ for node in nodes_to_add:
138
+ self.add_node(node)
139
+
140
+ def add_initializer(self, tensor):
141
+ if find_by_name(tensor.name, self.model.graph.initializer) is None:
142
+ self._check_init(tensor)
143
+ self.model.graph.initializer.extend([tensor])
144
+
145
+ def get_initializer(self, name):
146
+ for tensor in self.model.graph.initializer:
147
+ if tensor.name == name:
148
+ return tensor
149
+ return None
150
+
151
+ def find_graph_input(self, input_name):
152
+ for input in self.model.graph.input:
153
+ if input.name == input_name:
154
+ return input
155
+ return None
156
+
157
+ def find_graph_output(self, output_name):
158
+ for output in self.model.graph.output:
159
+ if output.name == output_name:
160
+ return output
161
+ return None
162
+
163
+ def get_tensor_type(self, tensor_name: str):
164
+ tensor_type_map = {obj.name: obj.type for obj in self.model.graph.value_info}
165
+
166
+ if tensor_name in tensor_type_map:
167
+ return tensor_type_map[tensor_name].tensor_type
168
+
169
+ g_input = self.find_graph_input(tensor_name)
170
+ if g_input:
171
+ return g_input.type.tensor_type
172
+
173
+ g_output = self.find_graph_output(tensor_name)
174
+ if g_output:
175
+ return g_output.type.tensor_type
176
+
177
+ return None
178
+
179
+ def get_constant_value(self, output_name):
180
+ for node in self.model.graph.node:
181
+ if node.op_type == "Constant":
182
+ if node.output[0] == output_name:
183
+ for attr in node.attribute:
184
+ if attr.name == "value":
185
+ return onnx_numpy_helper.to_array(attr.t)
186
+
187
+ # Fallback to initializer since constant folding may have been applied.
188
+ initializer = self.get_initializer(output_name)
189
+ if initializer is not None:
190
+ return onnx_numpy_helper.to_array(initializer)
191
+
192
+ return None
193
+
194
+ def get_initializer_name_set(self):
195
+ return {initializer.name for initializer in self.model.graph.initializer}
196
+
197
+ def remove_initializer(self, tensor):
198
+ if tensor in self.model.graph.initializer:
199
+ self.model.graph.initializer.remove(tensor)
200
+ for input in self.model.graph.input:
201
+ if input.name == tensor.name:
202
+ self.model.graph.input.remove(input)
203
+ break
204
+
205
+ def remove_initializers(self, init_to_remove):
206
+ for initializer in init_to_remove:
207
+ self.remove_initializer(initializer)
208
+
209
+ def get_non_initializer_inputs(self):
210
+ initializer_names = self.get_initializer_name_set()
211
+ non_initializer_inputs = set()
212
+ for input in self.model.graph.input:
213
+ if input.name not in initializer_names:
214
+ non_initializer_inputs.add(input.name)
215
+ return non_initializer_inputs
216
+
217
+ def input_name_to_nodes(self):
218
+ input_name_to_nodes = {}
219
+ for node in self.model.graph.node:
220
+ for input_name in node.input:
221
+ if input_name: # Could be empty when it is optional
222
+ if input_name not in input_name_to_nodes:
223
+ input_name_to_nodes[input_name] = [node]
224
+ else:
225
+ input_name_to_nodes[input_name].append(node)
226
+ return input_name_to_nodes
227
+
228
+ def output_name_to_node(self):
229
+ output_name_to_node = {}
230
+ for node in self.model.graph.node:
231
+ for output_name in node.output:
232
+ if output_name: # Could be empty when it is optional
233
+ output_name_to_node[output_name] = node
234
+ return output_name_to_node
235
+
236
+ def get_children(self, node, input_name_to_nodes=None):
237
+ if input_name_to_nodes is None:
238
+ input_name_to_nodes = self.input_name_to_nodes()
239
+
240
+ children = []
241
+ for output in node.output:
242
+ if output in input_name_to_nodes:
243
+ for node in input_name_to_nodes[output]:
244
+ children.append(node) # noqa: PERF402
245
+ return children
246
+
247
+ def get_parents(self, node, output_name_to_node=None):
248
+ if output_name_to_node is None:
249
+ output_name_to_node = self.output_name_to_node()
250
+
251
+ parents = []
252
+ for input in node.input:
253
+ if input in output_name_to_node:
254
+ parents.append(output_name_to_node[input])
255
+ return parents
256
+
257
+ def get_parent(self, node, idx, output_name_to_node=None):
258
+ if output_name_to_node is None:
259
+ output_name_to_node = self.output_name_to_node()
260
+
261
+ if len(node.input) <= idx:
262
+ return None
263
+
264
+ input = node.input[idx]
265
+ if input not in output_name_to_node:
266
+ return None
267
+
268
+ return output_name_to_node[input]
269
+
270
+ def find_node_by_name(self, node_name, new_nodes_list, graph):
271
+ """Find out if a node exists in a graph or a node is in the
272
+ new set of nodes created during quantization.
273
+
274
+ Returns:
275
+ The node found or None.
276
+ """
277
+ graph_nodes_list = list(graph.node) # deep copy
278
+ graph_nodes_list.extend(new_nodes_list)
279
+ node = find_by_name(node_name, graph_nodes_list)
280
+ return node
281
+
282
+ def get_largest_node_name_suffix(self, node_name_prefix):
283
+ """
284
+ Gets the largest node name (int) suffix for all node names that begin with `node_name_prefix`.
285
+ Example: for nodes my_prefix_0 and my_prefix_3, this method returns 3.
286
+ """
287
+ suffix = -1
288
+
289
+ for node in self.model.graph.node:
290
+ if node.name and node.name.startswith(node_name_prefix):
291
+ try:
292
+ index = int(node.name[len(node_name_prefix) :])
293
+ suffix = max(index, suffix)
294
+ except ValueError:
295
+ continue
296
+
297
+ return suffix
298
+
299
+ def get_largest_initializer_name_suffix(self, initializer_name_prefix):
300
+ """
301
+ Gets the largest initializer name integer suffix for all initializer names that begin
302
+ with `initializer_name_prefix`. This can be used to create unique initializer names.
303
+
304
+ Example: for initializer names 'my_weight_0' and 'my_weight_3', this method returns 3 if
305
+ `initializer_name_prefix` is 'my_weight_'.
306
+ """
307
+ suffix = -1
308
+
309
+ for initializer in self.model.graph.initializer:
310
+ if initializer.name.startswith(initializer_name_prefix):
311
+ try:
312
+ index = int(initializer.name[len(initializer_name_prefix) :])
313
+ suffix = max(index, suffix)
314
+ except ValueError:
315
+ continue
316
+
317
+ return suffix
318
+
319
+ def find_nodes_by_initializer(self, graph, initializer):
320
+ """
321
+ Find all nodes with given initializer as an input.
322
+ """
323
+ nodes = []
324
+ for node in graph.node:
325
+ for node_input in node.input:
326
+ if node_input == initializer.name:
327
+ nodes.append(node)
328
+ return nodes
329
+
330
+ @staticmethod
331
+ def __get_initializer(name, graph_path):
332
+ for gid in range(len(graph_path) - 1, -1, -1):
333
+ graph = graph_path[gid]
334
+ for tensor in graph.initializer:
335
+ if tensor.name == name:
336
+ return tensor, graph
337
+ return None, None
338
+
339
+ @staticmethod
340
+ def __replace_gemm_with_matmul(graph_path):
341
+ new_nodes = []
342
+ graph = graph_path[-1]
343
+ for node in graph.node:
344
+ graph_attrs = [attr for attr in node.attribute if attr.type == 5 or attr.type == 10]
345
+ if graph_attrs:
346
+ kwargs = {}
347
+ for attr in node.attribute:
348
+ if attr.type == 5:
349
+ graph_path.append(attr.g)
350
+ kv = {attr.name: ONNXModel.__replace_gemm_with_matmul(graph_path)}
351
+ elif attr.type == 10:
352
+ value = []
353
+ for subgraph in attr.graphs:
354
+ graph_path.append(subgraph)
355
+ value.extend([ONNXModel.__replace_gemm_with_matmul(graph_path)])
356
+ kv = {attr.name: value}
357
+ else:
358
+ kv = attribute_to_kwarg(attr)
359
+ kwargs.update(kv)
360
+ node = onnx_helper.make_node( # noqa: PLW2901
361
+ node.op_type, node.input, node.output, name=node.name, **kwargs
362
+ )
363
+
364
+ if node.op_type == "Gemm":
365
+ alpha = 1.0
366
+ beta = 1.0
367
+ transA = 0 # noqa: N806
368
+ transB = 0 # noqa: N806
369
+ for attr in node.attribute:
370
+ if attr.name == "alpha":
371
+ alpha = onnx_helper.get_attribute_value(attr)
372
+ elif attr.name == "beta":
373
+ beta = onnx_helper.get_attribute_value(attr)
374
+ elif attr.name == "transA":
375
+ transA = onnx_helper.get_attribute_value(attr) # noqa: N806
376
+ elif attr.name == "transB":
377
+ transB = onnx_helper.get_attribute_value(attr) # noqa: N806
378
+ if alpha == 1.0 and beta == 1.0 and transA == 0:
379
+ inputB = node.input[1] # noqa: N806
380
+ if transB == 1:
381
+ B, Bs_graph = ONNXModel.__get_initializer(node.input[1], graph_path) # noqa: N806
382
+ if B:
383
+ # assume B is not used by any other node
384
+ B_array = onnx_numpy_helper.to_array(B) # noqa: N806
385
+ B_trans = onnx_numpy_helper.from_array(B_array.T) # noqa: N806
386
+ B_trans.name = B.name
387
+ Bs_graph.initializer.remove(B)
388
+ for input in Bs_graph.input:
389
+ if input.name == inputB:
390
+ Bs_graph.input.remove(input)
391
+ break
392
+ Bs_graph.initializer.extend([B_trans])
393
+ else:
394
+ inputB += "_Transposed" # noqa: N806
395
+ transpose_node = onnx_helper.make_node(
396
+ "Transpose",
397
+ inputs=[node.input[1]],
398
+ outputs=[inputB],
399
+ name=node.name + "_Transpose" if node.name else "",
400
+ )
401
+ new_nodes.append(transpose_node)
402
+
403
+ matmul_node = onnx_helper.make_node(
404
+ "MatMul",
405
+ inputs=[node.input[0], inputB],
406
+ outputs=[node.output[0] + ("_MatMul" if len(node.input) > 2 else "")],
407
+ name=node.name + "_MatMul" if node.name else "",
408
+ )
409
+ new_nodes.append(matmul_node)
410
+
411
+ if len(node.input) > 2:
412
+ add_node = onnx_helper.make_node(
413
+ "Add",
414
+ inputs=[node.output[0] + "_MatMul", node.input[2]],
415
+ outputs=node.output,
416
+ name=node.name + "_Add" if node.name else "",
417
+ )
418
+ new_nodes.append(add_node)
419
+
420
+ # unsupported
421
+ else:
422
+ new_nodes.append(node)
423
+
424
+ # not GEMM
425
+ else:
426
+ new_nodes.append(node)
427
+
428
+ graph.ClearField("node")
429
+ graph.node.extend(new_nodes)
430
+ graph_path.pop()
431
+ return graph
432
+
433
+ def replace_gemm_with_matmul(self):
434
+ graph_path = [self.graph()]
435
+ ONNXModel.__replace_gemm_with_matmul(graph_path)
436
+
437
+ def save_model_to_file(self, output_path, use_external_data_format=False):
438
+ """
439
+ Save model to external data, which is needed for model size > 2GB
440
+ """
441
+ self.topological_sort()
442
+ if use_external_data_format:
443
+ onnx.external_data_helper.convert_model_to_external_data(
444
+ self.model,
445
+ all_tensors_to_one_file=True,
446
+ location=Path(output_path).name + ".data",
447
+ convert_attribute=True,
448
+ )
449
+ for init in self.model.graph.initializer:
450
+ self._check_init(init, "end")
451
+ onnx.save_model(self.model, output_path)
452
+
453
+ @staticmethod
454
+ def replace_node_input(node, old_input_name, new_input_name):
455
+ assert isinstance(old_input_name, str) and isinstance(new_input_name, str)
456
+ for j in range(len(node.input)):
457
+ if node.input[j] == old_input_name:
458
+ node.input[j] = new_input_name
459
+
460
+ def replace_input_of_all_nodes(self, old_input_name, new_input_name):
461
+ for node in self.model.graph.node:
462
+ ONNXModel.replace_node_input(node, old_input_name, new_input_name)
463
+
464
+ def replace_input_of_nodes(self, old_input_name, new_input_name, node_names_set):
465
+ for node in self.model.graph.node:
466
+ if node.name in node_names_set:
467
+ ONNXModel.replace_node_input(node, old_input_name, new_input_name)
468
+
469
+ @staticmethod
470
+ def replace_node_output(node, old_output_name, new_output_name):
471
+ assert isinstance(old_output_name, str) and isinstance(new_output_name, str)
472
+ for j in range(len(node.output)):
473
+ if node.output[j] == old_output_name:
474
+ node.output[j] = new_output_name
475
+
476
+ def replace_output_of_all_nodes(self, old_output_name, new_output_name):
477
+ for node in self.model.graph.node:
478
+ ONNXModel.replace_node_output(node, old_output_name, new_output_name)
479
+
480
+ def replace_output_of_nodes(self, old_output_name, new_output_name, node_names_set):
481
+ for node in self.model.graph.node:
482
+ if node.name in node_names_set:
483
+ ONNXModel.replace_node_output(node, old_output_name, new_output_name)
484
+
485
+ def remove_unused_constant(self):
486
+ input_name_to_nodes = self.input_name_to_nodes()
487
+
488
+ # remove unused constant
489
+ unused_nodes = []
490
+ nodes = self.nodes()
491
+ for node in nodes:
492
+ if (
493
+ node.op_type == "Constant"
494
+ and not self.is_graph_output(node.output[0])
495
+ and node.output[0] not in input_name_to_nodes
496
+ ):
497
+ unused_nodes.append(node)
498
+
499
+ self.remove_nodes(unused_nodes)
500
+
501
+ ununsed_weights = []
502
+ for w in self.initializer():
503
+ if w.name not in input_name_to_nodes and not self.is_graph_output(w.name):
504
+ ununsed_weights.append(w)
505
+ # Remove from graph.input
506
+ for graph_input in self.graph().input:
507
+ if graph_input.name == w.name:
508
+ self.graph().input.remove(graph_input)
509
+
510
+ self.remove_initializers(ununsed_weights)
511
+
512
+ def is_graph_output(self, output_name):
513
+ return any(output.name == output_name for output in self.model.graph.output)
514
+
515
+ def is_graph_input(self, tensor_name: str) -> bool:
516
+ return any(input.name == tensor_name for input in self.model.graph.input)
517
+
518
+ # TODO:use OnnxModel.graph_topological_sort(self.model.graph) from transformers.onnx_model
519
+ # Currently it breaks Openvino/Linux training gpu pipeline so hold off for 1.8 release
520
+ def topological_sort(self):
521
+ deps_count = [0] * len(self.nodes()) # dependency count of each node
522
+ deps_to_nodes = {} # input to node indice
523
+ sorted_nodes = [] # initialize sorted_nodes
524
+ for node_idx, node in enumerate(self.nodes()):
525
+ # CANNOT use len(node.input) directly because input can be optional
526
+ deps_count[node_idx] = sum(1 for _ in node.input if _)
527
+ if deps_count[node_idx] == 0: # Constant doesn't depend on any inputs
528
+ sorted_nodes.append(self.nodes()[node_idx])
529
+ continue
530
+
531
+ for input_name in node.input:
532
+ if not input_name:
533
+ continue
534
+ if input_name not in deps_to_nodes:
535
+ deps_to_nodes[input_name] = [node_idx]
536
+ else:
537
+ deps_to_nodes[input_name].append(node_idx)
538
+
539
+ initializer_names = [init.name for init in self.initializer()]
540
+ graph_input_names = [input.name for input in self.model.graph.input]
541
+ input_names = initializer_names + graph_input_names
542
+ input_names.sort()
543
+ prev_input_name = None
544
+ for input_name in input_names:
545
+ if prev_input_name == input_name:
546
+ continue
547
+
548
+ prev_input_name = input_name
549
+ if input_name in deps_to_nodes:
550
+ for node_idx in deps_to_nodes[input_name]:
551
+ deps_count[node_idx] = deps_count[node_idx] - 1
552
+ if deps_count[node_idx] == 0:
553
+ sorted_nodes.append(self.nodes()[node_idx])
554
+
555
+ start = 0
556
+ end = len(sorted_nodes)
557
+
558
+ while start < end:
559
+ for output in sorted_nodes[start].output:
560
+ if output in deps_to_nodes:
561
+ for node_idx in deps_to_nodes[output]:
562
+ deps_count[node_idx] = deps_count[node_idx] - 1
563
+ if deps_count[node_idx] == 0:
564
+ sorted_nodes.append(self.nodes()[node_idx])
565
+ end = end + 1
566
+ start = start + 1
567
+
568
+ assert end == len(self.graph().node), "Graph is not a DAG"
569
+ self.graph().ClearField("node")
570
+ self.graph().node.extend(sorted_nodes)
571
+
572
+ def clean_initializers(self):
573
+ return _clean_initializers_helper(self.graph(), self.model)
574
+
575
+ def _check_init(self, init, test=None):
576
+ if init.data_type == onnx.TensorProto.FLOAT8E4M3FN:
577
+ if init.HasField("raw_data"):
578
+ b = list(init.raw_data)
579
+ if any((i & 127) == 127 for i in b):
580
+ raise ValueError(f"Initializer {init.name!r} has nan.")
581
+ return init
582
+
583
+ def _check_node(self, node):
584
+ """
585
+ A quantization to float 8 does not use quantized bias but float 16 bias.
586
+ This function checks that DequantizeLinear is not used to
587
+ dequantize from float 16.
588
+ """
589
+ if node.op_type == "DequantizeLinear":
590
+ zero_point = node.input[2]
591
+ init = self.get_initializer(zero_point)
592
+ dtype = init.data_type
593
+ if dtype in {
594
+ onnx.TensorProto.FLOAT16,
595
+ onnx.TensorProto.FLOAT,
596
+ onnx.TensorProto.DOUBLE,
597
+ onnx.TensorProto.BFLOAT16,
598
+ }:
599
+ raise RuntimeError(f"Unsupported DequantizeLinear operator, dequantization from {dtype}.")
600
+ return node
ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/quantization/onnx_quantizer.py ADDED
@@ -0,0 +1,1174 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -------------------------------------------------------------------------
2
+ # Copyright (c) Microsoft Corporation. All rights reserved.
3
+ # Licensed under the MIT License. See License.txt in the project root for
4
+ # license information.
5
+ # --------------------------------------------------------------------------
6
+ import logging
7
+
8
+ import numpy as np
9
+ import onnx
10
+ import onnx.numpy_helper
11
+ from onnx import onnx_pb as onnx_proto
12
+
13
+ from .base_quantizer import BaseQuantizer, QuantizationParams
14
+ from .calibrate import TensorData
15
+ from .onnx_model import ONNXModel
16
+ from .quant_utils import (
17
+ TENSOR_NAME_QUANT_SUFFIX,
18
+ QuantizationMode,
19
+ QuantizedValue,
20
+ QuantizedValueType,
21
+ __producer__,
22
+ __version__,
23
+ add_infer_metadata,
24
+ attribute_to_kwarg,
25
+ compute_scale_zp,
26
+ compute_scale_zp_float8,
27
+ find_by_name,
28
+ get_qmin_qmax_for_qType,
29
+ get_qrange_for_qType,
30
+ ms_domain,
31
+ quantize_onnx_initializer,
32
+ save_and_reload_model_with_shape_infer,
33
+ snap_zero_point_to_uint8,
34
+ tensor_proto_to_array,
35
+ )
36
+ from .registry import CreateOpQuantizer
37
+
38
+
39
+ class ONNXQuantizer(BaseQuantizer):
40
+ def __init__(
41
+ self,
42
+ model,
43
+ per_channel,
44
+ reduce_range,
45
+ mode,
46
+ static,
47
+ weight_qType,
48
+ activation_qType,
49
+ tensors_range,
50
+ nodes_to_quantize,
51
+ nodes_to_exclude,
52
+ op_types_to_quantize,
53
+ extra_options=None,
54
+ ):
55
+ BaseQuantizer.__init__(
56
+ self,
57
+ model,
58
+ per_channel,
59
+ reduce_range,
60
+ weight_qType,
61
+ activation_qType,
62
+ tensors_range,
63
+ nodes_to_quantize,
64
+ nodes_to_exclude,
65
+ op_types_to_quantize,
66
+ extra_options,
67
+ )
68
+
69
+ if not static:
70
+ self.model.replace_gemm_with_matmul()
71
+ # We need to update value_infos.
72
+ model = save_and_reload_model_with_shape_infer(self.model.model)
73
+ self.value_infos = {vi.name: vi for vi in model.graph.value_info}
74
+ self.value_infos.update({ot.name: ot for ot in model.graph.output})
75
+ self.value_infos.update({it.name: it for it in model.graph.input})
76
+ self.model = ONNXModel(model)
77
+
78
+ self.mode = mode # QuantizationMode.Value
79
+ self.static = static # use static quantization for inputs.
80
+ self.fuse_dynamic_quant = self.opset_version > 10
81
+
82
+ self.q_matmul_const_b_only = "MatMulConstBOnly" in self.extra_options and self.extra_options["MatMulConstBOnly"]
83
+
84
+ self.new_nodes = []
85
+ self.graph_scope = "/" # for human readable debug information
86
+ self.tensor_names = {} # in case the shape inference not totally working
87
+ self.tensor_names.update({ot.name: 1 for ot in model.graph.output})
88
+ self.tensor_names.update({it.name: 1 for it in model.graph.input})
89
+ for node in self.model.model.graph.node:
90
+ self.tensor_names.update(dict.fromkeys(node.output, 1))
91
+
92
+ if self.mode not in QuantizationMode:
93
+ raise ValueError(f"unsupported quantization mode {self.mode}")
94
+
95
+ self.quantization_params = self.calculate_quantization_params()
96
+
97
+ # QuantizeRange tensor name and zero tensor name for scale and zero point calculation.
98
+ # Used when static is False
99
+ self.fixed_qrange_uint8_name = "fixed_quantization_range_uint8"
100
+ self.fixed_qrange_int8_name = "fixed_quantization_range_int8"
101
+ # For uint8 data-type, to compute zero point, we subtract rmin from 0 (represented by fixed_zero_name tensor)
102
+ self.fixed_zero_name = "fixed_zero"
103
+ # For int8 data-type, zero point is always zero (respresented by fixed_zero_point_name tensor)
104
+ self.fixed_zero_zp_name = "fixed_zero_zp"
105
+
106
+ # Map of all original value names to quantized value names
107
+ self.quantized_value_map = {}
108
+ # some output from nodes will be quantized, yet itself should be treat as existing so
109
+ # no dequantized will be applied when needed later
110
+ self.generated_value_names = self.model.get_non_initializer_inputs()
111
+
112
+ # routines for subgraph support
113
+ def quantize_subgraph(self, subgraph, graph_key):
114
+ """
115
+ generate submodel for the subgraph, so that we re-utilize current quantization implementation.
116
+ quantize the submodel
117
+ update subgraph and set it back to node
118
+ """
119
+ warped_model = onnx.helper.make_model(
120
+ subgraph,
121
+ producer_name="onnx-quantizer",
122
+ opset_imports=self.model.model.opset_import,
123
+ )
124
+ add_infer_metadata(warped_model)
125
+ sub_quantizer = ONNXQuantizer(
126
+ warped_model,
127
+ self.per_channel,
128
+ self.reduce_range,
129
+ self.mode,
130
+ self.static,
131
+ self.weight_qType,
132
+ self.activation_qType,
133
+ self.tensors_range,
134
+ self.nodes_to_quantize,
135
+ self.nodes_to_exclude,
136
+ self.op_types_to_quantize,
137
+ self.extra_options,
138
+ )
139
+ sub_quantizer.parent = self
140
+ sub_quantizer.graph_scope = f"{self.graph_scope}{graph_key}/"
141
+ sub_quantizer.quantize_model()
142
+ return sub_quantizer.model.model.graph
143
+
144
+ def quantize_node_with_sub_graph(self, node):
145
+ """
146
+ Check subgraph, if any, quantize it and replace it.
147
+ return new_nodes added for quantizing subgraph
148
+ """
149
+ graph_attrs = [
150
+ attr
151
+ for attr in node.attribute
152
+ if attr.type == onnx.AttributeProto.GRAPH or attr.type == onnx.AttributeProto.GRAPHS
153
+ ]
154
+ if len(graph_attrs) == 0:
155
+ return node
156
+ node_name = node.name if node.name else f"{node.op_type}_node_count_{len(self.new_nodes)}"
157
+ kwargs = {}
158
+ for attr in node.attribute:
159
+ if attr.type == onnx.AttributeProto.GRAPH:
160
+ kv = {attr.name: self.quantize_subgraph(attr.g, f"{node_name}:{attr.name}")}
161
+ elif attr.type == onnx.AttributeProto.GRAPHS:
162
+ value = []
163
+ for subgraph in attr.graphs:
164
+ value.extend(
165
+ [
166
+ self.quantize_subgraph(
167
+ subgraph,
168
+ f"{node_name}:{attr.name}:{len(value)}",
169
+ )
170
+ ]
171
+ )
172
+ kv = {attr.name: value}
173
+ else:
174
+ kv = attribute_to_kwarg(attr)
175
+ kwargs.update(kv)
176
+ return onnx.helper.make_node(node.op_type, node.input, node.output, name=node.name, **kwargs)
177
+
178
+ def has_QDQ_nodes(self): # noqa: N802
179
+ """
180
+ Detect if model already has QuantizeLinear or DequantizeLinear.
181
+ """
182
+ return any(
183
+ node.op_type == "QuantizeLinear" or node.op_type == "DequantizeLinear" for node in self.model.nodes()
184
+ )
185
+
186
+ def find_initializer_in_path(self, initializer_name):
187
+ if find_by_name(initializer_name, self.model.initializer()) is not None:
188
+ return True
189
+ if self.parent is not None:
190
+ return self.parent.find_initializer_in_path(initializer_name)
191
+ return False
192
+
193
+ def add_new_nodes(self, nodes):
194
+ self.new_nodes.extend(nodes)
195
+ for node in nodes:
196
+ for output_name in node.output:
197
+ self.generated_value_names.add(output_name)
198
+
199
+ def quantize_model(self):
200
+ if self.has_QDQ_nodes():
201
+ logging.warning(
202
+ "Please check if the model is already quantized. "
203
+ "Note you don't need to quantize a QAT model. OnnxRuntime support to run QAT model directly."
204
+ )
205
+
206
+ for node in self.model.nodes():
207
+ # quantize subgraphes if have
208
+ if self.enable_subgraph_quantization:
209
+ node = self.quantize_node_with_sub_graph(node) # noqa: PLW2901
210
+
211
+ number_of_existing_new_nodes = len(self.new_nodes)
212
+ op_quantizer = CreateOpQuantizer(self, node)
213
+ op_quantizer.quantize()
214
+ for i in range(number_of_existing_new_nodes, len(self.new_nodes)):
215
+ for output_name in self.new_nodes[i].output:
216
+ self.generated_value_names.add(output_name)
217
+
218
+ self._dequantize_outputs()
219
+
220
+ # extend is used to append to the list for a protobuf fields
221
+ # https://developers.google.com/protocol-buffers/docs/reference/python-generated?csw=1#fields
222
+ self.model.graph().ClearField("node")
223
+ self.model.graph().node.extend(self.new_nodes)
224
+
225
+ # Remove ununsed initializers from graph, starting from the top level graph.
226
+ if self.parent is None:
227
+ _, initializers_not_found = self.model.clean_initializers()
228
+ if len(initializers_not_found) > 0:
229
+ raise RuntimeError("Invalid model with unknown initializers/tensors." + str(initializers_not_found))
230
+
231
+ self.model.model.producer_name = __producer__
232
+ self.model.model.producer_version = __version__
233
+ # Add ms domain if needed
234
+ ms_opset = [opset for opset in self.model.model.opset_import if opset.domain == ms_domain]
235
+ if not ms_opset:
236
+ ms_nodes = [node for node in self.new_nodes if node.domain == "com.microsoft"]
237
+ if ms_nodes:
238
+ opset = self.model.model.opset_import.add()
239
+ opset.version = 1
240
+ opset.domain = ms_domain
241
+
242
+ return self.model.model
243
+
244
+ def _get_default_tensor_type(self, tensor_name):
245
+ if "DefaultTensorType" in self.extra_options:
246
+ logging.info(
247
+ "get_tensor_type returns DefaultTensorType for tensor name %r, use %d",
248
+ tensor_name,
249
+ self.extra_options["DefaultTensorType"],
250
+ )
251
+ return self.extra_options["DefaultTensorType"]
252
+ raise RuntimeError(
253
+ f"Unable to find data type for weight_name={tensor_name!r}. "
254
+ f"shape_inference failed to return a type probably this node is "
255
+ f"from a different domain or using an input produced by such an operator. "
256
+ f"This may happen if you quantize a model already quantized. "
257
+ f"You may use extra_options `DefaultTensorType` to indicate "
258
+ f"the default weight type, usually `onnx.TensorProto.FLOAT`."
259
+ )
260
+
261
+ def get_tensor_type(self, tensor_name, mandatory=False):
262
+ weight = find_by_name(tensor_name, self.model.initializer())
263
+ if weight is not None:
264
+ return weight.data_type
265
+ if tensor_name in self.value_infos:
266
+ vi = self.value_infos[tensor_name]
267
+ if vi.type.HasField("tensor_type"):
268
+ if mandatory and vi.type.tensor_type.elem_type == 0:
269
+ return self._get_default_tensor_type(tensor_name)
270
+ return vi.type.tensor_type.elem_type
271
+ if (not self.enable_subgraph_quantization) or (self.parent is None):
272
+ if mandatory:
273
+ return self._get_default_tensor_type(tensor_name)
274
+ return None
275
+ otype = self.parent.is_valid_quantize_weight(tensor_name)
276
+ if otype is not None:
277
+ return otype
278
+ if self.enable_subgraph_quantization and self.parent:
279
+ res = self.parent.get_tensor_type(tensor_name)
280
+ if res is not None:
281
+ return res
282
+ if mandatory:
283
+ return self._get_default_tensor_type(tensor_name)
284
+ return None
285
+
286
+ def is_float_tensor(self, tensor_name):
287
+ if self.is_input_a_initializer(tensor_name):
288
+ return self.is_valid_quantize_weight(tensor_name)
289
+
290
+ if tensor_name in self.value_infos:
291
+ vi = self.value_infos[tensor_name]
292
+ if vi.type.HasField("tensor_type") and vi.type.tensor_type.elem_type in (
293
+ onnx_proto.TensorProto.FLOAT,
294
+ onnx_proto.TensorProto.FLOAT16,
295
+ ):
296
+ return True
297
+ logging.warning(
298
+ f"Inference failed or unsupported type to quantize for tensor {tensor_name!r}, type is {vi.type}."
299
+ )
300
+ return False
301
+
302
+ if self.enable_subgraph_quantization and self.parent:
303
+ return self.parent.is_float_tensor(tensor_name)
304
+
305
+ logging.warning(
306
+ f"Failed to infer data type of tensor: {tensor_name!r}. Please add data type info for this tensor "
307
+ f"if your model has customized operators."
308
+ )
309
+ return False
310
+
311
+ def _get_dynamic_input_quantization_params(self, input_name, nodes_list, qType, initial_type):
312
+ """
313
+ Create nodes for dynamic quantization of input and add them to nodes_list.
314
+ parameter input_name: Name of the input.
315
+ parameter nodes_list: new nodes are appended to this list.
316
+ parameter qType: type to quantize to.
317
+ parameter initial_type: type to quantize from
318
+ return: scale_name, zero_point_name, scale_shape, zero_point_shape.
319
+ """
320
+ if qType == onnx_proto.TensorProto.INT8:
321
+ return self._get_dynamic_input_quantization_params_int8(input_name, nodes_list, initial_type)
322
+ if qType == onnx_proto.TensorProto.UINT8:
323
+ return self._get_dynamic_input_quantization_params_uint8(input_name, nodes_list, initial_type)
324
+ raise ValueError(f"Unexpected value for qType={qType}.")
325
+
326
+ def _get_dynamic_input_quantization_params_int8(self, input_name, nodes_list, initial_type):
327
+ """
328
+ Create nodes for dynamic quantization of input to int8 and add them to nodes_list
329
+ parameter input_name: Name of the input.
330
+ parameter nodes_list: new nodes are appended to this list.
331
+ parameter initial_type: initial weight type (FLOAT or FLOAT16)
332
+ return: scale_name, zero_point_name, scale_shape, zero_point_shape.
333
+ """
334
+ qType = onnx_proto.TensorProto.INT8 # noqa: N806
335
+
336
+ # Reduce min and Reduce max
337
+ input_scale_name = input_name + "_scale"
338
+
339
+ reduce_min_name = input_name + "_ReduceMin"
340
+ reduce_min_node = onnx.helper.make_node(
341
+ "ReduceMin",
342
+ [input_name],
343
+ [reduce_min_name + ":0"],
344
+ reduce_min_name,
345
+ keepdims=0,
346
+ )
347
+ nodes_list.append(reduce_min_node)
348
+
349
+ reduce_max_name = input_name + "_ReduceMax"
350
+ reduce_max_node = onnx.helper.make_node(
351
+ "ReduceMax",
352
+ [input_name],
353
+ [reduce_max_name + ":0"],
354
+ reduce_max_name,
355
+ keepdims=0,
356
+ )
357
+ nodes_list.append(reduce_max_node)
358
+
359
+ # Compute scale
360
+ # Find abs(rmin)
361
+ reduce_min_abs_name = reduce_min_name + "_Abs"
362
+ reduce_min_abs_node = onnx.helper.make_node(
363
+ "Abs",
364
+ [reduce_min_node.output[0]],
365
+ [reduce_min_abs_name + ":0"],
366
+ reduce_min_abs_name,
367
+ )
368
+ nodes_list.append(reduce_min_abs_node)
369
+ # Find abs(rmax)
370
+ reduce_max_abs_name = reduce_max_name + "_Abs"
371
+ reduce_max_abs_node = onnx.helper.make_node(
372
+ "Abs",
373
+ [reduce_max_node.output[0]],
374
+ [reduce_max_abs_name + ":0"],
375
+ reduce_max_abs_name,
376
+ )
377
+ nodes_list.append(reduce_max_abs_node)
378
+ # Compute max of abs(rmin) and abs(rmax)
379
+ abs_max_name = input_name + "_Abs_Max"
380
+ abs_max_node = onnx.helper.make_node(
381
+ "Max",
382
+ [reduce_min_abs_node.output[0], reduce_max_abs_node.output[0]],
383
+ [abs_max_name + ":0"],
384
+ abs_max_name,
385
+ )
386
+ nodes_list.append(abs_max_node)
387
+ # and divide by (quantize_range/2.0) which will be equal to max(...)*2.0/quantize_range
388
+ initializer_div = onnx.helper.make_tensor(
389
+ self.fixed_qrange_int8_name,
390
+ initial_type,
391
+ [],
392
+ [get_qrange_for_qType(qType) / 2.0],
393
+ )
394
+ self.model.add_initializer(initializer_div)
395
+ scale_div_name = input_name + "scale_Div"
396
+ scale_div_node = onnx.helper.make_node(
397
+ "Div",
398
+ [abs_max_node.output[0], self.fixed_qrange_int8_name],
399
+ [input_scale_name],
400
+ scale_div_name,
401
+ )
402
+ nodes_list.append(scale_div_node)
403
+
404
+ # Zero point
405
+ initializer_zp = onnx.helper.make_tensor(self.fixed_zero_zp_name, qType, [], [0])
406
+ self.model.add_initializer(initializer_zp)
407
+
408
+ return input_scale_name, self.fixed_zero_zp_name, [], []
409
+
410
+ def _get_dynamic_input_quantization_params_uint8(self, input_name, nodes_list, initial_type):
411
+ """
412
+ Create nodes for dynamic quantization of input to uint8 and add them to nodes_list
413
+ parameter input_name: Name of the input.
414
+ parameter nodes_list: new nodes are appended to this list.
415
+ parameter initial_type: initial weight type (FLAOT or FLOAT16)
416
+ return: scale_name, zero_point_name, scale_shape, zero_point_shape.
417
+ """
418
+ qType = onnx_proto.TensorProto.UINT8 # noqa: N806
419
+ # Reduce min and Reduce max
420
+ input_scale_name = input_name + "_scale"
421
+ input_zp_name = input_name + "_zero_point"
422
+
423
+ reduce_min_name = input_name + "_ReduceMin"
424
+ reduce_min_node = onnx.helper.make_node(
425
+ "ReduceMin",
426
+ [input_name],
427
+ [reduce_min_name + ":0"],
428
+ reduce_min_name,
429
+ keepdims=0,
430
+ )
431
+ nodes_list.append(reduce_min_node)
432
+
433
+ reduce_max_name = input_name + "_ReduceMax"
434
+ reduce_max_node = onnx.helper.make_node(
435
+ "ReduceMax",
436
+ [input_name],
437
+ [reduce_max_name + ":0"],
438
+ reduce_max_name,
439
+ keepdims=0,
440
+ )
441
+ nodes_list.append(reduce_max_node)
442
+
443
+ # Add tensors for quantize range and zero value.
444
+ initializer_qrange = onnx.helper.make_tensor(
445
+ self.fixed_qrange_uint8_name,
446
+ initial_type,
447
+ [],
448
+ [get_qrange_for_qType(qType)],
449
+ )
450
+ self.model.add_initializer(initializer_qrange)
451
+ initializer_qvalue = onnx.helper.make_tensor(self.fixed_zero_name, initial_type, [], [0.0])
452
+ self.model.add_initializer(initializer_qvalue)
453
+
454
+ # Compute Scale
455
+ # Subtract rmax and rmin
456
+ scale_sub_name = input_name + "_scale_Sub"
457
+ scale_sub_node = onnx.helper.make_node(
458
+ "Sub",
459
+ [reduce_max_node.output[0], reduce_min_node.output[0]],
460
+ [scale_sub_name + ":0"],
461
+ scale_sub_name,
462
+ )
463
+ nodes_list.append(scale_sub_node)
464
+ # and divide by quantize range
465
+ scale_div_name = input_name + "_scale_Div"
466
+ scale_div_node = onnx.helper.make_node(
467
+ "Div",
468
+ [scale_sub_node.output[0], self.fixed_qrange_uint8_name],
469
+ [input_scale_name],
470
+ scale_div_name,
471
+ )
472
+ nodes_list.append(scale_div_node)
473
+
474
+ # Compute zero point
475
+ # Subtract zero and rmin
476
+ zp_sub_name = input_name + "_zero_point_Sub"
477
+ zp_sub_node = onnx.helper.make_node(
478
+ "Sub",
479
+ [self.fixed_zero_name, reduce_min_node.output[0]],
480
+ [zp_sub_name + ":0"],
481
+ zp_sub_name,
482
+ )
483
+ nodes_list.append(zp_sub_node)
484
+ # Divide by scale
485
+ zp_div_name = input_name + "_zero_point_Div"
486
+ zp_div_node = onnx.helper.make_node(
487
+ "Div",
488
+ [zp_sub_node.output[0], input_scale_name],
489
+ [zp_div_name + ":0"],
490
+ zp_div_name,
491
+ )
492
+ nodes_list.append(zp_div_node)
493
+ # Compute floor
494
+ zp_floor_name = input_name + "_zero_point_Floor"
495
+ zp_floor_node = onnx.helper.make_node("Floor", zp_div_node.output, [zp_floor_name + ":0"], zp_floor_name)
496
+ nodes_list.append(zp_floor_node)
497
+ # Cast to integer
498
+ zp_cast_name = input_name + "_zero_point_Cast"
499
+ zp_cast_node = onnx.helper.make_node("Cast", zp_floor_node.output, [input_zp_name], zp_cast_name, to=qType)
500
+ nodes_list.append(zp_cast_node)
501
+
502
+ return input_scale_name, input_zp_name, [], []
503
+
504
+ def _get_quantization_params(self, param_name, use_scale=None, use_zeropoint=None):
505
+ """
506
+ Create initializers and inputs in the graph for zero point and scale of output.
507
+ Zero point and scale values are obtained from self.quantization_params if specified.
508
+ parameter param_name: Name of the quantization parameter.
509
+ return: result, scale_name, zero_point_name, scale_shape, zero_point_shape.
510
+ """
511
+ zero_point_type = self.activation_qType
512
+
513
+ if use_scale is None or use_zeropoint is None:
514
+ if self.quantization_params is None or param_name not in self.quantization_params:
515
+ logging.info(f'Quantization parameters for tensor:"{param_name}" not specified')
516
+ return False, "", "", "", ""
517
+
518
+ params = self.quantization_params[param_name]
519
+ if not isinstance(params, QuantizationParams):
520
+ raise TypeError(f"Unexpected type {type(params)} for {param_name!r}.")
521
+ if params is None or len(params) != 3:
522
+ raise ValueError(
523
+ "Quantization parameters should contain zero point, scale, quant type. "
524
+ f"Specified values for output {param_name}: {params}"
525
+ )
526
+
527
+ zero_point_values = np.array([params["zero_point"]])
528
+ if not hasattr(params["scale"], "dtype") or params["scale"].dtype not in (np.float32, np.float16):
529
+ raise ValueError(f"Unexpected type {type(params['scale'])} and param_name={param_name!r}")
530
+ scale_values = np.array([params["scale"]])
531
+ assert scale_values.dtype != np.float64
532
+ zero_point_type = params["quant_type"]
533
+ else:
534
+ zero_point_values = np.array([use_zeropoint])
535
+ scale_values = np.array([use_scale])
536
+ params = self.quantization_params[param_name]
537
+ if "scale" in params:
538
+ dtype = params["scale"].dtype
539
+ scale_values = scale_values.astype(dtype)
540
+ assert scale_values.dtype != np.float64
541
+
542
+ zero_point_shape = []
543
+ zero_point_name = param_name + "_zero_point"
544
+ scale_shape = []
545
+ scale_name = param_name + "_scale"
546
+
547
+ # Add initializers
548
+ init_zp = onnx.helper.make_tensor(
549
+ zero_point_name, zero_point_type, zero_point_shape, zero_point_values.ravel().tolist()
550
+ )
551
+ self.model.add_initializer(init_zp)
552
+ if scale_values.dtype == np.float32:
553
+ scale_type = onnx_proto.TensorProto.FLOAT
554
+ elif scale_values.dtype == np.float16:
555
+ scale_type = onnx_proto.TensorProto.FLOAT16
556
+ else:
557
+ raise ValueError(f"Unexpected dtype={scale_values.dtype} for param_name={param_name!r}")
558
+ init_scale = onnx.helper.make_tensor(scale_name, scale_type, scale_shape, scale_values.reshape((-1,)).tolist())
559
+ self.model.add_initializer(init_scale)
560
+
561
+ return True, scale_name, zero_point_name, scale_shape, zero_point_shape
562
+
563
+ def _get_quantize_input_nodes(
564
+ self, node, input_index, qType, given_scale_name=None, given_zp_name=None, initial_type=None
565
+ ):
566
+ """
567
+ Given an input for a node (which is not a initializer), this function
568
+
569
+ - add nodes to compute zero point and scale for this input if they don't exist.
570
+ - add new QuantizeLinear node to quantize the input.
571
+
572
+ :param node: node being quantized in NodeProto format.
573
+ :param input_index: index of input in node.input.
574
+ :param qType: type to quantize to.
575
+ :param given_scale_name: if those inputs need to be quanitzed using this scale tensor.
576
+ :param given_zp_name: if those inputs to be quantized using this zeropoint tensor.
577
+ :param initial_type: type of the weight to quantize
578
+ :return: List of newly created nodes in NodeProto format.
579
+ """
580
+ input_name = node.input[input_index]
581
+ assert input_name != "", "Cannot access undefined variable in graph."
582
+ output_name = input_name + TENSOR_NAME_QUANT_SUFFIX
583
+ ql_node_name = input_name + "_QuantizeLinear"
584
+
585
+ if (given_scale_name is not None) and (given_zp_name is not None):
586
+ data_found, scale_name, zp_name = (True, given_scale_name, given_zp_name)
587
+ else:
588
+ data_found, scale_name, zp_name, _, _ = self._get_quantization_params(input_name)
589
+
590
+ nodes = []
591
+ if data_found:
592
+ qlinear_node = onnx.helper.make_node(
593
+ "QuantizeLinear",
594
+ [input_name, scale_name, zp_name],
595
+ [output_name],
596
+ ql_node_name,
597
+ )
598
+ else:
599
+ if self.static:
600
+ return None
601
+ # dynamic mode
602
+ # Scale and Zero Points not available for this input. Add nodes to dynamically compute it
603
+ if self.fuse_dynamic_quant and qType == onnx_proto.TensorProto.UINT8:
604
+ scale_name = input_name + "_scale"
605
+ zp_name = input_name + "_zero_point"
606
+ qlinear_node = onnx.helper.make_node(
607
+ "DynamicQuantizeLinear",
608
+ [input_name],
609
+ [output_name, scale_name, zp_name],
610
+ ql_node_name,
611
+ )
612
+ else:
613
+ assert initial_type is not None, (
614
+ f"Cannot quantize input without knowing the initial type, "
615
+ f"input_name={input_name!r}, input_index={input_index}, qType={qType}, node={node}"
616
+ )
617
+ (
618
+ scale_name,
619
+ zp_name,
620
+ scale_shape,
621
+ zp_shape,
622
+ ) = self._get_dynamic_input_quantization_params(input_name, nodes, qType, initial_type=initial_type)
623
+ qlinear_node = onnx.helper.make_node(
624
+ "QuantizeLinear",
625
+ [input_name, scale_name, zp_name],
626
+ [output_name],
627
+ ql_node_name,
628
+ )
629
+
630
+ self.quantized_value_map[input_name] = QuantizedValue(input_name, output_name, scale_name, zp_name, qType)
631
+ return [*nodes, qlinear_node]
632
+
633
+ def find_quantized_value(self, input_name):
634
+ if input_name in self.quantized_value_map:
635
+ return self.quantized_value_map[input_name]
636
+ if self.parent is not None:
637
+ return self.parent.find_quantized_value(input_name)
638
+ return None
639
+
640
+ def adjust_single_weight_scale_if_needed(
641
+ self,
642
+ bias_val,
643
+ input_scale,
644
+ weight_scale,
645
+ weight_scale_dtype,
646
+ weight_name,
647
+ bias_name,
648
+ qrange,
649
+ multiplicative_epsilon,
650
+ idx=None,
651
+ ):
652
+ """Adjust a single weight scale to ensure the int32 bias does not overflow."""
653
+ absmax = np.abs(bias_val)
654
+ bias_smallest_valid_scale = multiplicative_epsilon * (2.0 * absmax) / qrange
655
+
656
+ input_scale_fp64 = np.array(input_scale.item(), dtype=np.float64)
657
+ weight_scale_fp64 = np.array(weight_scale.item(), dtype=np.float64)
658
+ bias_candidate_scale = input_scale_fp64 * weight_scale_fp64
659
+
660
+ if (bias_candidate_scale < bias_smallest_valid_scale) and (bias_candidate_scale > 0.0):
661
+ ratio = bias_smallest_valid_scale / bias_candidate_scale
662
+ new_scale = weight_scale_fp64 * ratio
663
+ if idx is None:
664
+ logging.info(
665
+ f"Increasing scale for weight `{weight_name}` by the ratio {ratio} to "
666
+ f"ensure bias `{bias_name}` has a valid scale."
667
+ )
668
+ return True, np.array(new_scale, dtype=weight_scale_dtype)
669
+ else:
670
+ logging.info(
671
+ f"Increased scale[{idx}] for weight `{weight_name}` by ratio {ratio} "
672
+ f"to ensure bias `{bias_name}` has a valid scale."
673
+ )
674
+ return True, new_scale.astype(weight_scale_dtype)
675
+ return False, weight_scale
676
+
677
+ def _adjust_weight_scale_for_int32_bias(
678
+ self,
679
+ input_scale: np.ndarray,
680
+ weight_scale: np.ndarray,
681
+ weight_name: str,
682
+ bias_tp: onnx.TensorProto,
683
+ is_per_channel: bool,
684
+ ) -> tuple[bool, np.ndarray | None]:
685
+ """Checks if the bias scale is too small and increases the weight scale if needed."""
686
+
687
+ if not weight_scale.size:
688
+ return False, None
689
+
690
+ bias_float_data = tensor_proto_to_array(bias_tp)
691
+ int32_info = np.iinfo(np.int32)
692
+ multiplicative_epsilon = 1.0001
693
+ qrange = np.array(int32_info.max, dtype=np.float64) - np.array(int32_info.min + 1, dtype=np.float64)
694
+ weight_scale_dtype = weight_scale.dtype
695
+ updated = False
696
+
697
+ if not is_per_channel:
698
+ rmin = np.minimum(bias_float_data.min(), np.array(0, dtype=np.float64))
699
+ rmax = np.maximum(bias_float_data.max(), np.array(0, dtype=np.float64))
700
+ absmax = np.maximum(np.abs(rmin), np.abs(rmax))
701
+ changed, new_scale = self.adjust_single_weight_scale_if_needed(
702
+ absmax,
703
+ input_scale,
704
+ weight_scale,
705
+ weight_scale_dtype,
706
+ weight_name,
707
+ bias_tp.name,
708
+ qrange,
709
+ multiplicative_epsilon,
710
+ )
711
+ if changed:
712
+ weight_scale = new_scale
713
+ updated = True
714
+ elif weight_scale.shape and len(weight_scale.shape) == 1:
715
+ for i in range(weight_scale.shape[0]):
716
+ changed, new_scale = self.adjust_single_weight_scale_if_needed(
717
+ bias_float_data[i],
718
+ input_scale,
719
+ weight_scale[i],
720
+ weight_scale_dtype,
721
+ weight_name,
722
+ bias_tp.name,
723
+ qrange,
724
+ multiplicative_epsilon,
725
+ idx=i,
726
+ )
727
+ if changed:
728
+ weight_scale[i] = new_scale
729
+ updated = True
730
+
731
+ return updated, weight_scale
732
+
733
+ def _requantize_weight(self, weight_name: str, new_scale: np.ndarray) -> None:
734
+ """Re-quantizes the given weight initializer using the provided scale."""
735
+
736
+ if weight_name not in self.quantized_value_map:
737
+ return
738
+
739
+ qv = self.quantized_value_map[weight_name]
740
+
741
+ weight_tp = find_by_name(weight_name, self.model.initializer())
742
+ scale_init = find_by_name(qv.scale_name, self.model.initializer())
743
+ zp_init = find_by_name(qv.zp_name, self.model.initializer())
744
+ q_weight_init = find_by_name(qv.q_name, self.model.initializer())
745
+
746
+ if weight_tp is None or scale_init is None or zp_init is None or q_weight_init is None:
747
+ return
748
+
749
+ self.model.remove_initializer(scale_init)
750
+ self.model.remove_initializer(q_weight_init)
751
+
752
+ weight_zero_point = onnx.numpy_helper.to_array(zp_init)
753
+ axis = qv.axis
754
+
755
+ # Add new scale initializer
756
+ scale_np = np.asarray(new_scale, dtype=onnx.helper.tensor_dtype_to_np_dtype(weight_tp.data_type))
757
+ new_scale_init = onnx.numpy_helper.from_array(scale_np.reshape(scale_init.dims), qv.scale_name)
758
+ self.model.add_initializer(new_scale_init)
759
+
760
+ # Add new quantized weight initializer
761
+ new_q_weight = quantize_onnx_initializer(
762
+ weight_tp,
763
+ self.weight_qType,
764
+ weight_zero_point,
765
+ scale_np,
766
+ axis,
767
+ quant_weight_name=qv.q_name,
768
+ )
769
+ self.model.add_initializer(new_q_weight)
770
+
771
+ def quantize_bias_static(self, bias_name, input_name, weight_name, beta=1.0):
772
+ """
773
+ Quantized the bias. Zero Point == 0 and Scale == Input_Scale * Weight_Scale
774
+ """
775
+
776
+ # Handle case where bias already in quantization map
777
+ if bias_name in self.quantized_value_map:
778
+ return self.quantized_value_map[bias_name].q_name
779
+
780
+ # get scale for weight
781
+ weight_scale_name = self.quantized_value_map[weight_name].scale_name
782
+ weight_initializer = find_by_name(weight_scale_name, self.model.initializer())
783
+ weight_scale = tensor_proto_to_array(weight_initializer)
784
+
785
+ # get scale for input
786
+ if input_name in self.quantized_value_map:
787
+ input_scale_name = self.quantized_value_map[input_name].scale_name
788
+ elif input_name in self.quantization_params:
789
+ _, input_scale_name, _, _, _ = self._get_quantization_params(input_name)
790
+ else:
791
+ raise ValueError(f"Expected {input_name} to be in quantized value map for static quantization")
792
+
793
+ inputscale_initializer = find_by_name(input_scale_name, self.model.initializer())
794
+ input_scale = tensor_proto_to_array(inputscale_initializer)
795
+
796
+ # Adjust weight scale if quantizing to int32 may overflow due to a small scale
797
+ weight_zp_name = self.quantized_value_map[weight_name].zp_name
798
+ weight_zp_init = find_by_name(weight_zp_name, self.model.initializer())
799
+ weight_zero_point = onnx.numpy_helper.to_array(weight_zp_init) if weight_zp_init is not None else None
800
+ is_per_channel = self.per_channel
801
+ if (
802
+ weight_zero_point is not None
803
+ and weight_zero_point.size
804
+ and not weight_zero_point.any()
805
+ and self.weight_qType in (onnx_proto.TensorProto.INT8,)
806
+ ):
807
+ bias_initializer = find_by_name(bias_name, self.model.initializer())
808
+ did_update, new_weight_scale = self._adjust_weight_scale_for_int32_bias(
809
+ input_scale,
810
+ weight_scale,
811
+ weight_name,
812
+ bias_initializer,
813
+ is_per_channel,
814
+ )
815
+ if did_update:
816
+ self._requantize_weight(weight_name, new_weight_scale)
817
+ weight_scale = new_weight_scale
818
+
819
+ (
820
+ quantized_bias_name,
821
+ quantized_bias_scale_name,
822
+ quantized_bias_zp_name,
823
+ bias_scale_data,
824
+ node_type,
825
+ node_qtype,
826
+ ) = self.quantize_bias_static_impl(bias_name, input_scale, weight_scale, beta)
827
+
828
+ assert bias_name not in self.quantized_value_map
829
+ quantized_value = QuantizedValue(
830
+ bias_name,
831
+ quantized_bias_name,
832
+ quantized_bias_scale_name,
833
+ quantized_bias_zp_name,
834
+ QuantizedValueType.Initializer,
835
+ 0 if bias_scale_data.size > 1 else None,
836
+ node_type=node_type,
837
+ node_qtype=node_qtype,
838
+ )
839
+ self.quantized_value_map[bias_name] = quantized_value
840
+
841
+ return quantized_bias_name
842
+
843
+ def contains_tensor(self, tensor_name):
844
+ """
845
+ only check for value info and newly generated tensor names, initializers are checked separately
846
+ """
847
+ return (
848
+ (tensor_name in self.value_infos)
849
+ or (tensor_name in self.tensor_names)
850
+ or (tensor_name in self.generated_value_names)
851
+ )
852
+
853
+ def quantize_activation(self, node, indices, from_subgraph=False):
854
+ return self.__quantize_inputs(
855
+ node=node,
856
+ indices=indices,
857
+ initializer_use_weight_qType=False,
858
+ reduce_range=False,
859
+ op_level_per_channel=False,
860
+ axis=-1,
861
+ from_subgraph=from_subgraph,
862
+ )
863
+
864
+ # In some circumstances a weight is not an initializer, for example of MatMul, if both A and B are not
865
+ # initializer, B can still be considered as Weight
866
+ def quantize_weight(
867
+ self,
868
+ node,
869
+ indices,
870
+ reduce_range=False,
871
+ op_level_per_channel=False,
872
+ axis=-1,
873
+ from_subgraph=False,
874
+ ):
875
+ return self.__quantize_inputs(
876
+ node=node,
877
+ indices=indices,
878
+ initializer_use_weight_qType=True,
879
+ reduce_range=reduce_range,
880
+ op_level_per_channel=op_level_per_channel,
881
+ axis=axis,
882
+ from_subgraph=from_subgraph,
883
+ )
884
+
885
+ def __quantize_inputs(
886
+ self,
887
+ node,
888
+ indices,
889
+ initializer_use_weight_qType=True,
890
+ reduce_range=False,
891
+ op_level_per_channel=False,
892
+ axis=-1,
893
+ from_subgraph=False,
894
+ ):
895
+ """
896
+ Given a node, this function quantizes the inputs as follows:
897
+ - If input is an initializer, quantize the initializer data, replace old initializer
898
+ with new initializer
899
+ - Else, add QuantizeLinear nodes to perform quantization
900
+ parameter node: node being quantized in NodeProto format.
901
+ parameter indices: input indices to quantize.
902
+ return: (List of quantized input names,
903
+ List of zero point names used for input quantization,
904
+ List of scale names used for input quantization,
905
+ List of new QuantizeLinear nodes created)
906
+ """
907
+
908
+ scale_names = []
909
+ zero_point_names = []
910
+ quantized_input_names = []
911
+ nodes = []
912
+
913
+ for input_index in indices:
914
+ node_input = node.input[input_index]
915
+
916
+ # Find if this input is already quantized
917
+ if node_input in self.quantized_value_map:
918
+ quantized_value = self.quantized_value_map[node_input]
919
+ scale_names.append(quantized_value.scale_name)
920
+ zero_point_names.append(quantized_value.zp_name)
921
+ quantized_input_names.append(quantized_value.q_name)
922
+ continue
923
+ # adding this for case embed_layernorm.py has optional segment_embedding
924
+ if not node_input:
925
+ quantized_input_names.append("")
926
+ scale_names.append("")
927
+ zero_point_names.append("")
928
+ continue
929
+ # Quantize the input
930
+ initializer = find_by_name(node_input, self.model.initializer())
931
+ if initializer is not None:
932
+ if self.per_channel and op_level_per_channel:
933
+ (
934
+ q_weight_name,
935
+ zp_name,
936
+ scale_name,
937
+ ) = self.quantize_weight_per_channel(
938
+ initializer.name,
939
+ self.weight_qType if initializer_use_weight_qType else self.activation_qType,
940
+ axis,
941
+ reduce_range,
942
+ )
943
+ else:
944
+ q_weight_name, zp_name, scale_name = self.quantize_initializer(
945
+ initializer,
946
+ self.weight_qType if initializer_use_weight_qType else self.activation_qType,
947
+ reduce_range,
948
+ )
949
+
950
+ quantized_input_names.append(q_weight_name)
951
+ zero_point_names.append(zp_name)
952
+ scale_names.append(scale_name)
953
+ elif self.contains_tensor(node_input):
954
+ # Add QuantizeLinear node.
955
+ qlinear_node = self.model.find_node_by_name(
956
+ node_input + "_QuantizeLinear", self.new_nodes, self.model.graph()
957
+ )
958
+ if qlinear_node is None:
959
+ input_name = node.input[input_index]
960
+ if input_name in self.value_infos:
961
+ value_info = self.value_infos[input_name]
962
+ assert value_info.HasField("type"), f"value_info={value_info} has no type."
963
+ assert value_info.type.HasField("tensor_type"), f"value_info={value_info} is not a tensor."
964
+ initial_type = value_info.type.tensor_type.elem_type
965
+ else:
966
+ # Shape inference failed. Fallback to self.tensor_names.
967
+ assert input_name in self.tensor_names, (
968
+ f"shape inference failed for {input_name!r} and "
969
+ f"attribute 'tensor_names' does not have any value for "
970
+ f"this tensor."
971
+ )
972
+ initial_type = self.tensor_names[input_name]
973
+ quantize_input_nodes = self._get_quantize_input_nodes(
974
+ node, input_index, self.activation_qType, initial_type=initial_type
975
+ )
976
+ if quantize_input_nodes is None:
977
+ return (None, None, None, None)
978
+ if from_subgraph:
979
+ self.add_new_nodes(quantize_input_nodes)
980
+ else:
981
+ nodes.extend(quantize_input_nodes)
982
+ qlinear_node = quantize_input_nodes[-1]
983
+
984
+ if qlinear_node.op_type == "QuantizeLinear":
985
+ quantized_input_names.extend(qlinear_node.output)
986
+ scale_names.append(qlinear_node.input[1])
987
+ zero_point_names.append(qlinear_node.input[2])
988
+ else:
989
+ quantized_input_names.append(qlinear_node.output[0])
990
+ scale_names.append(qlinear_node.output[1])
991
+ zero_point_names.append(qlinear_node.output[2])
992
+ elif self.parent is not None:
993
+ (
994
+ parent_quantized_input_names,
995
+ parent_zero_point_names,
996
+ parent_scale_names,
997
+ _,
998
+ ) = self.parent.__quantize_inputs(
999
+ node,
1000
+ [input_index],
1001
+ initializer_use_weight_qType=initializer_use_weight_qType,
1002
+ reduce_range=reduce_range,
1003
+ op_level_per_channel=op_level_per_channel,
1004
+ axis=axis,
1005
+ from_subgraph=True,
1006
+ )
1007
+ quantized_input_names.append(parent_quantized_input_names[0])
1008
+ scale_names.append(parent_scale_names[0])
1009
+ zero_point_names.append(parent_zero_point_names[0])
1010
+ # node should not be add this child level here
1011
+ else:
1012
+ raise ValueError(f"Invalid tensor name to quantize: {node_input} @graph scope{self.graph_scope}")
1013
+
1014
+ return quantized_input_names, zero_point_names, scale_names, nodes
1015
+
1016
+ def quantize_initializer(self, weight, qType, reduce_range=False, keep_float_weight=False):
1017
+ """
1018
+ :param weight: TensorProto initializer
1019
+ :param qType: type to quantize to
1020
+ :param keep_float_weight: Whether to quantize the weight. In some cases, we only want to qunatize scale and zero point.
1021
+ If keep_float_weight is False, quantize the weight, or don't quantize the weight.
1022
+ :return: quantized weight name, zero point name, scale name
1023
+ """
1024
+ # Find if this input is already quantized
1025
+ if weight.name in self.quantized_value_map:
1026
+ quantized_value = self.quantized_value_map[weight.name]
1027
+ return (
1028
+ quantized_value.q_name,
1029
+ quantized_value.zp_name,
1030
+ quantized_value.scale_name,
1031
+ )
1032
+
1033
+ q_weight_name, zp_name, scale_name = self.quantize_initializer_impl(
1034
+ weight, qType, reduce_range, keep_float_weight
1035
+ )
1036
+
1037
+ # Log entry for this quantized weight
1038
+ quantized_value = QuantizedValue(
1039
+ weight.name,
1040
+ q_weight_name,
1041
+ scale_name,
1042
+ zp_name,
1043
+ QuantizedValueType.Initializer,
1044
+ None,
1045
+ )
1046
+ self.quantized_value_map[weight.name] = quantized_value
1047
+ return q_weight_name, zp_name, scale_name
1048
+
1049
+ def quantize_weight_per_channel(
1050
+ self,
1051
+ weight_name,
1052
+ weight_qType,
1053
+ channel_axis,
1054
+ reduce_range=True,
1055
+ keep_float_weight=False,
1056
+ ):
1057
+ # Find if this input is already quantized
1058
+ if weight_name in self.quantized_value_map:
1059
+ quantized_value = self.quantized_value_map[weight_name]
1060
+ return (
1061
+ quantized_value.q_name,
1062
+ quantized_value.zp_name,
1063
+ quantized_value.scale_name,
1064
+ )
1065
+
1066
+ q_weight_name, zp_name, scale_name = self.quantize_weight_per_channel_impl(
1067
+ weight_name, weight_qType, channel_axis, reduce_range, keep_float_weight
1068
+ )
1069
+ quantized_value = QuantizedValue(
1070
+ weight_name,
1071
+ q_weight_name,
1072
+ scale_name,
1073
+ zp_name,
1074
+ QuantizedValueType.Initializer,
1075
+ channel_axis,
1076
+ )
1077
+ self.quantized_value_map[weight_name] = quantized_value
1078
+
1079
+ return q_weight_name, zp_name, scale_name
1080
+
1081
+ def _dequantize_value(self, value_name):
1082
+ """
1083
+ Given a value (input/output) which is quantized, add a DequantizeLinear node to dequantize
1084
+ it back to float32 or float16
1085
+ parameter value_name: value to dequantize
1086
+ parameter new_nodes_list: List of new nodes created before processing current node
1087
+ return: None if there is already a DequantizeLinear node that dequantizes it
1088
+ A DequantizeLinear node otherwise
1089
+ """
1090
+ if (value_name in self.quantized_value_map) and (value_name not in self.generated_value_names):
1091
+ quantized_value = self.quantized_value_map[value_name]
1092
+ # Add DequantizeLinear Node for this input
1093
+
1094
+ scale_init = find_by_name(quantized_value.scale_name, self.model.initializer())
1095
+
1096
+ # In case we are working with subgraphs, the graph `producer_name` is set to `"onnx-quantizer"` in the `quantize_subgraph` method. In this case, the scale initializer may be on the top level graph, so the check below can not be done.
1097
+ if self.model.model.producer_name != "onnx-quantizer" or (
1098
+ self.model.model.producer_name == "onnx-quantizer" and scale_init is not None
1099
+ ):
1100
+ # Per-tensor (axis=None) requires a scalar scale.
1101
+ if quantized_value.axis is None:
1102
+ assert scale_init is None or onnx.numpy_helper.to_array(scale_init).size == 1
1103
+
1104
+ dqlinear_name = value_name + "_DequantizeLinear"
1105
+ dqlinear_node = self.model.find_node_by_name(dqlinear_name, self.new_nodes, self.model.graph())
1106
+ if dqlinear_node is None:
1107
+ dqlinear_inputs = [
1108
+ quantized_value.q_name,
1109
+ quantized_value.scale_name,
1110
+ quantized_value.zp_name,
1111
+ ]
1112
+ dequantize_node = onnx.helper.make_node(
1113
+ "DequantizeLinear",
1114
+ dqlinear_inputs,
1115
+ [value_name],
1116
+ dqlinear_name,
1117
+ axis=quantized_value.axis,
1118
+ )
1119
+ return dequantize_node
1120
+ else:
1121
+ # DQ op is already present, assert it's output matches the input of current node
1122
+ assert value_name == dqlinear_node.output[0]
1123
+ return None
1124
+
1125
+ def _dequantize_outputs(self):
1126
+ """
1127
+ Dequantize output if it is quantized
1128
+ parameter new_nodes_list: List of new nodes created before processing current node
1129
+ return: List of new nodes created
1130
+ """
1131
+
1132
+ for output in self.model.graph().output:
1133
+ dequantize_node = self._dequantize_value(output.name)
1134
+ if dequantize_node is not None:
1135
+ self.new_nodes.append(dequantize_node)
1136
+
1137
+ def calculate_quantization_params(self):
1138
+ if self.tensors_range is None:
1139
+ return None
1140
+
1141
+ self.adjust_tensor_ranges()
1142
+
1143
+ quantization_params = {}
1144
+ for tensor_name in self.tensors_range:
1145
+ td = self.tensors_range[tensor_name]
1146
+ if not isinstance(td, TensorData):
1147
+ raise TypeError(f"Unexpected type {type(td)} for {tensor_name!r}.")
1148
+
1149
+ quant_overrides = self.tensor_quant_overrides.get_per_tensor_overrides(tensor_name, default_val={})
1150
+
1151
+ quant_type = self.activation_qType
1152
+ if "quant_type" in quant_overrides:
1153
+ quant_type = quant_overrides["quant_type"].tensor_type
1154
+
1155
+ if "scale" in quant_overrides and "zero_point" in quant_overrides:
1156
+ zero, scale = quant_overrides["zero_point"], quant_overrides["scale"]
1157
+ elif quant_type == onnx.TensorProto.FLOAT8E4M3FN:
1158
+ zero, scale = compute_scale_zp_float8(quant_type, td.avg_std[1])
1159
+ else:
1160
+ rmin = quant_overrides.get("rmin", td.range_value[0])
1161
+ rmax = quant_overrides.get("rmax", td.range_value[1])
1162
+ symmetric = quant_overrides.get("symmetric", self.is_activation_symmetric)
1163
+ reduce_range = quant_overrides.get("reduce_range", False)
1164
+ qmin, qmax = get_qmin_qmax_for_qType(quant_type, reduce_range=reduce_range, symmetric=symmetric)
1165
+ zero, scale = compute_scale_zp(rmin, rmax, qmin, qmax, symmetric, self.min_real_range)
1166
+ if self.is_activation_restricted_asymmetric and quant_type == onnx.TensorProto.UINT8 and not symmetric:
1167
+ # Forward effective qmin/qmax and min_real_range so reduce_range / MinimumRealRange are honored.
1168
+ zero, scale = snap_zero_point_to_uint8(
1169
+ rmin, rmax, qmin=qmin, qmax=qmax, min_real_range=self.min_real_range
1170
+ )
1171
+
1172
+ quantization_params[tensor_name] = QuantizationParams(zero_point=zero, scale=scale, quant_type=quant_type)
1173
+
1174
+ return quantization_params
ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/quantization/operators/__init__.py ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ # from .base_operator import QuantOperatorBase
2
+ # from .matmul import MatMulInteger
ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/quantization/operators/activation.py ADDED
@@ -0,0 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import onnx
2
+
3
+ from ..quant_utils import TENSOR_NAME_QUANT_SUFFIX, QuantizedValue, QuantizedValueType, attribute_to_kwarg, ms_domain
4
+ from .base_operator import QuantOperatorBase
5
+ from .qdq_base_operator import QDQOperatorBase
6
+
7
+
8
+ class QLinearActivation(QuantOperatorBase):
9
+ def __init__(self, onnx_quantizer, onnx_node):
10
+ super().__init__(onnx_quantizer, onnx_node)
11
+
12
+ def QuantizeClipRelu(self): # noqa: N802
13
+ node = self.node
14
+ assert node.op_type == "Relu" or node.op_type == "Clip"
15
+
16
+ # When mode is QLinearOps, the output quantization params are calculated based on outputs from
17
+ # activation nodes, therefore these nodes can be removed from the graph if they follow a quantized op.
18
+ # If input to this node is not quantized then keep this node
19
+ # If activation is symmetric, not quantize the op and simply return
20
+ if node.input[0] not in self.quantizer.quantized_value_map or self.quantizer.is_activation_symmetric:
21
+ return super().quantize()
22
+
23
+ quantized_value = self.quantizer.quantized_value_map[node.input[0]]
24
+ self.quantizer.quantized_value_map[node.output[0]] = quantized_value
25
+
26
+ def quantize(self):
27
+ node = self.node
28
+ if node.op_type == "Relu" or node.op_type == "Clip":
29
+ self.QuantizeClipRelu()
30
+ return
31
+
32
+ nnapi_sigmoid_option = "extra.Sigmoid.nnapi"
33
+ sigmoid_nnapi_mode = (
34
+ node.op_type == "Sigmoid"
35
+ and nnapi_sigmoid_option in self.quantizer.extra_options
36
+ and self.quantizer.extra_options[nnapi_sigmoid_option]
37
+ )
38
+ use_scale = 1 / 256.0 if sigmoid_nnapi_mode else None
39
+ use_zeropoint = 0 if sigmoid_nnapi_mode else None
40
+
41
+ # No assert on op_type as it is controlled by registry
42
+ # only try to quantize when given quantization parameters for it
43
+ (
44
+ data_found,
45
+ output_scale_name,
46
+ output_zp_name,
47
+ _,
48
+ _,
49
+ ) = self.quantizer._get_quantization_params(node.output[0], use_scale, use_zeropoint)
50
+ (
51
+ quantized_input_names,
52
+ zero_point_names,
53
+ scale_names,
54
+ nodes,
55
+ ) = self.quantizer.quantize_activation(node, [0])
56
+ if not data_found or quantized_input_names is None:
57
+ return super().quantize()
58
+
59
+ qlinear_activation_output = node.output[0] + TENSOR_NAME_QUANT_SUFFIX
60
+ qlinear_activation_name = ""
61
+ if node.name:
62
+ qlinear_activation_name = node.name + "_quant"
63
+ kwargs = {}
64
+ for attribute in node.attribute:
65
+ kwargs.update(attribute_to_kwarg(attribute))
66
+ kwargs["domain"] = ms_domain
67
+
68
+ qlinear_activation_inputs = [
69
+ quantized_input_names[0],
70
+ scale_names[0],
71
+ zero_point_names[0],
72
+ output_scale_name,
73
+ output_zp_name,
74
+ ]
75
+
76
+ qlinear_activation_node = onnx.helper.make_node(
77
+ "QLinear" + node.op_type,
78
+ qlinear_activation_inputs,
79
+ [qlinear_activation_output],
80
+ qlinear_activation_name,
81
+ **kwargs,
82
+ )
83
+
84
+ # Create an entry for this quantized value
85
+ q_output = QuantizedValue(
86
+ node.output[0],
87
+ qlinear_activation_output,
88
+ output_scale_name,
89
+ output_zp_name,
90
+ QuantizedValueType.Input,
91
+ )
92
+ self.quantizer.quantized_value_map[node.output[0]] = q_output
93
+
94
+ nodes.append(qlinear_activation_node)
95
+ self.quantizer.new_nodes += nodes
96
+
97
+
98
+ class QDQRemovableActivation(QDQOperatorBase):
99
+ def __init__(self, onnx_quantizer, onnx_node):
100
+ super().__init__(onnx_quantizer, onnx_node)
101
+
102
+ def quantize(self):
103
+ node = self.node
104
+
105
+ # If input to this node is not quantized then keep this node
106
+ if not self.quantizer.is_tensor_quantized(node.input[0]):
107
+ return
108
+
109
+ if (
110
+ not self.quantizer.is_activation_symmetric
111
+ and not self.quantizer.qdq_keep_removable_activations
112
+ and self.quantizer.try_replacing_upstream_output(node.input[0], node.output[0])
113
+ ):
114
+ self.quantizer.remove_node(self.node)
115
+ else:
116
+ self.quantizer.quantize_activation_tensor(node.input[0])
117
+
118
+ if not self.disable_qdq_for_node_output:
119
+ self.quantizer.quantize_activation_tensor(node.output[0])
ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/quantization/operators/argmax.py ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .base_operator import QuantOperatorBase
2
+
3
+
4
+ # Use the quantized tensor as input without DQ.
5
+ class QArgMax(QuantOperatorBase):
6
+ def __init__(self, onnx_quantizer, onnx_node):
7
+ super().__init__(onnx_quantizer, onnx_node)
8
+
9
+ def quantize(self):
10
+ node = self.node
11
+
12
+ quantized_input_value = self.quantizer.find_quantized_value(node.input[0])
13
+ if quantized_input_value is None:
14
+ self.quantizer.new_nodes += [node]
15
+ return
16
+
17
+ node.input[0] = quantized_input_value.q_name
18
+ self.quantizer.new_nodes += [node]