[Diffusion][Attention] Support per-role attention backend via CLI (#2681)

Signed-off-by: gcanlin <canlinguosdu@gmail.com>
Signed-off-by: Hongsheng Liu <liuhongsheng4@huawei.com>
Co-authored-by: Hongsheng Liu <liuhongsheng4@huawei.com>
This commit is contained in:
Canlin GuoandHongsheng Liu authored and GitHub committed 2026-05-10 11:59:05 +08:00
1 parent 26d481fc84
commit 11c4c7f0ff
29 files changed
+1262 -106

No files matched your search

@@ -2,8 +2,8 @@
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from abc import ABC, abstractmethod
from dataclasses import dataclass
from typing import Generic, TypeVar
from dataclasses import dataclass, field
from typing import Any, Generic, TypeVar
import torch
@@ -64,6 +64,9 @@ class AttentionMetadata:
# a replicated tensor among processes appended to the front or rear of value, depends the joint_strategy
joint_strategy: str = "front"
# the strategy to joint the query, key, and value, can be "front" or "rear"
extra: dict[str, Any] = field(default_factory=dict)
# Opaque backend-specific per-forward parameters (e.g. block masks, KV indices).
# Backends MUST silently ignore unknown keys.
T = TypeVar("T", bound=AttentionMetadata)
@@ -79,6 +82,8 @@ class AttentionImpl(ABC, Generic[T]):
causal: bool = False,
num_kv_heads: int | None = None,
prefix: str = "",
qkv_layout: str | None = None,
backend_kwargs: dict[str, Any] | None = None,
**extra_impl_args,
) -> None:
raise NotImplementedError
@@ -43,11 +43,16 @@ class FlashAttentionImpl(AttentionImpl):
causal: bool = False,
num_kv_heads: int | None = None,
prefix: str = "",
qkv_layout: str | None = None,
backend_kwargs: dict | None = None,
**extra_impl_args,
) -> None:
self.num_heads = num_heads
self.causal = causal
self.softmax_scale = softmax_scale
self.qkv_layout = qkv_layout
if backend_kwargs:
logger.warning("FlashAttentionImpl ignoring backend_kwargs: %s", list(backend_kwargs.keys()))
@staticmethod
def _unwrap_flash_output(out: torch.Tensor | tuple[torch.Tensor, ...]) -> torch.Tensor:
@@ -230,6 +235,7 @@ class FlashAttentionImpl(AttentionImpl):
)
attention_mask = attn_metadata.attn_mask if attn_metadata else None
layout = self.qkv_layout or "BNSD"
output = attention_forward(
query,
key,
@@ -237,6 +243,6 @@ class FlashAttentionImpl(AttentionImpl):
attn_mask=attention_mask,
opt_mode="manual",
op_type="fused_attn_score",
layout="BNSD",
layout=layout,
)
return output
@@ -49,10 +49,13 @@ class SageAttentionImpl(AttentionImpl):
causal: bool = False,
num_kv_heads: int | None = None,
prefix: str = "",
backend_kwargs: dict | None = None,
**extra_impl_args,
) -> None:
self.causal = causal
self.softmax_scale = softmax_scale
if backend_kwargs:
logger.warning("SageAttentionImpl ignoring backend_kwargs: %s", list(backend_kwargs.keys()))
def forward_cuda(
self,
@@ -84,10 +84,13 @@ class SDPAImpl(AttentionImpl):
causal: bool = False,
num_kv_heads: int | None = None,
prefix: str = "",
backend_kwargs: dict | None = None,
**extra_impl_args,
) -> None:
self.causal = causal
self.softmax_scale = softmax_scale
if backend_kwargs:
logger.warning("SDPAImpl ignoring backend_kwargs: %s", list(backend_kwargs.keys()))
def _forward_impl(
self,
+43 -10
View File
@@ -16,7 +16,8 @@ from vllm_omni.diffusion.attention.backends.sdpa import SDPABackend
from vllm_omni.diffusion.attention.parallel import build_parallel_attention_strategy
from vllm_omni.diffusion.attention.parallel.base import NoParallelAttention
from vllm_omni.diffusion.attention.parallel.ring import RingParallelAttention
from vllm_omni.diffusion.attention.selector import get_attn_backend
from vllm_omni.diffusion.attention.selector import get_attn_backend_for_role
from vllm_omni.diffusion.config import get_current_diffusion_config_or_none
from vllm_omni.diffusion.distributed.parallel_state import get_sp_group
from vllm_omni.diffusion.forward_context import get_forward_context, is_forward_context_available
@@ -32,6 +33,11 @@ class Attention(nn.Module):
softmax_scale: float,
num_kv_heads: int | None = None,
prefix: str = "",
# Per-role backend selection (RFC: per-role attention backend)
role: str = "self",
role_category: str | None = None,
# Model-defined Q/K/V tensor layout hint for backend execution.
qkv_layout: str | None = None,
# ulysses attention
scatter_idx: int = 2,
gather_idx: int = 1,
@@ -39,7 +45,34 @@ class Attention(nn.Module):
skip_sequence_parallel: bool = False,
):
super().__init__()
self.attn_backend = get_attn_backend(-1)
self.role = role
self.role_category = role_category
self.qkv_layout = qkv_layout
# Resolve backend via role-aware config.
# The global diffusion config is set during model init via
# set_current_diffusion_config(); no env-var re-parsing needed here.
backend_kwargs: dict | None = None
self.backend_pref = None
config = get_current_diffusion_config_or_none()
attention_config = config.attention_config if config is not None else None
attn_backend_cls, spec = get_attn_backend_for_role(
role=role,
head_size=head_size,
attention_config=attention_config,
role_category=role_category,
)
if spec is not None:
backend_kwargs = spec.extra or None
self.backend_pref = spec.backend
logger.debug("Attention(role=%s) → backend=%s", role, spec.backend)
else:
logger.debug("Attention(role=%s) → platform default", role)
self.attn_backend = attn_backend_cls
self.attn_impl_cls = self.attn_backend.get_impl_cls()
self.attention = self.attn_impl_cls(
num_heads=num_heads,
@@ -47,6 +80,8 @@ class Attention(nn.Module):
softmax_scale=softmax_scale,
causal=causal,
num_kv_heads=num_kv_heads,
qkv_layout=qkv_layout,
backend_kwargs=backend_kwargs,
)
# Instantiate fallback backend for float32 support
self.sdpa_fallback = SDPABackend.get_impl_cls()(
@@ -55,8 +90,8 @@ class Attention(nn.Module):
softmax_scale=softmax_scale,
causal=causal,
num_kv_heads=num_kv_heads,
qkv_layout=qkv_layout,
)
self.backend_pref = None
self.softmax_scale = softmax_scale
self.scatter_idx = scatter_idx
@@ -69,21 +104,19 @@ class Attention(nn.Module):
self.ring_pg = None
self.ring_runner = None
try:
config = get_forward_context().omni_diffusion_config
self.backend_pref = config.attention_backend
if config is not None:
if config.parallel_config.ring_degree > 1:
self.use_ring = True
try:
sp_group = get_sp_group()
self.ring_pg = sp_group.ring_group
self.ring_runner = RingParallelAttention(sp_group)
self.ring_runner = RingParallelAttention(
sp_group,
attn_backend_pref=self.backend_pref,
)
except Exception:
self.use_ring = False
self.ring_runner = None
except Exception:
self.use_ring = False
self.ring_runner = None
self.parallel_strategy = build_parallel_attention_strategy(
scatter_idx=scatter_idx,
+5 -12
View File
@@ -18,12 +18,11 @@ from vllm_omni.diffusion.attention.parallel.base import (
)
from vllm_omni.diffusion.distributed.group_coordinator import SequenceParallelGroupCoordinator
# from vllm_omni.diffusion.attention.backends.ring_selector import AttnType # Already imported above
from vllm_omni.diffusion.forward_context import get_forward_context
if TYPE_CHECKING:
from vllm_omni.diffusion.attention.backends.abstract import AttentionMetadata
logger = init_logger(__name__)
@dataclass(frozen=True, slots=True)
class _RingCtx(ParallelAttentionContext):
@@ -108,13 +107,8 @@ class RingParallelAttention:
softmax_scale = query.shape[-1] ** -0.5
backend_pref = self.attn_backend_pref
if backend_pref is None:
try:
config = get_forward_context().omni_diffusion_config
# config might not have attention_backend attribute if not updated
backend_pref = getattr(config, "attention_backend", None)
except Exception:
backend_pref = None
if backend_pref is not None:
backend_pref = backend_pref.lower()
# Determine attention type with fallback chain: FA3 -> FA2 -> SDPA
# FP32 is not supported by Flash Attention, force SDPA
@@ -122,7 +116,6 @@ class RingParallelAttention:
backend_pref = "sdpa"
elif not HAS_FA3 and not HAS_FLASH_ATTN:
if backend_pref != "sdpa":
logger = init_logger(__name__)
logger.warning_once("Flash Attention (FA2/FA3) is not available! Force enabling SDPA.")
backend_pref = "sdpa"
@@ -135,7 +128,7 @@ class RingParallelAttention:
if attn_metadata.joint_strategy is not None:
joint_strategy = attn_metadata.joint_strategy
if backend_pref == "sdpa" or backend_pref == "torch":
if backend_pref in {"sdpa", "torch", "torch_sdpa"}:
from vllm_omni.diffusion.attention.backends.ring_pytorch_attn import ring_pytorch_attn_func
return ring_pytorch_attn_func(
+101 -36
View File
@@ -3,23 +3,16 @@
"""
Diffusion attention backend selector.
This module provides the interface for selecting diffusion attention backends.
The actual backend selection logic is delegated to the platform layer
(vllm_omni.platforms), similar to how vLLM handles attention backend selection.
Usage:
from vllm_omni.diffusion.attention.selector import get_attn_backend
# Get the appropriate backend for current platform
backend_cls = get_attn_backend(head_size=64)
# Or override via environment variable
# export DIFFUSION_ATTENTION_BACKEND=FLASH_ATTN
This module resolves diffusion attention backends from:
1. per-role AttentionConfig
2. platform default
"""
from __future__ import annotations
import importlib
import os
from functools import cache
from typing import TYPE_CHECKING
from vllm.logger import init_logger
@@ -27,6 +20,9 @@ from vllm_omni.diffusion.attention.backends.abstract import (
AttentionBackend,
)
if TYPE_CHECKING:
from vllm_omni.diffusion.data import AttentionConfig, AttentionSpec
logger = init_logger(__name__)
@@ -52,34 +48,103 @@ def _load_backend_cls(cls_path: str) -> type[AttentionBackend]:
@cache
def get_attn_backend(head_size: int) -> type[AttentionBackend]:
"""
Get attention backend for diffusion models.
def _cached_get_backend_cls(
backend_name: str | None,
head_size: int,
) -> type[AttentionBackend]:
"""Cache backend class resolution by (backend_name, head_size).
The backend selection is delegated to the current platform
(vllm_omni.platforms.current_omni_platform), which selects the
appropriate backend based on:
1. User override via DIFFUSION_ATTENTION_BACKEND environment variable
2. Platform-specific defaults and capabilities
This is similar to how vLLM's get_attn_backend_cls works, where the
platform layer decides which backend to use based on hardware capabilities.
Args:
head_size: Head size for attention computation (may affect backend selection)
Returns:
The selected attention backend class
This ensures platform validation (compute capability checks, package
availability, etc.) runs only once per unique (backend_name, head_size)
combination, avoiding repeated log messages.
"""
from vllm_omni.platforms import current_omni_platform
# Check environment variable for user override
selected_backend = os.environ.get("DIFFUSION_ATTENTION_BACKEND")
# Delegate to platform for backend selection
backend_cls_path = current_omni_platform.get_diffusion_attn_backend_cls(
selected_backend=selected_backend,
selected_backend=backend_name,
head_size=head_size,
)
return _load_backend_cls(backend_cls_path)
@cache
def _log_backend_resolution(
role: str,
role_category: str | None,
backend_name: str,
source: str,
) -> None:
if role_category is not None:
logger.info(
"Resolved diffusion attention backend '%s' for role=%r (role_category=%r) via %s",
backend_name,
role,
role_category,
source,
)
return
logger.info(
"Resolved diffusion attention backend '%s' for role=%r via %s",
backend_name,
role,
source,
)
def get_attn_backend_for_role(
role: str,
head_size: int,
attention_config: AttentionConfig | None = None,
role_category: str | None = None,
) -> tuple[type[AttentionBackend], AttentionSpec | None]:
"""
Get attention backend for a specific attention role.
Lookup precedence:
1. attention_config.per_role[role] — exact match
2. attention_config.per_role[role_category] — category fallback
3. attention_config.default — global default
4. Platform default — hardware-specific
Args:
role: Attention role string (e.g. "self", "cross", "joint",
"ltx2.audio_to_video")
head_size: Head size for attention computation
attention_config: The AttentionConfig from OmniDiffusionConfig.
If None, falls back to platform default behavior.
role_category: Optional category for fallback (e.g. "cross" for
"ltx2.audio_to_video")
Returns:
Tuple of (backend_class, AttentionSpec or None).
AttentionSpec is None when using platform default without explicit config.
"""
# 1. Try config from OmniDiffusionConfig
spec = None
source = None
if attention_config is not None:
spec, source = attention_config.resolve_with_source(
role=role,
role_category=role_category,
)
if spec is not None:
backend_cls = _cached_get_backend_cls(spec.backend, head_size)
_log_backend_resolution(
role=role,
role_category=role_category,
backend_name=backend_cls.get_name(),
source=source or "attention_config",
)
return backend_cls, spec
# 2. Platform default
backend_cls = _cached_get_backend_cls(None, head_size)
_log_backend_resolution(
role=role,
role_category=role_category,
backend_name=backend_cls.get_name(),
source="platform default",
)
return backend_cls, None