Skip to content

Add NVFP4 Conv3d export for diffusers VAE (Wan 2.2) - #1809

Closed
jingyu-ml wants to merge 1 commit into
mainfrom
feat/nvfp4-conv3d-export
Closed

jingyu-ml wants to merge 1 commit into
mainfrom
feat/nvfp4-conv3d-export

Conversation

@jingyu-ml

@jingyu-ml jingyu-ml commented Jun 23, 2026 •

Copy link
Copy Markdown
Contributor

What does this PR do?

Adds narrowly scoped NVFP4 Conv3d export support for the Wan VAE WanCausalConv3d stack in unified Hugging Face deployment checkpoints.

Previously, quantized Wan Conv3d modules had no unified-export handler, so their weights were not serialized in the packed NVFP4 schema. The converted quantization config also hardcoded targets: ["Linear"], even for a Conv3d-only component.

This PR:

  • registers a WanCausalConv3d-specific export handler through the existing export registry;
  • flattens [O, C, kt, kh, kw] to logical [O, K], pads K to block size 16, and writes packed weight, weight_scale, scalar weight_scale_2, and calibrated input_scale tensors;
  • derives the NVFP4 config targets from the component's quantized module types, producing targets: ["Conv3d"] for a Conv3d-only VAE while preserving the historical Linear default for existing callers;
  • rejects GEMM-specific padding/swizzle options when Conv3d is present instead of adding layer-exclusion plumbing; and
  • fails before mutating a layer when the Conv3d configuration is unsupported or its activation quantizer was not calibrated.

Scope

The supported contract is deliberately narrow: ungrouped Wan WanCausalConv3d, full dynamic block-16 NVFP4 weight/input quantization, and no output quantization. Grouped Conv3d, ConvTranspose, Conv1d/2d, static NVFP4, and W4A16 Conv3d fail closed or remain outside this handler.

This API produces a unified HF deployment checkpoint for downstream inference frameworks. Native Diffusers from_pretrained() loading uses a different NVIDIAModelOptConfig/ModelOpt-state contract and is out of scope.

Calibration must exercise every Conv3d selected for export. Workflows that only exercise VAE decode should quantize/export the decoder and leave uncalibrated encoder layers unquantized.

Validation

  • pre-commit run --from-ref origin/main --to-ref HEAD
  • 50 focused and adjacent export tests covering registry routing, byte-exact packing, scale preservation, target generation, schema, quantizer-state removal, unsupported configurations, missing calibration, and padding/swizzle rejection
  • A real Wan 2.2 5B VAE checkpoint audit found 48 packed Conv3d layers and exposed 20 uncalibrated encoder activation quantizers; this PR now rejects that inconsistent full-VAE export instead of declaring static activations without input_scale

Before your PR is ready for review

  • Backward compatible: yes; the config-conversion argument is optional and defaults to the existing Linear target.
  • New dependencies: none.
  • Tests: added focused CPU coverage and ran adjacent export regressions.
  • Changelog: updated.

Summary by CodeRabbit

  • New Features

    • Added NVFP4 Hugging Face deployment-checkpoint export support for Wan VAE Conv3d layers.
    • Exported checkpoints now include flattened, packed weights, calibrated quantization scales, and correct Conv3d targets.
    • Added validation for unsupported padding and swizzle configurations, with actionable export errors.
    • Preserved existing support for NVFP4 linear layers while adapting quantization metadata to detected module types.
  • Documentation

    • Updated the changelog with the new Wan VAE export capability.

@jingyu-ml
jingyu-ml requested review from a team as code owners June 23, 2026 21:19
@jingyu-ml
jingyu-ml requested a review from Edwardf0t1 June 23, 2026 21:19
@coderabbitai

coderabbitai Bot commented Jun 23, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Adds NVFP4 export support for Wan WanCausalConv3d layers, including validated flattened-K weight packing and scale metadata. Diffusion export now detects Conv3d targets, rejects unsupported padding/swizzling, and emits target-specific Hugging Face quantization configuration.

Changes

NVFP4 Wan Conv3d export

