Skip to content

[6721556] Fix mixed-dtype NVFP4 ONNX precision conversion - #2415

Open
ajrasane wants to merge 12 commits into
mainfrom
ajrasane/nvbug-6721556-swin-mixed-dtype-add
Open

ajrasane wants to merge 12 commits into
mainfrom
ajrasane/nvbug-6721556-swin-mixed-dtype-add

Conversation

@ajrasane

@ajrasane ajrasane commented Sep 11, 2026 •

Copy link
Copy Markdown
Contributor

What does this PR do?

Type of change: Bug fix

Fixes NVFP4 ONNX export failing on mixed FP32/FP16 inputs by normalizing compute dtypes before TensorRT parsing.

  • Supports FP32, BF16, and mixed FP32/BF16 sources exported to FP16 or BF16, including NVFP4/FP8 hybrid models.
  • Uses one Q/DQ-aware AutoCast path, preserves explicit FP32 Cast boundaries, and limits inference deferral to opted-in NVFP4 deployment.
  • Preserves the sign of tiny negative initializers during precision conversion.

Compatibility: NVFP4 FP16 exports now use AutoCast's precision and clamping policies. Numerical results can change; revalidate model accuracy.

Usage

from modelopt.torch._deploy.utils import get_onnx_bytes_and_metadata

onnx_bytes, metadata = get_onnx_bytes_and_metadata(
    model, (sample_input,), weights_dtype="bf16"  # or "fp16"
)

NVFP4 deployment uses keep_io_types=False and enables inference deferral internally. Ordinary AutoCast callers retain their existing inference behavior.

Testing

Current head: d48e98cfe.

  • Seven-file CPU regression suite: 420 passed.
  • Relevant changelog and merge-commit hooks: passed.
  • Blackwell engine validation: not run on this head.

CPU coverage includes mixed-output dtypes, NVFP4 inference deferral, and FP16→BF16 interfaces.

Before your PR is "Ready for review"

  • Is this change backward compatible?: ❌ Numerical policy changes as noted above; existing call signatures remain supported.
  • Copied code or new dependencies?: N/A
  • New tests?: ✅
  • Changelog updated?: ✅
  • Claude approval?: ❌

Additional Information

The ModelOpt-side fix is complete, but Swin still fails on Blackwell/B200 during default level-3 TensorRT inference. The recorded Swin exports and engine builds succeed; execution fails for FP32→FP16, FP32→BF16, and BF16→FP16.

The remaining issue reproduces with native TensorRT APIs without ModelOpt or ONNX parsing. It requires a TensorRT-side fix, tracked in NVBug 6906055. End-to-end Swin validation remains blocked pending that fix and a fresh current-head run. No failure is waived; human maintainer sign-off remains outstanding.

weights_dtype="fp32" preserves existing boundaries; it does not request general BF16→FP32 conversion. Broader keep_io_types=True, aliased-output, and FP32-path dynamic-shape limitations remain outside this fix.

🤖 Generated by Codex (AI agent).

Co-Authored-By: Codex <[email protected]>
Signed-off-by: ajrasane <[email protected]>
@copy-pr-bot

copy-pr-bot Bot commented Sep 11, 2026

Copy link
Copy Markdown

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.

@coderabbitai

coderabbitai Bot commented Sep 11, 2026 •

Copy link
Copy Markdown
Contributor

Review Change StackReview Change Stack

Note

Reviews paused

It 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 reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Enterprise

Run ID: 2f0ba5a5-0fde-4549-ba6c-7a7f0ac6db45


📥 Commits

Reviewing files that changed from the base of the PR and between 7038eb8 and 7a2d3ed.


📒 Files selected for processing (1)
  • CHANGELOG.rst

Included review availability: Your plan provides up to 12 included reviews per hour; 10 remain after this review.



📝 Walkthrough

Walkthrough

The change updates NVFP4 and FP8 ONNX precision handling. It adds FP4 graph opset normalization, preserves compatible BF16 paths, aligns casted output types, and adds regression tests for conversion errors and mixed-precision graphs.

Changes

ONNX precision conversion and NVFP4 export

Layer / File(s) Summary
Conversion validation and export handling
modelopt/torch/_deploy/utils/torch_onnx.py
FP4 and FP8 graphs support BF16 no-op handling, reject unsupported conversions, and normalize FP4 graphs to the required opset.
NVFP4 graph casting
modelopt/onnx/export/nvfp4_exporter.py
The exporter casts Gemm inputs to the selected precision and restores original output types when required.
NVFP4 regression coverage
tests/unit/torch/deploy/utils/test_torch_onnx_utils.py, tests/unit/torch/quantization/test_onnx_export_cpu.py, CHANGELOG.rst
Tests cover conversion errors, converter selection, BF16 preservation, ONNX validity, and consistent elementwise and Gemm dtypes. The changelog records the mixed-precision NVFP4 export fix.

Priority: ➖ Normal

