Skip to content

Commit 306ee58

Browse files
Exporters: ModelOpt quantizer for the converted ONNX model
ModelOptOnnxQuantizer quantizes the converted ONNX graph for TensorRT, OnnxConfig(for_tensorrt=True) keeps the attention mask boolean at opset 22, and the ONNX runner hands TensorRT an ONNX Runtime calibration table. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent be48e7a commit 306ee58

13 files changed

Lines changed: 490 additions & 15 deletions

File tree

‎docs/source/en/main_classes/exporters.md‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -107,6 +107,8 @@ Learn how to use the built-in exporters in the [Exporters](../exporters) guide.
107107

108108
[[autodoc]] exporters.quantizers.OnnxRuntimeDynamicConfig
109109

110+
[[autodoc]] exporters.quantizers.OnnxRuntimeCalibrationTableConfig
111+
110112
[[autodoc]] exporters.quantizers.NNCFOpenVINOQuantizer
111113

112114
[[autodoc]] exporters.quantizers.NNCFOnnxQuantizer
@@ -117,6 +119,10 @@ Learn how to use the built-in exporters in the [Exporters](../exporters) guide.
117119

118120
[[autodoc]] exporters.quantizers.NNCFWeightCompressionConfig
119121

122+
[[autodoc]] exporters.quantizers.ModelOptOnnxQuantizer
123+
124+
[[autodoc]] exporters.quantizers.ModelOptOnnxConfig
125+
120126
## Utilities
121127

122128
Lower-level functions that power `export_for_generation`, useful when you need to intervene

‎src/transformers/exporters/__init__.py‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,11 +35,14 @@
3535
"metadata": ["ExportMetadata"],
3636
"quantizers": [
3737
"ExportQuantizer",
38+
"ModelOptOnnxConfig",
39+
"ModelOptOnnxQuantizer",
3840
"NNCFOnnxQuantizer",
3941
"NNCFOpenVINOQuantizer",
4042
"NNCFQuantizationConfig",
4143
"NNCFTorchFXQuantizer",
4244
"NNCFWeightCompressionConfig",
45+
"OnnxRuntimeCalibrationTableConfig",
4346
"OnnxRuntimeDynamicConfig",
4447
"OnnxRuntimeQuantizer",
4548
"OnnxRuntimeStaticConfig",
@@ -59,11 +62,14 @@
5962
from .metadata import ExportMetadata
6063
from .quantizers import (
6164
ExportQuantizer,
65+
ModelOptOnnxConfig,
66+
ModelOptOnnxQuantizer,
6267
NNCFOnnxQuantizer,
6368
NNCFOpenVINOQuantizer,
6469
NNCFQuantizationConfig,
6570
NNCFTorchFXQuantizer,
6671
NNCFWeightCompressionConfig,
72+
OnnxRuntimeCalibrationTableConfig,
6773
OnnxRuntimeDynamicConfig,
6874
OnnxRuntimeQuantizer,
6975
OnnxRuntimeStaticConfig,

‎src/transformers/exporters/configs.py‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -117,7 +117,8 @@ class DynamoConfig(ExportConfigMixin):
117117
[`~exporters.quantizers.NNCFTorchFXQuantizer`] on the FX graph for every backend,
118118
[`~exporters.quantizers.OnnxRuntimeQuantizer`] on the converted ONNX model, or
119119
[`~exporters.quantizers.NNCFOpenVINOQuantizer`] / [`~exporters.quantizers.NNCFOnnxQuantizer`] on the
120-
converted OpenVINO / ONNX model.
120+
converted OpenVINO / ONNX model, or [`~exporters.quantizers.ModelOptOnnxQuantizer`] on the converted ONNX
121+
model for TensorRT.
121122
"""
122123

123124
export_format: ExportFormat = ExportFormat.DYNAMO
@@ -149,17 +150,23 @@ class OnnxConfig(DynamoConfig):
149150
ort_fusions (`str`, *optional*):
150151
Fuse the graph into ONNX Runtime's ops for the execution provider it runs on: `"cpu"`, `"cuda"`,
151152
`"webgpu"` or `"dml"`. The fused graph only runs on ONNX Runtime. Requires `optimize=True`.
153+
for_tensorrt (`bool`, *optional*, defaults to `False`):
154+
Prepare the graph for ONNX Runtime's TensorRT provider: attention masks kept boolean, which TensorRT builds
155+
a faster engine from, at opset 22 by default. Takes no `ort_fusions`: TensorRT fuses the graph itself.
152156
"""
153157

154158
export_format: ExportFormat = ExportFormat.ONNX
155159

156160
opset_version: int | None = None
157161
optimize: bool = True
158162
ort_fusions: Literal["cpu", "cuda", "webgpu", "dml"] | None = None
163+
for_tensorrt: bool = False
159164

160165
def __post_init__(self):
161166
if self.ort_fusions not in (None, "cpu", "cuda", "webgpu", "dml"):
162167
raise ValueError(f"`ort_fusions` must be None, 'cpu', 'cuda', 'webgpu' or 'dml', got {self.ort_fusions!r}")
168+
if self.for_tensorrt and self.ort_fusions is not None:
169+
raise ValueError("`for_tensorrt` takes no `ort_fusions`: TensorRT fuses the graph itself.")
163170
if self.ort_fusions is not None and not self.optimize:
164171
raise ValueError("`ort_fusions` requires `optimize=True`.")
165172

‎src/transformers/exporters/exporter_onnx.py‎

Lines changed: 27 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,7 @@
4545
import functools
4646
import operator
4747
from collections.abc import MutableMapping, Sequence
48-
from contextlib import contextmanager
48+
from contextlib import contextmanager, nullcontext
4949
from pathlib import Path
5050
from typing import TYPE_CHECKING, Any
5151

@@ -60,6 +60,7 @@
6060
apply_fx_node_fixes,
6161
apply_patches,
6262
disambiguate_io_names,
63+
patch_attribute,
6364
patch_model_outputs,
6465
quantize_converted_model,
6566
register_fx_node_fix,
@@ -144,13 +145,18 @@ def export_program(
144145
# A model quantized before export has no ops the fusions match.
145146
quantizer = config.quantizer
146147
ort_fusions = config.ort_fusions if quantizer is None or not quantizer.quantizes_fx_graph else None
148+
# TensorRT builds opset 23's `Attention` only into a strongly typed network, which ONNX Runtime doesn't request.
149+
opset_version = 22 if config.opset_version is None and config.for_tensorrt else config.opset_version
147150
# `batched_mm` experts fuse into ONNX Runtime's CUDA `MoE`.
148151
experts_implementation = "batched_mm" if ort_fusions == "cuda" else None
149152

150153
with (
151154
patch_model_outputs(model) as (inputs_names, outputs_names, traced_outputs),
152155
apply_patches("onnx"),
153156
use_experts_implementation(model, experts_implementation),
157+
patch_attribute(torch.nn.functional, "scaled_dot_product_attention", _additive_sdpa_mask)
158+
if not config.for_tensorrt
159+
else nullcontext(),
154160
):
155161
exported_program, metadata = super().export_program(model, sample_inputs, config=config)
156162
inputs_names, outputs_names = disambiguate_io_names(inputs_names, outputs_names)
@@ -161,7 +167,7 @@ def export_program(
161167
input_names=inputs_names,
162168
kwargs=copy.deepcopy(dict(sample_inputs)),
163169
custom_translation_table=_ONNX_TRANSLATION_TABLE,
164-
opset_version=config.opset_version,
170+
opset_version=opset_version,
165171
optimize=config.optimize,
166172
)
167173

@@ -295,8 +301,7 @@ def _patch_sdpa(original):
295301
relative-position bias masks that way), returns `NaN` — which a later BatchNorm then spreads over
296302
the whole batch. Rows like these are routine: any padded frame under a padding mask has one.
297303
298-
A boolean mask goes in as an additive one (torchlib's boolean softmax adds a redundant `IsNaN`/`Where`), and
299-
unattended rows are counted with a sum (a bool `ReduceMax` runs on the CPU in ONNX Runtime's CUDA provider,
304+
Unattended rows are counted with a sum (a bool `ReduceMax` runs on the CPU in ONNX Runtime's CUDA provider,
300305
microsoft/onnxruntime#33876). The key, value and mask lengths are checked equal, so a dynamic export gives them
301306
one symbol, which onnxscript's attention fusion needs.
302307
"""
@@ -311,7 +316,6 @@ def patch(query, key, value, attn_mask=None, *args, **kwargs):
311316
# Built from scalars only, so every layer's copy of this, reading the same mask, is one after CSE.
312317
if attn_mask.dtype == torch.bool:
313318
attended = attn_mask.to(query.dtype)
314-
attn_mask = (~attn_mask).to(query.dtype) * torch.finfo(query.dtype).min
315319
else:
316320
attended = (attn_mask > torch.finfo(attn_mask.dtype).min).to(query.dtype)
317321
unattended = attended.sum(dim=-1, keepdim=True) < 1
@@ -322,6 +326,24 @@ def patch(query, key, value, attn_mask=None, *args, **kwargs):
322326
return patch
323327

324328

329+
def _additive_sdpa_mask(original):
330+
"""A boolean attention mask as an additive one, for every export but TensorRT's.
331+
332+
torchlib's boolean softmax guards every attention with an `IsNaN`/`Where` over the scores, which `_patch_sdpa`
333+
makes redundant and which ONNX Runtime pays for (2x on a 2520-patch vision attention on its CPU provider).
334+
TensorRT builds a faster engine from the boolean form (2.53 ms against 3.00 ms on EmbeddingGemma2 in bf16 on a
335+
B200).
336+
"""
337+
338+
def patch(query, key, value, attn_mask=None, *args, **kwargs):
339+
if attn_mask is not None and attn_mask.dtype == torch.bool:
340+
# Built from scalars only, so every layer's copy of this, reading the same mask, is one after CSE.
341+
attn_mask = (~attn_mask).to(query.dtype) * torch.finfo(query.dtype).min
342+
return original(query, key, value, attn_mask, *args, **kwargs)
343+
344+
return patch
345+
346+
325347
@register_patch("onnx", "torch.nn.RMSNorm.forward")
326348
def _patch_rms_norm_forward(original):
327349
"""Use non-fused RMS normalization when elementwise_affine is False."""

‎src/transformers/exporters/quantizers/__init__.py‎

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,27 +18,39 @@
1818

1919
_import_structure = {
2020
"base": ["CalibrationSet", "ExportQuantizer"],
21+
"quantizer_modelopt": ["ModelOptOnnxConfig", "ModelOptOnnxQuantizer"],
2122
"quantizer_nncf": [
2223
"NNCFOnnxQuantizer",
2324
"NNCFOpenVINOQuantizer",
2425
"NNCFQuantizationConfig",
2526
"NNCFTorchFXQuantizer",
2627
"NNCFWeightCompressionConfig",
2728
],
28-
"quantizer_onnxruntime": ["OnnxRuntimeDynamicConfig", "OnnxRuntimeQuantizer", "OnnxRuntimeStaticConfig"],
29+
"quantizer_onnxruntime": [
30+
"OnnxRuntimeCalibrationTableConfig",
31+
"OnnxRuntimeDynamicConfig",
32+
"OnnxRuntimeQuantizer",
33+
"OnnxRuntimeStaticConfig",
34+
],
2935
"quantizer_pt2e": ["PT2EQuantizer"],
3036
}
3137

3238
if TYPE_CHECKING:
3339
from .base import CalibrationSet, ExportQuantizer
40+
from .quantizer_modelopt import ModelOptOnnxConfig, ModelOptOnnxQuantizer
3441
from .quantizer_nncf import (
3542
NNCFOnnxQuantizer,
3643
NNCFOpenVINOQuantizer,
3744
NNCFQuantizationConfig,
3845
NNCFTorchFXQuantizer,
3946
NNCFWeightCompressionConfig,
4047
)
41-
from .quantizer_onnxruntime import OnnxRuntimeDynamicConfig, OnnxRuntimeQuantizer, OnnxRuntimeStaticConfig
48+
from .quantizer_onnxruntime import (
49+
OnnxRuntimeCalibrationTableConfig,
50+
OnnxRuntimeDynamicConfig,
51+
OnnxRuntimeQuantizer,
52+
OnnxRuntimeStaticConfig,
53+
)
4254
from .quantizer_pt2e import PT2EQuantizer
4355
else:
4456
import sys
Lines changed: 146 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,146 @@
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

Comments
 (0)