Skip to content

[FLYDSL] add MLA reduce decode kernel for gfx942 - #3901

Merged
valarLip merged 88 commits into
mainfrom
flydsl-mla-reduce-decode
Aug 6, 2026
Merged

valarLip merged 88 commits into
mainfrom
flydsl-mla-reduce-decode

Conversation

@anhminhnguyenhoang

@anhminhnguyenhoang anhminhnguyenhoang commented Jun 24, 2026 •

Copy link
Copy Markdown
Contributor

Motivation

Split-KV MLA decode stage 2 reduce/combine merges per-split fp32 partial O/LSE values into the final bf16/fp16 output using an LSE-weighted online softmax (kn_mla_reduce_v1 in csrc/kernels/mla/reduce.cu).

This PR adds a FlyDSL port for gfx942 (MI300X), targeting the validated GLM-5.2 sparse MLA decode configuration at TP8 (H=16, Dv=512).

Technical details

  • Kernel: The default configuration uses 256 threads per block. Tier.ALL, the production kernel, selects one of four per-tile algorithm bodies on-device: simple, m64, m256, or mlds. It handles multi-token direct-wrapper calls and empty tiles safely.
  • Launch selection: The wrapper first selects cooperative split-K (plan_splitk_capture_safe) for low-tile, high-split decode. Otherwise, it uses adaptive direct launch for eligible sparse multi-tile inputs. All other calls select conventional 3-D or persistent grid-stride launch from the total-work threshold. low_direct_pmap_thr is an adaptive-launch optimization that bypasses LDS staging for low split counts; it is not a separate launch mode.
  • Wiring: flydsl_mla_reduce_v1() is a drop-in alternative enabled with AITER_MLA_REDUCE_FLYDSL=1. HIP remains the production default. Tier selection happens on-device, so per-tile split counts can vary within a fixed captured launch topology. Changes that select split-K, adaptive, or persistent dispatch require a separately captured topology.
  • Occupancy: waves_per_eu is an explicit wrapper argument and is part of the FlyDSL launch-cache identity for both normal and split-K dispatch.

Test plan

Validation environment:

Component Value
GPU MI300X (gfx942)
ROCm 7.2.4
PyTorch 2.10.0+rocm7.2.4
FlyDSL 0.2.4

op_tests/test_flydsl_mla_reduce.py is a pytest-free, self-contained op test. The shared test helper was inlined into the test file; run the test directly with Python:

python3 op_tests/test_flydsl_mla_reduce.py

The suite compares production-shaped metadata against HIP and torch references across H=8, Dv=256 torch-reference cases, H=128, Dv=512 HIP-reference tier stress cases, and the production H=16, Dv=512 serving fixtures. It covers variable splits, gapped indices, tier boundaries, empty tiles, split-K thresholds, adaptive launches, the actual_max_splits gate, serving OOB guards, and CUDA-graph capture/replay.

Performance benchmark

The following results are CUDA-graph replay latency on H=16, Dv=512, bf16. Values are the mean of two runs: one with fresh JIT and FlyDSL caches and one warm-cache repeat. wrapper denotes flydsl_mla_reduce_v1(). All wrapper and HIP correctness checks reported zero error.

Active tiles Splits HIP (µs) FlyDSL (µs) FlyDSL / HIP Speedup
1 128 13.88 7.23 0.52× 1.92×
8 32 5.99 4.91 0.82× 1.22×
8 26 5.47 4.92 0.90× 1.11×
8 13 4.39 3.97 0.90× 1.11×
8 6 3.84 3.41 0.89× 1.13×
8 5 3.78 3.37 0.89× 1.12×
8 3 3.77 3.02 0.80× 1.25×
8 2 3.73 2.77 0.74× 1.35×

End-to-end serving

The kernel win above is small relative to a full decode step, so it was also measured end to end. Two vLLM servings of GLM-5.2-FP8 (TP8, fp8 KV cache, 131k context, gpu_memory_utilization: 0.82) were run over the same twelve request shapes, one with AITER_MLA_REDUCE_FLYDSL=0 and one with =1.

Input length Shapes Output throughput TPOT (decode)
1K 4 +0.8% −1.4%
8K 4 +3.0% −3.2%
128K 4 +1.3% −2.3%
All 12 +1.7% −2.3%

Geometric means; negative TPOT is faster. Across the twelve shapes, decode TPOT improved 2.3%.

TPOT is the metric this PR should move since the gate only fires on decode and it improves on most shapes. Per-shape throughput suggests no regression. Measured TTFT differences are not attributable to this PR as prefill never reaches the reduce kernel.

