[Perf][PCP] Shard decode requests across PCP ranks (#52162)

Signed-off-by: QiuChunshuo <qiuchunshuo@huawei.com>
Co-authored-by: Lucas Wilkinson <LucasWilkinson@users.noreply.github.com>
This commit is contained in:
Qiu Chunshuo
2026-10-01 23:50:13 -04:00
committed by GitHub
co-authored by Lucas Wilkinson
parent a810316c08
commit 8486f1ebfe
13 changed files with 406 additions and 33 deletions
+13
View File
@@ -599,6 +599,19 @@ class ParallelConfig:
"""Process world size across TP, PCP, PP, and DP."""
return self.world_size * self.data_parallel_size
@property
def pcp_shard_decode_requests(self) -> bool:
"""Whether PCP can shard decode requests across its ranks.
PCP-only execution replicates the KV cache, so each decode request can
have a single PCP owner. DCP shards the KV cache and therefore requires
every decode request to run on every participating DCP rank.
"""
return (
self.prefill_context_parallel_size > 1
and self.decode_context_parallel_size == 1
)
@property
def use_ubatching(self) -> bool:
return self.enable_dbo or self.ubatch_size > 1
@@ -609,6 +609,7 @@ class MLAAttention(nn.Module, AttentionLayerBase):
vllm_config = get_current_vllm_config()
parallel_config = vllm_config.parallel_config
self.use_pcp = parallel_config.prefill_context_parallel_size > 1
self.pcp_shard_decode_requests = parallel_config.pcp_shard_decode_requests
compilation_config = vllm_config.compilation_config
if prefix in compilation_config.static_forward_context:
raise ValueError(f"Duplicate layer name: {prefix}")
@@ -784,6 +785,7 @@ class MLAAttention(nn.Module, AttentionLayerBase):
slot_mapping,
attn_metadata.num_decode_tokens if attn_metadata is not None else None,
self.use_pcp,
pcp_shard_decode_requests=self.pcp_shard_decode_requests,
)
assert slot_mapping is not None
if cache is not None:
@@ -335,6 +335,7 @@ def sparse_attn_indexer(
topk_indices_buffer: torch.Tensor,
skip_k_cache_insert: bool,
use_pcp: bool,
pcp_shard_decode_requests: bool,
dense_mha_metadata_layer_name: LayerNameType,
use_fp4_cache: bool = False,
dcp_rank: int = 0,
@@ -404,6 +405,7 @@ def sparse_attn_indexer(
topk_indices_buffer,
skip_k_cache_insert,
use_pcp,
pcp_shard_decode_requests,
dense_mha_metadata_layer_name,
use_fp4_cache,
candidate_blocks=candidate_blocks,
@@ -442,6 +444,7 @@ def sparse_attn_indexer(
slot_mapping,
num_decode_tokens,
use_pcp,
pcp_shard_decode_requests=pcp_shard_decode_requests,
)
# scale_fmt can be None, but the function expects str
assert scale_fmt is not None
@@ -817,6 +820,7 @@ def sparse_attn_indexer_fake(
topk_indices_buffer: torch.Tensor | None,
skip_k_cache_insert: bool,
use_pcp: bool,
pcp_shard_decode_requests: bool,
dense_mha_metadata_layer_name: LayerNameType,
use_fp4_cache: bool = False,
dcp_rank: int = 0,
@@ -898,6 +902,7 @@ class SparseAttnIndexer(CustomOp):
self.dcp_world_size = parallel_config.decode_context_parallel_size
self.dcp_rank = get_dcp_group().rank_in_group if self.dcp_world_size > 1 else 0
self.use_pcp = parallel_config.prefill_context_parallel_size > 1
self.pcp_shard_decode_requests = parallel_config.pcp_shard_decode_requests
self._cp_kv_cache_interleave_size: int | None = None
if current_platform.is_cuda() and not has_deep_gemm():
raise RuntimeError(
@@ -994,6 +999,7 @@ class SparseAttnIndexer(CustomOp):
self.topk_indices_buffer,
self.skip_k_cache_insert,
self.use_pcp,
self.pcp_shard_decode_requests,
_encode_layer_name(self.dense_mha_metadata_layer_name),
self.use_fp4_cache,
self.dcp_rank,
+2
View File
@@ -500,6 +500,7 @@ class DeepseekV32Attention(MLAAttention):
self.topk_indices_buffer,
skip_k_cache_insert=not self.use_pcp,
use_pcp=self.use_pcp,
pcp_shard_decode_requests=self.pcp_shard_decode_requests,
dense_mha_metadata_layer_name=self._dense_mha_metadata_layer_name,
dcp_rank=(
self.dcp_manager.group.rank_in_group
@@ -535,6 +536,7 @@ class DeepseekV32Attention(MLAAttention):
layer_slot_mapping,
attn_metadata.num_decode_tokens,
True,
pcp_shard_decode_requests=self.pcp_shard_decode_requests,
)
)
self.impl.do_kv_cache_update( # type: ignore[attr-defined]
@@ -489,6 +489,14 @@ class FlashMLASparseMetadataBuilder(
num_tokens - metadata.num_decode_tokens,
)
FP8Meta = FlashMLASparseMetadata.FP8SeparatePrefillDecode
# PCP decode sharding can leave a rank with only its collective-padding
# row when the global decode batch is smaller than the PCP world size.
# The row has no actual query tokens and must not be interpreted as a
# zero-length decode request by the sparse FP8 metadata builder.
if num_tokens == 0:
return FP8Meta()
decode_query_len = 0
active_num_decodes = num_decodes
if num_decodes > 0:
@@ -498,7 +506,6 @@ class FlashMLASparseMetadataBuilder(
active_num_decodes = num_decode_tokens // decode_query_len
assert active_num_decodes * decode_query_len == num_decode_tokens
FP8Meta = FlashMLASparseMetadata.FP8SeparatePrefillDecode
fp8_metadata = FP8Meta(
num_decodes=active_num_decodes,
num_prefills=num_prefills,
+28 -11
View File
@@ -1298,17 +1298,6 @@ class DeepseekV32IndexerMetadataBuilder(AttentionMetadataBuilder):
slot_mapping = common_attn_metadata.slot_mapping
block_table = common_attn_metadata.block_table_tensor
dcp_local_seq_lens = common_attn_metadata.dcp_local_seq_lens
num_decodes, num_prefills, num_decode_tokens, num_prefill_tokens = (
split_decodes_and_prefills(
common_attn_metadata,
decode_threshold=self.decode_threshold,
require_uniform=not (self.use_flattening or self.supports_varlen),
treat_short_extends_as_decodes=not self.use_pcp,
)
)
assert num_decodes + num_prefills == num_reqs
assert num_decode_tokens + num_prefill_tokens == num_tokens
compressed_slot_mapping = slot_mapping
indexer_block_table = block_table
@@ -1347,6 +1336,34 @@ class DeepseekV32IndexerMetadataBuilder(AttentionMetadataBuilder):
dim=0,
)
# PCP decode sharding keeps a zero-token placeholder on ranks that own
# no request in a step so collectives retain a uniform rank shape. Do
# not turn that placeholder into a zero-length indexer decode request.
if num_tokens == 0:
return DeepseekV32IndexerMetadata(
seq_lens=seq_lens,
max_seq_len=common_attn_metadata.max_seq_len,
slot_mapping=compressed_slot_mapping,
num_decodes=0,
num_decode_tokens=0,
num_prefills=0,
num_prefill_tokens=0,
prefill=None,
decode=None,
)
num_decodes, num_prefills, num_decode_tokens, num_prefill_tokens = (
split_decodes_and_prefills(
common_attn_metadata,
decode_threshold=self.decode_threshold,
require_uniform=not (self.use_flattening or self.supports_varlen),
treat_short_extends_as_decodes=not self.use_pcp,
)
)
assert num_decodes + num_prefills == num_reqs
assert num_decode_tokens + num_prefill_tokens == num_tokens
prefill_metadata = None
if num_prefills > 0:
compressed_seq_lens = (
+24 -8
View File
@@ -12,29 +12,42 @@ def _gather_prefill_cache_inputs(
tensors: tuple[torch.Tensor, ...],
slot_mapping: torch.Tensor,
num_decode_tokens: int,
shard_decode_requests: bool = False,
) -> tuple[tuple[torch.Tensor, ...], torch.Tensor]:
"""Keep replicated decode writes local and gather partitioned prefills."""
"""Gather PCP cache inputs while preserving replicated KV-cache state.
PCP-only execution shards decode requests across ranks. In that mode each
rank must gather the other owners' decode KV as well as partitioned prefill
KV so every PCP rank retains a complete cache replica. DCP execution keeps
decode requests replicated and uses the legacy prefill-only gather.
"""
local_num_tokens = tensors[0].shape[0]
assert all(tensor.shape[0] == local_num_tokens for tensor in tensors)
assert 0 <= num_decode_tokens <= local_num_tokens
# Replicated draft decodes use unexpanded slot mappings, even with DP padding.
if (
num_decode_tokens == local_num_tokens
or slot_mapping.shape[0] <= local_num_tokens
):
if slot_mapping.shape[0] <= local_num_tokens:
return (
tuple(tensor[:num_decode_tokens] for tensor in tensors),
slot_mapping[:num_decode_tokens],
)
pcp_group = get_pcp_group()
pcp_size = pcp_group.world_size
gathered_slot_mapping = slot_mapping[: pcp_size * local_num_tokens]
if shard_decode_requests:
gathered_inputs = tuple(
pcp_group.all_gather(tensor.contiguous(), dim=0) for tensor in tensors
)
return gathered_inputs, gathered_slot_mapping
if num_decode_tokens == local_num_tokens:
return tensors, slot_mapping[:num_decode_tokens]
gathered_prefills = tuple(
pcp_group.all_gather(tensor[num_decode_tokens:].contiguous(), dim=0)
for tensor in tensors
)
pcp_size = pcp_group.world_size
gathered_slot_mapping = slot_mapping[: pcp_size * local_num_tokens]
if num_decode_tokens == 0:
return gathered_prefills, gathered_slot_mapping
@@ -58,6 +71,7 @@ def maybe_gather_mla_latent_cache_inputs(
slot_mapping: torch.Tensor | None,
num_decode_tokens: int | None,
use_pcp: bool,
pcp_shard_decode_requests: bool = False,
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor | None]:
if not use_pcp or num_decode_tokens is None:
return kv_c_normed, k_pe, slot_mapping
@@ -68,6 +82,7 @@ def maybe_gather_mla_latent_cache_inputs(
(kv_c_normed, k_pe_flat),
slot_mapping,
num_decode_tokens,
pcp_shard_decode_requests,
)
cache_k_pe = cache_k_pe_flat.view(-1, *k_pe.shape[1:])
return cache_kv_c, cache_k_pe, cache_slot_mapping
@@ -78,11 +93,12 @@ def maybe_gather_indexer_k(
slot_mapping: torch.Tensor,
num_decode_tokens: int,
use_pcp: bool,
pcp_shard_decode_requests: bool = False,
) -> tuple[torch.Tensor, torch.Tensor]:
if not use_pcp:
return k, slot_mapping
(cache_k,), cache_slot_mapping = _gather_prefill_cache_inputs(
(k,), slot_mapping, num_decode_tokens
(k,), slot_mapping, num_decode_tokens, pcp_shard_decode_requests
)
return cache_k, cache_slot_mapping
+26 -3
View File
@@ -49,6 +49,7 @@ class PCPManager:
pcp_world_size: int,
pcp_rank: int,
device: torch.device,
shard_decode_requests: bool,
max_num_reqs: int | None = None,
max_num_tokens: int | None = None,
block_tables: BlockTables | None = None,
@@ -62,6 +63,7 @@ class PCPManager:
self.dcp_world_size = dcp_world_size
self.dcp_rank = dcp_rank
self.cp_interleave = cp_interleave
self.shard_decode_requests = shard_decode_requests
self._global_batch: InputBatch | None = None
self._local_batch: InputBatch | None = None
@@ -248,6 +250,7 @@ class PCPManager:
Decodes, and prefills too short to fill all eight, are replicated instead.
"""
decode_ordinal = 0
num_chunks = 2 * self.pcp_world_size
replicated = self.replicated_requests(num_scheduled_tokens, is_prefilling)
for global_batch_req_idx, num_tokens in enumerate(num_scheduled_tokens):
@@ -258,7 +261,16 @@ class PCPManager:
if not replicated[global_batch_req_idx]:
chunk_size = (query_len + num_chunks - 1) // num_chunks
chunk_indices = (rank, num_chunks - 1 - rank)
else: # decodes, and short prefills under DCP, are replicated
elif self.shard_decode_requests:
chunk_size = query_len
# KV and hidden states are gathered back to every PCP rank, so
# decode ownership does not need to persist across steps. Use a
# compact decode-only ordinal to keep each step exactly
# balanced even when prefills and zero-token rows are present.
owner_rank = decode_ordinal % self.pcp_world_size
decode_ordinal += 1
chunk_indices = (0,) if rank == owner_rank else ()
else: # DCP requires decode queries on every participating rank.
chunk_size = query_len
chunk_indices = (0,)
@@ -346,8 +358,18 @@ class PCPManager:
segment.global_batch_slice.stop,
dtype=np.int64,
)
# Cache insertion pairs one slot entry with each rank's local decode.
if replicated[segment.global_batch_req_idx] and rank != 0:
# Replicated rows contain identical KV, so rank 0 is the
# canonical writer. A sharded decode has exactly one owner and
# therefore needs no de-duplication here.
is_sharded_decode = (
not bool(is_prefilling[segment.global_batch_req_idx])
and self.shard_decode_requests
)
if (
replicated[segment.global_batch_req_idx]
and not is_sharded_decode
and rank != 0
):
continue
gathered_kv_write_mask[padded_gathered_slice] = True
hidden_restore_idx[segment.global_batch_slice] = np.arange(
@@ -829,6 +851,7 @@ def maybe_build_pcp_manager(
pcp_world_size=pcp_size,
pcp_rank=pcp_rank,
device=device,
shard_decode_requests=parallel_config.pcp_shard_decode_requests,
max_num_reqs=vllm_config.scheduler_config.max_num_seqs,
max_num_tokens=vllm_config.scheduler_config.max_num_batched_tokens,
block_tables=block_tables,