Skip to content

[FlyDSL] [Kernel] gfx950 FP8 sparse MLA prefill and decode (FlyDSL) - #5301

Open
JohnQin-llm wants to merge 11 commits into
ROCm:mainfrom
JohnQin-llm:feat/flydsl-sparse-mla-gfx950
Open

JohnQin-llm wants to merge 11 commits into
ROCm:mainfrom
JohnQin-llm:feat/flydsl-sparse-mla-gfx950

Conversation

@JohnQin-llm

@JohnQin-llm JohnQin-llm commented Sep 7, 2026 •

Copy link
Copy Markdown
Contributor

Motivation

DSA-style sparse attention on gfx950 FlyDSL kernels for both prefill and decode phases, plus the split reducer decode needs.

Kernels

flydsl_sparse_mla_prefill takes q_nope and q_rope separately: the caller already holds them split and the kernel reads them into different LDS regions, so concatenating first would copy the larger half for nothing. Below 96 tokens it splits the topk range across CTAs, because one CTA covers one token and a short prefill otherwise leaves most of the device idle. The partials it emits are the layout the sparse-decode reducer already consumes. Above that the grid fills the device on its own and a const_expr selects the single-split path, which emits the same IR as before split-K. The 96-token bound is the shared decode reducer's supported scope, not a tuning constant.

Both entry points take 1 to 16 heads. The MFMA tile is 16 rows wide, so the head count is a runtime kernel argument rather than a padded staging copy: rows past it re-read head 0, in bounds and dropped by the store predicate. GLM-5.2 has 64 heads, so 16 is TP4 and 8 is TP8, and refusing the latter would have excluded the configuration the end-to-end runs used. The kernel takes the same time at 8 heads as at 16, because KV traffic does not scale with the head count.

flydsl_sparse_mla_decode adds a split-K reducer. sparse_mla_decode_workspace_shape sizes its scratch, so a caller can allocate once and reuse across layers.

mla_reduce_kernels.py and kernels/mla_reduce.py gain the split-reduce entry points decode needs. One pre-existing path does change: _resolve_actual_max_splits, which flydsl_mla_reduce_v1 calls, used to answer a graph-capture lookup straight from a pointer-keyed cache. A freed buffer hands its address to the next tensor, so a recycled key could return a stale split bound. Entries now carry a weak reference to the storage and a capture-time hit is honoured only while that storage is alive at the same base; a recycled key reports a miss, which the launch path already rejects with a message asking the caller to warm the buffer. Eager behaviour is unchanged.

Measurements

MI355X gfx950, torch 2.9.1+rocm7.2.0, tilelang 0.1.7.post3. fp8 e4m3 q and KV, fp32 softmax and accumulation, bf16 out, P requantised to fp8 for the PV MFMA. q reaches TileLang already in fp8, so the baseline is not charged for a conversion it would not do in service.

One harness throughout: 200k-row KV pool, uniformly random topk, minimum of five HIP-graph replays. SNR is against an fp32 oracle on the pre-quantisation inputs, so it includes the fp8 input error and is the same oracle for every kernel. That error dominates, which is why TileLang, Triton and FlyDSL land within 0.1 dB of one another. The inputs are Gaussian, so the softmax over the 2048 selected keys is close to uniform -- the worst case for quantising P, and not what real top-k selection produces. On scores with realistic structure the same kernel measures several dB higher and the split count stops mattering: 16 splits scores +0.04 to +0.30 dB against 1 split there, against -1.0 dB on these inputs. Read the absolute figures as a floor, not as production accuracy. Triton is sgl-project/sglang#30575, run unmodified, using that PR's triton_sparse_mla_fwd for prefill and triton_sparse_mla_decode for decode. aiter's own sparse-MLA ASM prefill is gfx1250-only, so mla_decode_fwd appears in the decode table only.

Prefill

T TileLang Triton FlyDSL vs TileLang vs Triton
1 13.52 us 10.94 us 7.82 us 1.73x 1.40x
4 14.56 us 11.48 us 8.20 us 1.78x 1.40x
16 20.25 us 13.96 us 10.42 us 1.94x 1.34x
64 34.02 us 34.30 us 20.91 us 1.63x 1.64x
96 41.90 us 55.77 us 25.66 us 1.63x 2.17x
128 56.82 us 58.46 us 54.66 us 1.04x 1.07x
256 102.43 us 87.48 us 59.30 us 1.73x 1.48x
512 193.90 us 103.66 us 98.15 us 1.98x 1.06x
1024 356.01 us 200.32 us 208.63 us 1.71x 0.96x
2048 610.52 us 391.42 us 380.40 us 1.60x 1.03x
4096 1185.05 us 764.04 us 752.28 us 1.58x 1.02x
8192 2312.95 us 1474.37 us 1492.33 us 1.55x 0.99x
16384 4562.58 us 2901.64 us 2968.91 us 1.54x 0.98x
32768 9030.53 us 5775.87 us 5924.40 us 1.52x 0.97x

14/14 against TileLang. Against Triton: ahead below 512, level within 2-4% from 2048 up where both are bandwidth-bound, 4% behind at 1024. Before split-K the first five rows against Triton were 0.24x, 0.25x, 0.26x, 0.64x and 0.61x. SNR spans 27.46-28.57 dB with the three kernels within 0.7 dB of each other.

Decode

Sizes speculative decode at c<=16 produces -- draft 1,2,4,8,16 and verify 6,12,24,48,96. aiter is mla_decode_fwd, each decode token issued as one request whose page table is its topk, with unity fp32 q_scale/kv_scale so the numerics match bare fp8.

