cp_utils.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  1. # SPDX-License-Identifier: Apache-2.0
  2. # SPDX-FileCopyrightText: Copyright contributors to the vLLM project
  3. from types import SimpleNamespace
  4. from typing import TYPE_CHECKING, Any, cast
  5. import torch
  6. from vllm.config import VllmConfig, get_layers_from_vllm_config
  7. from vllm.distributed import get_dcp_group
  8. from vllm.logger import init_logger
  9. from vllm.v1.attention.backend import CommonAttentionMetadata
  10. from vllm.v1.attention.backends.utils import split_decodes_prefills_and_extends
  11. if TYPE_CHECKING:
  12. from vllm.model_executor.layers.attention_layer_base import AttentionLayerBase
  13. else:
  14. AttentionLayerBase = object
  15. logger = init_logger(__name__)
  16. def check_attention_cp_compatibility(vllm_config: VllmConfig) -> None:
  17. pcp_size = vllm_config.parallel_config.prefill_context_parallel_size
  18. dcp_size = vllm_config.parallel_config.decode_context_parallel_size
  19. interleave_size = vllm_config.parallel_config.cp_kv_cache_interleave_size
  20. if pcp_size * dcp_size > 1:
  21. layer_type = cast(type[Any], AttentionLayerBase)
  22. layers = get_layers_from_vllm_config(vllm_config, layer_type)
  23. for layer in layers.values():
  24. get_attn_backend = getattr(layer, "get_attn_backend", None)
  25. if pcp_size > 1 and get_attn_backend is not None:
  26. backend = get_attn_backend()
  27. assert backend.supports_pcp(), (
  28. "PCP requires attention backend support, "
  29. f"but {backend.get_name()} does not support PCP."
  30. )
  31. layer_impl = getattr(layer, "impl", None)
  32. if layer_impl is None:
  33. continue
  34. if vllm_config.speculative_config is not None and interleave_size > 1:
  35. assert layer_impl.supports_mtp_with_cp_non_trivial_interleave_size, (
  36. "MTP with cp_kv_cache_interleave_size > 1 is not "
  37. f"supported in {layer_impl.__class__.__name__}."
  38. )
  39. if dcp_size > 1:
  40. assert layer_impl.need_to_return_lse_for_decode, (
  41. "Decode Context Parallelism (DCP) requires attention "
  42. "implementations to return the softmax LSE during decode, "
  43. f"but {layer_impl.__class__.__name__} does not. "
  44. "Try a different backend by setting "
  45. "--attention-backend or disable DCP."
  46. )
  47. def get_kv_cache_shard_count() -> int:
  48. try:
  49. dcp_world_size = get_dcp_group().world_size
  50. except AssertionError:
  51. # DCP might not be initialized in testing
  52. dcp_world_size = 1
  53. return dcp_world_size
  54. def get_dcp_dummy_context_len(
  55. dcp_world_size: int,
  56. cp_kv_cache_interleave_size: int,
  57. has_kv_cache_config: bool,
  58. create_mixed_batch: bool,
  59. is_graph_capturing: bool,
  60. uniform_decode: bool,
  61. ) -> int:
  62. if (
  63. dcp_world_size <= 1
  64. or not has_kv_cache_config
  65. or not (create_mixed_batch or (is_graph_capturing and uniform_decode))
  66. ):
  67. return 0
  68. return dcp_world_size * cp_kv_cache_interleave_size
  69. def prepare_dcp_dummy_context_metadata(
  70. *,
  71. input_batch: Any,
  72. kv_cache_config: Any,
  73. query_pos: Any,
  74. positions: torch.Tensor,
  75. query_start_loc: Any,
  76. num_reqs: int,
  77. num_tokens_unpadded: int,
  78. dcp_dummy_context_len: int,
  79. ) -> None:
  80. """Populate valid fake KV metadata for DCP CUDA graph warmup/capture."""
  81. if dcp_dummy_context_len == 0:
  82. return
  83. # DCP graph warmup may exercise context attention, so block-table entries
  84. # must point at allocated KV blocks.
  85. assert kv_cache_config is not None
  86. max_valid_block_id = kv_cache_config.num_blocks - 1
  87. assert max_valid_block_id > 0
  88. for blk_table in input_batch.block_table.block_tables:
  89. max_row_blocks = (
  90. blk_table.max_num_blocks_per_req // blk_table.blocks_per_kv_block
  91. )
  92. block_ids = [
  93. (block_idx % max_valid_block_id) + 1 for block_idx in range(max_row_blocks)
  94. ]
  95. for req_idx in range(num_reqs):
  96. blk_table.add_row(block_ids, req_idx)
  97. blk_table.commit_block_table(num_reqs)
  98. query_pos.copy_to_gpu(num_tokens_unpadded)
  99. positions[:num_tokens_unpadded] = (
  100. query_pos.gpu[:num_tokens_unpadded] + dcp_dummy_context_len
  101. )
  102. input_batch.block_table.compute_slot_mapping(
  103. num_reqs,
  104. query_start_loc.gpu[: num_reqs + 1],
  105. positions[:num_tokens_unpadded],
  106. )
  107. def should_skip_dcp_context_attention(context_kv_lens_cpu: torch.Tensor) -> bool:
  108. """Whether DCP context attention can be skipped for this batch.
  109. Must be computed from rank-invariant inputs only (the global context
  110. lengths, NOT this rank's local share from get_dcp_local_seq_lens): the
  111. non-skip path in _forward_with_dcp issues DCP collectives (query
  112. all-gather + LSE combine), so every DCP rank must take the same branch.
  113. A rank can hold zero local context tokens while other ranks still hold
  114. context for the same batch.
  115. """
  116. return int(context_kv_lens_cpu.max().item()) == 0
  117. def split_dcp_context_queries(
  118. query_start_loc: torch.Tensor,
  119. seq_lens_cpu_upper_bound: torch.Tensor | None,
  120. max_query_len: int,
  121. num_actual_tokens: int,
  122. ) -> tuple[int, int, int, int]:
  123. """Split reordered DCP context queries into decode and extend regions."""
  124. num_reqs = query_start_loc.shape[0] - 1
  125. if max_query_len <= 1:
  126. return num_reqs, 0, num_actual_tokens, 0
  127. if seq_lens_cpu_upper_bound is None:
  128. return 0, num_reqs, 0, num_actual_tokens
  129. common_attn_metadata = cast(
  130. CommonAttentionMetadata,
  131. SimpleNamespace(
  132. max_query_len=max_query_len,
  133. num_reqs=num_reqs,
  134. num_actual_tokens=num_actual_tokens,
  135. query_start_loc_cpu=query_start_loc,
  136. seq_lens_cpu_upper_bound=seq_lens_cpu_upper_bound,
  137. is_prefilling=None,
  138. ),
  139. )
  140. (
  141. num_decodes,
  142. num_extends,
  143. _num_prefills,
  144. num_decode_tokens,
  145. num_extend_tokens,
  146. _num_prefill_tokens,
  147. ) = split_decodes_prefills_and_extends(common_attn_metadata)
  148. return num_decodes, num_extends, num_decode_tokens, num_extend_tokens
  149. def should_split_fa2_dcp_context_attention(
  150. fa_version: int | None,
  151. max_query_len: int,
  152. num_reqs: int,
  153. num_decode_reqs: int,
  154. num_context_prefill_reqs: int,
  155. ) -> bool:
  156. num_prefills = num_reqs - num_decode_reqs
  157. # TODO: Remove this FA2-only DCP compatibility path once FA4 supports
  158. # the Qwen3.5 head_size=256 shape on Blackwell and can be used here.
  159. # FA2 paged-varlen context attention can fail for DCP mixed batches when
  160. # decode rows, context-bearing extend rows, and zero-context pure prefill
  161. # rows are submitted together.
  162. return (
  163. fa_version == 2
  164. and max_query_len > 1
  165. and num_prefills > 0
  166. and (num_decode_reqs > 0 or num_context_prefill_reqs < num_prefills)
  167. )
  168. def run_split_fa2_dcp_context_attention(
  169. flash_attn_varlen_func: Any,
  170. query_across_dcp: torch.Tensor,
  171. key_cache: torch.Tensor,
  172. value_cache: torch.Tensor,
  173. dcp_context_out: torch.Tensor,
  174. cu_seqlens_q: torch.Tensor,
  175. max_seqlen_q: int,
  176. dcp_context_kv_lens: torch.Tensor,
  177. max_dcp_context_kv_len: int,
  178. softmax_scale: float,
  179. alibi_slopes: torch.Tensor | None,
  180. sliding_window_size: list[int] | None,
  181. block_table: torch.Tensor,
  182. softcap: float,
  183. fa_version: int,
  184. q_descale: torch.Tensor | None,
  185. k_descale: torch.Tensor | None,
  186. v_descale: torch.Tensor | None,
  187. max_num_splits: int,
  188. num_heads: int,
  189. dcp_world_size: int,
  190. num_decode_reqs: int,
  191. num_context_prefill_reqs: int,
  192. num_decode_tokens: int,
  193. num_context_prefill_tokens: int,
  194. ) -> tuple[torch.Tensor, torch.Tensor]:
  195. dcp_context_out.zero_()
  196. context_lse = torch.full(
  197. (num_heads * dcp_world_size, query_across_dcp.shape[0]),
  198. -torch.inf,
  199. dtype=torch.float32,
  200. device=query_across_dcp.device,
  201. )
  202. if num_decode_tokens > 0:
  203. _, decode_context_lse = flash_attn_varlen_func(
  204. q=query_across_dcp[:num_decode_tokens],
  205. k=key_cache,
  206. v=value_cache,
  207. out=dcp_context_out[:num_decode_tokens],
  208. cu_seqlens_q=cu_seqlens_q[: num_decode_reqs + 1],
  209. max_seqlen_q=1,
  210. seqused_k=dcp_context_kv_lens[:num_decode_reqs],
  211. max_seqlen_k=max_dcp_context_kv_len,
  212. softmax_scale=softmax_scale,
  213. causal=False,
  214. alibi_slopes=alibi_slopes,
  215. window_size=sliding_window_size,
  216. block_table=block_table[:num_decode_reqs],
  217. softcap=softcap,
  218. return_softmax_lse=True,
  219. scheduler_metadata=None,
  220. fa_version=fa_version,
  221. q_descale=q_descale[:num_decode_reqs] if q_descale is not None else None,
  222. k_descale=k_descale[:num_decode_reqs] if k_descale is not None else None,
  223. v_descale=v_descale[:num_decode_reqs] if v_descale is not None else None,
  224. num_splits=max_num_splits,
  225. )
  226. context_lse[:, :num_decode_tokens] = decode_context_lse
  227. if num_context_prefill_tokens > 0:
  228. prefill_start = num_decode_tokens
  229. prefill_end = prefill_start + num_context_prefill_tokens
  230. prefill_query_start_loc = (
  231. cu_seqlens_q[
  232. num_decode_reqs : num_decode_reqs + num_context_prefill_reqs + 1
  233. ]
  234. - num_decode_tokens
  235. )
  236. prefill_req_slice = slice(
  237. num_decode_reqs, num_decode_reqs + num_context_prefill_reqs
  238. )
  239. _, prefill_context_lse = flash_attn_varlen_func(
  240. q=query_across_dcp[prefill_start:prefill_end],
  241. k=key_cache,
  242. v=value_cache,
  243. out=dcp_context_out[prefill_start:prefill_end],
  244. cu_seqlens_q=prefill_query_start_loc,
  245. max_seqlen_q=max_seqlen_q,
  246. seqused_k=dcp_context_kv_lens[prefill_req_slice],
  247. max_seqlen_k=max_dcp_context_kv_len,
  248. softmax_scale=softmax_scale,
  249. causal=False,
  250. alibi_slopes=alibi_slopes,
  251. window_size=sliding_window_size,
  252. block_table=block_table[prefill_req_slice],
  253. softcap=softcap,
  254. return_softmax_lse=True,
  255. scheduler_metadata=None,
  256. fa_version=fa_version,
  257. q_descale=q_descale[prefill_req_slice] if q_descale is not None else None,
  258. k_descale=k_descale[prefill_req_slice] if k_descale is not None else None,
  259. v_descale=v_descale[prefill_req_slice] if v_descale is not None else None,
  260. num_splits=max_num_splits,
  261. )
  262. context_lse[:, prefill_start:prefill_end] = prefill_context_lse
  263. return dcp_context_out, context_lse