Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
207 changes: 151 additions & 56 deletions vllm/v1/attention/backends/mla/flashmla_sparse.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
)
from vllm.v1.attention.backends.mla.sparse_utils import (
triton_convert_req_index_to_global_index,
triton_filter_and_convert_dcp_index,
)
from vllm.v1.attention.backends.utils import (
reshape_attn_output_for_spec_decode,
Expand Down Expand Up @@ -496,6 +497,13 @@ def build(
) -> FlashMLASparseMetadata:
metadata = super().build(common_prefix_len, common_attn_metadata, fast_build)

# The DCP index filter needs the real interleave size. The dataclass
# default is 1, so leaving this unset silently assumes interleave=1 and
# would filter against the wrong ownership stride.
metadata.cp_kv_cache_interleave_size = (
self.vllm_config.parallel_config.cp_kv_cache_interleave_size
)

fp8_use_mixed_batch = self.num_heads < MIN_HEADS_FOR_BF16_PREFILL
metadata.fp8_use_mixed_batch = fp8_use_mixed_batch
if self.use_fp8_kv_cache:
Expand All @@ -512,6 +520,8 @@ def build(


class FlashMLASparseImpl(SparseMLACommonImpl[FlashMLASparseMetadata]):
can_return_lse_for_decode: bool = True

@staticmethod
def _compute_fp8_decode_padded_heads(num_heads: int) -> int:
# FP8 decode kernel only supports h_q = 64 or 128
Expand Down Expand Up @@ -590,18 +600,39 @@ def _forward_bf16_kv(
kv_c_and_k_pe_cache: torch.Tensor,
topk_indices: torch.Tensor,
attn_metadata: FlashMLASparseMetadata,
) -> torch.Tensor:
# Convert per-request indices to global slots (decode) or workspace
# offsets (prefill). req_id_per_token covers the whole batch; slice it
# to the MQA tokens (q may exclude prefill tokens routed to dense MHA).
topk_indices, topk_length = triton_convert_req_index_to_global_index(
attn_metadata.req_id_per_token[: topk_indices.shape[0]],
attn_metadata.block_table,
topk_indices,
BLOCK_SIZE=attn_metadata.block_size,
NUM_TOPK_TOKENS=topk_indices.shape[1],
return_valid_counts=True,
)
) -> tuple[torch.Tensor, torch.Tensor | None]:
# Convert per-request indices to physical cache slots. Under DCP the
# top-k indices are global token positions, while each rank owns only
# its local KV-cache shard. Filter out indices owned by other ranks
# before translating the remaining positions through the local block
# table. Using the non-DCP converter here silently maps global indices
# to unrelated local cache slots and corrupts decode outputs.
req_id_per_token = attn_metadata.req_id_per_token[
: topk_indices.shape[0]
]
if self.dcp_world_size > 1:
topk_indices, topk_length = triton_filter_and_convert_dcp_index(
req_id_per_token,
attn_metadata.block_table,
topk_indices,
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=attn_metadata.block_size,
NUM_TOPK_TOKENS=topk_indices.shape[1],
return_valid_counts=True,
)
else:
topk_indices, topk_length = triton_convert_req_index_to_global_index(
req_id_per_token,
attn_metadata.block_table,
topk_indices,
BLOCK_SIZE=attn_metadata.block_size,
NUM_TOPK_TOKENS=topk_indices.shape[1],
return_valid_counts=True,
)

return self._bf16_flash_mla_kernel(
q,
Expand All @@ -616,7 +647,7 @@ def _forward_fp8_kv_separate_prefill_decode(
kv_c_and_k_pe_cache: torch.Tensor,
topk_indices: torch.Tensor,
attn_metadata: FlashMLASparseMetadata,
) -> torch.Tensor:
) -> tuple[torch.Tensor, torch.Tensor | None]:
fp8_metadata = attn_metadata.fp8_extra_metadata
assert isinstance(fp8_metadata, FlashMLASparseMetadata.FP8SeparatePrefillDecode)
num_decodes = fp8_metadata.num_decodes
Expand All @@ -642,25 +673,43 @@ def _forward_fp8_kv_separate_prefill_decode(
# For BF16 cache: always use global cache slots (no workspace)
# prefill_workspace_starts has been adjusted in-place per chunk so
# prefill indices automatically come out chunk-local
topk_indices, topk_length = triton_convert_req_index_to_global_index(
attn_metadata.req_id_per_token[: topk_indices.shape[0]],
attn_metadata.block_table,
topk_indices,
BLOCK_SIZE=attn_metadata.block_size,
NUM_TOPK_TOKENS=topk_indices.shape[1],
HAS_PREFILL_WORKSPACE=has_prefill_workspace,
prefill_workspace_request_ids=prefill_request_ids,
prefill_workspace_starts=prefill_workspace_starts,
return_valid_counts=True,
)
req_id_per_token = attn_metadata.req_id_per_token[
: topk_indices.shape[0]
]
if self.dcp_world_size > 1:
topk_indices, topk_length = triton_filter_and_convert_dcp_index(
req_id_per_token,
attn_metadata.block_table,
topk_indices,
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=attn_metadata.block_size,
NUM_TOPK_TOKENS=topk_indices.shape[1],
return_valid_counts=True,
)
else:
topk_indices, topk_length = triton_convert_req_index_to_global_index(
req_id_per_token,
attn_metadata.block_table,
topk_indices,
BLOCK_SIZE=attn_metadata.block_size,
NUM_TOPK_TOKENS=topk_indices.shape[1],
HAS_PREFILL_WORKSPACE=has_prefill_workspace,
prefill_workspace_request_ids=prefill_request_ids,
prefill_workspace_starts=prefill_workspace_starts,
return_valid_counts=True,
)

fp8_metadata = attn_metadata.fp8_extra_metadata
assert isinstance(fp8_metadata, FlashMLASparseMetadata.FP8SeparatePrefillDecode)

def _fp8_decode(
q: torch.Tensor,
topk_indices: torch.Tensor,
) -> torch.Tensor:
) -> tuple[torch.Tensor, torch.Tensor | None]:
# Reshape q: (num_decode_tokens, num_heads, head_dim)
# -> (num_decodes, seq_len, num_heads, head_dim)
q = reshape_query_for_spec_decode(q, num_decodes)
Expand All @@ -669,20 +718,28 @@ def _fp8_decode(
# -> (num_decodes, seq_len, topk)
topk_indices = topk_indices.view(num_decodes, seq_len, -1)
assert fp8_metadata.decode is not None
attn_out, _ = self._fp8_flash_mla_kernel(
attn_out, lse = self._fp8_flash_mla_kernel(
q=q,
kv_c_and_k_pe_cache=kv_c_and_k_pe_cache,
topk_indices=topk_indices,
kernel_metadata=fp8_metadata.decode.kernel_metadata,
)
# Reshape output: (num_decodes, seq_len, num_heads, head_dim_v)
# -> (num_decode_tokens, num_heads, head_dim_v)
return reshape_attn_output_for_spec_decode(attn_out)
attn_out = reshape_attn_output_for_spec_decode(attn_out)
if self.need_to_return_lse_for_decode and lse is not None:
# _fp8_flash_mla_kernel normalizes LSE to
# (num_decodes, seq_len, num_heads).
lse = lse.view(-1, lse.shape[-1])
else:
lse = None
return attn_out, lse

# Pure decode: direct call without allocation
decode_lse = None
if num_decode_tokens > 0 and num_prefill_tokens == 0:
assert fp8_metadata.decode is not None
attn_out = _fp8_decode(q, topk_indices)
attn_out, decode_lse = _fp8_decode(q, topk_indices)
else:
# Mixed or pure prefill: allocate output tensor
attn_out = q.new_empty(
Expand All @@ -692,10 +749,11 @@ def _fp8_decode(
)

if num_decode_tokens > 0:
attn_out[:num_decode_tokens] = _fp8_decode(
decode_out, decode_lse = _fp8_decode(
q[:num_decode_tokens],
topk_indices[:num_decode_tokens],
)
attn_out[:num_decode_tokens] = decode_out

assert fp8_metadata.prefill is not None
for chunk in fp8_metadata.prefill.chunks:
Expand All @@ -712,53 +770,75 @@ def _fp8_decode(
chunk_topk_indices_workspace = topk_indices[chunk.tokens_slice]
chunk_topk_length = topk_length[chunk.tokens_slice]

attn_out[chunk.tokens_slice] = self._bf16_flash_mla_kernel(
chunk_out, _ = self._bf16_flash_mla_kernel(
chunk_q,
chunk_workspace,
chunk_topk_indices_workspace,
chunk_topk_length,
)
attn_out[chunk.tokens_slice] = chunk_out

return attn_out
return attn_out, decode_lse

def _forward_fp8_kv_mixed_batch(
self,
q: torch.Tensor,
kv_c_and_k_pe_cache: torch.Tensor,
topk_indices: torch.Tensor,
attn_metadata: FlashMLASparseMetadata,
) -> torch.Tensor:
) -> tuple[torch.Tensor, torch.Tensor | None]:
"""Mixed batch FP8 forward path that treats all tokens as one batch.

This is equivalent to main branch's approach and avoids the BF16
prefill kernel which has head padding overhead when num_heads is small.
Used when use_mixed_batch is True.
"""
# Convert per-request indices to global slots (decode) or workspace
# offsets (prefill).
topk_indices = triton_convert_req_index_to_global_index(
attn_metadata.req_id_per_token[: topk_indices.shape[0]],
attn_metadata.block_table,
topk_indices,
BLOCK_SIZE=attn_metadata.block_size,
NUM_TOPK_TOKENS=topk_indices.shape[1],
)
# Convert global top-k positions to this rank's physical cache slots.
req_id_per_token = attn_metadata.req_id_per_token[
: topk_indices.shape[0]
]
if self.dcp_world_size > 1:
topk_indices = triton_filter_and_convert_dcp_index(
req_id_per_token,
attn_metadata.block_table,
topk_indices,
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=attn_metadata.block_size,
NUM_TOPK_TOKENS=topk_indices.shape[1],
)
else:
topk_indices = triton_convert_req_index_to_global_index(
req_id_per_token,
attn_metadata.block_table,
topk_indices,
BLOCK_SIZE=attn_metadata.block_size,
NUM_TOPK_TOKENS=topk_indices.shape[1],
)

assert attn_metadata.fp8_extra_metadata is not None
assert isinstance(
attn_metadata.fp8_extra_metadata, FlashMLASparseMetadata.FP8KernelMetadata
)
fp8_metadata = attn_metadata.fp8_extra_metadata

_attn_out, _ = self._fp8_flash_mla_kernel(
_attn_out, lse = self._fp8_flash_mla_kernel(
q=q.unsqueeze(0), # unsqueeze to add batch_dim: (T, H, D) -> (1, T, H, D)
kv_c_and_k_pe_cache=kv_c_and_k_pe_cache,
topk_indices=topk_indices.unsqueeze(0), # (T, topk) -> (1, T, topk)
kernel_metadata=fp8_metadata,
)

# Output is (1, T, H, D_v), squeeze back to (T, H, D_v)
return _attn_out.squeeze(0)
attn_out = _attn_out.squeeze(0)
if self.need_to_return_lse_for_decode and lse is not None:
lse = lse.view(-1, lse.shape[-1])
else:
lse = None
return attn_out, lse

def _fp8_flash_mla_kernel(
self,
Expand Down Expand Up @@ -797,6 +877,12 @@ def _fp8_flash_mla_kernel(
if actual_num_heads < padded_num_heads:
out = out[:, :, :actual_num_heads, :]

# FlashMLA returns LSE as (batch, num_heads, seq_len), while DCP
# reduction expects (num_tokens, num_heads).
lse = lse.transpose(1, 2)
if actual_num_heads < padded_num_heads:
lse = lse[:, :, :actual_num_heads]

return out, lse

def _bf16_flash_mla_kernel(
Expand All @@ -805,35 +891,43 @@ def _bf16_flash_mla_kernel(
kv_c_and_k_pe_cache: torch.Tensor,
topk_indices: torch.Tensor,
topk_length: torch.Tensor | None = None,
) -> torch.Tensor:
) -> tuple[torch.Tensor, torch.Tensor | None]:
num_tokens = q.shape[0]
# DCP may gather query heads across ranks, so use the runtime head
# count instead of the local configured count.
num_heads = q.shape[1]
kv_c_and_k_pe_cache = kv_c_and_k_pe_cache.view(
-1, 1, kv_c_and_k_pe_cache.shape[-1]
)

# NOTE(Chen): kernel requires num_local_head to be a multiple of
# 64 on hopper and 128 on blackwell
if self.num_heads % self.prefill_padding != 0:
assert self.prefill_padding % self.num_heads == 0
if num_heads % self.prefill_padding != 0:
assert self.prefill_padding % num_heads == 0
logger.warning_once(
f"Padding num_heads from {self.num_heads} to "
f"Padding num_heads from {num_heads} to "
f"{self.prefill_padding} for BF16 sparse prefill kernel"
)
q_padded = q.new_empty((q.shape[0], self.prefill_padding, q.shape[2]))
q_padded[:, : self.num_heads, :] = q
q_padded[:, :num_heads, :] = q
q = q_padded

topk_indices = topk_indices.view(num_tokens, 1, -1)
output = flash_mla_sparse_fwd(
# flash_mla_sparse_fwd returns (output, max_logits, lse).
kernel_out = flash_mla_sparse_fwd(
q,
kv_c_and_k_pe_cache,
topk_indices,
self.softmax_scale,
topk_length=topk_length,
)[0]
)
output = kernel_out[0][:, :num_heads, :]

lse = None
if self.need_to_return_lse_for_decode:
lse = kernel_out[2][:, :num_heads]

output = output[:, : self.num_heads, :]
return output
return output, lse

def forward_mqa(
self,
Expand All @@ -859,17 +953,18 @@ def forward_mqa(

use_fp8_cache = self.kv_cache_dtype == "fp8_ds_mla"

lse = None
if not use_fp8_cache:
attn_out = self._forward_bf16_kv(
attn_out, lse = self._forward_bf16_kv(
q, kv_c_and_k_pe_cache, topk_indices, attn_metadata
)
elif attn_metadata.fp8_use_mixed_batch:
attn_out = self._forward_fp8_kv_mixed_batch(
attn_out, lse = self._forward_fp8_kv_mixed_batch(
q, kv_c_and_k_pe_cache, topk_indices, attn_metadata
)
else:
attn_out = self._forward_fp8_kv_separate_prefill_decode(
attn_out, lse = self._forward_fp8_kv_separate_prefill_decode(
q, kv_c_and_k_pe_cache, topk_indices, attn_metadata
)

return attn_out, None
return attn_out, lse
Loading