Layer / File(s) Summary
Validated Conv3d NVFP4 export
modelopt/torch/export/hf_export_handlers.py
Adds strict quantizer and weight validation, flattened-K NVFP4 packing, calibrated scale handling, metadata buffers, and the registered WanCausalConv3d export handler.
Diffusion target detection and configuration wiring
modelopt/torch/export/unified_export_hf.py, modelopt/torch/export/convert_hf_config.py, CHANGELOG.rst
Detects NVFP4 Conv3d and Linear targets, blocks unsupported Conv3d padding or swizzling options, passes targets into HF config conversion, and documents the export capability.

Estimated code review effort: 4 (Complex) | ~45 minutes

Sequence Diagram(s)

sequenceDiagram
  participant Diffusers as Diffusers export
  participant TargetTypes as _diffusion_quantization_target_types
  participant ConvHandler as _export_quant_conv3d
  participant WeightExport as _export_quantized_conv3d_weight
  participant HFConfig as convert_hf_quant_config_format

  Diffusers->>TargetTypes: detect NVFP4 Conv3d and Linear targets
  Diffusers->>Diffusers: validate padding_strategy and enable_swizzle_layout
  Diffusers->>ConvHandler: export WanCausalConv3d weights
  ConvHandler->>WeightExport: validate and quantize flattened-K weights
  WeightExport-->>ConvHandler: return quantized weights and scales
  Diffusers->>HFConfig: pass target_types
  HFConfig-->>Diffusers: return target-specific HF configuration
Loading

Suggested reviewers: cjluo-nv, mxino, edwardf0t1, sychen52

🚥 Pre-merge checks | ✅ 5 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 61.90% which is insufficient. The required threshold is 80.00%. 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 No changed modelopt/examples Python files use torch.load/numpy.load unsafe flags, trust_remote_code, eval/exec, or nosec; no dependency manifests were modified.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the main change: adding NVFP4 Conv3d export support for the Wan 2.2 diffusers VAE.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/nvfp4-conv3d-export

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

@jingyu-ml
jingyu-ml requested review from cjluo-nv, mxinO and sychen52 June 23, 2026 21:22
@jingyu-ml

Copy link
Copy Markdown
Contributor Author

/claude review

@github-actions

github-actions Bot commented Jun 23, 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-1809/

Built to branch gh-pages at 2026-07-17 22:07 UTC.
Preview will be ready when the GitHub Pages deployment is complete.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Warning

CodeRabbit couldn't request changes on this pull request because it doesn't have sufficient GitHub permissions.

Please grant CodeRabbit Pull requests: Read and write permission and re-run the review.

👉 Steps to fix this

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
tests/unit/torch/export/test_nvfp4_conv_export_diffusers.py (1)

108-123: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Scope on-disk schema checks to the Conv3d modules discovered earlier.

conv_prefixes is currently built from every *.weight_scale_2 key, so this test can pass even if Conv3d export regresses but other NVFP4 layers remain valid.

Suggested patch
-    conv_prefixes = [
-        k[: -len(".weight_scale_2")] for k in state_dict if k.endswith(".weight_scale_2")
-    ]
-    assert conv_prefixes, "no NVFP4 conv layers found on disk"
-    for prefix in conv_prefixes:
+    exported_prefixes = {
+        k[: -len(".weight_scale_2")] for k in state_dict if k.endswith(".weight_scale_2")
+    }
+    expected_conv_prefixes = set(quant_convs)
+    missing = expected_conv_prefixes - exported_prefixes
+    assert not missing, f"missing exported NVFP4 conv layers on disk: {sorted(missing)}"
+    for prefix in sorted(expected_conv_prefixes):
         weight = state_dict[f"{prefix}.weight"]
         scale = state_dict[f"{prefix}.weight_scale"]
         scale_2 = state_dict[f"{prefix}.weight_scale_2"]
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@tests/unit/torch/export/test_nvfp4_conv_export_diffusers.py` around lines 108
- 123, The conv_prefixes list is currently built from all state_dict keys ending
with .weight_scale_2, which means the subsequent assertion checks can pass even
if Conv3d export regresses. Instead, build conv_prefixes from the list of Conv3d
modules that were discovered earlier in the test (before this section), so that
the assertions in this block only validate the Conv3d modules that were actually
expected to be exported. This ensures the test properly scopes its validation to
the specific Conv3d modules rather than all NVFP4 layers present in the
state_dict.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@tests/unit/torch/export/test_nvfp4_conv_export.py`:
- Line 318: Move the `from safetensors.torch import load_file, save_file` import
statement from line 318 inside the test function to the module scope at the top
of the file with the other imports. This ensures import failures are caught at
module load time rather than at runtime, and follows the project's import
convention that requires imports at the top of the file unless there is a
specific reason (circular imports or optional dependencies) to place them inside
functions.

---

Outside diff comments:
In `@tests/unit/torch/export/test_nvfp4_conv_export_diffusers.py`:
- Around line 108-123: The conv_prefixes list is currently built from all
state_dict keys ending with .weight_scale_2, which means the subsequent
assertion checks can pass even if Conv3d export regresses. Instead, build
conv_prefixes from the list of Conv3d modules that were discovered earlier in
the test (before this section), so that the assertions in this block only
validate the Conv3d modules that were actually expected to be exported. This
ensures the test properly scopes its validation to the specific Conv3d modules
rather than all NVFP4 layers present in the state_dict.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Enterprise

Run ID: 8ecadbbc-27bb-42c7-ba9f-6e8897cfd119

📥 Commits

Reviewing files that changed from the base of the PR and between 37dbbda and e0ebadbbc988f9f1d76b9d60f050a7f71a4a02f6.

📒 Files selected for processing (8)
  • CHANGELOG.rst
  • examples/diffusers/README.md
  • examples/diffusers/quantization/quantize.py
  • modelopt/torch/export/diffusers_utils.py
  • modelopt/torch/export/layer_utils.py
  • modelopt/torch/export/unified_export_hf.py
  • tests/unit/torch/export/test_nvfp4_conv_export.py
  • tests/unit/torch/export/test_nvfp4_conv_export_diffusers.py


def test_postprocess_safetensors_excludes_conv(tmp_path):
"""Conv stays logical on disk when pad/swizzle are enabled for other layers."""
from safetensors.torch import load_file, save_file

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

📐 Maintainability & Code Quality | 🟠 Major | ⚡ Quick win

Move safetensors imports to module scope.

Line 318 imports inside a test function without justification; this delays import failures until runtime and violates the test import convention.

As per path instructions, “Imports belong at the top of the file ... The only acceptable in-function imports are for circular imports or optional dependencies ... with a brief comment naming the reason.”

Suggested patch
 import pytest
 import torch
 import torch.nn as nn
