From 62c80129c18142c98f930984a8d6e52cd1550e38 Mon Sep 17 00:00:00 2001 From: mi804 <1576993271@qq.com> Date: Mon, 23 Nov 2026 18:08:58 +0800 Subject: [PATCH 1/6] support entropack-quantization --- docs/source/en/_toctree.yml | 2 + docs/source/en/api/quantization.md | 4 + docs/source/en/quantization/entropack.md | 148 +++++++++++++ docs/source/en/quantization/overview.md | 1 + setup.py | 2 + src/diffusers/__init__.py | 5 +- src/diffusers/dependency_versions_table.py | 1 + src/diffusers/quantizers/auto.py | 4 + .../quantizers/entropack/__init__.py | 4 + .../entropack/entropack_quantizer.py | 208 ++++++++++++++++++ src/diffusers/quantizers/entropack/utils.py | 118 ++++++++++ .../quantizers/quantization_config.py | 64 ++++++ src/diffusers/utils/__init__.py | 1 + src/diffusers/utils/import_utils.py | 6 + tests/quantization/entropack/__init__.py | 0 .../quantization/entropack/test_entropack.py | 182 +++++++++++++++ 16 files changed, 749 insertions(+), 1 deletion(-) create mode 100644 docs/source/en/quantization/entropack.md create mode 100644 src/diffusers/quantizers/entropack/__init__.py create mode 100644 src/diffusers/quantizers/entropack/entropack_quantizer.py create mode 100644 src/diffusers/quantizers/entropack/utils.py create mode 100644 tests/quantization/entropack/__init__.py create mode 100644 tests/quantization/entropack/test_entropack.py diff --git a/docs/source/en/_toctree.yml b/docs/source/en/_toctree.yml index e1a4a9247894..18f81cb41ba0 100644 --- a/docs/source/en/_toctree.yml +++ b/docs/source/en/_toctree.yml @@ -93,6 +93,8 @@ title: bitsandbytes - local: quantization/bfl title: BFL (fp8r / nvfp4) + - local: quantization/entropack + title: EntroPack - local: quantization/gguf title: gguf - local: quantization/nunchaku diff --git a/docs/source/en/api/quantization.md b/docs/source/en/api/quantization.md index 415762fb1d7b..43de7f62cb1c 100644 --- a/docs/source/en/api/quantization.md +++ b/docs/source/en/api/quantization.md @@ -30,6 +30,10 @@ Quantization techniques reduce memory and computational costs by representing we [[autodoc]] quantizers.quantization_config.BitsAndBytesConfig +## EntroPackConfig + +[[autodoc]] quantizers.quantization_config.EntroPackConfig + ## GGUFQuantizationConfig [[autodoc]] quantizers.quantization_config.GGUFQuantizationConfig diff --git a/docs/source/en/quantization/entropack.md b/docs/source/en/quantization/entropack.md new file mode 100644 index 000000000000..85bb8d8774b5 --- /dev/null +++ b/docs/source/en/quantization/entropack.md @@ -0,0 +1,148 @@ + + +# EntroPack + +[EntroPack](https://github.com/modelscope/entropack) compresses `nn.Linear` weights with lattice quantization and entropy coding. It supports fractional target rates, such as 3.5 bits per parameter (bpp), and does not require a calibration dataset. + +Install EntroPack with the extra that matches your CUDA version. Diffusers requires EntroPack 0.1.8 or newer. + +```bash +pip install --upgrade diffusers "entropack[cuda12]" +# CUDA 13 +pip install --upgrade diffusers "entropack[cuda13]" +``` + +## Quantize a model + +Pass an [`EntroPackConfig`] to [`~ModelMixin.from_pretrained`]. The linear weights are compressed as the checkpoint is loaded. + +```py +import torch +from diffusers import EntroPackConfig, ZImageTransformer2DModel + +model = ZImageTransformer2DModel.from_pretrained( + "Tongyi-MAI/Z-Image-Turbo", + subfolder="transformer", + quantization_config=EntroPackConfig(target_bpp=4.0), + torch_dtype=torch.bfloat16, + device_map={"": "cuda"}, +) +``` + +Only `torch.nn.Linear` weights are compressed. Embeddings and biases are left uncompressed; use `modules_to_not_convert` to keep specific projected layers in their original precision. + +### Linear implementations + +Set `linear_type` to choose how the decoded weight is used. + +| `linear_type` | Layer | Computation | Minimum hardware | +|---|---|---|---| +| `"default"` | `CompressedLinear` | Reconstruct the weight and apply a regular linear operation | CUDA GPU | +| `"fp8"` | `CompressedFP8Linear` | FP8 E4M3FN weights and activations | CUDA SM8.9+ | +| `"int8"` | `CompressedINT8Linear` | Symmetric INT8 weights and activations | CUDA SM8.0+ | + +```py +fp8_config = EntroPackConfig(target_bpp=4.0, linear_type="fp8") +int8_config = EntroPackConfig(target_bpp=4.0, linear_type="int8") +``` + +FP8 and INT8 checkpoints also store one FP32 scale per output channel. + +### INT8 rotation (ConvRot) + +With `linear_type="int8"`, weights and activations are rotated with a block Hadamard rotation before +quantization by default (`use_convrot=True`). The rotation spreads outlier magnitudes across each block, +which improves reconstruction quality at low bitrates. `convrot_groupsize` requests the rotation block size +(a power of four, reduced by factors of four until it divides the layer's input dimension): + +```py +int8_config = EntroPackConfig(target_bpp=4.0, linear_type="int8", use_convrot=True, convrot_groupsize=64) +``` + +The rotation setting is not part of the packed weights: it is saved in `config.json` and read back when +reloading. Pass `use_convrot=False` to disable rotation. Both settings are ignored for other linear types. + +### Compression settings + +`target_bpp` defaults to 4.0. The default linear implementation accepts rates from 0.001 through 11 bpp. The FP8 and INT8 implementations require a rate below 8 bpp. + +Use `entropack_lossy_config` for additional settings accepted by EntroPack's lossy compression backend. See the [EntroPack configuration reference](https://github.com/modelscope/entropack/blob/main/docs/en/Usage/Configuration.md#entropacklossyconfig) for the available fields. + +```py +quantization_config = EntroPackConfig( + target_bpp=4.0, + entropack_lossy_config={"row_rdo_iterations": 1}, +) +``` + +Use `modules_to_not_convert` to keep selected modules uncompressed. A name matches the module itself and everything under it. + +```py +quantization_config = EntroPackConfig( + target_bpp=4.0, + modules_to_not_convert=["all_final_layer", "t_embedder"], +) +``` + +## Quantize a pipeline + +Use [`~quantizers.PipelineQuantizationConfig`] to quantize one or more pipeline components. + +```py +import torch +from diffusers import EntroPackConfig, ZImagePipeline +from diffusers.quantizers import PipelineQuantizationConfig + +quantization_config = PipelineQuantizationConfig( + quant_mapping={"transformer": EntroPackConfig(target_bpp=4.0)}, +) +pipe = ZImagePipeline.from_pretrained( + "Tongyi-MAI/Z-Image-Turbo", + quantization_config=quantization_config, + torch_dtype=torch.bfloat16, +).to("cuda") +image = pipe( + prompt="A cat holding a sign that says hello world", + num_inference_steps=8, + guidance_scale=0.0, +).images[0] +``` + +## Save and reload + +Save an EntroPack model with [`~ModelMixin.save_pretrained`]. The packed weights are saved in safetensors format, and the EntroPack settings are included in `config.json`. + +```py +model.save_pretrained("zimage-entropack-4bpp") +``` + +Load the saved model without passing another [`EntroPackConfig`]. Diffusers reads the quantization settings from `config.json`. + +```py +model = ZImageTransformer2DModel.from_pretrained( + "zimage-entropack-4bpp", + torch_dtype=torch.bfloat16, + device_map={"": "cuda"}, +) +``` + +## Dequantize + +Call [`~ModelMixin.dequantize`] to restore dense `nn.Linear` layers from a quantized model, for example before merging adapters: + +```py +model = model.dequantize() +``` + +EntroPack compression is lossy: dequantize returns the reconstructed weights, not the original pre-quantization weights. diff --git a/docs/source/en/quantization/overview.md b/docs/source/en/quantization/overview.md index 06a6b55ce60f..b449af45543a 100644 --- a/docs/source/en/quantization/overview.md +++ b/docs/source/en/quantization/overview.md @@ -145,6 +145,7 @@ The following backends support loading prequantized checkpoints out of the box. |---|---| | [bitsandbytes](./bitsandbytes) | Config is saved in `config.json`; no extra arguments needed. Supports quantizing on the fly as well as loading prequantized checkpoints. | | [torchao](./torchao) | Same as above. | +| [EntroPack](./entropack) | Config is saved in `config.json`; supports online quantization and loading prequantized checkpoints. | | [GGUF](./gguf) | Uses `from_single_file` with Model classes; pipeline-level loading is not supported. | | [BFL](./bfl) | Loads Black Forest Labs `fp8r` and `nvfp4` single-file checkpoints with `from_single_file`; pipeline-level loading is not supported. | | [AutoRound](./autoround) | Only loading is supported; quantize first with the AutoRound CLI or Python API. | diff --git a/setup.py b/setup.py index ff84ed421292..83af4a0f6192 100644 --- a/setup.py +++ b/setup.py @@ -133,6 +133,7 @@ "bitsandbytes>=0.43.3", "nvidia_modelopt[hf]>=0.33.1", "sdnq>=0.2.2", + "entropack>=0.1.8", "regex!=2019.12.17", "requests", "tensorboard", @@ -252,6 +253,7 @@ def run(self): extras["torchao"] = deps_list("torchao", "accelerate") extras["nvidia_modelopt"] = deps_list("nvidia_modelopt[hf]") extras["sdnq"] = deps_list("sdnq") +extras["entropack"] = deps_list("entropack", "accelerate") extras["flashpack"] = deps_list("flashpack") extras["dev"] = extras["quality"] + extras["test"] + extras["training"] + extras["docs"] + extras["torch"] diff --git a/src/diffusers/__init__.py b/src/diffusers/__init__.py index 1435abc234cf..f50de2c9dac6 100644 --- a/src/diffusers/__init__.py +++ b/src/diffusers/__init__.py @@ -9,6 +9,7 @@ is_accelerate_available, is_auto_round_available, is_bitsandbytes_available, + is_entropack_available, is_gguf_available, is_librosa_available, is_note_seq_available, @@ -43,10 +44,11 @@ "modular_pipelines": [], "pipelines": [], "quantizers.pipe_quant_config": ["PipelineQuantizationConfig"], - "quantizers.quantization_config": [], + "quantizers.quantization_config": ["EntroPackConfig"], "schedulers": [], "utils": [ "OptionalDependencyNotAvailable", + "is_entropack_available", "is_inflect_available", "is_invisible_watermark_available", "is_librosa_available", @@ -1032,6 +1034,7 @@ from .utils.dummy_bitsandbytes_objects import * else: from .quantizers.quantization_config import BitsAndBytesConfig + from .quantizers.quantization_config import EntroPackConfig try: if not is_gguf_available(): diff --git a/src/diffusers/dependency_versions_table.py b/src/diffusers/dependency_versions_table.py index d1a5ab367f20..32c5082864c1 100644 --- a/src/diffusers/dependency_versions_table.py +++ b/src/diffusers/dependency_versions_table.py @@ -40,6 +40,7 @@ "bitsandbytes": "bitsandbytes>=0.43.3", "nvidia_modelopt[hf]": "nvidia_modelopt[hf]>=0.33.1", "sdnq": "sdnq>=0.2.2", + "entropack": "entropack>=0.1.8", "regex": "regex!=2019.12.17", "requests": "requests", "tensorboard": "tensorboard", diff --git a/src/diffusers/quantizers/auto.py b/src/diffusers/quantizers/auto.py index 377b46b7b361..5f5d34806e91 100644 --- a/src/diffusers/quantizers/auto.py +++ b/src/diffusers/quantizers/auto.py @@ -21,6 +21,7 @@ from .autoround import AutoRoundQuantizer from .bfl import BFLQuantizer from .bitsandbytes import BnB4BitDiffusersQuantizer, BnB8BitDiffusersQuantizer +from .entropack import EntroPackQuantizer from .gguf import GGUFQuantizer from .modelopt import NVIDIAModelOptQuantizer from .nunchaku import NunchakuLiteQuantizer @@ -28,6 +29,7 @@ AutoRoundConfig, BFLQuantizationConfig, BitsAndBytesConfig, + EntroPackConfig, GGUFQuantizationConfig, NunchakuLiteQuantizationConfig, NVIDIAModelOptConfig, @@ -46,6 +48,7 @@ "bfl": BFLQuantizer, "bitsandbytes_4bit": BnB4BitDiffusersQuantizer, "bitsandbytes_8bit": BnB8BitDiffusersQuantizer, + "entropack": EntroPackQuantizer, "gguf": GGUFQuantizer, "quanto": QuantoQuantizer, "torchao": TorchAoHfQuantizer, @@ -59,6 +62,7 @@ "bfl": BFLQuantizationConfig, "bitsandbytes_4bit": BitsAndBytesConfig, "bitsandbytes_8bit": BitsAndBytesConfig, + "entropack": EntroPackConfig, "gguf": GGUFQuantizationConfig, "quanto": QuantoConfig, "torchao": TorchAoConfig, diff --git a/src/diffusers/quantizers/entropack/__init__.py b/src/diffusers/quantizers/entropack/__init__.py new file mode 100644 index 000000000000..a1813737f238 --- /dev/null +++ b/src/diffusers/quantizers/entropack/__init__.py @@ -0,0 +1,4 @@ +from .entropack_quantizer import EntroPackQuantizer + + +__all__ = ["EntroPackQuantizer"] diff --git a/src/diffusers/quantizers/entropack/entropack_quantizer.py b/src/diffusers/quantizers/entropack/entropack_quantizer.py new file mode 100644 index 000000000000..e05400b2ff9a --- /dev/null +++ b/src/diffusers/quantizers/entropack/entropack_quantizer.py @@ -0,0 +1,208 @@ +# Copyright 2026 The HuggingFace Team. All rights reserved. +# +# 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 __future__ import annotations + +from typing import TYPE_CHECKING, Any + +from ...dependency_versions_table import deps +from ...utils import ( + get_module_from_name, + is_entropack_available, + is_torch_available, + logging, +) +from ..base import DiffusersQuantizer + + +if TYPE_CHECKING: + from ...models.modeling_utils import ModelMixin + + +if is_torch_available(): + import torch + import torch.nn as nn + + +logger = logging.get_logger(__name__) + + +class EntroPackQuantizer(DiffusersQuantizer): + """Diffusers quantizer for EntroPack weight compression: https://github.com/modelscope/entropack.""" + + requires_calibration = False + required_packages = ["entropack"] + use_keep_in_fp32_modules = True + + def __init__(self, quantization_config, **kwargs): + super().__init__(quantization_config, **kwargs) + self.modules_to_not_convert = list(quantization_config.modules_to_not_convert or []) + + def validate_environment(self, *args, **kwargs): + if not is_entropack_available(): + raise ImportError( + f"Loading an EntroPack quantized model requires `{deps['entropack']}`. Install it with " + "`pip install -U 'entropack[cuda12]'` (or `[cuda13]` for CUDA 13)." + ) + + from entropack.backends.cuda import probe + + reason = probe() + if reason is not None: + raise RuntimeError(f"The entropack CUDA codec is unavailable: {reason}") + + device_map = kwargs.get("device_map") + if isinstance(device_map, dict) and "disk" in device_map.values(): + raise ValueError("EntroPack does not support disk offloading; remove the `disk` device from `device_map`.") + + def update_torch_dtype(self, torch_dtype: "torch.dtype | None") -> "torch.dtype": + if torch_dtype is None: + logger.info("You did not specify `torch_dtype`; setting it to `torch.bfloat16` for EntroPack.") + torch_dtype = torch.bfloat16 + return torch_dtype + + def adjust_target_dtype(self, target_dtype: "torch.dtype") -> "torch.dtype": + return torch.uint8 + + def adjust_max_memory(self, max_memory: dict[str, int | str]) -> dict[str, int | str]: + return {key: value * 0.9 for key, value in max_memory.items()} + + def maybe_update_loaded_keys(self, loaded_keys: list[str], checkpoint_files: list[str]) -> list[str]: + if not self.pre_quantized: + return loaded_keys + suffix = ".entropack_quant_state" + return [key[: -len(suffix)] if key.endswith(suffix) else key for key in loaded_keys] + + def maybe_update_state_dict(self, state_dict: dict[str, Any]) -> dict[str, Any]: + if not self.pre_quantized: + return state_dict + import entropack + + quant_suffix = ".weight.entropack_quant_state" + converted = {} + for key, value in state_dict.items(): + if key.endswith(quant_suffix): + key = key[: -len(quant_suffix)] + ".weight" + value = entropack.CompressedTensor.from_state_dict({"entropack_quant_state": value}) + converted[key] = value + return converted + + def check_if_quantized_param( + self, + model: "ModelMixin", + param_value: "torch.Tensor", + param_name: str, + state_dict: dict[str, Any], + **kwargs, + ) -> bool: + import entropack + + module, tensor_name = get_module_from_name(model, param_name) + if not isinstance(module, entropack.CompressedLinear): + return False + + if self.pre_quantized: + if tensor_name == "weight": + return isinstance(param_value, entropack.CompressedTensor) + # scales are quantizer-loaded so they keep the float32 dtype stored in the checkpoint + return tensor_name in module.state_buffer_names + + return tensor_name == "weight" + + def check_quantized_param_shape(self, param_name, current_param, loaded_param): + current_shape = tuple(current_param.shape) + loaded_shape = tuple(loaded_param.shape) + if current_shape != loaded_shape: + raise ValueError(f"{param_name} has an expected shape of {current_shape}, but got {loaded_shape}.") + return True + + def create_quantized_param( + self, + model: "ModelMixin", + param_value: "torch.Tensor", + param_name: str, + target_device: "torch.device", + state_dict: dict[str, Any], + unexpected_keys: list[str] | None = None, + **kwargs, + ): + module, tensor_name = get_module_from_name(model, param_name) + if tensor_name in module.state_buffer_names: + # param_value has been converted to the model dtype; state_dict still holds the + # original float32 scale required by the layer. + setattr(module, tensor_name, state_dict[param_name].to(device=target_device, dtype=torch.float32)) + return + + # the packed wrapper carries the code dtype (fp8/int8); re-wrap it to the layer's logical + # dtype so param.dtype — and hence model.dtype — reflects the compute precision + if self.pre_quantized: + container = param_value._map_quant_state(lambda value: value, dtype=module._init_dtype) + module.weight = nn.Parameter(container.to(target_device), requires_grad=False) + else: + module.compress_weight(param_value.detach().to(target_device)) + module.weight = nn.Parameter( + module.weight._map_quant_state(lambda value: value, dtype=module._init_dtype), + requires_grad=False, + ) + + def update_missing_keys(self, model, missing_keys: list[str], prefix: str) -> list[str]: + if self.pre_quantized: + return missing_keys + import entropack + + kept = [] + for key in missing_keys: + module, tensor_name = get_module_from_name(model, key[len(prefix) :]) + if not (isinstance(module, entropack.CompressedLinear) and tensor_name in module.state_buffer_names): + kept.append(key) + return kept + + def _process_model_before_weight_loading( + self, + model: "ModelMixin", + keep_in_fp32_modules: list[str] = [], + **kwargs, + ): + self.modules_to_not_convert.extend(module for module in keep_in_fp32_modules if module) + from .utils import _replace_with_entropack_linear + + _replace_with_entropack_linear(model, self.quantization_config, self.modules_to_not_convert) + model.config.quantization_config = self.quantization_config + return model + + def _process_model_after_weight_loading(self, model: "ModelMixin", **kwargs): + import entropack + + for name, module in model.named_modules(): + if not isinstance(module, entropack.CompressedLinear): + continue + if not isinstance(module.weight, entropack.CompressedTensor): + raise RuntimeError(f"EntroPack layer {name} has no packed weight") + for buffer_name in module.state_buffer_names: + if getattr(module, buffer_name).device.type == "meta": + raise RuntimeError(f"EntroPack layer {name} did not load {buffer_name}") + return model + + @property + def is_serializable(self): + return True + + @property + def is_trainable(self) -> bool: + return True + + def _dequantize(self, model): + from .utils import _dequantize_and_replace + + return _dequantize_and_replace(model) diff --git a/src/diffusers/quantizers/entropack/utils.py b/src/diffusers/quantizers/entropack/utils.py new file mode 100644 index 000000000000..5afed9dcdd51 --- /dev/null +++ b/src/diffusers/quantizers/entropack/utils.py @@ -0,0 +1,118 @@ +# Copyright 2026 The HuggingFace Team. All rights reserved. +# +# 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 __future__ import annotations + +from typing import TYPE_CHECKING + +from ...utils import is_torch_available, logging + + +if TYPE_CHECKING: + from ...models.modeling_utils import ModelMixin + + +if is_torch_available(): + import torch + import torch.nn as nn + + +logger = logging.get_logger(__name__) + + +def _replace_with_entropack_linear( + model: "ModelMixin", + quantization_config, + modules_to_not_convert: list[str], +) -> "ModelMixin": + import entropack + + codec_options = dict(quantization_config.entropack_lossy_config or {}) + codec_options.update(target_bpp=quantization_config.target_bpp, execution_backend="cuda") + codec_config = entropack.EntroPackLossyConfig(**codec_options) + linear_cls = { + "default": entropack.CompressedLinear, + "fp8": entropack.CompressedFP8Linear, + "int8": entropack.CompressedINT8Linear, + }[quantization_config.linear_type] + linear_kwargs = {} + if quantization_config.linear_type == "int8": + linear_kwargs = { + "use_convrot": quantization_config.use_convrot, + "convrot_groupsize": quantization_config.convrot_groupsize, + } + + replaced = [] + + def replace(module: nn.Module, prefix: str) -> None: + for name, child in module.named_children(): + full_name = f"{prefix}.{name}" if prefix else name + if isinstance(child, nn.Linear) and name not in modules_to_not_convert: + if not any((key + "." in full_name) or (key == full_name) for key in modules_to_not_convert): + with torch.device("meta"): + new_module = linear_cls( + child.in_features, + child.out_features, + bias=child.bias is not None, + config=codec_config, + dtype=child.weight.dtype, + device="meta", + **linear_kwargs, + ) + new_module.weight = nn.Parameter( + torch.empty( + child.out_features, child.in_features, dtype=child.weight.dtype, device="meta" + ), + requires_grad=False, + ) + module._modules[name] = new_module + module._modules[name].source_cls = type(child) + module._modules[name].requires_grad_(False) + replaced.append(full_name) + else: + replace(child, full_name) + + replace(model, "") + + if not replaced: + logger.warning( + f"{model.__class__.__name__} does not appear to have any `nn.Linear` modules. Quantization will not be " + "applied. Please check your model architecture or submit an issue on GitHub if you think this is a bug." + ) + + return model + + +def _dequantize_and_replace(model: "ModelMixin") -> "ModelMixin": + import entropack + + for name, module in model.named_children(): + if isinstance(module, entropack.CompressedLinear): + device = module.weight.device + with torch.device("meta"): + new_module = nn.Linear( + module.in_features, + module.out_features, + bias=module.bias is not None, + dtype=module._init_dtype, + ) + new_module.weight = nn.Parameter( + module.dequantize(device).to(device=device, dtype=module._init_dtype), requires_grad=False + ) + if module.bias is not None: + new_module.bias = nn.Parameter(module.bias.data.to(device), requires_grad=False) + model._modules[name] = new_module + else: + _dequantize_and_replace(module) + return model diff --git a/src/diffusers/quantizers/quantization_config.py b/src/diffusers/quantizers/quantization_config.py index 8d7c0c343b19..78759801b339 100644 --- a/src/diffusers/quantizers/quantization_config.py +++ b/src/diffusers/quantizers/quantization_config.py @@ -50,6 +50,7 @@ class QuantizationMethod(str, Enum): MODELOPT = "modelopt" AUTOROUND = "auto-round" SDNQ = "sdnq" + ENTROPACK = "entropack" @dataclass @@ -1012,3 +1013,66 @@ def __new__(cls, *args, **kwargs): from sdnq import SDNQConfig as SDNQLibConfig return SDNQLibConfig(*args, **kwargs) + + +@dataclass +class EntroPackConfig(QuantizationConfigMixin): + """ + Configuration for loading a model with EntroPack weight compression. + + Args: + target_bpp (`float`, *optional*, defaults to 4.0): + Target number of bits per parameter for compressed linear weights. + linear_type (`str`, *optional*, defaults to `"default"`): + Linear implementation to use. Choose from `"default"`, `"fp8"`, and `"int8"`. + modules_to_not_convert (`list`, *optional*, default to `None`): + The list of modules to not quantize, useful for quantizing models that explicitly require to have + some modules left in their original precision. + entropack_lossy_config (`dict`, *optional*): + Additional settings for the EntroPack lossy compression backend. `target_bpp` takes precedence over the + value in this dictionary. + use_convrot (`bool`, *optional*, defaults to `True`): + For `linear_type="int8"`, rotate weights and activations with a block Hadamard rotation before + quantization. Ignored for other linear types. The flag is not stored in the packed weights, so it is + read back from `config.json` when reloading. + convrot_groupsize (`int`, *optional*, defaults to 256): + Requested power-of-four rotation block size for `use_convrot`, reduced by factors of four until it + divides the layer's `in_features`. + """ + + def __init__( + self, + target_bpp: float = 4.0, + linear_type: str = "default", + modules_to_not_convert: list | None = None, + entropack_lossy_config: dict | None = None, + use_convrot: bool = True, + convrot_groupsize: int = 256, + **kwargs, + ): + self.quant_method = QuantizationMethod.ENTROPACK + self.target_bpp = float(target_bpp) + self.linear_type = linear_type + self.modules_to_not_convert = list(modules_to_not_convert) if modules_to_not_convert else None + self.entropack_lossy_config = entropack_lossy_config + self.use_convrot = bool(use_convrot) + self.convrot_groupsize = convrot_groupsize + self.post_init() + + def post_init(self): + if self.linear_type not in ("default", "fp8", "int8"): + raise ValueError(f'linear_type must be "default", "fp8" or "int8", got {self.linear_type!r}') + if self.linear_type in ("fp8", "int8"): + valid_rate, rate_range = 0.001 <= self.target_bpp < 8.0, "[0.001, 8)" + else: + valid_rate, rate_range = 0.001 <= self.target_bpp <= 11.0, "[0.001, 11]" + if not valid_rate: + raise ValueError( + f"target_bpp must be within {rate_range} for linear_type={self.linear_type!r}, got {self.target_bpp}" + ) + if self.linear_type == "int8" and self.use_convrot: + group = self.convrot_groupsize + while group > 1 and group % 4 == 0: + group //= 4 + if group != 1 or self.convrot_groupsize < 4: + raise ValueError(f"convrot_groupsize must be a power of four >= 4, got {self.convrot_groupsize}") diff --git a/src/diffusers/utils/__init__.py b/src/diffusers/utils/__init__.py index 1fe67478be24..2c2e906eb26b 100644 --- a/src/diffusers/utils/__init__.py +++ b/src/diffusers/utils/__init__.py @@ -79,6 +79,7 @@ is_bitsandbytes_version, is_bs4_available, is_cosmos_guardrail_available, + is_entropack_available, is_flash_attn_3_available, is_flash_attn_available, is_flash_attn_version, diff --git a/src/diffusers/utils/import_utils.py b/src/diffusers/utils/import_utils.py index 020edbd5a4fa..3ea8325c8f52 100644 --- a/src/diffusers/utils/import_utils.py +++ b/src/diffusers/utils/import_utils.py @@ -72,6 +72,7 @@ "modelopt": "nvidia_modelopt[hf]", "sdnq": "sdnq", "auto_round": "auto-round", + "entropack": "entropack", } @@ -255,6 +256,7 @@ def _is_distribution_installed(name: str) -> tuple[bool, str]: _accelerate_available, _accelerate_version = _is_package_available("accelerate") _xformers_available, _xformers_version = _is_package_available("xformers") _gguf_available, _gguf_version = _is_package_available("gguf") +_entropack_available, _entropack_version = _is_package_available("entropack") _torchao_available, _torchao_version = _is_package_available("torchao") _optimum_quanto_available, _optimum_quanto_version = _is_package_available("optimum", get_dist_name=True) _pytorch_retinaface_available, _pytorch_retinaface_version = _is_package_available("pytorch_retinaface") @@ -418,6 +420,10 @@ def is_flashpack_available(): return _flashpack_available +def is_entropack_available(): + return _entropack_available + + def is_torchao_available(): return _torchao_available diff --git a/tests/quantization/entropack/__init__.py b/tests/quantization/entropack/__init__.py new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/tests/quantization/entropack/test_entropack.py b/tests/quantization/entropack/test_entropack.py new file mode 100644 index 000000000000..38ee3bf573e3 --- /dev/null +++ b/tests/quantization/entropack/test_entropack.py @@ -0,0 +1,182 @@ +import json + +import pytest +import torch +import torch.nn as nn + +from diffusers import EntroPackConfig, Transformer2DModel +from diffusers.quantizers.auto import DiffusersAutoQuantizer +from diffusers.utils import is_entropack_available + +from ...testing_utils import require_accelerate, require_torch, require_torch_accelerator + + +pytestmark = [ + pytest.mark.skipif(not is_entropack_available(), reason="test requires entropack"), + pytest.mark.skipif(not torch.cuda.is_available(), reason="test requires CUDA"), +] + + +def is_entropack_linear(module): + import entropack + + return isinstance(module, entropack.CompressedLinear) + + +def tiny_model() -> Transformer2DModel: + return Transformer2DModel( + in_channels=8, + num_attention_heads=2, + attention_head_dim=8, + cross_attention_dim=16, + num_layers=1, + norm_num_groups=2, + sample_size=8, + ).to(torch.bfloat16) + + +def model_inputs(device): + return ( + torch.randn(1, 8, 8, 8, dtype=torch.bfloat16, device=device), + torch.randn(1, 4, 16, dtype=torch.bfloat16, device=device), + ) + + +class TestEntroPackConfig: + def test_round_trip(self): + config = EntroPackConfig( + target_bpp=3.5, + linear_type="int8", + modules_to_not_convert=["to_q"], + entropack_lossy_config={"row_rdo_iterations": 1}, + use_convrot=False, + convrot_groupsize=64, + ) + serialized = json.loads(json.dumps(config.to_dict())) + restored = DiffusersAutoQuantizer.from_dict(serialized) + assert isinstance(restored, EntroPackConfig) + assert restored.to_dict() == config.to_dict() + + def test_invalid_values_are_rejected(self): + for kwargs in ( + {"target_bpp": 100.0}, + {"linear_type": "fp4"}, + {"linear_type": "fp8", "target_bpp": 8.0}, + {"linear_type": "int8", "convrot_groupsize": 8}, + {"linear_type": "int8", "convrot_groupsize": 3}, + ): + with pytest.raises(ValueError): + EntroPackConfig(**kwargs) + + +@require_torch +@require_accelerate +@require_torch_accelerator +class TestEntroPackQuantizer: + @pytest.mark.parametrize("linear_type", ["default", "int8", "fp8"]) + def test_online_quantize_save_reload(self, tmp_path, linear_type): + if linear_type == "fp8": + pytest.importorskip("entropack") + import entropack + + if torch.cuda.get_device_capability() < entropack.CompressedFP8Linear.min_capability: + pytest.skip("FP8 requires CUDA capability >= 8.9") + expected_cls = entropack.CompressedFP8Linear + elif linear_type == "int8": + import entropack + + if torch.cuda.get_device_capability() < entropack.CompressedINT8Linear.min_capability: + pytest.skip("INT8 requires CUDA capability >= 8.0") + expected_cls = entropack.CompressedINT8Linear + else: + import entropack + + expected_cls = entropack.CompressedLinear + + torch.manual_seed(0) + model = tiny_model() + model.save_pretrained(tmp_path / "base") + quantized = Transformer2DModel.from_pretrained( + tmp_path / "base", + quantization_config=EntroPackConfig(target_bpp=4.0, linear_type=linear_type), + torch_dtype=torch.bfloat16, + device_map={"": "cuda"}, + ) + layers = [(name, module) for name, module in quantized.named_modules() if is_entropack_linear(module)] + assert layers + assert all(isinstance(module, expected_cls) for _, module in layers) + if linear_type != "default": + assert all(module.weight_quant_scale.dtype == torch.float32 for _, module in layers) + if linear_type == "int8": + assert all(module.use_convrot for _, module in layers) + + x, encoder_hidden_states = model_inputs("cuda") + with torch.no_grad(): + output = quantized(x, encoder_hidden_states=encoder_hidden_states).sample + assert torch.isfinite(output).all() + + quantized.save_pretrained(tmp_path / "quantized", max_shard_size="1KB") + reloaded = Transformer2DModel.from_pretrained( + tmp_path / "quantized", + torch_dtype=torch.bfloat16, + device_map={"": "cuda"}, + ) + assert sum(is_entropack_linear(module) for module in reloaded.modules()) == len(layers) + with torch.no_grad(): + reloaded_output = reloaded(x, encoder_hidden_states=encoder_hidden_states).sample + torch.testing.assert_close(output, reloaded_output, rtol=0, atol=0) + + def test_int8_convrot_off_round_trip(self, tmp_path): + model = tiny_model() + model.save_pretrained(tmp_path / "base") + quantized = Transformer2DModel.from_pretrained( + tmp_path / "base", + quantization_config=EntroPackConfig(target_bpp=4.0, linear_type="int8", use_convrot=False), + torch_dtype=torch.bfloat16, + device_map={"": "cuda"}, + ) + layers = [m for m in quantized.modules() if is_entropack_linear(m)] + assert layers and not any(m.use_convrot for m in layers) + + x, encoder_hidden_states = model_inputs("cuda") + with torch.no_grad(): + output = quantized(x, encoder_hidden_states=encoder_hidden_states).sample + quantized.save_pretrained(tmp_path / "quantized", max_shard_size="1KB") + reloaded = Transformer2DModel.from_pretrained( + tmp_path / "quantized", torch_dtype=torch.bfloat16, device_map={"": "cuda"} + ) + assert not any(m.use_convrot for m in reloaded.modules() if is_entropack_linear(m)) + with torch.no_grad(): + reloaded_output = reloaded(x, encoder_hidden_states=encoder_hidden_states).sample + torch.testing.assert_close(output, reloaded_output, rtol=0, atol=0) + + def test_modules_to_not_convert_is_honoured(self, tmp_path): + model = tiny_model() + model.save_pretrained(tmp_path / "base") + quantized = Transformer2DModel.from_pretrained( + tmp_path / "base", + quantization_config=EntroPackConfig(target_bpp=4.0, modules_to_not_convert=["to_q"]), + torch_dtype=torch.bfloat16, + device_map={"": "cuda"}, + ) + attention = quantized.transformer_blocks[0].attn1 + assert type(attention.to_q) is nn.Linear + assert is_entropack_linear(attention.to_k) + + def test_dequantize_restores_linear_layers(self, tmp_path): + model = tiny_model() + model.save_pretrained(tmp_path / "base") + quantized = Transformer2DModel.from_pretrained( + tmp_path / "base", + quantization_config=EntroPackConfig(target_bpp=4.0, linear_type="int8"), + torch_dtype=torch.bfloat16, + device_map={"": "cuda"}, + ) + restored = quantized.dequantize() + assert not restored.is_quantized + assert not any(is_entropack_linear(module) for module in restored.modules()) + + x, encoder_hidden_states = model_inputs("cuda") + with torch.no_grad(): + output = restored(x, encoder_hidden_states=encoder_hidden_states).sample + assert torch.isfinite(output).all() From 57a48a182aa224bb7eb20391814384263b149894 Mon Sep 17 00:00:00 2001 From: mi804 <1576993271@qq.com> Date: Mon, 23 Nov 2026 21:30:29 +0800 Subject: [PATCH 2/6] fix fast gemm for fp8 and int8 --- .../entropack/entropack_quantizer.py | 9 +-------- src/diffusers/quantizers/entropack/utils.py | 20 +++++++++++++++++-- 2 files changed, 19 insertions(+), 10 deletions(-) diff --git a/src/diffusers/quantizers/entropack/entropack_quantizer.py b/src/diffusers/quantizers/entropack/entropack_quantizer.py index e05400b2ff9a..97735153d7a2 100644 --- a/src/diffusers/quantizers/entropack/entropack_quantizer.py +++ b/src/diffusers/quantizers/entropack/entropack_quantizer.py @@ -144,17 +144,10 @@ def create_quantized_param( setattr(module, tensor_name, state_dict[param_name].to(device=target_device, dtype=torch.float32)) return - # the packed wrapper carries the code dtype (fp8/int8); re-wrap it to the layer's logical - # dtype so param.dtype — and hence model.dtype — reflects the compute precision if self.pre_quantized: - container = param_value._map_quant_state(lambda value: value, dtype=module._init_dtype) - module.weight = nn.Parameter(container.to(target_device), requires_grad=False) + module.weight = nn.Parameter(param_value.to(target_device), requires_grad=False) else: module.compress_weight(param_value.detach().to(target_device)) - module.weight = nn.Parameter( - module.weight._map_quant_state(lambda value: value, dtype=module._init_dtype), - requires_grad=False, - ) def update_missing_keys(self, model, missing_keys: list[str], prefix: str) -> list[str]: if self.pre_quantized: diff --git a/src/diffusers/quantizers/entropack/utils.py b/src/diffusers/quantizers/entropack/utils.py index 5afed9dcdd51..06657347490f 100644 --- a/src/diffusers/quantizers/entropack/utils.py +++ b/src/diffusers/quantizers/entropack/utils.py @@ -16,7 +16,7 @@ from typing import TYPE_CHECKING -from ...utils import is_torch_available, logging +from ...utils import is_entropack_available, is_torch_available, logging if TYPE_CHECKING: @@ -28,6 +28,22 @@ import torch.nn as nn +if is_entropack_available(): + import entropack + + # present weights in the layer's compute dtype and decode codes directly from the packed header + class _CompressedFP8Linear(entropack.CompressedFP8Linear): + def __setattr__(self, name, value): + if name == "weight" and isinstance(value, nn.Parameter) and value.dtype == self.code_dtype: + value = nn.Parameter( + value.data._map_quant_state(lambda v: v, dtype=self._init_dtype), requires_grad=False + ) + super().__setattr__(name, value) + + def codes(self, device=None): + return entropack.decompress(self._container(), self._decode_config).to(self.code_dtype) + + logger = logging.get_logger(__name__) @@ -43,7 +59,7 @@ def _replace_with_entropack_linear( codec_config = entropack.EntroPackLossyConfig(**codec_options) linear_cls = { "default": entropack.CompressedLinear, - "fp8": entropack.CompressedFP8Linear, + "fp8": _CompressedFP8Linear, "int8": entropack.CompressedINT8Linear, }[quantization_config.linear_type] linear_kwargs = {} From 0670944d18f2455916d6039856d67c2ad5fcb9f5 Mon Sep 17 00:00:00 2001 From: mi804 <1576993271@qq.com> Date: Thu, 26 Nov 2026 16:26:12 +0800 Subject: [PATCH 3/6] refactor docs and expose _dequantize_and_replace to entropack --- docs/source/en/quantization/entropack.md | 33 ++++++++++++++++--- setup.py | 2 +- src/diffusers/dependency_versions_table.py | 2 +- .../entropack/entropack_quantizer.py | 4 +-- src/diffusers/quantizers/entropack/utils.py | 24 -------------- 5 files changed, 33 insertions(+), 32 deletions(-) diff --git a/docs/source/en/quantization/entropack.md b/docs/source/en/quantization/entropack.md index 85bb8d8774b5..bfc9f588fa41 100644 --- a/docs/source/en/quantization/entropack.md +++ b/docs/source/en/quantization/entropack.md @@ -15,7 +15,7 @@ specific language governing permissions and limitations under the License. [EntroPack](https://github.com/modelscope/entropack) compresses `nn.Linear` weights with lattice quantization and entropy coding. It supports fractional target rates, such as 3.5 bits per parameter (bpp), and does not require a calibration dataset. -Install EntroPack with the extra that matches your CUDA version. Diffusers requires EntroPack 0.1.8 or newer. +Install EntroPack with the extra that matches your CUDA version. Diffusers requires EntroPack 0.1.9 or newer. ```bash pip install --upgrade diffusers "entropack[cuda12]" @@ -36,7 +36,6 @@ model = ZImageTransformer2DModel.from_pretrained( subfolder="transformer", quantization_config=EntroPackConfig(target_bpp=4.0), torch_dtype=torch.bfloat16, - device_map={"": "cuda"}, ) ``` @@ -111,7 +110,8 @@ pipe = ZImagePipeline.from_pretrained( "Tongyi-MAI/Z-Image-Turbo", quantization_config=quantization_config, torch_dtype=torch.bfloat16, -).to("cuda") + device_map="cuda", +) image = pipe( prompt="A cat holding a sign that says hello world", num_inference_steps=8, @@ -119,6 +119,32 @@ image = pipe( ).images[0] ``` +`device_map="cuda"` quantizes on the GPU during loading: fast, but temporarily needs extra GPU memory for the original plus quantized weights. If GPU memory is tight, drop `device_map` and call `pipeline.to("cuda")` after loading: + +```py +pipe = ZImagePipeline.from_pretrained( + "Tongyi-MAI/Z-Image-Turbo", + quantization_config=quantization_config, + torch_dtype=torch.bfloat16, +) +pipe.to("cuda") +``` + +Without `device_map`, the layers are quantized on the CPU, which is slower but avoids the temporary GPU-memory spike. + +## Speed, memory, and quality trade-offs + +Lower target rates save memory but cost reconstruction quality. The entropy-coded (`default`) path reconstructs weights on every forward, adding a per-step decode overhead (within ~10% of bf16 on the setup below); the `fp8`/`int8` paths decode 8-bit codes and run low-precision tensor-core GEMMs, which can be faster than bf16 at some quality cost. Measured on Z-Image-Turbo (single H20, 1024x1024, 8 steps, fixed seed; PSNR against the bf16 output): + +| config | PSNR vs bf16 | per-step latency | peak VRAM | +|---|---|---|---| +| bf16 | — | 536.8 ms | 21.69 GiB | +| `target_bpp=8.0` | 31.89 dB | 587.6 ms | 15.99 GiB | +| `target_bpp=4.0` | 21.61 dB | 576.6 ms | 13.01 GiB | +| `target_bpp=3.0` | 13.66 dB | 572.4 ms | 12.33 GiB | +| `target_bpp=4.0, linear_type="int8"` | 18.50 dB | 440.5 ms | 13.01 GiB | +| `target_bpp=4.0, linear_type="fp8"` | 23.46 dB | 460.0 ms | 13.01 GiB | + ## Save and reload Save an EntroPack model with [`~ModelMixin.save_pretrained`]. The packed weights are saved in safetensors format, and the EntroPack settings are included in `config.json`. @@ -133,7 +159,6 @@ Load the saved model without passing another [`EntroPackConfig`]. Diffusers read model = ZImageTransformer2DModel.from_pretrained( "zimage-entropack-4bpp", torch_dtype=torch.bfloat16, - device_map={"": "cuda"}, ) ``` diff --git a/setup.py b/setup.py index 83af4a0f6192..de1464be0e5d 100644 --- a/setup.py +++ b/setup.py @@ -133,7 +133,7 @@ "bitsandbytes>=0.43.3", "nvidia_modelopt[hf]>=0.33.1", "sdnq>=0.2.2", - "entropack>=0.1.8", + "entropack>=0.1.9", "regex!=2019.12.17", "requests", "tensorboard", diff --git a/src/diffusers/dependency_versions_table.py b/src/diffusers/dependency_versions_table.py index 32c5082864c1..86f4a727f0f9 100644 --- a/src/diffusers/dependency_versions_table.py +++ b/src/diffusers/dependency_versions_table.py @@ -40,7 +40,7 @@ "bitsandbytes": "bitsandbytes>=0.43.3", "nvidia_modelopt[hf]": "nvidia_modelopt[hf]>=0.33.1", "sdnq": "sdnq>=0.2.2", - "entropack": "entropack>=0.1.8", + "entropack": "entropack>=0.1.9", "regex": "regex!=2019.12.17", "requests": "requests", "tensorboard": "tensorboard", diff --git a/src/diffusers/quantizers/entropack/entropack_quantizer.py b/src/diffusers/quantizers/entropack/entropack_quantizer.py index 97735153d7a2..59bbdd6b6fc6 100644 --- a/src/diffusers/quantizers/entropack/entropack_quantizer.py +++ b/src/diffusers/quantizers/entropack/entropack_quantizer.py @@ -196,6 +196,6 @@ def is_trainable(self) -> bool: return True def _dequantize(self, model): - from .utils import _dequantize_and_replace + import entropack - return _dequantize_and_replace(model) + return entropack.dequantize_model(model) diff --git a/src/diffusers/quantizers/entropack/utils.py b/src/diffusers/quantizers/entropack/utils.py index 06657347490f..b5f614588594 100644 --- a/src/diffusers/quantizers/entropack/utils.py +++ b/src/diffusers/quantizers/entropack/utils.py @@ -108,27 +108,3 @@ def replace(module: nn.Module, prefix: str) -> None: ) return model - - -def _dequantize_and_replace(model: "ModelMixin") -> "ModelMixin": - import entropack - - for name, module in model.named_children(): - if isinstance(module, entropack.CompressedLinear): - device = module.weight.device - with torch.device("meta"): - new_module = nn.Linear( - module.in_features, - module.out_features, - bias=module.bias is not None, - dtype=module._init_dtype, - ) - new_module.weight = nn.Parameter( - module.dequantize(device).to(device=device, dtype=module._init_dtype), requires_grad=False - ) - if module.bias is not None: - new_module.bias = nn.Parameter(module.bias.data.to(device), requires_grad=False) - model._modules[name] = new_module - else: - _dequantize_and_replace(module) - return model From f9ddf4f5131ac407c13af5a7e1726ac4dbde0b00 Mon Sep 17 00:00:00 2001 From: mi804 <1576993271@qq.com> Date: Thu, 26 Nov 2026 16:27:53 +0800 Subject: [PATCH 4/6] move tests to tests/models/testing_utils/quantization.py and fix ci --- src/diffusers/quantizers/entropack/utils.py | 3 +- .../quantizers/quantization_config.py | 12 +- tests/models/testing_utils/__init__.py | 4 + tests/models/testing_utils/quantization.py | 158 +++++++++++++++ .../test_models_transformer_flux.py | 15 ++ .../test_models_transformer_z_image.py | 4 + tests/quantization/entropack/__init__.py | 0 .../quantization/entropack/test_entropack.py | 182 ------------------ tests/testing_utils.py | 8 + 9 files changed, 197 insertions(+), 189 deletions(-) delete mode 100644 tests/quantization/entropack/__init__.py delete mode 100644 tests/quantization/entropack/test_entropack.py diff --git a/src/diffusers/quantizers/entropack/utils.py b/src/diffusers/quantizers/entropack/utils.py index b5f614588594..bafb5b40ca01 100644 --- a/src/diffusers/quantizers/entropack/utils.py +++ b/src/diffusers/quantizers/entropack/utils.py @@ -31,7 +31,8 @@ if is_entropack_available(): import entropack - # present weights in the layer's compute dtype and decode codes directly from the packed header + # fp8 code dtype is floating-point, so the plain wrapper would leak it into model.dtype; + # keep the compute dtype and decode from the header instead of a per-step wrapper cast. class _CompressedFP8Linear(entropack.CompressedFP8Linear): def __setattr__(self, name, value): if name == "weight" and isinstance(value, nn.Parameter) and value.dtype == self.code_dtype: diff --git a/src/diffusers/quantizers/quantization_config.py b/src/diffusers/quantizers/quantization_config.py index 78759801b339..552dc2c52c02 100644 --- a/src/diffusers/quantizers/quantization_config.py +++ b/src/diffusers/quantizers/quantization_config.py @@ -1026,18 +1026,18 @@ class EntroPackConfig(QuantizationConfigMixin): linear_type (`str`, *optional*, defaults to `"default"`): Linear implementation to use. Choose from `"default"`, `"fp8"`, and `"int8"`. modules_to_not_convert (`list`, *optional*, default to `None`): - The list of modules to not quantize, useful for quantizing models that explicitly require to have - some modules left in their original precision. + The list of modules to not quantize, useful for quantizing models that explicitly require to have some + modules left in their original precision. entropack_lossy_config (`dict`, *optional*): Additional settings for the EntroPack lossy compression backend. `target_bpp` takes precedence over the value in this dictionary. use_convrot (`bool`, *optional*, defaults to `True`): For `linear_type="int8"`, rotate weights and activations with a block Hadamard rotation before - quantization. Ignored for other linear types. The flag is not stored in the packed weights, so it is - read back from `config.json` when reloading. + quantization. Ignored for other linear types. The flag is not stored in the packed weights, so it is read + back from `config.json` when reloading. convrot_groupsize (`int`, *optional*, defaults to 256): - Requested power-of-four rotation block size for `use_convrot`, reduced by factors of four until it - divides the layer's `in_features`. + Requested power-of-four rotation block size for `use_convrot`, reduced by factors of four until it divides + the layer's `in_features`. """ def __init__( diff --git a/tests/models/testing_utils/__init__.py b/tests/models/testing_utils/__init__.py index dabdd518e996..596936cdef28 100644 --- a/tests/models/testing_utils/__init__.py +++ b/tests/models/testing_utils/__init__.py @@ -37,6 +37,8 @@ BitsAndBytesCompileTesterMixin, BitsAndBytesConfigMixin, BitsAndBytesTesterMixin, + EntroPackConfigMixin, + EntroPackTesterMixin, GGUFCompileTesterMixin, GGUFConfigMixin, GGUFTesterMixin, @@ -74,6 +76,8 @@ "BitsAndBytesTesterMixin", "CacheTesterMixin", "ContextParallelTesterMixin", + "EntroPackConfigMixin", + "EntroPackTesterMixin", "ContextParallelAttentionBackendsTesterMixin", "TensorParallelTesterMixin", "TensorParallelNeuronTesterMixin", diff --git a/tests/models/testing_utils/quantization.py b/tests/models/testing_utils/quantization.py index dc4681f23ecc..2ce03fa34285 100644 --- a/tests/models/testing_utils/quantization.py +++ b/tests/models/testing_utils/quantization.py @@ -25,6 +25,7 @@ AutoRoundConfig, BFLQuantizationConfig, BitsAndBytesConfig, + EntroPackConfig, GGUFQuantizationConfig, NunchakuLiteQuantizationConfig, NVIDIAModelOptConfig, @@ -34,6 +35,7 @@ from diffusers.loaders.single_file_model import SINGLE_FILE_LOADABLE_CLASSES, _get_single_file_loadable_mapping_class from diffusers.utils.import_utils import ( is_bitsandbytes_available, + is_entropack_available, is_flashinfer_available, is_gguf_available, is_kernels_available, @@ -48,6 +50,7 @@ is_autoround, is_bfl, is_bitsandbytes, + is_entropack, is_gguf, is_modelopt, is_quantization, @@ -2116,3 +2119,158 @@ def test_bfl_torch_compile(self, config_name): @pytest.mark.parametrize("config_name", ["fp8r"], ids=["fp8r"]) def test_bfl_torch_compile_with_group_offload(self, config_name): self._test_torch_compile_with_group_offload(BFLConfigMixin.BFL_CONFIGS[config_name]) + + +class EntroPackConfigMixin: + """ + Base mixin providing EntroPack quantization config and model creation. + + Expected class attributes: + - model_class: The model class to test + - pretrained_model_name_or_path: Hub repository ID for the pretrained model + - pretrained_model_kwargs: (Optional) Dict of kwargs to pass to from_pretrained + """ + + ENTROPACK_CONFIGS = { + "default": {"target_bpp": 4.0}, + "int8": {"target_bpp": 4.0, "linear_type": "int8"}, + "fp8": {"target_bpp": 4.0, "linear_type": "fp8"}, + "int8_convrot_off": {"target_bpp": 4.0, "linear_type": "int8", "use_convrot": False}, + } + + def _create_quantized_model(self, config_kwargs, **extra_kwargs): + linear_type = config_kwargs.get("linear_type", "default") + if linear_type != "default" and torch_device != "cuda": + pytest.skip("W8A8 requires CUDA") + if linear_type == "int8" and torch.cuda.get_device_capability() < (8, 0): + pytest.skip("int8 W8A8 requires CUDA compute capability 8.0+") + if linear_type == "fp8" and torch.cuda.get_device_capability() < (8, 9): + pytest.skip("fp8 W8A8 requires CUDA compute capability 8.9+") + config = EntroPackConfig(**config_kwargs) + kwargs = getattr(self, "pretrained_model_kwargs", {}).copy() + kwargs["quantization_config"] = config + kwargs["device_map"] = str(torch_device) + kwargs.update(extra_kwargs) + return self.model_class.from_pretrained(self.pretrained_model_name_or_path, **kwargs) + + def _verify_if_layer_quantized(self, name, module, config_kwargs): + import entropack + + assert isinstance(module, entropack.CompressedLinear), ( + f"Layer {name} is {type(module)}, expected an entropack CompressedLinear" + ) + + +@is_entropack +@require_accelerator +@pytest.mark.skipif(not is_entropack_available(), reason="test requires entropack") +class EntroPackTesterMixin(EntroPackConfigMixin, QuantizationTesterMixin): + """ + Mixin class for testing EntroPack quantization on models. + + Expected class attributes: + - model_class: The model class to test + - pretrained_model_name_or_path: Hub repository ID for the pretrained model + - pretrained_model_kwargs: (Optional) Dict of kwargs to pass to from_pretrained + + Expected methods to be implemented by subclasses: + - get_dummy_inputs(): Returns dict of inputs to pass to the model forward pass + + Pytest mark: entropack + Use `pytest -m "not entropack"` to skip these tests + """ + + @pytest.mark.parametrize( + "config_name", + list(EntroPackConfigMixin.ENTROPACK_CONFIGS.keys()), + ids=list(EntroPackConfigMixin.ENTROPACK_CONFIGS.keys()), + ) + def test_entropack_quantization_num_parameters(self, config_name): + self._test_quantization_num_parameters(EntroPackConfigMixin.ENTROPACK_CONFIGS[config_name]) + + @pytest.mark.parametrize( + "config_name", + list(EntroPackConfigMixin.ENTROPACK_CONFIGS.keys()), + ids=list(EntroPackConfigMixin.ENTROPACK_CONFIGS.keys()), + ) + def test_entropack_quantization_memory_footprint(self, config_name): + self._test_quantization_memory_footprint( + EntroPackConfigMixin.ENTROPACK_CONFIGS[config_name], expected_memory_reduction=1.5 + ) + + @pytest.mark.parametrize( + "config_name", + list(EntroPackConfigMixin.ENTROPACK_CONFIGS.keys()), + ids=list(EntroPackConfigMixin.ENTROPACK_CONFIGS.keys()), + ) + def test_entropack_quantization_inference(self, config_name): + self._test_quantization_inference(EntroPackConfigMixin.ENTROPACK_CONFIGS[config_name]) + + @pytest.mark.parametrize( + "config_name", + list(EntroPackConfigMixin.ENTROPACK_CONFIGS.keys()), + ids=list(EntroPackConfigMixin.ENTROPACK_CONFIGS.keys()), + ) + def test_entropack_quantized_layers(self, config_name): + self._test_quantized_layers(EntroPackConfigMixin.ENTROPACK_CONFIGS[config_name]) + + @pytest.mark.parametrize( + "config_name", + list(EntroPackConfigMixin.ENTROPACK_CONFIGS.keys()), + ids=list(EntroPackConfigMixin.ENTROPACK_CONFIGS.keys()), + ) + def test_entropack_quantization_serialization(self, config_name, tmp_path): + self._test_quantization_serialization(EntroPackConfigMixin.ENTROPACK_CONFIGS[config_name], tmp_path) + + @pytest.mark.parametrize( + "config_name", + list(EntroPackConfigMixin.ENTROPACK_CONFIGS.keys()), + ids=list(EntroPackConfigMixin.ENTROPACK_CONFIGS.keys()), + ) + def test_entropack_quantization_sharded_serialization(self, config_name, tmp_path): + self._test_quantization_serialization( + EntroPackConfigMixin.ENTROPACK_CONFIGS[config_name], tmp_path, max_shard_size="16KB" + ) + + def test_entropack_modules_to_not_convert(self): + modules_to_exclude = getattr(self, "modules_to_not_convert_for_test", None) + if modules_to_exclude is None: + pytest.skip("modules_to_not_convert_for_test not defined for this model") + config_kwargs = { + **EntroPackConfigMixin.ENTROPACK_CONFIGS["default"], + "modules_to_not_convert": modules_to_exclude, + } + model = self._create_quantized_model(config_kwargs) + found_excluded = False + for name, module in model.named_modules(): + if isinstance(module, torch.nn.Linear) and any(excluded in name for excluded in modules_to_exclude): + found_excluded = True + assert not self._is_module_quantized(module), f"Module {name} should not be quantized" + assert found_excluded, f"No linear layers found in excluded modules: {modules_to_exclude}" + with torch.no_grad(): + output = model(**self.get_dummy_inputs(), return_dict=False)[0] + assert output is not None, "Model output is None" + assert not torch.isnan(output).any(), "Model output contains NaN" + + @pytest.mark.parametrize( + "config_name", + list(EntroPackConfigMixin.ENTROPACK_CONFIGS.keys()), + ids=list(EntroPackConfigMixin.ENTROPACK_CONFIGS.keys()), + ) + def test_entropack_dequantize(self, config_name): + self._test_dequantize(EntroPackConfigMixin.ENTROPACK_CONFIGS[config_name]) + + @pytest.mark.parametrize( + "config_name", ["int8", "fp8", "int8_convrot_off"], ids=["int8", "fp8", "int8_convrot_off"] + ) + def test_entropack_w8a8_state(self, config_name): + import entropack + + config_kwargs = EntroPackConfigMixin.ENTROPACK_CONFIGS[config_name] + model = self._create_quantized_model(config_kwargs) + layers = [m for m in model.modules() if isinstance(m, entropack.CompressedLinear)] + assert layers + assert all(m.weight_quant_scale.dtype == torch.float32 for m in layers) + if config_kwargs.get("linear_type") == "int8": + expected_convrot = config_kwargs.get("use_convrot", True) + assert all(m.use_convrot == expected_convrot for m in layers) diff --git a/tests/models/transformers/test_models_transformer_flux.py b/tests/models/transformers/test_models_transformer_flux.py index 827987cf47c8..459b78ff09d2 100644 --- a/tests/models/transformers/test_models_transformer_flux.py +++ b/tests/models/transformers/test_models_transformer_flux.py @@ -33,6 +33,7 @@ BitsAndBytesTesterMixin, ContextParallelAttentionBackendsTesterMixin, ContextParallelTesterMixin, + EntroPackTesterMixin, FasterCacheTesterMixin, FirstBlockCacheTesterMixin, GGUFCompileTesterMixin, @@ -390,6 +391,20 @@ def get_dummy_inputs(self): return {k: v.to(self.torch_dtype) if torch.is_floating_point(v) else v for k, v in inputs.items()} +class TestFluxTransformerEntroPack(FluxTransformerTesterConfig, EntroPackTesterMixin): + """EntroPack quantization tests for Flux Transformer.""" + + modules_to_not_convert_for_test = ["proj_out"] + + @property + def torch_dtype(self): + return torch.bfloat16 + + def get_dummy_inputs(self): + inputs = super().get_dummy_inputs() + return {k: v.to(self.torch_dtype) if torch.is_floating_point(v) else v for k, v in inputs.items()} + + class TestFluxTransformerTorchAo(FluxTransformerTesterConfig, TorchAoTesterMixin): """TorchAO quantization tests for Flux Transformer.""" diff --git a/tests/models/transformers/test_models_transformer_z_image.py b/tests/models/transformers/test_models_transformer_z_image.py index 1a6881c13126..907801472da2 100644 --- a/tests/models/transformers/test_models_transformer_z_image.py +++ b/tests/models/transformers/test_models_transformer_z_image.py @@ -223,6 +223,10 @@ def test_lokr_ai_toolkit_checkpoint(self): # TODO: Add pretrained_model_name_or_path once a tiny Z-Image model is available on the Hub # class TestZImageTransformerTorchAo(ZImageTransformerTesterConfig, TorchAoTesterMixin): + + +# TODO: Add pretrained_model_name_or_path once a tiny Z-Image model is available on the Hub +# class TestZImageTransformerEntroPack(ZImageTransformerTesterConfig, EntroPackTesterMixin): # """TorchAo quantization tests for Z-Image Transformer.""" diff --git a/tests/quantization/entropack/__init__.py b/tests/quantization/entropack/__init__.py deleted file mode 100644 index e69de29bb2d1..000000000000 diff --git a/tests/quantization/entropack/test_entropack.py b/tests/quantization/entropack/test_entropack.py deleted file mode 100644 index 38ee3bf573e3..000000000000 --- a/tests/quantization/entropack/test_entropack.py +++ /dev/null @@ -1,182 +0,0 @@ -import json - -import pytest -import torch -import torch.nn as nn - -from diffusers import EntroPackConfig, Transformer2DModel -from diffusers.quantizers.auto import DiffusersAutoQuantizer -from diffusers.utils import is_entropack_available - -from ...testing_utils import require_accelerate, require_torch, require_torch_accelerator - - -pytestmark = [ - pytest.mark.skipif(not is_entropack_available(), reason="test requires entropack"), - pytest.mark.skipif(not torch.cuda.is_available(), reason="test requires CUDA"), -] - - -def is_entropack_linear(module): - import entropack - - return isinstance(module, entropack.CompressedLinear) - - -def tiny_model() -> Transformer2DModel: - return Transformer2DModel( - in_channels=8, - num_attention_heads=2, - attention_head_dim=8, - cross_attention_dim=16, - num_layers=1, - norm_num_groups=2, - sample_size=8, - ).to(torch.bfloat16) - - -def model_inputs(device): - return ( - torch.randn(1, 8, 8, 8, dtype=torch.bfloat16, device=device), - torch.randn(1, 4, 16, dtype=torch.bfloat16, device=device), - ) - - -class TestEntroPackConfig: - def test_round_trip(self): - config = EntroPackConfig( - target_bpp=3.5, - linear_type="int8", - modules_to_not_convert=["to_q"], - entropack_lossy_config={"row_rdo_iterations": 1}, - use_convrot=False, - convrot_groupsize=64, - ) - serialized = json.loads(json.dumps(config.to_dict())) - restored = DiffusersAutoQuantizer.from_dict(serialized) - assert isinstance(restored, EntroPackConfig) - assert restored.to_dict() == config.to_dict() - - def test_invalid_values_are_rejected(self): - for kwargs in ( - {"target_bpp": 100.0}, - {"linear_type": "fp4"}, - {"linear_type": "fp8", "target_bpp": 8.0}, - {"linear_type": "int8", "convrot_groupsize": 8}, - {"linear_type": "int8", "convrot_groupsize": 3}, - ): - with pytest.raises(ValueError): - EntroPackConfig(**kwargs) - - -@require_torch -@require_accelerate -@require_torch_accelerator -class TestEntroPackQuantizer: - @pytest.mark.parametrize("linear_type", ["default", "int8", "fp8"]) - def test_online_quantize_save_reload(self, tmp_path, linear_type): - if linear_type == "fp8": - pytest.importorskip("entropack") - import entropack - - if torch.cuda.get_device_capability() < entropack.CompressedFP8Linear.min_capability: - pytest.skip("FP8 requires CUDA capability >= 8.9") - expected_cls = entropack.CompressedFP8Linear - elif linear_type == "int8": - import entropack - - if torch.cuda.get_device_capability() < entropack.CompressedINT8Linear.min_capability: - pytest.skip("INT8 requires CUDA capability >= 8.0") - expected_cls = entropack.CompressedINT8Linear - else: - import entropack - - expected_cls = entropack.CompressedLinear - - torch.manual_seed(0) - model = tiny_model() - model.save_pretrained(tmp_path / "base") - quantized = Transformer2DModel.from_pretrained( - tmp_path / "base", - quantization_config=EntroPackConfig(target_bpp=4.0, linear_type=linear_type), - torch_dtype=torch.bfloat16, - device_map={"": "cuda"}, - ) - layers = [(name, module) for name, module in quantized.named_modules() if is_entropack_linear(module)] - assert layers - assert all(isinstance(module, expected_cls) for _, module in layers) - if linear_type != "default": - assert all(module.weight_quant_scale.dtype == torch.float32 for _, module in layers) - if linear_type == "int8": - assert all(module.use_convrot for _, module in layers) - - x, encoder_hidden_states = model_inputs("cuda") - with torch.no_grad(): - output = quantized(x, encoder_hidden_states=encoder_hidden_states).sample - assert torch.isfinite(output).all() - - quantized.save_pretrained(tmp_path / "quantized", max_shard_size="1KB") - reloaded = Transformer2DModel.from_pretrained( - tmp_path / "quantized", - torch_dtype=torch.bfloat16, - device_map={"": "cuda"}, - ) - assert sum(is_entropack_linear(module) for module in reloaded.modules()) == len(layers) - with torch.no_grad(): - reloaded_output = reloaded(x, encoder_hidden_states=encoder_hidden_states).sample - torch.testing.assert_close(output, reloaded_output, rtol=0, atol=0) - - def test_int8_convrot_off_round_trip(self, tmp_path): - model = tiny_model() - model.save_pretrained(tmp_path / "base") - quantized = Transformer2DModel.from_pretrained( - tmp_path / "base", - quantization_config=EntroPackConfig(target_bpp=4.0, linear_type="int8", use_convrot=False), - torch_dtype=torch.bfloat16, - device_map={"": "cuda"}, - ) - layers = [m for m in quantized.modules() if is_entropack_linear(m)] - assert layers and not any(m.use_convrot for m in layers) - - x, encoder_hidden_states = model_inputs("cuda") - with torch.no_grad(): - output = quantized(x, encoder_hidden_states=encoder_hidden_states).sample - quantized.save_pretrained(tmp_path / "quantized", max_shard_size="1KB") - reloaded = Transformer2DModel.from_pretrained( - tmp_path / "quantized", torch_dtype=torch.bfloat16, device_map={"": "cuda"} - ) - assert not any(m.use_convrot for m in reloaded.modules() if is_entropack_linear(m)) - with torch.no_grad(): - reloaded_output = reloaded(x, encoder_hidden_states=encoder_hidden_states).sample - torch.testing.assert_close(output, reloaded_output, rtol=0, atol=0) - - def test_modules_to_not_convert_is_honoured(self, tmp_path): - model = tiny_model() - model.save_pretrained(tmp_path / "base") - quantized = Transformer2DModel.from_pretrained( - tmp_path / "base", - quantization_config=EntroPackConfig(target_bpp=4.0, modules_to_not_convert=["to_q"]), - torch_dtype=torch.bfloat16, - device_map={"": "cuda"}, - ) - attention = quantized.transformer_blocks[0].attn1 - assert type(attention.to_q) is nn.Linear - assert is_entropack_linear(attention.to_k) - - def test_dequantize_restores_linear_layers(self, tmp_path): - model = tiny_model() - model.save_pretrained(tmp_path / "base") - quantized = Transformer2DModel.from_pretrained( - tmp_path / "base", - quantization_config=EntroPackConfig(target_bpp=4.0, linear_type="int8"), - torch_dtype=torch.bfloat16, - device_map={"": "cuda"}, - ) - restored = quantized.dequantize() - assert not restored.is_quantized - assert not any(is_entropack_linear(module) for module in restored.modules()) - - x, encoder_hidden_states = model_inputs("cuda") - with torch.no_grad(): - output = restored(x, encoder_hidden_states=encoder_hidden_states).sample - assert torch.isfinite(output).all() diff --git a/tests/testing_utils.py b/tests/testing_utils.py index e5448a054d16..66eb0d9592b3 100644 --- a/tests/testing_utils.py +++ b/tests/testing_utils.py @@ -438,6 +438,14 @@ def is_torchao(test_case): return pytest.mark.torchao(test_case) +def is_entropack(test_case): + """ + Decorator marking a test as an EntroPack quantization test. These tests can be filtered using: + pytest -m "not entropack" to skip pytest -m entropack to run only these tests + """ + return pytest.mark.entropack(test_case) + + def is_gguf(test_case): """ Decorator marking a test as a GGUF quantization test. These tests can be filtered using: From 1c5a753652ad4dd74a7a5aaff05b30698e198fb5 Mon Sep 17 00:00:00 2001 From: mi804 <1576993271@qq.com> Date: Thu, 26 Nov 2026 20:30:02 +0800 Subject: [PATCH 5/6] add tiny zimage test --- .../test_models_transformer_z_image.py | 117 +++++++++++++++++- 1 file changed, 114 insertions(+), 3 deletions(-) diff --git a/tests/models/transformers/test_models_transformer_z_image.py b/tests/models/transformers/test_models_transformer_z_image.py index 907801472da2..cbac349c8498 100644 --- a/tests/models/transformers/test_models_transformer_z_image.py +++ b/tests/models/transformers/test_models_transformer_z_image.py @@ -26,6 +26,8 @@ AutoRoundCompileTesterMixin, AutoRoundTesterMixin, BaseModelTesterConfig, + EntroPackConfigMixin, + EntroPackTesterMixin, LoKrTesterMixin, LoraTesterMixin, MemoryTesterMixin, @@ -225,9 +227,118 @@ def test_lokr_ai_toolkit_checkpoint(self): # class TestZImageTransformerTorchAo(ZImageTransformerTesterConfig, TorchAoTesterMixin): -# TODO: Add pretrained_model_name_or_path once a tiny Z-Image model is available on the Hub -# class TestZImageTransformerEntroPack(ZImageTransformerTesterConfig, EntroPackTesterMixin): -# """TorchAo quantization tests for Z-Image Transformer.""" +class TestZImageTransformerEntroPack(ZImageTransformerTesterConfig, EntroPackTesterMixin): + """EntroPack quantization tests for Z-Image Transformer.""" + + modules_to_not_convert_for_test = ["to_q"] + + @property + def pretrained_model_name_or_path(self): + return "DiffSynth-Studio/tiny-random-z-image-transformer" + + @property + def pretrained_model_kwargs(self): + return {"subfolder": "transformer"} + + @property + def torch_dtype(self): + return torch.bfloat16 + + def get_dummy_inputs(self): + inputs = super().get_dummy_inputs() + return { + k: [t.to(self.torch_dtype) for t in v] if isinstance(v, list) else v.to(self.torch_dtype) + for k, v in inputs.items() + } + + @torch.no_grad() + def _test_quantization_inference(self, config_kwargs): + model_quantized = self._create_quantized_model(config_kwargs) + model_quantized.to(torch_device) + + inputs = self.get_dummy_inputs() + output = model_quantized(**inputs, return_dict=False)[0] + # Z-Image returns a list of tensors from unpatchify + output = output[0] if isinstance(output, (list, tuple)) else output + + assert output is not None, "Model output is None" + assert not torch.isnan(output).any(), "Model output contains NaN" + + @torch.no_grad() + def _test_quantization_serialization(self, config_kwargs, tmp_path, max_shard_size=None): + import gc + + from ...testing_utils import backend_empty_cache + + model = self._create_quantized_model(config_kwargs) + model.to(torch_device) + + inputs = self.get_dummy_inputs() + expected_output = model(**inputs, return_dict=False)[0] + expected_output = expected_output[0] if isinstance(expected_output, (list, tuple)) else expected_output + expected_output = expected_output.detach().cpu() + + if max_shard_size == "auto": + max_shard_size = max(int(model.get_memory_footprint() // 2), 1) + + save_kwargs = {"safe_serialization": True} + if max_shard_size is not None: + save_kwargs["max_shard_size"] = max_shard_size + model.save_pretrained(str(tmp_path), **save_kwargs) + + del model + gc.collect() + backend_empty_cache(torch_device) + + if max_shard_size is not None: + assert len(list(tmp_path.glob("*.safetensors"))) > 1, "Expected a sharded safe-serialization checkpoint." + assert any(path.name.endswith(".index.json") for path in tmp_path.iterdir()), ( + "Expected an index file for sharded safe checkpoint." + ) + + model_loaded = self.model_class.from_pretrained(str(tmp_path), device_map=str(torch_device)) + + output = model_loaded(**inputs, return_dict=False)[0] + output = output[0] if isinstance(output, (list, tuple)) else output + assert_tensors_close(output.detach().cpu(), expected_output, rtol=1e-3, atol=1e-3) + + @torch.no_grad() + def _test_dequantize(self, config_kwargs): + model = self._create_quantized_model(config_kwargs) + model.to(torch_device) + + model.dequantize() + + for name, module in model.named_modules(): + if isinstance(module, torch.nn.Linear): + assert not self._is_module_quantized(module, config_kwargs), ( + f"Module {name} is still quantized after dequantize()" + ) + + inputs = self.get_dummy_inputs() + output = model(**inputs, return_dict=False)[0] + output = output[0] if isinstance(output, (list, tuple)) else output + assert output is not None, "Model output is None after dequantization" + assert not torch.isnan(output).any(), "Model output contains NaN after dequantization" + + def test_entropack_modules_to_not_convert(self): + modules_to_exclude = self.modules_to_not_convert_for_test + config_kwargs = { + **EntroPackConfigMixin.ENTROPACK_CONFIGS["default"], + "modules_to_not_convert": modules_to_exclude, + } + model = self._create_quantized_model(config_kwargs) + found_excluded = False + for name, module in model.named_modules(): + if isinstance(module, torch.nn.Linear) and any(excluded in name for excluded in modules_to_exclude): + found_excluded = True + assert not self._is_module_quantized(module), f"Module {name} should not be quantized" + assert found_excluded, f"No linear layers found in excluded modules: {modules_to_exclude}" + with torch.no_grad(): + output = model(**self.get_dummy_inputs(), return_dict=False)[0] + output = output[0] if isinstance(output, (list, tuple)) else output + assert output is not None, "Model output is None" + assert not torch.isnan(output).any(), "Model output contains NaN" class TestZImageTransformerCompile(ZImageTransformerTesterConfig, TorchCompileTesterMixin): From 24ffce457682ba8fbf512784132405baaef8d345 Mon Sep 17 00:00:00 2001 From: mi804 <1576993271@qq.com> Date: Fri, 27 Nov 2026 18:01:03 +0800 Subject: [PATCH 6/6] add comments for test overrides and sharded skip; move imports to top --- tests/models/testing_utils/quantization.py | 3 +++ .../transformers/test_models_transformer_z_image.py | 9 ++++----- 2 files changed, 7 insertions(+), 5 deletions(-) diff --git a/tests/models/testing_utils/quantization.py b/tests/models/testing_utils/quantization.py index 2ce03fa34285..96bd3714672f 100644 --- a/tests/models/testing_utils/quantization.py +++ b/tests/models/testing_utils/quantization.py @@ -2222,6 +2222,9 @@ def test_entropack_quantized_layers(self, config_name): def test_entropack_quantization_serialization(self, config_name, tmp_path): self._test_quantization_serialization(EntroPackConfigMixin.ENTROPACK_CONFIGS[config_name], tmp_path) + # The generic sharded test sizes shards from get_memory_footprint() // 2; EntroPack's footprint + # reports the dense wrapper view rather than the packed bytes, so "auto" yields a single shard. + # Multi-shard reload is covered here with a fixed shard size instead. @pytest.mark.parametrize( "config_name", list(EntroPackConfigMixin.ENTROPACK_CONFIGS.keys()), diff --git a/tests/models/transformers/test_models_transformer_z_image.py b/tests/models/transformers/test_models_transformer_z_image.py index cbac349c8498..05664bb9c1a1 100644 --- a/tests/models/transformers/test_models_transformer_z_image.py +++ b/tests/models/transformers/test_models_transformer_z_image.py @@ -12,6 +12,7 @@ # See the License for the specific language governing permissions and # limitations under the License. +import gc import os import pytest @@ -21,7 +22,7 @@ from diffusers.loaders.lora_pipeline import ZImageLoraLoaderMixin from diffusers.utils.torch_utils import randn_tensor -from ...testing_utils import assert_tensors_close, torch_device +from ...testing_utils import assert_tensors_close, backend_empty_cache, torch_device from ..testing_utils import ( AutoRoundCompileTesterMixin, AutoRoundTesterMixin, @@ -251,6 +252,8 @@ def get_dummy_inputs(self): for k, v in inputs.items() } + # Z-Image's forward returns a list of per-sample tensors, while the common quantization helpers + # assert on a single tensor; override them here to unwrap the list instead of changing the shared helpers. @torch.no_grad() def _test_quantization_inference(self, config_kwargs): model_quantized = self._create_quantized_model(config_kwargs) @@ -266,10 +269,6 @@ def _test_quantization_inference(self, config_kwargs): @torch.no_grad() def _test_quantization_serialization(self, config_kwargs, tmp_path, max_shard_size=None): - import gc - - from ...testing_utils import backend_empty_cache - model = self._create_quantized_model(config_kwargs) model.to(torch_device)