[Attention] Enable FA4 sparse MQA decode on Blackwell (#55866)

Signed-off-by: Simon Veitner <sveitner@redhat.com>
Co-authored-by: Lucas Wilkinson <lwilkins@redhat.com>
Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: Lucas Wilkinson <LucasWilkinson@users.noreply.github.com>
Co-authored-by: Matthew Bonanni <mbonanni@redhat.com>
This commit is contained in:
simon-veitner-redhat
2026-10-13 09:31:37 -04:00
committed by GitHub
co-authored by Lucas Wilkinson Claude Lucas Wilkinson Matthew Bonanni
parent 0838cd6593
commit 31e90ac370
14 changed files with 860 additions and 383 deletions
@@ -661,6 +661,7 @@ class MLAAttention(nn.Module, AttentionLayerBase):
"FLASHMLA_SPARSE",
"FLASHINFER_MLA_SPARSE",
"FLASHINFER_MLA_SPARSE_SM120",
"FLASH_ATTN_MLA_SPARSE_FA4",
"DEEPSEEK_V32_INDEXER",
):
from vllm.v1.attention.backends.mla.compressor_utils import (
@@ -751,7 +752,7 @@ class MLAAttention(nn.Module, AttentionLayerBase):
def _uses_flat_kv_cache(self) -> bool:
backend = self.attn_backend.get_name()
return backend == "FLASHINFER_MLA_SPARSE" or (
return backend in ("FLASHINFER_MLA_SPARSE", "FLASH_ATTN_MLA_SPARSE_FA4") or (
backend == "FLASHMLA_SPARSE"
and self.kv_cache_dtype not in ("fp8_ds_mla", "nvfp4_ds_mla")
)
@@ -1857,6 +1858,9 @@ def _use_masked_mha(
seq_len: int,
has_context: bool,
) -> bool:
if backend_name == "FLASH_ATTN_MLA_SPARSE_FA4":
# Its prefill batches run on FlashInfer's kernel, so it shares those rows.
backend_name = "FLASHINFER_MLA_SPARSE"
thresholds = (
_MASKED_MHA_THRESHOLDS.get((qk_head_dim, v_head_dim), {})
.get(backend_name, {})
@@ -36,12 +36,18 @@ from vllm.utils.torch_utils import (
is_quantized_kv_cache,
np_to_pinned_tensor,
)
from vllm.v1.attention.backend import AttentionMetadataBuilder
from vllm.v1.attention.backend import AttentionLayer, AttentionMetadataBuilder
from vllm.v1.attention.backends.fa_utils import get_flash_attn_version
from vllm.v1.attention.backends.mla.index_group import (
HiSparseMLAIndexGroup,
SparseMLAIndexGroup,
SparseMLAIndexGroupBuilder,
)
from vllm.v1.attention.backends.mla.sparse_utils import (
flat_kv_row_view,
triton_convert_req_index_to_global_index,
triton_filter_and_convert_dcp_index,
)
from vllm.v1.attention.backends.utils import split_decodes_and_prefills
from vllm.v1.attention.ops.dcp import MLADCPManager
from vllm.v1.attention.ops.merge_attn_states import merge_attn_states
@@ -630,6 +636,9 @@ class SparseMLACommonImpl(MLACommonBaseImpl[T], SharedTopkIndicesBuffer, Generic
"""Sparse MLA base with dense and masked-MHA prefill paths."""
is_sparse = True
# Reuse the index group's top-k conversion only for uniform decode batches
# of multi-layer groups; other batches convert per layer.
group_conversion_decode_only: ClassVar[bool] = False
def __init__(
self,
@@ -728,6 +737,154 @@ class SparseMLACommonImpl(MLACommonBaseImpl[T], SharedTopkIndicesBuffer, Generic
return_valid_counts=return_valid_counts,
)
def forward_mqa(
self,
q: torch.Tensor | tuple[torch.Tensor, torch.Tensor],
kv_c_and_k_pe_cache: torch.Tensor,
attn_metadata: T,
layer: AttentionLayer,
) -> tuple[torch.Tensor, torch.Tensor | None]:
assert self.topk_indices_buffer is not None
num_tokens = q[0].shape[0] if isinstance(q, tuple) else q.shape[0]
topk = self.topk_indices_buffer[:num_tokens]
num_decode_tokens = attn_metadata.num_decode_tokens
block_size = attn_metadata.block_size
index_group = self.index_group
if not isinstance(index_group, HiSparseMLAIndexGroup):
_, block_stride_rows = flat_kv_row_view(kv_c_and_k_pe_cache, block_size)
if self.dcp_world_size > 1:
physical_topk, valid_counts = triton_filter_and_convert_dcp_index(
attn_metadata.req_id_per_token[:num_tokens],
attn_metadata.block_table,
topk,
dcp_size=self.dcp_world_size,
dcp_rank=self.dcp_rank,
cp_kv_cache_interleave_size=attn_metadata.cp_kv_cache_interleave_size,
BLOCK_SIZE=block_size,
BLOCK_STRIDE_ROWS=block_stride_rows,
NUM_TOPK_TOKENS=topk.shape[1],
return_valid_counts=True,
)
elif self.group_conversion_decode_only and not (
index_group is not None
and index_group.num_layers > 1
and num_decode_tokens >= num_tokens
):
physical_topk, valid_counts = triton_convert_req_index_to_global_index(
attn_metadata.req_id_per_token[:num_tokens],
attn_metadata.block_table,
topk,
BLOCK_SIZE=block_size,
BLOCK_STRIDE_ROWS=block_stride_rows,
NUM_TOPK_TOKENS=topk.shape[1],
return_valid_counts=True,
)
else:
physical_topk, valid_counts = self._convert_logical_to_physical_topk(
topk,
attn_metadata,
block_stride_rows=block_stride_rows,
return_valid_counts=True,
)
return self._forward_mqa_kernel(
q,
kv_c_and_k_pe_cache,
physical_topk,
valid_counts,
layer=layer,
block_size=block_size,
is_decode=num_decode_tokens >= num_tokens,
)
assert self.dcp_world_size == 1
layer_index = self.index_group_index
hot_cache = index_group.physical_kv_cache(layer_index).view(
kv_c_and_k_pe_cache.dtype
)
assert hot_cache.is_contiguous(), "HiSparse hot buffer must be contiguous"
decode_out = decode_lse = None
if num_decode_tokens:
physical_topk, valid_counts = index_group.convert_logical_to_physical_topk(
layer_index,
topk[:num_decode_tokens],
attn_metadata,
block_stride_rows=None,
return_valid_counts=True,
)
q_decode = (
(q[0][:num_decode_tokens], q[1][:num_decode_tokens])
if isinstance(q, tuple)
else q[:num_decode_tokens]
)
decode_out, decode_lse = self._forward_mqa_kernel(
q_decode,
hot_cache,
physical_topk,
valid_counts,
layer=layer,
block_size=block_size,
is_decode=True,
)
if num_decode_tokens >= num_tokens:
return decode_out, decode_lse
cache = index_group.cache(layer_index)
if num_decode_tokens == 0 and cache.all_context_pages_resident:
physical_topk, valid_counts = index_group.convert_logical_to_physical_topk(
layer_index,
topk,
attn_metadata,
block_stride_rows=None,
return_valid_counts=True,
)
prefill_cache = hot_cache
else:
prefill_cache, block_table, req_ids = index_group.stage_prefill_rows(
layer_index, kv_c_and_k_pe_cache, attn_metadata
)
physical_topk, valid_counts = triton_convert_req_index_to_global_index(
req_ids,
block_table,
topk[num_decode_tokens:],
BLOCK_SIZE=block_size,
NUM_TOPK_TOKENS=topk.shape[1],
return_valid_counts=True,
)
q_prefill = (
(q[0][num_decode_tokens:], q[1][num_decode_tokens:])
if isinstance(q, tuple)
else q[num_decode_tokens:]
)
prefill_out, prefill_lse = self._forward_mqa_kernel(
q_prefill,
prefill_cache,
physical_topk,
valid_counts,
layer=layer,
block_size=block_size,
is_decode=False,
)
if decode_out is None:
return prefill_out, prefill_lse
out = torch.cat((decode_out, prefill_out))
if decode_lse is None:
return out, None
assert prefill_lse is not None
return out, torch.cat((decode_lse, prefill_lse))
def _forward_mqa_kernel(
self,
q: torch.Tensor | tuple[torch.Tensor, torch.Tensor],
kv_cache: torch.Tensor,
topk_indices: torch.Tensor,
valid_counts: torch.Tensor,
*,
layer: AttentionLayer,
block_size: int,
is_decode: bool,
) -> tuple[torch.Tensor, torch.Tensor | None]:
raise NotImplementedError
@staticmethod
def masked_mha_workspace_fits(prefill: MLACommonPrefillMetadata) -> bool:
"""Whether this prefill batch's top-k masks fit the workspace."""