From 7d38fb459fcf4781f1f5f5130bb843d2f4278d85 Mon Sep 17 00:00:00 2001 From: pramodp-dotcom Date: Mon, 31 Aug 2026 03:25:45 +0530 Subject: [PATCH] Filter sparse MLA top-k indices per DCP rank, and fix decode LSE Backport onto the v0.28.0 release, which does not carry the upstream fix: vllm-project/vllm#46514 (63ff748f6, 2026-08-19) landed this on main, but the v0.28.0 release branch forked before it, so the released wheel still has the bug. flashmla_sparse.py is byte-identical from v0.26.0 through v0.28.0, so this applies unchanged across all three. Under decode context parallelism each rank holds only its own shard of the KV cache, but the sparse FlashMLA path fed the top-k results - which are global token positions - straight into triton_convert_req_index_to_global_index. That converter assumes every index is local, so it translated positions owned by other ranks through this rank's block table and read unrelated cache slots, corrupting decode output. Use triton_filter_and_convert_dcp_index when dcp_world_size > 1: it drops the indices this rank does not own before converting the rest. Applied at all three call sites (bf16 KV, fp8 KV separate prefill/decode, fp8 KV mixed batch). Non-DCP runs keep the original converter unchanged. The helper is already in sparse_utils.py at this tag. Ownership depends on the interleave stride, so plumb cp_kv_cache_interleave_size from parallel_config through the metadata rather than leaving the dataclass default of 1. Two LSE fixes needed for the cross-rank reduction to be correct: - flash_mla_sparse_fwd returns (output, max_logits, lse), so read kernel_out[2]. The previous kernel_out[1] fed max_logits into the reduction. Upstream main expresses the same thing as 'output, _, lse = flash_mla_sparse_fwd(...)'. - flash_mla_with_kvcache returns LSE as (batch, num_heads, seq_len) while callers reshape assuming (batch, seq_len, num_heads); transpose it, and trim the padded head dim. Also guard the two LSE reshape sites against a None lse. Co-Authored-By: Claude Opus 5 Claude-Session: https://claude.ai/code/session_01MYhgsjgQ2GQcpkXZfM3dec --- .../attention/backends/mla/flashmla_sparse.py | 207 +++++++++++++----- 1 file changed, 151 insertions(+), 56 deletions(-) diff --git a/vllm/v1/attention/backends/mla/flashmla_sparse.py b/vllm/v1/attention/backends/mla/flashmla_sparse.py index e8be7ad5bb39..b628d67d28c3 100644 --- a/vllm/v1/attention/backends/mla/flashmla_sparse.py +++ b/vllm/v1/attention/backends/mla/flashmla_sparse.py @@ -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, @@ -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: @@ -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 @@ -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, @@ -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 @@ -642,17 +673,35 @@ 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) @@ -660,7 +709,7 @@ def _forward_fp8_kv_separate_prefill_decode( 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) @@ -669,7 +718,7 @@ 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, @@ -677,12 +726,20 @@ def _fp8_decode( ) # 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( @@ -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: @@ -712,14 +770,15 @@ 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, @@ -727,22 +786,38 @@ def _forward_fp8_kv_mixed_batch( 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( @@ -750,7 +825,7 @@ def _forward_fp8_kv_mixed_batch( ) 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) @@ -758,7 +833,12 @@ def _forward_fp8_kv_mixed_batch( ) # 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, @@ -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( @@ -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, @@ -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