Repository navigation
[2/4] [6466805] Add private Dynamo ONNX quantization lowering - #2683
Conversation
Signed-off-by: ajrasane <[email protected]>
|
Auto-sync is disabled for draft pull requests in this repository. Workflows must be run manually. Contributors can view more details about this message here. |
|
Important Review skippedAuto reviews are disabled on base/target branches other than the default branch. 🗂️ Base branches to auto review (3)
Please check the settings in the CodeRabbit UI or the ⚙️ Run configuration
You can disable this status message by setting the Use the checkbox below for a quick retry:
Comment |
cjluo-nv
left a comment
There was a problem hiding this comment.
Bot review (bedrock-claude-opus-5-5) — DM the bot to share feedback.
Requesting changes: the INT4 lowering emits standard-domain DequantizeLinear on float weights with no test, and several of the format branches it adds are never exercised.
Needs action:
- Fix or justify the INT4 branch in
_dynamo_onnx.py(inline). Legacyexport_int4emitstrt::DequantizeLinearbecause the input is still float. Standard ONNXDequantizeLineardoesn't accept float32/16 input. If #2684 makes the input int4 first, say so in the PR body. - Add tests to
test_dynamo_onnx_export.pyfor the untested branches: INT4 AWQ, signed INT8 export (it only appears in rejection tests), static NVFP4TRT_FP4QDQ, and dynamic MXFP8. - Decide what INT8 should do when
axisis given butamaxis per-tensor, e.g. shape(1,1)(inline). Legacy falls back to per-tensor whenamax.numel()==1. This branch emits a per-axis Q/DQ with a length-1 scale.
No action needed:
- Core logic is about 263 lines, under budget. The new file carries the standard NVIDIA Apache header, so there's no licensing concern.
- The PR body explains why the legacy
GraphContextcallbacks can't be reused for Dynamo's ONNXScript table, and the dtype map is shared. I accept that rationale. - I read the tests but didn't run them. CI doesn't run on this stacked base, as the PR body says.
| output_dtype = _resolve_dtype(inputs, high_precision_dtype) | ||
| amax = _OPSET.Cast(amax, to=output_dtype) | ||
| scale = _OPSET.Div(amax, _OPSET.CastLike(7.0, amax)) | ||
| output = _OPSET.DequantizeLinear(inputs, scale, axis=axis, block_size=block_size) |
There was a problem hiding this comment.
Bot comment.
Legacy export_int4 emits trt::DequantizeLinear here because inputs is still the float weight. Standard ONNX DequantizeLinear (opset 23) only accepts integer/float8/float4 types for x, so float32/16 input fails onnx.checker.check_model(full_check=True). That's the same check _assert_valid_without_custom_ops runs. Either emit the TRT-domain op like the legacy path, or explain in the PR body how #2684 turns inputs into int4 before this op runs. Either way, please add an INT4 test. Also consider rejecting amax is None here with a clear error.
There was a problem hiding this comment.
Fixed in d0e1447: INT4 now uses a typed trt::DequantizeLinear carrier while its input is float, matching the legacy path, and reports missing amax clearly. The lowering preserves intermediate dtype/shape metadata for mixed FP16 weight and FP32 scale inputs. Added FP32/FP16 strict INT4 export coverage with full ONNX checking. The next stack PR needs the accompanying carrier-domain adapter change; that patch was validated with the public FP16 INT4 AWQ export and remains pending in #2684.
| ), "TensorRT strongly typed mode requires Q/DQ in the input dtype, FP32, or BF16." | ||
| inputs = _cast(inputs, output_dtype) | ||
| input_rank = len(input_shape) | ||
| amax_shape = _static_shape(amax) |
There was a problem hiding this comment.
Bot comment.
When axis is passed explicitly and amax has no non-1 dims (e.g. (1,1) or a scalar), quantized_axis stays set. amax then gets reshaped to [1], and this emits a per-axis Q/DQ whose scale length (1) doesn't match input.shape[axis]. Legacy export_int8 falls back to per-tensor whenever amax.numel()==1. Suggest setting axis = None when quantized_axes is empty, and adding a test for it.
There was a problem hiding this comment.
Fixed in d0e1447: a one-element amax emits scalar scale/zero-point Q/DQ even with an explicit valid axis. Added regression cases for scalar, (1,), and (1,1) amax with positive and negative axes; existing multi-axis and axis-mismatch checks remain covered.
| ) | ||
| return onnx.numpy_helper.to_array(_attribute(node, "value")) | ||
|
|
||
|
|
There was a problem hiding this comment.
Bot comment.
_STRICT_CASES never covers signed int8 export (it only shows up in the rejection tests), INT4, nvfp4_static (TRT_FP4QDQ), or mxfp8_dynamic (TRT_MXFP8DynamicQuantize). Each of those is its own branch in the translation table, so please add a case for each.
There was a problem hiding this comment.
Added all four positive format cases in d0e1447: signed INT8, INT4 AWQ, static NVFP4, and dynamic MXFP8. The format matrix exercises FP32/FP16 strict capture and full ONNX checking, plus output dtype and INT4/INT8 attribute checks. The focused capture/lowering suite passes all 67 tests.
Signed-off-by: ajrasane <[email protected]>
cjluo-nv
left a comment
There was a problem hiding this comment.
Bot review (bedrock-claude-opus-5-5) — DM the bot to share feedback.
Approving: all three concerns from the last review are fixed in d0e1447fe, and each fix has a test.
No action needed:
- ✔️ Resolved since the last review: the INT4 lowering now emits
trt::DequantizeLinearand raises a clear error whenamaxis missing; a one-element INT8amaxnow falls back to per-tensor even whenaxisis given; and there are now positive tests for signed INT8, INT4 AWQ, static NVFP4 and dynamic MXFP8. - About 266 lines of core logic, under the 500-line budget. The new files carry the standard NVIDIA Apache header, so there's no licensing concern.
- The INT4 TRT-domain carrier only works end to end once the adapter change in #2684 lands. That belongs to the next PR in the stack, so it doesn't block this one.
- Minor: INT8 with
amax=Nonewould fail through_static_shapewith a misleading "dynamic shapes" error. Callers aren't expected to pass that today. - I read the tests but didn't run them. CI doesn't run on this stacked base, as the PR body notes.
### What does this PR do? Type of change: new feature Part 2 of the four-PR Dynamo ONNX export stack replacing #2418. Adds one private ONNXScript translation table for `quantize_op.default` and both dynamic-block overloads. Typed helpers cover FP8, INT8, INT4 AWQ, MXFP8, and NVFP4 without adding a public translation-table API or a direct `torch.onnx.ops` path. Adds 266 source lines (492 total additions including tests). Why a separate lowering implementation: the legacy `export_onnx.py` callbacks build TorchScript graphs through `GraphContext`, `torch.Value`, and `g.op`; Dynamo's custom translation table consumes ONNXScript symbolic tensors and returns ONNXScript values. Those callbacks are not interchangeable. Rewriting legacy graph construction into a common builder would enlarge this change and risk the requirement of no observable legacy changes. The dtype mapping and downstream format packers remain shared. The maintenance cost is two frontend-specific implementations of scale, axis, and dtype rules: future format changes need corresponding legacy and Dynamo tests. Within Dynamo, both capture strategies use this same table. INT4 lowering emits a TRT-domain DequantizeLinear carrier while its weights are still floating point, matching the legacy exporter. Intermediate output metadata is retained for mixed weight/scale dtypes. The normalization layer in #2684 needs the accompanying compatibility change to accept this carrier and convert it to the standard-domain packing form. That companion patch passed 51 adapter/packing tests plus the public FP16 INT4 AWQ export regression in an isolated copy; it remains a dependency for the downstream stack. ### Usage Internal prerequisite only. The table is private; bare `torch.onnx.export(..., dynamo=True)` is not a supported ModelOpt deployment workflow. Public helper wiring and static-weight packing land in part 4. ### Testing Ran this branch independently with CUDA hidden on PyTorch 2.14 development: **67 passed**. ```bash CUDA_VISIBLE_DEVICES="" python -m pytest -o addopts= -p no:cacheprovider \ tests/unit/torch/quantization/test_tensor_quant_cpu.py \ tests/unit/torch/quantization/test_dynamo_onnx_export.py -q ``` Strict captured-program translation covers signed INT8, INT4 AWQ, static NVFP4, dynamic MXFP8, and the existing formats in FP32/FP16. Regressions check INT8 singleton-scale fallback, missing INT4 amax, INT4 intermediate dtype metadata, and axis/shape errors. Exported test graphs pass full ONNX checking. Changed-file pre-commit checks and `git diff --check` passed. GPU and full multi-version CI were not rerun for this split. ### Before your PR is "*Ready for review*" Contributor guidelines: https://github.com/NVIDIA/Model-Optimizer/blob/main/CONTRIBUTING.md. Commits are signed and signed off with `git commit -s -S`. Security Best Practices: https://github.com/NVIDIA/Model-Optimizer/blob/main/SECURITY.md#security-coding-practices-for-contributors. - Is this change backward compatible?: ✅ - 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 — private prerequisite; part 4 contains the single user-facing feature entry. - Did you get Claude approval on this PR?: Pending re-review after addressing the three review findings. ### Additional Information Merge order: capture → lowering → normalization → integration. This PR targets `ajrasane/dynamo-onnx-capture` and must merge after part 1. Model-level preflight validation lands with its helper caller in part 4, keeping each source diff below 500 lines. > 🤖 _Generated by Codex (AI agent)._ ### Replacement stack Merge in order; each PR targets the preceding branch. Retarget the next PR when its dependency merges. 1. [#2682: capture and CPU routing](#2682) 2. [#2683: private ONNXScript lowering](#2683) 3. [#2684: canonical weight normalization](#2684) 4. [#2685: helper and deployment integration](#2685) CI note: repository pull-request workflows target `main`, `release/*`, and `feature/*`. They do not automatically run for this stacked base. Full CI needs manual workflow dispatch or retargeting after the dependency merges; the independent local validation above passed. --------- Signed-off-by: Ajinkya Rasane <[email protected]>
#2682) ### What does this PR do? Type of change: new feature Part 1 of the four-PR Dynamo ONNX export stack replacing #2418. Adds export metadata as optional trailing custom-op schema arguments, keeps amax detached during compiler capture, and routes CPU integer carriers through the existing tensor implementation. Legacy positional calls and eager numerical behavior are preserved. This is capture plumbing only; the supported quantized ONNX helper workflow is enabled in part 4. Automatic CPU INT8/INT4 carrier routing is deferred until the ONNX helper supplies its translation table. CPU integer quantizers retain the existing tensor-math path; the registered carriers can be captured explicitly. ### Usage No new public interface in this prerequisite. Existing quantization calls remain unchanged. ### Testing With CUDA hidden on PyTorch 2.14 development: **91 passed** across CPU quantization and ONNX helper tests. ```bash CUDA_VISIBLE_DEVICES="" python -m pytest -o addopts= -p no:cacheprovider \ tests/unit/torch/quantization/test_tensor_quant_cpu.py \ tests/unit/torch/deploy/utils/test_torch_onnx_utils.py -q ``` On PyTorch 2.9 development, the focused CPU quantization suite also passed **40 tests**, and both INT8/INT4 Dynamo helper calls retained their working legacy fallback. Coverage includes legacy positional schemas, CPU numerical parity, real strict `torch.export` capture of the registered INT8/INT4 carriers, and FP8 `TensorQuantizer` capture. Changed-file pre-commit checks and `git diff --check` passed. GPU and full multi-version CI were not run for this revision. Compatibility probes compared the original PR with its pinned `main` base on PyTorch 2.9, 2.13, and 2.14 development builds. For fixed-amax CPU INT8/INT4 quantizers, the original PR captured a carrier but failed ONNX translation; the base failed earlier on data-dependent capture. The PyTorch 2.9 helper succeeded for both through legacy fallback. These probes do not establish that nobody uses CPU Dynamo export, so this revision preserves the existing CPU routing instead of relying on that assumption. ### Before your PR is "*Ready for review*" Contributor guidelines: https://github.com/NVIDIA/Model-Optimizer/blob/main/CONTRIBUTING.md. Commits are signed and signed off with `git commit -s -S`. Security Best Practices: https://github.com/NVIDIA/Model-Optimizer/blob/main/SECURITY.md#security-coding-practices-for-contributors. - Is this change backward compatible?: ✅ - 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 — private prerequisite for the same unreleased feature; the user-facing feature entry lands with the helper in part 4. - Did you get Claude approval on this PR?: Review feedback addressed; awaiting re-review. ### Additional Information Merge order: capture → lowering → normalization → integration. This PR targets `main`; part 2 targets this branch. Parts 1–3 intentionally do not expose a new export workflow. The complete feature remains helper-owned and supports FP8, INT8, INT4 AWQ, MXFP8, NVFP4, and mixed FP8 + NVFP4. > 🤖 _Generated by Codex (AI agent)._ ### Replacement stack Merge in order; each PR targets the preceding branch. Retarget the next PR when its dependency merges. 1. [#2682: capture and CPU routing](#2682) 2. [#2683: private ONNXScript lowering](#2683) 3. [#2684: canonical weight normalization](#2684) 4. [#2685: helper and deployment integration](#2685) <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **New Features** * Dynamo ONNX export now supports quantization and dequantization for FP8, INT8/UINT8, INT4, NVFP4, and MXFP8 formats, with validation for supported configurations. * Quantization operators accept optional TensorRT dtype, block-size, axis, and ONNX quantizer metadata. * **Bug Fixes** * CPU quantization now matches eager fake-quantization behavior for supported inputs. * Quantization scale values are detached during export. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Signed-off-by: ajrasane <[email protected]> Signed-off-by: Ajinkya Rasane <[email protected]>
) ### What does this PR do? Type of change: new feature Part 3 of the four-PR Dynamo ONNX export stack replacing #2418. Adds a private canonical static-weight normalizer: initializer → optional constant reshape → format marker → optional restoring views/cast/transpose → one MatMul/Gemm weight input. It validates provenance and layout, materializes independent scales, and rejects shared weights, fanout, arbitrary views, or mismatched Q/DQ paths. Adds 484 source lines (1,175 total additions including tests). Final validation, metadata synchronization, and the packer integration hooks land together in part 4 so this slice stays below the source budget. No new helper behavior or changes to legacy packers are enabled here. ### Usage Internal prerequisite only. The normalizer is not a supported public export API; part 4 connects it to `get_onnx_bytes_and_metadata(..., dynamo_export=True)`. The normalized graph is an intermediate representation for the format packers and is not valid standalone ONNX. NVFP4 normalization removes the export-only Cast, so an fp16 Gemm can temporarily receive an fp32 weight. INT4 normalization removes restoring views and can leave blocked weights feeding MatMul directly. Part 4 runs the packers to restore the final layout and dtype, then performs final ONNX validation. ### Testing Ran the focused suite with CUDA hidden in the PyTorch 26.08 development container (PyTorch 2.14) on a source snapshot verified against the checkout: **93 passed**. ```bash CUDA_VISIBLE_DEVICES="" python -m pytest -o addopts= -p no:cacheprovider \ tests/unit/torch/quantization/test_tensor_quant_cpu.py \ tests/unit/torch/quantization/test_dynamo_onnx_export.py \ tests/unit/onnx/test_dynamo_adapter.py -q ``` Covers canonical paths; INT4 last-axis/full-block validation, prefix reshapes, restoring transpose and Cast rewiring; independent INT4/MXFP8 scales and packer name prefixes; NVFP4 Gemm transB toggling; unchanged FP8 attention Q/K/V and projected activations; unchanged INT8 convolution paths; and fail-closed static/dynamic weight-view errors. The original PR implementation fails 12 of the new axis/block and activation regression cases. Changed-file pre-commit checks and `git diff --check` passed. GPU and full multi-version CI were not rerun for this split. ### Before your PR is "*Ready for review*" Contributor guidelines: https://github.com/NVIDIA/Model-Optimizer/blob/main/CONTRIBUTING.md. Commits are signed and signed off with `git commit -s -S`. Security Best Practices: https://github.com/NVIDIA/Model-Optimizer/blob/main/SECURITY.md#security-coding-practices-for-contributors. - Is this change backward compatible?: ✅ - 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 — private prerequisite; part 4 contains the single user-facing feature entry. - Did you get Claude approval on this PR?: Pending — follow-up changes address the review; re-review is still required. ### Additional Information Merge order: capture → lowering → normalization → integration. This PR targets `ajrasane/dynamo-onnx-lowering` and must merge after part 2. Its tests call the normalizer without any dependency on later helper/packer changes. > 🤖 _Generated by Codex (AI agent)._ ### Replacement stack Merge in order; each PR targets the preceding branch. Retarget the next PR when its dependency merges. 1. [#2682: capture and CPU routing](#2682) 2. [#2683: private ONNXScript lowering](#2683) 3. [#2684: canonical weight normalization](#2684) 4. [#2685: helper and deployment integration](#2685) CI note: repository pull-request workflows target `main`, `release/*`, and `feature/*`. They do not automatically run for this stacked base. Full CI needs manual workflow dispatch or retargeting after the dependency merges; the independent local validation above passed. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **New Features** * Added support for exporting quantized models through Dynamo for INT4, INT8, FP8, NVFP4, and MXFP8 formats. * Improved CPU quantization support, including per-tensor, per-axis, and block quantization. * **Bug Fixes** * Improved handling of quantized weights and scales during ONNX export, including supported reshapes and shared scales. * Preserved correct quantization behavior for FP8 attention activations and INT8 convolution weights. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Signed-off-by: ajrasane <[email protected]>
What does this PR do?
Type of change: new feature
Part 2 of the four-PR Dynamo ONNX export stack replacing #2418. Adds one private ONNXScript translation table for
quantize_op.defaultand both dynamic-block overloads. Typed helpers cover FP8, INT8, INT4 AWQ, MXFP8, and NVFP4 without adding a public translation-table API or a directtorch.onnx.opspath. Adds 266 source lines (492 total additions including tests).Why a separate lowering implementation: the legacy
export_onnx.pycallbacks build TorchScript graphs throughGraphContext,torch.Value, andg.op; Dynamo's custom translation table consumes ONNXScript symbolic tensors and returns ONNXScript values. Those callbacks are not interchangeable. Rewriting legacy graph construction into a common builder would enlarge this change and risk the requirement of no observable legacy changes. The dtype mapping and downstream format packers remain shared. The maintenance cost is two frontend-specific implementations of scale, axis, and dtype rules: future format changes need corresponding legacy and Dynamo tests. Within Dynamo, both capture strategies use this same table.INT4 lowering emits a TRT-domain DequantizeLinear carrier while its weights are still floating point, matching the legacy exporter. Intermediate output metadata is retained for mixed weight/scale dtypes. The normalization layer in #2684 needs the accompanying compatibility change to accept this carrier and convert it to the standard-domain packing form. That companion patch passed 51 adapter/packing tests plus the public FP16 INT4 AWQ export regression in an isolated copy; it remains a dependency for the downstream stack.
Usage
Internal prerequisite only. The table is private; bare
torch.onnx.export(..., dynamo=True)is not a supported ModelOpt deployment workflow. Public helper wiring and static-weight packing land in part 4.Testing
Ran this branch independently with CUDA hidden on PyTorch 2.14 development: 67 passed.
CUDA_VISIBLE_DEVICES="" python -m pytest -o addopts= -p no:cacheprovider \ tests/unit/torch/quantization/test_tensor_quant_cpu.py \ tests/unit/torch/quantization/test_dynamo_onnx_export.py -qStrict captured-program translation covers signed INT8, INT4 AWQ, static NVFP4, dynamic MXFP8, and the existing formats in FP32/FP16. Regressions check INT8 singleton-scale fallback, missing INT4 amax, INT4 intermediate dtype metadata, and axis/shape errors. Exported test graphs pass full ONNX checking. Changed-file pre-commit checks and
git diff --checkpassed. GPU and full multi-version CI were not rerun for this split.Before your PR is "Ready for review"
Contributor guidelines: https://github.com/NVIDIA/Model-Optimizer/blob/main/CONTRIBUTING.md. Commits are signed and signed off with
git commit -s -S.Security Best Practices: https://github.com/NVIDIA/Model-Optimizer/blob/main/SECURITY.md#security-coding-practices-for-contributors.
CONTRIBUTING.md: N/A — neither added.Additional Information
Merge order: capture → lowering → normalization → integration. This PR targets
ajrasane/dynamo-onnx-captureand must merge after part 1. Model-level preflight validation lands with its helper caller in part 4, keeping each source diff below 500 lines.Replacement stack
Merge in order; each PR targets the preceding branch. Retarget the next PR when its dependency merges.
CI note: repository pull-request workflows target
main,release/*, andfeature/*. They do not automatically run for this stacked base. Full CI needs manual workflow dispatch or retargeting after the dependency merges; the independent local validation above passed.