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 | diff --git a/src/diffusers/models/attention_dispatch.py b/src/diffusers/models/attention_dispatch.py index 9d2135034a9f..886228f09a34 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,30 @@ def _xformers_attention( out = out.flatten(2, 3) return out + + +@_AttentionBackendRegistry.register( + AttentionBackendName.COMFY_KITCHEN_INT8, + constraints=[_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, + _parallel_config: "ParallelConfig" | None = None, +) -> torch.Tensor: + 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) + + 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