Estimated code review effort: 3 (Moderate) | ~20 minutes

Change: Bug fix

Suggested reviewers: edwardf0t1


Merge Risk: ⚪ Minimal · up to 7a2d3

Supported NVFP4 paths normalize opsets, reject unsupported conversions, and preserve the tested precision boundaries.

Pre-merge checks | Passed 5 | Failed 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage Warning Docstring coverage is 9.09% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 22 functions across 4 files. (1 skipped: 1… Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (5 passed)
Check name Status Explanation
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Security Anti-Patterns Passed PASS. The PR changes only two modelopt Python files and no examples or dependency manifests. The added-line scan found no torch.load(..., weights_only=False), unsafe NumPy loading, hardcoded trust_rem…
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check Passed The title clearly and concisely describes the main change: fixing mixed-dtype NVFP4 ONNX precision conversion.

Full details: Docstring Coverage

Explanation

Docstring coverage is 9.09% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 22 functions across 4 files. (1 skipped: 1 unsupported.)



  • Fix all pre-merge checks with AI
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Commit to this branch
  • Create a new PR



Comment @coderabbitai help to get the list of available commands.

@github-actions

github-actions Bot commented Sep 11, 2026 •

Copy link
Copy Markdown
Contributor
PR Preview Action v1.8.1

QR code for preview link

🚀 View preview at
https://NVIDIA.github.io/Model-Optimizer/pr-preview/pr-2415/

Built to branch gh-pages at 2026-10-09 19:21 UTC.
Preview will be ready when the GitHub Pages deployment is complete.

@codecov

codecov Bot commented Sep 11, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 98.88889% with 1 line in your changes missing coverage. Please review.
✅ Project coverage is 76.66%. Comparing base (eb524f3) to head (d48e98c).
⚠️ Report is 4 commits behind head on main.

Files with missing lines Patch % Lines
modelopt/onnx/export/nvfp4_exporter.py 98.24% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #2415      +/-   ##
==========================================
+ Coverage   71.72%   76.66%   +4.94%     
==========================================
  Files         642      642              
  Lines       71409    75365    +3956     
==========================================
+ Hits        51218    57780    +6562     
+ Misses      20191    17585    -2606     
Flag Coverage Δ
examples-diffusers 20.22% <3.33%> (-0.04%) ⬇️
examples-gpt-oss 13.45% <0.00%> (-0.01%) ⬇️
examples-hf_ptq 23.36% <0.00%> (-0.05%) ⬇️
examples-llm_distill 13.54% <0.00%> (+0.01%) ⬆️
examples-llm_eval 17.29% <0.00%> (-0.02%) ⬇️
examples-llm_qat 17.53% <0.00%> (+<0.01%) ⬆️
examples-llm_sparsity 15.82% <0.00%> (-0.03%) ⬇️
examples-megatron_bridge 26.42% <0.00%> (-0.20%) ⬇️
examples-specdec_bench 13.23% <0.00%> (-0.01%) ⬇️
examples-speculative_decoding 17.58% <0.00%> (-0.09%) ⬇️
examples-torch_onnx 21.65% <93.33%> (+0.04%) ⬆️
examples-torch_trt 15.23% <0.00%> (-0.01%) ⬇️
examples-vllm_serve 13.90% <0.00%> (-0.01%) ⬇️
gpu 59.06% <73.33%> (+25.54%) ⬆️
regression 15.08% <0.00%> (-0.02%) ⬇️
unit 60.01% <97.77%> (+0.12%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@ajrasane
ajrasane marked this pull request as ready for review September 11, 2026 22:07
@ajrasane
ajrasane requested review from a team as code owners September 11, 2026 22:07
@ajrasane
ajrasane requested a review from cjluo-nv September 11, 2026 22:07

@cjluo-nv cjluo-nv left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Bot review (claude-opus-5) — DM the bot to share feedback.

Nudge: the branch change itself is sound, but the new tests mock out both converters so nothing verifies the actual mixed-dtype fix, and the FP16 NVFP4 path now skips AutoCast's opset upgrade.

Needs action:

  • Confirm the opset regression in modelopt/torch/_deploy/utils/torch_onnx.py: convert_to_f16 bumped NVFP4 graphs to opset 23 (get_min_opset_for_precisions), the convert_float_to_float16 branch does not, so default exports now ship opset-20 metadata over opset-23 FP4 DequantizeLinear — fix it here or say why it's acceptable.
  • Add an end-to-end check that the exported FP16 NVFP4 graph has no mixed float-type elementwise inputs; tests/unit/torch/quantization/test_onnx_export_cpu.py::test_nvfp4_exported_onnx_is_topologically_sorted shows a CPU-feasible NVFP4 export pattern.
  • Explain whether weights_dtype="bf16" + NVFP4 still hits the same TensorRT parse failure, since it keeps routing through convert_to_f16 → GraphSanitizer.find_custom_nodes.

No action needed:

  • The added weights_dtype == "fp16" guard is a no-op for BF16 (the earlier ValueError already covers FP8/other quantizers), so the BF16 path is genuinely preserved.
  • PR body notes the change is Codex-authored without Claude approval, so a human pass is warranted regardless.

@ajrasane
ajrasane requested a review from a team as a code owner September 11, 2026 22:48
@ajrasane

Copy link
Copy Markdown
Contributor Author

@cjluo-nv Addressed the three review items in 1ffc34f89:

  • Opset: NVFP4 Q/DQ precision requirements are now derived after weight post-processing, and the graph is upgraded to opset 23 before precision conversion without invoking TensorRT custom-node discovery.
  • End-to-end coverage: added a real CPU NVFP4 MatMul→Add export regression. It retains dynamic FP4 activation quantization, passes full ONNX checking and strict shape inference, and asserts that every elementwise node has consistent floating input types.
  • BF16: pure native-BF16 NVFP4 export is now an explicit weight-focused no-op, so it does not enter AutoCast/TensorRT pre-parsing. FP32-to-BF16 and BF16-to-FP16 NVFP4 conversions fail early. The exporter also keeps MatMul/Gemm output annotations consistent with its inserted BF16/FP16 casts.

Validation: 128 affected CPU tests passed; the public Swin NVFP4 reproducer exported an opset-23 graph with zero mixed floating-type elementwise operations and completed a strongly typed TensorRT 11.1 engine build on Blackwell.

🤖 Generated by Codex (AI agent).

@cjluo-nv cjluo-nv left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Bot review (claude-opus-5) — DM the bot to share feedback.

Nudge: all three prior concerns are fixed with real code and real CPU coverage, but the PR quietly turns two previously-working NVFP4 conversions into hard errors and the agent-authored change still wants a human pass.

Needs action:

  • Document the new hard failures in CHANGELOG.rst: weights_dtype="bf16" with FP32 params + NVFP4, and weights_dtype="fp16" with BF16 params + NVFP4, previously ran through convert_to_f16 and now raise ValueError in modelopt/torch/_deploy/utils/torch_onnx.py. The PR body still marks this backward compatible.
  • Confirm the weights_dtype="fp32" NVFP4 path: the new if uses_fp4: opset block runs there too and nvfp4_exporter.post_process now stamps MatMul outputs as FP16, so that graph can still carry mixed FP16/FP32 elementwise inputs — say whether it is out of scope or add it to test_nvfp4_deploy_export_has_consistent_elementwise_types.
  • Have a human review the Codex-authored commits before merge.

No action needed:

  • ✔️ Resolved since the last review: the opset-23 upgrade before precision conversion, the real CPU NVFP4 export test asserting no mixed-float elementwise inputs, and the BF16 no-op routing.
  • Refactor of test_nvfp4_exported_onnx_is_topologically_sorted into _make_cpu_nvfp4_model keeps coverage intact.

@ajrasane

Copy link
Copy Markdown
Contributor Author

Addressed the current-head review items in c97ae4a5d and merged the latest main in 2b8c579cb:

  • Expanded the changelog and corrected the PR compatibility declaration to document the new FP32-to-BF16 and BF16-to-FP16 ValueError behavior.
  • Fixed the accepted weights_dtype="fp32" path: NVFP4 MatMul/Gemm operations stay in their supported low-precision compute type, an optional Gemm bias is cast to that type, and an explicit output cast restores the FP32 graph boundary.
  • Added real CPU NVFP4 coverage for both MatMul plus bias Add and biased Gemm, parameterized across FP32 preservation, FP32-to-FP16 conversion, and native-BF16 no-op behavior. The graphs retain dynamic FP4 activation quantization, use opset 23, and pass full ONNX checking and strict shape inference.
  • Reran 20 focused CPU cases after the base merge; all passed. Changed-file hooks also passed.

The PR is now conflict-free. Current-head Blackwell/TensorRT acceptance has not been rerun, and human approval remains external.

🤖 Generated by Codex (AI agent).

@cjluo-nv cjluo-nv left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Bot review (claude-opus-5) — DM the bot to share feedback.

Nudge: the two prior code concerns are resolved with real CPU coverage, but hardware acceptance is stale on current head and one BF16 branch in the exporter is unexplained.

Needs action:

  • Rerun or explicitly waive the Blackwell/TensorRT engine build for the current head; the PR body says it was not repeated after the final exporter change.
  • Explain (ideally as a code comment) why the BF16 branch in modelopt/onnx/export/nvfp4_exporter.py::_cast_input_dtypes re-stamps the node output value_info to BF16 instead of inserting a boundary Cast like the FP16 path — on a graph with any BF16 initializer this silently retypes outputs whose consumers are still FP32.
  • Have a human review the Codex-authored commits and the declared backward-incompatible ValueError behavior before merge.

No action needed:

  • ✔️ Resolved since the last review: the CHANGELOG.rst entry for the new FP32→BF16 / BF16→FP16 hard failures, and the weights_dtype="fp32" mixed-type path (Gemm bias cast + output boundary cast, covered by the new parameterized elementwise/gemm CPU tests).
  • The output cast is skipped when a node output has no value_info (e.g. after a failed shape inference), which just restores pre-PR behavior rather than regressing.

@ajrasane

Copy link
Copy Markdown
Contributor Author

@cjluo-nv Addressed the current-head review items in 7038eb84d:

  • BF16: the re-stamp is required for native-BF16 because TRT_FP4QDQ lacks shape inference and leaves MatMul/Gemm outputs annotated FLOAT; true FP32 boundaries are already explicit Casts. The actual bug was global precision inference: any BF16 initializer could retype unrelated FP32 branches. Precision is now derived per quantized weight, with an inline comment documenting the invariant.
  • Regression: added a real mixed FP32/BF16 NVFP4 export test. It failed before the fix with Add ... B has inconsistent type tensor(float) and now passes full ONNX checking and strict shape inference with both Add inputs FLOAT.
  • Validation: the formatter-final affected suite passed (133 passed); all changed-file hooks passed.
  • Blackwell: current-head engine-build acceptance is explicitly waived because the available a9 host currently exposes only RTX 6000 Ada (SM89), with no B100/B200/SM120 device. The earlier SM120 TensorRT 11.1 pass was pre-current-head and is not counted as current validation. The PR description now records the waiver and evidence boundary.

Human approval remains external.

🤖 Generated by Codex (AI agent).

@cjluo-nv cjluo-nv left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Bot review (claude-opus-5) — DM the bot to share feedback.

Nudge: both prior code concerns are now fixed with real CPU coverage, but the Blackwell acceptance was waived rather than run and the backward-incompatible ValueError behavior in agent-authored code still needs a human call.

Needs action:

  • Have a human sign off on the Codex-authored commits and the new ValueErrors in modelopt/torch/_deploy/utils/torch_onnx.py (FP32→BF16 and BF16→FP16 NVFP4 now hard-fail); CHANGELOG documents it, the PR body still needs the compatibility flag to match.
  • Decide whether the waived current-head Blackwell/TensorRT engine build is acceptable, or rerun it once a B100/B200/SM120 host is available.
  • Confirm the BF16 re-stamp in nvfp4_exporter.py::_cast_input_dtypes is safe when a BF16-weighted node output is a graph output under weights_dtype="fp32" — that path changes the declared model output dtype with no Cast and isn't covered by test_nvfp4_deploy_export_preserves_mixed_precision_boundaries.

No action needed:

  • ✔️ Resolved since the last review: the global-precision BF16 retyping bug (now derived per quantized weight, with an inline comment) and the new mixed FP32/BF16 export regression test.
  • Refactor into _make_cpu_nvfp4_model keeps the original topological-sort test coverage intact.

Support FP32 or mixed sources exported to BF16 and BF16 or mixed sources exported to FP16, including accompanying FP8 layers. Preserve fixed FP4/FP8 dynamic-quantizer output types before conversion so missing intermediate shapes do not trigger TensorRT parsing of mixed compute dtypes. Cover LayerNorm, Gemm, graph I/O, and FP8 scale boundaries.

Signed-off-by: ajrasane <[email protected]>
@ajrasane
ajrasane requested a review from a team as a code owner September 21, 2026 17:24
@ajrasane
ajrasane requested a review from cjluo-nv September 21, 2026 17:24
@ajrasane ajrasane changed the title [6721556] Fix mixed dtypes in NVFP4 FP16 ONNX export [6721556] Fix mixed-dtype NVFP4 ONNX precision conversion Sep 21, 2026
Use AutoCast policies for supported NVFP4 FP16 and BF16 exports, preserve native BF16 no-op and unrelated quantizer routes, and preserve the sign of tiny initializer values. Consolidate regression setup and verify packed payloads, dynamic converted shapes, and numerical limits.

Signed-off-by: ajrasane <[email protected]>

@cjluo-nv cjluo-nv left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Bot review (claude-opus-5) — DM the bot to share feedback.

Nudge: prior code findings are fixed, but the new AutoCast-wide changes in this round plus the still-open BF16 re-stamp question need an owner's call before merge.

Needs action:

  • 💬 Author replied that the BF16 re-stamp is required because TRT_FP4QDQ lacks shape inference — still needs the graph-output case: in nvfp4_exporter.py::_cast_input_dtypes, a BF16-weighted node whose output is a graph output is retyped with no Cast under weights_dtype="fp32". Confirm it is unreachable or cover it in test_nvfp4_deploy_export_preserves_mixed_precision_boundaries.
  • Justify hard-coding TRT_FP4DynamicQuantize and its exact FP4/FP8 output signature inside graphsanitizer.find_custom_nodes, or pass the skip as an explicit flag from the NVFP4 caller — this changes TRT inference for every AutoCast user with that plugin.
  • Add AutoCast coverage for the widened input retype in precisionconverter.convert (elem_type in ONNX_TYPES): an FP16 graph input is now silently declared BF16 when keep_io_types=False.
  • Have a human sign off on the Codex-authored commits and decide whether the waived current-head Blackwell engine build is acceptable.

No action needed:

  • ✔️ Resolved since the last review: the per-weight precision derivation, the mixed FP32/BF16 export regression, the CHANGELOG policy entry, and the sign-preserving initializer clamp (now tested).
  • 207 core-logic lines — under the size budget.

@ajrasane

Copy link
Copy Markdown
Contributor Author

Follow-up to the review, implemented in 03b814c1a:

  1. BF16 graph outputs: Added NVFP4 coverage under weights_dtype="fp32" for outputs [FP32, BF16, FP32], matching eager execution. The native BF16 output comes directly from the weighted node and the explicitly FP32 output retains its Cast. All six existing single-output mixed-precision cases and their payload/dynamic-shape assertions remain intact.

  2. Inference deferral: Added default-off defer_nvfp4_trt_inference, enabled by the supported NVFP4 deployment caller and forwarded through both sanitization passes. Bypass still requires the exact plugin/output signature. Encountering that plugin alone no longer changes ordinary AutoCast callers' inference behavior. Default, opted-in, missing-shape, invalid-type, and additional-custom-op cases are covered.

  3. FP16→BF16 interface: Public convert_to_f16 coverage now verifies keep_io_types=False in both inference modes: BF16 I/O, initializer values, names/shapes, wiring, no boundary Casts, and full ONNX validity. The additional keep_io_types=True experiment exposed a separate preservation failure; converting aliased multiple outputs also exposed cleanup/shape failures. Those general fixes are deliberately outside this original NVFP4 bug fix and remain unresolved, not waived or marked passing.

  4. Validation and approval: This commit's tree exactly matches the tree that passed 32 focused tests, the 409-test seven-file CPU suite, and relevant hooks. Eight B200 build/serialize/reload/runtime checks passed on an earlier staged tree; they do not validate this commit. The corrected full-matrix retry failed during setup before executing cases, so current-head Blackwell validation remains incomplete. These are synthetic smoke checks, not pretrained-model accuracy validation. No waiver or human maintainer sign-off is claimed; review threads remain unresolved.

🤖 Generated by Codex (AI agent).

@ajrasane

Copy link
Copy Markdown
Contributor Author

Blackwell validation update for 03b814c, following the existing review and the prior numbered reply:

  1. Explicit builder optimization level 0: 13/13 PASS on B200. All nine small-model conversions, the native-BF16/explicit-FP32 graph-output case, and reduced Swin FP32→FP16, FP32→BF16, and BF16→FP16 passed fresh CUDA quantization/export, full ONNX checking, strongly typed TensorRT engine building, serialization, reload, and runtime shape/dtype/finite-output checks. The mixed-output case produced [FP32, BF16, FP32] as intended.
  2. Default optimization level 3: 10/13 PASS; three Swin cases still FAIL with NaNs. Those engines build and reload, but fail runtime finite-output checks. No waiver is taken. A separate same-graph BF16 Swin diagnostic passes at level 0, and captured-activation tails pass at default level 3; this indicates optimization-context sensitivity, not a proven specific TensorRT defect. The level-0 result must not be read as default-level validation.
  3. Evidence: unchanged clean commit 03b814c1a9a85bcaa60c4135ee1e48c30c853202, tree ede0f480cd9dca8d57d8db4361a4ef68c439ac90; one B200, nvcr.io/nvidia/pytorch:26.07-py3 at sha256:2140e699b3beaf7f96a0081fd9c9406bc3832b435cdb60dfa2d261f7d2f34a1c, CUDA 13.3, TensorRT 11.1.0.106. Passing run completed on 2026-09-23 with harness/scheduler exit code 0. Every case recorded effective builder level 0, source fingerprints were unchanged, and all 26 artifact hashes were checked. The PR Testing section contains the command and complete environment details.
  4. Acceptance remains human-owned. No production changes or pushes were made for this validation. The original NVFP4 scope is unchanged. Default-level Swin failures remain open; no review threads are resolved and no human sign-off is claimed. This is synthetic/random-weight build/runtime smoke testing, not pretrained accuracy or performance validation.
Passing level-0 run: SHA256 evidence manifest
  • Harness: 89b038eef8c5d66102e500d184f72485fe0dbbb11ba8fa45ef189e7c76c8ac94
  • Job script: 831e8f9bae039ec383e67cc5e5f52285e957a4bee5ea3475dce4fbcbe17dbf7a
  • Completed result manifest: 27707bc62cfb5b0618c55164eaee86508a571afb5d198200f3ad470fa4875180
  • Completed job log: 11f0f2b0231d1a00d4b8b4c1fe42e4721e49461a0bc3eb30aa0156f298cd9543
Case ONNX SHA256 Engine SHA256
small_fp32_to_fp16_fp8_False 715f75be5e2638ce931dfd61b9468dca4b417200992445e90475b8d272aa85d0 33fd2bf757f3003afb18a2b99f7a6bc07102c315fc34ae421908cee7e7b726d5
small_fp32_to_fp16_fp8_True 88cc42635cc11ae039a3d28ec33ebc4807bf1deaefa9c331c325ec198d1d4a68 c36ca82fef25171e80baf76a6bd5f45dd69f19f949cdfc27deb0f7916a7aad2a
small_fp32_to_bf16_fp8_False 9bd6f77bab5d753f78d352b7de70333df8b097b19df01b3330cb1cb11523adb9 c1c36f80380f8be32535b7129e52f1a353223c84e5c9f0063bd56a33e313562f
small_bf16_to_fp16_fp8_False 720a8c8c4e1437d480f092b0e4c8366bfbc2c69f96f280498b391bea74b8dce4 fb1f635fe398ce51734ba8b2a7844c5609e0213c1c449af13c381f4e888a748f
small_bf16_to_bf16_fp8_False b57196e6de2b45e296c66381fc3a506dd3fc545d33d6d0cc8b9226d78173a8b5 368ee97d93ddf29a313067b3849b7760f46d4c321ffe48da85c596b246d1e16d
small_mixed_to_bf16_fp8_False 1eca4d0ee089bcfc0d832f53dce49eb5c09b99da7820fe6d48eeeb04150f65e4 93c44c2080e051557a5b39667b1164db820c2e8ca976c84d5a885bb9b9ecfe6d
small_mixed_to_fp16_fp8_False 84bec5c1cc38fd412a8ed3c1701a91152251d9f5ce5cc69d3e1ee1b9a6954cc3 4933bea79dfc6d50bdc34d112dfff7a9f84155f578040bb769eb421de949406e
small_mixed_to_bf16_fp8_True a64d330134f829772563b63c6a948018dafabe2f37e1b486a5b6ede18ec52824 42196dfec02f0fbb679c263ef98921e8a6437fa93ef1ebf31c37b8f1f2344c6c
small_mixed_to_fp16_fp8_True ca7717a177781de8d3751164bbd56027e92d1c8160b9f54994bd81881cf63fea 750cd2b4ce24f9fe7971bb99469f363d201b8bab7be662b311df49a5ff1d4898
mixed_native_bf16_and_explicit_fp32_outputs 10ea17bcf2c01eb753202278e6b70bd5b0d7a7cbfba42158f7b26e9513f6443f d9109d40ab4603daad881ecfd271bd26b14c5f4e86e0dd412178cc89278d1098
swin_fp32_to_fp16 63433fe8fb9f82238957ea0e30bccefad2222c4d271d02ce10f60af90b0b827d de01d35b75be3c170815ea548e0655bb160dae4402b1104038606978f31f4bc6
swin_fp32_to_bf16 3473fd48e4fc28343ea2fb4ca101ea524f1183ea13127ac4c05059be98adff7f 5ca55c694e63971f60e803f9dfbd5e95f4507d9465220b998db94293394eab50
swin_bf16_to_fp16 3920e754a1278525b33745f665f1e35b56286ac21149a81f44c8eaa4b5891e79 8a8c57e50f7492d7b78c4b6d51e090607335bf7656da7cd986cdcc5e1126ab8e

🤖 Generated by Codex (AI agent).

@ajrasane

ajrasane commented Oct 7, 2026

Copy link
Copy Markdown
Contributor Author

Swin runtime follow-up to the existing review:

  1. Cause and scope: The reproducible failure is in the optimized TensorRT GEMM/GELU/NVFP4 region. Preserving the GELU result as a compiler boundary fixes the observed NaNs/all-zero output without changing ONNX math, quantization, or public I/O. FP32 GELU, equivalent expression rewrites, and rank-2 layout did not fix it, so none were added to the exporter.
  2. Narrow implementation: A local, opt-in --trt_swin_nvfp4_workaround option is restricted to swin_tiny_patch4_window7_224 with --trt_build. It selects optimization level 3 and marks only GELU outputs directly feeding dynamic NVFP4 quantizers. Default builds and AutoCast are unchanged. It may reduce performance; this is a build workaround, not a TensorRT kernel fix.
  3. Validation: On B200 with verified TensorRT 11.2.1.2 libraries, the finalized local tree passed all 13 fresh export/build/reload/runtime cases, including all three Swin conversions, plus ten independent replays per engine. 8 focused/runtime tests, the 409-test seven-file suite, and relevant hooks passed. The original frozen BF16 Swin result is bit-identical to a fresh same-version level-0 control. An older 11.1 control differs numerically; that cross-version result is retained, not waived. The supplementary actual trtexec check also passed, but its bundled executable reports 11.1.0/b106, so it is not used to establish the 11.2 build result. Full provenance and hashes are in the PR description.
  4. Publication/acceptance: Tested tree: ff2313b1d25a03750e33d7e90eb70dfd5ad88667, based on public head 03b814c1a9a85bcaa60c4135ee1e48c30c853202. The implementation is still local, pending explicit push approval after signing; this comment does not claim it is on the public branch. Unmodified level-3 TensorRT builds still fail. Human maintainer sign-off remains outstanding, and no review threads are resolved. These are synthetic/random-weight smoke checks, not pretrained-model accuracy or performance validation.

Retain the NVFP4 compatibility warning and the independent upstream changelog entries. Validated with the seven-file CPU regression suite (420 passed) and changelog pre-commit checks.

Signed-off-by: ajrasane <[email protected]>

@cjluo-nv cjluo-nv left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Bot review (bedrock-claude-opus-5-5) — DM the bot to share feedback.

Nudge: every earlier code concern is fixed and tested, but the original Swin bug still fails at runtime. With default TensorRT optimization level 3, the Swin engines produce NaNs, and the only workaround found is still unpushed.

Needs action:

  • Decide whether a fix that clears ONNX/TRT parsing is enough to merge while default level-3 Swin engines still output NaNs on B200 (TRT 11.1 and 11.2.1.2). If it isn't, land the GELU-boundary workaround with this PR or as a linked follow-up.
  • Have a human sign off on the Codex-authored commits and the backward-incompatible numerics. NVFP4 FP16 exports now follow AutoCast's clamping and Div policy; CHANGELOG.rst documents this.
  • Confirm the PR body's testing claims match what's on the branch. The 13/13 pass was measured on local tree ff2313b, which has not been pushed. Only the level-0 run and the failing level-3 run cover public head 03b814c.

No action needed:

  • ✔️ Resolved since the last review:
    • the BF16 graph-output re-stamp (now covered by test_nvfp4_deploy_export_preserves_bf16_graph_outputs)
    • the TRT_FP4DynamicQuantize hard-coding (now behind an opt-in defer_nvfp4_trt_inference flag that is off by default)
    • the FP16→BF16 input retype (test_bf16_conversion_accepts_fp16_initializer now uses FP16 I/O through convert_to_f16)
  • The existing-test edits are justified. The find_custom_nodes test keeps its default-path assertions and adds parametrized cases, and the BF16 test moved to the public API with stronger assertions.
  • Design is settled: this extends AutoCast and the existing exporter rather than adding a new system. About 191 core-logic lines, under the size budget.

@ajrasane

ajrasane commented Oct 9, 2026

Copy link
Copy Markdown
Contributor Author

Swin on Blackwell: TensorRT runtime blocker

The ModelOpt-side fix for the original mixed-dtype Add parsing error is complete. In the recorded B200 runs, Swin ONNX export and TensorRT engine construction succeeded, but default optimization-level-3 inference produced nonfinite outputs for FP32→FP16, FP32→BF16, and BF16→FP16. TensorRT 11.2.1.2 is still affected.

The failure was reduced to an NVFP4 MLP using native TensorRT APIs, with no ModelOpt export or ONNX parsing. With the same engine and finite inputs, changing the initial contents of valid, aligned workspace memory changes outputs between zeros, finite values, and NaNs; the level-0 control is stable. This points to a read-before-write or unwritten-workspace defect in TensorRT's fused GEMM/GELU/requantization path. The exact faulty kernel instruction remains unconfirmed.

Opened TensorRT NVBug 6906055 with the reproducer and diagnostic evidence. The remaining runtime issue requires a TensorRT-side fix before end-to-end Swin validation can pass.

Current PR head d48e98cfe has 420 passing CPU tests, but no fresh Blackwell validation. The observations above are from the prior GPU investigation, not a validation of this head. No failure is waived; human maintainer sign-off remains outstanding.

🤖 Generated by Codex (AI agent).

kevalmorabia97 pushed a commit that referenced this pull request Oct 15, 2026
### What does this PR do?

Type of change: Bug fix

#1289 (in 0.44.0 through #1350) registered `nn.LayerNorm` in
`QuantModuleRegistry` so that FP8 MHA recipes can quantize its output.
As a side effect, presets and recipes that import
`configs/ptq/units/default_disabled_quantizers` and enable a bare
`*input_quantizer` (`INT8_DEFAULT_CFG`, `FP8_DEFAULT_CFG`,
`NVFP4_DEFAULT_CFG`, ...) also quantize every LayerNorm *input*, i.e.
the residual stream (49 extra NVFP4 quantizers in XLM-R large). In ONNX
export this becomes a dynamic quantize in front of `LayerNormalization`
that no GEMM consumes. Weight-only and layer-scoped presets are not
affected.

This adds a `parent_class: 'nn.LayerNorm'` exclusion to
`default_disabled_quantizers`, in the same form as the existing
`nn.BatchNorm*`, `nn.LeakyReLU` and `nn.Embedding` entries. LayerNorm
quantization stays opt-in: the FP8 MHA override in
`examples/torch_onnx/torch_quant_to_onnx.py`, appended after the preset,
enables the LayerNorm output quantizer and already disables the input
quantizer, so its result is unchanged. As with the BatchNorm entries, an
`nn.LayerNorm` subclass registered as its own quant class is not
covered.

#2402 fixed the same regression for the diffusers NVFP4 presets with the
same entry; those presets do not import this unit. Out of scope:
`NVFP4_FP8_MHA_CONFIG`, `model_type/vit/ptq/fp8.yaml` and the diffusers
`fp8`, `int8` and `nvfp4_fp8_conv` presets also skip this unit and still
quantize LayerNorm inputs.

Effect on `BAAI/bge-reranker-v2-m3` (XLM-R large), NVFP4 W4A4 fake quant
(ModelOpt 0.47.0, same as main here), 60 queries × 100 candidates each:

| NVFP4_DEFAULT_CFG (classifier excluded) | Ko-StrategyQA Recall@10 |
same top-1 as FP32 | mean \|logit − FP32\| | MIRACL-ko Recall@10 | same
top-1 | mean \|logit − FP32\| |
|---|---|---|---|---|---|---|
| as is (LayerNorm inputs quantized) | 87.6% | 80% | 0.94 | 91.1% | 80%
| 1.05 |
| LayerNorm quantizers disabled (this PR) | 90.6% | 90% | 0.61 | 94.5% |
87% | 0.66 |
| FP32 | 88.9% | | | 93.4% | | |

### Usage

No API change. A config that wants LayerNorm input quantization adds the
entry after the default exclusions:

```python
cfg = copy.deepcopy(mtq.FP8_DEFAULT_CFG)
cfg["quant_cfg"].append(
    {"parent_class": "nn.LayerNorm", "quantizer_name": "*input_quantizer", "cfg": {"num_bits": (4, 3), "axis": None}}
)
```

### Testing

- New `test_default_presets_keep_layernorm_inputs_unquantized`
(`INT8_DEFAULT_CFG`, `FP8_DEFAULT_CFG`, `NVFP4_DEFAULT_CFG`): fails on
main, passes here.
- `pytest tests/unit/torch/quantization tests/unit/recipe`: 1912 passed,
1 skipped.
- `pytest tests/examples/torch_onnx/test_torch_quant_to_onnx.py -k
"vit_tiny or swin"` (RTX PRO 6000, TensorRT 11.3): the 12 FP8, INT8,
MXFP8 and auto cases pass. The 3 NVFP4 cases fail the same way on main,
in the FP32 NVFP4 export that #2415 fixes, and pass with a local fix for
it.
- `pre-commit run --files` on the changed files: pass.
- End to end: `bge-reranker-v2-m3` with `NVFP4_DEFAULT_CFG` has 0
LayerNorm input quantizers enabled, and its TensorRT engine matches fake
quant (Recall@10 89.8% for both) with the #2415 export fix applied
locally.

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

Make sure you read and follow [Contributor
guidelines](https://github.com/NVIDIA/Model-Optimizer/blob/main/CONTRIBUTING.md)
and your commits are signed (`git commit -s -S`).

Make sure you read and follow the [Security Best
Practices](https://github.com/NVIDIA/Model-Optimizer/blob/main/SECURITY.md#security-coding-practices-for-contributors)
(e.g. avoiding hardcoded `trust_remote_code=True`, `torch.load(...,
weights_only=False)`, `pickle`, etc.).

- Is this change backward compatible?: ❌ New `mtq.quantize` calls with
these presets no longer add LayerNorm input quantizers, as before 0.44.
Saved checkpoints restore unchanged, because restore replays their
stored config. Usage shows how to re-enable them.
- If you copied code from any other sources or added a new PIP
dependency, did you follow guidance in `CONTRIBUTING.md`: N/A
- Did you write any new necessary tests?: ✅
- Did you update
[Changelog](https://github.com/NVIDIA/Model-Optimizer/blob/main/CHANGELOG.rst)?:
✅ Under 0.49.0; I can move the entry if this should go into 0.48.0.
- Did you get Claude approval on this PR?: N/A

### Additional Information

Found while quantizing `BAAI/bge-reranker-v2-m3` to NVFP4; its TensorRT
engine also needs the FP32 NVFP4 export fix in #2415.


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

## Summary by CodeRabbit

* **Bug Fixes**
* Default quantization presets no longer quantize inputs to `LayerNorm`
modules, avoiding added error in residual streams.
* Re-quantize models affected by this change. Recipes that need
`LayerNorm` input quantization can enable it after importing the
relevant preset.

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

Signed-off-by: Hanjun Cho <[email protected]>

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants