Repository navigation
Conversation
📝 WalkthroughWalkthroughAdds NVFP4 export support for Wan ChangesNVFP4 Wan Conv3d export
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
Suggested reviewers: 🚥 Pre-merge checks | ✅ 5 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (5 passed)
✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Comment |
|
/claude review |
|
There was a problem hiding this comment.
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.
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 winScope on-disk schema checks to the Conv3d modules discovered earlier.
conv_prefixesis currently built from every*.weight_scale_2key, 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.rstexamples/diffusers/README.mdexamples/diffusers/quantization/quantize.pymodelopt/torch/export/diffusers_utils.pymodelopt/torch/export/layer_utils.pymodelopt/torch/export/unified_export_hf.pytests/unit/torch/export/test_nvfp4_conv_export.pytests/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 |
There was a problem hiding this comment.
📐 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 Report❌ Patch coverage is
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
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:
|
cjluo-nv
left a comment
There was a problem hiding this comment.
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_dictwas generalized from "strip QuantLinear's weight/input/output quantizers" to "strip every*_quantizerchild 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 ONNXexport_fp8_mhasymbolic path, so the previously-serialized*_quantizer._amaxkeys 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_weightand_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.
e0ebadb to
ebb674f
Compare
There was a problem hiding this comment.
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 dimK = (in_channels // groups) * kt*kh*kwis correctly captured. Padding K with zeros leaves amax unchanged, soweight_scale_2and 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_dictstrips every*_quantizerchild and restores on exit; the delete-during-named_modules()walk is safe (the child_modulesmutation precedes that level's.items()iterator) and matches the prior pattern. - Export compatibility — Conv3d prefixes are correctly excluded from
pad_nvfp4_weights/swizzle_nvfp4_scalesvianvfp4_exclude_layers, keeping the logical flattened-K layout for the downstream conv kernel.input_scaleemission mirrors the NVFP4 Linear path verbatim. - Routing —
is_quantconv3dmatches_QuantConv3d/QuantConv3d/_QuantDiffusersWanCausalConv3d, and excludes Conv1d/Conv2d and all ConvTranspose variants; consistent string-matching style withis_quantlinear. - Lazy ONNX import in
quantize.pyis confined toexport_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, |
There was a problem hiding this comment.
what are the layers that we would like to exclude? can we infer by naming instead of introducing a new arg?
Signed-off-by: Jingyu Xin <[email protected]>
ebb674f to
0030d2b
Compare
There was a problem hiding this comment.
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.
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 winRestore buffers that existed before export.
register_buffer()replaces existingpre_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 thefinallycleanup.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
📒 Files selected for processing (4)
CHANGELOG.rstmodelopt/torch/export/convert_hf_config.pymodelopt/torch/export/hf_export_handlers.pymodelopt/torch/export/unified_export_hf.py
| input_quantizer = _validate_dynamic_nvfp4_quantizer( | ||
| getattr(sub_module, quantizer_attrs.input_quantizer, None), "input" | ||
| ) |
There was a problem hiding this comment.
🎯 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.
…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]>
…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]>
What does this PR do?
Adds narrowly scoped NVFP4 Conv3d export support for the Wan VAE
WanCausalConv3dstack 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:
WanCausalConv3d-specific export handler through the existing export registry;[O, C, kt, kh, kw]to logical[O, K], padsKto block size 16, and writes packedweight,weight_scale, scalarweight_scale_2, and calibratedinput_scaletensors;targets: ["Conv3d"]for a Conv3d-only VAE while preserving the historical Linear default for existing callers;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 differentNVIDIAModelOptConfig/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 HEADinput_scaleBefore your PR is ready for review
Summary by CodeRabbit
New Features
Conv3dlayers.Conv3dtargets.Documentation