Repository navigation
[FLYDSL] add MLA reduce decode kernel for gfx942 - #3901
Merged
Merged
Conversation
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]>
Contributor
🏷️ CI GuideRuns automatically on every PR:
Extended tests (opt-in via labels):
|
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-Authored-By: Claude <[email protected]>
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
force-pushed
the
flydsl-mla-reduce-decode
branch
from
July 27, 2026 13:13
1dd0a6d to
eb836d1
Compare
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: Cursor <[email protected]>
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
anhminhnguyenhoang
marked this pull request as ready for review
July 30, 2026 07:47
coderfeli
previously approved these changes
Jul 30, 2026
The partial kernel fully overwrites scratch rows each launch, so zero-init is unnecessary. Co-authored-by: Cursor <[email protected]>
… flydsl-mla-reduce-decode
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
previously approved these changes
Aug 4, 2026
valarLip
reviewed
Aug 4, 2026
| if reduce_indptr.numel() < 2: | ||
| return 0 | ||
| diffs = reduce_indptr[1:] - reduce_indptr[:-1] | ||
| return int(diffs.max().item()) |
This comment was marked as off-topic.
This comment was marked as off-topic.
anhminhnguyenhoang
marked this pull request as draft
August 5, 2026 08:04
Co-authored-by: Cursor <[email protected]>
anhminhnguyenhoang
marked this pull request as ready for review
August 5, 2026 13:11
valarLip
approved these changes
Aug 6, 2026
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.
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.
Motivation
Split-KV MLA decode stage 2 reduce/combine merges per-split fp32 partial
O/LSEvalues into the final bf16/fp16 output using an LSE-weighted online softmax (kn_mla_reduce_v1incsrc/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
Tier.ALL, the production kernel, selects one of four per-tile algorithm bodies on-device:simple,m64,m256, ormlds. It handles multi-token direct-wrapper calls and empty tiles safely.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_thris an adaptive-launch optimization that bypasses LDS staging for low split counts; it is not a separate launch mode.flydsl_mla_reduce_v1()is a drop-in alternative enabled withAITER_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.waves_per_euis an explicit wrapper argument and is part of the FlyDSL launch-cache identity for both normal and split-K dispatch.Test plan
Validation environment:
gfx942)op_tests/test_flydsl_mla_reduce.pyis a pytest-free, self-contained op test. The shared test helper was inlined into the test file; run the test directly with Python:The suite compares production-shaped metadata against HIP and torch references across
H=8, Dv=256torch-reference cases,H=128, Dv=512HIP-reference tier stress cases, and the productionH=16, Dv=512serving fixtures. It covers variable splits, gapped indices, tier boundaries, empty tiles, split-K thresholds, adaptive launches, theactual_max_splitsgate, 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.wrapperdenotesflydsl_mla_reduce_v1(). All wrapper and HIP correctness checks reported zero error.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 withAITER_MLA_REDUCE_FLYDSL=0and one with=1.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.8randomized 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-extractexact match and 95.00%strict-matchexact match, consistent with thereported 94.9% HIP score; with one run and roughly 0.6 percentage-point standard error.Safety coverage
reduce_indptrreaches the combine kernel, which readsreduce_final_mapand writes output/LSE only whenn_splits > 1. Mixed[0, 64]and[1, 64]cases with a stale map are tested eagerly and under CUDA-graph replay.H=16, andDv=512. Unsupported architectures, prefill or multi-token calls, and unsupported shapes remain on HIP without compiling FlyDSL.actual_max_splitsvalue; an unresolved capture does not launch.