| 1 | # SPDX-License-Identifier: Apache-2.0 |
| 2 | # SPDX-FileCopyrightText: Copyright contributors to the vLLM project |
| 3 | """XPU DeepSeek-V4 attention subclass. |
| 4 | |
| 5 | Subclasses the shared ``DeepseekV4Attention`` ABC and provides XPU-native |
| 6 | Triton kernels for decode (FP8 dequant + BF16 attention) and prefill |
| 7 | (BF16 gathered KV + sparse attention). |
| 8 | """ |
| 9 | |
| 10 | from typing import TYPE_CHECKING, cast |
| 11 | |
| 12 | import torch |
| 13 | |
| 14 | from vllm.forward_context import get_forward_context |
| 15 | from vllm.models.deepseek_v4.attention import DeepseekV4Attention |
| 16 | from vllm.models.deepseek_v4.common.ops import ( |
| 17 | combine_topk_swa_indices, |
| 18 | compute_global_topk_indices_and_lens, |
| 19 | dequantize_and_gather_k_cache, |
| 20 | ) |
| 21 | from vllm.models.deepseek_v4.sparse_mla import ( |
| 22 | DeepseekV4FlashMLAMetadata, |
| 23 | DeepseekV4SparseMLABackend, |
| 24 | ) |
| 25 | from vllm.models.deepseek_v4.xpu.xpu_sparse_decode_fp8 import ( |
| 26 | xpu_sparse_decode_fp8, |
| 27 | ) |
| 28 | from vllm.v1.attention.ops.xpu_mla_sparse import triton_bf16_mla_sparse_interface |
| 29 | from vllm.v1.worker.workspace import current_workspace_manager |
| 30 | |
| 31 | if TYPE_CHECKING: |
| 32 | from vllm.v1.attention.backends.mla.sparse_swa import DeepseekSparseSWAMetadata |
| 33 | |
| 34 | |
| 35 | class DeepseekV4XPUSparseBackend(DeepseekV4SparseMLABackend): |
| 36 | @staticmethod |
| 37 | def get_name() -> str: |
| 38 | return "XPU_V4_MLA_SPARSE" |
| 39 | |
| 40 | |
| 41 | class DeepseekV4XPUAttention(DeepseekV4Attention): |
| 42 | """XPU sparse MLA attention layer for DeepSeek V4.""" |
| 43 | |
| 44 | backend_cls = DeepseekV4XPUSparseBackend |
| 45 | use_flashmla_fp8_layout = True |
| 46 | |
| 47 | def __init__(self, *args, **kwargs) -> None: |
| 48 | # torch.cuda.Event() raises RuntimeError on XPU ("dummy base class"). |
| 49 | # The Base and DeepseekV4Indexer both create cuda Events in __init__, so |
| 50 | # we temporarily redirect torch.cuda.Event → torch.xpu.Event. |
| 51 | _orig_event = torch.cuda.Event |
| 52 | torch.cuda.Event = torch.xpu.Event # type: ignore[misc] |
| 53 | try: |
| 54 | super().__init__(*args, **kwargs) |
| 55 | finally: |
| 56 | torch.cuda.Event = _orig_event # type: ignore[misc] |
| 57 | |
| 58 | def _fused_qnorm_rope_kv_insert(self, q, kv, positions, attn_metadata): |
| 59 | from typing import cast |
| 60 | |
| 61 | if not isinstance(attn_metadata, dict): |
| 62 | # Profile run: no-op, just return q (no padding needed on XPU). |
| 63 | return q |
| 64 | |
| 65 | swa_metadata = cast( |
| 66 | "DeepseekSparseSWAMetadata | None", |
| 67 | attn_metadata.get(self.swa_cache_layer.prefix), |
| 68 | ) |
| 69 | assert swa_metadata is not None |
| 70 | |
| 71 | from vllm.models.deepseek_v4.xpu.xpu_qnorm_rope_kv_fp8_insert import ( |
| 72 | xpu_qnorm_rope_kv_fp8_insert, |
| 73 | ) |
| 74 | |
| 75 | xpu_qnorm_rope_kv_fp8_insert( |
| 76 | q, |
| 77 | kv, |
| 78 | self.swa_cache_layer.kv_cache, |
| 79 | swa_metadata.slot_mapping, |
| 80 | positions, |
| 81 | self.rotary_emb.cos_sin_cache, |
| 82 | self.eps, |
| 83 | swa_metadata.block_size, |
| 84 | ) |
| 85 | return q |
| 86 | |
| 87 | @classmethod |
| 88 | def get_padded_num_q_heads(cls, num_heads: int) -> int: |
| 89 | return num_heads |
| 90 | |
| 91 | def _o_proj(self, o: torch.Tensor, positions: torch.Tensor) -> torch.Tensor: |
| 92 | from vllm.models.deepseek_v4.common.ops.fused_inv_rope_fp8_quant import ( |
| 93 | fused_inv_rope_fp8_quant, |
| 94 | ) |
| 95 | |
| 96 | o_fp8, o_scale = fused_inv_rope_fp8_quant( |
| 97 | o, |
| 98 | positions, |
| 99 | self.rotary_emb.cos_sin_cache, |
| 100 | n_groups=self.n_local_groups, |
| 101 | heads_per_group=self.n_local_heads // self.n_local_groups, |
| 102 | nope_dim=self.nope_head_dim, |
| 103 | rope_dim=self.rope_head_dim, |
| 104 | tma_aligned_scales=False, |
| 105 | ) |
| 106 | |
| 107 | # Precomputed contiguous [G, K, N] weight and [G, K/bs, N/bs] scale. |
| 108 | wo_a_weight = self.wo_a.bmm_weight |
| 109 | wo_a_scale = self.wo_a.bmm_scale |
| 110 | |
| 111 | # TODO: optimize fused_inv_rope_fp8_quant for xpu bmm to |
| 112 | # eliminate o_scale transpose + contiguous |
| 113 | z = torch.ops.vllm.xpu_fp8_bmm( |
| 114 | o_fp8.transpose(0, 1), |
| 115 | wo_a_weight, |
| 116 | torch.bfloat16, |
| 117 | o_scale.transpose(0, 1).contiguous(), |
| 118 | wo_a_scale, |
| 119 | None, |
| 120 | ) |
| 121 | |
| 122 | return self.wo_b(z.transpose(0, 1).flatten(1)) |
| 123 | |
| 124 | def forward_mqa( |
| 125 | self, |
| 126 | q: torch.Tensor, |
| 127 | kv: torch.Tensor, |
| 128 | positions: torch.Tensor, |
| 129 | output: torch.Tensor, |
| 130 | ) -> None: |
| 131 | assert output.shape == q.shape, ( |
| 132 | f"output buffer shape {output.shape} must match q shape {q.shape}" |
| 133 | ) |
| 134 | assert output.dtype == q.dtype, ( |
| 135 | f"output buffer dtype {output.dtype} must match q dtype {q.dtype}" |
| 136 | ) |
| 137 | |
| 138 | forward_context = get_forward_context() |
| 139 | attn_metadata = forward_context.attn_metadata |
| 140 | |
| 141 | if attn_metadata is None: |
| 142 | # Warmup dummy run: reserve workspace, skip actual kernels. |
| 143 | swa_only = self.compress_ratio <= 1 |
| 144 | N = ( |
| 145 | 0 |
| 146 | if swa_only |
| 147 | else (self.max_model_len + self.compress_ratio - 1) |
| 148 | // self.compress_ratio |
| 149 | ) |
| 150 | M = N + self.window_size + self.max_num_batched_tokens |
| 151 | current_workspace_manager().get_simultaneous( |
| 152 | ((self.PREFILL_CHUNK_SIZE, M, q.shape[-1]), torch.bfloat16), |
| 153 | ) |
| 154 | output.zero_() |
| 155 | return |
| 156 | |
| 157 | assert isinstance(attn_metadata, dict) |
| 158 | flashmla_metadata = cast( |
| 159 | DeepseekV4FlashMLAMetadata | None, attn_metadata.get(self.prefix) |
| 160 | ) |
| 161 | swa_metadata = cast( |
| 162 | "DeepseekSparseSWAMetadata | None", |
| 163 | attn_metadata.get(self.swa_cache_layer.prefix), |
| 164 | ) |
| 165 | assert swa_metadata is not None |
| 166 | |
| 167 | swa_only = self.compress_ratio <= 1 |
| 168 | self_kv_cache = self.kv_cache if not swa_only else None |
| 169 | swa_kv_cache = self.swa_cache_layer.kv_cache |
| 170 | |
| 171 | # Split prefill and decode |
| 172 | num_decodes = swa_metadata.num_decodes |
| 173 | num_prefills = swa_metadata.num_prefills |
| 174 | num_decode_tokens = swa_metadata.num_decode_tokens |
| 175 | |
| 176 | if num_prefills > 0: |
| 177 | self._forward_prefill( |
| 178 | q=q[num_decode_tokens:], |
| 179 | positions=positions[num_decode_tokens:], |
| 180 | compressed_k_cache=self_kv_cache, |
| 181 | swa_k_cache=swa_kv_cache, |
| 182 | output=output[num_decode_tokens:], |
| 183 | attn_metadata=flashmla_metadata, |
| 184 | swa_metadata=swa_metadata, |
| 185 | ) |
| 186 | if num_decodes > 0: |
| 187 | self._forward_decode( |
| 188 | q=q[:num_decode_tokens], |
| 189 | kv_cache=self_kv_cache, |
| 190 | swa_metadata=swa_metadata, |
| 191 | attn_metadata=flashmla_metadata, |
| 192 | swa_only=swa_only, |
| 193 | output=output[:num_decode_tokens], |
| 194 | ) |
| 195 | |
| 196 | def _forward_decode( |
| 197 | self, |
| 198 | q: torch.Tensor, |
| 199 | kv_cache: torch.Tensor | None, |
| 200 | swa_metadata: "DeepseekSparseSWAMetadata", |
| 201 | attn_metadata: DeepseekV4FlashMLAMetadata | None, |
| 202 | swa_only: bool, |
| 203 | output: torch.Tensor, |
| 204 | ) -> None: |
| 205 | num_decodes = swa_metadata.num_decodes |
| 206 | num_decode_tokens = swa_metadata.num_decode_tokens |
| 207 | |
| 208 | topk_indices = None |
| 209 | topk_lens = None |
| 210 | if not swa_only: |
| 211 | assert attn_metadata is not None |
| 212 | assert swa_metadata.is_valid_token is not None |
| 213 | block_size = attn_metadata.block_size // self.compress_ratio |
| 214 | is_valid = swa_metadata.is_valid_token[:num_decode_tokens] |
| 215 | if self.compress_ratio == 4: |
| 216 | # C4A: local indices differ per layer (filled by Indexer). |
| 217 | assert self.topk_indices_buffer is not None |
| 218 | global_indices, topk_lens = compute_global_topk_indices_and_lens( |
| 219 | self.topk_indices_buffer[:num_decode_tokens], |
| 220 | swa_metadata.token_to_req_indices, |
| 221 | attn_metadata.block_table[:num_decodes], |
| 222 | block_size, |
| 223 | is_valid, |
| 224 | ) |
| 225 | topk_indices = global_indices.view(num_decode_tokens, 1, -1) |
| 226 | else: |
| 227 | # C128A: pre-computed during metadata build. |
| 228 | topk_indices = attn_metadata.c128a_global_decode_topk_indices |
| 229 | topk_lens = attn_metadata.c128a_decode_topk_lens |
| 230 | |
| 231 | swa_indices = swa_metadata.decode_swa_indices |
| 232 | swa_lens = swa_metadata.decode_swa_lens |
| 233 | |
| 234 | assert swa_indices is not None and swa_lens is not None |
| 235 | xpu_sparse_decode_fp8( |
| 236 | q=q, |
| 237 | kv_cache=kv_cache, |
| 238 | swa_kv_cache=self.swa_cache_layer.kv_cache, |
| 239 | swa_only=swa_only, |
| 240 | topk_indices=topk_indices, |
| 241 | topk_lens=topk_lens, |
| 242 | swa_indices=swa_indices, |
| 243 | swa_lens=swa_lens, |
| 244 | attn_sink=self.attn_sink, |
| 245 | softmax_scale=self.scale, |
| 246 | head_dim=self.head_dim, |
| 247 | nope_head_dim=self.nope_head_dim, |
| 248 | rope_head_dim=self.rope_head_dim, |
| 249 | out=output, |
| 250 | ) |
| 251 | |
| 252 | def _forward_prefill( |
| 253 | self, |
| 254 | q: torch.Tensor, |
| 255 | positions: torch.Tensor, |
| 256 | compressed_k_cache: torch.Tensor | None, |
| 257 | swa_k_cache: torch.Tensor, |
| 258 | output: torch.Tensor, |
| 259 | attn_metadata: DeepseekV4FlashMLAMetadata | None, |
| 260 | swa_metadata: "DeepseekSparseSWAMetadata", |
| 261 | ) -> None: |
| 262 | swa_only = attn_metadata is None |
| 263 | |
| 264 | num_prefills = swa_metadata.num_prefills |
| 265 | num_prefill_tokens = swa_metadata.num_prefill_tokens |
| 266 | num_decodes = swa_metadata.num_decodes |
| 267 | num_decode_tokens = swa_metadata.num_decode_tokens |
| 268 | |
| 269 | # Use pre-computed prefill metadata. |
| 270 | seq_lens = swa_metadata.prefill_seq_lens |
| 271 | gather_lens = swa_metadata.prefill_gather_lens |
| 272 | assert seq_lens is not None |
| 273 | assert gather_lens is not None |
| 274 | |
| 275 | # Derive prefill-local token offsets from the full query_start_loc_cpu. |
| 276 | query_start_loc_cpu = swa_metadata.query_start_loc_cpu |
| 277 | query_start_loc = swa_metadata.query_start_loc |
| 278 | assert query_start_loc_cpu is not None |
| 279 | assert query_start_loc is not None |
| 280 | prefill_token_base = query_start_loc_cpu[num_decodes] |
| 281 | |
| 282 | if not swa_only: |
| 283 | if self.compress_ratio == 4: |
| 284 | assert self.topk_indices_buffer is not None |
| 285 | topk_indices = self.topk_indices_buffer[num_decode_tokens:] |
| 286 | topk_indices = topk_indices[:num_prefill_tokens] |
| 287 | else: |
| 288 | # C128A: pre-computed during metadata build. |
| 289 | assert attn_metadata is not None |
| 290 | topk_indices = attn_metadata.c128a_prefill_topk_indices |
| 291 | top_k = topk_indices.shape[-1] |
| 292 | N = (self.max_model_len + self.compress_ratio - 1) // self.compress_ratio |
| 293 | else: |
| 294 | assert self.topk_indices_buffer is not None |
| 295 | topk_indices = self.topk_indices_buffer[num_decode_tokens:] |
| 296 | top_k = 0 |
| 297 | N = 0 |
| 298 | |
| 299 | M = N + self.window_size + self.max_num_batched_tokens |
| 300 | chunk_size_const = self.PREFILL_CHUNK_SIZE |
| 301 | num_chunks = (num_prefills + chunk_size_const - 1) // chunk_size_const |
| 302 | |
| 303 | workspace_manager = current_workspace_manager() |
| 304 | kv = workspace_manager.get_simultaneous( |
| 305 | ((chunk_size_const, M, q.shape[-1]), torch.bfloat16), |
| 306 | )[0] |
| 307 | for chunk_idx in range(num_chunks): |
| 308 | chunk_start = chunk_idx * chunk_size_const |
| 309 | chunk_end = min(chunk_start + chunk_size_const, num_prefills) |
| 310 | chunk_size = chunk_end - chunk_start |
| 311 | if not swa_only: |
| 312 | # Gather compressed KV |
| 313 | assert attn_metadata is not None |
| 314 | block_table = attn_metadata.block_table[num_decodes:] |
| 315 | dequantize_and_gather_k_cache( |
| 316 | kv[:chunk_size], |
| 317 | compressed_k_cache, |
| 318 | seq_lens=seq_lens[chunk_start:chunk_end] // self.compress_ratio, |
| 319 | gather_lens=None, |
| 320 | block_table=block_table[chunk_start:chunk_end], |
| 321 | block_size=attn_metadata.block_size // self.compress_ratio, |
| 322 | offset=0, |
| 323 | ) |
| 324 | |
| 325 | # Gather SWA KV |
| 326 | swa_block_table = swa_metadata.block_table[num_decodes:] |
| 327 | dequantize_and_gather_k_cache( |
| 328 | kv[:chunk_size], |
| 329 | swa_k_cache, |
| 330 | seq_lens=seq_lens[chunk_start:chunk_end], |
| 331 | gather_lens=gather_lens[chunk_start:chunk_end], |
| 332 | block_table=swa_block_table[chunk_start:chunk_end], |
| 333 | block_size=swa_metadata.block_size, |
| 334 | offset=N, |
| 335 | ) |
| 336 | |
| 337 | # Combine the topk indices and SWA indices for gathered KV cache |
| 338 | query_start = ( |
| 339 | query_start_loc_cpu[num_decodes + chunk_start] - prefill_token_base |
| 340 | ) |
| 341 | query_end = ( |
| 342 | query_start_loc_cpu[num_decodes + chunk_end] - prefill_token_base |
| 343 | ) |
| 344 | |
| 345 | combined_indices, combined_lens = combine_topk_swa_indices( |
| 346 | topk_indices[query_start:query_end], |
| 347 | query_start_loc[ |
| 348 | num_decodes + chunk_start : num_decodes + chunk_end + 1 |
| 349 | ], |
| 350 | seq_lens[chunk_start:chunk_end], |
| 351 | gather_lens[chunk_start:chunk_end], |
| 352 | self.window_size, |
| 353 | self.compress_ratio, |
| 354 | top_k, |
| 355 | M, |
| 356 | N, |
| 357 | ) |
| 358 | |
| 359 | kv_ws = kv[:chunk_size].reshape(-1, 1, q.shape[-1]) |
| 360 | out, _, _ = triton_bf16_mla_sparse_interface( |
| 361 | q=q[query_start:query_end], |
| 362 | kv=kv_ws, |
| 363 | indices=combined_indices.unsqueeze(1), |
| 364 | sm_scale=self.scale, |
| 365 | d_v=q.shape[-1], |
| 366 | block_dpe=0, |
| 367 | ) |
| 368 | output[query_start:query_end] = out |