diff --git a/docs/source/en/_toctree.yml b/docs/source/en/_toctree.yml index 21fc98873713..7196c5c75dc7 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..bfc9f588fa41 --- /dev/null +++ b/docs/source/en/quantization/entropack.md @@ -0,0 +1,173 @@ + + +# 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.9 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, +) +``` + +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, + device_map="cuda", +) +image = pipe( + prompt="A cat holding a sign that says hello world", + num_inference_steps=8, + guidance_scale=0.0, +).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`. + +```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, +) +``` + +## 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..de1464be0e5d 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.9", "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 b5f3134e42da..a021e8f2dcf6 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", @@ -1036,6 +1038,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..86f4a727f0f9 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.9", "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..59bbdd6b6fc6 --- /dev/null +++ b/src/diffusers/quantizers/entropack/entropack_quantizer.py @@ -0,0 +1,201 @@ +# 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 + + if self.pre_quantized: + module.weight = nn.Parameter(param_value.to(target_device), requires_grad=False) + else: + module.compress_weight(param_value.detach().to(target_device)) + + 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): + import entropack + + return entropack.dequantize_model(model) diff --git a/src/diffusers/quantizers/entropack/utils.py b/src/diffusers/quantizers/entropack/utils.py new file mode 100644 index 000000000000..bafb5b40ca01 --- /dev/null +++ b/src/diffusers/quantizers/entropack/utils.py @@ -0,0 +1,111 @@ +# 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_entropack_available, is_torch_available, logging + + +if TYPE_CHECKING: + from ...models.modeling_utils import ModelMixin + + +if is_torch_available(): + import torch + import torch.nn as nn + + +if is_entropack_available(): + import entropack + + # 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: + 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__) + + +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": _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 diff --git a/src/diffusers/quantizers/quantization_config.py b/src/diffusers/quantizers/quantization_config.py index 8d7c0c343b19..552dc2c52c02 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/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 f2f4d92fd913..8d9203cb8f3b 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_lora, is_modelopt, @@ -2122,3 +2125,161 @@ 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) + + # 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()), + 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 d4801e214436..b8c9cd662d63 100644 --- a/tests/models/transformers/test_models_transformer_flux.py +++ b/tests/models/transformers/test_models_transformer_flux.py @@ -34,6 +34,7 @@ BitsAndBytesTesterMixin, ContextParallelAttentionBackendsTesterMixin, ContextParallelTesterMixin, + EntroPackTesterMixin, FasterCacheTesterMixin, FirstBlockCacheTesterMixin, GGUFCompileTesterMixin, @@ -414,6 +415,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..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,11 +22,13 @@ 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, BaseModelTesterConfig, + EntroPackConfigMixin, + EntroPackTesterMixin, LoKrTesterMixin, LoraTesterMixin, MemoryTesterMixin, @@ -223,7 +226,118 @@ 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): -# """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() + } + + # 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) + 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): + 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): 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: