[Core] Prototype diffusion attention execution contracts with FA4 (#7379)
This commit is contained in:
1 parent
97d6c693a6
commit
596487fe62
13 files changed
+1703
-27
No files matched your search
@@ -7,6 +7,10 @@ from typing import Any, Generic, Literal, TypeVar
|
||||
|
||||
import torch
|
||||
|
||||
from vllm_omni.diffusion.attention.capabilities import (
|
||||
ExecutionContext,
|
||||
ExecutionPathResult,
|
||||
)
|
||||
from vllm_omni.platforms import current_omni_platform
|
||||
|
||||
|
||||
@@ -132,6 +136,15 @@ class AttentionBackend(ABC):
|
||||
|
||||
return False
|
||||
|
||||
@classmethod
|
||||
def resolve_capabilities(cls, context: ExecutionContext) -> ExecutionPathResult:
|
||||
"""Return conservative pre-construction capabilities.
|
||||
|
||||
Unmigrated backends remain advisory so introducing the contract cannot
|
||||
reject an execution path that works today.
|
||||
"""
|
||||
return ExecutionPathResult.unmigrated(cls.get_name(), context)
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class QueryRange:
|
||||
@@ -218,6 +231,9 @@ class AttentionMetadata:
|
||||
# "valid_kv_length": int — contiguous valid K/V prefix length. Local
|
||||
# backends may slice it directly; ring backends trim each circulated
|
||||
# K/V block from the same global prefix.
|
||||
# "attention_mask_mode": "none" | "padding" | "arbitrary" — producer
|
||||
# assertion used by capability planning. "none" means a present mask
|
||||
# is semantically a no-op; absent means its contents are runtime-dependent.
|
||||
# "npu_attn_varlen": bool — model opt-in for the NPU packed varlen path
|
||||
# (TND npu_fusion_attention driven by cu_seqlens, mask never read).
|
||||
# Requires the [real, pad] two-document packing contract; see
|
||||
@@ -277,6 +293,21 @@ class AttentionImpl(ABC, Generic[T]):
|
||||
return True
|
||||
return kv_cache_dtype in cls._supported_kv_cache_dtypes.get(platform_key, set())
|
||||
|
||||
def resolve_execution_path(
|
||||
self,
|
||||
context: ExecutionContext,
|
||||
query: torch.Tensor,
|
||||
key: torch.Tensor,
|
||||
value: torch.Tensor,
|
||||
attn_metadata: T | None,
|
||||
) -> ExecutionPathResult:
|
||||
"""Resolve the complete path after backend initialization.
|
||||
|
||||
Subclasses report verified results; this inspection API does not enforce them.
|
||||
"""
|
||||
del query, key, value, attn_metadata
|
||||
return ExecutionPathResult.unmigrated(type(self).__name__, context)
|
||||
|
||||
def forward(
|
||||
self,
|
||||
query: torch.Tensor,
|
||||
|
||||
@@ -3,7 +3,9 @@
|
||||
|
||||
import os
|
||||
from collections.abc import Callable
|
||||
from dataclasses import replace
|
||||
from functools import cache, partial
|
||||
from typing import NamedTuple
|
||||
|
||||
import torch
|
||||
from vllm.logger import init_logger
|
||||
@@ -14,6 +16,16 @@ from vllm_omni.diffusion.attention.backends.utils.piecewise_attn import (
|
||||
piecewise_attn,
|
||||
run_paged_piecewise_plan,
|
||||
)
|
||||
from vllm_omni.diffusion.attention.capabilities import (
|
||||
CapabilityResult,
|
||||
CompilationMode,
|
||||
ExecutionContext,
|
||||
ExecutionPathResult,
|
||||
MaskMode,
|
||||
PackingMode,
|
||||
ParallelStrategy,
|
||||
SupportStatus,
|
||||
)
|
||||
from vllm_omni.diffusion.config import get_current_diffusion_config_or_none
|
||||
from vllm_omni.platforms import current_omni_platform
|
||||
|
||||
@@ -29,6 +41,133 @@ def _get_npu_compressed_causal_mask(device: torch.device) -> torch.Tensor:
|
||||
).contiguous()
|
||||
|
||||
|
||||
if not hasattr(torch.ops.vllm_omni, "fa4_dense_attention"):
|
||||
|
||||
@torch.library.custom_op("vllm_omni::fa4_dense_attention", mutates_args=())
|
||||
def _fa4_dense_attention_op(
|
||||
query: torch.Tensor,
|
||||
key: torch.Tensor,
|
||||
value: torch.Tensor,
|
||||
softmax_scale: float,
|
||||
causal: bool,
|
||||
deterministic: bool,
|
||||
) -> torch.Tensor:
|
||||
from vllm_omni.diffusion.attention.backends.utils.fa import flash_attn_func
|
||||
|
||||
if flash_attn_func is None:
|
||||
raise RuntimeError("CuTe FlashAttention-4 is unavailable")
|
||||
kwargs = {
|
||||
"causal": causal,
|
||||
"softmax_scale": softmax_scale,
|
||||
}
|
||||
if deterministic:
|
||||
kwargs["deterministic"] = True
|
||||
out = flash_attn_func(query, key, value, **kwargs)
|
||||
return out[0] if isinstance(out, tuple) else out
|
||||
|
||||
@_fa4_dense_attention_op.register_fake
|
||||
def _fa4_dense_attention_fake(
|
||||
query,
|
||||
key,
|
||||
value,
|
||||
softmax_scale,
|
||||
causal,
|
||||
deterministic,
|
||||
):
|
||||
# FA4 returns contiguous output even when Q is noncontiguous; V sets its head dimension.
|
||||
return query.new_empty((*query.shape[:-1], value.shape[-1]))
|
||||
|
||||
|
||||
_fa4_dense_attention_op = torch.ops.vllm_omni.fa4_dense_attention
|
||||
|
||||
|
||||
_PACKED_KEYS = ("cu_seqlens_q", "cu_seqlens_k", "max_seqlen_q", "max_seqlen_k")
|
||||
|
||||
|
||||
class _FlashAttentionMetadataPlan(NamedTuple):
|
||||
attention_mask: torch.Tensor | None
|
||||
mask_mode: MaskMode
|
||||
full_attn_spans: list[list[tuple[int, int]]] | None
|
||||
extra: dict
|
||||
packing_mode: PackingMode
|
||||
|
||||
|
||||
def _normalize_flash_attention_metadata(
|
||||
attn_metadata: AttentionMetadata | None,
|
||||
) -> _FlashAttentionMetadataPlan:
|
||||
attention_mask = attn_metadata.attn_mask if attn_metadata is not None else None
|
||||
full_attn_spans = attn_metadata.full_attn_spans if attn_metadata is not None else None
|
||||
extra = attn_metadata.extra if attn_metadata is not None else {}
|
||||
published_mask_mode = extra.get("attention_mask_mode")
|
||||
if attention_mask is None:
|
||||
mask_mode = MaskMode.NONE
|
||||
elif published_mask_mode is None:
|
||||
mask_mode = MaskMode.UNKNOWN
|
||||
else:
|
||||
try:
|
||||
mask_mode = MaskMode(published_mask_mode)
|
||||
except ValueError as error:
|
||||
raise ValueError(f"Unknown attention_mask_mode {published_mask_mode!r}") from error
|
||||
if mask_mode is MaskMode.UNKNOWN:
|
||||
raise ValueError("attention_mask_mode='unknown' is reserved for unpublished semantics")
|
||||
# Piecewise dispatch takes precedence and does not consume packed metadata.
|
||||
present_packed_keys = [key for key in _PACKED_KEYS if key in extra] if full_attn_spans is None else []
|
||||
if present_packed_keys and len(present_packed_keys) != len(_PACKED_KEYS):
|
||||
missing = sorted(set(_PACKED_KEYS) - set(present_packed_keys))
|
||||
raise ValueError(f"Incomplete packed FlashAttention metadata; missing {missing}")
|
||||
|
||||
packing_mode = PackingMode.NONE
|
||||
if present_packed_keys:
|
||||
cu_seqlens_q = extra["cu_seqlens_q"]
|
||||
packing_mode = PackingMode.MULTI_DOCUMENT if cu_seqlens_q.shape[0] > 3 else PackingMode.PACKED_PADDING
|
||||
return _FlashAttentionMetadataPlan(
|
||||
attention_mask=attention_mask,
|
||||
mask_mode=mask_mode,
|
||||
full_attn_spans=full_attn_spans,
|
||||
extra=extra,
|
||||
packing_mode=packing_mode,
|
||||
)
|
||||
|
||||
|
||||
def _flash_attention_execution_path(
|
||||
context: ExecutionContext,
|
||||
) -> ExecutionPathResult:
|
||||
if context.mask_mode is MaskMode.UNKNOWN:
|
||||
return ExecutionPathResult.unmigrated(
|
||||
"FLASH_ATTN",
|
||||
context,
|
||||
path="runtime_mask_dependent",
|
||||
)
|
||||
if not (
|
||||
context.platform == "cuda"
|
||||
and context.kernel_variant == "fa4"
|
||||
and context.dtype in {"bfloat16", "torch.bfloat16"}
|
||||
and context.causal is False
|
||||
and context.mask_mode is MaskMode.NONE
|
||||
and context.packing_mode is PackingMode.NONE
|
||||
and not context.piecewise
|
||||
and not context.paged_kv
|
||||
and context.kv_cache_dtype is None
|
||||
and context.parallel_strategy is ParallelStrategy.NONE
|
||||
and not context.outer_boundaries
|
||||
):
|
||||
return ExecutionPathResult.unmigrated(
|
||||
"FLASH_ATTN",
|
||||
context,
|
||||
path="unverified",
|
||||
)
|
||||
|
||||
return ExecutionPathResult(
|
||||
backend="FLASH_ATTN",
|
||||
path="fa4_dense",
|
||||
support=CapabilityResult.supported(),
|
||||
compilation_mode=CompilationMode.CUSTOM_OP,
|
||||
platform=context.platform,
|
||||
kernel_variant=context.kernel_variant,
|
||||
parallel_strategy=context.parallel_strategy,
|
||||
)
|
||||
|
||||
|
||||
class FlashAttentionBackend(AttentionBackend):
|
||||
accept_output_buffer: bool = True
|
||||
supports_piecewise_spans: bool = True
|
||||
@@ -74,6 +213,10 @@ class FlashAttentionBackend(AttentionBackend):
|
||||
def get_impl_cls() -> type["FlashAttentionImpl"]:
|
||||
return FlashAttentionImpl
|
||||
|
||||
@classmethod
|
||||
def resolve_capabilities(cls, context: ExecutionContext) -> ExecutionPathResult:
|
||||
return _flash_attention_execution_path(replace(context, kernel_variant=None))
|
||||
|
||||
|
||||
class FlashAttentionImpl(AttentionImpl[AttentionMetadata]):
|
||||
# Per-platform attention quantization support.
|
||||
@@ -108,11 +251,135 @@ class FlashAttentionImpl(AttentionImpl[AttentionMetadata]):
|
||||
self.softmax_scale = softmax_scale
|
||||
self.qkv_layout = qkv_layout
|
||||
self.is_cross_attn = role == "cross"
|
||||
from vllm_omni.diffusion.attention.backends.utils.fa import IS_AITER, IS_FLASH_ATTN_4
|
||||
|
||||
self._kernel_variant = "fa4" if IS_FLASH_ATTN_4 else "aiter" if IS_AITER else None
|
||||
cfg = get_current_diffusion_config_or_none()
|
||||
self.fa_deterministic = bool(getattr(cfg, "fa_deterministic", False)) if cfg is not None else False
|
||||
if backend_kwargs:
|
||||
logger.warning("FlashAttentionImpl ignoring backend_kwargs: %s", list(backend_kwargs.keys()))
|
||||
|
||||
def resolve_execution_path(
|
||||
self,
|
||||
context: ExecutionContext,
|
||||
query: torch.Tensor,
|
||||
key: torch.Tensor,
|
||||
value: torch.Tensor,
|
||||
attn_metadata: AttentionMetadata | None,
|
||||
) -> ExecutionPathResult:
|
||||
if context.platform == "npu":
|
||||
return self._resolve_npu_execution_path(context, query, key, attn_metadata)
|
||||
metadata = _normalize_flash_attention_metadata(attn_metadata)
|
||||
context = replace(
|
||||
context,
|
||||
kernel_variant=self._kernel_variant,
|
||||
dtype=str(query.dtype).removeprefix("torch."),
|
||||
causal=self.causal,
|
||||
mask_mode=metadata.mask_mode,
|
||||
packing_mode=metadata.packing_mode,
|
||||
piecewise=metadata.full_attn_spans is not None,
|
||||
kv_cache_dtype=metadata.extra.get("kv_cache_dtype"),
|
||||
)
|
||||
if context.platform == "rocm":
|
||||
return self._resolve_rocm_execution_path(context)
|
||||
result = _flash_attention_execution_path(context)
|
||||
if result.support.status is not SupportStatus.SUPPORTED:
|
||||
return result
|
||||
|
||||
from vllm_omni.diffusion.attention.backends.utils.fa import validate_fa4_head_dims
|
||||
|
||||
try:
|
||||
if query.dtype != key.dtype or query.dtype != value.dtype:
|
||||
raise ValueError("Q, K, and V dtypes must match")
|
||||
if query.device != key.device or query.device != value.device:
|
||||
raise ValueError("Q, K, and V devices must match")
|
||||
if query.shape[-1] != key.shape[-1]:
|
||||
raise ValueError("Q and K head dimensions must match")
|
||||
verified = validate_fa4_head_dims(query.shape[-1], value.shape[-1], 16 // value.element_size())
|
||||
except (AssertionError, ValueError) as error:
|
||||
return replace(
|
||||
result,
|
||||
support=CapabilityResult.unsupported(f"FA4: {error} Select compatible inputs or another backend."),
|
||||
)
|
||||
if not verified:
|
||||
return replace(
|
||||
result,
|
||||
support=CapabilityResult.unmigrated("Selected FA4 kernel has no available head-dimension validator"),
|
||||
compilation_mode=CompilationMode.EAGER_ONLY,
|
||||
)
|
||||
return result
|
||||
|
||||
@staticmethod
|
||||
def _resolve_rocm_execution_path(context: ExecutionContext) -> ExecutionPathResult:
|
||||
"""Describe AITER dispatch; device and compiler validation is pending."""
|
||||
result = ExecutionPathResult.unmigrated("FLASH_ATTN", context, path="rocm_unverified")
|
||||
if (
|
||||
context.kernel_variant != "aiter"
|
||||
or context.parallel_strategy is not ParallelStrategy.NONE
|
||||
or context.outer_boundaries
|
||||
or context.paged_kv
|
||||
or context.piecewise
|
||||
or context.kv_cache_dtype is not None
|
||||
):
|
||||
return result
|
||||
if context.packing_mode is not PackingMode.NONE:
|
||||
path = "rocm_packed_varlen"
|
||||
elif context.mask_mode is MaskMode.UNKNOWN:
|
||||
path = "rocm_runtime_mask_dependent"
|
||||
elif context.mask_mode is not MaskMode.NONE:
|
||||
path = "rocm_masked_varlen"
|
||||
else:
|
||||
path = "rocm_dense"
|
||||
return replace(
|
||||
result,
|
||||
path=path,
|
||||
support=CapabilityResult.unmigrated("AITER routing only; kernel and compilation validation require ROCm"),
|
||||
)
|
||||
|
||||
def _resolve_npu_execution_path(
|
||||
self,
|
||||
context: ExecutionContext,
|
||||
query: torch.Tensor,
|
||||
key: torch.Tensor,
|
||||
attn_metadata: AttentionMetadata | None,
|
||||
) -> ExecutionPathResult:
|
||||
"""Describe existing MindIE routing without claiming hardware validation.
|
||||
|
||||
NPU packing has its own opt-in and [real, pad] contract. In particular,
|
||||
incomplete packed metadata can fall back to a mask, so CUDA metadata
|
||||
normalization must not run here. No tensor values are inspected.
|
||||
"""
|
||||
context = replace(context, kernel_variant="mindiesd")
|
||||
result = ExecutionPathResult.unmigrated("FLASH_ATTN", context, path="npu_unverified")
|
||||
extra = attn_metadata.extra if attn_metadata else {}
|
||||
if (
|
||||
context.parallel_strategy is not ParallelStrategy.NONE
|
||||
or context.outer_boundaries
|
||||
or context.paged_kv
|
||||
or self.causal
|
||||
or extra.get("kv_cache_dtype") not in (None, "float", "auto")
|
||||
or (attn_metadata is not None and attn_metadata.full_attn_spans is not None)
|
||||
):
|
||||
return result
|
||||
|
||||
path = "npu_masked" if attn_metadata is not None and attn_metadata.attn_mask is not None else "npu_dense"
|
||||
if extra.get("npu_attn_varlen", False):
|
||||
if self._resolve_packed_seq_npu(query, key, extra) is not None:
|
||||
path = (
|
||||
"npu_prefix_kv_slice"
|
||||
if os.environ.get("MINDIE_SD_FA_TYPE") == "ascend_laser_attention"
|
||||
else "npu_packed_varlen"
|
||||
)
|
||||
else:
|
||||
# This route may reject the request if neither an explicit mask
|
||||
# nor usable valid_kv_length is supplied; it is not support.
|
||||
path = "npu_masked_fallback"
|
||||
return replace(
|
||||
result,
|
||||
path=path,
|
||||
support=CapabilityResult.unmigrated("NPU routing only; kernel and compilation validation require Ascend"),
|
||||
)
|
||||
|
||||
def _warn_fa_deterministic_non_dense(self, path: str) -> None:
|
||||
if not self.fa_deterministic:
|
||||
return
|
||||
@@ -401,6 +668,7 @@ class FlashAttentionImpl(AttentionImpl[AttentionMetadata]):
|
||||
"""CUDA/ROCm/MUSA flash attention implementation."""
|
||||
from vllm_omni.diffusion.attention.backends.utils.fa import (
|
||||
HAS_FLASH_ATTN,
|
||||
IS_FLASH_ATTN_4,
|
||||
flash_attn_func,
|
||||
flash_attn_varlen_func,
|
||||
)
|
||||
@@ -412,9 +680,10 @@ class FlashAttentionImpl(AttentionImpl[AttentionMetadata]):
|
||||
"Otherwise, use SDPA backend by setting DIFFUSION_ATTENTION_BACKEND=TORCH_SDPA"
|
||||
)
|
||||
|
||||
attention_mask = attn_metadata.attn_mask if attn_metadata is not None else None
|
||||
full_attn_spans = attn_metadata.full_attn_spans if attn_metadata is not None else None
|
||||
extra = attn_metadata.extra if attn_metadata is not None else {}
|
||||
metadata_plan = _normalize_flash_attention_metadata(attn_metadata)
|
||||
attention_mask = metadata_plan.attention_mask
|
||||
full_attn_spans = metadata_plan.full_attn_spans
|
||||
extra = metadata_plan.extra
|
||||
|
||||
# Try piecewise attention
|
||||
if full_attn_spans is not None:
|
||||
@@ -443,12 +712,7 @@ class FlashAttentionImpl(AttentionImpl[AttentionMetadata]):
|
||||
query_ranges=None if attn_metadata is None else attn_metadata.query_ranges,
|
||||
)
|
||||
|
||||
packed_keys = ("cu_seqlens_q", "cu_seqlens_k", "max_seqlen_q", "max_seqlen_k")
|
||||
present_packed_keys = [key for key in packed_keys if key in extra]
|
||||
if present_packed_keys:
|
||||
if len(present_packed_keys) != len(packed_keys):
|
||||
missing = sorted(set(packed_keys) - set(present_packed_keys))
|
||||
raise ValueError(f"Incomplete packed FlashAttention metadata; missing {missing}")
|
||||
if metadata_plan.packing_mode is not PackingMode.NONE:
|
||||
self._warn_fa_deterministic_non_dense("packed-varlen")
|
||||
return self._forward_varlen_packed(
|
||||
query,
|
||||
@@ -460,7 +724,14 @@ class FlashAttentionImpl(AttentionImpl[AttentionMetadata]):
|
||||
max_seqlen_k=extra["max_seqlen_k"],
|
||||
)
|
||||
|
||||
if attention_mask is not None and torch.any(~attention_mask):
|
||||
use_masked_path = False
|
||||
if attention_mask is not None:
|
||||
use_masked_path = (
|
||||
torch.any(~attention_mask)
|
||||
if metadata_plan.mask_mode is MaskMode.UNKNOWN
|
||||
else metadata_plan.mask_mode is not MaskMode.NONE
|
||||
)
|
||||
if use_masked_path:
|
||||
self._warn_fa_deterministic_non_dense("masked-varlen")
|
||||
return self._forward_varlen_masked(
|
||||
query,
|
||||
@@ -470,6 +741,15 @@ class FlashAttentionImpl(AttentionImpl[AttentionMetadata]):
|
||||
)
|
||||
|
||||
if flash_attn_func is not None:
|
||||
if IS_FLASH_ATTN_4:
|
||||
return _fa4_dense_attention_op(
|
||||
query,
|
||||
key,
|
||||
value,
|
||||
self.softmax_scale,
|
||||
self.causal,
|
||||
self.fa_deterministic,
|
||||
)
|
||||
fa_kwargs = {
|
||||
"causal": self.causal,
|
||||
"softmax_scale": self.softmax_scale,
|
||||
|
||||
@@ -59,6 +59,8 @@ def is_flash_attn_4_available() -> bool:
|
||||
# Bind via aliases so mypy does not treat each candidate import as a redefinition.
|
||||
flash_attn_func: FlashAttnFn | None = None
|
||||
flash_attn_varlen_func: FlashAttnFn | None = None
|
||||
IS_FLASH_ATTN_4 = False
|
||||
IS_AITER = False
|
||||
|
||||
if current_omni_platform.is_rocm():
|
||||
# ROCm: try Aiter first
|
||||
@@ -71,6 +73,7 @@ if current_omni_platform.is_rocm():
|
||||
|
||||
flash_attn_func = _fa_func
|
||||
flash_attn_varlen_func = _fa_varlen
|
||||
IS_AITER = True
|
||||
except (ImportError, ModuleNotFoundError):
|
||||
pass
|
||||
elif current_omni_platform.is_xpu():
|
||||
@@ -102,6 +105,7 @@ else:
|
||||
|
||||
flash_attn_func = _fa_func
|
||||
flash_attn_varlen_func = _fa_varlen
|
||||
IS_FLASH_ATTN_4 = True
|
||||
logger.info("Using CuTe FlashAttention-4 on Blackwell")
|
||||
except Exception as exc:
|
||||
# Optional FA4 dependencies may be present but ABI-incompatible
|
||||
@@ -166,6 +170,27 @@ else:
|
||||
HAS_FLASH_ATTN = flash_attn_func is not None or flash_attn_varlen_func is not None
|
||||
|
||||
|
||||
def validate_fa4_head_dims(head_dim: int, head_dim_v: int, alignment: int) -> bool:
|
||||
"""Use the selected FA4 implementation's constraints during path resolution.
|
||||
|
||||
Return False when its validator is unavailable; propagate kernel validation
|
||||
errors for the backend to report. Keep the private FA4 API dependency here,
|
||||
rather than duplicating architecture/version-specific dimension rules.
|
||||
This is a planning-time call, never part of compiled tensor execution.
|
||||
"""
|
||||
try:
|
||||
from flash_attn.cute.interface import _get_device_arch, _validate_head_dims
|
||||
except ImportError:
|
||||
return False
|
||||
|
||||
arch = _get_device_arch() // 10
|
||||
# FA4 routes SM80/SM120 through separate kernels and bypasses this validator.
|
||||
if arch not in (9, 10, 11):
|
||||
return False
|
||||
_validate_head_dims(head_dim, head_dim_v, arch, alignment)
|
||||
return True
|
||||
|
||||
|
||||
def _choose_vllm_flash_attn_version(
|
||||
device_major: int,
|
||||
requested: str | int | None,
|
||||
|
||||
@@ -0,0 +1,126 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from enum import Enum
|
||||
|
||||
|
||||
class SupportStatus(str, Enum):
|
||||
SUPPORTED = "supported"
|
||||
UNSUPPORTED = "unsupported"
|
||||
UNMIGRATED = "unmigrated"
|
||||
|
||||
|
||||
class CompilationMode(str, Enum):
|
||||
TRACEABLE = "traceable"
|
||||
CUSTOM_OP = "custom_op"
|
||||
EAGER_ONLY = "eager_only"
|
||||
|
||||
|
||||
class PackingMode(str, Enum):
|
||||
NONE = "none"
|
||||
PACKED_PADDING = "packed_padding"
|
||||
MULTI_DOCUMENT = "multi_document"
|
||||
|
||||
|
||||
class MaskMode(str, Enum):
|
||||
NONE = "none"
|
||||
PADDING = "padding"
|
||||
ARBITRARY = "arbitrary"
|
||||
UNKNOWN = "unknown"
|
||||
|
||||
|
||||
class ParallelStrategy(str, Enum):
|
||||
NONE = "none"
|
||||
ULYSSES = "ulysses"
|
||||
RING = "ring"
|
||||
HYBRID_ULYSSES_RING = "hybrid_ulysses_ring"
|
||||
ALLGATHER_KV = "allgather_kv"
|
||||
|
||||
|
||||
class OuterBoundary(str, Enum):
|
||||
HSDP = "hsdp"
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class CapabilityResult:
|
||||
status: SupportStatus
|
||||
reason: str | None = None
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
if self.status is SupportStatus.UNSUPPORTED and not self.reason:
|
||||
raise ValueError("UNSUPPORTED capability results require an actionable reason")
|
||||
|
||||
@classmethod
|
||||
def supported(cls) -> CapabilityResult:
|
||||
return cls(SupportStatus.SUPPORTED)
|
||||
|
||||
@classmethod
|
||||
def unsupported(cls, reason: str) -> CapabilityResult:
|
||||
return cls(SupportStatus.UNSUPPORTED, reason)
|
||||
|
||||
@classmethod
|
||||
def unmigrated(cls, reason: str | None = None) -> CapabilityResult:
|
||||
return cls(SupportStatus.UNMIGRATED, reason)
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class ExecutionContext:
|
||||
platform: str
|
||||
kernel_variant: str | None = None
|
||||
dtype: str | None = None
|
||||
causal: bool | None = None
|
||||
mask_mode: MaskMode = MaskMode.NONE
|
||||
packing_mode: PackingMode = PackingMode.NONE
|
||||
piecewise: bool = False
|
||||
paged_kv: bool = False
|
||||
kv_cache_dtype: str | None = None
|
||||
parallel_strategy: ParallelStrategy = ParallelStrategy.NONE
|
||||
require_fullgraph: bool = False
|
||||
outer_boundaries: frozenset[OuterBoundary] = frozenset()
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class ExecutionPathResult:
|
||||
backend: str
|
||||
path: str
|
||||
support: CapabilityResult
|
||||
compilation_mode: CompilationMode
|
||||
platform: str
|
||||
kernel_variant: str | None
|
||||
parallel_strategy: ParallelStrategy
|
||||
|
||||
@classmethod
|
||||
def unmigrated(
|
||||
cls,
|
||||
backend: str,
|
||||
context: ExecutionContext,
|
||||
*,
|
||||
path: str = "unmigrated",
|
||||
) -> ExecutionPathResult:
|
||||
return cls(
|
||||
backend=backend,
|
||||
path=path,
|
||||
support=CapabilityResult.unmigrated(),
|
||||
compilation_mode=CompilationMode.EAGER_ONLY,
|
||||
platform=context.platform,
|
||||
kernel_variant=context.kernel_variant,
|
||||
parallel_strategy=context.parallel_strategy,
|
||||
)
|
||||
|
||||
def requested_support(self, context: ExecutionContext) -> CapabilityResult:
|
||||
"""Validate request-level guarantees without changing path migration state."""
|
||||
if context.require_fullgraph and self.support.status is SupportStatus.UNMIGRATED:
|
||||
return CapabilityResult.unsupported(
|
||||
f"{self.backend} path {self.path!r} has no verified fullgraph declaration; "
|
||||
"use a verified path or disable the guaranteed-fullgraph request"
|
||||
)
|
||||
if self.support.status is not SupportStatus.SUPPORTED:
|
||||
return self.support
|
||||
if context.require_fullgraph and self.compilation_mode is CompilationMode.EAGER_ONLY:
|
||||
return CapabilityResult.unsupported(
|
||||
f"{self.backend} path {self.path!r} does not support guaranteed fullgraph compilation"
|
||||
)
|
||||
return CapabilityResult.supported()
|
||||
@@ -19,7 +19,13 @@ from vllm.model_executor.models.utils import extract_layer_index
|
||||
from vllm.v1.kv_cache_interface import FullAttentionSpec, KVCacheSpec
|
||||
|
||||
from vllm_omni.diffusion.attention.backends.abstract import AttentionBackend, AttentionImpl, AttentionMetadata
|
||||
from vllm_omni.diffusion.attention.backends.sdpa import SDPABackend
|
||||
from vllm_omni.diffusion.attention.backends.sdpa import SDPABackend, SDPAImpl
|
||||
from vllm_omni.diffusion.attention.capabilities import (
|
||||
ExecutionContext,
|
||||
ExecutionPathResult,
|
||||
OuterBoundary,
|
||||
ParallelStrategy,
|
||||
)
|
||||
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
|
||||
@@ -119,6 +125,8 @@ class Attention(nn.Module):
|
||||
|
||||
config = get_current_diffusion_config_or_none()
|
||||
attention_config = config.diffusion_attention_config if config is not None else None
|
||||
parallel_config = getattr(config, "parallel_config", None)
|
||||
self._hsdp_compile_boundary_enabled = bool(getattr(parallel_config, "use_hsdp", False))
|
||||
|
||||
from vllm_omni.diffusion.model_metadata import get_diffusion_model_metadata
|
||||
|
||||
@@ -131,6 +139,9 @@ class Attention(nn.Module):
|
||||
is DiffusionKVCacheMode.PAGED_SCHEDULER
|
||||
)
|
||||
self._scheduler_paged_kv = scheduler_paged_kv
|
||||
self.attn_backend: type[AttentionBackend] | None
|
||||
self.attention: AttentionImpl | nn.Module
|
||||
self.sdpa_fallback: SDPAImpl | None
|
||||
if custom_attention is None:
|
||||
attn_backend_cls, spec = get_attn_backend_for_role(
|
||||
role=role,
|
||||
@@ -166,7 +177,6 @@ class Attention(nn.Module):
|
||||
attn_backend_cls.get_name(),
|
||||
dense_backend_name,
|
||||
)
|
||||
parallel_config = getattr(config, "parallel_config", None)
|
||||
allgather_degree = getattr(parallel_config, "allgather_degree", 1)
|
||||
# TODO: Move AllGather-KV compatibility into an AttentionBackend capability
|
||||
# so validation does not depend on backend names.
|
||||
@@ -279,6 +289,7 @@ class Attention(nn.Module):
|
||||
|
||||
if self.paged_kv_cache_role is None:
|
||||
return None
|
||||
assert self.attn_backend is not None # Custom attention cannot opt into paged KV.
|
||||
dtype = self.paged_kv_cache_dtype or vllm_config.model_config.dtype
|
||||
# Keep backend layout discovery under the same config context used by
|
||||
# upstream vLLM's attention-spec collector. vLLM 0.29 moved the
|
||||
@@ -378,17 +389,68 @@ class Attention(nn.Module):
|
||||
value: torch.Tensor,
|
||||
attn_metadata: AttentionMetadata | None = None,
|
||||
) -> torch.Tensor:
|
||||
if torch.compiler.is_compiling() and is_forward_context_available():
|
||||
od_config = get_forward_context().omni_diffusion_config
|
||||
parallel_config = getattr(od_config, "parallel_config", None)
|
||||
if getattr(parallel_config, "use_hsdp", False):
|
||||
# Keep HSDP/FSDP2 parameter all-gather outside Inductor's
|
||||
# attention graph; otherwise scheduler dependency analysis can
|
||||
# fail on the fused attention region.
|
||||
return self._forward_hsdp_compile_boundary(query, key, value, attn_metadata)
|
||||
if torch.compiler.is_compiling() and self._uses_hsdp_compile_boundary():
|
||||
# Keep HSDP/FSDP2 parameter all-gather outside Inductor's
|
||||
# attention graph; otherwise scheduler dependency analysis can
|
||||
# fail on the fused attention region.
|
||||
return self._forward_hsdp_compile_boundary(query, key, value, attn_metadata)
|
||||
|
||||
return self._forward_impl(query, key, value, attn_metadata)
|
||||
|
||||
def _uses_hsdp_compile_boundary(self) -> bool:
|
||||
if self._hsdp_compile_boundary_enabled:
|
||||
return True
|
||||
if not is_forward_context_available():
|
||||
return False
|
||||
od_config = get_forward_context().omni_diffusion_config
|
||||
parallel_config = getattr(od_config, "parallel_config", None)
|
||||
return bool(getattr(parallel_config, "use_hsdp", False))
|
||||
|
||||
def resolve_execution_path(
|
||||
self,
|
||||
context: ExecutionContext,
|
||||
query: torch.Tensor,
|
||||
key: torch.Tensor,
|
||||
value: torch.Tensor,
|
||||
attn_metadata: AttentionMetadata | None,
|
||||
) -> ExecutionPathResult:
|
||||
"""Compose backend capabilities with outer Attention boundaries."""
|
||||
boundaries = set(context.outer_boundaries)
|
||||
if self._uses_hsdp_compile_boundary():
|
||||
boundaries.add(OuterBoundary.HSDP)
|
||||
active_strategy = self._get_active_parallel_strategy()
|
||||
strategy_name = active_strategy.name
|
||||
if self.use_ring and active_strategy.enabled and strategy_name == "ulysses":
|
||||
parallel_strategy = ParallelStrategy.HYBRID_ULYSSES_RING
|
||||
elif self.use_ring and active_strategy.enabled:
|
||||
parallel_strategy = ParallelStrategy.RING
|
||||
else:
|
||||
parallel_strategy = {
|
||||
"allgather_kv": ParallelStrategy.ALLGATHER_KV,
|
||||
"ulysses": ParallelStrategy.ULYSSES,
|
||||
}.get(strategy_name, ParallelStrategy.NONE)
|
||||
resolved_context = replace(
|
||||
context,
|
||||
outer_boundaries=frozenset(boundaries),
|
||||
paged_kv=self.is_paged_kv_active(),
|
||||
parallel_strategy=parallel_strategy,
|
||||
)
|
||||
resolver = getattr(self.attention, "resolve_execution_path", None)
|
||||
if not callable(resolver):
|
||||
return ExecutionPathResult.unmigrated(
|
||||
type(self.attention).__name__,
|
||||
resolved_context,
|
||||
)
|
||||
if not resolved_context.paged_kv:
|
||||
attn_metadata = self._with_kv_cache_dtype(attn_metadata)
|
||||
return resolver(
|
||||
resolved_context,
|
||||
query,
|
||||
key,
|
||||
value,
|
||||
attn_metadata,
|
||||
)
|
||||
|
||||
@torch.compiler.disable
|
||||
def _forward_hsdp_compile_boundary(
|
||||
self,
|
||||
@@ -422,10 +484,11 @@ class Attention(nn.Module):
|
||||
)
|
||||
use_paged_attention = paged_adapter is not None and self.paged_kv_cache_role is not None
|
||||
if use_paged_attention and not getattr(self.attn_backend, "supports_paged_kv", False):
|
||||
assert self.attn_backend is not None
|
||||
backend_name = (
|
||||
self.attn_backend.get_name() if self.attn_backend is not None else type(self.attention).__name__
|
||||
)
|
||||
raise NotImplementedError(
|
||||
f"Diffusion paged KV requires an Omni backend with paged support; "
|
||||
f"selected {self.attn_backend.get_name()}"
|
||||
f"Diffusion paged KV requires an Omni backend with paged support; selected {backend_name}"
|
||||
)
|
||||
if use_paged_attention and strategy is not self._no_parallel_strategy:
|
||||
strategy_name = strategy.name
|
||||
@@ -554,9 +617,11 @@ class Attention(nn.Module):
|
||||
self._scheduler_paged_kv
|
||||
and self.paged_kv_cache_role is not None
|
||||
and in_kv_memory_profile
|
||||
and cast(type[AttentionBackend], self.attn_backend).get_name() == "FLASH_ATTN"
|
||||
and self.attn_backend is not None
|
||||
and self.attn_backend.get_name() == "FLASH_ATTN"
|
||||
and not current_omni_platform.supports_diffusion_dense_flash_attention()
|
||||
):
|
||||
assert self.sdpa_fallback is not None
|
||||
logger.warning_once(
|
||||
"The startup KV memory profile is using SDPA because dense FLASH_ATTN is unavailable. "
|
||||
"Formal paged requests still use the platform-native paged attention backend."
|
||||
|
||||
Reference in new issue
Block a user