Files
yingguo-trtandJingyu Xin 64cb6ed78e [NVBug 6927434] Fix the Wan VAE Hugging Face export declaring NVFP4 for 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 <244492186+yingguo-trt@users.noreply.github.com>
Co-authored-by: Jingyu Xin <jingyux@nvidia.com>
2026-11-09 09:50:17 +08:00
..
2026-06-27 01:00:25 +05:30

Diffusers Model Optimizations

Warning

The Diffusers ONNX export and TensorRT engine deployment workflow is deprecated in ModelOpt 0.48.0 and will be removed no earlier than 0.49.0, after the one-release migration period described in the Deprecation Policy section of the main README. The legacy workflow remains available during this period. Export a unified Hugging Face checkpoint with --hf-ckpt-dir for deployment with a compatible diffusion backend. Diffusers quantization, HF export, and PyTorch workflows remain supported.

Model Optimizer supports techniques like Cache Diffusion and Quantization for Diffusion models.

Post-training quantization (PTQ) is an effective model optimization technique that compresses your models to lower precision like INT8, FP8, NVFP4, etc. Quantization with Model Optimizer can compress model size by 2x-4x, speeding up inference while preserving model quality. Quantization-Aware Training (QAT) is a powerful technique for optimizing your models, particularly when PTQ methods fail to meet the requirements for your tasks.

Cache Diffusion is a technique that reuses cached outputs from previous diffusion steps instead of recalculating them. This training-free caching approach is compatible with a variety of models, like DiT and UNet, enabling considerable acceleration without compromising quality.

Section Description Link Docs
Pre-Requisites Required & optional packages to use this technique [Link]
Getting Started Learn how to optimize your models using quantization/cache diffusion to reduce precision and improve inference efficiency [Link] [docs]
Support Matrix View the support matrix to see quantization/cache diffusion compatibility and feature availability across different models [Link] [docs]
Sparse Attention (Skip-Softmax) Skip-softmax sparse attention for diffusion models [Link]
Cache Diffusion Caching technique to accelerate inference without compromising quality [Link]
Post Training Quantization (PTQ) Example scripts on how to run PTQ on diffusion models [Link] [docs]
Quantization Aware Training (QAT) Example scripts on how to run QAT on diffusion models [Link] [docs]
Quantization Aware Distillation (QAD) Example scripts on how to run QAD on diffusion models [Link] [docs]
HF Checkpoint Deployment Migrate to diffusion backends using unified HF checkpoints [Link]
Build and Run with TensorRT (Deprecated) Legacy ONNX export and TensorRT engine deployment [Link]
LoRA Fuse your LoRA weights prior to quantization [Link]
Pre-Quantized Checkpoints Ready to deploy Hugging Face pre-quantized checkpoints [Link]
Resources Extra links to relevant resources [Link]

Pre-Requisites

Docker

Please use the TensorRT docker image (e.g., nvcr.io/nvidia/tensorrt:26.02-py3) or visit our installation docs for more information.

Also follow the installation steps below to upgrade to the latest version of Model Optimizer and install example-specific dependencies.

Local Installation

Install Model Optimizer with onnx and hf dependencies using pip from PyPI:

pip install nvidia-modelopt[onnx,hf]
pip install -r requirements.txt

Each subsection (fastgen, distillation, etc.) may have their own requirements.txt file that needs to be installed separately.

You can find the latest TensorRT here.

Visit our installation docs for more information.

Getting Started

Quantization

With the simple API below, you can very easily use Model Optimizer to quantize your model. Model Optimizer achieves this by converting the precision of your model to the desired precision, and then using a small dataset (typically 128-512 samples) to calibrate the quantization scaling factors.

import modelopt.torch.quantization as mtq

def forward_pass(model):
    for prompt in prompts:
        _ = model(prompt)

mtq.quantize(model=transformer, config=quant_config, forward_func=forward_pass)

Support Matrix

TensorRT Compiler Framework

Warning

This ONNX/TensorRT deployment path is deprecated in 0.48.0, with removal no earlier than 0.49.0. This matrix describes the legacy path; it does not establish compatibility with HF checkpoint deployment backends.

