Skip to content

Commit 39ecc20

Browse files
authored
feat: add DeepSeek Sparse Attention kernels for sm89 (ada) (#1684)
* feat: add DeepSeek Sparse Attention kernels for sm89 (ada) * chore: perf tuning * fix: remove dead code * feat: enable DCP for sm89 DSA * chore: optimize DCP * chore: more warmup shapes and JIT optimizations * chore: cleanup the comments
1 parent 0f3fefe commit 39ecc20

37 files changed

Lines changed: 3971 additions & 83 deletions

File tree

‎CMakeLists.txt‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -547,6 +547,23 @@ if(APHRODITE_GPU_LANG STREQUAL "CUDA" OR APHRODITE_GPU_LANG STREQUAL "HIP")
547547
CUDA_ARCHS "${COOPERATIVE_TOPK_ARCHS}")
548548
endif()
549549

550+
# sm89 DeepSeek sparse attention (DSA) kernels; fp8 e4m3 mma codegen for
551+
# sm_89 requires CUDA 12.4+.
552+
if(${CMAKE_CUDA_COMPILER_VERSION} VERSION_GREATER_EQUAL 12.4)
553+
cuda_archs_loose_intersection(DSA_SM89_ARCHS "8.9+PTX" "${CUDA_ARCHS}")
554+
endif()
555+
if(DSA_SM89_ARCHS)
556+
set(SM89_DSA_SRC
557+
"csrc/libtorch_stable/attention/sm89_dsa/sm89_fp8_paged_mqa_logits.cu"
558+
"csrc/libtorch_stable/attention/sm89_dsa/sm89_fp8_mqa_logits.cu"
559+
"csrc/libtorch_stable/attention/sm89_dsa/sm89_sparse_mla_fwd.cu")
560+
list(APPEND APHRODITE_STABLE_EXT_SRC ${SM89_DSA_SRC})
561+
set_gencode_flags_for_srcs(
562+
SRCS "${SM89_DSA_SRC}"
563+
CUDA_ARCHS "${DSA_SM89_ARCHS}")
564+
message(STATUS "Building sm89 DSA kernels for archs: ${DSA_SM89_ARCHS}")
565+
endif()
566+
550567
# Only build Marlin kernels if we are building for at least some compatible archs.
551568
# Keep building Marlin for 9.0 as there are some group sizes and shapes that
552569
# are not supported by Machete yet.
@@ -1164,6 +1181,10 @@ if(APHRODITE_GPU_LANG STREQUAL "CUDA" OR APHRODITE_GPU_LANG STREQUAL "HIP")
11641181
target_compile_definitions(_C_stable_libtorch PRIVATE
11651182
APHRODITE_ENABLE_COOPERATIVE_TOPK=1)
11661183
endif()
1184+
if(DSA_SM89_ARCHS)
1185+
target_compile_definitions(_C_stable_libtorch PRIVATE
1186+
APHRODITE_ENABLE_SM89_DSA=1)
1187+
endif()
11671188
# Needed by CUTLASS kernels
11681189
target_compile_definitions(_C_stable_libtorch PRIVATE
11691190
CUTLASS_ENABLE_DIRECT_CUDA_DRIVER_CALL=1)

‎aphrodite/_custom_ops.py‎

Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
33

44
from enum import IntEnum
5+
from functools import cache
56
from typing import TYPE_CHECKING, Literal
67

78
import torch
@@ -3057,6 +3058,83 @@ def top_k_per_row_decode(
30573058
)
30583059

30593060

