Repository navigation
Conversation
|
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. |
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
No actionable comments were generated in the recent review.
|
| Layer / File(s) | Summary |
|---|---|
Export API and quantization validation modelopt/torch/_deploy/utils/torch_onnx.py, modelopt/torch/quantization/_dynamo_onnx.py, modelopt/torch/quantization/tensor_quant.py, tests/unit/torch/quantization/*, tests/unit/torch/deploy/utils/test_torch_onnx_utils.py |
The helper selects opset 23 for Dynamo export and opset 20 for legacy export when no opset is provided. Dynamo export validates supported quantizer configurations, preserves Python scalar arguments, rejects dynamic axes and opsets below 23, and disables exporter fallback when available. Tests cover supported formats, validation, and export behavior. |
Quantized graph normalization and finalization modelopt/onnx/export/_dynamo_adapter.py, modelopt/onnx/export/int4_exporter.py, modelopt/onnx/export/mxfp8_exporter.py, tests/unit/onnx/test_dynamo_adapter.py |
The adapter converts eligible quantization operators, checks opset imports and unresolved operators, and synchronizes graph metadata. INT4 and MXFP8 post-processing selects Dynamo-exported nodes. Tests cover graph transformations and finalization checks. |
TensorRT wiring and execution coverage modelopt/torch/_deploy/_runtime/tensorrt/engine_builder.py, modelopt/torch/_deploy/_runtime/trt_client.py, examples/torch_onnx/torch_quant_to_onnx.py, tests/examples/torch_onnx/*, tests/unit/torch/deploy/_runtime/tensorrt/test_engine_builder.py |
The TensorRT builder can enable decomposable attentions, and the client forwards the option. The example CLI enables it for Dynamo export and rejects TensorRT builds for INT4 AWQ models. Tests cover export and execution for supported formats, including mixed FP8 and NVFP4 AutoQuant models. |
Examples and export documentation examples/onnx_ptq/download_example_onnx.py, examples/torch_onnx/README.md, docs/source/guides/_pytorch_quantization.rst, CHANGELOG.rst |
The examples and documentation describe Dynamo export options, supported weight paths, opset defaults, and TensorRT limitations. The PTQ helper forwards the Dynamo and opset arguments. |
Priority:
Estimated code review effort: 4 (Complex) | ~60 minutes
Change: Feature
Sequence Diagram(s)
sequenceDiagram
participant Caller
participant get_onnx_bytes_and_metadata
participant QuantizationValidation
participant torch_onnx_export
participant finalize_dynamo_export
participant TRTLocalClient
participant build_engine
Caller->>get_onnx_bytes_and_metadata: request Dynamo export
get_onnx_bytes_and_metadata->>QuantizationValidation: validate quantized model
get_onnx_bytes_and_metadata->>torch_onnx_export: capture ONNX graph
get_onnx_bytes_and_metadata->>finalize_dynamo_export: finalize graph and metadata
TRTLocalClient->>build_engine: compile ONNX with decomposable-attention option
Suggested reviewers: cjluo-nv
Merge Risk: 
Minimal · up to 7fd9d
-
No concrete merge-blocking issue is established by this review; the change is mergeable subject to normal checks.
Pre-merge checks: 
5
-
Full details: Security Anti-Patterns
-
Explanation
PASS. The reviewed additions in modelopt and examples contain no torch.load(..., weights_only=False), numpy.load/np.load(..., allow_pickle=True), hardcoded trust_remote_code=True, external-input eval()/exec(), or new # nosec comments. The only # nosec lines are unchanged from the base revision. No pyproject.toml or requirements file changed.
-
Finishing Touches
-
📝 Generate docstrings
-
- Commit to this branch
- Create a new PR
🧪 Generate unit tests (beta)
-
- Commit to this branch
- Create a new PR
-
- Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts
Comment @coderabbitai help to get the list of available commands.
### 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: ajrasane <[email protected]>
cjluo-nv
left a comment
There was a problem hiding this comment.
Bot review (gpt-6.1-sol) — DM the bot to share feedback.
Changes requested: Dynamo scalar arguments can misname tensor inputs, and the new TensorRT guard rejects disabled INT4 quantizers.
Needs action:
- Fix Dynamo input-name filtering in
torch_onnx.py; add interleaved scalar/tensor regressions that exercisegenerate_onnx_inputand inference (see inline). - Fix the INT4 build guard in
torch_quant_to_onnx.pyto consider enabled weight quantizers, and test disabled INT4 weights (see inline). - Run or manually dispatch the supported Torch-version matrix and GPU/TensorRT tests on the current stack heads; link results before merging.
No action needed:
- The design addresses quantized Dynamo export without disturbing TorchScript: separate ONNXScript lowering is justified over reusing
GraphContextcallbacks or building a shared graph framework; existing dtype maps and packers remain shared. - Existing test edits retain model-parsing coverage and add opset assertions. The new file's header matches
LICENSE_HEADER. - Tests were inspected, not executed.
| # provided which is somewhat inconsistent (we always tensorize them!) | ||
| named_args, _ = standardize_named_model_args(model, dummy_input) | ||
| named_args = {k: _to_expected_onnx_type(v) for k, v in named_args.items()} | ||
| if not dynamo_export: |
There was a problem hiding this comment.
Bot comment.
Leaving Python scalars untensorized is appropriate for Dynamo specialization, but input_names below still includes every non-None leaf. Dynamo assigns these names to the remaining tensor graph inputs. For forward(self, flag: bool, x: Tensor) exported with (True, tensor), the tensor input receives flag rather than x; generate_onnx_input(metadata, args) then supplies the boolean under that name. Interleaved scalars similarly shift subsequent tensor names. Filter the Dynamo naming list to tensor leaves while retaining the full tree specification. Add a scalar-before-tensor and an interleaved-scalar regression that checks names and executes the graph using generated inputs; the current scalar test only puts scalars after the sole tensor.
There was a problem hiding this comment.
Fixed in 001d2f8d8. Dynamo input names now include tensor leaves only while retaining the full input tree and recording actual None inputs separately. Leading, trailing, and interleaved scalar regressions check generated names and execute ONNX Runtime inference with inputs from generate_onnx_input and changed tensor values.
| # Blackwell has no tactic for an FP8 Q→Conv fusion on the first RGB layer. | ||
| _disable_low_channel_fp8_conv_input_quantizers(quantized_model) | ||
|
|
||
| if args.trt_build and is_int4_quantized(quantized_model): |
There was a problem hiding this comment.
Bot comment.
is_int4_quantized() checks the stored weight bit width and whether the input quantizer is disabled, but does not check whether the weight quantizer is enabled. Disabling an INT4 layer leaves its bit-width configuration intact, so this new guard rejects --trt_build even when that layer exports ordinary floating weights. Check enabled INT4 weight quantizers (and preserve detection of enabled INT4 selections in mixed models), and add guard regressions for both enabled and disabled INT4 weights.
There was a problem hiding this comment.
Fixed in 001d2f8d8. Shared INT4 detection now requires enabled weight quantizers. CLI regressions use mixed FP8/INT4 models with all INT4 weights disabled or either INT4 layer enabled; the disabled case completes real ONNX export and full ONNX checking, while enabled INT4 weights still reject the build.
Codecov Report❌ Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## main #2685 +/- ##
==========================================
+ Coverage 73.80% 78.34% +4.53%
==========================================
Files 662 669 +7
Lines 75894 81816 +5922
==========================================
+ Hits 56016 64100 +8084
+ Misses 19878 17716 -2162
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
### 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]>
2a398ad to
6311787
Compare
001d2f8 to
2736824
Compare
Signed-off-by: ajrasane <[email protected]>
Signed-off-by: ajrasane <[email protected]>
Signed-off-by: ajrasane <[email protected]>
Signed-off-by: ajrasane <[email protected]>
Signed-off-by: ajrasane <[email protected]>
9f0981f to
5fd691a
Compare
shengliangxu
left a comment
There was a problem hiding this comment.
Bot review (gpt-6.1-sol) — DM the bot to share feedback.
Changes requested: zero-calibrated FP8 weights can become NaN during packing, and final validation misses quantization artifacts inside subgraphs.
Needs action:
- Fix zero-scale handling before Dynamo FP8 weight packing and add a numerical zero-weight regression; see
_dynamo_onnx.pyinline comment. - Validate nested graphs in
_dynamo_adapter.py, rejecting unsupported quantized branches before returning an export; see inline comment. - Move the Dynamo feature entry in
CHANGELOG.rstto the current0.49.0Quantization section rather than0.48.0.
No action needed:
- The separate-frontend/shared-packer rationale is reasonable, and the existing test edits preserve coverage.
| if not torch.isfinite(amax).all() or (amax < 0).any(): | ||
| raise ValueError(f"Quantizer '{name}' has an invalid amax tensor.") | ||
| if quant_format == "fp8" and amax.numel() != 1: | ||
| raise NotImplementedError("Dynamo FP8 export requires per-tensor scalar amax.") |
There was a problem hiding this comment.
Bot comment.
Zero amax passes this preflight, but a calibrated FP8 Linear with all-zero weights is not safe downstream. _translate_quantize_op emits scale = amax / 448, and FP8QuantExporter.compress_weights computes torch_weights / torch_scale before converting to FP8. For zero weights this is 0 / 0, producing NaN weights. The later replace_zero_scale_with_smallest_nonzero only repairs the scale, not those packed NaNs, while eager _fp8_eager returns finite zeros. Could the FP8 lowering use a zero-safe scale before packing, as the INT8 lowering already does? Add a helper-level export/execution regression for an all-zero calibrated FP8 Linear, checking finite weights and numerical agreement.
There was a problem hiding this comment.
Fixed in 7fd9d09d0. Dynamo FP8 lowering now substitutes a same-dtype positive scale when the computed scale is zero, before weight packing. Helper-level all-zero calibrated Linear regressions verify finite packed FP8 weights and execute the exported graph against eager PyTorch for FP32 and FP16. Both zero-weight cases fail against the original implementation and pass with the fix.
|
|
||
| unresolved = [ | ||
| f"{node.domain}::{node.op_type}" | ||
| for node in model.graph.node |
There was a problem hiding this comment.
Bot comment.
This scans only the top-level graph. An If/Loop branch containing trt::TRT_FP8QuantizeLinear, TRT_FP4QDQ, or an unapproved custom-domain node is invisible to this check. Normalization and the format packers likewise process only the root graph, so finalization can return unresolved branch artifacts; it can also remove the trt import when TRT operators exist only in a branch. Please inspect GRAPH/GRAPHS attributes recursively and fail closed on unsupported quantized subgraphs (supporting branch packing is not necessary for this PR). The repo already has walk_subgraphs_recursive in modelopt/onnx/autocast/utils.py. Add an If regression containing a nested marker and a nested TRT-domain operator.
There was a problem hiding this comment.
Fixed in 7fd9d09d0. Finalization now uses the existing recursive graph walker (GRAPH and GRAPHS) to reject quantized/custom-domain subgraphs before mutating root nodes or imports. Nested If regressions cover markers, TRT-domain operators, custom domains, and standard Q/DQ; rejected models remain byte-for-byte unchanged, and ordinary If branches remain accepted. Branch packing remains unsupported.
| - The ``iq1_s``, ``iq1_m``, ``iq2_xxs``, ``iq2_xs`` and ``iq2_s`` encoders accept an optional per-input-column ``importance`` that weights each value's squared error in the codebook search, as llama.cpp's imatrix does. GPTQ's new ``importance_weighted`` option passes them the square root of its Hessian diagonal, and the built-in IQ1 and IQ2 recipes enable it, so each block's search favours the columns its outputs depend on most. | ||
| - A recipe can now **delegate its whole body to another recipe** with a top-level ``$import``; any top-level key given alongside it overrides the imported one. ``metadata.recipe_type`` became optional along with it: a recipe states its kind with a ``# modelopt-schema:`` comment, with ``metadata.recipe_type``, or by delegating to a recipe that does, and only a recipe that another file imports has to carry the schema comment. Whatever a recipe does state must be true: a schema comment and a ``recipe_type`` must agree, and so must a recipe and the recipe it delegates to. ``modelopt_recipes/models/`` uses this for checkpoint entries that a portable recipe already reproduces: the entry aliases that recipe instead of copying it. | ||
| - Backfill the recipes behind NVIDIA's already-published checkpoints under ``modelopt_recipes/models/``, so a released checkpoint's quantization scheme is reachable from its own model-hub path rather than only from the general tier. For example, ``moonshotai/Kimi-K2.6`` (published as ``nvidia/Kimi-K2.6-NVFP4``) and ``Qwen/Qwen3.5-397B-A17B`` (published as ``nvidia/Qwen3.5-397B-A17B-NVFP4-V2``) each alias a portable recipe wholesale -- the general expert-only NVFP4 recipe and the ``qwen3_5_moe`` architecture recipe respectively -- rather than copying its body; other checkpoints follow in separate changes. | ||
| - Add opt-in Dynamo ONNX export through ``get_onnx_bytes_and_metadata(..., dynamo_export=True)`` for FP8, INT8, INT4 AWQ, MXFP8, NVFP4, and mixed FP8 plus NVFP4 AutoQuant models with canonical Linear, MatMul, or Gemm weight paths. Dynamo export defaults to opset 23; the legacy opset-20 exporter remains the default. |
There was a problem hiding this comment.
Bot comment.
This new feature is being inserted under 0.48.0, while the fetched branch already has 0.49.0 at the top. Please place the entry in the current release's **New Features** / *Quantization* section so the changelog does not imply this integration shipped in the previous release.
There was a problem hiding this comment.
Fixed in 7fd9d09d0. Moved the existing Dynamo feature entry to 0.49.0 → New Features → Quantization; no duplicate entry remains under 0.48.0.
There was a problem hiding this comment.
🔇 Additional comments: 1
CHANGELOG.rst-123-123: 1
123-123:Minor · Functional Correctness · Quick win
⚠️ Unverified finding
Verification ran but could not confirm this finding. It is shown for review, not as a verified issue.Move this entry to the 0.49.0 section.
This entry is under 0.48.0, although 0.49.0 is the current section. It tells users that 0.48.0 includes this export path.

Review info
-
Run configuration-
- Source mode: Auto
- Repository: NVIDIA/Model-Optimizer
- Branch: ajrasane/dynamo-onnx-integration
- File: .coderabbit.yaml
- Commit: 5fd691a
- Layers: Repository YAML
- Review profile: CHILL
- Plan: Enterprise
- Run ID:
b37fd792-7a44-4158-bdd4-0de6a0b01ca7
Files selected for processing: 7-
CHANGELOG.rstexamples/torch_onnx/torch_quant_to_onnx.pymodelopt/torch/_deploy/_runtime/tensorrt/engine_builder.pymodelopt/torch/quantization/tensor_quant.pytests/examples/torch_onnx/test_torch_quant_to_onnx.pytests/unit/torch/deploy/_runtime/tensorrt/test_engine_builder.pytests/unit/torch/quantization/test_tensor_quant_cpu.py
Included review availability: This review used your included allowance. Your plan provides up to 12 included reviews per hour; 11 remain after this review.
-
Signed-off-by: ajrasane <[email protected]>
Blackwell TensorRT execution results2 passed, 0 skipped. Both existing integration tests built real TensorRT engines and executed them on an NVIDIA RTX PRO 6000 Blackwell Max-Q Workstation Edition (SM 12.0). Outputs were finite and passed the existing numerical comparisons against PyTorch with
The mixed search selected 3 FP8 Linear weights and 1 NVFP4 Linear weight. The test's assertion that both formats were selected passed. Both comparisons used output shape Environment: PyTorch 2.14 development build from The model is the existing reduced ViT integration fixture: no pretrained weights, image size 32, depth 1, embedding dimension 128, four heads, and 16 output classes. Export uses Dynamo with opset 23 and TensorRT decomposable attention enabled. Test functions and assertions were unchanged; observation wrappers delegated to the original calls to record errors and selected-format counts. To reproduce the tests: PYTHONPATH=.:tests python -m pytest -o addopts= -vv -rA \
'tests/examples/torch_onnx/test_dynamo_onnx_export.py::test_quantized_dynamo_onnx_executes_with_tensorrt[nvfp4]' \
tests/examples/torch_onnx/test_dynamo_onnx_export.py::test_fp8_nvfp4_autoquant_executes_with_tensorrt \
--junitxml=blackwell-results.xmlResult excerpt: The review corrections also passed 234 focused export/deployment unit tests (1 skipped) and 9 CLI/export regressions. The new regressions reproduce eight failures against the original implementation, covering packed FP8 NaNs, nested graph artifacts, and the unsupported TensorRT opset combination. Changed-file pre-commit checks and |
shengliangxu
left a comment
There was a problem hiding this comment.
Bot review (gpt-6.1-sol) — DM the bot to share feedback.
Changes requested: the newly enabled FP8 Conv path discards calibrated weight scales and can quantize explicitly excluded Conv layers.
Needs action:
- Preserve calibrated scales and disabled Conv weights in the Dynamo integration in
torch_onnx.py; add numerical and exclusion regressions (see inline). - 💬 Author supplied Blackwell execution results — still link successful required repository CI, including the supported Torch-version matrix, for the current head.
No action needed:
- ✔️ Resolved since earlier reviews: scalar input naming, disabled-INT4 detection, zero-scale FP8 Linear packing, recursive subgraph rejection, TensorRT opset validation, and changelog placement.
- Existing test edits preserve coverage; the separate-lowering/shared-packer design is justified.
| and module.input_quantizer.is_enabled | ||
| and ( | ||
| module.input_quantizer.is_enabled | ||
| or isinstance(module, (nn.Conv1d, nn.Conv2d, nn.Conv3d)) |
There was a problem hiding this comment.
Bot comment.
[P1] Preserve Conv quantizer state when enabling this path. This now selects FP8QuantExporter for weight-only FP8 Conv, but get_onnx_bytes_and_metadata() still enters _disable_fp8_conv_weight_quantizers() during Dynamo capture. Consequently there is no weight marker, and FP8QuantExporter.post_process() calls _quantize_conv_weights_to_fp8(), which recomputes the scale from the raw weight maximum rather than using the calibrated quantizer.
For example, a Conv with disabled input quantization, weights equal to 1, and weight amax=0.5 passes preflight. Eager FP8 clips its weights to 0.5, whereas this export reconstructs weights equal to 1, doubling the output. This also arises when weights change after calibration during QAT. The restoration pass scans every constant-weight Conv, so a second Conv whose weight quantizer is explicitly disabled is packed anyway.
Could Dynamo retain its Conv weight markers instead of applying the TorchScript unknown-shape workaround, and restrict any restoration pass to the actual enabled Conv weights? Extend the Conv helper-export tests with a numerical calibrated-clipping case and an explicitly disabled Conv weight.
There was a problem hiding this comment.
Fixed in c8e6b006b. Dynamo now retains Conv weight markers and calibrated scales; its FP8 pipeline skips the legacy reconstruction pass, preserving explicitly disabled Conv weights. The shared packer saturates normalized FP8 weights before conversion, so the weight=1/amax=0.5 case clips correctly rather than becoming NaN. Four numerical FP32/FP16 helper regressions verify clipping, scale preservation, finite packed weights, and exclusions; all four fail before this fix and pass afterward. The focused suite passed 244 unit tests (1 skipped) plus 9 CLI tests, and all six Blackwell integration cases passed without skips. Details: #2685 (comment)
Signed-off-by: ajrasane <[email protected]>
FP8 Conv review fix and Blackwell validationDynamo capture now retains Conv weight quantizers and their calibrated scales. Its shared FP8 packing pipeline skips the legacy Conv reconstruction pass, so explicitly excluded Conv weights remain floating. FP8 packing saturates normalized weights before conversion, matching eager clipping and preventing NaNs when weights exceed their calibrated range. Focused validation: 244 export/deployment/legacy-FP8 unit tests passed (1 skipped), plus 9 CLI/export regressions. The four new helper-level Conv regressions cover calibrated clipping, finite packed weights, preserved scales, and explicitly excluded Conv weights in FP32 and FP16 exports. All four fail against the previous implementation. Changed-file pre-commit checks and Blackwell integration: 6 passed, 0 skipped. FP8, INT8, MXFP8, NVFP4, and mixed FP8/NVFP4 built real TensorRT engines and passed numerical execution against PyTorch. INT4 AWQ passed export and full ONNX checking; it remains export/checker-only.
The mixed search selected 3 FP8 Linear weights and 1 NVFP4 Linear weight; the existing assertion requiring both formats passed. All execution outputs were finite, with output shape Environment: NVIDIA RTX PRO 6000 Blackwell Max-Q Workstation Edition (SM 12.0), PyTorch 2.14 development build from The existing reduced ViT fixture uses no pretrained weights, image size 32, depth 1, embedding dimension 128, four heads, and 16 classes. Export uses Dynamo opset 23 and decomposable TensorRT attention. Test functions/assertions were unchanged; observation wrappers delegated to the original implementation to record numerical errors and selected formats. To reproduce: PYTHONPATH=.:tests python -m pytest -o addopts= -vv -rA \
tests/examples/torch_onnx/test_dynamo_onnx_export.py \
--junitxml=blackwell-results.xml |
shengliangxu
left a comment
There was a problem hiding this comment.
Bot review (gpt-6.1-sol) — DM the bot to share feedback.
Changes requested: prior bugs are fixed, but the FP8 zero-scale fallback mishandles positive FP16 ranges and NVFP4 ignores requested BF16 precision.
Needs action:
- Fix positive-scale underflow in
_dynamo_onnx.pyand extend the numerical helper regression to small, nonzero FP16 weights; see inline. - Honor or explicitly reject
weights_dtype="bf16"for Dynamo NVFP4 intorch_onnx.py; add a precision-contract regression. - 💬 Author supplied six Blackwell results — still link passing required repository CI, including the supported Torch-version matrix, for the current head.
No action needed:
- ✔️ 7 prior concerns addressed, including calibrated Conv scales/exclusions and recursive subgraph rejection.
- Separate lowering/shared packers remain justified; existing test edits preserve coverage.
| scale = _OPSET.Div(_OPSET.CastLike(amax, inputs), _OPSET.CastLike(448.0, inputs)) | ||
| scale = _OPSET.Where( | ||
| _OPSET.Equal(scale, _OPSET.CastLike(0.0, scale)), | ||
| _OPSET.CastLike(1.0, scale), |
There was a problem hiding this comment.
Bot comment.
[P1] This fallback also catches underflow of a positive calibrated scale, not just a genuinely zero range. CastLike(amax, inputs) / 448 runs in FP16 for an FP16 Linear. With weights and calibrated weight amax approximately 1e-5, the scale is approximately 2.2e-8, which rounds to zero in FP16; this branch substitutes 1.0, and packing those weights to E4M3 then rounds every weight to zero. In contrast, tensor_quant._fp8_eager computes normalization in FP32 and preserves the nonzero weights. The existing all-zero regression cannot detect this. Could the lowering preserve positive small scales, for example through FP32 Q/DQ with source-dtype boundaries, rather than treating their underflow as an uncalibrated range? Extend the helper numerical test with a calibrated FP16 Linear filled with small nonzero weights and check agreement with eager execution.
There was a problem hiding this comment.
Fixed in 9221795b4. FP8 scaling/QDQ now run in FP32 with source-dtype boundaries retained through packing and conversion. Extended helper regressions cover small nonzero FP16 weights with default and explicit FP16 requests, plus mixed-format conversion. Both new Blackwell TensorRT execution cases preserved nonzero outputs and matched eager with zero numerical error. Validation details.
| ["Div"] | ||
| if preserve_block_io_types | ||
| else ["QuantizeLinear", "DequantizeLinear", "Div"] | ||
| ) |
There was a problem hiding this comment.
Bot comment.
[P2] The new (dynamo_export and uses_fp4) condition routes pure NVFP4 through convert_float_to_float16 even when the caller requests weights_dtype="bf16". Pure NVFP4 passes the earlier BF16 checks because uses_other_unsupported_quantizer excludes NVFP4, so a float32 NVFP4 model with this option takes the FP16 conversion path and never reaches convert_to_f16(..., low_precision_type=weights_dtype). Its floating compute/bias/I/O are converted to FP16 despite the BF16 request. Please honor BF16 here, or reject this combination before capture if unsupported, and extend the NVFP4 helper test to assert the requested precision contract.
There was a problem hiding this comment.
Fixed in 9221795b4. Dynamo NVFP4 explicitly rejects BF16 requests before model execution/capture. Pure NVFP4 and mixed FP8/NVFP4 regressions verify this precision contract and confirm forward was not called. Legacy export and ONNX-load behavior are retained. Validation details.
Signed-off-by: ajrasane <[email protected]>
Signed-off-by: ajrasane <[email protected]>
|
Latest validation for the updated PR code. The zero-calibration regression was reproduced before the fix: all four CPU cases failed with an output difference of 16 (exported 32 versus eager 16). Sanitizing FP32 amax before dividing by 448 restores the eager clipping range. The extended helper matrix now passes 12 cases, including zero weights, small positive weights, and zero activation calibration followed by nonzero inference in FP32/FP16 with default/explicit FP16 requests.
Blackwell environment: RTX PRO 6000 Blackwell Max-Q, SM 12.0; Python 3.12.3; PyTorch 2.14.0a0+4fdf77b940.nv26.8.63802676; CUDA 13.4; TensorRT 11.2.1.2; ONNX 1.21.0; ONNXScript 0.7.1; ONNX Runtime 1.30.0. All nine numerical cases below built a real TensorRT engine, executed it, asserted finite outputs, and passed torch.testing.assert_close against the quantized PyTorch model. INT4 AWQ is the tenth integration case and is export/full-checker-only.
Mixed AutoQuant selected three FP8 Linear weights and one NVFP4 Linear weight; the test independently asserts both formats were selected before building/executing the engine. Both zero-activation-calibration TensorRT cases have zero numerical error after calibrating with zeros and inferring with inputs 2. The complete integration suite took 522.05 seconds; the two separate compatibility exports took 143.79 seconds. Peak PyTorch CUDA allocation was 70,181,888 bytes for the mixed case; this does not include TensorRT/CUDA allocations outside PyTorch. Reproduction (in a supported CUDA/TensorRT development environment; GPU cases require the corresponding hardware): pytest tests/unit/onnx/test_dynamo_adapter.py tests/unit/onnx/quantization/test_fp8_mha_exporter.py tests/unit/onnx/quantization/test_qdq_utils.py::TestFP8QuantExporter
pytest tests/unit/torch/quantization/test_dynamo_onnx_export.py tests/unit/torch/quantization/test_tensor_quant_cpu.py tests/unit/torch/deploy/utils/test_torch_onnx_utils.py tests/unit/torch/deploy/_runtime/tensorrt/test_engine_builder.py
pytest tests/examples/onnx_ptq/test_download_example_onnx.py tests/examples/torch_onnx/test_torch_quant_to_onnx.py
pytest tests/examples/torch_onnx/test_dynamo_onnx_export.py
pytest tests/examples/torch_onnx/test_hf_embedding_quant_to_onnx.pyProvenance: tests ran at their owning stack slices. The final aggregate stack tree equals the updated PR tree exactly. GPU/Torch tests ran at 698af3ce600d68ca4d210708a77528ea232e3549; the final Torch slice only adds an inherited ONNX test-file change, which passed at the final ONNX slice. Wrapper/CLI results likewise precede only that ONNX test-file addition; their application/test sources are unchanged. This is local execution evidence, not successful repository CI or a complete Torch-version matrix. Changed-file pre-commit checks and git diff --check passed for all four slices. Separate Standards and Spec reviews found no remaining code findings. A full tests/unit run was attempted but stopped during collection because the private development environment lacks immutabledict; no full-suite pass is claimed. Older-Torch focused execution could not collect in its separate image because OmegaConf was unavailable; it does not establish a Torch 2.8/2.9 matrix pass. |
|
Current-head CI for 55ef35939:
No required-CI pass is claimed yet. Before merging, link successful required checks and the complete configured Torch 2.8–2.14 matrix, explicitly including 2.8 and 2.9, on each resulting stack head. The earlier canceled partial-install job and timed-out example job are not current-head passing evidence. CI details remain outside the PR Testing section. |
shengliangxu
left a comment
There was a problem hiding this comment.
Bot review (gpt-6.1-sol) — DM the bot to share feedback.
Changes requested: the 520-line integration needs splitting, and zero-calibrated FP8 activations export with different numerical behavior from eager.
Needs action:
- ✂️ Split into linear, linked
[x/4]PRs, merging in order:[1/4]modelopt/onnxpackers/finalization;[2/4]modelopt/torchintegration;[3/4]examples/onnx_ptqwrapper;[4/4]examples/torch_onnxCLI/compatibility. State dependencies; each must build, include tests, and pass CI independently. - Fix zero-
amaxFP8 parity in_dynamo_onnx.pyand extend helper execution coverage to nonzero inference inputs after zero calibration; see inline. - 💬 Author reports eight Blackwell passes and unfinished CI — link successful required checks and all configured Torch-version jobs, including 2.8/2.9, for the resulting heads.
No action needed:
- ✔️ 9 prior code/documentation concerns addressed, including positive-scale underflow, NVFP4 BF16 precision, and calibrated Conv scales/exclusions.
- Existing test edits preserve coverage and reflect opset/capture changes; the separate-lowering/shared-packer design remains justified.
| return _fp8_qdq(inputs, scale) | ||
| scale = _OPSET.Where( | ||
| _OPSET.Equal(scale, _OPSET.CastLike(0.0, scale)), | ||
| _OPSET.CastLike(1.0, scale), |
There was a problem hiding this comment.
Bot comment.
[P2] This zero-scale fallback differs from eager FP8. Both tensor_quant._fp8_eager and CUDA fake_e4m3fy substitute amax = 1, then derive the dequantization scale 1/448. Substituting scale = 1 here instead changes the clipping range from [-1, 1] to [-448, 448].
For example, use an FP8 Linear(16, 16, bias=False) with weights filled with 1, calibrate its input quantizer with zeros, then export and execute with inputs filled with 2. The allowed zero activation amax reaches this branch: eager clips each input to 1 and yields 16, whereas the exported graph retains 2 and yields 32.
Could this sanitize zero amax before dividing, matching eager, rather than substituting a unit scale afterward? Extend the helper numerical regression with zero activation calibration followed by nonzero inference inputs. The current all-zero-weight cases produce zeros with either fallback and cannot catch this discrepancy.
There was a problem hiding this comment.
Verified and fixed in 9f69988b. The lowering now sanitizes FP32 amax using the eager/CUDA overflow threshold before dividing by 448, preserving scale 1/448 for a zero range. The uncalibrated amax=None path remains unchanged.
Reproduced the reported output 32 versus 16 failure in all four added CPU cases before the fix; all 12 helper cases now pass. Both Blackwell TensorRT zero-calibration cases also built and executed successfully with zero numerical error for default/explicit FP16 requests. Execution evidence and reproduction commands.
Signed-off-by: ajrasane <[email protected]>
Signed-off-by: ajrasane <[email protected]>
|
#2685 is now a draft reference for the combined implementation. The requested four replacement draft PRs are published:
Merge in order 1→2→3→4. Each PR links to this original discussion and the complete stack. The new heads preserve the prepared and tested split; the final aggregate tree equals the original combined PR. Execution evidence includes the zero-calibration fix and Blackwell numerical results. Successful required checks and all configured Torch 2.8–2.14 jobs still need to be linked for each resulting head before merging. |
Each replacement references #2685 and targets its immediate dependency, with part 1 targeting main.
What does this PR do?
Type of change: new feature
Part 4 of the four-PR Dynamo ONNX export stack replacing #2418. Enables the helper-owned workflow by wiring preflight, private lowering, canonical normalization, existing format packers, and final domain/opset/metadata validation. Supports FP8, INT8, INT4 AWQ, MXFP8, NVFP4, and mixed FP8 + NVFP4 AutoQuant.
Dynamo defaults to opset 23, rejects explicit older opsets, and never falls back to TorchScript. Legacy export remains the default with opset 20. Unsupported topologies and configurations fail closed. ONNXScript is imported only for Dynamo export.
Includes TensorRT decomposable-attention wiring, CLI flags, documentation, and integration tests. INT4 AWQ remains export/checker-only and is rejected with
--trt_build.Review fixes preserve all nine representative Dynamo input/output cases and reuse marker-prefix constants. Dynamo input names now include only tensor leaves while retaining the full input tree; INT4 detection checks enabled weight quantizers. New regressions cover leading/interleaved Python scalars with numerical execution of the exported graph with generated inputs, and enabled/disabled INT4 weights in mixed models. The current-main builder optimization-level option is retained.
The integration preserves main’s TensorRT profile-selection and post-input-copy shape-inference fixes while adding decomposable-attention support. Review fixes also make FP8 scales safe before packing, preserve calibrated Conv scales and exclusions, retain small positive FP8 scales through precision conversion, reject unsupported Dynamo NVFP4 BF16 requests, and reject unsupported quantized subgraphs.
Usage
This helper is the only supported library interface. Bare Dynamo export, public translation-table use, and caller-owned captured-program workflows are not supported.
Testing
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
Capture, lowering, and normalization have merged. This integration PR now targets
mainand preserves the complete feature and its regression coverage.Separate lowering rationale: the legacy callbacks use TorchScript
GraphContext/torch.Valueandg.op; Dynamo translations require ONNXScript symbolic values. A shared graph-building framework would expand scope and risk legacy behavior. Dtype mapping and format packers remain shared; frontend scale/axis/dtype rules must be maintained and regression-tested in both lowering implementations. Dynamo itself uses one private table for non-strict capture and strict retry.Replacement stack
Parts 1–3 have merged. #2685 is rebased onto current
mainand is the final integration PR.Summary by CodeRabbit
New Features
Bug Fixes
Documentation