All lengths cover concurrency 1/2/4/8. The 1K and 8K rows use nominal 1,024- and 8,192-token inputs, respectively, with 1,024 output tokens and 8/16/32/64 prompts; these retain the original random-range-ratio: 0.8 randomized traffic. The 128K sweep instead uses fixed 128,000-token inputs and 1,024-token outputs (random-range-ratio: 0.0), so every request stays within the 131,072-token model context. It uses 4/8/16/24 prompts, and both HIP and FlyDSL completed all four points with zero failed requests.

Accuracy

The FlyDSL serving path completed the 5-shot GSM8K evaluation (1,319 samples, deterministic decoding, 32 client requests in flight). The saved result reports 95.07% flexible-extract exact match and 95.00% strict-match exact match, consistent with thereported 94.9% HIP score; with one run and roughly 0.6 percentage-point standard error.

Safety coverage

  • Split-K overwrite: reduce_indptr reaches the combine kernel, which reads reduce_final_map and writes output/LSE only when n_splits > 1. Mixed [0, 64] and [1, 64] cases with a stale map are tested eagerly and under CUDA-graph replay.
  • Production dispatch: FlyDSL is selected only for the validated target: gfx942, one-token decode, H=16, and Dv=512. Unsupported architectures, prefill or multi-token calls, and unsupported shapes remain on HIP without compiling FlyDSL.
  • Pointer ABI: The direct FlyDSL API rejects invalid pointer dtypes, ranks, shapes, devices, contiguity, output strides, and split counts before JIT compilation.
  • Capture safety: CUDA-graph capture requires a warmed CSR cache or an explicit actual_max_splits value; an unresolved capture does not launch.

Add FlyDSL MLA reduce kernel and production opt-in fallback, with
multi-token decode support (decode_qlen > 1), num_kv_splits dispatch
compat, and fp8 partial/output dtype options. Include correctness tests
against the HIP kernel and standalone bench/profile harness scripts.

Co-authored-by: Cursor <[email protected]>
@anhminhnguyenhoang
anhminhnguyenhoang requested a review from a team June 24, 2026 12:58
@github-actions

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:triton-300x Run an additional Triton test job on MI300X in PRs; main branch always runs both MI35X and MI300X
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 3901 --add-label <label>

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
anhminhnguyenhoang and others added 20 commits June 24, 2026 09:02
Fix Check Code Style with Black CI failure on PR #3901.

Co-authored-by: Cursor <[email protected]>
Replace bare string tier values ("simple", "m64", "m256", "mlds") with
a proper Tier(enum.Enum) class. select_tier() now returns Tier; the
compile_mla_reduce() tier param is typed Tier = Tier.SIMPLE; all
string comparisons use enum members; the LDS global_sym_name f-string
uses tier.value to preserve the original naming.

Co-Authored-By: Claude <[email protected]>
Match psf/black@stable (Black 26) used by CI Checks workflow.

Co-authored-by: Cursor <[email protected]>
Replace the raw os.environ.get("AITER_MLA_REDUCE_FLYDSL") read with
FlyDSL's typed env helper (OptBool on an EnvManager subclass). The
helper import is kept inside the existing try/except alongside the
FlyDSL availability check, so the gate still falls back silently to
HIP when FlyDSL is not installed. Drops the now-unused `import os`.

Co-Authored-By: Claude <[email protected]>
Use fx.* qualified flydsl.expr access per review feedback and move the standalone MLA reduce benchmark under op_benchmarks/hip/.

Co-authored-by: Cursor <[email protected]>
Remove the standalone rocprofv3 driver; it was not used in CI or production
testing and is superseded by the bench/correctness harnesses.

Co-authored-by: Cursor <[email protected]>
Remove unverified HBM-bound and dev-doc references from MLA reduce docstrings and apply Black wrapping in mla_reduce.py.

Co-authored-by: Cursor <[email protected]>
Split shared helpers into flydsl_mla_reduce_common, convert correctness
coverage to pytest (HIP + torch ref for GLM Dv=256), and add a dedicated
FlyDSL bandwidth benchmark alongside the existing HIP bench.

Co-authored-by: Cursor <[email protected]>
Harden the FlyDSL kernel with gather/store bounds checks and a store q-range
guard, plus in-process guards-on/off tests that prove the guards matter via
mapped-allocation slack fixtures rather than only asserting passes-with-fix.

Co-authored-by: Cursor <[email protected]>
Wrap the per-work-item body in process_work_item() and add a kn_mla_reduce_v1_ps
-style 1-D persistent grid (num_cu*OCC*2 blocks) that grid-strides over the flat
work index with a CSR-sentinel early-out. Host (mla_reduce_kernels.py) and the
bench/test harness auto-select persistent via should_use_persistent_launch when
H*NTG*num_reduce_tile exceeds the HIP threshold. Guard semantics (bounds-checked
gather, q-range clamp, disable_guards) preserved.

