|
| 1 | +# Copyright 2026 The HuggingFace Inc. team. All rights reserved. |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | +"""NVIDIA ModelOpt quantization of the converted ONNX model, for TensorRT.""" |
| 15 | + |
| 16 | +from __future__ import annotations |
| 17 | + |
| 18 | +import os |
| 19 | +import sys |
| 20 | +import tempfile |
| 21 | +from collections.abc import Iterable |
| 22 | +from contextlib import contextmanager |
| 23 | +from dataclasses import dataclass |
| 24 | +from typing import Any |
| 25 | + |
| 26 | +from ...utils.import_utils import is_modelopt_available, is_onnxscript_available |
| 27 | +from ..configs import ExportFormat |
| 28 | +from ..utils import onnx_feed |
| 29 | +from .base import CalibrationSet, ExportQuantizer, QuantizationConfigMixin |
| 30 | +from .quantizer_onnxruntime import _FeedReader |
| 31 | + |
| 32 | + |
| 33 | +if is_onnxscript_available(): |
| 34 | + import onnx_ir |
| 35 | + |
| 36 | +if is_modelopt_available(): |
| 37 | + from modelopt.onnx.quantization import quantize as modelopt_quantize |
| 38 | + |
| 39 | + |
| 40 | +@contextmanager |
| 41 | +def _restored_onnxruntime_quantization(): |
| 42 | + """ModelOpt patches ONNX Runtime's quantization modules in place for its own calibration |
| 43 | + (`modelopt.onnx.quantization.ort_patches`) and leaves them patched, which breaks a later `OnnxRuntimeQuantizer` in |
| 44 | + the same process. Put back every attribute it adds or replaces on any loaded `onnxruntime.quantization` module or |
| 45 | + class defined there (ModelOpt imports the ones it patches before this runs).""" |
| 46 | + modules = [ |
| 47 | + module |
| 48 | + for name, module in list(sys.modules.items()) |
| 49 | + if module is not None and (name == "onnxruntime.quantization" or name.startswith("onnxruntime.quantization.")) |
| 50 | + ] |
| 51 | + classes = [ |
| 52 | + value |
| 53 | + for module in modules |
| 54 | + for value in vars(module).values() |
| 55 | + if isinstance(value, type) and value.__module__ == module.__name__ |
| 56 | + ] |
| 57 | + snapshots = [(owner, dict(vars(owner))) for owner in modules + classes] |
| 58 | + try: |
| 59 | + yield |
| 60 | + finally: |
| 61 | + for owner, attributes in snapshots: |
| 62 | + for name in set(vars(owner)) - set(attributes): |
| 63 | + delattr(owner, name) |
| 64 | + for name, value in attributes.items(): |
| 65 | + if vars(owner).get(name) is not value: |
| 66 | + setattr(owner, name, value) |
| 67 | + |
| 68 | + |
| 69 | +@dataclass |
| 70 | +class ModelOptOnnxConfig(QuantizationConfigMixin): |
| 71 | + """ |
| 72 | + Arguments of `modelopt.onnx.quantization.quantize`: int8 or fp8 QDQ calibrated on the quantizer's |
| 73 | + `calibration_dataset`, or int4 weights. The Q/DQ nodes go where TensorRT fuses them, and the rest of an fp32 model |
| 74 | + is converted to `high_precision_dtype` (fp16 by default). A field left to `None` keeps ModelOpt's default. See |
| 75 | + [ModelOpt's ONNX quantization](https://nvidia.github.io/Model-Optimizer/guides/_onnx_quantization.html) for each |
| 76 | + one. |
| 77 | + """ |
| 78 | + |
| 79 | + quantize_mode: str | None = None |
| 80 | + calibration_method: str | None = None |
| 81 | + calibration_eps: list[str] | None = None |
| 82 | + op_types_to_quantize: list[str] | None = None |
| 83 | + op_types_to_exclude: list[str] | None = None |
| 84 | + nodes_to_quantize: list[str] | None = None |
| 85 | + nodes_to_exclude: list[str] | None = None |
| 86 | + high_precision_dtype: str | None = None |
| 87 | + mha_accumulation_dtype: str | None = None |
| 88 | + disable_mha_qdq: bool | None = None |
| 89 | + block_size: int | None = None |
| 90 | + |
| 91 | + |
| 92 | +class ModelOptOnnxQuantizer(ExportQuantizer): |
| 93 | + """ |
| 94 | + Quantize the converted ONNX model with NVIDIA's [ModelOpt](https://github.com/NVIDIA/Model-Optimizer) |
| 95 | + (`modelopt.onnx.quantization.quantize`) for TensorRT, such as ONNX Runtime's TensorRT execution provider. Export |
| 96 | + the model in fp32: ModelOpt calibrates it in fp32, then converts what it leaves unquantized to fp16. |
| 97 | +
|
| 98 | + Example: |
| 99 | +
|
| 100 | + ```python |
| 101 | + >>> from transformers.exporters import ModelOptOnnxConfig, ModelOptOnnxQuantizer, OnnxConfig |
| 102 | +
|
| 103 | + >>> OnnxConfig(quantizer=ModelOptOnnxQuantizer(calibration_dataset=samples)) |
| 104 | + >>> OnnxConfig(quantizer=ModelOptOnnxQuantizer(ModelOptOnnxConfig(disable_mha_qdq=True), calibration_dataset=samples)) |
| 105 | + ``` |
| 106 | + """ |
| 107 | + |
| 108 | + supported_formats = (ExportFormat.ONNX,) |
| 109 | + |
| 110 | + required_packages = ("modelopt", "onnx", "onnx_ir", "onnxruntime") |
| 111 | + tested_versions = {"modelopt": "0.48.0", "onnx": "1.21.0", "onnx_ir": "1.1.0", "onnxruntime": "1.29.0"} |
| 112 | + min_versions = {"modelopt": "0.48.0"} |
| 113 | + |
| 114 | + def __init__( |
| 115 | + self, config: ModelOptOnnxConfig | None = None, calibration_dataset: Iterable[dict[str, Any]] | None = None |
| 116 | + ): |
| 117 | + super().__init__(calibration_dataset) |
| 118 | + self.config = config if config is not None else ModelOptOnnxConfig() |
| 119 | + |
| 120 | + def quantize( |
| 121 | + self, model: onnx_ir.Model, sample_inputs: dict[str, Any], export_format: ExportFormat |
| 122 | + ) -> onnx_ir.Model: |
| 123 | + names = [graph_input.name for graph_input in model.graph.inputs] |
| 124 | + # ModelOpt reads the feeds more than once (the first one for its graph analysis, then every calibration pass), |
| 125 | + # so a one-shot `calibration_dataset` such as a generator is read once here: re-iterating it would drop the |
| 126 | + # first sample, then every sample of a later pass |
| 127 | + calibration = list( |
| 128 | + CalibrationSet(self.calibration_dataset, sample_inputs, lambda sample: onnx_feed(names, sample)) |
| 129 | + ) |
| 130 | + with tempfile.TemporaryDirectory() as tmp: |
| 131 | + # ModelOpt quantizes from and to files with external data, so models past protobuf's 2GB limit work |
| 132 | + path = os.path.join(tmp, "model.onnx") |
| 133 | + quantized_path = os.path.join(tmp, "quantized.onnx") |
| 134 | + onnx_ir.save(model, path, external_data="model.onnx.data") |
| 135 | + with _restored_onnxruntime_quantization(): |
| 136 | + modelopt_quantize( |
| 137 | + path, |
| 138 | + calibration_data_reader=_FeedReader(calibration), |
| 139 | + output_path=quantized_path, |
| 140 | + use_external_data_format=True, |
| 141 | + **self.config.to_kwargs(), |
| 142 | + ) |
| 143 | + # Load the weights into memory before the temporary directory goes away |
| 144 | + quantized = onnx_ir.load(quantized_path) |
| 145 | + onnx_ir.external_data.load_to_model(quantized) |
| 146 | + return quantized |
0 commit comments