Model fp8 int8_sq int4_awq w4a8_awq1 nvfp42 nvfp4_svdquant3 Cache Diffusion
FLUX ✅ ✅ ✅ ✅ ✅ ✅ -
Stable Diffusion 3 ✅ ✅ ✅ ✅ ✅ ✅ ✅
Stable Diffusion XL ✅ ✅ ✅ ✅ ✅ ✅ ✅
SDXL-Turbo ✅ ✅ ✅ ✅ ✅ ✅ -
Stable Diffusion 2.1 ✅ ✅ ✅ ✅ ✅ ✅ -

1.The w4a8_awq is an experimental quantization scheme that may result in a higher accuracy penalty.

2.A selective set of the popular models are internally tested. The actual model support list may be longer. NVFP4 inference requires Blackwell GPUs and TensorRT-LLM v1.2 or later

3.The SVDQuant Perf in TRT might not good as the Nunchaku: MIT-Nvidia at this moment.

Post Training Quantization (PTQ)

We support calibration for INT8, FP8 and FP4 precision and for both weights and activations. The examples below shows how to use Model Optimizer to calibrate and quantize the backbone section of diffusion models. The backbone section typically consumes >95% of the E2E diffusion latency.

We also provide instructions on deploying and running E2E diffusion pipelines with Model Optimizer quantized INT8 and FP8 Backbone to generate images and measure latency on target GPUs. Note, Jetson devices are not supported at this time due to the incompatibility of the software.

Note

Model calibration requires relatively more GPU computing power than deployment. It does not need to be on the same GPUs as the deployment target GPUs. Deprecated ONNX export and TensorRT engine instructions remain available in quantization/ONNX-TRT-Deployment.md.

Quantize scripts

FLUX|SD3|SDXL INT8 Script

python quantize.py \
    --model {flux-dev|flux-schnell|sdxl-1.0|sdxl-turbo|sd3-medium|sd3.5-medium} \
    --format int8 --batch-size 2 \
    --calib-size 32 --alpha 0.8 --n-steps 20 \
    --model-dtype {Half/BFloat16} \
    --quantized-torch-ckpt-save-path ./{MODEL_NAME}.pt \
    --hf-ckpt-dir ./hf_ckpt

FLUX|SD3|SDXL|LTX|WAN2.2 FP8/FP4 Script

python quantize.py \
    --model {flux-dev|flux-schnell|sdxl-1.0|sdxl-turbo|sd3-medium|sd3.5-medium|ltx-video-dev|wan2.2-t2v-14b|wan2.2-t2v-5b} \
    --model-dtype {Half|BFloat16} \
    --format {fp8|fp4} --batch-size 2 --calib-size {128|256} --quantize-mha \
    --n-steps 20 --quantized-torch-ckpt-save-path ./{MODEL_NAME}.pt --collect-method default \
    --hf-ckpt-dir ./hf_ckpt

HF exports omit attention quantizer state by default, including when calibration uses --quantize-mha, except for FLUX.1. Qwen-Image's TRT-LLM loader requires this clean checkpoint. FLUX.1 retains enabled Q/K/V _amax keys by default for compatibility with the static FP8 attention path in TensorRT-LLM PR #18396. Use --extra-param export_attention_quantizers=true to retain enabled Q/K/V quantizers explicitly, or export_attention_quantizers=false to omit them, including for FLUX.1. Disabled quantizers are always omitted. The equivalent Python option is export_hf_checkpoint(pipe, export_dir="./hf_ckpt", export_attention_quantizers=True). Diffusion attention quantization, including native LTX-2 components, is not exported as KV-cache quantization. Transformers components retain their KV-cache metadata.

Wan 2.2 VAE NVFP4 (Conv3D Implicit GEMM)

The Wan 2.2 VAE (AutoencoderKLWan, shared between the 5B and 14B pipelines) is built from 3D convolutions. When quantizing the VAE with NVFP4, the Conv3d layers are automatically dispatched through a custom BF16 WMMA implicit-GEMM kernel with fused FP4 activation quantization. Requires SM80+ (Ampere or newer). See modelopt/torch/kernels/quantization/conv/README.md for kernel details.

