mirror of
https://github.com/NVIDIA/Model-Optimizer.git
synced 2026-10-31 07:43:00 +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>
196 lines
7.9 KiB
Python
196 lines
7.9 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 logging
|
|
from pathlib import Path
|
|
from typing import Any
|
|
|
|
from models_utils import MODEL_DEFAULTS, ModelType
|
|
from pipeline_manager import PipelineManager
|
|
from quantize_config import CalibrationConfig
|
|
from tqdm import tqdm
|
|
from utils import load_calib_prompts
|
|
|
|
|
|
class Calibrator:
|
|
"""Handles model calibration for quantization."""
|
|
|
|
def __init__(
|
|
self,
|
|
pipeline_manager: PipelineManager,
|
|
config: CalibrationConfig,
|
|
model_type: ModelType,
|
|
logger: logging.Logger,
|
|
):
|
|
"""
|
|
Initialize calibrator.
|
|
|
|
Args:
|
|
pipeline_manager: Pipeline manager with main and upsampler pipelines
|
|
config: Calibration configuration
|
|
model_type: Type of model being calibrated
|
|
logger: Logger instance
|
|
"""
|
|
self.pipeline_manager = pipeline_manager
|
|
self.pipe = pipeline_manager.pipe
|
|
self.pipe_upsample = pipeline_manager.pipe_upsample
|
|
self.config = config
|
|
self.model_type = model_type
|
|
self.logger = logger
|
|
|
|
def load_and_batch_prompts(self) -> list[list[str]]:
|
|
"""
|
|
Load calibration prompts from file.
|
|
|
|
Returns:
|
|
List of batched calibration prompts
|
|
"""
|
|
self.logger.info(f"Loading calibration prompts from {self.config.prompts_dataset}")
|
|
if isinstance(self.config.prompts_dataset, Path):
|
|
return load_calib_prompts(
|
|
self.config.batch_size,
|
|
self.config.prompts_dataset,
|
|
)
|
|
|
|
return load_calib_prompts(
|
|
self.config.batch_size,
|
|
self.config.prompts_dataset["name"],
|
|
self.config.prompts_dataset["split"],
|
|
self.config.prompts_dataset["column"],
|
|
)
|
|
|
|
def run_calibration(self, batched_prompts: list[list[str]]) -> None:
|
|
"""
|
|
Run calibration steps on the pipeline.
|
|
|
|
Args:
|
|
batched_prompts: List of batched calibration prompts
|
|
"""
|
|
self.logger.info(f"Starting calibration with {self.config.num_batches} batches")
|
|
extra_args = MODEL_DEFAULTS.get(self.model_type, {}).get("inference_extra_args", {})
|
|
|
|
with tqdm(total=self.config.num_batches, desc="Calibration", unit="batch") as pbar:
|
|
for i, prompt_batch in enumerate(batched_prompts):
|
|
if i >= self.config.num_batches:
|
|
break
|
|
|
|
if self.model_type == ModelType.LTX2:
|
|
self._run_ltx2_calibration(prompt_batch, extra_args)
|
|
elif self.model_type == ModelType.LTX_VIDEO_DEV:
|
|
# Special handling for LTX-Video
|
|
self._run_ltx_video_calibration(prompt_batch, extra_args)
|
|
elif self.model_type in [ModelType.WAN22_T2V_14b, ModelType.WAN22_T2V_5b]:
|
|
# Special handling for WAN video models
|
|
self._run_wan_video_calibration(prompt_batch, extra_args)
|
|
else:
|
|
common_args = {
|
|
"prompt": prompt_batch,
|
|
"num_inference_steps": self.config.n_steps,
|
|
}
|
|
self.pipe(**common_args, **extra_args).images
|
|
pbar.update(1)
|
|
self.logger.debug(f"Completed calibration batch {i + 1}/{self.config.num_batches}")
|
|
self.logger.info("Calibration completed successfully")
|
|
|
|
def _run_wan_video_calibration(
|
|
self, prompt_batch: list[str], extra_args: dict[str, Any]
|
|
) -> None:
|
|
kwargs = {}
|
|
kwargs["negative_prompt"] = extra_args["negative_prompt"]
|
|
kwargs["height"] = extra_args["height"]
|
|
kwargs["width"] = extra_args["width"]
|
|
kwargs["num_frames"] = extra_args["num_frames"]
|
|
kwargs["guidance_scale"] = extra_args["guidance_scale"]
|
|
if "guidance_scale_2" in extra_args:
|
|
kwargs["guidance_scale_2"] = extra_args["guidance_scale_2"]
|
|
kwargs["num_inference_steps"] = self.config.n_steps
|
|
|
|
self.pipe(prompt=prompt_batch, **kwargs).frames
|
|
|
|
def _run_ltx2_calibration(self, prompt_batch: list[str], extra_args: dict[str, Any]) -> None:
|
|
from ltx_core.model.video_vae import TilingConfig
|
|
|
|
prompt = prompt_batch[0]
|
|
extra_params = self.pipeline_manager.config.extra_params
|
|
kwargs = {
|
|
"negative_prompt": extra_args.get(
|
|
"negative_prompt", "worst quality, inconsistent motion, blurry, jittery, distorted"
|
|
),
|
|
"seed": extra_params.get("seed", 0),
|
|
"height": extra_params.get("height", extra_args.get("height", 1024)),
|
|
"width": extra_params.get("width", extra_args.get("width", 1536)),
|
|
"num_frames": extra_params.get("num_frames", extra_args.get("num_frames", 121)),
|
|
"frame_rate": extra_params.get("frame_rate", extra_args.get("frame_rate", 24.0)),
|
|
"num_inference_steps": self.config.n_steps,
|
|
"cfg_guidance_scale": extra_params.get(
|
|
"cfg_guidance_scale", extra_args.get("cfg_guidance_scale", 4.0)
|
|
),
|
|
"images": extra_params.get("images", []),
|
|
"tiling_config": extra_params.get("tiling_config", TilingConfig.default()),
|
|
}
|
|
self.pipe(prompt=prompt, **kwargs)
|
|
|
|
def _run_ltx_video_calibration(
|
|
self, prompt_batch: list[str], extra_args: dict[str, Any]
|
|
) -> None:
|
|
"""
|
|
Run calibration for LTX-Video model using the full multi-stage pipeline.
|
|
|
|
Args:
|
|
prompt_batch: Batch of prompts
|
|
extra_args: Model-specific arguments
|
|
"""
|
|
# Extract specific args for LTX-Video
|
|
expected_height = extra_args.get("height", 512)
|
|
expected_width = extra_args.get("width", 704)
|
|
num_frames = extra_args.get("num_frames", 121)
|
|
negative_prompt = extra_args.get(
|
|
"negative_prompt", "worst quality, inconsistent motion, blurry, jittery, distorted"
|
|
)
|
|
|
|
def round_to_nearest_resolution_acceptable_by_vae(height, width):
|
|
height = height - (height % self.pipe.vae_spatial_compression_ratio)
|
|
width = width - (width % self.pipe.vae_spatial_compression_ratio)
|
|
return height, width
|
|
|
|
downscale_factor = 2 / 3
|
|
# Part 1: Generate video at smaller resolution
|
|
downscaled_height, downscaled_width = (
|
|
int(expected_height * downscale_factor),
|
|
int(expected_width * downscale_factor),
|
|
)
|
|
downscaled_height, downscaled_width = round_to_nearest_resolution_acceptable_by_vae(
|
|
downscaled_height, downscaled_width
|
|
)
|
|
|
|
# Generate initial latents at lower resolution
|
|
latents = self.pipe(
|
|
conditions=None,
|
|
prompt=prompt_batch,
|
|
negative_prompt=negative_prompt,
|
|
width=downscaled_width,
|
|
height=downscaled_height,
|
|
num_frames=num_frames,
|
|
num_inference_steps=self.config.n_steps,
|
|
output_type="latent",
|
|
).frames
|
|
|
|
# Part 2: Upscale generated video using latent upsampler (if available)
|
|
if self.pipe_upsample is not None:
|
|
_ = self.pipe_upsample(latents=latents, output_type="latent").frames
|
|
|
|
# Part 3: Denoise the upscaled video with few steps to improve texture
|
|
# However, in this example code, we will omit the upscale step since its optional.
|