sparse_attn_indexer.py 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898
  1. # SPDX-License-Identifier: Apache-2.0
  2. # SPDX-FileCopyrightText: Copyright contributors to the vLLM project
  3. """Custom Sparse Attention Indexer layers."""
  4. import torch
  5. import vllm.envs as envs
  6. from vllm import _custom_ops as ops
  7. from vllm._aiter_ops import rocm_aiter_ops
  8. from vllm.compilation.breakable_cudagraph import eager_break_during_capture
  9. from vllm.config import CUDAGraphMode, get_current_vllm_config
  10. from vllm.distributed import get_dcp_group, get_pcp_group
  11. from vllm.forward_context import get_forward_context
  12. from vllm.logger import init_logger
  13. from vllm.model_executor.custom_op import CustomOp
  14. from vllm.model_executor.layers.quantization.utils.quant_utils import (
  15. get_fp8_min_max,
  16. )
  17. from vllm.platforms import current_platform
  18. from vllm.triton_utils import tl, triton
  19. from vllm.utils.deep_gemm import (
  20. fp8_fp4_mqa_logits,
  21. fp8_fp4_paged_mqa_logits,
  22. has_deep_gemm,
  23. )
  24. from vllm.utils.import_utils import has_cutedsl
  25. from vllm.utils.torch_utils import (
  26. LayerNameType,
  27. _encode_layer_name,
  28. _resolve_layer_name,
  29. direct_register_custom_op,
  30. )
  31. from vllm.v1.attention.backends.mla.indexer import (
  32. DeepseekV32IndexerMetadata,
  33. )
  34. from vllm.v1.attention.ops.common import pack_seq_triton, unpack_seq_triton
  35. from vllm.v1.attention.ops.pcp import maybe_gather_indexer_k
  36. from vllm.v1.worker.workspace import current_workspace_manager
  37. logger = init_logger(__name__)
  38. RADIX_TOPK_WORKSPACE_SIZE = 1024 * 1024
  39. # MXFP4 layout: 2 values packed per byte, ue8m0 (1-byte) scale per block of 32.
  40. MXFP4_BLOCK_SIZE = 32
  41. def _assert_cutedsl_dcp_merge_supported(
  42. logits: torch.Tensor,
  43. topk_indices: torch.Tensor,
  44. k: int,
  45. ) -> None:
  46. # The DCP merge only supports the CuteDSL path (Triton pack kernel + CuteDSL
  47. # stable-topk selector); there is no PyTorch fallback. The first cut targets
  48. # Blackwell/Hopper with index_topk in (512, 1024, 2048) (the selector's radix
  49. # sizing); the Triton pack itself has no shape/topk constraints.
  50. if not has_cutedsl():
  51. raise RuntimeError(
  52. "DCP sparse-indexer merge requires CuteDSL; install it or disable DCP."
  53. )
  54. if logits.device.type != "cuda":
  55. raise RuntimeError("DCP sparse-indexer merge requires CUDA tensors.")
  56. if logits.dtype != torch.float32 or topk_indices.dtype != torch.int32:
  57. raise RuntimeError(
  58. "DCP sparse-indexer merge requires fp32 logits and int32 indices."
  59. )
  60. if k not in (512, 1024, 2048):
  61. raise RuntimeError(
  62. f"DCP sparse-indexer merge requires index_topk in (512, 1024, 2048); "
  63. f"got {k}."
  64. )
  65. def _merge_dcp_topk_global(
  66. logits: torch.Tensor,
  67. topk_indices: torch.Tensor,
  68. topk_tokens: int,
  69. dcp_rank: int,
  70. dcp_world_size: int,
  71. cp_interleave: int,
  72. row_starts: torch.Tensor | None = None,
  73. ) -> None:
  74. """Merge each DCP rank's local top-K into the global top-K.
  75. ``topk_indices`` are this rank's local top-K positions into its 1/N KV
  76. shard. A token in the global top-K must also be in its owning rank's local
  77. top-K (at most ``topk_tokens - 1`` tokens rank globally above it, hence at
  78. most that many on its own rank), so exchanging only the per-rank local
  79. candidates is exact -- equivalent to all-gathering the full logit matrix,
  80. but it ships ``dcp_world_size * topk_tokens`` candidates instead of the whole
  81. score row. Overwrites ``topk_indices`` with global token ids (``-1`` for
  82. padding); the attention backend localizes them back to physical slots per
  83. rank.
  84. """
  85. if dcp_world_size <= 1:
  86. return
  87. # CuteDSL-only path (no PyTorch fallback): Triton-pack each rank's
  88. # (score, global_id) candidates on-device, all-gather, then the CuteDSL
  89. # stable-topk selector.
  90. _assert_cutedsl_dcp_merge_supported(logits, topk_indices, topk_tokens)
  91. from vllm.model_executor.kernels.attention.dsa.dcp_indexer_cutedsl import (
  92. pack_dcp_topk_candidates_cutedsl,
  93. stable_topk_from_gathered_candidates_cutedsl,
  94. )
  95. packed = torch.empty(
  96. (*topk_indices.shape, 2),
  97. dtype=torch.float32,
  98. device=topk_indices.device,
  99. )
  100. pack_dcp_topk_candidates_cutedsl(
  101. logits,
  102. topk_indices,
  103. packed,
  104. dcp_rank,
  105. dcp_world_size,
  106. cp_interleave,
  107. row_starts,
  108. )
  109. gathered = get_dcp_group().all_gather(packed, dim=1)
  110. stable_topk_from_gathered_candidates_cutedsl(
  111. gathered, topk_tokens, out=topk_indices
  112. )
  113. @triton.jit
  114. def _fused_indexer_q_rope_quant_kernel(
  115. positions,
  116. q,
  117. q_s0,
  118. q_s1,
  119. cos_sin_cache,
  120. cos_sin_s0,
  121. q_fp8,
  122. q_fp8_s0,
  123. q_fp8_s1,
  124. weights,
  125. weights_s0,
  126. weights_s1,
  127. weights_out,
  128. weights_out_s0,
  129. weights_out_s1,
  130. softmax_scale,
  131. head_scale,
  132. fp8_min: tl.constexpr,
  133. fp8_max: tl.constexpr,
  134. is_neox: tl.constexpr,
  135. ):
  136. token = tl.program_id(0)
  137. head = tl.program_id(1)
  138. offs32 = tl.arange(0, 32)
  139. offs64 = tl.arange(0, 64)
  140. pos = tl.load(positions + token)
  141. cos = tl.load(cos_sin_cache + pos * cos_sin_s0 + offs32).to(tl.float32)
  142. sin = tl.load(cos_sin_cache + pos * cos_sin_s0 + 32 + offs32).to(tl.float32)
  143. q_base = q + token * q_s0 + head * q_s1
  144. out_base = q_fp8 + token * q_fp8_s0 + head * q_fp8_s1
  145. if is_neox:
  146. # NeoX layout, x0 = q[0:32], x1 = q[32:64]
  147. x0 = tl.load(q_base + offs32).to(tl.float32)
  148. x1 = tl.load(q_base + 32 + offs32).to(tl.float32)
  149. else:
  150. # interleaved layout
  151. # x0 = q[0, 2, 4, ...], x1 = q[1, 3, 5, ...]
  152. x0 = tl.load(q_base + offs32 * 2).to(tl.float32)
  153. x1 = tl.load(q_base + offs32 * 2 + 1).to(tl.float32)
  154. r0 = (x0 * cos - x1 * sin).to(tl.bfloat16).to(tl.float32)
  155. r1 = (x1 * cos + x0 * sin).to(tl.bfloat16).to(tl.float32)
  156. amax = tl.maximum(tl.max(tl.abs(r0)), tl.max(tl.abs(r1)))
  157. q_nope = tl.load(q_base + 64 + offs64).to(tl.float32)
  158. amax = tl.maximum(amax, tl.max(tl.abs(q_nope)))
  159. scale_raw = tl.maximum(amax, 1e-10) * (1.0 / fp8_max)
  160. # e8m0 format
  161. q_scale = tl.math.exp2(tl.ceil(tl.log2(scale_raw)))
  162. if is_neox:
  163. tl.store(
  164. out_base + offs32,
  165. tl.clamp(r0 / q_scale, fp8_min, fp8_max).to(q_fp8.dtype.element_ty),
  166. )
  167. tl.store(
  168. out_base + 32 + offs32,
  169. tl.clamp(r1 / q_scale, fp8_min, fp8_max).to(q_fp8.dtype.element_ty),
  170. )
  171. else:
  172. tl.store(
  173. out_base + offs32 * 2,
  174. tl.clamp(r0 / q_scale, fp8_min, fp8_max).to(q_fp8.dtype.element_ty),
  175. )
  176. tl.store(
  177. out_base + offs32 * 2 + 1,
  178. tl.clamp(r1 / q_scale, fp8_min, fp8_max).to(q_fp8.dtype.element_ty),
  179. )
  180. tl.store(
  181. out_base + 64 + offs64,
  182. tl.clamp(q_nope / q_scale, fp8_min, fp8_max).to(q_fp8.dtype.element_ty),
  183. )
  184. weight = tl.load(weights + token * weights_s0 + head * weights_s1).to(tl.float32)
  185. tl.store(
  186. weights_out + token * weights_out_s0 + head * weights_out_s1,
  187. weight * q_scale * softmax_scale * head_scale,
  188. )
  189. def fused_indexer_q_rope_quant(
  190. positions: torch.Tensor,
  191. q: torch.Tensor,
  192. cos_sin_cache: torch.Tensor,
  193. weights: torch.Tensor,
  194. softmax_scale: float,
  195. head_scale: float,
  196. is_neox: bool,
  197. ) -> tuple[torch.Tensor, torch.Tensor]:
  198. assert current_platform.is_cuda()
  199. assert q.dtype == torch.bfloat16
  200. assert q.shape[-1] == 128
  201. assert cos_sin_cache.shape[-1] == 64
  202. assert weights.shape == q.shape[:2]
  203. q_fp8 = torch.empty_like(q, dtype=current_platform.fp8_dtype())
  204. weights_out = torch.empty_like(weights, dtype=torch.float32)
  205. fp8_min, fp8_max = get_fp8_min_max()
  206. _fused_indexer_q_rope_quant_kernel[(q.shape[0], q.shape[1])](
  207. positions,
  208. q,
  209. q.stride(0),
  210. q.stride(1),
  211. cos_sin_cache,
  212. cos_sin_cache.stride(0),
  213. q_fp8,
  214. q_fp8.stride(0),
  215. q_fp8.stride(1),
  216. weights,
  217. weights.stride(0),
  218. weights.stride(1),
  219. weights_out,
  220. weights_out.stride(0),
  221. weights_out.stride(1),
  222. softmax_scale,
  223. head_scale,
  224. fp8_min=fp8_min,
  225. fp8_max=fp8_max,
  226. is_neox=is_neox,
  227. num_warps=1,
  228. )
  229. return q_fp8, weights_out
  230. def _gather_workspace_shapes(
  231. total_seq_lens: int,
  232. head_dim: int,
  233. fp8_dtype: torch.dtype,
  234. use_fp4_cache: bool,
  235. ) -> tuple[tuple[tuple[int, int], torch.dtype], tuple[tuple[int, int], torch.dtype]]:
  236. """Return ((values_shape, values_dtype), (scales_shape, scales_dtype)) for
  237. the K-gather workspace. FP8 path: (T, head_dim) fp8 + (T, 4) uint8 fp32
  238. scales. MXFP4 path: (T, head_dim // 2) uint8 packed mxfp4 +
  239. (T, head_dim // MXFP4_BLOCK_SIZE) uint8 ue8m0 scales."""
  240. if use_fp4_cache:
  241. return (
  242. ((total_seq_lens, head_dim // 2), torch.uint8),
  243. ((total_seq_lens, head_dim // MXFP4_BLOCK_SIZE), torch.uint8),
  244. )
  245. return (
  246. ((total_seq_lens, head_dim), fp8_dtype),
  247. ((total_seq_lens, 4), torch.uint8),
  248. )
  249. def kv_cache_as_quant_view(
  250. kv_cache: torch.Tensor,
  251. head_dim: int,
  252. use_fp4_cache: bool,
  253. ) -> torch.Tensor:
  254. """4D ``[num_blocks, block_size, 1, head_width]`` view expected by
  255. DeepGEMM, from the 3D indexer kv-cache allocation."""
  256. if use_fp4_cache:
  257. assert kv_cache.ndim == 3 and kv_cache.dtype == torch.uint8
  258. num_blocks, block_size, _ = kv_cache.shape
  259. page_bytes = int(kv_cache.stride(0))
  260. fp4_bytes = head_dim // 2 + head_dim // MXFP4_BLOCK_SIZE
  261. return torch.as_strided(
  262. kv_cache,
  263. size=(num_blocks, block_size, 1, fp4_bytes),
  264. stride=(page_bytes, fp4_bytes, fp4_bytes, 1),
  265. )
  266. return kv_cache.unsqueeze(-2)
  267. @eager_break_during_capture
  268. def sparse_attn_indexer(
  269. hidden_states: torch.Tensor,
  270. k_cache_prefix: LayerNameType,
  271. kv_cache: torch.Tensor,
  272. q_quant: torch.Tensor,
  273. q_scale: torch.Tensor | None,
  274. k: torch.Tensor | None,
  275. weights: torch.Tensor,
  276. quant_block_size: int,
  277. scale_fmt: str | None,
  278. topk_tokens: int,
  279. head_dim: int,
  280. max_model_len: int,
  281. total_seq_lens: int,
  282. topk_indices_buffer: torch.Tensor,
  283. skip_k_cache_insert: bool,
  284. use_pcp: bool,
  285. dense_mha_metadata_layer_name: LayerNameType,
  286. use_fp4_cache: bool = False,
  287. dcp_rank: int = 0,
  288. dcp_world_size: int = 1,
  289. cp_kv_cache_interleave_size: int = 1,
  290. skip_topk_buffer_clear: bool = False,
  291. ) -> torch.Tensor:
  292. # careful! this will be None in dummy run
  293. forward_context = get_forward_context()
  294. attn_metadata = forward_context.attn_metadata
  295. fp8_dtype = current_platform.fp8_dtype()
  296. k_cache_prefix = _resolve_layer_name(k_cache_prefix)
  297. # assert isinstance(attn_metadata, dict)
  298. if not isinstance(attn_metadata, dict):
  299. # Reserve workspace for indexer during profiling run
  300. values_spec, scales_spec = _gather_workspace_shapes(
  301. total_seq_lens, head_dim, fp8_dtype, use_fp4_cache
  302. )
  303. current_workspace_manager().get_simultaneous(
  304. values_spec,
  305. scales_spec,
  306. ((RADIX_TOPK_WORKSPACE_SIZE,), torch.uint8),
  307. )
  308. # Dummy allocation to simulate for peak logits tensor memory during inference.
  309. # FP8 elements so elements == bytes
  310. max_logits_elems = envs.VLLM_SPARSE_INDEXER_MAX_LOGITS_MB * 1024 * 1024
  311. _ = torch.empty(
  312. max_logits_elems, dtype=torch.uint8, device=hidden_states.device
  313. )
  314. return sparse_attn_indexer_fake(
  315. hidden_states,
  316. k_cache_prefix,
  317. kv_cache,
  318. q_quant,
  319. q_scale,
  320. k,
  321. weights,
  322. quant_block_size,
  323. scale_fmt,
  324. topk_tokens,
  325. head_dim,
  326. max_model_len,
  327. total_seq_lens,
  328. topk_indices_buffer,
  329. skip_k_cache_insert,
  330. use_pcp,
  331. dense_mha_metadata_layer_name,
  332. use_fp4_cache,
  333. )
  334. attn_metadata_narrowed = attn_metadata[k_cache_prefix]
  335. assert isinstance(attn_metadata_narrowed, DeepseekV32IndexerMetadata)
  336. slot_mapping = attn_metadata_narrowed.slot_mapping
  337. has_decode = attn_metadata_narrowed.num_decodes > 0
  338. has_prefill = attn_metadata_narrowed.num_prefills > 0
  339. num_decode_tokens = attn_metadata_narrowed.num_decode_tokens
  340. # q_scale is required iff the FP4 cache path is enabled; the FP8 path
  341. # folds the Q scale into `weights` inside fused_indexer_q_rope_quant.
  342. if use_fp4_cache:
  343. assert q_scale is not None, "use_fp4_cache=True requires q_scale"
  344. else:
  345. assert q_scale is None, "q_scale must be None when use_fp4_cache=False"
  346. # During speculative decoding, k may be padded to the CUDA graph batch
  347. # size while slot_mapping only covers actual tokens. Truncate k to avoid
  348. # out-of-bounds reads in the kernel.
  349. # Keep PCP padding so every rank contributes the same all-gather shape.
  350. num_tokens = slot_mapping.shape[0]
  351. if use_pcp:
  352. num_tokens //= get_pcp_group().world_size
  353. if k is not None:
  354. k = k[:num_tokens]
  355. if not skip_k_cache_insert:
  356. assert k is not None
  357. k, slot_mapping_for_cache = maybe_gather_indexer_k(
  358. k,
  359. slot_mapping,
  360. num_decode_tokens,
  361. use_pcp,
  362. )
  363. # scale_fmt can be None, but the function expects str
  364. assert scale_fmt is not None
  365. assert not use_fp4_cache, "Unfused FP4 Insert is not supported yet"
  366. ops.indexer_k_quant_and_cache(
  367. k,
  368. kv_cache,
  369. slot_mapping_for_cache,
  370. quant_block_size,
  371. scale_fmt,
  372. )
  373. # The indexer and main MLA may classify the same short extend differently
  374. # because they use independent decode thresholds. Only the main MLA route
  375. # can determine whether the top-k indices will be consumed.
  376. if forward_context.cudagraph_runtime_mode != CUDAGraphMode.FULL:
  377. dense_mha_layer = _resolve_layer_name(dense_mha_metadata_layer_name)
  378. if dense_mha_layer:
  379. mla_metadata = attn_metadata.get(dense_mha_layer)
  380. prefill_metadata = getattr(mla_metadata, "prefill", None)
  381. if (
  382. getattr(prefill_metadata, "use_dense_mha", False)
  383. and getattr(mla_metadata, "num_decode_tokens", -1) == 0
  384. and not torch.cuda.is_current_stream_capturing()
  385. ):
  386. # Deliberately leave the buffer untouched. Dense MHA does not
  387. # consume top-k indices for this batch; clearing it would be
  388. # unnecessary work.
  389. return topk_indices_buffer
  390. # The buffer must be pre-filled with -1 (the "no token" sentinel) before the
  391. # top-k kernels scatter valid indices into it. On the fused deepseek_v32
  392. # nvidia path, _fused_norm_rope_kernel already cleared the same
  393. # [:num_tokens, :topk] region earlier in this forward, so skip the redundant
  394. # fill.
  395. if not skip_topk_buffer_clear:
  396. topk_indices_buffer[: hidden_states.shape[0]] = -1
  397. if has_prefill:
  398. prefill_metadata = attn_metadata_narrowed.prefill
  399. assert prefill_metadata is not None
  400. # Get the full shared workspace buffers once (will allocate on first use).
  401. # Layout switches between FP8 (head_dim bytes + 4-byte fp32 scale) and
  402. # MXFP4 (head_dim/2 bytes packed + head_dim/MXFP4_BLOCK_SIZE ue8m0
  403. # scales) based on use_fp4_cache.
  404. workspace_manager = current_workspace_manager()
  405. values_spec, scales_spec = _gather_workspace_shapes(
  406. total_seq_lens, head_dim, fp8_dtype, use_fp4_cache
  407. )
  408. k_quant_full, k_scale_full = workspace_manager.get_simultaneous(
  409. values_spec,
  410. scales_spec,
  411. )
  412. for chunk in prefill_metadata.chunks:
  413. cu_seqlen_ks = chunk.cu_seqlen_ks
  414. cu_seqlen_ke = chunk.cu_seqlen_ke
  415. assert chunk.local_cu_seq_lens is not None
  416. k_quant = k_quant_full[: chunk.max_local_total_seq_lens]
  417. k_scale = k_scale_full[: chunk.max_local_total_seq_lens]
  418. if not chunk.skip_kv_gather and chunk.local_total_seq_lens > 0:
  419. ops.cp_gather_indexer_k_quant_cache(
  420. kv_cache,
  421. k_quant,
  422. k_scale,
  423. chunk.block_table,
  424. chunk.local_cu_seq_lens,
  425. )
  426. q_slice = q_quant[chunk.token_start : chunk.token_end]
  427. q_scale_slice = (
  428. q_scale[chunk.token_start : chunk.token_end]
  429. if q_scale is not None
  430. else None
  431. )
  432. topk_indices = topk_indices_buffer[
  433. chunk.token_start : chunk.token_end, :topk_tokens
  434. ]
  435. if chunk.local_total_seq_lens == 0:
  436. logits = q_slice.new_empty((q_slice.shape[0], 0), dtype=torch.float32)
  437. topk_indices.fill_(-1)
  438. else:
  439. # DeepGEMM scalar-type tags (zero-copy): MXFP4 values → int8
  440. # (kPackedFP4), scales → int32 squeezed to 1-D kv_sf / 2-D q_sf.
  441. if use_fp4_cache:
  442. q_slice_cast = q_slice.view(torch.int8)
  443. k_quant_cast = k_quant.view(torch.int8)
  444. k_scale_cast = k_scale.view(torch.int32).squeeze(-1)
  445. else:
  446. q_slice_cast = q_slice
  447. k_quant_cast = k_quant
  448. k_scale_cast = k_scale.view(torch.float32).squeeze(-1)
  449. if current_platform.is_xpu():
  450. if q_scale_slice is not None:
  451. raise RuntimeError("XPU fp8_mqa_logits does not support FP4 Q")
  452. logits = torch.ops.vllm.xpu_fp8_mqa_logits(
  453. q_slice_cast,
  454. k_quant_cast,
  455. k_scale_cast,
  456. weights[chunk.token_start : chunk.token_end],
  457. cu_seqlen_ks,
  458. cu_seqlen_ke,
  459. )
  460. else:
  461. logits = fp8_fp4_mqa_logits(
  462. (q_slice_cast, q_scale_slice),
  463. (k_quant_cast, k_scale_cast),
  464. weights[chunk.token_start : chunk.token_end],
  465. cu_seqlen_ks,
  466. cu_seqlen_ke,
  467. clean_logits=False,
  468. )
  469. num_rows = logits.shape[0]
  470. ops.top_k_per_row_prefill(
  471. logits,
  472. cu_seqlen_ks,
  473. cu_seqlen_ke,
  474. topk_indices,
  475. num_rows,
  476. logits.stride(0),
  477. logits.stride(1),
  478. topk_tokens,
  479. )
  480. _merge_dcp_topk_global(
  481. logits,
  482. topk_indices,
  483. topk_tokens,
  484. dcp_rank,
  485. dcp_world_size,
  486. cp_kv_cache_interleave_size,
  487. row_starts=chunk.cu_seqlen_ks,
  488. )
  489. if has_decode:
  490. decode_metadata = attn_metadata_narrowed.decode
  491. assert decode_metadata is not None
  492. kv_cache = kv_cache_as_quant_view(kv_cache, head_dim, use_fp4_cache)
  493. decode_lens = decode_metadata.decode_lens
  494. if num_decode_tokens == 0:
  495. padded_q_quant_decode_tokens = q_quant[:1].reshape(1, 1, *q_quant.shape[1:])
  496. padded_q_scale = (
  497. q_scale[:1].reshape(1, 1, *q_scale.shape[1:])
  498. if q_scale is not None
  499. else None
  500. )
  501. elif decode_metadata.requires_padding:
  502. # pad in edge case where we have short chunked prefill length <
  503. # decode_threshold since we unstrictly split
  504. # prefill and decode by decode_threshold
  505. # (currently set to 1 + speculative tokens).
  506. # FP8 Q is float8_e4m3fn (pack_seq_triton's fp32 pad path is OK —
  507. # downstream context_lens masks stale slots). MXFP4 Q is two
  508. # uint8 tensors (values + ue8m0 scales) — use the dedicated uint8
  509. # packer with pad_byte=0 so padded slots dequantize to 0 and
  510. # can't produce NaN/Inf in the logits kernel.
  511. if q_scale is not None:
  512. padded_q_quant_decode_tokens = pack_seq_triton(
  513. q_quant[:num_decode_tokens], decode_lens, pad_value=0
  514. )
  515. padded_q_scale = pack_seq_triton(
  516. q_scale[:num_decode_tokens], decode_lens, pad_value=0
  517. )
  518. else:
  519. padded_q_quant_decode_tokens = pack_seq_triton(
  520. q_quant[:num_decode_tokens], decode_lens
  521. )
  522. padded_q_scale = None
  523. else:
  524. padded_q_quant_decode_tokens = q_quant[:num_decode_tokens].reshape(
  525. decode_lens.shape[0], -1, *q_quant.shape[1:]
  526. )
  527. if q_scale is not None:
  528. padded_q_scale = q_scale[:num_decode_tokens].reshape(
  529. decode_lens.shape[0], -1, *q_scale.shape[1:]
  530. )
  531. else:
  532. padded_q_scale = None
  533. # TODO: move and optimize below logic with triton kernels
  534. batch_size = padded_q_quant_decode_tokens.shape[0]
  535. next_n = padded_q_quant_decode_tokens.shape[1]
  536. num_padded_tokens = batch_size * next_n
  537. seq_lens = decode_metadata.seq_lens[:batch_size]
  538. # seq_lens is always 2D: (B, next_n) for native spec decode, (B, 1)
  539. # otherwise. deep_gemm fp8_fp4_paged_mqa_logits requires 2D context_lens;
  540. # the downstream topk kernels accept both 1D and 2D.
  541. padded_q_quant_cast = (
  542. padded_q_quant_decode_tokens.view(torch.int8)
  543. if use_fp4_cache
  544. else padded_q_quant_decode_tokens
  545. )
  546. if current_platform.is_xpu():
  547. if padded_q_scale is not None:
  548. raise RuntimeError("XPU fp8_paged_mqa_logits does not support FP4 Q")
  549. seq_lens_xpu = (
  550. seq_lens[:, -1].contiguous() if seq_lens.ndim == 2 else seq_lens
  551. )
  552. logits = torch.ops.vllm.xpu_fp8_paged_mqa_logits(
  553. padded_q_quant_cast,
  554. kv_cache,
  555. weights[:num_padded_tokens],
  556. seq_lens_xpu,
  557. decode_metadata.block_table,
  558. decode_metadata.schedule_metadata,
  559. max_model_len,
  560. )
  561. else:
  562. logits = fp8_fp4_paged_mqa_logits(
  563. (padded_q_quant_cast, padded_q_scale),
  564. kv_cache,
  565. weights[:num_padded_tokens],
  566. seq_lens,
  567. decode_metadata.block_table,
  568. decode_metadata.schedule_metadata,
  569. max_model_len=max_model_len,
  570. clean_logits=False,
  571. indices=decode_metadata.indices,
  572. )
  573. num_rows = logits.shape[0]
  574. topk_indices = topk_indices_buffer[:num_padded_tokens, :topk_tokens]
  575. use_cooperative_topk = (
  576. current_platform.is_cuda()
  577. and topk_tokens in (512, 1024, 2048)
  578. and num_rows <= 64
  579. and logits.stride(0) % 4 == 0 # TMA 16-byte alignment
  580. and current_platform.has_device_capability(90)
  581. and not current_platform.is_device_capability_family(120)
  582. )
  583. use_persistent_topk = current_platform.is_cuda() and topk_tokens in (
  584. 512,
  585. 1024,
  586. 2048,
  587. )
  588. if use_cooperative_topk:
  589. workspace_manager = current_workspace_manager()
  590. (topk_workspace,) = workspace_manager.get_simultaneous(
  591. ((RADIX_TOPK_WORKSPACE_SIZE,), torch.uint8),
  592. )
  593. torch.ops._C.cooperative_topk(
  594. logits,
  595. seq_lens,
  596. topk_indices,
  597. topk_workspace,
  598. topk_tokens,
  599. attn_metadata_narrowed.max_seq_len,
  600. )
  601. elif use_persistent_topk:
  602. workspace_manager = current_workspace_manager()
  603. (topk_workspace,) = workspace_manager.get_simultaneous(
  604. ((RADIX_TOPK_WORKSPACE_SIZE,), torch.uint8),
  605. )
  606. torch.ops._C.persistent_topk(
  607. logits,
  608. seq_lens,
  609. topk_indices,
  610. topk_workspace,
  611. topk_tokens,
  612. logits.shape[1],
  613. )
  614. else:
  615. ops.top_k_per_row_decode(
  616. logits,
  617. next_n,
  618. seq_lens,
  619. topk_indices,
  620. num_rows,
  621. logits.stride(0),
  622. logits.stride(1),
  623. topk_tokens,
  624. )
  625. if decode_metadata.global_seq_lens is not None:
  626. _merge_dcp_topk_global(
  627. logits,
  628. topk_indices,
  629. topk_tokens,
  630. dcp_rank,
  631. dcp_world_size,
  632. cp_kv_cache_interleave_size,
  633. )
  634. if decode_metadata.requires_padding:
  635. # if padded, we need to unpack
  636. # the topk indices removing padded tokens
  637. topk_indices = unpack_seq_triton(
  638. topk_indices.reshape(batch_size, -1, topk_indices.shape[-1]),
  639. decode_lens,
  640. )
  641. topk_indices_buffer[: topk_indices.shape[0], : topk_indices.shape[-1]] = (
  642. topk_indices
  643. )
  644. return topk_indices_buffer
  645. def sparse_attn_indexer_fake(
  646. hidden_states: torch.Tensor,
  647. k_cache_prefix: LayerNameType,
  648. kv_cache: torch.Tensor,
  649. q_quant: torch.Tensor,
  650. q_scale: torch.Tensor | None,
  651. k: torch.Tensor | None,
  652. weights: torch.Tensor,
  653. quant_block_size: int,
  654. scale_fmt: str | None,
  655. topk_tokens: int,
  656. head_dim: int,
  657. max_model_len: int,
  658. total_seq_lens: int,
  659. topk_indices_buffer: torch.Tensor | None,
  660. skip_k_cache_insert: bool,
  661. use_pcp: bool,
  662. dense_mha_metadata_layer_name: LayerNameType,
  663. use_fp4_cache: bool = False,
  664. dcp_rank: int = 0,
  665. dcp_world_size: int = 1,
  666. cp_kv_cache_interleave_size: int = 1,
  667. skip_topk_buffer_clear: bool = False,
  668. ) -> torch.Tensor:
  669. return topk_indices_buffer
  670. direct_register_custom_op(
  671. op_name="sparse_attn_indexer",
  672. op_func=sparse_attn_indexer,
  673. mutates_args=["topk_indices_buffer"],
  674. fake_impl=sparse_attn_indexer_fake,
  675. dispatch_key=current_platform.dispatch_key,
  676. )
  677. @CustomOp.register("sparse_attn_indexer")
  678. class SparseAttnIndexer(CustomOp):
  679. """Sparse Attention Indexer Custom Op Layer. This layer is extracted as a
  680. separate custom op since it involves heavy custom kernels like `mqa_logits`,
  681. `paged_mqa_logits` and `top_k_per_row`, etc. Those kernels maybe requires
  682. specific memory layout or implementation for different hardware backends to
  683. achieve optimal performance.
  684. For now, the default native path will use CUDA backend path. Other platform
  685. may requires add the corresponding Custom Op name `sparse_attn_indexer` to
  686. `custom_ops` in `CompilationConfig` to enable the platform specific path.
  687. """
  688. def __init__(
  689. self,
  690. k_cache,
  691. quant_block_size: int,
  692. scale_fmt: str,
  693. topk_tokens: int,
  694. head_dim: int,
  695. max_model_len: int,
  696. max_total_seq_len: int,
  697. topk_indices_buffer: torch.Tensor,
  698. skip_k_cache_insert: bool = False,
  699. use_fp4_cache: bool = False,
  700. compress_ratio: int = 1,
  701. ):
  702. super().__init__()
  703. self.k_cache = k_cache
  704. self.quant_block_size = quant_block_size
  705. self.scale_fmt = scale_fmt
  706. self.topk_tokens = topk_tokens
  707. self.head_dim = head_dim
  708. self.max_model_len = max_model_len
  709. self.max_total_seq_len = max_total_seq_len
  710. self.topk_indices_buffer = topk_indices_buffer
  711. self.skip_k_cache_insert = skip_k_cache_insert
  712. self.use_fp4_cache = use_fp4_cache
  713. self.compress_ratio = compress_ratio
  714. self.dense_mha_metadata_layer_name = ""
  715. # DCP scalars are constant for the run; resolve them here (config is set
  716. # during model construction) and pass them into the custom op, rather
  717. # than threading them through per-step metadata.
  718. parallel_config = get_current_vllm_config().parallel_config
  719. self._parallel_config = parallel_config
  720. self.dcp_world_size = parallel_config.decode_context_parallel_size
  721. self.dcp_rank = get_dcp_group().rank_in_group if self.dcp_world_size > 1 else 0
  722. self.use_pcp = parallel_config.prefill_context_parallel_size > 1
  723. self._cp_kv_cache_interleave_size: int | None = None
  724. if current_platform.is_cuda() and not has_deep_gemm():
  725. raise RuntimeError(
  726. "Sparse Attention Indexer CUDA op requires DeepGEMM support in "
  727. "the current vLLM environment."
  728. )
  729. @property
  730. def cp_kv_cache_interleave_size(self) -> int:
  731. """With PD+DCP, the real value isn't known until block_size is finalized,
  732. which happens after this layer is built. Safe to cache after the first access,
  733. as long as the adjustment always runs before any forward pass
  734. (it's set up in Worker.initialize_from_config, ahead of warmup/serving).
  735. """
  736. if self._cp_kv_cache_interleave_size is None:
  737. value = self._parallel_config.cp_kv_cache_interleave_size
  738. if isinstance(get_forward_context().attn_metadata, dict):
  739. self._cp_kv_cache_interleave_size = value
  740. return value
  741. return self._cp_kv_cache_interleave_size
  742. def forward_native(
  743. self,
  744. hidden_states: torch.Tensor,
  745. q_quant: torch.Tensor | tuple[torch.Tensor, torch.Tensor],
  746. k: torch.Tensor | None,
  747. weights: torch.Tensor,
  748. ):
  749. if current_platform.is_cuda() or current_platform.is_xpu():
  750. return self.forward_cuda(hidden_states, q_quant, k, weights)
  751. elif current_platform.is_rocm():
  752. return self.forward_hip(hidden_states, q_quant, k, weights)
  753. else:
  754. raise NotImplementedError(
  755. "SparseAttnIndexer native forward is only implemented for "
  756. "CUDA, ROCm and XPU platforms."
  757. )
  758. def forward_cuda(
  759. self,
  760. hidden_states: torch.Tensor,
  761. q_quant: torch.Tensor | tuple[torch.Tensor, torch.Tensor],
  762. k: torch.Tensor | None,
  763. weights: torch.Tensor,
  764. ):
  765. # FP8 path: single tensor (per-token scale is folded into `weights`).
  766. # FP4 path: (values, scales) tuple with scales required by the kernel.
  767. if isinstance(q_quant, tuple):
  768. q_values, q_scale = q_quant
  769. else:
  770. q_values, q_scale = q_quant, None
  771. return torch.ops.vllm.sparse_attn_indexer(
  772. hidden_states,
  773. _encode_layer_name(self.k_cache.prefix),
  774. self.k_cache.kv_cache,
  775. q_values,
  776. q_scale,
  777. k,
  778. weights,
  779. self.quant_block_size,
  780. self.scale_fmt,
  781. self.topk_tokens,
  782. self.head_dim,
  783. self.max_model_len,
  784. self.max_total_seq_len,
  785. self.topk_indices_buffer,
  786. self.skip_k_cache_insert,
  787. self.use_pcp,
  788. _encode_layer_name(self.dense_mha_metadata_layer_name),
  789. self.use_fp4_cache,
  790. self.dcp_rank,
  791. self.dcp_world_size,
  792. self.cp_kv_cache_interleave_size,
  793. )
  794. def forward_xpu(
  795. self,
  796. hidden_states: torch.Tensor,
  797. q_fp8: torch.Tensor,
  798. k: torch.Tensor | None,
  799. weights: torch.Tensor,
  800. ):
  801. return self.forward_cuda(hidden_states, q_fp8, k, weights)
  802. def forward_hip(
  803. self,
  804. hidden_states: torch.Tensor,
  805. q_quant: torch.Tensor | tuple[torch.Tensor, torch.Tensor],
  806. k: torch.Tensor | None,
  807. weights: torch.Tensor,
  808. ):
  809. assert not self.use_fp4_cache, "AMD platform doesn't support fp4 cache yet"
  810. assert isinstance(q_quant, torch.Tensor), (
  811. "AMD sparse_attn_indexer expects a single FP8 q_quant tensor"
  812. )
  813. from vllm.platforms.rocm import on_gfx11
  814. if (
  815. rocm_aiter_ops.is_enabled()
  816. or rocm_aiter_ops.is_rdna_aiter_enabled()
  817. or on_gfx11()
  818. ):
  819. return torch.ops.vllm.rocm_aiter_sparse_attn_indexer(
  820. hidden_states,
  821. _encode_layer_name(self.k_cache.prefix),
  822. self.k_cache.kv_cache,
  823. q_quant,
  824. k,
  825. weights,
  826. self.quant_block_size,
  827. self.scale_fmt,
  828. self.topk_tokens,
  829. self.head_dim,
  830. self.max_model_len,
  831. self.max_total_seq_len,
  832. self.topk_indices_buffer,
  833. skip_k_cache_insert=self.skip_k_cache_insert,
  834. compress_ratio=self.compress_ratio,
  835. )
  836. raise RuntimeError(
  837. "Sparse attention indexer ROCm path is only supported on AITER. "
  838. "Please enable aiter with VLLM_ROCM_USE_AITER=1"
  839. )