mirror of
https://github.com/NVIDIA/Model-Optimizer.git
synced 2026-10-21 06:10:05 +08:00
## What does this PR do?
**Type of change:** documentation <!-- Use one of the following: Bug
fix, new feature, new example, new tests, documentation. -->
**Overview:**
1. Added multi‑backbone support for quantization: --backbone now accepts
space- or comma-separated lists and resolves to a list of backbone
modules.
2. Introduced PipelineManager.iter_backbones() to iterate named backbone
modules and updated get_backbone() to return a single module or a
ModuleList for multi‑backbone.
3. Updated ExportManager to save/restore per‑backbone checkpoints when a
directory is provided, with {backbone_name}.pt files, and to create
target directories when missing.
4. Simplified save_checkpoint() calls to rely on the registered
pipeline_manager by default.
**Usage: **
```bash
python quantize.py --model wan2.2-t2v-14b --format fp4 --batch-size 1 --calib-size 32 \
--n-steps 30 --backbone transformer transformer_2 --model-dtype BFloat16 \
--quantized-torch-ckpt-save-path ./wan22_mo_ckpts \
--hf-ckpt-dir ./wan2.2-t2v-14b
```
Plans
- [x] [1/4] Add the basic functionalities to support limited image
models with NVFP4 + FP8, with some refactoring on the previous LLM code
and the diffusers example. PIC: @jingyu-ml
- [x] [2/4] Add support to more video gen models. PIC: @jingyu-ml
- [x] [3/4] Add test cases, refactor on the doc, and all related README.
PIC: @jingyu-ml
- [ ] [4/4] Add the final support to ComfyUI. PIC @jingyu-ml
## Testing
<!-- Mention how have you tested your change if applicable. -->
## Before your PR is "*Ready for review*"
<!-- If you haven't finished some of the above items you can still open
`Draft` PR. -->
- **Make sure you read and follow [Contributor
guidelines](https://github.com/NVIDIA/Model-Optimizer/blob/main/CONTRIBUTING.md)**
and your commits are signed.
- **Is this change backward compatible?**: No <!--- If No, explain why.
-->
- **Did you write any new necessary tests?**:No
- **Did you add or update any necessary documentation?**: Yes
- **Did you update
[Changelog](https://github.com/NVIDIA/Model-Optimizer/blob/main/CHANGELOG.rst)?**:
Yes <!--- Only for new features, API changes, critical bug fixes or bw
breaking changes. -->
## Additional Information
<!-- E.g. related issue. -->
<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit
## Release Notes
* **New Features**
* Unified Hugging Face export support for diffusers pipelines and
components
* LTX-2 and Wan2.2 (T2V) support in diffusers quantization workflow
* Comprehensive ONNX export and TensorRT engine build documentation for
diffusion models
* **Documentation**
* Updated to clarify support for both transformers and diffusers models
in unified export API
* Expanded diffusers examples with LoRA fusion guidance and additional
model options (Flux, SD3, SDXL variants)
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
---------
Signed-off-by: Jingyu Xin <jingyux@nvidia.com>
165 lines
5.3 KiB
Python
165 lines
5.3 KiB
Python
# SPDX-FileCopyrightText: Copyright (c) 2024 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
|
|
# SPDX-License-Identifier: Apache-2.0
|
|
#
|
|
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
# you may not use this file except in compliance with the License.
|
|
# You may obtain a copy of the License at
|
|
#
|
|
# http://www.apache.org/licenses/LICENSE-2.0
|
|
#
|
|
# Unless required by applicable law or agreed to in writing, software
|
|
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
# See the License for the specific language governing permissions and
|
|
# limitations under the License.
|
|
|
|
import torch.nn as nn
|
|
from calib.plugin_calib import PercentileCalibrator
|
|
|
|
FP8_DEFAULT_CONFIG = {
|
|
"quant_cfg": {
|
|
"*weight_quantizer": {"num_bits": (4, 3), "axis": None},
|
|
"*input_quantizer": {"num_bits": (4, 3), "axis": None},
|
|
"*output_quantizer": {"enable": False},
|
|
"*softmax_quantizer": {
|
|
"num_bits": (4, 3),
|
|
"axis": None,
|
|
},
|
|
"default": {"enable": False},
|
|
},
|
|
"algorithm": "max",
|
|
}
|
|
|
|
INT8_DEFAULT_CONFIG = {
|
|
"quant_cfg": {
|
|
"*weight_quantizer": {"num_bits": 8, "axis": 0},
|
|
"*input_quantizer": {"num_bits": 8, "axis": 0},
|
|
"*output_quantizer": {"enable": False},
|
|
"default": {"enable": False},
|
|
},
|
|
"algorithm": "max",
|
|
}
|
|
|
|
NVFP4_DEFAULT_CONFIG = {
|
|
"quant_cfg": {
|
|
"*weight_quantizer": {
|
|
"num_bits": (2, 1),
|
|
"block_sizes": {-1: 16, "type": "dynamic", "scale_bits": (4, 3)},
|
|
"axis": None,
|
|
"enable": True,
|
|
},
|
|
"*input_quantizer": {
|
|
"num_bits": (2, 1),
|
|
"block_sizes": {-1: 16, "type": "dynamic", "scale_bits": (4, 3)},
|
|
"axis": None,
|
|
"enable": True,
|
|
},
|
|
"*output_quantizer": {"enable": False},
|
|
"*softmax_quantizer": {
|
|
"num_bits": (4, 3),
|
|
"axis": None,
|
|
},
|
|
"default": {"enable": False},
|
|
},
|
|
"algorithm": "max",
|
|
}
|
|
|
|
NVFP4_FP8_MHA_CONFIG = {
|
|
"quant_cfg": {
|
|
"**weight_quantizer": {
|
|
"num_bits": (2, 1),
|
|
"block_sizes": {-1: 16, "type": "dynamic", "scale_bits": (4, 3)},
|
|
"axis": None,
|
|
"enable": True,
|
|
},
|
|
"**input_quantizer": {
|
|
"num_bits": (2, 1),
|
|
"block_sizes": {-1: 16, "type": "dynamic", "scale_bits": (4, 3)},
|
|
"axis": None,
|
|
"enable": True,
|
|
},
|
|
"*output_quantizer": {"enable": False},
|
|
"*[qkv]_bmm_quantizer": {
|
|
"num_bits": (4, 3),
|
|
"axis": None,
|
|
},
|
|
"*softmax_quantizer": {
|
|
"num_bits": (4, 3),
|
|
"axis": None,
|
|
},
|
|
"*bmm2_output_quantizer": {
|
|
"num_bits": (4, 3),
|
|
"axis": None,
|
|
},
|
|
"default": {"enable": False},
|
|
},
|
|
"algorithm": {"method": "svdquant", "lowrank": 32},
|
|
}
|
|
|
|
|
|
def set_quant_config_attr(quant_config, trt_high_precision_dtype, quant_algo, **kwargs):
|
|
algo_cfg = {"method": quant_algo}
|
|
|
|
if quant_algo == "smoothquant" and "alpha" in kwargs:
|
|
algo_cfg["alpha"] = kwargs["alpha"]
|
|
elif quant_algo == "svdquant" and "lowrank" in kwargs:
|
|
algo_cfg["lowrank"] = kwargs["lowrank"]
|
|
quant_config["algorithm"] = algo_cfg
|
|
|
|
for p in quant_config["quant_cfg"].values():
|
|
if "num_bits" in p and "trt_high_precision_dtype" not in p:
|
|
p["trt_high_precision_dtype"] = trt_high_precision_dtype
|
|
|
|
|
|
def reset_set_int8_config(quant_config, percentile, n_steps, collect_method, backbone):
|
|
"""
|
|
Configure INT8 quantization with different settings for Conv2d and Linear layers.
|
|
|
|
Args:
|
|
quant_config: The quantization configuration dictionary
|
|
percentile: Percentile value for calibration
|
|
n_steps: Number of calibration steps
|
|
collect_method: Method for collecting calibration statistics
|
|
backbone: The model backbone to analyze layer types
|
|
"""
|
|
|
|
# Build a mapping of layer names to their types
|
|
layer_type_map = {}
|
|
for name, module in backbone.named_modules():
|
|
if isinstance(module, (nn.Linear, nn.Conv2d)):
|
|
layer_type_map[name] = type(module)
|
|
|
|
quant_config["quant_cfg"] = {}
|
|
for layer_name, layer_type in layer_type_map.items():
|
|
wq_name = f"*{layer_name}*weight_quantizer*"
|
|
aq_name = f"*{layer_name}*input_quantizer*"
|
|
if layer_type is nn.Linear:
|
|
quant_config["quant_cfg"][wq_name] = {
|
|
"num_bits": 8,
|
|
"axis": 0,
|
|
}
|
|
quant_config["quant_cfg"][aq_name] = {
|
|
"num_bits": 8,
|
|
"axis": -1,
|
|
}
|
|
else:
|
|
quant_config["quant_cfg"][wq_name] = {
|
|
"num_bits": 8,
|
|
"axis": 0,
|
|
}
|
|
quant_config["quant_cfg"][aq_name] = {
|
|
"num_bits": 8,
|
|
"axis": None,
|
|
"calibrator": (
|
|
PercentileCalibrator,
|
|
(),
|
|
{
|
|
"num_bits": 8,
|
|
"axis": None,
|
|
"percentile": percentile,
|
|
"total_step": n_steps,
|
|
"collect_method": collect_method,
|
|
},
|
|
),
|
|
}
|