Repository navigation
[ROCm] Use the AITER sparse-MLA kernel for DSA prefill and decode - #33022
Closed
EricKing626 wants to merge 17 commits into
Closed
EricKing626 wants to merge 17 commits into
EricKing626 wants to merge 17 commits into
Conversation
EricKing626
requested review from
BBuf,
DarkSharpness,
Fridge003,
HaiShaw,
HydraQYH,
Qiaolin-Yu,
celve,
ch-wan,
fzyzcjy,
hebiao064,
ispobock,
merrymercy and
yuan-luo
as code owners
July 31, 2026 06:11
Contributor
|
Caution The consumer version of Gemini Code Assist on GitHub has been sunset. All code review activity has officially ceased. |
Ports ATOM's calling convention for aiter's persistent sparse MLA decode
pair (mla_a8w8_qh16_qseqlen1_gqaratio16_ps + kn_mla_reduce_v1_ps) into
sglang/kernels as a self-contained module.
The existing dsa_backend _forward_aiter path was dead code on ROCm (the
default forces tilelang) and diverges from the only known-good caller in
three ways that are silently wrong:
- it builds metadata with fast_mode=False + intra_batch_mode=True, which
selects get_mla_metadata_v1_0_device -- the one variant that ignores
topk, so a sparse batch is planned as if it were dense;
- it hands get_mla_metadata_v1 a full-capacity kv_indptr instead of a
[: bs + 1] view, and aiter derives its batch count from that length,
emitting work items for stale slots whose qo_start runs past Q and O
(illegal KV-cache access during CUDA graph capture);
- it allocates the output in Q dtype, but aiter's reduce kernels only
instantiate out_t for bf16/fp16 and hard-fail on fp8.
This module encodes the correct constants as a matched set, allocates the
persistent work buffers once, and exposes a build step meant to run once
per forward batch rather than once per attention layer.
No behaviour change yet: nothing imports it.
The aiter DSA decode path rebuilt aiter's persistent work plan inside _forward_aiter, i.e. once per attention layer, even though the plan depends only on the batch's sparse KV layout, which every layer shares. On a 90+ layer model that is ~5 redundant kernel launches per layer per decode step and it made the aiter path measurably slower than tilelang. The plan is now built once per forward batch, in the three places that own batch shape: the eager metadata path, CUDA graph capture, and both CUDA graph replay paths. All of them run outside the captured region, and replay writes into the same buffers the graph captured rather than reallocating. _forward_aiter keeps only the work that is genuinely per-layer: gathering this layer's top-k KV slots. The per-request *lengths* of that selection are layer-invariant and already available as dsa_cu_seqlens_k (seq_lens clamped to index_topk, cumulatively summed), so the mask/sum/cumsum that rederived them per layer is gone too. Routing the call through sglang.kernels.ops.attention.dsa.aiter_sparse_mla also picks up three corrections it encodes: the metadata kernel variant that honors topk, a [: bs + 1] indptr view so aiter derives the right batch count, and a bf16 output buffer that aiter's reduce kernels can actually instantiate.
… path aiter's asm_mla.cu rejects an fp8 Q tensor unless both q_scale and kv_scale are supplied. Both are a constant 1.0 here, because the fused rope/cache path quantizes Q and KV against a unit scale rather than a per-tensor one. _forward_aiter built those two scalars with torch.ones() on every call, so a 78-layer decode step issued 156 FillFunctor<float> launches that all wrote the same value into freshly allocated memory. Profiling an 8192/1024 concurrency-64 run on MI355X (TP4) attributed 0.62 ms per decode iteration to that kernel -- more than the 0.50 ms the aiter kernel pair saves over the TileLang path it replaces, which is why enabling --dsa-decode-backend aiter measured flat (median ITL 25.94 ms tilelang vs 25.96 ms aiter) despite the attention category itself dropping from 3.44 to 2.94 ms per iteration. Allocate one unit scalar alongside the sparse-MLA work buffers in __init__ and point both arguments at it. The tensor is read-only for the kernel and is created outside any CUDA graph capture, so its address is stable across replay.
Decode was moved onto the AITER persistent sparse-MLA kernel earlier; prefill was still on TileLang. _forward_aiter_extend already existed but had never been reached, and it repeated every mistake the decode path had: - It planned the work buffers once per layer. get_mla_metadata_v1 is batch-shaped, not layer-shaped, so 78 decoder layers meant 78 identical planning calls per prefill chunk. The plan is now built on the first attention layer of a batch and reused for the rest, invalidated by a per-batch serial counter. - It used the planner variant that ignores topk. fast_mode=False with intra_batch_mode=True dispatches to v1_0_device, which discards the top-k selection -- the whole point of the call for sparse attention. It now goes through build_sparse_mla_decode_metadata (fast_mode=True). - It rebuilt the index bookkeeping every layer: an arange, a mask, a sum, a cumsum and a fresh torch.zeros(num_tokens * topk) allocation, all to recompute values the batch metadata already holds. It now reads dsa_cu_seqlens_k / dsa_cu_seqlens_q directly and reuses one persistent index buffer that grows by powers of two. - It passed kv_scale without q_scale and allocated the output in Q's dtype. asm_mla.cu rejects fp8 Q unless both scales are given, and the AITER reduce kernels only instantiate bf16 and fp16 outputs, so an fp8 output buffer is an immediate hard failure. Both scales now come from the identity tensor allocated in __init__, and the output dtype comes from aiter_sparse_mla_out_dtype(). AITER has no separate sparse prefill kernel: prefill is a wide decode, feeding the chunk to mla_decode_fwd as num_tokens length-1 sequences with max_seqlen_q=1. mla_prefill_fwd takes no scales or work buffers and is only the bf16-KV fallback. So the decode helper module is reused as-is; the only structural difference is that the batch dimension counts tokens rather than requests, which is why the buffers are sized lazily from the chunk. Behaviour is unchanged unless requested: the new code lives entirely in the dsa_impl == "aiter" branch of forward_extend, the new buffers are allocated only when a DSA backend is "aiter" and the KV cache is fp8, and the ROCm default remains prefill=tilelang, decode=tilelang. The only line every backend now executes is a Python integer increment per forward batch. Run with --dsa-prefill-backend aiter --dsa-decode-backend aiter. Not yet benchmarked.
…ackend Passing only one of --dsa-prefill-backend / --dsa-decode-backend on ROCm kills the server at the first prefill with ImportError: flashmla_ops. The ROCm default in arg_groups/overrides.py applies tilelang to both roles only when neither flag was set. Set one and the other falls through to the generic fp8 branch, which picks trtllm on Blackwell and flashmla_kv on everything else; gfx950 reports device capability major 9, so ROCm gets flashmla_kv -- a backend that cannot exist there. Nothing in that resolution path can select a ROCm-capable backend, so a CUDA-only value arriving at the backend on ROCm is always the fall-through and never a real user choice. Coerce it to tilelang with a warning that names the cause, turning the crash into the documented default. Fixing it here rather than in overrides.py keeps the repair next to the code that knows which backends have a ROCm implementation.
On gfx95 the fused_qk_rope_cat_and_cache_mla path writes Q in the KV cache dtype, so folding rope into it is what makes Q fp8. The gate deciding that was a literal string test against "tilelang", which meant a server started with both DSA backends set to aiter silently kept Q in bf16. aiter selects its assembly kernel on the (Q, KV) dtype pair, so bf16 Q downgrades it from mla_a8w8_* to mla_a16w8_*. Measured on GLM-5.2 / MI355X, TP4, 8192 in / 1024 out, concurrency 64, prefill=aiter decode=aiter: decode attention mla_a8w8 1.83 ms -> mla_a16w8 4.20 ms per iteration prefill attention 320 ms (tilelang) -> 605 ms per window decode GPU busy 26.24 -> 29.33 ms per iteration prefill GPU busy 728.65 -> 1031.56 ms per window TTFT 13.64 -> 19.10 s TPOT 37.53 -> 45.99 ms Skipping the fused kernel also costs its other savings: one CatArrayBatchedCopy and one indirect cache write reappear per layer per step, both visible in the trace. The gate is really a list of backends whose kernels want fp8 Q, so make it one -- a named frozenset -- and put aiter on it. Rename the predicate and its local to _skip_rope_for_dsa_fp8_q_fused: it never had anything to do with tilelang specifically, and the old name is what made the omission easy to miss.
The aiter sparse-MLA kernel evaluates
logits = (Q_fp8 . KV_fp8) * q_scale * kv_scale
so the scales it is handed must be the ones the operands were quantized
with. Both are quantized against layer.k_scale: KV on cache write, and Q
inside fused_qk_rope_cat_and_cache_mla, which forward_mla.py calls with
self.attn_mqa.k_scale. The decode and extend paths were instead passing a
hardcoded 1.0 for both arguments.
That is correct only when k_scale == 1.0, which is what a checkpoint
without calibrated KV scales gets (see quantization/kv_cache.py). On a
checkpoint that does ship KV scales, every attention logit would have
been off by a factor of k_scale ** 2 -- no error and no warning, just
wrong attention weights.
Resolve the descale from layer.k_scale instead, cached per layer so the
hot path neither allocates nor synchronizes, and fall back to the
preallocated unit scalar when the layer has no scale. A per-tensor scale
is required; a layer carrying more than one element now raises with a
pointer at the tilelang backend rather than silently mis-scaling.
No performance change: the kernel already took both arguments, this only
changes which tensor they point at, and on an uncalibrated checkpoint the
numerical path is bit-identical.
Signed-off-by: Eric.Chin.AMD <[email protected]>
EricKing626
force-pushed
the
aiter_mla_gml52_add_prefill
branch
from
August 4, 2026 20:40
a5a68e3 to
0034a38
Compare
black joins the `.detach().to(...).reshape(())` chain because the result is exactly 88 characters, the configured line length. No behaviour change.
_build_aiter_sparse_mla_metadata() reads self.aiter_sparse_mla_metadata, which is only ever assigned inside the `if _is_hip:` branch of __init__. Four call sites in the shared metadata paths -- init_forward_metadata, CUDA graph capture, and both replay paths -- invoked it unconditionally, so on CUDA the method's own None-guard raised AttributeError and DSA metadata construction died on the first forward. test/registered/attention/unittests/dsa/test_dsa.py failed at startup on NVIDIA runners. Gate all four call sites on _is_hip so the planning step stays where the rest of the aiter state lives, and CUDA keeps aiter_sparse_mla=None.
This was referenced Aug 6, 2026
forward_absorb_rocm_core hands forward_extend a Q that
fused_qk_rope_cat_and_cache_mla already wrote as one contiguous
[num_tokens, num_heads, kv_lora_rank + qk_rope_head_dim] tensor, split into
two slice views (q_nope, q_rope) because most prefill kernels consume nope
and rope separately. The aiter branch needs the joined form back, and was
rebuilding it with torch.cat -- reassembling bytes that were already
adjacent, in order, and in the right dtype.
That copy is paid per attention layer, per prefill chunk:
- one full Q-sized allocation out of the caching allocator,
- one CatArrayBatchedCopy launch,
- 2x read + 1x write of Q through HBM,
none of which changes a single byte. Across 78 decoder layers it is the
dominant non-kernel cost of the aiter prefill path. In the profile window
used for the numbers below, CatArrayBatchedCopy accounted for 354.2 ms;
after this change it does not appear in the trace at all.
_join_split_q_as_view proves the two halves really are one tensor before
handing back a view, and returns None otherwise so torch.cat remains the
fallback: same storage, identical strides, unit stride in the last dim, a
row stride equal to the joined width, and q_rope starting exactly one
q_nope-width past q_nope. Independent tensors, padding or interleaved data
between the halves, or a mismatched dtype/device all take the copy. The
view that is returned has exactly the layout torch.cat would have produced,
so the kernel sees no change.
Measured on GLM-5.2-MXFP4 / MI355X, TP4, fp8_e4m3 KV, chunked-prefill
16384, --dsa-prefill-backend aiter --dsa-decode-backend aiter,
concurrency 64:
before after delta
Benchmark duration 219.87 s 210.19 s -4.4%
Total token throughput 12131 tok/s 12690 tok/s +4.6%
Token throughput / GPU 3033 tok/s 3172 tok/s +4.6%
Median TPOT 46.06 ms 43.93 ms -4.6%
Median TTFT 535.15 ms 505.60 ms -5.5%
Median E2E 42906 ms 41006 ms -4.4%
EXTEND GPU busy / TP 2743.6 ms 2651.4 ms -3.4%
The 354.2 ms of removed copy is larger than the 92.2 ms drop in EXTEND GPU
busy: part of the copy overlapped other work, and the HBM bandwidth it
freed is partly re-absorbed by the kernels around it. The end-to-end 4.4%
is the number to trust.
Decode is untouched. Its branch already receives a joined q_all from the
fused path and only falls back to torch.cat when q_all is None or the
platform is not HIP.
Signed-off-by: Eric.Chin.AMD <[email protected]>
… top-k GLM-5.2 recomputes the indexer top-k roughly every fourth attention layer (index_topk_freq=4): 21 of its 78 layers compute a table, the other 57 are handed the very same tensor back. The aiter sparse-MLA path nevertheless compacted that table -- stripping the -1 padding into the gap-free layout the kernel reads -- once per layer, rebuilding a byte-identical buffer three times out of four. The compaction is a pure function of the top-k table, so record which table the buffer currently describes and skip the launch when it has not changed. A recomputed top-k always arrives in a freshly allocated tensor and nothing writes into it afterwards, so comparing by object identity is exact; holding a reference to the table is what keeps it exact, since a bare data_ptr could match a different table after the allocator recycles a freed one. num_tokens and dsa_forward_serial cover the remaining inputs, sparse_kv_indptr being batch-scoped rather than per layer. This is safe under CUDA-graph capture: which layers share a table follows from layer_id and the model config alone, so the launches recorded at capture stay correct for every replay. Applies to both the decode and the extend path, each with its own slot.
The aiter sparse-MLA decode path reads the top-k slots without the -1 padding, a layout the padded table does not provide, so it launched a compaction kernel to build it. Even after that launch is shared across the layers that reuse one top-k table, GLM-5.2 still pays 21 of them per decode step for roughly 4us of work each -- almost pure launch overhead, so the only way to remove it is to stop launching. The decode top-k transform already holds every slot it would copy in registers at the point it writes the padded table. Give it an optional second output and it emits the gap-free list for two extra stores, and the compaction launch disappears entirely. The buffers are the ones the consumer was going to fill anyway (kv_indices, indexed by dsa_cu_seqlens_k), so this adds no allocation. Both new kernel arguments default to None and nothing outside the ROCm aiter decode path passes them, so every other caller and every other platform keeps its current behaviour bit for bit. Offered only for a one-row-per-request decode launch: the prefill and verify transforms fold several query rows onto one source row, which a per-row indptr cannot describe, and the kernel rejects them outright. Whether the offer was taken is reported back on the request object rather than predicted from the dispatch conditions, so a dispatch change degrades to the explicit gather instead of leaving the consumer on a stale buffer. A plain Python flag is enough under CUDA-graph capture: whichever branch ran at capture is the branch whose launches replay. Measured on GLM-5.2 MXFP4, MI355X TP4, 320 requests at concurrency 64: build output tput TTFT p50 TPOT p50 E2E p50 layer-shared compaction 12690.00 505.60 ms 43.93 ms 41006 ms + transform emits it 12821.44 478.24 ms 43.37 ms 40681 ms +1.0% total throughput, -5.4% median TTFT, and the best P90/P95/P99 of every build measured on TTFT, TPOT and end-to-end latency.
EricKing626
requested review from
1am9trash,
FlamingoPg,
YAMY1234,
hubertlu-tw,
kkHuang-amd,
rainj-me and
yizhang2077
as code owners
August 19, 2026 01:18
The sparse MLA split-K factor was ATOM's decode-tuned 16 everywhere. It is the right number for decode -- a decode batch is one row per request, order 64, well short of the 256 CUs on MI355X, so splitting each request's KV range 16 ways is what fills the device. Prefill is the opposite regime and the same constant is pure overhead there. Sparse prefill presents every query token as its own length-1 sequence, so the planner's batch is the chunk's token count. At 16384 tokens the device is already oversubscribed 64x before any split; splitting again asks the planner for 262144 work items. Measured on GLM-5.2 FP4 / MI355X / TP4, mean of 4 TP ranks over a five-step prefill window: kn_get_mla_metadata_v1_2 22.4 ms (4 calls, 5594 us each) kn_mla_reduce_v1_ps 13.0 ms (390 calls) Both are consequences of the split: the planner walks the work items, and the reduce pass exists only to merge partials. The MLA kernel itself wins 41.4 ms (-5.6%) against TileLang over the same window, and these two give it back. Carry the factor on the metadata object rather than passing it per call. The planner's max_split_per_batch and the kernel's num_kv_splits are the same quantity seen from two sides, and a build/launch pair that disagrees is a silent correctness bug, not a slowdown. Prefill allocates with 1; decode keeps 16 and is bit-for-bit unchanged. Still never None: an explicit value also pins aiter to persistent mode, whose non-persistent fallback cannot honor a top-k split scheme.
This reverts the compact-page-table fusion in the DSA top-k transform. The fusion added optional outputs to the CUDA top-k transform kernel, which means every deployment must rebuild sgl-kernel before the Python side can call it; running the new Python against a prebuilt wheel fails with "fast_topk_transform_fused() got an unexpected keyword argument compact_page_table". Reverting keeps the branch installable from a stock sgl-kernel build. The follow-up split-K change on top of this commit is preserved.
This was referenced Aug 31, 2026
Merged
4 of 5 tasks
Contributor
|
Thanks @EricKing626. Closing this because it has had no updates in 91 days. Reopen it if the work is still relevant. Some directories moved recently, so an older branch may need retargeting: |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Enable with
--dsa-prefill-backend aiter --dsa-decode-backend aiter(both flagsare required; passing only one skips the ROCm default path). The default is
unchanged.
What this does
On ROCm, DSA attention currently runs on TileLang for both prefill and decode.
This PR adds an
aiterbackend that routes both phases to the AITER sparse-MLAkernel
mla_a8w8_qh16_qseqlen1_gqaratio16_pswith fp8 Q and fp8 KV.Sparse DSA prefill is structurally a very wide decode: the chunk is handed to
mla_decode_fwdasnum_tokenssequences of length 1 (max_seqlen_q = 1), soone kernel serves both phases and no separate prefill kernel is needed.
Notable details:
mla_a16w8_qh16_m16x4_n16x1_coex0_mask1_psinstead, which is 4.2x slower. fp8 Q comes from
fused_qk_rope_cat_and_cache_mla, whose gate inforward_mla.pypreviouslytested
dsa_backend == "tilelang"literally. It is now a set of backends thatwant fp8 Q.
tilelangon ROCm with a warninginstead of raising
ImportError: flashmla_ops. The ROCm default is onlyapplied when both backend flags are unset, so passing one previously made the
other fall through to
flashmla_kv.Results
GLM-5.2 FP4, MI355X (gfx950) TP4, 8192 in / 1024 out, concurrency 64.
Kernel time from a rocprof trace:
Everything else is unchanged within noise: MoE GEMM, dense GEMM and all-reduce
all move by less than 1%.
Correctness
python3 -m sglang.test.few_shot_gsm8k --num-questions 200-> 0.945.Scope
ROCm only, and only when both DSA backends are set to
aiter. CUDA backends(
flashmla_*,flashinfer_sparse_mla,trtllm) and the ROCm default(
tilelang) are untouched; the default remainstilelang/tilelang.CI States
Latest PR Test (Base): Not run yet⚠️ Not enabled -- add
Latest PR Test (Extra):
run-ci-extralabel to opt in.