mirror of
https://github.com/NVIDIA/Model-Optimizer.git
synced 2026-11-10 09:34:01 +08:00
## What does this PR do?
**Type of change:** new example <!-- Use one of the following: Bug fix,
new feature, new example, new tests, documentation. -->
**Overview:**
- Register Flux2Attention and Flux2ParallelSelfAttention in the
quantization plugin so bmm quantizers are patched (enables
--quantize-mha).
- Add Flux2-specific dummy input generation for HF checkpoint export.
- Guard check_conv_and_mha with hasattr for bmm quantizer attributes
## Usage
<!-- You can potentially add a usage example below. -->
```bash
python quantize.py \
--model flux2-dev \
--model-dtype BFloat16 \
--format fp4 --batch-size 2 --calib-size 1 \
--n-steps 20 --quantized-torch-ckpt-save-path ./flux2-dev-fp4.pt --collect-method default \
--hf-ckpt-dir ./flux2-dev-fp4
```
## 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
* **New Features**
* Added Flux2-dev model support with Flux2-compatible dummy input
generation and default inference params (768×1024, guidance scale 4.0).
* **Refactor**
* Made attention quantization disabling more robust by iterating
available quantizers before disabling.
* **Infrastructure**
* Flux2 attention components are now optional and registered only when
present to avoid import issues.
* **Tests**
* Added Flux2 test helpers and coverage validating Flux2 dummy input
shapes.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
---------
Signed-off-by: Jingyu Xin <jingyux@nvidia.com>
160 lines
5.1 KiB
Python
160 lines
5.1 KiB
Python
# SPDX-FileCopyrightText: Copyright (c) 2023-2025 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 pathlib import Path
|
|
|
|
import pytest
|
|
import torch
|
|
|
|
pytest.importorskip("diffusers")
|
|
from diffusers import UNet2DConditionModel
|
|
|
|
try:
|
|
from diffusers.models.transformers import DiTTransformer2DModel, FluxTransformer2DModel
|
|
except Exception: # pragma: no cover - optional diffusers models
|
|
DiTTransformer2DModel = None
|
|
FluxTransformer2DModel = None
|
|
|
|
try:
|
|
from diffusers.models.transformers import Flux2Transformer2DModel
|
|
except Exception: # pragma: no cover - optional diffusers models
|
|
Flux2Transformer2DModel = None
|
|
|
|
import modelopt.torch.opt as mto
|
|
|
|
|
|
def get_tiny_unet(**config_kwargs) -> UNet2DConditionModel:
|
|
"""Create a tiny UNet2DConditionModel for testing."""
|
|
kwargs = {
|
|
"sample_size": 8,
|
|
"in_channels": 2,
|
|
"out_channels": 2,
|
|
"down_block_types": ("DownBlock2D",),
|
|
"up_block_types": ("UpBlock2D",),
|
|
"block_out_channels": (2,),
|
|
"layers_per_block": 1,
|
|
"cross_attention_dim": 2,
|
|
"attention_head_dim": 1,
|
|
"norm_num_groups": 1,
|
|
"mid_block_type": None,
|
|
}
|
|
kwargs.update(**config_kwargs)
|
|
tiny_unet = UNet2DConditionModel(**kwargs)
|
|
|
|
return tiny_unet
|
|
|
|
|
|
def get_tiny_dit(**config_kwargs):
|
|
"""Create a tiny DiTTransformer2DModel for testing."""
|
|
if DiTTransformer2DModel is None:
|
|
pytest.skip("DiTTransformer2DModel is not available in this diffusers version.")
|
|
|
|
kwargs = {
|
|
"num_attention_heads": 2,
|
|
"attention_head_dim": 8,
|
|
"in_channels": 2,
|
|
"out_channels": 2,
|
|
"num_layers": 1,
|
|
"norm_num_groups": 1,
|
|
"sample_size": 8,
|
|
"patch_size": 2,
|
|
"num_embeds_ada_norm": 10,
|
|
}
|
|
kwargs.update(**config_kwargs)
|
|
return DiTTransformer2DModel(**kwargs)
|
|
|
|
|
|
def get_tiny_flux(**config_kwargs):
|
|
"""Create a tiny FluxTransformer2DModel for testing."""
|
|
if FluxTransformer2DModel is None:
|
|
pytest.skip("FluxTransformer2DModel is not available in this diffusers version.")
|
|
|
|
kwargs = {
|
|
"patch_size": 1,
|
|
"in_channels": 4,
|
|
"out_channels": 4,
|
|
"num_layers": 1,
|
|
"num_single_layers": 1,
|
|
"attention_head_dim": 8,
|
|
"num_attention_heads": 2,
|
|
"joint_attention_dim": 8,
|
|
"pooled_projection_dim": 8,
|
|
"guidance_embeds": False,
|
|
"axes_dims_rope": (2, 2, 4),
|
|
}
|
|
kwargs.update(**config_kwargs)
|
|
return FluxTransformer2DModel(**kwargs)
|
|
|
|
|
|
def get_tiny_flux2(**config_kwargs):
|
|
"""Create a tiny Flux2Transformer2DModel for testing."""
|
|
if Flux2Transformer2DModel is None:
|
|
pytest.skip("Flux2Transformer2DModel is not available in this diffusers version.")
|
|
|
|
kwargs = {
|
|
"patch_size": 1,
|
|
"in_channels": 16,
|
|
"num_layers": 1,
|
|
"num_single_layers": 1,
|
|
"attention_head_dim": 16,
|
|
"num_attention_heads": 2,
|
|
"joint_attention_dim": 32,
|
|
"timestep_guidance_channels": 16,
|
|
"mlp_ratio": 3.0,
|
|
"axes_dims_rope": (4, 4, 4, 4),
|
|
}
|
|
kwargs.update(**config_kwargs)
|
|
return Flux2Transformer2DModel(**kwargs)
|
|
|
|
|
|
def create_tiny_unet_dir(tmp_path: Path, **config_kwargs) -> Path:
|
|
"""Create and save a tiny UNet model to a directory."""
|
|
tiny_unet = get_tiny_unet(**config_kwargs)
|
|
tiny_unet.save_pretrained(tmp_path / "tiny_unet")
|
|
return tmp_path / "tiny_unet"
|
|
|
|
|
|
def get_unet_dummy_inputs(model: UNet2DConditionModel, batch_size: int = 1):
|
|
"""Generate dummy inputs for testing UNet models."""
|
|
latents = torch.randn(
|
|
batch_size, model.config.in_channels, model.config.sample_size, model.config.sample_size
|
|
)
|
|
timestep = torch.tensor([0])
|
|
encoder_hidden_states = torch.randn(batch_size, 1, model.config.cross_attention_dim)
|
|
|
|
return {"sample": latents, "timestep": timestep, "encoder_hidden_states": encoder_hidden_states}
|
|
|
|
|
|
def df_output_tester(model_ref, model_test):
|
|
"""Test if two diffusers models produce the same output."""
|
|
inputs = get_unet_dummy_inputs(model_ref)
|
|
model_ref.eval()
|
|
model_test.eval()
|
|
|
|
with torch.no_grad():
|
|
output_ref = model_ref(**inputs).sample
|
|
output_test = model_test(**inputs).sample
|
|
|
|
assert torch.allclose(output_ref, output_test)
|
|
|
|
|
|
def df_modelopt_state_and_output_tester(model_ref, model_test):
|
|
"""Test if two diffusers models have the same modelopt state and outputs."""
|
|
model_ref_state = mto.modelopt_state(model_ref)
|
|
model_test_state = mto.modelopt_state(model_test)
|
|
assert model_ref_state == model_test_state
|
|
|
|
df_output_tester(model_ref, model_test)
|