python quantize.py \
    --model {wan2.2-t2v-14b|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

LTX-2 FP4

Warning

Third-Party License Notice — LTX-2

LTX-2 is a third-party model and set of packages developed and provided by Lightricks. LTX-2 is not covered by the Apache 2.0 license that governs NVIDIA Model Optimizer.

By installing and using LTX-2 packages (ltx-core, ltx-pipelines, ltx-trainer) with NVIDIA Model Optimizer, you must comply with the LTX Community License Agreement.

Any derivative models or fine-tuned weights produced from LTX-2 using NVIDIA Model Optimizer (including quantized or distilled checkpoints) remain subject to the LTX Community License Agreement and are not covered by Apache 2.0.

Note

This example targets the LTX-2 packages at commit 28c3c73 (QuantizationPolicy.fp8_cast() and checkpoint_path/gemma_root pipeline arguments), e.g. pip install "ltx-core @ git+https://github.com/Lightricks/LTX-2.git@28c3c73#subdirectory=packages/ltx-core" "ltx-pipelines @ git+https://github.com/Lightricks/LTX-2.git@28c3c73#subdirectory=packages/ltx-pipelines". Newer LTX-2 releases removed fp8_cast() and changed the pipeline constructor, so this example does not run on them yet.

This example produces three outputs: a PyTorch checkpoint (--quantized-torch-ckpt-save-path), a Hugging Face checkpoint (--hf-ckpt-dir), and a ComfyUI-compatible merged safetensor (--extra-param merged_base_safetensor_path).

python quantize.py \
    --model ltx-2 --format fp4 --batch-size 1 --calib-size 32 --n-steps 40 \
    --extra-param checkpoint_path=./ltx-2-19b-dev-fp8.safetensors \
    --extra-param distilled_lora_path=./ltx-2-19b-distilled-lora-384.safetensors \
    --extra-param spatial_upsampler_path=./ltx-2-spatial-upscaler-x2-1.0.safetensors \
    --extra-param gemma_root=./gemma-3-12b-it-qat-q4_0-unquantized \
    --extra-param fp8transformer=true \
    --quantized-torch-ckpt-save-path ./ltx-2-transformer.pt \
    --hf-ckpt-dir ./LTX2-NVFP4/ \
    --extra-param merged_base_safetensor_path=./ltx-2-19b-dev-fp8.safetensors

To additionally apply NVFP4 scale swizzle and padding , add:

    --extra-param enable_swizzle_layout=true \
    --extra-param padding_strategy=row_col

Important Parameters

  • percentile: Control quantization scaling factors (amax) collecting range, meaning that we will collect the chosen amax in the range of (n_steps * percentile) steps. Recommendation: 1.0
  • alpha: A parameter in SmoothQuant, used for linear layers only. Recommendation: 0.8 for SDXL
  • calib-size: For SDXL INT8, we recommend 32 or 64, for SDXL FP8, 128 is recommended.
  • n_steps: Recommendation: SD/SDXL 20 or 30, SDXL-Turbo 4.

Use the generated checkpoint directly in PyTorch or export a unified Hugging Face checkpoint with --hf-ckpt-dir. Choose a diffusion deployment backend that supports your model, quantization format, and hardware; compatibility must be checked for each backend. The deprecated ONNX/TensorRT workflow remains available during the migration period.

Quantization Aware Training (QAT)

Quantization-Aware Training (QAT) is a powerful technique for optimizing your models, particularly when post-training quantization (PTQ) methods fail to meet the requirements for your tasks. By simulating the effects of quantization during training, QAT allows the model to learn to minimize the quantization error, ultimately delivering better accuracy.

While the example below uses Hugging Face Accelerate for simplicity. You can integrate QAT into your workflow using your preferred training setup.

How QAT Works in ModelOPT

With ModelOPT, the forward pass simulates quantization, allowing the model to adjust its weights to minimize training loss and reduce quantization errors. This enables the model to better handle the constraints of quantized hardware without significant loss of performance.

import modelopt.torch.opt as mto

# Restore the model in its quantized state using ModelOPT's API
mto.restore(transformer_model, args.restore_quantized_ckpt)

# Move the model to the appropriate device and set the desired weight precision
transformer_model.to(accelerator.device, dtype=weight_dtype)
transformer_model.requires_grad_(True)

transformer_model, optimizer, train_dataloader, lr_scheduler = accelerator.prepare(
    transformer_model, optimizer, train_dataloader, lr_scheduler
)

Once the model is loaded in its quantized state through ModelOPT, you can proceed with regular training. The QAT process will automatically take place during the forward passes.

Quantization Aware Distillation (QAD)

Distillation is a powerful approach where a high-precision model (the teacher) guides the training of a quantized model (the student). ModelOPT simplifies the process of combining distillation with QAT by handling most of the complexity for you.

For more details about distillation, please refer to this link.

import modelopt.torch.opt as mto
import modelopt.torch.distill as mtd

# Restore the model in its quantized state using ModelOPT's API
mto.restore(transformer, args.restore_quantized_ckpt)

'''
After mtd.convert, the model structure becomes:

model:
    transformer_0
    transformer_1
    teacher_model:
        transformer_0
        transformer_1

And the forward pass is automatically monkey-patched to:

def forward(input):
    student_output = model(input)
    _ = teacher_model(input)
    return student_output
'''

+ # Configuration for knowledge distillation (KD)
+ kd_config = {
+     "teacher_model": teacher_model,
+     "criterion": distill_config["criterion"],
+     "loss_balancer": distill_config["loss_balancer"],
+ }
+ transformer = mtd.convert(transformer, mode=[("kd_loss", kd_config)])

# Move the model to the appropriate device and set the desired weight precision
transformer.to(accelerator.device, dtype=weight_dtype)
transformer.requires_grad_(True)

# Making sure to freeze the weights from model._teacher_model
transformer, optimizer, train_dataloader, lr_scheduler = accelerator.prepare(
    transformer, optimizer, train_dataloader, lr_scheduler
)

# Compute the distillation loss using ModelOPT's compute_kd_loss
+ ...
+ loss = transformer.compute_kd_loss(...)
+ ...

HF Checkpoint Deployment

Replace --onnx-dir with --hf-ckpt-dir in the quantization commands. For example, from examples/diffusers/quantization:

python quantize.py \
    --model flux-schnell --model-dtype BFloat16 \
    --format fp8 --collect-method default \
    --batch-size 1 --calib-size 128 --n-steps 4 \
    --hf-ckpt-dir ./flux-schnell-fp8

To reuse a ModelOpt PyTorch checkpoint, add --restore-from /path/to/checkpoint_dir/ to the matching model's command. This is the directory passed as --quantized-torch-ckpt-save-path in the original run; it must contain a <backbone>.pt file for each selected backbone (for example, transformer.pt for FLUX or unet.pt for SDXL). Keep the original model selection and any model-specific options. An ONNX file or TensorRT engine cannot be restored this way; use the saved ModelOpt checkpoint or quantize the original model again.

The export contains weights and configuration for downstream loading. Preserve the complete export directory, including component configuration and quantization metadata. See the unified HF export guide for the artifact format.

Select a backend using its diffusion-specific model and quantization support guide:

Backend Deployment guidance Compatibility considerations
vLLM-Omni ModelOpt quantization guide Documents FP8 and mixed FP8/NVFP4 diffusion checkpoints. Check the model-specific recipe; its NVFP4 recipes are validated on Blackwell.
SGLang Diffusion Diffusion quantization guide Distinguishes full Diffusers repos from converted transformer components. Some exports need backend-specific conversion or component overrides.
TensorRT-LLM VisualGen Visual generation guide and serving examples Supports pre-quantized checkpoints with ModelOpt metadata. Consult the model/precision matrix and model-specific configuration; VisualGen is beta.

Install the backend separately using its installation instructions and use documentation matching that backend version. The following command forms illustrate loading a full pipeline checkpoint supported by the selected backend; they do not establish support for every export produced above:

# vLLM-Omni: follow the model recipe for parallelism and kernel options.
vllm serve /path/to/supported-hf-checkpoint --omni

# SGLang Diffusion: full pipeline checkpoint, including model_index.json.
sglang generate --model-path /path/to/supported-hf-checkpoint \
    --prompt "A red ceramic teapot on a wooden table" --save-output

# TensorRT-LLM VisualGen: use the model's serving configuration as needed.
trtllm-serve /path/to/supported-hf-checkpoint

If no backend supports your model and precision yet, keep using the legacy workflow during the migration period and report the gap to the maintainers.

Build and Run with TensorRT Compiler Framework

This workflow is deprecated in 0.48.0, with removal no earlier than 0.49.0. Legacy ONNX export and TensorRT engine instructions remain available in quantization/ONNX-TRT-Deployment.md.

LoRA

For optimal performance of INT8/FP8 quantized models, we highly recommend fusing the LoRA weights prior to quantization. Failing to do so can disrupt TensorRT kernel fusion when integrating the LoRA layer with INT8/FP8 Quantize-Dequantize (QDQ) nodes, potentially leading to performance losses.

Detailed guidance on how to fuse LoRA weights can be found in the Hugging Face PEFT documentation:

After fusing the weights, proceed with the calibration and you can follow our code to do the quantization.

pipe = DiffusionPipeline.from_pretrained(
    "stabilityai/stable-diffusion-xl-base-1.0",
    torch_dtype=torch.float16,
    variant="fp16",
    use_safetensors=True,
).to("cuda")
pipe.load_lora_weights(
    "CiroN2022/toy-face", weight_name="toy_face_sdxl.safetensors", adapter_name="toy"
)
pipe.fuse_lora(lora_scale=0.9)
...
# All the LoRA layers should be fused
check_lora(pipe.unet)

mtq.quantize(pipe.unet, quant_config, forward_loop)
mto.save(pipe.unet, ...)

When it's time to export the model to ONNX format, ensure that you load the PEFT-modified LoRA model first.

pipe = DiffusionPipeline.from_pretrained(
    "stabilityai/stable-diffusion-xl-base-1.0",
    torch_dtype=torch.float16,
    variant="fp16",
    use_safetensors=True,
)
pipe.load_lora_weights(
    "CiroN2022/toy-face", weight_name="toy_face_sdxl.safetensors", adapter_name="toy"
)
pipe.fuse_lora(lora_scale=0.9)
mto.restore(pipe.unet, your_quantized_ckpt)
...
# Export the onnx model

By following these steps, your PEFT LoRA model should be efficiently quantized using ModelOpt, ready for deployment while maximizing performance.

Sparse Attention (Skip-Softmax)

Skip-softmax sparse attention skips KV tiles whose attention scores are negligible during the softmax computation, reducing FLOPs without retraining. An exponential model (scale_factor = a * exp(b * target_sparsity)) is calibrated once, then the target sparsity can be adjusted at runtime without recalibration. Calibrated coefficients can be exported as a Hugging Face checkpoint (embedded in each component's config.json under sparse_attention_config) in the schema TRT-LLM VisualGen loads (threshold_scale_factor.coefficients plus a scalar target_sparsity) — no extra conversion needed downstream.

Getting Started

import modelopt.torch.sparsity as mts

# 1. Define config with calibration
config = {
    "sparse_cfg": {
        "calibration": {
            "target_sparse_ratio": {"prefill": 0.5},
        },
        "*.attn1": {
            "method": "triton_skip_softmax",
            "backend": "triton",
            "is_causal": False,
            "collect_stats": True,
            "enable": True,
        },
        "*.attn2": {"enable": False},
        "default": {"enable": False},
    },
}

# 2. Provide a calibration forward loop
def forward_loop(model):
    pipeline(prompt="a cat", num_frames=81, num_inference_steps=40, ...)

# 3. Sparsify + calibrate
mts.sparsify(transformer, config, forward_loop=forward_loop)

# 4. Generate as usual — sparsity is applied automatically
output = pipeline(prompt="a dog on the beach", ...)

Example Scripts

Wan 2.2 Script

The 14B model automatically sparsifies both transformer and transformer_2.


# 5B/14B model — calibrate and export a TRT-LLM-ready checkpoint
python sparsity/wan22_skip_softmax.py \
    --model-path Wan-AI/Wan2.2-T2V-A14B-Diffusers|Wan-AI/Wan2.2-TI2V-5B-Diffusers \
    --calibrate --target-sparsity 0.5 --calib-size 4 \
    --export-dir /path/to/wan22-skip-softmax-ckpt \
    --prompt "A sunset over mountains" --output out.mp4

Cache Diffusion

Cache Diffusion methods, such as DeepCache, Block Caching and T-Gate, optimize performance by reusing cached outputs from previous steps instead of recalculating them. This training-free caching approach is compatible with a variety of models, like DiT and UNet, enabling considerable acceleration without compromising quality.

SDXL Cache This diagram shows the default SDXL Cache compute graph in this example. Significant speedup is achieve through skipping certain blocks at the specific steps.

Getting Started

With the simple API below, you can very easily use Model Optimizer to apply cache diffusion to your model. Model Optimizer achieves this by breaking down different blocks into a single TensorRT engine, and at inference time, we combine multiple TensorRT engines in the same way a PyTorch module would..

import torch
from cache_diffusion import cachify
from cache_diffusion.utils import SDXL_DEFAULT_CONFIG
from diffusers import DiffusionPipeline

pipe = DiffusionPipeline.from_pretrained(
    "stabilityai/stable-diffusion-xl-base-1.0",
    torch_dtype=torch.float16,
    variant="fp16",
    use_safetensors=True,
)
pipe = pipe.to("cuda")

num_inference_steps = 20
prompt = "beautiful lady, (freckles), big smile, blue eyes, short hair, dark makeup, hyperdetailed photography, soft light, head and shoulders portrait, cover"

cachify.prepare(pipe, SDXL_DEFAULT_CONFIG)
cachify.enable(pipe)

generator = torch.Generator(device="cuda").manual_seed(2946901)

with cachify.infer(pipe) as cached_pipe:
    img = cached_pipe(
        prompt=prompt, num_inference_steps=num_inference_steps, generator=generator
    ).images[0]

img

PyTorch Framework

Please refer to example.ipynb for more details on how to apply cache diffusion.

TensorRT Compiler Framework

Warning

The ONNX/TensorRT deployment instructions below are part of the deprecated workflow (0.48.0; removal no earlier than 0.49.0). PyTorch Cache Diffusion remains supported.

During the migration period, the legacy TensorRT instructions remain available:

# Load the model

compile(
    pipe.unet,
    model_id="sdxl",
    onnx_path=Path("./onnx"),
    engine_path=Path("./engine"),
)

cachify.prepare(pipe, SDXL_DEFAULT_CONFIG)

Afterward, use it as a standard cache diffusion pipeline to generate the image.

Please note that only the UNET component is running in TensorRT, while the other parts remain in PyTorch.

Customize

Model Optimizer also provides an API to create various compute graphs by simply adjusting the parameters. For instance, the default parameter for SDXL is:

SDXL_DEFAULT_CONFIG = [
    {
        "wildcard_or_filter_func": lambda name: "up_blocks.2" not in name,
        "select_cache_step_func": lambda step: (step % 2) != 0,
    }
]

cachify.prepare(pipe, SDXL_DEFAULT_CONFIG)

Two parameters are essential: wildcard_or_filter_func and select_cache_step_func.

wildcard_or_filter_func: This can be a str or a function. If the module matches the given str or filter_func, then it will perform the cache operation. For example, if your input is a string *up_blocks*, it will match all names containing up_blocks and will perform the cache operation in the future, as you use fnmatch to match the string. If you use a function instead, the module name will be passed into the function you provided, and if the function returns True, then it will perform the cache operation.

select_cache_step_func: During inference, code will check at each step to see if you want to perform the cache operation based on the select_cache_step_func you provided. If select_cache_step_func(current_step) returns True, the module will cached; otherwise, it won't.

Multiple configurations can be set up, but ensure that the wildcard_or_filter_func works correctly. If you input more than one pair of parameters with the same wildcard_or_filter_func, the later one in the list will overwrite the previous ones.

Demo

The following demo images are generated using torch==2.3.0 with a single RTX 6000 Ada GPU.

Comparing with naively reducing the generation steps, cache diffusion can achieve the same speedup and also much better image quality, even close to the reference image. If the image quality does not meet your needs or product requirements, you can replace our default configuration with your customized settings.

Stable Diffusion - XL

SDXL Cache Diffusion

Notes About Randomness

Stable Diffusion pipelines rely heavily on random sampling operations, which include creating Gaussian noise tensors to denoise and adding noise in the scheduling step. In the quantization recipe, we don't fix the random seed. As a result, every time you run the calibration pipeline, you could get different quantizer amax values. This may lead to the generated images being different from the ones generated with the original model. We suggest to run a few more times and choose the best one.

Pre-Quantized Checkpoints

Resources