3061+
@cache
3062+
def supports_sm89_dsa() -> bool:
3063+
"""Whether the sm89 DeepSeek sparse attention ops were compiled into _C."""
3064+
return hasattr(torch.ops._C, "sm89_sparse_mla_fwd")
3065+
3066+
3067+
def sm89_fp8_paged_mqa_logits(
3068+
q: torch.Tensor,
3069+
kv_cache_pool: torch.Tensor,
3070+
weights: torch.Tensor,
3071+
seq_lens: torch.Tensor,
3072+
block_table: torch.Tensor,
3073+
sched: torch.Tensor,
3074+
logits: torch.Tensor,
3075+
clean_logits: bool,
3076+
) -> None:
3077+
"""Paged fp8 MQA indexer logits for decode on sm89 (block size 64).
3078+
3079+
q is [B, next_n, 64, 128] fp8 e4m3 viewed as uint8; kv_cache_pool [pool_pages, 8448]
3080+
uint8 (per page, 8192B fp8 keys + 256B fp32 per-token scales); weights [B*next_n, 64]
3081+
fp32; sched [(P+1), 2] int32 built by sm89_paged_mqa_logits_metadata; logits
3082+
[B*next_n, max_model_len] fp32, written for columns [0, seq_len) per row. With
3083+
clean_logits, the tail columns of each row's last partial page are set to -inf.
3084+
"""
3085+
torch.ops._C.sm89_fp8_paged_mqa_logits(
3086+
q, kv_cache_pool, weights, seq_lens, block_table, sched, logits, clean_logits
3087+
)
3088+
3089+
3090+
def sm89_paged_mqa_logits_metadata(seq_lens: torch.Tensor, sched: torch.Tensor, next_n: int) -> None:
3091+
"""Build the [(P+1), 2] int32 (request, page) partition table for sm89_fp8_paged_mqa_logits."""
3092+
torch.ops._C.sm89_paged_mqa_logits_metadata(seq_lens, sched, next_n)
3093+
3094+
3095+
def sm89_fp8_mqa_logits(
3096+
q: torch.Tensor,
3097+
kv: torch.Tensor,
3098+
kv_scales: torch.Tensor,
3099+
weights: torch.Tensor,
3100+
cu_seqlen_ks: torch.Tensor,
3101+
cu_seqlen_ke: torch.Tensor,
3102+
logits: torch.Tensor,
3103+
) -> None:
3104+
"""Prefill/ragged fp8 MQA indexer logits on sm89 over a contiguous gathered kv buffer.
3105+
3106+
q is [M, 64, 128] fp8 e4m3 viewed as uint8; kv [N, 128] fp8 e4m3 viewed as uint8;
3107+
kv_scales [N] fp32; weights [M, 64] fp32; cu_seqlen_ks/cu_seqlen_ke [M] int32
3108+
per-row key windows (clamped to [0, N]); logits [M, N] fp32, written only in the
3109+
[ks, ke) window of each row (the caller owns the fill value outside the window).
3110+
"""
3111+
torch.ops._C.sm89_fp8_mqa_logits(q, kv, kv_scales, weights, cu_seqlen_ks, cu_seqlen_ke, logits)
3112+
3113+
3114+
def sm89_sparse_mla_fwd(
3115+
q: torch.Tensor,
3116+
kv_cache_pool: torch.Tensor,
3117+
indices: torch.Tensor,
3118+
out: torch.Tensor,
3119+
lse: torch.Tensor,
3120+
sm_scale: float,
3121+
topk_lens: torch.Tensor | None = None,
3122+
) -> None:
3123+
"""Sparse MLA forward on sm89, gathering directly from an fp8_ds_mla pool by slot.
3124+
3125+
q is [T, h, 576] bf16; kv_cache_pool [S, 656] uint8 (fp8_ds_mla rows); indices
3126+
[T, topk] int32 physical slots, -1 padded; out [T, h, 512] bf16; lse [T, h] fp32.
3127+
Rows whose indices are all -1 produce zero output and -inf LSE.
3128+
3129+
topk_lens is an optional [T] int32 of per-token valid counts. It requires index
3130+
rows to be front-compacted (valid slots first, then -1); the kernel then stops
3131+
after the last valid slot instead of scanning all topk columns, with output
3132+
identical to topk_lens=None. DCP passes its per-rank counts here
3133+
(~topk/dcp_world_size valid).
3134+
"""
3135+
torch.ops._C.sm89_sparse_mla_fwd(q, kv_cache_pool, indices, out, lse, sm_scale, topk_lens)
3136+
3137+
30603138
def cp_gather_indexer_k_quant_cache(
30613139
kv_cache: torch.Tensor,
30623140
dst_k: torch.Tensor,

‎aphrodite/envs.py‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -267,6 +267,7 @@
267267
APHRODITE_WEIGHT_OFFLOADING_DISABLE_UVA: bool = False
268268
APHRODITE_WSL2_ENABLE_PIN_MEMORY: bool = False
269269
APHRODITE_DISABLE_LOG_LOGO: bool = False
270+
APHRODITE_DISABLE_SM89_DSA: bool = False
270271
APHRODITE_LORA_DISABLE_PDL: bool = False
271272
APHRODITE_ENABLE_CUDA_COMPATIBILITY: bool = False
272273
APHRODITE_CUDA_COMPATIBILITY_PATH: str | None = None
@@ -1890,6 +1891,10 @@ def _resolve_rust_frontend_path() -> str | None:
18901891
),
18911892
# Disable logging of Aphrodite logo at server startup time.
18921893
"APHRODITE_DISABLE_LOG_LOGO": lambda: bool(int(os.getenv("APHRODITE_DISABLE_LOG_LOGO", "0"))),
1894+
# Kill switch for the sm89 (Ada, e.g. RTX 4090) DeepSeek sparse attention
1895+
# kernels. Skips the SM89_MLA_SPARSE backend and the sm89 indexer logits
1896+
# paths even if the kernels are compiled in.
1897+
"APHRODITE_DISABLE_SM89_DSA": lambda: bool(int(os.getenv("APHRODITE_DISABLE_SM89_DSA", "0"))),
18931898
# Disable PDL for LoRA, as enabling PDL with LoRA on SM100 causes
18941899
# Triton compilation to fail.
18951900
"APHRODITE_LORA_DISABLE_PDL": lambda: bool(int(os.getenv("APHRODITE_LORA_DISABLE_PDL", "0"))),

