[Blackwell] Add CUDNN_ATTN and FLASHINFER_ATTN backends for diffusion (auto-route) (#3079)

Signed-off-by: lishunyang <lishunyang12@163.com>
Signed-off-by: Zhang <jianmusings@gmail.com>
Signed-off-by: Zhang Jian <jianmusings@gmail.com>
Co-authored-by: frauttauteffasu <247219357+frauttauteffasu@users.noreply.github.com>
Co-authored-by: Zhang Jian <jianmusings@gmail.com>
This commit is contained in:
authored and GitHub committed 2026-05-28 11:09:25 +08:00
1 parent 1903cee56a
commit 373d3c7476
11 files changed
+859 -41

No files matched your search

@@ -0,0 +1,104 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import torch
from torch.nn.attention import SDPBackend, sdpa_kernel
from vllm.logger import init_logger
from vllm_omni.diffusion.attention.backends.abstract import (
AttentionBackend,
AttentionImpl,
AttentionMetadata,
)
from vllm_omni.diffusion.attention.backends.sdpa import _maybe_reshape_attn_mask
logger = init_logger(__name__)
class CuDNNAttentionBackend(AttentionBackend):
accept_output_buffer: bool = True
@classmethod
def supports_attention_mask(cls) -> bool:
return True
@staticmethod
def get_supported_head_sizes() -> list[int]:
# cuDNN 9.5+ FMHA on Blackwell supports any head_dim divisible by 8
# up to 256 for BF16/FP16. Empty list = "accept any"; the sdpa_kernel
# fallback chain handles shapes cuDNN can't take.
return []
@staticmethod
def get_name() -> str:
return "CUDNN_ATTN"
@staticmethod
def get_impl_cls() -> type["CuDNNAttentionImpl"]:
return CuDNNAttentionImpl
class CuDNNAttentionImpl(AttentionImpl):
def __init__(
self,
num_heads: int,
head_size: int,
softmax_scale: float,
causal: bool = False,
num_kv_heads: int | None = None,
prefix: str = "",
**extra_impl_args,
) -> None:
self.causal = causal
self.softmax_scale = softmax_scale
def forward_cuda(
self,
query: torch.Tensor,
key: torch.Tensor,
value: torch.Tensor,
attn_metadata: AttentionMetadata | None = None,
) -> torch.Tensor:
attention_mask = None
if attn_metadata:
attention_mask = _maybe_reshape_attn_mask(query, key, attn_metadata.attn_mask, mask_mode="broadcast_k")
query, key, value = (x.permute(0, 2, 1, 3) for x in (query, key, value))
# Pin cuDNN exclusively. A priority list like [CUDNN, FLASH, MATH] hits a
# PyTorch SDPA dispatch quirk: when FLASH rejects a non-None attn_mask,
# cuDNN gets runtime-disabled in the same call and the dispatcher falls
# through to MATH even though cuDNN alone handles the mask fine
# (~11 ms vs ~215 ms for MATH on sm_120 HV-1.5 shapes).
#
# Fall back to the default SDPA dispatcher if cuDNN rejects the shape,
# e.g. under torch.compile where Dynamo sees a symbolic head_dim and
# cuDNN's kernel selection fails (observed in LTX-2 audio attention).
# The unpinned dispatcher then picks EFFICIENT/MATH instead of raising.
try:
with sdpa_kernel([SDPBackend.CUDNN_ATTENTION]):
output = torch.nn.functional.scaled_dot_product_attention(
query,
key,
value,
attn_mask=attention_mask,
dropout_p=0.0,
is_causal=self.causal,
scale=self.softmax_scale,
)
except RuntimeError as e:
if "No available kernel" not in str(e):
raise
logger.warning_once(
"cuDNN SDPA rejected this shape; falling back to default SDPA dispatcher. "
"Set DIFFUSION_ATTENTION_BACKEND=TORCH_SDPA for the full dispatcher path on every call."
)
output = torch.nn.functional.scaled_dot_product_attention(
query,
key,
value,
attn_mask=attention_mask,
dropout_p=0.0,
is_causal=self.causal,
scale=self.softmax_scale,
)
return output.permute(0, 2, 1, 3)
@@ -0,0 +1,183 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import torch
from vllm.logger import init_logger
from vllm_omni.diffusion.attention.backends.abstract import (
AttentionBackend,
AttentionImpl,
AttentionMetadata,
)
logger = init_logger(__name__)
try:
from flashinfer.prefill import single_prefill_with_kv_cache
HAS_FLASHINFER = True
except Exception as e:
HAS_FLASHINFER = False
logger.warning(
"FlashInfer is unavailable; FLASHINFER_ATTN backend will not work. Reason: %s",
e,
)
class FlashInferAttentionBackend(AttentionBackend):
accept_output_buffer: bool = True
@classmethod
def supports_attention_mask(cls) -> bool:
# FlashInfer single_prefill_with_kv_cache accepts a ``custom_mask`` kwarg
# (2D boolean, ``True`` = keep) for non-causal attention. See reviewer
# comment on #3079 and the flashinfer docs:
# https://docs.flashinfer.ai/generated/flashinfer.prefill.single_prefill_with_kv_cache.html
return True
@staticmethod
def get_supported_head_sizes() -> list[int]:
# FlashInfer dense prefill is well-tested for these head_dims on
# Ampere/Hopper/Blackwell. Covers the dominant diffusion DiT shapes
# (SD3 = 64, Flux/HV/Wan = 128, joint-attn = 256).
return [64, 128, 256]
@staticmethod
def get_name() -> str:
return "FLASHINFER_ATTN"
@staticmethod
def get_impl_cls() -> type["FlashInferAttentionImpl"]:
return FlashInferAttentionImpl
class FlashInferAttentionImpl(AttentionImpl):
def __init__(
self,
num_heads: int,
head_size: int,
softmax_scale: float,
causal: bool = False,
num_kv_heads: int | None = None,
prefix: str = "",
**extra_impl_args,
) -> None:
self.causal = causal
self.softmax_scale = softmax_scale
@staticmethod
def _pack_mask_for_flashinfer(
attn_mask: torch.Tensor, batch_size: int, qo_len: int, kv_len: int
) -> torch.Tensor | None:
"""Convert a diffusion-style attn_mask into the boolean form
FlashInfer's ``custom_mask`` expects (``True`` = keep).
Returns either ``(qo_len, kv_len)`` (shared across the batch) or
``(batch_size, qo_len, kv_len)`` (per-sample), or ``None`` when the
mask is all-keep (elide). Only boolean masks are handled here;
additive/float masks raise ``ValueError`` so the caller falls back to
SDPA, which applies them with the correct softmax semantics. Shape
mismatches also raise ``ValueError``.
"""
mask = attn_mask
if mask.dtype != torch.bool:
# Additive masks (0 / -inf / -1e4 / finfo.min) cannot be faithfully
# reduced to a boolean keep-mask here; SDPA handles them correctly.
raise ValueError(
f"non-boolean attn_mask (dtype={mask.dtype}); FlashInfer custom_mask "
"is boolean-only — deferring to SDPA"
)
# Diffusion masks arrive as (qo,kv), (1,1,kv), (B,1,1,kv), (B,1,qo,kv)
# or (B,H,qo,kv). The mask is identical across heads, so collapse the
# head dim, but keep a real batch dim — indexing mask[0] would reuse
# sample 0's padding for every sample (wrong under CFG / mixed lengths).
if mask.dim() == 4:
mask = mask[:, 0] # (B, qo|1, kv)
if mask.dim() == 3 and mask.shape[0] == 1:
mask = mask[0] # (qo|1, kv) — shared across the batch
try:
if mask.dim() >= 3:
mask = mask.broadcast_to((batch_size, qo_len, kv_len))
else:
mask = mask.broadcast_to((qo_len, kv_len))
except RuntimeError as e:
raise ValueError(
f"attn_mask shape {tuple(attn_mask.shape)} cannot broadcast to "
f"(batch={batch_size}, qo_len={qo_len}, kv_len={kv_len})"
) from e
if mask.all():
return None
# ``broadcast_to`` returns a non-contiguous view; materialize for the
# kernel, which reads from GPU memory directly.
return mask.contiguous()
def _sdpa_fallback(
self,
query: torch.Tensor,
key: torch.Tensor,
value: torch.Tensor,
attn_metadata: AttentionMetadata | None,
) -> torch.Tensor:
from vllm_omni.diffusion.attention.backends.sdpa import SDPAImpl
impl = SDPAImpl(
num_heads=query.shape[2],
head_size=query.shape[3],
softmax_scale=self.softmax_scale,
causal=self.causal,
)
return impl.forward_cuda(query, key, value, attn_metadata)
def forward_cuda(
self,
query: torch.Tensor,
key: torch.Tensor,
value: torch.Tensor,
attn_metadata: AttentionMetadata | None = None,
) -> torch.Tensor:
if not HAS_FLASHINFER:
raise ImportError(
"FLASHINFER_ATTN backend requires flashinfer. "
"Install it or set DIFFUSION_ATTENTION_BACKEND to another backend."
)
# Try the custom_mask path; if the mask can't be packed into the
# (qo_len, kv_len) layout FlashInfer expects, fall back to SDPA
# instead of risking an illegal-memory-access crash in the kernel.
# Input layout is (B, S, H, D); FlashInfer dense prefill takes (S, H, D).
batch_size = query.shape[0]
custom_mask = None
if attn_metadata is not None and attn_metadata.attn_mask is not None:
try:
custom_mask = self._pack_mask_for_flashinfer(
attn_metadata.attn_mask,
batch_size=batch_size,
qo_len=query.shape[1],
kv_len=key.shape[1],
)
except ValueError as e:
logger.debug("Falling back to SDPA for mask path: %s", e)
return self._sdpa_fallback(query, key, value, attn_metadata)
# FlashInfer cannot combine causal masking with a custom_mask; rather
# than silently dropping the explicit mask (diverging from SDPA), let
# SDPA handle the causal+mask case correctly.
if custom_mask is not None and self.causal:
logger.debug("causal=True with explicit attn_mask; deferring to SDPA")
return self._sdpa_fallback(query, key, value, attn_metadata)
outputs = []
for b in range(batch_size):
kwargs: dict = {
"sm_scale": self.softmax_scale,
"causal": self.causal,
"return_lse": False,
}
if custom_mask is not None:
kwargs["custom_mask"] = custom_mask if custom_mask.dim() == 2 else custom_mask[b]
out = single_prefill_with_kv_cache(query[b], key[b], value[b], **kwargs)
outputs.append(out)
if batch_size == 1:
return outputs[0].unsqueeze(0)
return torch.stack(outputs, dim=0)
@@ -59,6 +59,8 @@ class DiffusionAttentionBackendEnum(Enum, metaclass=_DiffusionBackendEnumMeta):
FLASH_ATTN = "vllm_omni.diffusion.attention.backends.flash_attn.FlashAttentionBackend"
TORCH_SDPA = "vllm_omni.diffusion.attention.backends.sdpa.SDPABackend"
SAGE_ATTN = "vllm_omni.diffusion.attention.backends.sage_attn.SageAttentionBackend"
CUDNN_ATTN = "vllm_omni.diffusion.attention.backends.cudnn_attn.CuDNNAttentionBackend"
FLASHINFER_ATTN = "vllm_omni.diffusion.attention.backends.flashinfer_attn.FlashInferAttentionBackend"
def get_path(self, include_classname: bool = True) -> str:
"""Get the class path for this backend (respects overrides).