From ad8f205c618a8083297ba6237c78b08288c39aa5 Mon Sep 17 00:00:00 2001 From: asaiyume Date: Tue, 1 Dec 2026 20:10:02 +0800 Subject: [PATCH 1/4] Add Comfy Kitchen INT8 attention backend --- src/diffusers/models/attention_dispatch.py | 51 ++++++++++++++++++++++ src/diffusers/utils/__init__.py | 1 + src/diffusers/utils/import_utils.py | 16 +++++++ tests/models/testing_utils/attention.py | 15 ++++++- 4 files changed, 82 insertions(+), 1 deletion(-) diff --git a/src/diffusers/models/attention_dispatch.py b/src/diffusers/models/attention_dispatch.py index 9d2135034a9f..87990a6a8c0d 100644 --- a/src/diffusers/models/attention_dispatch.py +++ b/src/diffusers/models/attention_dispatch.py @@ -36,6 +36,8 @@ from .. import __version__ from ..utils import ( get_logger, + is_comfy_kitchen_available, + is_comfy_kitchen_version, is_flash_attn_3_available, is_flash_attn_available, is_flash_attn_version, @@ -63,6 +65,7 @@ _REQUIRED_FLEX_VERSION = "2.5.0" _REQUIRED_XLA_VERSION = "2.2" _REQUIRED_XFORMERS_VERSION = "0.0.29" +_REQUIRED_COMFY_KITCHEN_VERSION = "0.2.41" logger = get_logger(__name__) # pylint: disable=invalid-name @@ -73,6 +76,9 @@ _CAN_USE_NPU_ATTN = is_torch_npu_available() _CAN_USE_XLA_ATTN = is_torch_xla_available() and is_torch_xla_version(">=", _REQUIRED_XLA_VERSION) _CAN_USE_XFORMERS_ATTN = is_xformers_available() and is_xformers_version(">=", _REQUIRED_XFORMERS_VERSION) +_CAN_USE_COMFY_KITCHEN_ATTN = is_comfy_kitchen_available() and is_comfy_kitchen_version( + ">=", _REQUIRED_COMFY_KITCHEN_VERSION +) # torch>=2.9 hands the LSE to the cuDNN kernels with a trailing dim, (B, H, S, 1); before that the # forward returns (B, H, S) and the aten backward wrapper adds the trailing dim itself. Module-level # constant to avoid Dynamo tracing into the lru_cache-wrapped `is_torch_version` during torch.compile. @@ -112,6 +118,16 @@ flash_attn_3_func = None flash_attn_3_varlen_func = None +if _CAN_USE_COMFY_KITCHEN_ATTN: + try: + from comfy_kitchen import int8_attention as comfy_kitchen_int8_attention + except (ImportError, OSError, RuntimeError) as e: + logger.warning(f"comfy_kitchen failed to import: {e}. Falling back to native attention.") + _CAN_USE_COMFY_KITCHEN_ATTN = False + comfy_kitchen_int8_attention = None +else: + comfy_kitchen_int8_attention = None + if _CAN_USE_SAGE_ATTN: try: from sageattention import ( @@ -242,6 +258,9 @@ class AttentionBackendName(str, Enum): # `xformers` XFORMERS = "xformers" + # `comfy-kitchen` + COMFY_KITCHEN_INT8 = "comfy_kitchen_int8" + class _AttentionBackendRegistry: _backends = {} @@ -597,6 +616,12 @@ def _check_attention_backend_requirements(backend: AttentionBackendName) -> None f"Xformers Attention backend '{backend.value}' is not usable because of missing package or the version is too old. Please install `xformers>={_REQUIRED_XFORMERS_VERSION}`." ) + elif backend == AttentionBackendName.COMFY_KITCHEN_INT8: + if not _CAN_USE_COMFY_KITCHEN_ATTN: + raise RuntimeError( + f"Comfy Kitchen Attention backend '{backend.value}' is not usable because of missing package or the version is too old. Please install `comfy-kitchen>={_REQUIRED_COMFY_KITCHEN_VERSION}`." + ) + @lru_cache_unless_export(maxsize=128) def _prepare_for_flash_attn_or_sage_varlen_without_mask( @@ -4534,3 +4559,29 @@ def _xformers_attention( out = out.flatten(2, 3) return out + + +@_AttentionBackendRegistry.register( + AttentionBackendName.COMFY_KITCHEN_INT8, + constraints=[_check_attn_mask_or_causal, _check_device_cuda, _check_shape], +) +def _comfy_kitchen_int8_attention( + query: torch.Tensor, + key: torch.Tensor, + value: torch.Tensor, + attn_mask: torch.Tensor | None = None, + dropout_p: float = 0.0, + is_causal: bool = False, + scale: float | None = None, + enable_gqa: bool = False, + _parallel_config: "ParallelConfig" | None = None, +) -> torch.Tensor: + if query.shape[-1] > 256 or is_causal or dropout_p > 0.0: + return _native_attention(query, key, value, attn_mask, dropout_p, is_causal, scale, enable_gqa) + + if attn_mask is not None and attn_mask.ndim == 2 and attn_mask.shape == (query.shape[0], key.shape[1]): + attn_mask = attn_mask.unsqueeze(1).unsqueeze(1) + + query, key, value = (x.permute(0, 2, 1, 3) for x in (query, key, value)) + out = comfy_kitchen_int8_attention(query, key, value, scale=scale, attn_mask=attn_mask) + return out.permute(0, 2, 1, 3) diff --git a/src/diffusers/utils/__init__.py b/src/diffusers/utils/__init__.py index e82a62b61d2e..ebb6a4313a2c 100644 --- a/src/diffusers/utils/__init__.py +++ b/src/diffusers/utils/__init__.py @@ -79,6 +79,7 @@ is_bitsandbytes_version, is_bs4_available, is_comfy_kitchen_available, + is_comfy_kitchen_version, is_cosmos_guardrail_available, is_entropack_available, is_flash_attn_3_available, diff --git a/src/diffusers/utils/import_utils.py b/src/diffusers/utils/import_utils.py index a8fbd1823552..b0dffc038512 100644 --- a/src/diffusers/utils/import_utils.py +++ b/src/diffusers/utils/import_utils.py @@ -961,6 +961,22 @@ def is_xformers_version(operation: str, version: str): return compare_versions(parse(_xformers_version), operation, version) +@cache +def is_comfy_kitchen_version(operation: str, version: str): + """ + Compares the current comfy-kitchen version to a given reference with an operation. + + Args: + operation (`str`): + A string representation of an operator, such as `">"` or `"<="` + version (`str`): + A version string + """ + if not _comfy_kitchen_available: + return False + return compare_versions(parse(_comfy_kitchen_version), operation, version) + + @cache def is_sageattention_version(operation: str, version: str): """ diff --git a/tests/models/testing_utils/attention.py b/tests/models/testing_utils/attention.py index fc9037a7db64..4718387c9582 100644 --- a/tests/models/testing_utils/attention.py +++ b/tests/models/testing_utils/attention.py @@ -23,7 +23,7 @@ from diffusers.models.attention import AttentionMixin, AttentionModuleMixin from diffusers.models.attention_dispatch import AttentionBackendName, _AttentionBackendRegistry, attention_backend from diffusers.models.attention_processor import Attention, AttnProcessor -from diffusers.utils import is_kernels_available, is_torch_version +from diffusers.utils import is_comfy_kitchen_available, is_kernels_available, is_torch_version from diffusers.utils.constants import DIFFUSERS_TRUST_REMOTE_KERNELS from ...testing_utils import assert_tensors_close, backend_empty_cache, is_attention, is_torch_compile, torch_device @@ -165,6 +165,18 @@ ], ) +_PARAM_COMFY_KITCHEN_INT8 = pytest.param( + AttentionBackendName.COMFY_KITCHEN_INT8, + id="comfy_kitchen_int8", + marks=[ + pytest.mark.skipif(not _CUDA_AVAILABLE, reason="CUDA is required for comfy_kitchen_int8 backend."), + pytest.mark.skipif( + not is_comfy_kitchen_available(), + reason="`comfy-kitchen` is required for comfy_kitchen_int8 backend. Install with `pip install comfy-kitchen`.", + ), + ], +) + # All backends under test. _ALL_BACKEND_PARAMS = [ _PARAM_NATIVE_CUDNN, @@ -175,6 +187,7 @@ _PARAM_SAGE_HUB, _PARAM_SAGE_BLACKWELL_HUB, _PARAM_AITER_SAGE_HUB, + _PARAM_COMFY_KITCHEN_INT8, ] # Backends that perform non-deterministic operations and therefore cannot run when From 8edea516d9e4cf8eff7c39f5164b21dfa679dcc2 Mon Sep 17 00:00:00 2001 From: asaiyume Date: Tue, 1 Dec 2026 20:16:09 +0800 Subject: [PATCH 2/4] Update attention_backends.md --- docs/source/en/optimization/attention_backends.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/source/en/optimization/attention_backends.md b/docs/source/en/optimization/attention_backends.md index fd9e2bfe819d..7b3ea22e8fd5 100644 --- a/docs/source/en/optimization/attention_backends.md +++ b/docs/source/en/optimization/attention_backends.md @@ -26,6 +26,7 @@ Refer to the table below for an overview of the available attention families and | FlexAttention | PyTorch FlexAttention | | PyTorch native | built-in PyTorch implementation using [scaled_dot_product_attention](./fp16#scaled-dot-product-attention) | | xFormers | memory-efficient attention with support for various attention kernels | +| Comfy Kitchen | quantizes attention to int8 for inference | Hub backends (the `*_hub` names) need the [Kernels](https://github.com/huggingface/kernels) library and download the kernel on first use. The SageAttention Hub backends also need `DIFFUSERS_TRUST_REMOTE_KERNELS=true` (see [Trusting remote kernels](#trusting-remote-kernels)). Other backends need their own package, such as `flash-attn` or `sageattention`. The [Available backends](#available-backends) table lists the requirements Diffusers checks when you enable a backend. @@ -161,3 +162,4 @@ Refer to the table below for a complete list of available attention backends and | `_sage_qk_int8_pv_fp16_cuda` | [SageAttention](https://github.com/thu-ml/SageAttention) | INT8 QK + FP16 PV (CUDA) | `sageattention>=2.1.1` | | `_sage_qk_int8_pv_fp16_triton` | [SageAttention](https://github.com/thu-ml/SageAttention) | INT8 QK + FP16 PV (Triton) | `sageattention>=2.1.1` | | `xformers` | [xFormers](https://github.com/facebookresearch/xformers) | Memory-efficient attention | `xformers>=0.0.29` | +| `comfy_kitchen_int8` | [Comfy Kitchen](https://github.com/Comfy-Org/comfy-kitchen) | INT8 attention (inference only) | `comfy-kitchen>=0.2.41`; CUDA SM75 or newer | From d501f918fcb1408a3daaba2ea464ebb58bd3077d Mon Sep 17 00:00:00 2001 From: asaiyume Date: Tue, 1 Dec 2026 20:50:53 +0800 Subject: [PATCH 3/4] Raise on unsupported Comfy Kitchen attention inputs and add tests --- src/diffusers/models/attention_dispatch.py | 9 +-- tests/models/test_attention_dispatch.py | 82 ++++++++++++++++++++++ 2 files changed, 87 insertions(+), 4 deletions(-) diff --git a/src/diffusers/models/attention_dispatch.py b/src/diffusers/models/attention_dispatch.py index 87990a6a8c0d..886228f09a34 100644 --- a/src/diffusers/models/attention_dispatch.py +++ b/src/diffusers/models/attention_dispatch.py @@ -4563,7 +4563,7 @@ def _xformers_attention( @_AttentionBackendRegistry.register( AttentionBackendName.COMFY_KITCHEN_INT8, - constraints=[_check_attn_mask_or_causal, _check_device_cuda, _check_shape], + constraints=[_check_device_cuda, _check_shape], ) def _comfy_kitchen_int8_attention( query: torch.Tensor, @@ -4573,11 +4573,12 @@ def _comfy_kitchen_int8_attention( dropout_p: float = 0.0, is_causal: bool = False, scale: float | None = None, - enable_gqa: bool = False, _parallel_config: "ParallelConfig" | None = None, ) -> torch.Tensor: - if query.shape[-1] > 256 or is_causal or dropout_p > 0.0: - return _native_attention(query, key, value, attn_mask, dropout_p, is_causal, scale, enable_gqa) + if is_causal: + raise ValueError("`is_causal` is not supported for Comfy Kitchen INT8 attention") + if dropout_p > 0.0: + raise ValueError("`dropout_p` is not supported for Comfy Kitchen INT8 attention") if attn_mask is not None and attn_mask.ndim == 2 and attn_mask.shape == (query.shape[0], key.shape[1]): attn_mask = attn_mask.unsqueeze(1).unsqueeze(1) diff --git a/tests/models/test_attention_dispatch.py b/tests/models/test_attention_dispatch.py index aabf8eeb3f2c..79ae4cbe63f1 100644 --- a/tests/models/test_attention_dispatch.py +++ b/tests/models/test_attention_dispatch.py @@ -33,6 +33,7 @@ ) from diffusers.models.attention_dispatch import attention_backend as attention_backend_ctx from diffusers.models.transformers.transformer_flux import FluxAttention +from diffusers.utils import is_comfy_kitchen_available from ..testing_utils import ( IS_ROCM_SYSTEM, @@ -353,6 +354,87 @@ def test_output_close_to_native(self): assert cos > 0.99 +@is_attention +@pytest.mark.skipif(not torch.cuda.is_available(), reason="CUDA is required for the comfy_kitchen_int8 backend.") +@pytest.mark.skipif(not is_comfy_kitchen_available(), reason="`comfy-kitchen` is not available.") +class TestComfyKitchenInt8: + @staticmethod + def _qkv(seq_q=1024, seq_kv=1024, heads_q=4, heads_kv=4, head_dim=128, dtype=torch.bfloat16): + torch.manual_seed(0) + q = torch.randn(2, seq_q, heads_q, head_dim, device="cuda", dtype=dtype) + k = torch.randn(2, seq_kv, heads_kv, head_dim, device="cuda", dtype=dtype) + v = torch.randn(2, seq_kv, heads_kv, head_dim, device="cuda", dtype=dtype) + return q, k, v + + @staticmethod + def _assert_close_to_native(query, key, value, **kwargs): + with torch.no_grad(): + out = dispatch_attention_fn(query, key, value, backend=AttentionBackendName.COMFY_KITCHEN_INT8, **kwargs) + ref = dispatch_attention_fn(query, key, value, backend=AttentionBackendName.NATIVE, **kwargs) + assert out.shape == ref.shape + assert out.dtype == ref.dtype + assert not torch.equal(out, ref) + cos = F.cosine_similarity(out.float().flatten(), ref.float().flatten(), dim=0) + assert cos > 0.99 + + @pytest.mark.parametrize( + "qkv_kwargs", + [ + {}, + {"head_dim": 48}, + {"head_dim": 64}, + {"head_dim": 256}, + {"dtype": torch.float16}, + {"dtype": torch.float32}, + {"seq_kv": 77}, + ], + ids=["default", "head_dim_48", "head_dim_64", "head_dim_256", "fp16", "fp32", "cross_attention"], + ) + def test_output_close_to_native(self, qkv_kwargs): + self._assert_close_to_native(*self._qkv(**qkv_kwargs)) + + @pytest.mark.parametrize("mask_shape", [(2, 1024), (2, 1, 1, 1024), (2, 1, 1024, 1024)]) + @pytest.mark.parametrize("additive", [False, True]) + def test_attn_mask_close_to_native(self, mask_shape, additive): + mask = torch.ones(mask_shape, device="cuda", dtype=torch.bool) + mask[1, ..., 700:] = False + if additive: + mask = torch.zeros(mask_shape, device="cuda", dtype=torch.bfloat16).masked_fill(~mask, float("-inf")) + self._assert_close_to_native(*self._qkv(), attn_mask=mask) + + def test_masked_keys_do_not_change_output(self): + query, key, value = self._qkv() + mask = torch.ones(2, 1024, device="cuda", dtype=torch.bool) + mask[:, 700:] = False + changed_value = value.clone() + changed_value[:, 700:] = -value[:, 700:] + kwargs = {"attn_mask": mask, "backend": AttentionBackendName.COMFY_KITCHEN_INT8} + with torch.no_grad(): + out = dispatch_attention_fn(query, key, value, **kwargs) + changed_out = dispatch_attention_fn(query, key, changed_value, **kwargs) + unmasked_out = dispatch_attention_fn(query, key, value, backend=AttentionBackendName.COMFY_KITCHEN_INT8) + assert torch.equal(out, changed_out) + assert not torch.equal(out, unmasked_out) + + def test_grouped_query_attention_close_to_native(self): + self._assert_close_to_native(*self._qkv(heads_q=8, heads_kv=2), enable_gqa=True) + + @pytest.mark.parametrize( + "qkv_kwargs, call_kwargs, match", + [ + ({}, {"is_causal": True}, "is_causal"), + ({}, {"dropout_p": 0.1}, "dropout_p"), + ({"head_dim": 512}, {}, "head_dim"), + ], + ids=["causal", "dropout", "head_dim_512"], + ) + def test_unsupported_inputs_raise(self, qkv_kwargs, call_kwargs, match): + with pytest.raises(ValueError, match=match): + dispatch_attention_fn( + *self._qkv(**qkv_kwargs), backend=AttentionBackendName.COMFY_KITCHEN_INT8, **call_kwargs + ) + + @is_attention @require_torch_accelerator @pytest.mark.skipif(not IS_ROCM_SYSTEM, reason="K/V are only copied before native SDPA on ROCm.") From 388ce61b00186d698d1e550721ccefb253c8d665 Mon Sep 17 00:00:00 2001 From: asaiyume Date: Fri, 4 Dec 2026 18:43:09 +0800 Subject: [PATCH 4/4] Keep Comfy Kitchen attention tests in testing_utils/attention.py only --- tests/models/test_attention_dispatch.py | 82 ------------------------- 1 file changed, 82 deletions(-) diff --git a/tests/models/test_attention_dispatch.py b/tests/models/test_attention_dispatch.py index 79ae4cbe63f1..aabf8eeb3f2c 100644 --- a/tests/models/test_attention_dispatch.py +++ b/tests/models/test_attention_dispatch.py @@ -33,7 +33,6 @@ ) from diffusers.models.attention_dispatch import attention_backend as attention_backend_ctx from diffusers.models.transformers.transformer_flux import FluxAttention -from diffusers.utils import is_comfy_kitchen_available from ..testing_utils import ( IS_ROCM_SYSTEM, @@ -354,87 +353,6 @@ def test_output_close_to_native(self): assert cos > 0.99 -@is_attention -@pytest.mark.skipif(not torch.cuda.is_available(), reason="CUDA is required for the comfy_kitchen_int8 backend.") -@pytest.mark.skipif(not is_comfy_kitchen_available(), reason="`comfy-kitchen` is not available.") -class TestComfyKitchenInt8: - @staticmethod - def _qkv(seq_q=1024, seq_kv=1024, heads_q=4, heads_kv=4, head_dim=128, dtype=torch.bfloat16): - torch.manual_seed(0) - q = torch.randn(2, seq_q, heads_q, head_dim, device="cuda", dtype=dtype) - k = torch.randn(2, seq_kv, heads_kv, head_dim, device="cuda", dtype=dtype) - v = torch.randn(2, seq_kv, heads_kv, head_dim, device="cuda", dtype=dtype) - return q, k, v - - @staticmethod - def _assert_close_to_native(query, key, value, **kwargs): - with torch.no_grad(): - out = dispatch_attention_fn(query, key, value, backend=AttentionBackendName.COMFY_KITCHEN_INT8, **kwargs) - ref = dispatch_attention_fn(query, key, value, backend=AttentionBackendName.NATIVE, **kwargs) - assert out.shape == ref.shape - assert out.dtype == ref.dtype - assert not torch.equal(out, ref) - cos = F.cosine_similarity(out.float().flatten(), ref.float().flatten(), dim=0) - assert cos > 0.99 - - @pytest.mark.parametrize( - "qkv_kwargs", - [ - {}, - {"head_dim": 48}, - {"head_dim": 64}, - {"head_dim": 256}, - {"dtype": torch.float16}, - {"dtype": torch.float32}, - {"seq_kv": 77}, - ], - ids=["default", "head_dim_48", "head_dim_64", "head_dim_256", "fp16", "fp32", "cross_attention"], - ) - def test_output_close_to_native(self, qkv_kwargs): - self._assert_close_to_native(*self._qkv(**qkv_kwargs)) - - @pytest.mark.parametrize("mask_shape", [(2, 1024), (2, 1, 1, 1024), (2, 1, 1024, 1024)]) - @pytest.mark.parametrize("additive", [False, True]) - def test_attn_mask_close_to_native(self, mask_shape, additive): - mask = torch.ones(mask_shape, device="cuda", dtype=torch.bool) - mask[1, ..., 700:] = False - if additive: - mask = torch.zeros(mask_shape, device="cuda", dtype=torch.bfloat16).masked_fill(~mask, float("-inf")) - self._assert_close_to_native(*self._qkv(), attn_mask=mask) - - def test_masked_keys_do_not_change_output(self): - query, key, value = self._qkv() - mask = torch.ones(2, 1024, device="cuda", dtype=torch.bool) - mask[:, 700:] = False - changed_value = value.clone() - changed_value[:, 700:] = -value[:, 700:] - kwargs = {"attn_mask": mask, "backend": AttentionBackendName.COMFY_KITCHEN_INT8} - with torch.no_grad(): - out = dispatch_attention_fn(query, key, value, **kwargs) - changed_out = dispatch_attention_fn(query, key, changed_value, **kwargs) - unmasked_out = dispatch_attention_fn(query, key, value, backend=AttentionBackendName.COMFY_KITCHEN_INT8) - assert torch.equal(out, changed_out) - assert not torch.equal(out, unmasked_out) - - def test_grouped_query_attention_close_to_native(self): - self._assert_close_to_native(*self._qkv(heads_q=8, heads_kv=2), enable_gqa=True) - - @pytest.mark.parametrize( - "qkv_kwargs, call_kwargs, match", - [ - ({}, {"is_causal": True}, "is_causal"), - ({}, {"dropout_p": 0.1}, "dropout_p"), - ({"head_dim": 512}, {}, "head_dim"), - ], - ids=["causal", "dropout", "head_dim_512"], - ) - def test_unsupported_inputs_raise(self, qkv_kwargs, call_kwargs, match): - with pytest.raises(ValueError, match=match): - dispatch_attention_fn( - *self._qkv(**qkv_kwargs), backend=AttentionBackendName.COMFY_KITCHEN_INT8, **call_kwargs - ) - - @is_attention @require_torch_accelerator @pytest.mark.skipif(not IS_ROCM_SYSTEM, reason="K/V are only copied before native SDPA on ROCm.")