[1/4] [6466805] Support canonical Dynamo weight packing and finalization (#3145)

### What does this PR do?

Type of change: new feature

Dynamo-captured ONNX graphs name and lay out quantized weights
differently from TorchScript graphs. The existing FP8, INT4, MXFP8 and
NVFP4 packers can't find or pack those weights, and nothing checks the
final graph's domains, opset or metadata. This PR makes the packers
handle canonical Dynamo weight paths and adds the finalization step.
Nothing calls the Dynamo paths until [2/4].

- **FP8:** keeps calibrated clipping and dtype-changing casts, saturates
weights (shared with legacy export), and gives weights that share a
scale distinct names.
- **INT4 AWQ and MXFP8:** packers select only their own Dynamo Q/DQ
nodes and skip the TorchScript-only cast and Gelu rewrites. MXFP8 keeps
BF16 and FP16 dequantize types.
- **Odd widths:** INT4 and NVFP4 weights with an odd output width now
pack, in legacy export too.
- **Finalization** validates domains, opset and metadata, and rejects
quantized nested subgraphs before mutating the graph.
- `fold_dq_fp32_to_fp16_casts` can leave chosen DQ nodes in FP32.

### Usage

Internal; the supported entry point arrives in [2/4].

### Testing

- `tests/unit/onnx/test_dynamo_adapter.py`, `test_fold_casts.py`,
`quantization/test_qdq_utils.py` and
`quantization/test_fp8_mha_exporter.py`: 132 passed at this commit.
- `tests/unit/torch/deploy` and `test_tensor_quant_cpu.py` still pass
here: 164 passed.
- The NVFP4 odd-row and FP32-DQ regressions go through the export
helper, so they are in [2/4].
- Ruff, mypy (no new errors) and `git diff --check` passed.

### Before your PR is "*Ready for review*"

Follow [Contributor
guidelines](https://github.com/NVIDIA/Model-Optimizer/blob/main/CONTRIBUTING.md)
and [Security Best
Practices](https://github.com/NVIDIA/Model-Optimizer/blob/main/SECURITY.md#security-coding-practices-for-contributors).
Commits are signed and signed off.

- Is this change backward compatible?: ✅ — legacy export output is
unchanged apart from the odd-width packing fixes.
- If you copied code from any other sources or added a new PIP
dependency, did you follow guidance in CONTRIBUTING.md?: N/A — neither
added.
- Did you write any new necessary tests?: ✅
- Did you update Changelog?: N/A — one entry for the whole feature, in
[2/4].

### Stack

Split from [#2685](https://github.com/NVIDIA/Model-Optimizer/pull/2685),
which stays open as a draft reference and is not for merge. Merge in
order; each PR targets the one before it.

1. [[1/4] Dynamo weight packing and
finalization](https://github.com/NVIDIA/Model-Optimizer/pull/3145)
2. [[2/4] Helper-owned Dynamo ONNX
export](https://github.com/NVIDIA/Model-Optimizer/pull/3146)
3. [[3/4] ONNX example wrapper
options](https://github.com/NVIDIA/Model-Optimizer/pull/3147)
4. [[4/4] Torch ONNX example CLI
options](https://github.com/NVIDIA/Model-Optimizer/pull/3148)

🤖 Generated with [Claude Code](https://claude.com/claude-code)


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

<!-- coderabbit-ai-generated:v1 -->

## Summary by CodeRabbit

* **Bug Fixes**
* Improved ONNX export handling for quantized models, including FP8,
INT8, INT4, MXFP8, and NVFP4 weights.
* Corrected weight packing and shape handling, including for odd-sized
rows, and prevented FP8 weight values from exceeding the supported
range.
* Improved type and metadata consistency in exported graphs, while
preserving FP32 values where converting to FP16 could lose precision.
* **New Features**
* Added validation and normalization of exported graphs, with clearer
checks for unsupported operators and inconsistent opset versions.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Signed-off-by: Ajinkya Rasane <131806219+ajrasane@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Ajinkya Rasane
2026-12-04 16:51:14 -05:00
committed by GitHub
co-authored by Claude Opus 5.5
parent 1127ee6923
commit 91fb8a9a27
9 changed files with 634 additions and 57 deletions
+131 -2
View File
@@ -21,6 +21,7 @@ import numpy as np
import onnx
from onnx import numpy_helper
from modelopt.onnx.autocast.utils import walk_subgraphs_recursive
from modelopt.onnx.quantization.graph_indexing import (
get_tensor_consumer_nodes,
get_tensor_producer_nodes,
@@ -28,6 +29,14 @@ from modelopt.onnx.quantization.graph_indexing import (
__all__ = []
_CARRIER_OPS = {"quantize_op", "dynamic_block_quantize_op"}
_STATIC_MARKERS = {"TRT_FP4QDQ", "TRT_FP8QuantizeLinear", "TRT_FP8DequantizeLinear"}
_ALLOWED_TRT_OPS = {
"TRT_FP4DynamicQuantize",
"TRT_MXFP8DynamicQuantize",
"TRT_MXFP8DequantizeLinear",
}
_DYNAMO_BLOCK_QUANT_OPS = _ALLOWED_TRT_OPS | {"TRT_FP4QDQ"}
_DYNAMO_INT4_NODE_PREFIX = "__modelopt_dynamo_int4__"
_DYNAMO_MXFP8_NODE_PREFIX = "__modelopt_dynamo_mxfp8__"
@@ -66,6 +75,51 @@ def _replace_initializer(graph: onnx.GraphProto, tensor: onnx.TensorProto) -> No
existing.CopyFrom(tensor)
def _sync_initializer_metadata(graph: onnx.GraphProto) -> None:
"""Match declared types to initializers, and retype weight DQ outputs and their Casts."""
declarations = {}
for value in (*graph.input, *graph.value_info, *graph.output):
declarations.setdefault(value.name, []).append(value)
for tensor in graph.initializer:
for value in declarations.get(tensor.name, []):
value.type.CopyFrom(
onnx.helper.make_tensor_value_info(tensor.name, tensor.data_type, tensor.dims).type
)
initializers = {tensor.name: tensor for tensor in graph.initializer}
synchronized_outputs = set()
for node in graph.node:
if node.domain != "" or node.op_type != "DequantizeLinear":
continue
weight = initializers.get(node.input[0])
values = declarations.get(node.output[0], [])
if weight is None or not values:
continue
scale = initializers.get(node.input[1])
# Opset 23 DQ outputs its explicit output_dtype, else the scale's type.
elem_type = _attribute(node, "output_dtype") or (
scale.data_type if scale is not None else values[0].type.tensor_type.elem_type
)
for value in values:
value.CopyFrom(
onnx.helper.make_tensor_value_info(node.output[0], elem_type, weight.dims)
)
synchronized_outputs.add(node.output[0])
for node in graph.node:
if node.domain != "" or node.op_type != "Cast" or node.input[0] not in synchronized_outputs:
continue
input_values = declarations.get(node.input[0], [])
output_values = declarations.get(node.output[0], [])
output_dtype = _attribute(node, "to")
if not input_values or not output_values or output_dtype is None:
continue
for output_value in output_values:
output_value.type.CopyFrom(input_values[0].type)
output_value.type.tensor_type.elem_type = output_dtype
synchronized_outputs.add(node.output[0])
def _remove_nodes(graph: onnx.GraphProto, nodes: Iterable[onnx.NodeProto]) -> None:
output_names = {output for node in nodes for output in node.output}
for index in reversed(range(len(graph.node))):
@@ -465,12 +519,17 @@ def normalize_dynamo_weight_paths(model: onnx.ModelProto) -> onnx.ModelProto:
continue
if kind in {"fp8", "int8"}:
direct_consumers = consumers.get(marker_output, [])
conv_weight = marker_output
direct_consumers = consumers.get(conv_weight, [])
# FP8 Q/DQ runs in FP32, so a lower-precision Conv weight arrives through one Cast.
if len(direct_consumers) == 1 and direct_consumers[0].op_type == "Cast":
conv_weight = direct_consumers[0].output[0]
direct_consumers = consumers.get(conv_weight, [])
if (
len(direct_consumers) == 1
and direct_consumers[0].op_type == "Conv"
and len(direct_consumers[0].input) > 1
and direct_consumers[0].input[1] == marker_output
and direct_consumers[0].input[1] == conv_weight
):
continue
@@ -498,3 +557,73 @@ def normalize_dynamo_weight_paths(model: onnx.ModelProto) -> onnx.ModelProto:
_normalize_nvfp4_path(graph, marker, weight, prefix_reshape, path, terminal, producers)
return model
def _is_unlowered_marker(node: onnx.NodeProto) -> bool:
return (
node.op_type in _CARRIER_OPS
or node.op_type in _STATIC_MARKERS
or node.name.startswith((_DYNAMO_INT4_NODE_PREFIX, _DYNAMO_MXFP8_NODE_PREFIX))
)
def _reject_quantized_subgraphs(graph, _parent_node, is_subgraph):
if is_subgraph and any(
node.domain not in {"", "ai.onnx"}
or _is_unlowered_marker(node)
or node.op_type in _ALLOWED_TRT_OPS
or node.op_type in {"QuantizeLinear", "DequantizeLinear"}
for node in graph.node
):
raise NotImplementedError(
"Dynamo ONNX export does not support quantized or custom-domain subgraphs."
)
def finalize_dynamo_export(model: onnx.ModelProto, expected_opset: int) -> onnx.ModelProto:
"""Normalize final domains and reject unresolved Dynamo export artifacts."""
walk_subgraphs_recursive(model.graph, _reject_quantized_subgraphs)
producers = get_tensor_producer_nodes(model.graph)
initializers = {tensor.name: tensor for tensor in model.graph.initializer}
for node in model.graph.node:
if node.domain == "trt" and node.op_type == "QuantizeLinear":
node.domain = ""
elif node.domain == "trt" and node.op_type == "DequantizeLinear":
producer = producers.get(node.input[0])
initializer = initializers.get(node.input[0])
if (isinstance(producer, onnx.NodeProto) and producer.op_type == "QuantizeLinear") or (
initializer is not None and initializer.data_type == onnx.TensorProto.FLOAT8E4M3FN
):
node.domain = ""
unresolved = [
f"{node.domain}::{node.op_type}"
for node in model.graph.node
if _is_unlowered_marker(node)
or node.domain not in {"", "ai.onnx", "trt"}
or (node.op_type in _ALLOWED_TRT_OPS and node.domain != "trt")
or (node.domain == "trt" and node.op_type not in _ALLOWED_TRT_OPS)
]
if unresolved:
raise RuntimeError(
"Dynamo ONNX export left unresolved quantization operators: "
+ ", ".join(sorted(set(unresolved)))
)
if model.functions:
raise RuntimeError("Dynamo ONNX export left local ONNX functions in the model.")
default_opset = next(
(item for item in model.opset_import if item.domain in {"", "ai.onnx"}), None
)
if default_opset is None or default_opset.version != expected_opset:
actual = None if default_opset is None else default_opset.version
raise RuntimeError(f"Expected ONNX opset {expected_opset}; found {actual}.")
trt_nodes = [node for node in model.graph.node if node.domain == "trt"]
trt_import = next((item for item in model.opset_import if item.domain == "trt"), None)
if trt_nodes and (trt_import is None or trt_import.version != 1):
raise RuntimeError("TensorRT-domain operators require trt opset 1.")
if not trt_nodes and trt_import is not None:
model.opset_import.remove(trt_import)
_sync_initializer_metadata(model.graph)
return model
+53 -19
View File
@@ -78,6 +78,7 @@ class FP8QuantExporter(ONNXQuantExporter):
graph.cleanup().toposort().fold_constants().cleanup()
n_t_folded = 0
taken_names = set(graph.tensors())
for node in graph.nodes:
if node.op == "TRT_FP8QuantizeLinear":
@@ -104,6 +105,9 @@ class FP8QuantExporter(ONNXQuantExporter):
cast_to_remove = None
for candidate in list(dq_op.outputs[0].outputs):
if candidate.op == "Cast":
# Removing a dtype-changing Cast would retype the weight its consumer sees.
if candidate.outputs[0].dtype != dq_op.outputs[0].dtype:
continue
cast_to_remove = candidate
candidate = next(
(c for c in candidate.outputs[0].outputs if c.op == "Transpose"),
@@ -132,14 +136,27 @@ class FP8QuantExporter(ONNXQuantExporter):
# Replace it with Dequantize with FP8 weights. This is a WAR because numpy does not support fp8.
numpy_weights = (
(torch_weights / torch_scale).to(torch.float8_e4m3fn).view(torch.uint8).numpy()
(torch_weights / torch_scale)
.clamp_(-_FP8_E4M3_MAX, _FP8_E4M3_MAX)
.to(torch.float8_e4m3fn)
.view(torch.uint8)
.numpy()
)
tensor = onnx.TensorProto()
tensor.data_type = onnx.TensorProto.FLOAT8E4M3FN
tensor.dims.extend(numpy_weights.shape)
tensor.raw_data = numpy_weights.tobytes()
values = LazyValues(tensor)
onnx_weights_fp8 = gs.Constant(quantizer_name + "/fp8_weights", values)
# Distinct weights can share one deduplicated scale, and a weight's own name can
# match another scale's prefix, so check every name the graph already uses.
packed_name = quantizer_name + "/fp8_weights"
if packed_name in taken_names:
packed_name = weights.name + "/fp8_weights"
base_name, suffix = packed_name, 1
while packed_name in taken_names:
packed_name, suffix = f"{base_name}_{suffix}", suffix + 1
taken_names.add(packed_name)
onnx_weights_fp8 = gs.Constant(packed_name, values)
node.outputs.clear()
# Convert TRT DQ to native ONNX DequantizeLinear with FP8 weights
@@ -459,23 +476,8 @@ class FP8QuantExporter(ONNXQuantExporter):
return count
@staticmethod
def post_process(onnx_model: onnx.ModelProto) -> onnx.ModelProto:
"""Post-processes the ONNX model for FP8 quantization.
Converts TRT_FP8 QDQ ops to native ONNX QuantizeLinear/DequantizeLinear,
adds FP8 weight DQ for Conv layers whose weight quantizers were disabled during
TorchScript export, and rewrites attention scaling / K-transpose / softmax-output
patterns so TRT can fuse DQ into the attention MatMul kernels.
Args:
onnx_model: The ONNX model containing TRT_FP8 quantization nodes.
Returns:
The post-processed ONNX model with native ONNX quantization ops.
"""
logger.info("Post-processing FP8 quantized model")
graph = gs.import_onnx(onnx_model)
def _convert_trt_qdq_ops(graph: gs.Graph) -> None:
"""Convert TRT_FP8 Q/DQ ops to native ONNX QuantizeLinear/DequantizeLinear."""
# Convert TRT_FP8QuantizeLinear to native QuantizeLinear
for node in graph.nodes:
if node.op == "TRT_FP8QuantizeLinear":
@@ -502,6 +504,25 @@ class FP8QuantExporter(ONNXQuantExporter):
f"Converted {node.name} from TRT_FP8DequantizeLinear to DequantizeLinear"
)
@staticmethod
def post_process(onnx_model: onnx.ModelProto) -> onnx.ModelProto:
"""Post-processes the ONNX model for FP8 quantization.
Converts TRT_FP8 QDQ ops to native ONNX QuantizeLinear/DequantizeLinear,
adds FP8 weight DQ for Conv layers whose weight quantizers were disabled during
TorchScript export, and rewrites attention scaling / K-transpose / softmax-output
patterns so TRT can fuse DQ into the attention MatMul kernels.
Args:
onnx_model: The ONNX model containing TRT_FP8 quantization nodes.
Returns:
The post-processed ONNX model with native ONNX quantization ops.
"""
logger.info("Post-processing FP8 quantized model")
graph = gs.import_onnx(onnx_model)
FP8QuantExporter._convert_trt_qdq_ops(graph)
# Add FP8 weight DQ for Conv layers that had weight quantizers disabled during export
count = FP8QuantExporter._quantize_conv_weights_to_fp8(graph)
if count > 0:
@@ -519,3 +540,16 @@ class FP8QuantExporter(ONNXQuantExporter):
graph.cleanup().toposort()
return export_onnx(graph)
class _DynamoFP8QuantExporter(FP8QuantExporter):
"""Pack captured FP8 weights and keep every other Q/DQ where Dynamo captured it."""
@staticmethod
def post_process(onnx_model: onnx.ModelProto) -> onnx.ModelProto:
# Dynamo captures Conv weight and attention quantizers as eager runs them, so the legacy
# Conv reconstruction and attention fusion rewrites would only add or move quantization.
graph = gs.import_onnx(onnx_model)
FP8QuantExporter._convert_trt_qdq_ops(graph)
graph.cleanup().toposort()
return export_onnx(graph)
+27 -6
View File
@@ -23,9 +23,16 @@ from modelopt.onnx.quantization.graph_indexing import get_tensor_producer_nodes
from modelopt.onnx.quantization.qdq_utils import cast_initializer_to_dtype
from modelopt.onnx.quantization.quant_utils import pack_weights_to_int4
from ._dynamo_adapter import _DYNAMO_INT4_NODE_PREFIX
from .base_exporter import ONNXQuantExporter
def _get_weight_dq_nodes(graph: onnx.GraphProto) -> list[onnx.NodeProto]:
nodes = [node for node in graph.node if node.op_type == "DequantizeLinear"]
dynamo_nodes = [node for node in nodes if node.name.startswith(_DYNAMO_INT4_NODE_PREFIX)]
return dynamo_nodes or nodes
class INT4QuantExporter(ONNXQuantExporter):
"""Exporter for INT4 quantization."""
@@ -34,11 +41,16 @@ class INT4QuantExporter(ONNXQuantExporter):
"""Pre-processes the ONNX model for INT4 quantization."""
graph = onnx_model.graph
value_info_map = {value_info.name: value_info for value_info in graph.value_info}
weight_dq_nodes = [node for node in graph.node if node.op_type == "DequantizeLinear"]
weight_dq_nodes = _get_weight_dq_nodes(graph)
tensor_producer_map = get_tensor_producer_nodes(graph, get_initializer_producers=True)
nodes_to_remove = []
for node in weight_dq_nodes:
# The Dynamo adapter already restructured this weight and recorded its shape.
if node.name.startswith(_DYNAMO_INT4_NODE_PREFIX) and any(
attr.name == "_target_shape" for attr in node.attribute
):
continue
weight_name = node.input[0]
logger.debug(f"Restructuring graph for weight {weight_name}")
@@ -125,7 +137,7 @@ class INT4QuantExporter(ONNXQuantExporter):
"""Computes the scales for the weights in the ONNX model for INT4 quantization."""
graph = onnx_model.graph
initializer_map = {initializer.name: initializer for initializer in graph.initializer}
weight_dq_nodes = [node for node in graph.node if node.op_type == "DequantizeLinear"]
weight_dq_nodes = _get_weight_dq_nodes(graph)
tensor_producer_map = get_tensor_producer_nodes(graph, get_initializer_producers=True)
for node in weight_dq_nodes:
@@ -207,16 +219,18 @@ class INT4QuantExporter(ONNXQuantExporter):
"""Compresses the weights in the ONNX model for INT4 quantization."""
graph = onnx_model.graph
initializer_map = {initializer.name: initializer for initializer in graph.initializer}
weight_dq_nodes = [node for node in graph.node if node.op_type == "DequantizeLinear"]
weight_dq_nodes = _get_weight_dq_nodes(graph)
for node in weight_dq_nodes:
weight_name = node.input[0]
weight = numpy_helper.to_array(initializer_map[weight_name])
weight_shape = weight.shape
weights_int4_np = pack_weights_to_int4(weight)
# INT4 packs elements in flat order, so odd rows only need an even element count.
weights_int4_np = pack_weights_to_int4(weight.reshape(-1))
weights_int4_onnx = onnx.numpy_helper.from_array(weights_int4_np, weight_name)
weights_int4_onnx.data_type = onnx.TensorProto.INT4
weights_int4_onnx.dims[0] = weight_shape[0]
del weights_int4_onnx.dims[:]
weights_int4_onnx.dims.extend(weight_shape)
initializer_map[weight_name].CopyFrom(weights_int4_onnx)
logger.debug(f"Converted {weight_name} to INT4 precision")
@@ -225,12 +239,19 @@ class INT4QuantExporter(ONNXQuantExporter):
@staticmethod
def post_process(onnx_model: onnx.ModelProto) -> onnx.ModelProto:
"""Post-processes the ONNX model for INT4 quantization."""
graph = onnx_model.graph
dynamo_nodes = [n for n in graph.node if n.name.startswith(_DYNAMO_INT4_NODE_PREFIX)]
if dynamo_nodes:
# Dynamo emits only the casts the model computes, so the TorchScript cleanups below
# would change its types.
for node in dynamo_nodes:
node.name = node.name.removeprefix(_DYNAMO_INT4_NODE_PREFIX)
return onnx_model
def is_pre_quant_scale_node(node: onnx.NodeProto) -> bool:
has_pqs_input = any(input for input in node.input if "_pre_quant_scale" in input)
return node.op_type == "Mul" and has_pqs_input
graph = onnx_model.graph
initializer_map = {initializer.name: initializer for initializer in graph.initializer}
nodes_to_remove = []
+19 -9
View File
@@ -25,6 +25,7 @@ from modelopt.onnx.quantization.qdq_utils import _cast_fp8, onnx_dtype_map
from modelopt.onnx.quantization.quant_utils import compute_e8m0, get_amax
from modelopt.onnx.utils import get_attribute, has_attribute
from ._dynamo_adapter import _DYNAMO_MXFP8_NODE_PREFIX
from .base_exporter import ONNXQuantExporter
E8_M0_BIAS = 127
@@ -34,12 +35,9 @@ DEFAULT_QUANT_AXIS = -1
def _get_weight_dq_nodes(graph: onnx.GraphProto) -> list[onnx.NodeProto]:
"""Get weight DequantizeLinear nodes from the graph."""
return [
node
for node in graph.node
if node.op_type == "TRT_MXFP8DequantizeLinear"
and any(".weight" in inp for inp in node.input)
]
nodes = [node for node in graph.node if node.op_type == "TRT_MXFP8DequantizeLinear"]
dynamo_nodes = [node for node in nodes if node.name.startswith(_DYNAMO_MXFP8_NODE_PREFIX)]
return dynamo_nodes or [node for node in nodes if any(".weight" in inp for inp in node.input)]
def _get_quant_params(node: onnx.NodeProto) -> tuple[int, int]:
@@ -146,18 +144,30 @@ class MXFP8QuantExporter(ONNXQuantExporter):
def post_process(onnx_model: onnx.ModelProto) -> onnx.ModelProto:
"""Post-processes the ONNX model for MXFP8 quantization.
Sets DQ output type to FP16 and updates GELU nodes to use tanh approximation.
Sets FP32 DQ output types to FP16. For TorchScript graphs, sets every DQ output type to FP16,
updates GELU nodes to use tanh approximation and casts Sqrt outputs to FP16.
"""
logger.info("Post-processing MXFP8 quantized model")
graph = onnx_model.graph
dynamo_nodes = [n for n in graph.node if n.name.startswith(_DYNAMO_MXFP8_NODE_PREFIX)]
# Set output type of DQ to FP16
# Set output type of DQ to FP16. Dynamo DQs output the source type, and only FP32 graphs
# are converted to FP16 later, so BF16 and FP16 DQs keep theirs.
for node in graph.node:
if node.op_type == "TRT_MXFP8DequantizeLinear":
for attr in node.attribute:
if attr.name == "output_dtype":
if attr.name == "output_dtype" and (
not dynamo_nodes or attr.i == onnx_dtype_map["Float"]
):
attr.i = onnx_dtype_map["Half"]
if dynamo_nodes:
# Dynamo emits only the casts and Gelu approximation the model computes, so the
# TorchScript rewrites below would change its types and math.
for node in dynamo_nodes:
node.name = node.name.removeprefix(_DYNAMO_MXFP8_NODE_PREFIX)
return onnx_model
# Currently only tanh approximation is supported for Gelu
for node in graph.node:
if node.op_type == "Gelu":
+3 -2
View File
@@ -131,7 +131,7 @@ def _replace_fp4qdq_with_2dq(
w_f4_proto = onnx.helper.make_tensor(
name=w_f4_name,
data_type=onnx_dtype_map["Float4"],
dims=[w_f4.shape[0] * 2, *w_f4.shape[1:]],
dims=graph.initializer[initializer_indices[weight_name]].dims,
vals=w_f4.tobytes(),
raw=True,
)
@@ -302,7 +302,8 @@ class NVFP4QuantExporter(ONNXQuantExporter):
sw_f32_per_block, sw_f8_per_block = _encode_nvfp4_block_scale(sw_f32_per_block)
w_f32 = quantize(w32, block_size, sw_f32_per_block, sw_f32_per_tensor)
w_f4 = _cast_fp4(w_f32)
# FP4 packs elements in flat order, so odd rows only need an even element count.
w_f4 = _cast_fp4(w_f32.reshape(-1))
# Store compressed data as node attributes for post_process
w_f4_attr = node.attribute.add()
+35 -18
View File
@@ -23,7 +23,7 @@ import os
import sys
import tempfile
import uuid
from collections.abc import Iterator
from collections.abc import Collection, Iterator
from typing import Any
import numpy as np
@@ -1823,7 +1823,9 @@ def remove_redundant_casts(onnx_model: onnx.ModelProto) -> onnx.ModelProto:
return onnx_model
def fold_dq_fp32_to_fp16_casts(onnx_model: onnx.ModelProto) -> onnx.ModelProto:
def fold_dq_fp32_to_fp16_casts(
onnx_model: onnx.ModelProto, keep_fp32_dq_nodes: Collection[str] = ()
) -> onnx.ModelProto:
"""Remove Cast(FP32->FP16) nodes after DequantizeLinear by setting DQ output to FP16.
When convert_float_to_float16 blocks DequantizeLinear, it inserts Cast nodes to bridge
@@ -1838,6 +1840,8 @@ def fold_dq_fp32_to_fp16_casts(onnx_model: onnx.ModelProto) -> onnx.ModelProto:
Args:
onnx_model: The ONNX model with DQ -> Cast(FP32->FP16) patterns.
keep_fp32_dq_nodes: Names of nodes left in FP32 because FP16 cannot hold their scale.
Casts of their DQ outputs stay.
Returns:
The ONNX model with Cast nodes removed and DQ outputs set to FP16.
@@ -1868,6 +1872,23 @@ def fold_dq_fp32_to_fp16_casts(onnx_model: onnx.ModelProto) -> onnx.ModelProto:
retyped_dq_outputs: set[str] = set()
def _dq_chain(dq_node: onnx.NodeProto) -> list[onnx.NodeProto]:
"""Return the DQ and the DQs that produce its scale, outermost first."""
chain = [dq_node]
while len(chain) <= 4 and len(chain[-1].input) >= 2:
scale_producer = producer_map.get(chain[-1].input[1])
if scale_producer is None or scale_producer.op_type not in dq_ops:
break
chain.append(scale_producer)
return chain
# A kept DQ needs its whole scale chain in FP32, including scales other chains share.
kept_chains = [
_dq_chain(node) for node in onnx_model.graph.node if node.name in keep_fp32_dq_nodes
]
kept_dq_outputs = {dq.output[0] for chain in kept_chains for dq in chain}
kept_scales = {dq.input[1] for chain in kept_chains for dq in chain if len(dq.input) >= 2}
def _convert_fp32_init_to_fp16(init: onnx.TensorProto) -> None:
scale_data = np.frombuffer(init.raw_data, dtype=np.float32)
if not scale_data.size:
@@ -1876,23 +1897,13 @@ def fold_dq_fp32_to_fp16_casts(onnx_model: onnx.ModelProto) -> onnx.ModelProto:
init.raw_data = scale_data.astype(np.float16).tobytes()
del init.float_data[:]
def _retype_dq_chain(dq_node: onnx.NodeProto, depth: int = 0) -> None:
def _retype_dq_chain(chain: list[onnx.NodeProto]) -> None:
"""Propagate FP16 output type down through a DQ's scale chain."""
if depth > 4 or len(dq_node.input) < 2:
return
scale_name = dq_node.input[1]
scale_init = initializer_map.get(scale_name)
if scale_init is not None:
if scale_init.data_type == onnx.TensorProto.FLOAT:
for dq in chain:
scale_init = initializer_map.get(dq.input[1]) if len(dq.input) >= 2 else None
if scale_init is not None and scale_init.data_type == onnx.TensorProto.FLOAT:
_convert_fp32_init_to_fp16(scale_init)
return
scale_producer = producer_map.get(scale_name)
if scale_producer is None or scale_producer.op_type not in dq_ops:
return
_retype_dq_chain(scale_producer, depth + 1)
if scale_name in value_info_map:
value_info_map[scale_name].type.tensor_type.elem_type = onnx.TensorProto.FLOAT16
retyped_dq_outputs.add(scale_name)
retyped_dq_outputs.update(dq.output[0] for dq in chain[1:])
nodes_to_remove = []
for node in onnx_model.graph.node:
@@ -1909,8 +1920,14 @@ def fold_dq_fp32_to_fp16_casts(onnx_model: onnx.ModelProto) -> onnx.ModelProto:
producer = producer_map.get(node.input[0])
if producer is None or producer.op_type not in dq_ops:
continue
chain = _dq_chain(producer)
if any(
dq.output[0] in kept_dq_outputs or (len(dq.input) >= 2 and dq.input[1] in kept_scales)
for dq in chain
):
continue
_retype_dq_chain(producer)
_retype_dq_chain(chain)
_bypass_cast_node(onnx_model, node)
nodes_to_remove.append(node)
@@ -22,6 +22,7 @@ import onnx_graphsurgeon as gs
import onnxruntime as ort
import pytest
from onnx import TensorProto, helper, numpy_helper
from onnx.reference import ReferenceEvaluator
from modelopt.onnx.export import (
FP8QuantExporter,
@@ -543,6 +544,76 @@ class TestFP8QuantExporter:
)
assert output_scale.data_type == TensorProto.BFLOAT16
@pytest.mark.parametrize("compute_dtype", [np.float32, np.float16])
def test_fp8_packing_preserves_clipping_and_casts(self, compute_dtype):
weights = gs.Constant(
"weight", np.array([[1.0, 0.0, -1.0], [0.5, 0.25, -0.25]], dtype=np.float32)
)
scale = gs.Constant("linear/weight_quantizer/scale", np.array(0.5 / 448, dtype=np.float32))
q = gs.Variable("q", dtype=TensorProto.FLOAT8E4M3FN, shape=(2, 3))
dq = gs.Variable("dq", dtype=np.float32, shape=(2, 3))
cast = gs.Variable("cast", dtype=compute_dtype, shape=(2, 3))
transposed = gs.Variable("transposed", dtype=compute_dtype, shape=(3, 2))
inputs = gs.Variable("inputs", dtype=compute_dtype, shape=(1, 3))
output = gs.Variable("output", dtype=compute_dtype, shape=(1, 2))
graph = gs.Graph(
nodes=[
gs.Node(op="TRT_FP8QuantizeLinear", inputs=[weights, scale], outputs=[q]),
gs.Node(op="TRT_FP8DequantizeLinear", inputs=[q, scale], outputs=[dq]),
gs.Node(
op="Cast",
inputs=[dq],
outputs=[cast],
attrs={
"to": TensorProto.FLOAT16
if compute_dtype == np.float16
else TensorProto.FLOAT
},
),
gs.Node(
op="Transpose", inputs=[cast], outputs=[transposed], attrs={"perm": [1, 0]}
),
gs.Node(op="MatMul", inputs=[inputs, transposed], outputs=[output]),
],
inputs=[inputs],
outputs=[output],
opset=23,
)
converted = FP8QuantExporter.compress_weights(gs.export_onnx(graph))
onnx.checker.check_model(converted, full_check=True)
actual = ReferenceEvaluator(converted).run(
None, {"inputs": np.array([[1.0, 2.0, 3.0]], dtype=compute_dtype)}
)[0]
assert actual.dtype == compute_dtype
np.testing.assert_allclose(actual, np.array([[-1.0, 0.25]], dtype=compute_dtype))
def test_fp8_packing_keeps_weights_that_share_a_scale_apart(self):
# The second weight's name matches the shared scale's prefix, so both fallbacks collide.
scale = gs.Constant("block.weight/scale", np.array(1 / 448, dtype=np.float32))
inputs = gs.Variable("inputs", dtype=np.float32, shape=(1, 2))
nodes, outputs = [], []
for index, (name, value) in enumerate([("w0", 1.0), ("block.weight", -0.5)]):
weight = gs.Constant(name, np.full((2, 2), value, dtype=np.float32))
q = gs.Variable(f"q{index}", dtype=TensorProto.FLOAT8E4M3FN, shape=(2, 2))
dq = gs.Variable(f"dq{index}", dtype=np.float32, shape=(2, 2))
output = gs.Variable(f"y{index}", dtype=np.float32, shape=(1, 2))
nodes += [
gs.Node(op="TRT_FP8QuantizeLinear", inputs=[weight, scale], outputs=[q]),
gs.Node(op="TRT_FP8DequantizeLinear", inputs=[q, scale], outputs=[dq]),
gs.Node(op="MatMul", inputs=[inputs, dq], outputs=[output]),
]
outputs.append(output)
graph = gs.Graph(nodes=nodes, inputs=[inputs], outputs=outputs, opset=23)
converted = FP8QuantExporter.compress_weights(gs.export_onnx(graph))
onnx.checker.check_model(converted, full_check=True)
actual = ReferenceEvaluator(converted).run(
None, {"inputs": np.ones((1, 2), dtype=np.float32)}
)
np.testing.assert_allclose(actual[0], [[2.0, 2.0]])
np.testing.assert_allclose(actual[1], [[-1.0, -1.0]])
class TestMXFP8QuantExporter:
"""Test suite for MXFP8QuantExporter."""
@@ -708,6 +779,28 @@ class TestFP4QDQTo2DQ:
cast_nodes = [node for node in converted_model.graph.node if node.op_type == "Cast"]
assert len(cast_nodes) >= 1 # At least one cast node should be added
def test_fp4qdq_conversion_packs_odd_rows(self):
# Three rows of one 16-element block each; every value is on the FP4 grid.
grid = np.array([0, 0.5, 1, 1.5, 2, 3, 4, 6], dtype=np.float32)
weight = np.stack([np.concatenate([grid, -grid]) * scale for scale in (1, 2, 0.5)])
graph = helper.make_graph(
[
helper.make_node("TRT_FP4QDQ", ["weight"], ["weight_dq"], block_size=16),
helper.make_node("Identity", ["weight_dq"], ["output"]),
],
"odd_rows",
[],
[helper.make_tensor_value_info("output", TensorProto.FLOAT, [3, 16])],
[numpy_helper.from_array(weight, "weight")],
value_info=[helper.make_tensor_value_info("weight_dq", TensorProto.FLOAT, [3, 16])],
)
converted = NVFP4QuantExporter.process_model(helper.make_model(graph))
packed = next(i for i in converted.graph.initializer if i.name == "weight_f4")
assert list(packed.dims) == [3, 16]
np.testing.assert_array_equal(ReferenceEvaluator(converted).run(None, {})[0], weight)
def create_test_model_with_int4_dq_matmul():
"""Create a simple test model with INT4 DequantizeLinear -> MatMul pattern.
+225 -1
View File
@@ -16,10 +16,15 @@
"""Behavior-level tests for the private Dynamo ONNX graph adapter."""
import numpy as np
import onnx
import pytest
from onnx import TensorProto, helper, numpy_helper
from modelopt.onnx.export._dynamo_adapter import normalize_dynamo_weight_paths
from modelopt.onnx.export._dynamo_adapter import (
finalize_dynamo_export,
normalize_dynamo_weight_paths,
)
from modelopt.onnx.export.int4_exporter import INT4QuantExporter
def _tensor(name, values, dtype=np.float32):
@@ -708,6 +713,65 @@ def test_normalize_leaves_fp8_attention_activation_qdq_intact(domain, operand):
assert model.SerializeToString() == original
def test_int4_packer_ignores_standard_int8_qdq_in_dynamo_graph():
# An odd first dimension checks that packing keeps the logical shape.
values = np.arange(-3, 3, dtype=np.float32).reshape(3, 2)
weight = _tensor("weight", values)
int4_scale = _tensor("int4_scale", np.ones((3, 1)))
int8_scale = _tensor("int8_scale", 0.25)
int8_zero = _tensor("int8_zero", 0, np.int8)
model = _model(
[
helper.make_node(
"DequantizeLinear",
["weight", "int4_scale"],
["weight_dq"],
name="int4_weight_dq",
axis=1,
block_size=2,
),
helper.make_node("MatMul", ["input", "weight_dq"], ["matmul_output"], name="matmul"),
helper.make_node(
"QuantizeLinear",
["matmul_output", "int8_scale", "int8_zero"],
["int8_q"],
name="int8_q",
),
helper.make_node(
"DequantizeLinear",
["int8_q", "int8_scale", "int8_zero"],
["output"],
name="int8_dq",
),
],
initializers=[
weight,
int4_scale,
int8_scale,
int8_zero,
],
inputs=[_value("input", shape=(2, 3))],
outputs=[_value("output", shape=(2, 2))],
)
normalize_dynamo_weight_paths(model)
INT4QuantExporter.process_model(model)
packed = next(tensor for tensor in model.graph.initializer if tensor.name == "weight")
assert packed.data_type == TensorProto.INT4
assert list(packed.dims) == [3, 2]
np.testing.assert_array_equal(numpy_helper.to_array(packed), values)
int8_dq = next(node for node in model.graph.node if node.output[0] == "output")
assert int8_dq.op_type == "DequantizeLinear" and len(int8_dq.input) == 3
int4_dq = next(
node
for node in model.graph.node
if node.op_type == "DequantizeLinear" and len(node.input) == 2
)
assert next(attr.i for attr in int4_dq.attribute if attr.name == "block_size") == 2
def test_normalize_leaves_standard_int8_conv_weight_qdq_intact():
model = _model(
[
@@ -731,3 +795,163 @@ def test_normalize_leaves_standard_int8_conv_weight_qdq_intact():
"DequantizeLinear",
"Conv",
]
@pytest.mark.parametrize(
("domain", "op_type", "name"),
[
("tensorrt", "quantize_op", ""),
("", "dynamic_block_quantize_op", ""),
("trt", "TRT_FP4QDQ", ""),
("trt", "DequantizeLinear", ""),
("trt", "UnsupportedQuantize", ""),
("custom", "QuantizeLinear", ""),
("", "TRT_FP4DynamicQuantize", ""),
("", "DequantizeLinear", "__modelopt_dynamo_int4__weight"),
("trt", "TRT_MXFP8DequantizeLinear", "__modelopt_dynamo_mxfp8__weight"),
],
)
def test_finalize_rejects_unresolved_or_unapproved_operators(domain, op_type, name):
model = _model(
[helper.make_node(op_type, ["input"], ["output"], domain=domain, name=name)],
inputs=[_value("input")],
outputs=[_value("output")],
trt_opset=1,
)
with pytest.raises(RuntimeError, match="unresolved quantization operators"):
finalize_dynamo_export(model, 23)
@pytest.mark.parametrize(
("domain", "op_type"),
[
("trt", "TRT_FP8QuantizeLinear"),
("trt", "TRT_FP4QDQ"),
("trt", "TRT_FP4DynamicQuantize"),
("custom", "Identity"),
("", "QuantizeLinear"),
("", "Identity"),
],
)
def test_finalize_checks_nested_if_branches_before_mutation(domain, op_type):
branch = helper.make_graph(
[helper.make_node(op_type, ["input"], ["branch_output"], domain=domain)],
"nested_branch",
[],
[_value("branch_output")],
)
for depth in range(2):
branch = helper.make_graph(
[
helper.make_node(
"If",
["condition"],
[f"if_output_{depth}"],
then_branch=branch,
else_branch=branch,
)
],
f"branch_{depth}",
[],
[_value(f"if_output_{depth}")],
)
model = _model(
list(branch.node),
inputs=[_value("input"), _value("condition", TensorProto.BOOL, ())],
outputs=list(branch.output),
trt_opset=1,
)
original = model.SerializeToString()
if domain or op_type != "Identity":
with pytest.raises(NotImplementedError, match="subgraphs"):
finalize_dynamo_export(model, 23)
assert model.SerializeToString() == original
else:
assert finalize_dynamo_export(model, 23) is model
assert [(item.domain, item.version) for item in model.opset_import] == [("", 23)]
def test_finalize_synchronizes_initializer_and_dq_metadata_and_drops_unused_trt_import():
weight = _tensor("weight", np.ones((2, 4)), np.uint8)
scale = _tensor("scale", 0.5)
model = _model(
[
helper.make_node("DequantizeLinear", ["weight", "scale"], ["weight_dq"]),
helper.make_node("Cast", ["weight_dq"], ["weight_half"], to=TensorProto.FLOAT16),
],
initializers=[weight, scale],
inputs=[_value("weight", TensorProto.FLOAT, (9,))],
outputs=[_value("weight_half", TensorProto.FLOAT, (9,))],
value_info=[
_value("weight", TensorProto.FLOAT, (9,)),
_value("weight_dq", TensorProto.FLOAT, (9,)),
],
trt_opset=1,
)
finalize_dynamo_export(model, 23)
assert [(item.domain, item.version) for item in model.opset_import] == [("", 23)]
weight_type = model.graph.input[0].type.tensor_type
duplicate_weight_type = model.graph.value_info[0].type.tensor_type
dq_type = model.graph.value_info[1].type.tensor_type
output_type = model.graph.output[0].type.tensor_type
assert weight_type.elem_type == TensorProto.UINT8
assert [dim.dim_value for dim in weight_type.shape.dim] == [2, 4]
assert duplicate_weight_type.elem_type == TensorProto.UINT8
assert [dim.dim_value for dim in duplicate_weight_type.shape.dim] == [2, 4]
assert dq_type.elem_type == TensorProto.FLOAT
assert [dim.dim_value for dim in dq_type.shape.dim] == [2, 4]
assert output_type.elem_type == TensorProto.FLOAT16
assert [dim.dim_value for dim in output_type.shape.dim] == [2, 4]
def test_finalize_keeps_explicit_dq_output_dtype():
# Opset 23 DQ can output FP16 from an FP32 scale.
model = _model(
[
helper.make_node(
"DequantizeLinear",
["weight", "scale"],
["weight_dq"],
output_dtype=TensorProto.FLOAT16,
),
helper.make_node("Relu", ["weight_dq"], ["output"]),
],
initializers=[_tensor("weight", np.ones((2, 4)), np.uint8), _tensor("scale", 0.5)],
outputs=[_value("output", TensorProto.FLOAT16)],
value_info=[_value("weight_dq", TensorProto.FLOAT16)],
)
finalize_dynamo_export(model, 23)
(dq_value,) = (value for value in model.graph.value_info if value.name == "weight_dq")
assert dq_value.type.tensor_type.elem_type == TensorProto.FLOAT16
onnx.checker.check_model(model, full_check=True)
@pytest.mark.parametrize(
("model_opset", "trt_opset", "message"),
[
(24, None, "found 24"),
(23, None, "TensorRT-domain operators require trt opset 1"),
(23, 2, "TensorRT-domain operators require trt opset 1"),
],
)
def test_finalize_requires_exact_opset_imports(model_opset, trt_opset, message):
nodes = []
if model_opset == 23:
nodes.append(
helper.make_node("TRT_FP4DynamicQuantize", ["input"], ["output"], domain="trt")
)
model = _model(
nodes,
inputs=[_value("input")],
outputs=[_value("output")],
opset=model_opset,
trt_opset=trt_opset,
)
with pytest.raises(RuntimeError, match=message):
finalize_dynamo_export(model, 23)
+48
View File
@@ -97,3 +97,51 @@ def test_fold_is_noop_below_min_opset(fold_fn, build_model, scale_name):
assert "Cast" in {n.op_type for n in folded.graph.node}
scale = next(i for i in folded.graph.initializer if i.name == scale_name)
assert scale.data_type == TensorProto.FLOAT
def _dq(scale, output, name=""):
return helper.make_node("DequantizeLinear", ["w_q", scale, "zp"], [output], name)
@pytest.mark.parametrize(
"kept_nodes",
[
# The kept DQ dequantizes the folded DQ's scale.
[_dq("tiny_scale", "s", "kept_dq"), _dq("s", "dq_out")],
# A kept sibling shares the folded DQ's scale.
[_dq("tiny_scale", "kept", "kept_dq"), _dq("tiny_scale", "dq_out")],
# A kept DQ's own scale DQ shares a scale with the folded DQ's scale DQ.
[
_dq("tiny_scale", "kept_s"),
_dq("kept_s", "kept", "kept_dq"),
_dq("tiny_scale", "s"),
_dq("s", "dq_out"),
],
],
)
def test_fold_keeps_scales_of_fp32_dq_nodes(kept_nodes):
# FP16 rounds this scale to zero, so the DQ chains that read it must stay in FP32.
model = helper.make_model(
helper.make_graph(
[
*kept_nodes,
helper.make_node("Cast", ["dq_out"], ["cast_out"], "cast", to=TensorProto.FLOAT16),
helper.make_node("Relu", ["cast_out"], ["y"]),
],
"g",
[],
[helper.make_tensor_value_info("y", TensorProto.FLOAT16, [4, 4])],
initializer=[
numpy_helper.from_array(np.array(1e-10, dtype=np.float32), "tiny_scale"),
numpy_helper.from_array(np.array(0, dtype=np.int8), "zp"),
numpy_helper.from_array(np.ones((4, 4), dtype=np.int8), "w_q"),
],
),
opset_imports=[helper.make_opsetid("", 19)],
)
folded = fold_dq_fp32_to_fp16_casts(model, keep_fp32_dq_nodes=["kept_dq"])
scale = next(i for i in folded.graph.initializer if i.name == "tiny_scale")
assert scale.data_type == TensorProto.FLOAT
assert "cast" in {n.name for n in folded.graph.node}