diff --git a/.github/workflows/nightly_tests.yml b/.github/workflows/nightly_tests.yml index 79c825514231..20f68fd6903a 100644 --- a/.github/workflows/nightly_tests.yml +++ b/.github/workflows/nightly_tests.yml @@ -366,6 +366,9 @@ jobs: - backend: "torchao" marker: "torchao" additional_deps: ["mslk"] + - backend: "comfy-kitchen" + marker: "comfy" + additional_deps: [] - backend: "nvidia_modelopt" marker: "modelopt" additional_deps: [] diff --git a/docs/source/en/_toctree.yml b/docs/source/en/_toctree.yml index 7196c5c75dc7..1c3a1572e3b0 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/comfy + title: Comfy Quantization - local: quantization/entropack title: EntroPack - local: quantization/gguf diff --git a/docs/source/en/api/quantization.md b/docs/source/en/api/quantization.md index 43de7f62cb1c..5df94be2528d 100644 --- a/docs/source/en/api/quantization.md +++ b/docs/source/en/api/quantization.md @@ -38,6 +38,13 @@ Quantization techniques reduce memory and computational costs by representing we [[autodoc]] quantizers.quantization_config.GGUFQuantizationConfig +## ComfyQuantizationConfig + +Load prequantized single-file checkpoints with Comfy-Kitchen. See the [Comfy quantization guide](../quantization/comfy) +for usage, validated formats, and checkpoint limitations. + +[[autodoc]] quantizers.quantization_config.ComfyQuantizationConfig + ## NunchakuLiteQuantizationConfig [[autodoc]] quantizers.quantization_config.NunchakuLiteQuantizationConfig diff --git a/docs/source/en/quantization/comfy.md b/docs/source/en/quantization/comfy.md new file mode 100644 index 000000000000..47012847f81f --- /dev/null +++ b/docs/source/en/quantization/comfy.md @@ -0,0 +1,84 @@ + + +# Comfy Quantization + +[Comfy Quants](https://github.com/Comfy-Org/comfy-quants) exports prequantized checkpoints with per-layer +quantization metadata. Diffusers reads each layer's format and uses +[Comfy-Kitchen](https://github.com/Comfy-Org/comfy-kitchen) for inference. A checkpoint can mix quantization +formats and floating-point layers. + +Install the optional dependencies: + +```bash +pip install "comfy-kitchen>=0.2.41" accelerate +``` + +## Load a checkpoint + +Pass [`ComfyQuantizationConfig`] to `from_single_file`. Set `compute_dtype` to BF16 or FP16; the checkpoint +determines the quantization format of each layer. + +```python +import torch +from diffusers import ComfyQuantizationConfig, ZImagePipeline, ZImageTransformer2DModel + +transformer = ZImageTransformer2DModel.from_single_file( + "https://huggingface.co/Comfy-Org/Z-Image-Turbo/blob/main/split_files/diffusion_models/z_image_turbo_int8_convrot.safetensors", + config="Tongyi-MAI/Z-Image-Turbo", + subfolder="transformer", + quantization_config=ComfyQuantizationConfig(compute_dtype=torch.bfloat16), +) +pipe = ZImagePipeline.from_pretrained( + "Tongyi-MAI/Z-Image-Turbo", transformer=transformer, dtype=torch.bfloat16 +) +pipe.enable_model_cpu_offload() +image = pipe( + "A small orange cat sitting on a mossy stone wall in a mountain village", + height=1024, + width=1024, + num_inference_steps=8, + guidance_scale=0.0, + generator=torch.Generator("cpu").manual_seed(0), +).images[0] +``` + +## Validated formats + +The quantizer reads each layer's uint8 JSON `comfy_quant` marker and bundles the packed weight with its scales and other sidecar tensors before checkpoint conversion. + + +| Marker `format` | Stored weights | Associated tensors | +| --- | --- | --- | +| `float8_e4m3fn`, `float8_e5m2` | FP8 | Weight scale, optional activation scale | +| `int8_tensorwise` | INT8 | Scalar or row scales, optional ConvRot metadata | +| `mxfp8` | FP8 | E8M0 block scales | +| `convrot_w4a4` | Packed INT4 | Row scales and rotation metadata | +| `asym_w4a8_int8`, `w6a8_int8` | Packed INT4 or INT6 | Group and channel scales, optional codebook and correction | + +Checkpoint converters retain their usual weight splitting and concatenation. The quantized tensor keeps row +and block scales aligned without dequantizing the stored weights. Concatenation requires compatible +layouts and shared metadata. Input-feature splitting is unsupported. + +One `ComfyLinear` dispatches through the weight's Kitchen layout. Layers marked `full_precision_matrix_mult` +use dequantized matrix multiplication. Unquantized layers use the compute dtype, and model FP32 exclusions +receive dequantized FP32 weights. + +Kitchen selects an available execution backend. Hardware requirements differ by format; loading a checkpoint +does not guarantee native quantized acceleration on the current device. + +### INT8 ConvRot + +[ConvRot](https://arxiv.org/abs/2512.03673) rotates weights offline and activations at inference time to spread +activation outliers. Native `int8_tensorwise` checkpoints retain INT8 weights and FP32 scales. Rotated layers +include `convrot` and `convrot_groupsize` metadata. Both rotated and unrotated INT8 layers are supported. diff --git a/setup.py b/setup.py index de1464be0e5d..35d6ef9866b7 100644 --- a/setup.py +++ b/setup.py @@ -128,6 +128,7 @@ "onnx", "optimum_quanto>=0.2.6", "gguf>=0.10.0", + "comfy-kitchen>=0.2.41", "auto-round>=0.13.0", "torchao>=0.15.0", "bitsandbytes>=0.43.3", @@ -249,6 +250,7 @@ def run(self): extras["bitsandbytes"] = deps_list("bitsandbytes", "accelerate") extras["gguf"] = deps_list("gguf", "accelerate") +extras["comfy"] = deps_list("comfy-kitchen", "accelerate") extras["optimum_quanto"] = deps_list("optimum_quanto", "accelerate") extras["torchao"] = deps_list("torchao", "accelerate") extras["nvidia_modelopt"] = deps_list("nvidia_modelopt[hf]") diff --git a/src/diffusers/__init__.py b/src/diffusers/__init__.py index a021e8f2dcf6..4690e8bd197f 100644 --- a/src/diffusers/__init__.py +++ b/src/diffusers/__init__.py @@ -148,6 +148,18 @@ else: _import_structure["quantizers.quantization_config"].append("BFLQuantizationConfig") +try: + if not is_torch_available(): + raise OptionalDependencyNotAvailable() +except OptionalDependencyNotAvailable: + from .utils import dummy_comfy_objects + + _import_structure["utils.dummy_comfy_objects"] = [ + name for name in dir(dummy_comfy_objects) if not name.startswith("_") + ] +else: + _import_structure["quantizers.quantization_config"].append("ComfyQuantizationConfig") + try: if not is_auto_round_available(): raise OptionalDependencyNotAvailable() @@ -615,10 +627,10 @@ "PAN2SafetyChecker", "PH3ImageBlocks", "PH3ImageModularPipeline", - "PImageOSSBlocks", - "PImageOSSModularPipeline", "PikaH3FlexBlocks", "PikaH3FlexModularPipeline", + "PImageOSSBlocks", + "PImageOSSModularPipeline", "QwenImage21AutoBlocks", "QwenImage21ModularPipeline", "QwenImage21TurboAutoBlocks", @@ -1088,6 +1100,14 @@ else: from .quantizers.quantization_config import BFLQuantizationConfig + try: + if not is_torch_available(): + raise OptionalDependencyNotAvailable() + except OptionalDependencyNotAvailable: + from .utils.dummy_comfy_objects import * + else: + from .quantizers.quantization_config import ComfyQuantizationConfig + try: if not is_auto_round_available(): raise OptionalDependencyNotAvailable() diff --git a/src/diffusers/dependency_versions_table.py b/src/diffusers/dependency_versions_table.py index 86f4a727f0f9..08692bbc4791 100644 --- a/src/diffusers/dependency_versions_table.py +++ b/src/diffusers/dependency_versions_table.py @@ -35,6 +35,7 @@ "onnx": "onnx", "optimum_quanto": "optimum_quanto>=0.2.6", "gguf": "gguf>=0.10.0", + "comfy-kitchen": "comfy-kitchen>=0.2.41", "auto-round": "auto-round>=0.13.0", "torchao": "torchao>=0.15.0", "bitsandbytes": "bitsandbytes>=0.43.3", diff --git a/src/diffusers/quantizers/auto.py b/src/diffusers/quantizers/auto.py index 5f5d34806e91..7c00838720bc 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 .comfy import ComfyQuantizer from .entropack import EntroPackQuantizer from .gguf import GGUFQuantizer from .modelopt import NVIDIAModelOptQuantizer @@ -29,6 +30,7 @@ AutoRoundConfig, BFLQuantizationConfig, BitsAndBytesConfig, + ComfyQuantizationConfig, EntroPackConfig, GGUFQuantizationConfig, NunchakuLiteQuantizationConfig, @@ -45,6 +47,7 @@ AUTO_QUANTIZER_MAPPING = { + "comfy": ComfyQuantizer, "bfl": BFLQuantizer, "bitsandbytes_4bit": BnB4BitDiffusersQuantizer, "bitsandbytes_8bit": BnB8BitDiffusersQuantizer, @@ -59,6 +62,7 @@ } AUTO_QUANTIZATION_CONFIG_MAPPING = { + "comfy": ComfyQuantizationConfig, "bfl": BFLQuantizationConfig, "bitsandbytes_4bit": BitsAndBytesConfig, "bitsandbytes_8bit": BitsAndBytesConfig, diff --git a/src/diffusers/quantizers/comfy/__init__.py b/src/diffusers/quantizers/comfy/__init__.py new file mode 100644 index 000000000000..5767537ba2d1 --- /dev/null +++ b/src/diffusers/quantizers/comfy/__init__.py @@ -0,0 +1,15 @@ +# 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 .comfy_quantizer import ComfyQuantizer diff --git a/src/diffusers/quantizers/comfy/comfy_quantizer.py b/src/diffusers/quantizers/comfy/comfy_quantizer.py new file mode 100644 index 000000000000..78e6b32ed93f --- /dev/null +++ b/src/diffusers/quantizers/comfy/comfy_quantizer.py @@ -0,0 +1,252 @@ +# 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. + +import dataclasses +import json + +from ...utils import get_module_from_name, is_accelerate_available, is_comfy_kitchen_available, is_torch_available +from ..base import DiffusersQuantizer + + +if is_torch_available(): + import torch + from torch import nn + + COMFY_FORMATS = { + "float8_e4m3fn": ("TensorCoreFP8Layout", torch.float8_e4m3fn, 8), + "float8_e5m2": ("TensorCoreFP8Layout", torch.float8_e5m2, 8), + "int8_tensorwise": ("TensorWiseINT8Layout", torch.int8, 8), + "nvfp4": ("TensorCoreNVFP4Layout", torch.uint8, 4), + "mxfp8": ("TensorCoreMXFP8Layout", torch.float8_e4m3fn, 8), + "awq_w4a16": ("TensorCoreAWQW4A16Layout", torch.int8, 4), + "svdquant_w4a4": ("TensorCoreSVDQuantW4A4Layout", torch.int8, 4), + "convrot_w4a4": ("TensorCoreConvRotW4A4Layout", torch.int8, 4), + "asym_w4a8_int8": ("AsymW4A8Int8Layout", torch.int8, 4), + "w6a8_int8": ("AsymW4A8Int8Layout", torch.int8, 6), + } + +if is_torch_available() and is_comfy_kitchen_available(): + from comfy_kitchen.tensor import get_layout_class + + from .utils import ComfyLinear, ComfyQuantizedTensor, _dequantize_comfy_and_restore_linear + + +PADDED_LAYOUTS = ("TensorCoreNVFP4Layout", "TensorCoreMXFP8Layout") + + +class ComfyQuantizer(DiffusersQuantizer): + use_keep_in_fp32_modules = True + + def __init__(self, quantization_config, **kwargs): + super().__init__(quantization_config, **kwargs) + self.compute_dtype = quantization_config.compute_dtype + self.pre_quantized = True + self.keep_in_fp32_modules = [] + + def validate_environment(self, *args, **kwargs): + if not is_accelerate_available(): + raise ImportError("Loading Comfy checkpoints requires accelerate: `pip install accelerate`.") + if not is_comfy_kitchen_available(): + raise ImportError("Comfy inference requires comfy-kitchen: `pip install 'comfy-kitchen>=0.2.41'`.") + + def update_torch_dtype(self, torch_dtype): + if torch_dtype is not None and torch_dtype != self.compute_dtype: + raise ValueError("`dtype` must match ComfyQuantizationConfig.compute_dtype.") + return self.compute_dtype + + def maybe_update_state_dict(self, state_dict): + marker_keys = [key for key in state_dict if key.endswith(".comfy_quant")] + if not marker_keys: + raise ValueError("The checkpoint has no native Comfy quantization markers.") + for key in marker_keys: + prefix = key.removesuffix(".comfy_quant") + payload = state_dict.pop(key) + if payload.dtype != torch.uint8 or payload.ndim != 1: + raise ValueError(f"{key} must be a one-dimensional uint8 JSON marker.") + try: + marker = json.loads(bytes(payload.tolist())) + except (ValueError, UnicodeDecodeError) as exc: + raise ValueError(f"{key} is not valid JSON.") from exc + if not isinstance(marker, dict) or marker.get("format") not in COMFY_FORMATS: + raise ValueError(f"{key} must declare a supported Comfy format: {list(COMFY_FORMATS)}.") + quant_format = marker["format"] + layout_name, storage_dtype, bits = COMFY_FORMATS[quant_format] + if f"{prefix}.weight" not in state_dict: + raise ValueError(f"{prefix} requires weight.") + weight = state_dict[f"{prefix}.weight"] + if weight.dtype != storage_dtype or weight.ndim not in (2, 4): + raise ValueError(f"{prefix}.weight has an invalid shape or dtype for {quant_format}.") + if weight.ndim == 4: + if quant_format != "svdquant_w4a4" or tuple(weight.shape[2:]) != (32, 128): + raise ValueError(f"{prefix}.weight has an invalid tile-packed layout.") + shape = (weight.shape[0] * 128, weight.shape[1] * 64) + else: + if weight.shape[1] * 8 % bits: + raise ValueError(f"{prefix}.weight has an invalid packed input width.") + shape = (weight.shape[0], weight.shape[1] * 8 // bits) + + def pop_tensor(suffix, dtype=None): + name = f"{prefix}.{suffix}" + if name not in state_dict: + raise ValueError(f"{prefix} requires {suffix}.") + value = state_dict.pop(name) + return value.view(dtype) if dtype is not None else value + + if not isinstance(marker.get("params", {}), dict): + raise ValueError(f"{key}.params must be an object.") + options = {**marker.get("params", {}), **marker} + params = {"orig_dtype": self.compute_dtype, "orig_shape": shape} + if quant_format == "nvfp4": + params.update( + scale=pop_tensor("weight_scale_2"), block_scale=pop_tensor("weight_scale", torch.float8_e4m3fn) + ) + elif quant_format == "mxfp8": + params["scale"] = pop_tensor("weight_scale", torch.float8_e8m0fnu) + elif quant_format in ("asym_w4a8_int8", "w6a8_int8"): + params.update( + scale=pop_tensor("weight_s_rel", torch.float8_e4m3fn), + s_channel=pop_tensor("weight_s_channel"), + codebook=state_dict.pop(f"{prefix}.weight_codebook", None), + correction=state_dict.pop(f"{prefix}.weight_correction", None), + group_size=options.get("group_size", 16), + convrot_groupsize=options.get("convrot_groupsize", 256), + ) + else: + params["scale"] = pop_tensor("weight_scale") + if quant_format == "int8_tensorwise": + scale = params["scale"] + rows, columns = shape + if scale.dtype != torch.float32 or tuple(scale.shape) not in ((), (1,), (rows,), (rows, 1)): + raise ValueError(f"{prefix}.weight_scale must be FP32 with a scalar or per-output-row shape.") + if not torch.isfinite(scale).all() or not (scale > 0).all(): + raise ValueError(f"{prefix}.weight_scale must contain finite positive values.") + convrot = options.get("convrot", False) + group_size = options.get("convrot_groupsize", 256) + if not isinstance(convrot, bool): + raise ValueError(f"{prefix}.convrot must be a boolean.") + if convrot: + if ( + type(group_size) is not int + or group_size < 4 + or group_size & (group_size - 1) + or (group_size.bit_length() - 1) % 2 + ): + raise ValueError(f"{prefix}.convrot_groupsize must be a power of four, at least 4.") + if columns % group_size or scale.numel() != rows: + raise ValueError(f"{prefix} requires group-aligned input features and per-output-row scales.") + params.update(convrot=convrot, convrot_groupsize=group_size) + if scale.numel() > 1: + params["scale"] = scale.reshape(rows, 1) + elif quant_format == "awq_w4a16": + params.update(zeros=pop_tensor("weight_zero"), group_size=options.get("group_size", 64)) + elif quant_format == "svdquant_w4a4": + params.update( + proj_down=pop_tensor("proj_down"), + proj_up=pop_tensor("proj_up"), + smooth_factor=pop_tensor("smooth_factor"), + act_unsigned=options.get("act_unsigned", False), + ) + elif quant_format == "convrot_w4a4": + params.update( + convrot_groupsize=options.get("convrot_groupsize", 256), + linear_dtype=options.get("linear_dtype", "int4"), + ) + layout = get_layout_class(layout_name) + state_dict[f"{prefix}.weight"] = ComfyQuantizedTensor( + weight, + layout_name, + layout.Params(**params), + comfy_quant=marker, + input_scale=state_dict.pop(f"{prefix}.input_scale", None), + pre_quant_scale=state_dict.pop(f"{prefix}.pre_quant_scale", None), + ) + unmarked = [ + key + for key, value in state_dict.items() + if key.endswith(".weight") and value.dtype in {value[1] for value in COMFY_FORMATS.values()} + ] + if unmarked: + raise ValueError(f"Quantized weights require native Comfy quantization markers: {unmarked}.") + return state_dict + + def _process_model_before_weight_loading( + self, model, device_map, state_dict=None, keep_in_fp32_modules=(), **kwargs + ): + if state_dict is None: + raise ValueError("Comfy checkpoints must be loaded with from_single_file().") + self.keep_in_fp32_modules = [name for name in keep_in_fp32_modules if name is not None] + for prefix, module in list(model.named_modules()): + weight = state_dict.get(f"{prefix}.weight") + if not isinstance(weight, ComfyQuantizedTensor): + continue + if not isinstance(module, nn.Linear): + raise ValueError(f"{prefix} does not match a Linear layer with shape {tuple(weight.shape)}.") + shape = (module.out_features, module.in_features) + storage_shape = shape + if weight._layout_cls in PADDED_LAYOUTS: + storage_shape = get_layout_class(weight._layout_cls).get_padded_shape(shape) + if tuple(weight.shape) != storage_shape or (weight.rows_rearranged and storage_shape[0] != shape[0]): + raise ValueError(f"{prefix} does not match a Linear layer with shape {tuple(weight.shape)}.") + if storage_shape != shape: + weight = ComfyQuantizedTensor( + weight._qdata, + weight._layout_cls, + dataclasses.replace(weight.params, orig_shape=shape), + weight.comfy_quant, + weight.input_scale, + weight.pre_quant_scale, + ) + state_dict[f"{prefix}.weight"] = weight + if any(name in prefix.split(".") for name in self.keep_in_fp32_modules): + continue + parent, name = get_module_from_name(model, prefix) + linear = ComfyLinear( + module.in_features, + module.out_features, + bias=module.bias is not None, + device="meta", + dtype=self.compute_dtype, + ) + linear.bias = module.bias + setattr(parent, name, linear) + + def check_if_quantized_param(self, model, param_value, param_name, state_dict, **kwargs): + return isinstance(param_value, ComfyQuantizedTensor) + + def create_quantized_param( + self, model, param_value, param_name, target_device, state_dict, unexpected_keys=None, **kwargs + ): + module, name = get_module_from_name(model, param_name) + if isinstance(module, ComfyLinear): + value = param_value.to(target_device) + else: + value = param_value.to(torch.float32).dequantize().to(target_device) + module._parameters[name] = nn.Parameter(value, requires_grad=False) + + def _process_model_after_weight_loading(self, model, **kwargs): + missing = [name for name, tensor in model.state_dict().items() if tensor.is_meta] + if missing: + raise ValueError(f"The Comfy checkpoint is missing model tensors: {missing}.") + return model + + def _dequantize(self, model): + return _dequantize_comfy_and_restore_linear(model) + + @property + def is_serializable(self): + return False + + @property + def is_trainable(self): + return False diff --git a/src/diffusers/quantizers/comfy/utils.py b/src/diffusers/quantizers/comfy/utils.py new file mode 100644 index 000000000000..6f5f2da5e4b2 --- /dev/null +++ b/src/diffusers/quantizers/comfy/utils.py @@ -0,0 +1,286 @@ +# 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. + +import dataclasses +import math + +import torch +from torch import nn +from torch.nn import functional as F + +from ...utils import is_accelerate_available, is_comfy_kitchen_available + + +if is_accelerate_available(): + from accelerate.hooks import add_hook_to_module, remove_hook_from_module + +if is_comfy_kitchen_available(): + from comfy_kitchen.float_utils import from_blocked, to_blocked + from comfy_kitchen.tensor import QuantizedTensor + + class ComfyQuantizedTensor(QuantizedTensor): + """Packed Comfy weights whose sidecar tensors follow checkpoint row conversions.""" + + def __new__( + cls, + qdata, + layout_cls, + params, + comfy_quant=None, + input_scale=None, + pre_quant_scale=None, + shape=None, + rows_rearranged=False, + ): + return torch.Tensor._make_wrapper_subclass( + cls, + shape or params.orig_shape, + device=qdata.device, + dtype=params.orig_dtype, + requires_grad=False, + ) + + def __init__( + self, + qdata, + layout_cls, + params, + comfy_quant=None, + input_scale=None, + pre_quant_scale=None, + shape=None, + rows_rearranged=False, + ): + super().__init__(qdata, layout_cls, params) + self.comfy_quant = comfy_quant or {} + self.input_scale = input_scale + self.pre_quant_scale = pre_quant_scale + self.rows_rearranged = rows_rearranged + + def _copy_with(self, qdata=None, params=None, clone_params=True): + if params is None: + params = self.params.clone() if clone_params else self.params + data = self._qdata if qdata is None else qdata + input_scale, pre_quant_scale = ( + None if value is None else value.to(device=data.device).clone() + for value in (self.input_scale, self.pre_quant_scale) + ) + return type(self)( + data, + self._layout_cls, + params, + self.comfy_quant.copy(), + input_scale, + pre_quant_scale, + tuple(self.shape), + self.rows_rearranged, + ) + + def dequantize(self): + return super().dequantize().reshape(self.shape) + + def _row_components(self): + rows, columns = self.params.orig_shape + data = self._qdata + fields = {} + layout = self._layout_cls + if layout == "TensorCoreNVFP4Layout": + fields["block_scale"] = (from_blocked(self.params.block_scale, rows, columns // 16), 0) + elif layout == "TensorCoreMXFP8Layout": + fields["scale"] = (from_blocked(self.params.scale, rows, columns // 32), 0) + elif layout in ("TensorWiseINT8Layout", "TensorCoreConvRotW4A4Layout"): + fields["scale"] = (self.params.scale.reshape(-1, 1).expand(rows, 1), 0) + elif layout in ("TensorCoreAWQW4A16Layout", "TensorCoreSVDQuantW4A4Layout"): + scale = self.params.scale + if layout == "TensorCoreSVDQuantW4A4Layout" and data.ndim == 4: + data = ( + data.reshape(data.shape[0], data.shape[1], 32, 4, 32) + .permute(0, 2, 3, 1, 4) + .reshape(rows, columns // 2) + ) + scale = scale.permute(1, 0, 2).reshape(columns // 64, rows) + fields["proj_up"] = (self.params.proj_up.permute(0, 2, 1).reshape(rows, -1), 0) + elif layout == "TensorCoreSVDQuantW4A4Layout": + fields["proj_up"] = (self.params.proj_up, 0) + fields["scale"] = (scale, 1) + if layout == "TensorCoreAWQW4A16Layout": + fields["zeros"] = (self.params.zeros, 1) + elif layout == "AsymW4A8Int8Layout": + fields["scale"] = (self.params.scale, 0) + fields["s_channel"] = (self.params.s_channel, 0) + if self.params.correction is not None: + fields["correction"] = (self.params.correction, 1) + return data[:rows], fields + + def _from_rows(self, data, fields, shape): + values = {name: value for name, (value, _) in fields.items()} + if self._layout_cls == "TensorCoreNVFP4Layout": + values["block_scale"] = to_blocked(values["block_scale"]) + elif self._layout_cls == "TensorCoreMXFP8Layout": + values["scale"] = to_blocked(values["scale"]) + elif self._layout_cls == "TensorCoreConvRotW4A4Layout": + values["scale"] = values["scale"].flatten() + params = dataclasses.replace(self.params, orig_shape=(math.prod(shape[:-1]), shape[-1]), **values) + return type(self)( + data, + self._layout_cls, + params, + self.comfy_quant.copy(), + self.input_scale, + self.pre_quant_scale, + tuple(shape), + rows_rearranged=True, + ) + + def _select_rows(self, indices, shape): + data, fields = self._row_components() + + def select(tensor, dim): + if tensor.element_size() == 1: + return tensor.view(torch.uint8).index_select(dim, indices).view(tensor.dtype) + return tensor.index_select(dim, indices) + + return self._from_rows( + select(data, 0), {name: (select(value, dim), dim) for name, (value, dim) in fields.items()}, shape + ) + + @classmethod + def _split(cls, func, args, kwargs): + source, sizes = args[:2] + dim = (args[2] if len(args) > 2 else kwargs.get("dim", 0)) % source.ndim + if dim == source.ndim - 1: + raise NotImplementedError("Splitting quantized input features is not supported.") + indices = torch.arange(math.prod(source.shape[:-1]), device=source.device).reshape(source.shape[:-1]) + return [ + source._select_rows(part.flatten(), (*part.shape, source.shape[-1])) + for part in func(indices, sizes, dim) + ] + + @classmethod + def _cat(cls, args, kwargs): + tensors = args[0] + dim = (args[1] if len(args) > 1 else kwargs.get("dim", 0)) % tensors[0].ndim + if dim != 0 or any(not isinstance(t, cls) or t._layout_cls != tensors[0]._layout_cls for t in tensors): + raise NotImplementedError("Concatenation requires matching Comfy layouts along output rows.") + source = tensors[0] + components = [tensor._row_components() for tensor in tensors] + row_fields = components[0][1] + for tensor, (_, fields) in zip(tensors[1:], components[1:]): + if tensor.shape[1:] != source.shape[1:] or fields.keys() != row_fields.keys(): + raise ValueError("Cannot concatenate incompatible quantized weight shapes or scales.") + if tensor.comfy_quant != source.comfy_quant: + raise ValueError("Cannot concatenate weights with different quantization metadata.") + for name in ("input_scale", "pre_quant_scale"): + left, right = getattr(source, name), getattr(tensor, name) + if (left is None) != (right is None) or (left is not None and not torch.equal(left, right)): + raise ValueError(f"Cannot concatenate weights with different {name}.") + for field in dataclasses.fields(source.params): + if field.name in row_fields or field.name == "orig_shape": + continue + left, right = getattr(source.params, field.name), getattr(tensor.params, field.name) + equal = ( + torch.equal(left, right) + if isinstance(left, torch.Tensor) and isinstance(right, torch.Tensor) + else left == right + ) + if not equal: + raise ValueError(f"Cannot concatenate weights with different {field.name}.") + data = torch.cat([part[0] for part in components], dim=0) + fields = { + name: (torch.cat([part[1][name][0] for part in components], dim=axis), axis) + for name, (_, axis) in row_fields.items() + } + return source._from_rows(data, fields, (sum(t.shape[0] for t in tensors), *source.shape[1:])) + + @classmethod + def _view(cls, args): + source, shape = args[:2] + shape = list(shape) + if -1 in shape: + shape[shape.index(-1)] = source.numel() // -math.prod(shape) + if shape[-1] != source.shape[-1] or math.prod(shape) != source.numel(): + raise NotImplementedError("Reshaping quantized input features is not supported.") + return cls( + source._qdata, + source._layout_cls, + source.params, + source.comfy_quant, + source.input_scale, + source.pre_quant_scale, + tuple(shape), + source.rows_rearranged, + ) + + @classmethod + def _reorder(cls, func, args, kwargs): + source = args[0] + indices = torch.arange(math.prod(source.shape[:-1]), device=source.device).reshape(source.shape[:-1]) + dims = [dim % source.ndim for dim in args[1:]] + if any(dim == source.ndim - 1 for dim in dims): + raise NotImplementedError("Reordering quantized input features is not supported.") + transformed = func(indices, *dims, **kwargs) + if isinstance(transformed, torch.Tensor): + return source._select_rows(transformed.flatten(), (*transformed.shape, source.shape[-1])) + return [source._select_rows(part.flatten(), (*part.shape, source.shape[-1])) for part in transformed] + + @classmethod + def __torch_dispatch__(cls, func, types, args=(), kwargs=None): + kwargs = kwargs or {} + if func in (torch.ops.aten.split.Tensor, torch.ops.aten.split_with_sizes.default): + return cls._split(func, args, kwargs) + if func == torch.ops.aten.cat.default: + return cls._cat(args, kwargs) + if func in (torch.ops.aten.view.default, torch.ops.aten._unsafe_view.default): + return cls._view(args) + if func in (torch.ops.aten.transpose.int, torch.ops.aten.unbind.int): + return cls._reorder(func, args, kwargs) + return super().__torch_dispatch__(func, types, args, kwargs) + + +class ComfyLinear(nn.Linear): + """Linear inference dispatched through the weight's Comfy-Kitchen layout.""" + + def forward(self, inputs: torch.Tensor) -> torch.Tensor: + weight = self.weight + inputs = inputs.to(weight.dtype) + shape = inputs.shape + inputs = inputs.reshape(-1, shape[-1]) + if weight.pre_quant_scale is not None: + inputs = inputs * weight.pre_quant_scale.to(inputs.dtype) + if weight.comfy_quant.get("full_precision_matrix_mult", False): + output = F.linear(inputs, weight.dequantize().to(weight.dtype), self.bias) + else: + if weight._layout_cls in ("TensorCoreFP8Layout", "TensorCoreNVFP4Layout", "TensorCoreMXFP8Layout"): + quant_kwargs = {"scale": weight.input_scale} + if weight._layout_cls == "TensorCoreFP8Layout": + quant_kwargs["dtype"] = weight.storage_dtype + inputs = QuantizedTensor.from_float(inputs, weight._layout_cls, **quant_kwargs) + output = F.linear(inputs, weight, self.bias) + return output.to(weight.dtype).reshape(*shape[:-1], self.out_features) + + +def _dequantize_comfy_and_restore_linear(model): + for name, module in model.named_children(): + if isinstance(module, ComfyLinear): + linear = nn.Linear(module.in_features, module.out_features, module.bias is not None, device="meta") + linear.weight = nn.Parameter(module.weight.dequantize().to(module.weight.dtype)) + linear.bias = module.bias + if hasattr(module, "_hf_hook"): + hook = module._hf_hook + remove_hook_from_module(module) + add_hook_to_module(linear, hook) + model._modules[name] = linear + else: + _dequantize_comfy_and_restore_linear(module) + return model diff --git a/src/diffusers/quantizers/quantization_config.py b/src/diffusers/quantizers/quantization_config.py index 552dc2c52c02..5e3b0c018b35 100644 --- a/src/diffusers/quantizers/quantization_config.py +++ b/src/diffusers/quantizers/quantization_config.py @@ -43,6 +43,7 @@ class QuantizationMethod(str, Enum): BITS_AND_BYTES = "bitsandbytes" BFL = "bfl" + COMFY = "comfy" GGUF = "gguf" NUNCHAKU_LITE = "nunchaku_lite" TORCHAO = "torchao" @@ -424,6 +425,41 @@ def __init__(self, compute_dtype: "torch.dtype" | None = None): self.compute_dtype = torch.float32 +@dataclass +class ComfyQuantizationConfig(QuantizationConfigMixin): + """Load native Comfy checkpoints with Comfy-Kitchen kernels. + + Quantization formats are read from each layer's `comfy_quant` metadata in the prequantized checkpoint. See the + [Comfy quantization guide](https://huggingface.co/docs/diffusers/main/en/quantization/comfy) for validated formats + and checkpoint limitations. + + Args: + compute_dtype (`torch.dtype`, defaults to `torch.bfloat16`): + Precision of activations and unquantized layers. Supports BF16 and FP16. + """ + + def __init__(self, compute_dtype: "torch.dtype" | str | None = None): + self.quant_method = QuantizationMethod.COMFY + self.compute_dtype = compute_dtype if compute_dtype is not None else torch.bfloat16 + self.pre_quantized = True + self.post_init() + + def post_init(self): + if isinstance(self.compute_dtype, str): + self.compute_dtype = {"bfloat16": torch.bfloat16, "float16": torch.float16}.get(self.compute_dtype) + if self.compute_dtype not in (torch.bfloat16, torch.float16): + raise ValueError("Comfy compute_dtype must be torch.bfloat16 or torch.float16.") + + def to_dict(self): + result = super().to_dict() + result["compute_dtype"] = str(self.compute_dtype).replace("torch.", "") + return result + + def to_diff_dict(self): + default = ComfyQuantizationConfig().to_dict() + return {key: value for key, value in self.to_dict().items() if key == "quant_method" or value != default[key]} + + @dataclass class BFLQuantizationConfig(QuantizationConfigMixin): """Config for loading checkpoints quantized with the Black Forest Labs `fp8r` and `nvfp4` schemes. diff --git a/src/diffusers/utils/__init__.py b/src/diffusers/utils/__init__.py index 2c2e906eb26b..e82a62b61d2e 100644 --- a/src/diffusers/utils/__init__.py +++ b/src/diffusers/utils/__init__.py @@ -78,6 +78,7 @@ is_bitsandbytes_available, is_bitsandbytes_version, is_bs4_available, + is_comfy_kitchen_available, is_cosmos_guardrail_available, is_entropack_available, is_flash_attn_3_available, diff --git a/src/diffusers/utils/dummy_comfy_objects.py b/src/diffusers/utils/dummy_comfy_objects.py new file mode 100644 index 000000000000..6b70697eafed --- /dev/null +++ b/src/diffusers/utils/dummy_comfy_objects.py @@ -0,0 +1,17 @@ +# This file is autogenerated by the command `make fix-copies`, do not edit. +from ..utils import DummyObject, requires_backends + + +class ComfyQuantizationConfig(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + @classmethod + def from_config(cls, *args, **kwargs): + requires_backends(cls, ["torch"]) + + @classmethod + def from_pretrained(cls, *args, **kwargs): + requires_backends(cls, ["torch"]) diff --git a/src/diffusers/utils/import_utils.py b/src/diffusers/utils/import_utils.py index 3ea8325c8f52..a8fbd1823552 100644 --- a/src/diffusers/utils/import_utils.py +++ b/src/diffusers/utils/import_utils.py @@ -67,6 +67,7 @@ "safetensors": "safetensors", "bitsandbytes": "bitsandbytes", "gguf": "gguf", + "comfy_kitchen": "comfy-kitchen", "torchao": "torchao", "optimum": "optimum_quanto", "modelopt": "nvidia_modelopt[hf]", @@ -256,6 +257,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") +_comfy_kitchen_available, _comfy_kitchen_version = _is_package_available("comfy_kitchen") _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) @@ -412,6 +414,10 @@ def is_gguf_available(): return _gguf_available +def is_comfy_kitchen_available(): + return _comfy_kitchen_available + + def is_flashinfer_available(): return _flashinfer_available diff --git a/tests/conftest.py b/tests/conftest.py index 36234fe2d870..bc8215620cad 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -93,6 +93,7 @@ def pytest_configure(config): config.addinivalue_line("markers", "modelopt: marks tests for NVIDIA ModelOpt quantization functionality") config.addinivalue_line("markers", "sdnq: marks tests for SDNQ quantization functionality") config.addinivalue_line("markers", "bfl: marks tests for BFL (fp8r / nvfp4) quantization functionality") + config.addinivalue_line("markers", "comfy: marks tests for Comfy quantization functionality") config.addinivalue_line("markers", "context_parallel: marks tests for context parallel inference functionality") config.addinivalue_line("markers", "tensor_parallel: marks tests for tensor parallel inference functionality") config.addinivalue_line("markers", "slow: mark test as slow") diff --git a/tests/models/testing_utils/__init__.py b/tests/models/testing_utils/__init__.py index 596936cdef28..1694e6ed76f1 100644 --- a/tests/models/testing_utils/__init__.py +++ b/tests/models/testing_utils/__init__.py @@ -37,6 +37,8 @@ BitsAndBytesCompileTesterMixin, BitsAndBytesConfigMixin, BitsAndBytesTesterMixin, + ComfyConfigMixin, + ComfyTesterMixin, EntroPackConfigMixin, EntroPackTesterMixin, GGUFCompileTesterMixin, @@ -70,6 +72,8 @@ "BFLCompileTesterMixin", "BFLConfigMixin", "BFLTesterMixin", + "ComfyConfigMixin", + "ComfyTesterMixin", "BaseModelTesterConfig", "BitsAndBytesCompileTesterMixin", "BitsAndBytesConfigMixin", diff --git a/tests/models/testing_utils/quantization.py b/tests/models/testing_utils/quantization.py index 8d9203cb8f3b..5ea1382b78ce 100644 --- a/tests/models/testing_utils/quantization.py +++ b/tests/models/testing_utils/quantization.py @@ -25,6 +25,7 @@ AutoRoundConfig, BFLQuantizationConfig, BitsAndBytesConfig, + ComfyQuantizationConfig, EntroPackConfig, GGUFQuantizationConfig, NunchakuLiteQuantizationConfig, @@ -50,6 +51,7 @@ is_autoround, is_bfl, is_bitsandbytes, + is_comfy, is_entropack, is_gguf, is_lora, @@ -62,6 +64,7 @@ require_accelerator, require_auto_round_version_greater_or_equal, require_bitsandbytes_version_greater, + require_comfy_kitchen, require_gguf_version_greater_or_equal, require_modelopt_version_greater_or_equal, require_sdnq, @@ -2127,6 +2130,56 @@ def test_bfl_torch_compile_with_group_offload(self, config_name): self._test_torch_compile_with_group_offload(BFLConfigMixin.BFL_CONFIGS[config_name]) +class ComfyConfigMixin: + @property + def comfy_filename(self): + raise NotImplementedError("Subclasses must implement the `comfy_filename` property.") + + def _create_quantized_model(self, config_kwargs=None, **extra_kwargs): + if config_kwargs is None: + config_kwargs = {"compute_dtype": torch.bfloat16} + + config = ComfyQuantizationConfig(**config_kwargs) + kwargs = { + "quantization_config": config, + "torch_dtype": config.compute_dtype, + "device_map": str(torch_device), + } + kwargs.update(extra_kwargs) + return self.model_class.from_single_file(self.comfy_filename, **kwargs) + + def _verify_if_layer_quantized(self, name, module, config_kwargs=None): + from diffusers.quantizers.comfy.utils import ComfyLinear, ComfyQuantizedTensor + + assert isinstance(module, ComfyLinear), f"{name} is not a ComfyLinear" + assert isinstance(module.weight, ComfyQuantizedTensor), f"{name} weight is not a ComfyQuantizedTensor" + + +@is_quantization +@is_comfy +@require_accelerate +@require_accelerator +@require_comfy_kitchen +class ComfyTesterMixin(ComfyConfigMixin, QuantizationTesterMixin): + def test_comfy_quantization_inference(self): + self._test_quantization_inference({"compute_dtype": torch.bfloat16}) + + def test_comfy_keep_modules_in_fp32(self): + _keep_in_fp32_modules = self.model_class._keep_in_fp32_modules + self.model_class._keep_in_fp32_modules = ["to_q"] + + try: + self._test_keep_modules_in_fp32({"compute_dtype": torch.bfloat16}) + finally: + self.model_class._keep_in_fp32_modules = _keep_in_fp32_modules + + def test_comfy_quantization_dtype_assignment(self): + self._test_quantization_dtype_assignment({"compute_dtype": torch.bfloat16}) + + def test_comfy_dequantize(self): + self._test_dequantize({"compute_dtype": torch.bfloat16}) + + class EntroPackConfigMixin: """ Base mixin providing EntroPack quantization config and model creation. diff --git a/tests/models/transformers/test_models_transformer_krea2.py b/tests/models/transformers/test_models_transformer_krea2.py index 3b5fb4f37ac2..873351c7e9af 100644 --- a/tests/models/transformers/test_models_transformer_krea2.py +++ b/tests/models/transformers/test_models_transformer_krea2.py @@ -22,6 +22,7 @@ from ..testing_utils import ( AttentionTesterMixin, BaseModelTesterConfig, + ComfyTesterMixin, LoraTesterMixin, MemoryTesterMixin, ModelTesterMixin, @@ -178,3 +179,19 @@ def pretrained_model_kwargs(self): @property def torch_dtype(self): return torch.bfloat16 + + +class TestKrea2TransformerComfy(Krea2TransformerTesterConfig, ComfyTesterMixin): + _in_channels = 64 + _text_hidden_dim = 2560 + _num_text_layers = 12 + _text_seq_len = 32 + _grid_size = 16 + + @property + def comfy_filename(self): + return "https://huggingface.co/Comfy-Org/Krea-2/blob/main/diffusion_models/krea2_raw_int8_convrot.safetensors" + + @property + def torch_dtype(self): + return torch.bfloat16 diff --git a/tests/models/transformers/test_models_transformer_minimax_h3.py b/tests/models/transformers/test_models_transformer_minimax_h3.py index d9258f04127e..efd56bfad381 100644 --- a/tests/models/transformers/test_models_transformer_minimax_h3.py +++ b/tests/models/transformers/test_models_transformer_minimax_h3.py @@ -23,6 +23,7 @@ from ..testing_utils import ( AttentionTesterMixin, BaseModelTesterConfig, + ComfyTesterMixin, ContextParallelTesterMixin, LoraTesterMixin, MemoryTesterMixin, @@ -223,3 +224,18 @@ class TestMiniMaxH3TransformerTensorParallel(MiniMaxH3TransformerTesterConfig, T class TestMiniMaxH3TransformerTensorParallelNeuron(MiniMaxH3TransformerTesterConfig, TensorParallelNeuronTesterMixin): """Tensor Parallel inference test for the MiniMax-H3 transformer on AWS Neuron.""" + + +class TestMiniMaxH3TransformerComfy(MiniMaxH3TransformerTesterConfig, ComfyTesterMixin): + @property + def comfy_filename(self): + return "https://huggingface.co/Comfy-Org/MiniMax-H3/blob/main/diffusion_models/minimax_h3_fl2va_int8_convrot.safetensors" + + def get_init_dict(self) -> dict: + return {"patch_size": [1, 2, 2], "in_channels": 24, "audio_in_channels": 32, "text_dim": 5120} + + def get_dummy_inputs(self): + inputs = super().get_dummy_inputs(batch_size=1) + for name in ("hidden_states", "audio_hidden_states", "encoder_hidden_states"): + inputs[name] = inputs[name].to(torch.bfloat16) + return inputs diff --git a/tests/models/transformers/test_models_transformer_qwenimage21.py b/tests/models/transformers/test_models_transformer_qwenimage21.py index e178b954bd1d..90e5aa5ef890 100644 --- a/tests/models/transformers/test_models_transformer_qwenimage21.py +++ b/tests/models/transformers/test_models_transformer_qwenimage21.py @@ -25,6 +25,7 @@ from ..testing_utils import ( AttentionTesterMixin, BaseModelTesterConfig, + ComfyTesterMixin, MemoryTesterMixin, ModelTesterMixin, SingleFileTesterMixin, @@ -392,3 +393,37 @@ class TestQwenImage21TransformerTensorParallelNeuron( QwenImage21TransformerTesterConfig, TensorParallelNeuronTesterMixin ): """Tensor Parallel inference test for QwenImage 2.1 Transformer on AWS Neuron.""" + + +class TestQwenImage21TransformerComfy(QwenImage21TransformerTesterConfig, ComfyTesterMixin): + @property + def comfy_filename(self): + return "https://huggingface.co/Comfy-Org/Qwen-Image-2.1/blob/main/diffusion_models/qwen_image_2.1_int8_convrot.safetensors" + + @property + def torch_dtype(self): + return torch.bfloat16 + + def get_dummy_inputs(self): + batch_size = 1 + text_len, target_height, target_width = 32, 16, 16 + target_tokens = target_height * target_width + + hidden_states = randn_tensor( + (batch_size, target_tokens, 64), generator=self.generator, device=torch_device, dtype=self.torch_dtype + ) + encoder_hidden_states = randn_tensor( + (batch_size, text_len, 4096), generator=self.generator, device=torch_device, dtype=self.torch_dtype + ) + encoder_hidden_states_mask = torch.ones((batch_size, text_len), device=torch_device, dtype=torch.long) + img_mask = torch.zeros((batch_size, text_len + target_tokens // 4), device=torch_device, dtype=torch.bool) + img_mask[:, text_len:] = True + + return { + "hidden_states": hidden_states, + "encoder_hidden_states": encoder_hidden_states, + "encoder_hidden_states_mask": encoder_hidden_states_mask, + "timestep": torch.tensor([1.0], device=torch_device, dtype=self.torch_dtype).expand(batch_size), + "img_shapes": [[(1, target_height, target_width)]] * batch_size, + "img_mask": img_mask, + } diff --git a/tests/quantization/comfy/__init__.py b/tests/quantization/comfy/__init__.py new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/tests/quantization/comfy/test_comfy.py b/tests/quantization/comfy/test_comfy.py new file mode 100644 index 000000000000..13a8ad8bb312 --- /dev/null +++ b/tests/quantization/comfy/test_comfy.py @@ -0,0 +1,236 @@ +# Copyright 2026 HuggingFace Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import json + +import pytest +import torch +from torch import nn +from torch.nn import functional as F + +from diffusers import ComfyQuantizationConfig +from diffusers.quantizers.comfy import ComfyQuantizer +from diffusers.quantizers.comfy.comfy_quantizer import COMFY_FORMATS +from diffusers.utils import is_comfy_kitchen_available + +from ...testing_utils import is_comfy, is_quantization, require_comfy_kitchen + + +if is_comfy_kitchen_available(): + import comfy_kitchen as kitchen + from comfy_kitchen.float_utils import from_blocked, to_blocked + from comfy_kitchen.tensor import QuantizedTensor + + from diffusers.quantizers.comfy.utils import ComfyLinear, ComfyQuantizedTensor + + +FORMATS = list(COMFY_FORMATS) + + +def marker(**metadata): + return torch.tensor(list(json.dumps(metadata).encode()), dtype=torch.uint8) + + +def checkpoint(quant_format="int8_tensorwise", prefix="linear", rows=96, columns=256, **metadata): + torch.manual_seed(10) + layout, dtype, bits = COMFY_FORMATS[quant_format] + weight = torch.randint(0, 64, (rows, columns * bits // 8), dtype=torch.uint8).to(dtype) + state = {"weight": weight} + if quant_format == "nvfp4": + state.update( + weight_scale=to_blocked(torch.ones(rows, columns // 16).to(torch.float8_e4m3fn)), + weight_scale_2=torch.tensor(0.01), + ) + elif quant_format == "mxfp8": + state["weight_scale"] = to_blocked(torch.full((rows, columns // 32), 127, dtype=torch.uint8)) + elif quant_format in ("asym_w4a8_int8", "w6a8_int8"): + state.update( + weight_s_rel=torch.ones(rows, columns // 16).to(torch.float8_e4m3fn), + weight_s_channel=torch.full((rows,), 0.01), + ) + elif quant_format == "convrot_w4a4": + state["weight_scale"] = torch.full((rows,), 0.01) + elif quant_format in ("awq_w4a16", "svdquant_w4a4"): + state["weight_scale"] = torch.full((columns // 64, rows), 0.01) + if quant_format == "awq_w4a16": + state["weight_zero"] = torch.randn(columns // 64, rows) * 0.001 + elif quant_format == "svdquant_w4a4": + state.update( + proj_down=torch.randn(columns, 4) * 0.01, + proj_up=torch.randn(rows, 4) * 0.01, + smooth_factor=torch.ones(columns), + ) + else: + state["weight_scale"] = ( + torch.linspace(0.001, 0.004, rows).reshape(rows, 1) + if quant_format == "int8_tensorwise" + else torch.tensor(0.01) + ) + state["comfy_quant"] = marker(format=quant_format, **metadata) + return {f"{prefix}.{name}": value for name, value in state.items()} + + +def bundle(state): + return ComfyQuantizer(ComfyQuantizationConfig()).maybe_update_state_dict(state) + + +def padded_checkpoint(quant_format, rows, columns, prefix="linear"): + torch.manual_seed(0) + layout = COMFY_FORMATS[quant_format][0] + q = QuantizedTensor.from_float(torch.randn(rows, columns), layout) + state = {"weight": q._qdata, "comfy_quant": marker(format=quant_format)} + if quant_format == "nvfp4": + state.update(weight_scale=q.params.block_scale, weight_scale_2=q.params.scale) + else: + state["weight_scale"] = q.params.scale + return {f"{prefix}.{name}": value for name, value in state.items()}, q + + +@is_quantization +@is_comfy +@require_comfy_kitchen +class TestComfyQuantization: + @pytest.mark.parametrize("quant_format", FORMATS) + def test_split_and_cat_keep_codes_and_sidecars_aligned(self, quant_format): + q = bundle(checkpoint(quant_format))["linear.weight"] + original_data, original_fields = q._row_components() + parts = q.split([16, 48, 32], dim=0) + offset = 0 + for part, rows in zip(parts, (16, 48, 32)): + assert isinstance(part, ComfyQuantizedTensor) + assert part.shape == (rows, 256) + data, fields = part._row_components() + torch.testing.assert_close(data, original_data[offset : offset + rows], rtol=0, atol=0) + for name, (value, axis) in fields.items(): + expected = original_fields[name][0].narrow(axis, offset, rows) + torch.testing.assert_close(value.float(), expected.float(), rtol=0, atol=0) + offset += rows + joined = torch.cat(parts[::-1], dim=0) + data, fields = joined._row_components() + expected_order = torch.cat([torch.arange(64, 96), torch.arange(16, 64), torch.arange(16)]) + torch.testing.assert_close(data.float(), original_data.float()[expected_order], rtol=0, atol=0) + for name, (value, axis) in fields.items(): + torch.testing.assert_close( + value.float(), original_fields[name][0].float().index_select(axis, expected_order), rtol=0, atol=0 + ) + + @pytest.mark.parametrize("quant_format", ["nvfp4", "mxfp8"]) + def test_blocked_scale_conversion_preserves_distinct_rows(self, quant_format): + state = checkpoint(quant_format) + block = 16 if quant_format == "nvfp4" else 32 + scales = torch.arange(96 * (256 // block)).reshape(96, -1).remainder(20).add(1) + stored = scales.to(torch.float8_e4m3fn) if block == 16 else scales.add(110).to(torch.uint8) + state["linear.weight_scale"] = to_blocked(stored) + q = bundle(state)["linear.weight"] + parts = q.chunk(3) + for index, part in enumerate(parts): + scale = part.params.block_scale if block == 16 else part.params.scale + decoded = from_blocked(scale, 32, 256 // block) + torch.testing.assert_close( + decoded.view(torch.uint8), stored[index * 32 : (index + 1) * 32].view(torch.uint8), rtol=0, atol=0 + ) + + def test_negative_transpose_dims_match_positive_dims(self): + original = bundle(checkpoint(rows=96))["linear.weight"] + q = original.view(2, 3, 16, 256) + expected = q.transpose(1, 0) + actual = q.transpose(-3, 0) + order = torch.arange(96).reshape(2, 3, 16).transpose(0, 1).flatten() + assert actual.shape == expected.shape == (3, 2, 16, 256) + torch.testing.assert_close(actual._qdata, expected._qdata, rtol=0, atol=0) + torch.testing.assert_close(actual.params.scale, expected.params.scale, rtol=0, atol=0) + torch.testing.assert_close(actual._qdata, original._qdata[order], rtol=0, atol=0) + torch.testing.assert_close(actual.params.scale, original.params.scale[order], rtol=0, atol=0) + + @pytest.mark.parametrize("quant_format", ["nvfp4", "mxfp8"]) + def test_padded_weight_restores_linear_shape(self, quant_format): + state, reference = padded_checkpoint(quant_format, 100, 50, "0") + state = bundle(state) + model = nn.Sequential(nn.Linear(50, 100, bias=False, device="meta")) + quantizer = ComfyQuantizer(ComfyQuantizationConfig()) + quantizer.preprocess_model(model, device_map=None, state_dict=state, keep_in_fp32_modules=[]) + quantizer.create_quantized_param(model, state["0.weight"], "0.weight", "cpu", state) + assert model[0].weight.shape == (100, 50) + torch.testing.assert_close( + model[0].weight.dequantize().float(), reference.dequantize().float(), rtol=0.01, atol=1e-3 + ) + inputs = torch.randn(3, 50, dtype=torch.bfloat16) + with torch.inference_mode(), kitchen.use_backend("eager"): + assert model(inputs).shape == (3, 100) + + def test_svdquant_tile_packed_qkv_conversion(self): + from comfy_kitchen.backends.eager.svdquant import _tile_packed_weight_to_row_major + + rows, columns = 384, 256 + state = checkpoint("svdquant_w4a4", rows=rows) + expected = state["linear.weight"].clone() + expected_scale = state["linear.weight_scale"].clone() + expected_up = state["linear.proj_up"].clone() + state["linear.weight"] = ( + expected.reshape(3, 32, 4, columns // 64, 32).permute(0, 3, 1, 2, 4).reshape(3, columns // 64, 32, 128) + ) + state["linear.weight_scale"] = expected_scale.reshape(columns // 64, 3, 128).permute(1, 0, 2) + state["linear.proj_up"] = expected_up.reshape(3, 128, 4).transpose(1, 2) + torch.testing.assert_close(_tile_packed_weight_to_row_major(state["linear.weight"]), expected) + q = bundle(state)["linear.weight"] + for index, part in enumerate(q.chunk(3)): + torch.testing.assert_close(part._qdata, expected[index * 128 : (index + 1) * 128], rtol=0, atol=0) + torch.testing.assert_close( + part.params.scale, expected_scale[:, index * 128 : (index + 1) * 128], rtol=0, atol=0 + ) + torch.testing.assert_close( + part.params.proj_up, expected_up[index * 128 : (index + 1) * 128], rtol=0, atol=0 + ) + + def test_cat_rejects_different_shared_scales_and_metadata(self): + first = bundle(checkpoint("float8_e4m3fn"))["linear.weight"] + second = first.clone() + second._params = type(first.params)( + scale=torch.tensor(0.5), orig_dtype=first.dtype, orig_shape=tuple(first.shape) + ) + with pytest.raises(ValueError, match="different scale"): + torch.cat([first, second]) + with pytest.raises(NotImplementedError, match="input features"): + first.chunk(2, dim=1) + + @pytest.mark.parametrize("quant_format", FORMATS) + def test_linear_runtime_matches_layout_reference(self, quant_format): + q = bundle(checkpoint(quant_format, rows=128))["linear.weight"] + linear = ComfyLinear(256, 128, bias=False, dtype=torch.bfloat16) + linear.weight = nn.Parameter(q, requires_grad=False) + torch.manual_seed(42) + inputs = torch.randn(2, 3, 256, dtype=torch.bfloat16) + with torch.inference_mode(), kitchen.use_backend("eager"): + actual = linear(inputs) + reference_input = inputs.reshape(-1, 256) + if q._layout_cls in ("TensorCoreFP8Layout", "TensorCoreNVFP4Layout", "TensorCoreMXFP8Layout"): + kwargs = {"dtype": q.storage_dtype} if q._layout_cls == "TensorCoreFP8Layout" else {} + reference_input = QuantizedTensor.from_float(reference_input, q._layout_cls, **kwargs).dequantize() + if q._layout_cls == "TensorCoreSVDQuantW4A4Layout": + reference = F.linear(inputs, QuantizedTensor(q._qdata, q._layout_cls, q.params)) + else: + reference = F.linear(reference_input, q.dequantize().to(inputs.dtype)).reshape(2, 3, 128) + assert torch.isfinite(actual).all() + assert actual.dtype == torch.bfloat16 + relative_error = (actual.float() - reference.float()).norm() / reference.float().norm() + assert relative_error < (0.25 if quant_format == "convrot_w4a4" else 0.04), relative_error.item() + + def test_full_precision_mm_keeps_input_scaling(self): + state = checkpoint("float8_e4m3fn", full_precision_matrix_mult=True) + state["linear.pre_quant_scale"] = torch.full((256,), 0.5) + q = bundle(state)["linear.weight"] + linear = ComfyLinear(256, 96, bias=False, dtype=torch.bfloat16) + linear.weight = nn.Parameter(q, requires_grad=False) + inputs = torch.randn(2, 256, dtype=torch.bfloat16) + torch.testing.assert_close(linear(inputs), F.linear(inputs * 0.5, q.dequantize())) diff --git a/tests/testing_utils.py b/tests/testing_utils.py index 3f73e891b61b..7b9768531b39 100644 --- a/tests/testing_utils.py +++ b/tests/testing_utils.py @@ -35,6 +35,7 @@ is_accelerate_available, is_auto_round_available, is_bitsandbytes_available, + is_comfy_kitchen_available, is_compel_available, is_flashpack_available, is_gguf_available, @@ -479,6 +480,10 @@ def is_sdnq(test_case): return pytest.mark.sdnq(test_case) +def is_comfy(test_case): + return pytest.mark.comfy(test_case) + + def is_bfl(test_case): """ Decorator marking a test as a BFL (fp8r / nvfp4) quantization test. These tests can be filtered using: @@ -779,6 +784,10 @@ def require_sdnq(test_case): return pytest.mark.skipif(not is_sdnq_available(), reason="test requires sdnq")(test_case) +def require_comfy_kitchen(test_case): + return pytest.mark.skipif(not is_comfy_kitchen_available(), reason="test requires comfy-kitchen")(test_case) + + def require_accelerate(test_case): """ Decorator marking a test that requires accelerate. These tests are skipped when accelerate isn't installed.