Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- micromamba_root/envs/pytorch_env/Lib/site-packages/onnxruntime/__pycache__/__init__.cpython-311.pyc +0 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/onnxruntime/backend/__init__.py +6 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/onnxruntime/backend/backend.py +214 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/onnxruntime/backend/backend_rep.py +76 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/onnxruntime/capi/__init__.py +4 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/onnxruntime/capi/_ld_preload.py +7 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/onnxruntime/capi/_pybind_state.py +33 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/onnxruntime/capi/build_and_package_info.py +2 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/onnxruntime/capi/convert_npz_to_onnx_adapter.py +48 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/onnxruntime/capi/onnxruntime_collect_build_info.py +47 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/onnxruntime/capi/onnxruntime_inference_collection.py +1599 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/onnxruntime/capi/onnxruntime_providers_shared.dll +0 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/onnxruntime/capi/onnxruntime_validation.py +154 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/onnxruntime/capi/version_info.py +2 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/onnxruntime/datasets/__init__.py +18 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/onnxruntime/quantization/CalTableFlatBuffers/KeyValue.py +78 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/onnxruntime/quantization/CalTableFlatBuffers/TrtTable.py +90 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/onnxruntime/quantization/CalTableFlatBuffers/__init__.py +0 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/onnxruntime/quantization/__init__.py +19 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/onnxruntime/quantization/__pycache__/base_quantizer.cpython-311.pyc +0 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/onnxruntime/quantization/__pycache__/calibrate.cpython-311.pyc +0 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/onnxruntime/quantization/__pycache__/matmul_bnb4_quantizer.cpython-311.pyc +0 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/onnxruntime/quantization/__pycache__/matmul_nbits_quantizer.cpython-311.pyc +0 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/onnxruntime/quantization/__pycache__/onnx_model.cpython-311.pyc +0 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/onnxruntime/quantization/__pycache__/onnx_quantizer.cpython-311.pyc +0 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/onnxruntime/quantization/__pycache__/preprocess.cpython-311.pyc +0 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/onnxruntime/quantization/__pycache__/qdq_loss_debug.cpython-311.pyc +0 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/onnxruntime/quantization/__pycache__/qdq_quantizer.cpython-311.pyc +0 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/onnxruntime/quantization/__pycache__/quant_utils.cpython-311.pyc +0 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/onnxruntime/quantization/__pycache__/quantize.cpython-311.pyc +0 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/onnxruntime/quantization/__pycache__/registry.cpython-311.pyc +0 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/onnxruntime/quantization/__pycache__/shape_inference.cpython-311.pyc +0 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/onnxruntime/quantization/__pycache__/static_quantize_runner.cpython-311.pyc +0 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/onnxruntime/quantization/__pycache__/tensor_quant_overrides.cpython-311.pyc +0 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/onnxruntime/quantization/base_quantizer.py +529 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/onnxruntime/quantization/calibrate.py +1267 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/onnxruntime/quantization/fusions/__init__.py +4 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/onnxruntime/quantization/fusions/fusion.py +311 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/onnxruntime/quantization/fusions/fusion_gelu.py +272 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/onnxruntime/quantization/fusions/fusion_layernorm.py +146 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/onnxruntime/quantization/fusions/replace_upsample_with_resize.py +96 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/onnxruntime/quantization/matmul_bnb4_quantizer.py +239 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/onnxruntime/quantization/matmul_nbits_quantizer.py +1638 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/onnxruntime/quantization/neural_compressor/__init__.py +1 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/onnxruntime/quantization/neural_compressor/onnx_model.py +1236 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/onnxruntime/quantization/neural_compressor/util.py +80 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/onnxruntime/quantization/neural_compressor/weight_only.py +932 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/onnxruntime/quantization/onnx_model.py +600 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/onnxruntime/quantization/onnx_quantizer.py +1163 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/onnxruntime/quantization/operators/__init__.py +2 -0
micromamba_root/envs/pytorch_env/Lib/site-packages/onnxruntime/__pycache__/__init__.cpython-311.pyc
ADDED
|
Binary file (18.6 kB). View file
|
|
|
micromamba_root/envs/pytorch_env/Lib/site-packages/onnxruntime/backend/__init__.py
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -------------------------------------------------------------------------
|
| 2 |
+
# Copyright (c) Microsoft Corporation. All rights reserved.
|
| 3 |
+
# Licensed under the MIT License.
|
| 4 |
+
# --------------------------------------------------------------------------
|
| 5 |
+
|
| 6 |
+
from .backend import is_compatible, prepare, run, supports_device # noqa: F401
|
micromamba_root/envs/pytorch_env/Lib/site-packages/onnxruntime/backend/backend.py
ADDED
|
@@ -0,0 +1,214 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -------------------------------------------------------------------------
|
| 2 |
+
# Copyright (c) Microsoft Corporation. All rights reserved.
|
| 3 |
+
# Licensed under the MIT License.
|
| 4 |
+
# --------------------------------------------------------------------------
|
| 5 |
+
"""
|
| 6 |
+
Implements ONNX's backend API.
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
import os
|
| 10 |
+
import unittest
|
| 11 |
+
|
| 12 |
+
import packaging.version
|
| 13 |
+
from onnx import ModelProto, helper, version # noqa: F401
|
| 14 |
+
from onnx.backend.base import Backend
|
| 15 |
+
from onnx.checker import check_model
|
| 16 |
+
|
| 17 |
+
from onnxruntime import InferenceSession, SessionOptions, get_available_providers, get_device
|
| 18 |
+
from onnxruntime.backend.backend_rep import OnnxRuntimeBackendRep
|
| 19 |
+
|
| 20 |
+
# Allowlist of SessionOptions attributes that are safe to set via the backend API.
|
| 21 |
+
# Dangerous attributes intentionally excluded:
|
| 22 |
+
# optimized_model_filepath — triggers Model::Save(), overwrites arbitrary files
|
| 23 |
+
# profile_file_prefix — writes profiling JSON to arbitrary path
|
| 24 |
+
# enable_profiling — causes uncontrolled file writes to cwd
|
| 25 |
+
_ALLOWED_SESSION_OPTIONS = frozenset(
|
| 26 |
+
{
|
| 27 |
+
"enable_cpu_mem_arena",
|
| 28 |
+
"enable_mem_pattern",
|
| 29 |
+
"enable_mem_reuse",
|
| 30 |
+
"execution_mode",
|
| 31 |
+
"execution_order",
|
| 32 |
+
"graph_optimization_level",
|
| 33 |
+
"inter_op_num_threads",
|
| 34 |
+
"intra_op_num_threads",
|
| 35 |
+
"log_severity_level",
|
| 36 |
+
"log_verbosity_level",
|
| 37 |
+
"logid",
|
| 38 |
+
"use_deterministic_compute",
|
| 39 |
+
"use_per_session_threads",
|
| 40 |
+
}
|
| 41 |
+
)
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
class OnnxRuntimeBackend(Backend):
|
| 45 |
+
"""
|
| 46 |
+
Implements
|
| 47 |
+
`ONNX's backend API <https://github.com/onnx/onnx/blob/main/docs/ImplementingAnOnnxBackend.md>`_
|
| 48 |
+
with *ONNX Runtime*.
|
| 49 |
+
The backend is mostly used when you need to switch between
|
| 50 |
+
multiple runtimes with the same API.
|
| 51 |
+
`Importing models from ONNX to Caffe2 <https://github.com/onnx/tutorials/blob/master/tutorials/OnnxCaffe2Import.ipynb>`_
|
| 52 |
+
shows how to use *caffe2* as a backend for a converted model.
|
| 53 |
+
Note: This is not the official Python API.
|
| 54 |
+
"""
|
| 55 |
+
|
| 56 |
+
allowReleasedOpsetsOnly = bool(os.getenv("ALLOW_RELEASED_ONNX_OPSET_ONLY", "1") == "1") # noqa: N815
|
| 57 |
+
|
| 58 |
+
@classmethod
|
| 59 |
+
def is_compatible(cls, model, device=None, **kwargs):
|
| 60 |
+
"""
|
| 61 |
+
Return whether the model is compatible with the backend.
|
| 62 |
+
|
| 63 |
+
:param model: unused
|
| 64 |
+
:param device: None to use the default device or a string (ex: `'CPU'`)
|
| 65 |
+
:return: boolean
|
| 66 |
+
"""
|
| 67 |
+
if device is None:
|
| 68 |
+
device = get_device()
|
| 69 |
+
return cls.supports_device(device)
|
| 70 |
+
|
| 71 |
+
@classmethod
|
| 72 |
+
def is_opset_supported(cls, model):
|
| 73 |
+
"""
|
| 74 |
+
Return whether the opset for the model is supported by the backend.
|
| 75 |
+
When By default only released onnx opsets are allowed by the backend
|
| 76 |
+
To test new opsets env variable ALLOW_RELEASED_ONNX_OPSET_ONLY should be set to 0
|
| 77 |
+
|
| 78 |
+
:param model: Model whose opsets needed to be verified.
|
| 79 |
+
:return: boolean and error message if opset is not supported.
|
| 80 |
+
"""
|
| 81 |
+
if cls.allowReleasedOpsetsOnly:
|
| 82 |
+
for opset in model.opset_import:
|
| 83 |
+
domain = opset.domain if opset.domain else "ai.onnx"
|
| 84 |
+
try:
|
| 85 |
+
key = (domain, opset.version)
|
| 86 |
+
if key not in helper.OP_SET_ID_VERSION_MAP:
|
| 87 |
+
error_message = (
|
| 88 |
+
"Skipping this test as only released onnx opsets are supported."
|
| 89 |
+
"To run this test set env variable ALLOW_RELEASED_ONNX_OPSET_ONLY to 0."
|
| 90 |
+
f" Got Domain '{domain}' version '{opset.version}'."
|
| 91 |
+
)
|
| 92 |
+
return False, error_message
|
| 93 |
+
except AttributeError:
|
| 94 |
+
# for some CI pipelines accessing helper.OP_SET_ID_VERSION_MAP
|
| 95 |
+
# is generating attribute error. TODO investigate the pipelines to
|
| 96 |
+
# fix this error. Falling back to a simple version check when this error is encountered
|
| 97 |
+
if (domain == "ai.onnx" and opset.version > 12) or (domain == "ai.ommx.ml" and opset.version > 2):
|
| 98 |
+
error_message = (
|
| 99 |
+
"Skipping this test as only released onnx opsets are supported."
|
| 100 |
+
"To run this test set env variable ALLOW_RELEASED_ONNX_OPSET_ONLY to 0."
|
| 101 |
+
f" Got Domain '{domain}' version '{opset.version}'."
|
| 102 |
+
)
|
| 103 |
+
return False, error_message
|
| 104 |
+
return True, ""
|
| 105 |
+
|
| 106 |
+
@classmethod
|
| 107 |
+
def supports_device(cls, device):
|
| 108 |
+
"""
|
| 109 |
+
Check whether the backend is compiled with particular device support.
|
| 110 |
+
In particular it's used in the testing suite.
|
| 111 |
+
"""
|
| 112 |
+
if device == "CUDA":
|
| 113 |
+
device = "GPU"
|
| 114 |
+
return "-" + device in get_device() or device + "-" in get_device() or device == get_device()
|
| 115 |
+
|
| 116 |
+
@classmethod
|
| 117 |
+
def prepare(cls, model, device=None, **kwargs):
|
| 118 |
+
"""
|
| 119 |
+
Load the model and creates an :class:`onnxruntime.backend.backend_rep.OnnxRuntimeBackendRep`
|
| 120 |
+
ready to be used as a backend.
|
| 121 |
+
|
| 122 |
+
:param model: the model to prepare — accepts a file path (str), serialized
|
| 123 |
+
model (bytes), :class:`onnx.ModelProto`, :class:`onnxruntime.InferenceSession`,
|
| 124 |
+
or :class:`onnxruntime.backend.backend_rep.OnnxRuntimeBackendRep` (returned as-is)
|
| 125 |
+
:param device: requested device for the computation,
|
| 126 |
+
None means the default one which depends on
|
| 127 |
+
the compilation settings
|
| 128 |
+
:param kwargs: only a safe subset of :class:`onnxruntime.SessionOptions` attributes are
|
| 129 |
+
accepted; see ``_ALLOWED_SESSION_OPTIONS`` for the list
|
| 130 |
+
:return: :class:`onnxruntime.backend.backend_rep.OnnxRuntimeBackendRep`
|
| 131 |
+
"""
|
| 132 |
+
if isinstance(model, OnnxRuntimeBackendRep):
|
| 133 |
+
return model
|
| 134 |
+
elif isinstance(model, InferenceSession):
|
| 135 |
+
return OnnxRuntimeBackendRep(model)
|
| 136 |
+
elif isinstance(model, (str, bytes)):
|
| 137 |
+
options = SessionOptions()
|
| 138 |
+
for k, v in kwargs.items():
|
| 139 |
+
if k in _ALLOWED_SESSION_OPTIONS:
|
| 140 |
+
setattr(options, k, v)
|
| 141 |
+
elif hasattr(options, k):
|
| 142 |
+
raise RuntimeError(
|
| 143 |
+
f"SessionOptions attribute '{k}' is not permitted via the backend API. "
|
| 144 |
+
f"Allowed attributes: {', '.join(sorted(_ALLOWED_SESSION_OPTIONS))}"
|
| 145 |
+
)
|
| 146 |
+
# else: silently ignore unknown keys
|
| 147 |
+
|
| 148 |
+
excluded_providers = os.getenv("ORT_ONNX_BACKEND_EXCLUDE_PROVIDERS", default="").split(",")
|
| 149 |
+
providers = [x for x in get_available_providers() if (x not in excluded_providers)]
|
| 150 |
+
|
| 151 |
+
inf = InferenceSession(model, sess_options=options, providers=providers)
|
| 152 |
+
# backend API is primarily used for ONNX test/validation. As such, we should disable session.run() fallback
|
| 153 |
+
# which may hide test failures.
|
| 154 |
+
inf.disable_fallback()
|
| 155 |
+
if device is not None and not cls.supports_device(device):
|
| 156 |
+
raise RuntimeError(f"Incompatible device expected '{device}', got '{get_device()}'")
|
| 157 |
+
return cls.prepare(inf, device, **kwargs)
|
| 158 |
+
else:
|
| 159 |
+
# type: ModelProto
|
| 160 |
+
# check_model serializes the model anyways, so serialize the model once here
|
| 161 |
+
# and reuse it below in the cls.prepare call to avoid an additional serialization
|
| 162 |
+
# only works with onnx >= 1.10.0 hence the version check
|
| 163 |
+
onnx_version = packaging.version.parse(version.version) or packaging.version.Version("0")
|
| 164 |
+
onnx_supports_serialized_model_check = onnx_version.release >= (1, 10, 0)
|
| 165 |
+
bin_or_model = model.SerializeToString() if onnx_supports_serialized_model_check else model
|
| 166 |
+
check_model(bin_or_model)
|
| 167 |
+
opset_supported, error_message = cls.is_opset_supported(model)
|
| 168 |
+
if not opset_supported:
|
| 169 |
+
raise unittest.SkipTest(error_message)
|
| 170 |
+
# Now bin might be serialized, if it's not we need to serialize it otherwise we'll have
|
| 171 |
+
# an infinite recursive call
|
| 172 |
+
bin = bin_or_model
|
| 173 |
+
if not isinstance(bin, (str, bytes)):
|
| 174 |
+
bin = bin.SerializeToString()
|
| 175 |
+
return cls.prepare(bin, device, **kwargs)
|
| 176 |
+
|
| 177 |
+
@classmethod
|
| 178 |
+
def run_model(cls, model, inputs, device=None, **kwargs):
|
| 179 |
+
"""
|
| 180 |
+
Compute the prediction.
|
| 181 |
+
|
| 182 |
+
:param model: the model to run — accepts a file path (str), serialized
|
| 183 |
+
model (bytes), :class:`onnx.ModelProto`, :class:`onnxruntime.InferenceSession`,
|
| 184 |
+
or :class:`onnxruntime.backend.backend_rep.OnnxRuntimeBackendRep`
|
| 185 |
+
:param inputs: inputs
|
| 186 |
+
:param device: requested device for the computation,
|
| 187 |
+
None means the default one which depends on
|
| 188 |
+
the compilation settings
|
| 189 |
+
:param kwargs: ``run_model()`` forwards kwargs to both ``prepare()`` and ``rep.run()``.
|
| 190 |
+
``prepare()`` validates and applies ``_ALLOWED_SESSION_OPTIONS`` only when creating
|
| 191 |
+
a new session from a model path or bytes; if ``model`` is already an
|
| 192 |
+
``InferenceSession`` or ``OnnxRuntimeBackendRep``, session-option kwargs are
|
| 193 |
+
silently ignored. ``rep.run()`` always validates against ``_ALLOWED_RUN_OPTIONS``
|
| 194 |
+
and raises ``RuntimeError`` for known-but-blocked run attributes.
|
| 195 |
+
Logging-related kwargs (``log_severity_level``, ``log_verbosity_level``, ``logid``)
|
| 196 |
+
appear in both allowlists.
|
| 197 |
+
:return: predictions
|
| 198 |
+
"""
|
| 199 |
+
rep = cls.prepare(model, device, **kwargs)
|
| 200 |
+
return rep.run(inputs, **kwargs)
|
| 201 |
+
|
| 202 |
+
@classmethod
|
| 203 |
+
def run_node(cls, node, inputs, device=None, outputs_info=None, **kwargs):
|
| 204 |
+
"""
|
| 205 |
+
This method is not implemented as it is much more efficient
|
| 206 |
+
to run a whole model than every node independently.
|
| 207 |
+
"""
|
| 208 |
+
raise NotImplementedError("It is much more efficient to run a whole model than every node independently.")
|
| 209 |
+
|
| 210 |
+
|
| 211 |
+
is_compatible = OnnxRuntimeBackend.is_compatible
|
| 212 |
+
prepare = OnnxRuntimeBackend.prepare
|
| 213 |
+
run = OnnxRuntimeBackend.run_model
|
| 214 |
+
supports_device = OnnxRuntimeBackend.supports_device
|
micromamba_root/envs/pytorch_env/Lib/site-packages/onnxruntime/backend/backend_rep.py
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -------------------------------------------------------------------------
|
| 2 |
+
# Copyright (c) Microsoft Corporation. All rights reserved.
|
| 3 |
+
# Licensed under the MIT License.
|
| 4 |
+
# --------------------------------------------------------------------------
|
| 5 |
+
"""
|
| 6 |
+
Implements ONNX's backend API.
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
from onnx.backend.base import BackendRep
|
| 10 |
+
|
| 11 |
+
from onnxruntime import RunOptions
|
| 12 |
+
|
| 13 |
+
# Allowlist of RunOptions attributes that are safe to set via the backend API.
|
| 14 |
+
# 'terminate' excluded: setting it True would deny the current inference call.
|
| 15 |
+
# 'training_mode' excluded: silently switches inference behavior in training builds.
|
| 16 |
+
_ALLOWED_RUN_OPTIONS = frozenset(
|
| 17 |
+
{
|
| 18 |
+
"log_severity_level",
|
| 19 |
+
"log_verbosity_level",
|
| 20 |
+
"logid",
|
| 21 |
+
"only_execute_path_to_fetches",
|
| 22 |
+
}
|
| 23 |
+
)
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class OnnxRuntimeBackendRep(BackendRep):
|
| 27 |
+
"""
|
| 28 |
+
Wraps an :class:`onnxruntime.InferenceSession` to implement ONNX's
|
| 29 |
+
:class:`onnx.backend.base.BackendRep` interface for running predictions.
|
| 30 |
+
"""
|
| 31 |
+
|
| 32 |
+
def __init__(self, session):
|
| 33 |
+
"""
|
| 34 |
+
:param session: :class:`onnxruntime.InferenceSession`
|
| 35 |
+
"""
|
| 36 |
+
self._session = session
|
| 37 |
+
|
| 38 |
+
def run(self, inputs, **kwargs): # type: (Any, **Any) -> Tuple[Any, ...]
|
| 39 |
+
"""
|
| 40 |
+
Computes the prediction.
|
| 41 |
+
See :meth:`onnxruntime.InferenceSession.run`.
|
| 42 |
+
|
| 43 |
+
:param inputs: a list of input arrays (one per model input) or a single
|
| 44 |
+
array when the model has exactly one input
|
| 45 |
+
:param kwargs: only a safe subset of :class:`onnxruntime.RunOptions` attributes are
|
| 46 |
+
accepted; see ``_ALLOWED_RUN_OPTIONS`` for the list
|
| 47 |
+
:return: list of output arrays
|
| 48 |
+
"""
|
| 49 |
+
|
| 50 |
+
options = RunOptions()
|
| 51 |
+
for k, v in kwargs.items():
|
| 52 |
+
if k in _ALLOWED_RUN_OPTIONS:
|
| 53 |
+
setattr(options, k, v)
|
| 54 |
+
elif hasattr(options, k):
|
| 55 |
+
raise RuntimeError(
|
| 56 |
+
f"RunOptions attribute '{k}' is not permitted via the backend API. "
|
| 57 |
+
f"Allowed attributes: {', '.join(sorted(_ALLOWED_RUN_OPTIONS))}"
|
| 58 |
+
)
|
| 59 |
+
# else: silently ignore unknown keys
|
| 60 |
+
|
| 61 |
+
if isinstance(inputs, list):
|
| 62 |
+
inps = {}
|
| 63 |
+
for i, inp in enumerate(self._session.get_inputs()):
|
| 64 |
+
inps[inp.name] = inputs[i]
|
| 65 |
+
outs = self._session.run(None, inps, options)
|
| 66 |
+
if isinstance(outs, list):
|
| 67 |
+
return outs
|
| 68 |
+
else:
|
| 69 |
+
output_names = [o.name for o in self._session.get_outputs()]
|
| 70 |
+
return [outs[name] for name in output_names]
|
| 71 |
+
else:
|
| 72 |
+
inp = self._session.get_inputs()
|
| 73 |
+
if len(inp) != 1:
|
| 74 |
+
raise RuntimeError(f"Model expect {len(inp)} inputs")
|
| 75 |
+
inps = {inp[0].name: inputs}
|
| 76 |
+
return self._session.run(None, inps, options)
|
micromamba_root/envs/pytorch_env/Lib/site-packages/onnxruntime/capi/__init__.py
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -------------------------------------------------------------------------
|
| 2 |
+
# Copyright (c) Microsoft Corporation. All rights reserved.
|
| 3 |
+
# Licensed under the MIT License.
|
| 4 |
+
# --------------------------------------------------------------------------
|
micromamba_root/envs/pytorch_env/Lib/site-packages/onnxruntime/capi/_ld_preload.py
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -------------------------------------------------------------------------
|
| 2 |
+
# Copyright (c) Microsoft Corporation. All rights reserved.
|
| 3 |
+
# Licensed under the MIT License.
|
| 4 |
+
# --------------------------------------------------------------------------
|
| 5 |
+
|
| 6 |
+
# This file can be modified by setup.py when building a manylinux2010 wheel
|
| 7 |
+
# When modified, it will preload some libraries needed for the python C extension
|
micromamba_root/envs/pytorch_env/Lib/site-packages/onnxruntime/capi/_pybind_state.py
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -------------------------------------------------------------------------
|
| 2 |
+
# Copyright (c) Microsoft Corporation. All rights reserved.
|
| 3 |
+
# Licensed under the MIT License.
|
| 4 |
+
# --------------------------------------------------------------------------
|
| 5 |
+
"""
|
| 6 |
+
Ensure that dependencies are available and then load the extension module.
|
| 7 |
+
"""
|
| 8 |
+
import os
|
| 9 |
+
import platform
|
| 10 |
+
import warnings
|
| 11 |
+
|
| 12 |
+
from . import _ld_preload # noqa: F401
|
| 13 |
+
|
| 14 |
+
if platform.system() == "Windows":
|
| 15 |
+
from . import version_info
|
| 16 |
+
|
| 17 |
+
# If on Windows, check if this import error is caused by the user not installing the 2019 VC Runtime
|
| 18 |
+
# The VC Redist installer usually puts the VC Runtime dlls in the System32 folder, but it may also be found
|
| 19 |
+
# in some other locations.
|
| 20 |
+
# TODO, we may want to try to load the VC Runtime dlls instead of checking if the hardcoded file path
|
| 21 |
+
# is valid, and raise ImportError if the load fails
|
| 22 |
+
if version_info.vs2019 and platform.architecture()[0] == "64bit":
|
| 23 |
+
system_root = os.getenv("SystemRoot") or "C:\\Windows"
|
| 24 |
+
if not os.path.isfile(os.path.join(system_root, "System32", "vcruntime140_1.dll")):
|
| 25 |
+
warnings.warn("Please install the 2019 Visual C++ runtime and then try again. "
|
| 26 |
+
"If you've installed the runtime in a non-standard location "
|
| 27 |
+
"(other than %SystemRoot%\\System32), "
|
| 28 |
+
"make sure it can be found by setting the correct path.")
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
from .onnxruntime_pybind11_state import * # noqa
|
| 33 |
+
|
micromamba_root/envs/pytorch_env/Lib/site-packages/onnxruntime/capi/build_and_package_info.py
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
package_name = 'onnxruntime'
|
| 2 |
+
__version__ = '1.26.0'
|
micromamba_root/envs/pytorch_env/Lib/site-packages/onnxruntime/capi/convert_npz_to_onnx_adapter.py
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Microsoft Corporation. All rights reserved.
|
| 2 |
+
# Licensed under the MIT License.
|
| 3 |
+
|
| 4 |
+
# This script helps converting .npz files to .onnx_adapter files
|
| 5 |
+
|
| 6 |
+
import argparse
|
| 7 |
+
import os
|
| 8 |
+
import sys
|
| 9 |
+
|
| 10 |
+
import numpy as np
|
| 11 |
+
|
| 12 |
+
import onnxruntime as ort
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def get_args() -> argparse:
|
| 16 |
+
parser = argparse.ArgumentParser()
|
| 17 |
+
parser.add_argument("--npz_file_path", type=str, required=True)
|
| 18 |
+
parser.add_argument("--output_file_path", type=str, required=True)
|
| 19 |
+
parser.add_argument("--adapter_version", type=int, required=True)
|
| 20 |
+
parser.add_argument("--model_version", type=int, required=True)
|
| 21 |
+
return parser.parse_args()
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def export_lora_parameters(
|
| 25 |
+
npz_file_path: os.PathLike, adapter_version: int, model_version: int, output_file_path: os.PathLike
|
| 26 |
+
):
|
| 27 |
+
"""The function converts lora parameters in npz to onnx_adapter format"""
|
| 28 |
+
adapter_format = ort.AdapterFormat()
|
| 29 |
+
adapter_format.set_adapter_version(adapter_version)
|
| 30 |
+
adapter_format.set_model_version(model_version)
|
| 31 |
+
name_to_ort_value = {}
|
| 32 |
+
with np.load(npz_file_path) as data:
|
| 33 |
+
for name, np_arr in data.items():
|
| 34 |
+
ort_value = ort.OrtValue.ortvalue_from_numpy(np_arr)
|
| 35 |
+
name_to_ort_value[name] = ort_value
|
| 36 |
+
|
| 37 |
+
adapter_format.set_parameters(name_to_ort_value)
|
| 38 |
+
adapter_format.export_adapter(output_file_path)
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def main() -> int:
|
| 42 |
+
args = get_args()
|
| 43 |
+
export_lora_parameters(args.npz_file_path, args.adapter_version, args.model_version, args.output_file_path)
|
| 44 |
+
return 0
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
if __name__ == "__main__":
|
| 48 |
+
sys.exit(main())
|
micromamba_root/envs/pytorch_env/Lib/site-packages/onnxruntime/capi/onnxruntime_collect_build_info.py
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -------------------------------------------------------------------------
|
| 2 |
+
# Copyright (c) Microsoft Corporation. All rights reserved.
|
| 3 |
+
# Licensed under the MIT License.
|
| 4 |
+
# --------------------------------------------------------------------------
|
| 5 |
+
import ctypes
|
| 6 |
+
import sys
|
| 7 |
+
import warnings
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def find_cudart_versions(build_env=False, build_cuda_version=None):
|
| 11 |
+
# ctypes.CDLL and ctypes.util.find_library load the latest installed library.
|
| 12 |
+
# it may not the the library that would be loaded by onnxruntime.
|
| 13 |
+
# for example, in an environment with Cuda 11.1 and subsequently
|
| 14 |
+
# conda cudatoolkit 10.2.89 installed. ctypes will find cudart 10.2. however,
|
| 15 |
+
# onnxruntime built with Cuda 11.1 will find and load cudart for Cuda 11.1.
|
| 16 |
+
# for the above reason, we need find all versions in the environment and
|
| 17 |
+
# only give warnings if the expected cuda version is not found.
|
| 18 |
+
# in onnxruntime build environment, we expected only one Cuda version.
|
| 19 |
+
if not sys.platform.startswith("linux"):
|
| 20 |
+
warnings.warn("find_cudart_versions only works on Linux")
|
| 21 |
+
return None
|
| 22 |
+
|
| 23 |
+
cudart_possible_versions = {None, build_cuda_version}
|
| 24 |
+
|
| 25 |
+
def get_cudart_version(find_cudart_version=None):
|
| 26 |
+
cudart_lib_filename = "libcudart.so"
|
| 27 |
+
if find_cudart_version:
|
| 28 |
+
cudart_lib_filename = cudart_lib_filename + "." + find_cudart_version
|
| 29 |
+
|
| 30 |
+
try:
|
| 31 |
+
cudart = ctypes.CDLL(cudart_lib_filename)
|
| 32 |
+
cudart.cudaRuntimeGetVersion.restype = int
|
| 33 |
+
cudart.cudaRuntimeGetVersion.argtypes = [ctypes.POINTER(ctypes.c_int)]
|
| 34 |
+
version = ctypes.c_int()
|
| 35 |
+
status = cudart.cudaRuntimeGetVersion(ctypes.byref(version))
|
| 36 |
+
if status != 0:
|
| 37 |
+
return None
|
| 38 |
+
except Exception:
|
| 39 |
+
return None
|
| 40 |
+
|
| 41 |
+
return version.value
|
| 42 |
+
|
| 43 |
+
# use set to avoid duplications
|
| 44 |
+
cudart_found_versions = {get_cudart_version(cudart_version) for cudart_version in cudart_possible_versions}
|
| 45 |
+
|
| 46 |
+
# convert to list and remove None
|
| 47 |
+
return [ver for ver in cudart_found_versions if ver]
|
micromamba_root/envs/pytorch_env/Lib/site-packages/onnxruntime/capi/onnxruntime_inference_collection.py
ADDED
|
@@ -0,0 +1,1599 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -------------------------------------------------------------------------
|
| 2 |
+
# Copyright (c) Microsoft Corporation. All rights reserved.
|
| 3 |
+
# Licensed under the MIT License.
|
| 4 |
+
# --------------------------------------------------------------------------
|
| 5 |
+
from __future__ import annotations
|
| 6 |
+
|
| 7 |
+
import collections
|
| 8 |
+
import collections.abc
|
| 9 |
+
import os
|
| 10 |
+
import typing
|
| 11 |
+
import warnings
|
| 12 |
+
from collections.abc import Callable, Sequence
|
| 13 |
+
from enum import IntEnum
|
| 14 |
+
from typing import Any
|
| 15 |
+
|
| 16 |
+
import numpy as np
|
| 17 |
+
|
| 18 |
+
from onnxruntime.capi import _pybind_state as C
|
| 19 |
+
|
| 20 |
+
if typing.TYPE_CHECKING:
|
| 21 |
+
import numpy.typing as npt
|
| 22 |
+
|
| 23 |
+
import onnxruntime
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def get_ort_device_type(device_type: str) -> int:
|
| 27 |
+
if device_type == "cuda":
|
| 28 |
+
return C.OrtDevice.cuda()
|
| 29 |
+
elif device_type == "cann":
|
| 30 |
+
return C.OrtDevice.cann()
|
| 31 |
+
elif device_type == "cpu":
|
| 32 |
+
return C.OrtDevice.cpu()
|
| 33 |
+
elif device_type == "dml":
|
| 34 |
+
return C.OrtDevice.dml()
|
| 35 |
+
elif device_type == "webgpu":
|
| 36 |
+
return C.OrtDevice.webgpu()
|
| 37 |
+
elif device_type == "gpu":
|
| 38 |
+
return C.OrtDevice.gpu()
|
| 39 |
+
elif device_type == "npu":
|
| 40 |
+
return C.OrtDevice.npu()
|
| 41 |
+
else:
|
| 42 |
+
raise Exception("Unsupported device type: " + device_type)
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
class OrtDeviceVendorId(IntEnum):
|
| 46 |
+
"""Vendor IDs aligned with OrtDevice::VendorIds in ortdevice.h."""
|
| 47 |
+
|
| 48 |
+
NONE = 0x0000
|
| 49 |
+
AMD = 0x1002
|
| 50 |
+
NVIDIA = 0x10DE
|
| 51 |
+
ARM = 0x13B5
|
| 52 |
+
MICROSOFT = 0x1414
|
| 53 |
+
HUAWEI = 0x19E5
|
| 54 |
+
QUALCOMM = 0x5143
|
| 55 |
+
INTEL = 0x8086
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def get_vendor_id_for_device_type(device_type: str) -> OrtDeviceVendorId | None:
|
| 59 |
+
if device_type == "cuda":
|
| 60 |
+
return OrtDeviceVendorId.NVIDIA
|
| 61 |
+
elif device_type == "dml":
|
| 62 |
+
return OrtDeviceVendorId.MICROSOFT
|
| 63 |
+
elif device_type == "cann":
|
| 64 |
+
return OrtDeviceVendorId.HUAWEI
|
| 65 |
+
else:
|
| 66 |
+
return None
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
class AdapterFormat:
|
| 70 |
+
"""
|
| 71 |
+
This class is used to create adapter files from python structures
|
| 72 |
+
"""
|
| 73 |
+
|
| 74 |
+
def __init__(self, adapter=None) -> None:
|
| 75 |
+
if adapter is None:
|
| 76 |
+
self._adapter = C.AdapterFormat()
|
| 77 |
+
else:
|
| 78 |
+
self._adapter = adapter
|
| 79 |
+
|
| 80 |
+
@staticmethod
|
| 81 |
+
def read_adapter(file_path: os.PathLike) -> AdapterFormat:
|
| 82 |
+
return AdapterFormat(C.AdapterFormat.read_adapter(file_path))
|
| 83 |
+
|
| 84 |
+
def export_adapter(self, file_path: os.PathLike):
|
| 85 |
+
"""
|
| 86 |
+
This function writes a file at the specified location
|
| 87 |
+
in onnxrunitme adapter format containing Lora parameters.
|
| 88 |
+
|
| 89 |
+
:param file_path: absolute path for the adapter
|
| 90 |
+
"""
|
| 91 |
+
self._adapter.export_adapter(file_path)
|
| 92 |
+
|
| 93 |
+
def get_format_version(self) -> int:
|
| 94 |
+
return self._adapter.format_version
|
| 95 |
+
|
| 96 |
+
def set_adapter_version(self, adapter_version: int) -> None:
|
| 97 |
+
self._adapter.adapter_version = adapter_version
|
| 98 |
+
|
| 99 |
+
def get_adapter_version(self) -> int:
|
| 100 |
+
return self._adapter.adapter_version
|
| 101 |
+
|
| 102 |
+
def set_model_version(self, model_version: int) -> None:
|
| 103 |
+
self._adapter.model_version = model_version
|
| 104 |
+
|
| 105 |
+
def get_model_version(self) -> int:
|
| 106 |
+
return self._adapter.model_version
|
| 107 |
+
|
| 108 |
+
def set_parameters(self, params: dict[str, OrtValue]) -> None:
|
| 109 |
+
self._adapter.parameters = {k: v._ortvalue for k, v in params.items()}
|
| 110 |
+
|
| 111 |
+
def get_parameters(self) -> dict[str, OrtValue]:
|
| 112 |
+
return {k: OrtValue(v) for k, v in self._adapter.parameters.items()}
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
def check_and_normalize_provider_args(
|
| 116 |
+
providers: Sequence[str | tuple[str, dict[Any, Any]]] | None,
|
| 117 |
+
provider_options: Sequence[dict[Any, Any]] | None,
|
| 118 |
+
available_provider_names: Sequence[str],
|
| 119 |
+
):
|
| 120 |
+
"""
|
| 121 |
+
Validates the 'providers' and 'provider_options' arguments and returns a
|
| 122 |
+
normalized version.
|
| 123 |
+
|
| 124 |
+
:param providers: Optional sequence of providers in order of decreasing
|
| 125 |
+
precedence. Values can either be provider names or tuples of
|
| 126 |
+
(provider name, options dict).
|
| 127 |
+
:param provider_options: Optional sequence of options dicts corresponding
|
| 128 |
+
to the providers listed in 'providers'.
|
| 129 |
+
:param available_provider_names: The available provider names.
|
| 130 |
+
|
| 131 |
+
:return: Tuple of (normalized 'providers' sequence, normalized
|
| 132 |
+
'provider_options' sequence).
|
| 133 |
+
|
| 134 |
+
'providers' can contain either names or names and options. When any options
|
| 135 |
+
are given in 'providers', 'provider_options' should not be used.
|
| 136 |
+
|
| 137 |
+
The normalized result is a tuple of:
|
| 138 |
+
1. Sequence of provider names in the same order as 'providers'.
|
| 139 |
+
2. Sequence of corresponding provider options dicts with string keys and
|
| 140 |
+
values. Unspecified provider options yield empty dicts.
|
| 141 |
+
"""
|
| 142 |
+
if providers is None:
|
| 143 |
+
return [], []
|
| 144 |
+
|
| 145 |
+
provider_name_to_options = collections.OrderedDict()
|
| 146 |
+
|
| 147 |
+
def set_provider_options(name, options):
|
| 148 |
+
if name not in available_provider_names:
|
| 149 |
+
warnings.warn(
|
| 150 |
+
"Specified provider '{}' is not in available provider names.Available providers: '{}'".format(
|
| 151 |
+
name, ", ".join(available_provider_names)
|
| 152 |
+
)
|
| 153 |
+
)
|
| 154 |
+
|
| 155 |
+
if name in provider_name_to_options:
|
| 156 |
+
warnings.warn(f"Duplicate provider '{name}' encountered, ignoring.")
|
| 157 |
+
return
|
| 158 |
+
|
| 159 |
+
normalized_options = {str(key): str(value) for key, value in options.items()}
|
| 160 |
+
provider_name_to_options[name] = normalized_options
|
| 161 |
+
|
| 162 |
+
if not isinstance(providers, collections.abc.Sequence):
|
| 163 |
+
raise ValueError("'providers' should be a sequence.")
|
| 164 |
+
|
| 165 |
+
if provider_options is not None:
|
| 166 |
+
if not isinstance(provider_options, collections.abc.Sequence):
|
| 167 |
+
raise ValueError("'provider_options' should be a sequence.")
|
| 168 |
+
|
| 169 |
+
if len(providers) != len(provider_options):
|
| 170 |
+
raise ValueError("'providers' and 'provider_options' should be the same length if both are given.")
|
| 171 |
+
|
| 172 |
+
if not all(isinstance(provider, str) for provider in providers):
|
| 173 |
+
raise ValueError("Only string values for 'providers' are supported if 'provider_options' is given.")
|
| 174 |
+
|
| 175 |
+
if not all(isinstance(options_for_provider, dict) for options_for_provider in provider_options):
|
| 176 |
+
raise ValueError("'provider_options' values must be dicts.")
|
| 177 |
+
|
| 178 |
+
for name, options in zip(providers, provider_options, strict=False):
|
| 179 |
+
set_provider_options(name, options)
|
| 180 |
+
|
| 181 |
+
else:
|
| 182 |
+
for provider in providers:
|
| 183 |
+
if isinstance(provider, str):
|
| 184 |
+
set_provider_options(provider, {})
|
| 185 |
+
elif (
|
| 186 |
+
isinstance(provider, tuple)
|
| 187 |
+
and len(provider) == 2
|
| 188 |
+
and isinstance(provider[0], str)
|
| 189 |
+
and isinstance(provider[1], dict)
|
| 190 |
+
):
|
| 191 |
+
set_provider_options(provider[0], provider[1])
|
| 192 |
+
else:
|
| 193 |
+
raise ValueError("'providers' values must be either strings or (string, dict) tuples.")
|
| 194 |
+
|
| 195 |
+
return list(provider_name_to_options.keys()), list(provider_name_to_options.values())
|
| 196 |
+
|
| 197 |
+
|
| 198 |
+
class Session:
|
| 199 |
+
"""
|
| 200 |
+
This is the main class used to run a model.
|
| 201 |
+
"""
|
| 202 |
+
|
| 203 |
+
def __init__(self, enable_fallback: bool = True):
|
| 204 |
+
# self._sess is managed by the derived class and relies on bindings from C.InferenceSession
|
| 205 |
+
self._sess = None
|
| 206 |
+
self._enable_fallback = enable_fallback
|
| 207 |
+
|
| 208 |
+
def get_session_options(self) -> onnxruntime.SessionOptions:
|
| 209 |
+
"Return the session options. See :class:`onnxruntime.SessionOptions`."
|
| 210 |
+
return self._sess_options
|
| 211 |
+
|
| 212 |
+
def get_inputs(self) -> Sequence[onnxruntime.NodeArg]:
|
| 213 |
+
"Return the inputs metadata as a list of :class:`onnxruntime.NodeArg`."
|
| 214 |
+
return self._inputs_meta
|
| 215 |
+
|
| 216 |
+
def get_outputs(self) -> Sequence[onnxruntime.NodeArg]:
|
| 217 |
+
"Return the outputs metadata as a list of :class:`onnxruntime.NodeArg`."
|
| 218 |
+
return self._outputs_meta
|
| 219 |
+
|
| 220 |
+
def get_overridable_initializers(self) -> Sequence[onnxruntime.NodeArg]:
|
| 221 |
+
"Return the inputs (including initializers) metadata as a list of :class:`onnxruntime.NodeArg`."
|
| 222 |
+
return self._overridable_initializers
|
| 223 |
+
|
| 224 |
+
def get_modelmeta(self) -> onnxruntime.ModelMetadata:
|
| 225 |
+
"Return the metadata. See :class:`onnxruntime.ModelMetadata`."
|
| 226 |
+
return self._model_meta
|
| 227 |
+
|
| 228 |
+
def get_input_memory_infos(self) -> Sequence[onnxruntime.MemoryInfo]:
|
| 229 |
+
"Return the memory info for the inputs."
|
| 230 |
+
return self._input_meminfos
|
| 231 |
+
|
| 232 |
+
def get_output_memory_infos(self) -> Sequence[onnxruntime.MemoryInfo]:
|
| 233 |
+
"Return the memory info for the outputs."
|
| 234 |
+
return self._output_meminfos
|
| 235 |
+
|
| 236 |
+
def get_input_epdevices(self) -> Sequence[onnxruntime.OrtEpDevice]:
|
| 237 |
+
"Return the execution providers for the inputs."
|
| 238 |
+
return self._input_epdevices
|
| 239 |
+
|
| 240 |
+
def get_providers(self) -> Sequence[str]:
|
| 241 |
+
"Return list of registered execution providers."
|
| 242 |
+
return self._providers
|
| 243 |
+
|
| 244 |
+
def get_provider_options(self):
|
| 245 |
+
"Return registered execution providers' configurations."
|
| 246 |
+
return self._provider_options
|
| 247 |
+
|
| 248 |
+
def get_provider_graph_assignment_info(self) -> Sequence[onnxruntime.OrtEpAssignedSubgraph]:
|
| 249 |
+
"""
|
| 250 |
+
Get information about the subgraphs assigned to each execution provider and the nodes within.
|
| 251 |
+
|
| 252 |
+
Application must enable the recording of graph assignment information by setting the session configuration
|
| 253 |
+
for the key "session.record_ep_graph_assignment_info" to "1".
|
| 254 |
+
"""
|
| 255 |
+
return self._sess.get_provider_graph_assignment_info()
|
| 256 |
+
|
| 257 |
+
def set_providers(self, providers=None, provider_options=None) -> None:
|
| 258 |
+
"""
|
| 259 |
+
Register the input list of execution providers. The underlying session is re-created.
|
| 260 |
+
|
| 261 |
+
:param providers: Optional sequence of providers in order of decreasing
|
| 262 |
+
precedence. Values can either be provider names or tuples of
|
| 263 |
+
(provider name, options dict). If not provided, then all available
|
| 264 |
+
providers are used with the default precedence.
|
| 265 |
+
:param provider_options: Optional sequence of options dicts corresponding
|
| 266 |
+
to the providers listed in 'providers'.
|
| 267 |
+
|
| 268 |
+
'providers' can contain either names or names and options. When any options
|
| 269 |
+
are given in 'providers', 'provider_options' should not be used.
|
| 270 |
+
|
| 271 |
+
The list of providers is ordered by precedence. For example
|
| 272 |
+
`['CUDAExecutionProvider', 'CPUExecutionProvider']`
|
| 273 |
+
means execute a node using CUDAExecutionProvider if capable,
|
| 274 |
+
otherwise execute using CPUExecutionProvider.
|
| 275 |
+
"""
|
| 276 |
+
# recreate the underlying C.InferenceSession
|
| 277 |
+
self._reset_session(providers, provider_options)
|
| 278 |
+
|
| 279 |
+
def disable_fallback(self) -> None:
|
| 280 |
+
"""
|
| 281 |
+
Disable session.run() fallback mechanism.
|
| 282 |
+
"""
|
| 283 |
+
self._enable_fallback = False
|
| 284 |
+
|
| 285 |
+
def enable_fallback(self) -> None:
|
| 286 |
+
"""
|
| 287 |
+
Enable session.Run() fallback mechanism. If session.Run() fails due to an internal Execution Provider failure,
|
| 288 |
+
reset the Execution Providers enabled for this session.
|
| 289 |
+
If GPU is enabled, fall back to CUDAExecutionProvider.
|
| 290 |
+
otherwise fall back to CPUExecutionProvider.
|
| 291 |
+
"""
|
| 292 |
+
self._enable_fallback = True
|
| 293 |
+
|
| 294 |
+
def _validate_input(self, feed_input_names):
|
| 295 |
+
missing_input_names = []
|
| 296 |
+
for input in self._inputs_meta:
|
| 297 |
+
if input.name not in feed_input_names and not input.type.startswith("optional"):
|
| 298 |
+
missing_input_names.append(input.name)
|
| 299 |
+
if missing_input_names:
|
| 300 |
+
raise ValueError(
|
| 301 |
+
f"Required inputs ({missing_input_names}) are missing from input feed ({feed_input_names})."
|
| 302 |
+
)
|
| 303 |
+
|
| 304 |
+
def run(self, output_names, input_feed, run_options=None) -> Sequence[np.ndarray | SparseTensor | list | dict]:
|
| 305 |
+
"""
|
| 306 |
+
Compute the predictions.
|
| 307 |
+
|
| 308 |
+
:param output_names: name of the outputs
|
| 309 |
+
:param input_feed: dictionary ``{ input_name: input_value }``
|
| 310 |
+
:param run_options: See :class:`onnxruntime.RunOptions`.
|
| 311 |
+
:return: list of results, every result is either a numpy array,
|
| 312 |
+
a sparse tensor, a list or a dictionary.
|
| 313 |
+
|
| 314 |
+
::
|
| 315 |
+
|
| 316 |
+
sess.run([output_name], {input_name: x})
|
| 317 |
+
"""
|
| 318 |
+
self._validate_input(list(input_feed.keys()))
|
| 319 |
+
if not output_names:
|
| 320 |
+
output_names = [output.name for output in self._outputs_meta]
|
| 321 |
+
try:
|
| 322 |
+
return self._sess.run(output_names, input_feed, run_options)
|
| 323 |
+
except C.EPFail as err:
|
| 324 |
+
if self._enable_fallback:
|
| 325 |
+
print(f"EP Error: {err!s} using {self._providers}")
|
| 326 |
+
print(f"Falling back to {self._fallback_providers} and retrying.")
|
| 327 |
+
self.set_providers(self._fallback_providers)
|
| 328 |
+
# Fallback only once.
|
| 329 |
+
self.disable_fallback()
|
| 330 |
+
return self._sess.run(output_names, input_feed, run_options)
|
| 331 |
+
raise
|
| 332 |
+
|
| 333 |
+
def run_async(self, output_names, input_feed, callback, user_data, run_options=None):
|
| 334 |
+
"""
|
| 335 |
+
Compute the predictions asynchronously in a separate cxx thread from ort intra-op threadpool.
|
| 336 |
+
|
| 337 |
+
:param output_names: name of the outputs
|
| 338 |
+
:param input_feed: dictionary ``{ input_name: input_value }``
|
| 339 |
+
:param callback: python function that accept array of results, and a status string on error.
|
| 340 |
+
The callback will be invoked by a cxx thread from ort intra-op threadpool.
|
| 341 |
+
:param run_options: See :class:`onnxruntime.RunOptions`.
|
| 342 |
+
|
| 343 |
+
::
|
| 344 |
+
class MyData:
|
| 345 |
+
def __init__(self):
|
| 346 |
+
# ...
|
| 347 |
+
def save_results(self, results):
|
| 348 |
+
# ...
|
| 349 |
+
|
| 350 |
+
def callback(results: np.ndarray, user_data: MyData, err: str) -> None:
|
| 351 |
+
if err:
|
| 352 |
+
print (err)
|
| 353 |
+
else:
|
| 354 |
+
# save results to user_data
|
| 355 |
+
|
| 356 |
+
sess.run_async([output_name], {input_name: x}, callback)
|
| 357 |
+
"""
|
| 358 |
+
self._validate_input(list(input_feed.keys()))
|
| 359 |
+
if not output_names:
|
| 360 |
+
output_names = [output.name for output in self._outputs_meta]
|
| 361 |
+
return self._sess.run_async(output_names, input_feed, callback, user_data, run_options)
|
| 362 |
+
|
| 363 |
+
def run_with_ort_values(self, output_names, input_dict_ort_values, run_options=None) -> Sequence[OrtValue]:
|
| 364 |
+
"""
|
| 365 |
+
Compute the predictions.
|
| 366 |
+
|
| 367 |
+
:param output_names: name of the outputs
|
| 368 |
+
:param input_dict_ort_values: dictionary ``{ input_name: input_ort_value }``
|
| 369 |
+
See ``OrtValue`` class how to create `OrtValue`
|
| 370 |
+
from numpy array or `SparseTensor`
|
| 371 |
+
:param run_options: See :class:`onnxruntime.RunOptions`.
|
| 372 |
+
:return: an array of `OrtValue`
|
| 373 |
+
|
| 374 |
+
::
|
| 375 |
+
|
| 376 |
+
sess.run([output_name], {input_name: x})
|
| 377 |
+
"""
|
| 378 |
+
|
| 379 |
+
def invoke(sess, output_names, input_dict_ort_values, run_options):
|
| 380 |
+
input_dict = {}
|
| 381 |
+
for n, v in input_dict_ort_values.items():
|
| 382 |
+
input_dict[n] = v._get_c_value()
|
| 383 |
+
result = sess.run_with_ort_values(input_dict, output_names, run_options)
|
| 384 |
+
if not isinstance(result, C.OrtValueVector):
|
| 385 |
+
raise TypeError("run_with_ort_values() must return a instance of type 'OrtValueVector'.")
|
| 386 |
+
ort_values = [OrtValue(v) for v in result]
|
| 387 |
+
return ort_values
|
| 388 |
+
|
| 389 |
+
self._validate_input(list(input_dict_ort_values.keys()))
|
| 390 |
+
if not output_names:
|
| 391 |
+
output_names = [output.name for output in self._outputs_meta]
|
| 392 |
+
try:
|
| 393 |
+
return invoke(self._sess, output_names, input_dict_ort_values, run_options)
|
| 394 |
+
except C.EPFail as err:
|
| 395 |
+
if self._enable_fallback:
|
| 396 |
+
print(f"EP Error: {err!s} using {self._providers}")
|
| 397 |
+
print(f"Falling back to {self._fallback_providers} and retrying.")
|
| 398 |
+
self.set_providers(self._fallback_providers)
|
| 399 |
+
# Fallback only once.
|
| 400 |
+
self.disable_fallback()
|
| 401 |
+
return invoke(self._sess, output_names, input_dict_ort_values, run_options)
|
| 402 |
+
raise
|
| 403 |
+
|
| 404 |
+
def end_profiling(self):
|
| 405 |
+
"""
|
| 406 |
+
End profiling and return results in a file.
|
| 407 |
+
|
| 408 |
+
The results are stored in a filename if the option
|
| 409 |
+
:meth:`onnxruntime.SessionOptions.enable_profiling`.
|
| 410 |
+
"""
|
| 411 |
+
return self._sess.end_profiling()
|
| 412 |
+
|
| 413 |
+
def get_profiling_start_time_ns(self):
|
| 414 |
+
"""
|
| 415 |
+
Return the nanoseconds of profiling's start time
|
| 416 |
+
Comparable to time.monotonic_ns() after Python 3.3
|
| 417 |
+
On some platforms, this timer may not be as precise as nanoseconds
|
| 418 |
+
For instance, on Windows and MacOS, the precision will be ~100ns
|
| 419 |
+
"""
|
| 420 |
+
return self._sess.get_profiling_start_time_ns
|
| 421 |
+
|
| 422 |
+
def io_binding(self) -> IOBinding:
|
| 423 |
+
"Return an onnxruntime.IOBinding object`."
|
| 424 |
+
return IOBinding(self)
|
| 425 |
+
|
| 426 |
+
def run_with_iobinding(self, iobinding, run_options=None):
|
| 427 |
+
"""
|
| 428 |
+
Compute the predictions.
|
| 429 |
+
|
| 430 |
+
:param iobinding: the iobinding object that has graph inputs/outputs bind.
|
| 431 |
+
:param run_options: See :class:`onnxruntime.RunOptions`.
|
| 432 |
+
"""
|
| 433 |
+
self._sess.run_with_iobinding(iobinding._iobinding, run_options)
|
| 434 |
+
|
| 435 |
+
def set_ep_dynamic_options(self, options: dict[str, str]):
|
| 436 |
+
"""
|
| 437 |
+
Set dynamic options for execution providers.
|
| 438 |
+
|
| 439 |
+
:param options: Dictionary of key-value pairs where both keys and values are strings.
|
| 440 |
+
These options will be passed to the execution providers to modify
|
| 441 |
+
their runtime behavior.
|
| 442 |
+
"""
|
| 443 |
+
self._sess.set_ep_dynamic_options(options)
|
| 444 |
+
|
| 445 |
+
def get_tuning_results(self):
|
| 446 |
+
return self._sess.get_tuning_results()
|
| 447 |
+
|
| 448 |
+
def set_tuning_results(self, results, *, error_on_invalid=False):
|
| 449 |
+
return self._sess.set_tuning_results(results, error_on_invalid)
|
| 450 |
+
|
| 451 |
+
def run_with_ortvaluevector(self, run_options, feed_names, feeds, fetch_names, fetches, fetch_devices):
|
| 452 |
+
"""
|
| 453 |
+
Compute the predictions similar to other run_*() methods but with minimal C++/Python conversion overhead.
|
| 454 |
+
|
| 455 |
+
:param run_options: See :class:`onnxruntime.RunOptions`.
|
| 456 |
+
:param feed_names: list of input names.
|
| 457 |
+
:param feeds: list of input OrtValue.
|
| 458 |
+
:param fetch_names: list of output names.
|
| 459 |
+
:param fetches: list of output OrtValue.
|
| 460 |
+
:param fetch_devices: list of output devices.
|
| 461 |
+
"""
|
| 462 |
+
self._sess.run_with_ortvaluevector(run_options, feed_names, feeds, fetch_names, fetches, fetch_devices)
|
| 463 |
+
|
| 464 |
+
|
| 465 |
+
class InferenceSession(Session):
|
| 466 |
+
"""
|
| 467 |
+
This is the main class used to run a model.
|
| 468 |
+
"""
|
| 469 |
+
|
| 470 |
+
def __init__(
|
| 471 |
+
self,
|
| 472 |
+
path_or_bytes: str | bytes | os.PathLike,
|
| 473 |
+
sess_options: onnxruntime.SessionOptions | None = None,
|
| 474 |
+
providers: Sequence[str | tuple[str, dict[Any, Any]]] | None = None,
|
| 475 |
+
provider_options: Sequence[dict[Any, Any]] | None = None,
|
| 476 |
+
**kwargs,
|
| 477 |
+
) -> None:
|
| 478 |
+
"""
|
| 479 |
+
:param path_or_bytes: Filename or serialized ONNX or ORT format model in a byte string.
|
| 480 |
+
:param sess_options: Session options.
|
| 481 |
+
:param providers: Optional sequence of providers in order of decreasing
|
| 482 |
+
precedence. Values can either be provider names or tuples of
|
| 483 |
+
(provider name, options dict). If not provided, then all available
|
| 484 |
+
providers are used with the default precedence.
|
| 485 |
+
:param provider_options: Optional sequence of options dicts corresponding
|
| 486 |
+
to the providers listed in 'providers'.
|
| 487 |
+
|
| 488 |
+
The model type will be inferred unless explicitly set in the SessionOptions.
|
| 489 |
+
To explicitly set:
|
| 490 |
+
|
| 491 |
+
::
|
| 492 |
+
|
| 493 |
+
so = onnxruntime.SessionOptions()
|
| 494 |
+
# so.add_session_config_entry('session.load_model_format', 'ONNX') or
|
| 495 |
+
so.add_session_config_entry('session.load_model_format', 'ORT')
|
| 496 |
+
|
| 497 |
+
A file extension of '.ort' will be inferred as an ORT format model.
|
| 498 |
+
All other filenames are assumed to be ONNX format models.
|
| 499 |
+
|
| 500 |
+
'providers' can contain either names or names and options. When any options
|
| 501 |
+
are given in 'providers', 'provider_options' should not be used.
|
| 502 |
+
|
| 503 |
+
The list of providers is ordered by precedence. For example
|
| 504 |
+
`['CUDAExecutionProvider', 'CPUExecutionProvider']`
|
| 505 |
+
means execute a node using `CUDAExecutionProvider`
|
| 506 |
+
if capable, otherwise execute using `CPUExecutionProvider`.
|
| 507 |
+
"""
|
| 508 |
+
super().__init__(enable_fallback=int(kwargs.get("enable_fallback", 1)) == 1)
|
| 509 |
+
|
| 510 |
+
if isinstance(path_or_bytes, (str, os.PathLike)):
|
| 511 |
+
self._model_path = os.fspath(path_or_bytes)
|
| 512 |
+
self._model_bytes = None
|
| 513 |
+
elif isinstance(path_or_bytes, bytes):
|
| 514 |
+
self._model_path = None
|
| 515 |
+
self._model_bytes = path_or_bytes # TODO: This is bad as we're holding the memory indefinitely
|
| 516 |
+
else:
|
| 517 |
+
raise TypeError(f"Unable to load from type '{type(path_or_bytes)}'")
|
| 518 |
+
|
| 519 |
+
self._sess_options = sess_options
|
| 520 |
+
self._sess_options_initial = sess_options
|
| 521 |
+
if "read_config_from_model" in kwargs:
|
| 522 |
+
self._read_config_from_model = int(kwargs["read_config_from_model"]) == 1
|
| 523 |
+
else:
|
| 524 |
+
self._read_config_from_model = os.environ.get("ORT_LOAD_CONFIG_FROM_MODEL") == "1"
|
| 525 |
+
|
| 526 |
+
# internal parameters that we don't expect to be used in general so aren't documented
|
| 527 |
+
disabled_optimizers = kwargs.get("disabled_optimizers")
|
| 528 |
+
|
| 529 |
+
try:
|
| 530 |
+
self._create_inference_session(providers, provider_options, disabled_optimizers)
|
| 531 |
+
except (ValueError, RuntimeError) as e:
|
| 532 |
+
if self._enable_fallback:
|
| 533 |
+
try:
|
| 534 |
+
print("*************** EP Error ***************")
|
| 535 |
+
print(f"EP Error {e} when using {providers}")
|
| 536 |
+
print(f"Falling back to {self._fallback_providers} and retrying.")
|
| 537 |
+
print("****************************************")
|
| 538 |
+
self._create_inference_session(self._fallback_providers, None)
|
| 539 |
+
# Fallback only once.
|
| 540 |
+
self.disable_fallback()
|
| 541 |
+
return
|
| 542 |
+
except Exception as fallback_error:
|
| 543 |
+
raise fallback_error from e
|
| 544 |
+
# Fallback is disabled. Raise the original error.
|
| 545 |
+
raise e
|
| 546 |
+
|
| 547 |
+
def _create_inference_session(self, providers, provider_options, disabled_optimizers=None):
|
| 548 |
+
available_providers = C.get_available_providers()
|
| 549 |
+
|
| 550 |
+
# Validate that TensorrtExecutionProvider and NvTensorRTRTXExecutionProvider are not both specified
|
| 551 |
+
if providers:
|
| 552 |
+
has_tensorrt = any(
|
| 553 |
+
provider == "TensorrtExecutionProvider"
|
| 554 |
+
or (isinstance(provider, tuple) and provider[0] == "TensorrtExecutionProvider")
|
| 555 |
+
for provider in providers
|
| 556 |
+
)
|
| 557 |
+
has_tensorrt_rtx = any(
|
| 558 |
+
provider == "NvTensorRTRTXExecutionProvider"
|
| 559 |
+
or (isinstance(provider, tuple) and provider[0] == "NvTensorRTRTXExecutionProvider")
|
| 560 |
+
for provider in providers
|
| 561 |
+
)
|
| 562 |
+
if has_tensorrt and has_tensorrt_rtx:
|
| 563 |
+
raise ValueError(
|
| 564 |
+
"Cannot enable both 'TensorrtExecutionProvider' and 'NvTensorRTRTXExecutionProvider' "
|
| 565 |
+
"in the same session."
|
| 566 |
+
)
|
| 567 |
+
# Tensorrt and TensorRT RTX can fall back to CUDA if it's explicitly assigned. All others fall back to CPU.
|
| 568 |
+
if "NvTensorRTRTXExecutionProvider" in available_providers:
|
| 569 |
+
if (
|
| 570 |
+
providers
|
| 571 |
+
and any(
|
| 572 |
+
provider == "CUDAExecutionProvider"
|
| 573 |
+
or (isinstance(provider, tuple) and provider[0] == "CUDAExecutionProvider")
|
| 574 |
+
for provider in providers
|
| 575 |
+
)
|
| 576 |
+
and any(
|
| 577 |
+
provider == "NvTensorRTRTXExecutionProvider"
|
| 578 |
+
or (isinstance(provider, tuple) and provider[0] == "NvTensorRTRTXExecutionProvider")
|
| 579 |
+
for provider in providers
|
| 580 |
+
)
|
| 581 |
+
):
|
| 582 |
+
self._fallback_providers = ["CUDAExecutionProvider", "CPUExecutionProvider"]
|
| 583 |
+
else:
|
| 584 |
+
self._fallback_providers = ["CPUExecutionProvider"]
|
| 585 |
+
elif "TensorrtExecutionProvider" in available_providers:
|
| 586 |
+
if (
|
| 587 |
+
providers
|
| 588 |
+
and any(
|
| 589 |
+
provider == "CUDAExecutionProvider"
|
| 590 |
+
or (isinstance(provider, tuple) and provider[0] == "CUDAExecutionProvider")
|
| 591 |
+
for provider in providers
|
| 592 |
+
)
|
| 593 |
+
and any(
|
| 594 |
+
provider == "TensorrtExecutionProvider"
|
| 595 |
+
or (isinstance(provider, tuple) and provider[0] == "TensorrtExecutionProvider")
|
| 596 |
+
for provider in providers
|
| 597 |
+
)
|
| 598 |
+
):
|
| 599 |
+
self._fallback_providers = ["CUDAExecutionProvider", "CPUExecutionProvider"]
|
| 600 |
+
else:
|
| 601 |
+
self._fallback_providers = ["CPUExecutionProvider"]
|
| 602 |
+
else:
|
| 603 |
+
self._fallback_providers = ["CPUExecutionProvider"]
|
| 604 |
+
|
| 605 |
+
# validate providers and provider_options before other initialization
|
| 606 |
+
providers, provider_options = check_and_normalize_provider_args(
|
| 607 |
+
providers, provider_options, available_providers
|
| 608 |
+
)
|
| 609 |
+
|
| 610 |
+
# Print a warning if user passed providers to InferenceSession() but the SessionOptions instance
|
| 611 |
+
# already has provider information (e.g., via add_provider_for_devices()). The providers specified
|
| 612 |
+
# here will take precedence.
|
| 613 |
+
if self._sess_options is not None and (providers or provider_options) and self._sess_options.has_providers():
|
| 614 |
+
warnings.warn(
|
| 615 |
+
"Specified 'providers'/'provider_options' when creating InferenceSession but SessionOptions has "
|
| 616 |
+
"already been configured with providers. InferenceSession will only use the providers "
|
| 617 |
+
"passed to InferenceSession()."
|
| 618 |
+
)
|
| 619 |
+
|
| 620 |
+
session_options = self._sess_options if self._sess_options else C.get_default_session_options()
|
| 621 |
+
|
| 622 |
+
self._register_ep_custom_ops(session_options, providers, provider_options, available_providers)
|
| 623 |
+
|
| 624 |
+
if self._model_path:
|
| 625 |
+
sess = C.InferenceSession(session_options, self._model_path, True, self._read_config_from_model)
|
| 626 |
+
else:
|
| 627 |
+
sess = C.InferenceSession(session_options, self._model_bytes, False, self._read_config_from_model)
|
| 628 |
+
|
| 629 |
+
if disabled_optimizers is None:
|
| 630 |
+
disabled_optimizers = set()
|
| 631 |
+
elif not isinstance(disabled_optimizers, set):
|
| 632 |
+
# convert to set. assumes iterable
|
| 633 |
+
disabled_optimizers = set(disabled_optimizers)
|
| 634 |
+
|
| 635 |
+
# initialize the C++ InferenceSession
|
| 636 |
+
sess.initialize_session(providers, provider_options, disabled_optimizers)
|
| 637 |
+
|
| 638 |
+
self._sess = sess
|
| 639 |
+
self._sess_options = self._sess.session_options
|
| 640 |
+
self._inputs_meta = self._sess.inputs_meta
|
| 641 |
+
self._outputs_meta = self._sess.outputs_meta
|
| 642 |
+
self._overridable_initializers = self._sess.overridable_initializers
|
| 643 |
+
self._input_meminfos = self._sess.input_meminfos
|
| 644 |
+
self._output_meminfos = self._sess.output_meminfos
|
| 645 |
+
self._input_epdevices = self._sess.input_epdevices
|
| 646 |
+
self._model_meta = self._sess.model_meta
|
| 647 |
+
self._providers = self._sess.get_providers()
|
| 648 |
+
self._provider_options = self._sess.get_provider_options()
|
| 649 |
+
self._profiling_start_time_ns = self._sess.get_profiling_start_time_ns
|
| 650 |
+
|
| 651 |
+
def _reset_session(self, providers, provider_options) -> None:
|
| 652 |
+
"release underlying session object."
|
| 653 |
+
# meta data references session internal structures
|
| 654 |
+
# so they must be set to None to decrement _sess reference count.
|
| 655 |
+
self._sess_options = None
|
| 656 |
+
self._inputs_meta = None
|
| 657 |
+
self._outputs_meta = None
|
| 658 |
+
self._overridable_initializers = None
|
| 659 |
+
self._input_meminfos = None
|
| 660 |
+
self._output_meminfos = None
|
| 661 |
+
self._input_epdevices = None
|
| 662 |
+
self._model_meta = None
|
| 663 |
+
self._providers = None
|
| 664 |
+
self._provider_options = None
|
| 665 |
+
self._profiling_start_time_ns = None
|
| 666 |
+
|
| 667 |
+
# create a new C.InferenceSession
|
| 668 |
+
self._sess = None
|
| 669 |
+
self._sess_options = self._sess_options_initial
|
| 670 |
+
self._create_inference_session(providers, provider_options)
|
| 671 |
+
|
| 672 |
+
def _register_ep_custom_ops(self, session_options, providers, provider_options, available_providers):
|
| 673 |
+
for i in range(len(providers)):
|
| 674 |
+
if providers[i] in available_providers and providers[i] == "TensorrtExecutionProvider":
|
| 675 |
+
C.register_tensorrt_plugins_as_custom_ops(session_options, provider_options[i])
|
| 676 |
+
elif (
|
| 677 |
+
isinstance(providers[i], tuple)
|
| 678 |
+
and providers[i][0] in available_providers
|
| 679 |
+
and providers[i][0] == "TensorrtExecutionProvider"
|
| 680 |
+
):
|
| 681 |
+
C.register_tensorrt_plugins_as_custom_ops(session_options, providers[i][1])
|
| 682 |
+
|
| 683 |
+
if providers[i] in available_providers and providers[i] == "NvTensorRTRTXExecutionProvider":
|
| 684 |
+
C.register_nv_tensorrt_rtx_plugins_as_custom_ops(session_options, provider_options[i])
|
| 685 |
+
elif (
|
| 686 |
+
isinstance(providers[i], tuple)
|
| 687 |
+
and providers[i][0] in available_providers
|
| 688 |
+
and providers[i][0] == "NvTensorrtRTXExecutionProvider"
|
| 689 |
+
):
|
| 690 |
+
C.register_nv_tensorrt_rtx_plugins_as_custom_ops(session_options, providers[i][1])
|
| 691 |
+
|
| 692 |
+
|
| 693 |
+
def make_get_initializer_location_func_wrapper(
|
| 694 |
+
get_initializer_location_func: GetInitializerLocationFunc,
|
| 695 |
+
) -> GetInitializerLocationWrapperFunc:
|
| 696 |
+
"""
|
| 697 |
+
Wraps a user's "get initializer location" function. The returned wrapper function adheres to the
|
| 698 |
+
signature expected by ORT.
|
| 699 |
+
|
| 700 |
+
Need this wrapper to:
|
| 701 |
+
- Convert the `initializer_value` parameter from `C.OrtValue` to `onnxruntime.OrtValue`, which is more
|
| 702 |
+
convenient for the user's function to use.
|
| 703 |
+
- Allow the user's function to return the original `external_info` parameter (this wrapper makes a copy)
|
| 704 |
+
"""
|
| 705 |
+
|
| 706 |
+
def get_initializer_location_func_wrapper(
|
| 707 |
+
initializer_name: str,
|
| 708 |
+
initializer_value: C.OrtValue,
|
| 709 |
+
external_info: C.OrtExternalInitializerInfo | None,
|
| 710 |
+
) -> C.OrtExternalInitializerInfo | None:
|
| 711 |
+
ret_val: C.OrtExternalInitializerInfo | None = get_initializer_location_func(
|
| 712 |
+
initializer_name, OrtValue(initializer_value), external_info
|
| 713 |
+
)
|
| 714 |
+
if ret_val is not None and ret_val == external_info:
|
| 715 |
+
# User returned `external_info` (const and owned by ORT). ORT expects the returned value to be
|
| 716 |
+
# a new instance (that it deletes), so make a copy.
|
| 717 |
+
ret_val = C.OrtExternalInitializerInfo(ret_val.filepath, ret_val.file_offset, ret_val.byte_size)
|
| 718 |
+
return ret_val
|
| 719 |
+
|
| 720 |
+
return get_initializer_location_func_wrapper
|
| 721 |
+
|
| 722 |
+
|
| 723 |
+
class ModelCompiler:
|
| 724 |
+
"""
|
| 725 |
+
This class is used to compile an ONNX model. A compiled ONNX model has EPContext nodes that each
|
| 726 |
+
encapsulates a subgraph compiled/optimized for a specific execution provider.
|
| 727 |
+
|
| 728 |
+
Refer to the EPContext design document for more information about EPContext models:
|
| 729 |
+
https://onnxruntime.ai/docs/execution-providers/EP-Context-Design.html
|
| 730 |
+
|
| 731 |
+
::
|
| 732 |
+
|
| 733 |
+
sess_options = onnxruntime.SessionOptions()
|
| 734 |
+
sess_options.add_provider("SomeExecutionProvider", {"option1": "value1"})
|
| 735 |
+
# Alternatively, allow ONNX Runtime to select the provider automatically given a policy:
|
| 736 |
+
# sess_options.set_provider_selection_policy(onnxrt.OrtExecutionProviderDevicePolicy.PREFER_NPU)
|
| 737 |
+
|
| 738 |
+
model_compiler = onnxruntime.ModelCompiler(sess_options, "input_model.onnx")
|
| 739 |
+
model_compiler.compile_to_file("output_model.onnx")
|
| 740 |
+
"""
|
| 741 |
+
|
| 742 |
+
def __init__(
|
| 743 |
+
self,
|
| 744 |
+
sess_options: onnxruntime.SessionOptions,
|
| 745 |
+
input_model_path_or_bytes: str | os.PathLike | bytes,
|
| 746 |
+
embed_compiled_data_into_model: bool = False,
|
| 747 |
+
external_initializers_file_path: str | os.PathLike | None = None,
|
| 748 |
+
external_initializers_size_threshold: int = 1024,
|
| 749 |
+
flags: int = C.OrtCompileApiFlags.NONE,
|
| 750 |
+
graph_optimization_level: C.GraphOptimizationLevel = C.GraphOptimizationLevel.ORT_DISABLE_ALL,
|
| 751 |
+
get_initializer_location_func: GetInitializerLocationFunc | None = None,
|
| 752 |
+
):
|
| 753 |
+
"""
|
| 754 |
+
Creates a ModelCompiler instance.
|
| 755 |
+
|
| 756 |
+
:param sess_options: Session options containing the providers for which the model will be compiled.
|
| 757 |
+
Refer to SessionOptions.add_provider() and SessionOptions.set_provider_selection_policy().
|
| 758 |
+
:param input_model_path_or_bytes: The path to the input model file or bytes representing a serialized
|
| 759 |
+
ONNX model.
|
| 760 |
+
:param embed_compiled_data_into_model: Defaults to False. Set to True to embed compiled binary data into
|
| 761 |
+
EPContext nodes in the compiled model.
|
| 762 |
+
:param external_initializers_file_path: Defaults to None. Set to a path for a file that will store the
|
| 763 |
+
initializers for non-compiled nodes.
|
| 764 |
+
:param external_initializers_size_threshold: Defaults to 1024. Ignored if `external_initializers_file_path`
|
| 765 |
+
is None or empty. Initializers larger than this threshold are stored in the external initializers file.
|
| 766 |
+
:param flags: Additional boolean options to enable. Set this parameter to a bitwise OR of
|
| 767 |
+
flags in onnxruntime.OrtCompileApiFlags.
|
| 768 |
+
:param graph_optimization_level: The graph optimization level.
|
| 769 |
+
Defaults to onnxruntime.GraphOptimizationLevel.ORT_DISABLE_ALL.
|
| 770 |
+
:param get_initializer_location_func: Optional function called for every initializer to allow user to specify
|
| 771 |
+
whether an initializer should be stored within the model or externally. Example:
|
| 772 |
+
```
|
| 773 |
+
def get_initializer_location(
|
| 774 |
+
initializer_name: str,
|
| 775 |
+
initializer_value: onnxrt.OrtValue,
|
| 776 |
+
external_info: onnxrt.OrtExternalInitializerInfo | None,
|
| 777 |
+
) -> onnxrt.OrtExternalInitializerInfo | None:
|
| 778 |
+
byte_size = initializer_value.tensor_size_in_bytes()
|
| 779 |
+
|
| 780 |
+
if byte_size < 64:
|
| 781 |
+
return None # Store small initializer within compiled model.
|
| 782 |
+
|
| 783 |
+
# Else, write initializer to new external file.
|
| 784 |
+
value_np = initializer_value.numpy()
|
| 785 |
+
file_offset = ext_init_file.tell()
|
| 786 |
+
ext_init_file.write(value_np.tobytes())
|
| 787 |
+
return onnxrt.OrtExternalInitializerInfo(initializer_file_path, file_offset, byte_size)
|
| 788 |
+
```
|
| 789 |
+
"""
|
| 790 |
+
input_model_path: str | os.PathLike | None = None
|
| 791 |
+
input_model_bytes: bytes | None = None
|
| 792 |
+
if isinstance(input_model_path_or_bytes, (str, os.PathLike)):
|
| 793 |
+
if not input_model_path_or_bytes:
|
| 794 |
+
raise ValueError("Input model path is empty")
|
| 795 |
+
input_model_path = os.fspath(input_model_path_or_bytes)
|
| 796 |
+
elif isinstance(input_model_path_or_bytes, bytes):
|
| 797 |
+
if len(input_model_path_or_bytes) == 0:
|
| 798 |
+
raise ValueError("Input model bytes array is empty")
|
| 799 |
+
input_model_bytes = input_model_path_or_bytes
|
| 800 |
+
else:
|
| 801 |
+
raise TypeError(f"Unable to load from type '{type(input_model_path_or_bytes)}'")
|
| 802 |
+
|
| 803 |
+
if external_initializers_file_path:
|
| 804 |
+
if not isinstance(external_initializers_file_path, (str, os.PathLike)):
|
| 805 |
+
arg_type = type(external_initializers_file_path)
|
| 806 |
+
raise TypeError(f"Output external initializer filepath is of unexpected type '{arg_type}'")
|
| 807 |
+
external_initializers_file_path = os.fspath(external_initializers_file_path)
|
| 808 |
+
else:
|
| 809 |
+
external_initializers_file_path = ""
|
| 810 |
+
|
| 811 |
+
if get_initializer_location_func is not None:
|
| 812 |
+
if external_initializers_file_path:
|
| 813 |
+
raise ValueError(
|
| 814 |
+
"Cannot initialize ModelCompiler with both `external_initializers_file_path` "
|
| 815 |
+
"and `get_initializer_location_func`"
|
| 816 |
+
)
|
| 817 |
+
self.get_initializer_location_func_wrapper = make_get_initializer_location_func_wrapper(
|
| 818 |
+
get_initializer_location_func
|
| 819 |
+
)
|
| 820 |
+
else:
|
| 821 |
+
self.get_initializer_location_func_wrapper = None
|
| 822 |
+
|
| 823 |
+
if input_model_path:
|
| 824 |
+
self._model_compiler = C.ModelCompiler(
|
| 825 |
+
sess_options,
|
| 826 |
+
input_model_path,
|
| 827 |
+
True, # is path
|
| 828 |
+
embed_compiled_data_into_model,
|
| 829 |
+
external_initializers_file_path,
|
| 830 |
+
external_initializers_size_threshold,
|
| 831 |
+
flags,
|
| 832 |
+
graph_optimization_level,
|
| 833 |
+
self.get_initializer_location_func_wrapper,
|
| 834 |
+
)
|
| 835 |
+
else:
|
| 836 |
+
self._model_compiler = C.ModelCompiler(
|
| 837 |
+
sess_options,
|
| 838 |
+
input_model_bytes,
|
| 839 |
+
False, # is bytes
|
| 840 |
+
embed_compiled_data_into_model,
|
| 841 |
+
external_initializers_file_path,
|
| 842 |
+
external_initializers_size_threshold,
|
| 843 |
+
flags,
|
| 844 |
+
graph_optimization_level,
|
| 845 |
+
self.get_initializer_location_func_wrapper,
|
| 846 |
+
)
|
| 847 |
+
|
| 848 |
+
def compile_to_file(self, output_model_path: str | None = None):
|
| 849 |
+
"""
|
| 850 |
+
Compiles to an output file. If an output file path is not provided,
|
| 851 |
+
the output file path is generated based on the input model path by replacing
|
| 852 |
+
'.onnx' with '_ctx.onnx'. Ex: The generated output file is 'model_ctx.onnx' for
|
| 853 |
+
an input model with path 'model.onnx'.
|
| 854 |
+
|
| 855 |
+
Raises an 'InvalidArgument' exception if the compilation options are invalid.
|
| 856 |
+
|
| 857 |
+
:param output_model_path: Defaults to None. The path for the output/compiled model.
|
| 858 |
+
"""
|
| 859 |
+
if output_model_path:
|
| 860 |
+
if not isinstance(output_model_path, (str, os.PathLike)):
|
| 861 |
+
raise TypeError(f"Output model's filepath is of unexpected type '{type(output_model_path)}'")
|
| 862 |
+
output_model_path = os.fspath(output_model_path)
|
| 863 |
+
self._model_compiler.compile_to_file(output_model_path)
|
| 864 |
+
|
| 865 |
+
def compile_to_bytes(self) -> bytes:
|
| 866 |
+
"""
|
| 867 |
+
Compiles to bytes representing the serialized compiled ONNX model.
|
| 868 |
+
|
| 869 |
+
Raises an 'InvalidArgument' exception if the compilation options are invalid.
|
| 870 |
+
|
| 871 |
+
:return: A bytes object representing the compiled ONNX model.
|
| 872 |
+
"""
|
| 873 |
+
return self._model_compiler.compile_to_bytes()
|
| 874 |
+
|
| 875 |
+
def compile_to_stream(self, write_function: Callable[[bytes], None]):
|
| 876 |
+
"""
|
| 877 |
+
Compiles the input model and writes the serialized ONNX bytes to a stream using the provided write function.
|
| 878 |
+
Raises an 'InvalidArgument' exception if the compilation options are invalid.
|
| 879 |
+
:param write_function: A callable that accepts a bytes buffer to write.
|
| 880 |
+
"""
|
| 881 |
+
self._model_compiler.compile_to_stream(write_function)
|
| 882 |
+
|
| 883 |
+
|
| 884 |
+
class IOBinding:
|
| 885 |
+
"""
|
| 886 |
+
This class provides API to bind input/output to a specified device, e.g. GPU.
|
| 887 |
+
"""
|
| 888 |
+
|
| 889 |
+
def __init__(self, session: Session):
|
| 890 |
+
self._iobinding = C.SessionIOBinding(session._sess)
|
| 891 |
+
self._numpy_obj_references = {}
|
| 892 |
+
|
| 893 |
+
def bind_cpu_input(self, name, arr_on_cpu):
|
| 894 |
+
"""
|
| 895 |
+
bind an input to array on CPU
|
| 896 |
+
:param name: input name
|
| 897 |
+
:param arr_on_cpu: input values as a python array on CPU
|
| 898 |
+
"""
|
| 899 |
+
# Hold a reference to the numpy object as the bound OrtValue is backed
|
| 900 |
+
# directly by the data buffer of the numpy object and so the numpy object
|
| 901 |
+
# must be around until this IOBinding instance is around
|
| 902 |
+
self._numpy_obj_references[name] = arr_on_cpu
|
| 903 |
+
self._iobinding.bind_input(name, arr_on_cpu)
|
| 904 |
+
|
| 905 |
+
def bind_input(self, name, device_type, device_id, element_type, shape, buffer_ptr):
|
| 906 |
+
"""
|
| 907 |
+
:param name: input name
|
| 908 |
+
:param device_type: e.g. cpu, cuda, cann
|
| 909 |
+
:param device_id: device id, e.g. 0
|
| 910 |
+
: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)
|
| 911 |
+
:param shape: input shape
|
| 912 |
+
:param buffer_ptr: memory pointer to input data
|
| 913 |
+
"""
|
| 914 |
+
self._iobinding.bind_input(
|
| 915 |
+
name,
|
| 916 |
+
C.OrtDevice(
|
| 917 |
+
get_ort_device_type(device_type),
|
| 918 |
+
C.OrtDevice.default_memory(),
|
| 919 |
+
device_id,
|
| 920 |
+
),
|
| 921 |
+
element_type,
|
| 922 |
+
shape,
|
| 923 |
+
buffer_ptr,
|
| 924 |
+
)
|
| 925 |
+
|
| 926 |
+
def bind_ortvalue_input(self, name, ortvalue):
|
| 927 |
+
"""
|
| 928 |
+
:param name: input name
|
| 929 |
+
:param ortvalue: OrtValue instance to bind
|
| 930 |
+
"""
|
| 931 |
+
self._iobinding.bind_ortvalue_input(name, ortvalue._ortvalue)
|
| 932 |
+
|
| 933 |
+
def synchronize_inputs(self):
|
| 934 |
+
self._iobinding.synchronize_inputs()
|
| 935 |
+
|
| 936 |
+
def bind_output(
|
| 937 |
+
self,
|
| 938 |
+
name,
|
| 939 |
+
device_type="cpu",
|
| 940 |
+
device_id=0,
|
| 941 |
+
element_type=None,
|
| 942 |
+
shape=None,
|
| 943 |
+
buffer_ptr=None,
|
| 944 |
+
):
|
| 945 |
+
"""
|
| 946 |
+
:param name: output name
|
| 947 |
+
:param device_type: e.g. cpu, cuda, cann, cpu by default
|
| 948 |
+
:param device_id: device id, e.g. 0
|
| 949 |
+
: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)
|
| 950 |
+
:param shape: output shape
|
| 951 |
+
:param buffer_ptr: memory pointer to output data
|
| 952 |
+
"""
|
| 953 |
+
|
| 954 |
+
# Follow the `if` path when the user has not provided any pre-allocated buffer but still
|
| 955 |
+
# would like to bind an output to a specific device (e.g. cuda).
|
| 956 |
+
# Pre-allocating an output buffer may not be an option for the user as :
|
| 957 |
+
# (1) They may not want to use a custom allocator specific to the device they want to bind the output to,
|
| 958 |
+
# in which case ORT will allocate the memory for the user
|
| 959 |
+
# (2) The output has a dynamic shape and hence the size of the buffer may not be fixed across runs
|
| 960 |
+
if buffer_ptr is None:
|
| 961 |
+
self._iobinding.bind_output(
|
| 962 |
+
name,
|
| 963 |
+
C.OrtDevice(
|
| 964 |
+
get_ort_device_type(device_type),
|
| 965 |
+
C.OrtDevice.default_memory(),
|
| 966 |
+
device_id,
|
| 967 |
+
),
|
| 968 |
+
)
|
| 969 |
+
else:
|
| 970 |
+
if element_type is None or shape is None:
|
| 971 |
+
raise ValueError("`element_type` and `shape` are to be provided if pre-allocated memory is provided")
|
| 972 |
+
self._iobinding.bind_output(
|
| 973 |
+
name,
|
| 974 |
+
C.OrtDevice(
|
| 975 |
+
get_ort_device_type(device_type),
|
| 976 |
+
C.OrtDevice.default_memory(),
|
| 977 |
+
device_id,
|
| 978 |
+
),
|
| 979 |
+
element_type,
|
| 980 |
+
shape,
|
| 981 |
+
buffer_ptr,
|
| 982 |
+
)
|
| 983 |
+
|
| 984 |
+
def bind_ortvalue_output(self, name, ortvalue):
|
| 985 |
+
"""
|
| 986 |
+
:param name: output name
|
| 987 |
+
:param ortvalue: OrtValue instance to bind
|
| 988 |
+
"""
|
| 989 |
+
self._iobinding.bind_ortvalue_output(name, ortvalue._ortvalue)
|
| 990 |
+
|
| 991 |
+
def synchronize_outputs(self):
|
| 992 |
+
self._iobinding.synchronize_outputs()
|
| 993 |
+
|
| 994 |
+
def get_outputs(self):
|
| 995 |
+
"""
|
| 996 |
+
Returns the output OrtValues from the Run() that preceded the call.
|
| 997 |
+
The data buffer of the obtained OrtValues may not reside on CPU memory
|
| 998 |
+
"""
|
| 999 |
+
outputs = self._iobinding.get_outputs()
|
| 1000 |
+
if not isinstance(outputs, C.OrtValueVector):
|
| 1001 |
+
raise TypeError("get_outputs() must return an instance of type 'OrtValueVector'.")
|
| 1002 |
+
return [OrtValue(ortvalue) for ortvalue in outputs]
|
| 1003 |
+
|
| 1004 |
+
def get_outputs_as_ortvaluevector(self):
|
| 1005 |
+
return self._iobinding.get_outputs()
|
| 1006 |
+
|
| 1007 |
+
def copy_outputs_to_cpu(self):
|
| 1008 |
+
"""Copy output contents to CPU."""
|
| 1009 |
+
return self._iobinding.copy_outputs_to_cpu()
|
| 1010 |
+
|
| 1011 |
+
def clear_binding_inputs(self):
|
| 1012 |
+
self._iobinding.clear_binding_inputs()
|
| 1013 |
+
|
| 1014 |
+
def clear_binding_outputs(self):
|
| 1015 |
+
self._iobinding.clear_binding_outputs()
|
| 1016 |
+
|
| 1017 |
+
|
| 1018 |
+
class OrtValue:
|
| 1019 |
+
"""
|
| 1020 |
+
A data structure that supports all ONNX data formats (tensors and non-tensors) that allows users
|
| 1021 |
+
to place the data backing these on a device, for example, on a CUDA supported device.
|
| 1022 |
+
This class provides APIs to construct and deal with OrtValues.
|
| 1023 |
+
"""
|
| 1024 |
+
|
| 1025 |
+
def __init__(self, ortvalue: C.OrtValue, numpy_obj: np.ndarray | None = None):
|
| 1026 |
+
if isinstance(ortvalue, C.OrtValue):
|
| 1027 |
+
self._ortvalue = ortvalue
|
| 1028 |
+
# Hold a ref count to the numpy object if the OrtValue is backed directly
|
| 1029 |
+
# by its data buffer so that it isn't destroyed when the OrtValue is in use
|
| 1030 |
+
self._numpy_obj = numpy_obj
|
| 1031 |
+
else:
|
| 1032 |
+
# An end user won't hit this error
|
| 1033 |
+
raise ValueError(
|
| 1034 |
+
"`Provided ortvalue` needs to be of type `onnxruntime.capi.onnxruntime_pybind11_state.OrtValue`"
|
| 1035 |
+
)
|
| 1036 |
+
|
| 1037 |
+
def _get_c_value(self) -> C.OrtValue:
|
| 1038 |
+
return self._ortvalue
|
| 1039 |
+
|
| 1040 |
+
@classmethod
|
| 1041 |
+
def ortvalue_from_numpy(
|
| 1042 |
+
cls, numpy_obj: np.ndarray, /, device_type="cpu", device_id=0, vendor_id: int | OrtDeviceVendorId = -1
|
| 1043 |
+
) -> OrtValue:
|
| 1044 |
+
"""
|
| 1045 |
+
Factory method to construct an OrtValue (which holds a Tensor) from a given Numpy object
|
| 1046 |
+
A copy of the data in the Numpy object is held by the OrtValue only if the device is NOT cpu
|
| 1047 |
+
|
| 1048 |
+
:param numpy_obj: The Numpy object to construct the OrtValue from
|
| 1049 |
+
:param device_type: e.g. cpu, cuda, cann, cpu by default
|
| 1050 |
+
:param device_id: device id, e.g. 0
|
| 1051 |
+
:param vendor_id: The device's PCI vendor id as an int or OrtDeviceVendorId. If provided, the device_type should be "gpu" or "npu".
|
| 1052 |
+
"""
|
| 1053 |
+
# Hold a reference to the numpy object (if device_type is 'cpu') as the OrtValue
|
| 1054 |
+
# is backed directly by the data buffer of the numpy object and so the numpy object
|
| 1055 |
+
# must be around until this OrtValue instance is around
|
| 1056 |
+
return cls(
|
| 1057 |
+
C.OrtValue.ortvalue_from_numpy(
|
| 1058 |
+
numpy_obj,
|
| 1059 |
+
OrtDevice.make(device_type, device_id, vendor_id)._get_c_device(),
|
| 1060 |
+
),
|
| 1061 |
+
numpy_obj if device_type.lower() == "cpu" else None,
|
| 1062 |
+
)
|
| 1063 |
+
|
| 1064 |
+
@classmethod
|
| 1065 |
+
def ortvalue_from_numpy_with_onnx_type(cls, data: np.ndarray, /, onnx_element_type: int) -> OrtValue:
|
| 1066 |
+
"""
|
| 1067 |
+
This method creates an instance of OrtValue on top of the numpy array.
|
| 1068 |
+
No data copy is made and the lifespan of the resulting OrtValue should never
|
| 1069 |
+
exceed the lifespan of bytes object. The API attempts to reinterpret
|
| 1070 |
+
the data type which is expected to be the same size. This is useful
|
| 1071 |
+
when we want to use an ONNX data type that is not supported by numpy.
|
| 1072 |
+
|
| 1073 |
+
:param data: numpy.ndarray.
|
| 1074 |
+
:param onnx_element_type: a valid onnx TensorProto::DataType enum value
|
| 1075 |
+
"""
|
| 1076 |
+
return cls(C.OrtValue.ortvalue_from_numpy_with_onnx_type(data, onnx_element_type), data)
|
| 1077 |
+
|
| 1078 |
+
@classmethod
|
| 1079 |
+
def ortvalue_from_shape_and_type(
|
| 1080 |
+
cls,
|
| 1081 |
+
shape: Sequence[int],
|
| 1082 |
+
element_type,
|
| 1083 |
+
device_type: str = "cpu",
|
| 1084 |
+
device_id: int = 0,
|
| 1085 |
+
vendor_id: int | OrtDeviceVendorId = -1,
|
| 1086 |
+
) -> OrtValue:
|
| 1087 |
+
"""
|
| 1088 |
+
Factory method to construct an OrtValue (which holds a Tensor) from given shape and element_type
|
| 1089 |
+
|
| 1090 |
+
:param shape: List of integers indicating the shape of the OrtValue
|
| 1091 |
+
: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).
|
| 1092 |
+
:param device_type: e.g. cpu, cuda, cann, cpu by default
|
| 1093 |
+
:param device_id: device id, e.g. 0
|
| 1094 |
+
:param vendor_id: The device's PCI vendor id as an int or OrtDeviceVendorId. If provided, the device type should be "gpu" or "npu".
|
| 1095 |
+
"""
|
| 1096 |
+
|
| 1097 |
+
device = OrtDevice.make(device_type, device_id, vendor_id)._get_c_device()
|
| 1098 |
+
|
| 1099 |
+
# Integer for onnx element type (see https://onnx.ai/onnx/api/mapping.html).
|
| 1100 |
+
# This is helpful for some data type (like TensorProto.BFLOAT16) that is not available in numpy.
|
| 1101 |
+
if isinstance(element_type, int):
|
| 1102 |
+
return cls(
|
| 1103 |
+
C.OrtValue.ortvalue_from_shape_and_onnx_type(
|
| 1104 |
+
shape,
|
| 1105 |
+
element_type,
|
| 1106 |
+
device,
|
| 1107 |
+
)
|
| 1108 |
+
)
|
| 1109 |
+
|
| 1110 |
+
return cls(
|
| 1111 |
+
C.OrtValue.ortvalue_from_shape_and_type(
|
| 1112 |
+
shape,
|
| 1113 |
+
element_type,
|
| 1114 |
+
device,
|
| 1115 |
+
)
|
| 1116 |
+
)
|
| 1117 |
+
|
| 1118 |
+
@classmethod
|
| 1119 |
+
def ort_value_from_sparse_tensor(cls, sparse_tensor: SparseTensor) -> OrtValue:
|
| 1120 |
+
"""
|
| 1121 |
+
The function will construct an OrtValue instance from a valid SparseTensor
|
| 1122 |
+
The new instance of OrtValue will assume the ownership of sparse_tensor
|
| 1123 |
+
"""
|
| 1124 |
+
return cls(C.OrtValue.ort_value_from_sparse_tensor(sparse_tensor._get_c_tensor()))
|
| 1125 |
+
|
| 1126 |
+
def as_sparse_tensor(self) -> SparseTensor:
|
| 1127 |
+
"""
|
| 1128 |
+
The function will return SparseTensor contained in this OrtValue
|
| 1129 |
+
"""
|
| 1130 |
+
return SparseTensor(self._ortvalue.as_sparse_tensor())
|
| 1131 |
+
|
| 1132 |
+
def data_ptr(self) -> int:
|
| 1133 |
+
"""
|
| 1134 |
+
Returns the address of the first element in the OrtValue's data buffer
|
| 1135 |
+
"""
|
| 1136 |
+
return self._ortvalue.data_ptr()
|
| 1137 |
+
|
| 1138 |
+
def device_name(self) -> str:
|
| 1139 |
+
"""
|
| 1140 |
+
Returns the name of the device where the OrtValue's data buffer resides e.g. cpu, cuda, cann
|
| 1141 |
+
"""
|
| 1142 |
+
return self._ortvalue.device_name().lower()
|
| 1143 |
+
|
| 1144 |
+
def shape(self) -> Sequence[int]:
|
| 1145 |
+
"""
|
| 1146 |
+
Returns the shape of the data in the OrtValue
|
| 1147 |
+
"""
|
| 1148 |
+
return self._ortvalue.shape()
|
| 1149 |
+
|
| 1150 |
+
def data_type(self) -> str:
|
| 1151 |
+
"""
|
| 1152 |
+
Returns the data type of the data in the OrtValue. E.g. 'tensor(int64)'
|
| 1153 |
+
"""
|
| 1154 |
+
return self._ortvalue.data_type()
|
| 1155 |
+
|
| 1156 |
+
def element_type(self) -> int:
|
| 1157 |
+
"""
|
| 1158 |
+
Returns the proto type of the data in the OrtValue
|
| 1159 |
+
if the OrtValue is a tensor.
|
| 1160 |
+
"""
|
| 1161 |
+
return self._ortvalue.element_type()
|
| 1162 |
+
|
| 1163 |
+
def tensor_size_in_bytes(self) -> int:
|
| 1164 |
+
"""
|
| 1165 |
+
Returns the size of the data in the OrtValue in bytes
|
| 1166 |
+
if the OrtValue is a tensor.
|
| 1167 |
+
"""
|
| 1168 |
+
return self._ortvalue.tensor_size_in_bytes()
|
| 1169 |
+
|
| 1170 |
+
def has_value(self) -> bool:
|
| 1171 |
+
"""
|
| 1172 |
+
Returns True if the OrtValue corresponding to an
|
| 1173 |
+
optional type contains data, else returns False
|
| 1174 |
+
"""
|
| 1175 |
+
return self._ortvalue.has_value()
|
| 1176 |
+
|
| 1177 |
+
def is_tensor(self) -> bool:
|
| 1178 |
+
"""
|
| 1179 |
+
Returns True if the OrtValue contains a Tensor, else returns False
|
| 1180 |
+
"""
|
| 1181 |
+
return self._ortvalue.is_tensor()
|
| 1182 |
+
|
| 1183 |
+
def is_sparse_tensor(self) -> bool:
|
| 1184 |
+
"""
|
| 1185 |
+
Returns True if the OrtValue contains a SparseTensor, else returns False
|
| 1186 |
+
"""
|
| 1187 |
+
return self._ortvalue.is_sparse_tensor()
|
| 1188 |
+
|
| 1189 |
+
def is_tensor_sequence(self) -> bool:
|
| 1190 |
+
"""
|
| 1191 |
+
Returns True if the OrtValue contains a Tensor Sequence, else returns False
|
| 1192 |
+
"""
|
| 1193 |
+
return self._ortvalue.is_tensor_sequence()
|
| 1194 |
+
|
| 1195 |
+
def numpy(self) -> np.ndarray:
|
| 1196 |
+
"""
|
| 1197 |
+
Returns a Numpy object from the OrtValue.
|
| 1198 |
+
Valid only for OrtValues holding Tensors. Throws for OrtValues holding non-Tensors.
|
| 1199 |
+
Use accessors to gain a reference to non-Tensor objects such as SparseTensor
|
| 1200 |
+
"""
|
| 1201 |
+
return self._ortvalue.numpy()
|
| 1202 |
+
|
| 1203 |
+
def __array__(self, dtype=None, copy=None) -> np.ndarray:
|
| 1204 |
+
"""
|
| 1205 |
+
Supports ``numpy.asarray(ortvalue)`` and ``numpy.array(ortvalue)`` via the
|
| 1206 |
+
`numpy __array__ protocol <https://numpy.org/devdocs/user/basics.interoperability.html>`_.
|
| 1207 |
+
|
| 1208 |
+
Valid only for OrtValues holding Tensors on CPU.
|
| 1209 |
+
|
| 1210 |
+
:param dtype: Optional numpy dtype to cast the result to.
|
| 1211 |
+
:param copy: Optional bool (numpy >= 2.0). If ``False``, a copy will
|
| 1212 |
+
only be made if necessary. If ``True``, a copy is always forced.
|
| 1213 |
+
If ``None`` (default), a copy will be made only if needed.
|
| 1214 |
+
:return: A numpy array with the same data as the OrtValue.
|
| 1215 |
+
"""
|
| 1216 |
+
arr = self.numpy()
|
| 1217 |
+
|
| 1218 |
+
if copy is not None:
|
| 1219 |
+
# numpy >= 2.0 added the copy kwarg to np.asarray;
|
| 1220 |
+
# np.array has always accepted it but with weaker semantics pre-2.0.
|
| 1221 |
+
arr = np.array(arr, dtype=dtype, copy=copy)
|
| 1222 |
+
elif dtype is not None:
|
| 1223 |
+
# np.asarray avoids a copy when the dtype already matches,
|
| 1224 |
+
# preserving memory sharing with the underlying OrtValue.
|
| 1225 |
+
arr = np.asarray(arr, dtype=dtype)
|
| 1226 |
+
|
| 1227 |
+
return arr
|
| 1228 |
+
|
| 1229 |
+
def __dlpack__(self, *, stream=None):
|
| 1230 |
+
"""
|
| 1231 |
+
Returns a DLPack capsule representing the tensor (part of the
|
| 1232 |
+
`DLPack protocol <https://dmlc.github.io/dlpack/latest/>`_).
|
| 1233 |
+
|
| 1234 |
+
This enables interoperability with other frameworks via
|
| 1235 |
+
``from_dlpack(ortvalue)`` (e.g. ``torch.from_dlpack``,
|
| 1236 |
+
``jax.dlpack.from_dlpack``, ``numpy.from_dlpack``).
|
| 1237 |
+
|
| 1238 |
+
The OrtValue must hold a contiguous tensor. No data is copied;
|
| 1239 |
+
the consumer shares memory with this OrtValue, which must remain
|
| 1240 |
+
alive while the capsule is in use.
|
| 1241 |
+
|
| 1242 |
+
:param stream: Optional stream on which the tensor data is accessible.
|
| 1243 |
+
Currently unused; included for protocol compliance.
|
| 1244 |
+
:return: A PyCapsule holding a DLManagedTensor.
|
| 1245 |
+
"""
|
| 1246 |
+
return self._ortvalue.__dlpack__(stream=stream)
|
| 1247 |
+
|
| 1248 |
+
def __dlpack_device__(self) -> tuple[int, int]:
|
| 1249 |
+
"""
|
| 1250 |
+
Returns ``(device_type, device_id)`` indicating where the tensor data
|
| 1251 |
+
resides (part of the `DLPack protocol
|
| 1252 |
+
<https://dmlc.github.io/dlpack/latest/>`_).
|
| 1253 |
+
|
| 1254 |
+
:return: Tuple of ``(device_type, device_id)`` as ints following DLPack
|
| 1255 |
+
``DLDeviceType`` enum values.
|
| 1256 |
+
"""
|
| 1257 |
+
return self._ortvalue.__dlpack_device__()
|
| 1258 |
+
|
| 1259 |
+
@classmethod
|
| 1260 |
+
def from_dlpack(cls, data, /) -> OrtValue:
|
| 1261 |
+
"""
|
| 1262 |
+
Construct an OrtValue from an object that implements the DLPack protocol.
|
| 1263 |
+
|
| 1264 |
+
Accepts either:
|
| 1265 |
+
|
| 1266 |
+
* An object with ``__dlpack__`` / ``__dlpack_device__`` methods
|
| 1267 |
+
(e.g. a PyTorch tensor, JAX array, or numpy array).
|
| 1268 |
+
* A raw DLPack PyCapsule (legacy path).
|
| 1269 |
+
|
| 1270 |
+
Boolean tensors are automatically detected when the source object
|
| 1271 |
+
exposes a ``dtype`` attribute (numpy, PyTorch, etc.) or is an
|
| 1272 |
+
``OrtValue``. For raw DLPack capsules where the original dtype cannot
|
| 1273 |
+
be inspected, bool tensors encoded as uint8 by older DLPack versions
|
| 1274 |
+
are not distinguishable from true uint8 tensors and will be imported
|
| 1275 |
+
as uint8.
|
| 1276 |
+
|
| 1277 |
+
No data is copied; the new OrtValue shares memory with the source.
|
| 1278 |
+
|
| 1279 |
+
:param data: A tensor object supporting the DLPack protocol, or a raw
|
| 1280 |
+
DLPack PyCapsule.
|
| 1281 |
+
:return: An OrtValue wrapping the tensor data.
|
| 1282 |
+
"""
|
| 1283 |
+
# Detect boolean dtype from the source object before consuming it,
|
| 1284 |
+
# because DLPack encodes bool as uint8 and the capsule alone cannot
|
| 1285 |
+
# distinguish between the two.
|
| 1286 |
+
is_bool = False
|
| 1287 |
+
if isinstance(data, OrtValue):
|
| 1288 |
+
is_bool = data.data_type() == "tensor(bool)"
|
| 1289 |
+
elif hasattr(data, "dtype"):
|
| 1290 |
+
dtype_obj = data.dtype
|
| 1291 |
+
# Use .name when available (numpy, cupy, tensorflow all expose it).
|
| 1292 |
+
# Fall back to str() for frameworks that don't (e.g. PyTorch).
|
| 1293 |
+
dtype_name = getattr(dtype_obj, "name", str(dtype_obj))
|
| 1294 |
+
is_bool = dtype_name in ("bool", "bool_", "torch.bool")
|
| 1295 |
+
|
| 1296 |
+
# If the input supports the __dlpack__ protocol, call it to get the capsule.
|
| 1297 |
+
if hasattr(data, "__dlpack__"):
|
| 1298 |
+
capsule = data.__dlpack__()
|
| 1299 |
+
else:
|
| 1300 |
+
capsule = data
|
| 1301 |
+
|
| 1302 |
+
return cls(C.OrtValue.from_dlpack(capsule, is_bool))
|
| 1303 |
+
|
| 1304 |
+
def update_inplace(self, data) -> None:
|
| 1305 |
+
"""
|
| 1306 |
+
Update the OrtValue in place. The source data is copied over to the device
|
| 1307 |
+
memory backing the OrtValue. It can be used to update the input values for
|
| 1308 |
+
an InferenceSession with CUDA graph enabled or other scenarios where the
|
| 1309 |
+
OrtValue needs to be updated while the memory address can not be changed.
|
| 1310 |
+
|
| 1311 |
+
:param data: The source data, which can be a Numpy array or another OrtValue.
|
| 1312 |
+
When an OrtValue is provided, data can be copied between devices (e.g.,
|
| 1313 |
+
GPU to GPU) without going through the CPU.
|
| 1314 |
+
"""
|
| 1315 |
+
if isinstance(data, OrtValue):
|
| 1316 |
+
self._ortvalue.update_inplace(data._ortvalue)
|
| 1317 |
+
return
|
| 1318 |
+
|
| 1319 |
+
if not isinstance(data, np.ndarray):
|
| 1320 |
+
raise TypeError("data must be a numpy.ndarray or an OrtValue.")
|
| 1321 |
+
|
| 1322 |
+
self._ortvalue.update_inplace(data)
|
| 1323 |
+
|
| 1324 |
+
|
| 1325 |
+
def copy_tensors(src: Sequence[OrtValue], dst: Sequence[OrtValue], stream=None) -> None:
|
| 1326 |
+
"""
|
| 1327 |
+
Copy tensor data from source OrtValue sequence to destination OrtValue sequence.
|
| 1328 |
+
"""
|
| 1329 |
+
c_sources = [s._get_c_value() for s in src]
|
| 1330 |
+
c_dsts = [d._get_c_value() for d in dst]
|
| 1331 |
+
C.copy_tensors(c_sources, c_dsts, stream)
|
| 1332 |
+
|
| 1333 |
+
|
| 1334 |
+
class OrtDevice:
|
| 1335 |
+
"""
|
| 1336 |
+
A data structure that exposes the underlying C++ OrtDevice
|
| 1337 |
+
"""
|
| 1338 |
+
|
| 1339 |
+
def __init__(self, c_ort_device):
|
| 1340 |
+
"""
|
| 1341 |
+
Internal constructor
|
| 1342 |
+
"""
|
| 1343 |
+
if isinstance(c_ort_device, C.OrtDevice):
|
| 1344 |
+
self._ort_device = c_ort_device
|
| 1345 |
+
else:
|
| 1346 |
+
# An end user won't hit this error
|
| 1347 |
+
raise ValueError(
|
| 1348 |
+
"`Provided object` needs to be of type `onnxruntime.capi.onnxruntime_pybind11_state.OrtDevice`"
|
| 1349 |
+
)
|
| 1350 |
+
|
| 1351 |
+
def _get_c_device(self):
|
| 1352 |
+
"""
|
| 1353 |
+
Internal accessor to underlying object
|
| 1354 |
+
"""
|
| 1355 |
+
return self._ort_device
|
| 1356 |
+
|
| 1357 |
+
@staticmethod
|
| 1358 |
+
def make(ort_device_name, device_id, vendor_id: int | OrtDeviceVendorId = -1):
|
| 1359 |
+
if vendor_id < 0:
|
| 1360 |
+
# Preserve the historical convenience aliases ("cuda", "dml", "cann")
|
| 1361 |
+
# while making them work with plugin EP shared allocators. Those
|
| 1362 |
+
# allocators are keyed by vendor-specific OrtDevice values even when the
|
| 1363 |
+
# Python package itself was built without the corresponding built-in EP.
|
| 1364 |
+
alias_vendor_id = get_vendor_id_for_device_type(ort_device_name)
|
| 1365 |
+
if alias_vendor_id is not None:
|
| 1366 |
+
return OrtDevice(
|
| 1367 |
+
C.OrtDevice(
|
| 1368 |
+
get_ort_device_type(ort_device_name),
|
| 1369 |
+
C.OrtDevice.default_memory(),
|
| 1370 |
+
int(alias_vendor_id),
|
| 1371 |
+
device_id,
|
| 1372 |
+
)
|
| 1373 |
+
)
|
| 1374 |
+
|
| 1375 |
+
# backwards compatibility with generic predefined OrtDevice names
|
| 1376 |
+
return OrtDevice(
|
| 1377 |
+
C.OrtDevice(
|
| 1378 |
+
get_ort_device_type(ort_device_name),
|
| 1379 |
+
C.OrtDevice.default_memory(),
|
| 1380 |
+
device_id,
|
| 1381 |
+
)
|
| 1382 |
+
)
|
| 1383 |
+
else:
|
| 1384 |
+
# generic. use GPU or NPU for ort_device_name and provide a vendor id.
|
| 1385 |
+
# vendor id of 0 is valid in some cases (e.g. webgpu is generic and does not have a vendor id)
|
| 1386 |
+
return OrtDevice(
|
| 1387 |
+
C.OrtDevice(
|
| 1388 |
+
get_ort_device_type(ort_device_name),
|
| 1389 |
+
C.OrtDevice.default_memory(),
|
| 1390 |
+
int(vendor_id),
|
| 1391 |
+
device_id,
|
| 1392 |
+
)
|
| 1393 |
+
)
|
| 1394 |
+
|
| 1395 |
+
def device_id(self):
|
| 1396 |
+
return self._ort_device.device_id()
|
| 1397 |
+
|
| 1398 |
+
def device_type(self):
|
| 1399 |
+
return self._ort_device.device_type()
|
| 1400 |
+
|
| 1401 |
+
def device_vendor_id(self):
|
| 1402 |
+
return self._ort_device.vendor_id()
|
| 1403 |
+
|
| 1404 |
+
def device_mem_type(self):
|
| 1405 |
+
return self._ort_device.mem_type()
|
| 1406 |
+
|
| 1407 |
+
|
| 1408 |
+
class SparseTensor:
|
| 1409 |
+
"""
|
| 1410 |
+
A data structure that project the C++ SparseTensor object
|
| 1411 |
+
The class provides API to work with the object.
|
| 1412 |
+
Depending on the format, the class will hold more than one buffer
|
| 1413 |
+
depending on the format
|
| 1414 |
+
"""
|
| 1415 |
+
|
| 1416 |
+
def __init__(self, sparse_tensor: C.SparseTensor):
|
| 1417 |
+
"""
|
| 1418 |
+
Internal constructor
|
| 1419 |
+
"""
|
| 1420 |
+
if isinstance(sparse_tensor, C.SparseTensor):
|
| 1421 |
+
self._tensor = sparse_tensor
|
| 1422 |
+
else:
|
| 1423 |
+
# An end user won't hit this error
|
| 1424 |
+
raise ValueError(
|
| 1425 |
+
"`Provided object` needs to be of type `onnxruntime.capi.onnxruntime_pybind11_state.SparseTensor`"
|
| 1426 |
+
)
|
| 1427 |
+
|
| 1428 |
+
def _get_c_tensor(self) -> C.SparseTensor:
|
| 1429 |
+
return self._tensor
|
| 1430 |
+
|
| 1431 |
+
@classmethod
|
| 1432 |
+
def sparse_coo_from_numpy(
|
| 1433 |
+
cls,
|
| 1434 |
+
dense_shape: npt.NDArray[np.int64],
|
| 1435 |
+
values: np.ndarray,
|
| 1436 |
+
coo_indices: npt.NDArray[np.int64],
|
| 1437 |
+
ort_device: OrtDevice,
|
| 1438 |
+
) -> SparseTensor:
|
| 1439 |
+
"""
|
| 1440 |
+
Factory method to construct a SparseTensor in COO format from given arguments
|
| 1441 |
+
|
| 1442 |
+
:param dense_shape: 1-D numpy array(int64) or a python list that contains a dense_shape of the sparse tensor
|
| 1443 |
+
must be on cpu memory
|
| 1444 |
+
:param values: a homogeneous, contiguous 1-D numpy array that contains non-zero elements of the tensor
|
| 1445 |
+
of a type.
|
| 1446 |
+
:param coo_indices: contiguous numpy array(int64) that contains COO indices for the tensor. coo_indices may
|
| 1447 |
+
have a 1-D shape when it contains a linear index of non-zero values and its length must be equal to
|
| 1448 |
+
that of the values. It can also be of 2-D shape, in which has it contains pairs of coordinates for
|
| 1449 |
+
each of the nnz values and its length must be exactly twice of the values length.
|
| 1450 |
+
:param ort_device: - describes the backing memory owned by the supplied nummpy arrays. Only CPU memory is
|
| 1451 |
+
suppored for non-numeric data types.
|
| 1452 |
+
|
| 1453 |
+
For primitive types, the method will map values and coo_indices arrays into native memory and will use
|
| 1454 |
+
them as backing storage. It will increment the reference count for numpy arrays and it will decrement it
|
| 1455 |
+
on GC. The buffers may reside in any storage either CPU or GPU.
|
| 1456 |
+
For strings and objects, it will create a copy of the arrays in CPU memory as ORT does not support those
|
| 1457 |
+
on other devices and their memory can not be mapped.
|
| 1458 |
+
"""
|
| 1459 |
+
return cls(C.SparseTensor.sparse_coo_from_numpy(dense_shape, values, coo_indices, ort_device._get_c_device()))
|
| 1460 |
+
|
| 1461 |
+
@classmethod
|
| 1462 |
+
def sparse_csr_from_numpy(
|
| 1463 |
+
cls,
|
| 1464 |
+
dense_shape: npt.NDArray[np.int64],
|
| 1465 |
+
values: np.ndarray,
|
| 1466 |
+
inner_indices: npt.NDArray[np.int64],
|
| 1467 |
+
outer_indices: npt.NDArray[np.int64],
|
| 1468 |
+
ort_device: OrtDevice,
|
| 1469 |
+
) -> SparseTensor:
|
| 1470 |
+
"""
|
| 1471 |
+
Factory method to construct a SparseTensor in CSR format from given arguments
|
| 1472 |
+
|
| 1473 |
+
:param dense_shape: 1-D numpy array(int64) or a python list that contains a dense_shape of the
|
| 1474 |
+
sparse tensor (rows, cols) must be on cpu memory
|
| 1475 |
+
:param values: a contiguous, homogeneous 1-D numpy array that contains non-zero elements of the tensor
|
| 1476 |
+
of a type.
|
| 1477 |
+
:param inner_indices: contiguous 1-D numpy array(int64) that contains CSR inner indices for the tensor.
|
| 1478 |
+
Its length must be equal to that of the values.
|
| 1479 |
+
:param outer_indices: contiguous 1-D numpy array(int64) that contains CSR outer indices for the tensor.
|
| 1480 |
+
Its length must be equal to the number of rows + 1.
|
| 1481 |
+
:param ort_device: - describes the backing memory owned by the supplied nummpy arrays. Only CPU memory is
|
| 1482 |
+
suppored for non-numeric data types.
|
| 1483 |
+
|
| 1484 |
+
For primitive types, the method will map values and indices arrays into native memory and will use them as
|
| 1485 |
+
backing storage. It will increment the reference count and it will decrement then count when it is GCed.
|
| 1486 |
+
The buffers may reside in any storage either CPU or GPU.
|
| 1487 |
+
For strings and objects, it will create a copy of the arrays in CPU memory as ORT does not support those
|
| 1488 |
+
on other devices and their memory can not be mapped.
|
| 1489 |
+
"""
|
| 1490 |
+
return cls(
|
| 1491 |
+
C.SparseTensor.sparse_csr_from_numpy(
|
| 1492 |
+
dense_shape,
|
| 1493 |
+
values,
|
| 1494 |
+
inner_indices,
|
| 1495 |
+
outer_indices,
|
| 1496 |
+
ort_device._get_c_device(),
|
| 1497 |
+
)
|
| 1498 |
+
)
|
| 1499 |
+
|
| 1500 |
+
def values(self) -> np.ndarray:
|
| 1501 |
+
"""
|
| 1502 |
+
The method returns a numpy array that is backed by the native memory
|
| 1503 |
+
if the data type is numeric. Otherwise, the returned numpy array that contains
|
| 1504 |
+
copies of the strings.
|
| 1505 |
+
"""
|
| 1506 |
+
return self._tensor.values()
|
| 1507 |
+
|
| 1508 |
+
def as_coo_view(self):
|
| 1509 |
+
"""
|
| 1510 |
+
The method will return coo representation of the sparse tensor which will enable
|
| 1511 |
+
querying COO indices. If the instance did not contain COO format, it would throw.
|
| 1512 |
+
You can query coo indices as:
|
| 1513 |
+
|
| 1514 |
+
::
|
| 1515 |
+
|
| 1516 |
+
coo_indices = sparse_tensor.as_coo_view().indices()
|
| 1517 |
+
|
| 1518 |
+
which will return a numpy array that is backed by the native memory.
|
| 1519 |
+
"""
|
| 1520 |
+
return self._tensor.get_coo_data()
|
| 1521 |
+
|
| 1522 |
+
def as_csrc_view(self):
|
| 1523 |
+
"""
|
| 1524 |
+
The method will return CSR(C) representation of the sparse tensor which will enable
|
| 1525 |
+
querying CRS(C) indices. If the instance dit not contain CSR(C) format, it would throw.
|
| 1526 |
+
You can query indices as:
|
| 1527 |
+
|
| 1528 |
+
::
|
| 1529 |
+
|
| 1530 |
+
inner_ndices = sparse_tensor.as_csrc_view().inner()
|
| 1531 |
+
outer_ndices = sparse_tensor.as_csrc_view().outer()
|
| 1532 |
+
|
| 1533 |
+
returning numpy arrays backed by the native memory.
|
| 1534 |
+
"""
|
| 1535 |
+
return self._tensor.get_csrc_data()
|
| 1536 |
+
|
| 1537 |
+
def as_blocksparse_view(self):
|
| 1538 |
+
"""
|
| 1539 |
+
The method will return coo representation of the sparse tensor which will enable
|
| 1540 |
+
querying BlockSparse indices. If the instance did not contain BlockSparse format, it would throw.
|
| 1541 |
+
You can query coo indices as:
|
| 1542 |
+
|
| 1543 |
+
::
|
| 1544 |
+
|
| 1545 |
+
block_sparse_indices = sparse_tensor.as_blocksparse_view().indices()
|
| 1546 |
+
|
| 1547 |
+
which will return a numpy array that is backed by the native memory
|
| 1548 |
+
"""
|
| 1549 |
+
return self._tensor.get_blocksparse_data()
|
| 1550 |
+
|
| 1551 |
+
def to_cuda(self, ort_device):
|
| 1552 |
+
"""
|
| 1553 |
+
Returns a copy of this instance on the specified cuda device
|
| 1554 |
+
|
| 1555 |
+
:param ort_device: with name 'cuda' and valid gpu device id
|
| 1556 |
+
|
| 1557 |
+
The method will throw if:
|
| 1558 |
+
|
| 1559 |
+
- this instance contains strings
|
| 1560 |
+
- this instance is already on GPU. Cross GPU copy is not supported
|
| 1561 |
+
- CUDA is not present in this build
|
| 1562 |
+
- if the specified device is not valid
|
| 1563 |
+
"""
|
| 1564 |
+
return SparseTensor(self._tensor.to_cuda(ort_device._get_c_device()))
|
| 1565 |
+
|
| 1566 |
+
def format(self):
|
| 1567 |
+
"""
|
| 1568 |
+
Returns a OrtSparseFormat enumeration
|
| 1569 |
+
"""
|
| 1570 |
+
return self._tensor.format
|
| 1571 |
+
|
| 1572 |
+
def dense_shape(self) -> npt.NDArray[np.int64]:
|
| 1573 |
+
"""
|
| 1574 |
+
Returns a numpy array(int64) containing a dense shape of a sparse tensor
|
| 1575 |
+
"""
|
| 1576 |
+
return self._tensor.dense_shape()
|
| 1577 |
+
|
| 1578 |
+
def data_type(self) -> str:
|
| 1579 |
+
"""
|
| 1580 |
+
Returns a string data type of the data in the OrtValue
|
| 1581 |
+
"""
|
| 1582 |
+
return self._tensor.data_type()
|
| 1583 |
+
|
| 1584 |
+
def device_name(self) -> str:
|
| 1585 |
+
"""
|
| 1586 |
+
Returns the name of the device where the SparseTensor data buffers reside e.g. cpu, cuda
|
| 1587 |
+
"""
|
| 1588 |
+
return self._tensor.device_name().lower()
|
| 1589 |
+
|
| 1590 |
+
|
| 1591 |
+
# Type hint for user-specified function that allows the user to specify initializer locations when compiling a model.
|
| 1592 |
+
GetInitializerLocationFunc = Callable[
|
| 1593 |
+
[str, OrtValue, C.OrtExternalInitializerInfo | None], C.OrtExternalInitializerInfo | None
|
| 1594 |
+
]
|
| 1595 |
+
|
| 1596 |
+
# Type hint that adheres to the signature expected by ORT.
|
| 1597 |
+
GetInitializerLocationWrapperFunc = Callable[
|
| 1598 |
+
[str, C.OrtValue, C.OrtExternalInitializerInfo | None], C.OrtExternalInitializerInfo | None
|
| 1599 |
+
]
|
micromamba_root/envs/pytorch_env/Lib/site-packages/onnxruntime/capi/onnxruntime_providers_shared.dll
ADDED
|
Binary file (21.8 kB). View file
|
|
|
micromamba_root/envs/pytorch_env/Lib/site-packages/onnxruntime/capi/onnxruntime_validation.py
ADDED
|
@@ -0,0 +1,154 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -------------------------------------------------------------------------
|
| 2 |
+
# Copyright (c) Microsoft Corporation. All rights reserved.
|
| 3 |
+
# Licensed under the MIT License.
|
| 4 |
+
# --------------------------------------------------------------------------
|
| 5 |
+
"""
|
| 6 |
+
Check OS requirements for ONNX Runtime Python Bindings.
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
import linecache
|
| 10 |
+
import platform
|
| 11 |
+
import warnings
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def check_distro_info():
|
| 15 |
+
__my_distro__ = ""
|
| 16 |
+
__my_distro_ver__ = ""
|
| 17 |
+
__my_system__ = platform.system().lower()
|
| 18 |
+
|
| 19 |
+
__OS_RELEASE_FILE__ = "/etc/os-release" # noqa: N806
|
| 20 |
+
__LSB_RELEASE_FILE__ = "/etc/lsb-release" # noqa: N806
|
| 21 |
+
|
| 22 |
+
if __my_system__ == "windows":
|
| 23 |
+
__my_distro__ = __my_system__
|
| 24 |
+
__my_distro_ver__ = platform.release().lower()
|
| 25 |
+
|
| 26 |
+
if __my_distro_ver__ not in ["10", "11", "2016server", "2019server", "2022server", "2025server"]:
|
| 27 |
+
warnings.warn(
|
| 28 |
+
f"Unsupported Windows version ({__my_distro_ver__}). ONNX Runtime supports Windows 10 and above, or Windows Server 2016 and above."
|
| 29 |
+
)
|
| 30 |
+
elif __my_system__ == "linux":
|
| 31 |
+
"""Although the 'platform' python module for getting Distro information works well on standard OS images
|
| 32 |
+
running on real hardware, it is not accurate when running on Azure VMs, Git Bash, Cygwin, etc.
|
| 33 |
+
The returned values for release and version are unpredictable for virtualized or emulated environments.
|
| 34 |
+
/etc/os-release and /etc/lsb_release files, on the other hand, are guaranteed to exist and have standard values
|
| 35 |
+
in all OSes supported by onnxruntime. The former is the current standard file to check OS info and the latter
|
| 36 |
+
is its predecessor.
|
| 37 |
+
"""
|
| 38 |
+
# Newer systems have /etc/os-release with relevant distro info
|
| 39 |
+
__my_distro__ = linecache.getline(__OS_RELEASE_FILE__, 3)[3:-1]
|
| 40 |
+
__my_distro_ver__ = linecache.getline(__OS_RELEASE_FILE__, 6)[12:-2]
|
| 41 |
+
|
| 42 |
+
# Older systems may have /etc/os-release instead
|
| 43 |
+
if not __my_distro__:
|
| 44 |
+
__my_distro__ = linecache.getline(__LSB_RELEASE_FILE__, 1)[11:-1]
|
| 45 |
+
__my_distro_ver__ = linecache.getline(__LSB_RELEASE_FILE__, 2)[16:-1]
|
| 46 |
+
|
| 47 |
+
# Instead of trying to parse distro specific files,
|
| 48 |
+
# warn the user ONNX Runtime may not work out of the box
|
| 49 |
+
__my_distro__ = __my_distro__.lower()
|
| 50 |
+
__my_distro_ver__ = __my_distro_ver__.lower()
|
| 51 |
+
elif __my_system__ == "darwin":
|
| 52 |
+
__my_distro__ = __my_system__
|
| 53 |
+
__my_distro_ver__ = platform.release().lower()
|
| 54 |
+
|
| 55 |
+
if int(__my_distro_ver__.split(".")[0]) < 11:
|
| 56 |
+
warnings.warn(
|
| 57 |
+
f"Unsupported macOS version ({__my_distro_ver__}). ONNX Runtime supports macOS 11.0 or later."
|
| 58 |
+
)
|
| 59 |
+
elif __my_system__ == "aix":
|
| 60 |
+
import subprocess # noqa: PLC0415
|
| 61 |
+
|
| 62 |
+
returned_output = subprocess.check_output("oslevel")
|
| 63 |
+
__my_distro_ver__str = returned_output.decode("utf-8")
|
| 64 |
+
__my_distro_ver = __my_distro_ver__str[:3]
|
| 65 |
+
else:
|
| 66 |
+
warnings.warn(
|
| 67 |
+
f"Unsupported platform ({__my_system__}). ONNX Runtime supports Linux, macOS, AIX and Windows platforms, only."
|
| 68 |
+
)
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def get_package_name_and_version_info():
|
| 72 |
+
package_name = ""
|
| 73 |
+
version = ""
|
| 74 |
+
cuda_version = ""
|
| 75 |
+
|
| 76 |
+
try:
|
| 77 |
+
from .build_and_package_info import __version__ as version # noqa: PLC0415
|
| 78 |
+
from .build_and_package_info import package_name # noqa: PLC0415
|
| 79 |
+
|
| 80 |
+
try: # noqa: SIM105
|
| 81 |
+
from .build_and_package_info import cuda_version # noqa: PLC0415
|
| 82 |
+
except ImportError:
|
| 83 |
+
# cuda_version is optional. For example, cpu only package does not have the attribute.
|
| 84 |
+
pass
|
| 85 |
+
except Exception as e:
|
| 86 |
+
warnings.warn("WARNING: failed to collect package name and version info")
|
| 87 |
+
print(e)
|
| 88 |
+
|
| 89 |
+
return package_name, version, cuda_version
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def check_training_module():
|
| 93 |
+
import_ortmodule_exception = None
|
| 94 |
+
|
| 95 |
+
has_ortmodule = False
|
| 96 |
+
try:
|
| 97 |
+
from onnxruntime.training.ortmodule import ORTModule # noqa: F401, PLC0415
|
| 98 |
+
|
| 99 |
+
has_ortmodule = True
|
| 100 |
+
except ImportError:
|
| 101 |
+
# ORTModule not present
|
| 102 |
+
has_ortmodule = False
|
| 103 |
+
except Exception as e:
|
| 104 |
+
# this may happen if Cuda is not installed, we want to raise it after
|
| 105 |
+
# for any exception other than not having ortmodule, we want to continue
|
| 106 |
+
# device version validation and raise the exception after.
|
| 107 |
+
try:
|
| 108 |
+
from onnxruntime.training.ortmodule._fallback import ORTModuleInitException # noqa: PLC0415
|
| 109 |
+
|
| 110 |
+
if isinstance(e, ORTModuleInitException):
|
| 111 |
+
# ORTModule is present but not ready to run yet
|
| 112 |
+
has_ortmodule = True
|
| 113 |
+
except Exception:
|
| 114 |
+
# ORTModule not present
|
| 115 |
+
has_ortmodule = False
|
| 116 |
+
|
| 117 |
+
if not has_ortmodule:
|
| 118 |
+
import_ortmodule_exception = e
|
| 119 |
+
|
| 120 |
+
# collect onnxruntime package name, version, and cuda version
|
| 121 |
+
package_name, version, cuda_version = get_package_name_and_version_info()
|
| 122 |
+
|
| 123 |
+
if has_ortmodule and cuda_version:
|
| 124 |
+
try:
|
| 125 |
+
# collect cuda library build info. the library info may not be available
|
| 126 |
+
# when the build environment has none or multiple libraries installed
|
| 127 |
+
try:
|
| 128 |
+
from .build_and_package_info import cudart_version # noqa: PLC0415
|
| 129 |
+
except ImportError:
|
| 130 |
+
warnings.warn("WARNING: failed to get cudart_version from onnxruntime build info.")
|
| 131 |
+
cudart_version = None
|
| 132 |
+
|
| 133 |
+
def print_build_package_info():
|
| 134 |
+
warnings.warn(f"onnxruntime training package info: package_name: {package_name}")
|
| 135 |
+
warnings.warn(f"onnxruntime training package info: __version__: {version}")
|
| 136 |
+
warnings.warn(f"onnxruntime training package info: cuda_version: {cuda_version}")
|
| 137 |
+
warnings.warn(f"onnxruntime build info: cudart_version: {cudart_version}")
|
| 138 |
+
|
| 139 |
+
# collection cuda library info from current environment.
|
| 140 |
+
from onnxruntime.capi.onnxruntime_collect_build_info import find_cudart_versions # noqa: PLC0415
|
| 141 |
+
|
| 142 |
+
local_cudart_versions = find_cudart_versions(build_env=False, build_cuda_version=cuda_version)
|
| 143 |
+
if cudart_version and local_cudart_versions and cudart_version not in local_cudart_versions:
|
| 144 |
+
print_build_package_info()
|
| 145 |
+
warnings.warn("WARNING: failed to find cudart version that matches onnxruntime build info")
|
| 146 |
+
warnings.warn(f"WARNING: found cudart versions: {local_cudart_versions}")
|
| 147 |
+
except Exception as e:
|
| 148 |
+
warnings.warn("WARNING: failed to collect onnxruntime version and build info")
|
| 149 |
+
print(e)
|
| 150 |
+
|
| 151 |
+
if import_ortmodule_exception:
|
| 152 |
+
raise import_ortmodule_exception
|
| 153 |
+
|
| 154 |
+
return has_ortmodule, package_name, version, cuda_version
|
micromamba_root/envs/pytorch_env/Lib/site-packages/onnxruntime/capi/version_info.py
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
use_cuda = False
|
| 2 |
+
vs2019 = False
|
micromamba_root/envs/pytorch_env/Lib/site-packages/onnxruntime/datasets/__init__.py
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Microsoft Corporation. All rights reserved.
|
| 2 |
+
# Licensed under the MIT License.
|
| 3 |
+
"""
|
| 4 |
+
Short examples used in the documentation.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
import os
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def get_example(name):
|
| 11 |
+
"""
|
| 12 |
+
Retrieves the absolute file name of an example.
|
| 13 |
+
"""
|
| 14 |
+
this = os.path.abspath(os.path.dirname(__file__))
|
| 15 |
+
full = os.path.join(this, name)
|
| 16 |
+
if not os.path.exists(full):
|
| 17 |
+
raise FileNotFoundError(f"Unable to find example '{name}'")
|
| 18 |
+
return full
|
micromamba_root/envs/pytorch_env/Lib/site-packages/onnxruntime/quantization/CalTableFlatBuffers/KeyValue.py
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# automatically generated by the FlatBuffers compiler, do not modify
|
| 2 |
+
|
| 3 |
+
# namespace: CalTableFlatBuffers
|
| 4 |
+
|
| 5 |
+
import flatbuffers
|
| 6 |
+
from flatbuffers.compat import import_numpy
|
| 7 |
+
|
| 8 |
+
np = import_numpy()
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class KeyValue:
|
| 12 |
+
__slots__ = ["_tab"]
|
| 13 |
+
|
| 14 |
+
@classmethod
|
| 15 |
+
def GetRootAs(cls, buf, offset=0): # noqa: N802
|
| 16 |
+
n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset)
|
| 17 |
+
x = KeyValue()
|
| 18 |
+
x.Init(buf, n + offset)
|
| 19 |
+
return x
|
| 20 |
+
|
| 21 |
+
@classmethod
|
| 22 |
+
def GetRootAsKeyValue(cls, buf, offset=0): # noqa: N802
|
| 23 |
+
"""This method is deprecated. Please switch to GetRootAs."""
|
| 24 |
+
return cls.GetRootAs(buf, offset)
|
| 25 |
+
|
| 26 |
+
# KeyValue
|
| 27 |
+
def Init(self, buf, pos): # noqa: N802
|
| 28 |
+
self._tab = flatbuffers.table.Table(buf, pos)
|
| 29 |
+
|
| 30 |
+
# KeyValue
|
| 31 |
+
def Key(self): # noqa: N802
|
| 32 |
+
o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4))
|
| 33 |
+
if o != 0:
|
| 34 |
+
return self._tab.String(o + self._tab.Pos)
|
| 35 |
+
return None
|
| 36 |
+
|
| 37 |
+
# KeyValue
|
| 38 |
+
def Value(self): # noqa: N802
|
| 39 |
+
o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6))
|
| 40 |
+
if o != 0:
|
| 41 |
+
return self._tab.String(o + self._tab.Pos)
|
| 42 |
+
return None
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def Start(builder): # noqa: N802
|
| 46 |
+
builder.StartObject(2)
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def KeyValueStart(builder): # noqa: N802
|
| 50 |
+
"""This method is deprecated. Please switch to Start."""
|
| 51 |
+
return Start(builder)
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def AddKey(builder, key): # noqa: N802
|
| 55 |
+
builder.PrependUOffsetTRelativeSlot(0, flatbuffers.number_types.UOffsetTFlags.py_type(key), 0)
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def KeyValueAddKey(builder, key): # noqa: N802
|
| 59 |
+
"""This method is deprecated. Please switch to AddKey."""
|
| 60 |
+
return AddKey(builder, key)
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def AddValue(builder, value): # noqa: N802
|
| 64 |
+
builder.PrependUOffsetTRelativeSlot(1, flatbuffers.number_types.UOffsetTFlags.py_type(value), 0)
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def KeyValueAddValue(builder, value): # noqa: N802
|
| 68 |
+
"""This method is deprecated. Please switch to AddValue."""
|
| 69 |
+
return AddValue(builder, value)
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def End(builder): # noqa: N802
|
| 73 |
+
return builder.EndObject()
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def KeyValueEnd(builder): # noqa: N802
|
| 77 |
+
"""This method is deprecated. Please switch to End."""
|
| 78 |
+
return End(builder)
|
micromamba_root/envs/pytorch_env/Lib/site-packages/onnxruntime/quantization/CalTableFlatBuffers/TrtTable.py
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# automatically generated by the FlatBuffers compiler, do not modify
|
| 2 |
+
|
| 3 |
+
# namespace: CalTableFlatBuffers
|
| 4 |
+
|
| 5 |
+
import flatbuffers
|
| 6 |
+
from flatbuffers.compat import import_numpy
|
| 7 |
+
|
| 8 |
+
np = import_numpy()
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class TrtTable:
|
| 12 |
+
__slots__ = ["_tab"]
|
| 13 |
+
|
| 14 |
+
@classmethod
|
| 15 |
+
def GetRootAs(cls, buf, offset=0): # noqa: N802
|
| 16 |
+
n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset)
|
| 17 |
+
x = TrtTable()
|
| 18 |
+
x.Init(buf, n + offset)
|
| 19 |
+
return x
|
| 20 |
+
|
| 21 |
+
@classmethod
|
| 22 |
+
def GetRootAsTrtTable(cls, buf, offset=0): # noqa: N802
|
| 23 |
+
"""This method is deprecated. Please switch to GetRootAs."""
|
| 24 |
+
return cls.GetRootAs(buf, offset)
|
| 25 |
+
|
| 26 |
+
# TrtTable
|
| 27 |
+
def Init(self, buf, pos): # noqa: N802
|
| 28 |
+
self._tab = flatbuffers.table.Table(buf, pos)
|
| 29 |
+
|
| 30 |
+
# TrtTable
|
| 31 |
+
def Dict(self, j): # noqa: N802
|
| 32 |
+
o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4))
|
| 33 |
+
if o != 0:
|
| 34 |
+
x = self._tab.Vector(o)
|
| 35 |
+
x += flatbuffers.number_types.UOffsetTFlags.py_type(j) * 4
|
| 36 |
+
x = self._tab.Indirect(x)
|
| 37 |
+
from onnxruntime.quantization.CalTableFlatBuffers.KeyValue import KeyValue # noqa: PLC0415
|
| 38 |
+
|
| 39 |
+
obj = KeyValue()
|
| 40 |
+
obj.Init(self._tab.Bytes, x)
|
| 41 |
+
return obj
|
| 42 |
+
return None
|
| 43 |
+
|
| 44 |
+
# TrtTable
|
| 45 |
+
def DictLength(self): # noqa: N802
|
| 46 |
+
o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4))
|
| 47 |
+
if o != 0:
|
| 48 |
+
return self._tab.VectorLen(o)
|
| 49 |
+
return 0
|
| 50 |
+
|
| 51 |
+
# TrtTable
|
| 52 |
+
def DictIsNone(self): # noqa: N802
|
| 53 |
+
o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4))
|
| 54 |
+
return o == 0
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def Start(builder): # noqa: N802
|
| 58 |
+
builder.StartObject(1)
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def TrtTableStart(builder): # noqa: N802
|
| 62 |
+
"""This method is deprecated. Please switch to Start."""
|
| 63 |
+
return Start(builder)
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def AddDict(builder, dict): # noqa: N802
|
| 67 |
+
builder.PrependUOffsetTRelativeSlot(0, flatbuffers.number_types.UOffsetTFlags.py_type(dict), 0)
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def TrtTableAddDict(builder, dict): # noqa: N802
|
| 71 |
+
"""This method is deprecated. Please switch to AddDict."""
|
| 72 |
+
return AddDict(builder, dict)
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def StartDictVector(builder, numElems): # noqa: N802
|
| 76 |
+
return builder.StartVector(4, numElems, 4)
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def TrtTableStartDictVector(builder, numElems): # noqa: N802
|
| 80 |
+
"""This method is deprecated. Please switch to Start."""
|
| 81 |
+
return StartDictVector(builder, numElems)
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def End(builder): # noqa: N802
|
| 85 |
+
return builder.EndObject()
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def TrtTableEnd(builder): # noqa: N802
|
| 89 |
+
"""This method is deprecated. Please switch to End."""
|
| 90 |
+
return End(builder)
|
micromamba_root/envs/pytorch_env/Lib/site-packages/onnxruntime/quantization/CalTableFlatBuffers/__init__.py
ADDED
|
File without changes
|
micromamba_root/envs/pytorch_env/Lib/site-packages/onnxruntime/quantization/__init__.py
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from .calibrate import ( # noqa: F401
|
| 2 |
+
CalibraterBase,
|
| 3 |
+
CalibrationDataReader,
|
| 4 |
+
CalibrationMethod,
|
| 5 |
+
MinMaxCalibrater,
|
| 6 |
+
create_calibrator,
|
| 7 |
+
)
|
| 8 |
+
from .qdq_quantizer import QDQQuantizer # noqa: F401
|
| 9 |
+
from .quant_utils import QuantFormat, QuantType, write_calibration_table # noqa: F401
|
| 10 |
+
from .quantize import (
|
| 11 |
+
DynamicQuantConfig, # noqa: F401
|
| 12 |
+
QuantizationMode, # noqa: F401
|
| 13 |
+
StaticQuantConfig, # noqa: F401
|
| 14 |
+
get_qdq_config, # noqa: F401
|
| 15 |
+
quantize, # noqa: F401
|
| 16 |
+
quantize_dynamic, # noqa: F401
|
| 17 |
+
quantize_static, # noqa: F401
|
| 18 |
+
)
|
| 19 |
+
from .shape_inference import quant_pre_process # noqa: F401
|
micromamba_root/envs/pytorch_env/Lib/site-packages/onnxruntime/quantization/__pycache__/base_quantizer.cpython-311.pyc
ADDED
|
Binary file (30.5 kB). View file
|
|
|
micromamba_root/envs/pytorch_env/Lib/site-packages/onnxruntime/quantization/__pycache__/calibrate.cpython-311.pyc
ADDED
|
Binary file (70.2 kB). View file
|
|
|
micromamba_root/envs/pytorch_env/Lib/site-packages/onnxruntime/quantization/__pycache__/matmul_bnb4_quantizer.cpython-311.pyc
ADDED
|
Binary file (12.1 kB). View file
|
|
|
micromamba_root/envs/pytorch_env/Lib/site-packages/onnxruntime/quantization/__pycache__/matmul_nbits_quantizer.cpython-311.pyc
ADDED
|
Binary file (77.2 kB). View file
|
|
|
micromamba_root/envs/pytorch_env/Lib/site-packages/onnxruntime/quantization/__pycache__/onnx_model.cpython-311.pyc
ADDED
|
Binary file (35.3 kB). View file
|
|
|
micromamba_root/envs/pytorch_env/Lib/site-packages/onnxruntime/quantization/__pycache__/onnx_quantizer.cpython-311.pyc
ADDED
|
Binary file (51.8 kB). View file
|
|
|
micromamba_root/envs/pytorch_env/Lib/site-packages/onnxruntime/quantization/__pycache__/preprocess.cpython-311.pyc
ADDED
|
Binary file (5.5 kB). View file
|
|
|
micromamba_root/envs/pytorch_env/Lib/site-packages/onnxruntime/quantization/__pycache__/qdq_loss_debug.cpython-311.pyc
ADDED
|
Binary file (18.7 kB). View file
|
|
|
micromamba_root/envs/pytorch_env/Lib/site-packages/onnxruntime/quantization/__pycache__/qdq_quantizer.cpython-311.pyc
ADDED
|
Binary file (64.5 kB). View file
|
|
|
micromamba_root/envs/pytorch_env/Lib/site-packages/onnxruntime/quantization/__pycache__/quant_utils.cpython-311.pyc
ADDED
|
Binary file (55.4 kB). View file
|
|
|
micromamba_root/envs/pytorch_env/Lib/site-packages/onnxruntime/quantization/__pycache__/quantize.cpython-311.pyc
ADDED
|
Binary file (53.6 kB). View file
|
|
|
micromamba_root/envs/pytorch_env/Lib/site-packages/onnxruntime/quantization/__pycache__/registry.cpython-311.pyc
ADDED
|
Binary file (4.73 kB). View file
|
|
|
micromamba_root/envs/pytorch_env/Lib/site-packages/onnxruntime/quantization/__pycache__/shape_inference.cpython-311.pyc
ADDED
|
Binary file (8.85 kB). View file
|
|
|
micromamba_root/envs/pytorch_env/Lib/site-packages/onnxruntime/quantization/__pycache__/static_quantize_runner.cpython-311.pyc
ADDED
|
Binary file (14.3 kB). View file
|
|
|
micromamba_root/envs/pytorch_env/Lib/site-packages/onnxruntime/quantization/__pycache__/tensor_quant_overrides.cpython-311.pyc
ADDED
|
Binary file (21 kB). View file
|
|
|
micromamba_root/envs/pytorch_env/Lib/site-packages/onnxruntime/quantization/base_quantizer.py
ADDED
|
@@ -0,0 +1,529 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -------------------------------------------------------------------------
|
| 2 |
+
# Copyright (c) Microsoft Corporation. All rights reserved.
|
| 3 |
+
# Licensed under the MIT License. See License.txt in the project root for
|
| 4 |
+
# license information.
|
| 5 |
+
# --------------------------------------------------------------------------
|
| 6 |
+
import logging
|
| 7 |
+
from typing import Any
|
| 8 |
+
|
| 9 |
+
import numpy as np
|
| 10 |
+
import onnx
|
| 11 |
+
import onnx.numpy_helper
|
| 12 |
+
|
| 13 |
+
try:
|
| 14 |
+
from onnx.reference.op_run import to_array_extended
|
| 15 |
+
except ImportError:
|
| 16 |
+
# old version of onnx.
|
| 17 |
+
to_array_extended = None
|
| 18 |
+
|
| 19 |
+
from .calibrate import TensorData
|
| 20 |
+
from .onnx_model import ONNXModel
|
| 21 |
+
from .quant_utils import (
|
| 22 |
+
DEQUANT_OP_NAME,
|
| 23 |
+
ONNX_TYPE_TO_NP_TYPE,
|
| 24 |
+
QUANT_OP_NAME,
|
| 25 |
+
TENSOR_NAME_QUANT_SUFFIX,
|
| 26 |
+
find_by_name,
|
| 27 |
+
get_opset_version,
|
| 28 |
+
model_has_infer_metadata,
|
| 29 |
+
normalize_axis,
|
| 30 |
+
pack_bytes_to_4bit,
|
| 31 |
+
quantize_data,
|
| 32 |
+
quantize_nparray,
|
| 33 |
+
save_and_reload_model_with_shape_infer,
|
| 34 |
+
tensor_proto_to_array,
|
| 35 |
+
)
|
| 36 |
+
from .tensor_quant_overrides import TensorQuantOverridesHelper
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
class QuantizationParams:
|
| 40 |
+
def __init__(self, **data: dict[str, Any]):
|
| 41 |
+
self.data = {}
|
| 42 |
+
for k, v in data.items():
|
| 43 |
+
if not isinstance(k, str):
|
| 44 |
+
raise TypeError(f"Keys must be strings not {type(k)} for k={k!r}.")
|
| 45 |
+
if k != "axis" and not isinstance(v, (int, str, np.ndarray, float)):
|
| 46 |
+
raise TypeError(f"Values must be numpy arrays, int, float, str not {type(v)} for k={k!r}.")
|
| 47 |
+
if k == "axis" and not isinstance(v, int) and v is not None:
|
| 48 |
+
raise TypeError(f"Axis value must be an int or None, not {type(v)}.")
|
| 49 |
+
if k == "scale" and v.dtype not in (np.float32, np.float16):
|
| 50 |
+
raise ValueError(f"scale must a float32 or float16 numpy element but is {v.dtype} for k={k!r}")
|
| 51 |
+
self.data[k] = v
|
| 52 |
+
|
| 53 |
+
def get(self, key, default_value=None):
|
| 54 |
+
return self.data.get(key, default_value)
|
| 55 |
+
|
| 56 |
+
def __iter__(self):
|
| 57 |
+
yield from self.data
|
| 58 |
+
|
| 59 |
+
def __getitem__(self, key):
|
| 60 |
+
return self.data[key]
|
| 61 |
+
|
| 62 |
+
def __setitem__(self, key, value):
|
| 63 |
+
self.data[key] = value
|
| 64 |
+
|
| 65 |
+
def __len__(self):
|
| 66 |
+
return len(self.data)
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
class BaseQuantizer:
|
| 70 |
+
def __init__(
|
| 71 |
+
self,
|
| 72 |
+
model,
|
| 73 |
+
per_channel,
|
| 74 |
+
reduce_range,
|
| 75 |
+
weight_qType,
|
| 76 |
+
activation_qType,
|
| 77 |
+
tensors_range,
|
| 78 |
+
nodes_to_quantize,
|
| 79 |
+
nodes_to_exclude,
|
| 80 |
+
op_types_to_quantize,
|
| 81 |
+
extra_options=None,
|
| 82 |
+
):
|
| 83 |
+
if not model_has_infer_metadata(model):
|
| 84 |
+
model = save_and_reload_model_with_shape_infer(model)
|
| 85 |
+
self.value_infos = {vi.name: vi for vi in model.graph.value_info}
|
| 86 |
+
self.value_infos.update({ot.name: ot for ot in model.graph.output})
|
| 87 |
+
self.value_infos.update({it.name: it for it in model.graph.input})
|
| 88 |
+
|
| 89 |
+
self.model = ONNXModel(model)
|
| 90 |
+
self.opset_version = get_opset_version(model)
|
| 91 |
+
self.per_channel = per_channel # weight-pack per channel
|
| 92 |
+
self.reduce_range = reduce_range
|
| 93 |
+
|
| 94 |
+
self.extra_options = extra_options if extra_options else {}
|
| 95 |
+
self.enable_subgraph_quantization = (
|
| 96 |
+
"EnableSubgraph" in self.extra_options and self.extra_options["EnableSubgraph"]
|
| 97 |
+
)
|
| 98 |
+
self.parent = None
|
| 99 |
+
self.force_quantize_no_input_check = (
|
| 100 |
+
"ForceQuantizeNoInputCheck" in self.extra_options and self.extra_options["ForceQuantizeNoInputCheck"]
|
| 101 |
+
)
|
| 102 |
+
|
| 103 |
+
# If user does not explicitly set "WeightSymmetric", then the weight's quantization type determines
|
| 104 |
+
# the symmetry (i.e., signed integer types will use symmetric quantization). See `def is_weight_symmetric()`
|
| 105 |
+
self._is_weight_symmetric: bool | None = self.extra_options.get("WeightSymmetric", None)
|
| 106 |
+
self.is_activation_symmetric = self.extra_options.get("ActivationSymmetric", False)
|
| 107 |
+
self.min_real_range = self.extra_options.get("MinimumRealRange")
|
| 108 |
+
|
| 109 |
+
self.activation_qType = getattr(activation_qType, "tensor_type", activation_qType)
|
| 110 |
+
self.weight_qType = getattr(weight_qType, "tensor_type", weight_qType)
|
| 111 |
+
|
| 112 |
+
"""
|
| 113 |
+
Dictionary specifying the min and max values for tensors. It has following format:
|
| 114 |
+
{
|
| 115 |
+
"param_name": [min, max]
|
| 116 |
+
}
|
| 117 |
+
example:
|
| 118 |
+
{
|
| 119 |
+
'Conv_3:0': [np.float32(0), np.float32(0.5)],
|
| 120 |
+
'Conv_4:0': [np.float32(1), np.float32(3.5)]
|
| 121 |
+
}
|
| 122 |
+
"""
|
| 123 |
+
if tensors_range is not None and any(not isinstance(t, TensorData) for t in tensors_range.values()):
|
| 124 |
+
raise TypeError(
|
| 125 |
+
f"tensors_range contains unexpected types { {type(v) for v in tensors_range.values()} }, not TensorData."
|
| 126 |
+
)
|
| 127 |
+
self.tensors_range = tensors_range
|
| 128 |
+
self.nodes_to_quantize = nodes_to_quantize # specific nodes to quantize
|
| 129 |
+
self.nodes_to_exclude = nodes_to_exclude # specific nodes to exclude
|
| 130 |
+
self.op_types_to_quantize = op_types_to_quantize
|
| 131 |
+
|
| 132 |
+
# Get tensor-level quantization overrides and ensure they are valid.
|
| 133 |
+
self.tensor_quant_overrides = TensorQuantOverridesHelper(self.extra_options.get("TensorQuantOverrides", {}))
|
| 134 |
+
|
| 135 |
+
self.initializers = {initzer.name: initzer for initzer in self.model.initializer()}
|
| 136 |
+
overrides_valid, overrides_err = self.tensor_quant_overrides.is_valid(
|
| 137 |
+
self.initializers, self.value_infos.keys(), activation_qType
|
| 138 |
+
)
|
| 139 |
+
if not overrides_valid:
|
| 140 |
+
raise ValueError(overrides_err)
|
| 141 |
+
|
| 142 |
+
self.tensor_quant_override_qtypes = self.tensor_quant_overrides.get_quant_types()
|
| 143 |
+
|
| 144 |
+
def is_weight_symmetric(self, weight_quant_type: onnx.TensorProto.DataType) -> bool:
|
| 145 |
+
if self._is_weight_symmetric is not None:
|
| 146 |
+
return self._is_weight_symmetric # Return value explicitly set by user.
|
| 147 |
+
return weight_quant_type in (
|
| 148 |
+
onnx.TensorProto.INT4,
|
| 149 |
+
onnx.TensorProto.INT8,
|
| 150 |
+
onnx.TensorProto.INT16,
|
| 151 |
+
onnx.TensorProto.FLOAT8E4M3FN,
|
| 152 |
+
)
|
| 153 |
+
|
| 154 |
+
def quantize_model(self):
|
| 155 |
+
raise NotImplementedError
|
| 156 |
+
|
| 157 |
+
def is_input_a_initializer(self, input_name):
|
| 158 |
+
initializer = find_by_name(input_name, self.model.initializer())
|
| 159 |
+
return initializer is not None
|
| 160 |
+
|
| 161 |
+
def is_per_channel(self):
|
| 162 |
+
return self.per_channel
|
| 163 |
+
|
| 164 |
+
def is_valid_quantize_weight(self, weight_name):
|
| 165 |
+
weight = find_by_name(weight_name, self.model.initializer())
|
| 166 |
+
if weight is not None:
|
| 167 |
+
return weight.data_type in (onnx.TensorProto.FLOAT, onnx.TensorProto.FLOAT16)
|
| 168 |
+
if (not self.enable_subgraph_quantization) or (self.parent is None):
|
| 169 |
+
return False
|
| 170 |
+
return self.parent.is_valid_quantize_weight(weight_name)
|
| 171 |
+
|
| 172 |
+
def should_quantize_node(self, node):
|
| 173 |
+
if (
|
| 174 |
+
self.nodes_to_quantize is not None
|
| 175 |
+
and len(self.nodes_to_quantize) != 0
|
| 176 |
+
and node.name not in self.nodes_to_quantize
|
| 177 |
+
):
|
| 178 |
+
return False
|
| 179 |
+
|
| 180 |
+
if node.op_type not in self.op_types_to_quantize:
|
| 181 |
+
return False
|
| 182 |
+
|
| 183 |
+
if node.op_type in (DEQUANT_OP_NAME, QUANT_OP_NAME):
|
| 184 |
+
return False
|
| 185 |
+
|
| 186 |
+
if self.nodes_to_exclude is not None and node.name in self.nodes_to_exclude:
|
| 187 |
+
return False
|
| 188 |
+
|
| 189 |
+
return True
|
| 190 |
+
|
| 191 |
+
def quantize_bias_static_impl(self, bias_name, input_scale, weight_scale, beta=1.0):
|
| 192 |
+
"""
|
| 193 |
+
Quantized the bias. Zero Point == 0 and Scale == Input_Scale * Weight_Scale
|
| 194 |
+
"""
|
| 195 |
+
|
| 196 |
+
# get bias
|
| 197 |
+
bias_initializer = find_by_name(bias_name, self.model.initializer())
|
| 198 |
+
bias_data = tensor_proto_to_array(bias_initializer)
|
| 199 |
+
quantized_bias_name = bias_name + TENSOR_NAME_QUANT_SUFFIX
|
| 200 |
+
|
| 201 |
+
# quantize bias
|
| 202 |
+
if self.weight_qType == onnx.TensorProto.FLOAT8E4M3FN:
|
| 203 |
+
data = np.asarray(bias_data)
|
| 204 |
+
if data.dtype == np.float16:
|
| 205 |
+
node_qtype = onnx.TensorProto.FLOAT16
|
| 206 |
+
elif data.dtype == np.float32:
|
| 207 |
+
node_qtype = onnx.TensorProto.FLOAT
|
| 208 |
+
else:
|
| 209 |
+
raise TypeError(f"Only float16 or float32 are supported with float 8 but bias dtype is {data.dtype}.")
|
| 210 |
+
quantized_data = data.astype(np.float32)
|
| 211 |
+
bias_scale = np.array([1], dtype=quantized_data.dtype)
|
| 212 |
+
bias_scale_data = bias_scale.reshape(-1)
|
| 213 |
+
packed_bias_initializer = onnx.numpy_helper.from_array(quantized_data, quantized_bias_name)
|
| 214 |
+
self.model.initializer_extend([packed_bias_initializer])
|
| 215 |
+
node_type = "Cast"
|
| 216 |
+
else:
|
| 217 |
+
# calculate scale for bias
|
| 218 |
+
# TODO: This formula should be explained including why the scale is not estimated for the bias as well.
|
| 219 |
+
bias_scale = input_scale * weight_scale * beta
|
| 220 |
+
|
| 221 |
+
# Quantize by dividing by bias_scale
|
| 222 |
+
quantized_data = np.asarray(bias_data, dtype=np.float64) / np.asarray(bias_scale, dtype=np.float64)
|
| 223 |
+
quantized_data = quantized_data.round()
|
| 224 |
+
|
| 225 |
+
# Clip quantized data to the range of a int32
|
| 226 |
+
int32_min = np.float64(np.iinfo(np.int32).min)
|
| 227 |
+
int32_max = np.float64(np.iinfo(np.int32).max)
|
| 228 |
+
if np.any(quantized_data < int32_min) or np.any(quantized_data > int32_max):
|
| 229 |
+
logging.warning(
|
| 230 |
+
f"Quantized bias `{bias_name}` exceeds the range of a int32. The bias scale is too small."
|
| 231 |
+
)
|
| 232 |
+
|
| 233 |
+
quantized_data = np.clip(quantized_data, int32_min, int32_max).astype(np.int32)
|
| 234 |
+
|
| 235 |
+
# update bias initializer
|
| 236 |
+
bias_np_data = np.asarray(quantized_data, dtype=np.int32).reshape(bias_initializer.dims)
|
| 237 |
+
packed_bias_initializer = onnx.numpy_helper.from_array(bias_np_data, quantized_bias_name)
|
| 238 |
+
self.model.initializer_extend([packed_bias_initializer])
|
| 239 |
+
|
| 240 |
+
# Bias's scale dtype should match the original bias data's unquantized type (float32 or float16).
|
| 241 |
+
bias_scale_data = np.asarray(bias_scale, dtype=bias_data.dtype).reshape(-1)
|
| 242 |
+
node_type = "DequantizeLinear"
|
| 243 |
+
node_qtype = self.weight_qType
|
| 244 |
+
|
| 245 |
+
# update scale initializer
|
| 246 |
+
quantized_bias_scale_name = quantized_bias_name + "_scale"
|
| 247 |
+
packed_bias_scale_initializer = onnx.numpy_helper.from_array(bias_scale_data, quantized_bias_scale_name)
|
| 248 |
+
self.model.initializer_extend([packed_bias_scale_initializer])
|
| 249 |
+
|
| 250 |
+
# update zero initializer
|
| 251 |
+
if self.weight_qType == onnx.TensorProto.FLOAT8E4M3FN:
|
| 252 |
+
tensor_type = self.weight_qType
|
| 253 |
+
else:
|
| 254 |
+
tensor_type = onnx.TensorProto.INT32
|
| 255 |
+
|
| 256 |
+
quantized_bias_zp_name = quantized_bias_name + "_zero_point"
|
| 257 |
+
if self.weight_qType == onnx.TensorProto.FLOAT8E4M3FN:
|
| 258 |
+
packed_bias_zp_initializer = onnx.helper.make_tensor(quantized_bias_zp_name, self.weight_qType, [1], [0.0])
|
| 259 |
+
elif bias_scale.size > 1:
|
| 260 |
+
bias_zp_data = np.zeros(bias_scale.shape, dtype=np.int32).reshape(-1)
|
| 261 |
+
packed_bias_zp_initializer = onnx.numpy_helper.from_array(bias_zp_data, quantized_bias_zp_name)
|
| 262 |
+
else:
|
| 263 |
+
packed_bias_zp_initializer = onnx.helper.make_tensor(quantized_bias_zp_name, tensor_type, [], [0])
|
| 264 |
+
self.model.initializer_extend([packed_bias_zp_initializer])
|
| 265 |
+
|
| 266 |
+
return (
|
| 267 |
+
quantized_bias_name,
|
| 268 |
+
quantized_bias_scale_name,
|
| 269 |
+
quantized_bias_zp_name,
|
| 270 |
+
bias_scale_data,
|
| 271 |
+
node_type,
|
| 272 |
+
node_qtype,
|
| 273 |
+
)
|
| 274 |
+
|
| 275 |
+
def quantize_initializer_impl(self, weight, qType, reduce_range=False, keep_float_weight=False):
|
| 276 |
+
"""
|
| 277 |
+
:param weight: TensorProto initializer
|
| 278 |
+
:param qType: type to quantize to
|
| 279 |
+
:param keep_float_weight: Whether to quantize the weight. In some cases, we only want to qunatize scale and zero point.
|
| 280 |
+
If keep_float_weight is False, quantize the weight, or don't quantize the weight.
|
| 281 |
+
:return: quantized weight name, zero point name, scale name
|
| 282 |
+
"""
|
| 283 |
+
# TODO(adrianlizarraga): This function is now only used by onnx_quantizer.py, so move it there.
|
| 284 |
+
q_weight_name = weight.name + TENSOR_NAME_QUANT_SUFFIX
|
| 285 |
+
zp_name = weight.name + "_zero_point"
|
| 286 |
+
scale_name = weight.name + "_scale"
|
| 287 |
+
|
| 288 |
+
# Quantize weight data. Use quantization overrides if provided by the user.
|
| 289 |
+
weight_data = tensor_proto_to_array(weight)
|
| 290 |
+
quant_overrides = self.tensor_quant_overrides.get_per_tensor_overrides(weight.name, default_val={})
|
| 291 |
+
if "quant_type" in quant_overrides:
|
| 292 |
+
qType = quant_overrides["quant_type"].tensor_type # noqa: N806
|
| 293 |
+
|
| 294 |
+
if "scale" in quant_overrides and "zero_point" in quant_overrides:
|
| 295 |
+
zero_point = np.array(quant_overrides["zero_point"], dtype=ONNX_TYPE_TO_NP_TYPE[qType])
|
| 296 |
+
scale = np.array(quant_overrides["scale"])
|
| 297 |
+
q_weight_data = quantize_nparray(qType, weight_data.flatten(), scale, zero_point)
|
| 298 |
+
assert isinstance(zero_point, np.ndarray), f"Unexpected type {type(zero_point)}"
|
| 299 |
+
assert zero_point.dtype != np.float32 and zero_point.dtype != np.float16, (
|
| 300 |
+
f"Unexpected dtype {zero_point.dtype}"
|
| 301 |
+
)
|
| 302 |
+
assert isinstance(scale, np.ndarray), f"Unexpected type {type(scale)}"
|
| 303 |
+
|
| 304 |
+
else:
|
| 305 |
+
symmetric = self.is_weight_symmetric(qType) if qType == self.weight_qType else self.is_activation_symmetric
|
| 306 |
+
zero_point, scale, q_weight_data = quantize_data(
|
| 307 |
+
weight_data.flatten(),
|
| 308 |
+
qType,
|
| 309 |
+
quant_overrides.get("symmetric", symmetric),
|
| 310 |
+
reduce_range=quant_overrides.get("reduce_range", self.reduce_range and reduce_range),
|
| 311 |
+
min_real_range=self.min_real_range,
|
| 312 |
+
rmin_override=quant_overrides.get("rmin"),
|
| 313 |
+
rmax_override=quant_overrides.get("rmax"),
|
| 314 |
+
)
|
| 315 |
+
|
| 316 |
+
assert isinstance(zero_point, np.ndarray), f"Unexpected type {type(zero_point)}"
|
| 317 |
+
assert zero_point.dtype != np.float32 and zero_point.dtype != np.float16, (
|
| 318 |
+
f"Unexpected dtype {zero_point.dtype}"
|
| 319 |
+
)
|
| 320 |
+
assert isinstance(scale, np.ndarray), f"Unexpected type {type(scale)}"
|
| 321 |
+
|
| 322 |
+
scale_dtype = weight.data_type
|
| 323 |
+
scale_initializer = onnx.helper.make_tensor(scale_name, scale_dtype, [], scale.reshape((-1,)).tolist())
|
| 324 |
+
zero_initializer = onnx.helper.make_tensor(zp_name, qType, [], zero_point.reshape((-1,)).tolist())
|
| 325 |
+
self.model.initializer_extend([scale_initializer, zero_initializer])
|
| 326 |
+
|
| 327 |
+
if not keep_float_weight:
|
| 328 |
+
if self.weight_qType == onnx.TensorProto.FLOAT8E4M3FN:
|
| 329 |
+
q_weight_initializer = onnx.TensorProto()
|
| 330 |
+
q_weight_initializer.data_type = self.weight_qType
|
| 331 |
+
q_weight_initializer.dims.extend(weight.dims)
|
| 332 |
+
q_weight_initializer.name = q_weight_name
|
| 333 |
+
# Do not remove .flatten().copy() numpy is not clear about data persistence.
|
| 334 |
+
q_weight_initializer.raw_data = q_weight_data.flatten().copy().tobytes()
|
| 335 |
+
if to_array_extended is not None:
|
| 336 |
+
# This test should not be needed but it helped catch some issues
|
| 337 |
+
# with data persistence and tobytes.
|
| 338 |
+
check = to_array_extended(q_weight_initializer)
|
| 339 |
+
if check.shape != weight_data.shape or check.tobytes() != q_weight_data.tobytes():
|
| 340 |
+
raise RuntimeError(
|
| 341 |
+
f"The initializer of shape {weight_data.shape} could not be created, expecting "
|
| 342 |
+
f"{q_weight_data.tobytes()[:10]}, got {check.tobytes()[:10]} and shape={weight.shape}"
|
| 343 |
+
f"\nraw={str(q_weight_initializer)[:200]}."
|
| 344 |
+
)
|
| 345 |
+
elif qType in (onnx.TensorProto.INT4, onnx.TensorProto.UINT4):
|
| 346 |
+
if q_weight_data.dtype not in (np.int8, np.uint8):
|
| 347 |
+
raise RuntimeError(
|
| 348 |
+
f"Quantized weights for {q_weight_name} must be 8-bit before packing as 4-bit values."
|
| 349 |
+
)
|
| 350 |
+
|
| 351 |
+
# We do not use onnx.helper.pack_float32_to_4bit() due to performance.
|
| 352 |
+
# This can be the difference between a large model taking 30 minutes to quantize vs 5 minutes.
|
| 353 |
+
packed_data = bytes(pack_bytes_to_4bit(q_weight_data.tobytes()))
|
| 354 |
+
|
| 355 |
+
# We only use onnx.helper.make_tensor with raw data due to bug: https://github.com/onnx/onnx/pull/6161
|
| 356 |
+
q_weight_initializer = onnx.helper.make_tensor(q_weight_name, qType, weight.dims, packed_data, raw=True)
|
| 357 |
+
else:
|
| 358 |
+
q_weight_data = np.asarray(q_weight_data, dtype=onnx.helper.tensor_dtype_to_np_dtype(qType)).reshape(
|
| 359 |
+
weight.dims
|
| 360 |
+
)
|
| 361 |
+
q_weight_initializer = onnx.numpy_helper.from_array(q_weight_data, q_weight_name)
|
| 362 |
+
self.model.initializer_extend([q_weight_initializer])
|
| 363 |
+
|
| 364 |
+
return q_weight_name, zp_name, scale_name
|
| 365 |
+
|
| 366 |
+
def quantize_weight_per_channel_impl(
|
| 367 |
+
self,
|
| 368 |
+
weight_name,
|
| 369 |
+
weight_qType,
|
| 370 |
+
channel_axis,
|
| 371 |
+
reduce_range=True,
|
| 372 |
+
keep_float_weight=False,
|
| 373 |
+
):
|
| 374 |
+
# TODO(adrianlizarraga): This function is now only used by onnx_quantizer.py, so move it there.
|
| 375 |
+
initializer = find_by_name(weight_name, self.model.initializer())
|
| 376 |
+
if initializer is None:
|
| 377 |
+
raise ValueError("{} is not an initializer", weight_name)
|
| 378 |
+
|
| 379 |
+
weights = tensor_proto_to_array(initializer)
|
| 380 |
+
weights_rank = len(weights.shape)
|
| 381 |
+
is_axis_valid, axis_norm = normalize_axis(channel_axis, weights_rank)
|
| 382 |
+
if not is_axis_valid:
|
| 383 |
+
raise ValueError(
|
| 384 |
+
f"Weight {weight_name} has a per-channel axis with value {channel_axis} that is "
|
| 385 |
+
f"out-of-bounds for rank {weights_rank}"
|
| 386 |
+
)
|
| 387 |
+
|
| 388 |
+
channel_axis = axis_norm
|
| 389 |
+
channel_count = weights.shape[channel_axis]
|
| 390 |
+
quant_overrides_for_channels = self.tensor_quant_overrides.get_per_channel_overrides(
|
| 391 |
+
weight_name, default_val=[{"axis": channel_axis}]
|
| 392 |
+
)
|
| 393 |
+
|
| 394 |
+
num_channel_overrides = len(quant_overrides_for_channels)
|
| 395 |
+
if num_channel_overrides != 1 and num_channel_overrides != channel_count:
|
| 396 |
+
raise ValueError(
|
| 397 |
+
f"Per-channel tensor quantization overrides for {weight_name} must have "
|
| 398 |
+
f"either 1 or {channel_count} elements in the list of dictionaries."
|
| 399 |
+
)
|
| 400 |
+
|
| 401 |
+
is_axis_override_valid, axis_override = normalize_axis(quant_overrides_for_channels[0]["axis"], weights_rank)
|
| 402 |
+
if not is_axis_override_valid or axis_override != channel_axis:
|
| 403 |
+
raise ValueError(
|
| 404 |
+
f"Tensor quantization overrides for {weight_name} specify an unexpected axis. "
|
| 405 |
+
f"Expected {channel_axis}, but got {quant_overrides_for_channels[0]['axis']}."
|
| 406 |
+
)
|
| 407 |
+
|
| 408 |
+
# If user provides per-channel quantization overrides, all channels must use the same quant_type,
|
| 409 |
+
# axis, symmetric, and reduce_range values. So, just use the first channel's values.
|
| 410 |
+
if "quant_type" in quant_overrides_for_channels[0]:
|
| 411 |
+
weight_qType = quant_overrides_for_channels[0]["quant_type"].tensor_type # noqa: N806
|
| 412 |
+
|
| 413 |
+
symmetric = quant_overrides_for_channels[0].get("symmetric", self.is_weight_symmetric(weight_qType))
|
| 414 |
+
reduce_range = quant_overrides_for_channels[0].get("reduce_range", self.reduce_range and reduce_range)
|
| 415 |
+
zero_point_list = []
|
| 416 |
+
scale_list = []
|
| 417 |
+
quantized_per_channel_data_list = []
|
| 418 |
+
weights_shape = list(weights.shape)
|
| 419 |
+
reshape_dims = list(weights_shape) # deep copy
|
| 420 |
+
reshape_dims[channel_axis] = 1 # only one per channel for reshape
|
| 421 |
+
for i in range(channel_count):
|
| 422 |
+
per_channel_data = weights.take(i, channel_axis)
|
| 423 |
+
channel_override_index = i if i < num_channel_overrides else 0
|
| 424 |
+
channel_quant_overrides = quant_overrides_for_channels[channel_override_index]
|
| 425 |
+
|
| 426 |
+
if "scale" in channel_quant_overrides and "zero_point" in channel_quant_overrides:
|
| 427 |
+
zero_point = np.array(channel_quant_overrides["zero_point"], dtype=ONNX_TYPE_TO_NP_TYPE[weight_qType])
|
| 428 |
+
scale = np.array(channel_quant_overrides["scale"])
|
| 429 |
+
quantized_per_channel_data = quantize_nparray(
|
| 430 |
+
weight_qType, per_channel_data.flatten(), scale, zero_point
|
| 431 |
+
)
|
| 432 |
+
assert isinstance(zero_point, np.ndarray), f"Unexpected type {type(zero_point)}"
|
| 433 |
+
assert zero_point.dtype != np.float32 and zero_point.dtype != np.float16, (
|
| 434 |
+
f"Unexpected dtype {zero_point.dtype}"
|
| 435 |
+
)
|
| 436 |
+
assert isinstance(scale, np.ndarray), f"Unexpected type {type(scale)}"
|
| 437 |
+
assert isinstance(quantized_per_channel_data, np.ndarray), (
|
| 438 |
+
f"Unexpected type {type(quantized_per_channel_data)}"
|
| 439 |
+
)
|
| 440 |
+
|
| 441 |
+
else:
|
| 442 |
+
zero_point, scale, quantized_per_channel_data = quantize_data(
|
| 443 |
+
per_channel_data.flatten(),
|
| 444 |
+
weight_qType,
|
| 445 |
+
symmetric,
|
| 446 |
+
reduce_range=reduce_range,
|
| 447 |
+
min_real_range=self.min_real_range,
|
| 448 |
+
rmin_override=channel_quant_overrides.get("rmin"),
|
| 449 |
+
rmax_override=channel_quant_overrides.get("rmax"),
|
| 450 |
+
)
|
| 451 |
+
|
| 452 |
+
assert isinstance(zero_point, np.ndarray), f"Unexpected type {type(zero_point)}"
|
| 453 |
+
assert zero_point.dtype != np.float32 and zero_point.dtype != np.float16, (
|
| 454 |
+
f"Unexpected dtype {zero_point.dtype}"
|
| 455 |
+
)
|
| 456 |
+
assert isinstance(scale, np.ndarray), f"Unexpected type {type(scale)}"
|
| 457 |
+
assert isinstance(quantized_per_channel_data, np.ndarray), (
|
| 458 |
+
f"Unexpected type {type(quantized_per_channel_data)}"
|
| 459 |
+
)
|
| 460 |
+
|
| 461 |
+
zero_point_list.append(zero_point)
|
| 462 |
+
scale_list.append(scale)
|
| 463 |
+
quantized_per_channel_data_list.append(np.asarray(quantized_per_channel_data).reshape(reshape_dims))
|
| 464 |
+
|
| 465 |
+
# combine per_channel_data into one
|
| 466 |
+
quantized_weights = np.concatenate(quantized_per_channel_data_list, channel_axis)
|
| 467 |
+
q_weight_name = weight_name + TENSOR_NAME_QUANT_SUFFIX
|
| 468 |
+
zp_name = weight_name + "_zero_point"
|
| 469 |
+
scale_name = weight_name + "_scale"
|
| 470 |
+
|
| 471 |
+
# Update packed weight, zero point, and scale initializers
|
| 472 |
+
zero_scale_shape = [initializer.dims[channel_axis]]
|
| 473 |
+
scale_initializer = onnx.helper.make_tensor(
|
| 474 |
+
scale_name, initializer.data_type, zero_scale_shape, np.hstack(scale_list).tolist()
|
| 475 |
+
)
|
| 476 |
+
zero_initializer = onnx.helper.make_tensor(
|
| 477 |
+
zp_name, weight_qType, zero_scale_shape, np.hstack(zero_point_list).tolist()
|
| 478 |
+
)
|
| 479 |
+
|
| 480 |
+
self.model.initializer_extend([scale_initializer, zero_initializer])
|
| 481 |
+
|
| 482 |
+
if not keep_float_weight:
|
| 483 |
+
if weight_qType in (onnx.TensorProto.INT4, onnx.TensorProto.UINT4):
|
| 484 |
+
if quantized_weights.dtype not in (np.int8, np.uint8):
|
| 485 |
+
raise RuntimeError(
|
| 486 |
+
f"Quantized weights for {q_weight_name} must be 8-bit before packing as 4-bit values."
|
| 487 |
+
)
|
| 488 |
+
|
| 489 |
+
# We do not use onnx.helper.pack_float32_to_4bit() due to performance.
|
| 490 |
+
# This can be the difference between a large model taking 30 minutes to quantize vs 5 minutes.
|
| 491 |
+
packed_data = bytes(pack_bytes_to_4bit(quantized_weights.tobytes()))
|
| 492 |
+
|
| 493 |
+
# We only use onnx.helper.make_tensor with raw data due to bug: https://github.com/onnx/onnx/pull/6161
|
| 494 |
+
q_weight_initializer = onnx.helper.make_tensor(
|
| 495 |
+
q_weight_name, weight_qType, weights_shape, packed_data, raw=True
|
| 496 |
+
)
|
| 497 |
+
self.model.initializer_extend([q_weight_initializer])
|
| 498 |
+
else:
|
| 499 |
+
quantized_weights = np.asarray(
|
| 500 |
+
quantized_weights,
|
| 501 |
+
dtype=onnx.helper.tensor_dtype_to_np_dtype(weight_qType),
|
| 502 |
+
).reshape(initializer.dims)
|
| 503 |
+
q_weight_initializer = onnx.numpy_helper.from_array(quantized_weights, q_weight_name)
|
| 504 |
+
self.model.initializer_extend([q_weight_initializer])
|
| 505 |
+
|
| 506 |
+
return q_weight_name, zp_name, scale_name
|
| 507 |
+
|
| 508 |
+
def adjust_tensor_ranges(self):
|
| 509 |
+
if self.tensors_range is None:
|
| 510 |
+
return
|
| 511 |
+
|
| 512 |
+
for node in self.model.nodes():
|
| 513 |
+
# adjust tensor_ranges for input of Clip and Relu node
|
| 514 |
+
if node.op_type in ["Clip", "Relu"]:
|
| 515 |
+
if not self.should_quantize_node(node):
|
| 516 |
+
continue
|
| 517 |
+
if len(self.model.input_name_to_nodes()[node.input[0]]) != 1:
|
| 518 |
+
continue
|
| 519 |
+
if node.input[0] not in self.tensors_range or node.output[0] not in self.tensors_range:
|
| 520 |
+
continue
|
| 521 |
+
td = self.tensors_range[node.output[0]]
|
| 522 |
+
if not isinstance(td, TensorData):
|
| 523 |
+
raise TypeError(f"Unexpected type {type(td)} for {node.output[0]!r}.")
|
| 524 |
+
self.tensors_range[node.input[0]] = td
|
| 525 |
+
# Adjust Softmax to range from 0.0 to 1.0
|
| 526 |
+
elif node.op_type == "Softmax":
|
| 527 |
+
if not self.should_quantize_node(node):
|
| 528 |
+
continue
|
| 529 |
+
self.tensors_range[node.output[0]] = TensorData(lowest=np.float32(0.0), highest=np.float32(1.0))
|
micromamba_root/envs/pytorch_env/Lib/site-packages/onnxruntime/quantization/calibrate.py
ADDED
|
@@ -0,0 +1,1267 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python
|
| 2 |
+
# -------------------------------------------------------------------------
|
| 3 |
+
# Copyright (c) Microsoft, Intel Corporation. All rights reserved.
|
| 4 |
+
# Licensed under the MIT License. See License.txt in the project root for
|
| 5 |
+
# license information.
|
| 6 |
+
# --------------------------------------------------------------------------
|
| 7 |
+
import abc
|
| 8 |
+
import copy
|
| 9 |
+
import itertools
|
| 10 |
+
import os
|
| 11 |
+
import uuid
|
| 12 |
+
from collections.abc import Sequence
|
| 13 |
+
from enum import Enum
|
| 14 |
+
from pathlib import Path
|
| 15 |
+
|
| 16 |
+
import numpy as np
|
| 17 |
+
import onnx
|
| 18 |
+
from onnx import ModelProto, TensorProto, helper, numpy_helper
|
| 19 |
+
|
| 20 |
+
import onnxruntime
|
| 21 |
+
|
| 22 |
+
from .quant_utils import apply_plot, load_model_with_shape_infer, smooth_distribution
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def rel_entr(pk: np.ndarray, qk: np.ndarray) -> np.ndarray:
|
| 26 |
+
"""
|
| 27 |
+
See https://docs.scipy.org/doc/scipy/reference/generated/scipy.special.rel_entr.html#scipy.special.rel_entr.
|
| 28 |
+
Python implementation.
|
| 29 |
+
"""
|
| 30 |
+
res = np.empty(pk.shape, dtype=pk.dtype)
|
| 31 |
+
res[:] = pk[:] * np.log(pk[:] / qk[:])
|
| 32 |
+
c2 = (pk == 0) & (qk >= 0)
|
| 33 |
+
res[c2] = 0
|
| 34 |
+
c1 = (pk > 0) & (qk > 0)
|
| 35 |
+
res[~c1] = np.inf
|
| 36 |
+
return res
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def entropy(
|
| 40 |
+
pk: np.ndarray,
|
| 41 |
+
qk: np.ndarray,
|
| 42 |
+
base: float | None = None,
|
| 43 |
+
axis: int = 0,
|
| 44 |
+
) -> np.ndarray:
|
| 45 |
+
"""
|
| 46 |
+
Simplifeied version of entropy.
|
| 47 |
+
Source: https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.entropy.html.
|
| 48 |
+
This avoids taking a dependency on scipy just for this function.
|
| 49 |
+
"""
|
| 50 |
+
assert base is None or base > 0, "base={base} must be a positive number or `None`."
|
| 51 |
+
assert qk is not None, "qk is None"
|
| 52 |
+
|
| 53 |
+
pk = np.asarray(pk).astype(np.float32)
|
| 54 |
+
pk = 1.0 * pk / np.sum(pk, axis=axis, keepdims=True)
|
| 55 |
+
|
| 56 |
+
qk = np.asarray(qk).astype(np.float32)
|
| 57 |
+
pk, qk = np.broadcast_arrays(pk, qk)
|
| 58 |
+
qk = 1.0 * qk / np.sum(qk, axis=axis, keepdims=True)
|
| 59 |
+
vec = rel_entr(pk, qk)
|
| 60 |
+
|
| 61 |
+
s = np.sum(vec, axis=axis)
|
| 62 |
+
if base is not None:
|
| 63 |
+
s /= np.log(base)
|
| 64 |
+
return s.astype(pk.dtype)
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
class TensorData:
|
| 68 |
+
_allowed = frozenset(["avg", "std", "lowest", "highest", "hist", "hist_edges", "bins"])
|
| 69 |
+
_floats = frozenset(["avg", "std", "lowest", "highest", "hist_edges"])
|
| 70 |
+
|
| 71 |
+
def __init__(self, **kwargs):
|
| 72 |
+
self._attrs = list(kwargs.keys())
|
| 73 |
+
for k, v in kwargs.items():
|
| 74 |
+
if k not in TensorData._allowed:
|
| 75 |
+
raise ValueError(f"Unexpected value {k!r} not in {TensorData._allowed}.")
|
| 76 |
+
if k in TensorData._floats:
|
| 77 |
+
if not hasattr(v, "dtype"):
|
| 78 |
+
raise ValueError(f"Unexpected type {type(v)} for k={k!r}")
|
| 79 |
+
if v.dtype not in (np.float16, np.float32):
|
| 80 |
+
raise ValueError(f"Unexpected dtype {v.dtype} for k={k!r}")
|
| 81 |
+
setattr(self, k, v)
|
| 82 |
+
|
| 83 |
+
@property
|
| 84 |
+
def range_value(self):
|
| 85 |
+
if not hasattr(self, "lowest") or not hasattr(self, "highest"):
|
| 86 |
+
raise AttributeError(f"Attributes 'lowest' and/or 'highest' missing in {dir(self)}.")
|
| 87 |
+
return (self.lowest, self.highest)
|
| 88 |
+
|
| 89 |
+
@property
|
| 90 |
+
def avg_std(self):
|
| 91 |
+
if not hasattr(self, "avg") or not hasattr(self, "std"):
|
| 92 |
+
raise AttributeError(f"Attributes 'avg' and/or 'std' missing in {dir(self)}.")
|
| 93 |
+
return (self.avg, self.std)
|
| 94 |
+
|
| 95 |
+
def to_dict(self):
|
| 96 |
+
# This is needed to serialize the data into JSON.
|
| 97 |
+
data = {k: getattr(self, k) for k in self._attrs}
|
| 98 |
+
data["CLS"] = self.__class__.__name__
|
| 99 |
+
return data
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
class TensorsData:
|
| 103 |
+
def __init__(self, calibration_method, data: dict[str, TensorData | tuple]):
|
| 104 |
+
self.calibration_method = calibration_method
|
| 105 |
+
self.data = {}
|
| 106 |
+
for k, v in data.items():
|
| 107 |
+
if not isinstance(k, str):
|
| 108 |
+
raise TypeError(f"Keys must be strings not {type(k)}.")
|
| 109 |
+
if isinstance(v, tuple):
|
| 110 |
+
if calibration_method == CalibrationMethod.MinMax and len(v) == 2:
|
| 111 |
+
self.data[k] = TensorData(lowest=v[0], highest=v[1])
|
| 112 |
+
continue
|
| 113 |
+
if len(v) == 4:
|
| 114 |
+
self.data[k] = TensorData(lowest=v[0], highest=v[1], hist=v[2], bins=v[3])
|
| 115 |
+
continue
|
| 116 |
+
raise TypeError(f"Unexpected tuple for {k:r}, it has {len(v)} elements: {v}.")
|
| 117 |
+
if not isinstance(v, TensorData):
|
| 118 |
+
raise TypeError(f"Values must be TensorData not {type(v)}.")
|
| 119 |
+
self.data[k] = v
|
| 120 |
+
|
| 121 |
+
def __iter__(self):
|
| 122 |
+
yield from self.data
|
| 123 |
+
|
| 124 |
+
def __contains__(self, key):
|
| 125 |
+
return key in self.data
|
| 126 |
+
|
| 127 |
+
def __getitem__(self, key):
|
| 128 |
+
return self.data[key]
|
| 129 |
+
|
| 130 |
+
def __setitem__(self, key, value):
|
| 131 |
+
if key not in self.data:
|
| 132 |
+
raise RuntimeError(f"Only an existing tensor can be modified, {key!r} is not.")
|
| 133 |
+
self.data[key] = value
|
| 134 |
+
|
| 135 |
+
def keys(self):
|
| 136 |
+
return self.data.keys()
|
| 137 |
+
|
| 138 |
+
def values(self):
|
| 139 |
+
return self.data.values()
|
| 140 |
+
|
| 141 |
+
def items(self):
|
| 142 |
+
return self.data.items()
|
| 143 |
+
|
| 144 |
+
def to_dict(self):
|
| 145 |
+
# This is needed to serialize the data into JSON.
|
| 146 |
+
data = {
|
| 147 |
+
"CLS": self.__class__.__name__,
|
| 148 |
+
"data": self.data,
|
| 149 |
+
"calibration_method": self.calibration_method,
|
| 150 |
+
}
|
| 151 |
+
return data
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
class CalibrationMethod(Enum):
|
| 155 |
+
MinMax = 0
|
| 156 |
+
Entropy = 1
|
| 157 |
+
Percentile = 2
|
| 158 |
+
Distribution = 3
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
class CalibrationDataReader(metaclass=abc.ABCMeta):
|
| 162 |
+
@classmethod
|
| 163 |
+
def __subclasshook__(cls, subclass):
|
| 164 |
+
return (hasattr(subclass, "get_next") and callable(subclass.get_next)) or NotImplemented
|
| 165 |
+
|
| 166 |
+
@abc.abstractmethod
|
| 167 |
+
def get_next(self) -> dict:
|
| 168 |
+
"""generate the input data dict for ONNXinferenceSession run"""
|
| 169 |
+
raise NotImplementedError
|
| 170 |
+
|
| 171 |
+
def __iter__(self):
|
| 172 |
+
return self
|
| 173 |
+
|
| 174 |
+
def __next__(self):
|
| 175 |
+
result = self.get_next()
|
| 176 |
+
if result is None:
|
| 177 |
+
raise StopIteration
|
| 178 |
+
return result
|
| 179 |
+
|
| 180 |
+
def __len__(self):
|
| 181 |
+
raise NotImplementedError
|
| 182 |
+
|
| 183 |
+
def set_range(self, start_index: int, end_index: int):
|
| 184 |
+
raise NotImplementedError
|
| 185 |
+
|
| 186 |
+
|
| 187 |
+
class CalibraterBase:
|
| 188 |
+
def __init__(
|
| 189 |
+
self,
|
| 190 |
+
model_path: str | Path,
|
| 191 |
+
op_types_to_calibrate: Sequence[str] | None = None,
|
| 192 |
+
augmented_model_path="augmented_model.onnx",
|
| 193 |
+
symmetric=False,
|
| 194 |
+
use_external_data_format=False,
|
| 195 |
+
per_channel=False,
|
| 196 |
+
):
|
| 197 |
+
"""
|
| 198 |
+
:param model_path: ONNX model to calibrate. It should be a model file path
|
| 199 |
+
:param op_types_to_calibrate: operator types to calibrate. By default, calibrate all the float32/float16 tensors.
|
| 200 |
+
:param augmented_model_path: save augmented model to this path.
|
| 201 |
+
:param symmetric: make range of tensor symmetric (central point is 0).
|
| 202 |
+
:param use_external_data_format: use external data format to store model which size is >= 2Gb.
|
| 203 |
+
:param per_channel: whether to compute ranges per each channel.
|
| 204 |
+
"""
|
| 205 |
+
if isinstance(model_path, str):
|
| 206 |
+
self.model = load_model_with_shape_infer(Path(model_path))
|
| 207 |
+
elif isinstance(model_path, Path):
|
| 208 |
+
self.model = load_model_with_shape_infer(model_path)
|
| 209 |
+
else:
|
| 210 |
+
raise ValueError("model_path should be model path.")
|
| 211 |
+
|
| 212 |
+
self.op_types_to_calibrate = op_types_to_calibrate
|
| 213 |
+
self.augmented_model_path = augmented_model_path
|
| 214 |
+
self.symmetric = symmetric
|
| 215 |
+
self.use_external_data_format = use_external_data_format
|
| 216 |
+
self.per_channel = per_channel
|
| 217 |
+
|
| 218 |
+
self.augment_model = None
|
| 219 |
+
self.infer_session = None
|
| 220 |
+
self.execution_providers = ["CPUExecutionProvider"]
|
| 221 |
+
|
| 222 |
+
def set_execution_providers(self, execution_providers=["CPUExecutionProvider"]): # noqa: B006
|
| 223 |
+
"""
|
| 224 |
+
reset the execution providers to execute the collect_data. It triggers to re-creating inference session.
|
| 225 |
+
"""
|
| 226 |
+
self.execution_providers = execution_providers
|
| 227 |
+
self.create_inference_session()
|
| 228 |
+
|
| 229 |
+
def create_inference_session(self):
|
| 230 |
+
"""
|
| 231 |
+
create an OnnxRuntime InferenceSession.
|
| 232 |
+
"""
|
| 233 |
+
sess_options = onnxruntime.SessionOptions()
|
| 234 |
+
sess_options.graph_optimization_level = onnxruntime.GraphOptimizationLevel.ORT_DISABLE_ALL
|
| 235 |
+
self.infer_session = onnxruntime.InferenceSession(
|
| 236 |
+
self.augmented_model_path,
|
| 237 |
+
sess_options=sess_options,
|
| 238 |
+
providers=self.execution_providers,
|
| 239 |
+
)
|
| 240 |
+
|
| 241 |
+
def select_tensors_to_calibrate(self, model: ModelProto):
|
| 242 |
+
"""
|
| 243 |
+
select input/output tensors of candidate nodes to calibrate.
|
| 244 |
+
returns:
|
| 245 |
+
tensors (set): set of tensor name.
|
| 246 |
+
value_infos (dict): tensor name to value info.
|
| 247 |
+
"""
|
| 248 |
+
value_infos = {vi.name: vi for vi in model.graph.value_info}
|
| 249 |
+
value_infos.update({ot.name: ot for ot in model.graph.output})
|
| 250 |
+
value_infos.update({it.name: it for it in model.graph.input})
|
| 251 |
+
initializer = {init.name for init in model.graph.initializer}
|
| 252 |
+
|
| 253 |
+
tensors_to_calibrate = set()
|
| 254 |
+
tensor_type_to_calibrate = {TensorProto.FLOAT, TensorProto.FLOAT16}
|
| 255 |
+
|
| 256 |
+
for node in model.graph.node:
|
| 257 |
+
if not self.op_types_to_calibrate or node.op_type in self.op_types_to_calibrate:
|
| 258 |
+
for tensor_name in itertools.chain(node.input, node.output):
|
| 259 |
+
if tensor_name in value_infos:
|
| 260 |
+
vi = value_infos[tensor_name]
|
| 261 |
+
if (
|
| 262 |
+
vi.type.HasField("tensor_type")
|
| 263 |
+
and (vi.type.tensor_type.elem_type in tensor_type_to_calibrate)
|
| 264 |
+
and (tensor_name not in initializer)
|
| 265 |
+
):
|
| 266 |
+
tensors_to_calibrate.add(tensor_name)
|
| 267 |
+
|
| 268 |
+
return tensors_to_calibrate, value_infos
|
| 269 |
+
|
| 270 |
+
def get_augment_model(self):
|
| 271 |
+
"""
|
| 272 |
+
return: augmented onnx model. Call after calling augment_graph
|
| 273 |
+
"""
|
| 274 |
+
return self.model
|
| 275 |
+
|
| 276 |
+
def augment_graph(self):
|
| 277 |
+
"""
|
| 278 |
+
abstract method: augment the input model to prepare for collecting data. It will:
|
| 279 |
+
1. augment the model to be able to collect desired statistics data
|
| 280 |
+
2. save augmented model to augmented_model_paths
|
| 281 |
+
"""
|
| 282 |
+
raise NotImplementedError
|
| 283 |
+
|
| 284 |
+
def collect_data(self, data_reader: CalibrationDataReader):
|
| 285 |
+
"""
|
| 286 |
+
abstract method: collect the tensors that will be used for range computation. It can be called multiple times.
|
| 287 |
+
"""
|
| 288 |
+
raise NotImplementedError
|
| 289 |
+
|
| 290 |
+
def compute_data(self) -> TensorsData:
|
| 291 |
+
"""
|
| 292 |
+
abstract method: compute data based on the calibration method stored in TensorsData
|
| 293 |
+
"""
|
| 294 |
+
raise NotImplementedError
|
| 295 |
+
|
| 296 |
+
|
| 297 |
+
class MinMaxCalibrater(CalibraterBase):
|
| 298 |
+
def __init__(
|
| 299 |
+
self,
|
| 300 |
+
model_path: str | Path,
|
| 301 |
+
op_types_to_calibrate: Sequence[str] | None = None,
|
| 302 |
+
augmented_model_path="augmented_model.onnx",
|
| 303 |
+
symmetric=False,
|
| 304 |
+
use_external_data_format=False,
|
| 305 |
+
moving_average=False,
|
| 306 |
+
averaging_constant=0.01,
|
| 307 |
+
max_intermediate_outputs=None,
|
| 308 |
+
per_channel=False,
|
| 309 |
+
):
|
| 310 |
+
"""
|
| 311 |
+
:param model_path: ONNX model to calibrate. It is a model path
|
| 312 |
+
:param op_types_to_calibrate: operator types to calibrate. By default, calibrate all the float32/float16 tensors.
|
| 313 |
+
:param augmented_model_path: save augmented model to this path.
|
| 314 |
+
:param symmetric: make range of tensor symmetric (central point is 0).
|
| 315 |
+
:param use_external_data_format: use external data format to store model which size is >= 2Gb
|
| 316 |
+
:param moving_average: compute the moving average of the minimum and maximum values instead of the global minimum and maximum.
|
| 317 |
+
:param averaging_constant: constant smoothing factor to use when computing the moving average.
|
| 318 |
+
:param max_intermediate_outputs: maximum number of intermediate outputs before an intermediate range is computed.
|
| 319 |
+
:param per_channel: whether to compute ranges per each channel.
|
| 320 |
+
"""
|
| 321 |
+
super().__init__(
|
| 322 |
+
model_path,
|
| 323 |
+
op_types_to_calibrate=op_types_to_calibrate,
|
| 324 |
+
augmented_model_path=augmented_model_path,
|
| 325 |
+
symmetric=symmetric,
|
| 326 |
+
use_external_data_format=use_external_data_format,
|
| 327 |
+
per_channel=per_channel,
|
| 328 |
+
)
|
| 329 |
+
self.intermediate_outputs = []
|
| 330 |
+
self.calibrate_tensors_range = None
|
| 331 |
+
self.num_model_outputs = len(self.model.graph.output)
|
| 332 |
+
self.model_original_outputs = {output.name for output in self.model.graph.output}
|
| 333 |
+
self.moving_average = moving_average
|
| 334 |
+
if moving_average and (averaging_constant < 0 or averaging_constant > 1):
|
| 335 |
+
raise ValueError("Invalid averaging constant, which should not be < 0 or > 1.")
|
| 336 |
+
self.averaging_constant = averaging_constant
|
| 337 |
+
self.max_intermediate_outputs = max_intermediate_outputs
|
| 338 |
+
|
| 339 |
+
def augment_graph(self):
|
| 340 |
+
"""
|
| 341 |
+
Adds ReduceMin and ReduceMax nodes to all quantization_candidates op type nodes in
|
| 342 |
+
model and ensures their outputs are stored as part of the graph output
|
| 343 |
+
:return: augmented ONNX model
|
| 344 |
+
"""
|
| 345 |
+
tensors, _ = self.select_tensors_to_calibrate(self.model)
|
| 346 |
+
reshape_shape_name = str(uuid.uuid4())
|
| 347 |
+
reshape_shape = numpy_helper.from_array(np.array([-1], dtype=np.int64), reshape_shape_name)
|
| 348 |
+
self.model.graph.initializer.append(reshape_shape)
|
| 349 |
+
|
| 350 |
+
def get_op_version(op_type, model):
|
| 351 |
+
for opset_import in model.opset_import:
|
| 352 |
+
if onnx.defs.has(op_type, opset_import.domain):
|
| 353 |
+
return opset_import.version
|
| 354 |
+
raise RuntimeError(f"Model does not contain a version for '{op_type}'.")
|
| 355 |
+
|
| 356 |
+
def insert_nodes(tensor_name, new_nodes):
|
| 357 |
+
index = next(
|
| 358 |
+
(i for i, x in enumerate(self.model.graph.node) if tensor_name in x.input), len(self.model.graph.node)
|
| 359 |
+
)
|
| 360 |
+
for node in new_nodes:
|
| 361 |
+
self.model.graph.node.insert(index, node)
|
| 362 |
+
index += 1
|
| 363 |
+
|
| 364 |
+
def add_reduce_min_max(tensor_name, reduce_op_name):
|
| 365 |
+
# When doing ReduceMax/ReduceMin, ORT can't reduce on dim with value of 0 if 'keepdims' is false.
|
| 366 |
+
# To make the code simple, we always let keepdims to be 1.
|
| 367 |
+
keepdims = 1
|
| 368 |
+
|
| 369 |
+
# Adding ReduceMin/ReduceMax nodes: ReduceMin/ReduceMax -> Reshape-> (output)
|
| 370 |
+
reduce_output = tensor_name + "_" + reduce_op_name
|
| 371 |
+
intermediate_output = reduce_output + "_Reshape"
|
| 372 |
+
reduce_node = onnx.helper.make_node(
|
| 373 |
+
reduce_op_name, [tensor_name], [intermediate_output], keepdims=keepdims, name=reduce_output
|
| 374 |
+
)
|
| 375 |
+
|
| 376 |
+
reshape_node = onnx.helper.make_node(
|
| 377 |
+
"Reshape",
|
| 378 |
+
inputs=[intermediate_output, reshape_shape_name],
|
| 379 |
+
outputs=[reduce_output],
|
| 380 |
+
name=intermediate_output,
|
| 381 |
+
)
|
| 382 |
+
|
| 383 |
+
value_infos = {vi.name: vi for vi in self.model.graph.value_info}
|
| 384 |
+
value_infos.update({o.name: o for o in self.model.graph.output})
|
| 385 |
+
value_infos.update({i.name: i for i in self.model.graph.input})
|
| 386 |
+
if tensor_name in value_infos:
|
| 387 |
+
onnx_type = value_infos[tensor_name].type.tensor_type.elem_type
|
| 388 |
+
else:
|
| 389 |
+
raise ValueError(
|
| 390 |
+
f"Unable to guess tensor type for tensor {tensor_name!r}, "
|
| 391 |
+
"running shape inference before quantization may resolve this issue."
|
| 392 |
+
)
|
| 393 |
+
|
| 394 |
+
# Include axes in reduce_op when per_channel, always keeping axis=1
|
| 395 |
+
if self.per_channel:
|
| 396 |
+
tensor_rank = len(value_infos[tensor_name].type.tensor_type.shape.dim)
|
| 397 |
+
reduced_axes = [0, *range(2, tensor_rank)]
|
| 398 |
+
# Depending on opset version, axes in ReduceMin/ReduceMax are in attribute or inputs
|
| 399 |
+
if get_op_version(reduce_op_name, self.model) < 18:
|
| 400 |
+
reduce_node.attribute.append(helper.make_attribute("axes", reduced_axes))
|
| 401 |
+
else:
|
| 402 |
+
reduce_axes_name = str(uuid.uuid4())
|
| 403 |
+
reduce_axes = numpy_helper.from_array(np.array(reduced_axes, dtype=np.int64), reduce_axes_name)
|
| 404 |
+
reduce_node.input.append(reduce_axes_name)
|
| 405 |
+
self.model.graph.initializer.append(reduce_axes)
|
| 406 |
+
|
| 407 |
+
insert_nodes(tensor_name, [reduce_node, reshape_node])
|
| 408 |
+
self.model.graph.output.append(helper.make_tensor_value_info(reduce_output, onnx_type, [None]))
|
| 409 |
+
|
| 410 |
+
for tensor in tensors:
|
| 411 |
+
add_reduce_min_max(tensor, "ReduceMin")
|
| 412 |
+
add_reduce_min_max(tensor, "ReduceMax")
|
| 413 |
+
|
| 414 |
+
onnx.save(
|
| 415 |
+
self.model,
|
| 416 |
+
self.augmented_model_path,
|
| 417 |
+
save_as_external_data=self.use_external_data_format,
|
| 418 |
+
)
|
| 419 |
+
|
| 420 |
+
def clear_collected_data(self):
|
| 421 |
+
self.intermediate_outputs = []
|
| 422 |
+
|
| 423 |
+
def collect_data(self, data_reader: CalibrationDataReader):
|
| 424 |
+
while True:
|
| 425 |
+
inputs = data_reader.get_next()
|
| 426 |
+
if not inputs:
|
| 427 |
+
break
|
| 428 |
+
self.intermediate_outputs.append(
|
| 429 |
+
[
|
| 430 |
+
value if sess_o.name not in self.model_original_outputs else None
|
| 431 |
+
for sess_o, value in zip(
|
| 432 |
+
self.infer_session.get_outputs(), self.infer_session.run(None, inputs), strict=False
|
| 433 |
+
)
|
| 434 |
+
]
|
| 435 |
+
)
|
| 436 |
+
if (
|
| 437 |
+
self.max_intermediate_outputs is not None
|
| 438 |
+
and len(self.intermediate_outputs) == self.max_intermediate_outputs
|
| 439 |
+
):
|
| 440 |
+
self.clear_collected_data()
|
| 441 |
+
|
| 442 |
+
if len(self.intermediate_outputs) == 0 and self.calibrate_tensors_range is None:
|
| 443 |
+
raise ValueError("No data is collected.")
|
| 444 |
+
|
| 445 |
+
t = self.compute_data()
|
| 446 |
+
if not isinstance(t, TensorsData):
|
| 447 |
+
raise TypeError(f"compute_data must return a TensorsData not {type(t)}.")
|
| 448 |
+
self.clear_collected_data()
|
| 449 |
+
|
| 450 |
+
def merge_range(self, old_range, new_range):
|
| 451 |
+
if not old_range:
|
| 452 |
+
return new_range
|
| 453 |
+
|
| 454 |
+
for key, value in old_range.items():
|
| 455 |
+
# Handling for structured data types with TensorData
|
| 456 |
+
if isinstance(value, TensorData):
|
| 457 |
+
old_min = value.range_value[0]
|
| 458 |
+
old_max = value.range_value[1]
|
| 459 |
+
else:
|
| 460 |
+
old_min, old_max = value
|
| 461 |
+
|
| 462 |
+
if isinstance(new_range[key], TensorData):
|
| 463 |
+
new_min = new_range[key].range_value[0]
|
| 464 |
+
new_max = new_range[key].range_value[1]
|
| 465 |
+
else:
|
| 466 |
+
new_min, new_max = new_range[key]
|
| 467 |
+
|
| 468 |
+
if self.moving_average:
|
| 469 |
+
min_value = old_min + self.averaging_constant * (new_min - old_min)
|
| 470 |
+
max_value = old_max + self.averaging_constant * (new_max - old_max)
|
| 471 |
+
else:
|
| 472 |
+
min_value = min(old_min, new_min)
|
| 473 |
+
max_value = max(old_max, new_max)
|
| 474 |
+
|
| 475 |
+
# If structured as TensorData, wrap the result accordingly
|
| 476 |
+
if isinstance(value, TensorData) or isinstance(new_range[key], TensorData):
|
| 477 |
+
new_range[key] = TensorData(lowest=min_value, highest=max_value)
|
| 478 |
+
else:
|
| 479 |
+
new_range[key] = (min_value, max_value)
|
| 480 |
+
|
| 481 |
+
return new_range
|
| 482 |
+
|
| 483 |
+
def compute_data(self) -> TensorsData:
|
| 484 |
+
"""
|
| 485 |
+
Compute the min-max range of tensor
|
| 486 |
+
:return: dictionary mapping: {added node names: (ReduceMin, ReduceMax) pairs }
|
| 487 |
+
"""
|
| 488 |
+
|
| 489 |
+
if len(self.intermediate_outputs) == 0:
|
| 490 |
+
return self.calibrate_tensors_range
|
| 491 |
+
|
| 492 |
+
output_names = [self.infer_session.get_outputs()[i].name for i in range(len(self.intermediate_outputs[0]))]
|
| 493 |
+
output_dicts_list = [
|
| 494 |
+
dict(zip(output_names, intermediate_output, strict=False))
|
| 495 |
+
for intermediate_output in self.intermediate_outputs
|
| 496 |
+
]
|
| 497 |
+
|
| 498 |
+
merged_output_dict = {}
|
| 499 |
+
for d in output_dicts_list:
|
| 500 |
+
for k, v in d.items():
|
| 501 |
+
merged_output_dict.setdefault(k, []).append(v)
|
| 502 |
+
added_output_names = output_names[self.num_model_outputs :]
|
| 503 |
+
calibrate_tensor_names = [
|
| 504 |
+
added_output_names[i].rpartition("_")[0] for i in range(0, len(added_output_names), 2)
|
| 505 |
+
] # output names
|
| 506 |
+
|
| 507 |
+
merged_added_output_dict = {
|
| 508 |
+
i: merged_output_dict[i] for i in merged_output_dict if i not in self.model_original_outputs
|
| 509 |
+
}
|
| 510 |
+
|
| 511 |
+
pairs = []
|
| 512 |
+
for i in range(0, len(added_output_names), 2):
|
| 513 |
+
if self.moving_average:
|
| 514 |
+
min_value_array = np.nanmean(merged_added_output_dict[added_output_names[i]], axis=0)
|
| 515 |
+
max_value_array = np.nanmean(merged_added_output_dict[added_output_names[i + 1]], axis=0)
|
| 516 |
+
else:
|
| 517 |
+
min_value_array = np.nanmin(merged_added_output_dict[added_output_names[i]], axis=0)
|
| 518 |
+
max_value_array = np.nanmax(merged_added_output_dict[added_output_names[i + 1]], axis=0)
|
| 519 |
+
|
| 520 |
+
if self.symmetric:
|
| 521 |
+
max_absolute_value = np.nanmax([np.abs(min_value_array), np.abs(max_value_array)], axis=0)
|
| 522 |
+
pairs.append((-max_absolute_value, max_absolute_value))
|
| 523 |
+
else:
|
| 524 |
+
pairs.append((min_value_array, max_value_array))
|
| 525 |
+
|
| 526 |
+
new_calibrate_tensors_range = TensorsData(
|
| 527 |
+
CalibrationMethod.MinMax, dict(zip(calibrate_tensor_names, pairs, strict=False))
|
| 528 |
+
)
|
| 529 |
+
if self.calibrate_tensors_range:
|
| 530 |
+
self.calibrate_tensors_range = self.merge_range(self.calibrate_tensors_range, new_calibrate_tensors_range)
|
| 531 |
+
else:
|
| 532 |
+
self.calibrate_tensors_range = new_calibrate_tensors_range
|
| 533 |
+
|
| 534 |
+
return self.calibrate_tensors_range
|
| 535 |
+
|
| 536 |
+
|
| 537 |
+
class HistogramCalibrater(CalibraterBase):
|
| 538 |
+
def __init__(
|
| 539 |
+
self,
|
| 540 |
+
model_path: str | Path,
|
| 541 |
+
op_types_to_calibrate: Sequence[str] | None = None,
|
| 542 |
+
augmented_model_path="augmented_model.onnx",
|
| 543 |
+
use_external_data_format=False,
|
| 544 |
+
method="percentile",
|
| 545 |
+
symmetric=False,
|
| 546 |
+
num_bins=128,
|
| 547 |
+
num_quantized_bins=2048,
|
| 548 |
+
percentile=99.999,
|
| 549 |
+
scenario="same",
|
| 550 |
+
):
|
| 551 |
+
"""
|
| 552 |
+
:param model_path: ONNX model to calibrate. It is a model path.
|
| 553 |
+
:param op_types_to_calibrate: operator types to calibrate. By default, calibrate all the float32/float16 tensors.
|
| 554 |
+
:param augmented_model_path: save augmented model to this path.
|
| 555 |
+
:param use_external_data_format: use external data format to store model which size is >= 2Gb
|
| 556 |
+
:param method: A string. One of ['entropy', 'percentile'].
|
| 557 |
+
:param symmetric: make range of tensor symmetric (central point is 0).
|
| 558 |
+
:param num_bins: number of bins to create a new histogram for collecting tensor values.
|
| 559 |
+
:param num_quantized_bins: number of quantized bins. Default 128.
|
| 560 |
+
:param percentile: A float number between [0, 100]. Default 99.99.
|
| 561 |
+
:param scenario: see :class:`DistributionCalibrater`
|
| 562 |
+
"""
|
| 563 |
+
super().__init__(
|
| 564 |
+
model_path,
|
| 565 |
+
op_types_to_calibrate=op_types_to_calibrate,
|
| 566 |
+
augmented_model_path=augmented_model_path,
|
| 567 |
+
symmetric=symmetric,
|
| 568 |
+
use_external_data_format=use_external_data_format,
|
| 569 |
+
)
|
| 570 |
+
self.intermediate_outputs = []
|
| 571 |
+
self.calibrate_tensors_range = None
|
| 572 |
+
self.num_model_outputs = len(self.model.graph.output)
|
| 573 |
+
self.model_original_outputs = {output.name for output in self.model.graph.output}
|
| 574 |
+
self.collector = None
|
| 575 |
+
self.method = method
|
| 576 |
+
self.num_bins = num_bins
|
| 577 |
+
self.num_quantized_bins = num_quantized_bins
|
| 578 |
+
self.percentile = percentile
|
| 579 |
+
self.tensors_to_calibrate = None
|
| 580 |
+
self.scenario = scenario
|
| 581 |
+
|
| 582 |
+
def augment_graph(self):
|
| 583 |
+
"""
|
| 584 |
+
make all quantization_candidates op type nodes as part of the graph output.
|
| 585 |
+
:return: augmented ONNX model
|
| 586 |
+
"""
|
| 587 |
+
self.tensors_to_calibrate, value_infos = self.select_tensors_to_calibrate(self.model)
|
| 588 |
+
for tensor in self.tensors_to_calibrate:
|
| 589 |
+
if tensor not in self.model_original_outputs:
|
| 590 |
+
self.model.graph.output.append(value_infos[tensor])
|
| 591 |
+
|
| 592 |
+
onnx.save(
|
| 593 |
+
self.model,
|
| 594 |
+
self.augmented_model_path,
|
| 595 |
+
save_as_external_data=self.use_external_data_format,
|
| 596 |
+
)
|
| 597 |
+
|
| 598 |
+
def clear_collected_data(self):
|
| 599 |
+
self.intermediate_outputs = []
|
| 600 |
+
|
| 601 |
+
def collect_data(self, data_reader: CalibrationDataReader):
|
| 602 |
+
"""
|
| 603 |
+
Entropy Calibrator collects operators' tensors as well as generates tensor histogram for each operator.
|
| 604 |
+
"""
|
| 605 |
+
input_names_set = {node_arg.name for node_arg in self.infer_session.get_inputs()}
|
| 606 |
+
output_names = [node_arg.name for node_arg in self.infer_session.get_outputs()]
|
| 607 |
+
|
| 608 |
+
while True:
|
| 609 |
+
inputs = data_reader.get_next()
|
| 610 |
+
if not inputs:
|
| 611 |
+
break
|
| 612 |
+
outputs = self.infer_session.run(None, inputs)
|
| 613 |
+
|
| 614 |
+
# Copy np.ndarray only for graph outputs that are also graph inputs to workaround bug:
|
| 615 |
+
# https://github.com/microsoft/onnxruntime/issues/21922
|
| 616 |
+
fixed_outputs = []
|
| 617 |
+
for output_index, output in enumerate(outputs):
|
| 618 |
+
if output_names[output_index] in input_names_set:
|
| 619 |
+
fixed_outputs.append(copy.copy(output))
|
| 620 |
+
else:
|
| 621 |
+
fixed_outputs.append(output)
|
| 622 |
+
|
| 623 |
+
self.intermediate_outputs.append(fixed_outputs)
|
| 624 |
+
|
| 625 |
+
if len(self.intermediate_outputs) == 0:
|
| 626 |
+
raise ValueError("No data is collected.")
|
| 627 |
+
|
| 628 |
+
output_dicts_list = [
|
| 629 |
+
dict(zip(output_names, intermediate_output, strict=False))
|
| 630 |
+
for intermediate_output in self.intermediate_outputs
|
| 631 |
+
]
|
| 632 |
+
|
| 633 |
+
merged_dict = {}
|
| 634 |
+
for d in output_dicts_list:
|
| 635 |
+
for k, v in d.items():
|
| 636 |
+
merged_dict.setdefault(k, []).append(v)
|
| 637 |
+
|
| 638 |
+
clean_merged_dict = {i: merged_dict[i] for i in merged_dict if i in self.tensors_to_calibrate}
|
| 639 |
+
|
| 640 |
+
if not self.collector:
|
| 641 |
+
self.collector = HistogramCollector(
|
| 642 |
+
method=self.method,
|
| 643 |
+
symmetric=self.symmetric,
|
| 644 |
+
num_bins=self.num_bins,
|
| 645 |
+
num_quantized_bins=self.num_quantized_bins,
|
| 646 |
+
percentile=self.percentile,
|
| 647 |
+
scenario=self.scenario,
|
| 648 |
+
)
|
| 649 |
+
self.collector.collect(clean_merged_dict)
|
| 650 |
+
|
| 651 |
+
self.clear_collected_data()
|
| 652 |
+
|
| 653 |
+
def compute_data(self) -> TensorsData:
|
| 654 |
+
"""
|
| 655 |
+
Compute the min-max range of tensor
|
| 656 |
+
:return: dictionary mapping: {tensor name: (min value, max value)}
|
| 657 |
+
"""
|
| 658 |
+
if not self.collector:
|
| 659 |
+
raise ValueError("No collector created and can't generate calibration data.")
|
| 660 |
+
|
| 661 |
+
if isinstance(self, EntropyCalibrater):
|
| 662 |
+
cal = CalibrationMethod.Entropy
|
| 663 |
+
elif isinstance(self, PercentileCalibrater):
|
| 664 |
+
cal = CalibrationMethod.Percentile
|
| 665 |
+
elif isinstance(self, DistributionCalibrater):
|
| 666 |
+
cal = CalibrationMethod.Distribution
|
| 667 |
+
else:
|
| 668 |
+
raise TypeError(f"Unknown calibrater {type(self)}. This method must be overwritten.")
|
| 669 |
+
return TensorsData(cal, self.collector.compute_collection_result())
|
| 670 |
+
|
| 671 |
+
|
| 672 |
+
class EntropyCalibrater(HistogramCalibrater):
|
| 673 |
+
def __init__(
|
| 674 |
+
self,
|
| 675 |
+
model_path: str | Path,
|
| 676 |
+
op_types_to_calibrate: Sequence[str] | None = None,
|
| 677 |
+
augmented_model_path="augmented_model.onnx",
|
| 678 |
+
use_external_data_format=False,
|
| 679 |
+
method="entropy",
|
| 680 |
+
symmetric=False,
|
| 681 |
+
num_bins=128,
|
| 682 |
+
num_quantized_bins=128,
|
| 683 |
+
):
|
| 684 |
+
"""
|
| 685 |
+
:param model_path: ONNX model to calibrate. It is a model path
|
| 686 |
+
:param op_types_to_calibrate: operator types to calibrate. By default, calibrate all the float32/float16 tensors.
|
| 687 |
+
:param augmented_model_path: save augmented model to this path.
|
| 688 |
+
:param use_external_data_format: use external data format to store model which size is >= 2Gb
|
| 689 |
+
:param method: A string. One of ['entropy', 'percentile', 'distribution'].
|
| 690 |
+
:param symmetric: make range of tensor symmetric (central point is 0).
|
| 691 |
+
:param num_bins: number of bins to create a new histogram for collecting tensor values.
|
| 692 |
+
:param num_quantized_bins: number of quantized bins. Default 128.
|
| 693 |
+
"""
|
| 694 |
+
super().__init__(
|
| 695 |
+
model_path,
|
| 696 |
+
op_types_to_calibrate,
|
| 697 |
+
augmented_model_path,
|
| 698 |
+
use_external_data_format,
|
| 699 |
+
method=method,
|
| 700 |
+
symmetric=symmetric,
|
| 701 |
+
num_bins=num_bins,
|
| 702 |
+
num_quantized_bins=num_quantized_bins,
|
| 703 |
+
)
|
| 704 |
+
|
| 705 |
+
|
| 706 |
+
class PercentileCalibrater(HistogramCalibrater):
|
| 707 |
+
def __init__(
|
| 708 |
+
self,
|
| 709 |
+
model_path: str | Path,
|
| 710 |
+
op_types_to_calibrate: Sequence[str] | None = None,
|
| 711 |
+
augmented_model_path="augmented_model.onnx",
|
| 712 |
+
use_external_data_format=False,
|
| 713 |
+
method="percentile",
|
| 714 |
+
symmetric=False,
|
| 715 |
+
num_bins=2048,
|
| 716 |
+
percentile=99.999,
|
| 717 |
+
):
|
| 718 |
+
"""
|
| 719 |
+
:param model_path: ONNX model to calibrate. It is a model path
|
| 720 |
+
:param op_types_to_calibrate: operator types to calibrate. By default, calibrate all the float32/float16 tensors.
|
| 721 |
+
:param augmented_model_path: save augmented model to this path.
|
| 722 |
+
:param use_external_data_format: use external data format to store model which size is >= 2Gb
|
| 723 |
+
:param method: A string. One of ['entropy', 'percentile', 'distribution'].
|
| 724 |
+
:param symmetric: make range of tensor symmetric (central point is 0).
|
| 725 |
+
:param num_quantized_bins: number of quantized bins. Default 128.
|
| 726 |
+
:param percentile: A float number between [0, 100]. Default 99.99.
|
| 727 |
+
"""
|
| 728 |
+
super().__init__(
|
| 729 |
+
model_path,
|
| 730 |
+
op_types_to_calibrate,
|
| 731 |
+
augmented_model_path,
|
| 732 |
+
use_external_data_format,
|
| 733 |
+
method=method,
|
| 734 |
+
symmetric=symmetric,
|
| 735 |
+
num_bins=num_bins,
|
| 736 |
+
percentile=percentile,
|
| 737 |
+
)
|
| 738 |
+
|
| 739 |
+
|
| 740 |
+
class DistributionCalibrater(HistogramCalibrater):
|
| 741 |
+
def __init__(
|
| 742 |
+
self,
|
| 743 |
+
model_path: str | Path,
|
| 744 |
+
op_types_to_calibrate: Sequence[str] | None = None,
|
| 745 |
+
augmented_model_path="augmented_model.onnx",
|
| 746 |
+
use_external_data_format=False,
|
| 747 |
+
method="distribution",
|
| 748 |
+
num_bins=128,
|
| 749 |
+
scenario="same",
|
| 750 |
+
):
|
| 751 |
+
"""
|
| 752 |
+
:param model_path: ONNX model to calibrate. It is a model path
|
| 753 |
+
:param op_types_to_calibrate: operator types to calibrate. By default, calibrate all the float32/float16 tensors.
|
| 754 |
+
:param augmented_model_path: save augmented model to this path.
|
| 755 |
+
:param use_external_data_format: use external data format to store model which size is >= 2Gb
|
| 756 |
+
:param method: A string. One of ['entropy', 'percentile', 'distribution'].
|
| 757 |
+
:param symmetric: make range of tensor symmetric (central point is 0).
|
| 758 |
+
:param num_bins: number of bins to create a new histogram for collecting tensor values.
|
| 759 |
+
:param scenario: for float 8 only, if `scenario="same"`,
|
| 760 |
+
the algorithm weights and float 8 follow the same distribution,
|
| 761 |
+
if `scenario="p3"`, it assumes the weights follow
|
| 762 |
+
a gaussian law and float 8 ~ X^3 where X is a gaussian law
|
| 763 |
+
"""
|
| 764 |
+
super().__init__(
|
| 765 |
+
model_path,
|
| 766 |
+
op_types_to_calibrate,
|
| 767 |
+
augmented_model_path,
|
| 768 |
+
use_external_data_format,
|
| 769 |
+
method=method,
|
| 770 |
+
num_bins=num_bins,
|
| 771 |
+
scenario=scenario,
|
| 772 |
+
)
|
| 773 |
+
|
| 774 |
+
|
| 775 |
+
class CalibrationDataCollector(metaclass=abc.ABCMeta):
|
| 776 |
+
"""
|
| 777 |
+
Base class for collecting data for calibration-based quantization.
|
| 778 |
+
"""
|
| 779 |
+
|
| 780 |
+
@abc.abstractmethod
|
| 781 |
+
def collect(self, name_to_arr):
|
| 782 |
+
"""
|
| 783 |
+
Generate informative data based on given data.
|
| 784 |
+
name_to_arr : dict
|
| 785 |
+
tensor name to NDArray data
|
| 786 |
+
"""
|
| 787 |
+
raise NotImplementedError
|
| 788 |
+
|
| 789 |
+
@abc.abstractmethod
|
| 790 |
+
def compute_collection_result(self):
|
| 791 |
+
"""
|
| 792 |
+
Get the optimal result among collection data.
|
| 793 |
+
"""
|
| 794 |
+
raise NotImplementedError
|
| 795 |
+
|
| 796 |
+
|
| 797 |
+
class HistogramCollector(CalibrationDataCollector):
|
| 798 |
+
"""
|
| 799 |
+
Collecting histogram for each tensor. Percentile and Entropy method are supported.
|
| 800 |
+
|
| 801 |
+
ref: https://github.com//apache/incubator-mxnet/blob/master/python/mxnet/contrib/quantization.py
|
| 802 |
+
ref: https://docs.nvidia.com/deeplearning/tensorrt/pytorch-quantization-toolkit/docs/_modules/
|
| 803 |
+
pytorch_quantization/calib/histogram.html
|
| 804 |
+
"""
|
| 805 |
+
|
| 806 |
+
def __init__(self, method, symmetric, num_bins, num_quantized_bins, percentile, scenario):
|
| 807 |
+
self.histogram_dict = {}
|
| 808 |
+
self.method = method
|
| 809 |
+
self.symmetric = symmetric
|
| 810 |
+
self.num_bins = num_bins
|
| 811 |
+
self.num_quantized_bins = num_quantized_bins
|
| 812 |
+
self.percentile = percentile
|
| 813 |
+
self.scenario = scenario
|
| 814 |
+
|
| 815 |
+
def get_histogram_dict(self):
|
| 816 |
+
return self.histogram_dict
|
| 817 |
+
|
| 818 |
+
def collect(self, name_to_arr):
|
| 819 |
+
print("Collecting tensor data and making histogram ...")
|
| 820 |
+
|
| 821 |
+
# TODO: Currently we have different collect() for entropy and percentile method respectively.
|
| 822 |
+
# Need unified collect in the future.
|
| 823 |
+
if self.method in {"distribution", "entropy"}:
|
| 824 |
+
return self.collect_value(name_to_arr)
|
| 825 |
+
elif self.method == "percentile":
|
| 826 |
+
if self.symmetric:
|
| 827 |
+
return self.collect_absolute_value(name_to_arr)
|
| 828 |
+
else:
|
| 829 |
+
return self.collect_value(name_to_arr)
|
| 830 |
+
else:
|
| 831 |
+
raise ValueError("Only 'entropy', 'percentile' or 'distribution' methods are supported")
|
| 832 |
+
|
| 833 |
+
def collect_absolute_value(self, name_to_arr):
|
| 834 |
+
"""
|
| 835 |
+
Collect histogram on absolute value
|
| 836 |
+
"""
|
| 837 |
+
for tensor, data_arr in name_to_arr.items():
|
| 838 |
+
if isinstance(data_arr, list):
|
| 839 |
+
for arr in data_arr:
|
| 840 |
+
assert isinstance(arr, np.ndarray), f"Unexpected type {type(arr)} for tensor={tensor!r}"
|
| 841 |
+
dtypes = {a.dtype for a in data_arr}
|
| 842 |
+
assert len(dtypes) == 1, (
|
| 843 |
+
f"The calibration expects only one element type but got {dtypes} for tensor={tensor!r}"
|
| 844 |
+
)
|
| 845 |
+
data_arr_np = np.asarray(data_arr)
|
| 846 |
+
elif not isinstance(data_arr, np.ndarray):
|
| 847 |
+
raise ValueError(f"Unexpected type {type(data_arr)} for tensor={tensor!r}")
|
| 848 |
+
else:
|
| 849 |
+
data_arr_np = data_arr
|
| 850 |
+
data_arr_np = data_arr_np.flatten()
|
| 851 |
+
if data_arr_np.size > 0:
|
| 852 |
+
min_value = np.nanmin(data_arr_np)
|
| 853 |
+
max_value = np.nanmax(data_arr_np)
|
| 854 |
+
else:
|
| 855 |
+
min_value = np.array(0, dtype=data_arr_np.dtype)
|
| 856 |
+
max_value = np.array(0, dtype=data_arr_np.dtype)
|
| 857 |
+
|
| 858 |
+
data_arr_np = np.absolute(data_arr_np) # only consider absolute value
|
| 859 |
+
|
| 860 |
+
if tensor not in self.histogram_dict:
|
| 861 |
+
# first time it uses num_bins to compute histogram.
|
| 862 |
+
hist, hist_edges = np.histogram(data_arr_np, bins=self.num_bins)
|
| 863 |
+
hist_edges = hist_edges.astype(data_arr_np.dtype)
|
| 864 |
+
assert data_arr_np.dtype != np.float64, (
|
| 865 |
+
"only float32 or float16 is supported, every constant must be explicitly typed"
|
| 866 |
+
)
|
| 867 |
+
self.histogram_dict[tensor] = (hist, hist_edges, min_value, max_value)
|
| 868 |
+
else:
|
| 869 |
+
old_histogram = self.histogram_dict[tensor]
|
| 870 |
+
old_min = old_histogram[2]
|
| 871 |
+
old_max = old_histogram[3]
|
| 872 |
+
assert hasattr(old_min, "dtype"), f"old_min should be a numpy array but is {type(old_min)}"
|
| 873 |
+
assert hasattr(old_max, "dtype"), f"old_min should be a numpy array but is {type(old_max)}"
|
| 874 |
+
old_hist = old_histogram[0]
|
| 875 |
+
old_hist_edges = old_histogram[1]
|
| 876 |
+
temp_amax = np.nanmax(data_arr_np)
|
| 877 |
+
if temp_amax > old_hist_edges[-1]:
|
| 878 |
+
# increase the number of bins
|
| 879 |
+
width = old_hist_edges[1] - old_hist_edges[0]
|
| 880 |
+
# NOTE: np.arange may create an extra bin after the one containing temp_amax
|
| 881 |
+
new_bin_edges = np.arange(old_hist_edges[-1] + width, temp_amax + width, width)
|
| 882 |
+
old_hist_edges = np.hstack((old_hist_edges, new_bin_edges))
|
| 883 |
+
hist, hist_edges = np.histogram(data_arr_np, bins=old_hist_edges)
|
| 884 |
+
hist_edges = hist_edges.astype(data_arr_np.dtype)
|
| 885 |
+
hist[: len(old_hist)] += old_hist
|
| 886 |
+
assert data_arr_np.dtype != np.float64, (
|
| 887 |
+
"only float32 or float16 is supported, every constant must be explicitly typed"
|
| 888 |
+
)
|
| 889 |
+
self.histogram_dict[tensor] = (hist, hist_edges, min(old_min, min_value), max(old_max, max_value))
|
| 890 |
+
|
| 891 |
+
def collect_value(self, name_to_arr):
|
| 892 |
+
"""
|
| 893 |
+
Collect histogram on real value
|
| 894 |
+
"""
|
| 895 |
+
for tensor, data_arr in name_to_arr.items():
|
| 896 |
+
data_arr = np.asarray(data_arr) # noqa: PLW2901
|
| 897 |
+
data_arr = data_arr.flatten() # noqa: PLW2901
|
| 898 |
+
|
| 899 |
+
if data_arr.size > 0:
|
| 900 |
+
min_value = np.nanmin(data_arr)
|
| 901 |
+
max_value = np.nanmax(data_arr)
|
| 902 |
+
else:
|
| 903 |
+
min_value = np.array(0, dtype=data_arr.dtype)
|
| 904 |
+
max_value = np.array(0, dtype=data_arr.dtype)
|
| 905 |
+
|
| 906 |
+
threshold = np.array(max(abs(min_value), abs(max_value)), dtype=data_arr.dtype)
|
| 907 |
+
|
| 908 |
+
if tensor in self.histogram_dict:
|
| 909 |
+
old_histogram = self.histogram_dict[tensor]
|
| 910 |
+
self.histogram_dict[tensor] = self.merge_histogram(
|
| 911 |
+
old_histogram, data_arr, min_value, max_value, threshold
|
| 912 |
+
)
|
| 913 |
+
else:
|
| 914 |
+
hist, hist_edges = np.histogram(data_arr, self.num_bins, range=(-threshold, threshold))
|
| 915 |
+
self.histogram_dict[tensor] = (
|
| 916 |
+
hist,
|
| 917 |
+
hist_edges,
|
| 918 |
+
min_value,
|
| 919 |
+
max_value,
|
| 920 |
+
threshold,
|
| 921 |
+
)
|
| 922 |
+
|
| 923 |
+
def merge_histogram(self, old_histogram, data_arr, new_min, new_max, new_threshold):
|
| 924 |
+
(old_hist, old_hist_edges, old_min, old_max, old_threshold) = old_histogram
|
| 925 |
+
|
| 926 |
+
if new_threshold <= old_threshold:
|
| 927 |
+
new_hist, _ = np.histogram(data_arr, len(old_hist), range=(-old_threshold, old_threshold))
|
| 928 |
+
return (
|
| 929 |
+
new_hist + old_hist,
|
| 930 |
+
old_hist_edges,
|
| 931 |
+
min(old_min, new_min),
|
| 932 |
+
max(old_max, new_max),
|
| 933 |
+
old_threshold,
|
| 934 |
+
)
|
| 935 |
+
else:
|
| 936 |
+
if old_threshold == 0:
|
| 937 |
+
hist, hist_edges = np.histogram(data_arr, len(old_hist), range=(-new_threshold, new_threshold))
|
| 938 |
+
hist += old_hist
|
| 939 |
+
else:
|
| 940 |
+
old_num_bins = len(old_hist)
|
| 941 |
+
old_stride = 2 * old_threshold / old_num_bins
|
| 942 |
+
half_increased_bins = int((new_threshold - old_threshold) // old_stride + 1)
|
| 943 |
+
new_num_bins = old_num_bins + 2 * half_increased_bins
|
| 944 |
+
new_threshold = half_increased_bins * old_stride + old_threshold
|
| 945 |
+
hist, hist_edges = np.histogram(data_arr, new_num_bins, range=(-new_threshold, new_threshold))
|
| 946 |
+
hist[half_increased_bins : new_num_bins - half_increased_bins] += old_hist
|
| 947 |
+
return (
|
| 948 |
+
hist,
|
| 949 |
+
hist_edges,
|
| 950 |
+
min(old_min, new_min),
|
| 951 |
+
max(old_max, new_max),
|
| 952 |
+
new_threshold,
|
| 953 |
+
)
|
| 954 |
+
|
| 955 |
+
def compute_collection_result(self):
|
| 956 |
+
if not self.histogram_dict or len(self.histogram_dict) == 0:
|
| 957 |
+
raise ValueError("Histogram has not been collected. Please run collect() first.")
|
| 958 |
+
print(f"Finding optimal threshold for each tensor using {self.method!r} algorithm ...")
|
| 959 |
+
|
| 960 |
+
if self.method == "entropy":
|
| 961 |
+
return self.compute_entropy()
|
| 962 |
+
elif self.method == "percentile":
|
| 963 |
+
return self.compute_percentile()
|
| 964 |
+
elif self.method == "distribution":
|
| 965 |
+
return self.compute_distribution()
|
| 966 |
+
else:
|
| 967 |
+
raise ValueError("Only 'entropy', 'percentile' or 'distribution' methods are supported")
|
| 968 |
+
|
| 969 |
+
def compute_percentile(self):
|
| 970 |
+
if self.percentile < 0 or self.percentile > 100:
|
| 971 |
+
raise ValueError("Invalid percentile. Must be in range 0 <= percentile <= 100.")
|
| 972 |
+
|
| 973 |
+
histogram_dict = self.histogram_dict
|
| 974 |
+
percentile = self.percentile
|
| 975 |
+
|
| 976 |
+
thresholds_dict = {} # per tensor thresholds
|
| 977 |
+
|
| 978 |
+
print(f"Number of tensors : {len(histogram_dict)}")
|
| 979 |
+
print(f"Number of histogram bins : {self.num_bins}")
|
| 980 |
+
print(f"Percentile : ({100.0 - percentile},{percentile})")
|
| 981 |
+
|
| 982 |
+
for tensor, histogram in histogram_dict.items():
|
| 983 |
+
hist = histogram[0]
|
| 984 |
+
hist_edges = histogram[1]
|
| 985 |
+
total = hist.sum()
|
| 986 |
+
cdf = np.cumsum(hist / total)
|
| 987 |
+
if self.symmetric:
|
| 988 |
+
idx_right = np.searchsorted(cdf, percentile / 100.0)
|
| 989 |
+
|
| 990 |
+
thresholds_dict[tensor] = (
|
| 991 |
+
-np.array(hist_edges[idx_right], dtype=hist_edges.dtype),
|
| 992 |
+
np.array(hist_edges[idx_right], dtype=hist_edges.dtype),
|
| 993 |
+
)
|
| 994 |
+
else:
|
| 995 |
+
percent_to_cut_one_side = (100.0 - percentile) / 200.0
|
| 996 |
+
idx_right = np.searchsorted(cdf, 1.0 - percent_to_cut_one_side)
|
| 997 |
+
idx_left = np.searchsorted(cdf, percent_to_cut_one_side)
|
| 998 |
+
thresholds_dict[tensor] = (
|
| 999 |
+
np.array(hist_edges[idx_left], dtype=hist_edges.dtype),
|
| 1000 |
+
np.array(hist_edges[idx_right], dtype=hist_edges.dtype),
|
| 1001 |
+
)
|
| 1002 |
+
min_value = histogram[2]
|
| 1003 |
+
max_value = histogram[3]
|
| 1004 |
+
if thresholds_dict[tensor][0] < min_value:
|
| 1005 |
+
thresholds_dict[tensor] = (min_value, thresholds_dict[tensor][1])
|
| 1006 |
+
if thresholds_dict[tensor][1] > max_value:
|
| 1007 |
+
thresholds_dict[tensor] = (thresholds_dict[tensor][0], max_value)
|
| 1008 |
+
thresholds_dict[tensor] = (*thresholds_dict[tensor], *hist[:2])
|
| 1009 |
+
# Plot histogram for debug only
|
| 1010 |
+
if os.environ.get("QUANTIZATION_DEBUG", "0") in (1, "1"):
|
| 1011 |
+
apply_plot(hist, hist_edges)
|
| 1012 |
+
|
| 1013 |
+
return thresholds_dict
|
| 1014 |
+
|
| 1015 |
+
def compute_entropy(self):
|
| 1016 |
+
histogram_dict = self.histogram_dict
|
| 1017 |
+
num_quantized_bins = self.num_quantized_bins
|
| 1018 |
+
|
| 1019 |
+
thresholds_dict = {} # per tensor thresholds
|
| 1020 |
+
|
| 1021 |
+
print(f"Number of tensors : {len(histogram_dict)}")
|
| 1022 |
+
print(f"Number of histogram bins : {self.num_bins} (The number may increase depends on the data it collects)")
|
| 1023 |
+
print(f"Number of quantized bins : {self.num_quantized_bins}")
|
| 1024 |
+
|
| 1025 |
+
for tensor, histogram in histogram_dict.items():
|
| 1026 |
+
optimal_threshold = self.get_entropy_threshold(histogram, num_quantized_bins)
|
| 1027 |
+
thresholds_dict[tensor] = optimal_threshold
|
| 1028 |
+
thresholds_dict[tensor] = (*optimal_threshold, *histogram[:2])
|
| 1029 |
+
|
| 1030 |
+
# Plot histogram for debug only
|
| 1031 |
+
if os.environ.get("QUANTIZATION_DEBUG", "0") in (1, "1"):
|
| 1032 |
+
apply_plot(histogram[0], histogram[1])
|
| 1033 |
+
|
| 1034 |
+
return thresholds_dict
|
| 1035 |
+
|
| 1036 |
+
@staticmethod
|
| 1037 |
+
def _avg_std(hist, hist_edges, power=1):
|
| 1038 |
+
if power <= 0:
|
| 1039 |
+
raise ValueError(f"power={power} <= 0 is invalid.")
|
| 1040 |
+
values = (hist_edges[:-1] + hist_edges[1:]) * 0.5
|
| 1041 |
+
if power == 1:
|
| 1042 |
+
avg = (hist * values).sum() / hist.sum()
|
| 1043 |
+
std = ((hist * values**2).sum() / hist.sum() - avg**2) ** 0.5
|
| 1044 |
+
return np.array(avg, dtype=hist_edges.dtype), np.array(std, dtype=hist_edges.dtype)
|
| 1045 |
+
if int(power) == power and int(power) % 2 == 1:
|
| 1046 |
+
avg = (hist * values**power).sum() / hist.sum()
|
| 1047 |
+
std = ((hist * (values**power - avg) ** 2).sum() / hist.sum()) ** 0.5
|
| 1048 |
+
return np.array(avg, dtype=hist_edges.dtype), np.array(std, dtype=hist_edges.dtype)
|
| 1049 |
+
|
| 1050 |
+
fact = np.abs(values) / values
|
| 1051 |
+
fact[np.isnan(fact)] = 1
|
| 1052 |
+
fact[np.isinf(fact)] = 1
|
| 1053 |
+
values = np.abs(values) ** power * fact
|
| 1054 |
+
avg = (hist * values).sum() / hist.sum()
|
| 1055 |
+
std = ((hist * values**2).sum() / hist.sum() - avg**2) ** 0.5
|
| 1056 |
+
return np.array(avg, dtype=hist_edges.dtype), np.array(std, dtype=hist_edges.dtype)
|
| 1057 |
+
|
| 1058 |
+
def compute_distribution(self):
|
| 1059 |
+
if self.num_bins < 512:
|
| 1060 |
+
raise ValueError("Invalid num_bins. Must be in range 512 <= num_bins.")
|
| 1061 |
+
|
| 1062 |
+
histogram_dict = self.histogram_dict
|
| 1063 |
+
thresholds_dict = {} # per tensor thresholds
|
| 1064 |
+
|
| 1065 |
+
print(f"Number of tensors : {len(histogram_dict)}")
|
| 1066 |
+
print(f"Number of histogram bins : {self.num_bins}")
|
| 1067 |
+
print(f"Scenario : {self.scenario!r})")
|
| 1068 |
+
|
| 1069 |
+
for tensor, histogram in histogram_dict.items():
|
| 1070 |
+
hist = histogram[0]
|
| 1071 |
+
hist_edges = histogram[1]
|
| 1072 |
+
|
| 1073 |
+
assert hist_edges.dtype != np.float64
|
| 1074 |
+
if self.scenario == "same":
|
| 1075 |
+
avg_coef, std_coef = self._avg_std(hist, hist_edges, power=1)
|
| 1076 |
+
elif self.scenario == "p3":
|
| 1077 |
+
avg_coef, std_coef = self._avg_std(hist, hist_edges, power=1.0 / 3.0)
|
| 1078 |
+
else:
|
| 1079 |
+
raise ValueError("Invalid scenario. Must be in {'same', 'p3'}.")
|
| 1080 |
+
assert avg_coef.dtype != np.float64
|
| 1081 |
+
assert std_coef.dtype != np.float64
|
| 1082 |
+
assert hist_edges.dtype != np.float64
|
| 1083 |
+
thresholds_dict[tensor] = TensorData(
|
| 1084 |
+
avg=avg_coef,
|
| 1085 |
+
std=std_coef,
|
| 1086 |
+
hist=hist,
|
| 1087 |
+
hist_edges=hist_edges,
|
| 1088 |
+
lowest=hist_edges.min(),
|
| 1089 |
+
highest=hist_edges.max(),
|
| 1090 |
+
)
|
| 1091 |
+
|
| 1092 |
+
# Plot histogram for debug only
|
| 1093 |
+
if os.environ.get("QUANTIZATION_DEBUG", "0") in (1, "1"):
|
| 1094 |
+
apply_plot(hist, hist_edges)
|
| 1095 |
+
|
| 1096 |
+
return thresholds_dict
|
| 1097 |
+
|
| 1098 |
+
def get_entropy_threshold(self, histogram, num_quantized_bins):
|
| 1099 |
+
"""Given a dataset, find the optimal threshold for quantizing it.
|
| 1100 |
+
The reference distribution is `q`, and the candidate distribution is `p`.
|
| 1101 |
+
`q` is a truncated version of the original distribution.
|
| 1102 |
+
Ref: http://on-demand.gputechconf.com/gtc/2017/presentation/s7310-8-bit-inference-with-tensorrt.pdf
|
| 1103 |
+
"""
|
| 1104 |
+
hist = histogram[0]
|
| 1105 |
+
hist_edges = histogram[1]
|
| 1106 |
+
num_bins = hist.size
|
| 1107 |
+
zero_bin_index = num_bins // 2
|
| 1108 |
+
num_half_quantized_bin = num_quantized_bins // 2
|
| 1109 |
+
|
| 1110 |
+
dtype = histogram[1].dtype
|
| 1111 |
+
kl_divergence = np.zeros(zero_bin_index - num_half_quantized_bin + 1)
|
| 1112 |
+
thresholds = [(np.array(0, dtype=dtype), np.array(0, dtype=dtype)) for i in range(kl_divergence.size)]
|
| 1113 |
+
|
| 1114 |
+
# <------------ num bins ---------------->
|
| 1115 |
+
# <--- quantized bins ---->
|
| 1116 |
+
# |======|===========|===========|=======|
|
| 1117 |
+
# zero bin index
|
| 1118 |
+
# ^ ^
|
| 1119 |
+
# | |
|
| 1120 |
+
# start index end index (start of iteration)
|
| 1121 |
+
# ^ ^
|
| 1122 |
+
# | |
|
| 1123 |
+
# start index end index ...
|
| 1124 |
+
# ^ ^
|
| 1125 |
+
# | |
|
| 1126 |
+
# start index end index (end of iteration)
|
| 1127 |
+
|
| 1128 |
+
for i in range(num_half_quantized_bin, zero_bin_index + 1, 1):
|
| 1129 |
+
start_index = zero_bin_index - i
|
| 1130 |
+
end_index = min(zero_bin_index + i + 1, num_bins)
|
| 1131 |
+
|
| 1132 |
+
thresholds[i - num_half_quantized_bin] = (hist_edges[start_index], hist_edges[end_index])
|
| 1133 |
+
|
| 1134 |
+
sliced_distribution = copy.deepcopy(hist[start_index:end_index])
|
| 1135 |
+
|
| 1136 |
+
# reference distribution p
|
| 1137 |
+
p = sliced_distribution.copy() # a copy of np array
|
| 1138 |
+
left_outliers_count = sum(hist[:start_index])
|
| 1139 |
+
right_outliers_count = sum(hist[end_index:])
|
| 1140 |
+
p[0] += left_outliers_count
|
| 1141 |
+
p[-1] += right_outliers_count
|
| 1142 |
+
|
| 1143 |
+
# nonzeros[i] incidates whether p[i] is non-zero
|
| 1144 |
+
nonzeros = (p != 0).astype(np.int64)
|
| 1145 |
+
|
| 1146 |
+
# quantize p.size bins into quantized bins (default 128 bins)
|
| 1147 |
+
quantized_bins = np.zeros(num_quantized_bins, dtype=np.int64)
|
| 1148 |
+
num_merged_bins = sliced_distribution.size // num_quantized_bins
|
| 1149 |
+
|
| 1150 |
+
# merge bins into quantized bins
|
| 1151 |
+
for index in range(num_quantized_bins):
|
| 1152 |
+
start = index * num_merged_bins
|
| 1153 |
+
end = start + num_merged_bins
|
| 1154 |
+
quantized_bins[index] = sum(sliced_distribution[start:end])
|
| 1155 |
+
quantized_bins[-1] += sum(sliced_distribution[num_quantized_bins * num_merged_bins :])
|
| 1156 |
+
|
| 1157 |
+
# in order to compare p and q, we need to make length of q equals to length of p
|
| 1158 |
+
# expand quantized bins into p.size bins
|
| 1159 |
+
q = np.zeros(p.size, dtype=np.int64)
|
| 1160 |
+
for index in range(num_quantized_bins):
|
| 1161 |
+
start = index * num_merged_bins
|
| 1162 |
+
end = start + num_merged_bins
|
| 1163 |
+
|
| 1164 |
+
norm = sum(nonzeros[start:end])
|
| 1165 |
+
if norm != 0:
|
| 1166 |
+
q[start:end] = quantized_bins[index] / norm
|
| 1167 |
+
|
| 1168 |
+
p = smooth_distribution(p)
|
| 1169 |
+
q = smooth_distribution(q)
|
| 1170 |
+
if p is None or q is None:
|
| 1171 |
+
div = np.array(np.inf, dtype=dtype)
|
| 1172 |
+
else:
|
| 1173 |
+
div = np.array(entropy(p, q), dtype=dtype)
|
| 1174 |
+
kl_divergence[i - num_half_quantized_bin] = div
|
| 1175 |
+
|
| 1176 |
+
min_kl_divergence_idx = np.argmin(kl_divergence)
|
| 1177 |
+
optimal_threshold = thresholds[min_kl_divergence_idx]
|
| 1178 |
+
min_value = histogram[2]
|
| 1179 |
+
max_value = histogram[3]
|
| 1180 |
+
if optimal_threshold[0] < min_value:
|
| 1181 |
+
optimal_threshold = (min_value, optimal_threshold[1])
|
| 1182 |
+
if optimal_threshold[1] > max_value:
|
| 1183 |
+
optimal_threshold = (optimal_threshold[0], max_value)
|
| 1184 |
+
assert hasattr(optimal_threshold[0], "dtype")
|
| 1185 |
+
assert hasattr(optimal_threshold[1], "dtype")
|
| 1186 |
+
return optimal_threshold
|
| 1187 |
+
|
| 1188 |
+
|
| 1189 |
+
def create_calibrator(
|
| 1190 |
+
model: str | Path,
|
| 1191 |
+
op_types_to_calibrate: Sequence[str] | None = None,
|
| 1192 |
+
augmented_model_path="augmented_model.onnx",
|
| 1193 |
+
calibrate_method=CalibrationMethod.MinMax,
|
| 1194 |
+
use_external_data_format=False,
|
| 1195 |
+
providers=None,
|
| 1196 |
+
extra_options={}, # noqa: B006
|
| 1197 |
+
):
|
| 1198 |
+
calibrator = None
|
| 1199 |
+
if calibrate_method == CalibrationMethod.MinMax:
|
| 1200 |
+
# default settings for min-max algorithm
|
| 1201 |
+
symmetric = extra_options.get("symmetric", False)
|
| 1202 |
+
moving_average = extra_options.get("moving_average", False)
|
| 1203 |
+
averaging_constant = extra_options.get("averaging_constant", 0.01)
|
| 1204 |
+
max_intermediate_outputs = extra_options.get("max_intermediate_outputs", None)
|
| 1205 |
+
per_channel = extra_options.get("per_channel", False)
|
| 1206 |
+
calibrator = MinMaxCalibrater(
|
| 1207 |
+
model,
|
| 1208 |
+
op_types_to_calibrate,
|
| 1209 |
+
augmented_model_path,
|
| 1210 |
+
use_external_data_format=use_external_data_format,
|
| 1211 |
+
symmetric=symmetric,
|
| 1212 |
+
moving_average=moving_average,
|
| 1213 |
+
averaging_constant=averaging_constant,
|
| 1214 |
+
max_intermediate_outputs=max_intermediate_outputs,
|
| 1215 |
+
per_channel=per_channel,
|
| 1216 |
+
)
|
| 1217 |
+
elif calibrate_method == CalibrationMethod.Entropy:
|
| 1218 |
+
# default settings for entropy algorithm
|
| 1219 |
+
num_bins = extra_options.get("num_bins", 128)
|
| 1220 |
+
num_quantized_bins = extra_options.get("num_quantized_bins", 128)
|
| 1221 |
+
symmetric = extra_options.get("symmetric", False)
|
| 1222 |
+
calibrator = EntropyCalibrater(
|
| 1223 |
+
model,
|
| 1224 |
+
op_types_to_calibrate,
|
| 1225 |
+
augmented_model_path,
|
| 1226 |
+
use_external_data_format=use_external_data_format,
|
| 1227 |
+
symmetric=symmetric,
|
| 1228 |
+
num_bins=num_bins,
|
| 1229 |
+
num_quantized_bins=num_quantized_bins,
|
| 1230 |
+
)
|
| 1231 |
+
elif calibrate_method == CalibrationMethod.Percentile:
|
| 1232 |
+
# default settings for percentile algorithm
|
| 1233 |
+
num_bins = extra_options.get("num_bins", 2048)
|
| 1234 |
+
percentile = extra_options.get("percentile", 99.999)
|
| 1235 |
+
symmetric = extra_options.get("symmetric", True)
|
| 1236 |
+
calibrator = PercentileCalibrater(
|
| 1237 |
+
model,
|
| 1238 |
+
op_types_to_calibrate,
|
| 1239 |
+
augmented_model_path,
|
| 1240 |
+
use_external_data_format=use_external_data_format,
|
| 1241 |
+
symmetric=symmetric,
|
| 1242 |
+
num_bins=num_bins,
|
| 1243 |
+
percentile=percentile,
|
| 1244 |
+
)
|
| 1245 |
+
|
| 1246 |
+
elif calibrate_method == CalibrationMethod.Distribution:
|
| 1247 |
+
# default settings for percentile algorithm
|
| 1248 |
+
num_bins = extra_options.get("num_bins", 2048)
|
| 1249 |
+
scenario = extra_options.get("scenario", "same")
|
| 1250 |
+
|
| 1251 |
+
calibrator = DistributionCalibrater(
|
| 1252 |
+
model,
|
| 1253 |
+
op_types_to_calibrate,
|
| 1254 |
+
augmented_model_path,
|
| 1255 |
+
use_external_data_format=use_external_data_format,
|
| 1256 |
+
num_bins=num_bins,
|
| 1257 |
+
scenario=scenario,
|
| 1258 |
+
)
|
| 1259 |
+
|
| 1260 |
+
if calibrator:
|
| 1261 |
+
calibrator.augment_graph()
|
| 1262 |
+
if providers:
|
| 1263 |
+
calibrator.execution_providers = providers
|
| 1264 |
+
calibrator.create_inference_session()
|
| 1265 |
+
return calibrator
|
| 1266 |
+
|
| 1267 |
+
raise ValueError(f"Unsupported calibration method {calibrate_method}")
|
micromamba_root/envs/pytorch_env/Lib/site-packages/onnxruntime/quantization/fusions/__init__.py
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from .fusion import Fusion # noqa: F401
|
| 2 |
+
from .fusion_gelu import FusionGelu # noqa: F401
|
| 3 |
+
from .fusion_layernorm import FusionLayerNormalization # noqa: F401
|
| 4 |
+
from .replace_upsample_with_resize import ReplaceUpsampleWithResize # noqa: F401
|
micromamba_root/envs/pytorch_env/Lib/site-packages/onnxruntime/quantization/fusions/fusion.py
ADDED
|
@@ -0,0 +1,311 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -------------------------------------------------------------------------
|
| 2 |
+
# Copyright (c) Microsoft Corporation. All rights reserved.
|
| 3 |
+
# Licensed under the MIT License. See License.txt in the project root for
|
| 4 |
+
# license information.
|
| 5 |
+
# --------------------------------------------------------------------------
|
| 6 |
+
from __future__ import annotations
|
| 7 |
+
|
| 8 |
+
from collections import deque
|
| 9 |
+
|
| 10 |
+
import onnx
|
| 11 |
+
|
| 12 |
+
from ..onnx_model import ONNXModel
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
class Fusion:
|
| 16 |
+
"""
|
| 17 |
+
Base class for fusions.
|
| 18 |
+
"""
|
| 19 |
+
|
| 20 |
+
def __init__(self, model: ONNXModel, fused_op_type: str, search_op_type: str):
|
| 21 |
+
self.search_op_type: str = search_op_type
|
| 22 |
+
self.fused_op_type: str = fused_op_type
|
| 23 |
+
self.model: ONNXModel = model
|
| 24 |
+
self.nodes_to_remove: list = []
|
| 25 |
+
self.nodes_to_add: list = []
|
| 26 |
+
|
| 27 |
+
self._new_node_name_prefix = self.fused_op_type + "_fused_" + self.search_op_type + "_"
|
| 28 |
+
self._new_node_name_suffix = None # int|None used to create unique node names for the fused ops.
|
| 29 |
+
|
| 30 |
+
def fuse(
|
| 31 |
+
self,
|
| 32 |
+
node: onnx.NodeProto,
|
| 33 |
+
input_name_to_nodes: dict[str, list[onnx.NodeProto]],
|
| 34 |
+
output_name_to_node: dict[str, onnx.NodeProto],
|
| 35 |
+
):
|
| 36 |
+
"""
|
| 37 |
+
Interface function for derived fusion classes. Tries to fuse a node sequence containing
|
| 38 |
+
the specified node.
|
| 39 |
+
"""
|
| 40 |
+
raise NotImplementedError
|
| 41 |
+
|
| 42 |
+
def apply(self) -> bool:
|
| 43 |
+
"""
|
| 44 |
+
Apply graph fusion on the entire model graph.
|
| 45 |
+
"""
|
| 46 |
+
input_name_to_nodes = self.model.input_name_to_nodes()
|
| 47 |
+
output_name_to_node = self.model.output_name_to_node()
|
| 48 |
+
|
| 49 |
+
for node in self.model.nodes():
|
| 50 |
+
if node.op_type == self.search_op_type:
|
| 51 |
+
self.fuse(node, input_name_to_nodes, output_name_to_node)
|
| 52 |
+
|
| 53 |
+
self.model.remove_nodes(self.nodes_to_remove)
|
| 54 |
+
self.model.add_nodes(self.nodes_to_add)
|
| 55 |
+
|
| 56 |
+
graph_updated = bool(self.nodes_to_remove or self.nodes_to_add)
|
| 57 |
+
|
| 58 |
+
if graph_updated:
|
| 59 |
+
self.model.remove_unused_constant()
|
| 60 |
+
|
| 61 |
+
return graph_updated
|
| 62 |
+
|
| 63 |
+
def create_unique_node_name(self):
|
| 64 |
+
prefix = self._new_node_name_prefix
|
| 65 |
+
|
| 66 |
+
if self._new_node_name_suffix is None:
|
| 67 |
+
largest_suffix: int = self.model.get_largest_node_name_suffix(prefix)
|
| 68 |
+
self._new_node_name_suffix = largest_suffix + 1
|
| 69 |
+
|
| 70 |
+
new_name = f"{prefix}{self._new_node_name_suffix!s}"
|
| 71 |
+
self._new_node_name_suffix += 1
|
| 72 |
+
|
| 73 |
+
return new_name
|
| 74 |
+
|
| 75 |
+
@staticmethod
|
| 76 |
+
def is_safe_to_fuse_nodes(
|
| 77 |
+
nodes_to_remove: list[onnx.NodeProto],
|
| 78 |
+
keep_outputs: list[str],
|
| 79 |
+
input_name_to_nodes: dict[str, list[onnx.NodeProto]],
|
| 80 |
+
output_name_to_node: dict[str, onnx.NodeProto],
|
| 81 |
+
) -> bool:
|
| 82 |
+
for node_to_remove in nodes_to_remove:
|
| 83 |
+
for output_to_remove in node_to_remove.output:
|
| 84 |
+
if output_to_remove in keep_outputs:
|
| 85 |
+
continue
|
| 86 |
+
|
| 87 |
+
if output_to_remove in input_name_to_nodes:
|
| 88 |
+
for impacted_node in input_name_to_nodes[output_to_remove]:
|
| 89 |
+
if impacted_node not in nodes_to_remove:
|
| 90 |
+
# Not safe to remove nodes since output is used by impacted_node
|
| 91 |
+
return False
|
| 92 |
+
return True
|
| 93 |
+
|
| 94 |
+
@staticmethod
|
| 95 |
+
def get_node_attribute(node: onnx.NodeProto, attribute_name: str):
|
| 96 |
+
for attr in node.attribute:
|
| 97 |
+
if attr.name == attribute_name:
|
| 98 |
+
value = onnx.helper.get_attribute_value(attr)
|
| 99 |
+
return value
|
| 100 |
+
return None
|
| 101 |
+
|
| 102 |
+
@staticmethod
|
| 103 |
+
def input_index(node_output: str, child_node: onnx.NodeProto) -> int:
|
| 104 |
+
for index, input_name in enumerate(child_node.input):
|
| 105 |
+
if input_name == node_output:
|
| 106 |
+
return index
|
| 107 |
+
return -1
|
| 108 |
+
|
| 109 |
+
@staticmethod
|
| 110 |
+
def tensor_shape_to_list(tensor_type) -> list[int]:
|
| 111 |
+
shape_list = []
|
| 112 |
+
for d in tensor_type.shape.dim:
|
| 113 |
+
if d.HasField("dim_value"):
|
| 114 |
+
shape_list.append(d.dim_value) # known dimension
|
| 115 |
+
elif d.HasField("dim_param"):
|
| 116 |
+
shape_list.append(d.dim_param) # unknown dimension with symbolic name
|
| 117 |
+
else:
|
| 118 |
+
shape_list.append("?") # shall not happen
|
| 119 |
+
return shape_list
|
| 120 |
+
|
| 121 |
+
def get_constant_input(self, node: onnx.NodeProto):
|
| 122 |
+
for i, inp in enumerate(node.input):
|
| 123 |
+
value = self.model.get_constant_value(inp)
|
| 124 |
+
if value is not None:
|
| 125 |
+
return i, value
|
| 126 |
+
|
| 127 |
+
return None, None
|
| 128 |
+
|
| 129 |
+
def find_constant_input(self, node: onnx.NodeProto, expected_value: float, delta: float = 0.000001) -> int:
|
| 130 |
+
i, value = self.get_constant_input(node)
|
| 131 |
+
if value is not None and value.size == 1 and abs(value - expected_value) < delta:
|
| 132 |
+
return i
|
| 133 |
+
|
| 134 |
+
return -1
|
| 135 |
+
|
| 136 |
+
def has_constant_input(self, node: onnx.NodeProto, expected_value: float, delta: float = 0.000001) -> bool:
|
| 137 |
+
return self.find_constant_input(node, expected_value, delta) >= 0
|
| 138 |
+
|
| 139 |
+
def is_constant_with_specified_rank(self, output_name: str, rank: int) -> bool:
|
| 140 |
+
value = self.model.get_constant_value(output_name)
|
| 141 |
+
if value is None:
|
| 142 |
+
return False # Not an initializer
|
| 143 |
+
|
| 144 |
+
if len(value.shape) != rank:
|
| 145 |
+
return False # Wrong dimensions
|
| 146 |
+
|
| 147 |
+
return True
|
| 148 |
+
|
| 149 |
+
def match_first_parent(
|
| 150 |
+
self,
|
| 151 |
+
node: onnx.NodeProto,
|
| 152 |
+
parent_op_type: str,
|
| 153 |
+
output_name_to_node: dict[str, onnx.NodeProto] | None = None,
|
| 154 |
+
exclude: list[onnx.NodeProto] = [], # noqa: B006
|
| 155 |
+
) -> tuple[onnx.NodeProto | None, int | None]:
|
| 156 |
+
"""
|
| 157 |
+
Find parent node based on constraints on op_type.
|
| 158 |
+
|
| 159 |
+
Args:
|
| 160 |
+
node: current node.
|
| 161 |
+
parent_op_type (str): constraint of parent node op_type.
|
| 162 |
+
output_name_to_node (dict): dictionary with output name as key, and node as value.
|
| 163 |
+
exclude (list): list of nodes that are excluded (not allowed to match as parent).
|
| 164 |
+
|
| 165 |
+
Returns:
|
| 166 |
+
parent: The matched parent node. None if not found.
|
| 167 |
+
index: The input index of matched parent node. None if not found.
|
| 168 |
+
"""
|
| 169 |
+
if output_name_to_node is None:
|
| 170 |
+
output_name_to_node = self.model.output_name_to_node()
|
| 171 |
+
|
| 172 |
+
for i, inp in enumerate(node.input):
|
| 173 |
+
if inp in output_name_to_node:
|
| 174 |
+
parent = output_name_to_node[inp]
|
| 175 |
+
if parent.op_type == parent_op_type and parent not in exclude:
|
| 176 |
+
return parent, i
|
| 177 |
+
|
| 178 |
+
return None, None
|
| 179 |
+
|
| 180 |
+
def match_parent(
|
| 181 |
+
self,
|
| 182 |
+
node: onnx.NodeProto,
|
| 183 |
+
parent_op_type: str,
|
| 184 |
+
input_index: int | None = None,
|
| 185 |
+
output_name_to_node: dict[str, onnx.NodeProto] | None = None,
|
| 186 |
+
exclude: list[onnx.NodeProto] = [], # noqa: B006
|
| 187 |
+
return_indice: list[int] | None = None,
|
| 188 |
+
) -> onnx.NodeProto | None:
|
| 189 |
+
"""
|
| 190 |
+
Find parent node based on constraints on op_type and index.
|
| 191 |
+
When input_index is None, we will find the first parent node based on constraints,
|
| 192 |
+
and return_indice will be appended the corresponding input index.
|
| 193 |
+
|
| 194 |
+
Args:
|
| 195 |
+
node (str): current node name.
|
| 196 |
+
parent_op_type (str): constraint of parent node op_type.
|
| 197 |
+
input_index (int or None): only check the parent given input index of current node.
|
| 198 |
+
output_name_to_node (dict): dictionary with output name as key, and node as value.
|
| 199 |
+
exclude (list): list of nodes that are excluded (not allowed to match as parent).
|
| 200 |
+
return_indice (list): a list to append the input index when input_index is None.
|
| 201 |
+
|
| 202 |
+
Returns:
|
| 203 |
+
parent: The matched parent node.
|
| 204 |
+
"""
|
| 205 |
+
assert node is not None
|
| 206 |
+
assert input_index is None or input_index >= 0
|
| 207 |
+
|
| 208 |
+
if output_name_to_node is None:
|
| 209 |
+
output_name_to_node = self.model.output_name_to_node()
|
| 210 |
+
|
| 211 |
+
if input_index is None:
|
| 212 |
+
parent, index = self.match_first_parent(node, parent_op_type, output_name_to_node, exclude)
|
| 213 |
+
if return_indice is not None:
|
| 214 |
+
return_indice.append(index)
|
| 215 |
+
return parent
|
| 216 |
+
|
| 217 |
+
if input_index >= len(node.input):
|
| 218 |
+
# Input index out of bounds.
|
| 219 |
+
return None
|
| 220 |
+
|
| 221 |
+
parent = self.model.get_parent(node, input_index, output_name_to_node)
|
| 222 |
+
if parent is not None and parent.op_type == parent_op_type and parent not in exclude:
|
| 223 |
+
return parent
|
| 224 |
+
|
| 225 |
+
return None
|
| 226 |
+
|
| 227 |
+
def match_parent_path(
|
| 228 |
+
self,
|
| 229 |
+
node: onnx.NodeProto,
|
| 230 |
+
parent_op_types: list[str],
|
| 231 |
+
parent_input_index: list[int] | None = None,
|
| 232 |
+
output_name_to_node: dict[str, onnx.NodeProto] | None = None,
|
| 233 |
+
return_indice: list[int] | None = None,
|
| 234 |
+
) -> list[onnx.NodeProto] | None:
|
| 235 |
+
"""
|
| 236 |
+
Find a sequence of input edges based on constraints on parent op_type and index.
|
| 237 |
+
When input_index is None, we will find the first parent node based on constraints,
|
| 238 |
+
and return_indice will be appended the corresponding input index.
|
| 239 |
+
|
| 240 |
+
Args:
|
| 241 |
+
node (str): current node name.
|
| 242 |
+
parent_op_types (str): constraint of parent node op_type of each input edge.
|
| 243 |
+
parent_input_index (list): constraint of input index of each input edge. None means no constraint.
|
| 244 |
+
output_name_to_node (dict): dictionary with output name as key, and node as value.
|
| 245 |
+
return_indice (list): a list to append the input index
|
| 246 |
+
When there is no constraint on input index of an edge.
|
| 247 |
+
|
| 248 |
+
Returns:
|
| 249 |
+
parents: a list of matched parent node.
|
| 250 |
+
"""
|
| 251 |
+
if parent_input_index is not None:
|
| 252 |
+
assert len(parent_input_index) == len(parent_op_types)
|
| 253 |
+
|
| 254 |
+
if output_name_to_node is None:
|
| 255 |
+
output_name_to_node = self.model.output_name_to_node()
|
| 256 |
+
|
| 257 |
+
current_node = node
|
| 258 |
+
matched_parents = []
|
| 259 |
+
for i, op_type in enumerate(parent_op_types):
|
| 260 |
+
matched_parent = self.match_parent(
|
| 261 |
+
current_node,
|
| 262 |
+
op_type,
|
| 263 |
+
parent_input_index[i] if parent_input_index is not None else None,
|
| 264 |
+
output_name_to_node,
|
| 265 |
+
exclude=[],
|
| 266 |
+
return_indice=return_indice,
|
| 267 |
+
)
|
| 268 |
+
if matched_parent is None:
|
| 269 |
+
return None
|
| 270 |
+
|
| 271 |
+
matched_parents.append(matched_parent)
|
| 272 |
+
current_node = matched_parent
|
| 273 |
+
|
| 274 |
+
return matched_parents
|
| 275 |
+
|
| 276 |
+
def match_parent_paths(
|
| 277 |
+
self,
|
| 278 |
+
node: onnx.NodeProto,
|
| 279 |
+
paths: list[tuple[list[str], list[int]]],
|
| 280 |
+
output_name_to_node: dict[str, onnx.NodeProto],
|
| 281 |
+
) -> tuple[int, list[onnx.NodeProto] | None, list[int] | None]:
|
| 282 |
+
"""
|
| 283 |
+
Find a matching parent path to the given node.
|
| 284 |
+
"""
|
| 285 |
+
for i, path in enumerate(paths):
|
| 286 |
+
return_indice = []
|
| 287 |
+
matched = self.match_parent_path(node, path[0], path[1], output_name_to_node, return_indice)
|
| 288 |
+
if matched:
|
| 289 |
+
return i, matched, return_indice
|
| 290 |
+
return -1, None, None
|
| 291 |
+
|
| 292 |
+
def find_first_child_by_type(
|
| 293 |
+
self,
|
| 294 |
+
node: onnx.NodeProto,
|
| 295 |
+
child_type: str,
|
| 296 |
+
input_name_to_nodes: dict[str, list[onnx.NodeProto]] | None = None,
|
| 297 |
+
recursive: bool = True,
|
| 298 |
+
) -> onnx.NodeProto | None:
|
| 299 |
+
children = self.model.get_children(node, input_name_to_nodes)
|
| 300 |
+
dq = deque(children)
|
| 301 |
+
while len(dq) > 0:
|
| 302 |
+
current_node = dq.pop()
|
| 303 |
+
if current_node.op_type == child_type:
|
| 304 |
+
return current_node
|
| 305 |
+
|
| 306 |
+
if recursive:
|
| 307 |
+
children = self.model.get_children(current_node, input_name_to_nodes)
|
| 308 |
+
for child in children:
|
| 309 |
+
dq.appendleft(child)
|
| 310 |
+
|
| 311 |
+
return None
|
micromamba_root/envs/pytorch_env/Lib/site-packages/onnxruntime/quantization/fusions/fusion_gelu.py
ADDED
|
@@ -0,0 +1,272 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -------------------------------------------------------------------------
|
| 2 |
+
# Copyright (c) Microsoft Corporation. All rights reserved.
|
| 3 |
+
# Licensed under the MIT License. See License.txt in the project root for
|
| 4 |
+
# license information.
|
| 5 |
+
# --------------------------------------------------------------------------
|
| 6 |
+
from __future__ import annotations
|
| 7 |
+
|
| 8 |
+
import onnx
|
| 9 |
+
|
| 10 |
+
from ..onnx_model import ONNXModel
|
| 11 |
+
from .fusion import Fusion
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
class FusionGelu(Fusion):
|
| 15 |
+
def __init__(self, model: ONNXModel):
|
| 16 |
+
super().__init__(model, "Gelu", "Erf")
|
| 17 |
+
|
| 18 |
+
def fuse(
|
| 19 |
+
self,
|
| 20 |
+
erf_node: onnx.NodeProto,
|
| 21 |
+
input_name_to_nodes: dict[str, list[onnx.NodeProto]],
|
| 22 |
+
output_name_to_node: dict[str, onnx.NodeProto],
|
| 23 |
+
):
|
| 24 |
+
"""
|
| 25 |
+
Interface function that tries to fuse a node sequence containing an Erf node into a single
|
| 26 |
+
Gelu node.
|
| 27 |
+
"""
|
| 28 |
+
if (
|
| 29 |
+
self.fuse_1(erf_node, input_name_to_nodes, output_name_to_node)
|
| 30 |
+
or self.fuse_2(erf_node, input_name_to_nodes, output_name_to_node)
|
| 31 |
+
or self.fuse_3(erf_node, input_name_to_nodes, output_name_to_node)
|
| 32 |
+
):
|
| 33 |
+
self.model.set_opset_import("com.microsoft", 1)
|
| 34 |
+
|
| 35 |
+
def fuse_1(
|
| 36 |
+
self,
|
| 37 |
+
erf_node: onnx.NodeProto,
|
| 38 |
+
input_name_to_nodes: dict[str, list[onnx.NodeProto]],
|
| 39 |
+
output_name_to_node: dict[str, onnx.NodeProto],
|
| 40 |
+
) -> bool:
|
| 41 |
+
"""
|
| 42 |
+
This pattern is from PyTorch model
|
| 43 |
+
Fuse Gelu with Erf into one node:
|
| 44 |
+
Pattern 1:
|
| 45 |
+
+-------Mul(0.5)---------------------+
|
| 46 |
+
| |
|
| 47 |
+
| v
|
| 48 |
+
[root] --> Div -----> Erf --> Add --> Mul -->
|
| 49 |
+
(B=1.4142...) (1)
|
| 50 |
+
|
| 51 |
+
Pattern 2:
|
| 52 |
+
+------------------------------------+
|
| 53 |
+
| |
|
| 54 |
+
| v
|
| 55 |
+
[root] --> Div -----> Erf --> Add --> Mul -->Mul -->
|
| 56 |
+
(B=1.4142...) (1) (0.5)
|
| 57 |
+
|
| 58 |
+
Note that constant input for Add and Mul could be first or second input: like either A=0.5 or B=0.5 is fine.
|
| 59 |
+
"""
|
| 60 |
+
if erf_node.output[0] not in input_name_to_nodes:
|
| 61 |
+
return False
|
| 62 |
+
children = input_name_to_nodes[erf_node.output[0]]
|
| 63 |
+
if len(children) != 1 or children[0].op_type != "Add":
|
| 64 |
+
return False
|
| 65 |
+
add_after_erf = children[0]
|
| 66 |
+
|
| 67 |
+
if not self.has_constant_input(add_after_erf, 1):
|
| 68 |
+
return False
|
| 69 |
+
|
| 70 |
+
if add_after_erf.output[0] not in input_name_to_nodes:
|
| 71 |
+
return False
|
| 72 |
+
|
| 73 |
+
children = input_name_to_nodes[add_after_erf.output[0]]
|
| 74 |
+
if len(children) != 1 or children[0].op_type != "Mul":
|
| 75 |
+
return False
|
| 76 |
+
|
| 77 |
+
mul_after_erf = children[0]
|
| 78 |
+
|
| 79 |
+
div = self.match_parent(erf_node, "Div", 0, output_name_to_node)
|
| 80 |
+
if div is None:
|
| 81 |
+
return False
|
| 82 |
+
|
| 83 |
+
if self.find_constant_input(div, 1.4142, delta=0.001) != 1:
|
| 84 |
+
return False
|
| 85 |
+
|
| 86 |
+
subgraph_input = div.input[0]
|
| 87 |
+
|
| 88 |
+
another = 1 if mul_after_erf.input[0] == add_after_erf.output[0] else 0
|
| 89 |
+
if subgraph_input == mul_after_erf.input[another]: # pattern 2
|
| 90 |
+
children = input_name_to_nodes[mul_after_erf.output[0]]
|
| 91 |
+
if len(children) != 1 or children[0].op_type != "Mul":
|
| 92 |
+
return False
|
| 93 |
+
mul_half = children[0]
|
| 94 |
+
if not self.has_constant_input(mul_half, 0.5):
|
| 95 |
+
return False
|
| 96 |
+
subgraph_output = mul_half.output[0]
|
| 97 |
+
else: # pattern 1
|
| 98 |
+
mul_half = self.match_parent(mul_after_erf, "Mul", another, output_name_to_node)
|
| 99 |
+
if mul_half is None:
|
| 100 |
+
return False
|
| 101 |
+
|
| 102 |
+
if not self.has_constant_input(mul_half, 0.5):
|
| 103 |
+
return False
|
| 104 |
+
|
| 105 |
+
if subgraph_input not in mul_half.input:
|
| 106 |
+
return False
|
| 107 |
+
|
| 108 |
+
subgraph_output = mul_after_erf.output[0]
|
| 109 |
+
|
| 110 |
+
subgraph_nodes = [div, erf_node, add_after_erf, mul_after_erf, mul_half]
|
| 111 |
+
if not self.is_safe_to_fuse_nodes(subgraph_nodes, [subgraph_output], input_name_to_nodes, output_name_to_node):
|
| 112 |
+
return False
|
| 113 |
+
|
| 114 |
+
self.nodes_to_remove.extend(subgraph_nodes)
|
| 115 |
+
fused_node = onnx.helper.make_node(
|
| 116 |
+
"Gelu", name=self.create_unique_node_name(), inputs=[subgraph_input], outputs=[subgraph_output]
|
| 117 |
+
)
|
| 118 |
+
fused_node.domain = "com.microsoft"
|
| 119 |
+
self.nodes_to_add.append(fused_node)
|
| 120 |
+
return True
|
| 121 |
+
|
| 122 |
+
def fuse_2(
|
| 123 |
+
self,
|
| 124 |
+
erf_node: onnx.NodeProto,
|
| 125 |
+
input_name_to_nodes: dict[str, list[onnx.NodeProto]],
|
| 126 |
+
output_name_to_node: dict[str, onnx.NodeProto],
|
| 127 |
+
) -> bool:
|
| 128 |
+
"""
|
| 129 |
+
This pattern is from Keras model
|
| 130 |
+
Fuse Gelu with Erf into one node:
|
| 131 |
+
+------------------------------------------+
|
| 132 |
+
| |
|
| 133 |
+
| v
|
| 134 |
+
[root] --> Div -----> Erf --> Add --> Mul -->Mul
|
| 135 |
+
(B=1.4142...) (A=1) (A=0.5)
|
| 136 |
+
|
| 137 |
+
Note that constant input for Add and Mul could be first or second input: like either A=0.5 or B=0.5 is fine.
|
| 138 |
+
"""
|
| 139 |
+
if erf_node.output[0] not in input_name_to_nodes:
|
| 140 |
+
return False
|
| 141 |
+
children = input_name_to_nodes[erf_node.output[0]]
|
| 142 |
+
if len(children) != 1 or children[0].op_type != "Add":
|
| 143 |
+
return False
|
| 144 |
+
add_after_erf = children[0]
|
| 145 |
+
|
| 146 |
+
if not self.has_constant_input(add_after_erf, 1):
|
| 147 |
+
return False
|
| 148 |
+
|
| 149 |
+
if add_after_erf.output[0] not in input_name_to_nodes:
|
| 150 |
+
return False
|
| 151 |
+
children = input_name_to_nodes[add_after_erf.output[0]]
|
| 152 |
+
if len(children) != 1 or children[0].op_type != "Mul":
|
| 153 |
+
return False
|
| 154 |
+
mul_after_erf = children[0]
|
| 155 |
+
|
| 156 |
+
if not self.has_constant_input(mul_after_erf, 0.5):
|
| 157 |
+
return False
|
| 158 |
+
|
| 159 |
+
if mul_after_erf.output[0] not in input_name_to_nodes:
|
| 160 |
+
return False
|
| 161 |
+
children = input_name_to_nodes[mul_after_erf.output[0]]
|
| 162 |
+
if len(children) != 1 or children[0].op_type != "Mul":
|
| 163 |
+
return False
|
| 164 |
+
mul = children[0]
|
| 165 |
+
|
| 166 |
+
div = self.match_parent(erf_node, "Div", 0, output_name_to_node)
|
| 167 |
+
if div is None:
|
| 168 |
+
return False
|
| 169 |
+
|
| 170 |
+
sqrt_node = None
|
| 171 |
+
if self.find_constant_input(div, 1.4142, delta=0.001) != 1:
|
| 172 |
+
sqrt_node = self.match_parent(div, "Sqrt", 1, output_name_to_node)
|
| 173 |
+
if sqrt_node is None:
|
| 174 |
+
return False
|
| 175 |
+
if not self.has_constant_input(sqrt_node, 2.0):
|
| 176 |
+
return False
|
| 177 |
+
|
| 178 |
+
subgraph_input = div.input[0]
|
| 179 |
+
|
| 180 |
+
if subgraph_input not in mul.input:
|
| 181 |
+
return False
|
| 182 |
+
|
| 183 |
+
subgraph_nodes = [div, erf_node, add_after_erf, mul_after_erf, mul]
|
| 184 |
+
if sqrt_node:
|
| 185 |
+
subgraph_nodes.append(sqrt_node)
|
| 186 |
+
|
| 187 |
+
if not self.is_safe_to_fuse_nodes(subgraph_nodes, [mul.output[0]], input_name_to_nodes, output_name_to_node):
|
| 188 |
+
return False
|
| 189 |
+
|
| 190 |
+
self.nodes_to_remove.extend(subgraph_nodes)
|
| 191 |
+
fused_node = onnx.helper.make_node(
|
| 192 |
+
"Gelu", name=self.create_unique_node_name(), inputs=[subgraph_input], outputs=[mul.output[0]]
|
| 193 |
+
)
|
| 194 |
+
fused_node.domain = "com.microsoft"
|
| 195 |
+
self.nodes_to_add.append(fused_node)
|
| 196 |
+
return True
|
| 197 |
+
|
| 198 |
+
def fuse_3(
|
| 199 |
+
self,
|
| 200 |
+
erf_node: onnx.NodeProto,
|
| 201 |
+
input_name_to_nodes: dict[str, list[onnx.NodeProto]],
|
| 202 |
+
output_name_to_node: dict[str, onnx.NodeProto],
|
| 203 |
+
) -> bool:
|
| 204 |
+
"""
|
| 205 |
+
This pattern is from TensorFlow model
|
| 206 |
+
Fuse Gelu with Erf into one node:
|
| 207 |
+
+----------------------------------------------+
|
| 208 |
+
| |
|
| 209 |
+
| v
|
| 210 |
+
[root] --> Mul -----> Erf --> Add --> Mul -->Mul
|
| 211 |
+
(A=0.7071067690849304) (B=1) (B=0.5)
|
| 212 |
+
|
| 213 |
+
Note that constant input for Add and Mul could be first or second input: like either A=0.5 or B=0.5 is fine.
|
| 214 |
+
"""
|
| 215 |
+
|
| 216 |
+
if erf_node.output[0] not in input_name_to_nodes:
|
| 217 |
+
return False
|
| 218 |
+
children = input_name_to_nodes[erf_node.output[0]]
|
| 219 |
+
if len(children) != 1 or children[0].op_type != "Add":
|
| 220 |
+
return False
|
| 221 |
+
add_after_erf = children[0]
|
| 222 |
+
|
| 223 |
+
if not self.has_constant_input(add_after_erf, 1):
|
| 224 |
+
return False
|
| 225 |
+
|
| 226 |
+
if add_after_erf.output[0] not in input_name_to_nodes:
|
| 227 |
+
return False
|
| 228 |
+
children = input_name_to_nodes[add_after_erf.output[0]]
|
| 229 |
+
if len(children) != 1 or children[0].op_type != "Mul":
|
| 230 |
+
return False
|
| 231 |
+
mul_half = children[0]
|
| 232 |
+
|
| 233 |
+
if not self.has_constant_input(mul_half, 0.5):
|
| 234 |
+
return False
|
| 235 |
+
|
| 236 |
+
first_mul = self.match_parent(erf_node, "Mul", 0, output_name_to_node)
|
| 237 |
+
if first_mul is None:
|
| 238 |
+
return False
|
| 239 |
+
|
| 240 |
+
i = self.find_constant_input(first_mul, 0.7071067690849304, delta=0.001)
|
| 241 |
+
if i < 0:
|
| 242 |
+
return False
|
| 243 |
+
|
| 244 |
+
root_input_index = 1 - i
|
| 245 |
+
subgraph_input = first_mul.input[root_input_index]
|
| 246 |
+
|
| 247 |
+
if mul_half.output[0] not in input_name_to_nodes:
|
| 248 |
+
return False
|
| 249 |
+
children = input_name_to_nodes[mul_half.output[0]]
|
| 250 |
+
if len(children) != 1 or children[0].op_type != "Mul":
|
| 251 |
+
return False
|
| 252 |
+
last_mul = children[0]
|
| 253 |
+
|
| 254 |
+
if not (last_mul.input[0] == subgraph_input or last_mul.input[1] == subgraph_input):
|
| 255 |
+
return False
|
| 256 |
+
|
| 257 |
+
subgraph_nodes = [first_mul, erf_node, add_after_erf, mul_half, last_mul]
|
| 258 |
+
if not self.is_safe_to_fuse_nodes(
|
| 259 |
+
subgraph_nodes,
|
| 260 |
+
[last_mul.output[0]],
|
| 261 |
+
input_name_to_nodes,
|
| 262 |
+
output_name_to_node,
|
| 263 |
+
):
|
| 264 |
+
return False
|
| 265 |
+
|
| 266 |
+
self.nodes_to_remove.extend(subgraph_nodes)
|
| 267 |
+
fused_node = onnx.helper.make_node(
|
| 268 |
+
"Gelu", name=self.create_unique_node_name(), inputs=[subgraph_input], outputs=[last_mul.output[0]]
|
| 269 |
+
)
|
| 270 |
+
fused_node.domain = "com.microsoft"
|
| 271 |
+
self.nodes_to_add.append(fused_node)
|
| 272 |
+
return True
|
micromamba_root/envs/pytorch_env/Lib/site-packages/onnxruntime/quantization/fusions/fusion_layernorm.py
ADDED
|
@@ -0,0 +1,146 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -------------------------------------------------------------------------
|
| 2 |
+
# Copyright (c) Microsoft Corporation. All rights reserved.
|
| 3 |
+
# Licensed under the MIT License. See License.txt in the project root for
|
| 4 |
+
# license information.
|
| 5 |
+
# --------------------------------------------------------------------------
|
| 6 |
+
from __future__ import annotations
|
| 7 |
+
|
| 8 |
+
import onnx
|
| 9 |
+
|
| 10 |
+
from ..onnx_model import ONNXModel
|
| 11 |
+
from .fusion import Fusion
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
class FusionLayerNormalization(Fusion):
|
| 15 |
+
def __init__(self, model: ONNXModel):
|
| 16 |
+
super().__init__(model, "LayerNormalization", "ReduceMean")
|
| 17 |
+
|
| 18 |
+
def fuse(
|
| 19 |
+
self,
|
| 20 |
+
reduce_mean_node: onnx.NodeProto,
|
| 21 |
+
input_name_to_nodes: dict[str, list[onnx.NodeProto]],
|
| 22 |
+
output_name_to_node: dict[str, onnx.NodeProto],
|
| 23 |
+
):
|
| 24 |
+
"""
|
| 25 |
+
Interface function that tries to fuse a node sequence containing a ReduceMean node into a single
|
| 26 |
+
LayerNormalization node.
|
| 27 |
+
|
| 28 |
+
+----------------------+
|
| 29 |
+
| |
|
| 30 |
+
| v
|
| 31 |
+
[Root] --> ReduceMean --> Sub --> Pow --> ReduceMean --> Add --> Sqrt --> Div --> Mul --> Add
|
| 32 |
+
(axis=2 or -1) | (Y=2) (axis=2 or -1) (E-6 or E-12 or 0) ^
|
| 33 |
+
| |
|
| 34 |
+
+-------------------------------------------------+
|
| 35 |
+
|
| 36 |
+
Or, using Mul instead of Pow:
|
| 37 |
+
|
| 38 |
+
+----------------------+
|
| 39 |
+
| |
|
| 40 |
+
| v
|
| 41 |
+
[Root] --> ReduceMean --> Sub --> Mul --> ReduceMean --> Add --> Sqrt --> Div --> Mul --> Add
|
| 42 |
+
(axis=2 or -1) | (in0=in1) (axis=2 or -1) (E-6 or E-12 or 0) ^
|
| 43 |
+
| |
|
| 44 |
+
+-------------------------------------------------+
|
| 45 |
+
|
| 46 |
+
It also handles cases of duplicated sub nodes exported from older version of PyTorch:
|
| 47 |
+
|
| 48 |
+
+----------------------+
|
| 49 |
+
| v
|
| 50 |
+
| +-------> Sub-----------------------------------------------+
|
| 51 |
+
| | |
|
| 52 |
+
| | v
|
| 53 |
+
[Root] --> ReduceMean --> Sub --> (Pow or Mul) --> ReduceMean --> Add --> Sqrt --> Div --> Mul --> Add
|
| 54 |
+
| ^
|
| 55 |
+
| |
|
| 56 |
+
+----------------------+
|
| 57 |
+
"""
|
| 58 |
+
children = self.model.get_children(reduce_mean_node, input_name_to_nodes)
|
| 59 |
+
if len(children) == 0 or len(children) > 2:
|
| 60 |
+
return
|
| 61 |
+
|
| 62 |
+
root_input = reduce_mean_node.input[0]
|
| 63 |
+
|
| 64 |
+
if children[0].op_type != "Sub" or children[0].input[0] != root_input:
|
| 65 |
+
return
|
| 66 |
+
|
| 67 |
+
if len(children) == 2:
|
| 68 |
+
if children[1].op_type != "Sub" or children[1].input[0] != root_input:
|
| 69 |
+
return
|
| 70 |
+
|
| 71 |
+
div_node = None
|
| 72 |
+
for child in children:
|
| 73 |
+
div_node = self.find_first_child_by_type(child, "Div", input_name_to_nodes, recursive=False)
|
| 74 |
+
if div_node is not None:
|
| 75 |
+
break
|
| 76 |
+
if div_node is None:
|
| 77 |
+
return
|
| 78 |
+
|
| 79 |
+
path_id, parent_nodes, _ = self.match_parent_paths(
|
| 80 |
+
div_node,
|
| 81 |
+
[
|
| 82 |
+
(["Sqrt", "Add", "ReduceMean", "Pow", "Sub"], [1, 0, 0, 0, 0]),
|
| 83 |
+
(["Sqrt", "Add", "ReduceMean", "Pow", "Cast", "Sub"], [1, 0, 0, 0, 0, 0]),
|
| 84 |
+
(["Sqrt", "Add", "ReduceMean", "Mul", "Sub"], [1, 0, 0, 0, 0]),
|
| 85 |
+
(["Sqrt", "Add", "ReduceMean", "Mul", "Cast", "Sub"], [1, 0, 0, 0, 0, 0]),
|
| 86 |
+
],
|
| 87 |
+
output_name_to_node,
|
| 88 |
+
)
|
| 89 |
+
if path_id < 0:
|
| 90 |
+
return
|
| 91 |
+
|
| 92 |
+
sub_node = parent_nodes[-1]
|
| 93 |
+
if sub_node not in children:
|
| 94 |
+
return
|
| 95 |
+
|
| 96 |
+
second_add_node = parent_nodes[1]
|
| 97 |
+
i, add_weight = self.get_constant_input(second_add_node)
|
| 98 |
+
if add_weight is None or add_weight <= 0 or add_weight > 1.0e-4:
|
| 99 |
+
# Skip fusion since epsilon value is not expected.
|
| 100 |
+
return
|
| 101 |
+
|
| 102 |
+
pow_or_mul_node = parent_nodes[3]
|
| 103 |
+
if pow_or_mul_node.op_type == "Pow" and self.find_constant_input(pow_or_mul_node, 2.0) != 1:
|
| 104 |
+
return
|
| 105 |
+
elif pow_or_mul_node.op_type == "Mul" and pow_or_mul_node.input[0] != pow_or_mul_node.input[1]:
|
| 106 |
+
return
|
| 107 |
+
|
| 108 |
+
mul_node = input_name_to_nodes[div_node.output[0]][0]
|
| 109 |
+
if mul_node.op_type != "Mul":
|
| 110 |
+
return
|
| 111 |
+
|
| 112 |
+
last_add_node = input_name_to_nodes[mul_node.output[0]][0]
|
| 113 |
+
if last_add_node.op_type != "Add":
|
| 114 |
+
return
|
| 115 |
+
|
| 116 |
+
subgraph_nodes = [reduce_mean_node]
|
| 117 |
+
subgraph_nodes.extend(children)
|
| 118 |
+
subgraph_nodes.extend(parent_nodes[:-1])
|
| 119 |
+
|
| 120 |
+
subgraph_nodes.extend([last_add_node, mul_node, div_node])
|
| 121 |
+
if not self.is_safe_to_fuse_nodes(
|
| 122 |
+
subgraph_nodes,
|
| 123 |
+
last_add_node.output,
|
| 124 |
+
input_name_to_nodes,
|
| 125 |
+
output_name_to_node,
|
| 126 |
+
):
|
| 127 |
+
return
|
| 128 |
+
|
| 129 |
+
weight_input = mul_node.input[1 - self.input_index(div_node.output[0], mul_node)]
|
| 130 |
+
if not self.is_constant_with_specified_rank(weight_input, 1):
|
| 131 |
+
return
|
| 132 |
+
|
| 133 |
+
bias_input = last_add_node.input[1 - self.input_index(mul_node.output[0], last_add_node)]
|
| 134 |
+
if not self.is_constant_with_specified_rank(bias_input, 1):
|
| 135 |
+
return
|
| 136 |
+
|
| 137 |
+
self.nodes_to_remove.extend(subgraph_nodes)
|
| 138 |
+
|
| 139 |
+
normalize_node = onnx.helper.make_node(
|
| 140 |
+
"LayerNormalization",
|
| 141 |
+
name=self.create_unique_node_name(),
|
| 142 |
+
inputs=[reduce_mean_node.input[0], weight_input, bias_input],
|
| 143 |
+
outputs=[last_add_node.output[0]],
|
| 144 |
+
)
|
| 145 |
+
normalize_node.attribute.extend([onnx.helper.make_attribute("epsilon", float(add_weight))])
|
| 146 |
+
self.nodes_to_add.append(normalize_node)
|
micromamba_root/envs/pytorch_env/Lib/site-packages/onnxruntime/quantization/fusions/replace_upsample_with_resize.py
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -------------------------------------------------------------------------
|
| 2 |
+
# Copyright (c) Microsoft Corporation. All rights reserved.
|
| 3 |
+
# Licensed under the MIT License. See License.txt in the project root for
|
| 4 |
+
# license information.
|
| 5 |
+
# --------------------------------------------------------------------------
|
| 6 |
+
from __future__ import annotations
|
| 7 |
+
|
| 8 |
+
import numpy as np
|
| 9 |
+
import onnx
|
| 10 |
+
|
| 11 |
+
from ..onnx_model import ONNXModel
|
| 12 |
+
from .fusion import Fusion
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
class ReplaceUpsampleWithResize(Fusion):
|
| 16 |
+
"""Replace Upsample with Resize."""
|
| 17 |
+
|
| 18 |
+
def __init__(self, model: ONNXModel, opset):
|
| 19 |
+
"""Initialize."""
|
| 20 |
+
super().__init__(model, "Resize", "Upsample")
|
| 21 |
+
self.opset = opset
|
| 22 |
+
|
| 23 |
+
def fuse(
|
| 24 |
+
self,
|
| 25 |
+
node: onnx.NodeProto,
|
| 26 |
+
input_name_to_nodes: dict[str, list[onnx.NodeProto]],
|
| 27 |
+
output_name_to_node: dict[str, onnx.NodeProto],
|
| 28 |
+
):
|
| 29 |
+
"""Replace Upsample with Resize."""
|
| 30 |
+
mode = None
|
| 31 |
+
for attr in node.attribute:
|
| 32 |
+
if attr.name == "mode":
|
| 33 |
+
mode = attr.s.decode("utf-8")
|
| 34 |
+
break
|
| 35 |
+
|
| 36 |
+
scales_input = None
|
| 37 |
+
if self.opset > 7:
|
| 38 |
+
scales_input = node.input[1] if len(node.input) > 1 else ""
|
| 39 |
+
resize_inputs = [node.input[0], node.name + "_roi", scales_input]
|
| 40 |
+
else:
|
| 41 |
+
if self.opset == 7:
|
| 42 |
+
for attr in node.attribute:
|
| 43 |
+
if attr.name == "scales":
|
| 44 |
+
scales_input = attr.floats
|
| 45 |
+
break
|
| 46 |
+
|
| 47 |
+
scales_input = np.array(list(scales_input), np.float32)
|
| 48 |
+
else:
|
| 49 |
+
h_scale = 1
|
| 50 |
+
w_scale = 1
|
| 51 |
+
for attr in node.attribute:
|
| 52 |
+
if attr.name == "height_scale":
|
| 53 |
+
h_scale = attr.float
|
| 54 |
+
elif attr.name == "width_scale":
|
| 55 |
+
w_scale = attr.float
|
| 56 |
+
|
| 57 |
+
scales_input = np.array([1, 1, h_scale, w_scale], np.float32)
|
| 58 |
+
|
| 59 |
+
scales_tensor = onnx.helper.make_tensor(
|
| 60 |
+
name=node.name + "_scales",
|
| 61 |
+
data_type=onnx.TensorProto.FLOAT,
|
| 62 |
+
dims=scales_input.shape,
|
| 63 |
+
vals=scales_input.flatten().tolist(),
|
| 64 |
+
)
|
| 65 |
+
|
| 66 |
+
scales_node = onnx.helper.make_node(
|
| 67 |
+
"Constant", inputs=[], outputs=[node.name + "_scales"], value=scales_tensor
|
| 68 |
+
)
|
| 69 |
+
|
| 70 |
+
self.nodes_to_add.append(scales_node)
|
| 71 |
+
|
| 72 |
+
resize_inputs = [node.input[0], node.name + "_roi", node.name + "_scales"]
|
| 73 |
+
|
| 74 |
+
roi_tensor = onnx.helper.make_tensor(
|
| 75 |
+
name=node.name + "_roi",
|
| 76 |
+
data_type=onnx.TensorProto.FLOAT,
|
| 77 |
+
dims=(len(scales_input) * 2,),
|
| 78 |
+
vals=[0] * len(scales_input) + [1] * len(scales_input),
|
| 79 |
+
)
|
| 80 |
+
|
| 81 |
+
roi_node = onnx.helper.make_node("Constant", inputs=[], outputs=[node.name + "_roi"], value=roi_tensor)
|
| 82 |
+
|
| 83 |
+
resize_node = onnx.helper.make_node(
|
| 84 |
+
op_type="Resize", inputs=resize_inputs, outputs=node.output, mode=mode, nearest_mode="floor"
|
| 85 |
+
)
|
| 86 |
+
|
| 87 |
+
self.nodes_to_remove.append(node)
|
| 88 |
+
self.nodes_to_add.append(roi_node)
|
| 89 |
+
self.nodes_to_add.append(resize_node)
|
| 90 |
+
|
| 91 |
+
def apply(self) -> bool:
|
| 92 |
+
"""Apply."""
|
| 93 |
+
if super().apply():
|
| 94 |
+
self.model.topological_sort()
|
| 95 |
+
return True
|
| 96 |
+
return False
|
micromamba_root/envs/pytorch_env/Lib/site-packages/onnxruntime/quantization/matmul_bnb4_quantizer.py
ADDED
|
@@ -0,0 +1,239 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -------------------------------------------------------------------------
|
| 2 |
+
# Copyright (c) Microsoft Corporation. All rights reserved.
|
| 3 |
+
# Licensed under the MIT License. See License.txt in the project root for
|
| 4 |
+
# license information.
|
| 5 |
+
# --------------------------------------------------------------------------
|
| 6 |
+
|
| 7 |
+
import argparse
|
| 8 |
+
import logging
|
| 9 |
+
import os
|
| 10 |
+
|
| 11 |
+
import numpy as np
|
| 12 |
+
import numpy.typing as npt
|
| 13 |
+
import onnx
|
| 14 |
+
from onnx.onnx_pb import GraphProto, ModelProto, NodeProto, TensorProto
|
| 15 |
+
|
| 16 |
+
from onnxruntime.capi._pybind_state import quantize_matmul_bnb4
|
| 17 |
+
|
| 18 |
+
from .onnx_model import ONNXModel
|
| 19 |
+
from .quant_utils import attribute_to_kwarg
|
| 20 |
+
|
| 21 |
+
logger = logging.getLogger(__name__)
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class MatMulBnb4Quantizer:
|
| 25 |
+
"""Perform 4b quantization of constant MatMul weights using FP4 or NF4 data type"""
|
| 26 |
+
|
| 27 |
+
##################
|
| 28 |
+
# quantization types, must be consistent with native code type
|
| 29 |
+
# Bnb_DataType_t defined in blockwise_quant_block_bnb4.h
|
| 30 |
+
|
| 31 |
+
# 4b floating point with bias of 3
|
| 32 |
+
FP4 = 0
|
| 33 |
+
|
| 34 |
+
# 4b NormalFloat
|
| 35 |
+
NF4 = 1
|
| 36 |
+
|
| 37 |
+
def __init__(self, model: ModelProto, quant_type: int, block_size: int, nodes_to_exclude=None):
|
| 38 |
+
nodes_to_exclude = nodes_to_exclude or []
|
| 39 |
+
assert quant_type in [MatMulBnb4Quantizer.FP4, MatMulBnb4Quantizer.NF4]
|
| 40 |
+
self.model = ONNXModel(model)
|
| 41 |
+
self.quant_type = quant_type
|
| 42 |
+
self.block_size = block_size
|
| 43 |
+
self.nodes_to_exclude = set(nodes_to_exclude)
|
| 44 |
+
|
| 45 |
+
@staticmethod
|
| 46 |
+
def __get_initializer(name, graph_path: list[GraphProto]) -> tuple[TensorProto, GraphProto]:
|
| 47 |
+
for gid in range(len(graph_path) - 1, -1, -1):
|
| 48 |
+
graph = graph_path[gid]
|
| 49 |
+
for tensor in graph.initializer:
|
| 50 |
+
if tensor.name == name:
|
| 51 |
+
return tensor, graph
|
| 52 |
+
return None, None
|
| 53 |
+
|
| 54 |
+
def bnb4_block_quant(self, fpweight: npt.ArrayLike) -> np.ndarray:
|
| 55 |
+
"""4b quantize fp32/fp16 weight"""
|
| 56 |
+
|
| 57 |
+
if len(fpweight.shape) != 2:
|
| 58 |
+
raise ValueError("Current bnb4 block quantization only supports 2D tensors!")
|
| 59 |
+
# need to copy since the transposed weight still has the original memory layout
|
| 60 |
+
# Linear4bit quantizes its weight data which is the transposed weight
|
| 61 |
+
fpweight_t = fpweight.transpose().copy()
|
| 62 |
+
|
| 63 |
+
rows, cols = fpweight.shape
|
| 64 |
+
numel = rows * cols
|
| 65 |
+
block_size = self.block_size
|
| 66 |
+
num_blocks = (numel + block_size - 1) // block_size
|
| 67 |
+
quantized_numel = (numel + 1) // 2
|
| 68 |
+
|
| 69 |
+
packed = np.zeros(quantized_numel, dtype="uint8")
|
| 70 |
+
absmax = np.zeros(num_blocks, dtype=fpweight.dtype)
|
| 71 |
+
# block wise quantization, fpweight_t is flattened and divided into blocks
|
| 72 |
+
quantize_matmul_bnb4(packed, fpweight_t, absmax, block_size, self.quant_type, cols, rows)
|
| 73 |
+
|
| 74 |
+
return (packed, absmax)
|
| 75 |
+
|
| 76 |
+
def _bnb4_matmul_node_weight(self, node: NodeProto, graph_stack: list[GraphProto]) -> NodeProto:
|
| 77 |
+
"""If the node is MatMul with fp32 const weight, quantize the weight with int4, and return the new node"""
|
| 78 |
+
|
| 79 |
+
if node.op_type != "MatMul":
|
| 80 |
+
return node # only care about MatMul for now
|
| 81 |
+
|
| 82 |
+
logger.debug(f"start to quantize {node.name} ...")
|
| 83 |
+
if node.name in self.nodes_to_exclude:
|
| 84 |
+
logger.debug(f"exclude to quantize {node.name} as specified by nodes_to_exclude...")
|
| 85 |
+
return node
|
| 86 |
+
|
| 87 |
+
inputB = node.input[1] # noqa: N806
|
| 88 |
+
B, Bs_graph = MatMulBnb4Quantizer.__get_initializer(inputB, graph_stack) # noqa: N806
|
| 89 |
+
if B is None:
|
| 90 |
+
logger.debug("MatMul doesn't have const weight. Skip to quantize")
|
| 91 |
+
return node # only care about constant weight
|
| 92 |
+
|
| 93 |
+
B_array = onnx.numpy_helper.to_array(B) # noqa: N806
|
| 94 |
+
if len(B_array.shape) != 2:
|
| 95 |
+
logger.debug("MatMul weight is not 2D. Skip to quantize")
|
| 96 |
+
return node # can only process 2-D matrix
|
| 97 |
+
|
| 98 |
+
packed, absmax = self.bnb4_block_quant(B_array)
|
| 99 |
+
B_quant = onnx.numpy_helper.from_array(packed) # noqa: N806
|
| 100 |
+
B_quant.name = B.name + "_Bnb4"
|
| 101 |
+
for input in Bs_graph.input:
|
| 102 |
+
if input.name == inputB:
|
| 103 |
+
Bs_graph.input.remove(input)
|
| 104 |
+
break
|
| 105 |
+
|
| 106 |
+
absmax_tensor = onnx.numpy_helper.from_array(absmax)
|
| 107 |
+
absmax_tensor.name = B.name + "_absmax"
|
| 108 |
+
|
| 109 |
+
Bs_graph.initializer.extend([B_quant, absmax_tensor])
|
| 110 |
+
|
| 111 |
+
kwargs = {}
|
| 112 |
+
rows, cols = B_array.shape
|
| 113 |
+
kwargs["K"] = rows
|
| 114 |
+
kwargs["N"] = cols
|
| 115 |
+
kwargs["block_size"] = self.block_size
|
| 116 |
+
kwargs["quant_type"] = self.quant_type
|
| 117 |
+
|
| 118 |
+
matmul_bnb4_node = onnx.helper.make_node(
|
| 119 |
+
"MatMulBnb4",
|
| 120 |
+
inputs=[node.input[0], B_quant.name, absmax_tensor.name],
|
| 121 |
+
outputs=[node.output[0]],
|
| 122 |
+
name=node.name + "_Bnb4" if node.name else "",
|
| 123 |
+
domain="com.microsoft",
|
| 124 |
+
**kwargs,
|
| 125 |
+
)
|
| 126 |
+
|
| 127 |
+
logger.debug(f"complete quantization of {node.name} ...")
|
| 128 |
+
|
| 129 |
+
return matmul_bnb4_node
|
| 130 |
+
|
| 131 |
+
def _process_subgraph(self, graph_stack: list[GraphProto]):
|
| 132 |
+
new_nodes = []
|
| 133 |
+
graph = graph_stack[-1]
|
| 134 |
+
|
| 135 |
+
for node in graph.node:
|
| 136 |
+
graph_attrs = [
|
| 137 |
+
attr
|
| 138 |
+
for attr in node.attribute
|
| 139 |
+
if attr.type == onnx.AttributeProto.GRAPH or attr.type == onnx.AttributeProto.GRAPHS
|
| 140 |
+
]
|
| 141 |
+
if graph_attrs:
|
| 142 |
+
kwargs = {}
|
| 143 |
+
for attr in node.attribute:
|
| 144 |
+
if attr.type == onnx.AttributeProto.GRAPH:
|
| 145 |
+
# recursive call to take care of sub-graph
|
| 146 |
+
graph_stack.append(attr.g)
|
| 147 |
+
kv = {attr.name: self._process_subgraph(graph_stack)}
|
| 148 |
+
elif attr.type == onnx.AttributeProto.GRAPHS:
|
| 149 |
+
value = []
|
| 150 |
+
for subgraph in attr.graphs:
|
| 151 |
+
# recursive call to take care of sub-graph
|
| 152 |
+
graph_stack.append(subgraph)
|
| 153 |
+
value.extend([self._process_subgraph(graph_stack)])
|
| 154 |
+
kv = {attr.name: value}
|
| 155 |
+
else:
|
| 156 |
+
kv = attribute_to_kwarg(attr)
|
| 157 |
+
kwargs.update(kv)
|
| 158 |
+
node = onnx.helper.make_node( # noqa: PLW2901
|
| 159 |
+
node.op_type, node.input, node.output, name=node.name, **kwargs
|
| 160 |
+
)
|
| 161 |
+
|
| 162 |
+
new_nodes.append(self._bnb4_matmul_node_weight(node, graph_stack))
|
| 163 |
+
|
| 164 |
+
graph.ClearField("node")
|
| 165 |
+
graph.node.extend(new_nodes)
|
| 166 |
+
graph_stack.pop()
|
| 167 |
+
return graph
|
| 168 |
+
|
| 169 |
+
def process(self):
|
| 170 |
+
# use a stack to keep track of sub-graphs
|
| 171 |
+
graph_stack = [self.model.graph()]
|
| 172 |
+
opset_import = self.model.opset_import()
|
| 173 |
+
|
| 174 |
+
has_ms_domain = False
|
| 175 |
+
for opset in opset_import:
|
| 176 |
+
if opset.domain == "com.microsoft":
|
| 177 |
+
has_ms_domain = True
|
| 178 |
+
if not has_ms_domain:
|
| 179 |
+
opset_import.extend([onnx.helper.make_opsetid("com.microsoft", 1)])
|
| 180 |
+
|
| 181 |
+
self._process_subgraph(graph_stack)
|
| 182 |
+
self.model.clean_initializers()
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
def parse_args():
|
| 186 |
+
parser = argparse.ArgumentParser(
|
| 187 |
+
description="""Blockwise FP4/NF4 quantization for MatMul 2D weight matrices.
|
| 188 |
+
|
| 189 |
+
A weight matrix is partitioned into blocks, where each block is a contiguous
|
| 190 |
+
subset inside the flattened transposed weight matrix. Each block is quantized
|
| 191 |
+
into a set of 4b integers with an absolute value scaling factor.
|
| 192 |
+
"""
|
| 193 |
+
)
|
| 194 |
+
|
| 195 |
+
parser.add_argument("--input_model", required=True, help="Path to the input model file")
|
| 196 |
+
parser.add_argument("--output_model", required=True, help="Path to the output model file")
|
| 197 |
+
parser.add_argument(
|
| 198 |
+
"--quant_type",
|
| 199 |
+
required=False,
|
| 200 |
+
default=1,
|
| 201 |
+
choices=[MatMulBnb4Quantizer.FP4, MatMulBnb4Quantizer.NF4],
|
| 202 |
+
help="Quantization data type. 0: FP4, 1: NF4",
|
| 203 |
+
)
|
| 204 |
+
parser.add_argument(
|
| 205 |
+
"--block_size",
|
| 206 |
+
required=False,
|
| 207 |
+
default=64,
|
| 208 |
+
help="Block size for blockwise quantization. Note: bnb.nn.Linear4bit only uses block_size=64",
|
| 209 |
+
)
|
| 210 |
+
parser.add_argument("-v", "--verbose", required=False, action="store_true")
|
| 211 |
+
parser.set_defaults(verbose=False)
|
| 212 |
+
parser.add_argument(
|
| 213 |
+
"--nodes_to_exclude",
|
| 214 |
+
nargs="+",
|
| 215 |
+
type=str,
|
| 216 |
+
required=False,
|
| 217 |
+
default=[],
|
| 218 |
+
help="Specify the nodes to be excluded from quantization with node names",
|
| 219 |
+
)
|
| 220 |
+
|
| 221 |
+
return parser.parse_args()
|
| 222 |
+
|
| 223 |
+
|
| 224 |
+
if __name__ == "__main__":
|
| 225 |
+
args = parse_args()
|
| 226 |
+
if args.verbose:
|
| 227 |
+
logger.setLevel(logging.DEBUG)
|
| 228 |
+
|
| 229 |
+
input_model_path = args.input_model
|
| 230 |
+
output_model_path = args.output_model
|
| 231 |
+
|
| 232 |
+
if os.path.exists(output_model_path):
|
| 233 |
+
logger.error(f"file {output_model_path} already exists")
|
| 234 |
+
raise Exception(f"file {output_model_path} already exists")
|
| 235 |
+
|
| 236 |
+
model = onnx.load(input_model_path)
|
| 237 |
+
quant = MatMulBnb4Quantizer(model, args.quant_type, args.block_size, nodes_to_exclude=args.nodes_to_exclude)
|
| 238 |
+
quant.process()
|
| 239 |
+
quant.model.save_model_to_file(output_model_path, True)
|
micromamba_root/envs/pytorch_env/Lib/site-packages/onnxruntime/quantization/matmul_nbits_quantizer.py
ADDED
|
@@ -0,0 +1,1638 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -------------------------------------------------------------------------
|
| 2 |
+
# Copyright (c) Microsoft Corporation. All rights reserved.
|
| 3 |
+
# Licensed under the MIT License. See License.txt in the project root for
|
| 4 |
+
# license information.
|
| 5 |
+
# --------------------------------------------------------------------------
|
| 6 |
+
|
| 7 |
+
from __future__ import annotations
|
| 8 |
+
|
| 9 |
+
import argparse
|
| 10 |
+
import copy
|
| 11 |
+
import logging
|
| 12 |
+
import os
|
| 13 |
+
|
| 14 |
+
import ml_dtypes
|
| 15 |
+
import numpy as np
|
| 16 |
+
import numpy.typing as npt
|
| 17 |
+
import onnx
|
| 18 |
+
import onnx_ir as ir
|
| 19 |
+
from onnx.onnx_pb import GraphProto, ModelProto, NodeProto, TensorProto
|
| 20 |
+
|
| 21 |
+
from onnxruntime.capi._pybind_state import (
|
| 22 |
+
quantize_matmul_2bits,
|
| 23 |
+
quantize_matmul_4bits,
|
| 24 |
+
quantize_matmul_8bits,
|
| 25 |
+
quantize_qdq_matmul_4bits,
|
| 26 |
+
)
|
| 27 |
+
|
| 28 |
+
from .calibrate import CalibrationDataReader
|
| 29 |
+
from .neural_compressor import gptq_quantize, rtn_quantize
|
| 30 |
+
from .onnx_model import ONNXModel
|
| 31 |
+
from .quant_utils import QuantFormat, attribute_to_kwarg
|
| 32 |
+
|
| 33 |
+
logging.basicConfig(format="%(asctime)s %(name)s [%(levelname)s] - %(message)s", level=logging.INFO)
|
| 34 |
+
logger = logging.getLogger(__name__)
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
class WeightOnlyQuantConfig:
|
| 38 |
+
def __init__(
|
| 39 |
+
self,
|
| 40 |
+
algorithm: str,
|
| 41 |
+
quant_format: QuantFormat,
|
| 42 |
+
op_types_to_quantize: tuple[str, ...] | None = None,
|
| 43 |
+
quant_axes: tuple[tuple[str, int], ...] | None = None,
|
| 44 |
+
customized_weight_config: dict | None = None,
|
| 45 |
+
):
|
| 46 |
+
"""This is the Base class for Weight Only blockwise quantization Configuration.
|
| 47 |
+
|
| 48 |
+
Args:
|
| 49 |
+
algorithm:
|
| 50 |
+
weight only quantize algorithm name.
|
| 51 |
+
quant_format: QuantFormat{QOperator, QDQ}.
|
| 52 |
+
QOperator format quantizes the model with quantized operators directly.
|
| 53 |
+
QDQ format quantize the model by inserting QuantizeLinear/DeQuantizeLinear on the tensor.
|
| 54 |
+
op_types_to_quantize (optional):
|
| 55 |
+
set of operator types to quantize. Default {MatMul}
|
| 56 |
+
quant_axes (dict[str, int], optional):
|
| 57 |
+
op:axis, which axis to quantize for an op. Default {MatMul: 0, Gather: 1}
|
| 58 |
+
customized_weight_config:
|
| 59 |
+
customized weight config for nodes if needed. It is dictionary with node name as key,
|
| 60 |
+
and the value is a dict of customized config.
|
| 61 |
+
"""
|
| 62 |
+
self.algorithm = algorithm
|
| 63 |
+
self.quant_format = quant_format
|
| 64 |
+
self.op_types_to_quantize = set(op_types_to_quantize) if op_types_to_quantize else {"MatMul"}
|
| 65 |
+
self.quant_axes = dict(quant_axes) if quant_axes else {"MatMul": 0, "Gather": 1}
|
| 66 |
+
self.customized_weight_config = customized_weight_config
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
class RTNWeightOnlyQuantConfig(WeightOnlyQuantConfig):
|
| 70 |
+
def __init__(
|
| 71 |
+
self,
|
| 72 |
+
ratios=None,
|
| 73 |
+
quant_format=QuantFormat.QOperator,
|
| 74 |
+
op_types_to_quantize: tuple[str, ...] | None = None,
|
| 75 |
+
customized_weight_config: dict | None = None,
|
| 76 |
+
):
|
| 77 |
+
"""
|
| 78 |
+
This is a class for round-to-nearest (RTN) algorithm Weight Only Quant Configuration.
|
| 79 |
+
RTN is the most straightforward way to quantize weight using scale maps.
|
| 80 |
+
|
| 81 |
+
Args:
|
| 82 |
+
ratios:
|
| 83 |
+
percentile of clip. Defaults to {}.
|
| 84 |
+
quant_format (QuantFormat{QOperator, QDQ}, optional):
|
| 85 |
+
QOperator format quantizes the model with quantized operators directly.
|
| 86 |
+
QDQ format quantize the model by inserting QuantizeLinear/DeQuantizeLinear on the tensor.
|
| 87 |
+
Defaults to QuantFormat.QOperator.
|
| 88 |
+
op_types_to_quantize (optional):
|
| 89 |
+
set of operator types to quantize.
|
| 90 |
+
customized_weight_config:
|
| 91 |
+
customized weight config for nodes if needed. It is dictionary with node name as key,
|
| 92 |
+
and the value is a dict of customized config.
|
| 93 |
+
"""
|
| 94 |
+
assert quant_format == QuantFormat.QOperator, "RTN only supports QOperator format"
|
| 95 |
+
|
| 96 |
+
if ratios is None:
|
| 97 |
+
ratios = {}
|
| 98 |
+
super().__init__(
|
| 99 |
+
algorithm="RTN",
|
| 100 |
+
quant_format=quant_format,
|
| 101 |
+
op_types_to_quantize=op_types_to_quantize,
|
| 102 |
+
customized_weight_config=customized_weight_config,
|
| 103 |
+
)
|
| 104 |
+
self.ratios = ratios
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
class KQuantWeightOnlyQuantConfig(WeightOnlyQuantConfig):
|
| 108 |
+
def __init__(
|
| 109 |
+
self,
|
| 110 |
+
ratios=None,
|
| 111 |
+
quant_format=QuantFormat.QOperator,
|
| 112 |
+
op_types_to_quantize: tuple[str, ...] | None = None,
|
| 113 |
+
customized_weight_config: dict | None = None,
|
| 114 |
+
):
|
| 115 |
+
"""
|
| 116 |
+
This is a class for k-quant algorithm Weight Only Quant Configuration.
|
| 117 |
+
|
| 118 |
+
Args:
|
| 119 |
+
ratios:
|
| 120 |
+
percentile of clip. Defaults to {}.
|
| 121 |
+
quant_format (QuantFormat{QOperator, QDQ}, optional):
|
| 122 |
+
QOperator format quantizes the model with quantized operators directly.
|
| 123 |
+
QDQ format quantize the model by inserting QuantizeLinear/DeQuantizeLinear on the tensor.
|
| 124 |
+
Defaults to QuantFormat.QOperator.
|
| 125 |
+
op_types_to_quantize (optional):
|
| 126 |
+
set of operator types to quantize.
|
| 127 |
+
"""
|
| 128 |
+
assert quant_format == QuantFormat.QOperator, "k-quant only supports QOperator format"
|
| 129 |
+
|
| 130 |
+
if ratios is None:
|
| 131 |
+
ratios = {}
|
| 132 |
+
super().__init__(
|
| 133 |
+
algorithm="k_quant",
|
| 134 |
+
quant_format=quant_format,
|
| 135 |
+
op_types_to_quantize=op_types_to_quantize,
|
| 136 |
+
customized_weight_config=customized_weight_config,
|
| 137 |
+
)
|
| 138 |
+
self.ratios = ratios
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
class GPTQWeightOnlyQuantConfig(WeightOnlyQuantConfig):
|
| 142 |
+
def __init__(
|
| 143 |
+
self,
|
| 144 |
+
calibration_data_reader: CalibrationDataReader | None = None,
|
| 145 |
+
percdamp=0.01,
|
| 146 |
+
block_size=128,
|
| 147 |
+
actorder=False,
|
| 148 |
+
mse=False,
|
| 149 |
+
perchannel=True,
|
| 150 |
+
quant_format=QuantFormat.QOperator,
|
| 151 |
+
op_types_to_quantize: tuple[str, ...] | None = None,
|
| 152 |
+
):
|
| 153 |
+
"""
|
| 154 |
+
This is a class for GPTQ algorithm Weight Only Quant Configuration.
|
| 155 |
+
GPTQ algorithm provides more accurate quantization but requires more computational resources.
|
| 156 |
+
|
| 157 |
+
Args:
|
| 158 |
+
calibration_data_reader:
|
| 159 |
+
a calibration data reader. It enumerates calibration data and generates inputs for the original model.
|
| 160 |
+
percdamp:
|
| 161 |
+
percent of the average Hessian diagonal to use for dampening.
|
| 162 |
+
block_size (int, optional):
|
| 163 |
+
channel number in one block to execute a GPTQ quantization iteration.
|
| 164 |
+
actorder (bool, optional):
|
| 165 |
+
whether rearrange Hessian matrix considering the diag's value.
|
| 166 |
+
mse (bool, optional):
|
| 167 |
+
whether get scale and zero point with mse error.
|
| 168 |
+
perchannel (bool, optional):
|
| 169 |
+
whether quantize weight per-channel.
|
| 170 |
+
quant_format (QuantFormat{QOperator, QDQ}, optional):
|
| 171 |
+
QOperator format quantizes the model with quantized operators directly.
|
| 172 |
+
QDQ format quantize the model by inserting QuantizeLinear/DeQuantizeLinear on the tensor.
|
| 173 |
+
Defaults to QuantFormat.QOperator.
|
| 174 |
+
op_types_to_quantize (optional):
|
| 175 |
+
set of operator types to quantize.
|
| 176 |
+
"""
|
| 177 |
+
assert quant_format == QuantFormat.QOperator, "GPTQ only supports QOperator format"
|
| 178 |
+
|
| 179 |
+
super().__init__(
|
| 180 |
+
algorithm="GPTQ",
|
| 181 |
+
quant_format=quant_format,
|
| 182 |
+
op_types_to_quantize=op_types_to_quantize,
|
| 183 |
+
)
|
| 184 |
+
self.calibration_data_reader = calibration_data_reader
|
| 185 |
+
self.percdamp = percdamp
|
| 186 |
+
self.block_size = block_size
|
| 187 |
+
self.actorder = actorder
|
| 188 |
+
self.mse = mse
|
| 189 |
+
self.perchannel = perchannel
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
class HQQWeightOnlyQuantConfig(WeightOnlyQuantConfig):
|
| 193 |
+
def __init__(
|
| 194 |
+
self,
|
| 195 |
+
block_size=128,
|
| 196 |
+
bits=4,
|
| 197 |
+
axis=1,
|
| 198 |
+
quant_format=QuantFormat.QOperator,
|
| 199 |
+
op_types_to_quantize: tuple[str, ...] | None = None,
|
| 200 |
+
quant_axes: tuple[tuple[str, int], ...] | None = None,
|
| 201 |
+
):
|
| 202 |
+
"""
|
| 203 |
+
This is a class for HQQ algorithm Weight Only Quant Configuration.
|
| 204 |
+
HQQ algorithm quant weight without needing calibrate data.
|
| 205 |
+
|
| 206 |
+
Args:
|
| 207 |
+
block_size (int, optional):
|
| 208 |
+
channel number in one block to execute a HQQ quantization iteration.
|
| 209 |
+
bits (int, optional):
|
| 210 |
+
how many bits to represent weight.
|
| 211 |
+
axis (int, optional):
|
| 212 |
+
0 or 1. which axis to quantize. https://arxiv.org/pdf/2309.15531.pdf
|
| 213 |
+
quant_format (QuantFormat{QOperator, QDQ}, optional):
|
| 214 |
+
QOperator format quantizes the model with quantized operators directly.
|
| 215 |
+
QDQ format quantize the model by inserting QuantizeLinear/DeQuantizeLinear on the tensor.
|
| 216 |
+
Defaults to QuantFormat.QOperator.
|
| 217 |
+
op_types_to_quantize (optional):
|
| 218 |
+
set of operator types to quantize.
|
| 219 |
+
quant_axes (dict[str, int], optional):
|
| 220 |
+
op:axis, which axis to quantize for an op. Default {MatMul: 0, Gather: 1}
|
| 221 |
+
"""
|
| 222 |
+
assert quant_format == QuantFormat.QOperator, "HQQ only supports QOperator format"
|
| 223 |
+
|
| 224 |
+
super().__init__(
|
| 225 |
+
algorithm="HQQ",
|
| 226 |
+
quant_format=quant_format,
|
| 227 |
+
op_types_to_quantize=op_types_to_quantize,
|
| 228 |
+
quant_axes=quant_axes,
|
| 229 |
+
)
|
| 230 |
+
self.block_size = block_size
|
| 231 |
+
self.bits = bits
|
| 232 |
+
self.axis = axis
|
| 233 |
+
|
| 234 |
+
|
| 235 |
+
class DefaultWeightOnlyQuantConfig(WeightOnlyQuantConfig):
|
| 236 |
+
def __init__(
|
| 237 |
+
self,
|
| 238 |
+
block_size: int = 128,
|
| 239 |
+
is_symmetric: bool = False,
|
| 240 |
+
accuracy_level: int | None = None,
|
| 241 |
+
quant_format=QuantFormat.QOperator,
|
| 242 |
+
op_types_to_quantize: tuple[str, ...] | None = None,
|
| 243 |
+
quant_axes: tuple[tuple[str, int], ...] | None = None,
|
| 244 |
+
bits: int = 4,
|
| 245 |
+
channel_wised_quantize: bool = False,
|
| 246 |
+
):
|
| 247 |
+
"""
|
| 248 |
+
This is a class for weight only affine quantization configuration.
|
| 249 |
+
|
| 250 |
+
Args:
|
| 251 |
+
block_size (int, optional):
|
| 252 |
+
channel number in one block to execute an affine quantization iteration.
|
| 253 |
+
is_symmetric (bool, optional):
|
| 254 |
+
whether quantize weight symmetrically.
|
| 255 |
+
accuracy_level (int, optional):
|
| 256 |
+
Accuracy level of the 4-bit quantized MatMul computation.
|
| 257 |
+
Refer to the MatMulNBits contrib op's 'accuracy_level' attribute for details.
|
| 258 |
+
(https://github.com/microsoft/onnxruntime/blob/main/docs/ContribOperators.md#commicrosoftmatmulnbits)
|
| 259 |
+
quant_format (QuantFormat{QOperator, QDQ}, optional):
|
| 260 |
+
QOperator format quantizes the model with quantized operators directly.
|
| 261 |
+
QDQ format quantize the model by inserting QuantizeLinear/DeQuantizeLinear on the tensor.
|
| 262 |
+
Defaults to QuantFormat.QOperator.
|
| 263 |
+
op_types_to_quantize (optional):
|
| 264 |
+
set of operator types to quantize.
|
| 265 |
+
quant_axes (dict[str, int], optional):
|
| 266 |
+
op:axis, which axis to quantize for an op. Default {MatMul: 0, Gather: 1}
|
| 267 |
+
bits (int, optional):
|
| 268 |
+
number of bits per element after quantization. Default 4.
|
| 269 |
+
"""
|
| 270 |
+
super().__init__(
|
| 271 |
+
algorithm="DEFAULT",
|
| 272 |
+
quant_format=quant_format,
|
| 273 |
+
op_types_to_quantize=op_types_to_quantize,
|
| 274 |
+
quant_axes=quant_axes,
|
| 275 |
+
)
|
| 276 |
+
self.block_size = block_size
|
| 277 |
+
self.is_symmetric = is_symmetric
|
| 278 |
+
self.bits = bits
|
| 279 |
+
self.accuracy_level = accuracy_level
|
| 280 |
+
self.channel_wised_quantize = channel_wised_quantize
|
| 281 |
+
if channel_wised_quantize and quant_format == QuantFormat.QOperator:
|
| 282 |
+
raise NotImplementedError("QuantFormat.QOperator is not supported channel_wised_quantize yet")
|
| 283 |
+
|
| 284 |
+
|
| 285 |
+
class NVAWQWeightOnlyQuantConfig(WeightOnlyQuantConfig):
|
| 286 |
+
def __init__(
|
| 287 |
+
self,
|
| 288 |
+
tokenizer_dir,
|
| 289 |
+
dataset_name="cnn",
|
| 290 |
+
cache_dir="./cache",
|
| 291 |
+
calibration_method="awq_lite",
|
| 292 |
+
):
|
| 293 |
+
"""
|
| 294 |
+
Configuration for the nvidia_awq quantization method.
|
| 295 |
+
|
| 296 |
+
Args:
|
| 297 |
+
tokenizer_dir (str): pathof the tokenizer dir.
|
| 298 |
+
dataset_name (str): Name of the dataset.
|
| 299 |
+
cache_dir (str): Directory for caching.
|
| 300 |
+
calibration_method (str): calib method for nvidia_awq.
|
| 301 |
+
"""
|
| 302 |
+
# Import torch and DataLoader
|
| 303 |
+
try:
|
| 304 |
+
import torch # noqa: PLC0415
|
| 305 |
+
from torch.utils.data import DataLoader # noqa: PLC0415
|
| 306 |
+
|
| 307 |
+
self.torch = torch
|
| 308 |
+
self.DataLoader = DataLoader
|
| 309 |
+
except ImportError:
|
| 310 |
+
print(
|
| 311 |
+
"Error: The 'torch' library is required but not installed. Please install it using 'pip install torch'."
|
| 312 |
+
)
|
| 313 |
+
raise ImportError("torch is not installed. Exiting.") from None
|
| 314 |
+
|
| 315 |
+
# Import datasets
|
| 316 |
+
try:
|
| 317 |
+
from datasets import load_dataset # noqa: PLC0415
|
| 318 |
+
|
| 319 |
+
self.load_dataset = load_dataset
|
| 320 |
+
except ImportError:
|
| 321 |
+
print(
|
| 322 |
+
"Error: The 'datasets' library is required but not installed. Please install it using 'pip install datasets'."
|
| 323 |
+
)
|
| 324 |
+
raise ImportError("datasets is not installed. Exiting.") from None
|
| 325 |
+
|
| 326 |
+
# Import transformers
|
| 327 |
+
try:
|
| 328 |
+
from transformers import AutoConfig, AutoTokenizer # noqa: PLC0415
|
| 329 |
+
|
| 330 |
+
self.AutoConfig = AutoConfig
|
| 331 |
+
self.AutoTokenizer = AutoTokenizer
|
| 332 |
+
except ImportError:
|
| 333 |
+
print(
|
| 334 |
+
"Error: The 'transformers' library is required but not installed. Please install it using 'pip install transformers'."
|
| 335 |
+
)
|
| 336 |
+
raise ImportError("transformers is not installed. Exiting.") from None
|
| 337 |
+
|
| 338 |
+
super().__init__(
|
| 339 |
+
algorithm="nvidia_awq",
|
| 340 |
+
quant_format=QuantFormat.QDQ,
|
| 341 |
+
op_types_to_quantize=None, # Assuming op_types_to_quantize is handled elsewhere
|
| 342 |
+
quant_axes=None, # Assuming quant_axes is handled elsewhere
|
| 343 |
+
)
|
| 344 |
+
|
| 345 |
+
# Determine the device
|
| 346 |
+
device = self.torch.device("cuda" if self.torch.cuda.is_available() else "cpu")
|
| 347 |
+
|
| 348 |
+
calib_inputs = self.get_calib_inputs(
|
| 349 |
+
dataset_name=dataset_name,
|
| 350 |
+
model_name=tokenizer_dir,
|
| 351 |
+
cache_dir=cache_dir,
|
| 352 |
+
calib_size=32,
|
| 353 |
+
batch_size=1,
|
| 354 |
+
block_size=512,
|
| 355 |
+
device=device,
|
| 356 |
+
use_fp16=True,
|
| 357 |
+
use_buffer_share=False,
|
| 358 |
+
add_past_kv_inputs=True,
|
| 359 |
+
max_calib_rows_to_load=128,
|
| 360 |
+
add_position_ids=True,
|
| 361 |
+
)
|
| 362 |
+
|
| 363 |
+
self.calibration_data_reader = calib_inputs
|
| 364 |
+
self.calibration_method = calibration_method
|
| 365 |
+
|
| 366 |
+
def make_model_input(
|
| 367 |
+
self,
|
| 368 |
+
config,
|
| 369 |
+
input_ids_arg,
|
| 370 |
+
attention_mask_arg,
|
| 371 |
+
add_past_kv_inputs,
|
| 372 |
+
device,
|
| 373 |
+
use_fp16,
|
| 374 |
+
use_buffer_share,
|
| 375 |
+
add_position_ids,
|
| 376 |
+
):
|
| 377 |
+
# Access torch from the instance variable
|
| 378 |
+
torch = self.torch
|
| 379 |
+
|
| 380 |
+
input_ids = input_ids_arg
|
| 381 |
+
attention_mask = attention_mask_arg
|
| 382 |
+
|
| 383 |
+
if isinstance(input_ids_arg, list):
|
| 384 |
+
input_ids = torch.tensor(input_ids_arg, device=device, dtype=torch.int64)
|
| 385 |
+
attention_mask = torch.tensor(attention_mask_arg, device=device, dtype=torch.int64)
|
| 386 |
+
|
| 387 |
+
inputs = {
|
| 388 |
+
"input_ids": input_ids.contiguous(),
|
| 389 |
+
"attention_mask": attention_mask.contiguous(),
|
| 390 |
+
}
|
| 391 |
+
|
| 392 |
+
if add_position_ids:
|
| 393 |
+
position_ids = attention_mask.long().cumsum(-1) - 1
|
| 394 |
+
position_ids.masked_fill_(attention_mask == 0, 1)
|
| 395 |
+
inputs["position_ids"] = position_ids.contiguous()
|
| 396 |
+
|
| 397 |
+
if add_past_kv_inputs:
|
| 398 |
+
torch_dtype = torch.float16 if use_fp16 else torch.float32
|
| 399 |
+
batch_size, sequence_length = input_ids.shape
|
| 400 |
+
max_sequence_length = config.max_position_embeddings
|
| 401 |
+
num_heads, head_size = (
|
| 402 |
+
config.num_key_value_heads,
|
| 403 |
+
config.hidden_size // config.num_attention_heads,
|
| 404 |
+
)
|
| 405 |
+
for i in range(config.num_hidden_layers):
|
| 406 |
+
past_key = torch.zeros(
|
| 407 |
+
batch_size,
|
| 408 |
+
num_heads,
|
| 409 |
+
max_sequence_length if use_buffer_share else 0,
|
| 410 |
+
head_size,
|
| 411 |
+
device=device,
|
| 412 |
+
dtype=torch_dtype,
|
| 413 |
+
)
|
| 414 |
+
past_value = torch.zeros(
|
| 415 |
+
batch_size,
|
| 416 |
+
num_heads,
|
| 417 |
+
max_sequence_length if use_buffer_share else 0,
|
| 418 |
+
head_size,
|
| 419 |
+
device=device,
|
| 420 |
+
dtype=torch_dtype,
|
| 421 |
+
)
|
| 422 |
+
inputs.update(
|
| 423 |
+
{
|
| 424 |
+
f"past_key_values.{i}.key": past_key.contiguous(),
|
| 425 |
+
f"past_key_values.{i}.value": past_value.contiguous(),
|
| 426 |
+
}
|
| 427 |
+
)
|
| 428 |
+
|
| 429 |
+
return inputs
|
| 430 |
+
|
| 431 |
+
def get_calib_inputs(
|
| 432 |
+
self,
|
| 433 |
+
dataset_name,
|
| 434 |
+
model_name,
|
| 435 |
+
cache_dir,
|
| 436 |
+
calib_size,
|
| 437 |
+
batch_size,
|
| 438 |
+
block_size,
|
| 439 |
+
device,
|
| 440 |
+
use_fp16,
|
| 441 |
+
use_buffer_share,
|
| 442 |
+
add_past_kv_inputs,
|
| 443 |
+
max_calib_rows_to_load,
|
| 444 |
+
add_position_ids,
|
| 445 |
+
):
|
| 446 |
+
# Access transformers and datasets from the instance variables
|
| 447 |
+
auto_config = self.AutoConfig
|
| 448 |
+
auto_tokenizer = self.AutoTokenizer
|
| 449 |
+
load_dataset = self.load_dataset
|
| 450 |
+
|
| 451 |
+
config = auto_config.from_pretrained(
|
| 452 |
+
model_name, use_auth_token=True, cache_dir=cache_dir, trust_remote_code=True
|
| 453 |
+
)
|
| 454 |
+
tokenizer = auto_tokenizer.from_pretrained(
|
| 455 |
+
model_name, use_auth_token=True, cache_dir=cache_dir, trust_remote_code=True
|
| 456 |
+
)
|
| 457 |
+
tokenizer.add_special_tokens({"pad_token": "[PAD]"})
|
| 458 |
+
tokenizer.pad_token = tokenizer.eos_token
|
| 459 |
+
|
| 460 |
+
assert calib_size <= max_calib_rows_to_load, "calib size should be no more than max_calib_rows_to_load"
|
| 461 |
+
|
| 462 |
+
if "cnn" in dataset_name:
|
| 463 |
+
dataset2 = load_dataset("cnn_dailymail", name="3.0.0", split="train").select(range(max_calib_rows_to_load))
|
| 464 |
+
column = "article"
|
| 465 |
+
elif "pile" in dataset_name:
|
| 466 |
+
dataset2 = load_dataset("mit-han-lab/pile-val-backup", split="validation")
|
| 467 |
+
column = "text"
|
| 468 |
+
else:
|
| 469 |
+
raise ValueError(f'dataset "{dataset_name}" not supported')
|
| 470 |
+
|
| 471 |
+
dataset2 = dataset2[column][:calib_size]
|
| 472 |
+
batch_encoded = tokenizer.batch_encode_plus(
|
| 473 |
+
dataset2, return_tensors="pt", padding=True, truncation=True, max_length=block_size
|
| 474 |
+
)
|
| 475 |
+
batch_encoded = batch_encoded.to(device)
|
| 476 |
+
batch_encoded_input_ids = batch_encoded["input_ids"]
|
| 477 |
+
batch_encoded_attention_mask = batch_encoded["attention_mask"]
|
| 478 |
+
|
| 479 |
+
# Access DataLoader from the instance variable
|
| 480 |
+
data_loader = self.DataLoader
|
| 481 |
+
|
| 482 |
+
calib_dataloader_input_ids = data_loader(batch_encoded_input_ids, batch_size=batch_size, shuffle=False)
|
| 483 |
+
calib_dataloader_attention_mask = data_loader(
|
| 484 |
+
batch_encoded_attention_mask, batch_size=batch_size, shuffle=False
|
| 485 |
+
)
|
| 486 |
+
|
| 487 |
+
assert len(calib_dataloader_input_ids.dataset) == len(calib_dataloader_attention_mask.dataset)
|
| 488 |
+
assert len(calib_dataloader_input_ids) == len(calib_dataloader_attention_mask)
|
| 489 |
+
|
| 490 |
+
number_of_batched_samples = calib_size // batch_size
|
| 491 |
+
|
| 492 |
+
batched_input_ids = []
|
| 493 |
+
for idx, data in enumerate(calib_dataloader_input_ids):
|
| 494 |
+
batched_input_ids.append(data)
|
| 495 |
+
if idx == (number_of_batched_samples - 1):
|
| 496 |
+
break
|
| 497 |
+
|
| 498 |
+
batched_attention_mask = []
|
| 499 |
+
for idx, data in enumerate(calib_dataloader_attention_mask):
|
| 500 |
+
batched_attention_mask.append(data)
|
| 501 |
+
if idx == (number_of_batched_samples - 1):
|
| 502 |
+
break
|
| 503 |
+
|
| 504 |
+
print(
|
| 505 |
+
f"\n--Quantize-Script-- number_of_batched_samples={number_of_batched_samples}, "
|
| 506 |
+
f"batch-input-ids-list-len={len(batched_input_ids)}, batched_attention_mask={len(batched_attention_mask)}\n"
|
| 507 |
+
)
|
| 508 |
+
|
| 509 |
+
batched_inputs_list = []
|
| 510 |
+
for i in range(number_of_batched_samples):
|
| 511 |
+
input_ids = batched_input_ids[i]
|
| 512 |
+
attention_mask = batched_attention_mask[i]
|
| 513 |
+
|
| 514 |
+
inputs = self.make_model_input(
|
| 515 |
+
config,
|
| 516 |
+
input_ids,
|
| 517 |
+
attention_mask,
|
| 518 |
+
add_past_kv_inputs,
|
| 519 |
+
device,
|
| 520 |
+
use_fp16,
|
| 521 |
+
use_buffer_share,
|
| 522 |
+
add_position_ids,
|
| 523 |
+
)
|
| 524 |
+
inputs = {input_name: torch_tensor.cpu().numpy() for input_name, torch_tensor in inputs.items()}
|
| 525 |
+
batched_inputs_list.append(inputs)
|
| 526 |
+
|
| 527 |
+
print(f"\n--Quantize-Script-- number of batched inputs = {len(batched_inputs_list)}\n")
|
| 528 |
+
return batched_inputs_list
|
| 529 |
+
|
| 530 |
+
|
| 531 |
+
def is_divisible(val1, val2):
|
| 532 |
+
return int(val2 * np.ceil(val1 / val2)) == val1
|
| 533 |
+
|
| 534 |
+
|
| 535 |
+
class HQQWeightOnlyQuantizer:
|
| 536 |
+
def __init__(
|
| 537 |
+
self,
|
| 538 |
+
config: HQQWeightOnlyQuantConfig,
|
| 539 |
+
):
|
| 540 |
+
self.config = config
|
| 541 |
+
|
| 542 |
+
# Proximal solver || weight - dequantize(quantize(weight))||_p^p
|
| 543 |
+
@staticmethod
|
| 544 |
+
def optimize_weights(
|
| 545 |
+
tensor,
|
| 546 |
+
scale,
|
| 547 |
+
zero,
|
| 548 |
+
min_max: list[int],
|
| 549 |
+
axis: int = 0,
|
| 550 |
+
opt_params: dict | None = None,
|
| 551 |
+
verbose=False,
|
| 552 |
+
):
|
| 553 |
+
import torch # noqa: PLC0415
|
| 554 |
+
|
| 555 |
+
opt_params = {"lp_norm": 0.7, "beta": 1e1, "kappa": 1.01, "iters": 20} if opt_params is None else opt_params
|
| 556 |
+
lp_norm, beta, kappa, iters = (
|
| 557 |
+
opt_params["lp_norm"],
|
| 558 |
+
opt_params["beta"],
|
| 559 |
+
opt_params["kappa"],
|
| 560 |
+
opt_params["iters"],
|
| 561 |
+
)
|
| 562 |
+
|
| 563 |
+
dtype = torch.float16 if tensor.is_cuda else torch.float32
|
| 564 |
+
w_f = tensor.to(dtype)
|
| 565 |
+
scale = scale.to(dtype)
|
| 566 |
+
zero = zero.to(dtype)
|
| 567 |
+
|
| 568 |
+
def shrink_op(x, beta, p=lp_norm):
|
| 569 |
+
if p == 1:
|
| 570 |
+
return torch.sign(x) * torch.nn.functional.relu(torch.abs(x) - 1.0 / beta)
|
| 571 |
+
else:
|
| 572 |
+
return torch.sign(x) * torch.nn.functional.relu(
|
| 573 |
+
torch.abs(x) - (1.0 / beta) * torch.pow(torch.abs(x) + 1e-8, p - 1)
|
| 574 |
+
)
|
| 575 |
+
|
| 576 |
+
best_error = 1e4
|
| 577 |
+
for i in range(iters):
|
| 578 |
+
w_q = torch.round(w_f * scale + zero).clamp(min_max[0], min_max[1])
|
| 579 |
+
w_r = (w_q - zero) / scale
|
| 580 |
+
w_e = shrink_op(w_f - w_r, beta)
|
| 581 |
+
zero = torch.mean(w_q - (w_f - w_e) * scale, axis=axis, keepdim=True)
|
| 582 |
+
beta *= kappa
|
| 583 |
+
|
| 584 |
+
current_error = float(torch.abs(w_f - w_r).mean())
|
| 585 |
+
if verbose:
|
| 586 |
+
print(i, np.round(current_error, 6))
|
| 587 |
+
if current_error < best_error:
|
| 588 |
+
best_error = current_error
|
| 589 |
+
else:
|
| 590 |
+
break
|
| 591 |
+
|
| 592 |
+
del w_f, w_q, w_r, w_e
|
| 593 |
+
|
| 594 |
+
return scale, zero
|
| 595 |
+
|
| 596 |
+
@staticmethod
|
| 597 |
+
def pack_on_row_fast_248bit(pack_tensor, ori_int_tensor, bits):
|
| 598 |
+
if pack_tensor.shape[0] == ori_int_tensor.shape[0]:
|
| 599 |
+
ori_int_tensor = ori_int_tensor.T
|
| 600 |
+
pack_tensor = pack_tensor.T
|
| 601 |
+
if bits in [2, 4, 8]:
|
| 602 |
+
compress_ratio = pack_tensor.element_size() * 8 // bits
|
| 603 |
+
for j in range(compress_ratio):
|
| 604 |
+
pack_tensor[0:] |= ori_int_tensor[j::compress_ratio] << (bits * (j))
|
| 605 |
+
else:
|
| 606 |
+
raise NotImplementedError("Only 2,4,8 bits are supported.")
|
| 607 |
+
|
| 608 |
+
# from Official implementation of Half-Quadratic Quantization (HQQ)
|
| 609 |
+
def quantize_internal(
|
| 610 |
+
self, tensor, bits=4, channel_wise=True, group_size=64, optimize=True, round_zero=True, axis=1
|
| 611 |
+
):
|
| 612 |
+
import torch # noqa: PLC0415
|
| 613 |
+
|
| 614 |
+
weight = tensor.float()
|
| 615 |
+
ori_shape = weight.shape
|
| 616 |
+
|
| 617 |
+
pad_len = (group_size - ori_shape[axis] % group_size) % group_size
|
| 618 |
+
if axis == 1:
|
| 619 |
+
weight = torch.nn.functional.pad(weight, (0, pad_len), "constant", 0)
|
| 620 |
+
else:
|
| 621 |
+
weight = torch.nn.functional.pad(weight, (0, 0, 0, pad_len), "constant", 0)
|
| 622 |
+
shape = weight.shape
|
| 623 |
+
|
| 624 |
+
# Reshape for grouping
|
| 625 |
+
if (group_size is not None) and channel_wise:
|
| 626 |
+
weight = weight.reshape([-1, group_size]) if (axis == 1) else weight.reshape([group_size, -1])
|
| 627 |
+
|
| 628 |
+
# Get min/max values
|
| 629 |
+
if channel_wise is False:
|
| 630 |
+
_min, _max = weight.min(), weight.max()
|
| 631 |
+
optimize = False
|
| 632 |
+
else:
|
| 633 |
+
_min = weight.min(axis=axis, keepdim=True)[0]
|
| 634 |
+
_max = weight.max(axis=axis, keepdim=True)[0]
|
| 635 |
+
|
| 636 |
+
max_v = 2**bits - 1
|
| 637 |
+
min_v = 0
|
| 638 |
+
min_max = [min_v, max_v]
|
| 639 |
+
|
| 640 |
+
# Note: here we work with the inverse of the scale to avoid division and quantize instead via weight*scale + zero, the scale is inverted later on.
|
| 641 |
+
# clamp to avoid half-precision problems
|
| 642 |
+
scale = (max_v / (_max - _min)).clamp(max=2e4)
|
| 643 |
+
#!!!!!!!!!!!!!!!
|
| 644 |
+
min_max_axis = _max - _min
|
| 645 |
+
if (min_max_axis == 0).sum().item() > 0:
|
| 646 |
+
min_max_axis[min_max_axis == 0] = max_v
|
| 647 |
+
scale = (max_v / min_max_axis).clamp(max=2e4)
|
| 648 |
+
zero = -_min * scale
|
| 649 |
+
|
| 650 |
+
if round_zero:
|
| 651 |
+
zero = torch.round(zero)
|
| 652 |
+
|
| 653 |
+
# Fine-tune weights
|
| 654 |
+
if optimize:
|
| 655 |
+
scale, zero = self.optimize_weights(tensor=weight, scale=scale, zero=zero, min_max=min_max, axis=axis)
|
| 656 |
+
|
| 657 |
+
# Quantize
|
| 658 |
+
# Necessary for fake quantization backprop
|
| 659 |
+
w_q = torch.round(weight * scale + zero).clamp(min_max[0], min_max[1])
|
| 660 |
+
w_q = w_q.reshape(shape).int()
|
| 661 |
+
|
| 662 |
+
scale = 1.0 / scale
|
| 663 |
+
if axis == 1:
|
| 664 |
+
scale = scale.reshape(shape[0], -1)
|
| 665 |
+
zero = zero.reshape(shape[0], -1)
|
| 666 |
+
else:
|
| 667 |
+
scale = scale.reshape(-1, shape[-1])
|
| 668 |
+
zero = zero.reshape(-1, shape[-1])
|
| 669 |
+
# cleanup
|
| 670 |
+
del weight, _min, _max
|
| 671 |
+
|
| 672 |
+
return w_q, scale.to(tensor.dtype), zero.to(tensor.dtype)
|
| 673 |
+
|
| 674 |
+
def quantize(self, node: NodeProto, graph_stack: list[GraphProto]) -> list[NodeProto]:
|
| 675 |
+
"""
|
| 676 |
+
Target node: QOperator node: QDQ nodes:
|
| 677 |
+
MatMul MatMulNBits DeQuantizeLinear -> MatMul
|
| 678 |
+
Gather GatherBlockQuantized Gather, Gather, Gather (optional) -> DequantizeLinear
|
| 679 |
+
If the node is target node with fp32 or fp16 const weight, quantize the weight to int4 and
|
| 680 |
+
return the new nodes.
|
| 681 |
+
If QOperator format, return the corresponding QOperator nodes.
|
| 682 |
+
If QDQ format, return the corresdponging QDQ nodes.
|
| 683 |
+
Gather (quantized data) + Gather (scales) + Gather (optional, zero points) -> DequantizeLinear is
|
| 684 |
+
not supported yet because Gather does not support int4 data.
|
| 685 |
+
"""
|
| 686 |
+
# With HQQ, zero points are in float. Current GatherBlockQuantized does not support float zero points.
|
| 687 |
+
if node.op_type == "Gather":
|
| 688 |
+
raise NotImplementedError("Gather quantization is not supported yet in HQQ")
|
| 689 |
+
|
| 690 |
+
import torch # noqa: PLC0415
|
| 691 |
+
|
| 692 |
+
logger.info(f"start to quantize {node.name} ...")
|
| 693 |
+
input_b = node.input[1]
|
| 694 |
+
b_pb, bs_graph = get_initializer(input_b, graph_stack)
|
| 695 |
+
if b_pb is None:
|
| 696 |
+
logger.info("MatMul doesn't have const weight. Skip to quantize")
|
| 697 |
+
return [node] # only care about constant weight
|
| 698 |
+
|
| 699 |
+
b_array = onnx.numpy_helper.to_array(b_pb)
|
| 700 |
+
if len(b_array.shape) != 2:
|
| 701 |
+
logger.info("MatMul weight is not 2D. Skip to quantize")
|
| 702 |
+
return [node] # can only process 2-D matrix
|
| 703 |
+
b_array_torch = torch.from_numpy(b_array)
|
| 704 |
+
if torch.cuda.is_available():
|
| 705 |
+
b_array_torch = b_array_torch.cuda()
|
| 706 |
+
|
| 707 |
+
bits = self.config.bits
|
| 708 |
+
quant_weight_torch, scales_torch, zero_points_torch = self.quantize_internal(
|
| 709 |
+
b_array_torch.T, bits=bits, group_size=self.config.block_size
|
| 710 |
+
)
|
| 711 |
+
quant_weight_torch = quant_weight_torch.contiguous()
|
| 712 |
+
scales_torch = scales_torch.contiguous()
|
| 713 |
+
zero_points_torch = zero_points_torch.contiguous()
|
| 714 |
+
|
| 715 |
+
packed_size = 8 // bits # number of elements packed into one byte
|
| 716 |
+
|
| 717 |
+
packed_torch = torch.zeros(
|
| 718 |
+
(quant_weight_torch.shape[0], quant_weight_torch.shape[1] // packed_size),
|
| 719 |
+
dtype=torch.uint8,
|
| 720 |
+
device=quant_weight_torch.device,
|
| 721 |
+
)
|
| 722 |
+
self.pack_on_row_fast_248bit(packed_torch, quant_weight_torch, bits)
|
| 723 |
+
scales = scales_torch.cpu().numpy()
|
| 724 |
+
zero_points = zero_points_torch.cpu().numpy()
|
| 725 |
+
# reshape to the predefined shape in MatmulNbits
|
| 726 |
+
scales = scales.reshape(-1)
|
| 727 |
+
zero_points = zero_points.reshape(-1)
|
| 728 |
+
rows, cols = b_array_torch.shape
|
| 729 |
+
block_size = self.config.block_size
|
| 730 |
+
blob_size = block_size // packed_size
|
| 731 |
+
k_blocks = (rows + block_size - 1) // block_size
|
| 732 |
+
packed_torch = packed_torch.reshape(cols, k_blocks, blob_size)
|
| 733 |
+
|
| 734 |
+
b_quant = onnx.numpy_helper.from_array(packed_torch.cpu().numpy())
|
| 735 |
+
b_quant.name = b_pb.name + "_Q" + str(bits)
|
| 736 |
+
for input in bs_graph.input:
|
| 737 |
+
if input.name == input_b:
|
| 738 |
+
bs_graph.input.remove(input)
|
| 739 |
+
break
|
| 740 |
+
|
| 741 |
+
scales_tensor = onnx.numpy_helper.from_array(scales)
|
| 742 |
+
scales_tensor.name = b_pb.name + "_scales"
|
| 743 |
+
bs_graph.initializer.extend([b_quant, scales_tensor])
|
| 744 |
+
|
| 745 |
+
input_names = [node.input[0], b_quant.name, scales_tensor.name]
|
| 746 |
+
zp_tensor = onnx.numpy_helper.from_array(zero_points)
|
| 747 |
+
zp_tensor.name = b_pb.name + "_zero_points"
|
| 748 |
+
bs_graph.initializer.extend([zp_tensor])
|
| 749 |
+
input_names.append(zp_tensor.name)
|
| 750 |
+
|
| 751 |
+
kwargs = {}
|
| 752 |
+
rows, cols = b_array.shape
|
| 753 |
+
kwargs["K"] = rows
|
| 754 |
+
kwargs["N"] = cols
|
| 755 |
+
kwargs["bits"] = bits
|
| 756 |
+
kwargs["block_size"] = self.config.block_size
|
| 757 |
+
|
| 758 |
+
matmul_q_node = onnx.helper.make_node(
|
| 759 |
+
"MatMulNBits",
|
| 760 |
+
inputs=input_names,
|
| 761 |
+
outputs=[node.output[0]],
|
| 762 |
+
name=node.name + "_Q" + str(bits) if node.name else "",
|
| 763 |
+
domain="com.microsoft",
|
| 764 |
+
**kwargs,
|
| 765 |
+
)
|
| 766 |
+
|
| 767 |
+
logger.info(f"complete quantization of {node.name} ...")
|
| 768 |
+
|
| 769 |
+
return [matmul_q_node]
|
| 770 |
+
|
| 771 |
+
|
| 772 |
+
def get_initializer(name, graph_path: list[GraphProto]) -> tuple[TensorProto, GraphProto]:
|
| 773 |
+
for gid in range(len(graph_path) - 1, -1, -1):
|
| 774 |
+
graph = graph_path[gid]
|
| 775 |
+
for tensor in graph.initializer:
|
| 776 |
+
if tensor.name == name:
|
| 777 |
+
return tensor, graph
|
| 778 |
+
return None, None
|
| 779 |
+
|
| 780 |
+
|
| 781 |
+
# transpose int4 matrix (packed as uint8)
|
| 782 |
+
def transpose_packed_int4_matrix(packed, rows, cols):
|
| 783 |
+
# unpack to int4 matrix
|
| 784 |
+
total = rows * cols
|
| 785 |
+
high = (packed >> 4) & 0x0F
|
| 786 |
+
low = packed & 0x0F
|
| 787 |
+
int4_vals = np.empty(total, dtype=np.uint8)
|
| 788 |
+
int4_vals[0::2] = low
|
| 789 |
+
int4_vals[1::2] = high
|
| 790 |
+
int4_matrix = int4_vals.reshape((rows, cols))
|
| 791 |
+
|
| 792 |
+
# transpose int4 matrix
|
| 793 |
+
int4_matrix_transposed = int4_matrix.T
|
| 794 |
+
|
| 795 |
+
# pack to uint8
|
| 796 |
+
flat = int4_matrix_transposed.reshape(-1)
|
| 797 |
+
packed = ((flat[1::2] << 4) & 0xF0) | (flat[0::2] & 0x0F)
|
| 798 |
+
return packed.astype(np.uint8)
|
| 799 |
+
|
| 800 |
+
|
| 801 |
+
class DefaultWeightOnlyQuantizer:
|
| 802 |
+
def __init__(self, config: DefaultWeightOnlyQuantConfig):
|
| 803 |
+
self.config = config
|
| 804 |
+
|
| 805 |
+
def qbits_block_quant(self, fp32weight: npt.ArrayLike) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
|
| 806 |
+
"""4b/8b quantize fp32 weight to int4 using C++ kernels."""
|
| 807 |
+
|
| 808 |
+
qbits = self.config.bits
|
| 809 |
+
kpack = 8 // qbits
|
| 810 |
+
if len(fp32weight.shape) != 2:
|
| 811 |
+
raise ValueError("Current int4 block quantization only supports 2D tensors!")
|
| 812 |
+
rows, cols = fp32weight.shape
|
| 813 |
+
|
| 814 |
+
block_size = self.config.block_size
|
| 815 |
+
k_blocks = (rows + block_size - 1) // block_size
|
| 816 |
+
|
| 817 |
+
if self.config.quant_format == QuantFormat.QOperator:
|
| 818 |
+
blob_size = (block_size + kpack - 1) // kpack
|
| 819 |
+
padded_rows = k_blocks * block_size
|
| 820 |
+
pad_len = padded_rows - rows
|
| 821 |
+
if pad_len > 0:
|
| 822 |
+
fp32weight = np.pad(fp32weight, ((0, pad_len), (0, 0)), "constant")
|
| 823 |
+
|
| 824 |
+
# block wise quantization, each block comes from a single column
|
| 825 |
+
packed = np.zeros((cols, k_blocks, blob_size), dtype="uint8")
|
| 826 |
+
zero_point = np.zeros((cols, ((k_blocks + kpack - 1) // kpack)), dtype="uint8")
|
| 827 |
+
scales = np.zeros((cols, k_blocks), dtype=fp32weight.dtype)
|
| 828 |
+
if qbits == 2:
|
| 829 |
+
quantize_matmul_2bits(
|
| 830 |
+
packed, fp32weight, scales, zero_point, block_size, cols, rows, self.config.is_symmetric
|
| 831 |
+
)
|
| 832 |
+
elif qbits == 8:
|
| 833 |
+
quantize_matmul_8bits(
|
| 834 |
+
packed, fp32weight, scales, zero_point, block_size, cols, rows, self.config.is_symmetric
|
| 835 |
+
)
|
| 836 |
+
else:
|
| 837 |
+
quantize_matmul_4bits(
|
| 838 |
+
packed, fp32weight, scales, zero_point, block_size, cols, rows, self.config.is_symmetric
|
| 839 |
+
)
|
| 840 |
+
else:
|
| 841 |
+
# block size equal to rows (K) if channel wised quantize enabled
|
| 842 |
+
block_size = rows if self.config.channel_wised_quantize else self.config.block_size
|
| 843 |
+
k_blocks = (rows + block_size - 1) // block_size
|
| 844 |
+
|
| 845 |
+
assert qbits == 4, "QDQ format only support 4 bits quantization"
|
| 846 |
+
packed = np.zeros((rows * cols + 1) // 2, dtype="uint8")
|
| 847 |
+
zero_point = np.zeros((cols * k_blocks + 1) // 2, dtype="uint8")
|
| 848 |
+
scales = np.zeros((k_blocks, cols), dtype=fp32weight.dtype)
|
| 849 |
+
quantize_qdq_matmul_4bits(
|
| 850 |
+
packed, fp32weight, scales, zero_point, block_size, cols, rows, self.config.is_symmetric
|
| 851 |
+
)
|
| 852 |
+
|
| 853 |
+
return (packed, scales, zero_point)
|
| 854 |
+
|
| 855 |
+
def quantize_matmul(self, node: NodeProto, graph_stack: list[GraphProto]) -> list[NodeProto]:
|
| 856 |
+
"""
|
| 857 |
+
Quantize weight B of MatMul node to int4 or int8.
|
| 858 |
+
Currently only support 2D constant matrix and axis 0 blockwise quantization.
|
| 859 |
+
"""
|
| 860 |
+
bits = self.config.bits
|
| 861 |
+
if bits == 8:
|
| 862 |
+
qtype = TensorProto.INT8 if self.config.is_symmetric else TensorProto.UINT8
|
| 863 |
+
else:
|
| 864 |
+
qtype = TensorProto.INT4 if self.config.is_symmetric else TensorProto.UINT4
|
| 865 |
+
input_b = node.input[1]
|
| 866 |
+
b_tensor, b_graph = get_initializer(input_b, graph_stack)
|
| 867 |
+
if b_tensor is None:
|
| 868 |
+
logger.info("MatMul doesn't have const weight. Skip to quantize")
|
| 869 |
+
return [node] # only care about constant weight
|
| 870 |
+
|
| 871 |
+
b_ndarray = ir.from_proto(b_tensor).numpy()
|
| 872 |
+
if len(b_ndarray.shape) != 2:
|
| 873 |
+
logger.info("MatMul weight is not 2D. Skip to quantize")
|
| 874 |
+
return [node] # can only process 2-D matrix
|
| 875 |
+
|
| 876 |
+
bfloat16 = b_ndarray.dtype == "bfloat16"
|
| 877 |
+
if bfloat16:
|
| 878 |
+
b_ndarray = b_ndarray.astype(np.float32)
|
| 879 |
+
|
| 880 |
+
packed, scales, zero_points = self.qbits_block_quant(b_ndarray)
|
| 881 |
+
if bfloat16:
|
| 882 |
+
scales = scales.astype(ml_dtypes.bfloat16)
|
| 883 |
+
|
| 884 |
+
if self.config.quant_format == QuantFormat.QOperator:
|
| 885 |
+
b_quant = ir.serde.serialize_tensor(ir.Tensor(packed, name=b_tensor.name + f"_Q{bits}"))
|
| 886 |
+
scales_tensor = ir.serde.serialize_tensor(ir.Tensor(scales, name=b_tensor.name + "_scales"))
|
| 887 |
+
else:
|
| 888 |
+
b_quant = onnx.helper.make_tensor(
|
| 889 |
+
b_tensor.name + f"_DQ_Q{bits}", qtype, b_ndarray.shape, packed.tobytes(), True
|
| 890 |
+
)
|
| 891 |
+
scales_tensor = ir.serde.serialize_tensor(ir.Tensor(scales, name=b_tensor.name + "_DQ_scales"))
|
| 892 |
+
|
| 893 |
+
# if QDQ, CW and SYM enabled, optimize for Intel NPU, tranpose the weight to NHWC format will increase performance
|
| 894 |
+
qdq_opt_for_intel_npu_enabled = (
|
| 895 |
+
self.config.quant_format == QuantFormat.QDQ
|
| 896 |
+
and self.config.channel_wised_quantize
|
| 897 |
+
and self.config.is_symmetric
|
| 898 |
+
)
|
| 899 |
+
if qdq_opt_for_intel_npu_enabled:
|
| 900 |
+
rows, cols = b_ndarray.shape
|
| 901 |
+
packed = transpose_packed_int4_matrix(packed, rows, cols)
|
| 902 |
+
scales = scales.reshape((cols, 1)) # (cols, 1)
|
| 903 |
+
b_quant = onnx.helper.make_tensor(
|
| 904 |
+
b_tensor.name + f"_DQ_Q{bits}", qtype, [cols, rows], packed.tobytes(), True
|
| 905 |
+
)
|
| 906 |
+
scales_tensor = ir.serde.serialize_tensor(ir.Tensor(scales, name=b_tensor.name + "_DQ_scales"))
|
| 907 |
+
|
| 908 |
+
for input in b_graph.input:
|
| 909 |
+
if input.name == input_b:
|
| 910 |
+
b_graph.input.remove(input)
|
| 911 |
+
break
|
| 912 |
+
|
| 913 |
+
b_graph.initializer.extend([b_quant, scales_tensor])
|
| 914 |
+
|
| 915 |
+
output_nodes = []
|
| 916 |
+
|
| 917 |
+
if self.config.quant_format == QuantFormat.QOperator:
|
| 918 |
+
input_names = [node.input[0], b_quant.name, scales_tensor.name]
|
| 919 |
+
if not self.config.is_symmetric:
|
| 920 |
+
zp_tensor = onnx.numpy_helper.from_array(zero_points, b_tensor.name + "_zero_points")
|
| 921 |
+
input_names.append(zp_tensor.name)
|
| 922 |
+
b_graph.initializer.extend([zp_tensor])
|
| 923 |
+
kwargs = {}
|
| 924 |
+
rows, cols = b_ndarray.shape
|
| 925 |
+
kwargs["K"] = rows
|
| 926 |
+
kwargs["N"] = cols
|
| 927 |
+
kwargs["bits"] = bits
|
| 928 |
+
kwargs["block_size"] = self.config.block_size
|
| 929 |
+
|
| 930 |
+
# Do not output accuracy_level if it is 0 since the attribute is optional and is not supported by most EPs.
|
| 931 |
+
if self.config.accuracy_level:
|
| 932 |
+
kwargs["accuracy_level"] = self.config.accuracy_level
|
| 933 |
+
|
| 934 |
+
matmul_qbit_node = onnx.helper.make_node(
|
| 935 |
+
"MatMulNBits",
|
| 936 |
+
inputs=input_names,
|
| 937 |
+
outputs=[node.output[0]],
|
| 938 |
+
name=node.name + f"_Q{bits}" if node.name else "",
|
| 939 |
+
domain="com.microsoft",
|
| 940 |
+
**kwargs,
|
| 941 |
+
)
|
| 942 |
+
|
| 943 |
+
output_nodes.append(matmul_qbit_node)
|
| 944 |
+
else:
|
| 945 |
+
dq_input_names = [b_quant.name, scales_tensor.name]
|
| 946 |
+
dq_output_names = [b_quant.name + "_output"]
|
| 947 |
+
tp_input_names = [dq_output_names[0]]
|
| 948 |
+
tp_output_names = [dq_output_names[0] + "_transposed"]
|
| 949 |
+
matmul_input_names = [
|
| 950 |
+
node.input[0],
|
| 951 |
+
tp_output_names[0] if qdq_opt_for_intel_npu_enabled else dq_output_names[0],
|
| 952 |
+
]
|
| 953 |
+
matmul_output_names = [node.output[0]]
|
| 954 |
+
if not self.config.is_symmetric:
|
| 955 |
+
zp_tensor = onnx.helper.make_tensor(
|
| 956 |
+
b_tensor.name + "_DQ_zero_points", qtype, scales.shape, zero_points.tobytes(), True
|
| 957 |
+
)
|
| 958 |
+
dq_input_names.append(zp_tensor.name)
|
| 959 |
+
b_graph.initializer.extend([zp_tensor])
|
| 960 |
+
rows, cols = b_ndarray.shape
|
| 961 |
+
dq_kwargs = {
|
| 962 |
+
"axis": 1 if qdq_opt_for_intel_npu_enabled else 0,
|
| 963 |
+
"block_size": rows if self.config.channel_wised_quantize else self.config.block_size,
|
| 964 |
+
}
|
| 965 |
+
dq_node = onnx.helper.make_node(
|
| 966 |
+
"DequantizeLinear",
|
| 967 |
+
inputs=dq_input_names,
|
| 968 |
+
outputs=dq_output_names,
|
| 969 |
+
name=node.name + f"_DQ_Q{bits}" if node.name else "",
|
| 970 |
+
**dq_kwargs,
|
| 971 |
+
)
|
| 972 |
+
matmul_node = onnx.helper.make_node(
|
| 973 |
+
"MatMul",
|
| 974 |
+
inputs=matmul_input_names,
|
| 975 |
+
outputs=matmul_output_names,
|
| 976 |
+
name=node.name + f"_matmul_Q{bits}" if node.name else "",
|
| 977 |
+
)
|
| 978 |
+
if qdq_opt_for_intel_npu_enabled:
|
| 979 |
+
tp_node = onnx.helper.make_node(
|
| 980 |
+
"Transpose",
|
| 981 |
+
inputs=tp_input_names,
|
| 982 |
+
outputs=tp_output_names,
|
| 983 |
+
perm=[1, 0],
|
| 984 |
+
)
|
| 985 |
+
output_nodes.extend([dq_node, tp_node, matmul_node])
|
| 986 |
+
else:
|
| 987 |
+
output_nodes.extend([dq_node, matmul_node])
|
| 988 |
+
|
| 989 |
+
return output_nodes
|
| 990 |
+
|
| 991 |
+
@staticmethod
|
| 992 |
+
def quant_slice_symmetric(data: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
|
| 993 |
+
max_val = np.max(data, axis=1, keepdims=True)
|
| 994 |
+
min_val = np.min(data, axis=1, keepdims=True)
|
| 995 |
+
abs_max = np.where(np.abs(max_val) > np.abs(min_val), max_val, min_val)
|
| 996 |
+
|
| 997 |
+
scale = abs_max / -8.0 # if max == min, max may be clipped
|
| 998 |
+
quantized_slice = np.where(scale == 0, 0, data / scale).round().clip(-8, 7).astype(np.int8)
|
| 999 |
+
|
| 1000 |
+
return quantized_slice, scale
|
| 1001 |
+
|
| 1002 |
+
@staticmethod
|
| 1003 |
+
def quant_slice_asymmetric(data: np.ndarray) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
|
| 1004 |
+
min_val = np.minimum(data.min(axis=1, keepdims=True), 0)
|
| 1005 |
+
max_val = np.maximum(data.max(axis=1, keepdims=True), 0)
|
| 1006 |
+
|
| 1007 |
+
scale = (max_val - min_val) / 15.0
|
| 1008 |
+
zero_point = np.where(scale == 0, 8, -min_val / scale).round().clip(0, 15).astype(np.uint8)
|
| 1009 |
+
quantized_slice = np.where(scale == 0, 8, data / scale + zero_point).round().clip(0, 15).astype(np.uint8)
|
| 1010 |
+
|
| 1011 |
+
return quantized_slice, scale, zero_point
|
| 1012 |
+
|
| 1013 |
+
@staticmethod
|
| 1014 |
+
def pack_int8_to_int4(data: np.ndarray) -> np.ndarray:
|
| 1015 |
+
"""Pack int8 data to int4 and store in uint8 ndarray."""
|
| 1016 |
+
data_flat = data.reshape(-1)
|
| 1017 |
+
if len(data_flat) % 2 != 0:
|
| 1018 |
+
data_flat = np.append(data_flat, 0)
|
| 1019 |
+
quant_data_int4 = (data_flat[::2] & 0xF) | ((data_flat[1::2] & 0xF) << 4)
|
| 1020 |
+
|
| 1021 |
+
return quant_data_int4.astype("uint8")
|
| 1022 |
+
|
| 1023 |
+
@staticmethod
|
| 1024 |
+
def quantize_ndarray(
|
| 1025 |
+
data: np.ndarray,
|
| 1026 |
+
quantize_axis: int,
|
| 1027 |
+
block_size: int,
|
| 1028 |
+
is_symmetric: bool,
|
| 1029 |
+
) -> tuple[np.ndarray, np.ndarray, np.ndarray | None]:
|
| 1030 |
+
"""Quantize ndarray data to int4 using numpy, return (quantized data, scales, zero points)."""
|
| 1031 |
+
# Get the shape of the matrix
|
| 1032 |
+
m = 1 # dimension of the matrix before the quantize axis
|
| 1033 |
+
k = data.shape[quantize_axis] # dimension of the matrix along the quantize axis
|
| 1034 |
+
n = 1 # dimension of the matrix after the quantize axis
|
| 1035 |
+
for i, dim in enumerate(data.shape):
|
| 1036 |
+
if i < quantize_axis:
|
| 1037 |
+
m *= dim
|
| 1038 |
+
elif i > quantize_axis:
|
| 1039 |
+
n *= dim
|
| 1040 |
+
|
| 1041 |
+
k_blocks = (k + block_size - 1) // block_size
|
| 1042 |
+
scales_shape = list(data.shape)
|
| 1043 |
+
scales_shape[quantize_axis] = k_blocks
|
| 1044 |
+
|
| 1045 |
+
data_reshape = data.reshape((m, k, n))
|
| 1046 |
+
scales = np.zeros((m, k_blocks, n), dtype=data.dtype)
|
| 1047 |
+
if is_symmetric:
|
| 1048 |
+
quant_data_int8 = np.zeros((m, k, n), dtype="int8")
|
| 1049 |
+
else:
|
| 1050 |
+
quant_data_int8 = np.zeros((m, k, n), dtype="uint8")
|
| 1051 |
+
zero_point_int8 = np.zeros((m, k_blocks, n), dtype="uint8")
|
| 1052 |
+
|
| 1053 |
+
# slice and quantize
|
| 1054 |
+
for i in range(0, k, block_size):
|
| 1055 |
+
end_idx = min(i + block_size, k)
|
| 1056 |
+
slice = data_reshape[:, i:end_idx, :]
|
| 1057 |
+
|
| 1058 |
+
if is_symmetric:
|
| 1059 |
+
quantized_slice_int8, scale_slice = DefaultWeightOnlyQuantizer.quant_slice_symmetric(slice)
|
| 1060 |
+
else:
|
| 1061 |
+
quantized_slice_int8, scale_slice, zero_point_slice_int8 = (
|
| 1062 |
+
DefaultWeightOnlyQuantizer.quant_slice_asymmetric(slice)
|
| 1063 |
+
)
|
| 1064 |
+
|
| 1065 |
+
quant_data_int8[:, i:end_idx, :] = quantized_slice_int8
|
| 1066 |
+
j = i // block_size
|
| 1067 |
+
scales[:, j : (j + 1), :] = scale_slice
|
| 1068 |
+
if not is_symmetric:
|
| 1069 |
+
zero_point_int8[:, j : (j + 1), :] = zero_point_slice_int8
|
| 1070 |
+
|
| 1071 |
+
# pack int8 to int4
|
| 1072 |
+
quant_data_int4 = DefaultWeightOnlyQuantizer.pack_int8_to_int4(quant_data_int8)
|
| 1073 |
+
zero_point_int4 = None
|
| 1074 |
+
if not is_symmetric:
|
| 1075 |
+
zero_point_int4 = DefaultWeightOnlyQuantizer.pack_int8_to_int4(zero_point_int8)
|
| 1076 |
+
scales = scales.reshape(scales_shape)
|
| 1077 |
+
return quant_data_int4, scales, zero_point_int4
|
| 1078 |
+
|
| 1079 |
+
def quantize_gather(self, node: NodeProto, graph_stack: list[GraphProto]) -> list[NodeProto]:
|
| 1080 |
+
"""Quantize weight data of Gather node to int4."""
|
| 1081 |
+
assert self.config.quant_format == QuantFormat.QOperator, "Gather only supports QOperator format currently."
|
| 1082 |
+
|
| 1083 |
+
qtype = TensorProto.INT4 if self.config.is_symmetric else TensorProto.UINT4
|
| 1084 |
+
data_arg = node.input[0]
|
| 1085 |
+
data_tensorproto, data_graphproto = get_initializer(data_arg, graph_stack)
|
| 1086 |
+
if data_tensorproto is None:
|
| 1087 |
+
logger.info("Gather doesn't have const weight. Skip quantization.")
|
| 1088 |
+
return [node] # only care about constant weight
|
| 1089 |
+
|
| 1090 |
+
data_ndarray = onnx.numpy_helper.to_array(data_tensorproto)
|
| 1091 |
+
data_rank = len(data_ndarray.shape)
|
| 1092 |
+
quantize_axis = self.config.quant_axes.get("Gather", 1)
|
| 1093 |
+
block_size = self.config.block_size
|
| 1094 |
+
|
| 1095 |
+
assert quantize_axis < data_rank and quantize_axis >= -data_rank, "Invalid quantize axis for Gather node."
|
| 1096 |
+
assert block_size >= 16 and ((block_size - 1) & block_size == 0), "Invalid block size for Gather node."
|
| 1097 |
+
|
| 1098 |
+
quantize_axis = (quantize_axis + data_rank) % data_rank
|
| 1099 |
+
quantized_data, scales, zero_points = self.quantize_ndarray(
|
| 1100 |
+
data_ndarray, quantize_axis, block_size, self.config.is_symmetric
|
| 1101 |
+
)
|
| 1102 |
+
|
| 1103 |
+
for input in data_graphproto.input:
|
| 1104 |
+
if input.name == data_arg:
|
| 1105 |
+
data_graphproto.input.remove(input)
|
| 1106 |
+
break
|
| 1107 |
+
|
| 1108 |
+
quantized_data_tensorproto = onnx.helper.make_tensor(
|
| 1109 |
+
data_tensorproto.name + "_Q4", qtype, data_ndarray.shape, quantized_data.tobytes(), True
|
| 1110 |
+
)
|
| 1111 |
+
scales_tensorproto = onnx.numpy_helper.from_array(scales, data_tensorproto.name + "_scales")
|
| 1112 |
+
input_names = [quantized_data_tensorproto.name, node.input[1], scales_tensorproto.name]
|
| 1113 |
+
data_graphproto.initializer.extend([quantized_data_tensorproto, scales_tensorproto])
|
| 1114 |
+
if not self.config.is_symmetric:
|
| 1115 |
+
zp_tensorproto = onnx.helper.make_tensor(
|
| 1116 |
+
data_tensorproto.name + "_zero_points", qtype, scales.shape, zero_points.tobytes(), True
|
| 1117 |
+
)
|
| 1118 |
+
input_names.append(zp_tensorproto.name)
|
| 1119 |
+
data_graphproto.initializer.extend([zp_tensorproto])
|
| 1120 |
+
|
| 1121 |
+
try:
|
| 1122 |
+
gather_axis = onnx.helper.get_node_attr_value(node, "axis")
|
| 1123 |
+
except ValueError:
|
| 1124 |
+
gather_axis = 0
|
| 1125 |
+
|
| 1126 |
+
kwargs = {
|
| 1127 |
+
"gather_axis": gather_axis,
|
| 1128 |
+
"quantize_axis": quantize_axis,
|
| 1129 |
+
"block_size": block_size,
|
| 1130 |
+
}
|
| 1131 |
+
|
| 1132 |
+
gather_q4_node = onnx.helper.make_node(
|
| 1133 |
+
"GatherBlockQuantized",
|
| 1134 |
+
inputs=input_names,
|
| 1135 |
+
outputs=[node.output[0]],
|
| 1136 |
+
name=node.name + "_Q4" if node.name else "",
|
| 1137 |
+
domain="com.microsoft",
|
| 1138 |
+
**kwargs,
|
| 1139 |
+
)
|
| 1140 |
+
|
| 1141 |
+
return [gather_q4_node]
|
| 1142 |
+
|
| 1143 |
+
def quantize(self, node: NodeProto, graph_stack: list[GraphProto]) -> list[NodeProto]:
|
| 1144 |
+
"""
|
| 1145 |
+
Target node: QOperator node: QDQ nodes:
|
| 1146 |
+
MatMul MatMulNBits DeQuantizeLinear -> MatMul
|
| 1147 |
+
Gather GatherBlockQuantized Gather, Gather, Gather (optional) -> DequantizeLinear
|
| 1148 |
+
If the node is target node with fp32 or fp16 const weight, quantize the weight to int4 and
|
| 1149 |
+
return the new nodes.
|
| 1150 |
+
If QOperator format, return the corresponding QOperator nodes.
|
| 1151 |
+
If QDQ format, return the corresdponging QDQ nodes.
|
| 1152 |
+
Gather (quantized data) + Gather (scales) + Gather (optional, zero points) -> DequantizeLinear is
|
| 1153 |
+
not supported yet because Gather does not support int4 data.
|
| 1154 |
+
"""
|
| 1155 |
+
logger.info(f"start to quantize {node.name} ...")
|
| 1156 |
+
|
| 1157 |
+
bits = self.config.bits
|
| 1158 |
+
if node.op_type == "MatMul":
|
| 1159 |
+
if bits == 8 and self.config.quant_format == QuantFormat.QDQ:
|
| 1160 |
+
logger.error("MatMul only supports QOperator format for 8 bits quantization.")
|
| 1161 |
+
return [node]
|
| 1162 |
+
results = self.quantize_matmul(node, graph_stack)
|
| 1163 |
+
elif node.op_type == "Gather":
|
| 1164 |
+
if self.config.bits != 4:
|
| 1165 |
+
logger.error("Gather only supports 4 bits quantization.")
|
| 1166 |
+
return [node]
|
| 1167 |
+
|
| 1168 |
+
results = self.quantize_gather(node, graph_stack)
|
| 1169 |
+
else:
|
| 1170 |
+
logger.error(f"Unsupported operator {node.op_type} for weight only quantization. Skip quantization.")
|
| 1171 |
+
return [node]
|
| 1172 |
+
|
| 1173 |
+
logger.info(f"complete quantization of {node.name} with {self.config.bits} bits ...")
|
| 1174 |
+
return results
|
| 1175 |
+
|
| 1176 |
+
|
| 1177 |
+
class NVAWQWeightOnlyQuantizer:
|
| 1178 |
+
def __init__(
|
| 1179 |
+
self,
|
| 1180 |
+
config: NVAWQWeightOnlyQuantConfig,
|
| 1181 |
+
):
|
| 1182 |
+
self.config = config
|
| 1183 |
+
|
| 1184 |
+
def quantize_awq(self, model: ModelProto | str) -> ModelProto:
|
| 1185 |
+
"""
|
| 1186 |
+
Perform nvidia_awq quantization using ModelOpt's int4 quantize function.
|
| 1187 |
+
|
| 1188 |
+
Args:
|
| 1189 |
+
model (ModelProto): The ONNX model to quantize.
|
| 1190 |
+
|
| 1191 |
+
Returns:
|
| 1192 |
+
ModelProto: The quantized ONNX model.
|
| 1193 |
+
"""
|
| 1194 |
+
try:
|
| 1195 |
+
from modelopt.onnx.quantization.int4 import quantize as quantize_int4 # noqa: PLC0415
|
| 1196 |
+
except ImportError:
|
| 1197 |
+
print(
|
| 1198 |
+
"Please ensure that the 'modelopt' package is installed. Please install it using pip install nvidia_modelopt."
|
| 1199 |
+
)
|
| 1200 |
+
raise ImportError(
|
| 1201 |
+
"modelopt is not installed. Please install it using pip install nvidia_modelopt. Exiting."
|
| 1202 |
+
) from None
|
| 1203 |
+
|
| 1204 |
+
logger.info("Starting nvidia_awq quantization...")
|
| 1205 |
+
|
| 1206 |
+
# Prepare calibration inputs
|
| 1207 |
+
calib_inputs = self.config.calibration_data_reader
|
| 1208 |
+
|
| 1209 |
+
# Perform quantization using ModelOpt's int4 quantize function
|
| 1210 |
+
quantized_model = quantize_int4(
|
| 1211 |
+
model,
|
| 1212 |
+
calibration_method=self.config.calibration_method,
|
| 1213 |
+
calibration_data_reader=calib_inputs,
|
| 1214 |
+
)
|
| 1215 |
+
|
| 1216 |
+
logger.info("Completed nvidia_awq quantization.")
|
| 1217 |
+
return quantized_model
|
| 1218 |
+
|
| 1219 |
+
|
| 1220 |
+
class MatMulNBitsQuantizer:
|
| 1221 |
+
"""
|
| 1222 |
+
Target node: QOperator node: QDQ nodes:
|
| 1223 |
+
MatMul MatMulNBits DeQuantizeLinear -> MatMul
|
| 1224 |
+
Gather GatherBlockQuantized Gather, Gather, Gather (optional) -> DequantizeLinear
|
| 1225 |
+
|
| 1226 |
+
Perform 2/4/8 bits quantization of constant weights for target nodes.
|
| 1227 |
+
If algo_config.quant_format is QOperator:
|
| 1228 |
+
- nodes are replaced by the corresponding QOperator nodes.
|
| 1229 |
+
- quantized weights are stored in the contrib ops.
|
| 1230 |
+
If algo_config.quant_format is QDQ:
|
| 1231 |
+
- the quantized weight is stored in a standard onnx node. For MatMul, it is DequantizeLinear. For Gather,
|
| 1232 |
+
it is the three Gathers, one for quantized data, one for scales and one for optional zero points.
|
| 1233 |
+
- The nodes are replaced by the corresponding QDQ nodes.
|
| 1234 |
+
- currently Gather is not supported in QDQ because Gather does not support int4 yet.
|
| 1235 |
+
Note:
|
| 1236 |
+
- for quantized gather, the memory usage of "DequantizeLinear + Gather" is the same as the original Gather
|
| 1237 |
+
during runtime. Therefor it is not recommended.
|
| 1238 |
+
- when a node is in nodes_to_exclude, and the node configuration in algo_config.customized_weight_config will be ignored.
|
| 1239 |
+
"""
|
| 1240 |
+
|
| 1241 |
+
def __init__(
|
| 1242 |
+
self,
|
| 1243 |
+
model: ModelProto | str,
|
| 1244 |
+
bits: int = 4, # default to 4bit
|
| 1245 |
+
block_size: int = 128,
|
| 1246 |
+
is_symmetric: bool = False,
|
| 1247 |
+
accuracy_level: int | None = None,
|
| 1248 |
+
nodes_to_exclude=None,
|
| 1249 |
+
nodes_to_include: list[str] | None = None,
|
| 1250 |
+
quant_format=QuantFormat.QOperator,
|
| 1251 |
+
op_types_to_quantize: tuple[str, ...] | None = None,
|
| 1252 |
+
quant_axes: tuple[tuple[str, int], ...] | None = None,
|
| 1253 |
+
channel_wised_quantize: bool = False,
|
| 1254 |
+
algo_config: WeightOnlyQuantConfig | None = None,
|
| 1255 |
+
):
|
| 1256 |
+
if nodes_to_exclude is None:
|
| 1257 |
+
nodes_to_exclude = []
|
| 1258 |
+
self.model = ONNXModel(onnx.load(model)) if isinstance(model, str) else ONNXModel(model)
|
| 1259 |
+
self.model_path = model if isinstance(model, str) else None
|
| 1260 |
+
self.bits = bits
|
| 1261 |
+
self.block_size = block_size
|
| 1262 |
+
self.is_symmetric = is_symmetric
|
| 1263 |
+
self.accuracy_level = accuracy_level
|
| 1264 |
+
self.nodes_to_exclude = set(nodes_to_exclude)
|
| 1265 |
+
self.nodes_to_include = set(nodes_to_include) if nodes_to_include else None
|
| 1266 |
+
self.node_quantizer = None
|
| 1267 |
+
|
| 1268 |
+
if algo_config is None:
|
| 1269 |
+
algo_config = DefaultWeightOnlyQuantConfig(
|
| 1270 |
+
block_size=block_size,
|
| 1271 |
+
is_symmetric=is_symmetric,
|
| 1272 |
+
accuracy_level=accuracy_level,
|
| 1273 |
+
quant_format=quant_format,
|
| 1274 |
+
op_types_to_quantize=op_types_to_quantize,
|
| 1275 |
+
quant_axes=quant_axes,
|
| 1276 |
+
bits=bits,
|
| 1277 |
+
channel_wised_quantize=channel_wised_quantize,
|
| 1278 |
+
)
|
| 1279 |
+
|
| 1280 |
+
self.algo_config = algo_config
|
| 1281 |
+
if hasattr(self.algo_config, "bits"):
|
| 1282 |
+
assert self.algo_config.bits in [2, 4, 8], "Only support 2, 4 or 8 bits quantization"
|
| 1283 |
+
|
| 1284 |
+
if algo_config.algorithm == "HQQ":
|
| 1285 |
+
self.node_quantizer = HQQWeightOnlyQuantizer(self.algo_config)
|
| 1286 |
+
elif algo_config.algorithm == "DEFAULT":
|
| 1287 |
+
self.node_quantizer = DefaultWeightOnlyQuantizer(self.algo_config)
|
| 1288 |
+
elif algo_config.algorithm == "nvidia_awq":
|
| 1289 |
+
self.node_quantizer = NVAWQWeightOnlyQuantizer(self.algo_config)
|
| 1290 |
+
|
| 1291 |
+
def _process_subgraph(self, graph_stack: list[GraphProto]):
|
| 1292 |
+
new_nodes = []
|
| 1293 |
+
graph = graph_stack[-1]
|
| 1294 |
+
|
| 1295 |
+
for node in graph.node:
|
| 1296 |
+
graph_attrs = [
|
| 1297 |
+
attr
|
| 1298 |
+
for attr in node.attribute
|
| 1299 |
+
if attr.type == onnx.AttributeProto.GRAPH or attr.type == onnx.AttributeProto.GRAPHS
|
| 1300 |
+
]
|
| 1301 |
+
if graph_attrs:
|
| 1302 |
+
kwargs = {}
|
| 1303 |
+
for attr in node.attribute:
|
| 1304 |
+
if attr.type == onnx.AttributeProto.GRAPH:
|
| 1305 |
+
# recursive call to take care of sub-graph
|
| 1306 |
+
graph_stack.append(attr.g)
|
| 1307 |
+
kv = {attr.name: self._process_subgraph(graph_stack)}
|
| 1308 |
+
elif attr.type == onnx.AttributeProto.GRAPHS:
|
| 1309 |
+
value = []
|
| 1310 |
+
for subgraph in attr.graphs:
|
| 1311 |
+
# recursive call to take care of sub-graph
|
| 1312 |
+
graph_stack.append(subgraph)
|
| 1313 |
+
value.extend([self._process_subgraph(graph_stack)])
|
| 1314 |
+
kv = {attr.name: value}
|
| 1315 |
+
else:
|
| 1316 |
+
kv = attribute_to_kwarg(attr)
|
| 1317 |
+
kwargs.update(kv)
|
| 1318 |
+
node = onnx.helper.make_node( # noqa: PLW2901
|
| 1319 |
+
node.op_type, node.input, node.output, name=node.name, **kwargs
|
| 1320 |
+
)
|
| 1321 |
+
out_nodes = []
|
| 1322 |
+
if node.name in self.nodes_to_exclude:
|
| 1323 |
+
logger.info(f"exclude to quantize {node.name} as specified by nodes_to_exclude...")
|
| 1324 |
+
out_nodes = [node]
|
| 1325 |
+
elif (self.nodes_to_include and node.name in self.nodes_to_include) or (
|
| 1326 |
+
node.op_type in self.algo_config.op_types_to_quantize
|
| 1327 |
+
):
|
| 1328 |
+
out_nodes = self.node_quantizer.quantize(node, graph_stack)
|
| 1329 |
+
else:
|
| 1330 |
+
logger.info(f"skip to quantize {node.name} ...")
|
| 1331 |
+
out_nodes = [node]
|
| 1332 |
+
new_nodes.extend(out_nodes)
|
| 1333 |
+
|
| 1334 |
+
graph.ClearField("node")
|
| 1335 |
+
graph.node.extend(new_nodes)
|
| 1336 |
+
graph_stack.pop()
|
| 1337 |
+
return graph
|
| 1338 |
+
|
| 1339 |
+
def _generate_q4_node_config(self):
|
| 1340 |
+
"""Generate weight only quant configuration for nodes."""
|
| 1341 |
+
q4_node_config = {}
|
| 1342 |
+
for node in self.model.model.graph.node:
|
| 1343 |
+
if node.op_type in ["MatMul"]:
|
| 1344 |
+
if not all(self.model.get_initializer(i) is None for i in node.input):
|
| 1345 |
+
template_config_q4 = {
|
| 1346 |
+
"bits": 4,
|
| 1347 |
+
"group_size": self.block_size,
|
| 1348 |
+
"scheme": "sym" if self.is_symmetric else "asym",
|
| 1349 |
+
}
|
| 1350 |
+
if (
|
| 1351 |
+
self.algo_config.customized_weight_config
|
| 1352 |
+
and node.name in self.algo_config.customized_weight_config
|
| 1353 |
+
):
|
| 1354 |
+
for key, value in self.algo_config.customized_weight_config[node.name].items():
|
| 1355 |
+
if key in template_config_q4:
|
| 1356 |
+
template_config_q4[key] = value
|
| 1357 |
+
q4_node_config[node.name] = template_config_q4
|
| 1358 |
+
return q4_node_config
|
| 1359 |
+
|
| 1360 |
+
def int4_quant_algo(self):
|
| 1361 |
+
"""4b quantize a model with RTN or GPTQ algorithm. Please refer to
|
| 1362 |
+
https://github.com/intel/neural-compressor/blob/master/docs/source/quantization_weight_only.md
|
| 1363 |
+
for more details on weight only quantization using Intel® Neural Compressor.
|
| 1364 |
+
"""
|
| 1365 |
+
|
| 1366 |
+
def inc_dataloader():
|
| 1367 |
+
data_reader = copy.deepcopy(self.algo_config.calibration_data_reader)
|
| 1368 |
+
for data in data_reader:
|
| 1369 |
+
yield data, None
|
| 1370 |
+
|
| 1371 |
+
kwargs = {}
|
| 1372 |
+
if self.accuracy_level is not None:
|
| 1373 |
+
kwargs["accuracy_level"] = self.accuracy_level
|
| 1374 |
+
weight_only_node_config = self._generate_q4_node_config()
|
| 1375 |
+
|
| 1376 |
+
algorithm = self.algo_config.algorithm
|
| 1377 |
+
logger.info(f"start to quantize model with {algorithm} algorithm...")
|
| 1378 |
+
if algorithm in ["RTN", "k_quant"]:
|
| 1379 |
+
kwargs["ratios"] = self.algo_config.ratios
|
| 1380 |
+
kwargs["algorithm"] = algorithm
|
| 1381 |
+
|
| 1382 |
+
"""
|
| 1383 |
+
We uses fp32 to represent the node that skip quantization, it does not mean this node is fp32 type though.
|
| 1384 |
+
"""
|
| 1385 |
+
for n in self.nodes_to_exclude:
|
| 1386 |
+
weight_only_node_config[n] = "fp32"
|
| 1387 |
+
|
| 1388 |
+
self.model = rtn_quantize(
|
| 1389 |
+
model=self.model_path if self.model_path is not None else self.model.model,
|
| 1390 |
+
weight_config=weight_only_node_config,
|
| 1391 |
+
**kwargs,
|
| 1392 |
+
)
|
| 1393 |
+
elif algorithm == "GPTQ":
|
| 1394 |
+
kwargs["percdamp"] = self.algo_config.percdamp
|
| 1395 |
+
kwargs["blocksize"] = self.algo_config.block_size
|
| 1396 |
+
kwargs["actorder"] = self.algo_config.actorder
|
| 1397 |
+
kwargs["mse"] = self.algo_config.mse
|
| 1398 |
+
kwargs["perchannel"] = self.algo_config.perchannel
|
| 1399 |
+
kwargs["n_samples"] = -1
|
| 1400 |
+
dataloader = inc_dataloader()
|
| 1401 |
+
|
| 1402 |
+
self.model = gptq_quantize(
|
| 1403 |
+
model=self.model_path if self.model_path is not None else self.model.model,
|
| 1404 |
+
weight_config=weight_only_node_config,
|
| 1405 |
+
dataloader=dataloader,
|
| 1406 |
+
**kwargs,
|
| 1407 |
+
)
|
| 1408 |
+
logger.info(f"complete quantization of model with {algorithm} algorithm.")
|
| 1409 |
+
|
| 1410 |
+
def process(self):
|
| 1411 |
+
if self.algo_config.algorithm in ["HQQ", "DEFAULT"]:
|
| 1412 |
+
# use a stack to keep track of sub-graphs
|
| 1413 |
+
graph_stack = [self.model.graph()]
|
| 1414 |
+
|
| 1415 |
+
# Update domain opset
|
| 1416 |
+
if self.algo_config.quant_format == QuantFormat.QOperator:
|
| 1417 |
+
self.model.set_opset_import("com.microsoft", 1)
|
| 1418 |
+
|
| 1419 |
+
if self.algo_config.quant_format == QuantFormat.QDQ or "Gather" in self.algo_config.op_types_to_quantize:
|
| 1420 |
+
opset_import = self.model.opset_import()
|
| 1421 |
+
for opset in opset_import:
|
| 1422 |
+
if opset.domain in [None, "ai.onnx", ""] and opset.version < 21:
|
| 1423 |
+
logger.warning(
|
| 1424 |
+
"The opset of the input model is under 21 and doesn't support int4 data type. "
|
| 1425 |
+
"Force to update it to opset 21, but the generated model may not be a valid model."
|
| 1426 |
+
)
|
| 1427 |
+
self.model.set_opset_import(opset.domain, 21)
|
| 1428 |
+
|
| 1429 |
+
self._process_subgraph(graph_stack)
|
| 1430 |
+
self.model.clean_initializers()
|
| 1431 |
+
elif self.algo_config.algorithm == "nvidia_awq":
|
| 1432 |
+
# Handle nvidia_awq quantization
|
| 1433 |
+
logger.info("Processing nvidia_awq quantization...")
|
| 1434 |
+
self.model = self.node_quantizer.quantize_awq(
|
| 1435 |
+
self.model.model if self.model_path is None else self.model_path
|
| 1436 |
+
)
|
| 1437 |
+
logger.info("Completed nvidia_awq quantization.")
|
| 1438 |
+
self.model = ONNXModel(self.model) # Ensure the model is wrapped back into ONNXModel
|
| 1439 |
+
self.model.clean_initializers()
|
| 1440 |
+
else:
|
| 1441 |
+
# RTN or GPTQ weight-only quantize algorithm
|
| 1442 |
+
self.int4_quant_algo()
|
| 1443 |
+
|
| 1444 |
+
|
| 1445 |
+
def ort_convert_str_to_bool(value):
|
| 1446 |
+
return value.lower() in ("true", "1")
|
| 1447 |
+
|
| 1448 |
+
|
| 1449 |
+
# Custom function to parse str:int pairs
|
| 1450 |
+
def parse_key_value_pair(s):
|
| 1451 |
+
key, value = s.split(":")
|
| 1452 |
+
return key, int(value)
|
| 1453 |
+
|
| 1454 |
+
|
| 1455 |
+
def parse_args():
|
| 1456 |
+
parser = argparse.ArgumentParser(
|
| 1457 |
+
description="""Blockwise int4 quantization for MatMul 2D weight matrices.
|
| 1458 |
+
|
| 1459 |
+
A weight matrix is partitioned into into blocks, where each block is a
|
| 1460 |
+
continguous subset inside each column. Each block is quantized into a
|
| 1461 |
+
set of 4b integers with a scaling factor and an optional offset.
|
| 1462 |
+
"""
|
| 1463 |
+
)
|
| 1464 |
+
|
| 1465 |
+
parser.add_argument("--input_model", required=True, help="Path to the input model file")
|
| 1466 |
+
parser.add_argument("--output_model", required=True, help="Path to the output model file")
|
| 1467 |
+
parser.add_argument("--block_size", required=False, default=32, type=int, help="Block size for quantization")
|
| 1468 |
+
parser.add_argument(
|
| 1469 |
+
"--quant_method",
|
| 1470 |
+
default="default",
|
| 1471 |
+
type=str,
|
| 1472 |
+
choices=["default", "hqq", "rtn", "k_quant", "gptq", "nvidia_awq"],
|
| 1473 |
+
help="the algorithm used to quantize weight, \nrtn and gptq leverage Intel® Neural Compressor",
|
| 1474 |
+
)
|
| 1475 |
+
parser.add_argument("--bits", default=4, type=int, help="the target bits to represent weight")
|
| 1476 |
+
parser.add_argument(
|
| 1477 |
+
"--symmetric",
|
| 1478 |
+
required=False,
|
| 1479 |
+
default=True,
|
| 1480 |
+
const=True,
|
| 1481 |
+
nargs="?",
|
| 1482 |
+
type=ort_convert_str_to_bool,
|
| 1483 |
+
choices=[True, False],
|
| 1484 |
+
help="Indicate whether to quantize the model symmetrically, symmetric is not supported by hqq",
|
| 1485 |
+
)
|
| 1486 |
+
parser.add_argument(
|
| 1487 |
+
"--accuracy_level",
|
| 1488 |
+
required=False,
|
| 1489 |
+
type=int,
|
| 1490 |
+
help="Accuracy level of the 4-bit quantized MatMul computation. "
|
| 1491 |
+
"Refer to the MatMulNBits contrib op's 'accuracy_level' attribute for details "
|
| 1492 |
+
"(https://github.com/microsoft/onnxruntime/blob/main/docs/ContribOperators.md#commicrosoftmatmulnbits).",
|
| 1493 |
+
)
|
| 1494 |
+
parser.add_argument("-v", "--verbose", required=False, action="store_true")
|
| 1495 |
+
parser.set_defaults(verbose=False)
|
| 1496 |
+
parser.add_argument(
|
| 1497 |
+
"--nodes_to_exclude",
|
| 1498 |
+
nargs="+",
|
| 1499 |
+
type=str,
|
| 1500 |
+
required=False,
|
| 1501 |
+
default=[],
|
| 1502 |
+
help="Specify the nodes to be excluded from quantization with node names",
|
| 1503 |
+
)
|
| 1504 |
+
parser.add_argument(
|
| 1505 |
+
"--nodes_to_include",
|
| 1506 |
+
nargs="+",
|
| 1507 |
+
type=str,
|
| 1508 |
+
required=False,
|
| 1509 |
+
help="Specify the specific nodes to be included from quantization with node names",
|
| 1510 |
+
)
|
| 1511 |
+
parser.add_argument(
|
| 1512 |
+
"--quant_format",
|
| 1513 |
+
default="QOperator",
|
| 1514 |
+
type=str,
|
| 1515 |
+
choices=["QOperator", "QDQ"],
|
| 1516 |
+
help="QuantFormat {QOperator, QDQ}"
|
| 1517 |
+
"QOperator format quantizes the model with quantized operators directly."
|
| 1518 |
+
"QDQ format quantize the model by inserting DeQuantizeLinear before the MatMul.",
|
| 1519 |
+
)
|
| 1520 |
+
parser.add_argument(
|
| 1521 |
+
"--op_types_to_quantize",
|
| 1522 |
+
type=str,
|
| 1523 |
+
nargs="+",
|
| 1524 |
+
choices=["MatMul", "Gather"],
|
| 1525 |
+
help="op_types_to_quantize {MatMul, Gather}. Operators to quantize. Default is MatMul.",
|
| 1526 |
+
)
|
| 1527 |
+
parser.add_argument(
|
| 1528 |
+
"--quant_axes",
|
| 1529 |
+
type=parse_key_value_pair,
|
| 1530 |
+
nargs="+",
|
| 1531 |
+
required=False,
|
| 1532 |
+
help="Key-value pairs in op_type:axis_to_quantize separated by space."
|
| 1533 |
+
"Specify the axis to quantize for an op. Default {MatMul:0, Gather:1}"
|
| 1534 |
+
"Example: --quant_axes MatMul:0 Gather:1",
|
| 1535 |
+
)
|
| 1536 |
+
# Group arguments specific to nvidia_awq
|
| 1537 |
+
nv_awq_config = parser.add_argument_group("nvidia_awq", "Arguments specific to nvidia_awq quantization")
|
| 1538 |
+
nv_awq_config.add_argument(
|
| 1539 |
+
"--calib_dataset_name",
|
| 1540 |
+
type=str,
|
| 1541 |
+
default="cnn",
|
| 1542 |
+
help="Name of the calibration dataset for nvidia_awq.",
|
| 1543 |
+
)
|
| 1544 |
+
nv_awq_config.add_argument(
|
| 1545 |
+
"--tokenizer_dir",
|
| 1546 |
+
type=str,
|
| 1547 |
+
required=False,
|
| 1548 |
+
help="Path of the tokenizer dir.",
|
| 1549 |
+
)
|
| 1550 |
+
nv_awq_config.add_argument(
|
| 1551 |
+
"--calibration_method",
|
| 1552 |
+
type=str,
|
| 1553 |
+
required=False,
|
| 1554 |
+
choices=["awq", "awq_clip"],
|
| 1555 |
+
help="Support two options, awq implementation and weight clipping.",
|
| 1556 |
+
)
|
| 1557 |
+
nv_awq_config.add_argument(
|
| 1558 |
+
"--cache_dir",
|
| 1559 |
+
type=str,
|
| 1560 |
+
default="./cache",
|
| 1561 |
+
help="Cache directory for calibration data.",
|
| 1562 |
+
)
|
| 1563 |
+
return parser.parse_args()
|
| 1564 |
+
|
| 1565 |
+
|
| 1566 |
+
if __name__ == "__main__":
|
| 1567 |
+
args = parse_args()
|
| 1568 |
+
if args.verbose:
|
| 1569 |
+
logger.setLevel(logging.DEBUG)
|
| 1570 |
+
|
| 1571 |
+
input_model_path = args.input_model
|
| 1572 |
+
output_model_path = args.output_model
|
| 1573 |
+
quant_format = QuantFormat[args.quant_format]
|
| 1574 |
+
op_types_to_quantize = tuple(args.op_types_to_quantize) if args.op_types_to_quantize else ("MatMul",)
|
| 1575 |
+
quant_axes = tuple(args.quant_axes) if args.quant_axes else None
|
| 1576 |
+
|
| 1577 |
+
if os.path.exists(output_model_path):
|
| 1578 |
+
logger.error(f"file {output_model_path} already exists")
|
| 1579 |
+
raise Exception(f"file {output_model_path} already exists")
|
| 1580 |
+
|
| 1581 |
+
if args.symmetric and args.quant_method == "hqq":
|
| 1582 |
+
logger.warning("symmetric is not supportted by hqq, will force to symmetric=False")
|
| 1583 |
+
args.symmetric = False
|
| 1584 |
+
|
| 1585 |
+
model = onnx.load(input_model_path)
|
| 1586 |
+
if args.quant_method == "hqq":
|
| 1587 |
+
quant_config = HQQWeightOnlyQuantConfig(
|
| 1588 |
+
block_size=args.block_size, bits=args.bits, op_types_to_quantize=op_types_to_quantize, quant_axes=quant_axes
|
| 1589 |
+
)
|
| 1590 |
+
elif args.quant_method == "default":
|
| 1591 |
+
quant_config = DefaultWeightOnlyQuantConfig(
|
| 1592 |
+
block_size=args.block_size,
|
| 1593 |
+
is_symmetric=args.symmetric,
|
| 1594 |
+
accuracy_level=args.accuracy_level,
|
| 1595 |
+
quant_format=quant_format,
|
| 1596 |
+
op_types_to_quantize=op_types_to_quantize,
|
| 1597 |
+
quant_axes=quant_axes,
|
| 1598 |
+
bits=args.bits,
|
| 1599 |
+
)
|
| 1600 |
+
elif args.quant_method == "rtn":
|
| 1601 |
+
quant_config = RTNWeightOnlyQuantConfig(op_types_to_quantize=op_types_to_quantize)
|
| 1602 |
+
elif args.quant_method == "k_quant":
|
| 1603 |
+
quant_config = KQuantWeightOnlyQuantConfig(op_types_to_quantize=op_types_to_quantize)
|
| 1604 |
+
elif args.quant_method == "gptq":
|
| 1605 |
+
quant_config = GPTQWeightOnlyQuantConfig(block_size=args.block_size, op_types_to_quantize=op_types_to_quantize)
|
| 1606 |
+
elif args.quant_method == "nvidia_awq":
|
| 1607 |
+
if quant_format == QuantFormat.QOperator:
|
| 1608 |
+
logger.warning("QOperator is not applicable to nvidia_awq. overriding the value to QDQ")
|
| 1609 |
+
quant_format = QuantFormat.QDQ
|
| 1610 |
+
|
| 1611 |
+
model = input_model_path
|
| 1612 |
+
if args.calibration_method is not None:
|
| 1613 |
+
if args.calibration_method == "awq":
|
| 1614 |
+
calibration_method = "awq_lite"
|
| 1615 |
+
else:
|
| 1616 |
+
calibration_method = "awq_clip"
|
| 1617 |
+
else:
|
| 1618 |
+
calibration_method = "awq_lite"
|
| 1619 |
+
|
| 1620 |
+
quant_config = NVAWQWeightOnlyQuantConfig(
|
| 1621 |
+
dataset_name=args.calib_dataset_name,
|
| 1622 |
+
tokenizer_dir=args.tokenizer_dir,
|
| 1623 |
+
cache_dir=args.cache_dir,
|
| 1624 |
+
calibration_method=calibration_method,
|
| 1625 |
+
)
|
| 1626 |
+
else:
|
| 1627 |
+
raise ValueError(f"Unsupported quantization method: {args.quant_method}")
|
| 1628 |
+
|
| 1629 |
+
quant = MatMulNBitsQuantizer(
|
| 1630 |
+
model=model,
|
| 1631 |
+
bits=args.bits,
|
| 1632 |
+
accuracy_level=args.accuracy_level,
|
| 1633 |
+
nodes_to_exclude=args.nodes_to_exclude,
|
| 1634 |
+
nodes_to_include=args.nodes_to_include,
|
| 1635 |
+
algo_config=quant_config,
|
| 1636 |
+
)
|
| 1637 |
+
quant.process()
|
| 1638 |
+
quant.model.save_model_to_file(output_model_path, True)
|
micromamba_root/envs/pytorch_env/Lib/site-packages/onnxruntime/quantization/neural_compressor/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
from .weight_only import gptq_quantize, rtn_quantize # noqa: F401
|
micromamba_root/envs/pytorch_env/Lib/site-packages/onnxruntime/quantization/neural_compressor/onnx_model.py
ADDED
|
@@ -0,0 +1,1236 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#
|
| 2 |
+
# The implementation of this file is based on:
|
| 3 |
+
# https://github.com/intel/neural-compressor/tree/master/neural_compressor
|
| 4 |
+
#
|
| 5 |
+
# Copyright (c) 2023 Intel Corporation
|
| 6 |
+
#
|
| 7 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 8 |
+
# you may not use this file except in compliance with the License.
|
| 9 |
+
# You may obtain a copy of the License at
|
| 10 |
+
#
|
| 11 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 12 |
+
#
|
| 13 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 14 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 15 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 16 |
+
# See the License for the specific language governing permissions and
|
| 17 |
+
# limitations under the License.
|
| 18 |
+
|
| 19 |
+
"""Class for ONNX model."""
|
| 20 |
+
|
| 21 |
+
import copy
|
| 22 |
+
import logging
|
| 23 |
+
import os
|
| 24 |
+
from collections import deque
|
| 25 |
+
from pathlib import Path
|
| 26 |
+
|
| 27 |
+
import onnx
|
| 28 |
+
import onnx.external_data_helper
|
| 29 |
+
import onnx_ir as ir
|
| 30 |
+
|
| 31 |
+
from .util import MAXIMUM_PROTOBUF, find_by_name
|
| 32 |
+
|
| 33 |
+
logger = logging.getLogger("neural_compressor")
|
| 34 |
+
|
| 35 |
+
# TODO: Check https://github.com/microsoft/onnxruntime/blob/main/onnxruntime/python/tools/quantization/onnx_model.py to see if we can integrate with it.
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
class ONNXModel:
|
| 39 |
+
"""Build ONNX model."""
|
| 40 |
+
|
| 41 |
+
def __init__(self, model, **kwargs):
|
| 42 |
+
"""Initialize an ONNX model.
|
| 43 |
+
|
| 44 |
+
Args:
|
| 45 |
+
model (str or ModelProto): path to onnx model or loaded ModelProto model object.
|
| 46 |
+
ignore_warning (bool): ignore large model warning. Default is False.
|
| 47 |
+
load_external_data (bool): load external data for large model. Default is True.
|
| 48 |
+
"""
|
| 49 |
+
self._model = model if not isinstance(model, str) else onnx.load(model, load_external_data=False)
|
| 50 |
+
self._model_path = None if not isinstance(model, str) else model
|
| 51 |
+
|
| 52 |
+
self.check_is_large_model()
|
| 53 |
+
if self._is_large_model and self._model_path is None and not kwargs.get("ignore_warning", False):
|
| 54 |
+
logger.warning("Model size > 2GB. Please use model path instead of onnx model object to quantize")
|
| 55 |
+
|
| 56 |
+
if self._is_large_model and isinstance(model, str) and kwargs.get("load_external_data", True):
|
| 57 |
+
onnx.external_data_helper.load_external_data_for_model(self._model, os.path.dirname(self._model_path))
|
| 58 |
+
|
| 59 |
+
self._config = None
|
| 60 |
+
if isinstance(model, str) and os.path.exists(Path(model).parent.joinpath("config.json").as_posix()):
|
| 61 |
+
from transformers import AutoConfig # noqa: PLC0415
|
| 62 |
+
|
| 63 |
+
self._config = AutoConfig.from_pretrained(Path(model).parent.as_posix())
|
| 64 |
+
|
| 65 |
+
self.node_name_counter = {}
|
| 66 |
+
self._output_name_to_node = {}
|
| 67 |
+
self._input_name_to_nodes = {}
|
| 68 |
+
self._get_input_name_to_nodes(self._model.graph.node)
|
| 69 |
+
self._get_output_name_to_node(self._model.graph.node)
|
| 70 |
+
self._graph_info = {}
|
| 71 |
+
self._get_graph_info()
|
| 72 |
+
self._q_config = None
|
| 73 |
+
|
| 74 |
+
def check_is_large_model(self):
|
| 75 |
+
"""Check model > 2GB."""
|
| 76 |
+
ir_graph = ir.from_proto(self._model.graph)
|
| 77 |
+
initializer_size = sum(
|
| 78 |
+
v.const_value.nbytes for v in ir_graph.initializers.values() if v.const_value is not None
|
| 79 |
+
)
|
| 80 |
+
self._is_large_model = initializer_size > MAXIMUM_PROTOBUF
|
| 81 |
+
|
| 82 |
+
@property
|
| 83 |
+
def is_large_model(self):
|
| 84 |
+
"""Check the onnx model is over 2GB."""
|
| 85 |
+
return self._is_large_model
|
| 86 |
+
|
| 87 |
+
@property
|
| 88 |
+
def model_path(self):
|
| 89 |
+
"""Return model path."""
|
| 90 |
+
return self._model_path
|
| 91 |
+
|
| 92 |
+
@model_path.setter
|
| 93 |
+
def model_path(self, path):
|
| 94 |
+
"""Set model path."""
|
| 95 |
+
self._model_path = path
|
| 96 |
+
|
| 97 |
+
def framework(self):
|
| 98 |
+
"""Return framework."""
|
| 99 |
+
return "onnxruntime"
|
| 100 |
+
|
| 101 |
+
@property
|
| 102 |
+
def q_config(self):
|
| 103 |
+
"""Return q_config."""
|
| 104 |
+
return self._q_config
|
| 105 |
+
|
| 106 |
+
@q_config.setter
|
| 107 |
+
def q_config(self, q_config):
|
| 108 |
+
"""Set q_config."""
|
| 109 |
+
self._q_config = q_config
|
| 110 |
+
|
| 111 |
+
@property
|
| 112 |
+
def hf_config(self):
|
| 113 |
+
"""Return huggingface config if model is Transformer-based."""
|
| 114 |
+
return self._config
|
| 115 |
+
|
| 116 |
+
@property
|
| 117 |
+
def model(self):
|
| 118 |
+
"""Return model itself."""
|
| 119 |
+
return self._model
|
| 120 |
+
|
| 121 |
+
@model.setter
|
| 122 |
+
def model(self, model):
|
| 123 |
+
"""Set model itself."""
|
| 124 |
+
self._model = model
|
| 125 |
+
self._graph_info = {}
|
| 126 |
+
self._get_graph_info()
|
| 127 |
+
self._output_name_to_node = {}
|
| 128 |
+
self._input_name_to_nodes = {}
|
| 129 |
+
self._get_input_name_to_nodes(self._model.graph.node)
|
| 130 |
+
self._get_output_name_to_node(self._model.graph.node)
|
| 131 |
+
|
| 132 |
+
def input(self):
|
| 133 |
+
"""Return input of model."""
|
| 134 |
+
return [i.name for i in self._model.graph.input]
|
| 135 |
+
|
| 136 |
+
def output(self):
|
| 137 |
+
"""Return output of model."""
|
| 138 |
+
return [i.name for i in self._model.graph.output]
|
| 139 |
+
|
| 140 |
+
def update(self):
|
| 141 |
+
"""Update model info."""
|
| 142 |
+
self._graph_info = {}
|
| 143 |
+
self._get_graph_info()
|
| 144 |
+
self._output_name_to_node = {}
|
| 145 |
+
self._input_name_to_nodes = {}
|
| 146 |
+
self._get_input_name_to_nodes(self._model.graph.node)
|
| 147 |
+
self._get_output_name_to_node(self._model.graph.node)
|
| 148 |
+
|
| 149 |
+
@property
|
| 150 |
+
def graph_info(self):
|
| 151 |
+
"""Return ORT Graph Info object holding information about backend graph."""
|
| 152 |
+
return self._graph_info
|
| 153 |
+
|
| 154 |
+
def _get_graph_info(self):
|
| 155 |
+
"""Update graph info."""
|
| 156 |
+
for node in self._model.graph.node:
|
| 157 |
+
self.graph_info.update({node.name: node.op_type})
|
| 158 |
+
|
| 159 |
+
def save(self, root):
|
| 160 |
+
"""Save ONNX model."""
|
| 161 |
+
if os.path.split(root)[0] != "" and not os.path.exists(os.path.split(root)[0]):
|
| 162 |
+
raise ValueError('"root" directory does not exists.')
|
| 163 |
+
if self.is_large_model:
|
| 164 |
+
onnx.external_data_helper.load_external_data_for_model(self._model, os.path.split(self._model_path)[0])
|
| 165 |
+
onnx.save_model(
|
| 166 |
+
self._model,
|
| 167 |
+
root,
|
| 168 |
+
save_as_external_data=True,
|
| 169 |
+
all_tensors_to_one_file=True,
|
| 170 |
+
location=root.split("/")[-1] + "_data",
|
| 171 |
+
size_threshold=1024,
|
| 172 |
+
convert_attribute=False,
|
| 173 |
+
)
|
| 174 |
+
else:
|
| 175 |
+
onnx.save(self._model, root)
|
| 176 |
+
|
| 177 |
+
if self._config is not None:
|
| 178 |
+
model_type = "" if not hasattr(self._config, "model_type") else self._config.model_type
|
| 179 |
+
self._config.__class__.model_type = model_type
|
| 180 |
+
output_config_file = Path(root).parent.joinpath("config.json").as_posix()
|
| 181 |
+
self._config.to_json_file(output_config_file, use_diff=False)
|
| 182 |
+
|
| 183 |
+
def nodes(self):
|
| 184 |
+
"""Return model nodes."""
|
| 185 |
+
return self._model.graph.node
|
| 186 |
+
|
| 187 |
+
def initializer(self):
|
| 188 |
+
"""Return model initializer."""
|
| 189 |
+
return self._model.graph.initializer
|
| 190 |
+
|
| 191 |
+
def graph(self):
|
| 192 |
+
"""Return model graph."""
|
| 193 |
+
return self._model.graph
|
| 194 |
+
|
| 195 |
+
def ir_version(self):
|
| 196 |
+
"""Return model ir_version."""
|
| 197 |
+
return self._model.ir_version
|
| 198 |
+
|
| 199 |
+
def opset_import(self):
|
| 200 |
+
"""Return model opset_import."""
|
| 201 |
+
return self._model.opset_import
|
| 202 |
+
|
| 203 |
+
def remove_node(self, node):
|
| 204 |
+
"""Remove a node from model."""
|
| 205 |
+
if node in self._model.graph.node:
|
| 206 |
+
self._model.graph.node.remove(node)
|
| 207 |
+
|
| 208 |
+
def remove_nodes(self, nodes_to_remove):
|
| 209 |
+
"""Remove nodes from model."""
|
| 210 |
+
for node in nodes_to_remove:
|
| 211 |
+
self.remove_node(node)
|
| 212 |
+
|
| 213 |
+
def add_node(self, node):
|
| 214 |
+
"""Add a node to model."""
|
| 215 |
+
self._model.graph.node.extend([node])
|
| 216 |
+
|
| 217 |
+
def add_nodes(self, nodes_to_add):
|
| 218 |
+
"""Add nodes to model."""
|
| 219 |
+
self._model.graph.node.extend(nodes_to_add)
|
| 220 |
+
|
| 221 |
+
def add_initializer(self, tensor):
|
| 222 |
+
"""Add a initializer to model."""
|
| 223 |
+
if find_by_name(tensor.name, self._model.graph.initializer) is None:
|
| 224 |
+
self._model.graph.initializer.extend([tensor])
|
| 225 |
+
|
| 226 |
+
def add_initializers(self, tensors):
|
| 227 |
+
"""Add initializers to model."""
|
| 228 |
+
for tensor in tensors:
|
| 229 |
+
self.add_initializer(tensor)
|
| 230 |
+
|
| 231 |
+
def get_initializer(self, name):
|
| 232 |
+
"""Get an initializer by name."""
|
| 233 |
+
for tensor in self._model.graph.initializer:
|
| 234 |
+
if tensor.name == name:
|
| 235 |
+
return tensor
|
| 236 |
+
return None
|
| 237 |
+
|
| 238 |
+
def get_initializer_share_num(self, name):
|
| 239 |
+
"""Get the number of shares of initializer."""
|
| 240 |
+
num = 0
|
| 241 |
+
if self.get_initializer(name) is None:
|
| 242 |
+
return num
|
| 243 |
+
|
| 244 |
+
for node in self.nodes():
|
| 245 |
+
if name in node.input:
|
| 246 |
+
num += 1
|
| 247 |
+
return num
|
| 248 |
+
|
| 249 |
+
def get_node(self, name):
|
| 250 |
+
"""Get a node by name."""
|
| 251 |
+
for node in self._model.graph.node:
|
| 252 |
+
if node.name == name:
|
| 253 |
+
return node
|
| 254 |
+
return None
|
| 255 |
+
|
| 256 |
+
def remove_initializer(self, tensor):
|
| 257 |
+
"""Remove an initializer from model."""
|
| 258 |
+
if tensor in self._model.graph.initializer:
|
| 259 |
+
self._model.graph.initializer.remove(tensor)
|
| 260 |
+
|
| 261 |
+
def remove_initializers(self, init_to_remove):
|
| 262 |
+
"""Remove initializers from model."""
|
| 263 |
+
for initializer in init_to_remove:
|
| 264 |
+
self.remove_initializer(initializer)
|
| 265 |
+
|
| 266 |
+
def set_initializer(self, tensor, array, raw=False):
|
| 267 |
+
"""Update initializer."""
|
| 268 |
+
old_tensor = self.get_initializer(tensor)
|
| 269 |
+
self.remove_initializer(old_tensor)
|
| 270 |
+
dims = old_tensor.dims
|
| 271 |
+
data_type = old_tensor.data_type
|
| 272 |
+
new_tensor = (
|
| 273 |
+
onnx.helper.make_tensor(tensor, data_type, dims, array.flatten().tolist())
|
| 274 |
+
if not raw
|
| 275 |
+
else onnx.helper.make_tensor(tensor, data_type, dims, array.tostring(), raw=raw)
|
| 276 |
+
)
|
| 277 |
+
self.add_initializer(new_tensor)
|
| 278 |
+
|
| 279 |
+
@property
|
| 280 |
+
def input_name_to_nodes(self):
|
| 281 |
+
"""Return input names of nodes."""
|
| 282 |
+
return self._input_name_to_nodes
|
| 283 |
+
|
| 284 |
+
def _get_input_name_to_nodes(self, nodes):
|
| 285 |
+
"""Get input names of nodes."""
|
| 286 |
+
for node in nodes:
|
| 287 |
+
attrs = [
|
| 288 |
+
attr
|
| 289 |
+
for attr in node.attribute
|
| 290 |
+
if attr.type == onnx.AttributeProto.GRAPH or attr.type == onnx.AttributeProto.GRAPHS
|
| 291 |
+
]
|
| 292 |
+
if len(attrs) > 0:
|
| 293 |
+
for attr in attrs:
|
| 294 |
+
self._get_input_name_to_nodes(attr.g.node)
|
| 295 |
+
for input_name in node.input:
|
| 296 |
+
if len(input_name.strip()) != 0:
|
| 297 |
+
if input_name not in self._input_name_to_nodes:
|
| 298 |
+
self._input_name_to_nodes[input_name] = [node]
|
| 299 |
+
else:
|
| 300 |
+
self._input_name_to_nodes[input_name].append(node)
|
| 301 |
+
|
| 302 |
+
@property
|
| 303 |
+
def output_name_to_node(self):
|
| 304 |
+
"""Return output names of nodes."""
|
| 305 |
+
return self._output_name_to_node
|
| 306 |
+
|
| 307 |
+
def _get_output_name_to_node(self, nodes):
|
| 308 |
+
"""Get output names of nodes."""
|
| 309 |
+
for node in nodes:
|
| 310 |
+
attrs = [
|
| 311 |
+
attr
|
| 312 |
+
for attr in node.attribute
|
| 313 |
+
if attr.type == onnx.AttributeProto.GRAPH or attr.type == onnx.AttributeProto.GRAPHS
|
| 314 |
+
]
|
| 315 |
+
if len(attrs) > 0:
|
| 316 |
+
for attr in attrs:
|
| 317 |
+
self._get_output_name_to_node(attr.g.node)
|
| 318 |
+
for output_name in node.output:
|
| 319 |
+
if len(output_name.strip()) != 0:
|
| 320 |
+
self._output_name_to_node[output_name] = node
|
| 321 |
+
|
| 322 |
+
def get_siblings(self, node):
|
| 323 |
+
"""Get siblings nodes."""
|
| 324 |
+
siblings = []
|
| 325 |
+
for parent in self.get_parents(node):
|
| 326 |
+
for child in self.get_children(parent):
|
| 327 |
+
if child.name != node.name:
|
| 328 |
+
siblings.append(child)
|
| 329 |
+
return siblings
|
| 330 |
+
|
| 331 |
+
def get_children(self, node, input_name_to_nodes=None):
|
| 332 |
+
"""Get children nodes."""
|
| 333 |
+
if input_name_to_nodes is None:
|
| 334 |
+
input_name_to_nodes = self._input_name_to_nodes
|
| 335 |
+
|
| 336 |
+
children = []
|
| 337 |
+
for output in node.output:
|
| 338 |
+
if output in input_name_to_nodes:
|
| 339 |
+
for child in input_name_to_nodes[output]:
|
| 340 |
+
children.append(child) # noqa: PERF402
|
| 341 |
+
return children
|
| 342 |
+
|
| 343 |
+
def get_parents(self, node, output_name_to_node=None):
|
| 344 |
+
"""Get parents nodes."""
|
| 345 |
+
if output_name_to_node is None:
|
| 346 |
+
output_name_to_node = self._output_name_to_node
|
| 347 |
+
|
| 348 |
+
parents = []
|
| 349 |
+
for input in node.input:
|
| 350 |
+
if input in output_name_to_node:
|
| 351 |
+
parents.append(output_name_to_node[input])
|
| 352 |
+
return parents
|
| 353 |
+
|
| 354 |
+
def get_parent(self, node, idx, output_name_to_node=None):
|
| 355 |
+
"""Get parent node by idx."""
|
| 356 |
+
if output_name_to_node is None:
|
| 357 |
+
output_name_to_node = self._output_name_to_node
|
| 358 |
+
|
| 359 |
+
if len(node.input) <= idx:
|
| 360 |
+
return None
|
| 361 |
+
|
| 362 |
+
input = node.input[idx]
|
| 363 |
+
if input not in output_name_to_node:
|
| 364 |
+
return None
|
| 365 |
+
|
| 366 |
+
return output_name_to_node[input]
|
| 367 |
+
|
| 368 |
+
def find_node_by_name(self, node_name, new_nodes_list, graph):
|
| 369 |
+
"""Find out node by name."""
|
| 370 |
+
graph_nodes_list = list(graph.node) # deep copy
|
| 371 |
+
graph_nodes_list.extend(new_nodes_list)
|
| 372 |
+
node = find_by_name(node_name, graph_nodes_list)
|
| 373 |
+
return node
|
| 374 |
+
|
| 375 |
+
def find_nodes_by_initializer(self, graph, initializer):
|
| 376 |
+
"""Find all nodes with given initializer as an input."""
|
| 377 |
+
nodes = []
|
| 378 |
+
for node in graph.node:
|
| 379 |
+
for node_input in node.input:
|
| 380 |
+
if node_input == initializer.name:
|
| 381 |
+
nodes.append(node)
|
| 382 |
+
return nodes
|
| 383 |
+
|
| 384 |
+
def get_scale_zero(self, tensor):
|
| 385 |
+
"""Help function to get scale and zero_point."""
|
| 386 |
+
if not tensor.endswith("_quantized"):
|
| 387 |
+
logger.debug(f"Find {tensor} in the quantized graph is not quantized.")
|
| 388 |
+
return None, None
|
| 389 |
+
|
| 390 |
+
def _searcher(tensor_name):
|
| 391 |
+
"""Search scale and zero point tensor recursively."""
|
| 392 |
+
node = self._input_name_to_nodes[tensor_name][0]
|
| 393 |
+
parent = self._output_name_to_node.get(tensor_name, None)
|
| 394 |
+
direct_int8 = ["Reshape", "Transpose", "Squeeze", "Unsqueeze", "MaxPool", "Pad", "Split"]
|
| 395 |
+
if parent is not None and parent.op_type in direct_int8:
|
| 396 |
+
fp32_tensor_name = (
|
| 397 |
+
parent.input[0]
|
| 398 |
+
.replace("_quantized", "")
|
| 399 |
+
.replace("_QuantizeLinear", "")
|
| 400 |
+
.replace("_QuantizeInput", "")
|
| 401 |
+
)
|
| 402 |
+
elif node.op_type in ["Gather"]: # pragma: no cover
|
| 403 |
+
fp32_tensor_name = (
|
| 404 |
+
node.output[0]
|
| 405 |
+
.replace("_quantized", "")
|
| 406 |
+
.replace("_QuantizeLinear", "")
|
| 407 |
+
.replace("_QuantizeInput", "")
|
| 408 |
+
)
|
| 409 |
+
else:
|
| 410 |
+
fp32_tensor_name = (
|
| 411 |
+
tensor_name.replace("_quantized", "").replace("_QuantizeLinear", "").replace("_QuantizeInput", "")
|
| 412 |
+
)
|
| 413 |
+
scale = fp32_tensor_name + "_scale"
|
| 414 |
+
scale_tensor = self.get_initializer(scale)
|
| 415 |
+
zo = fp32_tensor_name + "_zero_point"
|
| 416 |
+
zo_tensor = self.get_initializer(zo)
|
| 417 |
+
|
| 418 |
+
if scale_tensor is None or zo_tensor is None:
|
| 419 |
+
if parent is not None:
|
| 420 |
+
scale_tensor, zo_tensor = _searcher(parent.input[0])
|
| 421 |
+
return scale_tensor, zo_tensor
|
| 422 |
+
|
| 423 |
+
node = self._input_name_to_nodes[tensor][0]
|
| 424 |
+
# TODO check if scale_tensor and zero_point is needed
|
| 425 |
+
# for bias of qlinearconv, scale and zero_point is not needed
|
| 426 |
+
if (node.op_type == "QLinearConv" and tensor == node.input[-1]) or (
|
| 427 |
+
node.op_type == "QGemm" and tensor == node.input[-3]
|
| 428 |
+
):
|
| 429 |
+
return None, None
|
| 430 |
+
else:
|
| 431 |
+
scale_tensor, zo_tensor = _searcher(tensor)
|
| 432 |
+
assert scale_tensor, f"missing scale for tensor {tensor}"
|
| 433 |
+
assert zo_tensor, f"missing zero point for tensor {tensor}"
|
| 434 |
+
return scale_tensor, zo_tensor
|
| 435 |
+
|
| 436 |
+
def save_model_to_file(self, output_path, use_external_data_format=False):
|
| 437 |
+
"""Save model to external data, which is needed for model size > 2GB."""
|
| 438 |
+
if use_external_data_format:
|
| 439 |
+
onnx.external_data_helper.convert_model_to_external_data(
|
| 440 |
+
self._model, all_tensors_to_one_file=True, location=Path(output_path).name + ".data"
|
| 441 |
+
)
|
| 442 |
+
onnx.save_model(self._model, output_path)
|
| 443 |
+
|
| 444 |
+
@staticmethod
|
| 445 |
+
def replace_node_input(node, old_input_name, new_input_name):
|
| 446 |
+
"""Replace input of a node."""
|
| 447 |
+
assert isinstance(old_input_name, str) and isinstance(new_input_name, str)
|
| 448 |
+
for j in range(len(node.input)):
|
| 449 |
+
if node.input[j] == old_input_name:
|
| 450 |
+
node.input[j] = new_input_name
|
| 451 |
+
|
| 452 |
+
def replace_input_of_all_nodes(self, old_input_name, new_input_name, white_optype=None, black_optype=None):
|
| 453 |
+
"""Replace inputs of all nodes."""
|
| 454 |
+
if white_optype is None:
|
| 455 |
+
white_optype = []
|
| 456 |
+
if black_optype is None:
|
| 457 |
+
black_optype = []
|
| 458 |
+
if len(white_optype) > 0:
|
| 459 |
+
for node in self.model.graph.node:
|
| 460 |
+
if node.op_type in white_optype:
|
| 461 |
+
ONNXModel.replace_node_input(node, old_input_name, new_input_name)
|
| 462 |
+
else:
|
| 463 |
+
for node in self.model.graph.node:
|
| 464 |
+
if node.op_type not in black_optype:
|
| 465 |
+
ONNXModel.replace_node_input(node, old_input_name, new_input_name)
|
| 466 |
+
|
| 467 |
+
@staticmethod
|
| 468 |
+
def replace_node_output(node, old_output_name, new_output_name):
|
| 469 |
+
"""Replace output of a node."""
|
| 470 |
+
assert isinstance(old_output_name, str) and isinstance(new_output_name, str)
|
| 471 |
+
for j in range(len(node.output)):
|
| 472 |
+
if node.output[j] == old_output_name:
|
| 473 |
+
node.output[j] = new_output_name
|
| 474 |
+
|
| 475 |
+
def replace_output_of_all_nodes(self, old_output_name, new_output_name, white_optype=None, black_optype=None):
|
| 476 |
+
"""Replace outputs of all nodes."""
|
| 477 |
+
if white_optype is None:
|
| 478 |
+
white_optype = []
|
| 479 |
+
if black_optype is None:
|
| 480 |
+
black_optype = []
|
| 481 |
+
if len(white_optype) > 0:
|
| 482 |
+
for node in self.model.graph.node:
|
| 483 |
+
if node.op_type in white_optype:
|
| 484 |
+
ONNXModel.replace_node_output(node, old_output_name, new_output_name)
|
| 485 |
+
else:
|
| 486 |
+
for node in self.model.graph.node:
|
| 487 |
+
if node.op_type not in black_optype:
|
| 488 |
+
ONNXModel.replace_node_output(node, old_output_name, new_output_name)
|
| 489 |
+
|
| 490 |
+
def remove_unused_nodes(self):
|
| 491 |
+
"""Remove unused nodes."""
|
| 492 |
+
unused_nodes = []
|
| 493 |
+
nodes = self.nodes()
|
| 494 |
+
for node in nodes:
|
| 495 |
+
if (
|
| 496 |
+
node.op_type == "Constant"
|
| 497 |
+
and node.output[0] not in self._model.graph.output
|
| 498 |
+
and node.output[0] not in self._input_name_to_nodes
|
| 499 |
+
):
|
| 500 |
+
unused_nodes.append(node)
|
| 501 |
+
elif (
|
| 502 |
+
node.op_type == "QuantizeLinear"
|
| 503 |
+
and len(self.get_children(node)) == 1
|
| 504 |
+
and self.get_children(node)[0].op_type == "DequantizeLinear"
|
| 505 |
+
and node.input[0] not in self._output_name_to_node
|
| 506 |
+
and self.get_children(node)[0].output[0] not in self._input_name_to_nodes
|
| 507 |
+
):
|
| 508 |
+
unused_nodes.append(node)
|
| 509 |
+
unused_nodes.extend(self.get_children(node))
|
| 510 |
+
else:
|
| 511 |
+
# remove the node if it does not serve as the input or output of any other nodes
|
| 512 |
+
unused = True
|
| 513 |
+
for output in node.output:
|
| 514 |
+
if output in self._input_name_to_nodes or output in self.output():
|
| 515 |
+
unused = False
|
| 516 |
+
break
|
| 517 |
+
for input in node.input:
|
| 518 |
+
if self.get_initializer(input) is not None:
|
| 519 |
+
continue
|
| 520 |
+
elif input in self._output_name_to_node or input in self.input():
|
| 521 |
+
unused = False
|
| 522 |
+
break
|
| 523 |
+
if unused:
|
| 524 |
+
unused_nodes.append(node)
|
| 525 |
+
self.remove_nodes(unused_nodes)
|
| 526 |
+
|
| 527 |
+
ununsed_weights = []
|
| 528 |
+
for w in self._model.graph.initializer:
|
| 529 |
+
if w.name not in self._input_name_to_nodes and w.name not in self._model.graph.output:
|
| 530 |
+
ununsed_weights.append(w)
|
| 531 |
+
# Remove from graph.input
|
| 532 |
+
for graph_input in self.graph().input:
|
| 533 |
+
if graph_input.name == w.name:
|
| 534 |
+
self.graph().input.remove(graph_input)
|
| 535 |
+
|
| 536 |
+
self.remove_initializers(ununsed_weights)
|
| 537 |
+
self.update()
|
| 538 |
+
|
| 539 |
+
def topological_sort(self, enable_subgraph=False):
|
| 540 |
+
"""Topological sort the model."""
|
| 541 |
+
|
| 542 |
+
if not enable_subgraph:
|
| 543 |
+
input_name_to_nodes = {}
|
| 544 |
+
output_name_to_node = {}
|
| 545 |
+
for node in self.model.graph.node:
|
| 546 |
+
for input_name in node.input:
|
| 547 |
+
if len(input_name.strip()) != 0:
|
| 548 |
+
if input_name not in input_name_to_nodes:
|
| 549 |
+
input_name_to_nodes[input_name] = [node]
|
| 550 |
+
else:
|
| 551 |
+
input_name_to_nodes[input_name].append(node)
|
| 552 |
+
for output_name in node.output:
|
| 553 |
+
if len(output_name.strip()) != 0:
|
| 554 |
+
output_name_to_node[output_name] = node
|
| 555 |
+
else: # pragma: no cover
|
| 556 |
+
input_name_to_nodes = self._input_name_to_nodes
|
| 557 |
+
output_name_to_node = self._output_name_to_node
|
| 558 |
+
|
| 559 |
+
all_nodes = {}
|
| 560 |
+
q = deque()
|
| 561 |
+
wait = deque()
|
| 562 |
+
for inp in self.model.graph.input:
|
| 563 |
+
q.extend(input_name_to_nodes[inp.name])
|
| 564 |
+
for n in self.model.graph.node:
|
| 565 |
+
if all(i not in output_name_to_node and i not in self.input() for i in n.input):
|
| 566 |
+
q.append(n)
|
| 567 |
+
|
| 568 |
+
while q:
|
| 569 |
+
n = q.popleft()
|
| 570 |
+
if not all(output_name_to_node[i].name in all_nodes for i in n.input if i in output_name_to_node):
|
| 571 |
+
if n not in wait:
|
| 572 |
+
wait.append(n)
|
| 573 |
+
continue
|
| 574 |
+
|
| 575 |
+
all_nodes[n.name] = n
|
| 576 |
+
for out in n.output:
|
| 577 |
+
if out in input_name_to_nodes:
|
| 578 |
+
q.extend([i for i in input_name_to_nodes[out] if i.name not in all_nodes and i not in q])
|
| 579 |
+
if len(q) == 0 and len(wait) != 0:
|
| 580 |
+
q = copy.deepcopy(wait)
|
| 581 |
+
wait.clear()
|
| 582 |
+
nodes = [i[1] for i in all_nodes.items()]
|
| 583 |
+
assert len(list({n.name for n in nodes})) == len(list({n.name for n in self.model.graph.node}))
|
| 584 |
+
self.model.graph.ClearField("node")
|
| 585 |
+
self.model.graph.node.extend(nodes)
|
| 586 |
+
|
| 587 |
+
def get_nodes_chain(self, start, stop, result_chain=None):
|
| 588 |
+
"""Get nodes chain with given start node and stop node."""
|
| 589 |
+
if result_chain is None:
|
| 590 |
+
result_chain = []
|
| 591 |
+
# process start node list
|
| 592 |
+
start_node = deque()
|
| 593 |
+
for node in start:
|
| 594 |
+
if isinstance(node, str):
|
| 595 |
+
start_node.append(node)
|
| 596 |
+
elif isinstance(node, onnx.NodeProto):
|
| 597 |
+
start_node.append(node.name)
|
| 598 |
+
else:
|
| 599 |
+
assert False, "'get_nodes_chain' function only support list[string]or list[NodeProto] params" # noqa: B011
|
| 600 |
+
|
| 601 |
+
# process stop node list
|
| 602 |
+
stop_node = []
|
| 603 |
+
for node in stop:
|
| 604 |
+
if isinstance(node, str):
|
| 605 |
+
stop_node.append(node)
|
| 606 |
+
elif isinstance(node, onnx.NodeProto):
|
| 607 |
+
stop_node.append(node.name)
|
| 608 |
+
else:
|
| 609 |
+
assert False, "'get_nodes_chain' function only support list[string]or list[NodeProto] params" # noqa: B011
|
| 610 |
+
|
| 611 |
+
while start_node:
|
| 612 |
+
node_name = start_node.popleft()
|
| 613 |
+
if node_name in stop_node:
|
| 614 |
+
continue
|
| 615 |
+
if node_name not in result_chain:
|
| 616 |
+
result_chain.append(node_name)
|
| 617 |
+
else:
|
| 618 |
+
continue
|
| 619 |
+
|
| 620 |
+
node = find_by_name(node_name, list(self.model.graph.node))
|
| 621 |
+
for parent in self.get_parents(node):
|
| 622 |
+
start_node.append(parent.name)
|
| 623 |
+
|
| 624 |
+
return result_chain
|
| 625 |
+
|
| 626 |
+
def find_split_node_for_layer_wise_quantization(self):
|
| 627 |
+
"""Find split node for layer wise quantization."""
|
| 628 |
+
# find split nodes of decoder blocks
|
| 629 |
+
# embed -> decoder.0 -(split_node)-> ... -(split_node)-> decoder.n -(split_node)-> norm -> head
|
| 630 |
+
# after split: embed -> decoder.0,
|
| 631 |
+
# decoder.1,
|
| 632 |
+
# decoder.2,
|
| 633 |
+
# ...,
|
| 634 |
+
# decoder.n,
|
| 635 |
+
# norm -> head
|
| 636 |
+
start_nodes = []
|
| 637 |
+
for node in self._model.graph.node:
|
| 638 |
+
start_node, qkv_nodes_list = None, None
|
| 639 |
+
if node.op_type == "SkipLayerNormalization":
|
| 640 |
+
start_node = node
|
| 641 |
+
qkv_nodes_list = [
|
| 642 |
+
self.match_parent_path(
|
| 643 |
+
start_node,
|
| 644 |
+
["MatMul", "Reshape", "Transpose", "Reshape", "MatMul"],
|
| 645 |
+
[None, 0, 0, 0, 0],
|
| 646 |
+
),
|
| 647 |
+
self.match_parent_path(
|
| 648 |
+
start_node,
|
| 649 |
+
["Add", "MatMul", "Reshape", "Transpose", "MatMul"],
|
| 650 |
+
[1, 1, 0, 0, 0],
|
| 651 |
+
),
|
| 652 |
+
]
|
| 653 |
+
if node.op_type == "Add":
|
| 654 |
+
start_node = node
|
| 655 |
+
qkv_nodes_list = [
|
| 656 |
+
# match base attention structure
|
| 657 |
+
self.match_parent_path(
|
| 658 |
+
start_node,
|
| 659 |
+
["Add", "MatMul", "Reshape", "Transpose", "MatMul"],
|
| 660 |
+
[0, None, 0, 0, 0],
|
| 661 |
+
),
|
| 662 |
+
self.match_parent_path(
|
| 663 |
+
start_node, ["Add", "MatMul", "Reshape", "Transpose", "MatMul"], [1, None, 0, 0, 0]
|
| 664 |
+
),
|
| 665 |
+
# match gpt attention no past structure
|
| 666 |
+
self.match_parent_path(
|
| 667 |
+
start_node,
|
| 668 |
+
["Reshape", "Gemm", "Reshape", "Reshape", "Transpose", "MatMul"],
|
| 669 |
+
[None, 0, 0, 0, 0, 0],
|
| 670 |
+
output_name_to_node=self.output_name_to_node,
|
| 671 |
+
return_indice=[],
|
| 672 |
+
),
|
| 673 |
+
# match bart attention structure
|
| 674 |
+
self.match_parent_path(
|
| 675 |
+
start_node,
|
| 676 |
+
["Add", "MatMul", "Reshape", "Transpose", "Reshape", "MatMul"],
|
| 677 |
+
[0, None, 0, 0, 0, 0],
|
| 678 |
+
),
|
| 679 |
+
self.match_parent_path(
|
| 680 |
+
start_node,
|
| 681 |
+
["Add", "MatMul", "Reshape", "Transpose", "Reshape", "MatMul"],
|
| 682 |
+
[1, None, 0, 0, 0, 0],
|
| 683 |
+
),
|
| 684 |
+
self.match_parent_path(
|
| 685 |
+
start_node,
|
| 686 |
+
["MatMul", "Mul", "MatMul", "Mul", "Div", "Add"],
|
| 687 |
+
[None, 0, None, 0, None, 0],
|
| 688 |
+
),
|
| 689 |
+
self.match_parent_path(
|
| 690 |
+
start_node,
|
| 691 |
+
["MatMul", "Mul", "MatMul", "SimplifiedLayerNormalization", "Add"],
|
| 692 |
+
[None, 0, None, 0, 0],
|
| 693 |
+
),
|
| 694 |
+
]
|
| 695 |
+
if not start_node:
|
| 696 |
+
continue
|
| 697 |
+
if not any(qkv_nodes_list):
|
| 698 |
+
continue
|
| 699 |
+
start_nodes.append(start_node)
|
| 700 |
+
return start_nodes
|
| 701 |
+
|
| 702 |
+
def find_qkv_in_attention(self, find_all=False):
|
| 703 |
+
"""Find qkv MatMul in Attention.
|
| 704 |
+
|
| 705 |
+
Args:
|
| 706 |
+
find_all (bool, optional): find all qkv MatMul. Defaults to False
|
| 707 |
+
|
| 708 |
+
Returns:
|
| 709 |
+
qkv (list): qkv MatMul list
|
| 710 |
+
"""
|
| 711 |
+
qkv = []
|
| 712 |
+
for node in self._model.graph.node:
|
| 713 |
+
if node.op_type == "Attention":
|
| 714 |
+
qkv.append([node.name])
|
| 715 |
+
continue
|
| 716 |
+
start_node, qkv_nodes_list = None, None
|
| 717 |
+
if node.op_type == "SkipLayerNormalization":
|
| 718 |
+
start_node = node
|
| 719 |
+
qkv_nodes_list = [
|
| 720 |
+
self.match_parent_path(
|
| 721 |
+
start_node,
|
| 722 |
+
["MatMul", "Reshape", "Transpose", "Reshape", "MatMul"],
|
| 723 |
+
[None, 0, 0, 0, 0],
|
| 724 |
+
),
|
| 725 |
+
self.match_parent_path(
|
| 726 |
+
start_node,
|
| 727 |
+
["Add", "MatMul", "Reshape", "Transpose", "MatMul"],
|
| 728 |
+
[1, 1, 0, 0, 0],
|
| 729 |
+
),
|
| 730 |
+
]
|
| 731 |
+
if node.op_type == "Add":
|
| 732 |
+
start_node = node
|
| 733 |
+
qkv_nodes_list = [
|
| 734 |
+
# match base attention structure
|
| 735 |
+
self.match_parent_path(
|
| 736 |
+
start_node,
|
| 737 |
+
["Add", "MatMul", "Reshape", "Transpose", "MatMul"],
|
| 738 |
+
[0, None, 0, 0, 0],
|
| 739 |
+
),
|
| 740 |
+
self.match_parent_path(
|
| 741 |
+
start_node, ["Add", "MatMul", "Reshape", "Transpose", "MatMul"], [1, None, 0, 0, 0]
|
| 742 |
+
),
|
| 743 |
+
# match gpt attention no past structure
|
| 744 |
+
self.match_parent_path(
|
| 745 |
+
start_node,
|
| 746 |
+
["Reshape", "Gemm", "Reshape", "Reshape", "Transpose", "MatMul"],
|
| 747 |
+
[None, 0, 0, 0, 0, 0],
|
| 748 |
+
output_name_to_node=self.output_name_to_node,
|
| 749 |
+
return_indice=[],
|
| 750 |
+
),
|
| 751 |
+
# match bart attention structure
|
| 752 |
+
self.match_parent_path(
|
| 753 |
+
start_node,
|
| 754 |
+
["Add", "MatMul", "Reshape", "Transpose", "Reshape", "MatMul"],
|
| 755 |
+
[0, None, 0, 0, 0, 0],
|
| 756 |
+
),
|
| 757 |
+
self.match_parent_path(
|
| 758 |
+
start_node,
|
| 759 |
+
["Add", "MatMul", "Reshape", "Transpose", "Reshape", "MatMul"],
|
| 760 |
+
[1, None, 0, 0, 0, 0],
|
| 761 |
+
),
|
| 762 |
+
]
|
| 763 |
+
if not start_node:
|
| 764 |
+
continue
|
| 765 |
+
if not any(qkv_nodes_list):
|
| 766 |
+
continue
|
| 767 |
+
qkv_nodes = [qkv for qkv in qkv_nodes_list if qkv is not None][-1]
|
| 768 |
+
other_inputs = []
|
| 769 |
+
for input in start_node.input:
|
| 770 |
+
if input not in self.output_name_to_node:
|
| 771 |
+
continue
|
| 772 |
+
if input == qkv_nodes[0].output[0]:
|
| 773 |
+
continue
|
| 774 |
+
other_inputs.append(input)
|
| 775 |
+
if len(other_inputs) != 1:
|
| 776 |
+
continue
|
| 777 |
+
root_input = other_inputs[0]
|
| 778 |
+
input_name_to_nodes = self.input_name_to_nodes
|
| 779 |
+
children = input_name_to_nodes[root_input]
|
| 780 |
+
children_types = [child.op_type for child in children]
|
| 781 |
+
if children_types.count("MatMul") == 3:
|
| 782 |
+
qkv.append([child.name for child in children if child.op_type == "MatMul"])
|
| 783 |
+
if not find_all:
|
| 784 |
+
break
|
| 785 |
+
return qkv
|
| 786 |
+
|
| 787 |
+
def find_ffn_matmul(self, attention_index, attention_matmul_list, block_len):
|
| 788 |
+
"""Find MatMul in FFN.
|
| 789 |
+
|
| 790 |
+
Args:
|
| 791 |
+
attention_index (list): index of Attention
|
| 792 |
+
attention_matmul_list (list): list of Attention and MatMul nodes
|
| 793 |
+
block_len (int): block length
|
| 794 |
+
|
| 795 |
+
Returns:
|
| 796 |
+
list: list of MatMul in FFN
|
| 797 |
+
"""
|
| 798 |
+
ffn_matmul = []
|
| 799 |
+
for idx in range(len(attention_index)):
|
| 800 |
+
if idx != len(attention_index) - 1:
|
| 801 |
+
index = attention_index[idx + 1]
|
| 802 |
+
if index - 2 >= 0:
|
| 803 |
+
ffn_matmul.append([attention_matmul_list[index - 2], attention_matmul_list[index - 1]])
|
| 804 |
+
else:
|
| 805 |
+
index = attention_index[idx]
|
| 806 |
+
if index + block_len - 1 < len(attention_matmul_list):
|
| 807 |
+
ffn_matmul.append(
|
| 808 |
+
[attention_matmul_list[index + block_len - 2], attention_matmul_list[index + block_len - 1]]
|
| 809 |
+
)
|
| 810 |
+
return ffn_matmul
|
| 811 |
+
|
| 812 |
+
def export(self, save_path, conf):
|
| 813 |
+
"""Export Qlinear to QDQ model."""
|
| 814 |
+
from neural_compressor.config import ONNXQlinear2QDQConfig # noqa: PLC0415
|
| 815 |
+
from neural_compressor.utils.export import onnx_qlinear_to_qdq # noqa: PLC0415
|
| 816 |
+
|
| 817 |
+
if isinstance(conf, ONNXQlinear2QDQConfig):
|
| 818 |
+
add_nodes, remove_nodes, inits = onnx_qlinear_to_qdq(self._model, self._input_name_to_nodes)
|
| 819 |
+
self.add_nodes(add_nodes)
|
| 820 |
+
self.remove_nodes(remove_nodes)
|
| 821 |
+
self.add_initializers(inits)
|
| 822 |
+
self.update()
|
| 823 |
+
self.remove_unused_nodes()
|
| 824 |
+
self.topological_sort()
|
| 825 |
+
self.save(save_path)
|
| 826 |
+
else:
|
| 827 |
+
logger.warning("Unsupported config for export, only ONNXQlinear2QDQConfig is supported!")
|
| 828 |
+
exit(0)
|
| 829 |
+
|
| 830 |
+
def add_tensors_to_outputs(self, tensor_names):
|
| 831 |
+
"""Add the tensors to the model outputs to gets their values.
|
| 832 |
+
|
| 833 |
+
Args:
|
| 834 |
+
tensor_names: The names of tensors to be dumped.
|
| 835 |
+
"""
|
| 836 |
+
added_outputs = []
|
| 837 |
+
for tensor in tensor_names:
|
| 838 |
+
if tensor not in self.output():
|
| 839 |
+
added_tensor = onnx.helper.ValueInfoProto()
|
| 840 |
+
added_tensor.name = tensor
|
| 841 |
+
added_outputs.append(added_tensor)
|
| 842 |
+
self._model.graph.output.extend(added_outputs) # pylint: disable=no-member
|
| 843 |
+
|
| 844 |
+
def remove_tensors_from_outputs(self, tensor_names):
|
| 845 |
+
"""Remove the tensors from the model outputs.
|
| 846 |
+
|
| 847 |
+
Args:
|
| 848 |
+
tensor_names: The names of tensors to be removed.
|
| 849 |
+
"""
|
| 850 |
+
removed_outputs = []
|
| 851 |
+
for tensor in tensor_names:
|
| 852 |
+
if tensor in self.output():
|
| 853 |
+
removed_outputs.append(self._model.graph.output[self.output().index(tensor)])
|
| 854 |
+
for output in removed_outputs:
|
| 855 |
+
self._model.graph.output.remove(output)
|
| 856 |
+
|
| 857 |
+
def match_first_parent(self, node, parent_op_type, output_name_to_node, exclude=None):
|
| 858 |
+
"""Find parent node based on constraints on op_type.
|
| 859 |
+
|
| 860 |
+
Args:
|
| 861 |
+
node (str): current node name.
|
| 862 |
+
parent_op_type (str): constraint of parent node op_type.
|
| 863 |
+
output_name_to_node (dict): dictionary with output name as key, and node as value.
|
| 864 |
+
exclude (list): list of nodes that are excluded (not allowed to match as parent).
|
| 865 |
+
|
| 866 |
+
Returns:
|
| 867 |
+
parent: The matched parent node. None if not found.
|
| 868 |
+
index: The input index of matched parent node. None if not found.
|
| 869 |
+
"""
|
| 870 |
+
if exclude is None:
|
| 871 |
+
exclude = []
|
| 872 |
+
for i, input in enumerate(node.input):
|
| 873 |
+
if input in output_name_to_node:
|
| 874 |
+
parent = output_name_to_node[input]
|
| 875 |
+
if parent.op_type == parent_op_type and parent not in exclude:
|
| 876 |
+
return parent, i
|
| 877 |
+
return None, None
|
| 878 |
+
|
| 879 |
+
def match_parent(
|
| 880 |
+
self,
|
| 881 |
+
node,
|
| 882 |
+
parent_op_type,
|
| 883 |
+
input_index=None,
|
| 884 |
+
output_name_to_node=None,
|
| 885 |
+
exclude=None,
|
| 886 |
+
return_indice=None,
|
| 887 |
+
):
|
| 888 |
+
"""Find parent node based on constraints on op_type and index.
|
| 889 |
+
|
| 890 |
+
Args:
|
| 891 |
+
node (str): current node name.
|
| 892 |
+
parent_op_type (str): constraint of parent node op_type.
|
| 893 |
+
input_index (int or None): only check the parent given input index of current node.
|
| 894 |
+
output_name_to_node (dict): dictionary with output name as key, and node as value.
|
| 895 |
+
exclude (list): list of nodes that are excluded (not allowed to match as parent).
|
| 896 |
+
return_indice (list): a list to append the input index when input_index is None.
|
| 897 |
+
|
| 898 |
+
Returns:
|
| 899 |
+
parent: The matched parent node.
|
| 900 |
+
"""
|
| 901 |
+
assert node is not None
|
| 902 |
+
assert input_index is None or input_index >= 0
|
| 903 |
+
if exclude is None:
|
| 904 |
+
exclude = []
|
| 905 |
+
if output_name_to_node is None:
|
| 906 |
+
output_name_to_node = self._output_name_to_node
|
| 907 |
+
|
| 908 |
+
if input_index is None:
|
| 909 |
+
parent, index = self.match_first_parent(node, parent_op_type, output_name_to_node, exclude)
|
| 910 |
+
if return_indice is not None:
|
| 911 |
+
return_indice.append(index)
|
| 912 |
+
return parent
|
| 913 |
+
|
| 914 |
+
if input_index >= len(node.input):
|
| 915 |
+
return None
|
| 916 |
+
|
| 917 |
+
parent = self.get_parent(node, input_index, output_name_to_node)
|
| 918 |
+
if parent is not None and parent.op_type == parent_op_type and parent not in exclude:
|
| 919 |
+
return parent
|
| 920 |
+
|
| 921 |
+
return None
|
| 922 |
+
|
| 923 |
+
def match_parent_path(
|
| 924 |
+
self,
|
| 925 |
+
node,
|
| 926 |
+
parent_op_types,
|
| 927 |
+
parent_input_index,
|
| 928 |
+
output_name_to_node=None,
|
| 929 |
+
return_indice=None,
|
| 930 |
+
):
|
| 931 |
+
"""Find a sequence of input edges based on constraints on parent op_type and index.
|
| 932 |
+
|
| 933 |
+
Args:
|
| 934 |
+
node (str): current node name.
|
| 935 |
+
parent_op_types (str): constraint of parent node op_type of each input edge.
|
| 936 |
+
parent_input_index (list): constraint of input index of each input edge.
|
| 937 |
+
None means no constraint.
|
| 938 |
+
output_name_to_node (dict): dictionary with output name as key, and node as value.
|
| 939 |
+
return_indice (list): a list to append the input index when there is
|
| 940 |
+
no constraint on input index of an edge.
|
| 941 |
+
|
| 942 |
+
Returns:
|
| 943 |
+
parents: a list of matched parent node.
|
| 944 |
+
"""
|
| 945 |
+
assert len(parent_input_index) == len(parent_op_types)
|
| 946 |
+
|
| 947 |
+
if output_name_to_node is None:
|
| 948 |
+
output_name_to_node = self._output_name_to_node
|
| 949 |
+
|
| 950 |
+
current_node = node
|
| 951 |
+
matched_parents = []
|
| 952 |
+
for i, op_type in enumerate(parent_op_types):
|
| 953 |
+
matched_parent = self.match_parent(
|
| 954 |
+
current_node,
|
| 955 |
+
op_type,
|
| 956 |
+
parent_input_index[i],
|
| 957 |
+
output_name_to_node,
|
| 958 |
+
exclude=[],
|
| 959 |
+
return_indice=return_indice,
|
| 960 |
+
)
|
| 961 |
+
if matched_parent is None:
|
| 962 |
+
return None
|
| 963 |
+
|
| 964 |
+
matched_parents.append(matched_parent)
|
| 965 |
+
current_node = matched_parent
|
| 966 |
+
|
| 967 |
+
return matched_parents
|
| 968 |
+
|
| 969 |
+
def is_smoothquant_model(self):
|
| 970 |
+
"""Check the model is smooth quantized or not.
|
| 971 |
+
|
| 972 |
+
Returns:
|
| 973 |
+
bool: the model is smooth quantized or not.
|
| 974 |
+
"""
|
| 975 |
+
for init in self.model.graph.initializer: # noqa: SIM110
|
| 976 |
+
if "_smooth_scale" in init.name:
|
| 977 |
+
return True
|
| 978 |
+
return False
|
| 979 |
+
|
| 980 |
+
def find_split_nodes(self):
|
| 981 |
+
"""Find split nodes for layer-wise quantization."""
|
| 982 |
+
split_nodes = self.find_split_node_for_layer_wise_quantization()
|
| 983 |
+
return split_nodes
|
| 984 |
+
|
| 985 |
+
def split_model_with_node(
|
| 986 |
+
self, split_node_name, path_of_model_to_split, shape_infer=True, save_both_split_models=True
|
| 987 |
+
):
|
| 988 |
+
"""Split model into two parts at a given node.
|
| 989 |
+
|
| 990 |
+
Args:
|
| 991 |
+
split_node_name (str): name of the node where the model is split at>
|
| 992 |
+
path_of_model_to_split (str): path of model to be split.
|
| 993 |
+
shape_infer (bool): do shape inference. Default is True.
|
| 994 |
+
save_both_split_models (bool): whether to save the two split models.
|
| 995 |
+
False means only save the first split model.
|
| 996 |
+
True means save both the two split models.
|
| 997 |
+
Default id True.
|
| 998 |
+
|
| 999 |
+
Returns:
|
| 1000 |
+
tuple: the first split model, the second split model
|
| 1001 |
+
"""
|
| 1002 |
+
# origin model : ... -> node_1 -> split_node -> node_2 -> ...
|
| 1003 |
+
# split model 1: ... -> node_1 -> split_node
|
| 1004 |
+
# split model 2: node_2 -> ...
|
| 1005 |
+
|
| 1006 |
+
split_model_part_1 = onnx.ModelProto()
|
| 1007 |
+
split_model_part_1.CopyFrom(self._model)
|
| 1008 |
+
split_model_part_1.graph.ClearField("node")
|
| 1009 |
+
|
| 1010 |
+
split_model_part_2 = onnx.ModelProto()
|
| 1011 |
+
split_model_part_2.CopyFrom(self._model)
|
| 1012 |
+
split_model_part_2.graph.ClearField("node")
|
| 1013 |
+
|
| 1014 |
+
split_node_output = None
|
| 1015 |
+
part_idx = 1
|
| 1016 |
+
for node in self._model.graph.node:
|
| 1017 |
+
if part_idx == 1:
|
| 1018 |
+
split_model_part_1.graph.node.append(node)
|
| 1019 |
+
elif part_idx == 2:
|
| 1020 |
+
split_model_part_2.graph.node.append(node)
|
| 1021 |
+
|
| 1022 |
+
if node.name == split_node_name:
|
| 1023 |
+
split_node_output = node.output
|
| 1024 |
+
part_idx = 2
|
| 1025 |
+
|
| 1026 |
+
assert len(split_node_output) == 1, (
|
| 1027 |
+
f"Only support split at node with 1 output tensor, while current split node {split_node_name} has {len(split_node_output)} output tensors"
|
| 1028 |
+
)
|
| 1029 |
+
split_tensor_name = split_node_output[0]
|
| 1030 |
+
|
| 1031 |
+
# infer shape of the model to be split
|
| 1032 |
+
if shape_infer:
|
| 1033 |
+
try:
|
| 1034 |
+
from neural_compressor.adaptor.ox_utils.util import infer_shapes # noqa: PLC0415
|
| 1035 |
+
|
| 1036 |
+
self._model = infer_shapes(self._model, auto_merge=True, base_dir=os.path.dirname(self._model_path))
|
| 1037 |
+
except Exception as e: # pragma: no cover
|
| 1038 |
+
logger.error(
|
| 1039 |
+
"Shape infer fails for layer-wise quantization. "
|
| 1040 |
+
"We would recommend checking the graph optimization level of your model "
|
| 1041 |
+
"and setting it to 'DISABLE_ALL' or 'ENABLE_BASIC', "
|
| 1042 |
+
"as this may help avoid this error."
|
| 1043 |
+
)
|
| 1044 |
+
raise e
|
| 1045 |
+
|
| 1046 |
+
split_tensor_type, split_tensor_shape = self._get_output_type_shape_by_tensor_name(split_tensor_name)
|
| 1047 |
+
split_tensor = onnx.helper.make_tensor_value_info(split_tensor_name, split_tensor_type, split_tensor_shape)
|
| 1048 |
+
|
| 1049 |
+
split_model_part_1 = ONNXModel(split_model_part_1, ignore_warning=True)
|
| 1050 |
+
split_model_part_2 = ONNXModel(split_model_part_2, ignore_warning=True)
|
| 1051 |
+
|
| 1052 |
+
# remove unused input & output
|
| 1053 |
+
split_model_part_1._remove_unused_input_output()
|
| 1054 |
+
split_model_part_2._remove_unused_input_output()
|
| 1055 |
+
|
| 1056 |
+
split_model_part_1.model.graph.output.append(split_tensor)
|
| 1057 |
+
split_model_part_2.model.graph.input.append(split_tensor)
|
| 1058 |
+
|
| 1059 |
+
insert_output_for_model_1 = []
|
| 1060 |
+
insert_input_for_model_2 = []
|
| 1061 |
+
for output in split_model_part_1.output_name_to_node:
|
| 1062 |
+
if output in split_model_part_2.input_name_to_nodes:
|
| 1063 |
+
output_type, output_shape = self._get_output_type_shape_by_tensor_name(output)
|
| 1064 |
+
output_tensor = onnx.helper.make_tensor_value_info(output, output_type, output_shape)
|
| 1065 |
+
if output_tensor not in split_model_part_1.model.graph.output:
|
| 1066 |
+
insert_output_for_model_1.append(output_tensor)
|
| 1067 |
+
if output_tensor not in split_model_part_2.model.graph.input:
|
| 1068 |
+
insert_input_for_model_2.append(output_tensor)
|
| 1069 |
+
|
| 1070 |
+
# insert model 1 output
|
| 1071 |
+
for output in insert_output_for_model_1:
|
| 1072 |
+
split_model_part_1.model.graph.output.append(output)
|
| 1073 |
+
|
| 1074 |
+
# insert model 2 input
|
| 1075 |
+
for input in insert_input_for_model_2:
|
| 1076 |
+
split_model_part_2.model.graph.input.append(input)
|
| 1077 |
+
|
| 1078 |
+
# remove unused init
|
| 1079 |
+
split_model_part_1.remove_unused_init()
|
| 1080 |
+
split_model_part_2.remove_unused_init()
|
| 1081 |
+
|
| 1082 |
+
split_model_part_1.update()
|
| 1083 |
+
split_model_part_2.update()
|
| 1084 |
+
|
| 1085 |
+
dir_of_model_to_split = os.path.dirname(path_of_model_to_split)
|
| 1086 |
+
|
| 1087 |
+
split_model_part_1.load_model_initializer_by_tensor(dir_of_model_to_split)
|
| 1088 |
+
split_model_part_1_path = os.path.join(dir_of_model_to_split, "split_model_part_1.onnx")
|
| 1089 |
+
split_model_part_1.model_path = split_model_part_1_path
|
| 1090 |
+
split_model_part_1._save_split_model(split_model_part_1_path)
|
| 1091 |
+
split_model_part_1.check_is_large_model()
|
| 1092 |
+
logger.debug(f"save split model part 1 to {split_model_part_1_path} for layer wise quantization")
|
| 1093 |
+
|
| 1094 |
+
if save_both_split_models:
|
| 1095 |
+
split_model_part_2.load_model_initializer_by_tensor(dir_of_model_to_split)
|
| 1096 |
+
split_model_part_2_path = os.path.join(dir_of_model_to_split, "split_model_part_2.onnx")
|
| 1097 |
+
split_model_part_2.model_path = split_model_part_2_path
|
| 1098 |
+
split_model_part_2._save_split_model(split_model_part_2_path)
|
| 1099 |
+
split_model_part_2.check_is_large_model()
|
| 1100 |
+
logger.debug(f"save split model part 2 to {split_model_part_2_path} for layer wise quantization")
|
| 1101 |
+
return split_model_part_1, split_model_part_2
|
| 1102 |
+
else:
|
| 1103 |
+
return split_model_part_1, split_model_part_2
|
| 1104 |
+
|
| 1105 |
+
def _save_split_model(self, save_path):
|
| 1106 |
+
"""Save split model as external data for layer wise quantization.
|
| 1107 |
+
|
| 1108 |
+
Args:
|
| 1109 |
+
save_path (str): the path to save the split model
|
| 1110 |
+
"""
|
| 1111 |
+
if os.path.exists(save_path + "_data"):
|
| 1112 |
+
os.remove(save_path + "_data")
|
| 1113 |
+
onnx.save_model(
|
| 1114 |
+
self._model,
|
| 1115 |
+
save_path,
|
| 1116 |
+
save_as_external_data=True,
|
| 1117 |
+
all_tensors_to_one_file=True,
|
| 1118 |
+
location=save_path.split("/")[-1] + "_data",
|
| 1119 |
+
size_threshold=1024,
|
| 1120 |
+
convert_attribute=False,
|
| 1121 |
+
)
|
| 1122 |
+
|
| 1123 |
+
def _get_output_type_shape_by_tensor_name(self, tensor_name):
|
| 1124 |
+
"""Get output type and shape with a tensor name.
|
| 1125 |
+
|
| 1126 |
+
Args:
|
| 1127 |
+
tensor_name (str): name of a tensor
|
| 1128 |
+
|
| 1129 |
+
Returns:
|
| 1130 |
+
tuple: output type and shape
|
| 1131 |
+
"""
|
| 1132 |
+
elem_type = onnx.TensorProto.FLOAT
|
| 1133 |
+
shape = None
|
| 1134 |
+
for output in self._model.graph.value_info:
|
| 1135 |
+
if output.name == tensor_name:
|
| 1136 |
+
elem_type = output.type.tensor_type.elem_type
|
| 1137 |
+
shape = [
|
| 1138 |
+
dim.dim_value if dim.HasField("dim_value") else -1 for dim in output.type.tensor_type.shape.dim
|
| 1139 |
+
]
|
| 1140 |
+
break
|
| 1141 |
+
return elem_type, shape
|
| 1142 |
+
|
| 1143 |
+
def _remove_unused_input_output(self):
|
| 1144 |
+
"""Remove unused input & output for split model."""
|
| 1145 |
+
remove_outputs = []
|
| 1146 |
+
remove_inputs = []
|
| 1147 |
+
for output in self._model.graph.output:
|
| 1148 |
+
if output.name not in self.output_name_to_node:
|
| 1149 |
+
remove_outputs.append(output)
|
| 1150 |
+
|
| 1151 |
+
for input in self._model.graph.input:
|
| 1152 |
+
if input.name not in self.input_name_to_nodes:
|
| 1153 |
+
remove_inputs.append(input)
|
| 1154 |
+
|
| 1155 |
+
for output in remove_outputs:
|
| 1156 |
+
self._model.graph.output.remove(output)
|
| 1157 |
+
for input in remove_inputs:
|
| 1158 |
+
self._model.graph.input.remove(input)
|
| 1159 |
+
|
| 1160 |
+
def remove_unused_init(self):
|
| 1161 |
+
"""Remove unused init."""
|
| 1162 |
+
remov_inits = []
|
| 1163 |
+
for init in self._model.graph.initializer:
|
| 1164 |
+
if init.name not in self.input_name_to_nodes:
|
| 1165 |
+
remov_inits.append(init)
|
| 1166 |
+
self.remove_initializers(remov_inits)
|
| 1167 |
+
|
| 1168 |
+
def load_model_initializer_by_tensor(self, data_path=None):
|
| 1169 |
+
"""Load model initializer by tensor.
|
| 1170 |
+
|
| 1171 |
+
Args:
|
| 1172 |
+
data_path (str, optional): the directory of saved initializer. Defaults to None.
|
| 1173 |
+
"""
|
| 1174 |
+
if data_path is None:
|
| 1175 |
+
data_path = os.path.dirname(self._model_path)
|
| 1176 |
+
for init in self._model.graph.initializer:
|
| 1177 |
+
if init.HasField("data_location") and init.data_location == onnx.TensorProto.EXTERNAL:
|
| 1178 |
+
onnx.external_data_helper.load_external_data_for_tensor(init, data_path)
|
| 1179 |
+
|
| 1180 |
+
def write_external_data_to_new_location(self, external_data_location="external.data", overwrite=False):
|
| 1181 |
+
"""Write external data of merged quantized model to new location to save memory.
|
| 1182 |
+
|
| 1183 |
+
Args:
|
| 1184 |
+
external_data_location (str, optional): external data location of merged quantized model.
|
| 1185 |
+
Defaults to "external.data".
|
| 1186 |
+
overwrite (bool, optional): if True, remove existed externa data. Defaults to False.
|
| 1187 |
+
"""
|
| 1188 |
+
if overwrite and os.path.exists(os.path.join(os.path.dirname(self._model_path), external_data_location)):
|
| 1189 |
+
os.remove(os.path.join(os.path.dirname(self._model_path), external_data_location))
|
| 1190 |
+
self.load_model_initializer_by_tensor()
|
| 1191 |
+
onnx.external_data_helper.convert_model_to_external_data(self._model, location=external_data_location)
|
| 1192 |
+
# TODO : if init is already saved, skip write it
|
| 1193 |
+
onnx.external_data_helper.write_external_data_tensors(self._model, filepath=os.path.dirname(self._model_path))
|
| 1194 |
+
|
| 1195 |
+
def merge_split_models(self, to_merge_model):
|
| 1196 |
+
"""Merge two split model into final model."""
|
| 1197 |
+
to_merge_model.write_external_data_to_new_location()
|
| 1198 |
+
self.add_nodes(list(to_merge_model.nodes()))
|
| 1199 |
+
self.add_initializers(list(to_merge_model.initializer()))
|
| 1200 |
+
self.update()
|
| 1201 |
+
|
| 1202 |
+
# add new output
|
| 1203 |
+
for output in to_merge_model.graph().output:
|
| 1204 |
+
if output.name not in self.output():
|
| 1205 |
+
self._model.graph.output.append(output)
|
| 1206 |
+
|
| 1207 |
+
# remove unused output
|
| 1208 |
+
remove_output = []
|
| 1209 |
+
for output in self._model.graph.output:
|
| 1210 |
+
if output.name in to_merge_model.input():
|
| 1211 |
+
remove_output.append(output)
|
| 1212 |
+
for output in remove_output:
|
| 1213 |
+
self._model.graph.output.remove(output)
|
| 1214 |
+
|
| 1215 |
+
# add new input
|
| 1216 |
+
for input in to_merge_model.graph().input:
|
| 1217 |
+
if (
|
| 1218 |
+
input.name not in self.input()
|
| 1219 |
+
and input.name not in self.output()
|
| 1220 |
+
and input.name not in self.output_name_to_node
|
| 1221 |
+
):
|
| 1222 |
+
self._model.graph.input.append(input)
|
| 1223 |
+
|
| 1224 |
+
def re_org_output(self, origin_output):
|
| 1225 |
+
"""Re-org output of merged model for layer-wise quantization."""
|
| 1226 |
+
outputs = {}
|
| 1227 |
+
tmp_remove = []
|
| 1228 |
+
for output in self._model.graph.output:
|
| 1229 |
+
outputs[output.name] = output
|
| 1230 |
+
tmp_remove.append(output)
|
| 1231 |
+
|
| 1232 |
+
for output in tmp_remove:
|
| 1233 |
+
self._model.graph.output.remove(output)
|
| 1234 |
+
|
| 1235 |
+
for out_name in origin_output:
|
| 1236 |
+
self._model.graph.output.append(outputs[out_name])
|
micromamba_root/envs/pytorch_env/Lib/site-packages/onnxruntime/quantization/neural_compressor/util.py
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#
|
| 2 |
+
# The implementation of this file is based on:
|
| 3 |
+
# https://github.com/intel/neural-compressor/tree/master/neural_compressor
|
| 4 |
+
#
|
| 5 |
+
# Copyright (c) 2023 Intel Corporation
|
| 6 |
+
#
|
| 7 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 8 |
+
# you may not use this file except in compliance with the License.
|
| 9 |
+
# You may obtain a copy of the License at
|
| 10 |
+
#
|
| 11 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 12 |
+
#
|
| 13 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 14 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 15 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 16 |
+
# See the License for the specific language governing permissions and
|
| 17 |
+
# limitations under the License.
|
| 18 |
+
|
| 19 |
+
"""Helper classes or functions for onnxrt adaptor."""
|
| 20 |
+
|
| 21 |
+
import importlib
|
| 22 |
+
import logging
|
| 23 |
+
|
| 24 |
+
import numpy as np
|
| 25 |
+
|
| 26 |
+
logger = logging.getLogger("neural_compressor")
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
MAXIMUM_PROTOBUF = 2147483648
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def simple_progress_bar(total, i):
|
| 33 |
+
"""Progress bar for cases where tqdm can't be used."""
|
| 34 |
+
progress = i / total
|
| 35 |
+
bar_length = 20
|
| 36 |
+
bar = "#" * int(bar_length * progress)
|
| 37 |
+
spaces = " " * (bar_length - len(bar))
|
| 38 |
+
percentage = progress * 100
|
| 39 |
+
print(f"\rProgress: [{bar}{spaces}] {percentage:.2f}%", end="")
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def find_by_name(name, item_list):
|
| 43 |
+
"""Helper function to find item by name in a list."""
|
| 44 |
+
items = []
|
| 45 |
+
for item in item_list:
|
| 46 |
+
assert hasattr(item, "name"), f"{item} should have a 'name' attribute defined" # pragma: no cover
|
| 47 |
+
if item.name == name:
|
| 48 |
+
items.append(item)
|
| 49 |
+
if len(items) > 0:
|
| 50 |
+
return items[0]
|
| 51 |
+
else:
|
| 52 |
+
return None
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def to_numpy(data):
|
| 56 |
+
"""Convert to numpy ndarrays."""
|
| 57 |
+
import torch # noqa: PLC0415
|
| 58 |
+
|
| 59 |
+
if not isinstance(data, np.ndarray):
|
| 60 |
+
if not importlib.util.find_spec("torch"):
|
| 61 |
+
logger.error(
|
| 62 |
+
"Please install torch to enable subsequent data type check and conversion, "
|
| 63 |
+
"or reorganize your data format to numpy array."
|
| 64 |
+
)
|
| 65 |
+
exit(0)
|
| 66 |
+
if isinstance(data, torch.Tensor):
|
| 67 |
+
if data.dtype is torch.bfloat16: # pragma: no cover
|
| 68 |
+
return data.detach().cpu().to(torch.float32).numpy()
|
| 69 |
+
if data.dtype is torch.chalf: # pragma: no cover
|
| 70 |
+
return data.detach().cpu().to(torch.cfloat).numpy()
|
| 71 |
+
return data.detach().cpu().numpy()
|
| 72 |
+
else:
|
| 73 |
+
try:
|
| 74 |
+
return np.array(data)
|
| 75 |
+
except Exception:
|
| 76 |
+
assert False, ( # noqa: B011
|
| 77 |
+
f"The input data for onnx model is {type(data)}, which is not supported to convert to numpy ndarrays."
|
| 78 |
+
)
|
| 79 |
+
else:
|
| 80 |
+
return data
|
micromamba_root/envs/pytorch_env/Lib/site-packages/onnxruntime/quantization/neural_compressor/weight_only.py
ADDED
|
@@ -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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#
|
| 2 |
+
# The implementation of this file is based on:
|
| 3 |
+
# https://github.com/intel/neural-compressor/tree/master/neural_compressor
|
| 4 |
+
#
|
| 5 |
+
# Copyright (c) 2023 Intel Corporation
|
| 6 |
+
#
|
| 7 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 8 |
+
# you may not use this file except in compliance with the License.
|
| 9 |
+
# You may obtain a copy of the License at
|
| 10 |
+
#
|
| 11 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 12 |
+
#
|
| 13 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 14 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 15 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 16 |
+
# See the License for the specific language governing permissions and
|
| 17 |
+
# limitations under the License.
|
| 18 |
+
#
|
| 19 |
+
# Modifications:
|
| 20 |
+
# Add k-quant quantization method.
|
| 21 |
+
# Copyright (c) Microsoft Corporation. All rights reserved.
|
| 22 |
+
# Licensed under the MIT License.
|
| 23 |
+
|
| 24 |
+
"""WeightOnly for onnxrt adaptor."""
|
| 25 |
+
|
| 26 |
+
import copy
|
| 27 |
+
import logging
|
| 28 |
+
import os
|
| 29 |
+
import sys
|
| 30 |
+
|
| 31 |
+
import numpy as np
|
| 32 |
+
import onnx
|
| 33 |
+
from onnx import numpy_helper
|
| 34 |
+
from onnx.helper import np_dtype_to_tensor_dtype
|
| 35 |
+
|
| 36 |
+
import onnxruntime as ort
|
| 37 |
+
|
| 38 |
+
from .onnx_model import ONNXModel
|
| 39 |
+
from .util import simple_progress_bar
|
| 40 |
+
|
| 41 |
+
logger = logging.getLogger("neural_compressor")
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def make_matmul_weight_only_node(
|
| 45 |
+
node,
|
| 46 |
+
weight_shape,
|
| 47 |
+
num_bits,
|
| 48 |
+
group_size,
|
| 49 |
+
k_blocks,
|
| 50 |
+
q_weight,
|
| 51 |
+
scale,
|
| 52 |
+
zero_point,
|
| 53 |
+
accuracy_level=0,
|
| 54 |
+
): # pragma: no cover
|
| 55 |
+
"""Build MatMulNBits node.
|
| 56 |
+
|
| 57 |
+
Args:
|
| 58 |
+
node: original matmul node
|
| 59 |
+
weight_shape: original weight shape
|
| 60 |
+
num_bits (int): num_bits
|
| 61 |
+
group_size (int): how many elements share one scale/zp
|
| 62 |
+
k_blocks (int): block number
|
| 63 |
+
q_weight (array): quantized weight
|
| 64 |
+
scale (array): scale
|
| 65 |
+
zero_point (array): zero point
|
| 66 |
+
accuracy_level (int): accuracy level. Support 0 (unset), 1(fp32), 2(fp16), 3(bf16), or 4(int8).
|
| 67 |
+
|
| 68 |
+
Returns:
|
| 69 |
+
matmul_weight_only_node: MatMulNBits node
|
| 70 |
+
new_inits: initializers of the new node
|
| 71 |
+
"""
|
| 72 |
+
blob_size = group_size * num_bits // 8
|
| 73 |
+
packed = np.zeros((q_weight.shape[0], blob_size), dtype="uint8")
|
| 74 |
+
q_weight_name = node.input[1] + f"_Q{num_bits!s}G{group_size!s}"
|
| 75 |
+
input_names = [node.input[0], q_weight_name]
|
| 76 |
+
new_inits = []
|
| 77 |
+
kwargs = {}
|
| 78 |
+
|
| 79 |
+
op_type = "MatMulNBits"
|
| 80 |
+
|
| 81 |
+
# pack quantized weight
|
| 82 |
+
if num_bits == 4:
|
| 83 |
+
q_weight_pairs = q_weight[:, ::2] | q_weight[:, 1::2] << 4
|
| 84 |
+
packed[:, :] = q_weight_pairs[:, :blob_size]
|
| 85 |
+
elif num_bits == 8:
|
| 86 |
+
packed = q_weight
|
| 87 |
+
else:
|
| 88 |
+
logger.error(f"MatMulNBits does not have kernel support for num_bits = {num_bits}.")
|
| 89 |
+
|
| 90 |
+
packed = np.reshape(packed, (-1, k_blocks, blob_size))
|
| 91 |
+
|
| 92 |
+
# build scale tensor
|
| 93 |
+
scale = np.reshape(scale, (-1, k_blocks))
|
| 94 |
+
assert scale.dtype == np.float32 or scale.dtype == np.float16
|
| 95 |
+
scale_tensor = onnx.helper.make_tensor(
|
| 96 |
+
name=node.input[1] + "_scale",
|
| 97 |
+
data_type=np_dtype_to_tensor_dtype(scale.dtype),
|
| 98 |
+
dims=scale.shape,
|
| 99 |
+
vals=scale.tobytes(),
|
| 100 |
+
raw=True,
|
| 101 |
+
)
|
| 102 |
+
input_names.append(scale_tensor.name)
|
| 103 |
+
new_inits.append(scale_tensor)
|
| 104 |
+
|
| 105 |
+
# build zero_point tensor
|
| 106 |
+
if zero_point is not None:
|
| 107 |
+
if num_bits == 8:
|
| 108 |
+
packed_zp = zero_point.astype("uint8")
|
| 109 |
+
elif num_bits == 4:
|
| 110 |
+
# For 4-bit case, the default zeros is 0x8. So it is 0x88 = 136 if we fill lower/higher 4 bits with 0x8.
|
| 111 |
+
packed_zp = np.full((zero_point.shape[0] + 1) // 2, 136, dtype="uint8")
|
| 112 |
+
# create an index array
|
| 113 |
+
idx = np.arange(zero_point.shape[0] // k_blocks * k_blocks).reshape(-1)
|
| 114 |
+
# separate odd and even indices
|
| 115 |
+
even_idx = idx[::2]
|
| 116 |
+
odd_idx = idx[1::2]
|
| 117 |
+
# vectorized operation for even and odd indices
|
| 118 |
+
packed_zp[even_idx // 2] = (packed_zp[even_idx // 2] & 0xF0) | zero_point[even_idx].ravel()
|
| 119 |
+
packed_zp[odd_idx // 2] = (packed_zp[odd_idx // 2] & 0x0F) | (zero_point[odd_idx].ravel() << 4)
|
| 120 |
+
else:
|
| 121 |
+
raise ValueError(f"MatMulNBits does not have kernel support for num_bits = {num_bits}.")
|
| 122 |
+
|
| 123 |
+
packed_zp = np.reshape(packed_zp, (weight_shape[1], -1))
|
| 124 |
+
zp_tensor = onnx.helper.make_tensor(
|
| 125 |
+
name=node.input[1] + "_zp", data_type=2, dims=packed_zp.shape, vals=packed_zp.tobytes(), raw=True
|
| 126 |
+
)
|
| 127 |
+
input_names.append(zp_tensor.name)
|
| 128 |
+
new_inits.append(zp_tensor)
|
| 129 |
+
|
| 130 |
+
# set kwargs
|
| 131 |
+
kwargs["K"] = weight_shape[0]
|
| 132 |
+
kwargs["N"] = weight_shape[1]
|
| 133 |
+
kwargs["bits"] = num_bits
|
| 134 |
+
kwargs["block_size"] = group_size
|
| 135 |
+
if accuracy_level > 0:
|
| 136 |
+
# require onnxruntime > 1.16.3
|
| 137 |
+
kwargs["accuracy_level"] = accuracy_level
|
| 138 |
+
|
| 139 |
+
q_weight_tensor = onnx.helper.make_tensor(
|
| 140 |
+
name=q_weight_name,
|
| 141 |
+
data_type=2,
|
| 142 |
+
dims=packed.shape,
|
| 143 |
+
vals=packed.tobytes(),
|
| 144 |
+
raw=True,
|
| 145 |
+
)
|
| 146 |
+
new_inits.append(q_weight_tensor)
|
| 147 |
+
|
| 148 |
+
matmul_weight_only_node = onnx.helper.make_node(
|
| 149 |
+
op_type,
|
| 150 |
+
inputs=input_names,
|
| 151 |
+
outputs=node.output,
|
| 152 |
+
name=node.name + "_Q" + str(num_bits) if node.name else "_Q" + str(num_bits),
|
| 153 |
+
domain="com.microsoft",
|
| 154 |
+
**kwargs,
|
| 155 |
+
)
|
| 156 |
+
return matmul_weight_only_node, new_inits
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
def quant_tensor(data, num_bits=4, group_size=32, scheme="asym", dtype="int", ratio=1.0):
|
| 160 |
+
"""Quantize tensor per group.
|
| 161 |
+
|
| 162 |
+
Args:
|
| 163 |
+
data : input weight
|
| 164 |
+
num_bits (int, optional): num_bits. Defaults to 4.
|
| 165 |
+
group_size (int, optional): how many elements share one scale/zp. Defaults to 4.
|
| 166 |
+
scheme (str, optional): quantization scheme. Defaults to "asym".
|
| 167 |
+
dtype (str, optional): data type. Defaults to "int".
|
| 168 |
+
ratio (float, optional): percentile of clip. Defaults to 1.0.
|
| 169 |
+
|
| 170 |
+
Returns:
|
| 171 |
+
output: quantized weight
|
| 172 |
+
scale: scale
|
| 173 |
+
zero_point: zero point
|
| 174 |
+
"""
|
| 175 |
+
data = np.reshape(data, (-1, group_size))
|
| 176 |
+
if scheme == "asym" or dtype == "uint":
|
| 177 |
+
maxq = 2**num_bits - 1
|
| 178 |
+
minq = 0
|
| 179 |
+
elif scheme == "sym":
|
| 180 |
+
maxq = 2 ** (num_bits - 1) - 1 if num_bits != 1 else 0
|
| 181 |
+
minq = -(2 ** (num_bits - 1)) if num_bits != 1 else -1
|
| 182 |
+
|
| 183 |
+
rmin = np.min(data, axis=1, keepdims=True) * ratio
|
| 184 |
+
rmax = np.max(data, axis=1, keepdims=True) * ratio
|
| 185 |
+
if scheme == "sym":
|
| 186 |
+
max_range = np.maximum(np.abs(rmin), np.abs(rmax))
|
| 187 |
+
scale = np.ones(rmax.shape)
|
| 188 |
+
mask = max_range > 0
|
| 189 |
+
scale[mask] = (max_range[mask] * 2.0).astype(np.float64) / (maxq - minq)
|
| 190 |
+
zero_point = (
|
| 191 |
+
np.zeros(scale.shape) if dtype == "int" else np.ones(rmax.shape, dtype="uint8") * (1 << (num_bits - 1))
|
| 192 |
+
)
|
| 193 |
+
else:
|
| 194 |
+
scale = np.ones(rmax.shape)
|
| 195 |
+
scale[rmin != rmax] = np.array(
|
| 196 |
+
[float(i) / (maxq - minq) for i in (rmax - rmin)[rmin != rmax].flatten().tolist()]
|
| 197 |
+
)
|
| 198 |
+
zero_point = (
|
| 199 |
+
((np.zeros(scale.shape) - rmin) / scale).round()
|
| 200 |
+
if dtype == "int"
|
| 201 |
+
else np.maximum(0, np.minimum(maxq, ((np.zeros(scale.shape) - rmin) / scale).round())).astype("uint8")
|
| 202 |
+
)
|
| 203 |
+
|
| 204 |
+
q_weight = np.empty_like(data, dtype=scale.dtype)
|
| 205 |
+
np.divide(data, scale, out=q_weight)
|
| 206 |
+
np.add(q_weight, zero_point, out=q_weight)
|
| 207 |
+
np.round(q_weight, out=q_weight)
|
| 208 |
+
np.clip(q_weight, minq, maxq, out=q_weight)
|
| 209 |
+
|
| 210 |
+
return q_weight, scale, zero_point
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
def quant_tensor_k_quant_cpu(data, num_bits=4, group_size=32):
|
| 214 |
+
"""Quantize tensor per group based on k quant.
|
| 215 |
+
|
| 216 |
+
Ref: https://github.com/ggml-org/llama.cpp/blob/64eda5deb9859e87a020e56bab5d2f9ca956f1de/ggml/src/ggml-quants.c
|
| 217 |
+
|
| 218 |
+
Args:
|
| 219 |
+
data : input weight
|
| 220 |
+
num_bits (int, optional): num_bits. Defaults to 4.
|
| 221 |
+
group_size (int, optional): how many elements share one scale/zp. Defaults to 32.
|
| 222 |
+
|
| 223 |
+
Returns:
|
| 224 |
+
output: quantized weight
|
| 225 |
+
scale: scale
|
| 226 |
+
zero_point: zero point
|
| 227 |
+
"""
|
| 228 |
+
data = np.reshape(data, (-1, group_size)).astype(np.float32) # nb = data.shape[0], (nb, group_size)
|
| 229 |
+
maxq = 2**num_bits - 1
|
| 230 |
+
minq = 0
|
| 231 |
+
sum_x2 = np.sum(data**2, axis=1, keepdims=True) # (nb, 1)
|
| 232 |
+
av_x = np.sqrt(sum_x2 / group_size) # (nb, 1)
|
| 233 |
+
weights = np.add(av_x, np.abs(data)) # (nb, group_size)
|
| 234 |
+
rmin = np.min(data, axis=1, keepdims=True) # (nb, 1)
|
| 235 |
+
rmax = np.max(data, axis=1, keepdims=True) # (nb, 1)
|
| 236 |
+
sum_w = np.sum(weights, axis=1, keepdims=True) # (nb, 1)
|
| 237 |
+
sum_x = np.sum(weights * data, axis=1, keepdims=True) # (nb, group_size)
|
| 238 |
+
iscale = np.ones(rmax.shape, dtype=data.dtype) # (nb, 1)
|
| 239 |
+
mask = rmin != rmax
|
| 240 |
+
iscale[mask] = (maxq - minq) / (rmax[mask] - rmin[mask])
|
| 241 |
+
scale = 1 / iscale
|
| 242 |
+
quant_data = np.clip(np.round(iscale * (data - rmin)), minq, maxq) # (nb, group_size)
|
| 243 |
+
diff = scale * quant_data + rmin - data # (nb, group_size)
|
| 244 |
+
best_mad = np.sum(weights * diff**2, axis=1, keepdims=True) # (nb, 1)
|
| 245 |
+
nstep = 20
|
| 246 |
+
rdelta = 0.1
|
| 247 |
+
# nstep * rdelta = -2 * rrmin, maxq - minq = 2**num_bits - 1
|
| 248 |
+
rrmin = -1
|
| 249 |
+
for is_ in range(nstep):
|
| 250 |
+
iscale_new = np.ones(rmax.shape, dtype=data.dtype) # (nb, 1)
|
| 251 |
+
factor = np.array([rrmin + rdelta * is_ + maxq - minq]).astype(data.dtype)[0]
|
| 252 |
+
mask = rmin != rmax
|
| 253 |
+
iscale_new[mask] = factor / (rmax[mask] - rmin[mask])
|
| 254 |
+
quant_data_new = np.clip(np.round(iscale_new * (data - rmin)), minq, maxq) # (nb, group_size)
|
| 255 |
+
mul_weights_quant_data_new = weights * quant_data_new
|
| 256 |
+
sum_l = np.sum(mul_weights_quant_data_new, axis=1, keepdims=True) # (nb, 1)
|
| 257 |
+
sum_l2 = np.sum(mul_weights_quant_data_new * quant_data_new, axis=1, keepdims=True) # (nb, 1)
|
| 258 |
+
sum_xl = np.sum(mul_weights_quant_data_new * data, axis=1, keepdims=True) # (nb, 1)
|
| 259 |
+
D = np.subtract(sum_w * sum_l2, sum_l**2) # noqa: N806
|
| 260 |
+
|
| 261 |
+
this_scale = (sum_w * sum_xl - sum_x * sum_l) / D # (nb, 1)
|
| 262 |
+
this_min = (sum_l2 * sum_x - sum_l * sum_xl) / D # (nb, 1)
|
| 263 |
+
|
| 264 |
+
diff = this_scale * quant_data_new + this_min - data # (nb, group_size)
|
| 265 |
+
mad = np.sum(weights * diff**2, axis=1, keepdims=True) # (nb, 1)
|
| 266 |
+
|
| 267 |
+
mad_1 = np.array(mad)
|
| 268 |
+
best_mad_1 = np.array(best_mad)
|
| 269 |
+
idx_to_replace = np.where(mad_1 < best_mad_1)[0]
|
| 270 |
+
quant_data[idx_to_replace, :] = quant_data_new[idx_to_replace, :]
|
| 271 |
+
best_mad[idx_to_replace] = mad[idx_to_replace]
|
| 272 |
+
scale[idx_to_replace] = this_scale[idx_to_replace]
|
| 273 |
+
rmin[idx_to_replace] = this_min[idx_to_replace]
|
| 274 |
+
|
| 275 |
+
zero_point = np.clip(((-rmin) / scale).round(), 0, maxq).astype("uint8")
|
| 276 |
+
scale = scale.astype(np.float64)
|
| 277 |
+
q_weight = np.empty_like(data, dtype=scale.dtype)
|
| 278 |
+
np.divide(data, scale, out=q_weight)
|
| 279 |
+
np.add(q_weight, zero_point, out=q_weight)
|
| 280 |
+
np.round(q_weight, out=q_weight)
|
| 281 |
+
np.clip(q_weight, minq, maxq, out=q_weight)
|
| 282 |
+
|
| 283 |
+
return q_weight, scale, zero_point
|
| 284 |
+
|
| 285 |
+
|
| 286 |
+
def quant_tensor_k_quant_cuda(data, num_bits=4, group_size=32):
|
| 287 |
+
"""Quantize tensor per group based on k quant.
|
| 288 |
+
|
| 289 |
+
Ref: https://github.com/ggml-org/llama.cpp/blob/64eda5deb9859e87a020e56bab5d2f9ca956f1de/ggml/src/ggml-quants.c
|
| 290 |
+
|
| 291 |
+
Args:
|
| 292 |
+
data : input weight
|
| 293 |
+
num_bits (int, optional): num_bits. Defaults to 4.
|
| 294 |
+
group_size (int, optional): how many elements share one scale/zp. Defaults to 4.
|
| 295 |
+
|
| 296 |
+
Returns:
|
| 297 |
+
output: quantized weight
|
| 298 |
+
scale: scale
|
| 299 |
+
zero_point: zero point
|
| 300 |
+
"""
|
| 301 |
+
try:
|
| 302 |
+
import cupy as cp # noqa: PLC0415
|
| 303 |
+
import torch # noqa: PLC0415
|
| 304 |
+
|
| 305 |
+
if torch.cuda.is_available():
|
| 306 |
+
data = cp.asarray(data)
|
| 307 |
+
data = data.reshape((-1, group_size)).astype(cp.float32) # nb = data.shape[0], (nb, group_size)
|
| 308 |
+
maxq = 2**num_bits - 1
|
| 309 |
+
minq = 0
|
| 310 |
+
sum_x2 = cp.sum(data**2, axis=1, keepdims=True) # (nb, 1)
|
| 311 |
+
av_x = cp.sqrt(sum_x2 / group_size) # (nb, 1)
|
| 312 |
+
weights = cp.add(av_x, cp.abs(data)) # (nb, group_size)
|
| 313 |
+
rmin = cp.min(data, axis=1, keepdims=True) # (nb, 1)
|
| 314 |
+
rmax = cp.max(data, axis=1, keepdims=True) # (nb, 1)
|
| 315 |
+
sum_w = cp.sum(weights, axis=1, keepdims=True) # (nb, 1)
|
| 316 |
+
sum_x = cp.sum(weights * data, axis=1, keepdims=True) # (nb, group_size)
|
| 317 |
+
iscale = cp.ones(rmax.shape, dtype=data.dtype) # (nb, 1)
|
| 318 |
+
mask = rmin != rmax
|
| 319 |
+
iscale[mask] = (maxq - minq) / (rmax[mask] - rmin[mask])
|
| 320 |
+
scale = 1 / iscale
|
| 321 |
+
quant_data = cp.clip(cp.round(iscale * (data - rmin)), minq, maxq) # (nb, group_size)
|
| 322 |
+
diff = scale * quant_data + rmin - data # (nb, group_size)
|
| 323 |
+
best_mad = cp.sum(weights * diff**2, axis=1, keepdims=True) # (nb, 1)
|
| 324 |
+
nstep = 20
|
| 325 |
+
rdelta = 0.1
|
| 326 |
+
rrmin = -1
|
| 327 |
+
for is_ in range(nstep):
|
| 328 |
+
iscale_new = cp.ones(rmax.shape, dtype=data.dtype) # (nb, 1)
|
| 329 |
+
factor = cp.array([rrmin + rdelta * is_ + maxq - minq]).astype(data.dtype)[0]
|
| 330 |
+
mask = rmin != rmax
|
| 331 |
+
iscale_new[mask] = factor / (rmax[mask] - rmin[mask])
|
| 332 |
+
quant_data_new = cp.clip(cp.round(iscale_new * (data - rmin)), minq, maxq) # (nb, group_size)
|
| 333 |
+
mul_weights_quant_data_new = weights * quant_data_new
|
| 334 |
+
sum_l = cp.sum(mul_weights_quant_data_new, axis=1, keepdims=True) # (nb, 1)
|
| 335 |
+
sum_l2 = cp.sum(mul_weights_quant_data_new * quant_data_new, axis=1, keepdims=True) # (nb, 1)
|
| 336 |
+
sum_xl = cp.sum(mul_weights_quant_data_new * data, axis=1, keepdims=True) # (nb, 1)
|
| 337 |
+
D = cp.subtract(sum_w * sum_l2, sum_l**2) # noqa: N806
|
| 338 |
+
|
| 339 |
+
this_scale = (sum_w * sum_xl - sum_x * sum_l) / D # (nb, 1)
|
| 340 |
+
this_min = (sum_l2 * sum_x - sum_l * sum_xl) / D # (nb, 1)
|
| 341 |
+
|
| 342 |
+
diff = this_scale * quant_data_new + this_min - data # (nb, group_size)
|
| 343 |
+
mad = cp.sum(weights * diff**2, axis=1, keepdims=True) # (nb, 1)
|
| 344 |
+
|
| 345 |
+
mad_1 = cp.array(mad)
|
| 346 |
+
best_mad_1 = cp.array(best_mad)
|
| 347 |
+
idx_to_replace = cp.where(mad_1 < best_mad_1)[0]
|
| 348 |
+
quant_data[idx_to_replace, :] = quant_data_new[idx_to_replace, :]
|
| 349 |
+
best_mad[idx_to_replace] = mad[idx_to_replace]
|
| 350 |
+
scale[idx_to_replace] = this_scale[idx_to_replace]
|
| 351 |
+
rmin[idx_to_replace] = this_min[idx_to_replace]
|
| 352 |
+
|
| 353 |
+
zero_point = cp.clip(((-rmin) / scale).round(), 0, maxq).astype("uint8")
|
| 354 |
+
scale = scale.astype(cp.float64)
|
| 355 |
+
q_weight = cp.empty_like(data, dtype=scale.dtype)
|
| 356 |
+
cp.divide(data, scale, out=q_weight)
|
| 357 |
+
cp.add(q_weight, zero_point, out=q_weight)
|
| 358 |
+
cp.round(q_weight, out=q_weight)
|
| 359 |
+
cp.clip(q_weight, minq, maxq, out=q_weight)
|
| 360 |
+
|
| 361 |
+
return q_weight.get(), scale.get(), zero_point.get()
|
| 362 |
+
else:
|
| 363 |
+
logger.warning(
|
| 364 |
+
"Try to use k-quant quantization on CUDA. However, CUDA is not available."
|
| 365 |
+
"Fall back to k-quant quantization on CPU."
|
| 366 |
+
)
|
| 367 |
+
return quant_tensor_k_quant_cpu(data, num_bits, group_size)
|
| 368 |
+
except ImportError:
|
| 369 |
+
logger.info(
|
| 370 |
+
"Now we are using k-quant quantization on cpu, which is time consuming."
|
| 371 |
+
"Please consider install cupy to speed up on CUDA. See https://cupy.dev/"
|
| 372 |
+
"Please also install torch to check CUDA availability."
|
| 373 |
+
)
|
| 374 |
+
return quant_tensor_k_quant_cpu(data, num_bits, group_size)
|
| 375 |
+
|
| 376 |
+
|
| 377 |
+
def qdq_tensor(data, num_bits=4, group_size=32, scheme="asym", dtype="int", ratio=1.0):
|
| 378 |
+
"""Quant dequant tensor per group.
|
| 379 |
+
|
| 380 |
+
Args:
|
| 381 |
+
data : input weight
|
| 382 |
+
num_bits (int, optional): num_bits. Defaults to 4.
|
| 383 |
+
group_size (int, optional): how many elements share one scale/zp. Defaults to 4.
|
| 384 |
+
scheme (str, optional): quantization scheme. Defaults to "asym".
|
| 385 |
+
dtype (str, optional): data type. Defaults to "int".
|
| 386 |
+
ratio (float, optional): percentile of clip. Defaults to 1.0.
|
| 387 |
+
|
| 388 |
+
Returns:
|
| 389 |
+
output: quant-dequant weight
|
| 390 |
+
"""
|
| 391 |
+
org_shape = data.shape
|
| 392 |
+
weight, scale, zp = quant_tensor(data, num_bits, group_size, scheme, dtype, ratio)
|
| 393 |
+
return np.reshape(scale * (weight - zp), org_shape)
|
| 394 |
+
|
| 395 |
+
|
| 396 |
+
def pad_tensor(weight, group_size, k_blocks):
|
| 397 |
+
"""Pad tensor rowi so that it can be is divisible by group_size.
|
| 398 |
+
|
| 399 |
+
Args:
|
| 400 |
+
weight (array): weight
|
| 401 |
+
group_size (int): how many elements share one scale/zp
|
| 402 |
+
k_blocks (int): the number of block
|
| 403 |
+
|
| 404 |
+
Returns:
|
| 405 |
+
weight: paded weight
|
| 406 |
+
"""
|
| 407 |
+
if group_size == -1:
|
| 408 |
+
return weight
|
| 409 |
+
|
| 410 |
+
org_w_shape = weight.shape
|
| 411 |
+
padded_rows = k_blocks * group_size
|
| 412 |
+
pad_len = padded_rows - org_w_shape[0]
|
| 413 |
+
|
| 414 |
+
if pad_len > 0:
|
| 415 |
+
weight = np.pad(weight, ((0, pad_len), (0, 0)), "constant")
|
| 416 |
+
|
| 417 |
+
return weight
|
| 418 |
+
|
| 419 |
+
|
| 420 |
+
def rtn_quantize(
|
| 421 |
+
model,
|
| 422 |
+
weight_config={}, # noqa: B006
|
| 423 |
+
num_bits=4,
|
| 424 |
+
group_size=32,
|
| 425 |
+
scheme="asym",
|
| 426 |
+
ratios={}, # noqa: B006
|
| 427 |
+
accuracy_level=0,
|
| 428 |
+
providers=["CPUExecutionProvider"], # noqa: B006
|
| 429 |
+
algorithm="k_quant",
|
| 430 |
+
):
|
| 431 |
+
"""Quant the model with round to nearst method.
|
| 432 |
+
|
| 433 |
+
Args:
|
| 434 |
+
model (ModelProto or ONNXModel): onnx model
|
| 435 |
+
weight_config (dict): quantization config
|
| 436 |
+
For example,
|
| 437 |
+
weight_config = {
|
| 438 |
+
'fc2':
|
| 439 |
+
{
|
| 440 |
+
'bits': 4,
|
| 441 |
+
'group_size': 32,
|
| 442 |
+
'scheme': 'sym',
|
| 443 |
+
'algorithm': 'RTN'
|
| 444 |
+
}
|
| 445 |
+
}
|
| 446 |
+
num_bits (int, optional): num_bits. Default is 4.
|
| 447 |
+
group_size (int, optional): how many elements share one scale/zp. Default is 32.
|
| 448 |
+
scheme (str, optional): sym or asym. Defaults to "asym".
|
| 449 |
+
ratios (dict, optional): percentile of clip. Defaults to {}.
|
| 450 |
+
accuracy_level (int): accuracy level. Support 0 (unset),1(fp32), 2(fp16), 3(bf16), or 4(int8).
|
| 451 |
+
providers (list): providers to use
|
| 452 |
+
|
| 453 |
+
Returns:
|
| 454 |
+
model: fake quantized ONNXModel
|
| 455 |
+
"""
|
| 456 |
+
model = ONNXModel(model)
|
| 457 |
+
base_dir = os.path.dirname(model.model_path) if model.model_path is not None else ""
|
| 458 |
+
new_nodes = []
|
| 459 |
+
remove_nodes = []
|
| 460 |
+
total_num = len([i for i in model.nodes() if i.op_type in ["MatMul"]])
|
| 461 |
+
curr_id = 0
|
| 462 |
+
for node in model.nodes():
|
| 463 |
+
if node.op_type in ["MatMul"]:
|
| 464 |
+
curr_id += 1
|
| 465 |
+
simple_progress_bar(total_num, curr_id)
|
| 466 |
+
if (
|
| 467 |
+
node.op_type in ["MatMul"]
|
| 468 |
+
and model.get_initializer(node.input[1]) is not None
|
| 469 |
+
and weight_config.get(node.name, {}) != "fp32"
|
| 470 |
+
):
|
| 471 |
+
weight_tensor = model.get_initializer(node.input[1])
|
| 472 |
+
weight = numpy_helper.to_array(weight_tensor, base_dir=base_dir).copy()
|
| 473 |
+
if len(weight.shape) != 2:
|
| 474 |
+
continue
|
| 475 |
+
|
| 476 |
+
dtype = weight.dtype
|
| 477 |
+
|
| 478 |
+
if node.name in weight_config:
|
| 479 |
+
num_bits = weight_config[node.name]["bits"]
|
| 480 |
+
group_size = weight_config[node.name]["group_size"]
|
| 481 |
+
scheme = weight_config[node.name]["scheme"]
|
| 482 |
+
|
| 483 |
+
org_w_shape = weight.shape # ic, oc
|
| 484 |
+
group_size = group_size if group_size != -1 else org_w_shape[0]
|
| 485 |
+
|
| 486 |
+
k_blocks = (org_w_shape[0] - 1) // group_size + 1
|
| 487 |
+
init_share_num = model.get_initializer_share_num(node.input[1])
|
| 488 |
+
|
| 489 |
+
weight = pad_tensor(weight, group_size, k_blocks)
|
| 490 |
+
|
| 491 |
+
satisfy_MatMulNBits_condition = num_bits == 4 or num_bits == 8 # noqa: N806
|
| 492 |
+
|
| 493 |
+
if satisfy_MatMulNBits_condition: # pragma: no cover
|
| 494 |
+
if algorithm == "k_quant":
|
| 495 |
+
q_weight, scale, zp = quant_tensor_k_quant_cuda(weight.T, num_bits, group_size)
|
| 496 |
+
else:
|
| 497 |
+
q_weight, scale, zp = quant_tensor(
|
| 498 |
+
weight.T, num_bits, group_size, scheme, "uint", ratios.get(node.input[1], 1)
|
| 499 |
+
)
|
| 500 |
+
|
| 501 |
+
q_matmul_node, new_inits = make_matmul_weight_only_node(
|
| 502 |
+
node=node,
|
| 503 |
+
weight_shape=org_w_shape,
|
| 504 |
+
num_bits=num_bits,
|
| 505 |
+
group_size=group_size,
|
| 506 |
+
k_blocks=k_blocks,
|
| 507 |
+
q_weight=q_weight.astype("uint8"),
|
| 508 |
+
scale=scale.astype(dtype),
|
| 509 |
+
zero_point=zp if scheme == "asym" or algorithm == "k_quant" else None,
|
| 510 |
+
accuracy_level=accuracy_level,
|
| 511 |
+
)
|
| 512 |
+
|
| 513 |
+
model.add_initializers(new_inits)
|
| 514 |
+
remove_nodes.append(node)
|
| 515 |
+
new_nodes.append(q_matmul_node)
|
| 516 |
+
else:
|
| 517 |
+
q_weight = qdq_tensor(weight.T, num_bits, group_size, scheme, "int", ratios.get(node.input[1], 1))
|
| 518 |
+
q_weight = np.reshape(q_weight, (org_w_shape[1], -1))
|
| 519 |
+
q_weight = np.transpose(q_weight)
|
| 520 |
+
q_weight = q_weight[: org_w_shape[0], :].astype(dtype)
|
| 521 |
+
q_weight_tensor = onnx.helper.make_tensor(
|
| 522 |
+
name=node.input[1] + f"_Q{num_bits!s}G{group_size!s}",
|
| 523 |
+
data_type=np_dtype_to_tensor_dtype(dtype),
|
| 524 |
+
dims=weight.shape,
|
| 525 |
+
vals=q_weight.tobytes(),
|
| 526 |
+
raw=True,
|
| 527 |
+
)
|
| 528 |
+
model.add_initializer(q_weight_tensor)
|
| 529 |
+
node.input[1] = q_weight_tensor.name
|
| 530 |
+
if init_share_num == 1:
|
| 531 |
+
model.remove_initializer(weight_tensor)
|
| 532 |
+
|
| 533 |
+
model.add_nodes(new_nodes)
|
| 534 |
+
model.remove_nodes(remove_nodes)
|
| 535 |
+
model.topological_sort()
|
| 536 |
+
return model
|
| 537 |
+
|
| 538 |
+
|
| 539 |
+
def get_weight_scale(weight, group_size):
|
| 540 |
+
"""Get the scale of weight."""
|
| 541 |
+
org_shape = weight.shape
|
| 542 |
+
weight = np.reshape(weight, (-1, group_size)) if group_size != -1 else weight
|
| 543 |
+
scale = np.mean(np.reshape(np.abs(weight) / np.max(np.abs(weight), axis=1, keepdims=True), org_shape), axis=0)
|
| 544 |
+
return scale
|
| 545 |
+
|
| 546 |
+
|
| 547 |
+
def prepare_inputs(model, n_samples, dataloader, providers):
|
| 548 |
+
"""Prepare inputs for weight only quantization.
|
| 549 |
+
|
| 550 |
+
Args:
|
| 551 |
+
model (ModelProto or ONNXModel): onnx model
|
| 552 |
+
n_samples (int, optional): calibration sample number. -1 means all samples.
|
| 553 |
+
dataloader (object): dataloader for calibration.
|
| 554 |
+
providers (list): providers to use
|
| 555 |
+
|
| 556 |
+
Returns:
|
| 557 |
+
inputs: prepared inputs.
|
| 558 |
+
so: session options
|
| 559 |
+
"""
|
| 560 |
+
from importlib.util import find_spec # noqa: PLC0415
|
| 561 |
+
|
| 562 |
+
from .util import to_numpy # noqa: PLC0415
|
| 563 |
+
|
| 564 |
+
so = ort.SessionOptions()
|
| 565 |
+
if sys.version_info < (3, 11) and find_spec("onnxruntime_extensions"): # pragma: no cover
|
| 566 |
+
from onnxruntime_extensions import get_library_path # noqa: PLC0415
|
| 567 |
+
|
| 568 |
+
so.register_custom_ops_library(get_library_path())
|
| 569 |
+
if model.is_large_model:
|
| 570 |
+
onnx.save_model(
|
| 571 |
+
model.model,
|
| 572 |
+
model.model_path + "_augment.onnx",
|
| 573 |
+
save_as_external_data=True,
|
| 574 |
+
all_tensors_to_one_file=True,
|
| 575 |
+
convert_attribute=False,
|
| 576 |
+
)
|
| 577 |
+
|
| 578 |
+
session = (
|
| 579 |
+
ort.InferenceSession(model.model.SerializeToString(), so, providers=providers)
|
| 580 |
+
if not model.is_large_model
|
| 581 |
+
else ort.InferenceSession(model.model_path + "_augment.onnx", so, providers=providers)
|
| 582 |
+
)
|
| 583 |
+
inputs_names = [i.name for i in session.get_inputs()]
|
| 584 |
+
del session
|
| 585 |
+
|
| 586 |
+
inputs = []
|
| 587 |
+
for i, data in enumerate(dataloader):
|
| 588 |
+
if n_samples != -1 and ((i + 1) * dataloader.batch_size) > n_samples:
|
| 589 |
+
break
|
| 590 |
+
if len(inputs_names) != 1 or isinstance(data[0], dict):
|
| 591 |
+
assert len(data[0]) == len(inputs_names), (
|
| 592 |
+
f"Input number mismatch, require {len(inputs_names)} but get {len(data[0])}"
|
| 593 |
+
)
|
| 594 |
+
|
| 595 |
+
if isinstance(data[0], dict):
|
| 596 |
+
inputs.append(dict([(name, to_numpy(inp_data)) for name, inp_data in data[0].items()])) # noqa: C404
|
| 597 |
+
elif isinstance(data[0], np.ndarray): # pragma: no cover
|
| 598 |
+
inputs.append(dict([(name, inp) for name, inp in zip(inputs_names, [data[0]], strict=False)])) # noqa: C404
|
| 599 |
+
else: # pragma: no cover
|
| 600 |
+
inputs.append(dict([(name, to_numpy(inp)) for name, inp in zip(inputs_names, data[0], strict=False)])) # noqa: C404
|
| 601 |
+
return inputs, so
|
| 602 |
+
|
| 603 |
+
|
| 604 |
+
def gptq(
|
| 605 |
+
W,
|
| 606 |
+
H,
|
| 607 |
+
num_bits=4,
|
| 608 |
+
group_size=32,
|
| 609 |
+
scheme="asym",
|
| 610 |
+
blocksize=128,
|
| 611 |
+
percdamp=0.01,
|
| 612 |
+
actorder=False,
|
| 613 |
+
mse=False,
|
| 614 |
+
perchannel=True,
|
| 615 |
+
):
|
| 616 |
+
"""Quant the weight with GPTQ method.
|
| 617 |
+
|
| 618 |
+
Args:
|
| 619 |
+
W (array): weight.
|
| 620 |
+
H (array): Hessian matrix.
|
| 621 |
+
num_bits (int, optional): num_bits. Default is 4.
|
| 622 |
+
group_size (int, optional): how many elements share one scale/zp. Default is 32.
|
| 623 |
+
scheme (str, optional): sym or asym. Defaults to "asym".
|
| 624 |
+
blocksize (int, optional): blocksize to quantize weight.
|
| 625 |
+
percdamp (float, optional): percent of the average Hessian diagonal to use for dampening.
|
| 626 |
+
actorder (bool, optional): whether rearrange Hessian matrix considering the diag's value.
|
| 627 |
+
mse (bool, optional): whether get scale and zero point with mse error.
|
| 628 |
+
perchannel (bool, optional): whether quantize weight per-channel.
|
| 629 |
+
|
| 630 |
+
Returns:
|
| 631 |
+
Q: fake quantized weight
|
| 632 |
+
"""
|
| 633 |
+
maxq = 2**num_bits - 1
|
| 634 |
+
grid = 100
|
| 635 |
+
maxshrink = 0.8
|
| 636 |
+
norm = 2.4
|
| 637 |
+
|
| 638 |
+
def find_params(weight):
|
| 639 |
+
org_shape = weight.shape
|
| 640 |
+
# find zp, scale
|
| 641 |
+
if not perchannel:
|
| 642 |
+
weight = np.expand_dims(weight.flatten(), axis=1)
|
| 643 |
+
tmp = np.zeros(weight.shape[1])
|
| 644 |
+
xmin = np.minimum(np.min(weight, axis=0), tmp)
|
| 645 |
+
xmax = np.maximum(np.max(weight, axis=0), tmp)
|
| 646 |
+
if scheme == "sym":
|
| 647 |
+
xmax = np.maximum(np.abs(xmin), xmax)
|
| 648 |
+
tmp = xmin < 0
|
| 649 |
+
if np.any(tmp):
|
| 650 |
+
xmin[tmp] = -xmax[tmp]
|
| 651 |
+
tmp = (xmin == 0) & (xmax == 0)
|
| 652 |
+
xmin[tmp] = -1
|
| 653 |
+
xmax[tmp] = +1
|
| 654 |
+
|
| 655 |
+
scale = (xmax - xmin) / maxq
|
| 656 |
+
if scheme == "sym":
|
| 657 |
+
zero = np.ones(scale.shape) * (maxq + 1) / 2
|
| 658 |
+
else:
|
| 659 |
+
zero = np.round(-xmin / scale)
|
| 660 |
+
if mse:
|
| 661 |
+
best = np.ones([weight.shape[1]]) * float("inf")
|
| 662 |
+
for i in range(int(maxshrink * grid)):
|
| 663 |
+
p = 1 - i / grid
|
| 664 |
+
xmin1 = p * xmin
|
| 665 |
+
xmax1 = p * xmax
|
| 666 |
+
scale1 = (xmax1 - xmin1) / maxq
|
| 667 |
+
zero1 = np.round(-xmin1 / scale1) if scheme != "sym" else zero
|
| 668 |
+
q = np.clip(np.round(weight / scale1) + zero1, 0, maxq)
|
| 669 |
+
q -= weight
|
| 670 |
+
q = np.power(np.abs(q), norm)
|
| 671 |
+
err = np.sum(q, 0)
|
| 672 |
+
tmp = err < best
|
| 673 |
+
if np.any(tmp):
|
| 674 |
+
best[tmp] = err[tmp]
|
| 675 |
+
scale[tmp] = scale1[tmp]
|
| 676 |
+
zero[tmp] = zero1[tmp]
|
| 677 |
+
if not perchannel:
|
| 678 |
+
tmp = org_shape[1]
|
| 679 |
+
scale = np.repeat(scale, tmp)
|
| 680 |
+
zero = np.repeat(zero, tmp)
|
| 681 |
+
shape = [-1] + [1] * (len(org_shape) - 1)
|
| 682 |
+
scale = np.reshape(scale, shape)
|
| 683 |
+
zero = np.reshape(zero, shape)
|
| 684 |
+
return scale, zero
|
| 685 |
+
|
| 686 |
+
shape = W.shape
|
| 687 |
+
scale, zp = find_params(W)
|
| 688 |
+
dead = np.diag(H) == 0
|
| 689 |
+
H[dead, dead] = 1
|
| 690 |
+
W[dead, :] = 0 # such channel makes no contribution to quantization computation
|
| 691 |
+
|
| 692 |
+
# rearrange considering the diag's value
|
| 693 |
+
if actorder:
|
| 694 |
+
perm = np.argsort(np.diag(H))[::-1]
|
| 695 |
+
W = W[perm, :] # noqa: N806
|
| 696 |
+
H = H[perm, :][:, perm] # noqa: N806
|
| 697 |
+
Losses = np.zeros_like(W) # noqa: N806
|
| 698 |
+
Q = np.zeros_like(W) # noqa: N806
|
| 699 |
+
damp = percdamp * np.mean(np.diag(H))
|
| 700 |
+
diag = np.arange(shape[0])
|
| 701 |
+
H[diag, diag] += damp # add a average value of
|
| 702 |
+
H = np.linalg.cholesky(np.linalg.inv(H)).T # noqa: N806
|
| 703 |
+
Hinv = H # noqa: N806
|
| 704 |
+
for i1 in range(0, shape[0], blocksize):
|
| 705 |
+
i2 = min(i1 + blocksize, shape[0])
|
| 706 |
+
count = i2 - i1
|
| 707 |
+
|
| 708 |
+
W1 = copy.deepcopy(W[i1:i2, :]) # noqa: N806
|
| 709 |
+
Q1 = np.zeros_like(W1) # noqa: N806
|
| 710 |
+
Err1 = np.zeros_like(W1) # noqa: N806
|
| 711 |
+
Losses1 = np.zeros_like(W1) # noqa: N806
|
| 712 |
+
Hinv1 = Hinv[i1:i2, i1:i2] # noqa: N806
|
| 713 |
+
|
| 714 |
+
for i in range(count): # within a block, channel wise
|
| 715 |
+
w = W1[i, :]
|
| 716 |
+
d = Hinv1[i, i]
|
| 717 |
+
|
| 718 |
+
if group_size != -1:
|
| 719 |
+
if (i1 + i) % group_size == 0:
|
| 720 |
+
scale, zp = find_params(W[(i1 + i) : (i1 + i + group_size), :])
|
| 721 |
+
|
| 722 |
+
q = (scale * (np.clip(np.round(w[:, np.newaxis] / scale) + zp, 0, maxq) - zp)).flatten()
|
| 723 |
+
Q1[i, :] = q
|
| 724 |
+
Losses1[i, :] = (w - q) ** 2 / d**2
|
| 725 |
+
|
| 726 |
+
err1 = (w - q) / d
|
| 727 |
+
W1[i:, :] -= np.matmul(np.expand_dims(Hinv1[i:, i], axis=1), np.expand_dims(err1, axis=0))
|
| 728 |
+
Err1[i, :] = err1
|
| 729 |
+
|
| 730 |
+
Q[i1:i2, :] = Q1
|
| 731 |
+
Losses[i1:i2, :] = Losses1 / 2
|
| 732 |
+
|
| 733 |
+
W[i2:, :] -= np.matmul(Hinv[i2:, i1:i2], Err1)
|
| 734 |
+
|
| 735 |
+
if actorder:
|
| 736 |
+
invperm = np.argsort(perm)
|
| 737 |
+
Q = Q[invperm, :] # noqa: N806
|
| 738 |
+
|
| 739 |
+
Q = np.reshape(Q, W.shape) # noqa: N806
|
| 740 |
+
del W
|
| 741 |
+
return Q
|
| 742 |
+
|
| 743 |
+
|
| 744 |
+
def gptq_quantize(
|
| 745 |
+
model,
|
| 746 |
+
dataloader,
|
| 747 |
+
weight_config={}, # noqa: B006
|
| 748 |
+
num_bits=4,
|
| 749 |
+
group_size=32,
|
| 750 |
+
scheme="asym",
|
| 751 |
+
n_samples=128,
|
| 752 |
+
percdamp=0.01,
|
| 753 |
+
blocksize=128,
|
| 754 |
+
actorder=False,
|
| 755 |
+
mse=False,
|
| 756 |
+
perchannel=True,
|
| 757 |
+
accuracy_level=0,
|
| 758 |
+
providers=["CPUExecutionProvider"], # noqa: B006
|
| 759 |
+
):
|
| 760 |
+
"""Quant the model with GPTQ method.
|
| 761 |
+
|
| 762 |
+
Args:
|
| 763 |
+
model (ModelProto or ONNXModel): onnx model
|
| 764 |
+
dataloader (object): dataloader for calibration.
|
| 765 |
+
weight_config (dict): quantization config
|
| 766 |
+
For example,
|
| 767 |
+
weight_config = {
|
| 768 |
+
'fc2':
|
| 769 |
+
{
|
| 770 |
+
'bits': 4,
|
| 771 |
+
'group_size': 32,
|
| 772 |
+
'scheme': 'sym',
|
| 773 |
+
'algorithm': 'GPTQ'
|
| 774 |
+
}
|
| 775 |
+
}
|
| 776 |
+
num_bits (int, optional): num_bits. Default is 4.
|
| 777 |
+
group_size (int, optional): how many elements share one scale/zp. Default is 32.
|
| 778 |
+
scheme (str, optional): sym or asym. Defaults to "asym".
|
| 779 |
+
n_samples (int, optional): calibration sample number.
|
| 780 |
+
percdamp (float, optional): percent of the average Hessian diagonal to use for dampening.
|
| 781 |
+
blocksize (int, optional): blocksize to quantize weight.
|
| 782 |
+
actorder (bool, optional): whether rearrange Hessian matrix considering the diag's value.
|
| 783 |
+
mse (bool, optional): whether get scale and zero point with mse error.
|
| 784 |
+
perchannel (bool, optional): whether quantize weight per-channel.
|
| 785 |
+
accuracy_level (int): accuracy level. Support 0 (unset), 1(fp32), 2(fp16), 3(bf16), or 4(int8).
|
| 786 |
+
providers (list): providers to use
|
| 787 |
+
|
| 788 |
+
Returns:
|
| 789 |
+
model: fake quantized ONNXModel
|
| 790 |
+
"""
|
| 791 |
+
model = ONNXModel(model)
|
| 792 |
+
base_dir = os.path.dirname(model.model_path) if model.model_path is not None else ""
|
| 793 |
+
|
| 794 |
+
inputs, so = prepare_inputs(model, n_samples, dataloader, providers)
|
| 795 |
+
del dataloader
|
| 796 |
+
org_output = copy.deepcopy(model.model.graph.output)
|
| 797 |
+
model.remove_tensors_from_outputs([i.name for i in org_output])
|
| 798 |
+
output_names = []
|
| 799 |
+
for node in model.nodes():
|
| 800 |
+
if (
|
| 801 |
+
node.op_type in ["MatMul"]
|
| 802 |
+
and weight_config.get(node.name, {}) != "fp32"
|
| 803 |
+
and weight_config.get(node.name, {}).get("algorithm", "GPTQ") == "GPTQ"
|
| 804 |
+
):
|
| 805 |
+
output_names.append(node.input[0])
|
| 806 |
+
output_names = list(set(output_names))
|
| 807 |
+
model.add_tensors_to_outputs(output_names)
|
| 808 |
+
if model.is_large_model:
|
| 809 |
+
onnx.save_model(
|
| 810 |
+
model.model,
|
| 811 |
+
model.model_path + "_augment.onnx",
|
| 812 |
+
save_as_external_data=True,
|
| 813 |
+
all_tensors_to_one_file=True,
|
| 814 |
+
convert_attribute=False,
|
| 815 |
+
)
|
| 816 |
+
|
| 817 |
+
session = (
|
| 818 |
+
ort.InferenceSession(model.model.SerializeToString(), so, providers=providers)
|
| 819 |
+
if not model.is_large_model
|
| 820 |
+
else ort.InferenceSession(model.model_path + "_augment.onnx", so, providers=providers)
|
| 821 |
+
)
|
| 822 |
+
|
| 823 |
+
for idx, input_name in enumerate(output_names):
|
| 824 |
+
simple_progress_bar(len(output_names), idx + 1)
|
| 825 |
+
node_list = []
|
| 826 |
+
weights = []
|
| 827 |
+
|
| 828 |
+
for node in model.input_name_to_nodes[input_name]:
|
| 829 |
+
if (
|
| 830 |
+
node.op_type in ["MatMul"]
|
| 831 |
+
and weight_config.get(node.name, {}) != "fp32"
|
| 832 |
+
and weight_config.get(node.name, {}).get("algorithm", "GPTQ") == "GPTQ"
|
| 833 |
+
and model.get_initializer(node.input[1]) is not None
|
| 834 |
+
):
|
| 835 |
+
weight = numpy_helper.to_array(
|
| 836 |
+
model.get_initializer(model.get_node(node.name).input[1]), base_dir
|
| 837 |
+
).copy()
|
| 838 |
+
if len(weight.shape) != 2:
|
| 839 |
+
continue
|
| 840 |
+
|
| 841 |
+
weights.append(weight)
|
| 842 |
+
node_list.append(model.get_node(node.name))
|
| 843 |
+
|
| 844 |
+
if len(weights) == 0:
|
| 845 |
+
continue
|
| 846 |
+
|
| 847 |
+
Hs = [np.zeros((i.shape[0], i.shape[0])) for i in weights] # noqa: N806
|
| 848 |
+
nsamples = 0
|
| 849 |
+
for data in inputs:
|
| 850 |
+
inp = session.run([input_name], data)[0]
|
| 851 |
+
tmp = inp.shape[0]
|
| 852 |
+
inp = np.reshape(inp, (-1, inp.shape[-1]))
|
| 853 |
+
Hs = [i * (nsamples / (nsamples + tmp)) for i in Hs] # noqa: N806
|
| 854 |
+
nsamples += tmp
|
| 855 |
+
inp = np.sqrt(2 / nsamples) * inp
|
| 856 |
+
Hs = [i + np.matmul(inp.T, inp) for i in Hs] # noqa: N806
|
| 857 |
+
|
| 858 |
+
for (
|
| 859 |
+
node,
|
| 860 |
+
weight,
|
| 861 |
+
H, # noqa: N806
|
| 862 |
+
) in zip(node_list, weights, Hs, strict=False):
|
| 863 |
+
if node.name in weight_config:
|
| 864 |
+
num_bits = weight_config[node.name]["bits"]
|
| 865 |
+
group_size = weight_config[node.name]["group_size"]
|
| 866 |
+
scheme = weight_config[node.name]["scheme"]
|
| 867 |
+
group_size = group_size if group_size != -1 else weight.shape[0]
|
| 868 |
+
dtype = weight.dtype
|
| 869 |
+
|
| 870 |
+
q_weight = gptq(
|
| 871 |
+
weight,
|
| 872 |
+
H,
|
| 873 |
+
num_bits=num_bits,
|
| 874 |
+
group_size=group_size,
|
| 875 |
+
scheme=scheme,
|
| 876 |
+
blocksize=blocksize,
|
| 877 |
+
percdamp=percdamp,
|
| 878 |
+
actorder=actorder,
|
| 879 |
+
mse=mse,
|
| 880 |
+
perchannel=perchannel,
|
| 881 |
+
)
|
| 882 |
+
|
| 883 |
+
weight_tensor = model.get_initializer(node.input[1])
|
| 884 |
+
init_share_num = model.get_initializer_share_num(node.input[1])
|
| 885 |
+
|
| 886 |
+
satisfy_MatMulNBits_condition = num_bits == 4 # noqa: N806
|
| 887 |
+
|
| 888 |
+
if satisfy_MatMulNBits_condition: # pragma: no cover
|
| 889 |
+
org_shape = weight.shape
|
| 890 |
+
k_blocks = (org_shape[0] + group_size - 1) // group_size
|
| 891 |
+
q_weight = pad_tensor(q_weight, group_size, k_blocks)
|
| 892 |
+
q_weight, scale, zp = quant_tensor(q_weight.T, num_bits, group_size, scheme, "uint")
|
| 893 |
+
q_matmul_node, new_inits = make_matmul_weight_only_node(
|
| 894 |
+
node=node,
|
| 895 |
+
weight_shape=org_shape,
|
| 896 |
+
num_bits=num_bits,
|
| 897 |
+
group_size=group_size,
|
| 898 |
+
k_blocks=k_blocks,
|
| 899 |
+
q_weight=q_weight.astype("uint8"),
|
| 900 |
+
scale=scale.astype(dtype),
|
| 901 |
+
zero_point=zp if scheme == "asym" else None,
|
| 902 |
+
accuracy_level=accuracy_level,
|
| 903 |
+
)
|
| 904 |
+
|
| 905 |
+
model.add_initializers(new_inits)
|
| 906 |
+
model.remove_node(node)
|
| 907 |
+
model.add_node(q_matmul_node)
|
| 908 |
+
else:
|
| 909 |
+
q_weight_tensor = onnx.helper.make_tensor(
|
| 910 |
+
name=node.input[1] + f"_Q{num_bits!s}G{group_size!s}",
|
| 911 |
+
data_type=np_dtype_to_tensor_dtype(dtype),
|
| 912 |
+
dims=q_weight.shape,
|
| 913 |
+
vals=q_weight.astype(dtype).tobytes(),
|
| 914 |
+
raw=True,
|
| 915 |
+
)
|
| 916 |
+
model.add_initializer(q_weight_tensor)
|
| 917 |
+
node.input[1] = q_weight_tensor.name
|
| 918 |
+
if init_share_num == 1:
|
| 919 |
+
model.remove_initializer(weight_tensor)
|
| 920 |
+
|
| 921 |
+
model.remove_tensors_from_outputs(output_names)
|
| 922 |
+
model.model.graph.output.MergeFrom(org_output)
|
| 923 |
+
|
| 924 |
+
model.topological_sort()
|
| 925 |
+
|
| 926 |
+
# reload external data to prevent external data file path errors
|
| 927 |
+
if model.is_large_model:
|
| 928 |
+
from onnx.external_data_helper import load_external_data_for_model # noqa: PLC0415
|
| 929 |
+
|
| 930 |
+
load_external_data_for_model(model.model, os.path.split(model.model_path)[0])
|
| 931 |
+
|
| 932 |
+
return model
|
micromamba_root/envs/pytorch_env/Lib/site-packages/onnxruntime/quantization/onnx_model.py
ADDED
|
@@ -0,0 +1,600 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
| 1 |
+
# --------------------------------------------------------------------------
|
| 2 |
+
# Copyright (c) Microsoft Corporation. All rights reserved.
|
| 3 |
+
# Licensed under the MIT License.
|
| 4 |
+
# --------------------------------------------------------------------------
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
|
| 7 |
+
import onnx
|
| 8 |
+
import onnx.helper as onnx_helper
|
| 9 |
+
import onnx.numpy_helper as onnx_numpy_helper
|
| 10 |
+
from onnx.onnx_pb import ModelProto
|
| 11 |
+
|
| 12 |
+
from .quant_utils import attribute_to_kwarg, find_by_name
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def _clean_initializers_helper(graph, model):
|
| 16 |
+
"""Clean unused initializers from graph.
|
| 17 |
+
|
| 18 |
+
Returns:
|
| 19 |
+
A cleaned graph without unused initializers
|
| 20 |
+
A list of tensor names, which are not produced by this graph and its subgraphes
|
| 21 |
+
"""
|
| 22 |
+
requesting_tensor_names = set()
|
| 23 |
+
requesting_tensor_names.update(input_name for node in graph.node for input_name in node.input if input_name)
|
| 24 |
+
requesting_tensor_names.update(g_out.name for g_out in graph.output if g_out.name)
|
| 25 |
+
|
| 26 |
+
new_nodes = []
|
| 27 |
+
for node in graph.node:
|
| 28 |
+
new_node = node
|
| 29 |
+
graph_attrs = [
|
| 30 |
+
attr
|
| 31 |
+
for attr in node.attribute
|
| 32 |
+
if attr.type == onnx.AttributeProto.GRAPH or attr.type == onnx.AttributeProto.GRAPHS
|
| 33 |
+
]
|
| 34 |
+
if graph_attrs:
|
| 35 |
+
kwargs = {}
|
| 36 |
+
for attr in node.attribute:
|
| 37 |
+
new_attribute = {}
|
| 38 |
+
if attr.type == onnx.AttributeProto.GRAPH:
|
| 39 |
+
(
|
| 40 |
+
cleaned_sub_graph,
|
| 41 |
+
sub_requesting_tensor_names,
|
| 42 |
+
) = _clean_initializers_helper(attr.g, model)
|
| 43 |
+
new_attribute = {attr.name: cleaned_sub_graph}
|
| 44 |
+
requesting_tensor_names.update(sub_requesting_tensor_names)
|
| 45 |
+
elif attr.type == onnx.AttributeProto.GRAPHS:
|
| 46 |
+
cleaned_graphes = []
|
| 47 |
+
for subgraph in attr.graphs:
|
| 48 |
+
(
|
| 49 |
+
cleaned_sub_graph,
|
| 50 |
+
sub_requesting_tensor_names,
|
| 51 |
+
) = _clean_initializers_helper(subgraph, model)
|
| 52 |
+
cleaned_graphes.append(cleaned_sub_graph)
|
| 53 |
+
requesting_tensor_names.update(sub_requesting_tensor_names)
|
| 54 |
+
new_attribute = {attr.name: cleaned_graphes}
|
| 55 |
+
else:
|
| 56 |
+
new_attribute = attribute_to_kwarg(attr)
|
| 57 |
+
kwargs.update(new_attribute)
|
| 58 |
+
new_node = onnx_helper.make_node(node.op_type, node.input, node.output, name=node.name, **kwargs)
|
| 59 |
+
new_nodes.append(new_node)
|
| 60 |
+
|
| 61 |
+
graph.ClearField("node")
|
| 62 |
+
graph.node.extend(new_nodes)
|
| 63 |
+
|
| 64 |
+
requesting_tensor_names.difference_update(output for node in graph.node for output in node.output)
|
| 65 |
+
|
| 66 |
+
unused_initializer = []
|
| 67 |
+
for initializer in graph.initializer:
|
| 68 |
+
if initializer.name in requesting_tensor_names:
|
| 69 |
+
requesting_tensor_names.remove(initializer.name)
|
| 70 |
+
else:
|
| 71 |
+
# mark it to remove, remove here directly will cause mis-behavier
|
| 72 |
+
unused_initializer.append(initializer)
|
| 73 |
+
|
| 74 |
+
name_to_input = {input.name: input for input in graph.input}
|
| 75 |
+
for initializer in unused_initializer:
|
| 76 |
+
graph.initializer.remove(initializer)
|
| 77 |
+
if initializer.name in name_to_input:
|
| 78 |
+
try:
|
| 79 |
+
graph.input.remove(name_to_input[initializer.name])
|
| 80 |
+
except StopIteration:
|
| 81 |
+
if model.ir_version < 4:
|
| 82 |
+
print(f"Warning: invalid weight name {initializer.name} found in the graph (not a graph input)")
|
| 83 |
+
|
| 84 |
+
requesting_tensor_names.difference_update(input.name for input in graph.input)
|
| 85 |
+
|
| 86 |
+
return graph, requesting_tensor_names
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
class ONNXModel:
|
| 90 |
+
def __init__(self, model: ModelProto):
|
| 91 |
+
self.model = model
|
| 92 |
+
|
| 93 |
+
def nodes(self):
|
| 94 |
+
return self.model.graph.node
|
| 95 |
+
|
| 96 |
+
def initializer(self):
|
| 97 |
+
return self.model.graph.initializer
|
| 98 |
+
|
| 99 |
+
def initializer_extend(self, inits):
|
| 100 |
+
if len(inits) == 0:
|
| 101 |
+
raise ValueError("Can add an empty list.")
|
| 102 |
+
for init in self.initializer():
|
| 103 |
+
self._check_init(init, "gain")
|
| 104 |
+
for init in inits:
|
| 105 |
+
self._check_init(init)
|
| 106 |
+
self.model.graph.initializer.append(init)
|
| 107 |
+
|
| 108 |
+
def graph(self):
|
| 109 |
+
return self.model.graph
|
| 110 |
+
|
| 111 |
+
def ir_version(self):
|
| 112 |
+
return self.model.ir_version
|
| 113 |
+
|
| 114 |
+
def opset_import(self):
|
| 115 |
+
return self.model.opset_import
|
| 116 |
+
|
| 117 |
+
def set_opset_import(self, domain, version):
|
| 118 |
+
for opset in self.model.opset_import:
|
| 119 |
+
if opset.domain == domain:
|
| 120 |
+
opset.version = version
|
| 121 |
+
return
|
| 122 |
+
|
| 123 |
+
self.model.opset_import.extend([onnx_helper.make_opsetid(domain, version)])
|
| 124 |
+
|
| 125 |
+
def remove_node(self, node):
|
| 126 |
+
if node in self.model.graph.node:
|
| 127 |
+
self.model.graph.node.remove(node)
|
| 128 |
+
|
| 129 |
+
def remove_nodes(self, nodes_to_remove):
|
| 130 |
+
for node in nodes_to_remove:
|
| 131 |
+
self.remove_node(node)
|
| 132 |
+
|
| 133 |
+
def add_node(self, node):
|
| 134 |
+
self.model.graph.node.extend([self._check_node(node)])
|
| 135 |
+
|
| 136 |
+
def add_nodes(self, nodes_to_add):
|
| 137 |
+
for node in nodes_to_add:
|
| 138 |
+
self.add_node(node)
|
| 139 |
+
|
| 140 |
+
def add_initializer(self, tensor):
|
| 141 |
+
if find_by_name(tensor.name, self.model.graph.initializer) is None:
|
| 142 |
+
self._check_init(tensor)
|
| 143 |
+
self.model.graph.initializer.extend([tensor])
|
| 144 |
+
|
| 145 |
+
def get_initializer(self, name):
|
| 146 |
+
for tensor in self.model.graph.initializer:
|
| 147 |
+
if tensor.name == name:
|
| 148 |
+
return tensor
|
| 149 |
+
return None
|
| 150 |
+
|
| 151 |
+
def find_graph_input(self, input_name):
|
| 152 |
+
for input in self.model.graph.input:
|
| 153 |
+
if input.name == input_name:
|
| 154 |
+
return input
|
| 155 |
+
return None
|
| 156 |
+
|
| 157 |
+
def find_graph_output(self, output_name):
|
| 158 |
+
for output in self.model.graph.output:
|
| 159 |
+
if output.name == output_name:
|
| 160 |
+
return output
|
| 161 |
+
return None
|
| 162 |
+
|
| 163 |
+
def get_tensor_type(self, tensor_name: str):
|
| 164 |
+
tensor_type_map = {obj.name: obj.type for obj in self.model.graph.value_info}
|
| 165 |
+
|
| 166 |
+
if tensor_name in tensor_type_map:
|
| 167 |
+
return tensor_type_map[tensor_name].tensor_type
|
| 168 |
+
|
| 169 |
+
g_input = self.find_graph_input(tensor_name)
|
| 170 |
+
if g_input:
|
| 171 |
+
return g_input.type.tensor_type
|
| 172 |
+
|
| 173 |
+
g_output = self.find_graph_output(tensor_name)
|
| 174 |
+
if g_output:
|
| 175 |
+
return g_output.type.tensor_type
|
| 176 |
+
|
| 177 |
+
return None
|
| 178 |
+
|
| 179 |
+
def get_constant_value(self, output_name):
|
| 180 |
+
for node in self.model.graph.node:
|
| 181 |
+
if node.op_type == "Constant":
|
| 182 |
+
if node.output[0] == output_name:
|
| 183 |
+
for attr in node.attribute:
|
| 184 |
+
if attr.name == "value":
|
| 185 |
+
return onnx_numpy_helper.to_array(attr.t)
|
| 186 |
+
|
| 187 |
+
# Fallback to initializer since constant folding may have been applied.
|
| 188 |
+
initializer = self.get_initializer(output_name)
|
| 189 |
+
if initializer is not None:
|
| 190 |
+
return onnx_numpy_helper.to_array(initializer)
|
| 191 |
+
|
| 192 |
+
return None
|
| 193 |
+
|
| 194 |
+
def get_initializer_name_set(self):
|
| 195 |
+
return {initializer.name for initializer in self.model.graph.initializer}
|
| 196 |
+
|
| 197 |
+
def remove_initializer(self, tensor):
|
| 198 |
+
if tensor in self.model.graph.initializer:
|
| 199 |
+
self.model.graph.initializer.remove(tensor)
|
| 200 |
+
for input in self.model.graph.input:
|
| 201 |
+
if input.name == tensor.name:
|
| 202 |
+
self.model.graph.input.remove(input)
|
| 203 |
+
break
|
| 204 |
+
|
| 205 |
+
def remove_initializers(self, init_to_remove):
|
| 206 |
+
for initializer in init_to_remove:
|
| 207 |
+
self.remove_initializer(initializer)
|
| 208 |
+
|
| 209 |
+
def get_non_initializer_inputs(self):
|
| 210 |
+
initializer_names = self.get_initializer_name_set()
|
| 211 |
+
non_initializer_inputs = set()
|
| 212 |
+
for input in self.model.graph.input:
|
| 213 |
+
if input.name not in initializer_names:
|
| 214 |
+
non_initializer_inputs.add(input.name)
|
| 215 |
+
return non_initializer_inputs
|
| 216 |
+
|
| 217 |
+
def input_name_to_nodes(self):
|
| 218 |
+
input_name_to_nodes = {}
|
| 219 |
+
for node in self.model.graph.node:
|
| 220 |
+
for input_name in node.input:
|
| 221 |
+
if input_name: # Could be empty when it is optional
|
| 222 |
+
if input_name not in input_name_to_nodes:
|
| 223 |
+
input_name_to_nodes[input_name] = [node]
|
| 224 |
+
else:
|
| 225 |
+
input_name_to_nodes[input_name].append(node)
|
| 226 |
+
return input_name_to_nodes
|
| 227 |
+
|
| 228 |
+
def output_name_to_node(self):
|
| 229 |
+
output_name_to_node = {}
|
| 230 |
+
for node in self.model.graph.node:
|
| 231 |
+
for output_name in node.output:
|
| 232 |
+
if output_name: # Could be empty when it is optional
|
| 233 |
+
output_name_to_node[output_name] = node
|
| 234 |
+
return output_name_to_node
|
| 235 |
+
|
| 236 |
+
def get_children(self, node, input_name_to_nodes=None):
|
| 237 |
+
if input_name_to_nodes is None:
|
| 238 |
+
input_name_to_nodes = self.input_name_to_nodes()
|
| 239 |
+
|
| 240 |
+
children = []
|
| 241 |
+
for output in node.output:
|
| 242 |
+
if output in input_name_to_nodes:
|
| 243 |
+
for node in input_name_to_nodes[output]:
|
| 244 |
+
children.append(node) # noqa: PERF402
|
| 245 |
+
return children
|
| 246 |
+
|
| 247 |
+
def get_parents(self, node, output_name_to_node=None):
|
| 248 |
+
if output_name_to_node is None:
|
| 249 |
+
output_name_to_node = self.output_name_to_node()
|
| 250 |
+
|
| 251 |
+
parents = []
|
| 252 |
+
for input in node.input:
|
| 253 |
+
if input in output_name_to_node:
|
| 254 |
+
parents.append(output_name_to_node[input])
|
| 255 |
+
return parents
|
| 256 |
+
|
| 257 |
+
def get_parent(self, node, idx, output_name_to_node=None):
|
| 258 |
+
if output_name_to_node is None:
|
| 259 |
+
output_name_to_node = self.output_name_to_node()
|
| 260 |
+
|
| 261 |
+
if len(node.input) <= idx:
|
| 262 |
+
return None
|
| 263 |
+
|
| 264 |
+
input = node.input[idx]
|
| 265 |
+
if input not in output_name_to_node:
|
| 266 |
+
return None
|
| 267 |
+
|
| 268 |
+
return output_name_to_node[input]
|
| 269 |
+
|
| 270 |
+
def find_node_by_name(self, node_name, new_nodes_list, graph):
|
| 271 |
+
"""Find out if a node exists in a graph or a node is in the
|
| 272 |
+
new set of nodes created during quantization.
|
| 273 |
+
|
| 274 |
+
Returns:
|
| 275 |
+
The node found or None.
|
| 276 |
+
"""
|
| 277 |
+
graph_nodes_list = list(graph.node) # deep copy
|
| 278 |
+
graph_nodes_list.extend(new_nodes_list)
|
| 279 |
+
node = find_by_name(node_name, graph_nodes_list)
|
| 280 |
+
return node
|
| 281 |
+
|
| 282 |
+
def get_largest_node_name_suffix(self, node_name_prefix):
|
| 283 |
+
"""
|
| 284 |
+
Gets the largest node name (int) suffix for all node names that begin with `node_name_prefix`.
|
| 285 |
+
Example: for nodes my_prefix_0 and my_prefix_3, this method returns 3.
|
| 286 |
+
"""
|
| 287 |
+
suffix = -1
|
| 288 |
+
|
| 289 |
+
for node in self.model.graph.node:
|
| 290 |
+
if node.name and node.name.startswith(node_name_prefix):
|
| 291 |
+
try:
|
| 292 |
+
index = int(node.name[len(node_name_prefix) :])
|
| 293 |
+
suffix = max(index, suffix)
|
| 294 |
+
except ValueError:
|
| 295 |
+
continue
|
| 296 |
+
|
| 297 |
+
return suffix
|
| 298 |
+
|
| 299 |
+
def get_largest_initializer_name_suffix(self, initializer_name_prefix):
|
| 300 |
+
"""
|
| 301 |
+
Gets the largest initializer name integer suffix for all initializer names that begin
|
| 302 |
+
with `initializer_name_prefix`. This can be used to create unique initializer names.
|
| 303 |
+
|
| 304 |
+
Example: for initializer names 'my_weight_0' and 'my_weight_3', this method returns 3 if
|
| 305 |
+
`initializer_name_prefix` is 'my_weight_'.
|
| 306 |
+
"""
|
| 307 |
+
suffix = -1
|
| 308 |
+
|
| 309 |
+
for initializer in self.model.graph.initializer:
|
| 310 |
+
if initializer.name.startswith(initializer_name_prefix):
|
| 311 |
+
try:
|
| 312 |
+
index = int(initializer.name[len(initializer_name_prefix) :])
|
| 313 |
+
suffix = max(index, suffix)
|
| 314 |
+
except ValueError:
|
| 315 |
+
continue
|
| 316 |
+
|
| 317 |
+
return suffix
|
| 318 |
+
|
| 319 |
+
def find_nodes_by_initializer(self, graph, initializer):
|
| 320 |
+
"""
|
| 321 |
+
Find all nodes with given initializer as an input.
|
| 322 |
+
"""
|
| 323 |
+
nodes = []
|
| 324 |
+
for node in graph.node:
|
| 325 |
+
for node_input in node.input:
|
| 326 |
+
if node_input == initializer.name:
|
| 327 |
+
nodes.append(node)
|
| 328 |
+
return nodes
|
| 329 |
+
|
| 330 |
+
@staticmethod
|
| 331 |
+
def __get_initializer(name, graph_path):
|
| 332 |
+
for gid in range(len(graph_path) - 1, -1, -1):
|
| 333 |
+
graph = graph_path[gid]
|
| 334 |
+
for tensor in graph.initializer:
|
| 335 |
+
if tensor.name == name:
|
| 336 |
+
return tensor, graph
|
| 337 |
+
return None, None
|
| 338 |
+
|
| 339 |
+
@staticmethod
|
| 340 |
+
def __replace_gemm_with_matmul(graph_path):
|
| 341 |
+
new_nodes = []
|
| 342 |
+
graph = graph_path[-1]
|
| 343 |
+
for node in graph.node:
|
| 344 |
+
graph_attrs = [attr for attr in node.attribute if attr.type == 5 or attr.type == 10]
|
| 345 |
+
if graph_attrs:
|
| 346 |
+
kwargs = {}
|
| 347 |
+
for attr in node.attribute:
|
| 348 |
+
if attr.type == 5:
|
| 349 |
+
graph_path.append(attr.g)
|
| 350 |
+
kv = {attr.name: ONNXModel.__replace_gemm_with_matmul(graph_path)}
|
| 351 |
+
elif attr.type == 10:
|
| 352 |
+
value = []
|
| 353 |
+
for subgraph in attr.graphs:
|
| 354 |
+
graph_path.append(subgraph)
|
| 355 |
+
value.extend([ONNXModel.__replace_gemm_with_matmul(graph_path)])
|
| 356 |
+
kv = {attr.name: value}
|
| 357 |
+
else:
|
| 358 |
+
kv = attribute_to_kwarg(attr)
|
| 359 |
+
kwargs.update(kv)
|
| 360 |
+
node = onnx_helper.make_node( # noqa: PLW2901
|
| 361 |
+
node.op_type, node.input, node.output, name=node.name, **kwargs
|
| 362 |
+
)
|
| 363 |
+
|
| 364 |
+
if node.op_type == "Gemm":
|
| 365 |
+
alpha = 1.0
|
| 366 |
+
beta = 1.0
|
| 367 |
+
transA = 0 # noqa: N806
|
| 368 |
+
transB = 0 # noqa: N806
|
| 369 |
+
for attr in node.attribute:
|
| 370 |
+
if attr.name == "alpha":
|
| 371 |
+
alpha = onnx_helper.get_attribute_value(attr)
|
| 372 |
+
elif attr.name == "beta":
|
| 373 |
+
beta = onnx_helper.get_attribute_value(attr)
|
| 374 |
+
elif attr.name == "transA":
|
| 375 |
+
transA = onnx_helper.get_attribute_value(attr) # noqa: N806
|
| 376 |
+
elif attr.name == "transB":
|
| 377 |
+
transB = onnx_helper.get_attribute_value(attr) # noqa: N806
|
| 378 |
+
if alpha == 1.0 and beta == 1.0 and transA == 0:
|
| 379 |
+
inputB = node.input[1] # noqa: N806
|
| 380 |
+
if transB == 1:
|
| 381 |
+
B, Bs_graph = ONNXModel.__get_initializer(node.input[1], graph_path) # noqa: N806
|
| 382 |
+
if B:
|
| 383 |
+
# assume B is not used by any other node
|
| 384 |
+
B_array = onnx_numpy_helper.to_array(B) # noqa: N806
|
| 385 |
+
B_trans = onnx_numpy_helper.from_array(B_array.T) # noqa: N806
|
| 386 |
+
B_trans.name = B.name
|
| 387 |
+
Bs_graph.initializer.remove(B)
|
| 388 |
+
for input in Bs_graph.input:
|
| 389 |
+
if input.name == inputB:
|
| 390 |
+
Bs_graph.input.remove(input)
|
| 391 |
+
break
|
| 392 |
+
Bs_graph.initializer.extend([B_trans])
|
| 393 |
+
else:
|
| 394 |
+
inputB += "_Transposed" # noqa: N806
|
| 395 |
+
transpose_node = onnx_helper.make_node(
|
| 396 |
+
"Transpose",
|
| 397 |
+
inputs=[node.input[1]],
|
| 398 |
+
outputs=[inputB],
|
| 399 |
+
name=node.name + "_Transpose" if node.name else "",
|
| 400 |
+
)
|
| 401 |
+
new_nodes.append(transpose_node)
|
| 402 |
+
|
| 403 |
+
matmul_node = onnx_helper.make_node(
|
| 404 |
+
"MatMul",
|
| 405 |
+
inputs=[node.input[0], inputB],
|
| 406 |
+
outputs=[node.output[0] + ("_MatMul" if len(node.input) > 2 else "")],
|
| 407 |
+
name=node.name + "_MatMul" if node.name else "",
|
| 408 |
+
)
|
| 409 |
+
new_nodes.append(matmul_node)
|
| 410 |
+
|
| 411 |
+
if len(node.input) > 2:
|
| 412 |
+
add_node = onnx_helper.make_node(
|
| 413 |
+
"Add",
|
| 414 |
+
inputs=[node.output[0] + "_MatMul", node.input[2]],
|
| 415 |
+
outputs=node.output,
|
| 416 |
+
name=node.name + "_Add" if node.name else "",
|
| 417 |
+
)
|
| 418 |
+
new_nodes.append(add_node)
|
| 419 |
+
|
| 420 |
+
# unsupported
|
| 421 |
+
else:
|
| 422 |
+
new_nodes.append(node)
|
| 423 |
+
|
| 424 |
+
# not GEMM
|
| 425 |
+
else:
|
| 426 |
+
new_nodes.append(node)
|
| 427 |
+
|
| 428 |
+
graph.ClearField("node")
|
| 429 |
+
graph.node.extend(new_nodes)
|
| 430 |
+
graph_path.pop()
|
| 431 |
+
return graph
|
| 432 |
+
|
| 433 |
+
def replace_gemm_with_matmul(self):
|
| 434 |
+
graph_path = [self.graph()]
|
| 435 |
+
ONNXModel.__replace_gemm_with_matmul(graph_path)
|
| 436 |
+
|
| 437 |
+
def save_model_to_file(self, output_path, use_external_data_format=False):
|
| 438 |
+
"""
|
| 439 |
+
Save model to external data, which is needed for model size > 2GB
|
| 440 |
+
"""
|
| 441 |
+
self.topological_sort()
|
| 442 |
+
if use_external_data_format:
|
| 443 |
+
onnx.external_data_helper.convert_model_to_external_data(
|
| 444 |
+
self.model,
|
| 445 |
+
all_tensors_to_one_file=True,
|
| 446 |
+
location=Path(output_path).name + ".data",
|
| 447 |
+
convert_attribute=True,
|
| 448 |
+
)
|
| 449 |
+
for init in self.model.graph.initializer:
|
| 450 |
+
self._check_init(init, "end")
|
| 451 |
+
onnx.save_model(self.model, output_path)
|
| 452 |
+
|
| 453 |
+
@staticmethod
|
| 454 |
+
def replace_node_input(node, old_input_name, new_input_name):
|
| 455 |
+
assert isinstance(old_input_name, str) and isinstance(new_input_name, str)
|
| 456 |
+
for j in range(len(node.input)):
|
| 457 |
+
if node.input[j] == old_input_name:
|
| 458 |
+
node.input[j] = new_input_name
|
| 459 |
+
|
| 460 |
+
def replace_input_of_all_nodes(self, old_input_name, new_input_name):
|
| 461 |
+
for node in self.model.graph.node:
|
| 462 |
+
ONNXModel.replace_node_input(node, old_input_name, new_input_name)
|
| 463 |
+
|
| 464 |
+
def replace_input_of_nodes(self, old_input_name, new_input_name, node_names_set):
|
| 465 |
+
for node in self.model.graph.node:
|
| 466 |
+
if node.name in node_names_set:
|
| 467 |
+
ONNXModel.replace_node_input(node, old_input_name, new_input_name)
|
| 468 |
+
|
| 469 |
+
@staticmethod
|
| 470 |
+
def replace_node_output(node, old_output_name, new_output_name):
|
| 471 |
+
assert isinstance(old_output_name, str) and isinstance(new_output_name, str)
|
| 472 |
+
for j in range(len(node.output)):
|
| 473 |
+
if node.output[j] == old_output_name:
|
| 474 |
+
node.output[j] = new_output_name
|
| 475 |
+
|
| 476 |
+
def replace_output_of_all_nodes(self, old_output_name, new_output_name):
|
| 477 |
+
for node in self.model.graph.node:
|
| 478 |
+
ONNXModel.replace_node_output(node, old_output_name, new_output_name)
|
| 479 |
+
|
| 480 |
+
def replace_output_of_nodes(self, old_output_name, new_output_name, node_names_set):
|
| 481 |
+
for node in self.model.graph.node:
|
| 482 |
+
if node.name in node_names_set:
|
| 483 |
+
ONNXModel.replace_node_output(node, old_output_name, new_output_name)
|
| 484 |
+
|
| 485 |
+
def remove_unused_constant(self):
|
| 486 |
+
input_name_to_nodes = self.input_name_to_nodes()
|
| 487 |
+
|
| 488 |
+
# remove unused constant
|
| 489 |
+
unused_nodes = []
|
| 490 |
+
nodes = self.nodes()
|
| 491 |
+
for node in nodes:
|
| 492 |
+
if (
|
| 493 |
+
node.op_type == "Constant"
|
| 494 |
+
and not self.is_graph_output(node.output[0])
|
| 495 |
+
and node.output[0] not in input_name_to_nodes
|
| 496 |
+
):
|
| 497 |
+
unused_nodes.append(node)
|
| 498 |
+
|
| 499 |
+
self.remove_nodes(unused_nodes)
|
| 500 |
+
|
| 501 |
+
ununsed_weights = []
|
| 502 |
+
for w in self.initializer():
|
| 503 |
+
if w.name not in input_name_to_nodes and not self.is_graph_output(w.name):
|
| 504 |
+
ununsed_weights.append(w)
|
| 505 |
+
# Remove from graph.input
|
| 506 |
+
for graph_input in self.graph().input:
|
| 507 |
+
if graph_input.name == w.name:
|
| 508 |
+
self.graph().input.remove(graph_input)
|
| 509 |
+
|
| 510 |
+
self.remove_initializers(ununsed_weights)
|
| 511 |
+
|
| 512 |
+
def is_graph_output(self, output_name):
|
| 513 |
+
return any(output.name == output_name for output in self.model.graph.output)
|
| 514 |
+
|
| 515 |
+
def is_graph_input(self, tensor_name: str) -> bool:
|
| 516 |
+
return any(input.name == tensor_name for input in self.model.graph.input)
|
| 517 |
+
|
| 518 |
+
# TODO:use OnnxModel.graph_topological_sort(self.model.graph) from transformers.onnx_model
|
| 519 |
+
# Currently it breaks Openvino/Linux training gpu pipeline so hold off for 1.8 release
|
| 520 |
+
def topological_sort(self):
|
| 521 |
+
deps_count = [0] * len(self.nodes()) # dependency count of each node
|
| 522 |
+
deps_to_nodes = {} # input to node indice
|
| 523 |
+
sorted_nodes = [] # initialize sorted_nodes
|
| 524 |
+
for node_idx, node in enumerate(self.nodes()):
|
| 525 |
+
# CANNOT use len(node.input) directly because input can be optional
|
| 526 |
+
deps_count[node_idx] = sum(1 for _ in node.input if _)
|
| 527 |
+
if deps_count[node_idx] == 0: # Constant doesn't depend on any inputs
|
| 528 |
+
sorted_nodes.append(self.nodes()[node_idx])
|
| 529 |
+
continue
|
| 530 |
+
|
| 531 |
+
for input_name in node.input:
|
| 532 |
+
if not input_name:
|
| 533 |
+
continue
|
| 534 |
+
if input_name not in deps_to_nodes:
|
| 535 |
+
deps_to_nodes[input_name] = [node_idx]
|
| 536 |
+
else:
|
| 537 |
+
deps_to_nodes[input_name].append(node_idx)
|
| 538 |
+
|
| 539 |
+
initializer_names = [init.name for init in self.initializer()]
|
| 540 |
+
graph_input_names = [input.name for input in self.model.graph.input]
|
| 541 |
+
input_names = initializer_names + graph_input_names
|
| 542 |
+
input_names.sort()
|
| 543 |
+
prev_input_name = None
|
| 544 |
+
for input_name in input_names:
|
| 545 |
+
if prev_input_name == input_name:
|
| 546 |
+
continue
|
| 547 |
+
|
| 548 |
+
prev_input_name = input_name
|
| 549 |
+
if input_name in deps_to_nodes:
|
| 550 |
+
for node_idx in deps_to_nodes[input_name]:
|
| 551 |
+
deps_count[node_idx] = deps_count[node_idx] - 1
|
| 552 |
+
if deps_count[node_idx] == 0:
|
| 553 |
+
sorted_nodes.append(self.nodes()[node_idx])
|
| 554 |
+
|
| 555 |
+
start = 0
|
| 556 |
+
end = len(sorted_nodes)
|
| 557 |
+
|
| 558 |
+
while start < end:
|
| 559 |
+
for output in sorted_nodes[start].output:
|
| 560 |
+
if output in deps_to_nodes:
|
| 561 |
+
for node_idx in deps_to_nodes[output]:
|
| 562 |
+
deps_count[node_idx] = deps_count[node_idx] - 1
|
| 563 |
+
if deps_count[node_idx] == 0:
|
| 564 |
+
sorted_nodes.append(self.nodes()[node_idx])
|
| 565 |
+
end = end + 1
|
| 566 |
+
start = start + 1
|
| 567 |
+
|
| 568 |
+
assert end == len(self.graph().node), "Graph is not a DAG"
|
| 569 |
+
self.graph().ClearField("node")
|
| 570 |
+
self.graph().node.extend(sorted_nodes)
|
| 571 |
+
|
| 572 |
+
def clean_initializers(self):
|
| 573 |
+
return _clean_initializers_helper(self.graph(), self.model)
|
| 574 |
+
|
| 575 |
+
def _check_init(self, init, test=None):
|
| 576 |
+
if init.data_type == onnx.TensorProto.FLOAT8E4M3FN:
|
| 577 |
+
if init.HasField("raw_data"):
|
| 578 |
+
b = list(init.raw_data)
|
| 579 |
+
if any((i & 127) == 127 for i in b):
|
| 580 |
+
raise ValueError(f"Initializer {init.name!r} has nan.")
|
| 581 |
+
return init
|
| 582 |
+
|
| 583 |
+
def _check_node(self, node):
|
| 584 |
+
"""
|
| 585 |
+
A quantization to float 8 does not use quantized bias but float 16 bias.
|
| 586 |
+
This function checks that DequantizeLinear is not used to
|
| 587 |
+
dequantize from float 16.
|
| 588 |
+
"""
|
| 589 |
+
if node.op_type == "DequantizeLinear":
|
| 590 |
+
zero_point = node.input[2]
|
| 591 |
+
init = self.get_initializer(zero_point)
|
| 592 |
+
dtype = init.data_type
|
| 593 |
+
if dtype in {
|
| 594 |
+
onnx.TensorProto.FLOAT16,
|
| 595 |
+
onnx.TensorProto.FLOAT,
|
| 596 |
+
onnx.TensorProto.DOUBLE,
|
| 597 |
+
onnx.TensorProto.BFLOAT16,
|
| 598 |
+
}:
|
| 599 |
+
raise RuntimeError(f"Unsupported DequantizeLinear operator, dequantization from {dtype}.")
|
| 600 |
+
return node
|
micromamba_root/envs/pytorch_env/Lib/site-packages/onnxruntime/quantization/onnx_quantizer.py
ADDED
|
@@ -0,0 +1,1163 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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|
| 3 |
+
# Licensed under the MIT License. See License.txt in the project root for
|
| 4 |
+
# license information.
|
| 5 |
+
# --------------------------------------------------------------------------
|
| 6 |
+
import logging
|
| 7 |
+
|
| 8 |
+
import numpy as np
|
| 9 |
+
import onnx
|
| 10 |
+
import onnx.numpy_helper
|
| 11 |
+
from onnx import onnx_pb as onnx_proto
|
| 12 |
+
|
| 13 |
+
from .base_quantizer import BaseQuantizer, QuantizationParams
|
| 14 |
+
from .calibrate import TensorData
|
| 15 |
+
from .onnx_model import ONNXModel
|
| 16 |
+
from .quant_utils import (
|
| 17 |
+
TENSOR_NAME_QUANT_SUFFIX,
|
| 18 |
+
QuantizationMode,
|
| 19 |
+
QuantizedValue,
|
| 20 |
+
QuantizedValueType,
|
| 21 |
+
__producer__,
|
| 22 |
+
__version__,
|
| 23 |
+
add_infer_metadata,
|
| 24 |
+
attribute_to_kwarg,
|
| 25 |
+
compute_scale_zp,
|
| 26 |
+
compute_scale_zp_float8,
|
| 27 |
+
find_by_name,
|
| 28 |
+
get_qmin_qmax_for_qType,
|
| 29 |
+
get_qrange_for_qType,
|
| 30 |
+
ms_domain,
|
| 31 |
+
quantize_onnx_initializer,
|
| 32 |
+
save_and_reload_model_with_shape_infer,
|
| 33 |
+
tensor_proto_to_array,
|
| 34 |
+
)
|
| 35 |
+
from .registry import CreateOpQuantizer
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
class ONNXQuantizer(BaseQuantizer):
|
| 39 |
+
def __init__(
|
| 40 |
+
self,
|
| 41 |
+
model,
|
| 42 |
+
per_channel,
|
| 43 |
+
reduce_range,
|
| 44 |
+
mode,
|
| 45 |
+
static,
|
| 46 |
+
weight_qType,
|
| 47 |
+
activation_qType,
|
| 48 |
+
tensors_range,
|
| 49 |
+
nodes_to_quantize,
|
| 50 |
+
nodes_to_exclude,
|
| 51 |
+
op_types_to_quantize,
|
| 52 |
+
extra_options=None,
|
| 53 |
+
):
|
| 54 |
+
BaseQuantizer.__init__(
|
| 55 |
+
self,
|
| 56 |
+
model,
|
| 57 |
+
per_channel,
|
| 58 |
+
reduce_range,
|
| 59 |
+
weight_qType,
|
| 60 |
+
activation_qType,
|
| 61 |
+
tensors_range,
|
| 62 |
+
nodes_to_quantize,
|
| 63 |
+
nodes_to_exclude,
|
| 64 |
+
op_types_to_quantize,
|
| 65 |
+
extra_options,
|
| 66 |
+
)
|
| 67 |
+
|
| 68 |
+
if not static:
|
| 69 |
+
self.model.replace_gemm_with_matmul()
|
| 70 |
+
# We need to update value_infos.
|
| 71 |
+
model = save_and_reload_model_with_shape_infer(self.model.model)
|
| 72 |
+
self.value_infos = {vi.name: vi for vi in model.graph.value_info}
|
| 73 |
+
self.value_infos.update({ot.name: ot for ot in model.graph.output})
|
| 74 |
+
self.value_infos.update({it.name: it for it in model.graph.input})
|
| 75 |
+
self.model = ONNXModel(model)
|
| 76 |
+
|
| 77 |
+
self.mode = mode # QuantizationMode.Value
|
| 78 |
+
self.static = static # use static quantization for inputs.
|
| 79 |
+
self.fuse_dynamic_quant = self.opset_version > 10
|
| 80 |
+
|
| 81 |
+
self.q_matmul_const_b_only = "MatMulConstBOnly" in self.extra_options and self.extra_options["MatMulConstBOnly"]
|
| 82 |
+
|
| 83 |
+
self.new_nodes = []
|
| 84 |
+
self.graph_scope = "/" # for human readable debug information
|
| 85 |
+
self.tensor_names = {} # in case the shape inference not totally working
|
| 86 |
+
self.tensor_names.update({ot.name: 1 for ot in model.graph.output})
|
| 87 |
+
self.tensor_names.update({it.name: 1 for it in model.graph.input})
|
| 88 |
+
for node in self.model.model.graph.node:
|
| 89 |
+
self.tensor_names.update(dict.fromkeys(node.output, 1))
|
| 90 |
+
|
| 91 |
+
if self.mode not in QuantizationMode:
|
| 92 |
+
raise ValueError(f"unsupported quantization mode {self.mode}")
|
| 93 |
+
|
| 94 |
+
self.quantization_params = self.calculate_quantization_params()
|
| 95 |
+
|
| 96 |
+
# QuantizeRange tensor name and zero tensor name for scale and zero point calculation.
|
| 97 |
+
# Used when static is False
|
| 98 |
+
self.fixed_qrange_uint8_name = "fixed_quantization_range_uint8"
|
| 99 |
+
self.fixed_qrange_int8_name = "fixed_quantization_range_int8"
|
| 100 |
+
# For uint8 data-type, to compute zero point, we subtract rmin from 0 (represented by fixed_zero_name tensor)
|
| 101 |
+
self.fixed_zero_name = "fixed_zero"
|
| 102 |
+
# For int8 data-type, zero point is always zero (respresented by fixed_zero_point_name tensor)
|
| 103 |
+
self.fixed_zero_zp_name = "fixed_zero_zp"
|
| 104 |
+
|
| 105 |
+
# Map of all original value names to quantized value names
|
| 106 |
+
self.quantized_value_map = {}
|
| 107 |
+
# some output from nodes will be quantized, yet itself should be treat as existing so
|
| 108 |
+
# no dequantized will be applied when needed later
|
| 109 |
+
self.generated_value_names = self.model.get_non_initializer_inputs()
|
| 110 |
+
|
| 111 |
+
# routines for subgraph support
|
| 112 |
+
def quantize_subgraph(self, subgraph, graph_key):
|
| 113 |
+
"""
|
| 114 |
+
generate submodel for the subgraph, so that we re-utilize current quantization implementation.
|
| 115 |
+
quantize the submodel
|
| 116 |
+
update subgraph and set it back to node
|
| 117 |
+
"""
|
| 118 |
+
warped_model = onnx.helper.make_model(
|
| 119 |
+
subgraph,
|
| 120 |
+
producer_name="onnx-quantizer",
|
| 121 |
+
opset_imports=self.model.model.opset_import,
|
| 122 |
+
)
|
| 123 |
+
add_infer_metadata(warped_model)
|
| 124 |
+
sub_quantizer = ONNXQuantizer(
|
| 125 |
+
warped_model,
|
| 126 |
+
self.per_channel,
|
| 127 |
+
self.reduce_range,
|
| 128 |
+
self.mode,
|
| 129 |
+
self.static,
|
| 130 |
+
self.weight_qType,
|
| 131 |
+
self.activation_qType,
|
| 132 |
+
self.tensors_range,
|
| 133 |
+
self.nodes_to_quantize,
|
| 134 |
+
self.nodes_to_exclude,
|
| 135 |
+
self.op_types_to_quantize,
|
| 136 |
+
self.extra_options,
|
| 137 |
+
)
|
| 138 |
+
sub_quantizer.parent = self
|
| 139 |
+
sub_quantizer.graph_scope = f"{self.graph_scope}{graph_key}/"
|
| 140 |
+
sub_quantizer.quantize_model()
|
| 141 |
+
return sub_quantizer.model.model.graph
|
| 142 |
+
|
| 143 |
+
def quantize_node_with_sub_graph(self, node):
|
| 144 |
+
"""
|
| 145 |
+
Check subgraph, if any, quantize it and replace it.
|
| 146 |
+
return new_nodes added for quantizing subgraph
|
| 147 |
+
"""
|
| 148 |
+
graph_attrs = [
|
| 149 |
+
attr
|
| 150 |
+
for attr in node.attribute
|
| 151 |
+
if attr.type == onnx.AttributeProto.GRAPH or attr.type == onnx.AttributeProto.GRAPHS
|
| 152 |
+
]
|
| 153 |
+
if len(graph_attrs) == 0:
|
| 154 |
+
return node
|
| 155 |
+
node_name = node.name if node.name else f"{node.op_type}_node_count_{len(self.new_nodes)}"
|
| 156 |
+
kwargs = {}
|
| 157 |
+
for attr in node.attribute:
|
| 158 |
+
if attr.type == onnx.AttributeProto.GRAPH:
|
| 159 |
+
kv = {attr.name: self.quantize_subgraph(attr.g, f"{node_name}:{attr.name}")}
|
| 160 |
+
elif attr.type == onnx.AttributeProto.GRAPHS:
|
| 161 |
+
value = []
|
| 162 |
+
for subgraph in attr.graphs:
|
| 163 |
+
value.extend(
|
| 164 |
+
[
|
| 165 |
+
self.quantize_subgraph(
|
| 166 |
+
subgraph,
|
| 167 |
+
f"{node_name}:{attr.name}:{len(value)}",
|
| 168 |
+
)
|
| 169 |
+
]
|
| 170 |
+
)
|
| 171 |
+
kv = {attr.name: value}
|
| 172 |
+
else:
|
| 173 |
+
kv = attribute_to_kwarg(attr)
|
| 174 |
+
kwargs.update(kv)
|
| 175 |
+
return onnx.helper.make_node(node.op_type, node.input, node.output, name=node.name, **kwargs)
|
| 176 |
+
|
| 177 |
+
def has_QDQ_nodes(self): # noqa: N802
|
| 178 |
+
"""
|
| 179 |
+
Detect if model already has QuantizeLinear or DequantizeLinear.
|
| 180 |
+
"""
|
| 181 |
+
return any(
|
| 182 |
+
node.op_type == "QuantizeLinear" or node.op_type == "DequantizeLinear" for node in self.model.nodes()
|
| 183 |
+
)
|
| 184 |
+
|
| 185 |
+
def find_initializer_in_path(self, initializer_name):
|
| 186 |
+
if find_by_name(initializer_name, self.model.initializer()) is not None:
|
| 187 |
+
return True
|
| 188 |
+
if self.parent is not None:
|
| 189 |
+
return self.parent.find_initializer_in_path(initializer_name)
|
| 190 |
+
return False
|
| 191 |
+
|
| 192 |
+
def add_new_nodes(self, nodes):
|
| 193 |
+
self.new_nodes.extend(nodes)
|
| 194 |
+
for node in nodes:
|
| 195 |
+
for output_name in node.output:
|
| 196 |
+
self.generated_value_names.add(output_name)
|
| 197 |
+
|
| 198 |
+
def quantize_model(self):
|
| 199 |
+
if self.has_QDQ_nodes():
|
| 200 |
+
logging.warning(
|
| 201 |
+
"Please check if the model is already quantized. "
|
| 202 |
+
"Note you don't need to quantize a QAT model. OnnxRuntime support to run QAT model directly."
|
| 203 |
+
)
|
| 204 |
+
|
| 205 |
+
for node in self.model.nodes():
|
| 206 |
+
# quantize subgraphes if have
|
| 207 |
+
if self.enable_subgraph_quantization:
|
| 208 |
+
node = self.quantize_node_with_sub_graph(node) # noqa: PLW2901
|
| 209 |
+
|
| 210 |
+
number_of_existing_new_nodes = len(self.new_nodes)
|
| 211 |
+
op_quantizer = CreateOpQuantizer(self, node)
|
| 212 |
+
op_quantizer.quantize()
|
| 213 |
+
for i in range(number_of_existing_new_nodes, len(self.new_nodes)):
|
| 214 |
+
for output_name in self.new_nodes[i].output:
|
| 215 |
+
self.generated_value_names.add(output_name)
|
| 216 |
+
|
| 217 |
+
self._dequantize_outputs()
|
| 218 |
+
|
| 219 |
+
# extend is used to append to the list for a protobuf fields
|
| 220 |
+
# https://developers.google.com/protocol-buffers/docs/reference/python-generated?csw=1#fields
|
| 221 |
+
self.model.graph().ClearField("node")
|
| 222 |
+
self.model.graph().node.extend(self.new_nodes)
|
| 223 |
+
|
| 224 |
+
# Remove ununsed initializers from graph, starting from the top level graph.
|
| 225 |
+
if self.parent is None:
|
| 226 |
+
_, initializers_not_found = self.model.clean_initializers()
|
| 227 |
+
if len(initializers_not_found) > 0:
|
| 228 |
+
raise RuntimeError("Invalid model with unknown initializers/tensors." + str(initializers_not_found))
|
| 229 |
+
|
| 230 |
+
self.model.model.producer_name = __producer__
|
| 231 |
+
self.model.model.producer_version = __version__
|
| 232 |
+
# Add ms domain if needed
|
| 233 |
+
ms_opset = [opset for opset in self.model.model.opset_import if opset.domain == ms_domain]
|
| 234 |
+
if not ms_opset:
|
| 235 |
+
ms_nodes = [node for node in self.new_nodes if node.domain == "com.microsoft"]
|
| 236 |
+
if ms_nodes:
|
| 237 |
+
opset = self.model.model.opset_import.add()
|
| 238 |
+
opset.version = 1
|
| 239 |
+
opset.domain = ms_domain
|
| 240 |
+
|
| 241 |
+
return self.model.model
|
| 242 |
+
|
| 243 |
+
def _get_default_tensor_type(self, tensor_name):
|
| 244 |
+
if "DefaultTensorType" in self.extra_options:
|
| 245 |
+
logging.info(
|
| 246 |
+
"get_tensor_type returns DefaultTensorType for tensor name %r, use %d",
|
| 247 |
+
tensor_name,
|
| 248 |
+
self.extra_options["DefaultTensorType"],
|
| 249 |
+
)
|
| 250 |
+
return self.extra_options["DefaultTensorType"]
|
| 251 |
+
raise RuntimeError(
|
| 252 |
+
f"Unable to find data type for weight_name={tensor_name!r}. "
|
| 253 |
+
f"shape_inference failed to return a type probably this node is "
|
| 254 |
+
f"from a different domain or using an input produced by such an operator. "
|
| 255 |
+
f"This may happen if you quantize a model already quantized. "
|
| 256 |
+
f"You may use extra_options `DefaultTensorType` to indicate "
|
| 257 |
+
f"the default weight type, usually `onnx.TensorProto.FLOAT`."
|
| 258 |
+
)
|
| 259 |
+
|
| 260 |
+
def get_tensor_type(self, tensor_name, mandatory=False):
|
| 261 |
+
weight = find_by_name(tensor_name, self.model.initializer())
|
| 262 |
+
if weight is not None:
|
| 263 |
+
return weight.data_type
|
| 264 |
+
if tensor_name in self.value_infos:
|
| 265 |
+
vi = self.value_infos[tensor_name]
|
| 266 |
+
if vi.type.HasField("tensor_type"):
|
| 267 |
+
if mandatory and vi.type.tensor_type.elem_type == 0:
|
| 268 |
+
return self._get_default_tensor_type(tensor_name)
|
| 269 |
+
return vi.type.tensor_type.elem_type
|
| 270 |
+
if (not self.enable_subgraph_quantization) or (self.parent is None):
|
| 271 |
+
if mandatory:
|
| 272 |
+
return self._get_default_tensor_type(tensor_name)
|
| 273 |
+
return None
|
| 274 |
+
otype = self.parent.is_valid_quantize_weight(tensor_name)
|
| 275 |
+
if otype is not None:
|
| 276 |
+
return otype
|
| 277 |
+
if self.enable_subgraph_quantization and self.parent:
|
| 278 |
+
res = self.parent.get_tensor_type(tensor_name)
|
| 279 |
+
if res is not None:
|
| 280 |
+
return res
|
| 281 |
+
if mandatory:
|
| 282 |
+
return self._get_default_tensor_type(tensor_name)
|
| 283 |
+
return None
|
| 284 |
+
|
| 285 |
+
def is_float_tensor(self, tensor_name):
|
| 286 |
+
if self.is_input_a_initializer(tensor_name):
|
| 287 |
+
return self.is_valid_quantize_weight(tensor_name)
|
| 288 |
+
|
| 289 |
+
if tensor_name in self.value_infos:
|
| 290 |
+
vi = self.value_infos[tensor_name]
|
| 291 |
+
if vi.type.HasField("tensor_type") and vi.type.tensor_type.elem_type in (
|
| 292 |
+
onnx_proto.TensorProto.FLOAT,
|
| 293 |
+
onnx_proto.TensorProto.FLOAT16,
|
| 294 |
+
):
|
| 295 |
+
return True
|
| 296 |
+
logging.warning(
|
| 297 |
+
f"Inference failed or unsupported type to quantize for tensor {tensor_name!r}, type is {vi.type}."
|
| 298 |
+
)
|
| 299 |
+
return False
|
| 300 |
+
|
| 301 |
+
if self.enable_subgraph_quantization and self.parent:
|
| 302 |
+
return self.parent.is_float_tensor(tensor_name)
|
| 303 |
+
|
| 304 |
+
logging.warning(
|
| 305 |
+
f"Failed to infer data type of tensor: {tensor_name!r}. Please add data type info for this tensor "
|
| 306 |
+
f"if your model has customized operators."
|
| 307 |
+
)
|
| 308 |
+
return False
|
| 309 |
+
|
| 310 |
+
def _get_dynamic_input_quantization_params(self, input_name, nodes_list, qType, initial_type):
|
| 311 |
+
"""
|
| 312 |
+
Create nodes for dynamic quantization of input and add them to nodes_list.
|
| 313 |
+
parameter input_name: Name of the input.
|
| 314 |
+
parameter nodes_list: new nodes are appended to this list.
|
| 315 |
+
parameter qType: type to quantize to.
|
| 316 |
+
parameter initial_type: type to quantize from
|
| 317 |
+
return: scale_name, zero_point_name, scale_shape, zero_point_shape.
|
| 318 |
+
"""
|
| 319 |
+
if qType == onnx_proto.TensorProto.INT8:
|
| 320 |
+
return self._get_dynamic_input_quantization_params_int8(input_name, nodes_list, initial_type)
|
| 321 |
+
if qType == onnx_proto.TensorProto.UINT8:
|
| 322 |
+
return self._get_dynamic_input_quantization_params_uint8(input_name, nodes_list, initial_type)
|
| 323 |
+
raise ValueError(f"Unexpected value for qType={qType}.")
|
| 324 |
+
|
| 325 |
+
def _get_dynamic_input_quantization_params_int8(self, input_name, nodes_list, initial_type):
|
| 326 |
+
"""
|
| 327 |
+
Create nodes for dynamic quantization of input to int8 and add them to nodes_list
|
| 328 |
+
parameter input_name: Name of the input.
|
| 329 |
+
parameter nodes_list: new nodes are appended to this list.
|
| 330 |
+
parameter initial_type: initial weight type (FLOAT or FLOAT16)
|
| 331 |
+
return: scale_name, zero_point_name, scale_shape, zero_point_shape.
|
| 332 |
+
"""
|
| 333 |
+
qType = onnx_proto.TensorProto.INT8 # noqa: N806
|
| 334 |
+
|
| 335 |
+
# Reduce min and Reduce max
|
| 336 |
+
input_scale_name = input_name + "_scale"
|
| 337 |
+
|
| 338 |
+
reduce_min_name = input_name + "_ReduceMin"
|
| 339 |
+
reduce_min_node = onnx.helper.make_node(
|
| 340 |
+
"ReduceMin",
|
| 341 |
+
[input_name],
|
| 342 |
+
[reduce_min_name + ":0"],
|
| 343 |
+
reduce_min_name,
|
| 344 |
+
keepdims=0,
|
| 345 |
+
)
|
| 346 |
+
nodes_list.append(reduce_min_node)
|
| 347 |
+
|
| 348 |
+
reduce_max_name = input_name + "_ReduceMax"
|
| 349 |
+
reduce_max_node = onnx.helper.make_node(
|
| 350 |
+
"ReduceMax",
|
| 351 |
+
[input_name],
|
| 352 |
+
[reduce_max_name + ":0"],
|
| 353 |
+
reduce_max_name,
|
| 354 |
+
keepdims=0,
|
| 355 |
+
)
|
| 356 |
+
nodes_list.append(reduce_max_node)
|
| 357 |
+
|
| 358 |
+
# Compute scale
|
| 359 |
+
# Find abs(rmin)
|
| 360 |
+
reduce_min_abs_name = reduce_min_name + "_Abs"
|
| 361 |
+
reduce_min_abs_node = onnx.helper.make_node(
|
| 362 |
+
"Abs",
|
| 363 |
+
[reduce_min_node.output[0]],
|
| 364 |
+
[reduce_min_abs_name + ":0"],
|
| 365 |
+
reduce_min_abs_name,
|
| 366 |
+
)
|
| 367 |
+
nodes_list.append(reduce_min_abs_node)
|
| 368 |
+
# Find abs(rmax)
|
| 369 |
+
reduce_max_abs_name = reduce_max_name + "_Abs"
|
| 370 |
+
reduce_max_abs_node = onnx.helper.make_node(
|
| 371 |
+
"Abs",
|
| 372 |
+
[reduce_max_node.output[0]],
|
| 373 |
+
[reduce_max_abs_name + ":0"],
|
| 374 |
+
reduce_max_abs_name,
|
| 375 |
+
)
|
| 376 |
+
nodes_list.append(reduce_max_abs_node)
|
| 377 |
+
# Compute max of abs(rmin) and abs(rmax)
|
| 378 |
+
abs_max_name = input_name + "_Abs_Max"
|
| 379 |
+
abs_max_node = onnx.helper.make_node(
|
| 380 |
+
"Max",
|
| 381 |
+
[reduce_min_abs_node.output[0], reduce_max_abs_node.output[0]],
|
| 382 |
+
[abs_max_name + ":0"],
|
| 383 |
+
abs_max_name,
|
| 384 |
+
)
|
| 385 |
+
nodes_list.append(abs_max_node)
|
| 386 |
+
# and divide by (quantize_range/2.0) which will be equal to max(...)*2.0/quantize_range
|
| 387 |
+
initializer_div = onnx.helper.make_tensor(
|
| 388 |
+
self.fixed_qrange_int8_name,
|
| 389 |
+
initial_type,
|
| 390 |
+
[],
|
| 391 |
+
[get_qrange_for_qType(qType) / 2.0],
|
| 392 |
+
)
|
| 393 |
+
self.model.add_initializer(initializer_div)
|
| 394 |
+
scale_div_name = input_name + "scale_Div"
|
| 395 |
+
scale_div_node = onnx.helper.make_node(
|
| 396 |
+
"Div",
|
| 397 |
+
[abs_max_node.output[0], self.fixed_qrange_int8_name],
|
| 398 |
+
[input_scale_name],
|
| 399 |
+
scale_div_name,
|
| 400 |
+
)
|
| 401 |
+
nodes_list.append(scale_div_node)
|
| 402 |
+
|
| 403 |
+
# Zero point
|
| 404 |
+
initializer_zp = onnx.helper.make_tensor(self.fixed_zero_zp_name, qType, [], [0])
|
| 405 |
+
self.model.add_initializer(initializer_zp)
|
| 406 |
+
|
| 407 |
+
return input_scale_name, self.fixed_zero_zp_name, [], []
|
| 408 |
+
|
| 409 |
+
def _get_dynamic_input_quantization_params_uint8(self, input_name, nodes_list, initial_type):
|
| 410 |
+
"""
|
| 411 |
+
Create nodes for dynamic quantization of input to uint8 and add them to nodes_list
|
| 412 |
+
parameter input_name: Name of the input.
|
| 413 |
+
parameter nodes_list: new nodes are appended to this list.
|
| 414 |
+
parameter initial_type: initial weight type (FLAOT or FLOAT16)
|
| 415 |
+
return: scale_name, zero_point_name, scale_shape, zero_point_shape.
|
| 416 |
+
"""
|
| 417 |
+
qType = onnx_proto.TensorProto.UINT8 # noqa: N806
|
| 418 |
+
# Reduce min and Reduce max
|
| 419 |
+
input_scale_name = input_name + "_scale"
|
| 420 |
+
input_zp_name = input_name + "_zero_point"
|
| 421 |
+
|
| 422 |
+
reduce_min_name = input_name + "_ReduceMin"
|
| 423 |
+
reduce_min_node = onnx.helper.make_node(
|
| 424 |
+
"ReduceMin",
|
| 425 |
+
[input_name],
|
| 426 |
+
[reduce_min_name + ":0"],
|
| 427 |
+
reduce_min_name,
|
| 428 |
+
keepdims=0,
|
| 429 |
+
)
|
| 430 |
+
nodes_list.append(reduce_min_node)
|
| 431 |
+
|
| 432 |
+
reduce_max_name = input_name + "_ReduceMax"
|
| 433 |
+
reduce_max_node = onnx.helper.make_node(
|
| 434 |
+
"ReduceMax",
|
| 435 |
+
[input_name],
|
| 436 |
+
[reduce_max_name + ":0"],
|
| 437 |
+
reduce_max_name,
|
| 438 |
+
keepdims=0,
|
| 439 |
+
)
|
| 440 |
+
nodes_list.append(reduce_max_node)
|
| 441 |
+
|
| 442 |
+
# Add tensors for quantize range and zero value.
|
| 443 |
+
initializer_qrange = onnx.helper.make_tensor(
|
| 444 |
+
self.fixed_qrange_uint8_name,
|
| 445 |
+
initial_type,
|
| 446 |
+
[],
|
| 447 |
+
[get_qrange_for_qType(qType)],
|
| 448 |
+
)
|
| 449 |
+
self.model.add_initializer(initializer_qrange)
|
| 450 |
+
initializer_qvalue = onnx.helper.make_tensor(self.fixed_zero_name, initial_type, [], [0.0])
|
| 451 |
+
self.model.add_initializer(initializer_qvalue)
|
| 452 |
+
|
| 453 |
+
# Compute Scale
|
| 454 |
+
# Subtract rmax and rmin
|
| 455 |
+
scale_sub_name = input_name + "_scale_Sub"
|
| 456 |
+
scale_sub_node = onnx.helper.make_node(
|
| 457 |
+
"Sub",
|
| 458 |
+
[reduce_max_node.output[0], reduce_min_node.output[0]],
|
| 459 |
+
[scale_sub_name + ":0"],
|
| 460 |
+
scale_sub_name,
|
| 461 |
+
)
|
| 462 |
+
nodes_list.append(scale_sub_node)
|
| 463 |
+
# and divide by quantize range
|
| 464 |
+
scale_div_name = input_name + "_scale_Div"
|
| 465 |
+
scale_div_node = onnx.helper.make_node(
|
| 466 |
+
"Div",
|
| 467 |
+
[scale_sub_node.output[0], self.fixed_qrange_uint8_name],
|
| 468 |
+
[input_scale_name],
|
| 469 |
+
scale_div_name,
|
| 470 |
+
)
|
| 471 |
+
nodes_list.append(scale_div_node)
|
| 472 |
+
|
| 473 |
+
# Compute zero point
|
| 474 |
+
# Subtract zero and rmin
|
| 475 |
+
zp_sub_name = input_name + "_zero_point_Sub"
|
| 476 |
+
zp_sub_node = onnx.helper.make_node(
|
| 477 |
+
"Sub",
|
| 478 |
+
[self.fixed_zero_name, reduce_min_node.output[0]],
|
| 479 |
+
[zp_sub_name + ":0"],
|
| 480 |
+
zp_sub_name,
|
| 481 |
+
)
|
| 482 |
+
nodes_list.append(zp_sub_node)
|
| 483 |
+
# Divide by scale
|
| 484 |
+
zp_div_name = input_name + "_zero_point_Div"
|
| 485 |
+
zp_div_node = onnx.helper.make_node(
|
| 486 |
+
"Div",
|
| 487 |
+
[zp_sub_node.output[0], input_scale_name],
|
| 488 |
+
[zp_div_name + ":0"],
|
| 489 |
+
zp_div_name,
|
| 490 |
+
)
|
| 491 |
+
nodes_list.append(zp_div_node)
|
| 492 |
+
# Compute floor
|
| 493 |
+
zp_floor_name = input_name + "_zero_point_Floor"
|
| 494 |
+
zp_floor_node = onnx.helper.make_node("Floor", zp_div_node.output, [zp_floor_name + ":0"], zp_floor_name)
|
| 495 |
+
nodes_list.append(zp_floor_node)
|
| 496 |
+
# Cast to integer
|
| 497 |
+
zp_cast_name = input_name + "_zero_point_Cast"
|
| 498 |
+
zp_cast_node = onnx.helper.make_node("Cast", zp_floor_node.output, [input_zp_name], zp_cast_name, to=qType)
|
| 499 |
+
nodes_list.append(zp_cast_node)
|
| 500 |
+
|
| 501 |
+
return input_scale_name, input_zp_name, [], []
|
| 502 |
+
|
| 503 |
+
def _get_quantization_params(self, param_name, use_scale=None, use_zeropoint=None):
|
| 504 |
+
"""
|
| 505 |
+
Create initializers and inputs in the graph for zero point and scale of output.
|
| 506 |
+
Zero point and scale values are obtained from self.quantization_params if specified.
|
| 507 |
+
parameter param_name: Name of the quantization parameter.
|
| 508 |
+
return: result, scale_name, zero_point_name, scale_shape, zero_point_shape.
|
| 509 |
+
"""
|
| 510 |
+
zero_point_type = self.activation_qType
|
| 511 |
+
|
| 512 |
+
if use_scale is None or use_zeropoint is None:
|
| 513 |
+
if self.quantization_params is None or param_name not in self.quantization_params:
|
| 514 |
+
logging.info(f'Quantization parameters for tensor:"{param_name}" not specified')
|
| 515 |
+
return False, "", "", "", ""
|
| 516 |
+
|
| 517 |
+
params = self.quantization_params[param_name]
|
| 518 |
+
if not isinstance(params, QuantizationParams):
|
| 519 |
+
raise TypeError(f"Unexpected type {type(params)} for {param_name!r}.")
|
| 520 |
+
if params is None or len(params) != 3:
|
| 521 |
+
raise ValueError(
|
| 522 |
+
"Quantization parameters should contain zero point, scale, quant type. "
|
| 523 |
+
f"Specified values for output {param_name}: {params}"
|
| 524 |
+
)
|
| 525 |
+
|
| 526 |
+
zero_point_values = np.array([params["zero_point"]])
|
| 527 |
+
if not hasattr(params["scale"], "dtype") or params["scale"].dtype not in (np.float32, np.float16):
|
| 528 |
+
raise ValueError(f"Unexpected type {type(params['scale'])} and param_name={param_name!r}")
|
| 529 |
+
scale_values = np.array([params["scale"]])
|
| 530 |
+
assert scale_values.dtype != np.float64
|
| 531 |
+
zero_point_type = params["quant_type"]
|
| 532 |
+
else:
|
| 533 |
+
zero_point_values = np.array([use_zeropoint])
|
| 534 |
+
scale_values = np.array([use_scale])
|
| 535 |
+
params = self.quantization_params[param_name]
|
| 536 |
+
if "scale" in params:
|
| 537 |
+
dtype = params["scale"].dtype
|
| 538 |
+
scale_values = scale_values.astype(dtype)
|
| 539 |
+
assert scale_values.dtype != np.float64
|
| 540 |
+
|
| 541 |
+
zero_point_shape = []
|
| 542 |
+
zero_point_name = param_name + "_zero_point"
|
| 543 |
+
scale_shape = []
|
| 544 |
+
scale_name = param_name + "_scale"
|
| 545 |
+
|
| 546 |
+
# Add initializers
|
| 547 |
+
init_zp = onnx.helper.make_tensor(
|
| 548 |
+
zero_point_name, zero_point_type, zero_point_shape, zero_point_values.ravel().tolist()
|
| 549 |
+
)
|
| 550 |
+
self.model.add_initializer(init_zp)
|
| 551 |
+
if scale_values.dtype == np.float32:
|
| 552 |
+
scale_type = onnx_proto.TensorProto.FLOAT
|
| 553 |
+
elif scale_values.dtype == np.float16:
|
| 554 |
+
scale_type = onnx_proto.TensorProto.FLOAT16
|
| 555 |
+
else:
|
| 556 |
+
raise ValueError(f"Unexpected dtype={scale_values.dtype} for param_name={param_name!r}")
|
| 557 |
+
init_scale = onnx.helper.make_tensor(scale_name, scale_type, scale_shape, scale_values.reshape((-1,)).tolist())
|
| 558 |
+
self.model.add_initializer(init_scale)
|
| 559 |
+
|
| 560 |
+
return True, scale_name, zero_point_name, scale_shape, zero_point_shape
|
| 561 |
+
|
| 562 |
+
def _get_quantize_input_nodes(
|
| 563 |
+
self, node, input_index, qType, given_scale_name=None, given_zp_name=None, initial_type=None
|
| 564 |
+
):
|
| 565 |
+
"""
|
| 566 |
+
Given an input for a node (which is not a initializer), this function
|
| 567 |
+
|
| 568 |
+
- add nodes to compute zero point and scale for this input if they don't exist.
|
| 569 |
+
- add new QuantizeLinear node to quantize the input.
|
| 570 |
+
|
| 571 |
+
:param node: node being quantized in NodeProto format.
|
| 572 |
+
:param input_index: index of input in node.input.
|
| 573 |
+
:param qType: type to quantize to.
|
| 574 |
+
:param given_scale_name: if those inputs need to be quanitzed using this scale tensor.
|
| 575 |
+
:param given_zp_name: if those inputs to be quantized using this zeropoint tensor.
|
| 576 |
+
:param initial_type: type of the weight to quantize
|
| 577 |
+
:return: List of newly created nodes in NodeProto format.
|
| 578 |
+
"""
|
| 579 |
+
input_name = node.input[input_index]
|
| 580 |
+
assert input_name != "", "Cannot access undefined variable in graph."
|
| 581 |
+
output_name = input_name + TENSOR_NAME_QUANT_SUFFIX
|
| 582 |
+
ql_node_name = input_name + "_QuantizeLinear"
|
| 583 |
+
|
| 584 |
+
if (given_scale_name is not None) and (given_zp_name is not None):
|
| 585 |
+
data_found, scale_name, zp_name = (True, given_scale_name, given_zp_name)
|
| 586 |
+
else:
|
| 587 |
+
data_found, scale_name, zp_name, _, _ = self._get_quantization_params(input_name)
|
| 588 |
+
|
| 589 |
+
nodes = []
|
| 590 |
+
if data_found:
|
| 591 |
+
qlinear_node = onnx.helper.make_node(
|
| 592 |
+
"QuantizeLinear",
|
| 593 |
+
[input_name, scale_name, zp_name],
|
| 594 |
+
[output_name],
|
| 595 |
+
ql_node_name,
|
| 596 |
+
)
|
| 597 |
+
else:
|
| 598 |
+
if self.static:
|
| 599 |
+
return None
|
| 600 |
+
# dynamic mode
|
| 601 |
+
# Scale and Zero Points not available for this input. Add nodes to dynamically compute it
|
| 602 |
+
if self.fuse_dynamic_quant and qType == onnx_proto.TensorProto.UINT8:
|
| 603 |
+
scale_name = input_name + "_scale"
|
| 604 |
+
zp_name = input_name + "_zero_point"
|
| 605 |
+
qlinear_node = onnx.helper.make_node(
|
| 606 |
+
"DynamicQuantizeLinear",
|
| 607 |
+
[input_name],
|
| 608 |
+
[output_name, scale_name, zp_name],
|
| 609 |
+
ql_node_name,
|
| 610 |
+
)
|
| 611 |
+
else:
|
| 612 |
+
assert initial_type is not None, (
|
| 613 |
+
f"Cannot quantize input without knowing the initial type, "
|
| 614 |
+
f"input_name={input_name!r}, input_index={input_index}, qType={qType}, node={node}"
|
| 615 |
+
)
|
| 616 |
+
(
|
| 617 |
+
scale_name,
|
| 618 |
+
zp_name,
|
| 619 |
+
scale_shape,
|
| 620 |
+
zp_shape,
|
| 621 |
+
) = self._get_dynamic_input_quantization_params(input_name, nodes, qType, initial_type=initial_type)
|
| 622 |
+
qlinear_node = onnx.helper.make_node(
|
| 623 |
+
"QuantizeLinear",
|
| 624 |
+
[input_name, scale_name, zp_name],
|
| 625 |
+
[output_name],
|
| 626 |
+
ql_node_name,
|
| 627 |
+
)
|
| 628 |
+
|
| 629 |
+
self.quantized_value_map[input_name] = QuantizedValue(input_name, output_name, scale_name, zp_name, qType)
|
| 630 |
+
return [*nodes, qlinear_node]
|
| 631 |
+
|
| 632 |
+
def find_quantized_value(self, input_name):
|
| 633 |
+
if input_name in self.quantized_value_map:
|
| 634 |
+
return self.quantized_value_map[input_name]
|
| 635 |
+
if self.parent is not None:
|
| 636 |
+
return self.parent.find_quantized_value(input_name)
|
| 637 |
+
return None
|
| 638 |
+
|
| 639 |
+
def adjust_single_weight_scale_if_needed(
|
| 640 |
+
self,
|
| 641 |
+
bias_val,
|
| 642 |
+
input_scale,
|
| 643 |
+
weight_scale,
|
| 644 |
+
weight_scale_dtype,
|
| 645 |
+
weight_name,
|
| 646 |
+
bias_name,
|
| 647 |
+
qrange,
|
| 648 |
+
multiplicative_epsilon,
|
| 649 |
+
idx=None,
|
| 650 |
+
):
|
| 651 |
+
"""Adjust a single weight scale to ensure the int32 bias does not overflow."""
|
| 652 |
+
absmax = np.abs(bias_val)
|
| 653 |
+
bias_smallest_valid_scale = multiplicative_epsilon * (2.0 * absmax) / qrange
|
| 654 |
+
|
| 655 |
+
input_scale_fp64 = np.array(input_scale.item(), dtype=np.float64)
|
| 656 |
+
weight_scale_fp64 = np.array(weight_scale.item(), dtype=np.float64)
|
| 657 |
+
bias_candidate_scale = input_scale_fp64 * weight_scale_fp64
|
| 658 |
+
|
| 659 |
+
if (bias_candidate_scale < bias_smallest_valid_scale) and (bias_candidate_scale > 0.0):
|
| 660 |
+
ratio = bias_smallest_valid_scale / bias_candidate_scale
|
| 661 |
+
new_scale = weight_scale_fp64 * ratio
|
| 662 |
+
if idx is None:
|
| 663 |
+
logging.info(
|
| 664 |
+
f"Increasing scale for weight `{weight_name}` by the ratio {ratio} to "
|
| 665 |
+
f"ensure bias `{bias_name}` has a valid scale."
|
| 666 |
+
)
|
| 667 |
+
return True, np.array(new_scale, dtype=weight_scale_dtype)
|
| 668 |
+
else:
|
| 669 |
+
logging.info(
|
| 670 |
+
f"Increased scale[{idx}] for weight `{weight_name}` by ratio {ratio} "
|
| 671 |
+
f"to ensure bias `{bias_name}` has a valid scale."
|
| 672 |
+
)
|
| 673 |
+
return True, new_scale.astype(weight_scale_dtype)
|
| 674 |
+
return False, weight_scale
|
| 675 |
+
|
| 676 |
+
def _adjust_weight_scale_for_int32_bias(
|
| 677 |
+
self,
|
| 678 |
+
input_scale: np.ndarray,
|
| 679 |
+
weight_scale: np.ndarray,
|
| 680 |
+
weight_name: str,
|
| 681 |
+
bias_tp: onnx.TensorProto,
|
| 682 |
+
is_per_channel: bool,
|
| 683 |
+
) -> tuple[bool, np.ndarray | None]:
|
| 684 |
+
"""Checks if the bias scale is too small and increases the weight scale if needed."""
|
| 685 |
+
|
| 686 |
+
if not weight_scale.size:
|
| 687 |
+
return False, None
|
| 688 |
+
|
| 689 |
+
bias_float_data = tensor_proto_to_array(bias_tp)
|
| 690 |
+
int32_info = np.iinfo(np.int32)
|
| 691 |
+
multiplicative_epsilon = 1.0001
|
| 692 |
+
qrange = np.array(int32_info.max, dtype=np.float64) - np.array(int32_info.min + 1, dtype=np.float64)
|
| 693 |
+
weight_scale_dtype = weight_scale.dtype
|
| 694 |
+
updated = False
|
| 695 |
+
|
| 696 |
+
if not is_per_channel:
|
| 697 |
+
rmin = np.minimum(bias_float_data.min(), np.array(0, dtype=np.float64))
|
| 698 |
+
rmax = np.maximum(bias_float_data.max(), np.array(0, dtype=np.float64))
|
| 699 |
+
absmax = np.maximum(np.abs(rmin), np.abs(rmax))
|
| 700 |
+
changed, new_scale = self.adjust_single_weight_scale_if_needed(
|
| 701 |
+
absmax,
|
| 702 |
+
input_scale,
|
| 703 |
+
weight_scale,
|
| 704 |
+
weight_scale_dtype,
|
| 705 |
+
weight_name,
|
| 706 |
+
bias_tp.name,
|
| 707 |
+
qrange,
|
| 708 |
+
multiplicative_epsilon,
|
| 709 |
+
)
|
| 710 |
+
if changed:
|
| 711 |
+
weight_scale = new_scale
|
| 712 |
+
updated = True
|
| 713 |
+
elif weight_scale.shape and len(weight_scale.shape) == 1:
|
| 714 |
+
for i in range(weight_scale.shape[0]):
|
| 715 |
+
changed, new_scale = self.adjust_single_weight_scale_if_needed(
|
| 716 |
+
bias_float_data[i],
|
| 717 |
+
input_scale,
|
| 718 |
+
weight_scale[i],
|
| 719 |
+
weight_scale_dtype,
|
| 720 |
+
weight_name,
|
| 721 |
+
bias_tp.name,
|
| 722 |
+
qrange,
|
| 723 |
+
multiplicative_epsilon,
|
| 724 |
+
idx=i,
|
| 725 |
+
)
|
| 726 |
+
if changed:
|
| 727 |
+
weight_scale[i] = new_scale
|
| 728 |
+
updated = True
|
| 729 |
+
|
| 730 |
+
return updated, weight_scale
|
| 731 |
+
|
| 732 |
+
def _requantize_weight(self, weight_name: str, new_scale: np.ndarray) -> None:
|
| 733 |
+
"""Re-quantizes the given weight initializer using the provided scale."""
|
| 734 |
+
|
| 735 |
+
if weight_name not in self.quantized_value_map:
|
| 736 |
+
return
|
| 737 |
+
|
| 738 |
+
qv = self.quantized_value_map[weight_name]
|
| 739 |
+
|
| 740 |
+
weight_tp = find_by_name(weight_name, self.model.initializer())
|
| 741 |
+
scale_init = find_by_name(qv.scale_name, self.model.initializer())
|
| 742 |
+
zp_init = find_by_name(qv.zp_name, self.model.initializer())
|
| 743 |
+
q_weight_init = find_by_name(qv.q_name, self.model.initializer())
|
| 744 |
+
|
| 745 |
+
if weight_tp is None or scale_init is None or zp_init is None or q_weight_init is None:
|
| 746 |
+
return
|
| 747 |
+
|
| 748 |
+
self.model.remove_initializer(scale_init)
|
| 749 |
+
self.model.remove_initializer(q_weight_init)
|
| 750 |
+
|
| 751 |
+
weight_zero_point = onnx.numpy_helper.to_array(zp_init)
|
| 752 |
+
axis = qv.axis
|
| 753 |
+
|
| 754 |
+
# Add new scale initializer
|
| 755 |
+
scale_np = np.asarray(new_scale, dtype=onnx.helper.tensor_dtype_to_np_dtype(weight_tp.data_type))
|
| 756 |
+
new_scale_init = onnx.numpy_helper.from_array(scale_np.reshape(scale_init.dims), qv.scale_name)
|
| 757 |
+
self.model.add_initializer(new_scale_init)
|
| 758 |
+
|
| 759 |
+
# Add new quantized weight initializer
|
| 760 |
+
new_q_weight = quantize_onnx_initializer(
|
| 761 |
+
weight_tp,
|
| 762 |
+
self.weight_qType,
|
| 763 |
+
weight_zero_point,
|
| 764 |
+
scale_np,
|
| 765 |
+
axis,
|
| 766 |
+
quant_weight_name=qv.q_name,
|
| 767 |
+
)
|
| 768 |
+
self.model.add_initializer(new_q_weight)
|
| 769 |
+
|
| 770 |
+
def quantize_bias_static(self, bias_name, input_name, weight_name, beta=1.0):
|
| 771 |
+
"""
|
| 772 |
+
Quantized the bias. Zero Point == 0 and Scale == Input_Scale * Weight_Scale
|
| 773 |
+
"""
|
| 774 |
+
|
| 775 |
+
# Handle case where bias already in quantization map
|
| 776 |
+
if bias_name in self.quantized_value_map:
|
| 777 |
+
return self.quantized_value_map[bias_name].q_name
|
| 778 |
+
|
| 779 |
+
# get scale for weight
|
| 780 |
+
weight_scale_name = self.quantized_value_map[weight_name].scale_name
|
| 781 |
+
weight_initializer = find_by_name(weight_scale_name, self.model.initializer())
|
| 782 |
+
weight_scale = tensor_proto_to_array(weight_initializer)
|
| 783 |
+
|
| 784 |
+
# get scale for input
|
| 785 |
+
if input_name in self.quantized_value_map:
|
| 786 |
+
input_scale_name = self.quantized_value_map[input_name].scale_name
|
| 787 |
+
elif input_name in self.quantization_params:
|
| 788 |
+
_, input_scale_name, _, _, _ = self._get_quantization_params(input_name)
|
| 789 |
+
else:
|
| 790 |
+
raise ValueError(f"Expected {input_name} to be in quantized value map for static quantization")
|
| 791 |
+
|
| 792 |
+
inputscale_initializer = find_by_name(input_scale_name, self.model.initializer())
|
| 793 |
+
input_scale = tensor_proto_to_array(inputscale_initializer)
|
| 794 |
+
|
| 795 |
+
# Adjust weight scale if quantizing to int32 may overflow due to a small scale
|
| 796 |
+
weight_zp_name = self.quantized_value_map[weight_name].zp_name
|
| 797 |
+
weight_zp_init = find_by_name(weight_zp_name, self.model.initializer())
|
| 798 |
+
weight_zero_point = onnx.numpy_helper.to_array(weight_zp_init) if weight_zp_init is not None else None
|
| 799 |
+
is_per_channel = self.per_channel
|
| 800 |
+
if (
|
| 801 |
+
weight_zero_point is not None
|
| 802 |
+
and weight_zero_point.size
|
| 803 |
+
and not weight_zero_point.any()
|
| 804 |
+
and self.weight_qType in (onnx_proto.TensorProto.INT8,)
|
| 805 |
+
):
|
| 806 |
+
bias_initializer = find_by_name(bias_name, self.model.initializer())
|
| 807 |
+
did_update, new_weight_scale = self._adjust_weight_scale_for_int32_bias(
|
| 808 |
+
input_scale,
|
| 809 |
+
weight_scale,
|
| 810 |
+
weight_name,
|
| 811 |
+
bias_initializer,
|
| 812 |
+
is_per_channel,
|
| 813 |
+
)
|
| 814 |
+
if did_update:
|
| 815 |
+
self._requantize_weight(weight_name, new_weight_scale)
|
| 816 |
+
weight_scale = new_weight_scale
|
| 817 |
+
|
| 818 |
+
(
|
| 819 |
+
quantized_bias_name,
|
| 820 |
+
quantized_bias_scale_name,
|
| 821 |
+
quantized_bias_zp_name,
|
| 822 |
+
bias_scale_data,
|
| 823 |
+
node_type,
|
| 824 |
+
node_qtype,
|
| 825 |
+
) = self.quantize_bias_static_impl(bias_name, input_scale, weight_scale, beta)
|
| 826 |
+
|
| 827 |
+
assert bias_name not in self.quantized_value_map
|
| 828 |
+
quantized_value = QuantizedValue(
|
| 829 |
+
bias_name,
|
| 830 |
+
quantized_bias_name,
|
| 831 |
+
quantized_bias_scale_name,
|
| 832 |
+
quantized_bias_zp_name,
|
| 833 |
+
QuantizedValueType.Initializer,
|
| 834 |
+
0 if bias_scale_data.size > 1 else None,
|
| 835 |
+
node_type=node_type,
|
| 836 |
+
node_qtype=node_qtype,
|
| 837 |
+
)
|
| 838 |
+
self.quantized_value_map[bias_name] = quantized_value
|
| 839 |
+
|
| 840 |
+
return quantized_bias_name
|
| 841 |
+
|
| 842 |
+
def contains_tensor(self, tensor_name):
|
| 843 |
+
"""
|
| 844 |
+
only check for value info and newly generated tensor names, initializers are checked separately
|
| 845 |
+
"""
|
| 846 |
+
return (
|
| 847 |
+
(tensor_name in self.value_infos)
|
| 848 |
+
or (tensor_name in self.tensor_names)
|
| 849 |
+
or (tensor_name in self.generated_value_names)
|
| 850 |
+
)
|
| 851 |
+
|
| 852 |
+
def quantize_activation(self, node, indices, from_subgraph=False):
|
| 853 |
+
return self.__quantize_inputs(
|
| 854 |
+
node=node,
|
| 855 |
+
indices=indices,
|
| 856 |
+
initializer_use_weight_qType=False,
|
| 857 |
+
reduce_range=False,
|
| 858 |
+
op_level_per_channel=False,
|
| 859 |
+
axis=-1,
|
| 860 |
+
from_subgraph=from_subgraph,
|
| 861 |
+
)
|
| 862 |
+
|
| 863 |
+
# In some circumstances a weight is not an initializer, for example of MatMul, if both A and B are not
|
| 864 |
+
# initializer, B can still be considered as Weight
|
| 865 |
+
def quantize_weight(
|
| 866 |
+
self,
|
| 867 |
+
node,
|
| 868 |
+
indices,
|
| 869 |
+
reduce_range=False,
|
| 870 |
+
op_level_per_channel=False,
|
| 871 |
+
axis=-1,
|
| 872 |
+
from_subgraph=False,
|
| 873 |
+
):
|
| 874 |
+
return self.__quantize_inputs(
|
| 875 |
+
node=node,
|
| 876 |
+
indices=indices,
|
| 877 |
+
initializer_use_weight_qType=True,
|
| 878 |
+
reduce_range=reduce_range,
|
| 879 |
+
op_level_per_channel=op_level_per_channel,
|
| 880 |
+
axis=axis,
|
| 881 |
+
from_subgraph=from_subgraph,
|
| 882 |
+
)
|
| 883 |
+
|
| 884 |
+
def __quantize_inputs(
|
| 885 |
+
self,
|
| 886 |
+
node,
|
| 887 |
+
indices,
|
| 888 |
+
initializer_use_weight_qType=True,
|
| 889 |
+
reduce_range=False,
|
| 890 |
+
op_level_per_channel=False,
|
| 891 |
+
axis=-1,
|
| 892 |
+
from_subgraph=False,
|
| 893 |
+
):
|
| 894 |
+
"""
|
| 895 |
+
Given a node, this function quantizes the inputs as follows:
|
| 896 |
+
- If input is an initializer, quantize the initializer data, replace old initializer
|
| 897 |
+
with new initializer
|
| 898 |
+
- Else, add QuantizeLinear nodes to perform quantization
|
| 899 |
+
parameter node: node being quantized in NodeProto format.
|
| 900 |
+
parameter indices: input indices to quantize.
|
| 901 |
+
return: (List of quantized input names,
|
| 902 |
+
List of zero point names used for input quantization,
|
| 903 |
+
List of scale names used for input quantization,
|
| 904 |
+
List of new QuantizeLinear nodes created)
|
| 905 |
+
"""
|
| 906 |
+
|
| 907 |
+
scale_names = []
|
| 908 |
+
zero_point_names = []
|
| 909 |
+
quantized_input_names = []
|
| 910 |
+
nodes = []
|
| 911 |
+
|
| 912 |
+
for input_index in indices:
|
| 913 |
+
node_input = node.input[input_index]
|
| 914 |
+
|
| 915 |
+
# Find if this input is already quantized
|
| 916 |
+
if node_input in self.quantized_value_map:
|
| 917 |
+
quantized_value = self.quantized_value_map[node_input]
|
| 918 |
+
scale_names.append(quantized_value.scale_name)
|
| 919 |
+
zero_point_names.append(quantized_value.zp_name)
|
| 920 |
+
quantized_input_names.append(quantized_value.q_name)
|
| 921 |
+
continue
|
| 922 |
+
# adding this for case embed_layernorm.py has optional segment_embedding
|
| 923 |
+
if not node_input:
|
| 924 |
+
quantized_input_names.append("")
|
| 925 |
+
scale_names.append("")
|
| 926 |
+
zero_point_names.append("")
|
| 927 |
+
continue
|
| 928 |
+
# Quantize the input
|
| 929 |
+
initializer = find_by_name(node_input, self.model.initializer())
|
| 930 |
+
if initializer is not None:
|
| 931 |
+
if self.per_channel and op_level_per_channel:
|
| 932 |
+
(
|
| 933 |
+
q_weight_name,
|
| 934 |
+
zp_name,
|
| 935 |
+
scale_name,
|
| 936 |
+
) = self.quantize_weight_per_channel(
|
| 937 |
+
initializer.name,
|
| 938 |
+
self.weight_qType if initializer_use_weight_qType else self.activation_qType,
|
| 939 |
+
axis,
|
| 940 |
+
reduce_range,
|
| 941 |
+
)
|
| 942 |
+
else:
|
| 943 |
+
q_weight_name, zp_name, scale_name = self.quantize_initializer(
|
| 944 |
+
initializer,
|
| 945 |
+
self.weight_qType if initializer_use_weight_qType else self.activation_qType,
|
| 946 |
+
reduce_range,
|
| 947 |
+
)
|
| 948 |
+
|
| 949 |
+
quantized_input_names.append(q_weight_name)
|
| 950 |
+
zero_point_names.append(zp_name)
|
| 951 |
+
scale_names.append(scale_name)
|
| 952 |
+
elif self.contains_tensor(node_input):
|
| 953 |
+
# Add QuantizeLinear node.
|
| 954 |
+
qlinear_node = self.model.find_node_by_name(
|
| 955 |
+
node_input + "_QuantizeLinear", self.new_nodes, self.model.graph()
|
| 956 |
+
)
|
| 957 |
+
if qlinear_node is None:
|
| 958 |
+
input_name = node.input[input_index]
|
| 959 |
+
if input_name in self.value_infos:
|
| 960 |
+
value_info = self.value_infos[input_name]
|
| 961 |
+
assert value_info.HasField("type"), f"value_info={value_info} has no type."
|
| 962 |
+
assert value_info.type.HasField("tensor_type"), f"value_info={value_info} is not a tensor."
|
| 963 |
+
initial_type = value_info.type.tensor_type.elem_type
|
| 964 |
+
else:
|
| 965 |
+
# Shape inference failed. Fallback to self.tensor_names.
|
| 966 |
+
assert input_name in self.tensor_names, (
|
| 967 |
+
f"shape inference failed for {input_name!r} and "
|
| 968 |
+
f"attribute 'tensor_names' does not have any value for "
|
| 969 |
+
f"this tensor."
|
| 970 |
+
)
|
| 971 |
+
initial_type = self.tensor_names[input_name]
|
| 972 |
+
quantize_input_nodes = self._get_quantize_input_nodes(
|
| 973 |
+
node, input_index, self.activation_qType, initial_type=initial_type
|
| 974 |
+
)
|
| 975 |
+
if quantize_input_nodes is None:
|
| 976 |
+
return (None, None, None, None)
|
| 977 |
+
if from_subgraph:
|
| 978 |
+
self.add_new_nodes(quantize_input_nodes)
|
| 979 |
+
else:
|
| 980 |
+
nodes.extend(quantize_input_nodes)
|
| 981 |
+
qlinear_node = quantize_input_nodes[-1]
|
| 982 |
+
|
| 983 |
+
if qlinear_node.op_type == "QuantizeLinear":
|
| 984 |
+
quantized_input_names.extend(qlinear_node.output)
|
| 985 |
+
scale_names.append(qlinear_node.input[1])
|
| 986 |
+
zero_point_names.append(qlinear_node.input[2])
|
| 987 |
+
else:
|
| 988 |
+
quantized_input_names.append(qlinear_node.output[0])
|
| 989 |
+
scale_names.append(qlinear_node.output[1])
|
| 990 |
+
zero_point_names.append(qlinear_node.output[2])
|
| 991 |
+
elif self.parent is not None:
|
| 992 |
+
(
|
| 993 |
+
parent_quantized_input_names,
|
| 994 |
+
parent_zero_point_names,
|
| 995 |
+
parent_scale_names,
|
| 996 |
+
_,
|
| 997 |
+
) = self.parent.__quantize_inputs(
|
| 998 |
+
node,
|
| 999 |
+
[input_index],
|
| 1000 |
+
initializer_use_weight_qType=initializer_use_weight_qType,
|
| 1001 |
+
reduce_range=reduce_range,
|
| 1002 |
+
op_level_per_channel=op_level_per_channel,
|
| 1003 |
+
axis=axis,
|
| 1004 |
+
from_subgraph=True,
|
| 1005 |
+
)
|
| 1006 |
+
quantized_input_names.append(parent_quantized_input_names[0])
|
| 1007 |
+
scale_names.append(parent_scale_names[0])
|
| 1008 |
+
zero_point_names.append(parent_zero_point_names[0])
|
| 1009 |
+
# node should not be add this child level here
|
| 1010 |
+
else:
|
| 1011 |
+
raise ValueError(f"Invalid tensor name to quantize: {node_input} @graph scope{self.graph_scope}")
|
| 1012 |
+
|
| 1013 |
+
return quantized_input_names, zero_point_names, scale_names, nodes
|
| 1014 |
+
|
| 1015 |
+
def quantize_initializer(self, weight, qType, reduce_range=False, keep_float_weight=False):
|
| 1016 |
+
"""
|
| 1017 |
+
:param weight: TensorProto initializer
|
| 1018 |
+
:param qType: type to quantize to
|
| 1019 |
+
:param keep_float_weight: Whether to quantize the weight. In some cases, we only want to qunatize scale and zero point.
|
| 1020 |
+
If keep_float_weight is False, quantize the weight, or don't quantize the weight.
|
| 1021 |
+
:return: quantized weight name, zero point name, scale name
|
| 1022 |
+
"""
|
| 1023 |
+
# Find if this input is already quantized
|
| 1024 |
+
if weight.name in self.quantized_value_map:
|
| 1025 |
+
quantized_value = self.quantized_value_map[weight.name]
|
| 1026 |
+
return (
|
| 1027 |
+
quantized_value.q_name,
|
| 1028 |
+
quantized_value.zp_name,
|
| 1029 |
+
quantized_value.scale_name,
|
| 1030 |
+
)
|
| 1031 |
+
|
| 1032 |
+
q_weight_name, zp_name, scale_name = self.quantize_initializer_impl(
|
| 1033 |
+
weight, qType, reduce_range, keep_float_weight
|
| 1034 |
+
)
|
| 1035 |
+
|
| 1036 |
+
# Log entry for this quantized weight
|
| 1037 |
+
quantized_value = QuantizedValue(
|
| 1038 |
+
weight.name,
|
| 1039 |
+
q_weight_name,
|
| 1040 |
+
scale_name,
|
| 1041 |
+
zp_name,
|
| 1042 |
+
QuantizedValueType.Initializer,
|
| 1043 |
+
None,
|
| 1044 |
+
)
|
| 1045 |
+
self.quantized_value_map[weight.name] = quantized_value
|
| 1046 |
+
return q_weight_name, zp_name, scale_name
|
| 1047 |
+
|
| 1048 |
+
def quantize_weight_per_channel(
|
| 1049 |
+
self,
|
| 1050 |
+
weight_name,
|
| 1051 |
+
weight_qType,
|
| 1052 |
+
channel_axis,
|
| 1053 |
+
reduce_range=True,
|
| 1054 |
+
keep_float_weight=False,
|
| 1055 |
+
):
|
| 1056 |
+
# Find if this input is already quantized
|
| 1057 |
+
if weight_name in self.quantized_value_map:
|
| 1058 |
+
quantized_value = self.quantized_value_map[weight_name]
|
| 1059 |
+
return (
|
| 1060 |
+
quantized_value.q_name,
|
| 1061 |
+
quantized_value.zp_name,
|
| 1062 |
+
quantized_value.scale_name,
|
| 1063 |
+
)
|
| 1064 |
+
|
| 1065 |
+
q_weight_name, zp_name, scale_name = self.quantize_weight_per_channel_impl(
|
| 1066 |
+
weight_name, weight_qType, channel_axis, reduce_range, keep_float_weight
|
| 1067 |
+
)
|
| 1068 |
+
quantized_value = QuantizedValue(
|
| 1069 |
+
weight_name,
|
| 1070 |
+
q_weight_name,
|
| 1071 |
+
scale_name,
|
| 1072 |
+
zp_name,
|
| 1073 |
+
QuantizedValueType.Initializer,
|
| 1074 |
+
None,
|
| 1075 |
+
)
|
| 1076 |
+
self.quantized_value_map[weight_name] = quantized_value
|
| 1077 |
+
|
| 1078 |
+
return q_weight_name, zp_name, scale_name
|
| 1079 |
+
|
| 1080 |
+
def _dequantize_value(self, value_name):
|
| 1081 |
+
"""
|
| 1082 |
+
Given a value (input/output) which is quantized, add a DequantizeLinear node to dequantize
|
| 1083 |
+
it back to float32 or float16
|
| 1084 |
+
parameter value_name: value to dequantize
|
| 1085 |
+
parameter new_nodes_list: List of new nodes created before processing current node
|
| 1086 |
+
return: None if there is already a DequantizeLinear node that dequantizes it
|
| 1087 |
+
A DequantizeLinear node otherwise
|
| 1088 |
+
"""
|
| 1089 |
+
if (value_name in self.quantized_value_map) and (value_name not in self.generated_value_names):
|
| 1090 |
+
quantized_value = self.quantized_value_map[value_name]
|
| 1091 |
+
# Add DequantizeLinear Node for this input
|
| 1092 |
+
|
| 1093 |
+
scale_init = find_by_name(quantized_value.scale_name, self.model.initializer())
|
| 1094 |
+
|
| 1095 |
+
# 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.
|
| 1096 |
+
if self.model.model.producer_name != "onnx-quantizer" or (
|
| 1097 |
+
self.model.model.producer_name == "onnx-quantizer" and scale_init is not None
|
| 1098 |
+
):
|
| 1099 |
+
# axis is not specified so scale_init must be a scalar.
|
| 1100 |
+
assert scale_init is None or onnx.numpy_helper.to_array(scale_init).size == 1
|
| 1101 |
+
|
| 1102 |
+
dqlinear_name = value_name + "_DequantizeLinear"
|
| 1103 |
+
dqlinear_node = self.model.find_node_by_name(dqlinear_name, self.new_nodes, self.model.graph())
|
| 1104 |
+
if dqlinear_node is None:
|
| 1105 |
+
dqlinear_inputs = [
|
| 1106 |
+
quantized_value.q_name,
|
| 1107 |
+
quantized_value.scale_name,
|
| 1108 |
+
quantized_value.zp_name,
|
| 1109 |
+
]
|
| 1110 |
+
dequantize_node = onnx.helper.make_node(
|
| 1111 |
+
"DequantizeLinear", dqlinear_inputs, [value_name], dqlinear_name
|
| 1112 |
+
)
|
| 1113 |
+
return dequantize_node
|
| 1114 |
+
else:
|
| 1115 |
+
# DQ op is already present, assert it's output matches the input of current node
|
| 1116 |
+
assert value_name == dqlinear_node.output[0]
|
| 1117 |
+
return None
|
| 1118 |
+
|
| 1119 |
+
def _dequantize_outputs(self):
|
| 1120 |
+
"""
|
| 1121 |
+
Dequantize output if it is quantized
|
| 1122 |
+
parameter new_nodes_list: List of new nodes created before processing current node
|
| 1123 |
+
return: List of new nodes created
|
| 1124 |
+
"""
|
| 1125 |
+
|
| 1126 |
+
for output in self.model.graph().output:
|
| 1127 |
+
dequantize_node = self._dequantize_value(output.name)
|
| 1128 |
+
if dequantize_node is not None:
|
| 1129 |
+
self.new_nodes.append(dequantize_node)
|
| 1130 |
+
|
| 1131 |
+
def calculate_quantization_params(self):
|
| 1132 |
+
if self.tensors_range is None:
|
| 1133 |
+
return None
|
| 1134 |
+
|
| 1135 |
+
self.adjust_tensor_ranges()
|
| 1136 |
+
|
| 1137 |
+
quantization_params = {}
|
| 1138 |
+
for tensor_name in self.tensors_range:
|
| 1139 |
+
td = self.tensors_range[tensor_name]
|
| 1140 |
+
if not isinstance(td, TensorData):
|
| 1141 |
+
raise TypeError(f"Unexpected type {type(td)} for {tensor_name!r}.")
|
| 1142 |
+
|
| 1143 |
+
quant_overrides = self.tensor_quant_overrides.get_per_tensor_overrides(tensor_name, default_val={})
|
| 1144 |
+
|
| 1145 |
+
quant_type = self.activation_qType
|
| 1146 |
+
if "quant_type" in quant_overrides:
|
| 1147 |
+
quant_type = quant_overrides["quant_type"].tensor_type
|
| 1148 |
+
|
| 1149 |
+
if "scale" in quant_overrides and "zero_point" in quant_overrides:
|
| 1150 |
+
zero, scale = quant_overrides["zero_point"], quant_overrides["scale"]
|
| 1151 |
+
elif quant_type == onnx.TensorProto.FLOAT8E4M3FN:
|
| 1152 |
+
zero, scale = compute_scale_zp_float8(quant_type, td.avg_std[1])
|
| 1153 |
+
else:
|
| 1154 |
+
rmin = quant_overrides.get("rmin", td.range_value[0])
|
| 1155 |
+
rmax = quant_overrides.get("rmax", td.range_value[1])
|
| 1156 |
+
symmetric = quant_overrides.get("symmetric", self.is_activation_symmetric)
|
| 1157 |
+
reduce_range = quant_overrides.get("reduce_range", False)
|
| 1158 |
+
qmin, qmax = get_qmin_qmax_for_qType(quant_type, reduce_range=reduce_range, symmetric=symmetric)
|
| 1159 |
+
zero, scale = compute_scale_zp(rmin, rmax, qmin, qmax, symmetric, self.min_real_range)
|
| 1160 |
+
|
| 1161 |
+
quantization_params[tensor_name] = QuantizationParams(zero_point=zero, scale=scale, quant_type=quant_type)
|
| 1162 |
+
|
| 1163 |
+
return quantization_params
|
micromamba_root/envs/pytorch_env/Lib/site-packages/onnxruntime/quantization/operators/__init__.py
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# from .base_operator import QuantOperatorBase
|
| 2 |
+
# from .matmul import MatMulInteger
|