PART 02 / PCP 原生设计

先把并行的三个坐标对齐。

关闭 HiSparse,理解 Prefill 切分、Decode 分工、KV 交换、hidden 恢复,以及混部与 PD 的职责边界。

8 章1 张内嵌图固定源码 · 分层走读
阅读顺序:HiSparse → PCP → HiSparse + PCP。
本篇基于 Core 24420b7a / Ascend 14a31903;详细 SHA 与证据随页保留。
本篇目录 ↑02 / 01

先把 PCP 单独看清楚

本篇先不启用 HiSparse,只解释固定版本的 PCP 管理器与 Ascend SFA 数据路径。读懂这里的三种行顺序,下一篇的组合适配才有基础。

PCP 的任务:把同一引擎本步的 query 工作拆给多个 rank,组织新 KV 的交换与正确落位,最后把 hidden states 恢复为全局请求顺序。它本身不建立 Host / Resident / Hot 分层缓存。
对象职责与下一篇的关系
Core PCPManager建立全局 batch → rank-local batch 的切分和恢复映射。组合适配继续使用这些映射,不能重建另一套请求编号。
AscendPCPManager : PCPManager承接 Ascend CPU 长度视图、attention 状态、graph padding 和 draft 布局。向 attention / HiSparse 提供同一份 AscendPCPAttentionContext。
Ascend SFA backend按 PCP 策略交换本步新 KV,再按 gathered slots 写入缓存。组合适配还要把正确写行镜像到 Host,不能只看本 rank 的 query。
restore_for_sampling汇集并恢复全局 hidden states,交给采样或 draft。HiSparse 的局部 query 布局不能泄漏成全局采样顺序。
源码依据 · 继承关系与上下文字段