seq TileLang Triton aiter ASM FlyDSL vs TL vs TR vs aiter
1 13.51 us 8.91 us 15.92 us 6.47 us 2.09x 1.38x 2.46x
2 13.96 us 9.09 us 15.74 us 6.72 us 2.08x 1.35x 2.34x
4 14.54 us 9.57 us 15.24 us 7.23 us 2.01x 1.32x 2.11x
6 15.03 us 10.68 us 16.75 us 7.76 us 1.94x 1.38x 2.16x
8 15.69 us 10.35 us 13.38 us 8.30 us 1.89x 1.25x 1.61x
12 18.68 us 11.05 us 17.28 us 9.63 us 1.94x 1.15x 1.79x
16 20.20 us 11.88 us 18.03 us 10.36 us 1.95x 1.15x 1.74x
24 23.19 us 15.56 us 20.19 us 12.97 us 1.79x 1.20x 1.56x
48 28.19 us 24.52 us 25.11 us 19.78 us 1.43x 1.24x 1.27x
96 42.11 us 39.54 us 39.44 us 32.87 us 1.28x 1.20x 1.20x

30/30, and decode output is bitwise deterministic across repeated runs at every size. Triton is the closest of the three.

aiter is about 1.6 dB more accurate on these inputs, and it is worth saying where that comes from, because it is not a scale tensor. Modelling the same arithmetic one step at a time: FP8 inputs with everything else exact give 31.8 dB; quantising P to FP8 for the PV MFMA costs 2.75 dB and lands at 29.06, which is where aiter measures. Quantising P against a running maximum rather than the row's final one costs a further 0.36 dB, and doing that once per split costs 1.25 dB more, putting TileLang, Triton and FlyDSL at a modelled 27.45 against a measured 27.54. So aiter is not doing something extra -- it sits at the FP8-P limit, and pays about 2.4x the time for it. The gap is also specific to these inputs: FP8 P against BF16 P is worth 3.92 dB here, 2.63 dB at a 1.2-bit score spread, and 0.02 dB at 12.6 bits.
27.3-28.2 dB for Triton -- which is consistent with it reading a scale tensor
per operand that the others do not. Its seq=96 SNR was not reproducible across runs, so it is left out rather than quoted.

Sensitivity to the KV pool

The prefill margin over TileLang depends on gather locality, and the two kernels do not react to it the same way:

T=1024, pool TileLang FlyDSL speedup
2048 rows (1.2 MB) 303.96 us 119.35 us 2.55x
8192 rows (4.7 MB) 337.19 us 136.06 us 2.48x
32768 rows (18.9 MB) 352.42 us 166.44 us 2.12x
131072 rows (75.5 MB) 355.63 us 200.13 us 1.78x
200000 rows (115.2 MB) 356.08 us 203.55 us 1.75x

TileLang moves 17% across that range, FlyDSL 72%: FlyDSL is near the bandwidth roofline (6.4 TB/s of effective KV read at T=4096 against a 5.15 TB/s streaming-copy ceiling) and pays in full when locality degrades, while TileLang is not bandwidth-bound at these sizes. T=4096 behaves the same way, 2.61x down to 1.58x. Since a token reaches only its own sequence's KV, the figure tracks context length: roughly 2.0-2.1x at 32k, 1.6-1.8x at 128k. The tables above use the conservative end.

Known gaps

FlyDSL trails Triton by 2-4% around T=768-1024 and I do not have the mechanism. It is not occupancy: the kernel sits at 152 VGPRs, which pins it to 3 CTAs per CU independently of LDS, and padding LDS from 44.5 KB to 69.5 KB or sweeping waves_per_eu over 1-4 changes nothing at any T.

Tests

op_tests/flydsl_tests/, four files, 35 tests: accepted shapes, the rejection path for every wrong dtype/shape/arch/contiguity case, the split scratch's capacity and its identity under reuse, and the compile-cache domain.

$ python3 -m pytest op_tests/flydsl_tests/test_flydsl_sparse_mla_prefill.py \
    op_tests/flydsl_tests/test_flydsl_sparse_mla_decode.py \
    op_tests/flydsl_tests/test_flydsl_split_cache_identity.py \
    op_tests/flydsl_tests/test_flydsl_compile_cache_domain.py -q
35 passed, 2 warnings in 9.56s

Black and Ruff 0.16 clean on all changed files.

Note for reviewers

#5167 also adds a flydsl_sparse_mla_prefill, written independently, with a
different signature -- single concatenated q plus indptr, attn_sink and split_kv, BF16, D=512 -- where this one takes q_nope/q_rope separately, fp8, D=576, and has no varlen or sink support. They are not drop-in replacements and whichever lands second collides on the name in aiter/ops/flydsl/__init__.py. Worth deciding which shape the namespace should carry before either merges; I am happy to adapt.

🤖 Generated with Claude Code

@JohnQin-llm
JohnQin-llm requested review from a team and a lite review from Copilot September 7, 2026 03:40
@github-actions

github-actions Bot commented Sep 7, 2026

Copy link
Copy Markdown
Contributor

🏷️ CI Guide