+from safetensors.torch import load_file, save_file
 
 import modelopt.torch.quantization as mtq
 from modelopt.torch.export.diffusers_utils import (
@@
 def test_postprocess_safetensors_excludes_conv(tmp_path):
     """Conv stays logical on disk when pad/swizzle are enabled for other layers."""
-    from safetensors.torch import load_file, save_file
 
     sd = {**_mk_nvfp4_layer("transformer.proj", 64, 256), **_mk_nvfp4_layer("vae.conv1", 120, 240)}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@tests/unit/torch/export/test_nvfp4_conv_export.py` at line 318, Move the
`from safetensors.torch import load_file, save_file` import statement from line
318 inside the test function to the module scope at the top of the file with the
other imports. This ensures import failures are caught at module load time
rather than at runtime, and follows the project's import convention that
requires imports at the top of the file unless there is a specific reason
(circular imports or optional dependencies) to place them inside functions.

Source: Path instructions

@codecov

codecov Bot commented Jun 23, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 97.29730% with 2 lines in your changes missing coverage. Please review.
✅ Project coverage is 77.22%. Comparing base (9392dfe) to head (0030d2b).

Files with missing lines Patch % Lines
modelopt/torch/export/hf_export_handlers.py 96.66% 2 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #1809      +/-   ##
==========================================
+ Coverage   76.65%   77.22%   +0.57%     
==========================================
  Files         524      518       -6     
  Lines       59288    58274    -1014     
==========================================
- Hits        45445    45002     -443     
+ Misses      13843    13272     -571     
Flag Coverage Δ
examples 33.26% <31.08%> (+0.33%) ⬆️
gpu 58.86% <31.08%> (+0.09%) ⬆️
regression 15.14% <17.56%> (+0.33%) ⬆️
unit 54.89% <95.94%> (+0.09%) ⬆️

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.

@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 — DM the bot to share feedback.

Adds NVFP4 Conv3d weight export for the diffusers Wan 2.2 VAE to the unified HF export path. +636/-18, 8 files. I traced the core logic and it holds up: the conv flatten weight.reshape(O, -1) matches the calibration-time flatten in _nvfp4_quantize_weight_along_k (so byte-exactness is plausible and is pinned by a real test); the pad-before-scale ordering is correct (get_weights_scaling_factor requires block-divisible last dim); the static-quantizer rejection via NVFP4QTensor._is_static_quantizer is sound and tested; is_quantconv3d correctly matches _QuantDiffusersWanCausalConv3d/QuantConv3d while excluding Conv1d/Conv2d (no "Conv3d" substring) and ConvTranspose; and the nvfp4_exclude_layers plumbing correctly keeps conv prefixes out of the Linear-targeted pad/swizzle. New optional kwargs are backward-compatible. The lazy ONNX import in quantize.py has a valid documented justification (heavy optional dependency). Test coverage is strong (byte-exact vs NVFP4QTensor.quantize, dequant round-trip, schema, K-order sensitivity, dispatch routing, quantizer-hiding, pad/swizzle exclusion, plus a tiny real Wan VAE e2e). New test files' license headers match the canonical LICENSE_HEADER (standard-header exception applies — no licensing concern). No prompt-injection in PR text.

Why nudge rather than approve:

  • hide_quantizers_from_state_dict was generalized from "strip QuantLinear's weight/input/output quantizers" to "strip every *_quantizer child of every module." This now also strips attention bmm/softmax quantizers across ALL diffusers exports, not just conv. My read is this is a cleanup (the unified HF safetensors path never converted attention quantizers into usable scale buffers — FP8 MHA scales go through the ONNX export_fp8_mha symbolic path, so the previously-serialized *_quantizer._amax keys were unusable junk), but it changes a shared code path with broad blast radius (Flux/SD3/Wan/LTX-2) and only has manual GPU e2e validation.
  • The real numeric conv export was only manually validated on a Wan 2.2 5B VAE (48 layers); CI coverage is CPU-only.
  • Minor: some scale-derivation/input_scale duplication between _export_quantized_conv_weight and _export_quantized_weight, acceptable given the conv-specific flatten/static-reject.

Recommend a diffusers-export owner confirm the hide_quantizers_from_state_dict broadening is safe for the FP8-MHA/Linear paths and that the GPU conv export numerics are signed off.

@jingyu-ml
jingyu-ml force-pushed the feat/nvfp4-conv3d-export branch from e0ebadb to ebb674f Compare June 23, 2026 21:34

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Claude review passed — no blocking issues found. LGTM

Scope reviewed: All 8 changed files (modelopt/torch/export/{diffusers_utils,layer_utils,unified_export_hf}.py, examples/diffusers/quantization/quantize.py, both new test files, README, CHANGELOG). Note: the two-dot git diff origin/main HEAD was polluted by unrelated MoE-refactor commits already on main; I reviewed against the authoritative gh pr diff (8 files).

What I verified:

  • Algorithm correctness — The export-time flatten weight.reshape(O, -1) exactly matches the calibration-time flatten in _nvfp4_quantize_weight_along_k (quant_conv.py:81), so per-block grouping is identical between calibration and export. Grouped-conv reduction dim K = (in_channels // groups) * kt*kh*kw is correctly captured. Padding K with zeros leaves amax unchanged, so weight_scale_2 and per-block scales are stable and the byte-exact round-trip holds.
  • Scope guards — static NVFP4 weight quantizer is rejected loudly (NotImplementedError); non-NVFP4 conv warns and leaves the weight unpacked. Both are strict improvements over the prior fall-through that leaked quantizer buffers.
  • Mode/State — the generalized hide_quantizers_from_state_dict strips every *_quantizer child and restores on exit; the delete-during-named_modules() walk is safe (the child _modules mutation precedes that level's .items() iterator) and matches the prior pattern.
  • Export compatibility — Conv3d prefixes are correctly excluded from pad_nvfp4_weights / swizzle_nvfp4_scales via nvfp4_exclude_layers, keeping the logical flattened-K layout for the downstream conv kernel. input_scale emission mirrors the NVFP4 Linear path verbatim.
  • Routing — is_quantconv3d matches _QuantConv3d / QuantConv3d / _QuantDiffusersWanCausalConv3d, and excludes Conv1d/Conv2d and all ConvTranspose variants; consistent string-matching style with is_quantlinear.
  • Lazy ONNX import in quantize.py is confined to export_onnx (its only use site).

Additive, backward-compatible, and covered by focused CPU unit + e2e tests. No correctness, mode/state, export, compatibility, or performance concerns found.

export_dir: Path,
pipe: Any | None = None,
hf_quant_config: dict | None = None,
nvfp4_exclude_layers: set[str] | None = None,

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.

what are the layers that we would like to exclude? can we infer by naming instead of introducing a new arg?

@jingyu-ml
jingyu-ml requested a review from cjluo-nv July 1, 2026 05:48
@jingyu-ml
jingyu-ml force-pushed the feat/nvfp4-conv3d-export branch from ebb674f to 0030d2b Compare July 17, 2026 22:01

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Warning

CodeRabbit couldn't request changes on this pull request because it doesn't have sufficient GitHub permissions.

Please grant CodeRabbit Pull requests: Read and write permission and re-run the review.

👉 Steps to fix this

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
modelopt/torch/export/unified_export_hf.py (1)

1071-1083: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Restore buffers that existed before export.

register_buffer() replaces existing pre_quant_scale/svdquant_lora_* buffers, then Lines 1095-1098 delete them unconditionally. Exporting a module that already has these buffers permanently mutates it. Snapshot each original buffer (including absence) and restore that state in the finally cleanup.

Also applies to: 1086-1098

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@modelopt/torch/export/unified_export_hf.py` around lines 1071 - 1083, Update
the export cleanup around the buffer promotion logic and its finally block to
snapshot each original pre_quant_scale and svdquant_lora_a/svdquant_lora_b
buffer, including whether it was absent, before register_buffer replaces it. In
the finally cleanup, restore each buffer’s original value or remove it when it
was originally absent, rather than unconditionally deleting the promoted
buffers; preserve normal cleanup for newly created buffers.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@modelopt/torch/export/hf_export_handlers.py`:
- Around line 215-217: Replace the _validate_dynamic_nvfp4_quantizer call for
input_quantizer with an input-specific validator that accepts the supported
calibrated activation quantizer contract and does not require dynamic block-16
NVFP4. Preserve the existing _validate_dynamic_nvfp4_quantizer validation for
the weight quantizer and ensure valid inputs continue to produce the input_scale
export.

---

Outside diff comments:
In `@modelopt/torch/export/unified_export_hf.py`:
- Around line 1071-1083: Update the export cleanup around the buffer promotion
logic and its finally block to snapshot each original pre_quant_scale and
svdquant_lora_a/svdquant_lora_b buffer, including whether it was absent, before
register_buffer replaces it. In the finally cleanup, restore each buffer’s
original value or remove it when it was originally absent, rather than
unconditionally deleting the promoted buffers; preserve normal cleanup for newly
created buffers.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Enterprise

Run ID: e79ac331-49d3-46e4-9e47-e505f040168f

📥 Commits

Reviewing files that changed from the base of the PR and between ebb674f and 0030d2b.

📒 Files selected for processing (4)
  • CHANGELOG.rst
  • modelopt/torch/export/convert_hf_config.py
  • modelopt/torch/export/hf_export_handlers.py
  • modelopt/torch/export/unified_export_hf.py

Comment on lines +215 to +217
input_quantizer = _validate_dynamic_nvfp4_quantizer(
getattr(sub_module, quantizer_attrs.input_quantizer, None), "input"
)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Do not require the weight-only dynamic contract for activations.

This applies _validate_dynamic_nvfp4_quantizer() to input_quantizer, requiring dynamic block-16 NVFP4. The supported contract documents only a dynamic weight quantizer, while Lines 264-272 export a calibrated scalar activation scale. Use an input-specific validator so supported calibrated input quantizers reach input_scale export.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@modelopt/torch/export/hf_export_handlers.py` around lines 215 - 217, Replace
the _validate_dynamic_nvfp4_quantizer call for input_quantizer with an
input-specific validator that accepts the supported calibrated activation
quantizer contract and does not require dynamic block-16 NVFP4. Preserve the
existing _validate_dynamic_nvfp4_quantizer validation for the weight quantizer
and ensure valid inputs continue to produce the input_scale export.

@jingyu-ml jingyu-ml closed this Oct 2, 2026
@kevalmorabia97
kevalmorabia97 deleted the feat/nvfp4-conv3d-export branch November 3, 2026 06:29
yingguo-trt added a commit to yingguo-trt/Model-Optimizer that referenced this pull request Nov 6, 2026
…or unquantized Conv3d weights

The unified Hugging Face export packs only the modules an export handler
matches, and none matched a quantized Wan VAE convolution: the generic
handler tests is_quantlinear, which checks the class name, and the
quantized class is named QuantWanCausalConv3d. Its weights were saved
unquantized, while get_quant_config, which reads the quantizer state of
every module, still declared NVFP4 (or FP8) for them, with targets
["Linear"]. TensorRT-LLM then loaded the VAE as BF16 without an error.

Port the Conv3d export of closed PR NVIDIA#1809. A handler keyed on
WanCausalConv3d packs dynamic block-16 NVFP4 weights along the flattened
[O, C*kt*kh*kw] reduction axis that the fake-quant path uses, and
registers weight_scale, weight_scale_2 and input_scale; the diffusers
export then declares targets ["Conv3d"]. Any other format, a partly
quantized or uncalibrated convolution, and the GEMM padding and swizzle
options raise instead of writing a checkpoint whose config does not
match its weights. Unlike NVIDIA#1809, the handlers import the format
constants from quant_format, and the Conv3d handler calls its packer
directly, since a diffusers export never takes the FSDP2 no-gather path.

Text-to-video calibration never runs the VAE encoder, so the diffusers
example now quantizes only the decoder's resnet convolutions; the
encoder's had no input range to export.

The Linear export, other module types, and the config of components
without Wan convolutions are unchanged.

Co-authored-by: Jingyu Xin <[email protected]>
Signed-off-by: yingguo-trt <[email protected]>
yingguo-trt added a commit that referenced this pull request Nov 9, 2026
…or unquantized Conv3d weights (#3247)

### What does this PR do?

Type of change: Bug fix

Quantizing the Wan VAE with `examples/diffusers/quantization/quantize.py
--backbone vae --format fp4 --hf-ckpt-dir ...` writes a checkpoint whose
`quantization_config` declares static NVFP4 (`group_size` 16, `targets:
["Linear"]`), while every `Conv3d` weight in it is BF16 and no scale is
saved. TensorRT-LLM VisualGen loads that VAE as BF16 without an error
and logs `Loaded NVFP4 Wan VAE: 0 quantized convs; 0 run on the FP4
kernel (0 static, 0 dynamic)`. `--format fp8` is mislabeled the same
way.

The unified Hugging Face export packs only the modules an export handler
matches. The generic handler tests `is_quantlinear`, which checks the
class name, so the quantized `QuantWanCausalConv3d` matched no handler
and kept its weight. `get_quant_config` reads the quantizer state of
every module, so it still declared the format, and
`convert_hf_quant_config_format` hard-codes `targets: ["Linear"]`.

This PR ports the Conv3d export of #1809, which was closed without being
merged:
- `hf_export_handlers.py`: a handler keyed on `WanCausalConv3d` packs
dynamic block-16 NVFP4 weights along the flattened `[O, C*kt*kh*kw]`
axis, the axis the `Conv3d` fake-quant path quantizes along, and
registers `weight_scale`, `weight_scale_2` and `input_scale`. This is
the layout TensorRT-LLM's Wan VAE loader reads (1.3.0rc27 and later).
Other formats, grouped convolutions, partly quantized convolutions and
convolutions with no calibrated input range raise.
- `unified_export_hf.py`, `convert_hf_config.py`: the diffusers export
declares `targets: ["Conv3d"]` for those modules. It rejects
`padding_strategy` and `enable_swizzle_layout`, which describe GEMM
weight layouts, for a component that has them.
- `examples/diffusers/quantization/utils.py`: text-to-video calibration
never runs the VAE encoder, so its convolutions had no input range and
the export now refuses them. The Wan VAE filter now keeps only the
decoder's resnet convolutions, as the LTX-2 VAE filter already does. The
generated video is unchanged, since text-to-video never runs the
encoder.

Changes from #1809: the handlers import the format constants from
`.quant_format`, since `model_config.py` moved in #2365, and the Conv3d
handler calls its packer directly, since a diffusers export never takes
the FSDP2 no-gather path. #1809's standalone test file is replaced by
the tests below.

Behavior change: an FP8, or any other non-NVFP4, Hugging Face export of
the Wan VAE now raises `NotImplementedError` instead of writing BF16
weights under an FP8 declaration. TensorRT-LLM's Wan VAE loader accepts
only NVFP4.

Unchanged: the Linear export, other module types, and the config of
components without Wan convolutions, which keep `targets: ["Linear"]`.

Out of scope: quantized `Conv2d` layers, and `Conv3d` classes other than
`WanCausalConv3d`, are still not packed by the HF export. The example's
filters keep them unquantized. Failing on every unpacked quantized
module would also fail the existing SDXL `Conv2d` exports.

### Usage

```bash
cd examples/diffusers/quantization
python quantize.py --model wan2.2-t2v-5b --backbone vae --format fp4 \
    --quant-algo max --collect-method default \
    --model-dtype BFloat16 --trt-high-precision-dtype BFloat16 \
    --batch-size 1 --calib-size 32 --n-steps 30 \
    --quantized-torch-ckpt-save-path ./wan22_vae_fp4.pt --hf-ckpt-dir ./wan22_vae_fp4_hf
```

`wan22_vae_fp4_hf/vae/` now holds packed NVFP4 weights with their scales
for the decoder's resnet convolutions, and its `quantization_config`
targets `Conv3d`.

### Testing

All GPU runs used one NVIDIA B300 (compute capability 10.3) in
`nvcr.io/nvidia/pytorch:26.07-py3`, on base `77ef48794f`. The branch was
then rebased onto `09a14b9ae8`, which adds one unrelated commit; `git
range-diff` shows the patch unchanged, and the new unit tests pass again
on the rebased head.

- New unit tests in `tests/unit/torch/export/test_export_diffusers.py`
(CPU, under 1 s each). They quantize a tiny `AutoencoderKLWan` as the
example does for text-to-video: calibration runs only `decode`, and only
the decoder's resnet convolutions stay quantized.
- `test_export_wan_vae_nvfp4_conv3d`: every quantized convolution is
exported as a uint8 `[O, C*kt*kh*kw/2]` weight with an E4M3
`weight_scale` of `[O, C*kt*kh*kw/16]`, a `weight_scale_2` equal to the
calibrated amax / (6 * 448), and an `input_scale`. Every other
convolution stays floating point and is covered by `ignore`. The config
is NVFP4 with `targets: ["Conv3d"]`.
- `test_export_wan_vae_conv3d_fails_closed`, for FP8, weight-only NVFP4,
an uncalibrated encoder convolution and `padding_strategy`: each export
raises, and no `config.json` is written.
- All 5 fail on the `upstream/main` source (`targets` is `['Linear']`;
`DID NOT RAISE`) and pass with the fix.
- `tests/examples/diffusers/test_diffusers.py`: `wan22_5b_vae_fp4_max`
now also exports the HF checkpoint and checks that the VAE holds packed
NVFP4 convolutions with all three scales. With the fix, all 7 `wan22`
example cases pass. On `upstream/main` this case fails (`assert
['Linear'] == ['Conv3d']`). With the export fix but the old example
filter, it fails with `Failed to export Conv3d
'encoder.down_blocks.0.conv1' (type=QuantWanCausalConv3d): Conv3d input
quantizer must be calibrated before export.`
- Numerics on GPU (scripts, not checked in):
- On the tiny VAE quantized as the example does, every exported
convolution dequantizes to exactly the weight the fake-quant forward
uses (20 of 20).
- The same weights packed as a `WanCausalConv3d(256, 256, 3)` by the new
export, and as an `nn.Linear(6912, 256)` by the existing Linear export,
give identical packed weights and scales. Both differ from the Triton
fake quantization in the same 866 of 1.77M elements (0.05%), elements
whose scaled value sits on an E2M1 rounding midpoint. The export matches
an IEEE-division emulation of the kernel's formula exactly, so the
difference comes from the kernel's fp32 division. It predates this PR
and is not specific to `Conv3d`.
- Packing the largest Wan 2.2 VAE decoder convolution (1024 to 1024
channels, 3x3x3, 54 MiB in BF16) takes 3.1 ms and peaks 386 MiB above
the starting allocation. The Linear export of the same weights takes 2.6
ms and peaks at 388 MiB.
- Existing tests, fix vs `upstream/main`:
- `tests/unit/torch/export`: 703 passed and 2 failed, vs 698 passed and
2 failed. The same two streaming-export tests in
`test_fsdp2_parallel_export.py` fail on both in this container.
- `tests/gpu/torch/export/test_export_diffusers.py` and
`tests/gpu/torch/export/test_export.py`: 76 passed on both.
- pre-commit passed on the changed files, except mypy and markdownlint:
- mypy fails on Windows on the unmodified base too; `mypy --platform
linux` reports nothing in the changed files, so the commit used
`SKIP=mypy`.
- markdownlint could not install Node locally, and no Markdown file
changed.

Still to come: the QA deployment case on the real
`Wan-AI/Wan2.2-TI2V-5B-Diffusers` VAE, exported from this branch and
loaded by TensorRT-LLM VisualGen on a B100 (SM100), which has to report
its quantized convolutions running on the FP4 kernel. Its result will be
added here.

Not run:
- multiple GPUs;
- an HF export of the Wan 2.2 14B pipeline's VAE (same
`AutoencoderKLWan` class), which the example tests only quantize and
restore;
- video quality.

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

Contributor and security guidance reviewed; the commit is signed and
signed off.

- Is this change backward compatible?: ❌ An FP8 (or other non-NVFP4) HF
export of the Wan VAE now raises instead of writing an FP8-labeled BF16
checkpoint, which no runtime could use as FP8. NVFP4 exports change from
mislabeled BF16 to packed NVFP4. Everything else is unchanged.
- If you copied code from any other sources or added a new PIP
dependency, did you follow guidance in `CONTRIBUTING.md`: N/A. The
ported code is from #1809 in this repository; its author is credited as
co-author.
- Did you write any new necessary tests?: ✅ Two unit tests (one
parametrized) and one extended example test, all failing without the
fix.
- Did you update
[Changelog](https://github.com/NVIDIA/Model-Optimizer/blob/main/CHANGELOG.rst)?:
✅ 0.49.0 Bug Fixes.
- Did you get Claude approval on this PR?: ❌ Not yet reviewed by Claude.

### Additional Information

Supersedes #1809.


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

## Summary by CodeRabbit

* **New Features**
* Added NVFP4 export support for quantized Wan VAE convolution layers,
with packed weights and scaling data.
  * Exported quantization settings now identify applicable layer types.

* **Bug Fixes**
* Wan VAE text-to-video calibration excludes encoder convolutions that
are not calibrated.
* Unsupported quantization formats and export options now raise clear
errors.

* **Documentation**
* Updated the 0.49.0 changelog with compatibility notes, including that
older VAE checkpoints may need to be re-exported.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Signed-off-by: yingguo-trt <[email protected]>
Co-authored-by: Jingyu Xin <[email protected]>
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