‎aphrodite/model_executor/kernels/attention/dsa/dcp_indexer_cutedsl.py‎

Lines changed: 23 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -66,19 +66,34 @@ def pack_dcp_topk_candidates_cutedsl(
6666
)
6767

6868

69-
@triton.jit
69+
# Strides and num_cols are runtime scalars excluded from specialization.
70+
# logits_stride0 is the gathered-K row length, which varies with every batch's
71+
# prompt/context length, so folding it into the compile key (constexpr or
72+
# divisibility specialization) would re-JIT this kernel per prefill shape.
73+
@triton.jit(
74+
do_not_specialize=[
75+
"logits_stride0",
76+
"logits_stride1",
77+
"topk_stride0",
78+
"topk_stride1",
79+
"packed_stride0",
80+
"packed_stride1",
81+
"packed_stride2",
82+
"num_cols",
83+
]
84+
)
7085
def _pack_dcp_topk_candidates_triton_kernel(
7186
logits,
7287
topk_indices,
7388
packed,
7489
row_starts,
75-
logits_stride0: tl.constexpr,
76-
logits_stride1: tl.constexpr,
77-
topk_stride0: tl.constexpr,
78-
topk_stride1: tl.constexpr,
79-
packed_stride0: tl.constexpr,
80-
packed_stride1: tl.constexpr,
81-
packed_stride2: tl.constexpr,
90+
logits_stride0,
91+
logits_stride1,
92+
topk_stride0,
93+
topk_stride1,
94+
packed_stride0,
95+
packed_stride1,
96+
packed_stride2,
8297
num_cols,
8398
DCP_RANK: tl.constexpr,
8499
DCP_WORLD_SIZE: tl.constexpr,

‎aphrodite/model_executor/layers/attention/mla_attention.py‎

Lines changed: 87 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -202,9 +202,9 @@
202202
from aphrodite._aiter_ops import rocm_aiter_ops
203203
from aphrodite.compilation.breakable_cudagraph import eager_break_during_capture
204204
from aphrodite.config import (
205+
AphroditeConfig,
205206
CacheConfig,
206207
ModelConfig,
207-
AphroditeConfig,
208208
get_current_aphrodite_config,
209209
get_current_aphrodite_config_or_none,
210210
)
@@ -325,7 +325,7 @@ def _canonicalize_sparse_mla_kv_cache_dtype(
325325
kv_cache_dtype: CacheDType,
326326
) -> CacheDType:
327327
backend_name = attn_backend.get_name()
328-
if backend_name == "FLASHMLA_SPARSE" and is_quantized_kv_cache(kv_cache_dtype):
328+
if backend_name in ("FLASHMLA_SPARSE", "SM89_MLA_SPARSE") and is_quantized_kv_cache(kv_cache_dtype):
329329
return "fp8_ds_mla"
330330
if backend_name == "FLASHINFER_MLA_SPARSE_SM120" and kv_cache_dtype in (
331331
"auto",
@@ -696,6 +696,24 @@ def forward_impl(
696696
# Sparse MLA impls only support forward_mqa (decode-style attention)
697697
is_sparse_impl = isinstance(self.impl, SparseMLAAttentionImpl)
698698

699+
# sm89 sparse local-prefill under DCP. When every prefill request is a
700+
# fresh prompt, its full KV is computable on-rank from the replicated
701+
# activations, so prefill tokens attend locally (no q all-gather, no
702+
# LSE combine) and only decode tokens take the DCP path. The metadata
703+
# builder sets prefill_local only for Sm89MLASparseImpl batches that
704+
# qualify; other impls/metadata lack the attribute.
705+
sparse_dcp_local_prefill = (
706+
is_sparse_impl
707+
and self.impl.dcp_world_size > 1
708+
and getattr(attn_metadata, "prefill_local", None) is not None
709+
)
710+
if sparse_dcp_local_prefill:
711+
# Build the per-forward shadow pool of this batch's fresh prompt
712+
# KV before the attention kernels below consume it.
713+
self.impl.build_local_prefill_pool( # type: ignore[attr-defined]
714+
k_c_normed, k_pe, attn_metadata, self._k_scale
715+
)
716+
699717
if is_sparse_impl:
700718
num_mqa_tokens = q.size(0)
701719
num_mha_tokens = 0
@@ -799,37 +817,85 @@ def forward_impl(
799817
)
800818
else:
801819
mqa_q = (mqa_ql_nope, mqa_q_pe)
820+
mqa_prefill_q: torch.Tensor | None = None
802821
if self.impl.dcp_world_size > 1:
803822
if isinstance(mqa_q, tuple):
804823
# concatenate mqa_ql_nope and mqa_q_pe -> (B, N, L + P)
805824
mqa_q = torch.cat(mqa_q, dim=-1)
806-
# mqa_q do allgather in head dim.
807-
mqa_q = get_dcp_group().all_gather(mqa_q, dim=1)
825+
if sparse_dcp_local_prefill:
826+
# Peel off the fresh-prompt prefill tokens (batch tail,
827+
# after the decode tokens) before the all-gather; they
828+
# attend locally with this rank's heads only. The gate is
829+
# batch-uniform across DCP ranks, so collective
830+
# participation stays aligned.
831+
num_dcp_decode_tokens = attn_metadata.num_decode_tokens
832+
mqa_prefill_q = mqa_q[num_dcp_decode_tokens:]
833+
mqa_q = mqa_q[:num_dcp_decode_tokens]
834+
if num_dcp_decode_tokens > 0:
835+
mqa_q = get_dcp_group().all_gather(mqa_q, dim=1)
836+
else:
837+
# all-gather q along the head dim
838+
mqa_q = get_dcp_group().all_gather(mqa_q, dim=1)
808839

809840
# call decode attn
810841
if not is_sparse_impl:
811842
assert attn_metadata.decode is not None
812-
attn_out, lse = self.impl.forward_mqa(mqa_q, kv_cache, attn_metadata, self) # type: ignore[attr-defined]
813843

814-
# correct dcp attn_out with lse.
815-
if self.impl.dcp_world_size > 1:
816-
if self.dcp_a2a:
817-
attn_out = dcp_a2a_lse_reduce(
818-
attn_out,
819-
lse,
820-
get_dcp_group(),
821-
is_lse_base_on_e=self.impl.lse_base_on_e,
844+
if sparse_dcp_local_prefill:
845+
assert mqa_prefill_q is not None
846+
num_dcp_decode_tokens = attn_metadata.num_decode_tokens
847+
if num_dcp_decode_tokens > 0:
848+
# Decode tokens keep the normal DCP path, all-gathered
849+
# heads on the local KV shard then cross-rank LSE combine.
850+
attn_out, lse = self.impl.forward_mqa( # type: ignore[attr-defined]
851+
mqa_q, kv_cache, attn_metadata, self
822852
)
823-
else:
824-
attn_out = cp_lse_ag_out_rs(
825-
attn_out,
826-
lse,
827-
get_dcp_group(),
828-
is_lse_base_on_e=self.impl.lse_base_on_e,
853+
if self.dcp_a2a:
854+
attn_out = dcp_a2a_lse_reduce(
855+
attn_out,
856+
lse,
857+
get_dcp_group(),
858+
is_lse_base_on_e=self.impl.lse_base_on_e,
859+
)
860+
else:
861+
attn_out = cp_lse_ag_out_rs(
862+
attn_out,
863+
lse,
864+
get_dcp_group(),
865+
is_lse_base_on_e=self.impl.lse_base_on_e,
866+
)
867+
self._v_up_proj(
868+
attn_out, out=mqa_output_slice[:num_dcp_decode_tokens]
869+
)
870+
if mqa_prefill_q.shape[0] > 0:
871+
prefill_attn_out = self.impl.forward_mqa_local_prefill( # type: ignore[attr-defined]
872+
mqa_prefill_q, attn_metadata
873+
)
874+
self._v_up_proj(
875+
prefill_attn_out,
876+
out=mqa_output_slice[num_dcp_decode_tokens:],
829877
)
878+
else:
879+
attn_out, lse = self.impl.forward_mqa(mqa_q, kv_cache, attn_metadata, self) # type: ignore[attr-defined]
880+
881+
# correct dcp attn_out with lse.
882+
if self.impl.dcp_world_size > 1:
883+
if self.dcp_a2a:
884+
attn_out = dcp_a2a_lse_reduce(
885+
attn_out,
886+
lse,
887+
get_dcp_group(),
888+
is_lse_base_on_e=self.impl.lse_base_on_e,
889+
)
890+
else:
891+
attn_out = cp_lse_ag_out_rs(
892+
attn_out,
893+
lse,
894+
get_dcp_group(),
895+
is_lse_base_on_e=self.impl.lse_base_on_e,
896+
)
830897

831-
# v_up projection
832-
self._v_up_proj(attn_out, out=mqa_output_slice)
898+
self._v_up_proj(attn_out, out=mqa_output_slice)
833899

834900
if quant_key is not None:
835901
quant_idx = num_mqa_tokens if mha_use_quant_output else num_actual_toks

0 commit comments

Comments
 (0)