Runs automatically on every PR:

  • ✅ Pre-checks (submodule verification, code formatting)
  • ✅ Aiter op tests (gfx942 + gfx950)
  • ✅ Triton tests on MI35X (only when aiter/ops/triton/** or related paths are changed)

Extended tests (opt-in via labels):

Label Tests
ci:gfx1250-ffm-triton Run the five-shard gfx1250 FFM Triton test suite
ci:triton-300x Run an additional Triton test job on MI300X in PRs; main branch always runs both MI35X and MI300X
multigpu Aiter multi-GPU tests on the 8-GPU runner
ci:sglang SGLang integration tests: DeepSeek-R1-MXFP4 accuracy, Qwen 3.5 accuracy
ci:atom ATOM benchmark: DeepSeek-R1-0528, GPT-OSS-120B
ci:atom_full ATOM accuracy suite for PR and main models from ATOM models_accuracy.json
ci:vllm vLLM benchmark: GPT-OSS-120B, DeepSeek-R1-0528, Kimi-K2.5
ci:all All standard extended tests (excludes ci:atom_full)

Only add ci:atom_full for FlyDSL or Triton upgrades.
Add labels via the sidebar or gh pr edit 5301 --add-label <label>

PR title tags & labels:
Component tags ([Triton/Gluon], [HIP], [CK], [ASM], ...) are added to the PR title and as PR labels automatically from the changed files and re-synced on every push — change-type tags like [fix]/[Perf], op tags like [MLA], and human labels (ci:*) are left untouched. Add the no-auto-title label to opt this PR out.

@github-actions github-actions Bot changed the title [Kernel] gfx950 FP8 sparse MLA prefill and decode (FlyDSL) [FlyDSL] [Kernel] gfx950 FP8 sparse MLA prefill and decode (FlyDSL) Sep 7, 2026
@github-actions github-actions Bot added the FlyDSL label Sep 7, 2026

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

The prefill launcher is missing robust CUDA/type/alignment validation and the capture-time split-cache liveness check can falsely miss for non-zero storage offsets, both of which can cause incorrect failures under real usage.

Once you've addressed the issues Copilot identified, you can request another Copilot review.

Pull request overview

Adds gfx950-specialized FlyDSL implementations of FP8 sparse-MLA prefill and decode, including decode’s split-reduce combiner and workspace sizing helper, plus targeted correctness + CUDA/HIP-graph replay coverage.

Changes:

  • Introduce flydsl_sparse_mla_prefill (FP8 Q/KV, BF16 out) with a q_nope/q_rope split interface and a 32-bit KV-extent safety guard.
  • Introduce flydsl_sparse_mla_decode with partial producer + split combiner, and sparse_mla_decode_workspace_shape for reusable scratch sizing.
  • Extend FlyDSL MLA reduce infrastructure to support decode’s combine path (narrow partial loads, base-2 LSE option, dv-split support) and harden capture-safe caching behavior.
File summaries
File Description
op_tests/flydsl_tests/test_flydsl_split_cache_identity.py New test ensuring capture-time cache doesn’t return stale values on pointer reuse.
op_tests/flydsl_tests/test_flydsl_sparse_mla_prefill.py Prefill correctness + CUDA graph replay + KV extent rejection coverage.
op_tests/flydsl_tests/test_flydsl_sparse_mla_decode.py Decode correctness, policy tests, and graph replay determinism checks.
op_tests/flydsl_tests/test_flydsl_compile_cache_domain.py Tests that compile caches cover the intended ni/ng domains.
aiter/ops/flydsl/sparse_mla_decode_kernels.py Public decode launcher + validation + workspace shape helper.
aiter/ops/flydsl/mla_reduce_kernels.py Adds decode combine entry points and strengthens capture-safe actual-max-splits caching.
aiter/ops/flydsl/kernels/sparse_mla_prefill.py New gfx950 FP8 sparse-MLA prefill kernel + Python launcher.
aiter/ops/flydsl/kernels/sparse_mla_decode.py New gfx950 decode partial-producer kernel and compile cache sizing.
aiter/ops/flydsl/kernels/mla_reduce.py Enhances reducer compilation to support narrow partial types, base-2 LSE, and dv-splitting.
aiter/ops/flydsl/init.py Exposes the new public FlyDSL APIs from aiter.ops.flydsl.
Review details

Suppressed comments (1)

aiter/ops/flydsl/kernels/sparse_mla_prefill.py:597

  • _require_vector_load_layout checks strides but not pointer alignment. Since the kernel reinterprets these fp8 tensors as i32 buffer views (alignment=4), a non-4B-aligned data_ptr() (e.g. from a storage_offset view) can violate the assumed alignment and lead to miscompiled/undefined loads. Add an explicit data_ptr() % 4 == 0 guard.
def _require_vector_load_layout(tensor, *, name):
    """Require unit inner stride and i32-aligned outer strides, without copying."""
    if tensor.stride(2) != 1 or tensor.stride(0) % 4 or tensor.stride(1) % 4:
        raise ValueError(
            f"{name} must have unit inner stride and 4-byte-aligned token/head "
  • Files reviewed: 10/10 changed files
  • Comments generated: 3
  • Review effort level: Lite

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

Comment thread aiter/ops/flydsl/mla_reduce_kernels.py Resolved
zufayu added a commit that referenced this pull request Sep 7, 2026
Both found by running the skill on #5301 -- 2385 added lines of new
FlyDSL kernels -- not by reading it. It came back with no candidates and
neither new kernel had been looked at.

The tree. The collector took $PROJECT_ROOT, the merge target. A file the PR
ADDS is not there at all, so #5301's sparse_mla_prefill.py and
sparse_mla_decode.py were invisible -- and new kernel files are the ones most
worth reading. Worse for a MODIFIED file: the collector matches AST node line
numbers against the diff's HEAD-side line numbers, and the base-side text does
not line up with those at all, so any hit would have been at the wrong site.
$WORK/head is the tree of the diff's own files at head and is what both
collectors now read. aotpair takes the merge target separately, because the
symbol table describes what AOT depends on today.

The historical checks passed because they were hand-built as `git show
<sha>:<path>`, which is head-side content. The fixture and the real invocation
disagreed and only the fixture was ever run.

The spelling. `max_size` DEFAULTS to True in both constructors, and flydsl's
own docstring says what that means: "max_size=True (default) sets the
descriptor to 0xFFFFFFFF". Matching the literal text `max_size=True` therefore
read every call that omits it as bounded -- 21 of the 138 calls in
aiter/ops/flydsl, 15%. #5301's one added buffer call is exactly that shape:
fx.rocdl.make_buffer_tensor(view), bare. The test is now "neither
num_records_bytes nor an explicit max_size=False", and positional forms are
read per constructor, since ptr_buffer_resource's second positional IS the
bound and reading it like the other two reports every use of it.

On #5301 B8 now reports one candidate: _flat_buffer_tensor builds a view whose
extent is the runtime `size` and hands it to make_buffer_tensor bare, so the
descriptor is 0xFFFFFFFF. The PR's own new test says that path has faulted --
"Memory access fault by GPU node-N" for a KV pool past 2 GiB -- and is guarded
host-side rather than in the descriptor. Whether that is the right trade is
the reviewer's call; B8 emits candidates.

A test now asserts fetch.sh passes $WORK/head to both, because this class of
defect is invisible to every unit test: the fixtures build their own root.
zufayu added a commit that referenced this pull request Sep 7, 2026
…y looked right

Pointing the FlyDSL collectors at $WORK/head was correct and insufficient: that
tree was populated only inside `if grep -q "invariant-removed\|api-signature"`.
On a PR deriving neither family it is an empty directory, and a collector that
reads files finds nothing to read.

#5207 has six buffer calls in its diff -- five bounded, one a bare
`make_buffer_tensor(W_scale, max_size=True)` -- and flydslbounds returned zero.
#5301, which the previous commit was verified against, deletes a guard and so
derives invariant-removed. That is the only reason the fix appeared to work. A
fixture cannot see this: every test here builds its own root and hands it over,
so the tree is always populated.

Materialising head is now unconditional; only the `evidence` call stays behind
the family test. The cost is a few `git show` calls against objects already
fetched at line 125.

On #5207 B8 now reports exactly one candidate and it is worth asking about:
`W_scale` is bound with `num_records_bytes=n_heads * self.n_per_head * 4` at
line 184 of the same file, and with `max_size=True` at line 92, inside a
BlockScale whose constructor already receives head and n_scale_cols. Same
tensor, two treatments, one of them unbounded.

Also verified silent for the right reason on #5146 (its one added buffer call
is buffer_ops.py forwarding variables, not a kernel binding a tensor) and on
#5282 (no buffer construction in the diff at all).
@coderfeli

coderfeli commented Sep 7, 2026 •

Copy link
Copy Markdown
Collaborator

why compare with tilelang? do you have perf of triton or hip? @JohnQinAMD

@zufayu
zufayu requested a review from coderfeli September 8, 2026 01:26
Copilot AI review requested due to automatic review settings September 10, 2026 02:56

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

There are correctness risks in the new prefill kernel wrapper/compilation (variant naming collision and empty-token handling) that should be fixed before approval.

Once you've addressed the issues Copilot identified, you can request another Copilot review.

Review details

Suppressed comments (1)

aiter/ops/flydsl/kernels/sparse_mla_prefill.py:794

  • flydsl_sparse_mla_prefill() can be called with num_tokens==0 (empty batch). In that case _prefill_splits() divides by num_tokens, raising ZeroDivisionError, and it’s unclear whether a 0-sized grid launch is valid here. Return early for the empty case after validating/allocating out.
    n_splits = _prefill_splits(num_tokens, device)
    if n_splits == 1:
  • Files reviewed: 10/10 changed files
  • Comments generated: 2
  • Review effort level: Lite

Copilot AI review requested due to automatic review settings September 10, 2026 03:50

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

There are confirmed correctness issues in new/updated logic (zero-token prefill division-by-zero, and missing device disambiguation in a capture-critical pointer-keyed cache) that should be fixed before approval.

Review details

Suppressed comments (4)

Previously missed (3) — in code that hasn't changed since the last review.

aiter/ops/flydsl/kernels/sparse_mla_prefill.py:711

  • num_tokens can be 0 for an empty Q tensor, which will later trigger a division-by-zero in _prefill_splits (and would also attempt a 0-sized launch grid). The public entry point should reject T==0 up front with a clear error to avoid a cryptic runtime failure.
    aiter/ops/flydsl/mla_reduce_kernels.py:483
  • _ACTUAL_MAX_SPLITS_CACHE keys only on (data_ptr, numel). On multi-GPU setups, different devices can legally return the same data_ptr() value, which would allow cross-device cache hits and return an incorrect split bound under capture. Include the tensor's device in the cache key to make the identity unambiguous.
    op_tests/flydsl_tests/test_flydsl_split_cache_identity.py:30
  • This test builds the expected cache key as (data_ptr, numel), but _resolve_actual_max_splits should key by (device, data_ptr, numel) to avoid cross-device collisions. Update the test key accordingly so it continues to validate the pointer-recycling behavior with the new, safer key.

This issue also appears on line 39 of the same file.

op_tests/flydsl_tests/test_flydsl_split_cache_identity.py:41

  • After extending the cache key tuple to include device (e.g. (device, ptr, numel)), the mocked data_ptr() should match the pointer element (index 1), not the device element (index 0), otherwise the test no longer simulates a recycled-pointer collision.
        with mock.patch.object(fake, "data_ptr", lambda: key[0]), mock.patch.object(
            torch.cuda, "is_current_stream_capturing", lambda: True
        ):
  • Files reviewed: 10/10 changed files
  • Comments generated: 0 new
  • Review effort level: Lite

Copilot AI review requested due to automatic review settings September 10, 2026 05:15

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

It introduces substantial new GPU kernel surface area and graph-capture-sensitive behavior, and there are a few concrete input-validation/error-handling issues that should be addressed first.

Review details

Suppressed comments (3)

Previously missed (3) — in code that hasn't changed since the last review.

aiter/ops/flydsl/kernels/sparse_mla_prefill.py:668

  • _require_tensor raises ValueError for dtype mismatch, but other FlyDSL input validators in this repo use TypeError for dtype mismatches (e.g. sparse_mla_decode_kernels._require_cuda_tensor, mla_reduce_kernels._require_tensor). Aligning exception types improves consistency for callers that distinguish TypeError vs ValueError.
    aiter/ops/flydsl/kernels/sparse_mla_prefill.py:795
  • Calling _prefill_splits() with num_tokens==0 will raise a ZeroDivisionError. Even if empty-token calls are rare, this should fail cleanly (or just return an empty output) rather than crashing inside the split policy.
    aiter/ops/flydsl/kernels/sparse_mla_prefill.py:709
  • The error message says "q_nope must be a CUDA tensor", but the rest of FlyDSL launchers in this repo use "ROCm" or "CUDA/ROCm" wording; this message is likely to confuse users on ROCm where the device type still prints as "cuda".
  • Files reviewed: 10/10 changed files
  • Comments generated: 0 new
  • Review effort level: Lite

Copilot AI review requested due to automatic review settings September 10, 2026 05:22

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

There are a couple of concrete correctness/robustness issues (a type-contract mismatch in the decode validator return annotation and a GPU-less test collection failure risk) that should be fixed before approval.

Once you've addressed the issues Copilot identified, you can request another Copilot review.

Review details

Suppressed comments (1)

Previously missed (1) — in code that hasn't changed since the last review.

op_tests/flydsl_tests/test_flydsl_split_cache_identity.py:17

  • This unittest module unconditionally allocates CUDA tensors; in environments without GPU access it will error instead of skipping like other flydsl_tests. Add a class-level skip so the suite is safe to collect/run on CPU-only machines.
  • Files reviewed: 10/10 changed files
  • Comments generated: 2
  • Review effort level: Lite

Copilot AI review requested due to automatic review settings September 10, 2026 06:07
@JohnQin-llm
JohnQin-llm force-pushed the feat/flydsl-sparse-mla-gfx950 branch from b0e3db0 to d11043f Compare September 10, 2026 06:07

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

The prefill kernel currently does not guard against positive out-of-range indices values, which can cause out-of-bounds KV reads and GPU faults.

Once you've addressed the issues Copilot identified, you can request another Copilot review.

Review details
  • Files reviewed: 10/10 changed files
  • Comments generated: 2
  • Review effort level: Lite

Copilot AI review requested due to automatic review settings September 10, 2026 06:12
@JohnQin-llm

Copy link
Copy Markdown
Contributor Author

why compare with tilelang? do you have perf of triton or hip? @JohnQinAMD

@coderfeli
TileLang was the starting point because it is the current only implementation covering both phases on gfx950 for glm5.2 and is what sglang's ROCm path picks by default. The description now carries Triton and aiter as well, all three under same test setup.

Triton is sgl-project/sglang#30575, which is going to be merged to sglang-- triton_sparse_mla_fwd for prefill, triton_sparse_mla_decode for decode.

HIP: aiter's mla_decode_fwd is the ASM column in the decode table. For prefill there is a gfx950 path — pa_sparse_prefill_fp8_opus — but it is a different operator rather than a different implementation of this one: D=448+64 with the NoPE half in MXFP8 (32-element blocks, E8M0 exponents packed into the row) and bf16 RoPE, against this kernel's D=512+64 with both halves in plain FP8. There is no shared input a like-for-like run could take. mla_sparse_prefill_fp8_asm is gfx1250-only.

vs TileLang vs Triton vs aiter ASM
prefill T=1..96 1.63-1.94x 1.27-2.17x —
prefill T=256..512 1.73-1.98x 1.06-1.48x —
prefill T>=2048 1.52-1.60x 0.97-1.03x —
decode seq=1..24 1.79-2.09x 1.15-1.38x 1.56-2.46x
decode seq=48..96 1.28-1.42x 1.20-1.24x 1.20-1.27x

The full sweep result has been updated in the PR body

Copilot AI review requested due to automatic review settings September 10, 2026 23:55

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Unresolved critical namespace and cache-lifetime issues remain, along with moderate launch and test gaps.

Once you've addressed the issues Copilot identified, you can request another Copilot review.

Review details

Suppressed comments (11)

Previously missed (1) — in code that hasn't changed since the last review.

op_tests/flydsl_tests/test_flydsl_sparse_mla_prefill.py:139

  • This test only checks GPU availability, but the entry point rejects non-gfx950 devices before reaching the 32-bit extent validation. On any available gfx942/other GPU it therefore fails with the architecture RuntimeError instead of skipping. Use _require_gfx950_flydsl() here and remove the local availability check so this rejection test is portable.

aiter/ops/flydsl/kernels/mla_reduce.py:137

  • This private dtype resolver has no callers in the repository; the only reference is its definition. Please remove it or use it to drive the numeric_t selection, otherwise the new reducer adds dead code and a second dtype-dispatch surface that can drift from _load_partial_out_narrow.
def _narrow_numeric_t(name: str):

aiter/ops/flydsl/kernels/sparse_mla_decode.py:203

  • The new raw_row < num_kv_rows masking path is a GPU-safety contract, but every decode case currently uses indices in [0, context) or -1; none exercises a positive out-of-range row. Add a decode case with an index equal to or above kv.shape[0] and compare it with -1, otherwise a regression here could reintroduce an OOB read/fault without detection.
            in_range = (raw_row >= fx.Int32(0)) & (raw_row < num_kv_rows)
            row = in_range.select(raw_row, fx.Int32(-1))

aiter/ops/flydsl/sparse_mla_decode_kernels.py:38

  • compile_fn() here only constructs/returns the cached @flyc.jit launcher; the actual MLIR/module compilation is deferred to _run_compiled() in the callers. Consequently seen.add(key) can run even when _run_compiled() raises, and a retry during graph capture will bypass this cold-variant guard and may compile inside capture. Record the key only after the first dispatch succeeds, or make the warm-up perform the real compilation.
    compiled = compile_fn()
    seen.add(key)

op_tests/flydsl_tests/test_flydsl_sparse_mla_decode.py:257

  • The reference keeps the softmax weights exact, while the producer intentionally converts probs * 448 to FP8 before the PV MFMA (aiter/ops/flydsl/kernels/sparse_mla_decode.py:278-290). For these near-uniform inputs that quantization is the dominant error, so a 30 dB gate against the unquantized reference can reject a correct implementation (the PR's own model is around 27–29 dB for this path). Quantize P in the reference or calibrate the threshold to the intended FP8-P contract.
    assert _snr_db(partial_output, ref_partial) >= 30.0
    assert _snr_db(out, ref_out) >= 30.0

op_tests/flydsl_tests/test_flydsl_sparse_mla_decode.py:387

  • The graph is captured on stream, but these input and scratch-buffer copies are issued on the surrounding current stream (normally the default stream). There is no event or stream context ordering those writes before graph.replay(), so replay can read the previous tag's inputs and make this test nondeterministic. Perform the copies, initialization, and replay on stream (or explicitly synchronize it).
        q_live.copy_(q_src)
        kv_live.copy_(kv_src)
        indices_live.copy_(indices_src)

op_tests/flydsl_tests/test_flydsl_sparse_mla_decode.py:18

  • All Case instances use the fixed H = 16, so the newly added q_heads < 16 path—including the wide partial workspace and final narrowing copy—is never exercised for decode. Add at least one narrow-head case (for example 1, 8, or 15 heads) to validate the advertised 1–16-head contract.
H = 16
DV = 512
DT = 64
DIM = DV + DT

op_tests/flydsl_tests/test_flydsl_sparse_mla_decode.py:70

  • This module-level marker makes the same build-time/runtime mix-up: get_gfx() can be overridden by a multi-arch GPU_ARCHS value, while the decode launcher checks the live device properties. In that setup the tests can be skipped on gfx950 or executed on a non-gfx950 device instead of being skipped. Use get_gfx_runtime() for the marker.
pytestmark = pytest.mark.skipif(
    get_gfx() != "gfx950",
    reason="FlyDSL sparse MLA decode requires gfx950 with FlyDSL installed",

op_tests/flydsl_tests/test_flydsl_sparse_mla_prefill.py:17

  • The prefill reference likewise computes exact softmax probabilities, but the kernel quantizes every probability to FP8 before the PV MFMA. The 35.3 dB gate therefore measures the implementation against a numerically different operation and can fail even when the intended FP8-P path is correct. Make the oracle model the FP8 probability path or set the gate from a measured FP8-P baseline.
_MIN_SNR_DB = 35.3

op_tests/flydsl_tests/test_flydsl_sparse_mla_prefill.py:119

  • The only short-prefill test forms expected by running the same kernel eagerly and then compares graph replay to it. It never calls _reference, so the new split-K producer/reducer path can be numerically wrong in both executions and still pass. Add an oracle comparison for a T <= 96 case before treating this as split-path correctness coverage.
    expected = torch.empty_like(output)
    flydsl_sparse_mla_prefill(q_nope, q_rope, kv, indices, _SOFTMAX_SCALE, out=expected)
    graph.replay()
    torch.cuda.synchronize()
    torch.testing.assert_close(output, expected, rtol=0, atol=0)

op_tests/flydsl_tests/test_flydsl_sparse_mla_prefill.py:22

  • This is a runtime-device skip, but get_gfx() honors GPU_ARCHS and can select the last entry of a multi-arch build rather than the GPU running the test. The launcher below gates on the actual device, so this can skip a gfx950 test or run it on another architecture and fail instead of skipping. Use get_gfx_runtime() (or the same runtime property check) for this guard.
def _require_gfx950_flydsl():
    if not torch.cuda.is_available() or get_gfx() != "gfx950":
        pytest.skip("requires gfx950")
  • Files reviewed: 10/10 changed files
  • Comments generated: 2
  • Review effort level: Lite

Comment on lines +73 to +76
"flydsl_sparse_mla_prefill": (
".kernels.sparse_mla_prefill",
"flydsl_sparse_mla_prefill",
),
def _storage_ref(t: torch.Tensor):
"""Weak reference to the tensor's storage, or None if it cannot be taken."""
try:
return weakref.ref(t.untyped_storage())
JohnQin-llm and others added 11 commits September 21, 2026 02:35
Sparse MLA for DSA-style attention on gfx950, both phases, plus the split
reducer the decode path needs.

Prefill takes q_nope/q_rope separately -- the caller already has them split
and the kernel reads them into different LDS regions, so concatenating first
would cost a copy of the larger half. Decode adds a split-K reducer;
`sparse_mla_decode_workspace_shape` sizes its scratch so the caller can
allocate once and reuse across layers.

Measured against TileLang on MI355X, fp8 e4m3 q/KV, fp32 softmax and
accumulation, bf16 out:

  prefill, T=256..32768   2.21x - 3.08x
  decode,  seq=1..96      1.30x - 1.46x, 10/10 win

Both sit at 36.5 dB against an fp64 oracle and agree with TileLang to
86-96 dB; decode output is bitwise deterministic at every size measured.

`mla_reduce_kernels.py` and `kernels/mla_reduce.py` gain the split-reduce
entry points decode needs; existing callers are untouched.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Prefill launched one CTA per token, so a short prefill could not reach
past `num_tokens` CUs: a 1-token call left 255 of 256 idle and took the
same 46us as a 64-token one. Split the topk range across CTAs and merge
through the sparse-decode reducer, which already accepts exactly this
partial layout. Measured against the Triton sparse-MLA prefill on
gfx950/MI355X (HIP-graph captured, GLM-5.2 shape, topk=2048):

  T=1    46.09 -> 8.33us   (1.32x vs Triton, was 0.24x)
  T=4    46.46 -> 8.79us   (1.31x, was 0.25x)
  T=16   52.50 -> 10.88us  (1.29x, was 0.26x)
  T=64   53.79 -> 21.53us  (1.60x, was 0.64x)
  T=96   54.28 -> 25.97us  (2.13x, was 0.61x)

The single-split path is selected by `const_expr`, so it emits the same
IR as before: T>=128 checksums are bit-identical and timings sit within
run-to-run noise. Two CTAs per CU rather than one, capped at 16 splits
where the reducer starts costing more than the parallelism returns and
where the BF16 partials stop giving up precision for free.

Correctness and cleanup from review:

- Decode bounded the KV row index only from below, so an out-of-range
  entry read unmapped memory and faulted the queue. Fold the upper
  bound into the existing negative sentinel.
- Drive both decode MFMAs through MMA atoms and `fx.gemm`, as prefill
  already does for the same two instructions. Bit-identical output and
  timings within 0.5%.
- Guard `num_tokens` in prefill: past 262143 the flydsl shim raised a
  bare struct.error from the argument pack several frames below the
  caller.
- Drop four parameters of `compile_mla_reduce` that had no non-default
  call site, so this PR no longer changes the shared reducer's
  signature.
- Refuse to JIT a cold variant inside a graph capture instead of
  failing unpredictably.
- Compare storage base against storage base in the split-count cache; a
  view whose data_ptr sits past its storage base missed on every
  capture-time lookup.
- Derive the compile-cache test's domain from the policy functions. The
  old bound counted only `ng`, ignoring `inner_iter` and `split_major`,
  so the test passed at every size it was meant to catch.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
`_use_fine_decode_combine` gated the Dv-sliced reducer on
`num_cu <= seq * 64 <= 3 * num_cu`, a window that is open only for
4 <= seq <= 12, plus an `ni > 16` term that closed it again on every
merged shape. Short decodes therefore ran the coarse reducer: `seq * 16`
blocks of 64 threads, 6% of the device at seq=1, each walking all 32
splits serially. Gate on the one thing that matters instead -- whether
the coarse grid would leave the device under-occupied.

Measured on gfx950/MI355X, 200k-row KV pool, HIP-graph captured, output
bit-identical at every size:

  seq=1   7.75 -> 6.46 us   seq=12  10.30 -> 9.70 us
  seq=2   8.07 -> 6.72 us   seq=16  10.98 -> 10.48 us
  seq=4   7.19 -> 7.21 us   seq=24  13.19 -> 12.79 us
  seq=48/96 unchanged

That is 17% at seq=1 and it lifts the two weakest points against the
Triton sparse-MLA decode kernel from 1.10x to 1.14-1.16x.

The policy test went with it. It was a table of five sampled points, and
every one of them sat inside the band -- which is why it passed while the
band excluded both ends of the range. It now asserts the property that
band violated: the choice is monotone in `seq`, on for a 1-row decode,
off once coarse saturates, exactly one transition. That form fails on the
old policy for every split count, and on `ni = 32` it reports the two
transitions that are the defect itself.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
## Narrow head counts

Both entry points required exactly 16 heads, the MFMA tile width. GLM-5.2
has 64 heads, so that covered TP4 and refused TP8 -- 8 per rank, which is
the configuration the end-to-end runs used. sglang's TileLang path takes any
head count and its Triton path pads below 16; refusing was the outlier.

The head count is a runtime kernel argument rather than a padded staging
copy. `q_heads` is the caller's row stride and rows past it re-read head 0
-- in bounds, finite, dropped by the store predicate. In prefill `out_heads`
also drives the store, so a single-split call writes the caller's
`[T, heads, Dv]` directly. Decode and split-K prefill still narrow once at
the end, because the shared reducer only takes the full 16 rows.

Staging was the entire cost of a narrow call: the kernel runs in the same
time at 8 heads as at 16 -- KV traffic does not scale with the head count,
and the idle MFMA rows are lanes the shape cannot fill either way -- while
the staging added 12.7us at T=64, 57% of the call. It was launch-bound, not
bandwidth-bound: the cost sat near 13us at both T=64 and T=1024.

  T=64    1.557x -> 1.115x of the 16-head call
  T=256   1.216x -> 0.988x
  T=1024  1.090x -> 1.005x
  T=4096  1.052x -> 0.991x

SNR is unchanged at 4, 8 and 16 heads, and the 16-head path is bit-identical.

## Derived tiling constants

The decode kernel spelled its tiling out as bare integers: `lane // 16` for
the head group, `range_constexpr(8)` for the Dv tiles a wave owns,
`lane * 144` for the per-lane Q stride, `64 * 144` for the LDS holding it.
Every one follows from `H`, `DV`, `DIM` and the 16x16 MFMA tile, so changing
a constant produced silently mis-addressed loads rather than an error.
Derive them and assert the relationships that cannot bend. Output is
bit-identical at all ten decode sizes.

## Copilot findings

- The prefill kernel is specialised by `n_splits` but its FlyDSL kernel name
  was constant, so variants could collide in the compile cache. Put the
  split count in the name, which the decode producer already does.
- `_require_warm` recorded a variant as warm before its caller compiled it,
  so a compile that raised left the variant marked warm and the next graph
  capture would proceed into a cold JIT. It now takes the compile callable
  and records only after it returns.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Two findings from Copilot on the previous push.

`_validate_sparse_decode_inputs` gained a third return value when it started
reporting the caller's head count, but its annotation still said
`tuple[int, int]`.

The gfx950 gate read `props.gcnArchName` directly. A CUDA build has no such
attribute, so the gate raised AttributeError from inside itself instead of
refusing the device with a clear message. Read it through `getattr`, which is
what `linear_attention_prefill_kernels.py` already does. Only the two sites
this PR introduced are touched; the third in `mla_reduce_kernels.py` predates
it, as do the ones in `fmha_kernels.py` and `topk_per_row.py`.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Two findings from Copilot on the previous push.

Prefill clamped a negative index to row 0 but let a positive one past the end
of `kv` through. I expected the buffer descriptor to catch that; it does not.
`_flat_buffer_tensor` builds the view with `num_records` at the descriptor
maximum rather than the tensor's length, so a row past the end reaches
unmapped memory. Every out-of-range value I tried -- one past the pool, 1<<20,
1<<28 -- faulted the queue outright. The decode producer already folds this
bound into its sentinel; prefill now does the same, at the point where indices
are staged, so both the KV address and the score mask downstream follow from
one check. An out-of-range row now lands on exactly the output of one spelled
-1, which the new test asserts.

`_SPLIT_CAP` is 16, so the 32 in `_SPLIT_CHOICES` could never be selected.
Derive the tuple from the cap instead of listing a value the policy cannot
reach.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The earlier pass derived the tiling from `H`, `DV` and `DIM` but left `H = 16`
and `BLOCK_I = 64` as bare literals, then asserted `H == MFMA_N` after the
fact -- the dependency stated backwards. `H` is not the model's head count
either, now that the kernel reads a runtime `q_heads`; it is the MFMA tile
width, and the name read as the other thing.

Order the constants the way they actually depend on each other: hardware
(`WAVE_SIZE`), then instruction shape (`MFMA_M`/`MFMA_N`/`PV_MFMA_K`), then
`H` and `BLOCK_I` from those, then the model shape, then the derived layout.
`PITCH`'s `+ 16` was an LDS bank pad that happened to match the MFMA tile;
it is named now so the two cannot be confused. Prefill gets the same
treatment.

Two comments went with it. `_SPLIT_TOKEN_LIMIT` said the grid already fills
the device past 96 tokens, which is false between 97 and 768; the bound is
the shared reducer's supported row count. And `_SPLIT_CHOICES` is generated
from `_SPLIT_CAP` rather than listing a 32 the policy filters back out.

Every shared constant keeps its value, decode output is bit-identical, and a
96-way cross product of head count, split count, out-of-range indices,
caller-supplied `out` and non-contiguous `q` passes.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…t do

A read of every comment and docstring the PR adds, checking the ones that
give a reason against what the code actually does. Four did not hold. No
behaviour changes; tests and the shape cross-product are unaffected.

`_pick_inner_iter` said it merges tiles "only while the reduced producer grid
still has enough CTAs to cover the GPU". Its floor is 192, and the part has
256 CUs, so the first merge leaves the device short by a quarter -- which is
why seq=12 and 16 are the weakest points against Triton. Say what the floors
are instead of claiming a property they do not provide.

The `inner_iter` pairing claimed it was "matching the reducer's first active
shuffle level". There is no such level: the reducer's max and sum are an
unconditional six-level butterfly over all 64 lanes, masked only on their
inputs, so producer pairing changes rounding order and nothing else. Keep the
pairing, drop the rationale, and record what adjacent pairing would actually
buy.

Both entry points still said a narrow head count "is padded up". That was the
previous commit's implementation; it now reads `q` in place at the caller's
row stride.

The `kv` size guard said the pack raises and "the launch that follows faults
the GPU". Those are alternatives, not a sequence -- if the pack raises there
is no launch.

`_prefill_splits` justified two CTAs per CU by exposed gather latency, which
I did not measure. What I did measure is that below it the grid does not
cover the device: 96 tokens at 2 splits is 192 CTAs against 256 CUs.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…ameter

Reading the logic rather than the prose this time.

`_prefill_splits` ends in `max(s for s in _SPLIT_CHOICES if s <= want)`. With
`want = 2 * num_cu // num_tokens`, a part with fewer than 48 CUs reaches
`want = 0` at 96 tokens and the generator is empty, so `max` raises instead of
settling on one split. That is reachable: CPX mode divides an MI355X into
eight partitions of 32 CUs, and the arch gate still sees gfx950. Give `max` a
default.

`_use_fine_decode_combine` stopped reading `ni` when its gate was rewritten,
but kept it as a parameter, so a reader would assume the split count still
influences the choice. Drop it from the signature, the call site and both
tests; the docstring now says the omission is deliberate.

Also checked and found sound: every barrier sits outside the divergent `if`
that precedes it, so the new store predicate cannot deadlock; the staged
index bound tops out at `keys_per_split - 1`; both staging paths mask through
`bounded`; and the empty-slice sentinel survives every degenerate input --
all indices out of range, all -1, all pointing at one row, and a single-row
KV pool each return finite zeros or that row's values.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
`get_gfx()` answers from `GPU_ARCHS` when it is set, and on a multi-arch
build such as "gfx942;gfx950" it reports the last entry regardless of the
part in the machine -- `chip_info` says so itself, and points runtime
dispatch at `get_gfx_runtime()` instead. So the prefill gate would admit a
gfx942 device under that build. The decode entry already reads the device
properties; prefill now does the same, which is also per-device rather than
per-process. Reported by Copilot.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
An empty KV pool reached both kernels as a null base pointer and faulted the
queue outright -- prefill through its buffer descriptor, decode through a plain
pointer -- rather than returning the all-masked answer that every index into a
zero-row pool implies. Both entries now reject it. Prefill additionally accepts
a zero-token chunk, which a chunked-prefill scheduler can hand over: the input
validation still runs, so a wrong-shaped `out` is caught either way, and only
the launch is skipped. Without that it raised a bare setStorage error from the
argument pack on the zero-length q pointer.

`_make_case` in the prefill tests built its tensors with a CPU generator but no
explicit device, which raises against the ambient default -- and importing any
sibling test in op_tests/flydsl_tests sets that default to cuda for the whole
session. Nine of this file's tests failed whenever the directory was collected
as a whole; they only ever passed because it was run one file at a time.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Copilot AI review requested due to automatic review settings September 21, 2026 02:38
@JohnQin-llm
JohnQin-llm force-pushed the feat/flydsl-sparse-mla-gfx950 branch from a75ba9b to 9b5cf23 Compare September 21, 2026 02:38

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot review overview

🟡 Changes recommended

One newly added pytest-style test module will execute zero tests under the repo’s python3 file.py op-test runner (and nested op_tests/flydsl_tests aren’t discovered by default), reducing confidence in coverage for a high-risk kernel change set.

Get a fresh assessment by requesting another Copilot review.

Review effort: Lite
Findings: 2 High severity · 1 Medium severity

Open (3)

Comment on lines +253 to +256
q_nope, q_rope, _, indices = _make_case(4)
empty = torch.empty(0, _HEAD_DIM, dtype=torch.float8_e4m3fn, device="cuda")
with pytest.raises(ValueError, match="at least one row"):
flydsl_sparse_mla_prefill(q_nope, q_rope, empty, indices, _SOFTMAX_SCALE)
@github-actions

github-actions Bot commented Oct 7, 2026

Copy link
Copy Markdown
Contributor

No activity for 15 days, so this is now labelled stale. A push or a comment clears it; keep-open exempts it. Nothing is closed automatically.

@github-actions github-actions Bot added the stale The PR hasn't been updated in 2 weeks label Oct 7, 2026
@zufayu
zufayu requested review from zhiding512 and removed request for coderfeli November 11, 2026 05:47
@zufayu
zufayu requested a review from coderfeli November 11, 2026 05:47
@github-actions github-actions Bot removed the stale The PR hasn't been updated in 2 weeks label Nov 12, 2026
@github-actions

Copy link
Copy Markdown
Contributor

No activity for 15 days, so this is now labelled stale. A push or a comment clears it; keep-open exempts it. Nothing is closed automatically.

@github-actions github-actions Bot added the stale The PR hasn't been updated in 2 weeks label Nov 28, 2026

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

FlyDSL stale The PR hasn't been updated in 2 weeks

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants