Skip to content

PTQ-Level Efficiency, QAT-Level Accuracy | 训练后量化的效率,量化感知训练的精度

fix: preserve diffusion mixed dtypes during loading (#2232)

Wang, Chang7585f13c3356
diff --git a/auto_round/compressors/diffusion_mixin.py b/auto_round/compressors/diffusion_mixin.py
index edfd651a4..72cde7649 100644
--- a/auto_round/compressors/diffusion_mixin.py
+++ b/auto_round/compressors/diffusion_mixin.py
@@ -117,25 +117,31 @@ class DiffusionMixin:
pipe = getattr(self.model_context, "pipe", None)
model = getattr(self.model_context, "model", None)
- if pipe is not None and model is not None:
- is_nextstep = hasattr(model, "config") and getattr(model.config, "model_type", None) == "nextstep"
- if not is_nextstep:
- self._align_pipeline_dtype(pipe, model.dtype)
+ if (
+ getattr(self.model_context, "preloaded_diffusion_pipeline", False)
+ and pipe is not None
+ and model is not None
+ ):
+ self._align_pipeline_dtype(pipe, model.dtype)
@staticmethod
def _align_pipeline_dtype(pipe, target_dtype) -> None:
- """Align ordinary components while preserving declared FP32 modules."""
+ """Align a preloaded pipeline without casting declared FP32 tensors."""
+
for component_name in pipe.components:
component = getattr(pipe, component_name, None)
- if (
- not isinstance(component, torch.nn.Module)
- or not hasattr(component, "dtype")
- or component.dtype == target_dtype
- ):
+ if not isinstance(component, torch.nn.Module):
continue
- if getattr(component, "_keep_in_fp32_modules", None):
- continue
- component.to(dtype=target_dtype)
+
+ fp32_modules = getattr(component, "_keep_in_fp32_modules", None) or []
+ tensors = list(component.named_parameters()) + list(component.named_buffers())
+ for tensor_name, tensor in tensors:
+ if not tensor.is_floating_point():
+ continue
+ keep_in_fp32 = any(module_name in tensor_name for module_name in fp32_modules)
+ desired_dtype = torch.float32 if keep_in_fp32 else target_dtype
+ if tensor.dtype != desired_dtype:
+ tensor.data = tensor.data.to(dtype=desired_dtype)
def _get_calibrator_kind(self) -> str:
"""Select the diffusion calibration strategy.
@@ -165,16 +171,12 @@ class DiffusionMixin:
return result
def _align_device_and_dtype_for_secondary(self, transformer_name: str):
- """Align safe component dtypes and dispatch a secondary transformer."""
+ """Dispatch a secondary transformer without changing component dtypes."""
pipe = getattr(self.model_context, "pipe", None)
model = getattr(self.model_context, "model", None)
if pipe is None or model is None:
return
- is_nextstep = hasattr(model, "config") and getattr(model.config, "model_type", None) == "nextstep"
- if not is_nextstep:
- self._align_pipeline_dtype(pipe, model.dtype)
-
# Dispatch secondary transformer to GPU(s)
device_map = getattr(self.compress_context, "device_map", None)
device_list = getattr(self.compress_context, "device_list", [])
diff --git a/auto_round/context/model.py b/auto_round/context/model.py
index 6497721ac..63f62ba7e 100644
--- a/auto_round/context/model.py
+++ b/auto_round/context/model.py
@@ -89,6 +89,7 @@ class ModelContext(BaseContext):
self.processor = None
self.image_processor = None
self.pipe = None
+ self.preloaded_diffusion_pipeline = False
# AWQ weight-clip thresholds kept for downstream block quantizers.
# Populated by AWQTransform when ``apply_clip`` is enabled; keyed by
@@ -156,8 +157,16 @@ class ModelContext(BaseContext):
def _load_model(self):
if is_diffusion_model(self.model):
self.is_diffusion = True
+ self.preloaded_diffusion_pipeline = not isinstance(self.model, str)
+ default_torch_dtype = "auto"
+ if self.amp and get_ar_device(self.device).supports_bf16():
+ default_torch_dtype = torch.bfloat16
self.pipe, self.model = diffusion_load_model(
- self.model, platform=self.platform, device="cpu", model_dtype=self.model_dtype
+ self.model,
+ platform=self.platform,
+ device="cpu",
+ model_dtype=self.model_dtype,
+ default_torch_dtype=default_torch_dtype,
)
elif is_mllm_model(self.model, platform=self.platform):
self.is_mllm = True
diff --git a/auto_round/utils/model.py b/auto_round/utils/model.py
index 8901e52ef..6f738e2cd 100644
--- a/auto_round/utils/model.py
+++ b/auto_round/utils/model.py
@@ -873,6 +873,7 @@ def diffusion_load_model(
use_auto_mapping: bool = False,
trust_remote_code: bool = True,
model_dtype: str = None,
+ default_torch_dtype: Union[str, torch.dtype] = "auto",
**kwargs,
):
from functools import partial
@@ -888,8 +889,9 @@ def diffusion_load_model(
)
device_str, use_auto_mapping = get_device_and_parallelism(device)
- torch_dtype = "auto"
- if device_str is not None and "hpu" in device_str:
+ if model_dtype is not None:
+ torch_dtype = convert_dtype_str2torch(model_dtype)
+ elif torch_dtype == "auto" and device_str is not None and "hpu" in device_str:
torch_dtype = torch.bfloat16
try:
@@ -934,7 +936,12 @@ def diffusion_load_model(
if isinstance(v, list) and os.path.exists(os.path.join(component_folder, "config.json")):
with open(os.path.join(component_folder, "config.json"), "r", encoding="utf-8") as file:
component_config = json.load(file)
- torch_dtype[k] = component_config.get("torch_dtype", "auto")
+ component_dtype = component_config.get("torch_dtype")
+ if component_dtype is None or component_dtype == "auto":
+ component_dtype = default_torch_dtype
+ elif isinstance(component_dtype, str):
+ component_dtype = convert_dtype_str2torch(component_dtype.removeprefix("torch."))
+ torch_dtype[k] = component_dtype
pipe = pipelines.pipeline_utils.DiffusionPipeline.from_pretrained(
pretrained_model_name_or_path, torch_dtype=torch_dtype
@@ -955,7 +962,6 @@ def diffusion_load_model(
if k not in pipe.config:
pipe.config[k] = v
- pipe = _to_model_dtype(pipe, model_dtype)
if hasattr(pipe, "unet"):
# Stable Diffusion pipelines (e.g., SD and SDXL) use a UNet denoiser.
model = pipe.unet
diff --git a/test/unit/common/compressors/test_diffusion_mixin.py b/test/unit/common/compressors/test_diffusion_mixin.py
index f9885b7e2..eea0ec9bf 100644
--- a/test/unit/common/compressors/test_diffusion_mixin.py
+++ b/test/unit/common/compressors/test_diffusion_mixin.py
@@ -50,18 +50,18 @@ class TestDiffusionMixinProperties:
comp.pipeline_call_kwargs = {"height": 512, "width": 512}
assert comp.pipeline_call_kwargs.get("height") == 512
- def test_align_pipeline_dtype_preserves_fp32_modules(self):
+ def test_align_pipeline_dtype_preserves_only_declared_fp32_tensors(self):
protected = torch.nn.Linear(2, 2)
protected._keep_in_fp32_modules = ["weight"]
- protected.dtype = torch.float32
ordinary = torch.nn.Linear(2, 2)
- ordinary.dtype = torch.float32
pipe = SimpleNamespace(components=["protected", "ordinary"], protected=protected, ordinary=ordinary)
DiffusionMixin._align_pipeline_dtype(pipe, torch.bfloat16)
assert protected.weight.dtype == torch.float32
+ assert protected.bias.dtype == torch.bfloat16
assert ordinary.weight.dtype == torch.bfloat16
+ assert ordinary.bias.dtype == torch.bfloat16
class TestFindAdditionalTransformers:
diff --git a/test/unit/test_cpu/models/test_diffusion.py b/test/unit/test_cpu/models/test_diffusion.py
index 48075aabc..e0fa62a3c 100644
--- a/test/unit/test_cpu/models/test_diffusion.py
+++ b/test/unit/test_cpu/models/test_diffusion.py
@@ -1,6 +1,9 @@
+import json
import os
import shutil
from test.helpers import get_model_path, transformers_version
+from types import SimpleNamespace
+from unittest.mock import patch
import pytest
import torch
@@ -8,10 +11,66 @@ from packaging import version
from auto_round import AutoRound
from auto_round.calibration.diffusion import _prepare_pipeline_for_calibration
+from auto_round.utils.model import diffusion_load_model
flux_name_or_path = get_model_path("black-forest-labs/FLUX.1-dev")
+def test_diffusion_load_preserves_declared_fp32_modules(tmp_path):
+ from diffusers import WanTransformer3DModel
+
+ transformer = WanTransformer3DModel(
+ patch_size=(1, 2, 2),
+ num_attention_heads=2,
+ attention_head_dim=8,
+ in_channels=4,
+ out_channels=4,
+ text_dim=16,
+ freq_dim=8,
+ ffn_dim=32,
+ num_layers=1,
+ rope_max_seq_len=16,
+ )
+ transformer.save_pretrained(tmp_path / "transformer")
+ model_index = {
+ "_class_name": "TestPipeline",
+ "transformer": ["diffusers", "WanTransformer3DModel"],
+ }
+ (tmp_path / "model_index.json").write_text(json.dumps(model_index))
+
+ class Config(dict):
+ __getattr__ = dict.__getitem__
+ __setattr__ = dict.__setitem__
+
+ class TestPipeline:
+ def __init__(self, model):
+ self.transformer = model
+ self.config = Config()
+ self.components = {"transformer": model}
+
+ @classmethod
+ def from_pretrained(cls, path, torch_dtype):
+ transformer_dtype = torch_dtype["transformer"] if isinstance(torch_dtype, dict) else torch_dtype
+ model = WanTransformer3DModel.from_pretrained(
+ os.path.join(path, "transformer"), torch_dtype=transformer_dtype
+ )
+ return cls(model)
+
+ @staticmethod
+ def load_config(path):
+ return json.loads((tmp_path / "model_index.json").read_text())
+
+ pipelines = SimpleNamespace(pipeline_utils=SimpleNamespace(DiffusionPipeline=TestPipeline))
+ with patch("auto_round.utils.common.LazyImport", return_value=pipelines):
+ for load_kwargs in ({"default_torch_dtype": torch.bfloat16}, {"model_dtype": "bf16"}):
+ _, loaded = diffusion_load_model(str(tmp_path), **load_kwargs)
+
+ assert loaded.dtype == torch.bfloat16
+ assert loaded.patch_embedding.weight.dtype == torch.bfloat16
+ assert loaded.condition_embedder.time_embedder.linear_1.weight.dtype == torch.float32
+ assert loaded.blocks[0].norm2.weight.dtype == torch.float32
+
+
def test_low_gpu_memory_diffusion_calibration_uses_model_cpu_offload():
class Pipeline:
device = torch.device("cpu")