[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).
+5
View File
@@ -691,6 +691,10 @@ class DiffusionEngine:
dummy_audio = np.random.randn(audio_sr * 2).astype(np.float32)
prompt.setdefault("multi_modal_data", {})["audio"] = dummy_audio
# Audio pipelines round audio token count from num_frames; the default
# of 1 yields seq_len=1 K/V which cuDNN SDPA refuses under torch.compile.
# 2 is the minimum that produces audio_num_frames > 1.
num_frames = 2 if supports_audio_input or supports_audio_output(self.od_config.model_class_name) else 1
req = OmniDiffusionRequest(
prompts=[prompt],
request_ids=["dummy_req_id"],
@@ -698,6 +702,7 @@ class DiffusionEngine:
height=height,
width=width,
num_inference_steps=num_inference_steps,
num_frames=num_frames,
# Keep warmup path minimal and robust across text encoders.
# Some models may fail when warmup implicitly triggers
# classifier-free guidance with an empty negative prompt.
+10 -2
View File
@@ -94,10 +94,18 @@ class RotaryEmbedding(CustomOp):
self.interleaved = not is_neox_style
self.apply_rotary_emb_flash_attn = None
self.has_mindie = False
# ``find_spec("flash_attn")`` is True as long as *any* package publishes
# the ``flash_attn`` namespace — including ``flash-attn-4``, which ships
# only ``flash_attn.cute`` and no ``flash_attn.ops``. Guard the import
# so a partial namespace doesn't crash the RoPE init; the CUDA forward
# path uses ``vllm.vllm_flash_attn.layers.rotary`` anyway.
if find_spec("flash_attn") is not None:
from flash_attn.ops.triton.rotary import apply_rotary
try:
from flash_attn.ops.triton.rotary import apply_rotary
self.apply_rotary_emb_flash_attn = apply_rotary
self.apply_rotary_emb_flash_attn = apply_rotary
except ImportError:
pass
if find_spec("mindiesd") is not None:
self.has_mindie = True
@@ -67,13 +67,20 @@ def _make_rms_norm(hidden_size: int, *, eps: float, elementwise_affine: bool) ->
def apply_interleaved_rotary_emb(x: torch.Tensor, freqs: tuple[torch.Tensor, torch.Tensor]) -> torch.Tensor:
cos, sin = freqs
x_real, x_imag = x.unflatten(2, (-1, 2)).unbind(-1) # [B, S, C // 2]
# Concrete pair count instead of -1 keeps SDPA shape static under torch.compile.
x_real, x_imag = x.unflatten(2, (x.shape[2] // 2, 2)).unbind(-1) # [B, S, C // 2]
x_rotated = torch.stack([-x_imag, x_real], dim=-1).flatten(2)
out = (x.float() * cos + x_rotated.float() * sin).to(x.dtype)
return out
def apply_split_rotary_emb(x: torch.Tensor, freqs: tuple[torch.Tensor, torch.Tensor]) -> torch.Tensor:
def apply_split_rotary_emb(
x: torch.Tensor,
freqs: tuple[torch.Tensor, torch.Tensor],
*,
head_dim: int,
) -> torch.Tensor:
# `head_dim` is plumbed in (not inferred via `-1`) so SDPA shape stays static under torch.compile.
cos, sin = freqs
x_dtype = x.dtype
@@ -83,7 +90,7 @@ def apply_split_rotary_emb(x: torch.Tensor, freqs: tuple[torch.Tensor, torch.Ten
# The cos/sin batch dim may only be broadcastable, so take batch size from x
b = x.shape[0]
_, h, t, _ = cos.shape
x = x.reshape(b, t, h, -1).swapaxes(1, 2)
x = x.reshape(b, t, h, head_dim).swapaxes(1, 2)
needs_reshape = True
# Split last dim (2*r) into (d=2, r)
@@ -110,7 +117,7 @@ def apply_split_rotary_emb(x: torch.Tensor, freqs: tuple[torch.Tensor, torch.Ten
out = out.reshape(*out.shape[:-2], last)
if needs_reshape:
out = out.swapaxes(1, 2).reshape(b, t, -1)
out = out.swapaxes(1, 2).reshape(b, t, h * head_dim)
out = out.to(dtype=x_dtype)
return out
@@ -488,12 +495,14 @@ class LTX2AudioVideoAttnProcessor:
key, key_rotary_emb if key_rotary_emb is not None else query_rotary_emb
)
elif attn.rope_type == "split":
query = apply_split_rotary_emb(query, query_rotary_emb)
key = apply_split_rotary_emb(key, key_rotary_emb if key_rotary_emb is not None else query_rotary_emb)
query = apply_split_rotary_emb(query, query_rotary_emb, head_dim=attn.head_dim)
key = apply_split_rotary_emb(
key, key_rotary_emb if key_rotary_emb is not None else query_rotary_emb, head_dim=attn.head_dim
)
query = query.unflatten(2, (attn.heads, -1))
key = key.unflatten(2, (attn.heads, -1))
value = value.unflatten(2, (attn.heads, -1))
query = query.unflatten(2, (attn.heads, attn.head_dim))
key = key.unflatten(2, (attn.heads, attn.head_dim))
value = value.unflatten(2, (attn.heads, attn.head_dim))
attn_metadata = AttentionMetadata(attn_mask=attention_mask) if attention_mask is not None else None
hidden_states = attn.attn(query, key, value, attn_metadata)
@@ -502,7 +511,7 @@ class LTX2AudioVideoAttnProcessor:
# LTX-2.3: per-head gated attention
if attn.to_gate_logits is not None:
hidden_states = hidden_states.unflatten(2, (attn.heads, -1)) # [B, T, H, D]
hidden_states = hidden_states.unflatten(2, (attn.heads, attn.head_dim)) # [B, T, H, D]
# 2.0 * sigmoid so zero-init gates produce 1.0 (identity)
gates = 2.0 * torch.sigmoid(gate_logits) # [B, T, H]
hidden_states = hidden_states * gates.unsqueeze(-1)
@@ -1391,9 +1400,11 @@ class LTX2AudioVideoRotaryPosEmbed(nn.Module):
# Reshape freqs to be compatible with multi-head attention
b = cos_freq.shape[0]
t = cos_freq.shape[1]
# Concrete per-head dim instead of -1 — see apply_split_rotary_emb
r = self.dim // self.num_attention_heads // 2
cos_freq = cos_freq.reshape(b, t, self.num_attention_heads, -1)
sin_freq = sin_freq.reshape(b, t, self.num_attention_heads, -1)
cos_freq = cos_freq.reshape(b, t, self.num_attention_heads, r)
sin_freq = sin_freq.reshape(b, t, self.num_attention_heads, r)
cos_freqs = torch.swapaxes(cos_freq, 1, 2) # (B,H,T,D//2)
sin_freqs = torch.swapaxes(sin_freq, 1, 2) # (B,H,T,D//2)
@@ -157,6 +157,9 @@ class _VideoAudioScheduler:
class LTX2Pipeline(nn.Module, CFGParallelMixin, ProgressBarMixin):
# Audio is diffused jointly with video; warmup must size audio tokens.
support_audio_output = True
def __init__(
self,
*,
@@ -115,6 +115,9 @@ class LTX23Pipeline(nn.Module, ProgressBarMixin):
- CPU offloading: text encoder, connectors, VAE, vocoder stay on CPU
"""
# Audio is diffused jointly with video; warmup must size audio tokens.
support_audio_output = True
def __init__(
self,
*,