Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- ScaleDF_rebuttal/python_dedup_pkgs/onnx-1.22.0.dist-info/entry_points.txtAdded+5
- ScaleDF_rebuttal/python_dedup_pkgs/onnx-1.22.0.dist-info/licenses/LICENSEAdded+202
- ScaleDF_rebuttal/python_dedup_pkgs/onnx-1.22.0.dist-info/licenses/NOTICEAdded+59
- ScaleDF_rebuttal/python_dedup_pkgs/onnx-1.22.0.dist-info/sboms/sbom.cdx.jsonAdded+75
- ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/LICENSEAdded+21
- ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/Privacy.mdAdded+21
- ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/ThirdPartyNotices.txtAdded
- ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/__init__.pyAdded+500
- ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/backend/__init__.pyAdded+6
- ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/backend/backend.pyAdded+214
- ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/backend/backend_rep.pyAdded+76
- ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/capi/__init__.pyAdded+4
- ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/capi/_ld_preload.pyAdded+7
- ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/capi/_pybind_state.pyAdded+33
- ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/capi/build_and_package_info.pyAdded+3
- ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/capi/convert_npz_to_onnx_adapter.pyAdded+48
- ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/capi/libonnxruntime_providers_shared.soAdded
- ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/capi/onnxruntime_collect_build_info.pyAdded+47
- ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/capi/onnxruntime_inference_collection.pyAdded+1627
- ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/capi/onnxruntime_validation.pyAdded+154
- ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/datasets/__init__.pyAdded+18
- ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/quantization/CalTableFlatBuffers/KeyValue.pyAdded+78
- ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/quantization/CalTableFlatBuffers/TrtTable.pyAdded+90
- ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/quantization/CalTableFlatBuffers/__init__.pyAdded
- ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/quantization/__init__.pyAdded+24
- ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/quantization/base_quantizer.pyAdded+530
- ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/quantization/calibrate.pyAdded+1353
- ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/quantization/cuda_quantizer.pyAdded+643
- ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/quantization/execution_providers/qnn/__init__.pyAdded+2
- ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/quantization/execution_providers/qnn/fusion_lpnorm.pyAdded+132
- ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/quantization/execution_providers/qnn/fusion_spacetodepth.pyAdded+162
- ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/quantization/execution_providers/qnn/mixed_precision_overrides_utils.pyAdded+413
- ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/quantization/execution_providers/qnn/preprocess.pyAdded+353
- ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/quantization/execution_providers/qnn/quant_config.pyAdded+389
- ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/quantization/fusions/__init__.pyAdded+4
- ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/quantization/fusions/fusion.pyAdded+311
- ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/quantization/fusions/fusion_gelu.pyAdded+272
- ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/quantization/fusions/fusion_layernorm.pyAdded+146
- ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/quantization/fusions/replace_upsample_with_resize.pyAdded+96
- ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/quantization/matmul_bnb4_quantizer.pyAdded+239
- ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/quantization/matmul_nbits_quantizer.pyAdded+1874
- ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/quantization/neural_compressor/__init__.pyAdded+1
- ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/quantization/neural_compressor/onnx_model.pyAdded+1236
- ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/quantization/neural_compressor/util.pyAdded+80
- ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/quantization/neural_compressor/weight_only.pyAdded+932
- ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/quantization/onnx_model.pyAdded+600
- ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/quantization/onnx_quantizer.pyAdded+1174
- ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/quantization/operators/__init__.pyAdded+2
- ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/quantization/operators/activation.pyAdded+119
- ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/quantization/operators/argmax.pyAdded+18
12345[console_scripts]backend-test-tools = onnx.backend.test.cmd_tools:maincheck-model = onnx.bin.checker:check_modelcheck-node = onnx.bin.checker:check_node
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
Apache License Version 2.0, January 2004 http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
(a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859ONNX is licensed under the Apache License, Version 2.0 (see LICENSE).
This product includes software from the following third-party projects, whichare linked into ONNX wheel builds. Their copyright notices are reproduced below.
---
## abseil-cpp
Copyright 2017 The Abseil Authors.
Version: 20250127.0Source: https://github.com/abseil/abseil-cppLicense: Apache-2.0 (see LICENSE)
---
## protobuf
Copyright 2008 Google Inc.
Version: 25.1Source: https://github.com/protocolbuffers/protobufLicense: Apache-2.0 (see LICENSE)
---
## nanobind
Copyright (c) 2022 Wenzel Jakob <wenzel.jakob@epfl.ch>
Version: 2.12.0Source: https://github.com/wjakob/nanobindLicense: BSD-3-Clause
Redistribution and use in source and binary forms, with or withoutmodification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THEIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE AREDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLEFOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIALDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS ORSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVERCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USEOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475{ "$schema": "https://cyclonedx.org/schema/bom-1.7.schema.json", "bomFormat": "CycloneDX", "specVersion": "1.7", "version": 1, "metadata": { "lifecycles": [{"phase": "build"}], "component": { "type": "library", "name": "onnx", "description": "Open Neural Network Exchange — open format for AI/ML models", "purl": "pkg:pypi/onnx", "bom-ref": "onnx" } }, "components": [ { "type": "library", "name": "abseil-cpp", "version": "20250127.0", "bom-ref": "abseil-cpp", "purl": "pkg:github/abseil/abseil-cpp@v20250127.0", "externalReferences": [ { "type": "distribution", "url": "https://github.com/abseil/abseil-cpp/releases/download/20250127.0/abseil-cpp-20250127.0.tar.gz" } ], "hashes": [ {"alg": "SHA-256", "content": "16242f394245627e508ec6bb296b433c90f8d914f73b9c026fddb905e27276e8"} ], "licenses": [{"license": {"id": "Apache-2.0"}}] }, { "type": "library", "name": "protobuf", "version": "25.1", "bom-ref": "protobuf", "purl": "pkg:github/protocolbuffers/protobuf@v25.1", "externalReferences": [ { "type": "distribution", "url": "https://github.com/protocolbuffers/protobuf/releases/download/v25.1/protobuf-25.1.tar.gz" } ], "hashes": [ {"alg": "SHA-256", "content": "9bd87b8280ef720d3240514f884e56a712f2218f0d693b48050c836028940a42"} ], "licenses": [{"license": {"id": "BSD-3-Clause"}}] }, { "type": "library", "name": "nanobind", "version": "2.12.0", "bom-ref": "nanobind", "purl": "pkg:github/wjakob/nanobind@v2.12.0", "externalReferences": [ { "type": "vcs", "url": "https://github.com/wjakob/nanobind.git" } ], "licenses": [{"license": {"id": "BSD-3-Clause"}}] } ], "dependencies": [ { "ref": "onnx", "dependsOn": ["abseil-cpp", "protobuf", "nanobind"] }, {"ref": "abseil-cpp"}, {"ref": "protobuf"}, {"ref": "nanobind"} ]}123456789101112131415161718192021MIT License
Copyright (c) Microsoft Corporation
Permission is hereby granted, free of charge, to any person obtaining a copyof this software and associated documentation files (the "Software"), to dealin the Software without restriction, including without limitation the rightsto use, copy, modify, merge, publish, distribute, sublicense, and/or sellcopies of the Software, and to permit persons to whom the Software isfurnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in allcopies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS ORIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THEAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHERLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THESOFTWARE.123456789101112131415161718192021# Privacy
## Data CollectionThe 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.
***
### Private BuildsNo data collection is performed when using your private builds built from source code.
### Official BuildsONNX 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.
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)).
#### Technical DetailsThe 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.
Windows ML and onnxruntime C APIs allow Trace Logging to be turned on/off (see [API pages](../README.md#api-documentation) for details).For information on how to enable and disable telemetry, see [C API: Telemetry](./C_API.md#telemetry). There are equivalent APIs in the C#, Python, and Java language bindings as well.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500# -------------------------------------------------------------------------# Copyright (c) Microsoft Corporation. All rights reserved.# Licensed under the MIT License.# --------------------------------------------------------------------------"""ONNX Runtime is a performance-focused scoring engine for Open Neural Network Exchange (ONNX) models.For more information on ONNX Runtime, please see `aka.ms/onnxruntime <https://aka.ms/onnxruntime/>`_or the `Github project <https://github.com/microsoft/onnxruntime/>`_."""
import contextlib
__version__ = "1.28.0"__author__ = "Microsoft"
# we need to do device version validation (for example to check Cuda version for an onnxruntime-training package).# in order to know whether the onnxruntime package is for training it needs# to do import onnxruntime.training.ortmodule first.# onnxruntime.capi._pybind_state is required before import onnxruntime.training.ortmodule.# however, import onnxruntime.capi._pybind_state will already raise an exception if a required Cuda version# is not found.# here we need to save the exception and continue with Cuda version validation in order to post# meaningful messages to the user.# the saved exception is raised after device version validation.try: from onnxruntime.capi._pybind_state import ( ExecutionMode, # noqa: F401 ExecutionOrder, # noqa: F401 GraphOptimizationLevel, # noqa: F401 LoraAdapter, # noqa: F401 ModelMetadata, # noqa: F401 NodeArg, # noqa: F401 OrtAllocatorType, # noqa: F401 OrtArenaCfg, # noqa: F401 OrtCompileApiFlags, # noqa: F401 OrtDeviceMemoryType, # noqa: F401 OrtEpAssignedNode, # noqa: F401 OrtEpAssignedSubgraph, # noqa: F401 OrtEpDevice, # noqa: F401 OrtExecutionProviderDevicePolicy, # noqa: F401 OrtExternalInitializerInfo, # noqa: F401 OrtHardwareDevice, # noqa: F401 OrtHardwareDeviceType, # noqa: F401 OrtMemoryInfo, # noqa: F401 OrtMemoryInfoDeviceType, # noqa: F401 OrtMemType, # noqa: F401 OrtSparseFormat, # noqa: F401 OrtSyncStream, # noqa: F401 RunOptions, # noqa: F401 SessionIOBinding, # noqa: F401 SessionOptions, # noqa: F401 create_and_register_allocator, # noqa: F401 create_and_register_allocator_v2, # noqa: F401 disable_telemetry_events, # noqa: F401 enable_telemetry_events, # noqa: F401 get_all_providers, # noqa: F401 get_available_providers, # noqa: F401 get_build_info, get_device, # noqa: F401 get_ep_devices, # noqa: F401 get_version_string, # noqa: F401 has_collective_ops, # noqa: F401 register_execution_provider_library, set_default_logger_severity, # noqa: F401 set_default_logger_verbosity, # noqa: F401 set_global_thread_pool_sizes, # noqa: F401 set_seed, # noqa: F401 unregister_execution_provider_library, # noqa: F401 )
import_capi_exception = Noneexcept Exception as e: import_capi_exception = e
from onnxruntime.capi import onnxruntime_validation
if import_capi_exception: raise import_capi_exception
from onnxruntime.capi.onnxruntime_inference_collection import ( AdapterFormat, # noqa: F401 InferenceSession, # noqa: F401 IOBinding, # noqa: F401 ModelCompiler, # noqa: F401 OrtDevice, # noqa: F401 OrtDeviceVendorId, # noqa: F401 OrtValue, # noqa: F401 SparseTensor, # noqa: F401 copy_tensors, # noqa: F401)
# TODO: thiagofc: Temporary experimental namespace for new PyTorch front-endtry: # noqa: SIM105 from . import experimental # noqa: F401except ImportError: pass
package_name, version, cuda_version = onnxruntime_validation.get_package_name_and_version_info()
if version: __version__ = version
onnxruntime_validation.check_distro_info()
def _get_cuda_plugin_ep_library_path() -> str | None: import os # noqa: PLC0415 import sys # noqa: PLC0415
if ", cuda-plugin-ep=" not in get_build_info(): return None
if sys.platform == "win32": library_name = "onnxruntime_providers_cuda.dll" elif sys.platform == "darwin": library_name = "libonnxruntime_providers_cuda.dylib" else: library_name = "libonnxruntime_providers_cuda.so"
library_path = os.path.join(os.path.dirname(__file__), "capi", library_name) return library_path if os.path.isfile(library_path) else None
def _register_bundled_cuda_plugin_ep(warn_on_failure: bool = False): library_path = _get_cuda_plugin_ep_library_path() if not library_path: return
try: register_execution_provider_library("CUDAExecutionProvider", library_path) except Exception as e: if "already registered" not in str(e).lower(): if warn_on_failure: import warnings # noqa: PLC0415
warnings.warn(f"Failed to register bundled CUDA plugin EP from {library_path}: {e}")
_register_bundled_cuda_plugin_ep(warn_on_failure=True)
def _get_package_version(package_name: str): from importlib.metadata import PackageNotFoundError, version # noqa: PLC0415
try: package_version = version(package_name) except PackageNotFoundError: package_version = None return package_version
def _get_package_root(package_name: str, directory_name: str | None = None): from importlib.metadata import PackageNotFoundError, distribution # noqa: PLC0415
root_directory_name = directory_name or package_name try: dist = distribution(package_name) files = dist.files or []
for file in files: if file.name.endswith("__init__.py") and root_directory_name in file.parts: return file.locate().parent
# Fallback to the first __init__.py if not directory_name: for file in files: if file.name.endswith("__init__.py"): return file.locate().parent except PackageNotFoundError: # package not found, do nothing pass
return None
def _extract_cuda_major_version(version_str: str) -> str: """Extract CUDA major version from version string (e.g., '12.1' -> '12').
Args: version_str: CUDA version string to parse
Returns: Major version as string, or "12" if parsing fails """ return version_str.split(".", maxsplit=1)[0] if version_str else "12"
def _get_cufft_version(cuda_major_version: str) -> str: """Get cufft library version based on CUDA major version.
Args: cuda_major_version: CUDA major version as string (e.g., "12", "13")
Returns: cufft version as string """ # cufft versions: CUDA 12.x -> 11, CUDA 13.x -> 12 return "12" if int(cuda_major_version) >= 13 else "11"
def _get_nvidia_dll_paths(is_windows: bool, cuda: bool = True, cudnn: bool = True): # Dynamically determine CUDA major version from build info. # build_cuda_version defaults to the version this package was built with; it is a parameter for testability. cuda_major_version = _extract_cuda_major_version(cuda_version) cufft_version = _get_cufft_version(cuda_major_version)
# Starting with CUDA 13, NVIDIA consolidated the per-component CUDA Toolkit wheels # (cublas, cufft, cuda_runtime, cuda_nvrtc, curand, ...) into a single "nvidia/cu{major}" # package and dropped the "-cuNN" suffix from those package names. On Windows the DLLs # moved into an architecture sub-folder ("bin/<arch>", e.g. "bin/x86_64"); on Linux the # libraries are placed directly in "lib" (the wheel itself is architecture specific, so # there is no arch sub-folder). cuDNN keeps its own "nvidia/cudnn" package and layout. use_consolidated_layout = cuda_major_version.isdigit() and int(cuda_major_version) >= 13
if use_consolidated_layout: cuda_dir = f"cu{cuda_major_version}" if is_windows: import platform # noqa: PLC0415
arch = "arm64" if platform.machine().lower() in ("arm64", "aarch64") else "x86_64" cuda_dll_paths = [ ("nvidia", cuda_dir, "bin", arch, f"cublasLt64_{cuda_major_version}.dll"), ("nvidia", cuda_dir, "bin", arch, f"cublas64_{cuda_major_version}.dll"), ("nvidia", cuda_dir, "bin", arch, f"cufft64_{cufft_version}.dll"), ("nvidia", cuda_dir, "bin", arch, f"cudart64_{cuda_major_version}.dll"), ] else: # Linux # cublas64 depends on cublasLt64, so cublasLt64 should be loaded first. cuda_dll_paths = [ ("nvidia", cuda_dir, "lib", f"libcublasLt.so.{cuda_major_version}"), ("nvidia", cuda_dir, "lib", f"libcublas.so.{cuda_major_version}"), ("nvidia", cuda_dir, "lib", f"libnvrtc.so.{cuda_major_version}"), ("nvidia", cuda_dir, "lib", "libcurand.so.10"), ("nvidia", cuda_dir, "lib", f"libcufft.so.{cufft_version}"), ("nvidia", cuda_dir, "lib", f"libcudart.so.{cuda_major_version}"), ] elif is_windows: # CUDA 12 and earlier: each component ships its own "nvidia/<component>" package. # Path is relative to site-packages directory. cuda_dll_paths = [ ("nvidia", "cublas", "bin", f"cublasLt64_{cuda_major_version}.dll"), ("nvidia", "cublas", "bin", f"cublas64_{cuda_major_version}.dll"), ("nvidia", "cufft", "bin", f"cufft64_{cufft_version}.dll"), ("nvidia", "cuda_runtime", "bin", f"cudart64_{cuda_major_version}.dll"), ] else: # Linux # cublas64 depends on cublasLt64, so cublasLt64 should be loaded first. cuda_dll_paths = [ ("nvidia", "cublas", "lib", f"libcublasLt.so.{cuda_major_version}"), ("nvidia", "cublas", "lib", f"libcublas.so.{cuda_major_version}"), ("nvidia", "cuda_nvrtc", "lib", f"libnvrtc.so.{cuda_major_version}"), ("nvidia", "curand", "lib", "libcurand.so.10"), ("nvidia", "cufft", "lib", f"libcufft.so.{cufft_version}"), ("nvidia", "cuda_runtime", "lib", f"libcudart.so.{cuda_major_version}"), ]
# cuDNN keeps its own "nvidia/cudnn" package layout in both old and consolidated schemes. if is_windows: cudnn_dll_paths = [ ("nvidia", "cudnn", "bin", "cudnn_engines_runtime_compiled64_9.dll"), ("nvidia", "cudnn", "bin", "cudnn_engines_precompiled64_9.dll"), ("nvidia", "cudnn", "bin", "cudnn_heuristic64_9.dll"), ("nvidia", "cudnn", "bin", "cudnn_ops64_9.dll"), ("nvidia", "cudnn", "bin", "cudnn_adv64_9.dll"), ("nvidia", "cudnn", "bin", "cudnn_graph64_9.dll"), ("nvidia", "cudnn", "bin", "cudnn64_9.dll"), ("nvidia", "cudnn", "bin", "cudnn_engines_tensor_ir64_9.dll"), ] else: # Linux # Do not load cudnn sub DLLs (they will be dynamically loaded later) to be consistent with PyTorch in Linux. cudnn_dll_paths = [ ("nvidia", "cudnn", "lib", "libcudnn.so.9"), ]
return (cuda_dll_paths if cuda else []) + (cudnn_dll_paths if cudnn else [])
def print_debug_info(): """Print information to help debugging.""" import importlib.util # noqa: PLC0415 import os # noqa: PLC0415 import platform # noqa: PLC0415 from importlib.metadata import distributions # noqa: PLC0415
print(f"{package_name} version: {__version__}") if cuda_version: print(f"CUDA version used in build: {cuda_version}") print("platform:", platform.platform())
print("\nPython package, version and location:") ort_packages = [] for dist in distributions(): package = dist.metadata["Name"] if package == "onnxruntime" or package.startswith(("onnxruntime-", "ort-")): # Exclude packages whose root directory name is not onnxruntime. location = _get_package_root(package, "onnxruntime") if location and (package not in ort_packages): ort_packages.append(package) print(f"{package}=={dist.version} at {location}")
if len(ort_packages) > 1: print( "\033[33mWARNING: multiple onnxruntime packages are installed to the same location. " "Please 'pip uninstall` all above packages, then `pip install` only one of them.\033[0m" )
if cuda_version: # Print version of installed packages that is related to CUDA or cuDNN DLLs. cuda_major = _extract_cuda_major_version(cuda_version)
# Starting with CUDA 13, NVIDIA dropped the "-cuNN" suffix from the per-component # CUDA Toolkit packages (cuDNN keeps its suffixed package name). cuda_pkg_suffix = "" if (cuda_major.isdigit() and int(cuda_major) >= 13) else f"-cu{cuda_major}"
packages = [ "torch", f"nvidia-cuda-runtime{cuda_pkg_suffix}", f"nvidia-cudnn-cu{cuda_major}", f"nvidia-cublas{cuda_pkg_suffix}", f"nvidia-cufft{cuda_pkg_suffix}", f"nvidia-curand{cuda_pkg_suffix}", f"nvidia-cuda-nvrtc{cuda_pkg_suffix}", f"nvidia-nvjitlink{cuda_pkg_suffix}", ] for package in packages: directory_name = "nvidia" if package.startswith("nvidia-") else None version = _get_package_version(package) if version: print(f"{package}=={version} at {_get_package_root(package, directory_name)}") else: print(f"{package} not installed")
if platform.system() == "Windows": print(f"\nEnvironment variable:\nPATH={os.environ.get('PATH', '(unset)')}") elif platform.system() == "Linux": print(f"\nEnvironment variable:\nLD_LIBRARY_PATH={os.environ.get('LD_LIBRARY_PATH', '(unset)')}")
if importlib.util.find_spec("psutil"):
def is_target_dll(path: str): target_keywords = ["vcruntime140", "msvcp140"] if cuda_version: target_keywords = ["cufft", "cublas", "cudart", "nvrtc", "curand", "cudnn", *target_keywords] return any(keyword in path for keyword in target_keywords)
import psutil # noqa: PLC0415
p = psutil.Process(os.getpid())
print("\nList of loaded DLLs:") for lib in p.memory_maps(): if is_target_dll(lib.path.lower()): print(lib.path)
if cuda_version: if importlib.util.find_spec("cpuinfo") and importlib.util.find_spec("py3nvml"): from .transformers.machine_info import get_device_info # noqa: PLC0415
print("\nDevice information:") print(get_device_info()) else: print("please `pip install py-cpuinfo py3nvml` to show device information.") else: print("please `pip install psutil` to show loaded DLLs.")
def preload_dlls(cuda: bool = True, cudnn: bool = True, msvc: bool = True, directory=None): """Preload CUDA 12.x+ and optional cuDNN 9.x DLLs in Windows or Linux, and MSVC runtime DLLs in Windows.
When the installed PyTorch is compatible (using same major version of CUDA and cuDNN), there is no need to call this function if `import torch` is done before `import onnxruntime`.
Args: cuda (bool, optional): enable loading CUDA DLLs. Defaults to True. cudnn (bool, optional): enable loading cuDNN DLLs. Defaults to True. Missing cuDNN DLLs are ignored. msvc (bool, optional): enable loading MSVC DLLs in Windows. Defaults to True. directory(str, optional): a directory contains CUDA or cuDNN DLLs. It can be an absolute path, or a path relative to the directory of this file. If directory is None (default value), the search order: the lib directory of compatible PyTorch in Windows, nvidia site packages, default DLL loading paths. If directory is empty string (""), the search order: nvidia site packages, default DLL loading paths. If directory is a path, the search order: the directory, default DLL loading paths. """ import ctypes # noqa: PLC0415 import os # noqa: PLC0415 import platform # noqa: PLC0415 import sys # noqa: PLC0415
if platform.system() not in ["Windows", "Linux"]: return
is_windows = platform.system() == "Windows" if is_windows and msvc: try: ctypes.CDLL("vcruntime140.dll") ctypes.CDLL("msvcp140.dll") if platform.machine() != "ARM64": ctypes.CDLL("vcruntime140_1.dll") except OSError: print("Microsoft Visual C++ Redistributable is not installed, this may lead to the DLL load failure.") print("It can be downloaded at https://aka.ms/vs/17/release/vc_redist.x64.exe.")
# Check if CUDA version is supported (12.x or 13.x+) ort_cuda_major = None if cuda_version: try: ort_cuda_major = int(cuda_version.split(".")[0]) if ort_cuda_major < 12 and (cuda or cudnn): print( f"\033[33mWARNING: {package_name} is built with CUDA {cuda_version}, which is not supported for preloading. " f"CUDA 12.x or newer is required. Call preload_dlls with cuda=False and cudnn=False.\033[0m" ) return except ValueError: print( f"\033[33mWARNING: Unable to parse CUDA version '{cuda_version}'. " "Skipping DLL preloading. Call preload_dlls with cuda=False and cudnn=False.\033[0m" ) return elif cuda or cudnn: # No CUDA version info available but CUDA/cuDNN preloading requested return
is_cuda_cudnn_imported_by_torch = False
if is_windows: torch_version = _get_package_version("torch") # Check if torch CUDA version matches onnxruntime CUDA version torch_cuda_major = None if torch_version and "+cu" in torch_version: with contextlib.suppress(ValueError): # Extract CUDA version from torch (e.g., "2.0.0+cu121" -> 12) cu_part = torch_version.split("+cu")[1] torch_cuda_major = int(cu_part[:2]) # First 2 digits are major version
is_torch_cuda_compatible = ( torch_cuda_major == ort_cuda_major if (torch_cuda_major and ort_cuda_major) else False )
if "torch" in sys.modules: is_cuda_cudnn_imported_by_torch = is_torch_cuda_compatible if torch_cuda_major and ort_cuda_major and torch_cuda_major != ort_cuda_major: print( f"\033[33mWARNING: The installed PyTorch {torch_version} uses CUDA {torch_cuda_major}.x, " f"but {package_name} is built with CUDA {ort_cuda_major}.x. " f"Please install PyTorch for CUDA {ort_cuda_major}.x to be compatible.\033[0m" )
if is_torch_cuda_compatible and directory is None: torch_root = _get_package_root("torch", "torch") if torch_root: directory = os.path.join(torch_root, "lib")
base_directory = directory or ".." if not os.path.isabs(base_directory): base_directory = os.path.join(os.path.dirname(__file__), base_directory) base_directory = os.path.normpath(base_directory) if not os.path.isdir(base_directory): raise RuntimeError(f"Invalid parameter of directory={directory}. The directory does not exist!")
if is_cuda_cudnn_imported_by_torch: # In Windows, PyTorch has loaded CUDA and cuDNN DLLs during `import torch`, no need to load them again. print("Skip loading CUDA and cuDNN DLLs since torch is imported.") return
# Try load DLLs from nvidia site packages. dll_paths = _get_nvidia_dll_paths(is_windows, cuda, cudnn) optional_dll_filenames = {relative_path[-1] for relative_path in _get_nvidia_dll_paths(is_windows, False, cudnn)} loaded_dlls = [] for relative_path in dll_paths: dll_path = ( os.path.join(base_directory, relative_path[-1]) if directory else os.path.join(base_directory, *relative_path) ) if os.path.isfile(dll_path): try: _ = ctypes.CDLL(dll_path) loaded_dlls.append(relative_path[-1]) except Exception as e: if relative_path[-1] not in optional_dll_filenames: print(f"Failed to load {dll_path}: {e}")
# Try load DLLs with default path settings. has_failure = False for relative_path in dll_paths: dll_filename = relative_path[-1] if dll_filename not in loaded_dlls: try: _ = ctypes.CDLL(dll_filename) except Exception as e: if dll_filename not in optional_dll_filenames: has_failure = True print(f"Failed to load {dll_filename}: {e}")
if has_failure: print("Please follow https://onnxruntime.ai/docs/install/#cuda-and-cudnn to install CUDA.")
_register_bundled_cuda_plugin_ep(warn_on_failure=True)123456# -------------------------------------------------------------------------# Copyright (c) Microsoft Corporation. All rights reserved.# Licensed under the MIT License.# --------------------------------------------------------------------------
from .backend import is_compatible, prepare, run, supports_device # noqa: F401123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214# -------------------------------------------------------------------------# Copyright (c) Microsoft Corporation. All rights reserved.# Licensed under the MIT License.# --------------------------------------------------------------------------"""Implements ONNX's backend API."""
import osimport unittest
import packaging.versionfrom onnx import ModelProto, helper, version # noqa: F401from onnx.backend.base import Backendfrom onnx.checker import check_model
from onnxruntime import InferenceSession, SessionOptions, get_available_providers, get_devicefrom onnxruntime.backend.backend_rep import OnnxRuntimeBackendRep
# Allowlist of SessionOptions attributes that are safe to set via the backend API.# Dangerous attributes intentionally excluded:# optimized_model_filepath — triggers Model::Save(), overwrites arbitrary files# profile_file_prefix — writes profiling JSON to arbitrary path# enable_profiling — causes uncontrolled file writes to cwd_ALLOWED_SESSION_OPTIONS = frozenset( { "enable_cpu_mem_arena", "enable_mem_pattern", "enable_mem_reuse", "execution_mode", "execution_order", "graph_optimization_level", "inter_op_num_threads", "intra_op_num_threads", "log_severity_level", "log_verbosity_level", "logid", "use_deterministic_compute", "use_per_session_threads", })
class OnnxRuntimeBackend(Backend): """ Implements `ONNX's backend API <https://github.com/onnx/onnx/blob/main/docs/ImplementingAnOnnxBackend.md>`_ with *ONNX Runtime*. The backend is mostly used when you need to switch between multiple runtimes with the same API. `Importing models from ONNX to Caffe2 <https://github.com/onnx/tutorials/blob/master/tutorials/OnnxCaffe2Import.ipynb>`_ shows how to use *caffe2* as a backend for a converted model. Note: This is not the official Python API. """
allowReleasedOpsetsOnly = bool(os.getenv("ALLOW_RELEASED_ONNX_OPSET_ONLY", "1") == "1") # noqa: N815
@classmethod def is_compatible(cls, model, device=None, **kwargs): """ Return whether the model is compatible with the backend.
:param model: unused :param device: None to use the default device or a string (ex: `'CPU'`) :return: boolean """ if device is None: device = get_device() return cls.supports_device(device)
@classmethod def is_opset_supported(cls, model): """ Return whether the opset for the model is supported by the backend. When By default only released onnx opsets are allowed by the backend To test new opsets env variable ALLOW_RELEASED_ONNX_OPSET_ONLY should be set to 0
:param model: Model whose opsets needed to be verified. :return: boolean and error message if opset is not supported. """ if cls.allowReleasedOpsetsOnly: for opset in model.opset_import: domain = opset.domain if opset.domain else "ai.onnx" try: key = (domain, opset.version) if key not in helper.OP_SET_ID_VERSION_MAP: error_message = ( "Skipping this test as only released onnx opsets are supported." "To run this test set env variable ALLOW_RELEASED_ONNX_OPSET_ONLY to 0." f" Got Domain '{domain}' version '{opset.version}'." ) return False, error_message except AttributeError: # for some CI pipelines accessing helper.OP_SET_ID_VERSION_MAP # is generating attribute error. TODO investigate the pipelines to # fix this error. Falling back to a simple version check when this error is encountered if (domain == "ai.onnx" and opset.version > 12) or (domain == "ai.ommx.ml" and opset.version > 2): error_message = ( "Skipping this test as only released onnx opsets are supported." "To run this test set env variable ALLOW_RELEASED_ONNX_OPSET_ONLY to 0." f" Got Domain '{domain}' version '{opset.version}'." ) return False, error_message return True, ""
@classmethod def supports_device(cls, device): """ Check whether the backend is compiled with particular device support. In particular it's used in the testing suite. """ if device == "CUDA": device = "GPU" return "-" + device in get_device() or device + "-" in get_device() or device == get_device()
@classmethod def prepare(cls, model, device=None, **kwargs): """ Load the model and creates an :class:`onnxruntime.backend.backend_rep.OnnxRuntimeBackendRep` ready to be used as a backend.
:param model: the model to prepare — accepts a file path (str), serialized model (bytes), :class:`onnx.ModelProto`, :class:`onnxruntime.InferenceSession`, or :class:`onnxruntime.backend.backend_rep.OnnxRuntimeBackendRep` (returned as-is) :param device: requested device for the computation, None means the default one which depends on the compilation settings :param kwargs: only a safe subset of :class:`onnxruntime.SessionOptions` attributes are accepted; see ``_ALLOWED_SESSION_OPTIONS`` for the list :return: :class:`onnxruntime.backend.backend_rep.OnnxRuntimeBackendRep` """ if isinstance(model, OnnxRuntimeBackendRep): return model elif isinstance(model, InferenceSession): return OnnxRuntimeBackendRep(model) elif isinstance(model, (str, bytes)): options = SessionOptions() for k, v in kwargs.items(): if k in _ALLOWED_SESSION_OPTIONS: setattr(options, k, v) elif hasattr(options, k): raise RuntimeError( f"SessionOptions attribute '{k}' is not permitted via the backend API. " f"Allowed attributes: {', '.join(sorted(_ALLOWED_SESSION_OPTIONS))}" ) # else: silently ignore unknown keys
excluded_providers = os.getenv("ORT_ONNX_BACKEND_EXCLUDE_PROVIDERS", default="").split(",") providers = [x for x in get_available_providers() if (x not in excluded_providers)]
inf = InferenceSession(model, sess_options=options, providers=providers) # backend API is primarily used for ONNX test/validation. As such, we should disable session.run() fallback # which may hide test failures. inf.disable_fallback() if device is not None and not cls.supports_device(device): raise RuntimeError(f"Incompatible device expected '{device}', got '{get_device()}'") return cls.prepare(inf, device, **kwargs) else: # type: ModelProto # check_model serializes the model anyways, so serialize the model once here # and reuse it below in the cls.prepare call to avoid an additional serialization # only works with onnx >= 1.10.0 hence the version check onnx_version = packaging.version.parse(version.version) or packaging.version.Version("0") onnx_supports_serialized_model_check = onnx_version.release >= (1, 10, 0) bin_or_model = model.SerializeToString() if onnx_supports_serialized_model_check else model check_model(bin_or_model) opset_supported, error_message = cls.is_opset_supported(model) if not opset_supported: raise unittest.SkipTest(error_message) # Now bin might be serialized, if it's not we need to serialize it otherwise we'll have # an infinite recursive call bin = bin_or_model if not isinstance(bin, (str, bytes)): bin = bin.SerializeToString() return cls.prepare(bin, device, **kwargs)
@classmethod def run_model(cls, model, inputs, device=None, **kwargs): """ Compute the prediction.
:param model: the model to run — accepts a file path (str), serialized model (bytes), :class:`onnx.ModelProto`, :class:`onnxruntime.InferenceSession`, or :class:`onnxruntime.backend.backend_rep.OnnxRuntimeBackendRep` :param inputs: inputs :param device: requested device for the computation, None means the default one which depends on the compilation settings :param kwargs: ``run_model()`` forwards kwargs to both ``prepare()`` and ``rep.run()``. ``prepare()`` validates and applies ``_ALLOWED_SESSION_OPTIONS`` only when creating a new session from a model path or bytes; if ``model`` is already an ``InferenceSession`` or ``OnnxRuntimeBackendRep``, session-option kwargs are silently ignored. ``rep.run()`` always validates against ``_ALLOWED_RUN_OPTIONS`` and raises ``RuntimeError`` for known-but-blocked run attributes. Logging-related kwargs (``log_severity_level``, ``log_verbosity_level``, ``logid``) appear in both allowlists. :return: predictions """ rep = cls.prepare(model, device, **kwargs) return rep.run(inputs, **kwargs)
@classmethod def run_node(cls, node, inputs, device=None, outputs_info=None, **kwargs): """ This method is not implemented as it is much more efficient to run a whole model than every node independently. """ raise NotImplementedError("It is much more efficient to run a whole model than every node independently.")
is_compatible = OnnxRuntimeBackend.is_compatibleprepare = OnnxRuntimeBackend.preparerun = OnnxRuntimeBackend.run_modelsupports_device = OnnxRuntimeBackend.supports_device12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576# -------------------------------------------------------------------------# Copyright (c) Microsoft Corporation. All rights reserved.# Licensed under the MIT License.# --------------------------------------------------------------------------"""Implements ONNX's backend API."""
from onnx.backend.base import BackendRep
from onnxruntime import RunOptions
# Allowlist of RunOptions attributes that are safe to set via the backend API.# 'terminate' excluded: setting it True would deny the current inference call.# 'training_mode' excluded: silently switches inference behavior in training builds._ALLOWED_RUN_OPTIONS = frozenset( { "log_severity_level", "log_verbosity_level", "logid", "only_execute_path_to_fetches", })
class OnnxRuntimeBackendRep(BackendRep): """ Wraps an :class:`onnxruntime.InferenceSession` to implement ONNX's :class:`onnx.backend.base.BackendRep` interface for running predictions. """
def __init__(self, session): """ :param session: :class:`onnxruntime.InferenceSession` """ self._session = session
def run(self, inputs, **kwargs): # type: (Any, **Any) -> Tuple[Any, ...] """ Computes the prediction. See :meth:`onnxruntime.InferenceSession.run`.
:param inputs: a list of input arrays (one per model input) or a single array when the model has exactly one input :param kwargs: only a safe subset of :class:`onnxruntime.RunOptions` attributes are accepted; see ``_ALLOWED_RUN_OPTIONS`` for the list :return: list of output arrays """
options = RunOptions() for k, v in kwargs.items(): if k in _ALLOWED_RUN_OPTIONS: setattr(options, k, v) elif hasattr(options, k): raise RuntimeError( f"RunOptions attribute '{k}' is not permitted via the backend API. " f"Allowed attributes: {', '.join(sorted(_ALLOWED_RUN_OPTIONS))}" ) # else: silently ignore unknown keys
if isinstance(inputs, list): inps = {} for i, inp in enumerate(self._session.get_inputs()): inps[inp.name] = inputs[i] outs = self._session.run(None, inps, options) if isinstance(outs, list): return outs else: output_names = [o.name for o in self._session.get_outputs()] return [outs[name] for name in output_names] else: inp = self._session.get_inputs() if len(inp) != 1: raise RuntimeError(f"Model expect {len(inp)} inputs") inps = {inp[0].name: inputs} return self._session.run(None, inps, options)1234# -------------------------------------------------------------------------# Copyright (c) Microsoft Corporation. All rights reserved.# Licensed under the MIT License.# --------------------------------------------------------------------------1234567# -------------------------------------------------------------------------# Copyright (c) Microsoft Corporation. All rights reserved.# Licensed under the MIT License.# --------------------------------------------------------------------------
# This file can be modified by setup.py when building a manylinux2010 wheel# When modified, it will preload some libraries needed for the python C extension123456789101112131415161718192021222324252627282930313233# -------------------------------------------------------------------------# Copyright (c) Microsoft Corporation. All rights reserved.# Licensed under the MIT License.# --------------------------------------------------------------------------"""Ensure that dependencies are available and then load the extension module."""import osimport platformimport warnings
from . import _ld_preload # noqa: F401
if platform.system() == "Windows": from . import version_info
# If on Windows, check if this import error is caused by the user not installing the 2019 VC Runtime # The VC Redist installer usually puts the VC Runtime dlls in the System32 folder, but it may also be found # in some other locations. # TODO, we may want to try to load the VC Runtime dlls instead of checking if the hardcoded file path # is valid, and raise ImportError if the load fails if version_info.vs2019 and platform.architecture()[0] == "64bit": system_root = os.getenv("SystemRoot") or "C:\\Windows" if not os.path.isfile(os.path.join(system_root, "System32", "vcruntime140_1.dll")): warnings.warn("Please install the 2019 Visual C++ runtime and then try again. " "If you've installed the runtime in a non-standard location " "(other than %SystemRoot%\\System32), " "make sure it can be found by setting the correct path.")
from .onnxruntime_pybind11_state import * # noqa
123package_name = 'onnxruntime-gpu'__version__ = '1.28.0'cuda_version = '13.0'123456789101112131415161718192021222324252627282930313233343536373839404142434445464748# Copyright (c) Microsoft Corporation. All rights reserved.# Licensed under the MIT License.
# This script helps converting .npz files to .onnx_adapter files
import argparseimport osimport sys
import numpy as np
import onnxruntime as ort
def get_args() -> argparse: parser = argparse.ArgumentParser() parser.add_argument("--npz_file_path", type=str, required=True) parser.add_argument("--output_file_path", type=str, required=True) parser.add_argument("--adapter_version", type=int, required=True) parser.add_argument("--model_version", type=int, required=True) return parser.parse_args()
def export_lora_parameters( npz_file_path: os.PathLike, adapter_version: int, model_version: int, output_file_path: os.PathLike): """The function converts lora parameters in npz to onnx_adapter format""" adapter_format = ort.AdapterFormat() adapter_format.set_adapter_version(adapter_version) adapter_format.set_model_version(model_version) name_to_ort_value = {} with np.load(npz_file_path) as data: for name, np_arr in data.items(): ort_value = ort.OrtValue.ortvalue_from_numpy(np_arr) name_to_ort_value[name] = ort_value
adapter_format.set_parameters(name_to_ort_value) adapter_format.export_adapter(output_file_path)
def main() -> int: args = get_args() export_lora_parameters(args.npz_file_path, args.adapter_version, args.model_version, args.output_file_path) return 0
if __name__ == "__main__": sys.exit(main())1234567891011121314151617181920212223242526272829303132333435363738394041424344454647# -------------------------------------------------------------------------# Copyright (c) Microsoft Corporation. All rights reserved.# Licensed under the MIT License.# --------------------------------------------------------------------------import ctypesimport sysimport warnings
def find_cudart_versions(build_env=False, build_cuda_version=None): # ctypes.CDLL and ctypes.util.find_library load the latest installed library. # it may not the the library that would be loaded by onnxruntime. # for example, in an environment with Cuda 11.1 and subsequently # conda cudatoolkit 10.2.89 installed. ctypes will find cudart 10.2. however, # onnxruntime built with Cuda 11.1 will find and load cudart for Cuda 11.1. # for the above reason, we need find all versions in the environment and # only give warnings if the expected cuda version is not found. # in onnxruntime build environment, we expected only one Cuda version. if not sys.platform.startswith("linux"): warnings.warn("find_cudart_versions only works on Linux") return None
cudart_possible_versions = {None, build_cuda_version}
def get_cudart_version(find_cudart_version=None): cudart_lib_filename = "libcudart.so" if find_cudart_version: cudart_lib_filename = cudart_lib_filename + "." + find_cudart_version
try: cudart = ctypes.CDLL(cudart_lib_filename) cudart.cudaRuntimeGetVersion.restype = int cudart.cudaRuntimeGetVersion.argtypes = [ctypes.POINTER(ctypes.c_int)] version = ctypes.c_int() status = cudart.cudaRuntimeGetVersion(ctypes.byref(version)) if status != 0: return None except Exception: return None
return version.value
# use set to avoid duplications cudart_found_versions = {get_cudart_version(cudart_version) for cudart_version in cudart_possible_versions}
# convert to list and remove None return [ver for ver in cudart_found_versions if ver]1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627# -------------------------------------------------------------------------# Copyright (c) Microsoft Corporation. All rights reserved.# Licensed under the MIT License.# --------------------------------------------------------------------------from __future__ import annotations
import collectionsimport collections.abcimport osimport typingimport warningsfrom collections.abc import Callable, Sequencefrom enum import IntEnumfrom typing import Any
import numpy as np
from onnxruntime.capi import _pybind_state as C
if typing.TYPE_CHECKING: import numpy.typing as npt
def get_ort_device_type(device_type: str) -> int: if device_type == "cuda": return C.OrtDevice.cuda() elif device_type == "cann": return C.OrtDevice.cann() elif device_type == "cpu": return C.OrtDevice.cpu() elif device_type == "dml": return C.OrtDevice.dml() elif device_type == "webgpu": return C.OrtDevice.webgpu() elif device_type == "gpu": return C.OrtDevice.gpu() elif device_type == "npu": return C.OrtDevice.npu() else: raise Exception("Unsupported device type: " + device_type)
class OrtDeviceVendorId(IntEnum): """Vendor IDs aligned with OrtDevice::VendorIds in ortdevice.h."""
NONE = 0x0000 AMD = 0x1002 NVIDIA = 0x10DE ARM = 0x13B5 MICROSOFT = 0x1414 HUAWEI = 0x19E5 QUALCOMM = 0x5143 INTEL = 0x8086
def get_vendor_id_for_device_type(device_type: str) -> OrtDeviceVendorId | None: if device_type == "cuda": return OrtDeviceVendorId.NVIDIA elif device_type == "dml": return OrtDeviceVendorId.MICROSOFT elif device_type == "cann": return OrtDeviceVendorId.HUAWEI else: return None
class AdapterFormat: """ This class is used to create adapter files from python structures """
def __init__(self, adapter=None) -> None: if adapter is None: self._adapter = C.AdapterFormat() else: self._adapter = adapter
@staticmethod def read_adapter(file_path: os.PathLike) -> AdapterFormat: return AdapterFormat(C.AdapterFormat.read_adapter(file_path))
def export_adapter(self, file_path: os.PathLike): """ This function writes a file at the specified location in onnxrunitme adapter format containing Lora parameters.
:param file_path: absolute path for the adapter """ self._adapter.export_adapter(file_path)
def get_format_version(self) -> int: return self._adapter.format_version
def set_adapter_version(self, adapter_version: int) -> None: self._adapter.adapter_version = adapter_version
def get_adapter_version(self) -> int: return self._adapter.adapter_version
def set_model_version(self, model_version: int) -> None: self._adapter.model_version = model_version
def get_model_version(self) -> int: return self._adapter.model_version
def set_parameters(self, params: dict[str, OrtValue]) -> None: """Set adapter parameters for export.""" self._adapter.parameters = {k: v._ortvalue for k, v in params.items()}
def get_parameters(self) -> dict[str, OrtValue]: """Get adapter parameters as a dict of name -> OrtValue.
On read instances, the returned OrtValues are zero-copy views; the backing memory stays alive as long as any returned OrtValue is referenced. """ return {k: OrtValue(v) for k, v in self._adapter.parameters.items()}
def check_and_normalize_provider_args( providers: Sequence[str | tuple[str, dict[Any, Any]]] | None, provider_options: Sequence[dict[Any, Any]] | None, available_provider_names: Sequence[str],): """ Validates the 'providers' and 'provider_options' arguments and returns a normalized version.
:param providers: Optional sequence of providers in order of decreasing precedence. Values can either be provider names or tuples of (provider name, options dict). :param provider_options: Optional sequence of options dicts corresponding to the providers listed in 'providers'. :param available_provider_names: The available provider names.
:return: Tuple of (normalized 'providers' sequence, normalized 'provider_options' sequence).
'providers' can contain either names or names and options. When any options are given in 'providers', 'provider_options' should not be used.
The normalized result is a tuple of: 1. Sequence of provider names in the same order as 'providers'. 2. Sequence of corresponding provider options dicts with string keys and values. Unspecified provider options yield empty dicts. """ if providers is None: return [], []
provider_name_to_options = collections.OrderedDict()
def set_provider_options(name, options): if name not in available_provider_names: warnings.warn( "Specified provider '{}' is not in available provider names.Available providers: '{}'".format( name, ", ".join(available_provider_names) ) )
if name in provider_name_to_options: warnings.warn(f"Duplicate provider '{name}' encountered, ignoring.") return
normalized_options = {str(key): str(value) for key, value in options.items()} provider_name_to_options[name] = normalized_options
if not isinstance(providers, collections.abc.Sequence): raise ValueError("'providers' should be a sequence.")
if provider_options is not None: if not isinstance(provider_options, collections.abc.Sequence): raise ValueError("'provider_options' should be a sequence.")
if len(providers) != len(provider_options): raise ValueError("'providers' and 'provider_options' should be the same length if both are given.")
if not all(isinstance(provider, str) for provider in providers): raise ValueError("Only string values for 'providers' are supported if 'provider_options' is given.")
if not all(isinstance(options_for_provider, dict) for options_for_provider in provider_options): raise ValueError("'provider_options' values must be dicts.")
for name, options in zip(providers, provider_options, strict=False): set_provider_options(name, options)
else: for provider in providers: if isinstance(provider, str): set_provider_options(provider, {}) elif ( isinstance(provider, tuple) and len(provider) == 2 and isinstance(provider[0], str) and isinstance(provider[1], dict) ): set_provider_options(provider[0], provider[1]) else: raise ValueError("'providers' values must be either strings or (string, dict) tuples.")
return list(provider_name_to_options.keys()), list(provider_name_to_options.values())
class Session: """ This is the main class used to run a model. """
def __init__(self, enable_fallback: bool = True): # self._sess is managed by the derived class and relies on bindings from C.InferenceSession self._sess = None self._enable_fallback = enable_fallback
def get_session_options(self) -> C.SessionOptions: "Return the session options. See :class:`onnxruntime.SessionOptions`." return self._sess_options
def get_inputs(self) -> Sequence[C.NodeArg]: "Return the inputs metadata as a list of :class:`onnxruntime.NodeArg`." return self._inputs_meta
def get_outputs(self) -> Sequence[C.NodeArg]: "Return the outputs metadata as a list of :class:`onnxruntime.NodeArg`." return self._outputs_meta
def get_overridable_initializers(self) -> Sequence[C.NodeArg]: "Return the inputs (including initializers) metadata as a list of :class:`onnxruntime.NodeArg`." return self._overridable_initializers
def get_modelmeta(self) -> C.ModelMetadata: "Return the metadata. See :class:`onnxruntime.ModelMetadata`." return self._model_meta
def get_input_memory_infos(self) -> Sequence[C.OrtMemoryInfo]: "Return the memory info for the inputs." return self._input_meminfos
def get_output_memory_infos(self) -> Sequence[C.OrtMemoryInfo]: "Return the memory info for the outputs." return self._output_meminfos
def get_input_epdevices(self) -> Sequence[C.OrtEpDevice]: "Return the execution providers for the inputs." return self._input_epdevices
def get_providers(self) -> Sequence[str]: "Return list of registered execution providers." return self._providers
def get_provider_options(self): "Return registered execution providers' configurations." return self._provider_options
def get_provider_graph_assignment_info(self) -> Sequence[C.OrtEpAssignedSubgraph]: """ Get information about the subgraphs assigned to each execution provider and the nodes within.
Application must enable the recording of graph assignment information by setting the session configuration for the key "session.record_ep_graph_assignment_info" to "1". """ return self._sess.get_provider_graph_assignment_info()
def set_providers(self, providers=None, provider_options=None) -> None: """ Register the input list of execution providers. The underlying session is re-created.
:param providers: Optional sequence of providers in order of decreasing precedence. Values can either be provider names or tuples of (provider name, options dict). If not provided, then all available providers are used with the default precedence. :param provider_options: Optional sequence of options dicts corresponding to the providers listed in 'providers'.
'providers' can contain either names or names and options. When any options are given in 'providers', 'provider_options' should not be used.
The list of providers is ordered by precedence. For example `['CUDAExecutionProvider', 'CPUExecutionProvider']` means execute a node using CUDAExecutionProvider if capable, otherwise execute using CPUExecutionProvider. """ # recreate the underlying C.InferenceSession self._reset_session(providers, provider_options)
def disable_fallback(self) -> None: """ Disable session.run() fallback mechanism. """ self._enable_fallback = False
def enable_fallback(self) -> None: """ Enable session.Run() fallback mechanism. If session.Run() fails due to an internal Execution Provider failure, reset the Execution Providers enabled for this session. If GPU is enabled, fall back to CUDAExecutionProvider. otherwise fall back to CPUExecutionProvider. """ self._enable_fallback = True
def _validate_input(self, feed_input_names): missing_input_names = [] for input in self._inputs_meta: if input.name not in feed_input_names and not input.type.startswith("optional"): missing_input_names.append(input.name) if missing_input_names: raise ValueError( f"Required inputs ({missing_input_names}) are missing from input feed ({feed_input_names})." )
def run(self, output_names, input_feed, run_options=None) -> Sequence[np.ndarray | SparseTensor | list | dict]: """ Compute the predictions.
:param output_names: name of the outputs :param input_feed: dictionary ``{ input_name: input_value }`` :param run_options: See :class:`onnxruntime.RunOptions`. :return: list of results, every result is either a numpy array, a sparse tensor, a list or a dictionary.
::
sess.run([output_name], {input_name: x}) """ self._validate_input(list(input_feed.keys())) if not output_names: output_names = [output.name for output in self._outputs_meta] try: return self._sess.run(output_names, input_feed, run_options) except C.EPFail as err: if self._enable_fallback: print(f"EP Error: {err!s} using {self._providers}") print(f"Falling back to {self._fallback_providers} and retrying.") self.set_providers(self._fallback_providers) # Fallback only once. self.disable_fallback() return self._sess.run(output_names, input_feed, run_options) raise
def run_async(self, output_names, input_feed, callback, user_data, run_options=None): """ Compute the predictions asynchronously in a separate cxx thread from ort intra-op threadpool.
:param output_names: name of the outputs :param input_feed: dictionary ``{ input_name: input_value }`` :param callback: python function that accept array of results, and a status string on error. The callback will be invoked by a cxx thread from ort intra-op threadpool. :param run_options: See :class:`onnxruntime.RunOptions`.
:: class MyData: def __init__(self): # ... def save_results(self, results): # ...
def callback(results: np.ndarray, user_data: MyData, err: str) -> None: if err: print (err) else: # save results to user_data
sess.run_async([output_name], {input_name: x}, callback) """ self._validate_input(list(input_feed.keys())) if not output_names: output_names = [output.name for output in self._outputs_meta] return self._sess.run_async(output_names, input_feed, callback, user_data, run_options)
def run_with_ort_values(self, output_names, input_dict_ort_values, run_options=None) -> Sequence[OrtValue]: """ Compute the predictions.
:param output_names: name of the outputs :param input_dict_ort_values: dictionary ``{ input_name: input_ort_value }`` See ``OrtValue`` class how to create `OrtValue` from numpy array or `SparseTensor` :param run_options: See :class:`onnxruntime.RunOptions`. :return: an array of `OrtValue`
::
sess.run([output_name], {input_name: x}) """
def invoke(sess, output_names, input_dict_ort_values, run_options): input_dict = {} for n, v in input_dict_ort_values.items(): input_dict[n] = v._get_c_value() result = sess.run_with_ort_values(input_dict, output_names, run_options) if not isinstance(result, C.OrtValueVector): raise TypeError("run_with_ort_values() must return a instance of type 'OrtValueVector'.") ort_values = [OrtValue(v) for v in result] return ort_values
self._validate_input(list(input_dict_ort_values.keys())) if not output_names: output_names = [output.name for output in self._outputs_meta] try: return invoke(self._sess, output_names, input_dict_ort_values, run_options) except C.EPFail as err: if self._enable_fallback: print(f"EP Error: {err!s} using {self._providers}") print(f"Falling back to {self._fallback_providers} and retrying.") self.set_providers(self._fallback_providers) # Fallback only once. self.disable_fallback() return invoke(self._sess, output_names, input_dict_ort_values, run_options) raise
def end_profiling(self): """ End profiling and return results in a file.
The results are stored in a filename if the option :meth:`onnxruntime.SessionOptions.enable_profiling`. """ return self._sess.end_profiling()
def get_profiling_start_time_ns(self): """ Return the nanoseconds of profiling's start time Comparable to time.monotonic_ns() after Python 3.3 On some platforms, this timer may not be as precise as nanoseconds For instance, on Windows and MacOS, the precision will be ~100ns """ return self._sess.get_profiling_start_time_ns
def io_binding(self) -> IOBinding: "Return an onnxruntime.IOBinding object`." return IOBinding(self)
def run_with_iobinding(self, iobinding, run_options=None): """ Compute the predictions.
:param iobinding: the iobinding object that has graph inputs/outputs bind. :param run_options: See :class:`onnxruntime.RunOptions`. """ self._sess.run_with_iobinding(iobinding._iobinding, run_options)
def set_ep_dynamic_options(self, options: dict[str, str]): """ Set dynamic options for execution providers.
:param options: Dictionary of key-value pairs where both keys and values are strings. These options will be passed to the execution providers to modify their runtime behavior. """ self._sess.set_ep_dynamic_options(options)
def get_tuning_results(self): return self._sess.get_tuning_results()
def set_tuning_results(self, results, *, error_on_invalid=False): return self._sess.set_tuning_results(results, error_on_invalid)
def run_with_ortvaluevector(self, run_options, feed_names, feeds, fetch_names, fetches, fetch_devices): """ Compute the predictions similar to other run_*() methods but with minimal C++/Python conversion overhead.
:param run_options: See :class:`onnxruntime.RunOptions`. :param feed_names: list of input names. :param feeds: list of input OrtValue. :param fetch_names: list of output names. :param fetches: list of output OrtValue. :param fetch_devices: list of output devices. """ self._sess.run_with_ortvaluevector(run_options, feed_names, feeds, fetch_names, fetches, fetch_devices)
class InferenceSession(Session): """ This is the main class used to run a model. """
def __init__( self, path_or_bytes: str | bytes | os.PathLike, sess_options: C.SessionOptions | None = None, providers: Sequence[str | tuple[str, dict[Any, Any]]] | None = None, provider_options: Sequence[dict[Any, Any]] | None = None, **kwargs, ) -> None: """ :param path_or_bytes: Filename or serialized ONNX or ORT format model in a byte string. :param sess_options: Session options. :param providers: Optional sequence of providers in order of decreasing precedence. Values can either be provider names or tuples of (provider name, options dict). If not provided, then all available providers are used with the default precedence. :param provider_options: Optional sequence of options dicts corresponding to the providers listed in 'providers'.
The model type will be inferred unless explicitly set in the SessionOptions. To explicitly set:
::
so = onnxruntime.SessionOptions() # so.add_session_config_entry('session.load_model_format', 'ONNX') or so.add_session_config_entry('session.load_model_format', 'ORT')
A file extension of '.ort' will be inferred as an ORT format model. All other filenames are assumed to be ONNX format models.
'providers' can contain either names or names and options. When any options are given in 'providers', 'provider_options' should not be used.
The list of providers is ordered by precedence. For example `['CUDAExecutionProvider', 'CPUExecutionProvider']` means execute a node using `CUDAExecutionProvider` if capable, otherwise execute using `CPUExecutionProvider`. """ super().__init__(enable_fallback=int(kwargs.get("enable_fallback", 1)) == 1)
if isinstance(path_or_bytes, (str, os.PathLike)): self._model_path = os.fspath(path_or_bytes) self._model_bytes = None elif isinstance(path_or_bytes, bytes): self._model_path = None self._model_bytes = path_or_bytes # TODO: This is bad as we're holding the memory indefinitely else: raise TypeError(f"Unable to load from type '{type(path_or_bytes)}'")
self._sess_options = sess_options self._sess_options_initial = sess_options if "read_config_from_model" in kwargs: self._read_config_from_model = int(kwargs["read_config_from_model"]) == 1 else: self._read_config_from_model = os.environ.get("ORT_LOAD_CONFIG_FROM_MODEL") == "1"
# internal parameters that we don't expect to be used in general so aren't documented disabled_optimizers = kwargs.get("disabled_optimizers")
try: self._create_inference_session(providers, provider_options, disabled_optimizers) except (ValueError, RuntimeError) as e: if self._enable_fallback: try: print("*************** EP Error ***************") print(f"EP Error {e} when using {providers}") print(f"Falling back to {self._fallback_providers} and retrying.") print("****************************************") self._create_inference_session(self._fallback_providers, None) # Fallback only once. self.disable_fallback() return except Exception as fallback_error: raise fallback_error from e # Fallback is disabled. Raise the original error. raise e
def _create_inference_session(self, providers, provider_options, disabled_optimizers=None): available_providers = C.get_available_providers()
# Validate that TensorrtExecutionProvider and NvTensorRTRTXExecutionProvider are not both specified if providers: has_tensorrt = any( provider == "TensorrtExecutionProvider" or (isinstance(provider, tuple) and provider[0] == "TensorrtExecutionProvider") for provider in providers ) has_tensorrt_rtx = any( provider == "NvTensorRTRTXExecutionProvider" or (isinstance(provider, tuple) and provider[0] == "NvTensorRTRTXExecutionProvider") for provider in providers ) if has_tensorrt and has_tensorrt_rtx: raise ValueError( "Cannot enable both 'TensorrtExecutionProvider' and 'NvTensorRTRTXExecutionProvider' " "in the same session." ) # Tensorrt and TensorRT RTX can fall back to CUDA if it's explicitly assigned. All others fall back to CPU. if "NvTensorRTRTXExecutionProvider" in available_providers: if ( providers and any( provider == "CUDAExecutionProvider" or (isinstance(provider, tuple) and provider[0] == "CUDAExecutionProvider") for provider in providers ) and any( provider == "NvTensorRTRTXExecutionProvider" or (isinstance(provider, tuple) and provider[0] == "NvTensorRTRTXExecutionProvider") for provider in providers ) ): self._fallback_providers = ["CUDAExecutionProvider", "CPUExecutionProvider"] else: self._fallback_providers = ["CPUExecutionProvider"] elif "TensorrtExecutionProvider" in available_providers: if ( providers and any( provider == "CUDAExecutionProvider" or (isinstance(provider, tuple) and provider[0] == "CUDAExecutionProvider") for provider in providers ) and any( provider == "TensorrtExecutionProvider" or (isinstance(provider, tuple) and provider[0] == "TensorrtExecutionProvider") for provider in providers ) ): self._fallback_providers = ["CUDAExecutionProvider", "CPUExecutionProvider"] else: self._fallback_providers = ["CPUExecutionProvider"] else: self._fallback_providers = ["CPUExecutionProvider"]
# validate providers and provider_options before other initialization providers, provider_options = check_and_normalize_provider_args( providers, provider_options, available_providers )
# Print a warning if user passed providers to InferenceSession() but the SessionOptions instance # already has provider information (e.g., via add_provider_for_devices()). The providers specified # here will take precedence. if self._sess_options is not None and (providers or provider_options) and self._sess_options.has_providers(): warnings.warn( "Specified 'providers'/'provider_options' when creating InferenceSession but SessionOptions has " "already been configured with providers. InferenceSession will only use the providers " "passed to InferenceSession()." )
session_options = self._sess_options if self._sess_options else C.get_default_session_options()
self._register_ep_custom_ops(session_options, providers, provider_options, available_providers)
if self._model_path: sess = C.InferenceSession(session_options, self._model_path, True, self._read_config_from_model) else: sess = C.InferenceSession(session_options, self._model_bytes, False, self._read_config_from_model)
if disabled_optimizers is None: disabled_optimizers = set() elif not isinstance(disabled_optimizers, set): # convert to set. assumes iterable disabled_optimizers = set(disabled_optimizers)
# initialize the C++ InferenceSession sess.initialize_session(providers, provider_options, disabled_optimizers)
self._sess = sess self._sess_options = self._sess.session_options self._inputs_meta = self._sess.inputs_meta self._outputs_meta = self._sess.outputs_meta self._overridable_initializers = self._sess.overridable_initializers self._input_meminfos = self._sess.input_meminfos self._output_meminfos = self._sess.output_meminfos self._input_epdevices = self._sess.input_epdevices self._model_meta = self._sess.model_meta self._providers = self._sess.get_providers() self._provider_options = self._sess.get_provider_options() self._profiling_start_time_ns = self._sess.get_profiling_start_time_ns
def _reset_session(self, providers, provider_options) -> None: "release underlying session object." # meta data references session internal structures # so they must be set to None to decrement _sess reference count. self._sess_options = None self._inputs_meta = None self._outputs_meta = None self._overridable_initializers = None self._input_meminfos = None self._output_meminfos = None self._input_epdevices = None self._model_meta = None self._providers = None self._provider_options = None self._profiling_start_time_ns = None
# create a new C.InferenceSession self._sess = None self._sess_options = self._sess_options_initial self._create_inference_session(providers, provider_options)
def _register_ep_custom_ops(self, session_options, providers, provider_options, available_providers): for i in range(len(providers)): if providers[i] in available_providers and providers[i] == "TensorrtExecutionProvider": C.register_tensorrt_plugins_as_custom_ops(session_options, provider_options[i]) elif ( isinstance(providers[i], tuple) and providers[i][0] in available_providers and providers[i][0] == "TensorrtExecutionProvider" ): C.register_tensorrt_plugins_as_custom_ops(session_options, providers[i][1])
if providers[i] in available_providers and providers[i] == "NvTensorRTRTXExecutionProvider": C.register_nv_tensorrt_rtx_plugins_as_custom_ops(session_options, provider_options[i]) elif ( isinstance(providers[i], tuple) and providers[i][0] in available_providers and providers[i][0] == "NvTensorrtRTXExecutionProvider" ): C.register_nv_tensorrt_rtx_plugins_as_custom_ops(session_options, providers[i][1])
def make_get_initializer_location_func_wrapper( get_initializer_location_func: GetInitializerLocationFunc,) -> GetInitializerLocationWrapperFunc: """ Wraps a user's "get initializer location" function. The returned wrapper function adheres to the signature expected by ORT.
Need this wrapper to: - Convert the `initializer_value` parameter from `C.OrtValue` to `onnxruntime.OrtValue`, which is more convenient for the user's function to use. - Allow the user's function to return the original `external_info` parameter (this wrapper makes a copy) """
def get_initializer_location_func_wrapper( initializer_name: str, initializer_value: C.OrtValue, external_info: C.OrtExternalInitializerInfo | None, ) -> C.OrtExternalInitializerInfo | None: ret_val: C.OrtExternalInitializerInfo | None = get_initializer_location_func( initializer_name, OrtValue(initializer_value), external_info ) if ret_val is not None and ret_val == external_info: # User returned `external_info` (const and owned by ORT). ORT expects the returned value to be # a new instance (that it deletes), so make a copy. ret_val = C.OrtExternalInitializerInfo(ret_val.filepath, ret_val.file_offset, ret_val.byte_size) return ret_val
return get_initializer_location_func_wrapper
class ModelCompiler: """ This class is used to compile an ONNX model. A compiled ONNX model has EPContext nodes that each encapsulates a subgraph compiled/optimized for a specific execution provider.
Refer to the EPContext design document for more information about EPContext models: https://onnxruntime.ai/docs/execution-providers/EP-Context-Design.html
::
sess_options = onnxruntime.SessionOptions() sess_options.add_provider("SomeExecutionProvider", {"option1": "value1"}) # Alternatively, allow ONNX Runtime to select the provider automatically given a policy: # sess_options.set_provider_selection_policy(onnxrt.OrtExecutionProviderDevicePolicy.PREFER_NPU)
model_compiler = onnxruntime.ModelCompiler(sess_options, "input_model.onnx") model_compiler.compile_to_file("output_model.onnx") """
def __init__( self, sess_options: C.SessionOptions, input_model_path_or_bytes: str | os.PathLike | bytes, embed_compiled_data_into_model: bool = False, external_initializers_file_path: str | os.PathLike | None = None, external_initializers_size_threshold: int = 1024, flags: int = C.OrtCompileApiFlags.NONE, graph_optimization_level: C.GraphOptimizationLevel = C.GraphOptimizationLevel.ORT_DISABLE_ALL, get_initializer_location_func: GetInitializerLocationFunc | None = None, ): """ Creates a ModelCompiler instance.
:param sess_options: Session options containing the providers for which the model will be compiled. Refer to SessionOptions.add_provider() and SessionOptions.set_provider_selection_policy(). :param input_model_path_or_bytes: The path to the input model file or bytes representing a serialized ONNX model. :param embed_compiled_data_into_model: Defaults to False. Set to True to embed compiled binary data into EPContext nodes in the compiled model. :param external_initializers_file_path: Defaults to None. Set to a path for a file that will store the initializers for non-compiled nodes. :param external_initializers_size_threshold: Defaults to 1024. Ignored if `external_initializers_file_path` is None or empty. Initializers larger than this threshold are stored in the external initializers file. :param flags: Additional boolean options to enable. Set this parameter to a bitwise OR of flags in onnxruntime.OrtCompileApiFlags. :param graph_optimization_level: The graph optimization level. Defaults to onnxruntime.GraphOptimizationLevel.ORT_DISABLE_ALL. :param get_initializer_location_func: Optional function called for every initializer to allow user to specify whether an initializer should be stored within the model or externally. Example: ``` def get_initializer_location( initializer_name: str, initializer_value: onnxrt.OrtValue, external_info: onnxrt.OrtExternalInitializerInfo | None, ) -> onnxrt.OrtExternalInitializerInfo | None: byte_size = initializer_value.tensor_size_in_bytes()
if byte_size < 64: return None # Store small initializer within compiled model.
# Else, write initializer to new external file. value_np = initializer_value.numpy() file_offset = ext_init_file.tell() ext_init_file.write(value_np.tobytes()) return onnxrt.OrtExternalInitializerInfo(initializer_file_path, file_offset, byte_size) ``` """ input_model_path: str | os.PathLike | None = None input_model_bytes: bytes | None = None if isinstance(input_model_path_or_bytes, (str, os.PathLike)): if not input_model_path_or_bytes: raise ValueError("Input model path is empty") input_model_path = os.fspath(input_model_path_or_bytes) elif isinstance(input_model_path_or_bytes, bytes): if len(input_model_path_or_bytes) == 0: raise ValueError("Input model bytes array is empty") input_model_bytes = input_model_path_or_bytes else: raise TypeError(f"Unable to load from type '{type(input_model_path_or_bytes)}'")
if external_initializers_file_path: if not isinstance(external_initializers_file_path, (str, os.PathLike)): arg_type = type(external_initializers_file_path) raise TypeError(f"Output external initializer filepath is of unexpected type '{arg_type}'") external_initializers_file_path = os.fspath(external_initializers_file_path) else: external_initializers_file_path = ""
if get_initializer_location_func is not None: if external_initializers_file_path: raise ValueError( "Cannot initialize ModelCompiler with both `external_initializers_file_path` " "and `get_initializer_location_func`" ) self.get_initializer_location_func_wrapper = make_get_initializer_location_func_wrapper( get_initializer_location_func ) else: self.get_initializer_location_func_wrapper = None
if input_model_path: self._model_compiler = C.ModelCompiler( sess_options, input_model_path, True, # is path embed_compiled_data_into_model, external_initializers_file_path, external_initializers_size_threshold, flags, graph_optimization_level, self.get_initializer_location_func_wrapper, ) else: self._model_compiler = C.ModelCompiler( sess_options, input_model_bytes, False, # is bytes embed_compiled_data_into_model, external_initializers_file_path, external_initializers_size_threshold, flags, graph_optimization_level, self.get_initializer_location_func_wrapper, )
def compile_to_file(self, output_model_path: str | None = None): """ Compiles to an output file. If an output file path is not provided, the output file path is generated based on the input model path by replacing '.onnx' with '_ctx.onnx'. Ex: The generated output file is 'model_ctx.onnx' for an input model with path 'model.onnx'.
Raises an 'InvalidArgument' exception if the compilation options are invalid.
:param output_model_path: Defaults to None. The path for the output/compiled model. """ if output_model_path: if not isinstance(output_model_path, (str, os.PathLike)): raise TypeError(f"Output model's filepath is of unexpected type '{type(output_model_path)}'") output_model_path = os.fspath(output_model_path) self._model_compiler.compile_to_file(output_model_path)
def compile_to_bytes(self) -> bytes: """ Compiles to bytes representing the serialized compiled ONNX model.
Raises an 'InvalidArgument' exception if the compilation options are invalid.
:return: A bytes object representing the compiled ONNX model. """ return self._model_compiler.compile_to_bytes()
def compile_to_stream(self, write_function: Callable[[bytes], None]): """ Compiles the input model and writes the serialized ONNX bytes to a stream using the provided write function. Raises an 'InvalidArgument' exception if the compilation options are invalid. :param write_function: A callable that accepts a bytes buffer to write. """ self._model_compiler.compile_to_stream(write_function)
class IOBinding: """ This class provides API to bind input/output to a specified device, e.g. GPU. """
def __init__(self, session: Session): self._iobinding = C.SessionIOBinding(session._sess) self._numpy_obj_references = {}
def bind_cpu_input(self, name, arr_on_cpu): """ bind an input to array on CPU :param name: input name :param arr_on_cpu: input values as a python array on CPU """ # Hold a reference to the numpy object as the bound OrtValue is backed # directly by the data buffer of the numpy object and so the numpy object # must be around until this IOBinding instance is around self._numpy_obj_references[name] = arr_on_cpu self._iobinding.bind_input(name, arr_on_cpu)
def bind_input(self, name, device_type, device_id, element_type, shape, buffer_ptr): """ :param name: input name :param device_type: e.g. cpu, cuda, cann :param device_id: device id, e.g. 0 :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) :param shape: input shape :param buffer_ptr: memory pointer to input data """ self._iobinding.bind_input( name, C.OrtDevice( get_ort_device_type(device_type), C.OrtDevice.default_memory(), device_id, ), element_type, shape, buffer_ptr, )
def bind_ortvalue_input(self, name, ortvalue): """ :param name: input name :param ortvalue: OrtValue instance to bind """ self._iobinding.bind_ortvalue_input(name, ortvalue._ortvalue)
def synchronize_inputs(self): self._iobinding.synchronize_inputs()
def bind_output( self, name, device_type="cpu", device_id=0, element_type=None, shape=None, buffer_ptr=None, ): """ :param name: output name :param device_type: e.g. cpu, cuda, cann, cpu by default :param device_id: device id, e.g. 0 :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) :param shape: output shape :param buffer_ptr: memory pointer to output data """
# Follow the `if` path when the user has not provided any pre-allocated buffer but still # would like to bind an output to a specific device (e.g. cuda). # Pre-allocating an output buffer may not be an option for the user as : # (1) They may not want to use a custom allocator specific to the device they want to bind the output to, # in which case ORT will allocate the memory for the user # (2) The output has a dynamic shape and hence the size of the buffer may not be fixed across runs if buffer_ptr is None: self._iobinding.bind_output( name, C.OrtDevice( get_ort_device_type(device_type), C.OrtDevice.default_memory(), device_id, ), ) else: if element_type is None or shape is None: raise ValueError("`element_type` and `shape` are to be provided if pre-allocated memory is provided") self._iobinding.bind_output( name, C.OrtDevice( get_ort_device_type(device_type), C.OrtDevice.default_memory(), device_id, ), element_type, shape, buffer_ptr, )
def bind_ortvalue_output(self, name, ortvalue): """ :param name: output name :param ortvalue: OrtValue instance to bind """ self._iobinding.bind_ortvalue_output(name, ortvalue._ortvalue)
def synchronize_outputs(self): self._iobinding.synchronize_outputs()
def get_outputs(self): """ Returns the output OrtValues from the Run() that preceded the call. The data buffer of the obtained OrtValues may not reside on CPU memory """ outputs = self._iobinding.get_outputs() if not isinstance(outputs, C.OrtValueVector): raise TypeError("get_outputs() must return an instance of type 'OrtValueVector'.") return [OrtValue(ortvalue) for ortvalue in outputs]
def get_outputs_as_ortvaluevector(self): return self._iobinding.get_outputs()
def copy_outputs_to_cpu(self): """Copy output contents to CPU.""" return self._iobinding.copy_outputs_to_cpu()
def clear_binding_inputs(self): self._iobinding.clear_binding_inputs()
def clear_binding_outputs(self): self._iobinding.clear_binding_outputs()
class OrtValue: """ A data structure that supports all ONNX data formats (tensors and non-tensors) that allows users to place the data backing these on a device, for example, on a CUDA supported device. This class provides APIs to construct and deal with OrtValues. """
def __init__(self, ortvalue: C.OrtValue, numpy_obj: np.ndarray | None = None): if isinstance(ortvalue, C.OrtValue): self._ortvalue = ortvalue # Hold a ref count to the numpy object if the OrtValue is backed directly # by its data buffer so that it isn't destroyed when the OrtValue is in use self._numpy_obj = numpy_obj else: # An end user won't hit this error raise ValueError( "`Provided ortvalue` needs to be of type `onnxruntime.capi.onnxruntime_pybind11_state.OrtValue`" )
def _get_c_value(self) -> C.OrtValue: return self._ortvalue
@classmethod def ortvalue_from_numpy( cls, numpy_obj: np.ndarray, /, device_type="cpu", device_id=0, vendor_id: int | OrtDeviceVendorId = -1 ) -> OrtValue: """ Factory method to construct an OrtValue (which holds a Tensor) from a given Numpy object A copy of the data in the Numpy object is held by the OrtValue only if the device is NOT cpu
:param numpy_obj: The Numpy object to construct the OrtValue from :param device_type: e.g. cpu, cuda, cann, cpu by default :param device_id: device id, e.g. 0 :param vendor_id: The device's PCI vendor id as an int or OrtDeviceVendorId. If provided, the device_type should be "gpu" or "npu". """ # Hold a reference to the numpy object (if device_type is 'cpu') as the OrtValue # is backed directly by the data buffer of the numpy object and so the numpy object # must be around until this OrtValue instance is around return cls( C.OrtValue.ortvalue_from_numpy( numpy_obj, OrtDevice.make(device_type, device_id, vendor_id)._get_c_device(), ), numpy_obj if device_type.lower() == "cpu" else None, )
@classmethod def ortvalue_from_numpy_with_onnx_type(cls, data: np.ndarray, /, onnx_element_type: int) -> OrtValue: """ This method creates an instance of OrtValue on top of the numpy array. No data copy is made and the lifespan of the resulting OrtValue should never exceed the lifespan of bytes object. The API attempts to reinterpret the data type which is expected to be the same size. This is useful when we want to use an ONNX data type that is not supported by numpy.
:param data: numpy.ndarray. :param onnx_element_type: a valid onnx TensorProto::DataType enum value """ return cls(C.OrtValue.ortvalue_from_numpy_with_onnx_type(data, onnx_element_type), data)
@classmethod def ortvalue_from_shape_and_type( cls, shape: Sequence[int], element_type, device_type: str = "cpu", device_id: int = 0, vendor_id: int | OrtDeviceVendorId = -1, memory_info: C.OrtMemoryInfo | None = None, ) -> OrtValue: """ Factory method to construct an OrtValue (which holds a Tensor) from given shape and element_type
:param shape: List of integers indicating the shape of the OrtValue :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). :param device_type: e.g. cpu, cuda, cann, cpu by default :param device_id: device id, e.g. 0 :param vendor_id: The device's PCI vendor id as an int or OrtDeviceVendorId. If provided, the device type should be "gpu" or "npu". :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. """
if memory_info is not None: if device_type != "cpu" or device_id != 0 or vendor_id != -1: warnings.warn( "device_type, device_id, and vendor_id are ignored when memory_info is provided.", stacklevel=2, ) if isinstance(element_type, int): return cls( C.OrtValue.ortvalue_from_shape_and_onnx_type_for_memory_info( shape, element_type, memory_info, ) ) return cls( C.OrtValue.ortvalue_from_shape_and_type_for_memory_info( shape, element_type, memory_info, ) )
device = OrtDevice.make(device_type, device_id, vendor_id)._get_c_device()
# Integer for onnx element type (see https://onnx.ai/onnx/api/mapping.html). # This is helpful for some data type (like TensorProto.BFLOAT16) that is not available in numpy. if isinstance(element_type, int): return cls( C.OrtValue.ortvalue_from_shape_and_onnx_type( shape, element_type, device, ) )
return cls( C.OrtValue.ortvalue_from_shape_and_type( shape, element_type, device, ) )
@classmethod def ort_value_from_sparse_tensor(cls, sparse_tensor: SparseTensor) -> OrtValue: """ The function will construct an OrtValue instance from a valid SparseTensor The new instance of OrtValue will assume the ownership of sparse_tensor """ return cls(C.OrtValue.ort_value_from_sparse_tensor(sparse_tensor._get_c_tensor()))
def as_sparse_tensor(self) -> SparseTensor: """ The function will return SparseTensor contained in this OrtValue """ return SparseTensor(self._ortvalue.as_sparse_tensor())
def data_ptr(self) -> int: """ Returns the address of the first element in the OrtValue's data buffer """ return self._ortvalue.data_ptr()
def device_name(self) -> str: """ Returns the name of the device where the OrtValue's data buffer resides e.g. cpu, cuda, cann """ return self._ortvalue.device_name().lower()
def shape(self) -> Sequence[int]: """ Returns the shape of the data in the OrtValue """ return self._ortvalue.shape()
def data_type(self) -> str: """ Returns the data type of the data in the OrtValue. E.g. 'tensor(int64)' """ return self._ortvalue.data_type()
def element_type(self) -> int: """ Returns the proto type of the data in the OrtValue if the OrtValue is a tensor. """ return self._ortvalue.element_type()
def tensor_size_in_bytes(self) -> int: """ Returns the size of the data in the OrtValue in bytes if the OrtValue is a tensor. """ return self._ortvalue.tensor_size_in_bytes()
def has_value(self) -> bool: """ Returns True if the OrtValue corresponding to an optional type contains data, else returns False """ return self._ortvalue.has_value()
def is_tensor(self) -> bool: """ Returns True if the OrtValue contains a Tensor, else returns False """ return self._ortvalue.is_tensor()
def is_sparse_tensor(self) -> bool: """ Returns True if the OrtValue contains a SparseTensor, else returns False """ return self._ortvalue.is_sparse_tensor()
def is_tensor_sequence(self) -> bool: """ Returns True if the OrtValue contains a Tensor Sequence, else returns False """ return self._ortvalue.is_tensor_sequence()
def numpy(self) -> np.ndarray: """ Returns a Numpy object from the OrtValue. Valid only for OrtValues holding Tensors. Throws for OrtValues holding non-Tensors. Use accessors to gain a reference to non-Tensor objects such as SparseTensor """ return self._ortvalue.numpy()
def __array__(self, dtype=None, copy=None) -> np.ndarray: """ Supports ``numpy.asarray(ortvalue)`` and ``numpy.array(ortvalue)`` via the `numpy __array__ protocol <https://numpy.org/devdocs/user/basics.interoperability.html>`_.
Valid only for OrtValues holding Tensors on CPU.
:param dtype: Optional numpy dtype to cast the result to. :param copy: Optional bool (numpy >= 2.0). If ``False``, a copy will only be made if necessary. If ``True``, a copy is always forced. If ``None`` (default), a copy will be made only if needed. :return: A numpy array with the same data as the OrtValue. """ arr = self.numpy()
if copy is not None: # numpy >= 2.0 added the copy kwarg to np.asarray; # np.array has always accepted it but with weaker semantics pre-2.0. arr = np.array(arr, dtype=dtype, copy=copy) elif dtype is not None: # np.asarray avoids a copy when the dtype already matches, # preserving memory sharing with the underlying OrtValue. arr = np.asarray(arr, dtype=dtype)
return arr
def __dlpack__(self, *, stream=None): """ Returns a DLPack capsule representing the tensor (part of the `DLPack protocol <https://dmlc.github.io/dlpack/latest/>`_).
This enables interoperability with other frameworks via ``from_dlpack(ortvalue)`` (e.g. ``torch.from_dlpack``, ``jax.dlpack.from_dlpack``, ``numpy.from_dlpack``).
The OrtValue must hold a contiguous tensor. No data is copied; the consumer shares memory with this OrtValue, which must remain alive while the capsule is in use.
:param stream: Optional stream on which the tensor data is accessible. Currently unused; included for protocol compliance. :return: A PyCapsule holding a DLManagedTensor. """ return self._ortvalue.__dlpack__(stream=stream)
def __dlpack_device__(self) -> tuple[int, int]: """ Returns ``(device_type, device_id)`` indicating where the tensor data resides (part of the `DLPack protocol <https://dmlc.github.io/dlpack/latest/>`_).
:return: Tuple of ``(device_type, device_id)`` as ints following DLPack ``DLDeviceType`` enum values. """ return self._ortvalue.__dlpack_device__()
@classmethod def from_dlpack(cls, data, /) -> OrtValue: """ Construct an OrtValue from an object that implements the DLPack protocol.
Accepts either:
* An object with ``__dlpack__`` / ``__dlpack_device__`` methods (e.g. a PyTorch tensor, JAX array, or numpy array). * A raw DLPack PyCapsule (legacy path).
Boolean tensors are automatically detected when the source object exposes a ``dtype`` attribute (numpy, PyTorch, etc.) or is an ``OrtValue``. For raw DLPack capsules where the original dtype cannot be inspected, bool tensors encoded as uint8 by older DLPack versions are not distinguishable from true uint8 tensors and will be imported as uint8.
No data is copied; the new OrtValue shares memory with the source.
:param data: A tensor object supporting the DLPack protocol, or a raw DLPack PyCapsule. :return: An OrtValue wrapping the tensor data. """ # Detect boolean dtype from the source object before consuming it, # because DLPack encodes bool as uint8 and the capsule alone cannot # distinguish between the two. is_bool = False if isinstance(data, OrtValue): is_bool = data.data_type() == "tensor(bool)" elif hasattr(data, "dtype"): dtype_obj = data.dtype # Use .name when available (numpy, cupy, tensorflow all expose it). # Fall back to str() for frameworks that don't (e.g. PyTorch). dtype_name = getattr(dtype_obj, "name", str(dtype_obj)) is_bool = dtype_name in ("bool", "bool_", "torch.bool")
# If the input supports the __dlpack__ protocol, call it to get the capsule. if hasattr(data, "__dlpack__"): capsule = data.__dlpack__() else: capsule = data
return cls(C.OrtValue.from_dlpack(capsule, is_bool))
def update_inplace(self, data) -> None: """ Update the OrtValue in place. The source data is copied over to the device memory backing the OrtValue. It can be used to update the input values for an InferenceSession with CUDA graph enabled or other scenarios where the OrtValue needs to be updated while the memory address can not be changed.
:param data: The source data, which can be a Numpy array or another OrtValue. When an OrtValue is provided, data can be copied between devices (e.g., GPU to GPU) without going through the CPU. """ if isinstance(data, OrtValue): self._ortvalue.update_inplace(data._ortvalue) return
if not isinstance(data, np.ndarray): raise TypeError("data must be a numpy.ndarray or an OrtValue.")
self._ortvalue.update_inplace(data)
def copy_tensors(src: Sequence[OrtValue], dst: Sequence[OrtValue], stream=None) -> None: """ Copy tensor data from source OrtValue sequence to destination OrtValue sequence. """ c_sources = [s._get_c_value() for s in src] c_dsts = [d._get_c_value() for d in dst] C.copy_tensors(c_sources, c_dsts, stream)
class OrtDevice: """ A data structure that exposes the underlying C++ OrtDevice """
def __init__(self, c_ort_device): """ Internal constructor """ if isinstance(c_ort_device, C.OrtDevice): self._ort_device = c_ort_device else: # An end user won't hit this error raise ValueError( "`Provided object` needs to be of type `onnxruntime.capi.onnxruntime_pybind11_state.OrtDevice`" )
def _get_c_device(self): """ Internal accessor to underlying object """ return self._ort_device
@staticmethod def make(ort_device_name, device_id, vendor_id: int | OrtDeviceVendorId = -1): if vendor_id < 0: # Preserve the historical convenience aliases ("cuda", "dml", "cann") # while making them work with plugin EP shared allocators. Those # allocators are keyed by vendor-specific OrtDevice values even when the # Python package itself was built without the corresponding built-in EP. alias_vendor_id = get_vendor_id_for_device_type(ort_device_name) if alias_vendor_id is not None: return OrtDevice( C.OrtDevice( get_ort_device_type(ort_device_name), C.OrtDevice.default_memory(), int(alias_vendor_id), device_id, ) )
# backwards compatibility with generic predefined OrtDevice names return OrtDevice( C.OrtDevice( get_ort_device_type(ort_device_name), C.OrtDevice.default_memory(), device_id, ) ) else: # generic. use GPU or NPU for ort_device_name and provide a vendor id. # vendor id of 0 is valid in some cases (e.g. webgpu is generic and does not have a vendor id) return OrtDevice( C.OrtDevice( get_ort_device_type(ort_device_name), C.OrtDevice.default_memory(), int(vendor_id), device_id, ) )
def device_id(self): return self._ort_device.device_id()
def device_type(self): return self._ort_device.device_type()
def device_vendor_id(self): return self._ort_device.vendor_id()
def device_mem_type(self): return self._ort_device.mem_type()
class SparseTensor: """ A data structure that project the C++ SparseTensor object The class provides API to work with the object. Depending on the format, the class will hold more than one buffer depending on the format """
def __init__(self, sparse_tensor: C.SparseTensor): """ Internal constructor """ if isinstance(sparse_tensor, C.SparseTensor): self._tensor = sparse_tensor else: # An end user won't hit this error raise ValueError( "`Provided object` needs to be of type `onnxruntime.capi.onnxruntime_pybind11_state.SparseTensor`" )
def _get_c_tensor(self) -> C.SparseTensor: return self._tensor
@classmethod def sparse_coo_from_numpy( cls, dense_shape: npt.NDArray[np.int64], values: np.ndarray, coo_indices: npt.NDArray[np.int64], ort_device: OrtDevice, ) -> SparseTensor: """ Factory method to construct a SparseTensor in COO format from given arguments
:param dense_shape: 1-D numpy array(int64) or a python list that contains a dense_shape of the sparse tensor must be on cpu memory :param values: a homogeneous, contiguous 1-D numpy array that contains non-zero elements of the tensor of a type. :param coo_indices: contiguous numpy array(int64) that contains COO indices for the tensor. coo_indices may have a 1-D shape when it contains a linear index of non-zero values and its length must be equal to that of the values. It can also be of 2-D shape, in which has it contains pairs of coordinates for each of the nnz values and its length must be exactly twice of the values length. :param ort_device: - describes the backing memory owned by the supplied nummpy arrays. Only CPU memory is suppored for non-numeric data types.
For primitive types, the method will map values and coo_indices arrays into native memory and will use them as backing storage. It will increment the reference count for numpy arrays and it will decrement it on GC. The buffers may reside in any storage either CPU or GPU. For strings and objects, it will create a copy of the arrays in CPU memory as ORT does not support those on other devices and their memory can not be mapped. """ return cls(C.SparseTensor.sparse_coo_from_numpy(dense_shape, values, coo_indices, ort_device._get_c_device()))
@classmethod def sparse_csr_from_numpy( cls, dense_shape: npt.NDArray[np.int64], values: np.ndarray, inner_indices: npt.NDArray[np.int64], outer_indices: npt.NDArray[np.int64], ort_device: OrtDevice, ) -> SparseTensor: """ Factory method to construct a SparseTensor in CSR format from given arguments
:param dense_shape: 1-D numpy array(int64) or a python list that contains a dense_shape of the sparse tensor (rows, cols) must be on cpu memory :param values: a contiguous, homogeneous 1-D numpy array that contains non-zero elements of the tensor of a type. :param inner_indices: contiguous 1-D numpy array(int64) that contains CSR inner indices for the tensor. Its length must be equal to that of the values. :param outer_indices: contiguous 1-D numpy array(int64) that contains CSR outer indices for the tensor. Its length must be equal to the number of rows + 1. :param ort_device: - describes the backing memory owned by the supplied nummpy arrays. Only CPU memory is suppored for non-numeric data types.
For primitive types, the method will map values and indices arrays into native memory and will use them as backing storage. It will increment the reference count and it will decrement then count when it is GCed. The buffers may reside in any storage either CPU or GPU. For strings and objects, it will create a copy of the arrays in CPU memory as ORT does not support those on other devices and their memory can not be mapped. """ return cls( C.SparseTensor.sparse_csr_from_numpy( dense_shape, values, inner_indices, outer_indices, ort_device._get_c_device(), ) )
def values(self) -> np.ndarray: """ The method returns a numpy array that is backed by the native memory if the data type is numeric. Otherwise, the returned numpy array that contains copies of the strings. """ return self._tensor.values()
def as_coo_view(self): """ The method will return coo representation of the sparse tensor which will enable querying COO indices. If the instance did not contain COO format, it would throw. You can query coo indices as:
::
coo_indices = sparse_tensor.as_coo_view().indices()
which will return a numpy array that is backed by the native memory. """ return self._tensor.get_coo_data()
def as_csrc_view(self): """ The method will return CSR(C) representation of the sparse tensor which will enable querying CRS(C) indices. If the instance dit not contain CSR(C) format, it would throw. You can query indices as:
::
inner_ndices = sparse_tensor.as_csrc_view().inner() outer_ndices = sparse_tensor.as_csrc_view().outer()
returning numpy arrays backed by the native memory. """ return self._tensor.get_csrc_data()
def as_blocksparse_view(self): """ The method will return coo representation of the sparse tensor which will enable querying BlockSparse indices. If the instance did not contain BlockSparse format, it would throw. You can query coo indices as:
::
block_sparse_indices = sparse_tensor.as_blocksparse_view().indices()
which will return a numpy array that is backed by the native memory """ return self._tensor.get_blocksparse_data()
def to_cuda(self, ort_device): """ Returns a copy of this instance on the specified cuda device
:param ort_device: with name 'cuda' and valid gpu device id
The method will throw if:
- this instance contains strings - this instance is already on GPU. Cross GPU copy is not supported - CUDA is not present in this build - if the specified device is not valid """ return SparseTensor(self._tensor.to_cuda(ort_device._get_c_device()))
def format(self): """ Returns a OrtSparseFormat enumeration """ return self._tensor.format
def dense_shape(self) -> npt.NDArray[np.int64]: """ Returns a numpy array(int64) containing a dense shape of a sparse tensor """ return self._tensor.dense_shape()
def data_type(self) -> str: """ Returns a string data type of the data in the OrtValue """ return self._tensor.data_type()
def device_name(self) -> str: """ Returns the name of the device where the SparseTensor data buffers reside e.g. cpu, cuda """ return self._tensor.device_name().lower()
# Type hint for user-specified function that allows the user to specify initializer locations when compiling a model.GetInitializerLocationFunc = Callable[ [str, OrtValue, C.OrtExternalInitializerInfo | None], C.OrtExternalInitializerInfo | None]
# Type hint that adheres to the signature expected by ORT.GetInitializerLocationWrapperFunc = Callable[ [str, C.OrtValue, C.OrtExternalInitializerInfo | None], C.OrtExternalInitializerInfo | None]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154# -------------------------------------------------------------------------# Copyright (c) Microsoft Corporation. All rights reserved.# Licensed under the MIT License.# --------------------------------------------------------------------------"""Check OS requirements for ONNX Runtime Python Bindings."""
import linecacheimport platformimport warnings
def check_distro_info(): __my_distro__ = "" __my_distro_ver__ = "" __my_system__ = platform.system().lower()
__OS_RELEASE_FILE__ = "/etc/os-release" # noqa: N806 __LSB_RELEASE_FILE__ = "/etc/lsb-release" # noqa: N806
if __my_system__ == "windows": __my_distro__ = __my_system__ __my_distro_ver__ = platform.release().lower()
if __my_distro_ver__ not in ["10", "11", "2016server", "2019server", "2022server", "2025server"]: warnings.warn( f"Unsupported Windows version ({__my_distro_ver__}). ONNX Runtime supports Windows 10 and above, or Windows Server 2016 and above." ) elif __my_system__ == "linux": """Although the 'platform' python module for getting Distro information works well on standard OS images running on real hardware, it is not accurate when running on Azure VMs, Git Bash, Cygwin, etc. The returned values for release and version are unpredictable for virtualized or emulated environments. /etc/os-release and /etc/lsb_release files, on the other hand, are guaranteed to exist and have standard values in all OSes supported by onnxruntime. The former is the current standard file to check OS info and the latter is its predecessor. """ # Newer systems have /etc/os-release with relevant distro info __my_distro__ = linecache.getline(__OS_RELEASE_FILE__, 3)[3:-1] __my_distro_ver__ = linecache.getline(__OS_RELEASE_FILE__, 6)[12:-2]
# Older systems may have /etc/os-release instead if not __my_distro__: __my_distro__ = linecache.getline(__LSB_RELEASE_FILE__, 1)[11:-1] __my_distro_ver__ = linecache.getline(__LSB_RELEASE_FILE__, 2)[16:-1]
# Instead of trying to parse distro specific files, # warn the user ONNX Runtime may not work out of the box __my_distro__ = __my_distro__.lower() __my_distro_ver__ = __my_distro_ver__.lower() elif __my_system__ == "darwin": __my_distro__ = __my_system__ __my_distro_ver__ = platform.release().lower()
if int(__my_distro_ver__.split(".")[0]) < 11: warnings.warn( f"Unsupported macOS version ({__my_distro_ver__}). ONNX Runtime supports macOS 11.0 or later." ) elif __my_system__ == "aix": import subprocess # noqa: PLC0415
returned_output = subprocess.check_output("oslevel") __my_distro_ver__str = returned_output.decode("utf-8") __my_distro_ver = __my_distro_ver__str[:3] else: warnings.warn( f"Unsupported platform ({__my_system__}). ONNX Runtime supports Linux, macOS, AIX and Windows platforms, only." )
def get_package_name_and_version_info(): package_name = "" version = "" cuda_version = ""
try: from .build_and_package_info import __version__ as version # noqa: PLC0415 from .build_and_package_info import package_name # noqa: PLC0415
try: # noqa: SIM105 from .build_and_package_info import cuda_version # noqa: PLC0415 except ImportError: # cuda_version is optional. For example, cpu only package does not have the attribute. pass except Exception as e: warnings.warn("WARNING: failed to collect package name and version info") print(e)
return package_name, version, cuda_version
def check_training_module(): import_ortmodule_exception = None
has_ortmodule = False try: from onnxruntime.training.ortmodule import ORTModule # noqa: F401, PLC0415
has_ortmodule = True except ImportError: # ORTModule not present has_ortmodule = False except Exception as e: # this may happen if Cuda is not installed, we want to raise it after # for any exception other than not having ortmodule, we want to continue # device version validation and raise the exception after. try: from onnxruntime.training.ortmodule._fallback import ORTModuleInitException # noqa: PLC0415
if isinstance(e, ORTModuleInitException): # ORTModule is present but not ready to run yet has_ortmodule = True except Exception: # ORTModule not present has_ortmodule = False
if not has_ortmodule: import_ortmodule_exception = e
# collect onnxruntime package name, version, and cuda version package_name, version, cuda_version = get_package_name_and_version_info()
if has_ortmodule and cuda_version: try: # collect cuda library build info. the library info may not be available # when the build environment has none or multiple libraries installed try: from .build_and_package_info import cudart_version # noqa: PLC0415 except ImportError: warnings.warn("WARNING: failed to get cudart_version from onnxruntime build info.") cudart_version = None
def print_build_package_info(): warnings.warn(f"onnxruntime training package info: package_name: {package_name}") warnings.warn(f"onnxruntime training package info: __version__: {version}") warnings.warn(f"onnxruntime training package info: cuda_version: {cuda_version}") warnings.warn(f"onnxruntime build info: cudart_version: {cudart_version}")
# collection cuda library info from current environment. from onnxruntime.capi.onnxruntime_collect_build_info import find_cudart_versions # noqa: PLC0415
local_cudart_versions = find_cudart_versions(build_env=False, build_cuda_version=cuda_version) if cudart_version and local_cudart_versions and cudart_version not in local_cudart_versions: print_build_package_info() warnings.warn("WARNING: failed to find cudart version that matches onnxruntime build info") warnings.warn(f"WARNING: found cudart versions: {local_cudart_versions}") except Exception as e: warnings.warn("WARNING: failed to collect onnxruntime version and build info") print(e)
if import_ortmodule_exception: raise import_ortmodule_exception
return has_ortmodule, package_name, version, cuda_version123456789101112131415161718# Copyright (c) Microsoft Corporation. All rights reserved.# Licensed under the MIT License."""Short examples used in the documentation."""
import os
def get_example(name): """ Retrieves the absolute file name of an example. """ this = os.path.abspath(os.path.dirname(__file__)) full = os.path.join(this, name) if not os.path.exists(full): raise FileNotFoundError(f"Unable to find example '{name}'") return full123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778# automatically generated by the FlatBuffers compiler, do not modify
# namespace: CalTableFlatBuffers
import flatbuffersfrom flatbuffers.compat import import_numpy
np = import_numpy()
class KeyValue: __slots__ = ["_tab"]
@classmethod def GetRootAs(cls, buf, offset=0): # noqa: N802 n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) x = KeyValue() x.Init(buf, n + offset) return x
@classmethod def GetRootAsKeyValue(cls, buf, offset=0): # noqa: N802 """This method is deprecated. Please switch to GetRootAs.""" return cls.GetRootAs(buf, offset)
# KeyValue def Init(self, buf, pos): # noqa: N802 self._tab = flatbuffers.table.Table(buf, pos)
# KeyValue def Key(self): # noqa: N802 o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) if o != 0: return self._tab.String(o + self._tab.Pos) return None
# KeyValue def Value(self): # noqa: N802 o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) if o != 0: return self._tab.String(o + self._tab.Pos) return None
def Start(builder): # noqa: N802 builder.StartObject(2)
def KeyValueStart(builder): # noqa: N802 """This method is deprecated. Please switch to Start.""" return Start(builder)
def AddKey(builder, key): # noqa: N802 builder.PrependUOffsetTRelativeSlot(0, flatbuffers.number_types.UOffsetTFlags.py_type(key), 0)
def KeyValueAddKey(builder, key): # noqa: N802 """This method is deprecated. Please switch to AddKey.""" return AddKey(builder, key)
def AddValue(builder, value): # noqa: N802 builder.PrependUOffsetTRelativeSlot(1, flatbuffers.number_types.UOffsetTFlags.py_type(value), 0)
def KeyValueAddValue(builder, value): # noqa: N802 """This method is deprecated. Please switch to AddValue.""" return AddValue(builder, value)
def End(builder): # noqa: N802 return builder.EndObject()
def KeyValueEnd(builder): # noqa: N802 """This method is deprecated. Please switch to End.""" return End(builder)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990# automatically generated by the FlatBuffers compiler, do not modify
# namespace: CalTableFlatBuffers
import flatbuffersfrom flatbuffers.compat import import_numpy
np = import_numpy()
class TrtTable: __slots__ = ["_tab"]
@classmethod def GetRootAs(cls, buf, offset=0): # noqa: N802 n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) x = TrtTable() x.Init(buf, n + offset) return x
@classmethod def GetRootAsTrtTable(cls, buf, offset=0): # noqa: N802 """This method is deprecated. Please switch to GetRootAs.""" return cls.GetRootAs(buf, offset)
# TrtTable def Init(self, buf, pos): # noqa: N802 self._tab = flatbuffers.table.Table(buf, pos)
# TrtTable def Dict(self, j): # noqa: N802 o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) if o != 0: x = self._tab.Vector(o) x += flatbuffers.number_types.UOffsetTFlags.py_type(j) * 4 x = self._tab.Indirect(x) from onnxruntime.quantization.CalTableFlatBuffers.KeyValue import KeyValue # noqa: PLC0415
obj = KeyValue() obj.Init(self._tab.Bytes, x) return obj return None
# TrtTable def DictLength(self): # noqa: N802 o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) if o != 0: return self._tab.VectorLen(o) return 0
# TrtTable def DictIsNone(self): # noqa: N802 o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) return o == 0
def Start(builder): # noqa: N802 builder.StartObject(1)
def TrtTableStart(builder): # noqa: N802 """This method is deprecated. Please switch to Start.""" return Start(builder)
def AddDict(builder, dict): # noqa: N802 builder.PrependUOffsetTRelativeSlot(0, flatbuffers.number_types.UOffsetTFlags.py_type(dict), 0)
def TrtTableAddDict(builder, dict): # noqa: N802 """This method is deprecated. Please switch to AddDict.""" return AddDict(builder, dict)
def StartDictVector(builder, numElems): # noqa: N802 return builder.StartVector(4, numElems, 4)
def TrtTableStartDictVector(builder, numElems): # noqa: N802 """This method is deprecated. Please switch to Start.""" return StartDictVector(builder, numElems)
def End(builder): # noqa: N802 return builder.EndObject()
def TrtTableEnd(builder): # noqa: N802 """This method is deprecated. Please switch to End.""" return End(builder)123456789101112131415161718192021222324from .calibrate import ( # noqa: F401 CalibraterBase, CalibrationDataReader, CalibrationMethod, MinMaxCalibrater, TensorData, TensorsData, create_calibrator, load_tensors_data, save_tensors_data,)from .cuda_quantizer import CudaQuantizer # noqa: F401from .qdq_quantizer import QDQQuantizer # noqa: F401from .quant_utils import QuantFormat, QuantType, write_calibration_table # noqa: F401from .quantize import ( DynamicQuantConfig, # noqa: F401 QuantizationMode, # noqa: F401 StaticQuantConfig, # noqa: F401 get_qdq_config, # noqa: F401 quantize, # noqa: F401 quantize_dynamic, # noqa: F401 quantize_static, # noqa: F401)from .shape_inference import quant_pre_process # noqa: F401123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530# -------------------------------------------------------------------------# Copyright (c) Microsoft Corporation. All rights reserved.# Licensed under the MIT License. See License.txt in the project root for# license information.# --------------------------------------------------------------------------import loggingfrom typing import Any
import numpy as npimport onnximport onnx.numpy_helper
try: from onnx.reference.op_run import to_array_extendedexcept ImportError: # old version of onnx. to_array_extended = None
from .calibrate import TensorDatafrom .onnx_model import ONNXModelfrom .quant_utils import ( DEQUANT_OP_NAME, ONNX_TYPE_TO_NP_TYPE, QUANT_OP_NAME, TENSOR_NAME_QUANT_SUFFIX, find_by_name, get_opset_version, model_has_infer_metadata, normalize_axis, pack_bytes_to_4bit, quantize_data, quantize_nparray, save_and_reload_model_with_shape_infer, tensor_proto_to_array,)from .tensor_quant_overrides import TensorQuantOverridesHelper
class QuantizationParams: def __init__(self, **data: dict[str, Any]): self.data = {} for k, v in data.items(): if not isinstance(k, str): raise TypeError(f"Keys must be strings not {type(k)} for k={k!r}.") if k != "axis" and not isinstance(v, (int, str, np.ndarray, float)): raise TypeError(f"Values must be numpy arrays, int, float, str not {type(v)} for k={k!r}.") if k == "axis" and not isinstance(v, int) and v is not None: raise TypeError(f"Axis value must be an int or None, not {type(v)}.") if k == "scale" and v.dtype not in (np.float32, np.float16): raise ValueError(f"scale must a float32 or float16 numpy element but is {v.dtype} for k={k!r}") self.data[k] = v
def get(self, key, default_value=None): return self.data.get(key, default_value)
def __iter__(self): yield from self.data
def __getitem__(self, key): return self.data[key]
def __setitem__(self, key, value): self.data[key] = value
def __len__(self): return len(self.data)
class BaseQuantizer: def __init__( self, model, per_channel, reduce_range, weight_qType, activation_qType, tensors_range, nodes_to_quantize, nodes_to_exclude, op_types_to_quantize, extra_options=None, ): if not model_has_infer_metadata(model): model = save_and_reload_model_with_shape_infer(model) self.value_infos = {vi.name: vi for vi in model.graph.value_info} self.value_infos.update({ot.name: ot for ot in model.graph.output}) self.value_infos.update({it.name: it for it in model.graph.input})
self.model = ONNXModel(model) self.opset_version = get_opset_version(model) self.per_channel = per_channel # weight-pack per channel self.reduce_range = reduce_range
self.extra_options = extra_options if extra_options else {} self.enable_subgraph_quantization = ( "EnableSubgraph" in self.extra_options and self.extra_options["EnableSubgraph"] ) self.parent = None self.force_quantize_no_input_check = ( "ForceQuantizeNoInputCheck" in self.extra_options and self.extra_options["ForceQuantizeNoInputCheck"] )
# If user does not explicitly set "WeightSymmetric", then the weight's quantization type determines # the symmetry (i.e., signed integer types will use symmetric quantization). See `def is_weight_symmetric()` self._is_weight_symmetric: bool | None = self.extra_options.get("WeightSymmetric", None) self.is_activation_symmetric = self.extra_options.get("ActivationSymmetric", False) self.is_activation_restricted_asymmetric = self.extra_options.get("ActivationRestrictedAsymmetric", False) self.min_real_range = self.extra_options.get("MinimumRealRange")
self.activation_qType = getattr(activation_qType, "tensor_type", activation_qType) self.weight_qType = getattr(weight_qType, "tensor_type", weight_qType)
""" Dictionary specifying the min and max values for tensors. It has following format: { "param_name": [min, max] } example: { 'Conv_3:0': [np.float32(0), np.float32(0.5)], 'Conv_4:0': [np.float32(1), np.float32(3.5)] } """ if tensors_range is not None and any(not isinstance(t, TensorData) for t in tensors_range.values()): raise TypeError( f"tensors_range contains unexpected types { {type(v) for v in tensors_range.values()} }, not TensorData." ) self.tensors_range = tensors_range self.nodes_to_quantize = nodes_to_quantize # specific nodes to quantize self.nodes_to_exclude = nodes_to_exclude # specific nodes to exclude self.op_types_to_quantize = op_types_to_quantize
# Get tensor-level quantization overrides and ensure they are valid. self.tensor_quant_overrides = TensorQuantOverridesHelper(self.extra_options.get("TensorQuantOverrides", {}))
self.initializers = {initzer.name: initzer for initzer in self.model.initializer()} overrides_valid, overrides_err = self.tensor_quant_overrides.is_valid( self.initializers, self.value_infos.keys(), activation_qType ) if not overrides_valid: raise ValueError(overrides_err)
self.tensor_quant_override_qtypes = self.tensor_quant_overrides.get_quant_types()
def is_weight_symmetric(self, weight_quant_type: onnx.TensorProto.DataType) -> bool: if self._is_weight_symmetric is not None: return self._is_weight_symmetric # Return value explicitly set by user. return weight_quant_type in ( onnx.TensorProto.INT4, onnx.TensorProto.INT8, onnx.TensorProto.INT16, onnx.TensorProto.FLOAT8E4M3FN, )
def quantize_model(self): raise NotImplementedError
def is_input_a_initializer(self, input_name): initializer = find_by_name(input_name, self.model.initializer()) return initializer is not None
def is_per_channel(self): return self.per_channel
def is_valid_quantize_weight(self, weight_name): weight = find_by_name(weight_name, self.model.initializer()) if weight is not None: return weight.data_type in (onnx.TensorProto.FLOAT, onnx.TensorProto.FLOAT16) if (not self.enable_subgraph_quantization) or (self.parent is None): return False return self.parent.is_valid_quantize_weight(weight_name)
def should_quantize_node(self, node): if ( self.nodes_to_quantize is not None and len(self.nodes_to_quantize) != 0 and node.name not in self.nodes_to_quantize ): return False
if node.op_type not in self.op_types_to_quantize: return False
if node.op_type in (DEQUANT_OP_NAME, QUANT_OP_NAME): return False
if self.nodes_to_exclude is not None and node.name in self.nodes_to_exclude: return False
return True
def quantize_bias_static_impl(self, bias_name, input_scale, weight_scale, beta=1.0): """ Quantized the bias. Zero Point == 0 and Scale == Input_Scale * Weight_Scale """
# get bias bias_initializer = find_by_name(bias_name, self.model.initializer()) bias_data = tensor_proto_to_array(bias_initializer) quantized_bias_name = bias_name + TENSOR_NAME_QUANT_SUFFIX
# quantize bias if self.weight_qType == onnx.TensorProto.FLOAT8E4M3FN: data = np.asarray(bias_data) if data.dtype == np.float16: node_qtype = onnx.TensorProto.FLOAT16 elif data.dtype == np.float32: node_qtype = onnx.TensorProto.FLOAT else: raise TypeError(f"Only float16 or float32 are supported with float 8 but bias dtype is {data.dtype}.") quantized_data = data.astype(np.float32) bias_scale = np.array([1], dtype=quantized_data.dtype) bias_scale_data = bias_scale.reshape(-1) packed_bias_initializer = onnx.numpy_helper.from_array(quantized_data, quantized_bias_name) self.model.initializer_extend([packed_bias_initializer]) node_type = "Cast" else: # calculate scale for bias # TODO: This formula should be explained including why the scale is not estimated for the bias as well. bias_scale = input_scale * weight_scale * beta
# Quantize by dividing by bias_scale quantized_data = np.asarray(bias_data, dtype=np.float64) / np.asarray(bias_scale, dtype=np.float64) quantized_data = quantized_data.round()
# Clip quantized data to the range of a int32 int32_min = np.float64(np.iinfo(np.int32).min) int32_max = np.float64(np.iinfo(np.int32).max) if np.any(quantized_data < int32_min) or np.any(quantized_data > int32_max): logging.warning( f"Quantized bias `{bias_name}` exceeds the range of a int32. The bias scale is too small." )
quantized_data = np.clip(quantized_data, int32_min, int32_max).astype(np.int32)
# update bias initializer bias_np_data = np.asarray(quantized_data, dtype=np.int32).reshape(bias_initializer.dims) packed_bias_initializer = onnx.numpy_helper.from_array(bias_np_data, quantized_bias_name) self.model.initializer_extend([packed_bias_initializer])
# Bias's scale dtype should match the original bias data's unquantized type (float32 or float16). bias_scale_data = np.asarray(bias_scale, dtype=bias_data.dtype).reshape(-1) node_type = "DequantizeLinear" node_qtype = self.weight_qType
# update scale initializer quantized_bias_scale_name = quantized_bias_name + "_scale" packed_bias_scale_initializer = onnx.numpy_helper.from_array(bias_scale_data, quantized_bias_scale_name) self.model.initializer_extend([packed_bias_scale_initializer])
# update zero initializer if self.weight_qType == onnx.TensorProto.FLOAT8E4M3FN: tensor_type = self.weight_qType else: tensor_type = onnx.TensorProto.INT32
quantized_bias_zp_name = quantized_bias_name + "_zero_point" if self.weight_qType == onnx.TensorProto.FLOAT8E4M3FN: packed_bias_zp_initializer = onnx.helper.make_tensor(quantized_bias_zp_name, self.weight_qType, [1], [0.0]) elif bias_scale.size > 1: bias_zp_data = np.zeros(bias_scale.shape, dtype=np.int32).reshape(-1) packed_bias_zp_initializer = onnx.numpy_helper.from_array(bias_zp_data, quantized_bias_zp_name) else: packed_bias_zp_initializer = onnx.helper.make_tensor(quantized_bias_zp_name, tensor_type, [], [0]) self.model.initializer_extend([packed_bias_zp_initializer])
return ( quantized_bias_name, quantized_bias_scale_name, quantized_bias_zp_name, bias_scale_data, node_type, node_qtype, )
def quantize_initializer_impl(self, weight, qType, reduce_range=False, keep_float_weight=False): """ :param weight: TensorProto initializer :param qType: type to quantize to :param keep_float_weight: Whether to quantize the weight. In some cases, we only want to qunatize scale and zero point. If keep_float_weight is False, quantize the weight, or don't quantize the weight. :return: quantized weight name, zero point name, scale name """ # TODO(adrianlizarraga): This function is now only used by onnx_quantizer.py, so move it there. q_weight_name = weight.name + TENSOR_NAME_QUANT_SUFFIX zp_name = weight.name + "_zero_point" scale_name = weight.name + "_scale"
# Quantize weight data. Use quantization overrides if provided by the user. weight_data = tensor_proto_to_array(weight) quant_overrides = self.tensor_quant_overrides.get_per_tensor_overrides(weight.name, default_val={}) if "quant_type" in quant_overrides: qType = quant_overrides["quant_type"].tensor_type # noqa: N806
if "scale" in quant_overrides and "zero_point" in quant_overrides: zero_point = np.array(quant_overrides["zero_point"], dtype=ONNX_TYPE_TO_NP_TYPE[qType]) scale = np.array(quant_overrides["scale"]) q_weight_data = quantize_nparray(qType, weight_data.flatten(), scale, zero_point) assert isinstance(zero_point, np.ndarray), f"Unexpected type {type(zero_point)}" assert zero_point.dtype != np.float32 and zero_point.dtype != np.float16, ( f"Unexpected dtype {zero_point.dtype}" ) assert isinstance(scale, np.ndarray), f"Unexpected type {type(scale)}"
else: symmetric = self.is_weight_symmetric(qType) if qType == self.weight_qType else self.is_activation_symmetric zero_point, scale, q_weight_data = quantize_data( weight_data.flatten(), qType, quant_overrides.get("symmetric", symmetric), reduce_range=quant_overrides.get("reduce_range", self.reduce_range and reduce_range), min_real_range=self.min_real_range, rmin_override=quant_overrides.get("rmin"), rmax_override=quant_overrides.get("rmax"), )
assert isinstance(zero_point, np.ndarray), f"Unexpected type {type(zero_point)}" assert zero_point.dtype != np.float32 and zero_point.dtype != np.float16, ( f"Unexpected dtype {zero_point.dtype}" ) assert isinstance(scale, np.ndarray), f"Unexpected type {type(scale)}"
scale_dtype = weight.data_type scale_initializer = onnx.helper.make_tensor(scale_name, scale_dtype, [], scale.reshape((-1,)).tolist()) zero_initializer = onnx.helper.make_tensor(zp_name, qType, [], zero_point.reshape((-1,)).tolist()) self.model.initializer_extend([scale_initializer, zero_initializer])
if not keep_float_weight: if self.weight_qType == onnx.TensorProto.FLOAT8E4M3FN: q_weight_initializer = onnx.TensorProto() q_weight_initializer.data_type = self.weight_qType q_weight_initializer.dims.extend(weight.dims) q_weight_initializer.name = q_weight_name # Do not remove .flatten().copy() numpy is not clear about data persistence. q_weight_initializer.raw_data = q_weight_data.flatten().copy().tobytes() if to_array_extended is not None: # This test should not be needed but it helped catch some issues # with data persistence and tobytes. check = to_array_extended(q_weight_initializer) if check.shape != weight_data.shape or check.tobytes() != q_weight_data.tobytes(): raise RuntimeError( f"The initializer of shape {weight_data.shape} could not be created, expecting " f"{q_weight_data.tobytes()[:10]}, got {check.tobytes()[:10]} and shape={weight.shape}" f"\nraw={str(q_weight_initializer)[:200]}." ) elif qType in (onnx.TensorProto.INT4, onnx.TensorProto.UINT4): if q_weight_data.dtype not in (np.int8, np.uint8): raise RuntimeError( f"Quantized weights for {q_weight_name} must be 8-bit before packing as 4-bit values." )
# We do not use onnx.helper.pack_float32_to_4bit() due to performance. # This can be the difference between a large model taking 30 minutes to quantize vs 5 minutes. packed_data = bytes(pack_bytes_to_4bit(q_weight_data.tobytes()))
# We only use onnx.helper.make_tensor with raw data due to bug: https://github.com/onnx/onnx/pull/6161 q_weight_initializer = onnx.helper.make_tensor(q_weight_name, qType, weight.dims, packed_data, raw=True) else: q_weight_data = np.asarray(q_weight_data, dtype=onnx.helper.tensor_dtype_to_np_dtype(qType)).reshape( weight.dims ) q_weight_initializer = onnx.numpy_helper.from_array(q_weight_data, q_weight_name) self.model.initializer_extend([q_weight_initializer])
return q_weight_name, zp_name, scale_name
def quantize_weight_per_channel_impl( self, weight_name, weight_qType, channel_axis, reduce_range=True, keep_float_weight=False, ): # TODO(adrianlizarraga): This function is now only used by onnx_quantizer.py, so move it there. initializer = find_by_name(weight_name, self.model.initializer()) if initializer is None: raise ValueError("{} is not an initializer", weight_name)
weights = tensor_proto_to_array(initializer) weights_rank = len(weights.shape) is_axis_valid, axis_norm = normalize_axis(channel_axis, weights_rank) if not is_axis_valid: raise ValueError( f"Weight {weight_name} has a per-channel axis with value {channel_axis} that is " f"out-of-bounds for rank {weights_rank}" )
channel_axis = axis_norm channel_count = weights.shape[channel_axis] quant_overrides_for_channels = self.tensor_quant_overrides.get_per_channel_overrides( weight_name, default_val=[{"axis": channel_axis}] )
num_channel_overrides = len(quant_overrides_for_channels) if num_channel_overrides != 1 and num_channel_overrides != channel_count: raise ValueError( f"Per-channel tensor quantization overrides for {weight_name} must have " f"either 1 or {channel_count} elements in the list of dictionaries." )
is_axis_override_valid, axis_override = normalize_axis(quant_overrides_for_channels[0]["axis"], weights_rank) if not is_axis_override_valid or axis_override != channel_axis: raise ValueError( f"Tensor quantization overrides for {weight_name} specify an unexpected axis. " f"Expected {channel_axis}, but got {quant_overrides_for_channels[0]['axis']}." )
# If user provides per-channel quantization overrides, all channels must use the same quant_type, # axis, symmetric, and reduce_range values. So, just use the first channel's values. if "quant_type" in quant_overrides_for_channels[0]: weight_qType = quant_overrides_for_channels[0]["quant_type"].tensor_type # noqa: N806
symmetric = quant_overrides_for_channels[0].get("symmetric", self.is_weight_symmetric(weight_qType)) reduce_range = quant_overrides_for_channels[0].get("reduce_range", self.reduce_range and reduce_range) zero_point_list = [] scale_list = [] quantized_per_channel_data_list = [] weights_shape = list(weights.shape) reshape_dims = list(weights_shape) # deep copy reshape_dims[channel_axis] = 1 # only one per channel for reshape for i in range(channel_count): per_channel_data = weights.take(i, channel_axis) channel_override_index = i if i < num_channel_overrides else 0 channel_quant_overrides = quant_overrides_for_channels[channel_override_index]
if "scale" in channel_quant_overrides and "zero_point" in channel_quant_overrides: zero_point = np.array(channel_quant_overrides["zero_point"], dtype=ONNX_TYPE_TO_NP_TYPE[weight_qType]) scale = np.array(channel_quant_overrides["scale"]) quantized_per_channel_data = quantize_nparray( weight_qType, per_channel_data.flatten(), scale, zero_point ) assert isinstance(zero_point, np.ndarray), f"Unexpected type {type(zero_point)}" assert zero_point.dtype != np.float32 and zero_point.dtype != np.float16, ( f"Unexpected dtype {zero_point.dtype}" ) assert isinstance(scale, np.ndarray), f"Unexpected type {type(scale)}" assert isinstance(quantized_per_channel_data, np.ndarray), ( f"Unexpected type {type(quantized_per_channel_data)}" )
else: zero_point, scale, quantized_per_channel_data = quantize_data( per_channel_data.flatten(), weight_qType, symmetric, reduce_range=reduce_range, min_real_range=self.min_real_range, rmin_override=channel_quant_overrides.get("rmin"), rmax_override=channel_quant_overrides.get("rmax"), )
assert isinstance(zero_point, np.ndarray), f"Unexpected type {type(zero_point)}" assert zero_point.dtype != np.float32 and zero_point.dtype != np.float16, ( f"Unexpected dtype {zero_point.dtype}" ) assert isinstance(scale, np.ndarray), f"Unexpected type {type(scale)}" assert isinstance(quantized_per_channel_data, np.ndarray), ( f"Unexpected type {type(quantized_per_channel_data)}" )
zero_point_list.append(zero_point) scale_list.append(scale) quantized_per_channel_data_list.append(np.asarray(quantized_per_channel_data).reshape(reshape_dims))
# combine per_channel_data into one quantized_weights = np.concatenate(quantized_per_channel_data_list, channel_axis) q_weight_name = weight_name + TENSOR_NAME_QUANT_SUFFIX zp_name = weight_name + "_zero_point" scale_name = weight_name + "_scale"
# Update packed weight, zero point, and scale initializers zero_scale_shape = [initializer.dims[channel_axis]] scale_initializer = onnx.helper.make_tensor( scale_name, initializer.data_type, zero_scale_shape, np.hstack(scale_list).tolist() ) zero_initializer = onnx.helper.make_tensor( zp_name, weight_qType, zero_scale_shape, np.hstack(zero_point_list).tolist() )
self.model.initializer_extend([scale_initializer, zero_initializer])
if not keep_float_weight: if weight_qType in (onnx.TensorProto.INT4, onnx.TensorProto.UINT4): if quantized_weights.dtype not in (np.int8, np.uint8): raise RuntimeError( f"Quantized weights for {q_weight_name} must be 8-bit before packing as 4-bit values." )
# We do not use onnx.helper.pack_float32_to_4bit() due to performance. # This can be the difference between a large model taking 30 minutes to quantize vs 5 minutes. packed_data = bytes(pack_bytes_to_4bit(quantized_weights.tobytes()))
# We only use onnx.helper.make_tensor with raw data due to bug: https://github.com/onnx/onnx/pull/6161 q_weight_initializer = onnx.helper.make_tensor( q_weight_name, weight_qType, weights_shape, packed_data, raw=True ) self.model.initializer_extend([q_weight_initializer]) else: quantized_weights = np.asarray( quantized_weights, dtype=onnx.helper.tensor_dtype_to_np_dtype(weight_qType), ).reshape(initializer.dims) q_weight_initializer = onnx.numpy_helper.from_array(quantized_weights, q_weight_name) self.model.initializer_extend([q_weight_initializer])
return q_weight_name, zp_name, scale_name
def adjust_tensor_ranges(self): if self.tensors_range is None: return
for node in self.model.nodes(): # adjust tensor_ranges for input of Clip and Relu node if node.op_type in ["Clip", "Relu"]: if not self.should_quantize_node(node): continue if len(self.model.input_name_to_nodes()[node.input[0]]) != 1: continue if node.input[0] not in self.tensors_range or node.output[0] not in self.tensors_range: continue td = self.tensors_range[node.output[0]] if not isinstance(td, TensorData): raise TypeError(f"Unexpected type {type(td)} for {node.output[0]!r}.") self.tensors_range[node.input[0]] = td # Adjust Softmax to range from 0.0 to 1.0 elif node.op_type == "Softmax": if not self.should_quantize_node(node): continue self.tensors_range[node.output[0]] = TensorData(lowest=np.float32(0.0), highest=np.float32(1.0))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353#!/usr/bin/env python# -------------------------------------------------------------------------# Copyright (c) Microsoft, Intel Corporation. All rights reserved.# Licensed under the MIT License. See License.txt in the project root for# license information.# --------------------------------------------------------------------------import abcimport contextlibimport copyimport itertoolsimport jsonimport osimport tempfileimport uuidfrom collections.abc import Sequencefrom enum import Enumfrom pathlib import Path
import numpy as npimport onnxfrom onnx import ModelProto, TensorProto, helper, numpy_helper
import onnxruntime
from .quant_utils import apply_plot, load_model_with_shape_infer, smooth_distribution
def rel_entr(pk: np.ndarray, qk: np.ndarray) -> np.ndarray: """ See https://docs.scipy.org/doc/scipy/reference/generated/scipy.special.rel_entr.html#scipy.special.rel_entr. Python implementation. """ res = np.empty(pk.shape, dtype=pk.dtype) res[:] = pk[:] * np.log(pk[:] / qk[:]) c2 = (pk == 0) & (qk >= 0) res[c2] = 0 c1 = (pk > 0) & (qk > 0) res[~c1] = np.inf return res
def entropy( pk: np.ndarray, qk: np.ndarray, base: float | None = None, axis: int = 0,) -> np.ndarray: """ Simplifeied version of entropy. Source: https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.entropy.html. This avoids taking a dependency on scipy just for this function. """ assert base is None or base > 0, "base={base} must be a positive number or `None`." assert qk is not None, "qk is None"
pk = np.asarray(pk).astype(np.float32) pk = 1.0 * pk / np.sum(pk, axis=axis, keepdims=True)
qk = np.asarray(qk).astype(np.float32) pk, qk = np.broadcast_arrays(pk, qk) qk = 1.0 * qk / np.sum(qk, axis=axis, keepdims=True) vec = rel_entr(pk, qk)
s = np.sum(vec, axis=axis) if base is not None: s /= np.log(base) return s.astype(pk.dtype)
class TensorData: _allowed = frozenset(["avg", "std", "lowest", "highest", "hist", "hist_edges", "bins"]) _floats = frozenset(["avg", "std", "lowest", "highest", "hist_edges"])
def __init__(self, **kwargs): self._attrs = list(kwargs.keys()) for k, v in kwargs.items(): if k not in TensorData._allowed: raise ValueError(f"Unexpected value {k!r} not in {TensorData._allowed}.") if k in TensorData._floats: if not hasattr(v, "dtype"): raise ValueError(f"Unexpected type {type(v)} for k={k!r}") if v.dtype not in (np.float16, np.float32): raise ValueError(f"Unexpected dtype {v.dtype} for k={k!r}") setattr(self, k, v)
@property def range_value(self): if not hasattr(self, "lowest") or not hasattr(self, "highest"): raise AttributeError(f"Attributes 'lowest' and/or 'highest' missing in {dir(self)}.") return (self.lowest, self.highest)
@property def avg_std(self): if not hasattr(self, "avg") or not hasattr(self, "std"): raise AttributeError(f"Attributes 'avg' and/or 'std' missing in {dir(self)}.") return (self.avg, self.std)
def to_dict(self): # This is needed to serialize the data into JSON. data = {k: getattr(self, k) for k in self._attrs} data["CLS"] = self.__class__.__name__ return data
@classmethod def from_dict(cls, d: dict) -> "TensorData": """Reconstruct a TensorData from a dict produced by to_dict().""" kwargs = {} for k, v in d.items(): if k == "CLS": continue value = v if isinstance(value, dict) and value.get("CLS") == "numpy.array": value = np.array(value["data"], dtype=np.dtype(value["dtype"])) elif k in cls._floats and isinstance(value, (int, float)): value = np.array(value, dtype=np.float32) kwargs[k] = value return cls(**kwargs)
class TensorsData: def __init__(self, calibration_method, data: dict[str, TensorData | tuple]): self.calibration_method = calibration_method self.data = {} for k, v in data.items(): if not isinstance(k, str): raise TypeError(f"Keys must be strings not {type(k)}.") if isinstance(v, tuple): if calibration_method == CalibrationMethod.MinMax and len(v) == 2: self.data[k] = TensorData(lowest=v[0], highest=v[1]) continue if len(v) == 4: self.data[k] = TensorData(lowest=v[0], highest=v[1], hist=v[2], bins=v[3]) continue raise TypeError(f"Unexpected tuple for {k:r}, it has {len(v)} elements: {v}.") if not isinstance(v, TensorData): raise TypeError(f"Values must be TensorData not {type(v)}.") self.data[k] = v
def __iter__(self): yield from self.data
def __contains__(self, key): return key in self.data
def __getitem__(self, key): return self.data[key]
def __setitem__(self, key, value): if key not in self.data: raise RuntimeError(f"Only an existing tensor can be modified, {key!r} is not.") self.data[key] = value
def keys(self): return self.data.keys()
def values(self): return self.data.values()
def items(self): return self.data.items()
def to_dict(self): # This is needed to serialize the data into JSON. data = { "CLS": self.__class__.__name__, "data": self.data, "calibration_method": self.calibration_method, } return data
@classmethod def from_dict(cls, d: dict) -> "TensorsData": """Reconstruct a TensorsData from a dict produced by to_dict().""" method_val = d["calibration_method"] if isinstance(method_val, dict) and method_val.get("CLS") == "CalibrationMethod": name = method_val["value"].split(".")[-1] method = CalibrationMethod[name] else: method = method_val reconstructed = {k: TensorData.from_dict(v) for k, v in d["data"].items()} return cls(method, reconstructed)
class CalibrationMethod(Enum): MinMax = 0 Entropy = 1 Percentile = 2 Distribution = 3
class CalibrationDataReader(metaclass=abc.ABCMeta): @classmethod def __subclasshook__(cls, subclass): return (hasattr(subclass, "get_next") and callable(subclass.get_next)) or NotImplemented
@abc.abstractmethod def get_next(self) -> dict: """generate the input data dict for ONNXinferenceSession run""" raise NotImplementedError
def __iter__(self): return self
def __next__(self): result = self.get_next() if result is None: raise StopIteration return result
def __len__(self): raise NotImplementedError
def set_range(self, start_index: int, end_index: int): raise NotImplementedError
class CalibrationCacheEncoder(json.JSONEncoder): """Shared JSON encoder for calibration caches.
Handles numpy ndarrays and numpy scalar types (integer/floating) so calibration JSON output is consistent across ``save_tensors_data`` and ``quant_utils.write_calibration_table``. """
def default(self, obj): if isinstance(obj, (TensorData, TensorsData)): return obj.to_dict() if isinstance(obj, np.ndarray): return {"data": obj.tolist(), "dtype": str(obj.dtype), "CLS": "numpy.array"} if isinstance(obj, CalibrationMethod): return {"CLS": obj.__class__.__name__, "value": str(obj)} if isinstance(obj, np.integer): return int(obj) if isinstance(obj, np.floating): return float(obj) return json.JSONEncoder.default(self, obj)
def save_tensors_data(tensors_data: "TensorsData", path: "str | Path", *, smooth_quant: bool = False) -> None: """Serialize calibration tensor ranges to a JSON file at *path*.
:param smooth_quant: whether the producing run used SmoothQuant. Stored in the cache so a later load can detect a mismatch and recompute. """ path = Path(path) path.parent.mkdir(parents=True, exist_ok=True) fd, tmp_name = tempfile.mkstemp(dir=path.parent, prefix=".calibcache_", suffix=".tmp") try: with os.fdopen(fd, "w") as f: payload = tensors_data.to_dict() payload["smooth_quant"] = smooth_quant json.dump(payload, f, cls=CalibrationCacheEncoder) f.flush() os.replace(tmp_name, path) except BaseException: with contextlib.suppress(FileNotFoundError): os.unlink(tmp_name) raise
def load_tensors_data(path: "str | Path") -> "TensorsData": """Load calibration tensor ranges from a JSON file written by save_tensors_data().""" path = Path(path) if not path.exists(): raise FileNotFoundError(f"Calibration cache not found: {path}") if not path.is_file(): raise ValueError(f"Calibration cache path is not a file: {path}") with path.open("r") as f: d = json.load(f) return TensorsData.from_dict(d)
class CalibraterBase: def __init__( self, model_path: str | Path, op_types_to_calibrate: Sequence[str] | None = None, augmented_model_path="augmented_model.onnx", symmetric=False, use_external_data_format=False, per_channel=False, ): """ :param model_path: ONNX model to calibrate. It should be a model file path :param op_types_to_calibrate: operator types to calibrate. By default, calibrate all the float32/float16 tensors. :param augmented_model_path: save augmented model to this path. :param symmetric: make range of tensor symmetric (central point is 0). :param use_external_data_format: use external data format to store model which size is >= 2Gb. :param per_channel: whether to compute ranges per each channel. """ if isinstance(model_path, str): self.model = load_model_with_shape_infer(Path(model_path)) elif isinstance(model_path, Path): self.model = load_model_with_shape_infer(model_path) else: raise ValueError("model_path should be model path.")
self.op_types_to_calibrate = op_types_to_calibrate self.augmented_model_path = augmented_model_path self.symmetric = symmetric self.use_external_data_format = use_external_data_format self.per_channel = per_channel
self.augment_model = None self.infer_session = None self.execution_providers = ["CPUExecutionProvider"]
def set_execution_providers(self, execution_providers=["CPUExecutionProvider"]): # noqa: B006 """ reset the execution providers to execute the collect_data. It triggers to re-creating inference session. """ self.execution_providers = execution_providers self.create_inference_session()
def create_inference_session(self): """ create an OnnxRuntime InferenceSession. """ sess_options = onnxruntime.SessionOptions() sess_options.graph_optimization_level = onnxruntime.GraphOptimizationLevel.ORT_DISABLE_ALL self.infer_session = onnxruntime.InferenceSession( self.augmented_model_path, sess_options=sess_options, providers=self.execution_providers, )
def select_tensors_to_calibrate(self, model: ModelProto): """ select input/output tensors of candidate nodes to calibrate. returns: tensors (set): set of tensor name. value_infos (dict): tensor name to value info. """ value_infos = {vi.name: vi for vi in model.graph.value_info} value_infos.update({ot.name: ot for ot in model.graph.output}) value_infos.update({it.name: it for it in model.graph.input}) initializer = {init.name for init in model.graph.initializer}
tensors_to_calibrate = set() tensor_type_to_calibrate = {TensorProto.FLOAT, TensorProto.FLOAT16}
for node in model.graph.node: if not self.op_types_to_calibrate or node.op_type in self.op_types_to_calibrate: for tensor_name in itertools.chain(node.input, node.output): if tensor_name in value_infos: vi = value_infos[tensor_name] if ( vi.type.HasField("tensor_type") and (vi.type.tensor_type.elem_type in tensor_type_to_calibrate) and (tensor_name not in initializer) ): tensors_to_calibrate.add(tensor_name)
return tensors_to_calibrate, value_infos
def get_augment_model(self): """ return: augmented onnx model. Call after calling augment_graph """ return self.model
def augment_graph(self): """ abstract method: augment the input model to prepare for collecting data. It will: 1. augment the model to be able to collect desired statistics data 2. save augmented model to augmented_model_paths """ raise NotImplementedError
def collect_data(self, data_reader: CalibrationDataReader): """ abstract method: collect the tensors that will be used for range computation. It can be called multiple times. """ raise NotImplementedError
def compute_data(self) -> TensorsData: """ abstract method: compute data based on the calibration method stored in TensorsData """ raise NotImplementedError
class MinMaxCalibrater(CalibraterBase): def __init__( self, model_path: str | Path, op_types_to_calibrate: Sequence[str] | None = None, augmented_model_path="augmented_model.onnx", symmetric=False, use_external_data_format=False, moving_average=False, averaging_constant=0.01, max_intermediate_outputs=None, per_channel=False, ): """ :param model_path: ONNX model to calibrate. It is a model path :param op_types_to_calibrate: operator types to calibrate. By default, calibrate all the float32/float16 tensors. :param augmented_model_path: save augmented model to this path. :param symmetric: make range of tensor symmetric (central point is 0). :param use_external_data_format: use external data format to store model which size is >= 2Gb :param moving_average: compute the moving average of the minimum and maximum values instead of the global minimum and maximum. :param averaging_constant: constant smoothing factor to use when computing the moving average. :param max_intermediate_outputs: maximum number of intermediate outputs before an intermediate range is computed. :param per_channel: whether to compute ranges per each channel. """ super().__init__( model_path, op_types_to_calibrate=op_types_to_calibrate, augmented_model_path=augmented_model_path, symmetric=symmetric, use_external_data_format=use_external_data_format, per_channel=per_channel, ) self.intermediate_outputs = [] self.calibrate_tensors_range = None self.num_model_outputs = len(self.model.graph.output) self.model_original_outputs = {output.name for output in self.model.graph.output} self.moving_average = moving_average if moving_average and (averaging_constant < 0 or averaging_constant > 1): raise ValueError("Invalid averaging constant, which should not be < 0 or > 1.") self.averaging_constant = averaging_constant self.max_intermediate_outputs = max_intermediate_outputs
def augment_graph(self): """ Adds ReduceMin and ReduceMax nodes to all quantization_candidates op type nodes in model and ensures their outputs are stored as part of the graph output :return: augmented ONNX model """ tensors, _ = self.select_tensors_to_calibrate(self.model) reshape_shape_name = str(uuid.uuid4()) reshape_shape = numpy_helper.from_array(np.array([-1], dtype=np.int64), reshape_shape_name) self.model.graph.initializer.append(reshape_shape)
def get_op_version(op_type, model): for opset_import in model.opset_import: if onnx.defs.has(op_type, opset_import.domain): return opset_import.version raise RuntimeError(f"Model does not contain a version for '{op_type}'.")
def insert_nodes(tensor_name, new_nodes): index = next( (i for i, x in enumerate(self.model.graph.node) if tensor_name in x.input), len(self.model.graph.node) ) for node in new_nodes: self.model.graph.node.insert(index, node) index += 1
def add_reduce_min_max(tensor_name, reduce_op_name): # When doing ReduceMax/ReduceMin, ORT can't reduce on dim with value of 0 if 'keepdims' is false. # To make the code simple, we always let keepdims to be 1. keepdims = 1
# Adding ReduceMin/ReduceMax nodes: ReduceMin/ReduceMax -> Reshape-> (output) reduce_output = tensor_name + "_" + reduce_op_name intermediate_output = reduce_output + "_Reshape" reduce_node = onnx.helper.make_node( reduce_op_name, [tensor_name], [intermediate_output], keepdims=keepdims, name=reduce_output )
reshape_node = onnx.helper.make_node( "Reshape", inputs=[intermediate_output, reshape_shape_name], outputs=[reduce_output], name=intermediate_output, )
value_infos = {vi.name: vi for vi in self.model.graph.value_info} value_infos.update({o.name: o for o in self.model.graph.output}) value_infos.update({i.name: i for i in self.model.graph.input}) if tensor_name in value_infos: onnx_type = value_infos[tensor_name].type.tensor_type.elem_type else: raise ValueError( f"Unable to guess tensor type for tensor {tensor_name!r}, " "running shape inference before quantization may resolve this issue." )
# Include axes in reduce_op when per_channel, always keeping axis=1 if self.per_channel: tensor_rank = len(value_infos[tensor_name].type.tensor_type.shape.dim) reduced_axes = [0, *range(2, tensor_rank)] # Depending on opset version, axes in ReduceMin/ReduceMax are in attribute or inputs if get_op_version(reduce_op_name, self.model) < 18: reduce_node.attribute.append(helper.make_attribute("axes", reduced_axes)) else: reduce_axes_name = str(uuid.uuid4()) reduce_axes = numpy_helper.from_array(np.array(reduced_axes, dtype=np.int64), reduce_axes_name) reduce_node.input.append(reduce_axes_name) self.model.graph.initializer.append(reduce_axes)
insert_nodes(tensor_name, [reduce_node, reshape_node]) self.model.graph.output.append(helper.make_tensor_value_info(reduce_output, onnx_type, [None]))
for tensor in tensors: add_reduce_min_max(tensor, "ReduceMin") add_reduce_min_max(tensor, "ReduceMax")
onnx.save( self.model, self.augmented_model_path, save_as_external_data=self.use_external_data_format, )
def clear_collected_data(self): self.intermediate_outputs = []
def collect_data(self, data_reader: CalibrationDataReader): while True: inputs = data_reader.get_next() if not inputs: break self.intermediate_outputs.append( [ value if sess_o.name not in self.model_original_outputs else None for sess_o, value in zip( self.infer_session.get_outputs(), self.infer_session.run(None, inputs), strict=False ) ] ) if ( self.max_intermediate_outputs is not None and len(self.intermediate_outputs) == self.max_intermediate_outputs ): self.clear_collected_data()
if len(self.intermediate_outputs) == 0 and self.calibrate_tensors_range is None: raise ValueError("No data is collected.")
t = self.compute_data() if not isinstance(t, TensorsData): raise TypeError(f"compute_data must return a TensorsData not {type(t)}.") self.clear_collected_data()
def merge_range(self, old_range, new_range): if not old_range: return new_range
for key, value in old_range.items(): # Handling for structured data types with TensorData if isinstance(value, TensorData): old_min = value.range_value[0] old_max = value.range_value[1] else: old_min, old_max = value
if isinstance(new_range[key], TensorData): new_min = new_range[key].range_value[0] new_max = new_range[key].range_value[1] else: new_min, new_max = new_range[key]
if self.moving_average: min_value = old_min + self.averaging_constant * (new_min - old_min) max_value = old_max + self.averaging_constant * (new_max - old_max) else: min_value = min(old_min, new_min) max_value = max(old_max, new_max)
# If structured as TensorData, wrap the result accordingly if isinstance(value, TensorData) or isinstance(new_range[key], TensorData): new_range[key] = TensorData(lowest=min_value, highest=max_value) else: new_range[key] = (min_value, max_value)
return new_range
def compute_data(self) -> TensorsData: """ Compute the min-max range of tensor :return: dictionary mapping: {added node names: (ReduceMin, ReduceMax) pairs } """
if len(self.intermediate_outputs) == 0: return self.calibrate_tensors_range
output_names = [self.infer_session.get_outputs()[i].name for i in range(len(self.intermediate_outputs[0]))] output_dicts_list = [ dict(zip(output_names, intermediate_output, strict=False)) for intermediate_output in self.intermediate_outputs ]
merged_output_dict = {} for d in output_dicts_list: for k, v in d.items(): merged_output_dict.setdefault(k, []).append(v) added_output_names = output_names[self.num_model_outputs :] calibrate_tensor_names = [ added_output_names[i].rpartition("_")[0] for i in range(0, len(added_output_names), 2) ] # output names
merged_added_output_dict = { i: merged_output_dict[i] for i in merged_output_dict if i not in self.model_original_outputs }
pairs = [] for i in range(0, len(added_output_names), 2): if self.moving_average: min_value_array = np.nanmean(merged_added_output_dict[added_output_names[i]], axis=0) max_value_array = np.nanmean(merged_added_output_dict[added_output_names[i + 1]], axis=0) else: min_value_array = np.nanmin(merged_added_output_dict[added_output_names[i]], axis=0) max_value_array = np.nanmax(merged_added_output_dict[added_output_names[i + 1]], axis=0)
if self.symmetric: max_absolute_value = np.nanmax([np.abs(min_value_array), np.abs(max_value_array)], axis=0) pairs.append((-max_absolute_value, max_absolute_value)) else: pairs.append((min_value_array, max_value_array))
new_calibrate_tensors_range = TensorsData( CalibrationMethod.MinMax, dict(zip(calibrate_tensor_names, pairs, strict=False)) ) if self.calibrate_tensors_range: self.calibrate_tensors_range = self.merge_range(self.calibrate_tensors_range, new_calibrate_tensors_range) else: self.calibrate_tensors_range = new_calibrate_tensors_range
return self.calibrate_tensors_range
class HistogramCalibrater(CalibraterBase): def __init__( self, model_path: str | Path, op_types_to_calibrate: Sequence[str] | None = None, augmented_model_path="augmented_model.onnx", use_external_data_format=False, method="percentile", symmetric=False, num_bins=128, num_quantized_bins=2048, percentile=99.999, scenario="same", ): """ :param model_path: ONNX model to calibrate. It is a model path. :param op_types_to_calibrate: operator types to calibrate. By default, calibrate all the float32/float16 tensors. :param augmented_model_path: save augmented model to this path. :param use_external_data_format: use external data format to store model which size is >= 2Gb :param method: A string. One of ['entropy', 'percentile']. :param symmetric: make range of tensor symmetric (central point is 0). :param num_bins: number of bins to create a new histogram for collecting tensor values. :param num_quantized_bins: number of quantized bins. Default 128. :param percentile: A float number between [0, 100]. Default 99.99. :param scenario: see :class:`DistributionCalibrater` """ super().__init__( model_path, op_types_to_calibrate=op_types_to_calibrate, augmented_model_path=augmented_model_path, symmetric=symmetric, use_external_data_format=use_external_data_format, ) self.intermediate_outputs = [] self.calibrate_tensors_range = None self.num_model_outputs = len(self.model.graph.output) self.model_original_outputs = {output.name for output in self.model.graph.output} self.collector = None self.method = method self.num_bins = num_bins self.num_quantized_bins = num_quantized_bins self.percentile = percentile self.tensors_to_calibrate = None self.scenario = scenario
def augment_graph(self): """ make all quantization_candidates op type nodes as part of the graph output. :return: augmented ONNX model """ self.tensors_to_calibrate, value_infos = self.select_tensors_to_calibrate(self.model) for tensor in self.tensors_to_calibrate: if tensor not in self.model_original_outputs: self.model.graph.output.append(value_infos[tensor])
onnx.save( self.model, self.augmented_model_path, save_as_external_data=self.use_external_data_format, )
def clear_collected_data(self): self.intermediate_outputs = []
def collect_data(self, data_reader: CalibrationDataReader): """ Entropy Calibrator collects operators' tensors as well as generates tensor histogram for each operator. """ input_names_set = {node_arg.name for node_arg in self.infer_session.get_inputs()} output_names = [node_arg.name for node_arg in self.infer_session.get_outputs()]
while True: inputs = data_reader.get_next() if not inputs: break outputs = self.infer_session.run(None, inputs)
# Copy np.ndarray only for graph outputs that are also graph inputs to workaround bug: # https://github.com/microsoft/onnxruntime/issues/21922 fixed_outputs = [] for output_index, output in enumerate(outputs): if output_names[output_index] in input_names_set: fixed_outputs.append(copy.copy(output)) else: fixed_outputs.append(output)
self.intermediate_outputs.append(fixed_outputs)
if len(self.intermediate_outputs) == 0: raise ValueError("No data is collected.")
output_dicts_list = [ dict(zip(output_names, intermediate_output, strict=False)) for intermediate_output in self.intermediate_outputs ]
merged_dict = {} for d in output_dicts_list: for k, v in d.items(): merged_dict.setdefault(k, []).append(v)
clean_merged_dict = {i: merged_dict[i] for i in merged_dict if i in self.tensors_to_calibrate}
if not self.collector: self.collector = HistogramCollector( method=self.method, symmetric=self.symmetric, num_bins=self.num_bins, num_quantized_bins=self.num_quantized_bins, percentile=self.percentile, scenario=self.scenario, ) self.collector.collect(clean_merged_dict)
self.clear_collected_data()
def compute_data(self) -> TensorsData: """ Compute the min-max range of tensor :return: dictionary mapping: {tensor name: (min value, max value)} """ if not self.collector: raise ValueError("No collector created and can't generate calibration data.")
if isinstance(self, EntropyCalibrater): cal = CalibrationMethod.Entropy elif isinstance(self, PercentileCalibrater): cal = CalibrationMethod.Percentile elif isinstance(self, DistributionCalibrater): cal = CalibrationMethod.Distribution else: raise TypeError(f"Unknown calibrater {type(self)}. This method must be overwritten.") return TensorsData(cal, self.collector.compute_collection_result())
class EntropyCalibrater(HistogramCalibrater): def __init__( self, model_path: str | Path, op_types_to_calibrate: Sequence[str] | None = None, augmented_model_path="augmented_model.onnx", use_external_data_format=False, method="entropy", symmetric=False, num_bins=128, num_quantized_bins=128, ): """ :param model_path: ONNX model to calibrate. It is a model path :param op_types_to_calibrate: operator types to calibrate. By default, calibrate all the float32/float16 tensors. :param augmented_model_path: save augmented model to this path. :param use_external_data_format: use external data format to store model which size is >= 2Gb :param method: A string. One of ['entropy', 'percentile', 'distribution']. :param symmetric: make range of tensor symmetric (central point is 0). :param num_bins: number of bins to create a new histogram for collecting tensor values. :param num_quantized_bins: number of quantized bins. Default 128. """ super().__init__( model_path, op_types_to_calibrate, augmented_model_path, use_external_data_format, method=method, symmetric=symmetric, num_bins=num_bins, num_quantized_bins=num_quantized_bins, )
class PercentileCalibrater(HistogramCalibrater): def __init__( self, model_path: str | Path, op_types_to_calibrate: Sequence[str] | None = None, augmented_model_path="augmented_model.onnx", use_external_data_format=False, method="percentile", symmetric=False, num_bins=2048, percentile=99.999, ): """ :param model_path: ONNX model to calibrate. It is a model path :param op_types_to_calibrate: operator types to calibrate. By default, calibrate all the float32/float16 tensors. :param augmented_model_path: save augmented model to this path. :param use_external_data_format: use external data format to store model which size is >= 2Gb :param method: A string. One of ['entropy', 'percentile', 'distribution']. :param symmetric: make range of tensor symmetric (central point is 0). :param num_quantized_bins: number of quantized bins. Default 128. :param percentile: A float number between [0, 100]. Default 99.99. """ super().__init__( model_path, op_types_to_calibrate, augmented_model_path, use_external_data_format, method=method, symmetric=symmetric, num_bins=num_bins, percentile=percentile, )
class DistributionCalibrater(HistogramCalibrater): def __init__( self, model_path: str | Path, op_types_to_calibrate: Sequence[str] | None = None, augmented_model_path="augmented_model.onnx", use_external_data_format=False, method="distribution", num_bins=128, scenario="same", ): """ :param model_path: ONNX model to calibrate. It is a model path :param op_types_to_calibrate: operator types to calibrate. By default, calibrate all the float32/float16 tensors. :param augmented_model_path: save augmented model to this path. :param use_external_data_format: use external data format to store model which size is >= 2Gb :param method: A string. One of ['entropy', 'percentile', 'distribution']. :param symmetric: make range of tensor symmetric (central point is 0). :param num_bins: number of bins to create a new histogram for collecting tensor values. :param scenario: for float 8 only, if `scenario="same"`, the algorithm weights and float 8 follow the same distribution, if `scenario="p3"`, it assumes the weights follow a gaussian law and float 8 ~ X^3 where X is a gaussian law """ super().__init__( model_path, op_types_to_calibrate, augmented_model_path, use_external_data_format, method=method, num_bins=num_bins, scenario=scenario, )
class CalibrationDataCollector(metaclass=abc.ABCMeta): """ Base class for collecting data for calibration-based quantization. """
@abc.abstractmethod def collect(self, name_to_arr): """ Generate informative data based on given data. name_to_arr : dict tensor name to NDArray data """ raise NotImplementedError
@abc.abstractmethod def compute_collection_result(self): """ Get the optimal result among collection data. """ raise NotImplementedError
class HistogramCollector(CalibrationDataCollector): """ Collecting histogram for each tensor. Percentile and Entropy method are supported.
ref: https://github.com//apache/incubator-mxnet/blob/master/python/mxnet/contrib/quantization.py ref: https://docs.nvidia.com/deeplearning/tensorrt/pytorch-quantization-toolkit/docs/_modules/ pytorch_quantization/calib/histogram.html """
def __init__(self, method, symmetric, num_bins, num_quantized_bins, percentile, scenario): self.histogram_dict = {} self.method = method self.symmetric = symmetric self.num_bins = num_bins self.num_quantized_bins = num_quantized_bins self.percentile = percentile self.scenario = scenario
def get_histogram_dict(self): return self.histogram_dict
def collect(self, name_to_arr): print("Collecting tensor data and making histogram ...")
# TODO: Currently we have different collect() for entropy and percentile method respectively. # Need unified collect in the future. if self.method in {"distribution", "entropy"}: return self.collect_value(name_to_arr) elif self.method == "percentile": if self.symmetric: return self.collect_absolute_value(name_to_arr) else: return self.collect_value(name_to_arr) else: raise ValueError("Only 'entropy', 'percentile' or 'distribution' methods are supported")
def collect_absolute_value(self, name_to_arr): """ Collect histogram on absolute value """ for tensor, data_arr in name_to_arr.items(): if isinstance(data_arr, list): for arr in data_arr: assert isinstance(arr, np.ndarray), f"Unexpected type {type(arr)} for tensor={tensor!r}" dtypes = {a.dtype for a in data_arr} assert len(dtypes) == 1, ( f"The calibration expects only one element type but got {dtypes} for tensor={tensor!r}" ) data_arr_np = np.asarray(data_arr) elif not isinstance(data_arr, np.ndarray): raise ValueError(f"Unexpected type {type(data_arr)} for tensor={tensor!r}") else: data_arr_np = data_arr data_arr_np = data_arr_np.flatten() if data_arr_np.size > 0: min_value = np.nanmin(data_arr_np) max_value = np.nanmax(data_arr_np) else: min_value = np.array(0, dtype=data_arr_np.dtype) max_value = np.array(0, dtype=data_arr_np.dtype)
data_arr_np = np.absolute(data_arr_np) # only consider absolute value
if tensor not in self.histogram_dict: # first time it uses num_bins to compute histogram. hist, hist_edges = np.histogram(data_arr_np, bins=self.num_bins) hist_edges = hist_edges.astype(data_arr_np.dtype) assert data_arr_np.dtype != np.float64, ( "only float32 or float16 is supported, every constant must be explicitly typed" ) self.histogram_dict[tensor] = (hist, hist_edges, min_value, max_value) else: old_histogram = self.histogram_dict[tensor] old_min = old_histogram[2] old_max = old_histogram[3] assert hasattr(old_min, "dtype"), f"old_min should be a numpy array but is {type(old_min)}" assert hasattr(old_max, "dtype"), f"old_min should be a numpy array but is {type(old_max)}" old_hist = old_histogram[0] old_hist_edges = old_histogram[1] temp_amax = np.nanmax(data_arr_np) if temp_amax > old_hist_edges[-1]: # increase the number of bins width = old_hist_edges[1] - old_hist_edges[0] # NOTE: np.arange may create an extra bin after the one containing temp_amax new_bin_edges = np.arange(old_hist_edges[-1] + width, temp_amax + width, width) old_hist_edges = np.hstack((old_hist_edges, new_bin_edges)) hist, hist_edges = np.histogram(data_arr_np, bins=old_hist_edges) hist_edges = hist_edges.astype(data_arr_np.dtype) hist[: len(old_hist)] += old_hist assert data_arr_np.dtype != np.float64, ( "only float32 or float16 is supported, every constant must be explicitly typed" ) self.histogram_dict[tensor] = (hist, hist_edges, min(old_min, min_value), max(old_max, max_value))
def collect_value(self, name_to_arr): """ Collect histogram on real value """ for tensor, data_arr in name_to_arr.items(): data_arr = np.asarray(data_arr) # noqa: PLW2901 data_arr = data_arr.flatten() # noqa: PLW2901
if data_arr.size > 0: min_value = np.nanmin(data_arr) max_value = np.nanmax(data_arr) else: min_value = np.array(0, dtype=data_arr.dtype) max_value = np.array(0, dtype=data_arr.dtype)
threshold = np.array(max(abs(min_value), abs(max_value)), dtype=data_arr.dtype)
if tensor in self.histogram_dict: old_histogram = self.histogram_dict[tensor] self.histogram_dict[tensor] = self.merge_histogram( old_histogram, data_arr, min_value, max_value, threshold ) else: hist, hist_edges = np.histogram(data_arr, self.num_bins, range=(-threshold, threshold)) self.histogram_dict[tensor] = ( hist, hist_edges, min_value, max_value, threshold, )
def merge_histogram(self, old_histogram, data_arr, new_min, new_max, new_threshold): (old_hist, old_hist_edges, old_min, old_max, old_threshold) = old_histogram
if new_threshold <= old_threshold: new_hist, _ = np.histogram(data_arr, len(old_hist), range=(-old_threshold, old_threshold)) return ( new_hist + old_hist, old_hist_edges, min(old_min, new_min), max(old_max, new_max), old_threshold, ) else: if old_threshold == 0: hist, hist_edges = np.histogram(data_arr, len(old_hist), range=(-new_threshold, new_threshold)) hist += old_hist else: old_num_bins = len(old_hist) old_stride = 2 * old_threshold / old_num_bins half_increased_bins = int((new_threshold - old_threshold) // old_stride + 1) new_num_bins = old_num_bins + 2 * half_increased_bins new_threshold = half_increased_bins * old_stride + old_threshold hist, hist_edges = np.histogram(data_arr, new_num_bins, range=(-new_threshold, new_threshold)) hist[half_increased_bins : new_num_bins - half_increased_bins] += old_hist return ( hist, hist_edges, min(old_min, new_min), max(old_max, new_max), new_threshold, )
def compute_collection_result(self): if not self.histogram_dict or len(self.histogram_dict) == 0: raise ValueError("Histogram has not been collected. Please run collect() first.") print(f"Finding optimal threshold for each tensor using {self.method!r} algorithm ...")
if self.method == "entropy": return self.compute_entropy() elif self.method == "percentile": return self.compute_percentile() elif self.method == "distribution": return self.compute_distribution() else: raise ValueError("Only 'entropy', 'percentile' or 'distribution' methods are supported")
def compute_percentile(self): if self.percentile < 0 or self.percentile > 100: raise ValueError("Invalid percentile. Must be in range 0 <= percentile <= 100.")
histogram_dict = self.histogram_dict percentile = self.percentile
thresholds_dict = {} # per tensor thresholds
print(f"Number of tensors : {len(histogram_dict)}") print(f"Number of histogram bins : {self.num_bins}") print(f"Percentile : ({100.0 - percentile},{percentile})")
for tensor, histogram in histogram_dict.items(): hist = histogram[0] hist_edges = histogram[1] total = hist.sum() cdf = np.cumsum(hist / total) if self.symmetric: idx_right = np.searchsorted(cdf, percentile / 100.0)
thresholds_dict[tensor] = ( -np.array(hist_edges[idx_right], dtype=hist_edges.dtype), np.array(hist_edges[idx_right], dtype=hist_edges.dtype), ) else: percent_to_cut_one_side = (100.0 - percentile) / 200.0 idx_right = np.searchsorted(cdf, 1.0 - percent_to_cut_one_side) idx_left = np.searchsorted(cdf, percent_to_cut_one_side) thresholds_dict[tensor] = ( np.array(hist_edges[idx_left], dtype=hist_edges.dtype), np.array(hist_edges[idx_right], dtype=hist_edges.dtype), ) min_value = histogram[2] max_value = histogram[3] if thresholds_dict[tensor][0] < min_value: thresholds_dict[tensor] = (min_value, thresholds_dict[tensor][1]) if thresholds_dict[tensor][1] > max_value: thresholds_dict[tensor] = (thresholds_dict[tensor][0], max_value) thresholds_dict[tensor] = (*thresholds_dict[tensor], *hist[:2]) # Plot histogram for debug only if os.environ.get("QUANTIZATION_DEBUG", "0") in (1, "1"): apply_plot(hist, hist_edges)
return thresholds_dict
def compute_entropy(self): histogram_dict = self.histogram_dict num_quantized_bins = self.num_quantized_bins
thresholds_dict = {} # per tensor thresholds
print(f"Number of tensors : {len(histogram_dict)}") print(f"Number of histogram bins : {self.num_bins} (The number may increase depends on the data it collects)") print(f"Number of quantized bins : {self.num_quantized_bins}")
for tensor, histogram in histogram_dict.items(): optimal_threshold = self.get_entropy_threshold(histogram, num_quantized_bins) thresholds_dict[tensor] = optimal_threshold thresholds_dict[tensor] = (*optimal_threshold, *histogram[:2])
# Plot histogram for debug only if os.environ.get("QUANTIZATION_DEBUG", "0") in (1, "1"): apply_plot(histogram[0], histogram[1])
return thresholds_dict
@staticmethod def _avg_std(hist, hist_edges, power=1): if power <= 0: raise ValueError(f"power={power} <= 0 is invalid.") values = (hist_edges[:-1] + hist_edges[1:]) * 0.5 if power == 1: avg = (hist * values).sum() / hist.sum() std = ((hist * values**2).sum() / hist.sum() - avg**2) ** 0.5 return np.array(avg, dtype=hist_edges.dtype), np.array(std, dtype=hist_edges.dtype) if int(power) == power and int(power) % 2 == 1: avg = (hist * values**power).sum() / hist.sum() std = ((hist * (values**power - avg) ** 2).sum() / hist.sum()) ** 0.5 return np.array(avg, dtype=hist_edges.dtype), np.array(std, dtype=hist_edges.dtype)
fact = np.abs(values) / values fact[np.isnan(fact)] = 1 fact[np.isinf(fact)] = 1 values = np.abs(values) ** power * fact avg = (hist * values).sum() / hist.sum() std = ((hist * values**2).sum() / hist.sum() - avg**2) ** 0.5 return np.array(avg, dtype=hist_edges.dtype), np.array(std, dtype=hist_edges.dtype)
def compute_distribution(self): if self.num_bins < 512: raise ValueError("Invalid num_bins. Must be in range 512 <= num_bins.")
histogram_dict = self.histogram_dict thresholds_dict = {} # per tensor thresholds
print(f"Number of tensors : {len(histogram_dict)}") print(f"Number of histogram bins : {self.num_bins}") print(f"Scenario : {self.scenario!r})")
for tensor, histogram in histogram_dict.items(): hist = histogram[0] hist_edges = histogram[1]
assert hist_edges.dtype != np.float64 if self.scenario == "same": avg_coef, std_coef = self._avg_std(hist, hist_edges, power=1) elif self.scenario == "p3": avg_coef, std_coef = self._avg_std(hist, hist_edges, power=1.0 / 3.0) else: raise ValueError("Invalid scenario. Must be in {'same', 'p3'}.") assert avg_coef.dtype != np.float64 assert std_coef.dtype != np.float64 assert hist_edges.dtype != np.float64 thresholds_dict[tensor] = TensorData( avg=avg_coef, std=std_coef, hist=hist, hist_edges=hist_edges, lowest=hist_edges.min(), highest=hist_edges.max(), )
# Plot histogram for debug only if os.environ.get("QUANTIZATION_DEBUG", "0") in (1, "1"): apply_plot(hist, hist_edges)
return thresholds_dict
def get_entropy_threshold(self, histogram, num_quantized_bins): """Given a dataset, find the optimal threshold for quantizing it. The reference distribution is `q`, and the candidate distribution is `p`. `q` is a truncated version of the original distribution. Ref: http://on-demand.gputechconf.com/gtc/2017/presentation/s7310-8-bit-inference-with-tensorrt.pdf """ hist = histogram[0] hist_edges = histogram[1] num_bins = hist.size zero_bin_index = num_bins // 2 num_half_quantized_bin = num_quantized_bins // 2
dtype = histogram[1].dtype kl_divergence = np.zeros(zero_bin_index - num_half_quantized_bin + 1) thresholds = [(np.array(0, dtype=dtype), np.array(0, dtype=dtype)) for i in range(kl_divergence.size)]
# <------------ num bins ----------------> # <--- quantized bins ----> # |======|===========|===========|=======| # zero bin index # ^ ^ # | | # start index end index (start of iteration) # ^ ^ # | | # start index end index ... # ^ ^ # | | # start index end index (end of iteration)
for i in range(num_half_quantized_bin, zero_bin_index + 1, 1): start_index = zero_bin_index - i end_index = min(zero_bin_index + i + 1, num_bins)
thresholds[i - num_half_quantized_bin] = (hist_edges[start_index], hist_edges[end_index])
sliced_distribution = copy.deepcopy(hist[start_index:end_index])
# reference distribution p p = sliced_distribution.copy() # a copy of np array left_outliers_count = sum(hist[:start_index]) right_outliers_count = sum(hist[end_index:]) p[0] += left_outliers_count p[-1] += right_outliers_count
# nonzeros[i] incidates whether p[i] is non-zero nonzeros = (p != 0).astype(np.int64)
# quantize p.size bins into quantized bins (default 128 bins) quantized_bins = np.zeros(num_quantized_bins, dtype=np.int64) num_merged_bins = sliced_distribution.size // num_quantized_bins
# merge bins into quantized bins for index in range(num_quantized_bins): start = index * num_merged_bins end = start + num_merged_bins quantized_bins[index] = sum(sliced_distribution[start:end]) quantized_bins[-1] += sum(sliced_distribution[num_quantized_bins * num_merged_bins :])
# in order to compare p and q, we need to make length of q equals to length of p # expand quantized bins into p.size bins q = np.zeros(p.size, dtype=np.int64) for index in range(num_quantized_bins): start = index * num_merged_bins end = start + num_merged_bins
norm = sum(nonzeros[start:end]) if norm != 0: q[start:end] = quantized_bins[index] / norm
p = smooth_distribution(p) q = smooth_distribution(q) if p is None or q is None: div = np.array(np.inf, dtype=dtype) else: div = np.array(entropy(p, q), dtype=dtype) kl_divergence[i - num_half_quantized_bin] = div
min_kl_divergence_idx = np.argmin(kl_divergence) optimal_threshold = thresholds[min_kl_divergence_idx] min_value = histogram[2] max_value = histogram[3] if optimal_threshold[0] < min_value: optimal_threshold = (min_value, optimal_threshold[1]) if optimal_threshold[1] > max_value: optimal_threshold = (optimal_threshold[0], max_value) assert hasattr(optimal_threshold[0], "dtype") assert hasattr(optimal_threshold[1], "dtype") return optimal_threshold
def create_calibrator( model: str | Path, op_types_to_calibrate: Sequence[str] | None = None, augmented_model_path="augmented_model.onnx", calibrate_method=CalibrationMethod.MinMax, use_external_data_format=False, providers=None, extra_options={}, # noqa: B006): calibrator = None if calibrate_method == CalibrationMethod.MinMax: # default settings for min-max algorithm symmetric = extra_options.get("symmetric", False) moving_average = extra_options.get("moving_average", False) averaging_constant = extra_options.get("averaging_constant", 0.01) max_intermediate_outputs = extra_options.get("max_intermediate_outputs", None) per_channel = extra_options.get("per_channel", False) calibrator = MinMaxCalibrater( model, op_types_to_calibrate, augmented_model_path, use_external_data_format=use_external_data_format, symmetric=symmetric, moving_average=moving_average, averaging_constant=averaging_constant, max_intermediate_outputs=max_intermediate_outputs, per_channel=per_channel, ) elif calibrate_method == CalibrationMethod.Entropy: # default settings for entropy algorithm num_bins = extra_options.get("num_bins", 128) num_quantized_bins = extra_options.get("num_quantized_bins", 128) symmetric = extra_options.get("symmetric", False) calibrator = EntropyCalibrater( model, op_types_to_calibrate, augmented_model_path, use_external_data_format=use_external_data_format, symmetric=symmetric, num_bins=num_bins, num_quantized_bins=num_quantized_bins, ) elif calibrate_method == CalibrationMethod.Percentile: # default settings for percentile algorithm num_bins = extra_options.get("num_bins", 2048) percentile = extra_options.get("percentile", 99.999) symmetric = extra_options.get("symmetric", True) calibrator = PercentileCalibrater( model, op_types_to_calibrate, augmented_model_path, use_external_data_format=use_external_data_format, symmetric=symmetric, num_bins=num_bins, percentile=percentile, )
elif calibrate_method == CalibrationMethod.Distribution: # default settings for percentile algorithm num_bins = extra_options.get("num_bins", 2048) scenario = extra_options.get("scenario", "same")
calibrator = DistributionCalibrater( model, op_types_to_calibrate, augmented_model_path, use_external_data_format=use_external_data_format, num_bins=num_bins, scenario=scenario, )
if calibrator: calibrator.augment_graph() if providers: calibrator.execution_providers = providers calibrator.create_inference_session() return calibrator
raise ValueError(f"Unsupported calibration method {calibrate_method}")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643# -------------------------------------------------------------------------# Copyright (c) Microsoft Corporation. All rights reserved.# Licensed under the MIT License. See License.txt in the project root for# license information.# --------------------------------------------------------------------------
"""CUDA weight-only quantization helpers.
This module contains small Python utilities for producing the weight layoutsconsumed by CUDA weight-only kernels. The blockwise quantizers wrap the same C++pybind entry points used by runtime prepacking, and the mixed-GEMM weight packeris a PyTorch reimplementation of the runtime CUDA packing, so tests and modelbuilders can generate byte-identical quantized weights. The PyTorch packer runson CUDA when a device is available and falls back to CPU otherwise, which is theonly option on platforms where the standalone CUDA packer is not built (Windows).A GPU-gated parity test validates it against that standalone CUDA packer.
Two storage families are exposed:
* raw MatMulNBits blockwise storage, laid out by output channel as ``[N, K/pack]``;* CUDA mixed-GEMM prepacked storage. MatMulNBits prepacked initializers keep the schema shape ``[N, K/block_size, block_size*bits/8]`` and require the node attribute ``weight_prepacked=1``. QMoE/CUTLASS callers use the kernel-facing shape ``[K, N/pack]``.
All public helpers take one logical expert weight matrix with shape ``[N, K]``."""
from __future__ import annotations
import functoolsimport loggingfrom typing import TYPE_CHECKING
import numpy as np
_logger = logging.getLogger(__name__)
if TYPE_CHECKING: import torch
def _get_torch(): """Import torch lazily so importing onnxruntime.quantization does not require torch.""" try: import torch # noqa: PLC0415 except ImportError as e: raise ImportError("CUDA weight-only quantization requires torch. Please install torch to use it.") from e
return torch
def _get_pack_weights_for_cuda_mixed_gemm(): """Return the standalone CUDA mixed-GEMM weight packer (parity oracle).
Production packing uses the PyTorch implementation (``_pack_weights_for_cuda_mixed_gemm``). This standalone packer lives in ``onnxruntime.capi.onnxruntime_cuda_quant_preprocess``, a separate extension module that links the CUDA runtime (built only on non-Windows CUDA builds). It is imported lazily here (never at ``import onnxruntime`` time) and is used by the parity test to validate the PyTorch packer byte-for-byte. """ try: from onnxruntime.capi import onnxruntime_cuda_quant_preprocess as _cuda_quant # noqa: PLC0415 except ImportError as e: raise ImportError( "The standalone CUDA weight packer (onnxruntime_cuda_quant_preprocess) is unavailable; " "it is built only on non-Windows onnxruntime-gpu CUDA builds." ) from e
try: return _cuda_quant.pack_weights_for_cuda_mixed_gemm except AttributeError as e: raise ImportError("onnxruntime_cuda_quant_preprocess is missing pack_weights_for_cuda_mixed_gemm.") from e
def has_cuda_weight_prepacking() -> bool: """Return True if mixed-GEMM weight prepacking is available.
Prepacking is implemented with PyTorch (CUDA when available, CPU otherwise), so it is available whenever torch is importable. Callers use this to skip prepack code paths (and tests) when torch is unavailable. """ try: _get_torch() except ImportError: return False return True
@functools.lru_cache(maxsize=1)def _warn_cpu_prepack_once() -> None: _logger.warning( "CUDA device is not available; packing mixed-GEMM weights on CPU with PyTorch. " "This is correct but significantly slower for large Mixture-of-Experts models. " "Pack on a CUDA-enabled machine for best performance." )
def _prepack_device(): """Pick the torch device for mixed-GEMM weight packing (CUDA if available, else CPU).""" torch = _get_torch() if torch.cuda.is_available(): return torch.device("cuda") _warn_cpu_prepack_once() return torch.device("cpu")
def _preprocess_weights_for_mixed_gemm_torch(tensor, bits: int, sm: int): """PyTorch port of the runtime CUDA ``preprocess_weights_for_mixed_gemm``.
``tensor`` is a signed int8 weight in ``(K, N/pack)`` packed row-major layout on any device. Returns the CUTLASS mixed-GEMM layout with the same shape/dtype/device. This mirrors ``preprocess_weights_for_mixed_gemm_cuda`` (permute_B_rows -> subbyte_transpose -> interleave_column_major -> add_bias_and_interleave) so its output is byte-identical to the standalone CUDA packer, for both the SM80 (Ampere) and SM90 (Hopper) layouts. """ torch = _get_torch() bits_a = 16 # fp16/bf16 activations bits_b = 4 if bits == 4 else 8
if tensor.dim() == 2: tensor = tensor.unsqueeze(0)
permutation_map = { "16_8": [0, 1, 8, 9, 2, 3, 10, 11, 4, 5, 12, 13, 6, 7, 14, 15], "16_4": [ 0, 1, 8, 9, 16, 17, 24, 25, 2, 3, 10, 11, 18, 19, 26, 27, 4, 5, 12, 13, 20, 21, 28, 29, 6, 7, 14, 15, 22, 23, 30, 31, ], } mma_shape_n = 8 b_rows_per_mma = 8 * 16 // bits_b
num_experts, num_rows, num_cols = tensor.shape[0], tensor.shape[1], tensor.shape[2] if num_rows % b_rows_per_mma != 0 or num_cols % mma_shape_n != 0: raise ValueError( f"weight shape (rows={num_rows}, packed_cols={num_cols}) is incompatible with mixed-GEMM " f"packing (rows must be a multiple of {b_rows_per_mma}, packed cols a multiple of {mma_shape_n})." )
# permute_B_rows_for_mixed_gemm if sm < 100: pmap = permutation_map[f"{bits_a}_{bits_b}"] row_idx = [(r // b_rows_per_mma) * b_rows_per_mma + pmap[r % b_rows_per_mma] for r in range(num_rows)] tensor = tensor[:, row_idx, :]
# subbyte_transpose original_shape = tensor.shape if bits_b == 4: u = tensor.view(torch.uint8) high = (u >> 4).permute(0, 2, 1).unsqueeze(2) low = ((u << 4) >> 4).permute(0, 2, 1).unsqueeze(2) merged = torch.cat([low, high], dim=2).reshape(u.shape[0], -1, u.shape[1]) merged = merged[:, :, 0::2] + merged[:, :, 1::2] * 16 tensor = merged.view(torch.int8).reshape(original_shape) else: tensor = tensor.permute(0, 2, 1).reshape(original_shape)
# interleave_column_major_tensor interleave = bits_a // bits_b if interleave > 1 and sm < 90: rows_per_tile = 128 * 8 // bits_a elts_in_int32 = 32 // bits_b if num_rows % elts_in_int32 != 0 or num_rows % rows_per_tile != 0: raise ValueError(f"num_rows ({num_rows}) is incompatible with column-interleave tiling.") tensor = tensor.reshape( num_experts, -1, interleave, num_rows // rows_per_tile, rows_per_tile * 4 // elts_in_int32 ) tensor = tensor.permute(0, 1, 3, 2, 4).reshape(original_shape)
# add_bias_and_interleave_quantized_tensor_inplace if bits_b == 8: t = tensor.to(torch.int64) # widen so the +128 rebias cannot overflow int8 t += -256 * (t > 127).to(torch.int64) + 128 t = t.reshape(-1, 4)[:, [0, 2, 1, 3]].reshape(original_shape) tensor = t.to(torch.uint8).view(torch.int8) else: u = tensor.view(torch.uint8) high = (u >> 4).unsqueeze(-1) low = ((u << 4) >> 4).unsqueeze(-1) merged = torch.cat([low, high], dim=-1).reshape(u.shape[0], u.shape[1], -1) merged = merged.reshape(-1, 8)[:, [0, 2, 4, 6, 1, 3, 5, 7]].reshape(merged.shape) merged = merged.to(torch.int16) merged += -16 * (merged > 7).to(torch.int16) + 8 merged = merged[:, :, 0::2] + merged[:, :, 1::2] * 16 tensor = merged.to(torch.uint8).view(torch.int8)
return tensor.squeeze(0).contiguous()
def _pack_weights_for_cuda_mixed_gemm(q_weights, n: int, k: int, bits: int, force_arch: int = 80) -> np.ndarray: """PyTorch implementation of the CUDA ``pack_weights_for_cuda_mixed_gemm``.
``q_weights`` is ORT's unsigned MatMulNBits/QMoE storage ``(N, K/pack)`` (uint8). Returns a flat ``int8`` numpy array with the CUTLASS mixed-GEMM layout, byte-identical to the standalone CUDA packer. Runs on CUDA when available, otherwise on CPU. """ torch = _get_torch() bits = int(bits) force_arch = int(force_arch) if bits not in (4, 8): raise ValueError(f"bits must be 4 or 8, got {bits}.") if force_arch not in (80, 90): raise ValueError(f"force_arch must be 80 (SM80) or 90 (SM90), got {force_arch}.") pack = 8 // bits device = _prepack_device()
q = torch.as_tensor(np.ascontiguousarray(q_weights)).view(torch.uint8).reshape(n, k // pack).to(device)
# Front-end adaptor: transpose ORT (N, K) -> (K, N) and convert unsigned -> signed int8. if bits == 4: low = (q & 0x0F).to(torch.int16) high = (q >> 4).to(torch.int16) unpacked = torch.empty((n, k), dtype=torch.int16, device=device) unpacked[:, 0::2] = low unpacked[:, 1::2] = high signed_t = (unpacked - 8).transpose(0, 1).contiguous() # (K, N), zero point 8 packed_t = ((signed_t[:, 0::2] & 0x0F) | ((signed_t[:, 1::2] & 0x0F) << 4)).to(torch.uint8).view(torch.int8) else: signed_t = (q.to(torch.int16) - 128).transpose(0, 1).contiguous() # (K, N), zero point 128 packed_t = signed_t.to(torch.uint8).view(torch.int8)
out = _preprocess_weights_for_mixed_gemm_torch(packed_t.contiguous(), bits, force_arch) return out.reshape(-1).cpu().numpy()
def _get_quantize_matmul_nbits(): """Return MatMulNBits blockwise quantizers from the ORT pybind module.""" try: from onnxruntime.capi._pybind_state import ( # noqa: PLC0415 quantize_matmul_4bits, quantize_matmul_8bits, ) except ImportError as e: raise ImportError( "CUDA blockwise quantization requires quantize_matmul_4bits and quantize_matmul_8bits from onnxruntime." ) from e
return quantize_matmul_4bits, quantize_matmul_8bits
class CudaQuantizer: """CUDA quantizer utilities for MoE/QMoE and MatMulNBits-style weight-only kernels.
The methods are stateless; callers may use the class directly without constructing an object. """
@staticmethod def qmoe_symmetric_per_channel_quantize( weights: torch.Tensor, bits: int, *, unsigned_full_range: bool = True, ) -> tuple[torch.Tensor, torch.Tensor]: """Quantize one QMoE expert with symmetric per-channel storage.
``weights`` has logical shape ``[N, K]``. Returns raw QMoE storage ``[N, K/pack]`` and scales ``[N]``. By default, this emits the ORT CUDA QMoE storage contract: unsigned bytes/nibbles with an implicit zero-point offset, so each stored value is ``q + zero_point`` even though the numeric quantization is symmetric. By default it uses the full ``[-8, 7]`` / ``[-128, 127]`` range. Set ``unsigned_full_range=False`` to use the legacy ``[-7, 7]`` / ``[-127, 127]`` range. """ torch = _get_torch()
weights = weights.detach().cpu().to(torch.float32).contiguous() bits = int(bits) if bits not in (4, 8): raise ValueError(f"QMoE per-channel quantization only supports 4 or 8 bits, got {bits}.")
n, k = weights.shape pack = 8 // bits if k % pack != 0: raise ValueError(f"K ({k}) must be divisible by {pack} for QMoE per-channel quantization.")
if bits == 4: if unsigned_full_range: qmin, qmax, scale_divisor, zero_point = -8, 7, 8, 8 else: qmin, qmax, scale_divisor, zero_point = -7, 7, 7, 8 else: # bits == 8, already validated above if unsigned_full_range: qmin, qmax, scale_divisor, zero_point = -128, 127, 128, 128 else: qmin, qmax, scale_divisor, zero_point = -127, 127, 127, 128 scales = weights.abs().amax(dim=1, keepdim=True) / float(scale_divisor) scales = torch.clamp(scales, min=torch.finfo(torch.float32).eps) quantized = torch.clamp(torch.round(weights / scales), qmin, qmax).to(torch.int16).contiguous() quantized = (quantized + zero_point).to(torch.uint8)
if bits == 4: qweight = (quantized[:, 0::2] & 0xF) | ((quantized[:, 1::2] & 0xF) << 4) qweight = qweight.to(torch.uint8) else: qweight = quantized
return qweight.contiguous(), scales.squeeze(-1).contiguous()
@staticmethod def qmoe_per_channel_quantize( weights: torch.Tensor, bits: int, prepack: bool, force_arch: int = 80, *, unsigned_full_range: bool = True, ) -> tuple[torch.Tensor, torch.Tensor]: """Quantize per-channel QMoE weights and optionally CUTLASS-prepack them.
When ``prepack`` is true, returned weights have shape ``[K, N/pack]``. Otherwise, returned weights keep raw per-channel storage ``[N, K/pack]``. Prepacking uses PyTorch (CUDA when available, CPU otherwise). """ torch = _get_torch()
qweight, scales = CudaQuantizer.qmoe_symmetric_per_channel_quantize( weights, bits, unsigned_full_range=unsigned_full_range, ) if not prepack: return qweight, scales
n, k = weights.shape pack = 8 // int(bits) if n % pack != 0: raise ValueError(f"N ({n}) must be divisible by {pack} for CUDA QMoE prepacked weights.")
packed = _pack_weights_for_cuda_mixed_gemm(qweight.numpy(), n, k, int(bits), force_arch) packed = np.asarray(packed).view(np.uint8).reshape(k, n // pack) return torch.from_numpy(np.ascontiguousarray(packed)), scales
@staticmethod def _matmulnbits_blockwise_quantize_impl( weights: torch.Tensor, bits: int, block_size: int, *, symmetric: bool, abs_scales: bool, unsigned_full_range: bool, ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: """Quantize ``weights`` with MatMulNBits pybinds and return unflattened storage.""" torch = _get_torch()
bits = int(bits) block_size = int(block_size) w = weights.detach().cpu().to(torch.float32).contiguous().numpy() n, k = w.shape if bits not in (4, 8): raise ValueError(f"Blockwise quantization only supports 4 or 8 bits, got {bits}.") if block_size <= 0: raise ValueError(f"Blockwise quantization requires a positive block_size, got {block_size}.")
num_blocks = (k + block_size - 1) // block_size pack = 8 // bits blob_size = (block_size + pack - 1) // pack
if symmetric: if bits == 4: qmin, qmax, scale_divisor, zero_point = (-8, 7, 8, 8) if unsigned_full_range else (-7, 7, 7, 8) else: qmin, qmax, scale_divisor, zero_point = ( (-128, 127, 128, 128) if unsigned_full_range else (-127, 127, 127, 128) )
padded_k = num_blocks * block_size if padded_k != k: w = np.pad(w, ((0, 0), (0, padded_k - k)), "constant")
blocked = w.reshape(n, num_blocks, block_size) scales = np.max(np.abs(blocked), axis=2).astype(np.float32) / np.float32(scale_divisor) scales = np.maximum(scales, np.finfo(np.float32).eps) quantized = np.clip(np.rint(blocked / scales[:, :, np.newaxis]), qmin, qmax).astype(np.int16) quantized = (quantized + zero_point).astype(np.uint8)
if bits == 4: qweight = np.zeros((n, num_blocks, blob_size), dtype=np.uint8) qweight[:, :, : quantized[:, :, 0::2].shape[2]] = quantized[:, :, 0::2] & 0xF qweight[:, :, : quantized[:, :, 1::2].shape[2]] |= (quantized[:, :, 1::2] & 0xF) << 4 else: qweight = quantized
zero_points = np.zeros((n, (num_blocks + 1) // 2 if bits == 4 else num_blocks), dtype=np.uint8) return torch.from_numpy(qweight), torch.from_numpy(scales), torch.from_numpy(zero_points)
w_t = np.ascontiguousarray(w.T) qweight = np.zeros((n, num_blocks, blob_size), dtype=np.uint8) scales = np.zeros((n, num_blocks), dtype=np.float32) zero_points = np.zeros((n, (num_blocks + 1) // 2 if bits == 4 else num_blocks), dtype=np.uint8)
quantize_matmul_4bits, quantize_matmul_8bits = _get_quantize_matmul_nbits() quantize = quantize_matmul_4bits if bits == 4 else quantize_matmul_8bits quantize(qweight, w_t, scales, zero_points, block_size, n, k, symmetric)
if abs_scales: scales = np.abs(scales)
return torch.from_numpy(qweight), torch.from_numpy(scales), torch.from_numpy(zero_points)
@staticmethod def matmulnbits_blockwise_quantize( weights: torch.Tensor, bits: int, block_size: int, *, symmetric: bool = True, return_zero_points: bool = False, abs_scales: bool = True, flatten_qweight: bool = True, unsigned_full_range: bool = True, ) -> tuple[torch.Tensor, torch.Tensor] | tuple[torch.Tensor, torch.Tensor, torch.Tensor]: """Quantize one expert with ONNX Runtime's MatMulNBits blockwise encoding.
``weights`` has logical shape ``[N, K]``. Returns raw flattened storage ``[N, ceil(K/block_size)*ceil(block_size/pack)]`` and block scales ``[N, ceil(K/block_size)]`` by default. Set ``flatten_qweight=False`` for the MatMulNBits initializer shape ``[N, ceil(K/block_size), ceil(block_size/pack)]``. Set ``return_zero_points=True`` to also return packed block zero-points. Symmetric quantization uses the full ``[-8, 7]`` / ``[-128, 127]`` range by default. Set ``unsigned_full_range=False`` to use the legacy ``[-7, 7]`` / ``[-127, 127]`` range. """ qweight, scales, zero_points = CudaQuantizer._matmulnbits_blockwise_quantize_impl( weights, bits, block_size, symmetric=symmetric, abs_scales=abs_scales, unsigned_full_range=unsigned_full_range, ) if flatten_qweight: qweight = qweight.reshape(qweight.shape[0], -1).contiguous() if return_zero_points: return qweight, scales, zero_points
return qweight, scales
@staticmethod def matmulnbits_prepacked_blockwise_quantize( weights: torch.Tensor, bits: int, block_size: int, force_arch: int = 80, *, symmetric: bool = True, return_zero_points: bool = False, abs_scales: bool = True, unsigned_full_range: bool = True, ) -> tuple[torch.Tensor, torch.Tensor] | tuple[torch.Tensor, torch.Tensor, torch.Tensor]: """Quantize and CUDA-prepack one MatMulNBits weight initializer.
``weights`` has logical shape ``[N, K]``. Returns ``B`` with the standard MatMulNBits initializer shape ``[N, K/block_size, block_size*bits/8]`` and scales with shape ``[N, K/block_size]``.
The ``force_arch`` value selects the mixed-GEMM weight layout and must match the ``weight_prepacked`` attribute set on the MatMulNBits node:
* ``force_arch=80`` (default): SM80/Ampere layout, consumed by the SM80 kernel (also used on newer GPUs via the compatibility path). Use ``weight_prepacked=1``. * ``force_arch=90``: SM90/Hopper layout, consumed by the native SM90 TMA/WGMMA kernel. Use ``weight_prepacked=2``. Requires ``block_size`` in {64, 128}. """ torch = _get_torch()
bits = int(bits) block_size = int(block_size) force_arch = int(force_arch) if force_arch not in (80, 90): raise ValueError(f"force_arch must be 80 (SM80) or 90 (SM90), but got {force_arch}.") # The native SM90 kernel needs group_size to be a multiple of the 64-element Hopper K tile, # so block_size=32 is only supported by the SM80/Ampere-class kernel. allowed_block_sizes = (32, 64, 128) if force_arch == 80 else (64, 128) if block_size not in allowed_block_sizes: raise ValueError( f"block_size must be one of {allowed_block_sizes} for force_arch={force_arch}, but got {block_size}." ) n, k = weights.shape if k % block_size != 0: raise ValueError(f"K ({k}) must be divisible by block_size ({block_size}) for CUDA-prepacked weights.")
qweight, scales, zero_points = CudaQuantizer._matmulnbits_blockwise_quantize_impl( weights, bits, block_size, symmetric=symmetric, abs_scales=abs_scales, unsigned_full_range=unsigned_full_range, )
pack_weights_for_cuda_mixed_gemm = _pack_weights_for_cuda_mixed_gemm packed = pack_weights_for_cuda_mixed_gemm(qweight.reshape(n, -1).numpy(), n, k, bits, force_arch) packed = np.asarray(packed).view(np.uint8).reshape(qweight.shape) packed = torch.from_numpy(np.ascontiguousarray(packed)) if return_zero_points: return packed, scales, zero_points
return packed, scales
@staticmethod def qmoe_prepacked_blockwise_quantize( weights: torch.Tensor, bits: int, block_size: int, force_arch: int = 80, *, symmetric: bool = True, return_zero_points: bool = False, abs_scales: bool = False, unsigned_full_range: bool = True, ) -> tuple[torch.Tensor, torch.Tensor] | tuple[torch.Tensor, torch.Tensor, torch.Tensor]: """Quantize one expert and CUTLASS-prepack it for CUDA QMoE fpA_intB GEMM.
``weights`` has logical shape ``[N, K]``. Returns ``qweight`` with shape ``[K, N/pack]`` and block scales with shape ``[N, K/block_size]``. Set ``return_zero_points=True`` to also return packed block zero-points. """ bits = int(bits) block_size = int(block_size) n, k = weights.shape pack = 8 // bits if k % block_size != 0: raise ValueError(f"K ({k}) must be divisible by block_size ({block_size}) for CUDA-prepacked weights.") if n % pack != 0: raise ValueError(f"N ({n}) must be divisible by {pack} for QMoE blockwise quantization.")
qweight, scales, zero_points = CudaQuantizer._matmulnbits_blockwise_quantize_impl( weights, bits, block_size, symmetric=symmetric, abs_scales=abs_scales, unsigned_full_range=unsigned_full_range, )
pack_weights_for_cuda_mixed_gemm = _pack_weights_for_cuda_mixed_gemm packed = pack_weights_for_cuda_mixed_gemm(qweight.reshape(n, -1).numpy(), n, k, bits, force_arch) packed = np.asarray(packed).view(np.uint8).reshape(k, n // pack) torch = _get_torch() packed = torch.from_numpy(np.ascontiguousarray(packed)) if return_zero_points: return packed, scales, zero_points
return packed, scales
@staticmethod def symmetric_blockwise_quantize( weights: torch.Tensor, bits: int, block_size: int, *, unsigned_full_range: bool = True, ) -> tuple[torch.Tensor, torch.Tensor]: """Quantize one expert with a pure-PyTorch symmetric blockwise encoding.
This helper is useful for non-CUDA reference paths. Unlike the pybind-backed helpers above, it pads the last dimension when it is not divisible by ``block_size`` and returns storage with the same leading shape as ``weights``. """ torch = _get_torch()
weights = weights.detach().cpu().contiguous() original_shape = weights.shape bits = int(bits) block_size = int(block_size) if bits == 4: qmin, qmax, scale_divisor = (-8, 7, 8) if unsigned_full_range else (-7, 7, 7) elif bits == 8: qmin, qmax, scale_divisor = (-128, 127, 128) if unsigned_full_range else (-127, 127, 127) else: raise ValueError(f"CUDA blockwise quantization only supports 4 or 8 bits, got {bits}.")
last_dim = original_shape[-1] num_blocks = (last_dim + block_size - 1) // block_size pad_size = num_blocks * block_size - last_dim if pad_size > 0: pad_shape = list(original_shape) pad_shape[-1] = pad_size padding = torch.zeros(pad_shape, dtype=weights.dtype, device=weights.device) weights_padded = torch.cat([weights, padding], dim=-1) else: weights_padded = weights
reshaped_weights = weights_padded.view(*original_shape[:-1], num_blocks, block_size) block_max_abs = torch.max(torch.abs(reshaped_weights), dim=-1)[0] scales = torch.clamp(block_max_abs / scale_divisor, min=1e-8)
quantized = torch.round(reshaped_weights / scales.unsqueeze(-1)) quantized = torch.clamp(quantized, qmin, qmax)
if bits == 4: quantized_flat = quantized.to(torch.int8).view(*original_shape[:-1], num_blocks * block_size) if pad_size > 0: quantized_flat = quantized_flat[..., :-pad_size]
quantized_uint4 = (quantized_flat + 8).to(torch.uint8) packed_shape = list(original_shape) packed_shape[-1] = (original_shape[-1] + 1) // 2 qweight = torch.zeros(packed_shape, dtype=torch.uint8, device=weights.device) qweight[..., :] = quantized_uint4[..., 0::2] & 0xF if quantized_uint4.shape[-1] > 1: qweight[..., : quantized_uint4[..., 1::2].shape[-1]] |= (quantized_uint4[..., 1::2] & 0xF) << 4 else: qweight = quantized.to(torch.int8).view(*original_shape[:-1], num_blocks * block_size) if pad_size > 0: qweight = qweight[..., :-pad_size] qweight = qweight.view(original_shape)
return qweight.cpu(), scales.cpu()12from .preprocess import qnn_preprocess_model # noqa: F401from .quant_config import get_qnn_qdq_config # noqa: F401123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132# -------------------------------------------------------------------------# Copyright (c) Microsoft Corporation. All rights reserved.# Licensed under the MIT License. See License.txt in the project root for# license information.# --------------------------------------------------------------------------from __future__ import annotations
import onnx
from ...fusions import Fusionfrom ...onnx_model import ONNXModel
class FusionLpNormalization(Fusion): def __init__(self, model: ONNXModel, epsilon: float = 1e-12): super().__init__(model, "LpNormalization", "ReduceL2") self.epsilon = epsilon
def fuse( self, reduce_node: onnx.NodeProto, input_name_to_nodes: dict[str, list[onnx.NodeProto]], output_name_to_node: dict[str, onnx.NodeProto], ): """ Interface function that tries to fuse a node sequence containing a ReduceL2 node into a single LpNormalization node.
Pattern 1: [root] --> ReduceL2 -----> Clip --> Expand ----> Div --> | (axis=-1) (min=epsilon) (shape=root) ^ | (keepdims=True) | | | +-----------------------------------------------+ Notes: - ReduceL2 must use the last axis, and keepdims == True - Clip must only have a min attribute that is ~1e-12 - Expand must restore the shape to root.shape - The output of Expand must be the second input to Div. """ if reduce_node.output[0] not in input_name_to_nodes: return
# ReduceL2 must have one Clip child children = input_name_to_nodes[reduce_node.output[0]] if len(children) != 1 or children[0].op_type != "Clip": return
# ReduceL2 must have keepdims == True keepdims = self.get_node_attribute(reduce_node, "keepdims") if not keepdims: return
# ReduceL2 axes must refer only to the last dimension. # Axes became an input in opset 18. Before then, axes was an attribute reduce_input_ttype = self.model.get_tensor_type(reduce_node.input[0]) if not reduce_input_ttype: return
reduce_input_shape = self.tensor_shape_to_list(reduce_input_ttype) if not reduce_input_shape: return
axes = self.get_node_attribute(reduce_node, "axes") if not axes and len(reduce_node.input) > 1: axes = self.model.get_constant_value(reduce_node.input[1])
if not axes or len(axes) != 1: return
last_dim = len(reduce_input_shape) - 1 if axes[0] != -1 and axes[0] != last_dim: return
# Clip node must have a min attribute approximately equal to 1e-12 clip_node = children[0] clip_min = self.get_node_attribute(clip_node, "min") if clip_min is None and len(clip_node.input) > 1: clip_min = self.model.get_constant_value(clip_node.input[1])
clip_max = self.get_node_attribute(clip_node, "max") # TODO: clip_max could be FLOAT_MAX if clip_max is None and len(clip_node.input) > 2: clip_max = self.model.get_constant_value(clip_node.input[2])
if not (clip_max is None and clip_min is not None and clip_min > 0 and abs(clip_min - self.epsilon) < 1e-13): return
if clip_node.output[0] not in input_name_to_nodes: return
# Clip must have a single Expand child. children = input_name_to_nodes[clip_node.output[0]] if len(children) != 1 or children[0].op_type != "Expand": return
expand_node = children[0] if expand_node.output[0] not in input_name_to_nodes: return
# Expand must have a single Div child children = input_name_to_nodes[expand_node.output[0]] if len(children) != 1 or children[0].op_type != "Div": return
div_node = children[0]
# The first input to Div must be the root of the subgraph (i.e., reduce_node.input[0]) # The second input to Div must be the output of the Expand. # As long as these two inputs go to the same Div node, then ONNX validation will ensure that # their shapes match. if div_node.input[0] != reduce_node.input[0]: return if div_node.input[1] != expand_node.output[0]: return
subgraph_input = reduce_node.input[0] subgraph_output = div_node.output[0]
subgraph_nodes = [reduce_node, clip_node, expand_node, div_node] if not self.is_safe_to_fuse_nodes(subgraph_nodes, [subgraph_output], input_name_to_nodes, output_name_to_node): return
self.nodes_to_remove.extend(subgraph_nodes) fused_node = onnx.helper.make_node( self.fused_op_type, name=self.create_unique_node_name(), inputs=[subgraph_input], outputs=[subgraph_output], p=2, axis=-1, ) self.nodes_to_add.append(fused_node)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162# -------------------------------------------------------------------------# Copyright (c) Microsoft Corporation. All rights reserved.# Licensed under the MIT License. See License.txt in the project root for# license information.# --------------------------------------------------------------------------"""Define SpaceToDepth fusion."""
import onnx
from ... import fusions, onnx_model
class FusionSpaceToDepth(fusions.Fusion): """Fusion for SpaceToDepth."""
def __init__(self, model: onnx_model.ONNXModel): """Initialize.
Args: model: An onnx_model.ONNXModel instance. """ super().__init__(model, "SpaceToDepth", "Reshape")
def _fuse_yolo( self, node: onnx.NodeProto, input_name_to_nodes: dict[str, list[onnx.NodeProto]], output_name_to_node: dict[str, onnx.NodeProto], ): """Fuse for early version of YOLO.
Pattern:
| [N, C, H, W] Reshape | [N, C, H/blk, blk, W/blk, blk] Transpose | [N, C, H/blk, W/blk, blk, blk] Reshape | [N, C, H/blk * W/blk, blk * blk] Transpose | [N, C, blk * blk, H/blk * W/blk] Reshape | [N, C, blk * blk, H/blk, W/blk] Transpose | [N, blk * blk, C, H/blk, W/blk] Reshape | [N, blk * blk * C, H/blk, W/blk]
This sequence can be fused into a single SpaceToDepth with blocksize `blk`. Note that unlike DepthToSpace supporting DCR or CRD mode, SpaceToDepth only supports DCR mode in its latest opset version (13), which matches the pattern here. """ reshape_node1 = node
def get_target_child(parent_node, target_op_type): """Get target child of given node.""" if parent_node.output[0] not in input_name_to_nodes: return None
children = input_name_to_nodes[parent_node.output[0]] if len(children) > 1 or children[0].op_type != target_op_type: return None
return children[0]
if ( (transpose_node1 := get_target_child(reshape_node1, "Transpose")) is None or (reshape_node2 := get_target_child(transpose_node1, "Reshape")) is None or (transpose_node2 := get_target_child(reshape_node2, "Transpose")) is None or (reshape_node3 := get_target_child(transpose_node2, "Reshape")) is None or (transpose_node3 := get_target_child(reshape_node3, "Transpose")) is None or (reshape_node4 := get_target_child(transpose_node3, "Reshape")) is None ): return False
def get_tensor_shape(tensor_name): """Get shape for given tensor name.""" tensor_type = self.model.get_tensor_type(tensor_name) if not tensor_type: return None
tensor_shape = self.tensor_shape_to_list(tensor_type) if not tensor_shape: return None
return tensor_shape
if ( (input_shape := get_tensor_shape(reshape_node1.input[0])) is None or (reshape_shape1 := get_tensor_shape(reshape_node1.output[0])) is None or (reshape_shape2 := get_tensor_shape(reshape_node2.output[0])) is None or (reshape_shape3 := get_tensor_shape(reshape_node3.output[0])) is None or (reshape_shape4 := get_tensor_shape(reshape_node4.output[0])) is None ): return False
transpose_perm1 = self.get_node_attribute(transpose_node1, "perm") transpose_perm2 = self.get_node_attribute(transpose_node2, "perm") transpose_perm3 = self.get_node_attribute(transpose_node3, "perm")
# Check rank. if ( len(input_shape) != 4 or len(reshape_shape1) != 6 or len(reshape_shape2) != 4 or len(reshape_shape3) != 5 or len(reshape_shape4) != 4 ): return False
# Check shape and perm. batch, channel, height, width = input_shape blocksize = reshape_shape1[3] if ( reshape_shape1 != [batch, channel, height // blocksize, blocksize, width // blocksize, blocksize] or transpose_perm1 != [0, 1, 2, 4, 3, 5] or reshape_shape2 != [batch, channel, (height // blocksize) * (width // blocksize), blocksize**2] or transpose_perm2 != [0, 1, 3, 2] or reshape_shape3 != [batch, channel, blocksize**2, height // blocksize, width // blocksize] or transpose_perm3 != [0, 2, 1, 3, 4] or reshape_shape4 != [batch, blocksize**2 * channel, height // blocksize, width // blocksize] ): return False
self.nodes_to_remove.extend( [ reshape_node1, transpose_node1, reshape_node2, transpose_node2, reshape_node3, transpose_node3, reshape_node4, ] )
s2d_node = onnx.helper.make_node( self.fused_op_type, name=self.create_unique_node_name(), inputs=[reshape_node1.input[0]], outputs=[reshape_node4.output[0]], blocksize=blocksize, ) self.nodes_to_add.append(s2d_node)
return True
def fuse( self, node: onnx.NodeProto, input_name_to_nodes: dict[str, list[onnx.NodeProto]], output_name_to_node: dict[str, onnx.NodeProto], ): """Fuse a sequence of Reshape and Transpose nodes into a single SpaceToDepth node.
Args: node: An onnx.NodeProto matching the specified search type (i.e., Reshape). input_name_to_nodes: A dict mapping tensor name to consumed nodes. output_name_to_node: A dict mapping tensor name to produced node. """ self._fuse_yolo(node, input_name_to_nodes, output_name_to_node)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413# -------------------------------------------------------------------------# Copyright (c) Microsoft Corporation. All rights reserved.# Licensed under the MIT License. See License.txt in the project root for# license information.# --------------------------------------------------------------------------from __future__ import annotations
import loggingfrom dataclasses import dataclass
import onnx
from ...quant_utils import QuantTypefrom ...tensor_quant_overrides import QuantTypeInfo, TensorQuantOverridesHelper
@dataclassclass TensorTypeRequest: """ Bundles desired quantization type requests for a tensor. A distinction is made between the produced type and the consumed type. """
# The tensor's quant type at the producer end. If None, assumed to be the default activation quant type. producer: QuantTypeInfo | None
# The tensor's quant type received by a set of consumer nodes. # If None, assumed to be the default activation quant type for all consumers. # consumers[1] is a set of consumer node names. consumers: tuple[QuantTypeInfo, set[str]] | None
class MixedPrecisionTensorQuantOverridesFixer: """ Helper that generates tensor quantization overrides for mixed-precision QDQ models.
Specifically, this helper fixes an initial set of quantization overrides that assign a non-default activation quantization type to one or more tensors by doing the following: - Inferring which other tensors need to be overridden to the non-default activation quantization type. - Inserting quantization data type conversions.
Example: --------
Float model:
input_0 --> Op1 --> Op3 --> Op5 --> Op6 --> output_0 ^ | input_1 --> Op2 -+-> Op4 ----+ | +-> Op7 --> output_1 | +-> Op8 --> output_2
If we'd like to quantize this model to uint8 precision, but would like to make sure tensor "Op4_out" is quantized to 16-bit, then we would specify the following initial tensor quantization overrides:
``` init_overrides = {"Op4_out": [{"quant_type": QuantType.QUInt16}]} ```
These initial overrides may not create a valid model because Op4 and Op5 may require both the input and output to be the same type (e.g., uint16). This helper fixes the overrides so that input/output data types are valid:
``` overrides = TensorQuantOverridesHelper(init_overrides)
fixer = MixedPrecisionTensorQuantOverridesFixer.create_from_model(overrides, model, QuantType.QUInt8) fixer.apply( default_activation_qtype=QuantType.QUInt8, default_activation_symmetric=False, ) ```
The above snippet generates the following "fixed" overrides (get via overrides.get_dict()):
{ "Op2_out": [{"quant_type": QUInt8, "convert": {"quant_type": QUInt16, "recv_nodes": {"Op4"}}}], "Op3_out": [{"quant_type": QUInt8, "convert": {"quant_type": QUInt16, "recv_nodes": {"Op5"}}}], "Op4_out": [{"quant_type": QUInt16}], "Op5_out": [{"quant_type": QUInt16, "convert": {"quant_type": QUInt8, "recv_nodes": {"Op6"}}}] }
How to interpret the fixed overrides: - Op2's output is consumed by Op4, Op7, and Op8. Op4 consumes the converted u16 type, but Op7 and Op8 consume the original u8 type. - Op3's output is converted from u8 to u16. Op5 consumes the converted u16 type. - Op4's output is just u16 (not converted). All consumers of Op4_out get the u16 type. - Op5's output is converted from u16 to u8. Op6 consumes the u8 type. """
def __init__( self, overrides: TensorQuantOverridesHelper, producers: dict[str, onnx.NodeProto], consumers: dict[str, list[onnx.NodeProto]], value_infos: dict[str, onnx.ValueInfoProto], initializers: dict[str, onnx.TensorProto], ): """ Params: overrides: The initial tensor quantization overrides to fix. producers: Dictionary that maps a tensor name to the producer node that generates the tensor. consumers: Dictionary that maps a tensor name to the consumer nodes that take the tensor as input. value_infos: Dictionary that maps a tensor name to its onnx.ValueInfoProto. initializers: Dictionary that maps an initializer name to its onnx.TensorProto. """ self.overrides = overrides self.consumers = consumers self.producers = producers self.value_infos = value_infos self.initializers = initializers
@staticmethod def create_from_model( overrides: TensorQuantOverridesHelper, model: onnx.ModelProto, default_activation_qtype: QuantType ) -> MixedPrecisionTensorQuantOverridesFixer: """ Helper function that creates an instance of this class from a loaded ONNX model.
Params: overrides: The initial tensor quantization overrides to fix. model: Loaded ONNX model default_activation_qtype: The intended default activation quantization type. Used to validate the initial overrides.
Returns: Initialized MixedPrecisionTensorQuantOverridesFixer object """ model = onnx.shape_inference.infer_shapes(model) # Need to infer shapes to get value_infos
# Build dictionaries that enable convenient lookups of initializers and value_infos by name. initializers = {initializer.name: initializer for initializer in model.graph.initializer} value_infos = {vi.name: vi for vi in model.graph.value_info} value_infos.update({ot.name: ot for ot in model.graph.output}) value_infos.update({it.name: it for it in model.graph.input})
# Ensure that the user-provided initial overrides are actually valid. valid, err = overrides.is_valid(initializers, set(value_infos), default_activation_qtype) if not valid: pprint_overrides = overrides.pprint_str(indent=4) logging.error(f"Provided invalid tensor quantization overrides:\n{pprint_overrides}") raise ValueError(err)
consumers = {} producers = {}
# Build dictionaries that map a tensor name to the consumer or producer nodes. for node in model.graph.node: for input_name in node.input: if input_name: if input_name not in consumers: consumers[input_name] = []
consumers[input_name].append(node)
for output_name in node.output: producers[output_name] = node
return MixedPrecisionTensorQuantOverridesFixer(overrides, producers, consumers, value_infos, initializers)
def apply( self, default_activation_qtype: QuantType, default_activation_symmetric: bool, ): """ Fixes the initial tensor quantization overrides (in-place) for use in mixed-precision QDQ models.
Params: default_activation_qtype: The intended default activation quantization type. default_activation_symmetric: The intended default symmetry used to quantize activations. """ type_requests = self.get_desired_tensor_types(default_activation_qtype, default_activation_symmetric)
# Use type requests to "fix" tensor quantization overrides by adding # quantization type conversions where necessary. for tensor_name, type_req in type_requests.items(): all_consumers = {node.name for node in self.consumers.get(tensor_name, [])} has_producer_req = type_req.producer is not None has_consumer_req = bool(type_req.consumers)
# Only producer type: Add conversion back to default activation type if has_producer_req and not has_consumer_req: self._update_converted_tensor( tensor_name, type_req.producer, QuantTypeInfo(default_activation_qtype), all_consumers ) # Only consumers elif not has_producer_req and has_consumer_req: prod_type_info = self.overrides.get_node_output_qtype_info(tensor_name, default_activation_qtype) consumer_type_info = type_req.consumers[0]
if prod_type_info != consumer_type_info: self._update_converted_tensor( tensor_name, prod_type_info, consumer_type_info, type_req.consumers[1] ) else: if not self._check_nodes_are_not_convert_consumers(tensor_name, type_req.consumers[1]): raise ValueError( f"Tensor override for '{tensor_name}' converts the type for consumers that need the original type." ) # Both producer and consumers elif has_producer_req and has_consumer_req: prod_type_info = type_req.producer consumer_type_info = type_req.consumers[0]
if prod_type_info != consumer_type_info: self._update_converted_tensor( tensor_name, prod_type_info, consumer_type_info, type_req.consumers[1] ) else: consumers_for_original_type = all_consumers.difference(type_req.consumers[1])
if len(consumers_for_original_type) == 0: # All consumers want the overridden type, so no need for convert nodes! # Just add the override to the new new if not already present. if tensor_name not in self.overrides: self.overrides[tensor_name] = [{}] prod_type_info.save_to_dict(self.overrides[tensor_name][0])
assert "convert" not in self.overrides[tensor_name][0] else: # Some consumers don't want the overridden type. self._update_converted_tensor( tensor_name, prod_type_info, QuantTypeInfo(default_activation_qtype), consumers_for_original_type, ) else: raise ValueError(f"TypeRequest for tensor {tensor_name} has no producer or consumers.")
# Done. Check if the overrides are valid. valid, err = self.overrides.is_valid(self.initializers, set(self.value_infos), default_activation_qtype) if not valid: pprint_overrides = self.overrides.pprint_str(indent=4) logging.error( f"Generated invalid tensor quantization overrides for mixed-precision QDQ model:\n{pprint_overrides}" ) raise ValueError(err)
def get_desired_tensor_types( self, default_activation_qtype: QuantType, default_activation_symmetric: bool, ) -> dict[str, TensorTypeRequest]: """ Iterates through the initial tensor quantization overrides and builds a set of TensorTypeRequests objects that describe the quantization types required at each tensor. These TensorTypeRequests objects are ultimately used to generated the "fixed" overrides.
Params: default_activation_qtype: The intended default activation quantization type. default_activation_symmetric: The intended default symmetry used to quantize activations.
Returns: TensorTypeRequest objects as a dict that maps a tensor name to its requested types. """ type_requests = {} default_activation_type_info = QuantTypeInfo(default_activation_qtype, default_activation_symmetric)
# Scan tensor overrides for type conversion requests. for tensor_name, override_list in self.overrides.items(): if not self.__is_tensor_quantizable(tensor_name): continue # Skip non-quantizable tensors (e.g., not a float)
if tensor_name in self.initializers: continue # Skip initializers
if not override_list or len(override_list) > 1: continue # Skip per-channel stuff
override_dict = override_list[0] quant_type_info = QuantTypeInfo.load_from_dict(override_dict, default_activation_type_info.quant_type) producer_node = self.producers.get(tensor_name) # None if this is a model input
if quant_type_info != default_activation_type_info and "convert" not in override_dict: if producer_node is not None: self._add_type_requests_for_node(type_requests, quant_type_info, producer_node)
# Find all consumer nodes of `tensor_name` and update their inputs/outputs to the new type. for consumer_node in self.consumers.get(tensor_name, []): self._add_type_requests_for_node(type_requests, quant_type_info, consumer_node)
return type_requests
def _add_type_requests_for_node( self, type_requests: dict[str, TensorTypeRequest], quant_type_info: QuantTypeInfo, node: onnx.NodeProto, ): """ Adds TensorTypeRequest objects for a given node, assuming that we want all its inputs and outputs to have the same quantization type (as specified by the `quant_type_info` parameter).
Params: type_requests: Dictionary of type requests to append to for this node. quant_type_info: The quantization type to use for inputs and outputs. node: The node for which the TensorTypeRequest objects are created and added to type_requests. """ # Add output side for output_name in node.output: if not self.__is_tensor_quantizable(output_name): continue
if output_name not in type_requests: type_requests[output_name] = TensorTypeRequest(quant_type_info, None) else: if ( type_requests[output_name].producer is not None and type_requests[output_name].producer != quant_type_info ): raise ValueError(f"Tensor {output_name} has multiple types.")
type_requests[output_name].producer = quant_type_info
# Add the consumer side for input_name in node.input: if input_name and input_name not in self.initializers and self.__is_tensor_quantizable(input_name): if input_name not in type_requests: type_requests[input_name] = TensorTypeRequest(None, None)
if type_requests[input_name].consumers is None: type_requests[input_name].consumers = (quant_type_info, set())
if type_requests[input_name].consumers[0] != quant_type_info: raise ValueError(f"Tensor {input_name} has consumers requesting different types.")
if not node.name: raise ValueError( f"Node of type {node.op_type} with output 0 {node.output[0]} does not have a name!" )
type_requests[input_name].consumers[1].add(node.name)
def _update_converted_tensor( self, tensor_name: str, producer_type_info: QuantTypeInfo, consumer_type_info: QuantTypeInfo, consumer_names: set[str], ): """ Updates the tensor quantization overrides for a tensor that is converted from one type to another.
Params: tensor_name: The name of the tensor for which to update overrides. producer_type_info: Info for the tensor's produced type. consumer_type_info: Info for the tensor's consumed (i.e., converted) type. consumer_names: Nodes names of consumers that consume the converted type. """ if tensor_name not in self.overrides or not self.overrides[tensor_name]: self.overrides[tensor_name] = [{}] producer_type_info.save_to_dict(self.overrides[tensor_name][0])
overrides = self.overrides[tensor_name][0] if producer_type_info != QuantTypeInfo.load_from_dict(overrides): raise ValueError(f"Desired producer quant_type for {tensor_name} doesn't match existing type.")
if consumer_names: if "convert" not in overrides: overrides["convert"] = {} consumer_type_info.save_to_dict(overrides["convert"])
convert_dict = overrides["convert"] if consumer_type_info != QuantTypeInfo.load_from_dict(convert_dict): raise ValueError(f"Desired consumer quant_type for {tensor_name} doesn't match existing type.")
if "recv_nodes" not in convert_dict: convert_dict["recv_nodes"] = set()
convert_dict["recv_nodes"].update(consumer_names)
def _check_nodes_are_not_convert_consumers(self, tensor_name: str, node_names: set[str]): """ Returns true if the given nodes do not consume/receive a converted quantization type.
Params: tensor_name: The name of the tensor to check. node_names: Set of node names that should not be consumers of the converted type. """ if tensor_name not in self.overrides or not self.overrides[tensor_name]: return True
overrides = self.overrides[tensor_name][0]
if "convert" not in overrides: return True
convert_dict = overrides["convert"]
if "recv_nodes" not in convert_dict: return False
return not convert_dict["recv_nodes"].intersection(node_names)
def __is_tensor_quantizable(self, tensor_name): weight = self.initializers.get(tensor_name) if weight is not None: if weight.data_type in (onnx.TensorProto.FLOAT, onnx.TensorProto.FLOAT16): return True elif tensor_name in self.value_infos: vi = self.value_infos[tensor_name] if vi.type.HasField("tensor_type") and vi.type.tensor_type.elem_type in ( onnx.TensorProto.FLOAT, onnx.TensorProto.FLOAT16, ): return True
return False123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353# -------------------------------------------------------------------------# Copyright (c) Microsoft Corporation. All rights reserved.# Licensed under the MIT License. See License.txt in the project root for# license information.# --------------------------------------------------------------------------from __future__ import annotations
import loggingimport tempfilefrom pathlib import Path
import onnx
from ....tools.onnx_model_utils import fix_output_shapes, make_input_shape_fixed, optimize_modelfrom ....tools.remove_initializer_from_input import remove_initializer_from_inputfrom ...fusions import FusionGelu, FusionLayerNormalizationfrom ...onnx_model import ONNXModelfrom .fusion_lpnorm import FusionLpNormalizationfrom .fusion_spacetodepth import FusionSpaceToDepth
def qnn_preprocess_model( model_input: str | Path | onnx.ModelProto, model_output: str | Path, exclude_initializer_from_input: bool = False, fuse_layernorm: bool = False, save_as_external_data: bool = False, all_tensors_to_one_file: bool = False, external_data_location: str | None = None, external_data_size_threshold: int = 1024, external_data_convert_attribute: bool = False, inputs_to_make_channel_last: list[str] | None = None, outputs_to_make_channel_last: list[str] | None = None, dynamic_input_shapes: list[tuple[str, str]] | None = None,) -> bool: """ If necessary, this method creates a new "pre-processed" model in preparation for quantization of a model to be used in QNN EP. Returns true if a new model was created.
This method perfoms the following operations: - Fuse Erf sequence into a single Gelu node. - Fuse ReduceL2 sequence into a single LpNormalization node (p == 2). - (Optional) Fuse ReduceMean sequence into a single LayerNormalization node.
Args: model_input: Path to the input model file or ModelProto. model_output: Path the output model file, which is only created if this method returns True. exclude_initializer_from_input: A bool specifying whether to exclude initializer from input. Defaults to False. fuse_layernorm: True if ReduceMean sequences should be fused into LayerNormalization nodes. Defaults to False. save_as_external_data: True if output model should be saved with external data. Defaults to false. all_tensors_to_one_file: Effective only if save_as_external_data is true. Defaults to false. If true, save all tensors to one external file specified by external_data_location. If false, save each tensor to a file named with the tensor name. external_data_location: Effective only if save_as_external_data is true. Defaults to None. Specify the external file to which all tensors are saved. Path is relative to the model path. If not specified, the model's name is used. external_data_size_threshold: Effective only if save_as_external_data is true. Defaults to 1024. Tensors with a data size >= external_data_size_threshold are converted to external data. To convert every tensor with raw data to external data, set to 0. external_data_convert_attribute: Effective only if save_as_external_data is true. Defaults to false. If true, convert all tensors to external data. If false, convert only non-attribute tensors to external data. inputs_to_make_channel_last: List of graph input names to transpose to be "channel-last". For example, if "input0" originally has the shape (N, C, D1, D2, ..., Dn), the resulting model will change input0's shape to (N, D1, D2, ..., Dn, C) and add a transpose node after it.
Original: input0 (N, C, D1, D2, ..., Dn) --> <Nodes>
Updated: input0 (N, D1, D2, ..., Dn, C) --> Transpose --> input0_chanfirst (N, C, D1, D2, ..., Dn) --> <Nodes>
This can potentially improve inference latency for QDQ models running on QNN EP because the additional transpose node may allow other transpose nodes inserted during ORT layout transformation to cancel out. outputs_to_make_channel_last: List of graph output names to transpose to be "channel-last". For example, if "output0" originally has the shape (N, C, D1, D2, ..., Dn), the resulting model will change output0's shape to (N, D1, D2, ..., Dn, C) and add a transpose node before it.
Original: <Nodes> --> output0 (N, C, D1, D2, ..., Dn)
Updated: <Nodes> --> output0_chanfirst (N, C, D1, D2, ..., Dn) --> Transpose --> output0 (N, D1, D2, ..., Dn, C)
This can potentially improve inference latency for QDQ models running on QNN EP because the additional transpose node may allow other transpose nodes inserted during ORT layout transformation to cancel out. dynamic_input_shapes: A list of tuples specifying model input name to and its static shape in comma seprated format, for example: [('input', '1,3,256,256')]. Defaults to None. """ modified = False model = model_input if isinstance(model_input, onnx.ModelProto) else onnx.load_model(model_input) model = save_and_reload_optimize_model(model, shape_infer=True) onnx_model = ONNXModel(model)
# Optionally, fix the dynamic input shapes. if dynamic_input_shapes: for input_name, input_shape_str in dynamic_input_shapes: input_shape = [int(i) for i in input_shape_str.split(",")] make_input_shape_fixed(onnx_model.graph(), input_name, input_shape) fix_output_shapes(onnx_model.model) modified = True
# Exclude initializer from input if model.ir_version >= 4 if exclude_initializer_from_input: modified |= remove_initializer_from_input(onnx_model.model)
# Fuse Erf sequence into a single Gelu fusion_gelu = FusionGelu(onnx_model) if fusion_gelu.apply(): modified = True
# Fuse ReduceL2 sequence into a single LpNormalization node with p == 2. fusion_lpnorm = FusionLpNormalization(onnx_model) if fusion_lpnorm.apply(): modified = True
# Fuse Reshape/Transpose sequence into a single SpaceToDepth. fusion_s2d = FusionSpaceToDepth(onnx_model) if fusion_s2d.apply(): modified = True
# Optionally, fuse ReduceMean sequence into a single LayerNormalization node. if fuse_layernorm: onnx_opset = next(x for x in model.opset_import if x.domain == "" or x.domain == "ai.onnx")
# Need opset >= 17 to use LayerNormalization. if onnx_opset.version < 17: logging.warning( "Unable to fuse ReduceMean sequence into a LayerNormalization node. " "ONNX model must use an opset >= 17 in order to use LayerNormalization, " f"but found version {onnx_opset.version}. Please use onnx.version_converter to update your model." ) else: fusion_layernorm = FusionLayerNormalization(onnx_model) if fusion_layernorm.apply(): modified = True
# Optionally, transpose inputs and/or outputs to make them "channel-last". if inputs_to_make_channel_last or outputs_to_make_channel_last: transpose_node_prefix = "Transpose_channel_" transpose_node_suffix: int = onnx_model.get_largest_node_name_suffix(transpose_node_prefix) + 1 update_io_to_channel_last( onnx_model.model, inputs_to_make_channel_last, outputs_to_make_channel_last, transpose_node_name_prefix=transpose_node_prefix, transpose_node_name_start_suffix=transpose_node_suffix, ) modified = True
# Make sure all nodes have a name. unnamed_node_prefix = "qnn_preproc_node_" available_suffix = onnx_model.get_largest_node_name_suffix(unnamed_node_prefix) + 1 for node in onnx_model.model.graph.node: if node.op_type != "Constant" and not node.name: new_node_name = f"{unnamed_node_prefix}{available_suffix!s}" available_suffix += 1 node.name = new_node_name modified = True logging.warning(f"Node of type {node.op_type} does not have a name. Renamed to {new_node_name}.")
if modified: onnx_model.topological_sort() onnx.save_model( model, model_output, save_as_external_data=save_as_external_data, all_tensors_to_one_file=all_tensors_to_one_file, location=external_data_location, size_threshold=external_data_size_threshold, convert_attribute=external_data_convert_attribute, )
return modified
def save_and_reload_optimize_model(model: onnx.ModelProto, shape_infer: bool) -> onnx.ModelProto: with tempfile.TemporaryDirectory(prefix="ort.qnn_preproc.") as qnn_preproc_tmp_dir: model_in_path = Path(qnn_preproc_tmp_dir).joinpath("qnn_proc_input.onnx") onnx.save_model(model, model_in_path, save_as_external_data=True) if shape_infer: model_infer_path = Path(qnn_preproc_tmp_dir).joinpath("qnn_proc_infer.onnx") onnx.shape_inference.infer_shapes_path(str(model_in_path), str(model_infer_path)) model_in_path = model_infer_path model_out_path = Path(qnn_preproc_tmp_dir).joinpath("qnn_proc_output.onnx") optimize_model(model_in_path, model_out_path) ret_model = onnx.load_model(model_out_path) ret_metaprops = {"onnx.infer": "onnxruntime.tools.qnn.preprocess"} if ret_model.metadata_props: ret_metaprops.update(ret_model.metadata_props) onnx.helper.set_model_props(ret_model, ret_metaprops) return ret_model
class InputOutputNameMap: def __init__( self, orig_tensor_names: set[str], orig_graph_inputs: dict[str, onnx.ValueInfoProto], orig_graph_outputs: dict[str, onnx.ValueInfoProto], ): self.orig_tensor_names = orig_tensor_names self.orig_graph_inputs = orig_graph_inputs self.orig_graph_outputs = orig_graph_outputs self.updated_io_names = {} self.new_value_infos = []
def get_new_name(self, orig_name: str): if orig_name in self.updated_io_names: return self.updated_io_names[orig_name]
# Make a new tensor name that is unique among all tensors in the graph. prefix: str = f"{orig_name}_channel_first_" suffix: int = -1 for tensor_name in self.orig_tensor_names: if tensor_name.startswith(prefix) and tensor_name[len(prefix) :].isdigit(): index = int(tensor_name[len(prefix) :]) suffix = max(suffix, index)
suffix += 1 # This is the first available suffix. new_name = f"{prefix}{suffix!s}"
# Add new value_info objects for these new tensors. orig_value_info = self.orig_graph_inputs.get(orig_name) or self.orig_graph_outputs[orig_name] value_info_proto = onnx.ValueInfoProto() value_info_proto.CopyFrom(orig_value_info) value_info_proto.name = new_name self.new_value_infos.append(value_info_proto)
self.updated_io_names[orig_name] = new_name return self.updated_io_names[orig_name]
def update_io_to_channel_last( model: onnx.ModelProto, inputs_to_update: list[str] | None, outputs_to_update: list[str] | None, transpose_node_name_prefix: str = "Transpose_channel_", transpose_node_name_start_suffix: int = 0,): inputs_to_update = set(inputs_to_update or []) outputs_to_update = set(outputs_to_update or [])
if not inputs_to_update and not outputs_to_update: return
graph = model.graph orig_graph_inputs = {ginput.name: ginput for ginput in graph.input} orig_graph_outputs = {goutput.name: goutput for goutput in graph.output}
# Check that the user passed in actual input and output names. for input_name in inputs_to_update: if input_name not in orig_graph_inputs: raise ValueError(f"{input_name} is not a graph input")
for output_name in outputs_to_update: if output_name not in orig_graph_outputs: raise ValueError(f"{output_name} is not a graph output")
orig_tensor_names = set() orig_tensor_names.update(set(orig_graph_inputs)) orig_tensor_names.update(set(orig_graph_outputs)) orig_tensor_names.update(input_name for node in graph.node for input_name in node.input if input_name)
# Maps original input (or output) name to its updated name used within the graph. io_map = InputOutputNameMap(orig_tensor_names, orig_graph_inputs, orig_graph_outputs)
# Update each node's inputs/outputs to use the transposed versions. for node in graph.node: for i in range(len(node.input)): if node.input[i] and node.input[i] in inputs_to_update: node.input[i] = io_map.get_new_name(node.input[i]) elif node.input[i] and node.input[i] in outputs_to_update: node.input[i] = io_map.get_new_name(node.input[i])
for i in range(len(node.output)): if node.output[i] in outputs_to_update: node.output[i] = io_map.get_new_name(node.output[i])
# Update graph inputs to channel-last and a Transpose (to channel-first) after each. for g_input_name in inputs_to_update: g_input = orig_graph_inputs[g_input_name]
if not g_input.type.HasField("tensor_type") or not g_input.type.tensor_type.HasField("shape"): raise ValueError(f"Expected input {g_input.name} to have a tensor_type with a shape")
input_shape = g_input.type.tensor_type.shape input_rank = len(input_shape.dim)
if input_rank < 3: raise ValueError(f"Expected input {g_input.name} to be of rank >= 3")
channel_dim = onnx.TensorShapeProto.Dimension() channel_dim.CopyFrom(input_shape.dim[1]) for i in range(1, input_rank - 1): input_shape.dim[i].CopyFrom(input_shape.dim[i + 1]) input_shape.dim[input_rank - 1].CopyFrom(channel_dim)
transpose_perm = list(range(input_rank)) for i in range(input_rank): transpose_perm[i] = i if i < 1 else i - 1 transpose_perm[1] = input_rank - 1
transpose_node = onnx.helper.make_node( "Transpose", name=f"{transpose_node_name_prefix}{transpose_node_name_start_suffix!s}", inputs=[g_input.name], outputs=[io_map.get_new_name(g_input.name)], perm=transpose_perm, ) transpose_node_name_start_suffix += 1
graph.node.extend([transpose_node])
# Update graph outputs to channel-last and a Transpose (from channel-first) before each. for g_output_name in outputs_to_update: g_output = orig_graph_outputs[g_output_name] if not g_output.type.HasField("tensor_type") or not g_output.type.tensor_type.HasField("shape"): raise ValueError(f"Expected output {g_output.name} to have a tensor_type with a shape")
output_shape = g_output.type.tensor_type.shape output_rank = len(output_shape.dim)
if output_rank < 3: raise ValueError(f"Expected output {g_output.name} to be of rank >= 3")
channel_dim = onnx.TensorShapeProto.Dimension() channel_dim.CopyFrom(output_shape.dim[1]) for i in range(1, output_rank - 1): output_shape.dim[i].CopyFrom(output_shape.dim[i + 1]) output_shape.dim[output_rank - 1].CopyFrom(channel_dim)
transpose_perm = list(range(output_rank)) for i in range(output_rank): transpose_perm[i] = i if i == 0 else i + 1 transpose_perm[output_rank - 1] = 1
transpose_node = onnx.helper.make_node( "Transpose", name=f"{transpose_node_name_prefix}{transpose_node_name_start_suffix!s}", inputs=[io_map.get_new_name(g_output.name)], outputs=[g_output.name], perm=transpose_perm, ) transpose_node_name_start_suffix += 1
graph.node.extend([transpose_node])
graph.value_info.extend(io_map.new_value_infos)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389# -------------------------------------------------------------------------# Copyright (c) Microsoft Corporation. All rights reserved.# Licensed under the MIT License. See License.txt in the project root for# license information.# --------------------------------------------------------------------------from __future__ import annotations
import copyimport loggingfrom pathlib import Pathfrom typing import Any
import numpy as npimport onnx
from ...calibrate import CalibrationDataReader, CalibrationMethodfrom ...quant_utils import QuantTypefrom ...quantize import StaticQuantConfigfrom ...tensor_quant_overrides import TensorQuantOverridesHelperfrom .mixed_precision_overrides_utils import MixedPrecisionTensorQuantOverridesFixer
Q16_TYPES = {QuantType.QInt16, QuantType.QUInt16}Q8_TYPES = {QuantType.QInt8, QuantType.QUInt8}Q4_TYPES = {QuantType.QInt4, QuantType.QUInt4}OP_TYPES_TO_EXCLUDE = {"Cast"}MODEL_SIZE_THRESHOLD = 2147483648 # Quant model should use external data if >= 2GB
def warn_unable_to_override( node: onnx.NodeProto, what_str: str, tensor_name: str, io_kind: str,): logging.warning( f"Unable to override {what_str} for {node.op_type} node's {io_kind} " "because it has already been overridden! Check the initial quantization overrides provided " "to get_qnn_qdq_config() if the generated QDQ model does not run on QNN EP. " f"Node name: {node.name}, {io_kind} name: {tensor_name}" )
def get_qnn_qdq_config( model_input: str | Path | onnx.ModelProto, calibration_data_reader: CalibrationDataReader, calibrate_method: CalibrationMethod = CalibrationMethod.MinMax, activation_type: QuantType = QuantType.QUInt8, weight_type: QuantType = QuantType.QUInt8, per_channel: bool = False, init_overrides: dict[str, list[dict[str, Any]]] | None = None, add_qtype_converts: bool = True, activation_symmetric: bool = False, weight_symmetric: bool | None = None, keep_removable_activations: bool = False, stride: int | None = None, calibration_providers: list[str] | None = None, op_types_to_quantize: list[str] | None = None, nodes_to_exclude: list[str] | None = None,) -> StaticQuantConfig: """ Returns a static quantization configuration suitable for running QDQ models on QNN EP. This is done primarily by setting tensor-level quantization overrides.
Params: model_input: Path to the input model file or ModelProto. calibration_data_reader: Calibration data reader. calibrate_methode: The calibration method. Defaults to MinMax. activation_type: The default activation quantization type. Defaults to QUInt8. weight_type: The default weight quantization type. Defaults to QUInt8. per_channel: Global option that determines if a fixed set of operator types should be quantized per-channel. Defaults to false. Alternatively, use the tensor-level `init_overrides` to select individual operators and their quantization axes.
If set, the quantization tool uses per-channel quantization for the following operator types and inputs: - Conv: - input[1] on axis 0 - input[2] (bias) on axis 0 - ConvTranspose: - input[1] on axis 1 - input[2] (bias) on axis 0 init_overrides: Initial tensor-level quantization overrides. Defaults to None. This function updates of a copy of these overrides with any necessary adjustments and includes them in the returned configuration object (i.e., config.extra_options['TensorQuantOverrides']).
The key is a tensor name and the value is a list of dictionaries. For per-tensor quantization, the list contains a single dictionary. For per-channel quantization, the list contains either a dictionary for each channel in the tensor or a single dictionary that is assumed to apply to all channels. An 'axis' key must be present in the first dictionary for per-channel quantization.
Each dictionary contains optional overrides with the following keys and values. 'quant_type' = QuantType : The tensor's quantization data type. 'axis' = Int : The per-channel axis. Must be present for per-channel weights. 'scale' = Float : The scale value to use. Must also specify `zero_point` if set. 'zero_point' = Int : The zero-point value to use. Must also specify `scale` is set. 'symmetric' = Bool : If the tensor should use symmetric quantization. Invalid if also set `scale` or `zero_point`. 'reduce_range' = Bool : If the quantization range should be reduced. Invalid if also set `scale` or `zero_point`. Only valid for initializers. 'rmax' = Float : Override the maximum real tensor value in calibration data. Invalid if also set `scale` or `zero_point`. 'rmin' = Float : Override the minimum real tensor value in calibration data. Invalid if also set `scale` or `zero_point`. 'convert' = Dict : A nested dictionary with the same keys for an activation tensor that should be converted to another quantization type. 'convert["recv_nodes"] = Set : Set of node names that consume the converted activation, other nodes get the original type. If not specified, assume all consumer nodes get the converted type. add_qtype_converts: True if this function should automatically add "convert" entries to the provided `init_overrides` to ensure that operators use valid input/output types (activations only). Ex: if you override the output of an Add to 16-bit, this option ensures that the activation inputs of the Add are also up-converted to 16-bit and that data types for surrounding ops are converted appropriately. Refer to the documentation in mixed_precision_overrides_utils.py for additional details. activation_symmetric: True if activations should be quantized symmetrically (i.e, rmax == -rmin) by default. Defaults to false. For int8 and int16, this results in zero-point values of 0. For uint8 and uin16, the zero-point values are 128 and 32,768, respectively. weight_symmetric: True if weights should be quantized symmetrically (i.e., rmax == -rmin) by default. Defaults to None. If set to None, weight_symmetric is assumed true if the weight_type is a signed int. keep_removable_activations: Defaults to false. If true, "removable" activations (e.g., Clip or Relu) will not be removed, and will be explicitly represented in the QDQ model. If false, these activations are automatically removed if activations are asymmetrically quantized. Keeping these activations is necessary if optimizations or EP transformations will later remove QuantizeLinear/DequantizeLinear operators from the model. calibration_providers: Execution providers to run the session during calibration. Default is None which uses [ "CPUExecutionProvider" ]. op_types_to_quantize: If set to None, all operator types will be quantized except for OP_TYPES_TO_EXCLUDE nodes_to_exclude: List of nodes names to exclude from quantization. The nodes in this list will be excluded from quantization when it is not None.
Returns: A StaticQuantConfig object """ if weight_symmetric is None: weight_symmetric = weight_type in {QuantType.QInt8, QuantType.QInt16}
model = ( model_input if isinstance(model_input, onnx.ModelProto) else onnx.load_model(model_input, load_external_data=False) )
op_types = set() model_has_external_data = False name_to_initializer = {}
# Build map of initializers (name -> initializer) and # check if the model has external data. for initializer in model.graph.initializer: name_to_initializer[initializer.name] = initializer if onnx.external_data_helper.uses_external_data(initializer): model_has_external_data = True
overrides_helper = TensorQuantOverridesHelper(copy.deepcopy(init_overrides) if init_overrides else {})
if not overrides_helper.empty() and add_qtype_converts: # Fix mixed-precision overrides. overrides_fixer = MixedPrecisionTensorQuantOverridesFixer.create_from_model( overrides_helper, model, activation_type ) overrides_fixer.apply(activation_type, activation_symmetric)
# Setup quantization overrides for specific operator types to ensure compatibility with QNN EP. qnn_compat = QnnCompatibilityOverrides( activation_type, weight_type, activation_symmetric, weight_symmetric, per_channel, overrides_helper, name_to_initializer, )
op_types_to_quantize_set = set(op_types_to_quantize) if op_types_to_quantize else None nodes_to_exclude_set = set(nodes_to_exclude) if nodes_to_exclude else None
for node in model.graph.node: if op_types_to_quantize_set and node.op_type not in op_types_to_quantize_set: continue if nodes_to_exclude_set and node.name in nodes_to_exclude_set: continue op_types.add(node.op_type) qnn_compat.process_node(node)
extra_options = { "MinimumRealRange": 0.0001, "DedicatedQDQPair": False, # Let ORT optimizer duplicate DQ nodes "QDQKeepRemovableActivations": keep_removable_activations, "TensorQuantOverrides": overrides_helper.get_dict(), "ActivationSymmetric": activation_symmetric, "WeightSymmetric": weight_symmetric, "CalibStridedMinMax": stride, }
# ONNX opset < 21 does not support 16-bit quantization, so must use 'com.microsoft' domain # on Q/DQ operators if using 16-bit or 4-bit quantization. onnx_opset = next(x for x in model.opset_import if x.domain == "" or x.domain == "ai.onnx") if onnx_opset.version < 21: opset21_types = Q16_TYPES.union(Q4_TYPES) overrides_have_opset21_types = any(t in opset21_types for t in overrides_helper.get_quant_types()) if activation_type in opset21_types or weight_type in opset21_types or overrides_have_opset21_types: extra_options["UseQDQContribOps"] = True
return StaticQuantConfig( calibration_data_reader, calibrate_method=calibrate_method, activation_type=activation_type, weight_type=weight_type, op_types_to_quantize=( op_types_to_quantize if op_types_to_quantize else list(op_types.difference(OP_TYPES_TO_EXCLUDE)) ), nodes_to_exclude=nodes_to_exclude, per_channel=per_channel, use_external_data_format=(model_has_external_data or model.ByteSize() >= MODEL_SIZE_THRESHOLD), calibration_providers=calibration_providers, extra_options=extra_options, )
class QnnCompatibilityOverrides: """ Helper that processes nodes to generate quantization overrides that make the resulting QDQ model compatible with QNN EP. """
def __init__( self, default_activation_qtype: QuantType, default_weight_qtype: QuantType, activation_symmetric: bool, weight_symmetric: bool, per_channel: bool, overrides: TensorQuantOverridesHelper, initializers: dict[str, onnx.TensorProto], ): self.default_activation_qtype = default_activation_qtype self.default_weight_qtype = default_weight_qtype self.activation_symmetric = activation_symmetric self.weight_symmetric = weight_symmetric self.per_channel = per_channel self.overrides = overrides self.initializers = initializers
self.process_fns = { "MatMul": self._process_matmul, "LayerNormalization": self._process_layernorm, "Sigmoid": self._process_sigmoid, "Tanh": self._process_tanh, }
def process_node(self, node: onnx.NodeProto): process_fn = self.process_fns.get(node.op_type)
if process_fn is not None: process_fn(node)
def _make_static_inputs_use_default_weight_type(self, node: onnx.NodeProto): """ Overrides initializer input(s) to use the default weight type if: - The default weight type is 8-bit - One of the inputs is a 16-bit activation - The other input is an initializer (per-tensor quantized)
This is necessary because the quantization tool does not assign MatMul or LayerNorm initializer inputs the default weight type. Instead, it assigns the default activation type. """ if self.default_weight_qtype not in Q8_TYPES: return
input_16bit_act_name = None input_weight_name = None
# Loop through first 2 inputs to find a 16-bit activation and a (per-tensor) weight. for i in range(2): input_name = node.input[i] if not input_name: continue
is_weight = input_name in self.initializers qtype_info = self.overrides.get_node_input_qtype_info( input_name, node.name, default_qtype=None if is_weight else self.default_activation_qtype, )
if qtype_info.axis is not None: return # Don't process MatMul with a per-channel quantized input.
if ( is_weight and qtype_info.quant_type == self.default_weight_qtype and qtype_info.symmetric == self.weight_symmetric ): return # Return. Weight is already overridden to use the desired weight type.
if is_weight: input_weight_name = input_name elif qtype_info.quant_type in Q16_TYPES: input_16bit_act_name = input_name
# Override initializer input to use the default weight type. if input_16bit_act_name and input_weight_name: did_update = self.overrides.update_tensor_overrides( input_weight_name, {"quant_type": self.default_weight_qtype, "symmetric": self.weight_symmetric}, overwrite=False, )
if not did_update: warn_unable_to_override(node, "quant_type/symmetric", input_weight_name, "input weight")
def _process_matmul(self, node: onnx.NodeProto): assert node.op_type == "MatMul", f"Expected MatMul, but got {node.op_type}"
if not self.per_channel: self._make_static_inputs_use_default_weight_type(node) return
# QNN does not support per-channel MatMul. However, the ORT quantization tool attempts to use per-channel # quantization for MatMul by default *if* the global per_channel setting is enabled. So, we need to # provide explicit per-tensor quantization overrides for MatMul if per_channel is enabled and # the user did not provide any other overrides. for input_name in node.input: is_weight_no_overrides = input_name in self.initializers and input_name not in self.overrides if is_weight_no_overrides: self.overrides.update_tensor_overrides( input_name, {"quant_type": self.default_weight_qtype, "symmetric": self.weight_symmetric}, )
def _process_layernorm(self, node: onnx.NodeProto): assert node.op_type == "LayerNormalization", f"Expected LayerNormalization, but got {node.op_type}"
if not self.per_channel: self._make_static_inputs_use_default_weight_type(node)
def _process_sigmoid(self, node: onnx.NodeProto): """ Overrides 16-bit Sigmoid's output scale and zero-point as per QNN requirements. """ assert node.op_type == "Sigmoid", f"Expected Sigmoid, but got {node.op_type}" output_type = self.overrides.get_node_output_qtype_info( node.output[0], self.default_activation_qtype ).quant_type
if output_type == QuantType.QUInt16: self.overrides.update_tensor_overrides( node.output[0], { "quant_type": output_type, "scale": np.array(1.0 / 65536.0, dtype=np.float32), "zero_point": np.array(0, dtype=np.uint16), }, ) elif output_type == QuantType.QInt16: self.overrides.update_tensor_overrides( node.output[0], { "quant_type": output_type, "scale": np.array(1.0 / 32768.0, dtype=np.float32), "zero_point": np.array(0, dtype=np.int16), }, )
def _process_tanh(self, node: onnx.NodeProto): """ Overrides 16-bit Tanh's output scale and zero-point as per QNN requirements. """ assert node.op_type == "Tanh", f"Expected Tanh, but got {node.op_type}" output_type = self.overrides.get_node_output_qtype_info( node.output[0], self.default_activation_qtype ).quant_type
if output_type == QuantType.QUInt16: self.overrides.update_tensor_overrides( node.output[0], { "quant_type": output_type, "scale": np.array(1.0 / 32768.0, dtype=np.float32), "zero_point": np.array(32768, dtype=np.uint16), }, ) elif output_type == QuantType.QInt16: self.overrides.update_tensor_overrides( node.output[0], { "quant_type": output_type, "scale": np.array(1.0 / 32768.0, dtype=np.float32), "zero_point": np.array(0, dtype=np.int16), }, )1234from .fusion import Fusion # noqa: F401from .fusion_gelu import FusionGelu # noqa: F401from .fusion_layernorm import FusionLayerNormalization # noqa: F401from .replace_upsample_with_resize import ReplaceUpsampleWithResize # noqa: F401123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311# -------------------------------------------------------------------------# Copyright (c) Microsoft Corporation. All rights reserved.# Licensed under the MIT License. See License.txt in the project root for# license information.# --------------------------------------------------------------------------from __future__ import annotations
from collections import deque
import onnx
from ..onnx_model import ONNXModel
class Fusion: """ Base class for fusions. """
def __init__(self, model: ONNXModel, fused_op_type: str, search_op_type: str): self.search_op_type: str = search_op_type self.fused_op_type: str = fused_op_type self.model: ONNXModel = model self.nodes_to_remove: list = [] self.nodes_to_add: list = []
self._new_node_name_prefix = self.fused_op_type + "_fused_" + self.search_op_type + "_" self._new_node_name_suffix = None # int|None used to create unique node names for the fused ops.
def fuse( self, node: onnx.NodeProto, input_name_to_nodes: dict[str, list[onnx.NodeProto]], output_name_to_node: dict[str, onnx.NodeProto], ): """ Interface function for derived fusion classes. Tries to fuse a node sequence containing the specified node. """ raise NotImplementedError
def apply(self) -> bool: """ Apply graph fusion on the entire model graph. """ input_name_to_nodes = self.model.input_name_to_nodes() output_name_to_node = self.model.output_name_to_node()
for node in self.model.nodes(): if node.op_type == self.search_op_type: self.fuse(node, input_name_to_nodes, output_name_to_node)
self.model.remove_nodes(self.nodes_to_remove) self.model.add_nodes(self.nodes_to_add)
graph_updated = bool(self.nodes_to_remove or self.nodes_to_add)
if graph_updated: self.model.remove_unused_constant()
return graph_updated
def create_unique_node_name(self): prefix = self._new_node_name_prefix
if self._new_node_name_suffix is None: largest_suffix: int = self.model.get_largest_node_name_suffix(prefix) self._new_node_name_suffix = largest_suffix + 1
new_name = f"{prefix}{self._new_node_name_suffix!s}" self._new_node_name_suffix += 1
return new_name
@staticmethod def is_safe_to_fuse_nodes( nodes_to_remove: list[onnx.NodeProto], keep_outputs: list[str], input_name_to_nodes: dict[str, list[onnx.NodeProto]], output_name_to_node: dict[str, onnx.NodeProto], ) -> bool: for node_to_remove in nodes_to_remove: for output_to_remove in node_to_remove.output: if output_to_remove in keep_outputs: continue
if output_to_remove in input_name_to_nodes: for impacted_node in input_name_to_nodes[output_to_remove]: if impacted_node not in nodes_to_remove: # Not safe to remove nodes since output is used by impacted_node return False return True
@staticmethod def get_node_attribute(node: onnx.NodeProto, attribute_name: str): for attr in node.attribute: if attr.name == attribute_name: value = onnx.helper.get_attribute_value(attr) return value return None
@staticmethod def input_index(node_output: str, child_node: onnx.NodeProto) -> int: for index, input_name in enumerate(child_node.input): if input_name == node_output: return index return -1
@staticmethod def tensor_shape_to_list(tensor_type) -> list[int]: shape_list = [] for d in tensor_type.shape.dim: if d.HasField("dim_value"): shape_list.append(d.dim_value) # known dimension elif d.HasField("dim_param"): shape_list.append(d.dim_param) # unknown dimension with symbolic name else: shape_list.append("?") # shall not happen return shape_list
def get_constant_input(self, node: onnx.NodeProto): for i, inp in enumerate(node.input): value = self.model.get_constant_value(inp) if value is not None: return i, value
return None, None
def find_constant_input(self, node: onnx.NodeProto, expected_value: float, delta: float = 0.000001) -> int: i, value = self.get_constant_input(node) if value is not None and value.size == 1 and abs(value - expected_value) < delta: return i
return -1
def has_constant_input(self, node: onnx.NodeProto, expected_value: float, delta: float = 0.000001) -> bool: return self.find_constant_input(node, expected_value, delta) >= 0
def is_constant_with_specified_rank(self, output_name: str, rank: int) -> bool: value = self.model.get_constant_value(output_name) if value is None: return False # Not an initializer
if len(value.shape) != rank: return False # Wrong dimensions
return True
def match_first_parent( self, node: onnx.NodeProto, parent_op_type: str, output_name_to_node: dict[str, onnx.NodeProto] | None = None, exclude: list[onnx.NodeProto] = [], # noqa: B006 ) -> tuple[onnx.NodeProto | None, int | None]: """ Find parent node based on constraints on op_type.
Args: node: current node. parent_op_type (str): constraint of parent node op_type. output_name_to_node (dict): dictionary with output name as key, and node as value. exclude (list): list of nodes that are excluded (not allowed to match as parent).
Returns: parent: The matched parent node. None if not found. index: The input index of matched parent node. None if not found. """ if output_name_to_node is None: output_name_to_node = self.model.output_name_to_node()
for i, inp in enumerate(node.input): if inp in output_name_to_node: parent = output_name_to_node[inp] if parent.op_type == parent_op_type and parent not in exclude: return parent, i
return None, None
def match_parent( self, node: onnx.NodeProto, parent_op_type: str, input_index: int | None = None, output_name_to_node: dict[str, onnx.NodeProto] | None = None, exclude: list[onnx.NodeProto] = [], # noqa: B006 return_indice: list[int] | None = None, ) -> onnx.NodeProto | None: """ Find parent node based on constraints on op_type and index. When input_index is None, we will find the first parent node based on constraints, and return_indice will be appended the corresponding input index.
Args: node (str): current node name. parent_op_type (str): constraint of parent node op_type. input_index (int or None): only check the parent given input index of current node. output_name_to_node (dict): dictionary with output name as key, and node as value. exclude (list): list of nodes that are excluded (not allowed to match as parent). return_indice (list): a list to append the input index when input_index is None.
Returns: parent: The matched parent node. """ assert node is not None assert input_index is None or input_index >= 0
if output_name_to_node is None: output_name_to_node = self.model.output_name_to_node()
if input_index is None: parent, index = self.match_first_parent(node, parent_op_type, output_name_to_node, exclude) if return_indice is not None: return_indice.append(index) return parent
if input_index >= len(node.input): # Input index out of bounds. return None
parent = self.model.get_parent(node, input_index, output_name_to_node) if parent is not None and parent.op_type == parent_op_type and parent not in exclude: return parent
return None
def match_parent_path( self, node: onnx.NodeProto, parent_op_types: list[str], parent_input_index: list[int] | None = None, output_name_to_node: dict[str, onnx.NodeProto] | None = None, return_indice: list[int] | None = None, ) -> list[onnx.NodeProto] | None: """ Find a sequence of input edges based on constraints on parent op_type and index. When input_index is None, we will find the first parent node based on constraints, and return_indice will be appended the corresponding input index.
Args: node (str): current node name. parent_op_types (str): constraint of parent node op_type of each input edge. parent_input_index (list): constraint of input index of each input edge. None means no constraint. output_name_to_node (dict): dictionary with output name as key, and node as value. return_indice (list): a list to append the input index When there is no constraint on input index of an edge.
Returns: parents: a list of matched parent node. """ if parent_input_index is not None: assert len(parent_input_index) == len(parent_op_types)
if output_name_to_node is None: output_name_to_node = self.model.output_name_to_node()
current_node = node matched_parents = [] for i, op_type in enumerate(parent_op_types): matched_parent = self.match_parent( current_node, op_type, parent_input_index[i] if parent_input_index is not None else None, output_name_to_node, exclude=[], return_indice=return_indice, ) if matched_parent is None: return None
matched_parents.append(matched_parent) current_node = matched_parent
return matched_parents
def match_parent_paths( self, node: onnx.NodeProto, paths: list[tuple[list[str], list[int]]], output_name_to_node: dict[str, onnx.NodeProto], ) -> tuple[int, list[onnx.NodeProto] | None, list[int] | None]: """ Find a matching parent path to the given node. """ for i, path in enumerate(paths): return_indice = [] matched = self.match_parent_path(node, path[0], path[1], output_name_to_node, return_indice) if matched: return i, matched, return_indice return -1, None, None
def find_first_child_by_type( self, node: onnx.NodeProto, child_type: str, input_name_to_nodes: dict[str, list[onnx.NodeProto]] | None = None, recursive: bool = True, ) -> onnx.NodeProto | None: children = self.model.get_children(node, input_name_to_nodes) dq = deque(children) while len(dq) > 0: current_node = dq.pop() if current_node.op_type == child_type: return current_node
if recursive: children = self.model.get_children(current_node, input_name_to_nodes) for child in children: dq.appendleft(child)
return None123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272# -------------------------------------------------------------------------# Copyright (c) Microsoft Corporation. All rights reserved.# Licensed under the MIT License. See License.txt in the project root for# license information.# --------------------------------------------------------------------------from __future__ import annotations
import onnx
from ..onnx_model import ONNXModelfrom .fusion import Fusion
class FusionGelu(Fusion): def __init__(self, model: ONNXModel): super().__init__(model, "Gelu", "Erf")
def fuse( self, erf_node: onnx.NodeProto, input_name_to_nodes: dict[str, list[onnx.NodeProto]], output_name_to_node: dict[str, onnx.NodeProto], ): """ Interface function that tries to fuse a node sequence containing an Erf node into a single Gelu node. """ if ( self.fuse_1(erf_node, input_name_to_nodes, output_name_to_node) or self.fuse_2(erf_node, input_name_to_nodes, output_name_to_node) or self.fuse_3(erf_node, input_name_to_nodes, output_name_to_node) ): self.model.set_opset_import("com.microsoft", 1)
def fuse_1( self, erf_node: onnx.NodeProto, input_name_to_nodes: dict[str, list[onnx.NodeProto]], output_name_to_node: dict[str, onnx.NodeProto], ) -> bool: """ This pattern is from PyTorch model Fuse Gelu with Erf into one node: Pattern 1: +-------Mul(0.5)---------------------+ | | | v [root] --> Div -----> Erf --> Add --> Mul --> (B=1.4142...) (1)
Pattern 2: +------------------------------------+ | | | v [root] --> Div -----> Erf --> Add --> Mul -->Mul --> (B=1.4142...) (1) (0.5)
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. """ if erf_node.output[0] not in input_name_to_nodes: return False children = input_name_to_nodes[erf_node.output[0]] if len(children) != 1 or children[0].op_type != "Add": return False add_after_erf = children[0]
if not self.has_constant_input(add_after_erf, 1): return False
if add_after_erf.output[0] not in input_name_to_nodes: return False
children = input_name_to_nodes[add_after_erf.output[0]] if len(children) != 1 or children[0].op_type != "Mul": return False
mul_after_erf = children[0]
div = self.match_parent(erf_node, "Div", 0, output_name_to_node) if div is None: return False
if self.find_constant_input(div, 1.4142, delta=0.001) != 1: return False
subgraph_input = div.input[0]
another = 1 if mul_after_erf.input[0] == add_after_erf.output[0] else 0 if subgraph_input == mul_after_erf.input[another]: # pattern 2 children = input_name_to_nodes[mul_after_erf.output[0]] if len(children) != 1 or children[0].op_type != "Mul": return False mul_half = children[0] if not self.has_constant_input(mul_half, 0.5): return False subgraph_output = mul_half.output[0] else: # pattern 1 mul_half = self.match_parent(mul_after_erf, "Mul", another, output_name_to_node) if mul_half is None: return False
if not self.has_constant_input(mul_half, 0.5): return False
if subgraph_input not in mul_half.input: return False
subgraph_output = mul_after_erf.output[0]
subgraph_nodes = [div, erf_node, add_after_erf, mul_after_erf, mul_half] if not self.is_safe_to_fuse_nodes(subgraph_nodes, [subgraph_output], input_name_to_nodes, output_name_to_node): return False
self.nodes_to_remove.extend(subgraph_nodes) fused_node = onnx.helper.make_node( "Gelu", name=self.create_unique_node_name(), inputs=[subgraph_input], outputs=[subgraph_output] ) fused_node.domain = "com.microsoft" self.nodes_to_add.append(fused_node) return True
def fuse_2( self, erf_node: onnx.NodeProto, input_name_to_nodes: dict[str, list[onnx.NodeProto]], output_name_to_node: dict[str, onnx.NodeProto], ) -> bool: """ This pattern is from Keras model Fuse Gelu with Erf into one node: +------------------------------------------+ | | | v [root] --> Div -----> Erf --> Add --> Mul -->Mul (B=1.4142...) (A=1) (A=0.5)
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. """ if erf_node.output[0] not in input_name_to_nodes: return False children = input_name_to_nodes[erf_node.output[0]] if len(children) != 1 or children[0].op_type != "Add": return False add_after_erf = children[0]
if not self.has_constant_input(add_after_erf, 1): return False
if add_after_erf.output[0] not in input_name_to_nodes: return False children = input_name_to_nodes[add_after_erf.output[0]] if len(children) != 1 or children[0].op_type != "Mul": return False mul_after_erf = children[0]
if not self.has_constant_input(mul_after_erf, 0.5): return False
if mul_after_erf.output[0] not in input_name_to_nodes: return False children = input_name_to_nodes[mul_after_erf.output[0]] if len(children) != 1 or children[0].op_type != "Mul": return False mul = children[0]
div = self.match_parent(erf_node, "Div", 0, output_name_to_node) if div is None: return False
sqrt_node = None if self.find_constant_input(div, 1.4142, delta=0.001) != 1: sqrt_node = self.match_parent(div, "Sqrt", 1, output_name_to_node) if sqrt_node is None: return False if not self.has_constant_input(sqrt_node, 2.0): return False
subgraph_input = div.input[0]
if subgraph_input not in mul.input: return False
subgraph_nodes = [div, erf_node, add_after_erf, mul_after_erf, mul] if sqrt_node: subgraph_nodes.append(sqrt_node)
if not self.is_safe_to_fuse_nodes(subgraph_nodes, [mul.output[0]], input_name_to_nodes, output_name_to_node): return False
self.nodes_to_remove.extend(subgraph_nodes) fused_node = onnx.helper.make_node( "Gelu", name=self.create_unique_node_name(), inputs=[subgraph_input], outputs=[mul.output[0]] ) fused_node.domain = "com.microsoft" self.nodes_to_add.append(fused_node) return True
def fuse_3( self, erf_node: onnx.NodeProto, input_name_to_nodes: dict[str, list[onnx.NodeProto]], output_name_to_node: dict[str, onnx.NodeProto], ) -> bool: """ This pattern is from TensorFlow model Fuse Gelu with Erf into one node: +----------------------------------------------+ | | | v [root] --> Mul -----> Erf --> Add --> Mul -->Mul (A=0.7071067690849304) (B=1) (B=0.5)
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. """
if erf_node.output[0] not in input_name_to_nodes: return False children = input_name_to_nodes[erf_node.output[0]] if len(children) != 1 or children[0].op_type != "Add": return False add_after_erf = children[0]
if not self.has_constant_input(add_after_erf, 1): return False
if add_after_erf.output[0] not in input_name_to_nodes: return False children = input_name_to_nodes[add_after_erf.output[0]] if len(children) != 1 or children[0].op_type != "Mul": return False mul_half = children[0]
if not self.has_constant_input(mul_half, 0.5): return False
first_mul = self.match_parent(erf_node, "Mul", 0, output_name_to_node) if first_mul is None: return False
i = self.find_constant_input(first_mul, 0.7071067690849304, delta=0.001) if i < 0: return False
root_input_index = 1 - i subgraph_input = first_mul.input[root_input_index]
if mul_half.output[0] not in input_name_to_nodes: return False children = input_name_to_nodes[mul_half.output[0]] if len(children) != 1 or children[0].op_type != "Mul": return False last_mul = children[0]
if not (last_mul.input[0] == subgraph_input or last_mul.input[1] == subgraph_input): return False
subgraph_nodes = [first_mul, erf_node, add_after_erf, mul_half, last_mul] if not self.is_safe_to_fuse_nodes( subgraph_nodes, [last_mul.output[0]], input_name_to_nodes, output_name_to_node, ): return False
self.nodes_to_remove.extend(subgraph_nodes) fused_node = onnx.helper.make_node( "Gelu", name=self.create_unique_node_name(), inputs=[subgraph_input], outputs=[last_mul.output[0]] ) fused_node.domain = "com.microsoft" self.nodes_to_add.append(fused_node) return True123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146# -------------------------------------------------------------------------# Copyright (c) Microsoft Corporation. All rights reserved.# Licensed under the MIT License. See License.txt in the project root for# license information.# --------------------------------------------------------------------------from __future__ import annotations
import onnx
from ..onnx_model import ONNXModelfrom .fusion import Fusion
class FusionLayerNormalization(Fusion): def __init__(self, model: ONNXModel): super().__init__(model, "LayerNormalization", "ReduceMean")
def fuse( self, reduce_mean_node: onnx.NodeProto, input_name_to_nodes: dict[str, list[onnx.NodeProto]], output_name_to_node: dict[str, onnx.NodeProto], ): """ Interface function that tries to fuse a node sequence containing a ReduceMean node into a single LayerNormalization node.
+----------------------+ | | | v [Root] --> ReduceMean --> Sub --> Pow --> ReduceMean --> Add --> Sqrt --> Div --> Mul --> Add (axis=2 or -1) | (Y=2) (axis=2 or -1) (E-6 or E-12 or 0) ^ | | +-------------------------------------------------+
Or, using Mul instead of Pow:
+----------------------+ | | | v [Root] --> ReduceMean --> Sub --> Mul --> ReduceMean --> Add --> Sqrt --> Div --> Mul --> Add (axis=2 or -1) | (in0=in1) (axis=2 or -1) (E-6 or E-12 or 0) ^ | | +-------------------------------------------------+
It also handles cases of duplicated sub nodes exported from older version of PyTorch:
+----------------------+ | v | +-------> Sub-----------------------------------------------+ | | | | | v [Root] --> ReduceMean --> Sub --> (Pow or Mul) --> ReduceMean --> Add --> Sqrt --> Div --> Mul --> Add | ^ | | +----------------------+ """ children = self.model.get_children(reduce_mean_node, input_name_to_nodes) if len(children) == 0 or len(children) > 2: return
root_input = reduce_mean_node.input[0]
if children[0].op_type != "Sub" or children[0].input[0] != root_input: return
if len(children) == 2: if children[1].op_type != "Sub" or children[1].input[0] != root_input: return
div_node = None for child in children: div_node = self.find_first_child_by_type(child, "Div", input_name_to_nodes, recursive=False) if div_node is not None: break if div_node is None: return
path_id, parent_nodes, _ = self.match_parent_paths( div_node, [ (["Sqrt", "Add", "ReduceMean", "Pow", "Sub"], [1, 0, 0, 0, 0]), (["Sqrt", "Add", "ReduceMean", "Pow", "Cast", "Sub"], [1, 0, 0, 0, 0, 0]), (["Sqrt", "Add", "ReduceMean", "Mul", "Sub"], [1, 0, 0, 0, 0]), (["Sqrt", "Add", "ReduceMean", "Mul", "Cast", "Sub"], [1, 0, 0, 0, 0, 0]), ], output_name_to_node, ) if path_id < 0: return
sub_node = parent_nodes[-1] if sub_node not in children: return
second_add_node = parent_nodes[1] i, add_weight = self.get_constant_input(second_add_node) if add_weight is None or add_weight <= 0 or add_weight > 1.0e-4: # Skip fusion since epsilon value is not expected. return
pow_or_mul_node = parent_nodes[3] if pow_or_mul_node.op_type == "Pow" and self.find_constant_input(pow_or_mul_node, 2.0) != 1: return elif pow_or_mul_node.op_type == "Mul" and pow_or_mul_node.input[0] != pow_or_mul_node.input[1]: return
mul_node = input_name_to_nodes[div_node.output[0]][0] if mul_node.op_type != "Mul": return
last_add_node = input_name_to_nodes[mul_node.output[0]][0] if last_add_node.op_type != "Add": return
subgraph_nodes = [reduce_mean_node] subgraph_nodes.extend(children) subgraph_nodes.extend(parent_nodes[:-1])
subgraph_nodes.extend([last_add_node, mul_node, div_node]) if not self.is_safe_to_fuse_nodes( subgraph_nodes, last_add_node.output, input_name_to_nodes, output_name_to_node, ): return
weight_input = mul_node.input[1 - self.input_index(div_node.output[0], mul_node)] if not self.is_constant_with_specified_rank(weight_input, 1): return
bias_input = last_add_node.input[1 - self.input_index(mul_node.output[0], last_add_node)] if not self.is_constant_with_specified_rank(bias_input, 1): return
self.nodes_to_remove.extend(subgraph_nodes)
normalize_node = onnx.helper.make_node( "LayerNormalization", name=self.create_unique_node_name(), inputs=[reduce_mean_node.input[0], weight_input, bias_input], outputs=[last_add_node.output[0]], ) normalize_node.attribute.extend([onnx.helper.make_attribute("epsilon", float(add_weight))]) self.nodes_to_add.append(normalize_node)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596# -------------------------------------------------------------------------# Copyright (c) Microsoft Corporation. All rights reserved.# Licensed under the MIT License. See License.txt in the project root for# license information.# --------------------------------------------------------------------------from __future__ import annotations
import numpy as npimport onnx
from ..onnx_model import ONNXModelfrom .fusion import Fusion
class ReplaceUpsampleWithResize(Fusion): """Replace Upsample with Resize."""
def __init__(self, model: ONNXModel, opset): """Initialize.""" super().__init__(model, "Resize", "Upsample") self.opset = opset
def fuse( self, node: onnx.NodeProto, input_name_to_nodes: dict[str, list[onnx.NodeProto]], output_name_to_node: dict[str, onnx.NodeProto], ): """Replace Upsample with Resize.""" mode = None for attr in node.attribute: if attr.name == "mode": mode = attr.s.decode("utf-8") break
scales_input = None if self.opset > 7: scales_input = node.input[1] if len(node.input) > 1 else "" resize_inputs = [node.input[0], node.name + "_roi", scales_input] else: if self.opset == 7: for attr in node.attribute: if attr.name == "scales": scales_input = attr.floats break
scales_input = np.array(list(scales_input), np.float32) else: h_scale = 1 w_scale = 1 for attr in node.attribute: if attr.name == "height_scale": h_scale = attr.float elif attr.name == "width_scale": w_scale = attr.float
scales_input = np.array([1, 1, h_scale, w_scale], np.float32)
scales_tensor = onnx.helper.make_tensor( name=node.name + "_scales", data_type=onnx.TensorProto.FLOAT, dims=scales_input.shape, vals=scales_input.flatten().tolist(), )
scales_node = onnx.helper.make_node( "Constant", inputs=[], outputs=[node.name + "_scales"], value=scales_tensor )
self.nodes_to_add.append(scales_node)
resize_inputs = [node.input[0], node.name + "_roi", node.name + "_scales"]
roi_tensor = onnx.helper.make_tensor( name=node.name + "_roi", data_type=onnx.TensorProto.FLOAT, dims=(len(scales_input) * 2,), vals=[0] * len(scales_input) + [1] * len(scales_input), )
roi_node = onnx.helper.make_node("Constant", inputs=[], outputs=[node.name + "_roi"], value=roi_tensor)
resize_node = onnx.helper.make_node( op_type="Resize", inputs=resize_inputs, outputs=node.output, mode=mode, nearest_mode="floor" )
self.nodes_to_remove.append(node) self.nodes_to_add.append(roi_node) self.nodes_to_add.append(resize_node)
def apply(self) -> bool: """Apply.""" if super().apply(): self.model.topological_sort() return True return False123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239# -------------------------------------------------------------------------# Copyright (c) Microsoft Corporation. All rights reserved.# Licensed under the MIT License. See License.txt in the project root for# license information.# --------------------------------------------------------------------------
import argparseimport loggingimport os
import numpy as npimport numpy.typing as nptimport onnxfrom onnx.onnx_pb import GraphProto, ModelProto, NodeProto, TensorProto
from onnxruntime.capi._pybind_state import quantize_matmul_bnb4
from .onnx_model import ONNXModelfrom .quant_utils import attribute_to_kwarg
logger = logging.getLogger(__name__)
class MatMulBnb4Quantizer: """Perform 4b quantization of constant MatMul weights using FP4 or NF4 data type"""
################## # quantization types, must be consistent with native code type # Bnb_DataType_t defined in blockwise_quant_block_bnb4.h
# 4b floating point with bias of 3 FP4 = 0
# 4b NormalFloat NF4 = 1
def __init__(self, model: ModelProto, quant_type: int, block_size: int, nodes_to_exclude=None): nodes_to_exclude = nodes_to_exclude or [] assert quant_type in [MatMulBnb4Quantizer.FP4, MatMulBnb4Quantizer.NF4] self.model = ONNXModel(model) self.quant_type = quant_type self.block_size = block_size self.nodes_to_exclude = set(nodes_to_exclude)
@staticmethod def __get_initializer(name, graph_path: list[GraphProto]) -> tuple[TensorProto, GraphProto]: for gid in range(len(graph_path) - 1, -1, -1): graph = graph_path[gid] for tensor in graph.initializer: if tensor.name == name: return tensor, graph return None, None
def bnb4_block_quant(self, fpweight: npt.ArrayLike) -> np.ndarray: """4b quantize fp32/fp16 weight"""
if len(fpweight.shape) != 2: raise ValueError("Current bnb4 block quantization only supports 2D tensors!") # need to copy since the transposed weight still has the original memory layout # Linear4bit quantizes its weight data which is the transposed weight fpweight_t = fpweight.transpose().copy()
rows, cols = fpweight.shape numel = rows * cols block_size = self.block_size num_blocks = (numel + block_size - 1) // block_size quantized_numel = (numel + 1) // 2
packed = np.zeros(quantized_numel, dtype="uint8") absmax = np.zeros(num_blocks, dtype=fpweight.dtype) # block wise quantization, fpweight_t is flattened and divided into blocks quantize_matmul_bnb4(packed, fpweight_t, absmax, block_size, self.quant_type, cols, rows)
return (packed, absmax)
def _bnb4_matmul_node_weight(self, node: NodeProto, graph_stack: list[GraphProto]) -> NodeProto: """If the node is MatMul with fp32 const weight, quantize the weight with int4, and return the new node"""
if node.op_type != "MatMul": return node # only care about MatMul for now
logger.debug(f"start to quantize {node.name} ...") if node.name in self.nodes_to_exclude: logger.debug(f"exclude to quantize {node.name} as specified by nodes_to_exclude...") return node
inputB = node.input[1] # noqa: N806 B, Bs_graph = MatMulBnb4Quantizer.__get_initializer(inputB, graph_stack) # noqa: N806 if B is None: logger.debug("MatMul doesn't have const weight. Skip to quantize") return node # only care about constant weight
B_array = onnx.numpy_helper.to_array(B) # noqa: N806 if len(B_array.shape) != 2: logger.debug("MatMul weight is not 2D. Skip to quantize") return node # can only process 2-D matrix
packed, absmax = self.bnb4_block_quant(B_array) B_quant = onnx.numpy_helper.from_array(packed) # noqa: N806 B_quant.name = B.name + "_Bnb4" for input in Bs_graph.input: if input.name == inputB: Bs_graph.input.remove(input) break
absmax_tensor = onnx.numpy_helper.from_array(absmax) absmax_tensor.name = B.name + "_absmax"
Bs_graph.initializer.extend([B_quant, absmax_tensor])
kwargs = {} rows, cols = B_array.shape kwargs["K"] = rows kwargs["N"] = cols kwargs["block_size"] = self.block_size kwargs["quant_type"] = self.quant_type
matmul_bnb4_node = onnx.helper.make_node( "MatMulBnb4", inputs=[node.input[0], B_quant.name, absmax_tensor.name], outputs=[node.output[0]], name=node.name + "_Bnb4" if node.name else "", domain="com.microsoft", **kwargs, )
logger.debug(f"complete quantization of {node.name} ...")
return matmul_bnb4_node
def _process_subgraph(self, graph_stack: list[GraphProto]): new_nodes = [] graph = graph_stack[-1]
for node in graph.node: graph_attrs = [ attr for attr in node.attribute if attr.type == onnx.AttributeProto.GRAPH or attr.type == onnx.AttributeProto.GRAPHS ] if graph_attrs: kwargs = {} for attr in node.attribute: if attr.type == onnx.AttributeProto.GRAPH: # recursive call to take care of sub-graph graph_stack.append(attr.g) kv = {attr.name: self._process_subgraph(graph_stack)} elif attr.type == onnx.AttributeProto.GRAPHS: value = [] for subgraph in attr.graphs: # recursive call to take care of sub-graph graph_stack.append(subgraph) value.extend([self._process_subgraph(graph_stack)]) kv = {attr.name: value} else: kv = attribute_to_kwarg(attr) kwargs.update(kv) node = onnx.helper.make_node( # noqa: PLW2901 node.op_type, node.input, node.output, name=node.name, **kwargs )
new_nodes.append(self._bnb4_matmul_node_weight(node, graph_stack))
graph.ClearField("node") graph.node.extend(new_nodes) graph_stack.pop() return graph
def process(self): # use a stack to keep track of sub-graphs graph_stack = [self.model.graph()] opset_import = self.model.opset_import()
has_ms_domain = False for opset in opset_import: if opset.domain == "com.microsoft": has_ms_domain = True if not has_ms_domain: opset_import.extend([onnx.helper.make_opsetid("com.microsoft", 1)])
self._process_subgraph(graph_stack) self.model.clean_initializers()
def parse_args(): parser = argparse.ArgumentParser( description="""Blockwise FP4/NF4 quantization for MatMul 2D weight matrices.
A weight matrix is partitioned into blocks, where each block is a contiguoussubset inside the flattened transposed weight matrix. Each block is quantizedinto a set of 4b integers with an absolute value scaling factor.""" )
parser.add_argument("--input_model", required=True, help="Path to the input model file") parser.add_argument("--output_model", required=True, help="Path to the output model file") parser.add_argument( "--quant_type", required=False, default=1, choices=[MatMulBnb4Quantizer.FP4, MatMulBnb4Quantizer.NF4], help="Quantization data type. 0: FP4, 1: NF4", ) parser.add_argument( "--block_size", required=False, default=64, help="Block size for blockwise quantization. Note: bnb.nn.Linear4bit only uses block_size=64", ) parser.add_argument("-v", "--verbose", required=False, action="store_true") parser.set_defaults(verbose=False) parser.add_argument( "--nodes_to_exclude", nargs="+", type=str, required=False, default=[], help="Specify the nodes to be excluded from quantization with node names", )
return parser.parse_args()
if __name__ == "__main__": args = parse_args() if args.verbose: logger.setLevel(logging.DEBUG)
input_model_path = args.input_model output_model_path = args.output_model
if os.path.exists(output_model_path): logger.error(f"file {output_model_path} already exists") raise Exception(f"file {output_model_path} already exists")
model = onnx.load(input_model_path) quant = MatMulBnb4Quantizer(model, args.quant_type, args.block_size, nodes_to_exclude=args.nodes_to_exclude) quant.process() quant.model.save_model_to_file(output_model_path, True)12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874# -------------------------------------------------------------------------# Copyright (c) Microsoft Corporation. All rights reserved.# Licensed under the MIT License. See License.txt in the project root for# license information.# --------------------------------------------------------------------------
from __future__ import annotations
import argparseimport copyimport loggingimport os
import ml_dtypesimport numpy as npimport numpy.typing as nptimport onnximport onnx_ir as irfrom onnx.onnx_pb import GraphProto, ModelProto, NodeProto, TensorProto
from onnxruntime.capi._pybind_state import ( quantize_matmul_2bits, quantize_matmul_4bits, quantize_matmul_8bits, quantize_qdq_matmul_4bits,)
from .calibrate import CalibrationDataReaderfrom .neural_compressor import gptq_quantize, rtn_quantizefrom .onnx_model import ONNXModelfrom .quant_utils import QuantFormat, attribute_to_kwarg
logging.basicConfig(format="%(asctime)s %(name)s [%(levelname)s] - %(message)s", level=logging.INFO)logger = logging.getLogger(__name__)
class WeightOnlyQuantConfig: def __init__( self, algorithm: str, quant_format: QuantFormat, op_types_to_quantize: tuple[str, ...] | None = None, quant_axes: tuple[tuple[str, int], ...] | None = None, customized_weight_config: dict | None = None, ): """This is the Base class for Weight Only blockwise quantization Configuration.
Args: algorithm: weight only quantize algorithm name. quant_format: QuantFormat{QOperator, QDQ}. QOperator format quantizes the model with quantized operators directly. QDQ format quantize the model by inserting QuantizeLinear/DeQuantizeLinear on the tensor. op_types_to_quantize (optional): set of operator types to quantize. Default {MatMul} quant_axes (dict[str, int], optional): op:axis, which axis to quantize for an op. Default {MatMul: 0, Gather: 1} customized_weight_config: customized weight config for nodes if needed. It is dictionary with node name as key, and the value is a dict of customized config. """ self.algorithm = algorithm self.quant_format = quant_format self.op_types_to_quantize = set(op_types_to_quantize) if op_types_to_quantize else {"MatMul"} self.quant_axes = dict(quant_axes) if quant_axes else {"MatMul": 0, "Gather": 1} self.customized_weight_config = customized_weight_config
class RTNWeightOnlyQuantConfig(WeightOnlyQuantConfig): def __init__( self, ratios=None, quant_format=QuantFormat.QOperator, op_types_to_quantize: tuple[str, ...] | None = None, customized_weight_config: dict | None = None, ): """ This is a class for round-to-nearest (RTN) algorithm Weight Only Quant Configuration. RTN is the most straightforward way to quantize weight using scale maps.
Args: ratios: percentile of clip. Defaults to {}. quant_format (QuantFormat{QOperator, QDQ}, optional): QOperator format quantizes the model with quantized operators directly. QDQ format quantize the model by inserting QuantizeLinear/DeQuantizeLinear on the tensor. Defaults to QuantFormat.QOperator. op_types_to_quantize (optional): set of operator types to quantize. customized_weight_config: customized weight config for nodes if needed. It is dictionary with node name as key, and the value is a dict of customized config. """ assert quant_format == QuantFormat.QOperator, "RTN only supports QOperator format"
if ratios is None: ratios = {} super().__init__( algorithm="RTN", quant_format=quant_format, op_types_to_quantize=op_types_to_quantize, customized_weight_config=customized_weight_config, ) self.ratios = ratios
class KQuantWeightOnlyQuantConfig(WeightOnlyQuantConfig): def __init__( self, ratios=None, quant_format=QuantFormat.QOperator, op_types_to_quantize: tuple[str, ...] | None = None, customized_weight_config: dict | None = None, ): """ This is a class for k-quant algorithm Weight Only Quant Configuration.
Args: ratios: percentile of clip. Defaults to {}. quant_format (QuantFormat{QOperator, QDQ}, optional): QOperator format quantizes the model with quantized operators directly. QDQ format quantize the model by inserting QuantizeLinear/DeQuantizeLinear on the tensor. Defaults to QuantFormat.QOperator. op_types_to_quantize (optional): set of operator types to quantize. """ assert quant_format == QuantFormat.QOperator, "k-quant only supports QOperator format"
if ratios is None: ratios = {} super().__init__( algorithm="k_quant", quant_format=quant_format, op_types_to_quantize=op_types_to_quantize, customized_weight_config=customized_weight_config, ) self.ratios = ratios
class GPTQWeightOnlyQuantConfig(WeightOnlyQuantConfig): def __init__( self, calibration_data_reader: CalibrationDataReader | None = None, percdamp=0.01, block_size=128, actorder=False, mse=False, perchannel=True, quant_format=QuantFormat.QOperator, op_types_to_quantize: tuple[str, ...] | None = None, ): """ This is a class for GPTQ algorithm Weight Only Quant Configuration. GPTQ algorithm provides more accurate quantization but requires more computational resources.
Args: calibration_data_reader: a calibration data reader. It enumerates calibration data and generates inputs for the original model. percdamp: percent of the average Hessian diagonal to use for dampening. block_size (int, optional): channel number in one block to execute a GPTQ quantization iteration. actorder (bool, optional): whether rearrange Hessian matrix considering the diag's value. mse (bool, optional): whether get scale and zero point with mse error. perchannel (bool, optional): whether quantize weight per-channel. quant_format (QuantFormat{QOperator, QDQ}, optional): QOperator format quantizes the model with quantized operators directly. QDQ format quantize the model by inserting QuantizeLinear/DeQuantizeLinear on the tensor. Defaults to QuantFormat.QOperator. op_types_to_quantize (optional): set of operator types to quantize. """ assert quant_format == QuantFormat.QOperator, "GPTQ only supports QOperator format"
super().__init__( algorithm="GPTQ", quant_format=quant_format, op_types_to_quantize=op_types_to_quantize, ) self.calibration_data_reader = calibration_data_reader self.percdamp = percdamp self.block_size = block_size self.actorder = actorder self.mse = mse self.perchannel = perchannel
class HQQWeightOnlyQuantConfig(WeightOnlyQuantConfig): def __init__( self, block_size=128, bits=4, axis=1, quant_format=QuantFormat.QOperator, op_types_to_quantize: tuple[str, ...] | None = None, quant_axes: tuple[tuple[str, int], ...] | None = None, ): """ This is a class for HQQ algorithm Weight Only Quant Configuration. HQQ algorithm quant weight without needing calibrate data.
Args: block_size (int, optional): channel number in one block to execute a HQQ quantization iteration. bits (int, optional): how many bits to represent weight. axis (int, optional): 0 or 1. which axis to quantize. https://arxiv.org/pdf/2309.15531.pdf quant_format (QuantFormat{QOperator, QDQ}, optional): QOperator format quantizes the model with quantized operators directly. QDQ format quantize the model by inserting QuantizeLinear/DeQuantizeLinear on the tensor. Defaults to QuantFormat.QOperator. op_types_to_quantize (optional): set of operator types to quantize. quant_axes (dict[str, int], optional): op:axis, which axis to quantize for an op. Default {MatMul: 0, Gather: 1} """ assert quant_format == QuantFormat.QOperator, "HQQ only supports QOperator format"
super().__init__( algorithm="HQQ", quant_format=quant_format, op_types_to_quantize=op_types_to_quantize, quant_axes=quant_axes, ) self.block_size = block_size self.bits = bits self.axis = axis
class DefaultWeightOnlyQuantConfig(WeightOnlyQuantConfig): def __init__( self, block_size: int = 128, is_symmetric: bool = False, accuracy_level: int | None = None, quant_format=QuantFormat.QOperator, op_types_to_quantize: tuple[str, ...] | None = None, quant_axes: tuple[tuple[str, int], ...] | None = None, bits: int = 4, channel_wised_quantize: bool = False, ): """ This is a class for weight only affine quantization configuration.
Args: block_size (int, optional): channel number in one block to execute an affine quantization iteration. is_symmetric (bool, optional): whether quantize weight symmetrically. accuracy_level (int, optional): Accuracy level of the 4-bit quantized MatMul computation. Refer to the MatMulNBits contrib op's 'accuracy_level' attribute for details. (https://github.com/microsoft/onnxruntime/blob/main/docs/ContribOperators.md#commicrosoftmatmulnbits) quant_format (QuantFormat{QOperator, QDQ}, optional): QOperator format quantizes the model with quantized operators directly. QDQ format quantize the model by inserting QuantizeLinear/DeQuantizeLinear on the tensor. Defaults to QuantFormat.QOperator. op_types_to_quantize (optional): set of operator types to quantize. quant_axes (dict[str, int], optional): op:axis, which axis to quantize for an op. Default {MatMul: 0, Gather: 1} bits (int, optional): number of bits per element after quantization. Default 4. """ super().__init__( algorithm="DEFAULT", quant_format=quant_format, op_types_to_quantize=op_types_to_quantize, quant_axes=quant_axes, ) self.block_size = block_size self.is_symmetric = is_symmetric self.bits = bits self.accuracy_level = accuracy_level self.channel_wised_quantize = channel_wised_quantize if channel_wised_quantize and quant_format == QuantFormat.QOperator: raise NotImplementedError("QuantFormat.QOperator is not supported channel_wised_quantize yet")
class NVAWQWeightOnlyQuantConfig(WeightOnlyQuantConfig): def __init__( self, tokenizer_dir, dataset_name="cnn", cache_dir="./cache", calibration_method="awq_lite", ): """ Configuration for the nvidia_awq quantization method.
Args: tokenizer_dir (str): pathof the tokenizer dir. dataset_name (str): Name of the dataset. cache_dir (str): Directory for caching. calibration_method (str): calib method for nvidia_awq. """ # Import torch and DataLoader try: import torch # noqa: PLC0415 from torch.utils.data import DataLoader # noqa: PLC0415
self.torch = torch self.DataLoader = DataLoader except ImportError: print( "Error: The 'torch' library is required but not installed. Please install it using 'pip install torch'." ) raise ImportError("torch is not installed. Exiting.") from None
# Import datasets try: from datasets import load_dataset # noqa: PLC0415
self.load_dataset = load_dataset except ImportError: print( "Error: The 'datasets' library is required but not installed. Please install it using 'pip install datasets'." ) raise ImportError("datasets is not installed. Exiting.") from None
# Import transformers try: from transformers import AutoConfig, AutoTokenizer # noqa: PLC0415
self.AutoConfig = AutoConfig self.AutoTokenizer = AutoTokenizer except ImportError: print( "Error: The 'transformers' library is required but not installed. Please install it using 'pip install transformers'." ) raise ImportError("transformers is not installed. Exiting.") from None
super().__init__( algorithm="nvidia_awq", quant_format=QuantFormat.QDQ, op_types_to_quantize=None, # Assuming op_types_to_quantize is handled elsewhere quant_axes=None, # Assuming quant_axes is handled elsewhere )
# Determine the device device = self.torch.device("cuda" if self.torch.cuda.is_available() else "cpu")
calib_inputs = self.get_calib_inputs( dataset_name=dataset_name, model_name=tokenizer_dir, cache_dir=cache_dir, calib_size=32, batch_size=1, block_size=512, device=device, use_fp16=True, use_buffer_share=False, add_past_kv_inputs=True, max_calib_rows_to_load=128, add_position_ids=True, )
self.calibration_data_reader = calib_inputs self.calibration_method = calibration_method
def make_model_input( self, config, input_ids_arg, attention_mask_arg, add_past_kv_inputs, device, use_fp16, use_buffer_share, add_position_ids, ): # Access torch from the instance variable torch = self.torch
input_ids = input_ids_arg attention_mask = attention_mask_arg
if isinstance(input_ids_arg, list): input_ids = torch.tensor(input_ids_arg, device=device, dtype=torch.int64) attention_mask = torch.tensor(attention_mask_arg, device=device, dtype=torch.int64)
inputs = { "input_ids": input_ids.contiguous(), "attention_mask": attention_mask.contiguous(), }
if add_position_ids: position_ids = attention_mask.long().cumsum(-1) - 1 position_ids.masked_fill_(attention_mask == 0, 1) inputs["position_ids"] = position_ids.contiguous()
if add_past_kv_inputs: torch_dtype = torch.float16 if use_fp16 else torch.float32 batch_size, sequence_length = input_ids.shape max_sequence_length = config.max_position_embeddings num_heads, head_size = ( config.num_key_value_heads, config.hidden_size // config.num_attention_heads, ) for i in range(config.num_hidden_layers): past_key = torch.zeros( batch_size, num_heads, max_sequence_length if use_buffer_share else 0, head_size, device=device, dtype=torch_dtype, ) past_value = torch.zeros( batch_size, num_heads, max_sequence_length if use_buffer_share else 0, head_size, device=device, dtype=torch_dtype, ) inputs.update( { f"past_key_values.{i}.key": past_key.contiguous(), f"past_key_values.{i}.value": past_value.contiguous(), } )
return inputs
def get_calib_inputs( self, dataset_name, model_name, cache_dir, calib_size, batch_size, block_size, device, use_fp16, use_buffer_share, add_past_kv_inputs, max_calib_rows_to_load, add_position_ids, ): # Access transformers and datasets from the instance variables auto_config = self.AutoConfig auto_tokenizer = self.AutoTokenizer load_dataset = self.load_dataset
config = auto_config.from_pretrained( model_name, use_auth_token=True, cache_dir=cache_dir, trust_remote_code=True ) tokenizer = auto_tokenizer.from_pretrained( model_name, use_auth_token=True, cache_dir=cache_dir, trust_remote_code=True ) tokenizer.add_special_tokens({"pad_token": "[PAD]"}) tokenizer.pad_token = tokenizer.eos_token
assert calib_size <= max_calib_rows_to_load, "calib size should be no more than max_calib_rows_to_load"
if "cnn" in dataset_name: dataset2 = load_dataset("cnn_dailymail", name="3.0.0", split="train").select(range(max_calib_rows_to_load)) column = "article" elif "pile" in dataset_name: dataset2 = load_dataset("mit-han-lab/pile-val-backup", split="validation") column = "text" else: raise ValueError(f'dataset "{dataset_name}" not supported')
dataset2 = dataset2[column][:calib_size] batch_encoded = tokenizer.batch_encode_plus( dataset2, return_tensors="pt", padding=True, truncation=True, max_length=block_size ) batch_encoded = batch_encoded.to(device) batch_encoded_input_ids = batch_encoded["input_ids"] batch_encoded_attention_mask = batch_encoded["attention_mask"]
# Access DataLoader from the instance variable data_loader = self.DataLoader
calib_dataloader_input_ids = data_loader(batch_encoded_input_ids, batch_size=batch_size, shuffle=False) calib_dataloader_attention_mask = data_loader( batch_encoded_attention_mask, batch_size=batch_size, shuffle=False )
assert len(calib_dataloader_input_ids.dataset) == len(calib_dataloader_attention_mask.dataset) assert len(calib_dataloader_input_ids) == len(calib_dataloader_attention_mask)
number_of_batched_samples = calib_size // batch_size
batched_input_ids = [] for idx, data in enumerate(calib_dataloader_input_ids): batched_input_ids.append(data) if idx == (number_of_batched_samples - 1): break
batched_attention_mask = [] for idx, data in enumerate(calib_dataloader_attention_mask): batched_attention_mask.append(data) if idx == (number_of_batched_samples - 1): break
print( f"\n--Quantize-Script-- number_of_batched_samples={number_of_batched_samples}, " f"batch-input-ids-list-len={len(batched_input_ids)}, batched_attention_mask={len(batched_attention_mask)}\n" )
batched_inputs_list = [] for i in range(number_of_batched_samples): input_ids = batched_input_ids[i] attention_mask = batched_attention_mask[i]
inputs = self.make_model_input( config, input_ids, attention_mask, add_past_kv_inputs, device, use_fp16, use_buffer_share, add_position_ids, ) inputs = {input_name: torch_tensor.cpu().numpy() for input_name, torch_tensor in inputs.items()} batched_inputs_list.append(inputs)
print(f"\n--Quantize-Script-- number of batched inputs = {len(batched_inputs_list)}\n") return batched_inputs_list
def is_divisible(val1, val2): return int(val2 * np.ceil(val1 / val2)) == val1
class HQQWeightOnlyQuantizer: def __init__( self, config: HQQWeightOnlyQuantConfig, ): self.config = config
# Proximal solver || weight - dequantize(quantize(weight))||_p^p @staticmethod def optimize_weights( tensor, scale, zero, min_max: list[int], axis: int = 0, opt_params: dict | None = None, verbose=False, ): import torch # noqa: PLC0415
opt_params = {"lp_norm": 0.7, "beta": 1e1, "kappa": 1.01, "iters": 20} if opt_params is None else opt_params lp_norm, beta, kappa, iters = ( opt_params["lp_norm"], opt_params["beta"], opt_params["kappa"], opt_params["iters"], )
dtype = torch.float16 if tensor.is_cuda else torch.float32 w_f = tensor.to(dtype) scale = scale.to(dtype) zero = zero.to(dtype)
def shrink_op(x, beta, p=lp_norm): if p == 1: return torch.sign(x) * torch.nn.functional.relu(torch.abs(x) - 1.0 / beta) else: return torch.sign(x) * torch.nn.functional.relu( torch.abs(x) - (1.0 / beta) * torch.pow(torch.abs(x) + 1e-8, p - 1) )
best_error = 1e4 for i in range(iters): w_q = torch.round(w_f * scale + zero).clamp(min_max[0], min_max[1]) w_r = (w_q - zero) / scale w_e = shrink_op(w_f - w_r, beta) zero = torch.mean(w_q - (w_f - w_e) * scale, axis=axis, keepdim=True) beta *= kappa
current_error = float(torch.abs(w_f - w_r).mean()) if verbose: print(i, np.round(current_error, 6)) if current_error < best_error: best_error = current_error else: break
del w_f, w_q, w_r, w_e
return scale, zero
@staticmethod def pack_on_row_fast_248bit(pack_tensor, ori_int_tensor, bits): if pack_tensor.shape[0] == ori_int_tensor.shape[0]: ori_int_tensor = ori_int_tensor.T pack_tensor = pack_tensor.T if bits in [2, 4, 8]: compress_ratio = pack_tensor.element_size() * 8 // bits for j in range(compress_ratio): pack_tensor[0:] |= ori_int_tensor[j::compress_ratio] << (bits * (j)) else: raise NotImplementedError("Only 2,4,8 bits are supported.")
# from Official implementation of Half-Quadratic Quantization (HQQ) def quantize_internal( self, tensor, bits=4, channel_wise=True, group_size=64, optimize=True, round_zero=True, axis=1 ): import torch # noqa: PLC0415
weight = tensor.float() ori_shape = weight.shape
pad_len = (group_size - ori_shape[axis] % group_size) % group_size if axis == 1: weight = torch.nn.functional.pad(weight, (0, pad_len), "constant", 0) else: weight = torch.nn.functional.pad(weight, (0, 0, 0, pad_len), "constant", 0) shape = weight.shape
# Reshape for grouping if (group_size is not None) and channel_wise: weight = weight.reshape([-1, group_size]) if (axis == 1) else weight.reshape([group_size, -1])
# Get min/max values if channel_wise is False: _min, _max = weight.min(), weight.max() optimize = False else: _min = weight.min(axis=axis, keepdim=True)[0] _max = weight.max(axis=axis, keepdim=True)[0]
max_v = 2**bits - 1 min_v = 0 min_max = [min_v, max_v]
# 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. # clamp to avoid half-precision problems scale = (max_v / (_max - _min)).clamp(max=2e4) #!!!!!!!!!!!!!!! min_max_axis = _max - _min if (min_max_axis == 0).sum().item() > 0: min_max_axis[min_max_axis == 0] = max_v scale = (max_v / min_max_axis).clamp(max=2e4) zero = -_min * scale
if round_zero: zero = torch.round(zero)
# Fine-tune weights if optimize: scale, zero = self.optimize_weights(tensor=weight, scale=scale, zero=zero, min_max=min_max, axis=axis)
# Quantize # Necessary for fake quantization backprop w_q = torch.round(weight * scale + zero).clamp(min_max[0], min_max[1]) w_q = w_q.reshape(shape).int()
scale = 1.0 / scale if axis == 1: scale = scale.reshape(shape[0], -1) zero = zero.reshape(shape[0], -1) else: scale = scale.reshape(-1, shape[-1]) zero = zero.reshape(-1, shape[-1]) # cleanup del weight, _min, _max
return w_q, scale.to(tensor.dtype), zero.to(tensor.dtype)
def quantize(self, node: NodeProto, graph_stack: list[GraphProto]) -> list[NodeProto]: """ Target node: QOperator node: QDQ nodes: MatMul MatMulNBits DeQuantizeLinear -> MatMul Gather GatherBlockQuantized Gather, Gather, Gather (optional) -> DequantizeLinear If the node is target node with fp32 or fp16 const weight, quantize the weight to int4 and return the new nodes. If QOperator format, return the corresponding QOperator nodes. If QDQ format, return the corresdponging QDQ nodes. Gather (quantized data) + Gather (scales) + Gather (optional, zero points) -> DequantizeLinear is not supported yet because Gather does not support int4 data. """ # With HQQ, zero points are in float. Current GatherBlockQuantized does not support float zero points. if node.op_type == "Gather": raise NotImplementedError("Gather quantization is not supported yet in HQQ")
import torch # noqa: PLC0415
logger.info(f"start to quantize {node.name} ...") input_b = node.input[1] b_pb, bs_graph = get_initializer(input_b, graph_stack) if b_pb is None: logger.info("MatMul doesn't have const weight. Skip to quantize") return [node] # only care about constant weight
b_array = onnx.numpy_helper.to_array(b_pb) b_original_shape = b_array.shape if len(b_original_shape) != 2: if len(b_original_shape) < 2: logger.info("MatMul weight has fewer than 2 dimensions. Skip to quantize.") return [node] leading = b_original_shape[:-2] if any(d != 1 for d in leading): logger.info( "MatMul weight has non-unit batch dims %s; N-D batched quantization not supported. " "Skip to quantize.", list(leading), ) return [node] # Squeeze all unit leading dims to obtain a 2-D weight [K, N] b_array = b_array.reshape(b_original_shape[-2], b_original_shape[-1]) else: b_original_shape = None # already 2-D, no reshape needed b_array_torch = torch.from_numpy(b_array) if torch.cuda.is_available(): b_array_torch = b_array_torch.cuda()
bits = self.config.bits quant_weight_torch, scales_torch, zero_points_torch = self.quantize_internal( b_array_torch.T, bits=bits, group_size=self.config.block_size ) quant_weight_torch = quant_weight_torch.contiguous() scales_torch = scales_torch.contiguous() zero_points_torch = zero_points_torch.contiguous()
packed_size = 8 // bits # number of elements packed into one byte
packed_torch = torch.zeros( (quant_weight_torch.shape[0], quant_weight_torch.shape[1] // packed_size), dtype=torch.uint8, device=quant_weight_torch.device, ) self.pack_on_row_fast_248bit(packed_torch, quant_weight_torch, bits) scales = scales_torch.cpu().numpy() zero_points = zero_points_torch.cpu().numpy() # reshape to the predefined shape in MatmulNbits scales = scales.reshape(-1) zero_points = zero_points.reshape(-1) rows, cols = b_array_torch.shape block_size = self.config.block_size blob_size = block_size // packed_size k_blocks = (rows + block_size - 1) // block_size packed_torch = packed_torch.reshape(cols, k_blocks, blob_size)
b_quant = onnx.numpy_helper.from_array(packed_torch.cpu().numpy()) b_quant.name = b_pb.name + "_Q" + str(bits) for input in bs_graph.input: if input.name == input_b: bs_graph.input.remove(input) break
scales_tensor = onnx.numpy_helper.from_array(scales) scales_tensor.name = b_pb.name + "_scales" bs_graph.initializer.extend([b_quant, scales_tensor])
input_names = [node.input[0], b_quant.name, scales_tensor.name] zp_tensor = onnx.numpy_helper.from_array(zero_points) zp_tensor.name = b_pb.name + "_zero_points" bs_graph.initializer.extend([zp_tensor]) input_names.append(zp_tensor.name)
kwargs = {} rows, cols = b_array.shape kwargs["K"] = rows kwargs["N"] = cols kwargs["bits"] = bits kwargs["block_size"] = self.config.block_size
# When rank(A) >= rank_b_orig, the reshape would be a no-op since MatMulNBits # already produces the correct output shape. a_static_rank = _get_static_rank(node.input[0], graph_stack) rank_b_orig = len(b_original_shape) if b_original_shape is not None else 0 needs_reshape = b_original_shape is not None and (a_static_rank is None or a_static_rank < rank_b_orig) matmul_q_output = node.output[0] if not needs_reshape else node.output[0] + "_pre_reshape" matmul_q_node = onnx.helper.make_node( "MatMulNBits", inputs=input_names, outputs=[matmul_q_output], name=node.name + "_Q" + str(bits) if node.name else "", domain="com.microsoft", **kwargs, )
output_nodes = [matmul_q_node] if needs_reshape: # Restore ONNX MatMul broadcast shape on the output. # MatMul(A, B_orig) output shape (with B_orig leading dims all 1) is: # [1] * max(rank(B_orig) - rank(A), 0) + A.shape[:-1] + [N] # MatMulNBits with squeezed B produces [...A.shape[:-1], N] (rank=rank(A)), # so we only need to prepend leading 1s when rank(B_orig) > rank(A). output_nodes.extend( _build_nbits_output_reshape( a_input_name=node.input[0], b_original_shape=b_original_shape, target_graph=bs_graph, name_prefix=(node.name + "_Q" + str(bits)) if node.name else (b_pb.name + "_Q" + str(bits)), pre_reshape_output=matmul_q_output, final_output=node.output[0], ) )
logger.info(f"complete quantization of {node.name} ...")
return output_nodes
def get_initializer(name, graph_path: list[GraphProto]) -> tuple[TensorProto, GraphProto]: for gid in range(len(graph_path) - 1, -1, -1): graph = graph_path[gid] for tensor in graph.initializer: if tensor.name == name: return tensor, graph return None, None
def _get_static_rank(tensor_name: str, graph_path: list[GraphProto]) -> int | None: """Return the static rank of a tensor if its shape is known, else None.
Searches graph inputs, value_info, and outputs in the graph stack (inner-most graph first). A known shape requires ``HasField('shape')`` to be true on the tensor_type; the rank is then ``len(shape.dim)``. Individual dim sizes may still be symbolic — only the rank (dimension count) matters here. """ for gid in range(len(graph_path) - 1, -1, -1): graph = graph_path[gid] for vi in list(graph.input) + list(graph.value_info) + list(graph.output): if vi.name == tensor_name: tt = vi.type.tensor_type if tt.HasField("shape"): return len(tt.shape.dim) return None return None
def _build_nbits_output_reshape( a_input_name: str, b_original_shape: tuple, target_graph: GraphProto, name_prefix: str, pre_reshape_output: str, final_output: str,) -> list[NodeProto]: """Build the reshape chain that restores the ONNX MatMul-broadcast output shape.
MatMulNBits produces shape ``[...A_batch_dims, M, N]`` (rank = rank(A)). To match the original ``MatMul(A, B_orig)`` output, where B_orig has all-unit leading dims, we need:
a_rank_eff = max(rank(A), 2) # ONNX promotes 1-D A to rank-2 out_shape = [1] * max(rank(B_orig) - a_rank_eff, 0) + A.shape[:-1] + [N]
This is built dynamically via Shape/Gather/Max/Sub/Max/ConstantOfShape/Slice/Concat so it works regardless of A's static rank (handles rank(A) == 1, rank(A) == 2 — the common transformer case — as well as rank(A) >= rank(B_orig) where no leading-1 prepending is needed). All ops used are valid from opset 11 onward.
Args: a_input_name: name of the activation input edge (A) feeding MatMulNBits. b_original_shape: the original (pre-squeeze) shape of B, e.g. ``(1, K, N)``. target_graph: graph proto to append helper initializers into. name_prefix: unique prefix for generated node/initializer names. pre_reshape_output: name of the MatMulNBits output edge (the input of the generated Reshape). final_output: name of the final edge produced by the generated Reshape (must match the original MatMul output edge).
Returns: List of nodes to append to the consumer's ``output_nodes`` after the MatMulNBits node. Initializers are appended to ``target_graph`` in place. """ rank_b_orig = len(b_original_shape) n_dim = b_original_shape[-1]
# Incorporate the unique output tensor name so initializer names are unique # even when multiple MatMul nodes share the same node.name (Fix 2). p = name_prefix + "_" + final_output init_zero = p + "_zero" init_one = p + "_one" init_two = p + "_two" init_one_vec = p + "_one_vec" init_rank_b = p + "_rank_b" init_n_vec = p + "_n_vec" init_zero_vec = p + "_zero_vec" init_one_value_template = p + "_one_value"
target_graph.initializer.extend( [ onnx.numpy_helper.from_array(np.array(0, dtype=np.int64), name=init_zero), onnx.numpy_helper.from_array(np.array(1, dtype=np.int64), name=init_one), onnx.numpy_helper.from_array(np.array(2, dtype=np.int64), name=init_two), onnx.numpy_helper.from_array(np.array([1], dtype=np.int64), name=init_one_vec), onnx.numpy_helper.from_array(np.array(rank_b_orig, dtype=np.int64), name=init_rank_b), onnx.numpy_helper.from_array(np.array([n_dim], dtype=np.int64), name=init_n_vec), onnx.numpy_helper.from_array(np.array([0], dtype=np.int64), name=init_zero_vec), ] )
a_shape = p + "_a_shape" a_shape_of_shape = p + "_a_shape_of_shape" a_rank = p + "_a_rank" a_rank_eff = p + "_a_rank_eff" extra_raw = p + "_extra_raw" extra_count = p + "_extra_count" extra_count_vec = p + "_extra_count_vec" extra_ones = p + "_extra_ones" a_rank_minus_one = p + "_a_rank_m1" a_rank_minus_one_vec = p + "_a_rank_m1_vec" a_prefix_shape = p + "_a_prefix_shape" target_shape = p + "_target_shape"
nodes = [ onnx.helper.make_node("Shape", [a_input_name], [a_shape], name=p + "_shape_a"), # Use Shape(shape) + Gather instead of Size to stay within opset 11 # (Size requires opset >= 13 when applied to a shape tensor). # Shape applied to the 1-D shape vector yields [rank_a] as a 1-element # tensor; Gather with scalar index 0 extracts it as a scalar int64. onnx.helper.make_node("Shape", [a_shape], [a_shape_of_shape], name=p + "_shape_of_a_shape"), onnx.helper.make_node("Gather", [a_shape_of_shape, init_zero], [a_rank], name=p + "_gather_rank"), # ONNX MatMul promotes a 1-D activation to rank-2 before computing the # output shape, so use Max(a_rank, 2) as the effective rank when # computing how many leading 1s to prepend. onnx.helper.make_node("Max", [a_rank, init_two], [a_rank_eff], name=p + "_max_rank_eff"), onnx.helper.make_node("Sub", [init_rank_b, a_rank_eff], [extra_raw], name=p + "_sub"), onnx.helper.make_node("Max", [extra_raw, init_zero], [extra_count], name=p + "_max"), onnx.helper.make_node("Reshape", [extra_count, init_one_vec], [extra_count_vec], name=p + "_reshape_extra"), onnx.helper.make_node( "ConstantOfShape", [extra_count_vec], [extra_ones], name=p + "_const_ones", value=onnx.helper.make_tensor( name=init_one_value_template, data_type=TensorProto.INT64, dims=[1], vals=[1], ), ), onnx.helper.make_node("Sub", [a_rank, init_one], [a_rank_minus_one], name=p + "_sub_one"), onnx.helper.make_node( "Reshape", [a_rank_minus_one, init_one_vec], [a_rank_minus_one_vec], name=p + "_reshape_rank_m1" ), onnx.helper.make_node( "Slice", [a_shape, init_zero_vec, a_rank_minus_one_vec, init_zero_vec], [a_prefix_shape], name=p + "_slice_a_prefix", ), onnx.helper.make_node( "Concat", [extra_ones, a_prefix_shape, init_n_vec], [target_shape], name=p + "_concat_target", axis=0, ), onnx.helper.make_node( "Reshape", [pre_reshape_output, target_shape], [final_output], name=p + "_reshape_out", ), ] return nodes
# transpose int4 matrix (packed as uint8)def transpose_packed_int4_matrix(packed, rows, cols): # unpack to int4 matrix total = rows * cols high = (packed >> 4) & 0x0F low = packed & 0x0F int4_vals = np.empty(total, dtype=np.uint8) int4_vals[0::2] = low int4_vals[1::2] = high int4_matrix = int4_vals.reshape((rows, cols))
# transpose int4 matrix int4_matrix_transposed = int4_matrix.T
# pack to uint8 flat = int4_matrix_transposed.reshape(-1) packed = ((flat[1::2] << 4) & 0xF0) | (flat[0::2] & 0x0F) return packed.astype(np.uint8)
class DefaultWeightOnlyQuantizer: def __init__(self, config: DefaultWeightOnlyQuantConfig): self.config = config
def qbits_block_quant(self, fp32weight: npt.ArrayLike) -> tuple[np.ndarray, np.ndarray, np.ndarray]: """4b/8b quantize fp32 weight to int4 using C++ kernels."""
qbits = self.config.bits kpack = 8 // qbits if len(fp32weight.shape) != 2: raise ValueError("Current int4 block quantization only supports 2D tensors!") rows, cols = fp32weight.shape
block_size = self.config.block_size k_blocks = (rows + block_size - 1) // block_size
if self.config.quant_format == QuantFormat.QOperator: blob_size = (block_size + kpack - 1) // kpack padded_rows = k_blocks * block_size pad_len = padded_rows - rows if pad_len > 0: fp32weight = np.pad(fp32weight, ((0, pad_len), (0, 0)), "constant")
# block wise quantization, each block comes from a single column packed = np.zeros((cols, k_blocks, blob_size), dtype="uint8") zero_point = np.zeros((cols, ((k_blocks + kpack - 1) // kpack)), dtype="uint8") scales = np.zeros((cols, k_blocks), dtype=fp32weight.dtype) if qbits == 2: quantize_matmul_2bits( packed, fp32weight, scales, zero_point, block_size, cols, rows, self.config.is_symmetric ) elif qbits == 8: quantize_matmul_8bits( packed, fp32weight, scales, zero_point, block_size, cols, rows, self.config.is_symmetric ) else: quantize_matmul_4bits( packed, fp32weight, scales, zero_point, block_size, cols, rows, self.config.is_symmetric ) else: # block size equal to rows (K) if channel wised quantize enabled block_size = rows if self.config.channel_wised_quantize else self.config.block_size k_blocks = (rows + block_size - 1) // block_size
assert qbits == 4, "QDQ format only support 4 bits quantization" packed = np.zeros((rows * cols + 1) // 2, dtype="uint8") zero_point = np.zeros((cols * k_blocks + 1) // 2, dtype="uint8") scales = np.zeros((k_blocks, cols), dtype=fp32weight.dtype) quantize_qdq_matmul_4bits( packed, fp32weight, scales, zero_point, block_size, cols, rows, self.config.is_symmetric )
return (packed, scales, zero_point)
def quantize_matmul(self, node: NodeProto, graph_stack: list[GraphProto]) -> list[NodeProto]: """ Quantize weight B of MatMul node to int4 or int8. Supports 2D constant matrix, and N-D constant matrices whose leading dimensions are all 1 (which are squeezed to 2D before quantization). Axis 0 blockwise quantization only. """ bits = self.config.bits if bits == 8: qtype = TensorProto.INT8 if self.config.is_symmetric else TensorProto.UINT8 else: qtype = TensorProto.INT4 if self.config.is_symmetric else TensorProto.UINT4 input_b = node.input[1] b_tensor, b_graph = get_initializer(input_b, graph_stack) if b_tensor is None: logger.info("MatMul doesn't have const weight. Skip to quantize") return [node] # only care about constant weight
b_ndarray = ir.from_proto(b_tensor).numpy() b_original_shape = b_ndarray.shape if len(b_original_shape) != 2: if len(b_original_shape) < 2: logger.info("MatMul weight has fewer than 2 dimensions. Skip to quantize.") return [node] leading = b_original_shape[:-2] if any(d != 1 for d in leading): logger.info( "MatMul weight has non-unit batch dims %s; N-D batched quantization not supported. " "Skip to quantize.", list(leading), ) return [node] # Squeeze all unit leading dims to obtain a 2-D weight [K, N] b_ndarray = b_ndarray.reshape(b_original_shape[-2], b_original_shape[-1]) else: b_original_shape = None # already 2-D, no reshape needed
bfloat16 = b_ndarray.dtype == "bfloat16" if bfloat16: b_ndarray = b_ndarray.astype(np.float32)
packed, scales, zero_points = self.qbits_block_quant(b_ndarray) if bfloat16: scales = scales.astype(ml_dtypes.bfloat16)
if self.config.quant_format == QuantFormat.QOperator: b_quant = ir.serde.serialize_tensor(ir.Tensor(packed, name=b_tensor.name + f"_Q{bits}")) scales_tensor = ir.serde.serialize_tensor(ir.Tensor(scales, name=b_tensor.name + "_scales")) else: b_quant = onnx.helper.make_tensor( b_tensor.name + f"_DQ_Q{bits}", qtype, b_ndarray.shape, packed.tobytes(), True ) scales_tensor = ir.serde.serialize_tensor(ir.Tensor(scales, name=b_tensor.name + "_DQ_scales"))
# if QDQ, CW and SYM enabled, optimize for Intel NPU, tranpose the weight to NHWC format will increase performance qdq_opt_for_intel_npu_enabled = ( self.config.quant_format == QuantFormat.QDQ and self.config.channel_wised_quantize and self.config.is_symmetric ) if qdq_opt_for_intel_npu_enabled: rows, cols = b_ndarray.shape packed = transpose_packed_int4_matrix(packed, rows, cols) scales = scales.reshape((cols, 1)) # (cols, 1) b_quant = onnx.helper.make_tensor( b_tensor.name + f"_DQ_Q{bits}", qtype, [cols, rows], packed.tobytes(), True ) scales_tensor = ir.serde.serialize_tensor(ir.Tensor(scales, name=b_tensor.name + "_DQ_scales"))
for input in b_graph.input: if input.name == input_b: b_graph.input.remove(input) break
b_graph.initializer.extend([b_quant, scales_tensor])
output_nodes = []
if self.config.quant_format == QuantFormat.QOperator: input_names = [node.input[0], b_quant.name, scales_tensor.name] if not self.config.is_symmetric: zp_tensor = onnx.numpy_helper.from_array(zero_points, b_tensor.name + "_zero_points") input_names.append(zp_tensor.name) b_graph.initializer.extend([zp_tensor]) kwargs = {} rows, cols = b_ndarray.shape kwargs["K"] = rows kwargs["N"] = cols kwargs["bits"] = bits kwargs["block_size"] = self.config.block_size
# Do not output accuracy_level if it is 0 since the attribute is optional and is not supported by most EPs. if self.config.accuracy_level: kwargs["accuracy_level"] = self.config.accuracy_level
# When rank(A) >= rank_b_orig, the reshape would be a no-op since MatMulNBits # already produces the correct output shape. a_static_rank = _get_static_rank(node.input[0], graph_stack) rank_b_orig = len(b_original_shape) if b_original_shape is not None else 0 needs_reshape = b_original_shape is not None and (a_static_rank is None or a_static_rank < rank_b_orig) qop_output = node.output[0] if not needs_reshape else node.output[0] + "_pre_reshape" matmul_qbit_node = onnx.helper.make_node( "MatMulNBits", inputs=input_names, outputs=[qop_output], name=node.name + f"_Q{bits}" if node.name else "", domain="com.microsoft", **kwargs, )
output_nodes.append(matmul_qbit_node) if needs_reshape: output_nodes.extend( _build_nbits_output_reshape( a_input_name=node.input[0], b_original_shape=b_original_shape, target_graph=b_graph, name_prefix=(node.name + f"_Q{bits}") if node.name else (b_tensor.name + f"_Q{bits}"), pre_reshape_output=qop_output, final_output=node.output[0], ) ) else: dq_input_names = [b_quant.name, scales_tensor.name] dq_output_names = [b_quant.name + "_output"] tp_input_names = [dq_output_names[0]] tp_output_names = [dq_output_names[0] + "_transposed"] matmul_input_names = [ node.input[0], tp_output_names[0] if qdq_opt_for_intel_npu_enabled else dq_output_names[0], ] # When rank(A) >= rank_b_orig, the reshape would be a no-op since MatMul # already produces the correct output shape. a_static_rank = _get_static_rank(node.input[0], graph_stack) rank_b_orig = len(b_original_shape) if b_original_shape is not None else 0 needs_reshape = b_original_shape is not None and (a_static_rank is None or a_static_rank < rank_b_orig) qdq_matmul_out = node.output[0] if not needs_reshape else node.output[0] + "_pre_reshape" matmul_output_names = [qdq_matmul_out] if not self.config.is_symmetric: zp_tensor = onnx.helper.make_tensor( b_tensor.name + "_DQ_zero_points", qtype, scales.shape, zero_points.tobytes(), True ) dq_input_names.append(zp_tensor.name) b_graph.initializer.extend([zp_tensor]) rows, cols = b_ndarray.shape dq_kwargs = { "axis": 1 if qdq_opt_for_intel_npu_enabled else 0, "block_size": rows if self.config.channel_wised_quantize else self.config.block_size, } dq_node = onnx.helper.make_node( "DequantizeLinear", inputs=dq_input_names, outputs=dq_output_names, name=node.name + f"_DQ_Q{bits}" if node.name else "", **dq_kwargs, ) matmul_node = onnx.helper.make_node( "MatMul", inputs=matmul_input_names, outputs=matmul_output_names, name=node.name + f"_matmul_Q{bits}" if node.name else "", ) if qdq_opt_for_intel_npu_enabled: tp_node = onnx.helper.make_node( "Transpose", inputs=tp_input_names, outputs=tp_output_names, perm=[1, 0], ) output_nodes.extend([dq_node, tp_node, matmul_node]) else: output_nodes.extend([dq_node, matmul_node]) if needs_reshape: output_nodes.extend( _build_nbits_output_reshape( a_input_name=node.input[0], b_original_shape=b_original_shape, target_graph=b_graph, name_prefix=(node.name + f"_DQ_Q{bits}") if node.name else (b_tensor.name + f"_DQ_Q{bits}"), pre_reshape_output=qdq_matmul_out, final_output=node.output[0], ) )
return output_nodes
@staticmethod def quant_slice_symmetric(data: np.ndarray) -> tuple[np.ndarray, np.ndarray]: max_val = np.max(data, axis=1, keepdims=True) min_val = np.min(data, axis=1, keepdims=True) abs_max = np.where(np.abs(max_val) > np.abs(min_val), max_val, min_val)
scale = abs_max / -8.0 # if max == min, max may be clipped quantized_slice = np.where(scale == 0, 0, data / scale).round().clip(-8, 7).astype(np.int8)
return quantized_slice, scale
@staticmethod def quant_slice_asymmetric(data: np.ndarray) -> tuple[np.ndarray, np.ndarray, np.ndarray]: min_val = np.minimum(data.min(axis=1, keepdims=True), 0) max_val = np.maximum(data.max(axis=1, keepdims=True), 0)
scale = (max_val - min_val) / 15.0 zero_point = np.where(scale == 0, 8, -min_val / scale).round().clip(0, 15).astype(np.uint8) quantized_slice = np.where(scale == 0, 8, data / scale + zero_point).round().clip(0, 15).astype(np.uint8)
return quantized_slice, scale, zero_point
@staticmethod def pack_int8_to_int4(data: np.ndarray) -> np.ndarray: """Pack int8 data to int4 and store in uint8 ndarray.""" data_flat = data.reshape(-1) if len(data_flat) % 2 != 0: data_flat = np.append(data_flat, 0) quant_data_int4 = (data_flat[::2] & 0xF) | ((data_flat[1::2] & 0xF) << 4)
return quant_data_int4.astype("uint8")
@staticmethod def quantize_ndarray( data: np.ndarray, quantize_axis: int, block_size: int, is_symmetric: bool, ) -> tuple[np.ndarray, np.ndarray, np.ndarray | None]: """Quantize ndarray data to int4 using numpy, return (quantized data, scales, zero points).""" # Get the shape of the matrix m = 1 # dimension of the matrix before the quantize axis k = data.shape[quantize_axis] # dimension of the matrix along the quantize axis n = 1 # dimension of the matrix after the quantize axis for i, dim in enumerate(data.shape): if i < quantize_axis: m *= dim elif i > quantize_axis: n *= dim
k_blocks = (k + block_size - 1) // block_size scales_shape = list(data.shape) scales_shape[quantize_axis] = k_blocks
data_reshape = data.reshape((m, k, n)) scales = np.zeros((m, k_blocks, n), dtype=data.dtype) if is_symmetric: quant_data_int8 = np.zeros((m, k, n), dtype="int8") else: quant_data_int8 = np.zeros((m, k, n), dtype="uint8") zero_point_int8 = np.zeros((m, k_blocks, n), dtype="uint8")
# slice and quantize for i in range(0, k, block_size): end_idx = min(i + block_size, k) slice = data_reshape[:, i:end_idx, :]
if is_symmetric: quantized_slice_int8, scale_slice = DefaultWeightOnlyQuantizer.quant_slice_symmetric(slice) else: quantized_slice_int8, scale_slice, zero_point_slice_int8 = ( DefaultWeightOnlyQuantizer.quant_slice_asymmetric(slice) )
quant_data_int8[:, i:end_idx, :] = quantized_slice_int8 j = i // block_size scales[:, j : (j + 1), :] = scale_slice if not is_symmetric: zero_point_int8[:, j : (j + 1), :] = zero_point_slice_int8
# pack int8 to int4 quant_data_int4 = DefaultWeightOnlyQuantizer.pack_int8_to_int4(quant_data_int8) zero_point_int4 = None if not is_symmetric: zero_point_int4 = DefaultWeightOnlyQuantizer.pack_int8_to_int4(zero_point_int8) scales = scales.reshape(scales_shape) return quant_data_int4, scales, zero_point_int4
def quantize_gather(self, node: NodeProto, graph_stack: list[GraphProto]) -> list[NodeProto]: """Quantize weight data of Gather node to int4.""" assert self.config.quant_format == QuantFormat.QOperator, "Gather only supports QOperator format currently."
qtype = TensorProto.INT4 if self.config.is_symmetric else TensorProto.UINT4 data_arg = node.input[0] data_tensorproto, data_graphproto = get_initializer(data_arg, graph_stack) if data_tensorproto is None: logger.info("Gather doesn't have const weight. Skip quantization.") return [node] # only care about constant weight
data_ndarray = onnx.numpy_helper.to_array(data_tensorproto) data_rank = len(data_ndarray.shape) quantize_axis = self.config.quant_axes.get("Gather", 1) block_size = self.config.block_size
assert quantize_axis < data_rank and quantize_axis >= -data_rank, "Invalid quantize axis for Gather node." assert block_size >= 16 and ((block_size - 1) & block_size == 0), "Invalid block size for Gather node."
quantize_axis = (quantize_axis + data_rank) % data_rank quantized_data, scales, zero_points = self.quantize_ndarray( data_ndarray, quantize_axis, block_size, self.config.is_symmetric )
for input in data_graphproto.input: if input.name == data_arg: data_graphproto.input.remove(input) break
quantized_data_tensorproto = onnx.helper.make_tensor( data_tensorproto.name + "_Q4", qtype, data_ndarray.shape, quantized_data.tobytes(), True ) scales_tensorproto = onnx.numpy_helper.from_array(scales, data_tensorproto.name + "_scales") input_names = [quantized_data_tensorproto.name, node.input[1], scales_tensorproto.name] data_graphproto.initializer.extend([quantized_data_tensorproto, scales_tensorproto]) if not self.config.is_symmetric: zp_tensorproto = onnx.helper.make_tensor( data_tensorproto.name + "_zero_points", qtype, scales.shape, zero_points.tobytes(), True ) input_names.append(zp_tensorproto.name) data_graphproto.initializer.extend([zp_tensorproto])
try: gather_axis = onnx.helper.get_node_attr_value(node, "axis") except ValueError: gather_axis = 0
kwargs = { "gather_axis": gather_axis, "quantize_axis": quantize_axis, "block_size": block_size, }
gather_q4_node = onnx.helper.make_node( "GatherBlockQuantized", inputs=input_names, outputs=[node.output[0]], name=node.name + "_Q4" if node.name else "", domain="com.microsoft", **kwargs, )
return [gather_q4_node]
def quantize(self, node: NodeProto, graph_stack: list[GraphProto]) -> list[NodeProto]: """ Target node: QOperator node: QDQ nodes: MatMul MatMulNBits DeQuantizeLinear -> MatMul Gather GatherBlockQuantized Gather, Gather, Gather (optional) -> DequantizeLinear If the node is target node with fp32 or fp16 const weight, quantize the weight to int4 and return the new nodes. If QOperator format, return the corresponding QOperator nodes. If QDQ format, return the corresdponging QDQ nodes. Gather (quantized data) + Gather (scales) + Gather (optional, zero points) -> DequantizeLinear is not supported yet because Gather does not support int4 data. """ logger.info(f"start to quantize {node.name} ...")
bits = self.config.bits if node.op_type == "MatMul": if bits == 8 and self.config.quant_format == QuantFormat.QDQ: logger.error("MatMul only supports QOperator format for 8 bits quantization.") return [node] results = self.quantize_matmul(node, graph_stack) elif node.op_type == "Gather": if self.config.bits != 4: logger.error("Gather only supports 4 bits quantization.") return [node]
results = self.quantize_gather(node, graph_stack) else: logger.error(f"Unsupported operator {node.op_type} for weight only quantization. Skip quantization.") return [node]
logger.info(f"complete quantization of {node.name} with {self.config.bits} bits ...") return results
class NVAWQWeightOnlyQuantizer: def __init__( self, config: NVAWQWeightOnlyQuantConfig, ): self.config = config
def quantize_awq(self, model: ModelProto | str) -> ModelProto: """ Perform nvidia_awq quantization using ModelOpt's int4 quantize function.
Args: model (ModelProto): The ONNX model to quantize.
Returns: ModelProto: The quantized ONNX model. """ try: from modelopt.onnx.quantization.int4 import quantize as quantize_int4 # noqa: PLC0415 except ImportError: print( "Please ensure that the 'modelopt' package is installed. Please install it using pip install nvidia_modelopt." ) raise ImportError( "modelopt is not installed. Please install it using pip install nvidia_modelopt. Exiting." ) from None
logger.info("Starting nvidia_awq quantization...")
# Prepare calibration inputs calib_inputs = self.config.calibration_data_reader
# Perform quantization using ModelOpt's int4 quantize function quantized_model = quantize_int4( model, calibration_method=self.config.calibration_method, calibration_data_reader=calib_inputs, )
logger.info("Completed nvidia_awq quantization.") return quantized_model
class MatMulNBitsQuantizer: """ Target node: QOperator node: QDQ nodes: MatMul MatMulNBits DeQuantizeLinear -> MatMul Gather GatherBlockQuantized Gather, Gather, Gather (optional) -> DequantizeLinear
Perform 2/4/8 bits quantization of constant weights for target nodes. If algo_config.quant_format is QOperator: - nodes are replaced by the corresponding QOperator nodes. - quantized weights are stored in the contrib ops. If algo_config.quant_format is QDQ: - the quantized weight is stored in a standard onnx node. For MatMul, it is DequantizeLinear. For Gather, it is the three Gathers, one for quantized data, one for scales and one for optional zero points. - The nodes are replaced by the corresponding QDQ nodes. - currently Gather is not supported in QDQ because Gather does not support int4 yet. Note: - for quantized gather, the memory usage of "DequantizeLinear + Gather" is the same as the original Gather during runtime. Therefor it is not recommended. - when a node is in nodes_to_exclude, and the node configuration in algo_config.customized_weight_config will be ignored. """
def __init__( self, model: ModelProto | str, bits: int = 4, # default to 4bit block_size: int = 128, is_symmetric: bool = False, accuracy_level: int | None = None, nodes_to_exclude=None, nodes_to_include: list[str] | None = None, quant_format=QuantFormat.QOperator, op_types_to_quantize: tuple[str, ...] | None = None, quant_axes: tuple[tuple[str, int], ...] | None = None, channel_wised_quantize: bool = False, algo_config: WeightOnlyQuantConfig | None = None, ): if nodes_to_exclude is None: nodes_to_exclude = [] self.model = ONNXModel(onnx.load(model)) if isinstance(model, str) else ONNXModel(model) self.model_path = model if isinstance(model, str) else None self.bits = bits self.block_size = block_size self.is_symmetric = is_symmetric self.accuracy_level = accuracy_level self.nodes_to_exclude = set(nodes_to_exclude) self.nodes_to_include = set(nodes_to_include) if nodes_to_include else None self.node_quantizer = None
if algo_config is None: algo_config = DefaultWeightOnlyQuantConfig( block_size=block_size, is_symmetric=is_symmetric, accuracy_level=accuracy_level, quant_format=quant_format, op_types_to_quantize=op_types_to_quantize, quant_axes=quant_axes, bits=bits, channel_wised_quantize=channel_wised_quantize, )
self.algo_config = algo_config if hasattr(self.algo_config, "bits"): assert self.algo_config.bits in [2, 4, 8], "Only support 2, 4 or 8 bits quantization"
if algo_config.algorithm == "HQQ": self.node_quantizer = HQQWeightOnlyQuantizer(self.algo_config) elif algo_config.algorithm == "DEFAULT": self.node_quantizer = DefaultWeightOnlyQuantizer(self.algo_config) elif algo_config.algorithm == "nvidia_awq": self.node_quantizer = NVAWQWeightOnlyQuantizer(self.algo_config)
def _process_subgraph(self, graph_stack: list[GraphProto]): new_nodes = [] graph = graph_stack[-1]
for node in graph.node: graph_attrs = [ attr for attr in node.attribute if attr.type == onnx.AttributeProto.GRAPH or attr.type == onnx.AttributeProto.GRAPHS ] if graph_attrs: kwargs = {} for attr in node.attribute: if attr.type == onnx.AttributeProto.GRAPH: # recursive call to take care of sub-graph graph_stack.append(attr.g) kv = {attr.name: self._process_subgraph(graph_stack)} elif attr.type == onnx.AttributeProto.GRAPHS: value = [] for subgraph in attr.graphs: # recursive call to take care of sub-graph graph_stack.append(subgraph) value.extend([self._process_subgraph(graph_stack)]) kv = {attr.name: value} else: kv = attribute_to_kwarg(attr) kwargs.update(kv) node = onnx.helper.make_node( # noqa: PLW2901 node.op_type, node.input, node.output, name=node.name, **kwargs ) out_nodes = [] if node.name in self.nodes_to_exclude: logger.info(f"exclude to quantize {node.name} as specified by nodes_to_exclude...") out_nodes = [node] elif (self.nodes_to_include and node.name in self.nodes_to_include) or ( node.op_type in self.algo_config.op_types_to_quantize ): out_nodes = self.node_quantizer.quantize(node, graph_stack) else: logger.info(f"skip to quantize {node.name} ...") out_nodes = [node] new_nodes.extend(out_nodes)
graph.ClearField("node") graph.node.extend(new_nodes) graph_stack.pop() return graph
def _generate_q4_node_config(self): """Generate weight only quant configuration for nodes.""" q4_node_config = {} for node in self.model.model.graph.node: if node.op_type in ["MatMul"]: if not all(self.model.get_initializer(i) is None for i in node.input): template_config_q4 = { "bits": 4, "group_size": self.block_size, "scheme": "sym" if self.is_symmetric else "asym", } if ( self.algo_config.customized_weight_config and node.name in self.algo_config.customized_weight_config ): for key, value in self.algo_config.customized_weight_config[node.name].items(): if key in template_config_q4: template_config_q4[key] = value q4_node_config[node.name] = template_config_q4 return q4_node_config
def int4_quant_algo(self): """4b quantize a model with RTN or GPTQ algorithm. Please refer to https://github.com/intel/neural-compressor/blob/master/docs/source/quantization_weight_only.md for more details on weight only quantization using Intel® Neural Compressor. """
def inc_dataloader(): data_reader = copy.deepcopy(self.algo_config.calibration_data_reader) for data in data_reader: yield data, None
kwargs = {} if self.accuracy_level is not None: kwargs["accuracy_level"] = self.accuracy_level weight_only_node_config = self._generate_q4_node_config()
algorithm = self.algo_config.algorithm logger.info(f"start to quantize model with {algorithm} algorithm...") if algorithm in ["RTN", "k_quant"]: kwargs["ratios"] = self.algo_config.ratios kwargs["algorithm"] = algorithm
""" We uses fp32 to represent the node that skip quantization, it does not mean this node is fp32 type though. """ for n in self.nodes_to_exclude: weight_only_node_config[n] = "fp32"
self.model = rtn_quantize( model=self.model_path if self.model_path is not None else self.model.model, weight_config=weight_only_node_config, **kwargs, ) elif algorithm == "GPTQ": kwargs["percdamp"] = self.algo_config.percdamp kwargs["blocksize"] = self.algo_config.block_size kwargs["actorder"] = self.algo_config.actorder kwargs["mse"] = self.algo_config.mse kwargs["perchannel"] = self.algo_config.perchannel kwargs["n_samples"] = -1 dataloader = inc_dataloader()
self.model = gptq_quantize( model=self.model_path if self.model_path is not None else self.model.model, weight_config=weight_only_node_config, dataloader=dataloader, **kwargs, ) logger.info(f"complete quantization of model with {algorithm} algorithm.")
def process(self): if self.algo_config.algorithm in ["HQQ", "DEFAULT"]: # use a stack to keep track of sub-graphs graph_stack = [self.model.graph()]
# Update domain opset if self.algo_config.quant_format == QuantFormat.QOperator: self.model.set_opset_import("com.microsoft", 1)
if self.algo_config.quant_format == QuantFormat.QDQ or "Gather" in self.algo_config.op_types_to_quantize: opset_import = self.model.opset_import() for opset in opset_import: if opset.domain in [None, "ai.onnx", ""] and opset.version < 21: logger.warning( "The opset of the input model is under 21 and doesn't support int4 data type. " "Force to update it to opset 21, but the generated model may not be a valid model." ) self.model.set_opset_import(opset.domain, 21)
self._process_subgraph(graph_stack) self.model.clean_initializers() elif self.algo_config.algorithm == "nvidia_awq": # Handle nvidia_awq quantization logger.info("Processing nvidia_awq quantization...") self.model = self.node_quantizer.quantize_awq( self.model.model if self.model_path is None else self.model_path ) logger.info("Completed nvidia_awq quantization.") self.model = ONNXModel(self.model) # Ensure the model is wrapped back into ONNXModel self.model.clean_initializers() else: # RTN or GPTQ weight-only quantize algorithm self.int4_quant_algo()
def ort_convert_str_to_bool(value): return value.lower() in ("true", "1")
# Custom function to parse str:int pairsdef parse_key_value_pair(s): key, value = s.split(":") return key, int(value)
def parse_args(): parser = argparse.ArgumentParser( description="""Blockwise int4 quantization for MatMul 2D weight matrices.
A weight matrix is partitioned into into blocks, where each block is acontinguous subset inside each column. Each block is quantized into aset of 4b integers with a scaling factor and an optional offset.""" )
parser.add_argument("--input_model", required=True, help="Path to the input model file") parser.add_argument("--output_model", required=True, help="Path to the output model file") parser.add_argument("--block_size", required=False, default=32, type=int, help="Block size for quantization") parser.add_argument( "--quant_method", default="default", type=str, choices=["default", "hqq", "rtn", "k_quant", "gptq", "nvidia_awq"], help="the algorithm used to quantize weight, \nrtn and gptq leverage Intel® Neural Compressor", ) parser.add_argument("--bits", default=4, type=int, help="the target bits to represent weight") parser.add_argument( "--symmetric", required=False, default=True, const=True, nargs="?", type=ort_convert_str_to_bool, choices=[True, False], help="Indicate whether to quantize the model symmetrically, symmetric is not supported by hqq", ) parser.add_argument( "--accuracy_level", required=False, type=int, help="Accuracy level of the 4-bit quantized MatMul computation. " "Refer to the MatMulNBits contrib op's 'accuracy_level' attribute for details " "(https://github.com/microsoft/onnxruntime/blob/main/docs/ContribOperators.md#commicrosoftmatmulnbits).", ) parser.add_argument("-v", "--verbose", required=False, action="store_true") parser.set_defaults(verbose=False) parser.add_argument( "--nodes_to_exclude", nargs="+", type=str, required=False, default=[], help="Specify the nodes to be excluded from quantization with node names", ) parser.add_argument( "--nodes_to_include", nargs="+", type=str, required=False, help="Specify the specific nodes to be included from quantization with node names", ) parser.add_argument( "--quant_format", default="QOperator", type=str, choices=["QOperator", "QDQ"], help="QuantFormat {QOperator, QDQ}" "QOperator format quantizes the model with quantized operators directly." "QDQ format quantize the model by inserting DeQuantizeLinear before the MatMul.", ) parser.add_argument( "--op_types_to_quantize", type=str, nargs="+", choices=["MatMul", "Gather"], help="op_types_to_quantize {MatMul, Gather}. Operators to quantize. Default is MatMul.", ) parser.add_argument( "--quant_axes", type=parse_key_value_pair, nargs="+", required=False, help="Key-value pairs in op_type:axis_to_quantize separated by space." "Specify the axis to quantize for an op. Default {MatMul:0, Gather:1}" "Example: --quant_axes MatMul:0 Gather:1", ) # Group arguments specific to nvidia_awq nv_awq_config = parser.add_argument_group("nvidia_awq", "Arguments specific to nvidia_awq quantization") nv_awq_config.add_argument( "--calib_dataset_name", type=str, default="cnn", help="Name of the calibration dataset for nvidia_awq.", ) nv_awq_config.add_argument( "--tokenizer_dir", type=str, required=False, help="Path of the tokenizer dir.", ) nv_awq_config.add_argument( "--calibration_method", type=str, required=False, choices=["awq", "awq_clip"], help="Support two options, awq implementation and weight clipping.", ) nv_awq_config.add_argument( "--cache_dir", type=str, default="./cache", help="Cache directory for calibration data.", ) return parser.parse_args()
if __name__ == "__main__": args = parse_args() if args.verbose: logger.setLevel(logging.DEBUG)
input_model_path = args.input_model output_model_path = args.output_model quant_format = QuantFormat[args.quant_format] op_types_to_quantize = tuple(args.op_types_to_quantize) if args.op_types_to_quantize else ("MatMul",) quant_axes = tuple(args.quant_axes) if args.quant_axes else None
if os.path.exists(output_model_path): logger.error(f"file {output_model_path} already exists") raise Exception(f"file {output_model_path} already exists")
if args.symmetric and args.quant_method == "hqq": logger.warning("symmetric is not supportted by hqq, will force to symmetric=False") args.symmetric = False
model = onnx.load(input_model_path) if args.quant_method == "hqq": quant_config = HQQWeightOnlyQuantConfig( block_size=args.block_size, bits=args.bits, op_types_to_quantize=op_types_to_quantize, quant_axes=quant_axes ) elif args.quant_method == "default": quant_config = DefaultWeightOnlyQuantConfig( block_size=args.block_size, is_symmetric=args.symmetric, accuracy_level=args.accuracy_level, quant_format=quant_format, op_types_to_quantize=op_types_to_quantize, quant_axes=quant_axes, bits=args.bits, ) elif args.quant_method == "rtn": quant_config = RTNWeightOnlyQuantConfig(op_types_to_quantize=op_types_to_quantize) elif args.quant_method == "k_quant": quant_config = KQuantWeightOnlyQuantConfig(op_types_to_quantize=op_types_to_quantize) elif args.quant_method == "gptq": quant_config = GPTQWeightOnlyQuantConfig(block_size=args.block_size, op_types_to_quantize=op_types_to_quantize) elif args.quant_method == "nvidia_awq": if quant_format == QuantFormat.QOperator: logger.warning("QOperator is not applicable to nvidia_awq. overriding the value to QDQ") quant_format = QuantFormat.QDQ
model = input_model_path if args.calibration_method is not None: if args.calibration_method == "awq": calibration_method = "awq_lite" else: calibration_method = "awq_clip" else: calibration_method = "awq_lite"
quant_config = NVAWQWeightOnlyQuantConfig( dataset_name=args.calib_dataset_name, tokenizer_dir=args.tokenizer_dir, cache_dir=args.cache_dir, calibration_method=calibration_method, ) else: raise ValueError(f"Unsupported quantization method: {args.quant_method}")
quant = MatMulNBitsQuantizer( model=model, bits=args.bits, accuracy_level=args.accuracy_level, nodes_to_exclude=args.nodes_to_exclude, nodes_to_include=args.nodes_to_include, algo_config=quant_config, ) quant.process() quant.model.save_model_to_file(output_model_path, True)1from .weight_only import gptq_quantize, rtn_quantize # noqa: F401123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236## The implementation of this file is based on:# https://github.com/intel/neural-compressor/tree/master/neural_compressor## Copyright (c) 2023 Intel Corporation## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.
"""Class for ONNX model."""
import copyimport loggingimport osfrom collections import dequefrom pathlib import Path
import onnximport onnx.external_data_helperimport onnx_ir as ir
from .util import MAXIMUM_PROTOBUF, find_by_name
logger = logging.getLogger("neural_compressor")
# TODO: Check https://github.com/microsoft/onnxruntime/blob/main/onnxruntime/python/tools/quantization/onnx_model.py to see if we can integrate with it.
class ONNXModel: """Build ONNX model."""
def __init__(self, model, **kwargs): """Initialize an ONNX model.
Args: model (str or ModelProto): path to onnx model or loaded ModelProto model object. ignore_warning (bool): ignore large model warning. Default is False. load_external_data (bool): load external data for large model. Default is True. """ self._model = model if not isinstance(model, str) else onnx.load(model, load_external_data=False) self._model_path = None if not isinstance(model, str) else model
self.check_is_large_model() if self._is_large_model and self._model_path is None and not kwargs.get("ignore_warning", False): logger.warning("Model size > 2GB. Please use model path instead of onnx model object to quantize")
if self._is_large_model and isinstance(model, str) and kwargs.get("load_external_data", True): onnx.external_data_helper.load_external_data_for_model(self._model, os.path.dirname(self._model_path))
self._config = None if isinstance(model, str) and os.path.exists(Path(model).parent.joinpath("config.json").as_posix()): from transformers import AutoConfig # noqa: PLC0415
self._config = AutoConfig.from_pretrained(Path(model).parent.as_posix())
self.node_name_counter = {} self._output_name_to_node = {} self._input_name_to_nodes = {} self._get_input_name_to_nodes(self._model.graph.node) self._get_output_name_to_node(self._model.graph.node) self._graph_info = {} self._get_graph_info() self._q_config = None
def check_is_large_model(self): """Check model > 2GB.""" ir_graph = ir.from_proto(self._model.graph) initializer_size = sum( v.const_value.nbytes for v in ir_graph.initializers.values() if v.const_value is not None ) self._is_large_model = initializer_size > MAXIMUM_PROTOBUF
@property def is_large_model(self): """Check the onnx model is over 2GB.""" return self._is_large_model
@property def model_path(self): """Return model path.""" return self._model_path
@model_path.setter def model_path(self, path): """Set model path.""" self._model_path = path
def framework(self): """Return framework.""" return "onnxruntime"
@property def q_config(self): """Return q_config.""" return self._q_config
@q_config.setter def q_config(self, q_config): """Set q_config.""" self._q_config = q_config
@property def hf_config(self): """Return huggingface config if model is Transformer-based.""" return self._config
@property def model(self): """Return model itself.""" return self._model
@model.setter def model(self, model): """Set model itself.""" self._model = model self._graph_info = {} self._get_graph_info() self._output_name_to_node = {} self._input_name_to_nodes = {} self._get_input_name_to_nodes(self._model.graph.node) self._get_output_name_to_node(self._model.graph.node)
def input(self): """Return input of model.""" return [i.name for i in self._model.graph.input]
def output(self): """Return output of model.""" return [i.name for i in self._model.graph.output]
def update(self): """Update model info.""" self._graph_info = {} self._get_graph_info() self._output_name_to_node = {} self._input_name_to_nodes = {} self._get_input_name_to_nodes(self._model.graph.node) self._get_output_name_to_node(self._model.graph.node)
@property def graph_info(self): """Return ORT Graph Info object holding information about backend graph.""" return self._graph_info
def _get_graph_info(self): """Update graph info.""" for node in self._model.graph.node: self.graph_info.update({node.name: node.op_type})
def save(self, root): """Save ONNX model.""" if os.path.split(root)[0] != "" and not os.path.exists(os.path.split(root)[0]): raise ValueError('"root" directory does not exists.') if self.is_large_model: onnx.external_data_helper.load_external_data_for_model(self._model, os.path.split(self._model_path)[0]) onnx.save_model( self._model, root, save_as_external_data=True, all_tensors_to_one_file=True, location=root.split("/")[-1] + "_data", size_threshold=1024, convert_attribute=False, ) else: onnx.save(self._model, root)
if self._config is not None: model_type = "" if not hasattr(self._config, "model_type") else self._config.model_type self._config.__class__.model_type = model_type output_config_file = Path(root).parent.joinpath("config.json").as_posix() self._config.to_json_file(output_config_file, use_diff=False)
def nodes(self): """Return model nodes.""" return self._model.graph.node
def initializer(self): """Return model initializer.""" return self._model.graph.initializer
def graph(self): """Return model graph.""" return self._model.graph
def ir_version(self): """Return model ir_version.""" return self._model.ir_version
def opset_import(self): """Return model opset_import.""" return self._model.opset_import
def remove_node(self, node): """Remove a node from model.""" if node in self._model.graph.node: self._model.graph.node.remove(node)
def remove_nodes(self, nodes_to_remove): """Remove nodes from model.""" for node in nodes_to_remove: self.remove_node(node)
def add_node(self, node): """Add a node to model.""" self._model.graph.node.extend([node])
def add_nodes(self, nodes_to_add): """Add nodes to model.""" self._model.graph.node.extend(nodes_to_add)
def add_initializer(self, tensor): """Add a initializer to model.""" if find_by_name(tensor.name, self._model.graph.initializer) is None: self._model.graph.initializer.extend([tensor])
def add_initializers(self, tensors): """Add initializers to model.""" for tensor in tensors: self.add_initializer(tensor)
def get_initializer(self, name): """Get an initializer by name.""" for tensor in self._model.graph.initializer: if tensor.name == name: return tensor return None
def get_initializer_share_num(self, name): """Get the number of shares of initializer.""" num = 0 if self.get_initializer(name) is None: return num
for node in self.nodes(): if name in node.input: num += 1 return num
def get_node(self, name): """Get a node by name.""" for node in self._model.graph.node: if node.name == name: return node return None
def remove_initializer(self, tensor): """Remove an initializer from model.""" if tensor in self._model.graph.initializer: self._model.graph.initializer.remove(tensor)
def remove_initializers(self, init_to_remove): """Remove initializers from model.""" for initializer in init_to_remove: self.remove_initializer(initializer)
def set_initializer(self, tensor, array, raw=False): """Update initializer.""" old_tensor = self.get_initializer(tensor) self.remove_initializer(old_tensor) dims = old_tensor.dims data_type = old_tensor.data_type new_tensor = ( onnx.helper.make_tensor(tensor, data_type, dims, array.flatten().tolist()) if not raw else onnx.helper.make_tensor(tensor, data_type, dims, array.tostring(), raw=raw) ) self.add_initializer(new_tensor)
@property def input_name_to_nodes(self): """Return input names of nodes.""" return self._input_name_to_nodes
def _get_input_name_to_nodes(self, nodes): """Get input names of nodes.""" for node in nodes: attrs = [ attr for attr in node.attribute if attr.type == onnx.AttributeProto.GRAPH or attr.type == onnx.AttributeProto.GRAPHS ] if len(attrs) > 0: for attr in attrs: self._get_input_name_to_nodes(attr.g.node) for input_name in node.input: if len(input_name.strip()) != 0: if input_name not in self._input_name_to_nodes: self._input_name_to_nodes[input_name] = [node] else: self._input_name_to_nodes[input_name].append(node)
@property def output_name_to_node(self): """Return output names of nodes.""" return self._output_name_to_node
def _get_output_name_to_node(self, nodes): """Get output names of nodes.""" for node in nodes: attrs = [ attr for attr in node.attribute if attr.type == onnx.AttributeProto.GRAPH or attr.type == onnx.AttributeProto.GRAPHS ] if len(attrs) > 0: for attr in attrs: self._get_output_name_to_node(attr.g.node) for output_name in node.output: if len(output_name.strip()) != 0: self._output_name_to_node[output_name] = node
def get_siblings(self, node): """Get siblings nodes.""" siblings = [] for parent in self.get_parents(node): for child in self.get_children(parent): if child.name != node.name: siblings.append(child) return siblings
def get_children(self, node, input_name_to_nodes=None): """Get children nodes.""" if input_name_to_nodes is None: input_name_to_nodes = self._input_name_to_nodes
children = [] for output in node.output: if output in input_name_to_nodes: for child in input_name_to_nodes[output]: children.append(child) # noqa: PERF402 return children
def get_parents(self, node, output_name_to_node=None): """Get parents nodes.""" if output_name_to_node is None: output_name_to_node = self._output_name_to_node
parents = [] for input in node.input: if input in output_name_to_node: parents.append(output_name_to_node[input]) return parents
def get_parent(self, node, idx, output_name_to_node=None): """Get parent node by idx.""" if output_name_to_node is None: output_name_to_node = self._output_name_to_node
if len(node.input) <= idx: return None
input = node.input[idx] if input not in output_name_to_node: return None
return output_name_to_node[input]
def find_node_by_name(self, node_name, new_nodes_list, graph): """Find out node by name.""" graph_nodes_list = list(graph.node) # deep copy graph_nodes_list.extend(new_nodes_list) node = find_by_name(node_name, graph_nodes_list) return node
def find_nodes_by_initializer(self, graph, initializer): """Find all nodes with given initializer as an input.""" nodes = [] for node in graph.node: for node_input in node.input: if node_input == initializer.name: nodes.append(node) return nodes
def get_scale_zero(self, tensor): """Help function to get scale and zero_point.""" if not tensor.endswith("_quantized"): logger.debug(f"Find {tensor} in the quantized graph is not quantized.") return None, None
def _searcher(tensor_name): """Search scale and zero point tensor recursively.""" node = self._input_name_to_nodes[tensor_name][0] parent = self._output_name_to_node.get(tensor_name, None) direct_int8 = ["Reshape", "Transpose", "Squeeze", "Unsqueeze", "MaxPool", "Pad", "Split"] if parent is not None and parent.op_type in direct_int8: fp32_tensor_name = ( parent.input[0] .replace("_quantized", "") .replace("_QuantizeLinear", "") .replace("_QuantizeInput", "") ) elif node.op_type in ["Gather"]: # pragma: no cover fp32_tensor_name = ( node.output[0] .replace("_quantized", "") .replace("_QuantizeLinear", "") .replace("_QuantizeInput", "") ) else: fp32_tensor_name = ( tensor_name.replace("_quantized", "").replace("_QuantizeLinear", "").replace("_QuantizeInput", "") ) scale = fp32_tensor_name + "_scale" scale_tensor = self.get_initializer(scale) zo = fp32_tensor_name + "_zero_point" zo_tensor = self.get_initializer(zo)
if scale_tensor is None or zo_tensor is None: if parent is not None: scale_tensor, zo_tensor = _searcher(parent.input[0]) return scale_tensor, zo_tensor
node = self._input_name_to_nodes[tensor][0] # TODO check if scale_tensor and zero_point is needed # for bias of qlinearconv, scale and zero_point is not needed if (node.op_type == "QLinearConv" and tensor == node.input[-1]) or ( node.op_type == "QGemm" and tensor == node.input[-3] ): return None, None else: scale_tensor, zo_tensor = _searcher(tensor) assert scale_tensor, f"missing scale for tensor {tensor}" assert zo_tensor, f"missing zero point for tensor {tensor}" return scale_tensor, zo_tensor
def save_model_to_file(self, output_path, use_external_data_format=False): """Save model to external data, which is needed for model size > 2GB.""" if use_external_data_format: onnx.external_data_helper.convert_model_to_external_data( self._model, all_tensors_to_one_file=True, location=Path(output_path).name + ".data" ) onnx.save_model(self._model, output_path)
@staticmethod def replace_node_input(node, old_input_name, new_input_name): """Replace input of a node.""" assert isinstance(old_input_name, str) and isinstance(new_input_name, str) for j in range(len(node.input)): if node.input[j] == old_input_name: node.input[j] = new_input_name
def replace_input_of_all_nodes(self, old_input_name, new_input_name, white_optype=None, black_optype=None): """Replace inputs of all nodes.""" if white_optype is None: white_optype = [] if black_optype is None: black_optype = [] if len(white_optype) > 0: for node in self.model.graph.node: if node.op_type in white_optype: ONNXModel.replace_node_input(node, old_input_name, new_input_name) else: for node in self.model.graph.node: if node.op_type not in black_optype: ONNXModel.replace_node_input(node, old_input_name, new_input_name)
@staticmethod def replace_node_output(node, old_output_name, new_output_name): """Replace output of a node.""" assert isinstance(old_output_name, str) and isinstance(new_output_name, str) for j in range(len(node.output)): if node.output[j] == old_output_name: node.output[j] = new_output_name
def replace_output_of_all_nodes(self, old_output_name, new_output_name, white_optype=None, black_optype=None): """Replace outputs of all nodes.""" if white_optype is None: white_optype = [] if black_optype is None: black_optype = [] if len(white_optype) > 0: for node in self.model.graph.node: if node.op_type in white_optype: ONNXModel.replace_node_output(node, old_output_name, new_output_name) else: for node in self.model.graph.node: if node.op_type not in black_optype: ONNXModel.replace_node_output(node, old_output_name, new_output_name)
def remove_unused_nodes(self): """Remove unused nodes.""" unused_nodes = [] nodes = self.nodes() for node in nodes: if ( node.op_type == "Constant" and node.output[0] not in self._model.graph.output and node.output[0] not in self._input_name_to_nodes ): unused_nodes.append(node) elif ( node.op_type == "QuantizeLinear" and len(self.get_children(node)) == 1 and self.get_children(node)[0].op_type == "DequantizeLinear" and node.input[0] not in self._output_name_to_node and self.get_children(node)[0].output[0] not in self._input_name_to_nodes ): unused_nodes.append(node) unused_nodes.extend(self.get_children(node)) else: # remove the node if it does not serve as the input or output of any other nodes unused = True for output in node.output: if output in self._input_name_to_nodes or output in self.output(): unused = False break for input in node.input: if self.get_initializer(input) is not None: continue elif input in self._output_name_to_node or input in self.input(): unused = False break if unused: unused_nodes.append(node) self.remove_nodes(unused_nodes)
ununsed_weights = [] for w in self._model.graph.initializer: if w.name not in self._input_name_to_nodes and w.name not in self._model.graph.output: ununsed_weights.append(w) # Remove from graph.input for graph_input in self.graph().input: if graph_input.name == w.name: self.graph().input.remove(graph_input)
self.remove_initializers(ununsed_weights) self.update()
def topological_sort(self, enable_subgraph=False): """Topological sort the model."""
if not enable_subgraph: input_name_to_nodes = {} output_name_to_node = {} for node in self.model.graph.node: for input_name in node.input: if len(input_name.strip()) != 0: if input_name not in input_name_to_nodes: input_name_to_nodes[input_name] = [node] else: input_name_to_nodes[input_name].append(node) for output_name in node.output: if len(output_name.strip()) != 0: output_name_to_node[output_name] = node else: # pragma: no cover input_name_to_nodes = self._input_name_to_nodes output_name_to_node = self._output_name_to_node
all_nodes = {} q = deque() wait = deque() for inp in self.model.graph.input: q.extend(input_name_to_nodes[inp.name]) for n in self.model.graph.node: if all(i not in output_name_to_node and i not in self.input() for i in n.input): q.append(n)
while q: n = q.popleft() if not all(output_name_to_node[i].name in all_nodes for i in n.input if i in output_name_to_node): if n not in wait: wait.append(n) continue
all_nodes[n.name] = n for out in n.output: if out in input_name_to_nodes: q.extend([i for i in input_name_to_nodes[out] if i.name not in all_nodes and i not in q]) if len(q) == 0 and len(wait) != 0: q = copy.deepcopy(wait) wait.clear() nodes = [i[1] for i in all_nodes.items()] assert len(list({n.name for n in nodes})) == len(list({n.name for n in self.model.graph.node})) self.model.graph.ClearField("node") self.model.graph.node.extend(nodes)
def get_nodes_chain(self, start, stop, result_chain=None): """Get nodes chain with given start node and stop node.""" if result_chain is None: result_chain = [] # process start node list start_node = deque() for node in start: if isinstance(node, str): start_node.append(node) elif isinstance(node, onnx.NodeProto): start_node.append(node.name) else: assert False, "'get_nodes_chain' function only support list[string]or list[NodeProto] params" # noqa: B011
# process stop node list stop_node = [] for node in stop: if isinstance(node, str): stop_node.append(node) elif isinstance(node, onnx.NodeProto): stop_node.append(node.name) else: assert False, "'get_nodes_chain' function only support list[string]or list[NodeProto] params" # noqa: B011
while start_node: node_name = start_node.popleft() if node_name in stop_node: continue if node_name not in result_chain: result_chain.append(node_name) else: continue
node = find_by_name(node_name, list(self.model.graph.node)) for parent in self.get_parents(node): start_node.append(parent.name)
return result_chain
def find_split_node_for_layer_wise_quantization(self): """Find split node for layer wise quantization.""" # find split nodes of decoder blocks # embed -> decoder.0 -(split_node)-> ... -(split_node)-> decoder.n -(split_node)-> norm -> head # after split: embed -> decoder.0, # decoder.1, # decoder.2, # ..., # decoder.n, # norm -> head start_nodes = [] for node in self._model.graph.node: start_node, qkv_nodes_list = None, None if node.op_type == "SkipLayerNormalization": start_node = node qkv_nodes_list = [ self.match_parent_path( start_node, ["MatMul", "Reshape", "Transpose", "Reshape", "MatMul"], [None, 0, 0, 0, 0], ), self.match_parent_path( start_node, ["Add", "MatMul", "Reshape", "Transpose", "MatMul"], [1, 1, 0, 0, 0], ), ] if node.op_type == "Add": start_node = node qkv_nodes_list = [ # match base attention structure self.match_parent_path( start_node, ["Add", "MatMul", "Reshape", "Transpose", "MatMul"], [0, None, 0, 0, 0], ), self.match_parent_path( start_node, ["Add", "MatMul", "Reshape", "Transpose", "MatMul"], [1, None, 0, 0, 0] ), # match gpt attention no past structure self.match_parent_path( start_node, ["Reshape", "Gemm", "Reshape", "Reshape", "Transpose", "MatMul"], [None, 0, 0, 0, 0, 0], output_name_to_node=self.output_name_to_node, return_indice=[], ), # match bart attention structure self.match_parent_path( start_node, ["Add", "MatMul", "Reshape", "Transpose", "Reshape", "MatMul"], [0, None, 0, 0, 0, 0], ), self.match_parent_path( start_node, ["Add", "MatMul", "Reshape", "Transpose", "Reshape", "MatMul"], [1, None, 0, 0, 0, 0], ), self.match_parent_path( start_node, ["MatMul", "Mul", "MatMul", "Mul", "Div", "Add"], [None, 0, None, 0, None, 0], ), self.match_parent_path( start_node, ["MatMul", "Mul", "MatMul", "SimplifiedLayerNormalization", "Add"], [None, 0, None, 0, 0], ), ] if not start_node: continue if not any(qkv_nodes_list): continue start_nodes.append(start_node) return start_nodes
def find_qkv_in_attention(self, find_all=False): """Find qkv MatMul in Attention.
Args: find_all (bool, optional): find all qkv MatMul. Defaults to False
Returns: qkv (list): qkv MatMul list """ qkv = [] for node in self._model.graph.node: if node.op_type == "Attention": qkv.append([node.name]) continue start_node, qkv_nodes_list = None, None if node.op_type == "SkipLayerNormalization": start_node = node qkv_nodes_list = [ self.match_parent_path( start_node, ["MatMul", "Reshape", "Transpose", "Reshape", "MatMul"], [None, 0, 0, 0, 0], ), self.match_parent_path( start_node, ["Add", "MatMul", "Reshape", "Transpose", "MatMul"], [1, 1, 0, 0, 0], ), ] if node.op_type == "Add": start_node = node qkv_nodes_list = [ # match base attention structure self.match_parent_path( start_node, ["Add", "MatMul", "Reshape", "Transpose", "MatMul"], [0, None, 0, 0, 0], ), self.match_parent_path( start_node, ["Add", "MatMul", "Reshape", "Transpose", "MatMul"], [1, None, 0, 0, 0] ), # match gpt attention no past structure self.match_parent_path( start_node, ["Reshape", "Gemm", "Reshape", "Reshape", "Transpose", "MatMul"], [None, 0, 0, 0, 0, 0], output_name_to_node=self.output_name_to_node, return_indice=[], ), # match bart attention structure self.match_parent_path( start_node, ["Add", "MatMul", "Reshape", "Transpose", "Reshape", "MatMul"], [0, None, 0, 0, 0, 0], ), self.match_parent_path( start_node, ["Add", "MatMul", "Reshape", "Transpose", "Reshape", "MatMul"], [1, None, 0, 0, 0, 0], ), ] if not start_node: continue if not any(qkv_nodes_list): continue qkv_nodes = [qkv for qkv in qkv_nodes_list if qkv is not None][-1] other_inputs = [] for input in start_node.input: if input not in self.output_name_to_node: continue if input == qkv_nodes[0].output[0]: continue other_inputs.append(input) if len(other_inputs) != 1: continue root_input = other_inputs[0] input_name_to_nodes = self.input_name_to_nodes children = input_name_to_nodes[root_input] children_types = [child.op_type for child in children] if children_types.count("MatMul") == 3: qkv.append([child.name for child in children if child.op_type == "MatMul"]) if not find_all: break return qkv
def find_ffn_matmul(self, attention_index, attention_matmul_list, block_len): """Find MatMul in FFN.
Args: attention_index (list): index of Attention attention_matmul_list (list): list of Attention and MatMul nodes block_len (int): block length
Returns: list: list of MatMul in FFN """ ffn_matmul = [] for idx in range(len(attention_index)): if idx != len(attention_index) - 1: index = attention_index[idx + 1] if index - 2 >= 0: ffn_matmul.append([attention_matmul_list[index - 2], attention_matmul_list[index - 1]]) else: index = attention_index[idx] if index + block_len - 1 < len(attention_matmul_list): ffn_matmul.append( [attention_matmul_list[index + block_len - 2], attention_matmul_list[index + block_len - 1]] ) return ffn_matmul
def export(self, save_path, conf): """Export Qlinear to QDQ model.""" from neural_compressor.config import ONNXQlinear2QDQConfig # noqa: PLC0415 from neural_compressor.utils.export import onnx_qlinear_to_qdq # noqa: PLC0415
if isinstance(conf, ONNXQlinear2QDQConfig): add_nodes, remove_nodes, inits = onnx_qlinear_to_qdq(self._model, self._input_name_to_nodes) self.add_nodes(add_nodes) self.remove_nodes(remove_nodes) self.add_initializers(inits) self.update() self.remove_unused_nodes() self.topological_sort() self.save(save_path) else: logger.warning("Unsupported config for export, only ONNXQlinear2QDQConfig is supported!") exit(0)
def add_tensors_to_outputs(self, tensor_names): """Add the tensors to the model outputs to gets their values.
Args: tensor_names: The names of tensors to be dumped. """ added_outputs = [] for tensor in tensor_names: if tensor not in self.output(): added_tensor = onnx.helper.ValueInfoProto() added_tensor.name = tensor added_outputs.append(added_tensor) self._model.graph.output.extend(added_outputs) # pylint: disable=no-member
def remove_tensors_from_outputs(self, tensor_names): """Remove the tensors from the model outputs.
Args: tensor_names: The names of tensors to be removed. """ removed_outputs = [] for tensor in tensor_names: if tensor in self.output(): removed_outputs.append(self._model.graph.output[self.output().index(tensor)]) for output in removed_outputs: self._model.graph.output.remove(output)
def match_first_parent(self, node, parent_op_type, output_name_to_node, exclude=None): """Find parent node based on constraints on op_type.
Args: node (str): current node name. parent_op_type (str): constraint of parent node op_type. output_name_to_node (dict): dictionary with output name as key, and node as value. exclude (list): list of nodes that are excluded (not allowed to match as parent).
Returns: parent: The matched parent node. None if not found. index: The input index of matched parent node. None if not found. """ if exclude is None: exclude = [] for i, input in enumerate(node.input): if input in output_name_to_node: parent = output_name_to_node[input] if parent.op_type == parent_op_type and parent not in exclude: return parent, i return None, None
def match_parent( self, node, parent_op_type, input_index=None, output_name_to_node=None, exclude=None, return_indice=None, ): """Find parent node based on constraints on op_type and index.
Args: node (str): current node name. parent_op_type (str): constraint of parent node op_type. input_index (int or None): only check the parent given input index of current node. output_name_to_node (dict): dictionary with output name as key, and node as value. exclude (list): list of nodes that are excluded (not allowed to match as parent). return_indice (list): a list to append the input index when input_index is None.
Returns: parent: The matched parent node. """ assert node is not None assert input_index is None or input_index >= 0 if exclude is None: exclude = [] if output_name_to_node is None: output_name_to_node = self._output_name_to_node
if input_index is None: parent, index = self.match_first_parent(node, parent_op_type, output_name_to_node, exclude) if return_indice is not None: return_indice.append(index) return parent
if input_index >= len(node.input): return None
parent = self.get_parent(node, input_index, output_name_to_node) if parent is not None and parent.op_type == parent_op_type and parent not in exclude: return parent
return None
def match_parent_path( self, node, parent_op_types, parent_input_index, output_name_to_node=None, return_indice=None, ): """Find a sequence of input edges based on constraints on parent op_type and index.
Args: node (str): current node name. parent_op_types (str): constraint of parent node op_type of each input edge. parent_input_index (list): constraint of input index of each input edge. None means no constraint. output_name_to_node (dict): dictionary with output name as key, and node as value. return_indice (list): a list to append the input index when there is no constraint on input index of an edge.
Returns: parents: a list of matched parent node. """ assert len(parent_input_index) == len(parent_op_types)
if output_name_to_node is None: output_name_to_node = self._output_name_to_node
current_node = node matched_parents = [] for i, op_type in enumerate(parent_op_types): matched_parent = self.match_parent( current_node, op_type, parent_input_index[i], output_name_to_node, exclude=[], return_indice=return_indice, ) if matched_parent is None: return None
matched_parents.append(matched_parent) current_node = matched_parent
return matched_parents
def is_smoothquant_model(self): """Check the model is smooth quantized or not.
Returns: bool: the model is smooth quantized or not. """ for init in self.model.graph.initializer: # noqa: SIM110 if "_smooth_scale" in init.name: return True return False
def find_split_nodes(self): """Find split nodes for layer-wise quantization.""" split_nodes = self.find_split_node_for_layer_wise_quantization() return split_nodes
def split_model_with_node( self, split_node_name, path_of_model_to_split, shape_infer=True, save_both_split_models=True ): """Split model into two parts at a given node.
Args: split_node_name (str): name of the node where the model is split at> path_of_model_to_split (str): path of model to be split. shape_infer (bool): do shape inference. Default is True. save_both_split_models (bool): whether to save the two split models. False means only save the first split model. True means save both the two split models. Default id True.
Returns: tuple: the first split model, the second split model """ # origin model : ... -> node_1 -> split_node -> node_2 -> ... # split model 1: ... -> node_1 -> split_node # split model 2: node_2 -> ...
split_model_part_1 = onnx.ModelProto() split_model_part_1.CopyFrom(self._model) split_model_part_1.graph.ClearField("node")
split_model_part_2 = onnx.ModelProto() split_model_part_2.CopyFrom(self._model) split_model_part_2.graph.ClearField("node")
split_node_output = None part_idx = 1 for node in self._model.graph.node: if part_idx == 1: split_model_part_1.graph.node.append(node) elif part_idx == 2: split_model_part_2.graph.node.append(node)
if node.name == split_node_name: split_node_output = node.output part_idx = 2
assert len(split_node_output) == 1, ( f"Only support split at node with 1 output tensor, while current split node {split_node_name} has {len(split_node_output)} output tensors" ) split_tensor_name = split_node_output[0]
# infer shape of the model to be split if shape_infer: try: from neural_compressor.adaptor.ox_utils.util import infer_shapes # noqa: PLC0415
self._model = infer_shapes(self._model, auto_merge=True, base_dir=os.path.dirname(self._model_path)) except Exception as e: # pragma: no cover logger.error( "Shape infer fails for layer-wise quantization. " "We would recommend checking the graph optimization level of your model " "and setting it to 'DISABLE_ALL' or 'ENABLE_BASIC', " "as this may help avoid this error." ) raise e
split_tensor_type, split_tensor_shape = self._get_output_type_shape_by_tensor_name(split_tensor_name) split_tensor = onnx.helper.make_tensor_value_info(split_tensor_name, split_tensor_type, split_tensor_shape)
split_model_part_1 = ONNXModel(split_model_part_1, ignore_warning=True) split_model_part_2 = ONNXModel(split_model_part_2, ignore_warning=True)
# remove unused input & output split_model_part_1._remove_unused_input_output() split_model_part_2._remove_unused_input_output()
split_model_part_1.model.graph.output.append(split_tensor) split_model_part_2.model.graph.input.append(split_tensor)
insert_output_for_model_1 = [] insert_input_for_model_2 = [] for output in split_model_part_1.output_name_to_node: if output in split_model_part_2.input_name_to_nodes: output_type, output_shape = self._get_output_type_shape_by_tensor_name(output) output_tensor = onnx.helper.make_tensor_value_info(output, output_type, output_shape) if output_tensor not in split_model_part_1.model.graph.output: insert_output_for_model_1.append(output_tensor) if output_tensor not in split_model_part_2.model.graph.input: insert_input_for_model_2.append(output_tensor)
# insert model 1 output for output in insert_output_for_model_1: split_model_part_1.model.graph.output.append(output)
# insert model 2 input for input in insert_input_for_model_2: split_model_part_2.model.graph.input.append(input)
# remove unused init split_model_part_1.remove_unused_init() split_model_part_2.remove_unused_init()
split_model_part_1.update() split_model_part_2.update()
dir_of_model_to_split = os.path.dirname(path_of_model_to_split)
split_model_part_1.load_model_initializer_by_tensor(dir_of_model_to_split) split_model_part_1_path = os.path.join(dir_of_model_to_split, "split_model_part_1.onnx") split_model_part_1.model_path = split_model_part_1_path split_model_part_1._save_split_model(split_model_part_1_path) split_model_part_1.check_is_large_model() logger.debug(f"save split model part 1 to {split_model_part_1_path} for layer wise quantization")
if save_both_split_models: split_model_part_2.load_model_initializer_by_tensor(dir_of_model_to_split) split_model_part_2_path = os.path.join(dir_of_model_to_split, "split_model_part_2.onnx") split_model_part_2.model_path = split_model_part_2_path split_model_part_2._save_split_model(split_model_part_2_path) split_model_part_2.check_is_large_model() logger.debug(f"save split model part 2 to {split_model_part_2_path} for layer wise quantization") return split_model_part_1, split_model_part_2 else: return split_model_part_1, split_model_part_2
def _save_split_model(self, save_path): """Save split model as external data for layer wise quantization.
Args: save_path (str): the path to save the split model """ if os.path.exists(save_path + "_data"): os.remove(save_path + "_data") onnx.save_model( self._model, save_path, save_as_external_data=True, all_tensors_to_one_file=True, location=save_path.split("/")[-1] + "_data", size_threshold=1024, convert_attribute=False, )
def _get_output_type_shape_by_tensor_name(self, tensor_name): """Get output type and shape with a tensor name.
Args: tensor_name (str): name of a tensor
Returns: tuple: output type and shape """ elem_type = onnx.TensorProto.FLOAT shape = None for output in self._model.graph.value_info: if output.name == tensor_name: elem_type = output.type.tensor_type.elem_type shape = [ dim.dim_value if dim.HasField("dim_value") else -1 for dim in output.type.tensor_type.shape.dim ] break return elem_type, shape
def _remove_unused_input_output(self): """Remove unused input & output for split model.""" remove_outputs = [] remove_inputs = [] for output in self._model.graph.output: if output.name not in self.output_name_to_node: remove_outputs.append(output)
for input in self._model.graph.input: if input.name not in self.input_name_to_nodes: remove_inputs.append(input)
for output in remove_outputs: self._model.graph.output.remove(output) for input in remove_inputs: self._model.graph.input.remove(input)
def remove_unused_init(self): """Remove unused init.""" remov_inits = [] for init in self._model.graph.initializer: if init.name not in self.input_name_to_nodes: remov_inits.append(init) self.remove_initializers(remov_inits)
def load_model_initializer_by_tensor(self, data_path=None): """Load model initializer by tensor.
Args: data_path (str, optional): the directory of saved initializer. Defaults to None. """ if data_path is None: data_path = os.path.dirname(self._model_path) for init in self._model.graph.initializer: if init.HasField("data_location") and init.data_location == onnx.TensorProto.EXTERNAL: onnx.external_data_helper.load_external_data_for_tensor(init, data_path)
def write_external_data_to_new_location(self, external_data_location="external.data", overwrite=False): """Write external data of merged quantized model to new location to save memory.
Args: external_data_location (str, optional): external data location of merged quantized model. Defaults to "external.data". overwrite (bool, optional): if True, remove existed externa data. Defaults to False. """ if overwrite and os.path.exists(os.path.join(os.path.dirname(self._model_path), external_data_location)): os.remove(os.path.join(os.path.dirname(self._model_path), external_data_location)) self.load_model_initializer_by_tensor() onnx.external_data_helper.convert_model_to_external_data(self._model, location=external_data_location) # TODO : if init is already saved, skip write it onnx.external_data_helper.write_external_data_tensors(self._model, filepath=os.path.dirname(self._model_path))
def merge_split_models(self, to_merge_model): """Merge two split model into final model.""" to_merge_model.write_external_data_to_new_location() self.add_nodes(list(to_merge_model.nodes())) self.add_initializers(list(to_merge_model.initializer())) self.update()
# add new output for output in to_merge_model.graph().output: if output.name not in self.output(): self._model.graph.output.append(output)
# remove unused output remove_output = [] for output in self._model.graph.output: if output.name in to_merge_model.input(): remove_output.append(output) for output in remove_output: self._model.graph.output.remove(output)
# add new input for input in to_merge_model.graph().input: if ( input.name not in self.input() and input.name not in self.output() and input.name not in self.output_name_to_node ): self._model.graph.input.append(input)
def re_org_output(self, origin_output): """Re-org output of merged model for layer-wise quantization.""" outputs = {} tmp_remove = [] for output in self._model.graph.output: outputs[output.name] = output tmp_remove.append(output)
for output in tmp_remove: self._model.graph.output.remove(output)
for out_name in origin_output: self._model.graph.output.append(outputs[out_name])1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980## The implementation of this file is based on:# https://github.com/intel/neural-compressor/tree/master/neural_compressor## Copyright (c) 2023 Intel Corporation## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.
"""Helper classes or functions for onnxrt adaptor."""
import importlibimport logging
import numpy as np
logger = logging.getLogger("neural_compressor")
MAXIMUM_PROTOBUF = 2147483648
def simple_progress_bar(total, i): """Progress bar for cases where tqdm can't be used.""" progress = i / total bar_length = 20 bar = "#" * int(bar_length * progress) spaces = " " * (bar_length - len(bar)) percentage = progress * 100 print(f"\rProgress: [{bar}{spaces}] {percentage:.2f}%", end="")
def find_by_name(name, item_list): """Helper function to find item by name in a list.""" items = [] for item in item_list: assert hasattr(item, "name"), f"{item} should have a 'name' attribute defined" # pragma: no cover if item.name == name: items.append(item) if len(items) > 0: return items[0] else: return None
def to_numpy(data): """Convert to numpy ndarrays.""" import torch # noqa: PLC0415
if not isinstance(data, np.ndarray): if not importlib.util.find_spec("torch"): logger.error( "Please install torch to enable subsequent data type check and conversion, " "or reorganize your data format to numpy array." ) exit(0) if isinstance(data, torch.Tensor): if data.dtype is torch.bfloat16: # pragma: no cover return data.detach().cpu().to(torch.float32).numpy() if data.dtype is torch.chalf: # pragma: no cover return data.detach().cpu().to(torch.cfloat).numpy() return data.detach().cpu().numpy() else: try: return np.array(data) except Exception: assert False, ( # noqa: B011 f"The input data for onnx model is {type(data)}, which is not supported to convert to numpy ndarrays." ) else: return data123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932## The implementation of this file is based on:# https://github.com/intel/neural-compressor/tree/master/neural_compressor## Copyright (c) 2023 Intel Corporation## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.## Modifications:# Add k-quant quantization method.# Copyright (c) Microsoft Corporation. All rights reserved.# Licensed under the MIT License.
"""WeightOnly for onnxrt adaptor."""
import copyimport loggingimport osimport sys
import numpy as npimport onnxfrom onnx import numpy_helperfrom onnx.helper import np_dtype_to_tensor_dtype
import onnxruntime as ort
from .onnx_model import ONNXModelfrom .util import simple_progress_bar
logger = logging.getLogger("neural_compressor")
def make_matmul_weight_only_node( node, weight_shape, num_bits, group_size, k_blocks, q_weight, scale, zero_point, accuracy_level=0,): # pragma: no cover """Build MatMulNBits node.
Args: node: original matmul node weight_shape: original weight shape num_bits (int): num_bits group_size (int): how many elements share one scale/zp k_blocks (int): block number q_weight (array): quantized weight scale (array): scale zero_point (array): zero point accuracy_level (int): accuracy level. Support 0 (unset), 1(fp32), 2(fp16), 3(bf16), or 4(int8).
Returns: matmul_weight_only_node: MatMulNBits node new_inits: initializers of the new node """ blob_size = group_size * num_bits // 8 packed = np.zeros((q_weight.shape[0], blob_size), dtype="uint8") q_weight_name = node.input[1] + f"_Q{num_bits!s}G{group_size!s}" input_names = [node.input[0], q_weight_name] new_inits = [] kwargs = {}
op_type = "MatMulNBits"
# pack quantized weight if num_bits == 4: q_weight_pairs = q_weight[:, ::2] | q_weight[:, 1::2] << 4 packed[:, :] = q_weight_pairs[:, :blob_size] elif num_bits == 8: packed = q_weight else: logger.error(f"MatMulNBits does not have kernel support for num_bits = {num_bits}.")
packed = np.reshape(packed, (-1, k_blocks, blob_size))
# build scale tensor scale = np.reshape(scale, (-1, k_blocks)) assert scale.dtype == np.float32 or scale.dtype == np.float16 scale_tensor = onnx.helper.make_tensor( name=node.input[1] + "_scale", data_type=np_dtype_to_tensor_dtype(scale.dtype), dims=scale.shape, vals=scale.tobytes(), raw=True, ) input_names.append(scale_tensor.name) new_inits.append(scale_tensor)
# build zero_point tensor if zero_point is not None: if num_bits == 8: packed_zp = zero_point.astype("uint8") elif num_bits == 4: # For 4-bit case, the default zeros is 0x8. So it is 0x88 = 136 if we fill lower/higher 4 bits with 0x8. packed_zp = np.full((zero_point.shape[0] + 1) // 2, 136, dtype="uint8") # create an index array idx = np.arange(zero_point.shape[0] // k_blocks * k_blocks).reshape(-1) # separate odd and even indices even_idx = idx[::2] odd_idx = idx[1::2] # vectorized operation for even and odd indices packed_zp[even_idx // 2] = (packed_zp[even_idx // 2] & 0xF0) | zero_point[even_idx].ravel() packed_zp[odd_idx // 2] = (packed_zp[odd_idx // 2] & 0x0F) | (zero_point[odd_idx].ravel() << 4) else: raise ValueError(f"MatMulNBits does not have kernel support for num_bits = {num_bits}.")
packed_zp = np.reshape(packed_zp, (weight_shape[1], -1)) zp_tensor = onnx.helper.make_tensor( name=node.input[1] + "_zp", data_type=2, dims=packed_zp.shape, vals=packed_zp.tobytes(), raw=True ) input_names.append(zp_tensor.name) new_inits.append(zp_tensor)
# set kwargs kwargs["K"] = weight_shape[0] kwargs["N"] = weight_shape[1] kwargs["bits"] = num_bits kwargs["block_size"] = group_size if accuracy_level > 0: # require onnxruntime > 1.16.3 kwargs["accuracy_level"] = accuracy_level
q_weight_tensor = onnx.helper.make_tensor( name=q_weight_name, data_type=2, dims=packed.shape, vals=packed.tobytes(), raw=True, ) new_inits.append(q_weight_tensor)
matmul_weight_only_node = onnx.helper.make_node( op_type, inputs=input_names, outputs=node.output, name=node.name + "_Q" + str(num_bits) if node.name else "_Q" + str(num_bits), domain="com.microsoft", **kwargs, ) return matmul_weight_only_node, new_inits
def quant_tensor(data, num_bits=4, group_size=32, scheme="asym", dtype="int", ratio=1.0): """Quantize tensor per group.
Args: data : input weight num_bits (int, optional): num_bits. Defaults to 4. group_size (int, optional): how many elements share one scale/zp. Defaults to 4. scheme (str, optional): quantization scheme. Defaults to "asym". dtype (str, optional): data type. Defaults to "int". ratio (float, optional): percentile of clip. Defaults to 1.0.
Returns: output: quantized weight scale: scale zero_point: zero point """ data = np.reshape(data, (-1, group_size)) if scheme == "asym" or dtype == "uint": maxq = 2**num_bits - 1 minq = 0 elif scheme == "sym": maxq = 2 ** (num_bits - 1) - 1 if num_bits != 1 else 0 minq = -(2 ** (num_bits - 1)) if num_bits != 1 else -1
rmin = np.min(data, axis=1, keepdims=True) * ratio rmax = np.max(data, axis=1, keepdims=True) * ratio if scheme == "sym": max_range = np.maximum(np.abs(rmin), np.abs(rmax)) scale = np.ones(rmax.shape) mask = max_range > 0 scale[mask] = (max_range[mask] * 2.0).astype(np.float64) / (maxq - minq) zero_point = ( np.zeros(scale.shape) if dtype == "int" else np.ones(rmax.shape, dtype="uint8") * (1 << (num_bits - 1)) ) else: scale = np.ones(rmax.shape) scale[rmin != rmax] = np.array( [float(i) / (maxq - minq) for i in (rmax - rmin)[rmin != rmax].flatten().tolist()] ) zero_point = ( ((np.zeros(scale.shape) - rmin) / scale).round() if dtype == "int" else np.maximum(0, np.minimum(maxq, ((np.zeros(scale.shape) - rmin) / scale).round())).astype("uint8") )
q_weight = np.empty_like(data, dtype=scale.dtype) np.divide(data, scale, out=q_weight) np.add(q_weight, zero_point, out=q_weight) np.round(q_weight, out=q_weight) np.clip(q_weight, minq, maxq, out=q_weight)
return q_weight, scale, zero_point
def quant_tensor_k_quant_cpu(data, num_bits=4, group_size=32): """Quantize tensor per group based on k quant.
Ref: https://github.com/ggml-org/llama.cpp/blob/64eda5deb9859e87a020e56bab5d2f9ca956f1de/ggml/src/ggml-quants.c
Args: data : input weight num_bits (int, optional): num_bits. Defaults to 4. group_size (int, optional): how many elements share one scale/zp. Defaults to 32.
Returns: output: quantized weight scale: scale zero_point: zero point """ data = np.reshape(data, (-1, group_size)).astype(np.float32) # nb = data.shape[0], (nb, group_size) maxq = 2**num_bits - 1 minq = 0 sum_x2 = np.sum(data**2, axis=1, keepdims=True) # (nb, 1) av_x = np.sqrt(sum_x2 / group_size) # (nb, 1) weights = np.add(av_x, np.abs(data)) # (nb, group_size) rmin = np.min(data, axis=1, keepdims=True) # (nb, 1) rmax = np.max(data, axis=1, keepdims=True) # (nb, 1) sum_w = np.sum(weights, axis=1, keepdims=True) # (nb, 1) sum_x = np.sum(weights * data, axis=1, keepdims=True) # (nb, group_size) iscale = np.ones(rmax.shape, dtype=data.dtype) # (nb, 1) mask = rmin != rmax iscale[mask] = (maxq - minq) / (rmax[mask] - rmin[mask]) scale = 1 / iscale quant_data = np.clip(np.round(iscale * (data - rmin)), minq, maxq) # (nb, group_size) diff = scale * quant_data + rmin - data # (nb, group_size) best_mad = np.sum(weights * diff**2, axis=1, keepdims=True) # (nb, 1) nstep = 20 rdelta = 0.1 # nstep * rdelta = -2 * rrmin, maxq - minq = 2**num_bits - 1 rrmin = -1 for is_ in range(nstep): iscale_new = np.ones(rmax.shape, dtype=data.dtype) # (nb, 1) factor = np.array([rrmin + rdelta * is_ + maxq - minq]).astype(data.dtype)[0] mask = rmin != rmax iscale_new[mask] = factor / (rmax[mask] - rmin[mask]) quant_data_new = np.clip(np.round(iscale_new * (data - rmin)), minq, maxq) # (nb, group_size) mul_weights_quant_data_new = weights * quant_data_new sum_l = np.sum(mul_weights_quant_data_new, axis=1, keepdims=True) # (nb, 1) sum_l2 = np.sum(mul_weights_quant_data_new * quant_data_new, axis=1, keepdims=True) # (nb, 1) sum_xl = np.sum(mul_weights_quant_data_new * data, axis=1, keepdims=True) # (nb, 1) D = np.subtract(sum_w * sum_l2, sum_l**2) # noqa: N806
this_scale = (sum_w * sum_xl - sum_x * sum_l) / D # (nb, 1) this_min = (sum_l2 * sum_x - sum_l * sum_xl) / D # (nb, 1)
diff = this_scale * quant_data_new + this_min - data # (nb, group_size) mad = np.sum(weights * diff**2, axis=1, keepdims=True) # (nb, 1)
mad_1 = np.array(mad) best_mad_1 = np.array(best_mad) idx_to_replace = np.where(mad_1 < best_mad_1)[0] quant_data[idx_to_replace, :] = quant_data_new[idx_to_replace, :] best_mad[idx_to_replace] = mad[idx_to_replace] scale[idx_to_replace] = this_scale[idx_to_replace] rmin[idx_to_replace] = this_min[idx_to_replace]
zero_point = np.clip(((-rmin) / scale).round(), 0, maxq).astype("uint8") scale = scale.astype(np.float64) q_weight = np.empty_like(data, dtype=scale.dtype) np.divide(data, scale, out=q_weight) np.add(q_weight, zero_point, out=q_weight) np.round(q_weight, out=q_weight) np.clip(q_weight, minq, maxq, out=q_weight)
return q_weight, scale, zero_point
def quant_tensor_k_quant_cuda(data, num_bits=4, group_size=32): """Quantize tensor per group based on k quant.
Ref: https://github.com/ggml-org/llama.cpp/blob/64eda5deb9859e87a020e56bab5d2f9ca956f1de/ggml/src/ggml-quants.c
Args: data : input weight num_bits (int, optional): num_bits. Defaults to 4. group_size (int, optional): how many elements share one scale/zp. Defaults to 4.
Returns: output: quantized weight scale: scale zero_point: zero point """ try: import cupy as cp # noqa: PLC0415 import torch # noqa: PLC0415
if torch.cuda.is_available(): data = cp.asarray(data) data = data.reshape((-1, group_size)).astype(cp.float32) # nb = data.shape[0], (nb, group_size) maxq = 2**num_bits - 1 minq = 0 sum_x2 = cp.sum(data**2, axis=1, keepdims=True) # (nb, 1) av_x = cp.sqrt(sum_x2 / group_size) # (nb, 1) weights = cp.add(av_x, cp.abs(data)) # (nb, group_size) rmin = cp.min(data, axis=1, keepdims=True) # (nb, 1) rmax = cp.max(data, axis=1, keepdims=True) # (nb, 1) sum_w = cp.sum(weights, axis=1, keepdims=True) # (nb, 1) sum_x = cp.sum(weights * data, axis=1, keepdims=True) # (nb, group_size) iscale = cp.ones(rmax.shape, dtype=data.dtype) # (nb, 1) mask = rmin != rmax iscale[mask] = (maxq - minq) / (rmax[mask] - rmin[mask]) scale = 1 / iscale quant_data = cp.clip(cp.round(iscale * (data - rmin)), minq, maxq) # (nb, group_size) diff = scale * quant_data + rmin - data # (nb, group_size) best_mad = cp.sum(weights * diff**2, axis=1, keepdims=True) # (nb, 1) nstep = 20 rdelta = 0.1 rrmin = -1 for is_ in range(nstep): iscale_new = cp.ones(rmax.shape, dtype=data.dtype) # (nb, 1) factor = cp.array([rrmin + rdelta * is_ + maxq - minq]).astype(data.dtype)[0] mask = rmin != rmax iscale_new[mask] = factor / (rmax[mask] - rmin[mask]) quant_data_new = cp.clip(cp.round(iscale_new * (data - rmin)), minq, maxq) # (nb, group_size) mul_weights_quant_data_new = weights * quant_data_new sum_l = cp.sum(mul_weights_quant_data_new, axis=1, keepdims=True) # (nb, 1) sum_l2 = cp.sum(mul_weights_quant_data_new * quant_data_new, axis=1, keepdims=True) # (nb, 1) sum_xl = cp.sum(mul_weights_quant_data_new * data, axis=1, keepdims=True) # (nb, 1) D = cp.subtract(sum_w * sum_l2, sum_l**2) # noqa: N806
this_scale = (sum_w * sum_xl - sum_x * sum_l) / D # (nb, 1) this_min = (sum_l2 * sum_x - sum_l * sum_xl) / D # (nb, 1)
diff = this_scale * quant_data_new + this_min - data # (nb, group_size) mad = cp.sum(weights * diff**2, axis=1, keepdims=True) # (nb, 1)
mad_1 = cp.array(mad) best_mad_1 = cp.array(best_mad) idx_to_replace = cp.where(mad_1 < best_mad_1)[0] quant_data[idx_to_replace, :] = quant_data_new[idx_to_replace, :] best_mad[idx_to_replace] = mad[idx_to_replace] scale[idx_to_replace] = this_scale[idx_to_replace] rmin[idx_to_replace] = this_min[idx_to_replace]
zero_point = cp.clip(((-rmin) / scale).round(), 0, maxq).astype("uint8") scale = scale.astype(cp.float64) q_weight = cp.empty_like(data, dtype=scale.dtype) cp.divide(data, scale, out=q_weight) cp.add(q_weight, zero_point, out=q_weight) cp.round(q_weight, out=q_weight) cp.clip(q_weight, minq, maxq, out=q_weight)
return q_weight.get(), scale.get(), zero_point.get() else: logger.warning( "Try to use k-quant quantization on CUDA. However, CUDA is not available." "Fall back to k-quant quantization on CPU." ) return quant_tensor_k_quant_cpu(data, num_bits, group_size) except ImportError: logger.info( "Now we are using k-quant quantization on cpu, which is time consuming." "Please consider install cupy to speed up on CUDA. See https://cupy.dev/" "Please also install torch to check CUDA availability." ) return quant_tensor_k_quant_cpu(data, num_bits, group_size)
def qdq_tensor(data, num_bits=4, group_size=32, scheme="asym", dtype="int", ratio=1.0): """Quant dequant tensor per group.
Args: data : input weight num_bits (int, optional): num_bits. Defaults to 4. group_size (int, optional): how many elements share one scale/zp. Defaults to 4. scheme (str, optional): quantization scheme. Defaults to "asym". dtype (str, optional): data type. Defaults to "int". ratio (float, optional): percentile of clip. Defaults to 1.0.
Returns: output: quant-dequant weight """ org_shape = data.shape weight, scale, zp = quant_tensor(data, num_bits, group_size, scheme, dtype, ratio) return np.reshape(scale * (weight - zp), org_shape)
def pad_tensor(weight, group_size, k_blocks): """Pad tensor rowi so that it can be is divisible by group_size.
Args: weight (array): weight group_size (int): how many elements share one scale/zp k_blocks (int): the number of block
Returns: weight: paded weight """ if group_size == -1: return weight
org_w_shape = weight.shape padded_rows = k_blocks * group_size pad_len = padded_rows - org_w_shape[0]
if pad_len > 0: weight = np.pad(weight, ((0, pad_len), (0, 0)), "constant")
return weight
def rtn_quantize( model, weight_config={}, # noqa: B006 num_bits=4, group_size=32, scheme="asym", ratios={}, # noqa: B006 accuracy_level=0, providers=["CPUExecutionProvider"], # noqa: B006 algorithm="k_quant",): """Quant the model with round to nearst method.
Args: model (ModelProto or ONNXModel): onnx model weight_config (dict): quantization config For example, weight_config = { 'fc2': { 'bits': 4, 'group_size': 32, 'scheme': 'sym', 'algorithm': 'RTN' } } num_bits (int, optional): num_bits. Default is 4. group_size (int, optional): how many elements share one scale/zp. Default is 32. scheme (str, optional): sym or asym. Defaults to "asym". ratios (dict, optional): percentile of clip. Defaults to {}. accuracy_level (int): accuracy level. Support 0 (unset),1(fp32), 2(fp16), 3(bf16), or 4(int8). providers (list): providers to use
Returns: model: fake quantized ONNXModel """ model = ONNXModel(model) base_dir = os.path.dirname(model.model_path) if model.model_path is not None else "" new_nodes = [] remove_nodes = [] total_num = len([i for i in model.nodes() if i.op_type in ["MatMul"]]) curr_id = 0 for node in model.nodes(): if node.op_type in ["MatMul"]: curr_id += 1 simple_progress_bar(total_num, curr_id) if ( node.op_type in ["MatMul"] and model.get_initializer(node.input[1]) is not None and weight_config.get(node.name, {}) != "fp32" ): weight_tensor = model.get_initializer(node.input[1]) weight = numpy_helper.to_array(weight_tensor, base_dir=base_dir).copy() if len(weight.shape) != 2: continue
dtype = weight.dtype
if node.name in weight_config: num_bits = weight_config[node.name]["bits"] group_size = weight_config[node.name]["group_size"] scheme = weight_config[node.name]["scheme"]
org_w_shape = weight.shape # ic, oc group_size = group_size if group_size != -1 else org_w_shape[0]
k_blocks = (org_w_shape[0] - 1) // group_size + 1 init_share_num = model.get_initializer_share_num(node.input[1])
weight = pad_tensor(weight, group_size, k_blocks)
satisfy_MatMulNBits_condition = num_bits == 4 or num_bits == 8 # noqa: N806
if satisfy_MatMulNBits_condition: # pragma: no cover if algorithm == "k_quant": q_weight, scale, zp = quant_tensor_k_quant_cuda(weight.T, num_bits, group_size) else: q_weight, scale, zp = quant_tensor( weight.T, num_bits, group_size, scheme, "uint", ratios.get(node.input[1], 1) )
q_matmul_node, new_inits = make_matmul_weight_only_node( node=node, weight_shape=org_w_shape, num_bits=num_bits, group_size=group_size, k_blocks=k_blocks, q_weight=q_weight.astype("uint8"), scale=scale.astype(dtype), zero_point=zp if scheme == "asym" or algorithm == "k_quant" else None, accuracy_level=accuracy_level, )
model.add_initializers(new_inits) remove_nodes.append(node) new_nodes.append(q_matmul_node) else: q_weight = qdq_tensor(weight.T, num_bits, group_size, scheme, "int", ratios.get(node.input[1], 1)) q_weight = np.reshape(q_weight, (org_w_shape[1], -1)) q_weight = np.transpose(q_weight) q_weight = q_weight[: org_w_shape[0], :].astype(dtype) q_weight_tensor = onnx.helper.make_tensor( name=node.input[1] + f"_Q{num_bits!s}G{group_size!s}", data_type=np_dtype_to_tensor_dtype(dtype), dims=weight.shape, vals=q_weight.tobytes(), raw=True, ) model.add_initializer(q_weight_tensor) node.input[1] = q_weight_tensor.name if init_share_num == 1: model.remove_initializer(weight_tensor)
model.add_nodes(new_nodes) model.remove_nodes(remove_nodes) model.topological_sort() return model
def get_weight_scale(weight, group_size): """Get the scale of weight.""" org_shape = weight.shape weight = np.reshape(weight, (-1, group_size)) if group_size != -1 else weight scale = np.mean(np.reshape(np.abs(weight) / np.max(np.abs(weight), axis=1, keepdims=True), org_shape), axis=0) return scale
def prepare_inputs(model, n_samples, dataloader, providers): """Prepare inputs for weight only quantization.
Args: model (ModelProto or ONNXModel): onnx model n_samples (int, optional): calibration sample number. -1 means all samples. dataloader (object): dataloader for calibration. providers (list): providers to use
Returns: inputs: prepared inputs. so: session options """ from importlib.util import find_spec # noqa: PLC0415
from .util import to_numpy # noqa: PLC0415
so = ort.SessionOptions() if sys.version_info < (3, 11) and find_spec("onnxruntime_extensions"): # pragma: no cover from onnxruntime_extensions import get_library_path # noqa: PLC0415
so.register_custom_ops_library(get_library_path()) if model.is_large_model: onnx.save_model( model.model, model.model_path + "_augment.onnx", save_as_external_data=True, all_tensors_to_one_file=True, convert_attribute=False, )
session = ( ort.InferenceSession(model.model.SerializeToString(), so, providers=providers) if not model.is_large_model else ort.InferenceSession(model.model_path + "_augment.onnx", so, providers=providers) ) inputs_names = [i.name for i in session.get_inputs()] del session
inputs = [] for i, data in enumerate(dataloader): if n_samples != -1 and ((i + 1) * dataloader.batch_size) > n_samples: break if len(inputs_names) != 1 or isinstance(data[0], dict): assert len(data[0]) == len(inputs_names), ( f"Input number mismatch, require {len(inputs_names)} but get {len(data[0])}" )
if isinstance(data[0], dict): inputs.append(dict([(name, to_numpy(inp_data)) for name, inp_data in data[0].items()])) # noqa: C404 elif isinstance(data[0], np.ndarray): # pragma: no cover inputs.append(dict([(name, inp) for name, inp in zip(inputs_names, [data[0]], strict=False)])) # noqa: C404 else: # pragma: no cover inputs.append(dict([(name, to_numpy(inp)) for name, inp in zip(inputs_names, data[0], strict=False)])) # noqa: C404 return inputs, so
def gptq( W, H, num_bits=4, group_size=32, scheme="asym", blocksize=128, percdamp=0.01, actorder=False, mse=False, perchannel=True,): """Quant the weight with GPTQ method.
Args: W (array): weight. H (array): Hessian matrix. num_bits (int, optional): num_bits. Default is 4. group_size (int, optional): how many elements share one scale/zp. Default is 32. scheme (str, optional): sym or asym. Defaults to "asym". blocksize (int, optional): blocksize to quantize weight. percdamp (float, optional): percent of the average Hessian diagonal to use for dampening. actorder (bool, optional): whether rearrange Hessian matrix considering the diag's value. mse (bool, optional): whether get scale and zero point with mse error. perchannel (bool, optional): whether quantize weight per-channel.
Returns: Q: fake quantized weight """ maxq = 2**num_bits - 1 grid = 100 maxshrink = 0.8 norm = 2.4
def find_params(weight): org_shape = weight.shape # find zp, scale if not perchannel: weight = np.expand_dims(weight.flatten(), axis=1) tmp = np.zeros(weight.shape[1]) xmin = np.minimum(np.min(weight, axis=0), tmp) xmax = np.maximum(np.max(weight, axis=0), tmp) if scheme == "sym": xmax = np.maximum(np.abs(xmin), xmax) tmp = xmin < 0 if np.any(tmp): xmin[tmp] = -xmax[tmp] tmp = (xmin == 0) & (xmax == 0) xmin[tmp] = -1 xmax[tmp] = +1
scale = (xmax - xmin) / maxq if scheme == "sym": zero = np.ones(scale.shape) * (maxq + 1) / 2 else: zero = np.round(-xmin / scale) if mse: best = np.ones([weight.shape[1]]) * float("inf") for i in range(int(maxshrink * grid)): p = 1 - i / grid xmin1 = p * xmin xmax1 = p * xmax scale1 = (xmax1 - xmin1) / maxq zero1 = np.round(-xmin1 / scale1) if scheme != "sym" else zero q = np.clip(np.round(weight / scale1) + zero1, 0, maxq) q -= weight q = np.power(np.abs(q), norm) err = np.sum(q, 0) tmp = err < best if np.any(tmp): best[tmp] = err[tmp] scale[tmp] = scale1[tmp] zero[tmp] = zero1[tmp] if not perchannel: tmp = org_shape[1] scale = np.repeat(scale, tmp) zero = np.repeat(zero, tmp) shape = [-1] + [1] * (len(org_shape) - 1) scale = np.reshape(scale, shape) zero = np.reshape(zero, shape) return scale, zero
shape = W.shape scale, zp = find_params(W) dead = np.diag(H) == 0 H[dead, dead] = 1 W[dead, :] = 0 # such channel makes no contribution to quantization computation
# rearrange considering the diag's value if actorder: perm = np.argsort(np.diag(H))[::-1] W = W[perm, :] # noqa: N806 H = H[perm, :][:, perm] # noqa: N806 Losses = np.zeros_like(W) # noqa: N806 Q = np.zeros_like(W) # noqa: N806 damp = percdamp * np.mean(np.diag(H)) diag = np.arange(shape[0]) H[diag, diag] += damp # add a average value of H = np.linalg.cholesky(np.linalg.inv(H)).T # noqa: N806 Hinv = H # noqa: N806 for i1 in range(0, shape[0], blocksize): i2 = min(i1 + blocksize, shape[0]) count = i2 - i1
W1 = copy.deepcopy(W[i1:i2, :]) # noqa: N806 Q1 = np.zeros_like(W1) # noqa: N806 Err1 = np.zeros_like(W1) # noqa: N806 Losses1 = np.zeros_like(W1) # noqa: N806 Hinv1 = Hinv[i1:i2, i1:i2] # noqa: N806
for i in range(count): # within a block, channel wise w = W1[i, :] d = Hinv1[i, i]
if group_size != -1: if (i1 + i) % group_size == 0: scale, zp = find_params(W[(i1 + i) : (i1 + i + group_size), :])
q = (scale * (np.clip(np.round(w[:, np.newaxis] / scale) + zp, 0, maxq) - zp)).flatten() Q1[i, :] = q Losses1[i, :] = (w - q) ** 2 / d**2
err1 = (w - q) / d W1[i:, :] -= np.matmul(np.expand_dims(Hinv1[i:, i], axis=1), np.expand_dims(err1, axis=0)) Err1[i, :] = err1
Q[i1:i2, :] = Q1 Losses[i1:i2, :] = Losses1 / 2
W[i2:, :] -= np.matmul(Hinv[i2:, i1:i2], Err1)
if actorder: invperm = np.argsort(perm) Q = Q[invperm, :] # noqa: N806
Q = np.reshape(Q, W.shape) # noqa: N806 del W return Q
def gptq_quantize( model, dataloader, weight_config={}, # noqa: B006 num_bits=4, group_size=32, scheme="asym", n_samples=128, percdamp=0.01, blocksize=128, actorder=False, mse=False, perchannel=True, accuracy_level=0, providers=["CPUExecutionProvider"], # noqa: B006): """Quant the model with GPTQ method.
Args: model (ModelProto or ONNXModel): onnx model dataloader (object): dataloader for calibration. weight_config (dict): quantization config For example, weight_config = { 'fc2': { 'bits': 4, 'group_size': 32, 'scheme': 'sym', 'algorithm': 'GPTQ' } } num_bits (int, optional): num_bits. Default is 4. group_size (int, optional): how many elements share one scale/zp. Default is 32. scheme (str, optional): sym or asym. Defaults to "asym". n_samples (int, optional): calibration sample number. percdamp (float, optional): percent of the average Hessian diagonal to use for dampening. blocksize (int, optional): blocksize to quantize weight. actorder (bool, optional): whether rearrange Hessian matrix considering the diag's value. mse (bool, optional): whether get scale and zero point with mse error. perchannel (bool, optional): whether quantize weight per-channel. accuracy_level (int): accuracy level. Support 0 (unset), 1(fp32), 2(fp16), 3(bf16), or 4(int8). providers (list): providers to use
Returns: model: fake quantized ONNXModel """ model = ONNXModel(model) base_dir = os.path.dirname(model.model_path) if model.model_path is not None else ""
inputs, so = prepare_inputs(model, n_samples, dataloader, providers) del dataloader org_output = copy.deepcopy(model.model.graph.output) model.remove_tensors_from_outputs([i.name for i in org_output]) output_names = [] for node in model.nodes(): if ( node.op_type in ["MatMul"] and weight_config.get(node.name, {}) != "fp32" and weight_config.get(node.name, {}).get("algorithm", "GPTQ") == "GPTQ" ): output_names.append(node.input[0]) output_names = list(set(output_names)) model.add_tensors_to_outputs(output_names) if model.is_large_model: onnx.save_model( model.model, model.model_path + "_augment.onnx", save_as_external_data=True, all_tensors_to_one_file=True, convert_attribute=False, )
session = ( ort.InferenceSession(model.model.SerializeToString(), so, providers=providers) if not model.is_large_model else ort.InferenceSession(model.model_path + "_augment.onnx", so, providers=providers) )
for idx, input_name in enumerate(output_names): simple_progress_bar(len(output_names), idx + 1) node_list = [] weights = []
for node in model.input_name_to_nodes[input_name]: if ( node.op_type in ["MatMul"] and weight_config.get(node.name, {}) != "fp32" and weight_config.get(node.name, {}).get("algorithm", "GPTQ") == "GPTQ" and model.get_initializer(node.input[1]) is not None ): weight = numpy_helper.to_array( model.get_initializer(model.get_node(node.name).input[1]), base_dir ).copy() if len(weight.shape) != 2: continue
weights.append(weight) node_list.append(model.get_node(node.name))
if len(weights) == 0: continue
Hs = [np.zeros((i.shape[0], i.shape[0])) for i in weights] # noqa: N806 nsamples = 0 for data in inputs: inp = session.run([input_name], data)[0] tmp = inp.shape[0] inp = np.reshape(inp, (-1, inp.shape[-1])) Hs = [i * (nsamples / (nsamples + tmp)) for i in Hs] # noqa: N806 nsamples += tmp inp = np.sqrt(2 / nsamples) * inp Hs = [i + np.matmul(inp.T, inp) for i in Hs] # noqa: N806
for ( node, weight, H, # noqa: N806 ) in zip(node_list, weights, Hs, strict=False): if node.name in weight_config: num_bits = weight_config[node.name]["bits"] group_size = weight_config[node.name]["group_size"] scheme = weight_config[node.name]["scheme"] group_size = group_size if group_size != -1 else weight.shape[0] dtype = weight.dtype
q_weight = gptq( weight, H, num_bits=num_bits, group_size=group_size, scheme=scheme, blocksize=blocksize, percdamp=percdamp, actorder=actorder, mse=mse, perchannel=perchannel, )
weight_tensor = model.get_initializer(node.input[1]) init_share_num = model.get_initializer_share_num(node.input[1])
satisfy_MatMulNBits_condition = num_bits == 4 # noqa: N806
if satisfy_MatMulNBits_condition: # pragma: no cover org_shape = weight.shape k_blocks = (org_shape[0] + group_size - 1) // group_size q_weight = pad_tensor(q_weight, group_size, k_blocks) q_weight, scale, zp = quant_tensor(q_weight.T, num_bits, group_size, scheme, "uint") q_matmul_node, new_inits = make_matmul_weight_only_node( node=node, weight_shape=org_shape, num_bits=num_bits, group_size=group_size, k_blocks=k_blocks, q_weight=q_weight.astype("uint8"), scale=scale.astype(dtype), zero_point=zp if scheme == "asym" else None, accuracy_level=accuracy_level, )
model.add_initializers(new_inits) model.remove_node(node) model.add_node(q_matmul_node) else: q_weight_tensor = onnx.helper.make_tensor( name=node.input[1] + f"_Q{num_bits!s}G{group_size!s}", data_type=np_dtype_to_tensor_dtype(dtype), dims=q_weight.shape, vals=q_weight.astype(dtype).tobytes(), raw=True, ) model.add_initializer(q_weight_tensor) node.input[1] = q_weight_tensor.name if init_share_num == 1: model.remove_initializer(weight_tensor)
model.remove_tensors_from_outputs(output_names) model.model.graph.output.MergeFrom(org_output)
model.topological_sort()
# reload external data to prevent external data file path errors if model.is_large_model: from onnx.external_data_helper import load_external_data_for_model # noqa: PLC0415
load_external_data_for_model(model.model, os.path.split(model.model_path)[0])
return model123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600# --------------------------------------------------------------------------# Copyright (c) Microsoft Corporation. All rights reserved.# Licensed under the MIT License.# --------------------------------------------------------------------------from pathlib import Path
import onnximport onnx.helper as onnx_helperimport onnx.numpy_helper as onnx_numpy_helperfrom onnx.onnx_pb import ModelProto
from .quant_utils import attribute_to_kwarg, find_by_name
def _clean_initializers_helper(graph, model): """Clean unused initializers from graph.
Returns: A cleaned graph without unused initializers A list of tensor names, which are not produced by this graph and its subgraphes """ requesting_tensor_names = set() requesting_tensor_names.update(input_name for node in graph.node for input_name in node.input if input_name) requesting_tensor_names.update(g_out.name for g_out in graph.output if g_out.name)
new_nodes = [] for node in graph.node: new_node = node graph_attrs = [ attr for attr in node.attribute if attr.type == onnx.AttributeProto.GRAPH or attr.type == onnx.AttributeProto.GRAPHS ] if graph_attrs: kwargs = {} for attr in node.attribute: new_attribute = {} if attr.type == onnx.AttributeProto.GRAPH: ( cleaned_sub_graph, sub_requesting_tensor_names, ) = _clean_initializers_helper(attr.g, model) new_attribute = {attr.name: cleaned_sub_graph} requesting_tensor_names.update(sub_requesting_tensor_names) elif attr.type == onnx.AttributeProto.GRAPHS: cleaned_graphes = [] for subgraph in attr.graphs: ( cleaned_sub_graph, sub_requesting_tensor_names, ) = _clean_initializers_helper(subgraph, model) cleaned_graphes.append(cleaned_sub_graph) requesting_tensor_names.update(sub_requesting_tensor_names) new_attribute = {attr.name: cleaned_graphes} else: new_attribute = attribute_to_kwarg(attr) kwargs.update(new_attribute) new_node = onnx_helper.make_node(node.op_type, node.input, node.output, name=node.name, **kwargs) new_nodes.append(new_node)
graph.ClearField("node") graph.node.extend(new_nodes)
requesting_tensor_names.difference_update(output for node in graph.node for output in node.output)
unused_initializer = [] for initializer in graph.initializer: if initializer.name in requesting_tensor_names: requesting_tensor_names.remove(initializer.name) else: # mark it to remove, remove here directly will cause mis-behavier unused_initializer.append(initializer)
name_to_input = {input.name: input for input in graph.input} for initializer in unused_initializer: graph.initializer.remove(initializer) if initializer.name in name_to_input: try: graph.input.remove(name_to_input[initializer.name]) except StopIteration: if model.ir_version < 4: print(f"Warning: invalid weight name {initializer.name} found in the graph (not a graph input)")
requesting_tensor_names.difference_update(input.name for input in graph.input)
return graph, requesting_tensor_names
class ONNXModel: def __init__(self, model: ModelProto): self.model = model
def nodes(self): return self.model.graph.node
def initializer(self): return self.model.graph.initializer
def initializer_extend(self, inits): if len(inits) == 0: raise ValueError("Can add an empty list.") for init in self.initializer(): self._check_init(init, "gain") for init in inits: self._check_init(init) self.model.graph.initializer.append(init)
def graph(self): return self.model.graph
def ir_version(self): return self.model.ir_version
def opset_import(self): return self.model.opset_import
def set_opset_import(self, domain, version): for opset in self.model.opset_import: if opset.domain == domain: opset.version = version return
self.model.opset_import.extend([onnx_helper.make_opsetid(domain, version)])
def remove_node(self, node): if node in self.model.graph.node: self.model.graph.node.remove(node)
def remove_nodes(self, nodes_to_remove): for node in nodes_to_remove: self.remove_node(node)
def add_node(self, node): self.model.graph.node.extend([self._check_node(node)])
def add_nodes(self, nodes_to_add): for node in nodes_to_add: self.add_node(node)
def add_initializer(self, tensor): if find_by_name(tensor.name, self.model.graph.initializer) is None: self._check_init(tensor) self.model.graph.initializer.extend([tensor])
def get_initializer(self, name): for tensor in self.model.graph.initializer: if tensor.name == name: return tensor return None
def find_graph_input(self, input_name): for input in self.model.graph.input: if input.name == input_name: return input return None
def find_graph_output(self, output_name): for output in self.model.graph.output: if output.name == output_name: return output return None
def get_tensor_type(self, tensor_name: str): tensor_type_map = {obj.name: obj.type for obj in self.model.graph.value_info}
if tensor_name in tensor_type_map: return tensor_type_map[tensor_name].tensor_type
g_input = self.find_graph_input(tensor_name) if g_input: return g_input.type.tensor_type
g_output = self.find_graph_output(tensor_name) if g_output: return g_output.type.tensor_type
return None
def get_constant_value(self, output_name): for node in self.model.graph.node: if node.op_type == "Constant": if node.output[0] == output_name: for attr in node.attribute: if attr.name == "value": return onnx_numpy_helper.to_array(attr.t)
# Fallback to initializer since constant folding may have been applied. initializer = self.get_initializer(output_name) if initializer is not None: return onnx_numpy_helper.to_array(initializer)
return None
def get_initializer_name_set(self): return {initializer.name for initializer in self.model.graph.initializer}
def remove_initializer(self, tensor): if tensor in self.model.graph.initializer: self.model.graph.initializer.remove(tensor) for input in self.model.graph.input: if input.name == tensor.name: self.model.graph.input.remove(input) break
def remove_initializers(self, init_to_remove): for initializer in init_to_remove: self.remove_initializer(initializer)
def get_non_initializer_inputs(self): initializer_names = self.get_initializer_name_set() non_initializer_inputs = set() for input in self.model.graph.input: if input.name not in initializer_names: non_initializer_inputs.add(input.name) return non_initializer_inputs
def input_name_to_nodes(self): input_name_to_nodes = {} for node in self.model.graph.node: for input_name in node.input: if input_name: # Could be empty when it is optional if input_name not in input_name_to_nodes: input_name_to_nodes[input_name] = [node] else: input_name_to_nodes[input_name].append(node) return input_name_to_nodes
def output_name_to_node(self): output_name_to_node = {} for node in self.model.graph.node: for output_name in node.output: if output_name: # Could be empty when it is optional output_name_to_node[output_name] = node return output_name_to_node
def get_children(self, node, input_name_to_nodes=None): if input_name_to_nodes is None: input_name_to_nodes = self.input_name_to_nodes()
children = [] for output in node.output: if output in input_name_to_nodes: for node in input_name_to_nodes[output]: children.append(node) # noqa: PERF402 return children
def get_parents(self, node, output_name_to_node=None): if output_name_to_node is None: output_name_to_node = self.output_name_to_node()
parents = [] for input in node.input: if input in output_name_to_node: parents.append(output_name_to_node[input]) return parents
def get_parent(self, node, idx, output_name_to_node=None): if output_name_to_node is None: output_name_to_node = self.output_name_to_node()
if len(node.input) <= idx: return None
input = node.input[idx] if input not in output_name_to_node: return None
return output_name_to_node[input]
def find_node_by_name(self, node_name, new_nodes_list, graph): """Find out if a node exists in a graph or a node is in the new set of nodes created during quantization.
Returns: The node found or None. """ graph_nodes_list = list(graph.node) # deep copy graph_nodes_list.extend(new_nodes_list) node = find_by_name(node_name, graph_nodes_list) return node
def get_largest_node_name_suffix(self, node_name_prefix): """ Gets the largest node name (int) suffix for all node names that begin with `node_name_prefix`. Example: for nodes my_prefix_0 and my_prefix_3, this method returns 3. """ suffix = -1
for node in self.model.graph.node: if node.name and node.name.startswith(node_name_prefix): try: index = int(node.name[len(node_name_prefix) :]) suffix = max(index, suffix) except ValueError: continue
return suffix
def get_largest_initializer_name_suffix(self, initializer_name_prefix): """ Gets the largest initializer name integer suffix for all initializer names that begin with `initializer_name_prefix`. This can be used to create unique initializer names.
Example: for initializer names 'my_weight_0' and 'my_weight_3', this method returns 3 if `initializer_name_prefix` is 'my_weight_'. """ suffix = -1
for initializer in self.model.graph.initializer: if initializer.name.startswith(initializer_name_prefix): try: index = int(initializer.name[len(initializer_name_prefix) :]) suffix = max(index, suffix) except ValueError: continue
return suffix
def find_nodes_by_initializer(self, graph, initializer): """ Find all nodes with given initializer as an input. """ nodes = [] for node in graph.node: for node_input in node.input: if node_input == initializer.name: nodes.append(node) return nodes
@staticmethod def __get_initializer(name, graph_path): for gid in range(len(graph_path) - 1, -1, -1): graph = graph_path[gid] for tensor in graph.initializer: if tensor.name == name: return tensor, graph return None, None
@staticmethod def __replace_gemm_with_matmul(graph_path): new_nodes = [] graph = graph_path[-1] for node in graph.node: graph_attrs = [attr for attr in node.attribute if attr.type == 5 or attr.type == 10] if graph_attrs: kwargs = {} for attr in node.attribute: if attr.type == 5: graph_path.append(attr.g) kv = {attr.name: ONNXModel.__replace_gemm_with_matmul(graph_path)} elif attr.type == 10: value = [] for subgraph in attr.graphs: graph_path.append(subgraph) value.extend([ONNXModel.__replace_gemm_with_matmul(graph_path)]) kv = {attr.name: value} else: kv = attribute_to_kwarg(attr) kwargs.update(kv) node = onnx_helper.make_node( # noqa: PLW2901 node.op_type, node.input, node.output, name=node.name, **kwargs )
if node.op_type == "Gemm": alpha = 1.0 beta = 1.0 transA = 0 # noqa: N806 transB = 0 # noqa: N806 for attr in node.attribute: if attr.name == "alpha": alpha = onnx_helper.get_attribute_value(attr) elif attr.name == "beta": beta = onnx_helper.get_attribute_value(attr) elif attr.name == "transA": transA = onnx_helper.get_attribute_value(attr) # noqa: N806 elif attr.name == "transB": transB = onnx_helper.get_attribute_value(attr) # noqa: N806 if alpha == 1.0 and beta == 1.0 and transA == 0: inputB = node.input[1] # noqa: N806 if transB == 1: B, Bs_graph = ONNXModel.__get_initializer(node.input[1], graph_path) # noqa: N806 if B: # assume B is not used by any other node B_array = onnx_numpy_helper.to_array(B) # noqa: N806 B_trans = onnx_numpy_helper.from_array(B_array.T) # noqa: N806 B_trans.name = B.name Bs_graph.initializer.remove(B) for input in Bs_graph.input: if input.name == inputB: Bs_graph.input.remove(input) break Bs_graph.initializer.extend([B_trans]) else: inputB += "_Transposed" # noqa: N806 transpose_node = onnx_helper.make_node( "Transpose", inputs=[node.input[1]], outputs=[inputB], name=node.name + "_Transpose" if node.name else "", ) new_nodes.append(transpose_node)
matmul_node = onnx_helper.make_node( "MatMul", inputs=[node.input[0], inputB], outputs=[node.output[0] + ("_MatMul" if len(node.input) > 2 else "")], name=node.name + "_MatMul" if node.name else "", ) new_nodes.append(matmul_node)
if len(node.input) > 2: add_node = onnx_helper.make_node( "Add", inputs=[node.output[0] + "_MatMul", node.input[2]], outputs=node.output, name=node.name + "_Add" if node.name else "", ) new_nodes.append(add_node)
# unsupported else: new_nodes.append(node)
# not GEMM else: new_nodes.append(node)
graph.ClearField("node") graph.node.extend(new_nodes) graph_path.pop() return graph
def replace_gemm_with_matmul(self): graph_path = [self.graph()] ONNXModel.__replace_gemm_with_matmul(graph_path)
def save_model_to_file(self, output_path, use_external_data_format=False): """ Save model to external data, which is needed for model size > 2GB """ self.topological_sort() if use_external_data_format: onnx.external_data_helper.convert_model_to_external_data( self.model, all_tensors_to_one_file=True, location=Path(output_path).name + ".data", convert_attribute=True, ) for init in self.model.graph.initializer: self._check_init(init, "end") onnx.save_model(self.model, output_path)
@staticmethod def replace_node_input(node, old_input_name, new_input_name): assert isinstance(old_input_name, str) and isinstance(new_input_name, str) for j in range(len(node.input)): if node.input[j] == old_input_name: node.input[j] = new_input_name
def replace_input_of_all_nodes(self, old_input_name, new_input_name): for node in self.model.graph.node: ONNXModel.replace_node_input(node, old_input_name, new_input_name)
def replace_input_of_nodes(self, old_input_name, new_input_name, node_names_set): for node in self.model.graph.node: if node.name in node_names_set: ONNXModel.replace_node_input(node, old_input_name, new_input_name)
@staticmethod def replace_node_output(node, old_output_name, new_output_name): assert isinstance(old_output_name, str) and isinstance(new_output_name, str) for j in range(len(node.output)): if node.output[j] == old_output_name: node.output[j] = new_output_name
def replace_output_of_all_nodes(self, old_output_name, new_output_name): for node in self.model.graph.node: ONNXModel.replace_node_output(node, old_output_name, new_output_name)
def replace_output_of_nodes(self, old_output_name, new_output_name, node_names_set): for node in self.model.graph.node: if node.name in node_names_set: ONNXModel.replace_node_output(node, old_output_name, new_output_name)
def remove_unused_constant(self): input_name_to_nodes = self.input_name_to_nodes()
# remove unused constant unused_nodes = [] nodes = self.nodes() for node in nodes: if ( node.op_type == "Constant" and not self.is_graph_output(node.output[0]) and node.output[0] not in input_name_to_nodes ): unused_nodes.append(node)
self.remove_nodes(unused_nodes)
ununsed_weights = [] for w in self.initializer(): if w.name not in input_name_to_nodes and not self.is_graph_output(w.name): ununsed_weights.append(w) # Remove from graph.input for graph_input in self.graph().input: if graph_input.name == w.name: self.graph().input.remove(graph_input)
self.remove_initializers(ununsed_weights)
def is_graph_output(self, output_name): return any(output.name == output_name for output in self.model.graph.output)
def is_graph_input(self, tensor_name: str) -> bool: return any(input.name == tensor_name for input in self.model.graph.input)
# TODO:use OnnxModel.graph_topological_sort(self.model.graph) from transformers.onnx_model # Currently it breaks Openvino/Linux training gpu pipeline so hold off for 1.8 release def topological_sort(self): deps_count = [0] * len(self.nodes()) # dependency count of each node deps_to_nodes = {} # input to node indice sorted_nodes = [] # initialize sorted_nodes for node_idx, node in enumerate(self.nodes()): # CANNOT use len(node.input) directly because input can be optional deps_count[node_idx] = sum(1 for _ in node.input if _) if deps_count[node_idx] == 0: # Constant doesn't depend on any inputs sorted_nodes.append(self.nodes()[node_idx]) continue
for input_name in node.input: if not input_name: continue if input_name not in deps_to_nodes: deps_to_nodes[input_name] = [node_idx] else: deps_to_nodes[input_name].append(node_idx)
initializer_names = [init.name for init in self.initializer()] graph_input_names = [input.name for input in self.model.graph.input] input_names = initializer_names + graph_input_names input_names.sort() prev_input_name = None for input_name in input_names: if prev_input_name == input_name: continue
prev_input_name = input_name if input_name in deps_to_nodes: for node_idx in deps_to_nodes[input_name]: deps_count[node_idx] = deps_count[node_idx] - 1 if deps_count[node_idx] == 0: sorted_nodes.append(self.nodes()[node_idx])
start = 0 end = len(sorted_nodes)
while start < end: for output in sorted_nodes[start].output: if output in deps_to_nodes: for node_idx in deps_to_nodes[output]: deps_count[node_idx] = deps_count[node_idx] - 1 if deps_count[node_idx] == 0: sorted_nodes.append(self.nodes()[node_idx]) end = end + 1 start = start + 1
assert end == len(self.graph().node), "Graph is not a DAG" self.graph().ClearField("node") self.graph().node.extend(sorted_nodes)
def clean_initializers(self): return _clean_initializers_helper(self.graph(), self.model)
def _check_init(self, init, test=None): if init.data_type == onnx.TensorProto.FLOAT8E4M3FN: if init.HasField("raw_data"): b = list(init.raw_data) if any((i & 127) == 127 for i in b): raise ValueError(f"Initializer {init.name!r} has nan.") return init
def _check_node(self, node): """ A quantization to float 8 does not use quantized bias but float 16 bias. This function checks that DequantizeLinear is not used to dequantize from float 16. """ if node.op_type == "DequantizeLinear": zero_point = node.input[2] init = self.get_initializer(zero_point) dtype = init.data_type if dtype in { onnx.TensorProto.FLOAT16, onnx.TensorProto.FLOAT, onnx.TensorProto.DOUBLE, onnx.TensorProto.BFLOAT16, }: raise RuntimeError(f"Unsupported DequantizeLinear operator, dequantization from {dtype}.") return node1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174# -------------------------------------------------------------------------# Copyright (c) Microsoft Corporation. All rights reserved.# Licensed under the MIT License. See License.txt in the project root for# license information.# --------------------------------------------------------------------------import logging
import numpy as npimport onnximport onnx.numpy_helperfrom onnx import onnx_pb as onnx_proto
from .base_quantizer import BaseQuantizer, QuantizationParamsfrom .calibrate import TensorDatafrom .onnx_model import ONNXModelfrom .quant_utils import ( TENSOR_NAME_QUANT_SUFFIX, QuantizationMode, QuantizedValue, QuantizedValueType, __producer__, __version__, add_infer_metadata, attribute_to_kwarg, compute_scale_zp, compute_scale_zp_float8, find_by_name, get_qmin_qmax_for_qType, get_qrange_for_qType, ms_domain, quantize_onnx_initializer, save_and_reload_model_with_shape_infer, snap_zero_point_to_uint8, tensor_proto_to_array,)from .registry import CreateOpQuantizer
class ONNXQuantizer(BaseQuantizer): def __init__( self, model, per_channel, reduce_range, mode, static, weight_qType, activation_qType, tensors_range, nodes_to_quantize, nodes_to_exclude, op_types_to_quantize, extra_options=None, ): BaseQuantizer.__init__( self, model, per_channel, reduce_range, weight_qType, activation_qType, tensors_range, nodes_to_quantize, nodes_to_exclude, op_types_to_quantize, extra_options, )
if not static: self.model.replace_gemm_with_matmul() # We need to update value_infos. model = save_and_reload_model_with_shape_infer(self.model.model) self.value_infos = {vi.name: vi for vi in model.graph.value_info} self.value_infos.update({ot.name: ot for ot in model.graph.output}) self.value_infos.update({it.name: it for it in model.graph.input}) self.model = ONNXModel(model)
self.mode = mode # QuantizationMode.Value self.static = static # use static quantization for inputs. self.fuse_dynamic_quant = self.opset_version > 10
self.q_matmul_const_b_only = "MatMulConstBOnly" in self.extra_options and self.extra_options["MatMulConstBOnly"]
self.new_nodes = [] self.graph_scope = "/" # for human readable debug information self.tensor_names = {} # in case the shape inference not totally working self.tensor_names.update({ot.name: 1 for ot in model.graph.output}) self.tensor_names.update({it.name: 1 for it in model.graph.input}) for node in self.model.model.graph.node: self.tensor_names.update(dict.fromkeys(node.output, 1))
if self.mode not in QuantizationMode: raise ValueError(f"unsupported quantization mode {self.mode}")
self.quantization_params = self.calculate_quantization_params()
# QuantizeRange tensor name and zero tensor name for scale and zero point calculation. # Used when static is False self.fixed_qrange_uint8_name = "fixed_quantization_range_uint8" self.fixed_qrange_int8_name = "fixed_quantization_range_int8" # For uint8 data-type, to compute zero point, we subtract rmin from 0 (represented by fixed_zero_name tensor) self.fixed_zero_name = "fixed_zero" # For int8 data-type, zero point is always zero (respresented by fixed_zero_point_name tensor) self.fixed_zero_zp_name = "fixed_zero_zp"
# Map of all original value names to quantized value names self.quantized_value_map = {} # some output from nodes will be quantized, yet itself should be treat as existing so # no dequantized will be applied when needed later self.generated_value_names = self.model.get_non_initializer_inputs()
# routines for subgraph support def quantize_subgraph(self, subgraph, graph_key): """ generate submodel for the subgraph, so that we re-utilize current quantization implementation. quantize the submodel update subgraph and set it back to node """ warped_model = onnx.helper.make_model( subgraph, producer_name="onnx-quantizer", opset_imports=self.model.model.opset_import, ) add_infer_metadata(warped_model) sub_quantizer = ONNXQuantizer( warped_model, self.per_channel, self.reduce_range, self.mode, self.static, self.weight_qType, self.activation_qType, self.tensors_range, self.nodes_to_quantize, self.nodes_to_exclude, self.op_types_to_quantize, self.extra_options, ) sub_quantizer.parent = self sub_quantizer.graph_scope = f"{self.graph_scope}{graph_key}/" sub_quantizer.quantize_model() return sub_quantizer.model.model.graph
def quantize_node_with_sub_graph(self, node): """ Check subgraph, if any, quantize it and replace it. return new_nodes added for quantizing subgraph """ graph_attrs = [ attr for attr in node.attribute if attr.type == onnx.AttributeProto.GRAPH or attr.type == onnx.AttributeProto.GRAPHS ] if len(graph_attrs) == 0: return node node_name = node.name if node.name else f"{node.op_type}_node_count_{len(self.new_nodes)}" kwargs = {} for attr in node.attribute: if attr.type == onnx.AttributeProto.GRAPH: kv = {attr.name: self.quantize_subgraph(attr.g, f"{node_name}:{attr.name}")} elif attr.type == onnx.AttributeProto.GRAPHS: value = [] for subgraph in attr.graphs: value.extend( [ self.quantize_subgraph( subgraph, f"{node_name}:{attr.name}:{len(value)}", ) ] ) kv = {attr.name: value} else: kv = attribute_to_kwarg(attr) kwargs.update(kv) return onnx.helper.make_node(node.op_type, node.input, node.output, name=node.name, **kwargs)
def has_QDQ_nodes(self): # noqa: N802 """ Detect if model already has QuantizeLinear or DequantizeLinear. """ return any( node.op_type == "QuantizeLinear" or node.op_type == "DequantizeLinear" for node in self.model.nodes() )
def find_initializer_in_path(self, initializer_name): if find_by_name(initializer_name, self.model.initializer()) is not None: return True if self.parent is not None: return self.parent.find_initializer_in_path(initializer_name) return False
def add_new_nodes(self, nodes): self.new_nodes.extend(nodes) for node in nodes: for output_name in node.output: self.generated_value_names.add(output_name)
def quantize_model(self): if self.has_QDQ_nodes(): logging.warning( "Please check if the model is already quantized. " "Note you don't need to quantize a QAT model. OnnxRuntime support to run QAT model directly." )
for node in self.model.nodes(): # quantize subgraphes if have if self.enable_subgraph_quantization: node = self.quantize_node_with_sub_graph(node) # noqa: PLW2901
number_of_existing_new_nodes = len(self.new_nodes) op_quantizer = CreateOpQuantizer(self, node) op_quantizer.quantize() for i in range(number_of_existing_new_nodes, len(self.new_nodes)): for output_name in self.new_nodes[i].output: self.generated_value_names.add(output_name)
self._dequantize_outputs()
# extend is used to append to the list for a protobuf fields # https://developers.google.com/protocol-buffers/docs/reference/python-generated?csw=1#fields self.model.graph().ClearField("node") self.model.graph().node.extend(self.new_nodes)
# Remove ununsed initializers from graph, starting from the top level graph. if self.parent is None: _, initializers_not_found = self.model.clean_initializers() if len(initializers_not_found) > 0: raise RuntimeError("Invalid model with unknown initializers/tensors." + str(initializers_not_found))
self.model.model.producer_name = __producer__ self.model.model.producer_version = __version__ # Add ms domain if needed ms_opset = [opset for opset in self.model.model.opset_import if opset.domain == ms_domain] if not ms_opset: ms_nodes = [node for node in self.new_nodes if node.domain == "com.microsoft"] if ms_nodes: opset = self.model.model.opset_import.add() opset.version = 1 opset.domain = ms_domain
return self.model.model
def _get_default_tensor_type(self, tensor_name): if "DefaultTensorType" in self.extra_options: logging.info( "get_tensor_type returns DefaultTensorType for tensor name %r, use %d", tensor_name, self.extra_options["DefaultTensorType"], ) return self.extra_options["DefaultTensorType"] raise RuntimeError( f"Unable to find data type for weight_name={tensor_name!r}. " f"shape_inference failed to return a type probably this node is " f"from a different domain or using an input produced by such an operator. " f"This may happen if you quantize a model already quantized. " f"You may use extra_options `DefaultTensorType` to indicate " f"the default weight type, usually `onnx.TensorProto.FLOAT`." )
def get_tensor_type(self, tensor_name, mandatory=False): weight = find_by_name(tensor_name, self.model.initializer()) if weight is not None: return weight.data_type if tensor_name in self.value_infos: vi = self.value_infos[tensor_name] if vi.type.HasField("tensor_type"): if mandatory and vi.type.tensor_type.elem_type == 0: return self._get_default_tensor_type(tensor_name) return vi.type.tensor_type.elem_type if (not self.enable_subgraph_quantization) or (self.parent is None): if mandatory: return self._get_default_tensor_type(tensor_name) return None otype = self.parent.is_valid_quantize_weight(tensor_name) if otype is not None: return otype if self.enable_subgraph_quantization and self.parent: res = self.parent.get_tensor_type(tensor_name) if res is not None: return res if mandatory: return self._get_default_tensor_type(tensor_name) return None
def is_float_tensor(self, tensor_name): if self.is_input_a_initializer(tensor_name): return self.is_valid_quantize_weight(tensor_name)
if tensor_name in self.value_infos: vi = self.value_infos[tensor_name] if vi.type.HasField("tensor_type") and vi.type.tensor_type.elem_type in ( onnx_proto.TensorProto.FLOAT, onnx_proto.TensorProto.FLOAT16, ): return True logging.warning( f"Inference failed or unsupported type to quantize for tensor {tensor_name!r}, type is {vi.type}." ) return False
if self.enable_subgraph_quantization and self.parent: return self.parent.is_float_tensor(tensor_name)
logging.warning( f"Failed to infer data type of tensor: {tensor_name!r}. Please add data type info for this tensor " f"if your model has customized operators." ) return False
def _get_dynamic_input_quantization_params(self, input_name, nodes_list, qType, initial_type): """ Create nodes for dynamic quantization of input and add them to nodes_list. parameter input_name: Name of the input. parameter nodes_list: new nodes are appended to this list. parameter qType: type to quantize to. parameter initial_type: type to quantize from return: scale_name, zero_point_name, scale_shape, zero_point_shape. """ if qType == onnx_proto.TensorProto.INT8: return self._get_dynamic_input_quantization_params_int8(input_name, nodes_list, initial_type) if qType == onnx_proto.TensorProto.UINT8: return self._get_dynamic_input_quantization_params_uint8(input_name, nodes_list, initial_type) raise ValueError(f"Unexpected value for qType={qType}.")
def _get_dynamic_input_quantization_params_int8(self, input_name, nodes_list, initial_type): """ Create nodes for dynamic quantization of input to int8 and add them to nodes_list parameter input_name: Name of the input. parameter nodes_list: new nodes are appended to this list. parameter initial_type: initial weight type (FLOAT or FLOAT16) return: scale_name, zero_point_name, scale_shape, zero_point_shape. """ qType = onnx_proto.TensorProto.INT8 # noqa: N806
# Reduce min and Reduce max input_scale_name = input_name + "_scale"
reduce_min_name = input_name + "_ReduceMin" reduce_min_node = onnx.helper.make_node( "ReduceMin", [input_name], [reduce_min_name + ":0"], reduce_min_name, keepdims=0, ) nodes_list.append(reduce_min_node)
reduce_max_name = input_name + "_ReduceMax" reduce_max_node = onnx.helper.make_node( "ReduceMax", [input_name], [reduce_max_name + ":0"], reduce_max_name, keepdims=0, ) nodes_list.append(reduce_max_node)
# Compute scale # Find abs(rmin) reduce_min_abs_name = reduce_min_name + "_Abs" reduce_min_abs_node = onnx.helper.make_node( "Abs", [reduce_min_node.output[0]], [reduce_min_abs_name + ":0"], reduce_min_abs_name, ) nodes_list.append(reduce_min_abs_node) # Find abs(rmax) reduce_max_abs_name = reduce_max_name + "_Abs" reduce_max_abs_node = onnx.helper.make_node( "Abs", [reduce_max_node.output[0]], [reduce_max_abs_name + ":0"], reduce_max_abs_name, ) nodes_list.append(reduce_max_abs_node) # Compute max of abs(rmin) and abs(rmax) abs_max_name = input_name + "_Abs_Max" abs_max_node = onnx.helper.make_node( "Max", [reduce_min_abs_node.output[0], reduce_max_abs_node.output[0]], [abs_max_name + ":0"], abs_max_name, ) nodes_list.append(abs_max_node) # and divide by (quantize_range/2.0) which will be equal to max(...)*2.0/quantize_range initializer_div = onnx.helper.make_tensor( self.fixed_qrange_int8_name, initial_type, [], [get_qrange_for_qType(qType) / 2.0], ) self.model.add_initializer(initializer_div) scale_div_name = input_name + "scale_Div" scale_div_node = onnx.helper.make_node( "Div", [abs_max_node.output[0], self.fixed_qrange_int8_name], [input_scale_name], scale_div_name, ) nodes_list.append(scale_div_node)
# Zero point initializer_zp = onnx.helper.make_tensor(self.fixed_zero_zp_name, qType, [], [0]) self.model.add_initializer(initializer_zp)
return input_scale_name, self.fixed_zero_zp_name, [], []
def _get_dynamic_input_quantization_params_uint8(self, input_name, nodes_list, initial_type): """ Create nodes for dynamic quantization of input to uint8 and add them to nodes_list parameter input_name: Name of the input. parameter nodes_list: new nodes are appended to this list. parameter initial_type: initial weight type (FLAOT or FLOAT16) return: scale_name, zero_point_name, scale_shape, zero_point_shape. """ qType = onnx_proto.TensorProto.UINT8 # noqa: N806 # Reduce min and Reduce max input_scale_name = input_name + "_scale" input_zp_name = input_name + "_zero_point"
reduce_min_name = input_name + "_ReduceMin" reduce_min_node = onnx.helper.make_node( "ReduceMin", [input_name], [reduce_min_name + ":0"], reduce_min_name, keepdims=0, ) nodes_list.append(reduce_min_node)
reduce_max_name = input_name + "_ReduceMax" reduce_max_node = onnx.helper.make_node( "ReduceMax", [input_name], [reduce_max_name + ":0"], reduce_max_name, keepdims=0, ) nodes_list.append(reduce_max_node)
# Add tensors for quantize range and zero value. initializer_qrange = onnx.helper.make_tensor( self.fixed_qrange_uint8_name, initial_type, [], [get_qrange_for_qType(qType)], ) self.model.add_initializer(initializer_qrange) initializer_qvalue = onnx.helper.make_tensor(self.fixed_zero_name, initial_type, [], [0.0]) self.model.add_initializer(initializer_qvalue)
# Compute Scale # Subtract rmax and rmin scale_sub_name = input_name + "_scale_Sub" scale_sub_node = onnx.helper.make_node( "Sub", [reduce_max_node.output[0], reduce_min_node.output[0]], [scale_sub_name + ":0"], scale_sub_name, ) nodes_list.append(scale_sub_node) # and divide by quantize range scale_div_name = input_name + "_scale_Div" scale_div_node = onnx.helper.make_node( "Div", [scale_sub_node.output[0], self.fixed_qrange_uint8_name], [input_scale_name], scale_div_name, ) nodes_list.append(scale_div_node)
# Compute zero point # Subtract zero and rmin zp_sub_name = input_name + "_zero_point_Sub" zp_sub_node = onnx.helper.make_node( "Sub", [self.fixed_zero_name, reduce_min_node.output[0]], [zp_sub_name + ":0"], zp_sub_name, ) nodes_list.append(zp_sub_node) # Divide by scale zp_div_name = input_name + "_zero_point_Div" zp_div_node = onnx.helper.make_node( "Div", [zp_sub_node.output[0], input_scale_name], [zp_div_name + ":0"], zp_div_name, ) nodes_list.append(zp_div_node) # Compute floor zp_floor_name = input_name + "_zero_point_Floor" zp_floor_node = onnx.helper.make_node("Floor", zp_div_node.output, [zp_floor_name + ":0"], zp_floor_name) nodes_list.append(zp_floor_node) # Cast to integer zp_cast_name = input_name + "_zero_point_Cast" zp_cast_node = onnx.helper.make_node("Cast", zp_floor_node.output, [input_zp_name], zp_cast_name, to=qType) nodes_list.append(zp_cast_node)
return input_scale_name, input_zp_name, [], []
def _get_quantization_params(self, param_name, use_scale=None, use_zeropoint=None): """ Create initializers and inputs in the graph for zero point and scale of output. Zero point and scale values are obtained from self.quantization_params if specified. parameter param_name: Name of the quantization parameter. return: result, scale_name, zero_point_name, scale_shape, zero_point_shape. """ zero_point_type = self.activation_qType
if use_scale is None or use_zeropoint is None: if self.quantization_params is None or param_name not in self.quantization_params: logging.info(f'Quantization parameters for tensor:"{param_name}" not specified') return False, "", "", "", ""
params = self.quantization_params[param_name] if not isinstance(params, QuantizationParams): raise TypeError(f"Unexpected type {type(params)} for {param_name!r}.") if params is None or len(params) != 3: raise ValueError( "Quantization parameters should contain zero point, scale, quant type. " f"Specified values for output {param_name}: {params}" )
zero_point_values = np.array([params["zero_point"]]) if not hasattr(params["scale"], "dtype") or params["scale"].dtype not in (np.float32, np.float16): raise ValueError(f"Unexpected type {type(params['scale'])} and param_name={param_name!r}") scale_values = np.array([params["scale"]]) assert scale_values.dtype != np.float64 zero_point_type = params["quant_type"] else: zero_point_values = np.array([use_zeropoint]) scale_values = np.array([use_scale]) params = self.quantization_params[param_name] if "scale" in params: dtype = params["scale"].dtype scale_values = scale_values.astype(dtype) assert scale_values.dtype != np.float64
zero_point_shape = [] zero_point_name = param_name + "_zero_point" scale_shape = [] scale_name = param_name + "_scale"
# Add initializers init_zp = onnx.helper.make_tensor( zero_point_name, zero_point_type, zero_point_shape, zero_point_values.ravel().tolist() ) self.model.add_initializer(init_zp) if scale_values.dtype == np.float32: scale_type = onnx_proto.TensorProto.FLOAT elif scale_values.dtype == np.float16: scale_type = onnx_proto.TensorProto.FLOAT16 else: raise ValueError(f"Unexpected dtype={scale_values.dtype} for param_name={param_name!r}") init_scale = onnx.helper.make_tensor(scale_name, scale_type, scale_shape, scale_values.reshape((-1,)).tolist()) self.model.add_initializer(init_scale)
return True, scale_name, zero_point_name, scale_shape, zero_point_shape
def _get_quantize_input_nodes( self, node, input_index, qType, given_scale_name=None, given_zp_name=None, initial_type=None ): """ Given an input for a node (which is not a initializer), this function
- add nodes to compute zero point and scale for this input if they don't exist. - add new QuantizeLinear node to quantize the input.
:param node: node being quantized in NodeProto format. :param input_index: index of input in node.input. :param qType: type to quantize to. :param given_scale_name: if those inputs need to be quanitzed using this scale tensor. :param given_zp_name: if those inputs to be quantized using this zeropoint tensor. :param initial_type: type of the weight to quantize :return: List of newly created nodes in NodeProto format. """ input_name = node.input[input_index] assert input_name != "", "Cannot access undefined variable in graph." output_name = input_name + TENSOR_NAME_QUANT_SUFFIX ql_node_name = input_name + "_QuantizeLinear"
if (given_scale_name is not None) and (given_zp_name is not None): data_found, scale_name, zp_name = (True, given_scale_name, given_zp_name) else: data_found, scale_name, zp_name, _, _ = self._get_quantization_params(input_name)
nodes = [] if data_found: qlinear_node = onnx.helper.make_node( "QuantizeLinear", [input_name, scale_name, zp_name], [output_name], ql_node_name, ) else: if self.static: return None # dynamic mode # Scale and Zero Points not available for this input. Add nodes to dynamically compute it if self.fuse_dynamic_quant and qType == onnx_proto.TensorProto.UINT8: scale_name = input_name + "_scale" zp_name = input_name + "_zero_point" qlinear_node = onnx.helper.make_node( "DynamicQuantizeLinear", [input_name], [output_name, scale_name, zp_name], ql_node_name, ) else: assert initial_type is not None, ( f"Cannot quantize input without knowing the initial type, " f"input_name={input_name!r}, input_index={input_index}, qType={qType}, node={node}" ) ( scale_name, zp_name, scale_shape, zp_shape, ) = self._get_dynamic_input_quantization_params(input_name, nodes, qType, initial_type=initial_type) qlinear_node = onnx.helper.make_node( "QuantizeLinear", [input_name, scale_name, zp_name], [output_name], ql_node_name, )
self.quantized_value_map[input_name] = QuantizedValue(input_name, output_name, scale_name, zp_name, qType) return [*nodes, qlinear_node]
def find_quantized_value(self, input_name): if input_name in self.quantized_value_map: return self.quantized_value_map[input_name] if self.parent is not None: return self.parent.find_quantized_value(input_name) return None
def adjust_single_weight_scale_if_needed( self, bias_val, input_scale, weight_scale, weight_scale_dtype, weight_name, bias_name, qrange, multiplicative_epsilon, idx=None, ): """Adjust a single weight scale to ensure the int32 bias does not overflow.""" absmax = np.abs(bias_val) bias_smallest_valid_scale = multiplicative_epsilon * (2.0 * absmax) / qrange
input_scale_fp64 = np.array(input_scale.item(), dtype=np.float64) weight_scale_fp64 = np.array(weight_scale.item(), dtype=np.float64) bias_candidate_scale = input_scale_fp64 * weight_scale_fp64
if (bias_candidate_scale < bias_smallest_valid_scale) and (bias_candidate_scale > 0.0): ratio = bias_smallest_valid_scale / bias_candidate_scale new_scale = weight_scale_fp64 * ratio if idx is None: logging.info( f"Increasing scale for weight `{weight_name}` by the ratio {ratio} to " f"ensure bias `{bias_name}` has a valid scale." ) return True, np.array(new_scale, dtype=weight_scale_dtype) else: logging.info( f"Increased scale[{idx}] for weight `{weight_name}` by ratio {ratio} " f"to ensure bias `{bias_name}` has a valid scale." ) return True, new_scale.astype(weight_scale_dtype) return False, weight_scale
def _adjust_weight_scale_for_int32_bias( self, input_scale: np.ndarray, weight_scale: np.ndarray, weight_name: str, bias_tp: onnx.TensorProto, is_per_channel: bool, ) -> tuple[bool, np.ndarray | None]: """Checks if the bias scale is too small and increases the weight scale if needed."""
if not weight_scale.size: return False, None
bias_float_data = tensor_proto_to_array(bias_tp) int32_info = np.iinfo(np.int32) multiplicative_epsilon = 1.0001 qrange = np.array(int32_info.max, dtype=np.float64) - np.array(int32_info.min + 1, dtype=np.float64) weight_scale_dtype = weight_scale.dtype updated = False
if not is_per_channel: rmin = np.minimum(bias_float_data.min(), np.array(0, dtype=np.float64)) rmax = np.maximum(bias_float_data.max(), np.array(0, dtype=np.float64)) absmax = np.maximum(np.abs(rmin), np.abs(rmax)) changed, new_scale = self.adjust_single_weight_scale_if_needed( absmax, input_scale, weight_scale, weight_scale_dtype, weight_name, bias_tp.name, qrange, multiplicative_epsilon, ) if changed: weight_scale = new_scale updated = True elif weight_scale.shape and len(weight_scale.shape) == 1: for i in range(weight_scale.shape[0]): changed, new_scale = self.adjust_single_weight_scale_if_needed( bias_float_data[i], input_scale, weight_scale[i], weight_scale_dtype, weight_name, bias_tp.name, qrange, multiplicative_epsilon, idx=i, ) if changed: weight_scale[i] = new_scale updated = True
return updated, weight_scale
def _requantize_weight(self, weight_name: str, new_scale: np.ndarray) -> None: """Re-quantizes the given weight initializer using the provided scale."""
if weight_name not in self.quantized_value_map: return
qv = self.quantized_value_map[weight_name]
weight_tp = find_by_name(weight_name, self.model.initializer()) scale_init = find_by_name(qv.scale_name, self.model.initializer()) zp_init = find_by_name(qv.zp_name, self.model.initializer()) q_weight_init = find_by_name(qv.q_name, self.model.initializer())
if weight_tp is None or scale_init is None or zp_init is None or q_weight_init is None: return
self.model.remove_initializer(scale_init) self.model.remove_initializer(q_weight_init)
weight_zero_point = onnx.numpy_helper.to_array(zp_init) axis = qv.axis
# Add new scale initializer scale_np = np.asarray(new_scale, dtype=onnx.helper.tensor_dtype_to_np_dtype(weight_tp.data_type)) new_scale_init = onnx.numpy_helper.from_array(scale_np.reshape(scale_init.dims), qv.scale_name) self.model.add_initializer(new_scale_init)
# Add new quantized weight initializer new_q_weight = quantize_onnx_initializer( weight_tp, self.weight_qType, weight_zero_point, scale_np, axis, quant_weight_name=qv.q_name, ) self.model.add_initializer(new_q_weight)
def quantize_bias_static(self, bias_name, input_name, weight_name, beta=1.0): """ Quantized the bias. Zero Point == 0 and Scale == Input_Scale * Weight_Scale """
# Handle case where bias already in quantization map if bias_name in self.quantized_value_map: return self.quantized_value_map[bias_name].q_name
# get scale for weight weight_scale_name = self.quantized_value_map[weight_name].scale_name weight_initializer = find_by_name(weight_scale_name, self.model.initializer()) weight_scale = tensor_proto_to_array(weight_initializer)
# get scale for input if input_name in self.quantized_value_map: input_scale_name = self.quantized_value_map[input_name].scale_name elif input_name in self.quantization_params: _, input_scale_name, _, _, _ = self._get_quantization_params(input_name) else: raise ValueError(f"Expected {input_name} to be in quantized value map for static quantization")
inputscale_initializer = find_by_name(input_scale_name, self.model.initializer()) input_scale = tensor_proto_to_array(inputscale_initializer)
# Adjust weight scale if quantizing to int32 may overflow due to a small scale weight_zp_name = self.quantized_value_map[weight_name].zp_name weight_zp_init = find_by_name(weight_zp_name, self.model.initializer()) weight_zero_point = onnx.numpy_helper.to_array(weight_zp_init) if weight_zp_init is not None else None is_per_channel = self.per_channel if ( weight_zero_point is not None and weight_zero_point.size and not weight_zero_point.any() and self.weight_qType in (onnx_proto.TensorProto.INT8,) ): bias_initializer = find_by_name(bias_name, self.model.initializer()) did_update, new_weight_scale = self._adjust_weight_scale_for_int32_bias( input_scale, weight_scale, weight_name, bias_initializer, is_per_channel, ) if did_update: self._requantize_weight(weight_name, new_weight_scale) weight_scale = new_weight_scale
( quantized_bias_name, quantized_bias_scale_name, quantized_bias_zp_name, bias_scale_data, node_type, node_qtype, ) = self.quantize_bias_static_impl(bias_name, input_scale, weight_scale, beta)
assert bias_name not in self.quantized_value_map quantized_value = QuantizedValue( bias_name, quantized_bias_name, quantized_bias_scale_name, quantized_bias_zp_name, QuantizedValueType.Initializer, 0 if bias_scale_data.size > 1 else None, node_type=node_type, node_qtype=node_qtype, ) self.quantized_value_map[bias_name] = quantized_value
return quantized_bias_name
def contains_tensor(self, tensor_name): """ only check for value info and newly generated tensor names, initializers are checked separately """ return ( (tensor_name in self.value_infos) or (tensor_name in self.tensor_names) or (tensor_name in self.generated_value_names) )
def quantize_activation(self, node, indices, from_subgraph=False): return self.__quantize_inputs( node=node, indices=indices, initializer_use_weight_qType=False, reduce_range=False, op_level_per_channel=False, axis=-1, from_subgraph=from_subgraph, )
# In some circumstances a weight is not an initializer, for example of MatMul, if both A and B are not # initializer, B can still be considered as Weight def quantize_weight( self, node, indices, reduce_range=False, op_level_per_channel=False, axis=-1, from_subgraph=False, ): return self.__quantize_inputs( node=node, indices=indices, initializer_use_weight_qType=True, reduce_range=reduce_range, op_level_per_channel=op_level_per_channel, axis=axis, from_subgraph=from_subgraph, )
def __quantize_inputs( self, node, indices, initializer_use_weight_qType=True, reduce_range=False, op_level_per_channel=False, axis=-1, from_subgraph=False, ): """ Given a node, this function quantizes the inputs as follows: - If input is an initializer, quantize the initializer data, replace old initializer with new initializer - Else, add QuantizeLinear nodes to perform quantization parameter node: node being quantized in NodeProto format. parameter indices: input indices to quantize. return: (List of quantized input names, List of zero point names used for input quantization, List of scale names used for input quantization, List of new QuantizeLinear nodes created) """
scale_names = [] zero_point_names = [] quantized_input_names = [] nodes = []
for input_index in indices: node_input = node.input[input_index]
# Find if this input is already quantized if node_input in self.quantized_value_map: quantized_value = self.quantized_value_map[node_input] scale_names.append(quantized_value.scale_name) zero_point_names.append(quantized_value.zp_name) quantized_input_names.append(quantized_value.q_name) continue # adding this for case embed_layernorm.py has optional segment_embedding if not node_input: quantized_input_names.append("") scale_names.append("") zero_point_names.append("") continue # Quantize the input initializer = find_by_name(node_input, self.model.initializer()) if initializer is not None: if self.per_channel and op_level_per_channel: ( q_weight_name, zp_name, scale_name, ) = self.quantize_weight_per_channel( initializer.name, self.weight_qType if initializer_use_weight_qType else self.activation_qType, axis, reduce_range, ) else: q_weight_name, zp_name, scale_name = self.quantize_initializer( initializer, self.weight_qType if initializer_use_weight_qType else self.activation_qType, reduce_range, )
quantized_input_names.append(q_weight_name) zero_point_names.append(zp_name) scale_names.append(scale_name) elif self.contains_tensor(node_input): # Add QuantizeLinear node. qlinear_node = self.model.find_node_by_name( node_input + "_QuantizeLinear", self.new_nodes, self.model.graph() ) if qlinear_node is None: input_name = node.input[input_index] if input_name in self.value_infos: value_info = self.value_infos[input_name] assert value_info.HasField("type"), f"value_info={value_info} has no type." assert value_info.type.HasField("tensor_type"), f"value_info={value_info} is not a tensor." initial_type = value_info.type.tensor_type.elem_type else: # Shape inference failed. Fallback to self.tensor_names. assert input_name in self.tensor_names, ( f"shape inference failed for {input_name!r} and " f"attribute 'tensor_names' does not have any value for " f"this tensor." ) initial_type = self.tensor_names[input_name] quantize_input_nodes = self._get_quantize_input_nodes( node, input_index, self.activation_qType, initial_type=initial_type ) if quantize_input_nodes is None: return (None, None, None, None) if from_subgraph: self.add_new_nodes(quantize_input_nodes) else: nodes.extend(quantize_input_nodes) qlinear_node = quantize_input_nodes[-1]
if qlinear_node.op_type == "QuantizeLinear": quantized_input_names.extend(qlinear_node.output) scale_names.append(qlinear_node.input[1]) zero_point_names.append(qlinear_node.input[2]) else: quantized_input_names.append(qlinear_node.output[0]) scale_names.append(qlinear_node.output[1]) zero_point_names.append(qlinear_node.output[2]) elif self.parent is not None: ( parent_quantized_input_names, parent_zero_point_names, parent_scale_names, _, ) = self.parent.__quantize_inputs( node, [input_index], initializer_use_weight_qType=initializer_use_weight_qType, reduce_range=reduce_range, op_level_per_channel=op_level_per_channel, axis=axis, from_subgraph=True, ) quantized_input_names.append(parent_quantized_input_names[0]) scale_names.append(parent_scale_names[0]) zero_point_names.append(parent_zero_point_names[0]) # node should not be add this child level here else: raise ValueError(f"Invalid tensor name to quantize: {node_input} @graph scope{self.graph_scope}")
return quantized_input_names, zero_point_names, scale_names, nodes
def quantize_initializer(self, weight, qType, reduce_range=False, keep_float_weight=False): """ :param weight: TensorProto initializer :param qType: type to quantize to :param keep_float_weight: Whether to quantize the weight. In some cases, we only want to qunatize scale and zero point. If keep_float_weight is False, quantize the weight, or don't quantize the weight. :return: quantized weight name, zero point name, scale name """ # Find if this input is already quantized if weight.name in self.quantized_value_map: quantized_value = self.quantized_value_map[weight.name] return ( quantized_value.q_name, quantized_value.zp_name, quantized_value.scale_name, )
q_weight_name, zp_name, scale_name = self.quantize_initializer_impl( weight, qType, reduce_range, keep_float_weight )
# Log entry for this quantized weight quantized_value = QuantizedValue( weight.name, q_weight_name, scale_name, zp_name, QuantizedValueType.Initializer, None, ) self.quantized_value_map[weight.name] = quantized_value return q_weight_name, zp_name, scale_name
def quantize_weight_per_channel( self, weight_name, weight_qType, channel_axis, reduce_range=True, keep_float_weight=False, ): # Find if this input is already quantized if weight_name in self.quantized_value_map: quantized_value = self.quantized_value_map[weight_name] return ( quantized_value.q_name, quantized_value.zp_name, quantized_value.scale_name, )
q_weight_name, zp_name, scale_name = self.quantize_weight_per_channel_impl( weight_name, weight_qType, channel_axis, reduce_range, keep_float_weight ) quantized_value = QuantizedValue( weight_name, q_weight_name, scale_name, zp_name, QuantizedValueType.Initializer, channel_axis, ) self.quantized_value_map[weight_name] = quantized_value
return q_weight_name, zp_name, scale_name
def _dequantize_value(self, value_name): """ Given a value (input/output) which is quantized, add a DequantizeLinear node to dequantize it back to float32 or float16 parameter value_name: value to dequantize parameter new_nodes_list: List of new nodes created before processing current node return: None if there is already a DequantizeLinear node that dequantizes it A DequantizeLinear node otherwise """ if (value_name in self.quantized_value_map) and (value_name not in self.generated_value_names): quantized_value = self.quantized_value_map[value_name] # Add DequantizeLinear Node for this input
scale_init = find_by_name(quantized_value.scale_name, self.model.initializer())
# 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. if self.model.model.producer_name != "onnx-quantizer" or ( self.model.model.producer_name == "onnx-quantizer" and scale_init is not None ): # Per-tensor (axis=None) requires a scalar scale. if quantized_value.axis is None: assert scale_init is None or onnx.numpy_helper.to_array(scale_init).size == 1
dqlinear_name = value_name + "_DequantizeLinear" dqlinear_node = self.model.find_node_by_name(dqlinear_name, self.new_nodes, self.model.graph()) if dqlinear_node is None: dqlinear_inputs = [ quantized_value.q_name, quantized_value.scale_name, quantized_value.zp_name, ] dequantize_node = onnx.helper.make_node( "DequantizeLinear", dqlinear_inputs, [value_name], dqlinear_name, axis=quantized_value.axis, ) return dequantize_node else: # DQ op is already present, assert it's output matches the input of current node assert value_name == dqlinear_node.output[0] return None
def _dequantize_outputs(self): """ Dequantize output if it is quantized parameter new_nodes_list: List of new nodes created before processing current node return: List of new nodes created """
for output in self.model.graph().output: dequantize_node = self._dequantize_value(output.name) if dequantize_node is not None: self.new_nodes.append(dequantize_node)
def calculate_quantization_params(self): if self.tensors_range is None: return None
self.adjust_tensor_ranges()
quantization_params = {} for tensor_name in self.tensors_range: td = self.tensors_range[tensor_name] if not isinstance(td, TensorData): raise TypeError(f"Unexpected type {type(td)} for {tensor_name!r}.")
quant_overrides = self.tensor_quant_overrides.get_per_tensor_overrides(tensor_name, default_val={})
quant_type = self.activation_qType if "quant_type" in quant_overrides: quant_type = quant_overrides["quant_type"].tensor_type
if "scale" in quant_overrides and "zero_point" in quant_overrides: zero, scale = quant_overrides["zero_point"], quant_overrides["scale"] elif quant_type == onnx.TensorProto.FLOAT8E4M3FN: zero, scale = compute_scale_zp_float8(quant_type, td.avg_std[1]) else: rmin = quant_overrides.get("rmin", td.range_value[0]) rmax = quant_overrides.get("rmax", td.range_value[1]) symmetric = quant_overrides.get("symmetric", self.is_activation_symmetric) reduce_range = quant_overrides.get("reduce_range", False) qmin, qmax = get_qmin_qmax_for_qType(quant_type, reduce_range=reduce_range, symmetric=symmetric) zero, scale = compute_scale_zp(rmin, rmax, qmin, qmax, symmetric, self.min_real_range) if self.is_activation_restricted_asymmetric and quant_type == onnx.TensorProto.UINT8 and not symmetric: # Forward effective qmin/qmax and min_real_range so reduce_range / MinimumRealRange are honored. zero, scale = snap_zero_point_to_uint8( rmin, rmax, qmin=qmin, qmax=qmax, min_real_range=self.min_real_range )
quantization_params[tensor_name] = QuantizationParams(zero_point=zero, scale=scale, quant_type=quant_type)
return quantization_params12# from .base_operator import QuantOperatorBase# from .matmul import MatMulInteger123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119import onnx
from ..quant_utils import TENSOR_NAME_QUANT_SUFFIX, QuantizedValue, QuantizedValueType, attribute_to_kwarg, ms_domainfrom .base_operator import QuantOperatorBasefrom .qdq_base_operator import QDQOperatorBase
class QLinearActivation(QuantOperatorBase): def __init__(self, onnx_quantizer, onnx_node): super().__init__(onnx_quantizer, onnx_node)
def QuantizeClipRelu(self): # noqa: N802 node = self.node assert node.op_type == "Relu" or node.op_type == "Clip"
# When mode is QLinearOps, the output quantization params are calculated based on outputs from # activation nodes, therefore these nodes can be removed from the graph if they follow a quantized op. # If input to this node is not quantized then keep this node # If activation is symmetric, not quantize the op and simply return if node.input[0] not in self.quantizer.quantized_value_map or self.quantizer.is_activation_symmetric: return super().quantize()
quantized_value = self.quantizer.quantized_value_map[node.input[0]] self.quantizer.quantized_value_map[node.output[0]] = quantized_value
def quantize(self): node = self.node if node.op_type == "Relu" or node.op_type == "Clip": self.QuantizeClipRelu() return
nnapi_sigmoid_option = "extra.Sigmoid.nnapi" sigmoid_nnapi_mode = ( node.op_type == "Sigmoid" and nnapi_sigmoid_option in self.quantizer.extra_options and self.quantizer.extra_options[nnapi_sigmoid_option] ) use_scale = 1 / 256.0 if sigmoid_nnapi_mode else None use_zeropoint = 0 if sigmoid_nnapi_mode else None
# No assert on op_type as it is controlled by registry # only try to quantize when given quantization parameters for it ( data_found, output_scale_name, output_zp_name, _, _, ) = self.quantizer._get_quantization_params(node.output[0], use_scale, use_zeropoint) ( quantized_input_names, zero_point_names, scale_names, nodes, ) = self.quantizer.quantize_activation(node, [0]) if not data_found or quantized_input_names is None: return super().quantize()
qlinear_activation_output = node.output[0] + TENSOR_NAME_QUANT_SUFFIX qlinear_activation_name = "" if node.name: qlinear_activation_name = node.name + "_quant" kwargs = {} for attribute in node.attribute: kwargs.update(attribute_to_kwarg(attribute)) kwargs["domain"] = ms_domain
qlinear_activation_inputs = [ quantized_input_names[0], scale_names[0], zero_point_names[0], output_scale_name, output_zp_name, ]
qlinear_activation_node = onnx.helper.make_node( "QLinear" + node.op_type, qlinear_activation_inputs, [qlinear_activation_output], qlinear_activation_name, **kwargs, )
# Create an entry for this quantized value q_output = QuantizedValue( node.output[0], qlinear_activation_output, output_scale_name, output_zp_name, QuantizedValueType.Input, ) self.quantizer.quantized_value_map[node.output[0]] = q_output
nodes.append(qlinear_activation_node) self.quantizer.new_nodes += nodes
class QDQRemovableActivation(QDQOperatorBase): def __init__(self, onnx_quantizer, onnx_node): super().__init__(onnx_quantizer, onnx_node)
def quantize(self): node = self.node
# If input to this node is not quantized then keep this node if not self.quantizer.is_tensor_quantized(node.input[0]): return
if ( not self.quantizer.is_activation_symmetric and not self.quantizer.qdq_keep_removable_activations and self.quantizer.try_replacing_upstream_output(node.input[0], node.output[0]) ): self.quantizer.remove_node(self.node) else: self.quantizer.quantize_activation_tensor(node.input[0])
if not self.disable_qdq_for_node_output: self.quantizer.quantize_activation_tensor(node.output[0])123456789101112131415161718from .base_operator import QuantOperatorBase
# Use the quantized tensor as input without DQ.class QArgMax(QuantOperatorBase): def __init__(self, onnx_quantizer, onnx_node): super().__init__(onnx_quantizer, onnx_node)
def quantize(self): node = self.node
quantized_input_value = self.quantizer.find_quantized_value(node.input[0]) if quantized_input_value is None: self.quantizer.new_nodes += [node] return
node.input[0] = quantized_input_value.q_name self.quantizer.new_nodes += [node]ScaleDF_rebuttal/python_dedup_pkgs/onnx-1.22.0.dist-info/entry_points.txtAdded+5
ScaleDF_rebuttal/python_dedup_pkgs/onnx-1.22.0.dist-info/licenses/LICENSEAdded+202
ScaleDF_rebuttal/python_dedup_pkgs/onnx-1.22.0.dist-info/licenses/NOTICEAdded+59
ScaleDF_rebuttal/python_dedup_pkgs/onnx-1.22.0.dist-info/sboms/sbom.cdx.jsonAdded+75
ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/LICENSEAdded+21
ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/Privacy.mdAdded+21
ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/ThirdPartyNotices.txtAdded
ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/__init__.pyAdded+500
ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/backend/__init__.pyAdded+6
ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/backend/backend.pyAdded+214
ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/backend/backend_rep.pyAdded+76
ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/capi/__init__.pyAdded+4
ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/capi/_ld_preload.pyAdded+7
ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/capi/_pybind_state.pyAdded+33
ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/capi/build_and_package_info.pyAdded+3
ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/capi/convert_npz_to_onnx_adapter.pyAdded+48
ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/capi/libonnxruntime_providers_shared.soAdded
ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/capi/onnxruntime_collect_build_info.pyAdded+47
ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/capi/onnxruntime_inference_collection.pyAdded+1627
ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/capi/onnxruntime_validation.pyAdded+154
ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/datasets/__init__.pyAdded+18
ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/quantization/CalTableFlatBuffers/KeyValue.pyAdded+78
ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/quantization/CalTableFlatBuffers/TrtTable.pyAdded+90
ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/quantization/CalTableFlatBuffers/__init__.pyAdded
ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/quantization/__init__.pyAdded+24
ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/quantization/base_quantizer.pyAdded+530
ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/quantization/calibrate.pyAdded+1353
ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/quantization/cuda_quantizer.pyAdded+643
ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/quantization/execution_providers/qnn/__init__.pyAdded+2
ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/quantization/execution_providers/qnn/fusion_lpnorm.pyAdded+132
ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/quantization/execution_providers/qnn/fusion_spacetodepth.pyAdded+162
ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/quantization/execution_providers/qnn/mixed_precision_overrides_utils.pyAdded+413
ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/quantization/execution_providers/qnn/preprocess.pyAdded+353
ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/quantization/execution_providers/qnn/quant_config.pyAdded+389
ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/quantization/fusions/__init__.pyAdded+4
ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/quantization/fusions/fusion.pyAdded+311
ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/quantization/fusions/fusion_gelu.pyAdded+272
ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/quantization/fusions/fusion_layernorm.pyAdded+146
ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/quantization/fusions/replace_upsample_with_resize.pyAdded+96
ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/quantization/matmul_bnb4_quantizer.pyAdded+239
ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/quantization/matmul_nbits_quantizer.pyAdded+1874
ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/quantization/neural_compressor/__init__.pyAdded+1
ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/quantization/neural_compressor/onnx_model.pyAdded+1236
ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/quantization/neural_compressor/util.pyAdded+80
ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/quantization/neural_compressor/weight_only.pyAdded+932
ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/quantization/onnx_model.pyAdded+600
ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/quantization/onnx_quantizer.pyAdded+1174
ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/quantization/operators/__init__.pyAdded+2
ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/quantization/operators/activation.pyAdded+119
ScaleDF_rebuttal/python_dedup_pkgs/onnxruntime/quantization/operators/argmax.pyAdded+18