Bench (MI300X, H=16, Dv=512): sparse 16384-tile/8-active 127.8us->12.3us (~10x);
uniform tiles=8/splits=32 7.3->6.8us; tiles=256/splits=8 flat (below threshold).
pytest: 40 passed + 8 slow/serving (sparse grid) passed.

Co-authored-by: Cursor <[email protected]>
Truncate each accumulator element to out_t before packing into the out_t
vector so the epilogue lowers to buffer_store_dwordx2/4 instead of a
scalarized per-element store. Drops the unused f32 acc_vt staging vector.

pytest: 40 passed (matrix, not-slow). Bench within noise of opt1 at the
prod replay shapes (store path already saturated post-opt1).

Co-authored-by: Cursor <[email protected]>
Use a tuple init and range_constexpr (compile-time) indexing in the
massive-path accumulator loop, removing _as_list and its runtime range(n)
index workaround that could lower to i64 index arithmetic. VEC==1 scalar
unwrap after the yield is handled explicitly.

pytest: 40 passed (matrix, not-slow). Bench flat at prod shapes (bandwidth
-bound kernel; this is a codegen cleanup).

Co-authored-by: Cursor <[email protected]>
Stamp rocdl.waves_per_eu on the emitted gpu.func at compile time and expose
AITER_MLA_REDUCE_WAVES_PER_EU for sweeps. Default lowered 8->4 (opt4 sweep:
on H=16 Dv=512 tiles=8 splits=32, wpe=4 best at 6.6us; H=128 graph time flat
across 2/4/6/8). Host wrapper and bench/test harness pass the env-resolved
value.

pytest: 40 passed (matrix, not-slow).

Co-authored-by: Cursor <[email protected]>
Replace the raw scf.ForOp seq loop with FlyDSL range(seq0, ub_seq, ntg,
init=None) so the AST rewriter emits scf_range without iter_args, letting
hot_loop_scheduler interleave the inner split-loop VMEM loads with compute.
Body unchanged; seq -> seq_i32 induction value.

pytest: 40 passed (matrix, not-slow). Perf-neutral on the prod shapes by
CUDA-graph replay (the bandwidth-bound reduce is already at 24-72% BW); kept
for codegen hygiene / scheduler enablement.

Co-authored-by: Cursor <[email protected]>
Defer the pmap bounds select to point-of-use in emit_massive_body so the
prefetched os[s+1] load stays in flight (vmcnt(1)) instead of draining
every iteration. Add load_split_o_raw and carry a float OOB mask folded
into the LDS scale at the FMA.

Wire Tier.ALL as the production compile path (device-side runtime tier
selection per tile, mirrors HIP) and update tests/benchmarks accordingly.
Cooperative-copy pmap[t0:t1] into lds_pmap before the split loop so
gather_row reads LDS instead of repeated global pmap loads (mirrors
reduce.cu:431-438). Adds pmap to the shared allocator for all tiers.

Co-authored-by: Cursor <[email protected]>
Process 2 splits/iter with two output buffer_loads in flight (mirror HIP
reduce_output_massive oaccu_0/oaccu_1). Carrying two distinct loaded vectors
(os0/os1) plus the next pair's prefetch as separate SSA yields lets the
compiler allocate separate VGPRs, so the accumulate loop reaches
s_waitcnt vmcnt(1) overlap instead of the depth-1 vmcnt(0) drain (register
aliasing). Split index is clamped for OOB prefetch (lds_pmap[0]/lds_scale[0]
always written) with a deferred float mask -> no NaN*0 pollution.

Graph mode: b8_s32 9.0->7.0us (ratio 1.50->1.17x), b1_s128 25.8->16.9us
(ratio 1.86->1.22x). SIMPLE unchanged. vgpr 42->56.
Generalize the depth-2 double-rate loop to process GRP splits/iter with GRP
output buffer_loads in flight (loop-carried grouped state). GRP=8 is the
gfx942 sweet spot: vgpr ~125 keeps 2 waves/SIMD while the accumulate loop
reaches s_waitcnt vmcnt(7) overlap (was vmcnt(1) at depth-2). GRP=16 pushes
vgpr ~199 (1 wave/SIMD) for no b8_s32 gain and only marginal b1_s128 gain.

Graph mode: b8_s32 7.0->6.5 (ratio 1.17->1.08x), b1_s128 16.9->15.3 (ratio
1.22->1.10x) vs depth-2. SIMPLE unchanged. buffer_load_dwordx4 14->50,
vmcnt_max 3->7.
@anhminhnguyenhoang
anhminhnguyenhoang force-pushed the flydsl-mla-reduce-decode branch from 1dd0a6d to eb836d1 Compare July 27, 2026 13:13
anhminhnguyenhoang and others added 8 commits July 28, 2026 15:53
Merge eager/CUDA-graph replay test pairs behind a replay flag, fold the
small_split graph case into the shared case table, extract shared
helpers for the guard-differential and split-K b1_s128 tests, replace
the hand-written run_checks() call list with a data-driven registry,
dedupe benchmark roofline/candidate/table logic across the three perf
sweeps, and drop redundant local imports/duplicated constants. No
scenario, assertion, or CLI behavior changes.

