sparse_attn_indexer.py 37 KB

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