vllm_ascend/worker/v2/pcp_manager.py · L36–95 ↗vllm-ascend @14a31903a98f · 真实源码,已裁剪,保留原行号

  36  from vllm.v1.worker.gpu.pcp_manager import PCPManager
  37  from vllm.v1.worker.gpu.states import RequestState
  38  from vllm.v1.worker.utils import AttentionGroup
  39  
  40  from vllm_ascend.attention.context_parallel.common_cp import is_pcp_decode_sharding_enabled
  41  from vllm_ascend.ops.rotary_embedding import update_cos_sin
  42  from vllm_ascend.worker.v2.attn_utils import build_attn_state
  43  from vllm_ascend.worker.v2.input_batch import AscendInputBatch, AscendInputBuffers
  44  
  45  if TYPE_CHECKING:
  46      from vllm.v1.worker.gpu.spec_decode.speculator import DraftModelSpeculator
  47  
  48  
  49  @dataclass(frozen=True)
  50  class AscendPCPAttentionContext:
  51      """Canonical global PCP view for one attention step."""
  52  
  53      # The global batch and its associated metadata, used to build DSA attention metadata.
  54      global_batch: AscendInputBatch
  55      global_block_tables: tuple[torch.Tensor, ...]
  56      global_slot_mappings: torch.Tensor
  57      hidden_restore_idx: torch.Tensor
  58      padded_gather_idx: torch.Tensor | None = None
  59      gathered_kv_write_mask: torch.Tensor | None = None
  60      # Device snapshot of allocated kernel-block counts in global request order.
  61      global_block_table_num_blocks: torch.Tensor | None = None
  62      # Original batch row for each local request, in upstream segment order.
  63      local_to_global_req_indices: tuple[int, ...] | None = None
  64      # Actual local tokens in the unpartitioned batch, excluding padding.
  65      local_token_indices: torch.Tensor | None = None
  66      # Padded tensor width consumed by each rank's model forward.
  67      local_num_tokens: int | None = None
  68      # Local request order, including dual-chunk duplicates and graph padding.
  69      local_request_state_indices: torch.Tensor | None = None
  70  
  71  
  72  class AscendPCPManager(PCPManager):
  73      """PCP manager that refreshes Ascend-only local-batch metadata."""
  74  
  75      vllm_config: VllmConfig
  76      kv_cache_config: KVCacheConfig | None = None
  77      _hidden_restore_idx: torch.Tensor | None
  78      _global_batch_slot_mappings: torch.Tensor | None
  79      _gathered_kv_slot_mappings: torch.Tensor | None
  80      _pad_slot_id: torch.Tensor
  81      # The runner's global input buffers, which back global graph metadata.
  82      global_input_buffers: AscendInputBuffers | None = None
  83      # Draft-only attention layers; metadata built only for them runs replicated.
  84      _draft_layer_names: frozenset[str] = frozenset()
  85      # Whether the speculator shards draft prefill with the target, i.e. the
  86      # draft runs with the target's PCP topology (upstream MTP/Eagle3) rather
  87      # than replicated with PCP=1 (upstream DFlash/DSpark).
  88      _is_draft_prefill_sharded: bool = False
  89      # The batch restore_for_sampling handed to sampling and the speculator.
  90      _sampling_global_batch: InputBatch | None = None
  91      # Draft input buffers and row count overwritten by staged rank-local
  92      # draft prefill inputs; the rows are stashed in the _draft_*_stash buffers.
  93      _staged_draft_inputs: tuple[InputBuffers, int] | None = None
  94  
  95      def __init__(
本篇目录 ↑02 / 02

Prefill 怎么切,Decode 怎么分

不能只记住“PCP 切 Prefill”。固定版本里也存在按请求分片的 Decode 策略,具体是否启用由模型与并行配置决定。

Prefill:首尾配对的 DualChunkSwap

  1. 对一条需要分片的 query,取 2 × PCP world size 个 chunk;chunk 长度向上取整。
  2. rank r 取第 r 块和倒数第 r 块。PCP=2 时,rank0 取 chunk0 / chunk3,rank1 取 chunk1 / chunk2。
  3. 首尾配对是分工方式;rank 的实际本地 batch 还会组合多请求,并为 collective / graph 补齐。不能把本地行号当原请求 token 位置。

Decode:复制执行与按请求分片分开理解

模式计算归属新 KV 的处理
replicated decode各 PCP rank 看到相同 Decode query。重复行只保留规范写者;没有其他分片工作时无需重复交换相同 KV。
request-sharded decode本步 Decode 请求按 ordinal % PCP world size 分给 owner rank。owner 计算的新 KV 要交换;hidden states 随后也恢复全局顺序。owner 无需跨 step 固定。
Ascend 策略非 KPool 模型,PCP > 1 且 DCP = 1 时启用 decode sharding;KPool 分支返回 False。模型例外以 common_cp.py 为准,不能仅凭模型名称或 PCP 数值判断。
源码依据 · Core chunk / owner 与 Ascend 策略

vllm/v1/worker/gpu/pcp_manager.py · L257–317 ↗vllm @24420b7a341a · 真实源码,已裁剪,保留原行号

 257      def replicated_requests(
 258          self, num_scheduled_tokens: np.ndarray, is_prefilling: np.ndarray
 259      ) -> np.ndarray:
 260          """Per global request, whether every PCP rank gets the whole query."""
 261          num_chunks = 2 * self.pcp_world_size
 262          query_lens = np.asarray(num_scheduled_tokens, dtype=np.int64)
 263          replicated = ~np.asarray(is_prefilling, dtype=np.bool_)
 264          if self.dcp_world_size > 1:
 265              chunk_sizes = (query_lens + num_chunks - 1) // num_chunks
 266              drops_a_chunk = (num_chunks - 1) * chunk_sizes >= query_lens
 267              replicated |= drops_a_chunk
 268          return replicated
 269  
 270      def _iter_rank_chunks(
 271          self,
 272          rank: int,
 273          num_scheduled_tokens: np.ndarray,
 274          is_prefilling: np.ndarray,
 275      ) -> Iterator[tuple[int, int, int]]:
 276          """Yield ``(request index, query offset, length)`` for one PCP rank.
 277  
 278          PCP=4 partitions each prefill into eight chunks:
 279  
 280              full:  | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
 281              rank 0:  0                           7
 282              rank 1:      1                   6
 283              rank 2:          2           5
 284              rank 3:              3   4
 285  
 286          Decodes, and prefills too short to fill all eight, are replicated instead.
 287          """
 288          decode_ordinal = 0
 289          num_chunks = 2 * self.pcp_world_size
 290          replicated = self.replicated_requests(num_scheduled_tokens, is_prefilling)
 291          for global_batch_req_idx, num_tokens in enumerate(num_scheduled_tokens):
 292              query_len = int(num_tokens)
 293              if query_len == 0:
 294                  continue
 295              chunk_indices: tuple[int, ...]
 296              if not replicated[global_batch_req_idx]:
 297                  chunk_size = (query_len + num_chunks - 1) // num_chunks
 298                  chunk_indices = (rank, num_chunks - 1 - rank)
 299              elif self.shard_decode_requests:
 300                  chunk_size = query_len
 301                  # KV and hidden states are gathered back to every PCP rank, so
 302                  # decode ownership does not need to persist across steps. Use a
 303                  # compact decode-only ordinal to keep each step exactly
 304                  # balanced even when prefills and zero-token rows are present.
 305                  owner_rank = decode_ordinal % self.pcp_world_size
 306                  decode_ordinal += 1
 307                  chunk_indices = (0,) if rank == owner_rank else ()
 308              else:  # DCP requires decode queries on every participating rank.
 309                  chunk_size = query_len
 310                  chunk_indices = (0,)
 311  
 312              for chunk_idx in chunk_indices:
 313                  chunk_offset = chunk_idx * chunk_size
 314                  chunk_len = min(chunk_size, query_len - chunk_offset)
 315                  if chunk_len <= 0:
 316                      continue
 317                  yield global_batch_req_idx, chunk_offset, chunk_len

vllm_ascend/attention/context_parallel/common_cp.py · L36–58 ↗vllm-ascend @14a31903a98f · 真实源码,已裁剪,保留原行号

  36  def is_pcp_decode_sharding_enabled(vllm_config) -> bool:
  37      """Shard PCP decode requests, including speculative target verification.
  38  
  39      The decision uses declared vLLM fields so cloning a draft
  40      ``ParallelConfig`` with ``replace()`` remains supported. KPool models
  41      keep replicated decodes so every PCP rank advances its head-sharded
  42      Mamba state in the same request order.
  43      """
  44      if model_uses_kpool_indexer(getattr(vllm_config, "model_config", None)):
  45          # TODO: Adapt PCP decode request sharding for GLM-5.3-Flash, including
  46          # recurrent-state ownership and request ordering across PCP ranks.
  47          return False
  48      parallel_config = vllm_config.parallel_config
  49      return parallel_config.prefill_context_parallel_size > 1 and parallel_config.decode_context_parallel_size == 1
  50  
  51  
  52  def get_pcp_num_replicated_tokens(num_decode_tokens: int, is_decode_sharded: bool) -> int:
  53      """Return the leading rank-local tokens that every PCP rank computes identically.
  54  
  55      Replicated decodes need no KV gather. A sharded decode belongs to one PCP
  56      rank, so its KV is gathered together with the prefill tokens.
  57      """
  58      return 0 if is_decode_sharded else num_decode_tokens

vllm_ascend/worker/v2/pcp_manager.py · L181–235 ↗vllm-ascend @14a31903a98f · 真实源码,已裁剪,保留原行号

 181      def bind_config(self, vllm_config: VllmConfig) -> None:
 182          self.vllm_config = vllm_config
 183          self.shard_decode_requests: bool = self.shard_decode_requests and self.is_decode_sharded
 184  
 185      @property
 186      def is_decode_sharded(self) -> bool:
 187          """Use the shared policy after the runner injects vllm_config."""
 188          return is_pcp_decode_sharding_enabled(self.vllm_config)
 189  
 190      # TODO: Remove replicated_requests and _iter_rank_chunks once the paired
 191      # vLLM includes #52162, which shards decode requests upstream.
 192      def replicated_requests(self, num_scheduled_tokens: np.ndarray, is_prefilling: np.ndarray) -> np.ndarray:
 193          """Sharded decodes have a single owner, so none of them is replicated."""
 194          replicated = super().replicated_requests(num_scheduled_tokens, is_prefilling)
 195          if self.is_decode_sharded:
 196              replicated &= np.asarray(is_prefilling, dtype=np.bool_)
 197          return replicated
 198  
 199      def _iter_rank_chunks(
 200          self,
 201          rank: int,
 202          num_scheduled_tokens: np.ndarray,
 203          is_prefilling: np.ndarray,
 204      ) -> Iterator[tuple[int, int, int]]:
 205          """Split prefills as upstream does and assign decodes round-robin.
 206  
 207          Only scheduled decodes count toward the round-robin order, which keeps
 208          every step balanced. Ownership may change between steps because KV
 209          and hidden states are gathered back to every PCP rank.
 210          """
 211          if not self.is_decode_sharded:
 212              yield from super()._iter_rank_chunks(rank, num_scheduled_tokens, is_prefilling)
 213              return
 214  
 215          decode_ordinal = 0
 216          num_chunks = 2 * self.pcp_world_size
 217          for req_idx, num_tokens in enumerate(num_scheduled_tokens):
 218              query_len = int(num_tokens)
 219              if query_len == 0:
 220                  continue
 221  
 222              if not is_prefilling[req_idx]:
 223                  owner_rank = decode_ordinal % self.pcp_world_size
 224                  decode_ordinal += 1
 225                  if rank == owner_rank:
 226                      yield req_idx, 0, query_len
 227                  continue
 228  
 229              # DCP == 1 here, so prefills use upstream's DualChunkSwap split.
 230              chunk_size = (query_len + num_chunks - 1) // num_chunks
 231              for chunk_idx in (rank, num_chunks - 1 - rank):
 232                  chunk_offset = chunk_idx * chunk_size
 233                  chunk_len = min(chunk_size, query_len - chunk_offset)
 234                  if chunk_len > 0:
 235                      yield req_idx, chunk_offset, chunk_len
本篇目录 ↑02 / 03

三个坐标:global、local、gathered

三个顺序分别回答“请求本来是什么顺序”“本 rank 算哪些行”“collective 后按什么顺序写 KV”。它们不是三个不同的请求池。

坐标长什么样谁使用
global batchScheduler 本步规范的请求 / token 顺序。请求状态、全局 block / slot 映射、恢复后的采样输入。
rank-local batch本 rank 被分配到的 token,可能混合不同请求,含执行 padding。模型前向、局部 query、局部 attention metadata。
padded gathered rowsrank0 的本地行及 padding,接着 rank1,依次拼接。KV collective 后的写入顺序;需要与 gathered slot mapping 一一对应。

用源码自带的字母例子理解映射

global:               [A B C D E F G]
rank0 / rank1:        [A B G] / [C D E F]
padded gathered:      [A B G _ | C D E F]
hidden_restore_idx:   [0,1,4,5,6,7,2]
padded_gather_idx:    [0,1,6,0,2,3,4,5]

gathered[hidden_restore_idx] 恢复 A~G;global[padded_gather_idx] 得到 rank-major 写行。padding 位置的索引即使合法,也必须由 gathered_kv_write_mask 标为不可写,再变成 PAD_SLOT。否则例子中的占位行会误写 A 的缓存。

源码依据 · 映射定义与有效写 mask

vllm/v1/worker/gpu/pcp_manager.py · L343–425 ↗vllm @24420b7a341a · 真实源码,已裁剪,保留原行号

 343      def _build_batch_layout(
 344          self,
 345          num_scheduled_tokens: np.ndarray,
 346          num_computed_tokens: np.ndarray,
 347          is_prefilling: np.ndarray,
 348          query_start_loc_np: np.ndarray,
 349          padded_num_tokens: int | None = None,
 350      ) -> tuple[list[list[RankSegment]], list[int]]:
 351          replicated = self.replicated_requests(num_scheduled_tokens, is_prefilling)
 352          segments_by_rank = []
 353          per_rank_num_tokens = []
 354          for rank in range(self.pcp_world_size):
 355              segments = self._get_rank_segments(
 356                  rank,
 357                  num_scheduled_tokens,
 358                  is_prefilling,
 359                  query_start_loc_np,
 360              )
 361              num_rank_tokens = sum(segment.num_tokens for segment in segments)
 362              segments_by_rank.append(segments)
 363              per_rank_num_tokens.append(num_rank_tokens)
 364  
 365          # PCP=2 example:
 366          #   global batch:       [A B C D E F G]
 367          #   rank 0 / rank 1:    [A B G] / [C D E F]
 368          #   padded gathered:    [A B G _ | C D E F]
 369          #   hidden_restore_idx: [0, 1, 4, 5, 6, 7, 2]
 370          #   padded_gather_idx:  [0, 1, 6, 0, 2, 3, 4, 5]
 371          # Therefore global = gathered[hidden_restore_idx] and
 372          # padded_gathered = global[padded_gather_idx].
 373          hidden_restore_idx = np.empty(int(query_start_loc_np[-1]), dtype=np.int64)
 374          if padded_num_tokens is None:
 375              padded_num_tokens = max(per_rank_num_tokens)
 376          elif padded_num_tokens < max(per_rank_num_tokens):
 377              raise ValueError(
 378                  "PCP padded token count is smaller than the largest rank-local "
 379                  f"batch: {padded_num_tokens} < {max(per_rank_num_tokens)}."
 380              )
 381          num_expanded_tokens = padded_num_tokens * self.pcp_world_size
 382          padded_gather_idx = np.zeros(num_expanded_tokens, dtype=np.int64)
 383          gathered_kv_write_mask = np.zeros(num_expanded_tokens, dtype=np.bool_)
 384          for rank, segments in enumerate(segments_by_rank):
 385              expanded_rank_offset = rank * padded_num_tokens
 386              for segment in segments:
 387                  padded_gathered_slice = slice(
 388                      expanded_rank_offset + segment.rank_local_batch_slice.start,
 389                      expanded_rank_offset + segment.rank_local_batch_slice.stop,
 390                  )
 391                  padded_gather_idx[padded_gathered_slice] = np.arange(
 392                      segment.global_batch_slice.start,
 393                      segment.global_batch_slice.stop,
 394                      dtype=np.int64,
 395                  )
 396                  # Replicated rows contain identical KV, so rank 0 is the
 397                  # canonical writer. A sharded decode has exactly one owner and
 398                  # therefore needs no de-duplication here.
 399                  is_sharded_decode = (
 400                      not bool(is_prefilling[segment.global_batch_req_idx])
 401                      and self.shard_decode_requests
 402                  )
 403                  if (
 404                      replicated[segment.global_batch_req_idx]
 405                      and not is_sharded_decode
 406                      and rank != 0
 407                  ):
 408                      continue
 409                  gathered_kv_write_mask[padded_gathered_slice] = True
 410                  hidden_restore_idx[segment.global_batch_slice] = np.arange(
 411                      padded_gathered_slice.start,
 412                      padded_gathered_slice.stop,
 413                      dtype=np.int64,
 414                  )
 415  
 416          self._hidden_restore_idx = async_tensor_h2d(
 417              hidden_restore_idx, device=self.device
 418          )
 419          self._padded_gather_idx = async_tensor_h2d(
 420              padded_gather_idx, device=self.device
 421          )
 422          self._gathered_kv_write_mask = async_tensor_h2d(
 423              gathered_kv_write_mask, device=self.device
 424          )
 425          return segments_by_rank, per_rank_num_tokens

vllm/v1/worker/gpu/pcp_manager.py · L787–838 ↗vllm @24420b7a341a · 真实源码,已裁剪,保留原行号

 787      def prepare_slot_mappings(self) -> torch.Tensor:
 788          assert self._block_tables is not None
 789          assert self._global_batch_slot_mappings is not None
 790          assert self._global_batch is not None
 791          global_batch = self._global_batch
 792          global_batch_slot_mappings = self._block_tables.compute_slot_mappings(
 793              global_batch.idx_mapping,
 794              global_batch.query_start_loc,
 795              global_batch.positions,
 796              global_batch.num_tokens,
 797              out=self._global_batch_slot_mappings,
 798          )
 799          return self._convert_to_gathered_slot_mappings(global_batch_slot_mappings)
 800  
 801      def get_dummy_slot_mappings(self, num_tokens: int) -> torch.Tensor:
 802          assert self._gathered_kv_slot_mappings is not None
 803          self._gathered_kv_slot_mappings.fill_(PAD_SLOT_ID)
 804          return self._gathered_kv_slot_mappings[:, : num_tokens * self.pcp_world_size]
 805  
 806      def _convert_to_gathered_slot_mappings(
 807          self, global_batch_slot_mappings: torch.Tensor
 808      ) -> torch.Tensor:
 809          assert self._padded_gather_idx is not None
 810          assert self._gathered_kv_write_mask is not None
 811          padded_gather_idx = self._padded_gather_idx
 812          num_expanded_tokens = padded_gather_idx.shape[0]
 813          if self._gathered_kv_slot_mappings is None:
 814              self._gathered_kv_slot_mappings = global_batch_slot_mappings.new_empty(
 815                  global_batch_slot_mappings.shape[0], num_expanded_tokens
 816              )
 817          gathered_kv_slot_mappings = self._gathered_kv_slot_mappings[
 818              :, :num_expanded_tokens
 819          ]
 820          torch.index_select(
 821              global_batch_slot_mappings,
 822              1,
 823              padded_gather_idx,
 824              out=gathered_kv_slot_mappings,
 825          )
 826          torch.where(
 827              self._gathered_kv_write_mask.unsqueeze(0),
 828              gathered_kv_slot_mappings,
 829              self._pad_slot_id,
 830              out=gathered_kv_slot_mappings,
 831          )
 832          return gathered_kv_slot_mappings
 833  
 834      def restore_hidden_states(self, hidden_states: torch.Tensor) -> torch.Tensor:
 835          if self._hidden_restore_idx is None:
 836              return hidden_states
 837          gathered = get_pcp_group().all_gather(hidden_states, dim=0)
 838          return gathered[self._hidden_restore_idx]
本篇目录 ↑02 / 04

一轮执行:先切输入,再写 KV,最后还原输出

以下时序限定不开 HiSparse 的 PCP 数据契约;缓存如何量化和计算由具体 attention backend 承担。

PCP 图 A|单步输入与输出的闭环
全局 InputBatchPCPManager本 rank 模型 / SFAPCP group采样 / Draft输入切分partition_batch(global batch)local batch + attention context逐层:本地 query,KV 按正确行落位需要交换的本步新 KV:AllGatherrank-major KV + gathered slots有效行写 cache;执行局部 query attention输出恢复rank-local hidden statesall_gather(hidden states)用 hidden_restore_idx 恢复 global order规范请求顺序;draft 另有布局规则

根据 PCPManager 的 slot / hidden 恢复与 Ascend SFA exec_kv 重绘。是否交换 KV 由布局和 replicated / sharded 策略决定;并非每一步必然提交同一 collective。 · 箭头表示标注的调用或数据关系,非未标明的继承关系。版本:Core 24420b7a / Ascend 14a31903。

源码依据 · partition 后的本地状态修正与 hidden 恢复

vllm_ascend/worker/v2/pcp_manager.py · L310–371 ↗vllm-ascend @14a31903a98f · 真实源码,已裁剪,保留原行号

 310      def partition_batch(
 311          self,
 312          input_batch: AscendInputBatch,
 313          batch_desc: BatchExecutionDescriptor,
 314      ) -> AscendInputBatch:
 315          """Partition the batch and update Ascend-specific local metadata."""
 316          local_batch = super().partition_batch(input_batch, batch_desc)
 317          assert isinstance(local_batch, AscendInputBatch)
 318          # A sharded decode graph is sized per rank, so upstream can pad the
 319          # local requests. Replicated decode graphs are padded below instead.
 320          padded_num_reqs = batch_desc.num_reqs if batch_desc.cg_mode == CUDAGraphMode.FULL else None
 321          local_batch = self._finalize_partition(input_batch, local_batch, padded_num_reqs)
 322          # Upstream draft prefill reuses _local_batch; keep it the exact batch the
 323          # target ran, including Ascend FIA/graph padding, so the draft input
 324          # length equals the target metadata's last query offset.
 325          self._local_batch = local_batch
 326          self._sampling_global_batch = None
 327          return local_batch
 328  
 329      def _finalize_partition(
 330          self,
 331          global_batch: AscendInputBatch,
 332          local_batch: AscendInputBatch,
 333          padded_num_reqs: int | None,
 334      ) -> AscendInputBatch:
 335          """Refresh Ascend-only local metadata after upstream PCP partitioning."""
 336          local_batch.is_dummy = getattr(global_batch, "is_dummy", False)
 337          local_batch.is_cpp_profile = getattr(global_batch, "is_cpp_profile", False)
 338          self._pad_hidden_restore_idx(global_batch)
 339          if not self.is_decode_sharded:
 340              local_batch = self._pad_replicated_decode_graph(global_batch, local_batch)
 341          elif padded_num_reqs is not None:
 342              self._pad_uniform_query_start_loc(global_batch, local_batch)
 343  
 344          actual_seq_lens_np = local_batch.num_computed_tokens_np + local_batch.num_scheduled_tokens
 345          if local_batch.num_tokens == 0:
 346              # An empty rank keeps one zero-token placeholder request whose
 347              # device sequence length upstream already sets to zero.
 348              actual_seq_lens_np[:] = 0
 349              local_batch.seq_lens_cpu_upper_bound.zero_()
 350          if local_batch.num_reqs_after_padding > local_batch.num_reqs:
 351              assert self._input_buffers is not None
 352              seq_lens_np = self._input_buffers.seq_lens_np
 353              seq_lens_np[: local_batch.num_reqs] = actual_seq_lens_np
 354              seq_lens_np[local_batch.num_reqs : local_batch.num_reqs_after_padding] = 0
 355              local_batch.seq_lens_np = seq_lens_np[: local_batch.num_reqs_after_padding]
 356          else:
 357              local_batch.seq_lens_np = actual_seq_lens_np
 358          # Preserve the global attention state for decode-only batches, including
 359          # empty ranks, before upstream clears local draft metadata.
 360          if not bool(global_batch.is_prefilling_np.any()):
 361              return local_batch
 362  
 363          local_batch.attn_state = build_attn_state(
 364              self.vllm_config,
 365              actual_seq_lens_np,
 366              local_batch.num_reqs,
 367              local_batch.num_scheduled_tokens,
 368              local_batch.num_scheduled_tokens,
 369              kv_cache_config=self.kv_cache_config,
 370          )
 371          return local_batch

vllm_ascend/worker/v2/pcp_manager.py · L514–538 ↗vllm-ascend @14a31903a98f · 真实源码,已裁剪,保留原行号

 514      def restore_hidden_states(self, hidden_states: torch.Tensor) -> torch.Tensor:
 515          """Restore tokens to the global PCP layout, following the batch length.
 516  
 517          The FIA-padded global ``query_start_loc`` sizes upstream's restore
 518          indices to ``num_tokens_after_padding``; ``_pad_hidden_restore_idx``
 519          makes those padding rows valid, and they read as zeros here. Fixed-K
 520          speculative decode sharding restores to the unpadded global batch
 521          instead, returning the compact ``num_tokens`` rows.
 522          """
 523          if not self.is_last_pp_rank:
 524              return hidden_states
 525  
 526          # PP and draft states can be strided views; HCCL requires dense inputs.
 527          restored_hidden_states = super().restore_hidden_states(hidden_states.contiguous())
 528          if self._global_batch is None:
 529              return restored_hidden_states
 530  
 531          num_tokens = self._global_batch.num_tokens
 532          if num_tokens == self._global_batch.num_tokens_after_padding:
 533              return restored_hidden_states
 534  
 535          restored_hidden_states[num_tokens:].zero_()
 536          if self._restore_unpadded_global_batch():
 537              restored_hidden_states = restored_hidden_states[:num_tokens]
 538          return restored_hidden_states

vllm/v1/worker/gpu/pcp_manager.py · L834–838 ↗vllm @24420b7a341a · 真实源码,已裁剪,保留原行号

 834      def restore_hidden_states(self, hidden_states: torch.Tensor) -> torch.Tensor:
 835          if self._hidden_restore_idx is None:
 836              return hidden_states
 837          gathered = get_pcp_group().all_gather(hidden_states, dim=0)
 838          return gathered[self._hidden_restore_idx]
本篇目录 ↑02 / 05

不开 HiSparse 时,Ascend SFA 如何交换 KV

本节选取 Ascend SFA 的 exec_kv 作为具体例子,不把它外推为所有 attention backend 的共同实现。

  1. needs_pcp_kv_gather 先看是否为 PCP sharded layout。分片 Decode,或本地 / 全局存在 Prefill 时需要交换;复制 draft 的未扩展布局不按分片布局处理。
  2. 确定本地行数与 replicated decode 行数。相同的复制行保留一次,分片部分通过 PCP group 的 all_gather_async 汇集。
  3. 需要时同时交换 KV 投影输入及 cos / sin;slot mapping 取相同的 rank-major 范围。不是先把 query 排回 global 再写缓存。
  4. 允许 defer_wait 时,返回一个 finish 闭包;在 finish 中等待 collective,拼接复制段与 gathered 段,检查每个写行对应一个 slot,再进入 _exec_kv_local。
  5. 这段代码使 KV AllGather 可与 Q projection 重叠;它不等于 HiSparse Host H2D 被完全掩盖,更不能从代码直接推出整网 TPOT 收益。
为什么“本 rank 没 Prefill”仍可能要 gather?另一个 rank 可能分到了本步 Prefill。pcp_has_global_prefill 使所有参与者遵循同一 collective 决策;只检查本地 num_prefills 会破坏这一契约。
源码依据 · SFA 判断、提交与完成闭包

vllm_ascend/attention/sfa_v1.py · L484–494 ↗vllm-ascend @14a31903a98f · 真实源码,已裁剪,保留原行号

 484  def needs_pcp_kv_gather(attn_metadata: AscendSFAMetadata, is_decode_sharded: bool) -> bool:
 485      """Whether PCP ranks must exchange this step's KV.
 486  
 487      Only replicated decode-only steps already hold identical KV on every
 488      rank, including graph padding. Ranks without local prefill still join the
 489      gather when another rank has one. A step built without a PCP context
 490      (e.g. a replicated draft decode) keeps an unexpanded slot mapping.
 491      """
 492      if not attn_metadata.uses_pcp_sharded_layout:
 493          return False
 494      return is_decode_sharded or attn_metadata.num_prefills > 0 or attn_metadata.pcp_has_global_prefill

vllm_ascend/attention/sfa_v1.py · L1290–1350 ↗vllm-ascend @14a31903a98f · 真实源码,已裁剪,保留原行号

1290          """Prepare KV once; optionally defer completion until after Q projection."""
1291          gather_kv = self.pcp_enabled and needs_pcp_kv_gather(attn_metadata, self.is_pcp_decode_sharded)
1292          if gather_kv and self.qk_rope_head_dim == 0:
1293              # NoPE projects actual tokens, but slots retain the padded rank stride.
1294              pad = attn_metadata.num_input_tokens - kv_no_split.shape[0]
1295              if pad < 0:
1296                  raise ValueError("SFA PCP KV exceeds the rank-local padded token count.")
1297              if pad:
1298                  kv_no_split = nn.functional.pad(kv_no_split, (0, 0, 0, pad))
1299          local_rows = kv_no_split.shape[0]
1300          replicated = 0
1301          inputs: tuple[torch.Tensor, ...] = (kv_no_split,)
1302          pending: tuple[tuple[torch.Tensor, torch.distributed.Work | None], ...] = ()
1303          sends: tuple[torch.Tensor, ...] = ()
1304          if gather_kv:
1305              replicated = get_pcp_num_replicated_tokens(attn_metadata.num_decode_tokens or 0, self.is_pcp_decode_sharded)
1306              assert 0 <= replicated <= local_rows
1307              if self.qk_rope_head_dim:
1308                  assert cos is not None and sin is not None
1309                  inputs = (kv_no_split, cos, sin)
1310              assert all(value.shape[0] == local_rows for value in inputs)
1311              # Preserve replicated/draft decode writes without submitting a collective.
1312              if slots.shape[0] <= local_rows or replicated == local_rows:
1313                  inputs = tuple(value[:replicated] for value in inputs)
1314                  slots = slots[:replicated]
1315              else:
1316                  group = get_pcp_group()
1317                  sends = tuple(value[replicated:].contiguous() for value in inputs)
1318                  pending = tuple(all_gather_async(send, group) for send in sends)
1319                  slots = slots[: group.world_size * local_rows]
1320                  if replicated:
1321                      rank_slots = slots.view(group.world_size, local_rows)
1322                      slots = torch.cat((rank_slots[0, :replicated], rank_slots[:, replicated:].flatten()))
1323                  if defer_wait:
1324                      logger.info_once("SFA PCP main KV AllGather overlaps MLA Q projection.")
1325          elif self.pcp_enabled:
1326              slots = slots[:local_rows]
1327  
1328          def finish():
1329              # Retain the contiguous sends until HCCL has finished reading them.
1330              _ = sends
1331              for _, work in pending:
1332                  if work is not None:
1333                      work.wait()
1334              values = (
1335                  tuple(
1336                      torch.cat((value[:replicated], gathered), dim=0) if replicated else gathered
1337                      for value, (gathered, _) in zip(inputs, pending)
1338                  )
1339                  if pending
1340                  else inputs
1341              )
1342              if gather_kv:
1343                  assert values[0].shape[0] == slots.numel(), (
1344                      "SFA PCP cache write requires one slot per gathered token: "
1345                      f"tokens={values[0].shape[0]}, slots={slots.numel()}."
1346                  )
1347              gathered_cos, gathered_sin = values[1:] if len(values) > 1 else (cos, sin)
1348              return self._exec_kv_local(values[0], gathered_cos, gathered_sin, kv_cache, slots, attn_metadata)
1349  
1350          return finish if defer_wait else finish()
本篇目录 ↑02 / 06

Graph 与 MTP:padding 和真实 token 要分开

图捕获需要稳定地址与形状,采样和 draft 仍需要正确的真实请求边界。固定分支在 PCP 管理器里明确区分这两个用途。

边界固定实现为什么需要
分片后的 attention 状态_finalize_partition 更新本地 CPU 长度视图,按本地实际工作重建状态;空 rank 使用零长度占位。全局 mixed batch 到某个 rank 上可以变成纯 Decode,甚至没有真实 query。
FULL decode graph slotsprepare_slot_mappings 把 compact gather slots 放入每 rank 的固定 graph stride;无效槽填 -1。捕获形状不是实际 token 数;跨 rank padding 不能当真实 KV 写入。
持久 contextbuild_attention_context 交付 global batch、local indices、restore / gather indices 与 mask;捕获 / dummy 不沿用旧请求布局。图内读的 buffer 地址和内容要对应本步,而不是上一轮 Python 临时 tensor。
sampling / draft 恢复restore_for_sampling 区分 sharded draft aux hidden 与全局采样 hidden;需要时暴露无 padding 的 global batch。目标模型图 padding 不能直接冒充 draft 自己的执行 padding。
源码依据 · 图 slot 布局与采样 / draft 边界

vllm_ascend/worker/v2/pcp_manager.py · L251–275 ↗vllm-ascend @14a31903a98f · 真实源码,已裁剪,保留原行号

 251      def validate_config(
 252          vllm_config: VllmConfig,
 253          supports_mm_inputs: bool,
 254      ) -> None:
 255          """Validate the graph-safe Ascend MRV2 PCP configuration."""
 256          model_config = vllm_config.model_config
 257          pcp_size = vllm_config.parallel_config.prefill_context_parallel_size
 258          if pcp_size <= 1:
 259              return
 260  
 261          if model_config.is_encoder_decoder:
 262              raise NotImplementedError("MRV2 PCP does not support encoder-decoder models yet.")
 263          if vllm_config.lora_config is not None:
 264              raise NotImplementedError("MRV2 PCP does not support LoRA yet.")
 265  
 266          speculative_config = vllm_config.speculative_config
 267          if speculative_config is not None:
 268              if speculative_config.method not in ("mtp", "eagle3", "dspark"):
 269                  raise NotImplementedError(
 270                      "Ascend MRV2 PCP supports speculative decoding only with MTP, Eagle3 and DSpark."
 271                  )
 272  
 273          cudagraph_mode = vllm_config.compilation_config.cudagraph_mode
 274          if cudagraph_mode == CUDAGraphMode.FULL:
 275              raise NotImplementedError("MRV2 PCP does not support FULL CUDA graphs.")

vllm_ascend/worker/v2/pcp_manager.py · L564–591 ↗vllm-ascend @14a31903a98f · 真实源码,已裁剪,保留原行号

 564      def restore_for_sampling(
 565          self,
 566          hidden_states: torch.Tensor,
 567          aux_hidden_states: list[torch.Tensor] | None,
 568      ) -> tuple[torch.Tensor, list[torch.Tensor] | None, InputBatch]:
 569          """Restore sampling inputs and remember the batch given to the draft.
 570  
 571          Aux hidden states feed only the speculator. Sharded drafts (Eagle3)
 572          consume them in the target's rank-local layout, next to the local
 573          last hidden states; replicated drafts (DSpark) consume them globally.
 574          """
 575          assert self._global_batch is not None
 576          if self._is_draft_prefill_sharded:
 577              # Keep local aux states for the sharded draft; only sampling needs
 578              # the main hidden states restored to the global layout.
 579              hidden_states, _, global_batch = super().restore_for_sampling(hidden_states, None)
 580          else:
 581              hidden_states, aux_hidden_states, global_batch = super().restore_for_sampling(
 582                  hidden_states, aux_hidden_states
 583              )
 584          if self._restore_unpadded_global_batch():
 585              global_batch = self._expose_unpadded_global_batch(global_batch)
 586              num_tokens = global_batch.num_tokens
 587              hidden_states = hidden_states[:num_tokens]
 588              if not self._is_draft_prefill_sharded and aux_hidden_states is not None:
 589                  aux_hidden_states = [states[:num_tokens] for states in aux_hidden_states]
 590          self._sampling_global_batch = global_batch
 591          return hidden_states, aux_hidden_states, global_batch

vllm_ascend/worker/v2/pcp_manager.py · L645–694 ↗vllm-ascend @14a31903a98f · 真实源码,已裁剪,保留原行号

 645      def prepare_slot_mappings(self) -> torch.Tensor:
 646          """Pad PCP slot mappings to the fixed FULL-decode graph layout.
 647  
 648          The upstream manager packs current local rows as
 649          [rank 0 rows | rank 1 rows | ...]. A full-decode graph pads the model
 650          input of each PCP rank to graph_num_tokens. Preserve that rank-major
 651          layout when expanding the slot mapping:
 652          [rank 0 rows | rank 0 padding | rank 1 rows | rank 1 padding | ...].
 653  
 654          Sharded decode already uses the rank-local graph stride upstream.
 655          """
 656          slot_mappings = super().prepare_slot_mappings()
 657          assert self._global_batch is not None
 658          graph_num_tokens = self._global_batch.num_tokens_after_padding
 659          is_decode_only = not bool(self._global_batch.is_prefilling_np.any())
 660          if self.is_decode_sharded or not is_decode_only or graph_num_tokens <= self._global_batch.num_tokens:
 661              return slot_mappings
 662  
 663          assert self._gathered_kv_slot_mappings is not None
 664          graph_num_slots = graph_num_tokens * self.pcp_world_size
 665          local_num_tokens = slot_mappings.shape[1] // self.pcp_world_size
 666          if local_num_tokens * self.pcp_world_size != slot_mappings.shape[1]:
 667              raise RuntimeError(
 668                  "PCP gathered slot mappings must contain an equal local span "
 669                  f"for every rank, got {slot_mappings.shape[1]} slots for "
 670                  f"pcp_world_size={self.pcp_world_size}."
 671              )
 672  
 673          graph_slot_mappings = self._gathered_kv_slot_mappings[:, :graph_num_slots]
 674          # The compact source is a view of this reusable destination buffer.
 675          # Snapshot it first: a graph stride can overlap the next compact rank
 676          # span (for example, 3 compact tokens expanded to a 4-token graph).
 677          compact_slot_mappings = slot_mappings.clone()
 678          for pcp_rank in range(self.pcp_world_size):
 679              source_start = pcp_rank * local_num_tokens
 680              target_start = pcp_rank * graph_num_tokens
 681              graph_slot_mappings[:, target_start : target_start + local_num_tokens].copy_(
 682                  compact_slot_mappings[:, source_start : source_start + local_num_tokens]
 683              )
 684              graph_slot_mappings[:, target_start + local_num_tokens : target_start + graph_num_tokens].fill_(-1)
 685          return graph_slot_mappings
 686  
 687      def refresh_gathered_slot_mappings(self, slot_mappings: torch.Tensor) -> None:
 688          """Publish updated global slots in the original rank-major PCP layout."""
 689          assert self._global_batch is not None
 690          assert self._global_batch_slot_mappings is not None
 691          global_slots = self._global_batch_slot_mappings[:, : self._global_batch.num_tokens]
 692          gathered_slots = self._convert_to_gathered_slot_mappings(global_slots)
 693          if gathered_slots.data_ptr() != slot_mappings.data_ptr():
 694              slot_mappings.copy_(gathered_slots)

vllm_ascend/worker/v2/pcp_manager.py · L729–794 ↗vllm-ascend @14a31903a98f · 真实源码,已裁剪,保留原行号

 729      def build_attention_context(
 730          self,
 731          input_batch: AscendInputBatch | None = None,
 732          block_tables: tuple[torch.Tensor, ...] | None = None,
 733          slot_mappings: torch.Tensor | None = None,
 734      ) -> AscendPCPAttentionContext:
 735          """Build PCP context for the current real, capture, or idle DP batch."""
 736          if input_batch is not None and input_batch.is_dummy and not input_batch.is_cpp_profile:
 737              # Both capture and runtime dummy batches bypass partition_batch().
 738              # Saved layout state may be absent or belong to a previous request.
 739              assert block_tables is not None
 740              assert slot_mappings is not None
 741              num_tokens = input_batch.num_tokens_after_padding
 742              query_len, remainder = divmod(num_tokens, input_batch.num_reqs_after_padding)
 743              if self.is_decode_sharded and remainder == 0:
 744                  return self._build_sharded_dummy_attention_context(input_batch, query_len)
 745              restore_start = self.pcp_rank * num_tokens
 746              return AscendPCPAttentionContext(
 747                  global_batch=input_batch,
 748                  local_request_state_indices=input_batch.idx_mapping,
 749                  local_num_tokens=num_tokens,
 750                  local_to_global_req_indices=tuple(range(input_batch.num_reqs)),
 751                  global_block_tables=block_tables,
 752                  global_slot_mappings=slot_mappings.view(slot_mappings.shape[0], self.pcp_world_size, num_tokens)[
 753                      :, self.pcp_rank
 754                  ],
 755                  hidden_restore_idx=torch.arange(restore_start, restore_start + num_tokens, device=self.device),
 756              )
 757  
 758          global_batch = self._global_batch
 759          hidden_restore_idx = self._hidden_restore_idx
 760          assert global_batch is not None
 761          local_batch = self._local_batch if input_batch is None else input_batch
 762          assert local_batch is not None
 763          assert self._local_gather_idx is not None
 764          assert self._block_tables is not None
 765          assert self._global_batch_slot_mappings is not None
 766          assert hidden_restore_idx is not None
 767          global_block_table_num_blocks = None
 768          local_to_global_req_indices = None
 769          if self.dcp_world_size > 1 and bool(global_batch.is_prefilling_np.any()):
 770              global_block_table_num_blocks = torch.from_numpy(
 771                  self._block_tables.num_blocks.np[:, global_batch.idx_mapping_np[: global_batch.num_reqs]]
 772              ).to(device=self.device, non_blocking=True)
 773              global_rows = {
 774                  int(state): row for row, state in enumerate(global_batch.idx_mapping_np[: global_batch.num_reqs])
 775              }
 776              local_to_global_req_indices = tuple(
 777                  global_rows[int(state)] for state in local_batch.idx_mapping_np[: local_batch.num_reqs]
 778              )
 779          return AscendPCPAttentionContext(
 780              global_batch=global_batch,
 781              local_request_state_indices=local_batch.idx_mapping,
 782              local_num_tokens=local_batch.num_tokens_after_padding,
 783              local_to_global_req_indices=local_to_global_req_indices,
 784              local_token_indices=self._local_gather_idx[: local_batch.num_tokens],
 785              global_block_tables=self._block_tables.gather_block_tables(
 786                  global_batch.idx_mapping,
 787                  global_batch.num_reqs_after_padding,
 788              ),
 789              global_slot_mappings=self._global_batch_slot_mappings[:, : global_batch.num_tokens_after_padding],
 790              hidden_restore_idx=hidden_restore_idx,
 791              padded_gather_idx=self._padded_gather_idx,
 792              gathered_kv_write_mask=self._gathered_kv_write_mask,
 793              global_block_table_num_blocks=global_block_table_num_blocks,
 794          )
本篇目录 ↑02 / 07

混部与 PD 分离:PCP 始终是引擎内部的分工

Prefill 阶段的计算语义相通,部署中的交付责任不同。P 节点算完之后,D 能不能接着用缓存,还涉及另一套传输契约。

场景PCP 负责另一个边界
混部 Prefill / Decode同一引擎的 local query、gathered KV 与 global hidden 恢复。没有跨引擎 KV 交付;是否用 HiSparse 由本引擎配置决定。
PD 的 P 节点在 P 引擎内对 Prefill 做相同的切分与恢复。生成的 KV 如何交给 D,取决于 KV connector、可传输组与内存布局。
PD 的 D 节点D 用自己的并行配置和本地请求 / 缓存状态执行。不能继承 P 的 rank-local slot / Resident / Hot 编号;接收完成要建立 D 的本地状态。

因此,“P 不开 HiSparse,D 开 HiSparse,再加 PCP”同时涉及 P 引擎 PCP、P→D KV 交付、D 引擎 HiSparse 三层。下一篇把当前分支已经实现的同引擎组合,与尚未支持的外部 connector 组合分开。

跨引擎机制的固定源码依据见 HiSparse 篇:Core PD 接口与收端恢复;当前 Ascend 组合限制见 组合篇:支持矩阵。

本篇目录 ↑02 / 08

带着这四个契约进入组合篇

先把 PCP 已提供的东西列清楚,再看 HiSparse 增加了什么。

  1. global batch 保留规范请求身份;local batch 只描述本 rank 的计算工作。
  2. 新 KV 的写行顺序以 gathered slots 和 write mask 为准,不能使用 query 行数来代替。
  3. hidden states 汇集后按 restore indices 回到全局顺序,采样 / draft 有各自边界。
  4. graph / padding / 空 rank 必须服从同一 collective 与写入布局;HiSparse 适配继续复用这些契约。

接下来读 HiSparse + PCP 组合设计 →。