[Model] Add MiniMax H3 diffusion support (#5691)
This commit is contained in:
1 parent
727f90958e
commit
24741961eb
45 files changed
+7356
-31
No files matched your search
@@ -79,6 +79,10 @@ class AttentionMetadata:
|
||||
# Well-known optional keys (convention, not required on all forwards):
|
||||
# "kv_cache_dtype": str | None — quantized KV dtype (e.g. "fp8"); backends
|
||||
# decide whether/how to apply.
|
||||
# "cu_seqlens_q" / "cu_seqlens_k": int32 CUDA tensors describing packed
|
||||
# variable-length query/key sequences for FlashAttention.
|
||||
# "max_seqlen_q" / "max_seqlen_k": maximum sequence lengths paired with
|
||||
# the packed cu_seqlens tensors.
|
||||
|
||||
# Piecewise attention metadata (mixed causal/full masks).
|
||||
# full_attn_spans: per-sample [start, end) spans in global coordinates using full attention.
|
||||
|
||||
@@ -141,6 +141,46 @@ class FlashAttentionImpl(AttentionImpl):
|
||||
out_unpad = self._unwrap_flash_output(out_unpad)
|
||||
return _pad_input(out_unpad, indices_q, query.size(0), query_length)
|
||||
|
||||
def _forward_varlen_packed(
|
||||
self,
|
||||
query: torch.Tensor,
|
||||
key: torch.Tensor,
|
||||
value: torch.Tensor,
|
||||
*,
|
||||
cu_seqlens_q: torch.Tensor,
|
||||
cu_seqlens_k: torch.Tensor,
|
||||
max_seqlen_q: int,
|
||||
max_seqlen_k: int,
|
||||
) -> torch.Tensor:
|
||||
"""Run FlashAttention directly on an already packed sequence.
|
||||
|
||||
Some diffusion transformers already maintain exact packed-document
|
||||
boundaries. Reusing those boundaries avoids rebuilding boolean masks
|
||||
and gathering/scattering Q/K/V in every attention layer.
|
||||
"""
|
||||
from vllm_omni.diffusion.attention.backends.utils.fa import (
|
||||
flash_attn_varlen_func,
|
||||
)
|
||||
|
||||
if flash_attn_varlen_func is None:
|
||||
raise ImportError("Packed variable-length attention requires flash_attn_varlen_func")
|
||||
if query.shape[0] != 1 or key.shape[0] != 1 or value.shape[0] != 1:
|
||||
raise ValueError("Packed variable-length attention currently requires batch size 1")
|
||||
|
||||
out = flash_attn_varlen_func(
|
||||
q=query.flatten(0, 1),
|
||||
k=key.flatten(0, 1),
|
||||
v=value.flatten(0, 1),
|
||||
cu_seqlens_q=cu_seqlens_q,
|
||||
cu_seqlens_k=cu_seqlens_k,
|
||||
max_seqlen_q=max_seqlen_q,
|
||||
max_seqlen_k=max_seqlen_k,
|
||||
causal=self.causal,
|
||||
softmax_scale=self.softmax_scale,
|
||||
)
|
||||
out = self._unwrap_flash_output(out)
|
||||
return out.reshape_as(query)
|
||||
|
||||
def _forward_varlen_dense(
|
||||
self,
|
||||
query: torch.Tensor,
|
||||
@@ -206,6 +246,7 @@ class FlashAttentionImpl(AttentionImpl):
|
||||
|
||||
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 {}
|
||||
|
||||
# Try piecewise attention
|
||||
if full_attn_spans is not None:
|
||||
@@ -233,6 +274,22 @@ class FlashAttentionImpl(AttentionImpl):
|
||||
query_ranges=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}")
|
||||
return self._forward_varlen_packed(
|
||||
query,
|
||||
key,
|
||||
value,
|
||||
cu_seqlens_q=extra["cu_seqlens_q"],
|
||||
cu_seqlens_k=extra["cu_seqlens_k"],
|
||||
max_seqlen_q=extra["max_seqlen_q"],
|
||||
max_seqlen_k=extra["max_seqlen_k"],
|
||||
)
|
||||
|
||||
if attention_mask is not None and torch.any(~attention_mask):
|
||||
return self._forward_varlen_masked(
|
||||
query,
|
||||
|
||||
@@ -23,6 +23,19 @@ HAS_FA3 = False
|
||||
fa3_fwd_func = None # Low-level forward function (_flash_attn_forward)
|
||||
fa3_attn_func = None # High-level attention function (flash_attn_func)
|
||||
|
||||
# FA4 detection. The CuTe API returns LSE directly, so it can participate in
|
||||
# Ring Attention's numerically stable block-wise output accumulation.
|
||||
HAS_FA4 = False
|
||||
fa4_attn_func = None
|
||||
try:
|
||||
from flash_attn.cute import flash_attn_func as fa4_attn_func # noqa: F401
|
||||
|
||||
HAS_FA4 = True
|
||||
except Exception:
|
||||
# Optional CuTe/CUTLASS/Quack components can be importable but
|
||||
# ABI-incompatible. Treat the whole optional backend as unavailable.
|
||||
pass
|
||||
|
||||
# Try flash_attn_interface first (from flash-attention source build)
|
||||
try:
|
||||
from flash_attn_interface import _flash_attn_forward as fa3_fwd_func # noqa: F401
|
||||
|
||||
@@ -9,9 +9,11 @@ import torch
|
||||
from .ring_globals import (
|
||||
HAS_AITER,
|
||||
HAS_FA3,
|
||||
HAS_FA4,
|
||||
HAS_FLASH_ATTN,
|
||||
HAS_FLASHINFER,
|
||||
fa3_fwd_func,
|
||||
fa4_attn_func,
|
||||
)
|
||||
|
||||
_scaled_dot_product_flash_attention = torch.ops.aten._scaled_dot_product_flash_attention
|
||||
@@ -190,6 +192,40 @@ def fa3_forward(q, k, v, dropout_p, softmax_scale, causal, window_size, softcap,
|
||||
flash_attn3_func_forward = fa3_forward
|
||||
|
||||
|
||||
def flash_attn4_func_forward(
|
||||
q,
|
||||
k,
|
||||
v,
|
||||
dropout_p=0.0,
|
||||
softmax_scale=None,
|
||||
causal=False,
|
||||
window_size=(-1, -1),
|
||||
softcap=None,
|
||||
alibi_slopes=None,
|
||||
return_softmax=False,
|
||||
):
|
||||
"""FA4 forward pass returning the LSE required by Ring Attention."""
|
||||
del dropout_p, alibi_slopes, return_softmax
|
||||
assert HAS_FA4, "FA4 is not available"
|
||||
assert fa4_attn_func is not None, "FA4 high-level API is not available"
|
||||
|
||||
left, right = window_size if window_size else (-1, -1)
|
||||
out, softmax_lse = fa4_attn_func(
|
||||
q,
|
||||
k,
|
||||
v,
|
||||
softmax_scale=softmax_scale,
|
||||
causal=causal,
|
||||
window_size=(
|
||||
None if left == -1 else left,
|
||||
None if right == -1 else right,
|
||||
),
|
||||
softcap=softcap or 0.0,
|
||||
return_lse=True,
|
||||
)
|
||||
return out, softmax_lse
|
||||
|
||||
|
||||
def flash_attn_forward_aiter(
|
||||
q,
|
||||
k,
|
||||
|
||||
@@ -15,6 +15,7 @@ from .ring_globals import (
|
||||
)
|
||||
from .ring_kernels import (
|
||||
flash_attn3_func_forward,
|
||||
flash_attn4_func_forward,
|
||||
flash_attn_forward,
|
||||
flash_attn_forward_aiter,
|
||||
flashinfer_attn_forward,
|
||||
@@ -32,6 +33,7 @@ class AttnType(Enum):
|
||||
AITER = "aiter"
|
||||
FA = "fa"
|
||||
FA3 = "fa3"
|
||||
FA4 = "fa4"
|
||||
FLASHINFER = "flashinfer"
|
||||
TORCH = "torch"
|
||||
SAGE_AUTO = "sage_auto"
|
||||
@@ -77,6 +79,9 @@ def select_flash_attn_impl(
|
||||
elif impl_type == AttnType.FA3:
|
||||
return flash_attn3_func_forward
|
||||
|
||||
elif impl_type == AttnType.FA4:
|
||||
return flash_attn4_func_forward
|
||||
|
||||
elif impl_type == AttnType.FLASHINFER:
|
||||
return flashinfer_attn_forward
|
||||
|
||||
|
||||
@@ -22,6 +22,15 @@ from vllm_omni.platforms import current_omni_platform
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
|
||||
def _is_blackwell() -> bool:
|
||||
try:
|
||||
capability = current_omni_platform.get_device_capability()
|
||||
except Exception:
|
||||
return False
|
||||
return capability is not None and capability.major >= 10
|
||||
|
||||
|
||||
# Flash Attention function detection with fallback chain
|
||||
flash_attn_func = None
|
||||
flash_attn_varlen_func = None
|
||||
@@ -48,12 +57,27 @@ elif current_omni_platform.is_musa():
|
||||
except (ImportError, ModuleNotFoundError):
|
||||
pass
|
||||
else:
|
||||
# CUDA: try FA3 -> FA2 fallback chain
|
||||
# CUDA: prefer the CuTe-based FA4 package when present. This matters on
|
||||
# Blackwell, where an importable Hopper-only FA3 wheel may otherwise be
|
||||
# selected and fail at launch with "no kernel image is available".
|
||||
if _is_blackwell():
|
||||
try:
|
||||
from flash_attn.cute import flash_attn_func, flash_attn_varlen_func # noqa: F401
|
||||
|
||||
logger.info("Using CuTe FlashAttention-4 on Blackwell")
|
||||
except Exception as exc:
|
||||
# Optional FA4 dependencies may be present but ABI-incompatible
|
||||
# (for example, mismatched CUTLASS DSL and Quack builds). Treat
|
||||
# that as unavailable so backend discovery can continue.
|
||||
logger.debug("CuTe FlashAttention-4 is unavailable: %s", exc)
|
||||
|
||||
# Try FA3 -> FA2 fallback chain.
|
||||
# Try FA3 from fa3-fwd PyPI package
|
||||
try:
|
||||
from fa3_fwd_interface import flash_attn_func, flash_attn_varlen_func # noqa: F401
|
||||
except (ImportError, ModuleNotFoundError):
|
||||
pass
|
||||
if flash_attn_func is None:
|
||||
try:
|
||||
from fa3_fwd_interface import flash_attn_func, flash_attn_varlen_func # noqa: F401
|
||||
except (ImportError, ModuleNotFoundError):
|
||||
pass
|
||||
|
||||
# Fallback: Try FA3 from flash-attention source build
|
||||
if flash_attn_func is None:
|
||||
@@ -100,7 +124,16 @@ def is_flash_attn_installed() -> bool:
|
||||
Shared by CUDA/ROCm/MUSA platforms.
|
||||
"""
|
||||
try:
|
||||
# Check for any FA backend: FA3 (fa3_fwd_interface, flash_attn_interface) or FA2 (flash_attn)
|
||||
# Check for any FA backend: FA4 (flash_attn.cute), FA3
|
||||
# (fa3_fwd_interface, flash_attn_interface), or FA2 (flash_attn).
|
||||
if _is_blackwell():
|
||||
try:
|
||||
from flash_attn.cute import flash_attn_varlen_func # noqa: F401
|
||||
|
||||
return True
|
||||
except Exception as exc:
|
||||
logger.debug("CuTe FlashAttention-4 is unavailable: %s", exc)
|
||||
|
||||
# Try FA3 from fa3-fwd PyPI package
|
||||
try:
|
||||
import fa3_fwd_interface # noqa: F401
|
||||
|
||||
Reference in new issue
Block a user