Co-authored-by: Cursor <[email protected]>
Two of the four raw buffer_ops paths in mla_reduce now go through the public
layout API, cutting direct call sites from 13 to 5. The f32 scratch load and
store use a buffer tensor with a copy atom over a row view; VEC=8 f32 is wider
than one atom, so it composes two atoms over adjacent chunks -- the same shape
fused_compress_attn already uses, expressed through the layout API.

The final-output store moves into shared helpers used by both the normal and
split-K combine kernels, where a single atom always covers the fragment. A
probe confirmed the layout copy still emits one packed store, refuting an
in-code comment that had claimed it would scalarize the write.

Invariant checks pass, ISA opcode counts are identical across all four emitted
kernels, VGPR counts are unchanged, and the perf sweep shows no regression. The
two paths still on buffer_ops are documented in the code.

Co-authored-by: Cursor <[email protected]>
mla_reduce no longer references buffer_ops. The indptr reads use a plain
layout view, which the backend already lowers to a scalar load, so the raw
descriptor and the explicit readfirstlane broadcast were both unnecessary.
The partial-output load now uses the same slice/copy form as the output
store; the regression seen in the earlier attempt came from a redundant
predicate, not from the load itself. The f32 atom/chunk helpers move to
module level so the 2-D and 3-D paths share one composition.

All bounds guards are unchanged. Invariant checks pass, the split-K ISA is
byte-identical, VGPR counts are unchanged, and the perf sweep shows no
regression.

Co-authored-by: Cursor <[email protected]>
Resolve FlyDSL export conflicts while preserving the MLA reduce integration.

Co-authored-by: Cursor <[email protected]>
Remove stale noqa and simplify mechanical expressions flagged by the pinned CI linter.

Co-authored-by: Cursor <[email protected]>
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
@anhminhnguyenhoang
anhminhnguyenhoang marked this pull request as ready for review July 30, 2026 07:47
coderfeli
coderfeli previously approved these changes Jul 30, 2026
anhminhnguyenhoang and others added 3 commits July 30, 2026 14:43
The partial kernel fully overwrites scratch rows each launch, so zero-init is unnecessary.

Co-authored-by: Cursor <[email protected]>
Resolve the tensor shim pointer ABI conflict and use CUDA-event timing to avoid ROCTracer crashes around HIP graph captures.

Co-authored-by: Cursor <[email protected]>
coderfeli
coderfeli previously approved these changes Aug 4, 2026
if reduce_indptr.numel() < 2:
return 0
diffs = reduce_indptr[1:] - reduce_indptr[:-1]
return int(diffs.max().item())

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

D2H ?

@anhminhnguyenhoang

This comment was marked as off-topic.

@anhminhnguyenhoang
anhminhnguyenhoang marked this pull request as draft August 5, 2026 08:04
@anhminhnguyenhoang
anhminhnguyenhoang marked this pull request as ready for review August 5, 2026 13:11
@valarLip
valarLip merged commit bc54a24 into main Aug 6, 2026
61 checks passed
@valarLip
valarLip deleted the flydsl-mla-reduce-decode branch August 6, 2026 10:34
JohnQin-llm added a commit to JohnQin-llm/aiter-amd that referenced this pull request Aug 31, 2026
_resolve_actual_max_splits caches derived actual_max_splits under
(data_ptr, numel). A raw address is not an identity: once a buffer is freed the
allocator hands the same address to the next tensor, so a later CSR landing on
that address gets a hit carrying someone else's split bound.

That is worse than a normal stale cache. The value exists precisely because
deriving it needs a device read, which is illegal under CUDA-graph capture -- so
under capture the launch path has no way to check it and simply trusts whatever
the cache returns. A recycled pointer therefore feeds an unvalidated split bound
straight into a launch.

Each entry now also holds a weak reference to the storage its pointer came from.
A hit is honoured only while that storage is alive and still sits at the cached
address; otherwise the entry is dropped and the lookup reports a miss, which the
launch path already rejects rather than proceeding on an unvalidated bound.

The cache dates to bc54a24 ([FLYDSL] add MLA reduce decode kernel for gfx942,
 ROCm#3901). It is reachable only through flydsl_mla_reduce_v1, i.e. behind
AITER_MLA_REDUCE_FLYDSL=1, so this is latent today -- the sparse MLA decode path
uses _flydsl_sparse_mla_decode_combine and never touches it.

Adds op_tests/test_flydsl_split_cache_identity.py: a hit while the buffer is
alive, a recycled pointer reporting a miss rather than a stale hit (with the
entry evicted), and a plain capture-time miss.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants