Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions docs/source/en/optimization/attention_backends.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down Expand Up @@ -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 |
52 changes: 52 additions & 0 deletions src/diffusers/models/attention_dispatch.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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

Expand All @@ -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.
Expand Down Expand Up @@ -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 (
Expand Down Expand Up @@ -242,6 +258,9 @@ class AttentionBackendName(str, Enum):
# `xformers`
XFORMERS = "xformers"

# `comfy-kitchen`
COMFY_KITCHEN_INT8 = "comfy_kitchen_int8"


class _AttentionBackendRegistry:
_backends = {}
Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -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)
1 change: 1 addition & 0 deletions src/diffusers/utils/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
16 changes: 16 additions & 0 deletions src/diffusers/utils/import_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
"""
Expand Down
15 changes: 14 additions & 1 deletion tests/models/testing_utils/attention.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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,
Expand All @@ -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
Expand Down
Loading