mirror of
https://github.com/NVIDIA/Model-Optimizer.git
synced 2026-10-17 05:29:39 +08:00
## What does this PR do? **Type of change:** New feature <!-- Use one of the following: Bug fix, new feature, new example, new tests, documentation. --> **Overview:** This MR adds HuggingFace checkpoint export support for LTX‑2 by treating TI2VidTwoStagesPipeline as a diffusion-like pipeline, exporting only the stage‑1 transformer (with QKV-fusion-enabled dummy inputs) and falling back to writing model.safetensors when save_pretrained isn’t available. It also preserves the original forward in DynamicModule patching (_forward_pre_dm) so downstream callers can still invoke the pre-patched forward implementation. **Changes** 1. Added the calibration & quantization support of the LTX2, even with FP8 precision. 2. Preserve original forward before `DynamicModule` patching: when patching forward, we now stash the pre-patched implementation in `self._forward_pre_dm` (once) so downstream code can still call the original forward, then re-bind forward to the class implementation. This is needed for the LTX2 FP8 calibration. 3. Added LTX‑2 HF export path: `export_hf_checkpoint()` now also treats ltx_pipelines.ti2vid_two_stages.TI2VidTwoStagesPipeline as a “diffusion-like” object and routes it through _export_diffusers_checkpoint() (import guarded; no hard dependency). 4. Generalized component discovery: introduced get_diffusion_components() (aliasing the old get_diffusers_components) to support non-diffusers pipelines; for LTX‑2 it returns only stage_1_transformer. 5. Enabled QKV fusion for LTX‑2 backbone: added a model-aware dummy forward generator (generate_diffusion_dummy_forward_fn) that builds minimal LTX Modality inputs (including correct timesteps broadcasting) so shared-input hooks can run and fuse QKV when applicable. 6. Export fallback for non-save_pretrained modules: when a component lacks save_pretrained (LTX‑2 transformer), export now writes model.safetensors + minimal config.json instead of pytorch_model.bin. 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 - [ ] [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 ## Usage <!-- You can potentially add a usage example below. --> ```bash python quantize.py --model ltx-2 --format fp4 --batch-size 64 --calib-size 1 --n-steps 40 --extra-param checkpoint_path=/home/scratch.omniml_data_2/jingyux/models/LTX-2/ltx-2-19b-dev-fp8.safetensors --extra-param distilled_lora_path=/home/scratch.omniml_data_2/jingyux/models/LTX-2/ltx-2-19b-distilled-lora-384.safetensors --extra-param spatial_upsampler_path=/home/scratch.omniml_data_2/jingyux/models/LTX-2/ltx-2-spatial-upscaler-x2-1.0.safetensors --extra-param gemma_root=/home/scratch.omniml_data_2/jingyux/models/LTX-2/gemma-3-12b-it-qat-q4_0-unquantized --extra-param fp8transformer=true --hf-ckpt-dir ./ltx2-nvfp4 ``` ## 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?**: Yes <!--- If No, explain why. --> - **Did you write any new necessary tests?**:No - **Did you add or update any necessary documentation?**:No - **Did you update [Changelog](https://github.com/NVIDIA/Model-Optimizer/blob/main/CHANGELOG.rst)?**:No <!--- 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** * Added LTX-2 video model support with complete quantization and export pipeline integration * Introduced `--extra-param` CLI option for flexible model configuration and parameter passing * Enhanced export capabilities with broader diffusion model compatibility * **Chores** * Changed default model data type from Half to BFloat16 for improved numerical stability <sub>✏️ Tip: You can customize this high-level summary in your review settings.</sub> <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Signed-off-by: Jingyu Xin <jingyux@nvidia.com>
161 lines
5.0 KiB
Python
161 lines
5.0 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.
|
|
from dataclasses import dataclass, field
|
|
from enum import Enum
|
|
from pathlib import Path
|
|
from typing import Any
|
|
|
|
import torch
|
|
from models_utils import MODEL_REGISTRY, ModelType
|
|
|
|
|
|
class DataType(str, Enum):
|
|
"""Supported data types for model loading."""
|
|
|
|
HALF = "Half"
|
|
BFLOAT16 = "BFloat16"
|
|
FLOAT = "Float"
|
|
|
|
@property
|
|
def torch_dtype(self) -> torch.dtype:
|
|
return self._dtype_map[self.value]
|
|
|
|
|
|
DataType._dtype_map = {
|
|
DataType.HALF: torch.float16,
|
|
DataType.BFLOAT16: torch.bfloat16,
|
|
DataType.FLOAT: torch.float32,
|
|
}
|
|
|
|
|
|
class QuantFormat(str, Enum):
|
|
"""Supported quantization formats."""
|
|
|
|
INT8 = "int8"
|
|
FP8 = "fp8"
|
|
FP4 = "fp4"
|
|
|
|
|
|
class QuantAlgo(str, Enum):
|
|
"""Supported quantization algorithms."""
|
|
|
|
MAX = "max"
|
|
SVDQUANT = "svdquant"
|
|
SMOOTHQUANT = "smoothquant"
|
|
|
|
|
|
class CollectMethod(str, Enum):
|
|
"""Calibration collection methods."""
|
|
|
|
GLOBAL_MIN = "global_min"
|
|
MIN_MAX = "min-max"
|
|
MIN_MEAN = "min-mean"
|
|
MEAN_MAX = "mean-max"
|
|
DEFAULT = "default"
|
|
|
|
|
|
@dataclass
|
|
class QuantizationConfig:
|
|
"""Configuration for model quantization."""
|
|
|
|
format: QuantFormat = QuantFormat.INT8
|
|
algo: QuantAlgo = QuantAlgo.MAX
|
|
percentile: float = 1.0
|
|
collect_method: CollectMethod = CollectMethod.DEFAULT
|
|
alpha: float = 1.0 # SmoothQuant alpha
|
|
lowrank: int = 32 # SVDQuant lowrank
|
|
quantize_mha: bool = False
|
|
compress: bool = False
|
|
|
|
def validate(self) -> None:
|
|
"""Validate configuration consistency."""
|
|
if self.format == QuantFormat.FP8 and self.collect_method != CollectMethod.DEFAULT:
|
|
raise NotImplementedError("Only 'default' collect method is implemented for FP8.")
|
|
if self.quantize_mha and self.format == QuantFormat.INT8:
|
|
raise ValueError("MHA quantization is only supported for FP8, not INT8.")
|
|
if self.compress and self.format == QuantFormat.INT8:
|
|
raise ValueError("Compression is only supported for FP8 and FP4, not INT8.")
|
|
|
|
|
|
@dataclass
|
|
class CalibrationConfig:
|
|
"""Configuration for calibration process."""
|
|
|
|
prompts_dataset: dict | Path
|
|
batch_size: int = 2
|
|
calib_size: int = 128
|
|
n_steps: int = 30
|
|
|
|
def validate(self) -> None:
|
|
"""Validate calibration configuration."""
|
|
if self.batch_size <= 0:
|
|
raise ValueError("Batch size must be positive.")
|
|
if self.calib_size <= 0:
|
|
raise ValueError("Calibration size must be positive.")
|
|
if self.n_steps <= 0:
|
|
raise ValueError("Number of steps must be positive.")
|
|
|
|
@property
|
|
def num_batches(self) -> int:
|
|
"""Calculate number of calibration batches."""
|
|
return self.calib_size // self.batch_size
|
|
|
|
|
|
@dataclass
|
|
class ModelConfig:
|
|
"""Configuration for model loading and inference."""
|
|
|
|
model_type: ModelType = ModelType.FLUX_DEV
|
|
model_dtype: dict[str, torch.dtype] = field(default_factory=lambda: {"default": torch.float16})
|
|
backbone: str = ""
|
|
trt_high_precision_dtype: DataType = DataType.HALF
|
|
override_model_path: Path | None = None
|
|
cpu_offloading: bool = False
|
|
ltx_skip_upsampler: bool = False # Skip upsampler for LTX-Video (faster calibration)
|
|
extra_params: dict[str, Any] = field(default_factory=dict)
|
|
|
|
@property
|
|
def model_path(self) -> str:
|
|
"""Get the model path (override or default)."""
|
|
if self.override_model_path:
|
|
return str(self.override_model_path)
|
|
return MODEL_REGISTRY[self.model_type]
|
|
|
|
|
|
@dataclass
|
|
class ExportConfig:
|
|
"""Configuration for model export."""
|
|
|
|
quantized_torch_ckpt_path: Path | None = None
|
|
onnx_dir: Path | None = None
|
|
hf_ckpt_dir: Path | None = None
|
|
restore_from: Path | None = None
|
|
|
|
def validate(self) -> None:
|
|
"""Validate export configuration."""
|
|
if self.restore_from and not self.restore_from.exists():
|
|
raise FileNotFoundError(f"Restore checkpoint not found: {self.restore_from}")
|
|
|
|
if self.quantized_torch_ckpt_path:
|
|
parent_dir = self.quantized_torch_ckpt_path.parent
|
|
if not parent_dir.exists():
|
|
parent_dir.mkdir(parents=True, exist_ok=True)
|
|
|
|
if self.onnx_dir and not self.onnx_dir.exists():
|
|
self.onnx_dir.mkdir(parents=True, exist_ok=True)
|
|
|
|
if self.hf_ckpt_dir and not self.hf_ckpt_dir.exists():
|
|
self.hf_ckpt_dir.mkdir(parents=True, exist_ok=True)
|