Repository navigation
[HIP] [FlyDSL] [Bugfix][MLA] Correct final_lse in PS MLA prefill kernel for chunked prefill - #3606
Conversation
The PS scheduler in v1_2_host.cuh's generate_work_info tagged tiles that a single threadgroup could absorb from block 0 with the sentinel partial_o_loc = -1, causing generate_reduce_info to exclude them from reduce_indptr / reduce_final_map / reduce_partial_map. As a result mla_reduce_v1 never wrote final_lse[qo_start:qo_end, :] for those tiles, leaving stale workspace bytes that downstream consumers (vLLM's chunked-context MLA prefill on MI350) read as garbage LSE and fed into merge_attn_states, causing a ~2-3pp gsm8k accuracy regression on DeepSeek-V3. Always assign a real partial_o_loc so every tile produces a partial output + partial LSE that reduce processes (num_partials==1 for what used to be the fast-path tiles). The kernel already supports this path -- only the host scheduler needed changing; no assembly edits. The if(work.partial_o_loc == -1) continue; guard in generate_reduce_info is left in as defensive coding. Mirrors PR ROCm#3542 ("[Triton-Gluon-MLA-GFX950] return_lse: full decode + merged fp32 lse"), which fixed the analogous bug in the triton-gluon decode kernel's NUM_KV_SPLITS==1 fast path.
Signed-off-by: simondanielsson <[email protected]>
Signed-off-by: simondanielsson <[email protected]>
Signed-off-by: simondanielsson <[email protected]>
Signed-off-by: simondanielsson <[email protected]>
Signed-off-by: simondanielsson <[email protected]>
🏷️ CI GuideRuns automatically on every PR:
Extended tests (opt-in via labels):
|
Signed-off-by: simondanielsson <[email protected]>
Signed-off-by: simondanielsson <[email protected]>
Signed-off-by: simondanielsson <[email protected]>
Signed-off-by: simondanielsson <[email protected]>
Signed-off-by: simondanielsson <[email protected]>
Signed-off-by: simondanielsson <[email protected]>
Signed-off-by: simondanielsson <[email protected]>
Signed-off-by: simondanielsson <[email protected]>
Signed-off-by: simondanielsson <[email protected]>
…final-lse Signed-off-by: simondanielsson <[email protected]>
|
In theory, if a device-side implementation is desirable, there is already a device-side counterpart for MLA decode that handles similar metadata computation, which could be a good reference: https://github.com/simondanielsson/aiter/blob/75f77cf79bac1794acfd7b4037507b69e06caa46/csrc/kernels/mla/metadata/v1_2_device.cuh |
Thanks @Wanzizhu.
|
|
Reviewed the Python side and the fix rationale — the four changes (workspace sizing for non-causal KV tiles, dropping the
The host-side memcpy sync question is fine to defer as you and @Wanzizhu agreed — not a blocker for this PR. |
Thanks @ChuanLi1101! Who can I ask for help in triggering the accuracy CI? |
Signed-off-by: simondanielsson <[email protected]>
Signed-off-by: simondanielsson <[email protected]>
Signed-off-by: simondanielsson <[email protected]>
valarLip
left a comment
There was a problem hiding this comment.
Re-review of 3faf013
Thanks for the rework — the need_lse threading is the right shape, and most of the previous round is genuinely resolved. Verified against 3faf013 in a worktree; measurements included.
Resolved since the last review, so nobody re-litigates them:
- The
-1sentinel corruption on the decode path is fixed —reduce.cu:783/882now guards withp_reduce_partial_map[reduce_tile_start] != -1, andv1_0_device.cuh:137does write-1into that map, so the check is load-bearing there. mla_reduce_v1_impl_simple's unconditionalp_lds_reduce_partial_map[1]read is fixed exactly as suggested (reduce.cu:468/586).- The direct-to-O fast path is preserved via
need_lserather than removed. max_partialsis now the tight bound:qo_tile_cnt + (cus_per_cluster - 1)(attention.py:1035).generate_reduce_infohas bounds asserts.- The LSE check now has a real
isneginfstructural assertion.
Blocking
1. csrc/kernels/mla/reduce.cu:1015 — kn_mla_reduce_v1_d64 still has the unconditional early return.
This was flagged last round and reported fixed; it is not:
const int32_t num_splits = reduce_tile_end - reduce_tile_start;
if(num_splits <= 1)
{
return;
}dispatch_mla_reduce_v1 (:1100) routes here unconditionally for kSizeDV == 64 && kNumHeadQ == 64, and MLA_REDUCE_ROUTER:953 instantiates exactly that pair. With need_lse=true the ASM kernel now sends every qo tile into the partial pool instead of direct-to-O, so for that config every tile is a 1-split reduce group, d64 returns immediately, and neither final_output nor final_lse is written — both keep the caller's torch.empty contents. That is worse than the LSE bug being fixed, because it costs the output tensor too.
Repro: test_mla_prefill_ps.py -n 64 -vh 64 --need_lse true. grep -n num_splits csrc/kernels/mla/reduce.cu shows all four sites; two got the escape hatch, d64 and the FlyDSL port did not.
1b. Same predicate, same miss in aiter/ops/flydsl/kernels/mla_reduce.py:443:
has_work = (n_splits > fx.Int32(1)) & (t0 != last)op_tests/test_flydsl_mla_reduce.py claims HIP-equivalence, so AITER_MLA_REDUCE_FLYDSL=1 diverges under need_lse.
2. reduce.cu:641 — the int32 byte-offset overflow ships as a NOTE comment, and need_lse is what makes it reachable.
// NOTE(need_lse): these are int32 byte offsets into the partial buffer and are ...
const int32_t reduce_tile_pos_lse_start = reduce_partial_map_0 * int32_t(Traits::kNumHeadQ);
const int32_t reduce_tile_pos_out_byte_start =
reduce_tile_pos_lse_start * Traits::kSizeDV * int32_t(sizeof(float));Before this PR only genuinely KV-split tiles consumed partial slots; with need_lse every qo tile does, so partial_tile_idx grows by roughly the tile count. Computed thresholds for the instantiated (kNumHeadQ, kSizeDV) pairs, at the default qlen_granularity = 256:
| shape | one slot | int32 offset wraps at partial_tile_idx ≥ |
|---|---|---|
| 16 × 128 (test default) | 8 KiB | 1024 |
64 × 64 (d64 path) |
16 KiB | 512 |
| 128 × 512 (DeepSeek MLA) | 256 KiB | 32 |
MLA_REDUCE_ROUTER:958 instantiates (128, 512), so on the shape this kernel exists for, the offset wraps after ~32 partial tiles. A wrapped negative voffset on a raw buffer load returns zeros or aliases another tile: silently wrong O and final_lse, no fault, no assert. The same int32 offsets are unannotated in the massive path and in d64 (:1069). This needs int64 addressing, or at minimum an AITER_CHECK on pool bytes < 2^31 in mla_reduce_v1 (:1225).
3. aiter/mla.py:1198 — mla_prefill_ps_fwd returns final_lse but has no need_lse parameter and does not build the metadata.
need_lse defaults to false in both the pybind (rocm_ops.hpp:2380) and the Python stub (attention.py:1065). So a caller that does get_ps_metadata_v1(...) with defaults and then mla_prefill_ps_fwd(...) gets every single-TG tile assigned partial_o_loc = -1 (v1_2_host.cuh:192), forming no reduce group — and those rows of final_lse = torch.empty(...) are never written. Uninitialized VRAM with the right shape and dtype, straight into a chunked-prefill LSE merge.
This is also an unannounced API break: element 2 changed from attn_lse [max_partials*256, nhead] to final_lse [total_s, nhead]. Both are 2-D fp32 CUDA tensors, so nothing type-errors. Either plumb need_lse through the wrapper, or fill the buffer with -inf when it can't be produced.
Should fix before merge
4. csrc/kernels/mla/metadata/v1_2_host.cuh:192 — the need_lse invariant is broken for zero-effective-KV tiles.
const bool skip_reduce =
(consuming_blocks == 0) || (!need_lse && current_block_idx == 0);The consuming_blocks == 0 term is unconditional, so a tile whose effective_kv_length rounds to 0 units (context_lens[b] == 0, or a causal tile above the diagonal when kv_len < qo_len) still gets partial_o_loc = -1, is continued by generate_reduce_info (:37), forms no reduce group, and keeps torch.empty contents in both final_lse and O. The invariant this PR establishes — need_lse ⇒ every qo tile is covered by a reduce group — does not hold, and nothing re-establishes it downstream.
The new test can't see it: assert (seq_lens_qo <= seq_lens_kv).all() (:265) guarantees effective_kv_length > 0.
5. reduce.cu:783 (and the verbatim copy at :882) — the guard is correct but the comment attributes it to the wrong mechanism.
// num_split==1 with real partial slot (!=1) means need_lse has been set
// so we need to reduce even this single split tile to get a correct final_lse
else if(num_splits > 1 ||
(num_splits == 1 && params.p_reduce_partial_map[reduce_tile_start] != -1))On the v1_0_device decode path the != -1 test is load-bearing — v1_0_device.cuh:124/137 writes -1 into p_reduce_partial_map, and this is what fixes last round's decode corruption. Good.
On the PS path it is tautological: v1_2_host.cuh:309 builds reduce_partial_map_vec(numel, 0) and generate_reduce_info only ever copies non-negative qlen_granularity * partial_tile_idx values into it; -1 goes into work_info.partial_o_loc, never into the map. So for PS the condition collapses to num_splits >= 1, and it carries none of the need_lse information the comment claims.
Two consequences worth addressing: the comment documents one predicate as if it had a single meaning across two producers with different conventions (and its (!=1) is a typo for !=-1); and the PS-side need_lse intent has no representation in MlaReduceKernelV1Params, which already carries output_lse and use_reduce_final_map and would be the natural home.
6. reduce.cu:583 (and :465) — a new device-side precondition is enforced only by assert, in a bandwidth-critical kernel.
assert(num_splits > 1 || params.use_reduce_final_map);These asserts are live: the JIT compiles with flags_cc = ["-O3", "-std=c++20", "-Wno-unknown-warning-option"] (aiter/jit/core.py:944) and no -DNDEBUG anywhere, including optCompilerConfig.json.
mla_reduce_v1 sets use_reduce_final_map = reduce_final_map.has_value() (:1275), and aiter/mla.py:438, :534 and pa_reduce_v1 all pass None. Combined with the always-true PS gate above, a 1-entry reduce tile on such a caller now enters impl_simple and either (a) __assertfails and aborts the GPU context where base silently skipped, or (b) if ever compiled with NDEBUG, takes reduce_partial_map_1 = reduce_partial_map_0 ⇒ qo_len = 0 ⇒ final_loc = {0,0} ⇒ the seq loop never runs and nothing is written. Either way this belongs as a host-side AITER_CHECK in mla_reduce_v1, not a device assert inside __launch_bounds__(kNumThreads, 8).
(The identical assert+ternary at :465 in impl_massive is unreachable: that path is only entered when num_splits >= kMassiveThreshold = 4.)
7. csrc/kernels/mla/metadata/v1_2_host.cuh:52 — six assert() uses, no <cassert>.
Includes are aiter_hip_common.h, ps.h, v1_comm.cuh, <algorithm>, <iomanip>, <iostream>, <map>, <set>, <utility>, <vector> — none guarantees the assert macro. It compiles today only through a transitive libstdc++ include; on a toolchain where that doesn't hold, the JIT build of module_ps_metadata fails at first call rather than at packaging time. (reduce.cu did get the include.)
Separately, these asserts are the only protection for the newly-tightened max_partials, and assert aborts the process rather than raising a catchable AITER_CHECK naming computed-vs-available sizes. csrc/include/attention_common.cuh:15-22 and csrc/cpp_itfs/pa/pa.cuh:34-38 show the repo's #undef NDEBUG idiom if you want them to survive release builds.
8. aiter/ops/attention.py:1035 — max_partials is now exactly tight, derived in Python, while the code that emits partials is in C++.
max_partials = qo_tile_cnt + (cus_per_cluster - 1)Zero slack, and the two derivations are coupled only by a comment. The bound holds only if the caller passes the same qlen_granularity and a true max_qlen to both get_ps_metadata_info_v1 and get_ps_metadata_v1. Both default to 256, but op_tests passes tile_q // qhead_granularity (16 at gqa_ratio 16) — so a caller that sizes with the default and generates with a smaller granularity gets max_qo_split_per_batch up to 16× too small, and generate_reduce_info's std::copy(..., reduce_partial_map.begin() + partial_idx) writes past the end of the host vector before hipMemcpying corrupted metadata to the device. The sizer also takes no need_lse argument even though the count now depends on it. The # TODO: consider split q to reduce max_works & max_partials directly above invites exactly the change that breaks the bound.
9. csrc/kernels/mla/metadata/v1_2_host.cuh:191 — need_lse=true costs ~4-5× the output-path traffic to produce 4 B of LSE.
Disabling direct-to-O for every qo tile means the reduce for a single-split tile divides by a sum_e_lse that is exactly 1.0 — a pure copy. Per (token, head) at kSizeDV = 512: 2048 B fp32 partial write + 2048 B read + 1024 B bf16 final write = 5120 B, vs 1024 B direct. At batch 16 × 8192 tokens × 128 heads that is ~17 GB → ~86 GB. The if(reduce_tile_start == last_reduce_tile) return false; early-out in kn_mla_reduce_v1_ps (:726) also stops trimming work, since no tile has an empty partial range any more.
Threading need_lse was the right first step, but an LSE-only fast path — having the ASM kernel write final_lse directly for unsplit tiles, where final_lse == attn_lse exactly — would avoid the round trip entirely. Worth at least a follow-up issue if it's out of scope here.
Tests
10. op_tests/test_mla_prefill_ps.py:779 — the sweep filter still doesn't prevent the varlen assert.
if qo_len is not None and qo_len > ctx_len:
# Skip invalid combos in the sweep rather than asserting mid-run.
continueUnder --varlen true, line 255 draws seq_lens_kv[i] = max(min(normalvariate(ctx_lens, ctx_lens/2), ctx_lens), 1) — routinely single digits. --varlen true --qo_len 64 passes the filter (64 ≤ ctx_len) and then trips assert (seq_lens_qo <= seq_lens_kv).all() at :265. @benchmark doesn't catch it, and df.to_csv / calculate_pass_rate run only after the whole itertools.product loop, so hours of 16k-context results are discarded. The filter needs to compare against seq_lens_kv.min() — and a bad LSE should record result='failed' and continue, the way the output check already does.
11. op_tests/test_mla_prefill_ps.py:461 — ctx_len is not a local; it resolves only via a leaked global.
The changed line is (qo_len if qo_len is not None else ctx_len), but the function parameter is ctx_lens (:221). Verified by AST: ctx_len is read inside test_mla_prefill and is neither a parameter nor bound locally. It works only because the module-level sweep at :770 leaks the loop variable, and the file has no __main__ guard.
So from op_tests.test_mla_prefill_ps import test_mla_prefill; test_mla_prefill(..., profile_ps=True) raises NameError — and merely importing the module runs the entire default sweep. Inside the sweep it silently reads the loop's current global, which under varlen is the nominal max rather than the per-case value, so the reported TFLOPs is wrong. (:462 has the same bug pre-existing; :461 is new code propagating it. :239 already computes the identical expression correctly against ctx_lens.)
12. op_tests/test_mla_prefill_ps.py:557 — the new isneginf assert encodes a convention the kernel doesn't implement.
assert torch.equal(asm_lse.isneginf(), lse_ref.isneginf())For a fully-masked row the kernel emits positive INFINITY — reduce.cu:290 (impl_simple), :691 (massive), :1062 (d64) all do ((sum_lse == 0.f) || (sum_lse != sum_lse)) ? INFINITY : ... — while the torch reference's logsumexp gives -inf.
So any config producing a fully-masked query row trips this assert with the misleading message "some tiles did not get an LSE written", when the actual issue is a sign mismatch. Or, worse, it passes vacuously because torch.empty garbage is neither +inf nor -inf on either side — hiding exactly the unwritten row it is meant to catch. The empty-row convention needs pinning down in the kernel and the reference before this check means anything.
13. op_tests/test_mla_prefill_ps.py:741 — --need_lse is a non-swept scalar defaulting to the opposite of the API default.
parser.add_argument("--need_lse", type=dtypes.str2bool, default=True, ...)No nargs, and it's passed as need_lse=args.need_lse at :794, outside itertools.product. Every other behavior axis in this file — including this PR's own --qo_len — is a swept list with nargs="*". So the need_lse=False path, which is what production callers get (rocm_ops.hpp:2380), is never exercised: a regression in the direct-to-O fast path that skip_reduce (v1_2_host.cuh:192) and both reduce dispatch branches touch would ship green. Making it nargs="*", default=[False, True] and folding it into the product would cover both.
Also: us_mla_prefill_ps is now measured on the need_lse=True slow path by default, so the numbers aren't comparable to pre-PR CSVs. And with --need_lse false every row gets lse result='skipped', which _print_pass_rate counts in the denominator, printing LSE: passed 0/N(0.00%) ... failed 0/N(0.00%).
14. aiter/mla.py:1198 — the only in-repo caller of mla_prefill_ps_fwd was deleted in the same change that altered its return value.
grep -rn mla_prefill_ps_fwd --include=*.py now matches only the definition. The test hand-rolls the asm+reduce sequence with duplicated buffer shapes (reduce_partial_map.size(0) * tile_q), so the two copies must stay in lockstep with nothing enforcing it.
While that line is being touched: the wrapper defaults softmax_scale to 1.0 / (v_head_dim ** 0.5) from output.shape[-1] (128) rather than the QK head dim (192) — a 1.22× over-scale on every score, and a correspondingly wrong final_lse, for any caller that omits the argument. Pre-existing, but now nothing exercises that default at all.
Minor
15. csrc/include/rocm_ops.hpp:2379 — the added trailing comma broke the escaped-newline alignment of the PS_METADATA_PYBIND block.
Measured: lines 2359-2378 all place their \ at column 47; line 2379 (py::arg("is_causal") = true,) is at column 48. .clang-format sets AlignEscapedNewlines: Left, and .githooks/pre-commit runs clang-format-18 on C/C++ files, so anyone with the repo hooks installed gets a ~20-line realignment hunk injected into an unrelated commit.
(Scoped to this block deliberately — the file is not clang-format-clean overall at the merge base, so a whole-file check isn't meaningful here.)
Signed-off-by: simondanielsson <[email protected]>
Signed-off-by: simondanielsson <[email protected]>
Signed-off-by: simondanielsson <[email protected]>
…ed completely if return_lse (ROCm#3 & ROCm#4) Signed-off-by: simondanielsson <[email protected]>
Signed-off-by: simondanielsson <[email protected]>
Signed-off-by: simondanielsson <[email protected]>
Signed-off-by: simondanielsson <[email protected]>
Signed-off-by: simondanielsson <[email protected]>
Signed-off-by: simondanielsson <[email protected]>
Signed-off-by: simondanielsson <[email protected]>
Signed-off-by: simondanielsson <[email protected]>
…final-lse Signed-off-by: simondanielsson <[email protected]>
|
Thanks! Fixed most comments, and the ones not fixed I comment on below. Please have a look @valarLip 🙏
Agree with this, I should file a separate issue to have the asm team help update the kernel to write final_lse directly!
Since it's unrelated to this work I'd suggest we do not include this in this PR to avoid increasing its scope. Happy to hear your thoughts though.
Fixed, but I kept the partial-lse offsets as int32 since it's kSizeDV times smaller than the output offsets so you'd need a 1TiB partial pool to have it wrap.
Didn't add a need_lse argument on the sizer because qo_tile_cnt already bounds it. Added new AITER_CHECKs catch it if that stops being true. |
|
Re-ran validation after the latest changes (int64 slot offsets, Unit testsNon-causal, 8192: Causal, 4096 (the warning is the usual fp8 roundin, wrapper checks pass): Sweep: Huge 100k context + 512-token extend still fine: MLA reduce kernelOK: |
|
CI errors look transient, can we re-run? Thanks e2e validationAlso validated e2e in vLLM running DeepSeek-V3 with this causal and non-causal prefill kernel (with FP8 KV cache) in 8xMI350. GSM8kGSM8k accuracy unchanged: PR vllm-project/vllm#44544 with aiter built in this branch:
vllm main
TracesZooming in on a mixed batch with chunked prefills: Causal works as prefill as expected (causal ps kernel + reduce) |


Motivation
Correct the LSE output from the non-causal PS ASM MLA prefill kernel.
Context
vllm-project/vllm#44544 integrates the non-causal prefill kernel into vLLM. However, using the kernel shipped with AITER v0.1.19 yields an accuracy degradation of ~3pp on GSM8k with DeepSeekv3. As this bug report reports, this has to do with incorrect LSE's being calculated and returned from the kernel. The accuracy degradation disappears when disabling chunked prefill, implying the issue is in the non-causal path.
AFAIK no other frameworks (SGL, ATOM) use the non-causal ASM PS prefill kernel for chunked contexts (they default to FA for those batches), why this haven't been spotted and/or fixed earlier.
vllm-project/vllm#44544 adds this non-causal kernel to vLLM, where it gives identical accuracy results to flash attn, showing it works.
Technical Details
We needed to change:
Test Plan
Test Result
Huge 100k context length + 512 tokens extend also fine:
Question to experts
Somewhat unrelated to the PR.
I can see from traces after integrating this non-causal kernel into vLLM that calling
aiter::get_ps_metadata_v1yields a host-device sync from 5 memcpys taking place insideget_ps_metadata_v1_2_host.Do you have ideas on how we coulkd get rid of this? Is the best option to re-write this as device-side computation instead of a host-side one with memcpys? If you think this sounds like something we should tackle I'll open an issue.
After inte
Submission Checklist