Skip to content

[HIP] [FlyDSL] [Bugfix][MLA] Correct final_lse in PS MLA prefill kernel for chunked prefill - #3606

Merged
valarLip merged 62 commits into
ROCm:mainfrom
simondanielsson:fix/mla-prefill-ps-final-lse
Sep 11, 2026
Merged

valarLip merged 62 commits into
ROCm:mainfrom
simondanielsson:fix/mla-prefill-ps-final-lse

Conversation

@simondanielsson

@simondanielsson simondanielsson commented Jun 8, 2026 •

Copy link
Copy Markdown
Contributor

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:

  1. Allow reducing non-split tiles, since it's the reduction kernel that emits the final_lse used in chunked prefill
  2. size the workspace correctly, accounting for that partials can be created even for non-split tiles (when we need_lse)
  3. return final_lse instead of attn_lse from wrapper

Test Plan

  1. Validate main produces incorrect LSE's for non-causal kernel
git switch fix/mla-prefill-ps-final-lse # this branch
# revert the kernel fixes (but keep the updated test)
git checkout main -- csrc/kernels/mla/metadata/v1_2_host.cuh csrc/kernels/mla/reduce.cu
AITER_REBUILD=1 python3 op_tests/test_mla_prefill_ps.py -c 8192 -b 16 -n 16 --causal false --qo_len 64
  1. Tests run successfully on this branch:
git switch fix/mla-prefill-ps-final-lse
python3 op_tests/test_mla_prefill_ps.py -qkh 192 -vh 128 -n 1 -c 4096 -b 1 --causal true
python3 op_tests/test_mla_prefill_ps.py -qkh 192 -vh 128 -n 1 -c 8192 -b 1 --causal false
python3 op_tests/test_mla_prefill_ps.py -c 1200 8192 16384 -b 16 -n 16 --causal false --qo_len 8 64 512
python3 op_tests/test_mla_prefill_ps.py -qkh 192 -vh 128 -n 1 -c 102400 -b 1 --causal false --qo_len 512

Test Result

  1. Fails on main, incorrect LSE
[aiter] mla_prefill_ps    [torch vs aiter_asm]: us......[checkAllclose atol=0.05 rtol=0.05 passed~]
[aiter] mla_prefill_lse   [torch vs aiter_asm]: us......[checkAllclose atol=0.05 rtol=0.05 failed!]
    a    : torch.Size([16384])
           tensor([9.4984, 9.5649, 9.5843, 9.5271, 9.5342, 9.4879, 9.4919, 9.4832],
       device='cuda:0')
    b    : torch.Size([16384])
           tensor([0., 0., 0., 0., 0., 0., 0., 0.], device='cuda:0')
    delta:
           tensor([9.4984, 9.5649, 9.5843, 9.5271, 9.5342, 9.4879, 9.4919, 9.4832],
       device='cuda:0')
[aiter] -->max abs delta:9.728719711303711, delta details: 100.0% (16384 of 16384) elements
[aiter] mla_prefill_ps summary (markdown):
|   ctx_lens |   batch_size |   num_head |   qk_head_dim |   v_head_dim | dtype               | kv_dtype            |   block_size | varlen   | is_causal   |   qo_len | load_metadata   | dump_metadata   | profile_ps   | skip_reference   |   us_mla_prefill_ps |   err fp8 | acc result   |   err lse | lse result   |   lse max_abs_diff |   lse mean_abs_diff |   lse max_rel_err |   lse mean_rel_err |
|-----------:|-------------:|-----------:|--------------:|-------------:|:--------------------|:--------------------|-------------:|:---------|:------------|---------:|:----------------|:----------------|:-------------|:-----------------|--------------------:|----------:|:-------------|----------:|:-------------|-------------------:|--------------------:|------------------:|-------------------:|
|       8192 |           16 |         16 |           192 |          128 | torch.float8_e4m3fn | torch.float8_e4m3fn |            1 | False    | False       |       64 | False           | False           | False        | False            |             256.616 |         0 | passed       |         1 | failed       |            9.72872 |             9.51081 |                 1 |                  1 |
[aiter] Output: passed 1/1(100.00%) warning 0/1(0.00%) failed 0/1(0.00%)
[aiter] LSE: passed 0/1(0.00%) warning 0/1(0.00%) failed 1/1(100.00%)
  1. All test passes.
$ python3 op_tests/test_mla_prefill_ps.py -qkh 192 -vh 128 -n 1 -c 4096 -b 1 --causal true
|   ctx_lens |   batch_size |   num_head |   qk_head_dim |   v_head_dim | dtype               | kv_dtype            |   block_size | varlen   | is_causal   |   qo_len | load_metadata   | dump_metadata   | profile_ps   | skip_reference   |   us_mla_prefill_ps |     err fp8 | acc result   |   err lse | lse result   |   lse max_abs_diff |   lse mean_abs_diff |   lse max_rel_err |   lse mean_rel_err |
|-----------:|-------------:|-----------:|--------------:|-------------:|:--------------------|:--------------------|-------------:|:---------|:------------|---------:|:----------------|:----------------|:-------------|:-----------------|--------------------:|------------:|:-------------|----------:|:-------------|-------------------:|--------------------:|------------------:|-------------------:|
|       4096 |            1 |          1 |           192 |          128 | torch.float8_e4m3fn | torch.float8_e4m3fn |            1 | False    | True        |     4096 | False           | False           | False        | False            |             37.7739 | 5.53131e-05 | warning      |         0 | passed       |          0.0498431 |           0.0034463 |           2.09234 |         0.00099875 |
[aiter] Output: passed 0/1(0.00%) warning 1/1(100.00%) failed 0/1(0.00%)
[aiter] LSE: passed 1/1(100.00%) warning 0/1(0.00%) failed 0/1(0.00%)
$ python3 op_tests/test_mla_prefill_ps.py -qkh 192 -vh 128 -n 1 -c 8192 -b 1 --causal false
[aiter] import [module_aiter_core] under /home/pedaniel/repos/aiter/.venv/lib/python3.12/site-packages/aiter/jit/module_aiter_core.so
[aiter]
calling test_mla_prefill(ctx_lens                     = 8192,
                         batch_size                   = 1,
                         num_head                     = 1,
                         qk_head_dim                  = 192,
                         v_head_dim                   = 128,
                         dtype                        = torch.float8_e4m3fn,
                         kv_dtype                     = torch.float8_e4m3fn,
                         block_size                   = 1,
                         varlen                       = False,
                         is_causal                    = False,
                         load_metadata                = False,
                         dump_metadata                = False,
                         profile_ps                   = False,
                         skip_reference               = False)
[aiter] import [module_ps_metadata] under /home/pedaniel/repos/aiter/.venv/lib/python3.12/site-packages/aiter/jit/module_ps_metadata.so
[aiter] LoadKernel: _ZN5aiter40mla_pfl_qh192_vh128_m32x8_n128x1_causal0E hsaco: /home/pedaniel/repos/aiter/.venv/lib/python3.12/site-packages/aiter_meta/hsa//gfx950/mla/mla_pfl_qh192_vh128_m32x8_n128x1_causal0.co
/home/pedaniel/repos/aiter/.venv/lib/python3.12/site-packages/torch/profiler/profiler.py:272: UserWarning: Warning: Profiler clears events at the end of each cycle.Only events from the current cycle will be reported.To keep events across cycles, set acc_events=True.
  _warn_once(
USDT:2026-06-08 08:59:21 303490:303490 ActivityProfilerController.cpp:415] profiler_start
USDT:2026-06-08 08:59:21 303490:303490 ActivityProfilerController.cpp:455] profiler_stop
[W608 08:59:21.930083243 collection.cpp:1182] Warning: ROCTracer produced duplicate flow start: 4 (function operator())
[aiter] import [module_mla_reduce] under /home/pedaniel/repos/aiter/.venv/lib/python3.12/site-packages/aiter/jit/module_mla_reduce.so
USDT:2026-06-08 08:59:21 303490:303490 ActivityProfilerController.cpp:415] profiler_start
USDT:2026-06-08 08:59:21 303490:303490 ActivityProfilerController.cpp:455] profiler_stop
[aiter] mla_prefill_ps    [torch vs aiter_asm]: us......[checkAllclose atol=0.05 rtol=0.05 passed~]
[aiter] mla_prefill_lse   [torch vs aiter_asm]: us......[checkAllclose atol=0.05 rtol=0.05 passed~]
[aiter] mla_prefill_ps summary (markdown):
|   ctx_lens |   batch_size |   num_head |   qk_head_dim |   v_head_dim | dtype               | kv_dtype            |   block_size | varlen   | is_causal   | load_metadata   | dump_metadata   | profile_ps   | skip_reference   |   us_mla_prefill_ps |   err fp8 | acc result   |   err lse | lse result   |   lse max_abs_diff |   lse mean_abs_diff |   lse max_rel_err |   lse mean_rel_err |
|-----------:|-------------:|-----------:|--------------:|-------------:|:--------------------|:--------------------|-------------:|:---------|:------------|:----------------|:----------------|:-------------|:-----------------|--------------------:|----------:|:-------------|----------:|:-------------|-------------------:|--------------------:|------------------:|-------------------:|
|       8192 |            1 |          1 |           192 |          128 | torch.float8_e4m3fn | torch.float8_e4m3fn |            1 | False    | False       | False           | False           | False        | False            |             49.8771 |         0 | passed       |         0 | passed       |          0.0152264 |          0.00302858 |        0.00159649 |        0.000318251 |
[aiter] Output: passed 1/1(100.00%) warning 0/1(0.00%) failed 0/1(0.00%)
[aiter] LSE: passed 1/1(100.00%) warning 0/1(0.00%) failed 0/1(0.00%)
$ python3 op_tests/test_mla_prefill_ps.py -c 1200 8192 16384 -b 16 -n 16 --causal false --qo_len 8 64 512
|   ctx_lens |   batch_size |   num_head |   qk_head_dim |   v_head_dim | dtype               | kv_dtype            |   block_size | varlen   | is_causal   |   qo_len | load_metadata   | dump_metadata   | profile_ps   | skip_reference   |   us_mla_prefill_ps |   err fp8 | acc result   |   err lse | lse result   |   lse max_abs_diff |   lse mean_abs_diff |   lse max_rel_err |   lse mean_rel_err |
|-----------:|-------------:|-----------:|--------------:|-------------:|:--------------------|:--------------------|-------------:|:---------|:------------|---------:|:----------------|:----------------|:-------------|:-----------------|--------------------:|----------:|:-------------|----------:|:-------------|-------------------:|--------------------:|------------------:|-------------------:|
|       1200 |           16 |         16 |           192 |          128 | torch.float8_e4m3fn | torch.float8_e4m3fn |            1 | False    | False       |        8 | False           | False           | False        | False            |             55.3607 |         0 | passed       |         0 | passed       |          0.0210309 |          0.00350829 |        0.00270641 |        0.000461878 |
|       1200 |           16 |         16 |           192 |          128 | torch.float8_e4m3fn | torch.float8_e4m3fn |            1 | False    | False       |       64 | False           | False           | False        | False            |             77.1186 |         0 | passed       |         0 | passed       |          0.0241623 |          0.00327467 |        0.00313123 |        0.000431029 |
|       1200 |           16 |         16 |           192 |          128 | torch.float8_e4m3fn | torch.float8_e4m3fn |            1 | False    | False       |      512 | False           | False           | False        | False            |            137.659  |         0 | passed       |         0 | passed       |          0.0199704 |          0.00304723 |        0.00255882 |        0.00040115  |
|       8192 |           16 |         16 |           192 |          128 | torch.float8_e4m3fn | torch.float8_e4m3fn |            1 | False    | False       |        8 | False           | False           | False        | False            |            229.692  |         0 | passed       |         0 | passed       |          0.0130825 |          0.00290009 |        0.00136965 |        0.00030466  |
|       8192 |           16 |         16 |           192 |          128 | torch.float8_e4m3fn | torch.float8_e4m3fn |            1 | False    | False       |       64 | False           | False           | False        | False            |            263.113  |         0 | passed       |         0 | passed       |          0.0144272 |          0.00269423 |        0.00149811 |        0.000283149 |
|       8192 |           16 |         16 |           192 |          128 | torch.float8_e4m3fn | torch.float8_e4m3fn |            1 | False    | False       |      512 | False           | False           | False        | False            |            538.601  |         0 | passed       |         0 | passed       |          0.0149899 |          0.00269361 |        0.00155649 |        0.000283062 |
|      16384 |           16 |         16 |           192 |          128 | torch.float8_e4m3fn | torch.float8_e4m3fn |            1 | False    | False       |        8 | False           | False           | False        | False            |            470.746  |         0 | passed       |         0 | passed       |          0.0118876 |          0.00268014 |        0.00114751 |        0.000262612 |
|      16384 |           16 |         16 |           192 |          128 | torch.float8_e4m3fn | torch.float8_e4m3fn |            1 | False    | False       |       64 | False           | False           | False        | False            |            523.362  |         0 | passed       |         0 | passed       |          0.0153761 |          0.00287412 |        0.00149573 |        0.000281534 |
|      16384 |           16 |         16 |           192 |          128 | torch.float8_e4m3fn | torch.float8_e4m3fn |            1 | False    | False       |      512 | False           | False           | False        | False            |           1082.52   |         0 | passed       |         0 | passed       |          0.0152369 |          0.00264482 |        0.00148217 |        0.000259062 |
[aiter] Output: passed 9/9(100.00%) warning 0/9(0.00%) failed 0/9(0.00%)
[aiter] LSE: passed 9/9(100.00%) warning 0/9(0.00%) failed 0/9(0.00%)

Huge 100k context length + 512 tokens extend also fine:

python3 op_tests/test_mla_prefill_ps.py -qkh 192 -vh 128 -n 1 -c 102400 -b 1 --causal false --qo_len 512
|   ctx_lens |   batch_size |   num_head |   qk_head_dim |   v_head_dim | dtype               | kv_dtype            |   block_size | varlen   | is_causal   |   qo_len | need_lse
 | load_metadata   | dump_metadata   | profile_ps   | skip_reference   |   us_mla_prefill_ps |   err fp8 | acc result   |   lse max_abs_diff |   lse mean_abs_diff |   lse
 max_rel_err |   lse mean_rel_err |   err lse | lse result   |
 |-----------:|-------------:|-----------:|--------------:|-------------:|:--------------------|:--------------------|-------------:|:---------|:------------|---------:|:----------
 -|:----------------|:----------------|:-------------|:-----------------|--------------------:|----------:|:-------------|-------------------:|--------------------:|---------------
 ---:|-------------------:|----------:|:-------------|
 |     102400 |            1 |          1 |           192 |          128 | torch.float8_e4m3fn | torch.float8_e4m3fn |            1 | False    | False       |      512 | True
 | False           | False           | False        | False            |             156.539 |         0 | passed       |          0.0111656 |          0.00276231 |
 0.000924684 |        0.000229404 |         0 | passed       |
 [aiter] Output: passed 1/1(100.00%) warning 0/1(0.00%) failed 0/1(0.00%)
 [aiter] LSE: passed 1/1(100.00%) warning 0/1(0.00%) failed 0/1(0.00%)

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_v1 yields a host-device sync from 5 memcpys taking place inside get_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.

image

After inte

Submission Checklist

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.
@github-actions

github-actions Bot commented Jun 8, 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: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 3606 --add-label <label>

@simondanielsson simondanielsson changed the title [Bugfix][MLA] Correct PS MLA prefill final_lse for chunked prefill [Bugfix][MLA] Correct final_lse in PS MLA prefill kernel for chunked prefill Jun 8, 2026
@simondanielsson
simondanielsson marked this pull request as ready for review June 11, 2026 11:23
@simondanielsson
simondanielsson requested a review from a team June 11, 2026 11:23
@zufayu
zufayu requested a review from amd-ruitang3 June 26, 2026 08:55
@Wanzizhu

Wanzizhu commented Jul 3, 2026

Copy link
Copy Markdown
Contributor

In theory, get_ps_metadata only needs to be called once per decode step, so the host-device sync overhead can be amortized across all layers in that step — is this showing up as a meaningful bottleneck in your profiling?

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

@simondanielsson

Copy link
Copy Markdown
Contributor Author

In theory, get_ps_metadata only needs to be called once per decode step, so the host-device sync overhead can be amortized across all layers in that step — is this showing up as a meaningful bottleneck in your profiling?

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.

  • You are right. At the moment the syncs are not bottlenecking perf when called just once per layer. It's only the host-side trace that looks almost overly busy, but device is kept busy nonetheless.
  • Thanks for the reference, we'll keep this in mind if for any reason in the future this does become a bottleneck. Then we can write a similar device-side func.

@jamestangg
jamestangg requested a review from Wanzizhu July 7, 2026 14:06
@ChuanLi1101

Copy link
Copy Markdown
Contributor

Reviewed the Python side and the fix rationale — the four changes (workspace sizing for non-causal KV tiles, dropping the partial_o_loc=-1 exclusion, enabling single-KV-split reduction, returning final_lse) are coherent and the LSE test evidence is convincing. Two things before this is merge-ready, since it changes prefill accuracy:

  1. Please trigger the accuracy CI (ci:vllm + ci:sglang labels) so we get a DeepSeek/Kimi accuracy signal on the causal path and confirm no regression there — the current rollup shows no accuracy job has run.
  2. The behavioral risk is in the C++ (csrc/kernels/mla/reduce.cu, csrc/kernels/mla/metadata/v1_2_host.cuh); could a kernel maintainer (@Wanzizhu) sign off on the reduce/metadata changes?

The host-side memcpy sync question is fine to defer as you and @Wanzizhu agreed — not a blocker for this PR.

@simondanielsson

Copy link
Copy Markdown
Contributor Author
  1. Please trigger the accuracy CI (ci:vllm + ci:sglang labels) so we get a DeepSeek/Kimi accuracy signal on the causal path and confirm no regression there — the current rollup shows no accuracy job has run.

Thanks @ChuanLi1101! Who can I ask for help in triggering the accuracy CI?

@valarLip valarLip left a comment

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.

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 -1 sentinel corruption on the decode path is fixed — reduce.cu:783/882 now guards with p_reduce_partial_map[reduce_tile_start] != -1, and v1_0_device.cuh:137 does write -1 into that map, so the check is load-bearing there.
  • mla_reduce_v1_impl_simple's unconditional p_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_lse rather than removed.
  • max_partials is now the tight bound: qo_tile_cnt + (cus_per_cluster - 1) (attention.py:1035).
  • generate_reduce_info has bounds asserts.
  • The LSE check now has a real isneginf structural 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.
    continue

Under --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.)

@github-actions github-actions Bot changed the title [HIP] [Bugfix][MLA] Correct final_lse in PS MLA prefill kernel for chunked prefill [HIP] [FlyDSL] [Bugfix][MLA] Correct final_lse in PS MLA prefill kernel for chunked prefill Sep 9, 2026
@github-actions github-actions Bot added the FlyDSL label Sep 9, 2026
@simondanielsson

Copy link
Copy Markdown
Contributor Author

Thanks! Fixed most comments, and the ones not fixed I comment on below. Please have a look @valarLip 🙏

  1. 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.
    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.

Agree with this, I should file a separate issue to have the asm team help update the kernel to write final_lse directly!

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.

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.

  1. reduce.cu:641 — the int32 byte-offset overflow ships as a NOTE comment, and need_lse is what makes it reachable.

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.

  1. aiter/ops/attention.py:1035 — max_partials is now exactly tight, derived in Python, while the code that emits partials is in C++.
    The sizer also takes no need_lse argument even though the count now depends on it.

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.

@simondanielsson

Copy link
Copy Markdown
Contributor Author

Re-ran validation after the latest changes (int64 slot offsets, need_lse flow, wrapper-level mla_prefill_ps_fwd test, and the flydsl reduce alignment).

Unit tests

Non-causal, 8192:

python3 op_tests/test_mla_prefill_ps.py -qkh 192 -vh 128 -n 1 -c 8192 -b 1 --causal false
[aiter] mla_prefill_ps_fwd[hand-rolled vs wrapper]: us......[checkAllclose atol=0.05 rtol=0.05 passed~]
[aiter] mla_prefill_ps_fwd_lse[hand-rolled vs wrapper]: us......[checkAllclose atol=0.03 rtol=0 passed~]
[aiter] mla_prefill_ps    [torch vs aiter_asm]: us......[checkAllclose atol=0.05 rtol=0.05 passed~]
[aiter] mla_prefill_lse   [torch vs aiter_asm]: us......[checkAllclose atol=0.03 rtol=0 passed~]
|   ctx_lens |   batch_size |   num_head |   qk_head_dim |   v_head_dim | dtype               | kv_dtype            |   block_size | varlen   | is_causal   |   qo_len | need_lse   | load_metadata   | dump_metadata   | profile_ps   | skip_reference   |   us_mla_prefill_ps | wrapper result   |   err fp8 | acc result   |   err lse | lse result   |   lse max_abs_diff |   lse mean_abs_diff |   lse max_rel_err |   lse mean_rel_err |
|-----------:|-------------:|-----------:|--------------:|-------------:|:--------------------|:--------------------|-------------:|:---------|:------------|---------:|:-----------|:----------------|:----------------|:-------------|:-----------------|--------------------:|:-----------------|----------:|:-------------|----------:|:-------------|-------------------:|--------------------:|------------------:|-------------------:|
|       8192 |            1 |          1 |           192 |          128 | torch.float8_e4m3fn | torch.float8_e4m3fn |            1 | False    | False       |     8192 | False      | False           | False           | False        | False            |             49.8827 | passed           |         0 | passed       |         0 | skipped      |         nan        |        nan          |       nan         |      nan           |
|       8192 |            1 |          1 |           192 |          128 | torch.float8_e4m3fn | torch.float8_e4m3fn |            1 | False    | False       |     8192 | True       | False           | False           | False        | False            |            189.707  | passed           |         0 | passed       |         0 | passed       |           0.013628 |          0.00274948 |         0.0014363 |        0.000288965 |
[aiter] Output: passed 2/2(100.00%) warning 0/2(0.00%) failed 0/2(0.00%)
[aiter] LSE: passed 1/1(100.00%) warning 0/1(0.00%) failed 0/1(0.00%)
[aiter] mla_prefill_ps_fwd: passed 2/2(100.00%) warning 0/2(0.00%) failed 0/2(0.00%)

Causal, 4096 (the warning is the usual fp8 roundin, wrapper checks pass):

python3 op_tests/test_mla_prefill_ps.py -qkh 192 -vh 128 -n 1 -c 4096 -b 1 --causal true
[aiter] mla_prefill_ps_fwd[hand-rolled vs wrapper]: us......[checkAllclose atol=0.05 rtol=0.05 passed~]
[aiter] mla_prefill_ps_fwd_lse[hand-rolled vs wrapper]: us......[checkAllclose atol=0.03 rtol=0 passed~]
[aiter] mla_prefill_ps    [torch vs aiter_asm]: us......[checkAllclose atol=0.05 rtol=0.05 warning!] a and b results are not all close
[aiter] -->max abs delta:0.115234375, delta details: 0.0% (11 of 524288) elements
[aiter] mla_prefill_lse   [torch vs aiter_asm]: us......[checkAllclose atol=0.03 rtol=0 warning!] a and b results are not all close
[aiter] -->max abs delta:0.09484326839447021, delta details: 0.1% (3 of 4096) elements
|   ctx_lens |   batch_size |   num_head |   qk_head_dim |   v_head_dim | dtype               | kv_dtype            |   block_size | varlen   | is_causal   |   qo_len | need_lse   | load_metadata   | dump_metadata   | profile_ps   | skip_reference   |   us_mla_prefill_ps | wrapper result   |     err fp8 | acc result   |     err lse | lse result   |   lse max_abs_diff |   lse mean_abs_diff |   lse max_rel_err |   lse mean_rel_err |
|-----------:|-------------:|-----------:|--------------:|-------------:|:--------------------|:--------------------|-------------:|:---------|:------------|---------:|:-----------|:----------------|:----------------|:-------------|:-----------------|--------------------:|:-----------------|------------:|:-------------|------------:|:-------------|-------------------:|--------------------:|------------------:|-------------------:|
|       4096 |            1 |          1 |           192 |          128 | torch.float8_e4m3fn | torch.float8_e4m3fn |            1 | False    | True        |     4096 | False      | False           | False           | False        | False            |             38.0733 | passed           | 2.09808e-05 | warning      | 0           | skipped      |        nan         |        nan          |       nan         |      nan           |
|       4096 |            1 |          1 |           192 |          128 | torch.float8_e4m3fn | torch.float8_e4m3fn |            1 | False    | True        |     4096 | True       | False           | False           | False        | False            |             43.2343 | passed           | 2.09808e-05 | warning      | 0.000732422 | warning      |          0.0948433 |          0.00323885 |         0.0946244 |        0.000472133 |
[aiter] Output: passed 0/2(0.00%) warning 2/2(100.00%) failed 0/2(0.00%)
[aiter] LSE: passed 0/1(0.00%) warning 1/1(100.00%) failed 0/1(0.00%)
[aiter] mla_prefill_ps_fwd: passed 2/2(100.00%) warning 0/2(0.00%) failed 0/2(0.00%)

Sweep:

python3 op_tests/test_mla_prefill_ps.py -c 1200 8192 16384 -b 16 -n 16 --causal false --qo_len 8 64 512
|   ctx_lens |   batch_size |   num_head |   qk_head_dim |   v_head_dim | dtype               | kv_dtype            |   block_size | varlen   | is_causal   |   qo_len | need_lse   | load_metadata   | dump_metadata   | profile_ps   | skip_reference   |   us_mla_prefill_ps | wrapper result   |   err fp8 | acc result   |   err lse | lse result   |   lse max_abs_diff |   lse mean_abs_diff |   lse max_rel_err |   lse mean_rel_err |
|-----------:|-------------:|-----------:|--------------:|-------------:|:--------------------|:--------------------|-------------:|:---------|:------------|---------:|:-----------|:----------------|:----------------|:-------------|:-----------------|--------------------:|:-----------------|----------:|:-------------|----------:|:-------------|-------------------:|--------------------:|------------------:|-------------------:|
|       1200 |           16 |         16 |           192 |          128 | torch.float8_e4m3fn | torch.float8_e4m3fn |            1 | False    | False       |        8 | False      | False           | False           | False        | False            |             89.6327 | passed           |         0 | passed       |         0 | skipped      |        nan         |        nan          |      nan          |      nan           |
|       1200 |           16 |         16 |           192 |          128 | torch.float8_e4m3fn | torch.float8_e4m3fn |            1 | False    | False       |        8 | True       | False           | False           | False        | False            |             59.3138 | passed           |         0 | passed       |         0 | passed       |          0.0154648 |          0.00304602 |        0.00200171 |        0.000401045 |
|       1200 |           16 |         16 |           192 |          128 | torch.float8_e4m3fn | torch.float8_e4m3fn |            1 | False    | False       |       64 | False      | False           | False           | False        | False            |             57.2945 | passed           |         0 | passed       |         0 | skipped      |        nan         |        nan          |      nan          |      nan           |
|       1200 |           16 |         16 |           192 |          128 | torch.float8_e4m3fn | torch.float8_e4m3fn |            1 | False    | False       |       64 | True       | False           | False           | False        | False            |             76.3747 | passed           |         0 | passed       |         0 | passed       |          0.0171232 |          0.00301688 |        0.00220812 |        0.00039717  |
|       1200 |           16 |         16 |           192 |          128 | torch.float8_e4m3fn | torch.float8_e4m3fn |            1 | False    | False       |      512 | False      | False           | False           | False        | False            |            103.774  | passed           |         0 | passed       |         0 | skipped      |        nan         |        nan          |      nan          |      nan           |
|       1200 |           16 |         16 |           192 |          128 | torch.float8_e4m3fn | torch.float8_e4m3fn |            1 | False    | False       |      512 | True       | False           | False           | False        | False            |            145.633  | passed           |         0 | passed       |         0 | passed       |          0.0205021 |          0.00311632 |        0.00265977 |        0.000410247 |
|       8192 |           16 |         16 |           192 |          128 | torch.float8_e4m3fn | torch.float8_e4m3fn |            1 | False    | False       |        8 | False      | False           | False           | False        | False            |            179.422  | passed           |         0 | passed       |         0 | skipped      |        nan         |        nan          |      nan          |      nan           |
|       8192 |           16 |         16 |           192 |          128 | torch.float8_e4m3fn | torch.float8_e4m3fn |            1 | False    | False       |        8 | True       | False           | False           | False        | False            |            192.502  | passed           |         0 | passed       |         0 | passed       |          0.0137272 |          0.00277828 |        0.00142453 |        0.000291914 |
|       8192 |           16 |         16 |           192 |          128 | torch.float8_e4m3fn | torch.float8_e4m3fn |            1 | False    | False       |       64 | False      | False           | False           | False        | False            |            199.819  | passed           |         0 | passed       |         0 | skipped      |        nan         |        nan          |      nan          |      nan           |
|       8192 |           16 |         16 |           192 |          128 | torch.float8_e4m3fn | torch.float8_e4m3fn |            1 | False    | False       |       64 | True       | False           | False           | False        | False            |            216.178  | passed           |         0 | passed       |         0 | passed       |          0.017498  |          0.00289513 |        0.00182742 |        0.000304261 |
|       8192 |           16 |         16 |           192 |          128 | torch.float8_e4m3fn | torch.float8_e4m3fn |            1 | False    | False       |      512 | False      | False           | False           | False        | False            |            415.564  | passed           |         0 | passed       |         0 | skipped      |        nan         |        nan          |      nan          |      nan           |
|       8192 |           16 |         16 |           192 |          128 | torch.float8_e4m3fn | torch.float8_e4m3fn |            1 | False    | False       |      512 | True       | False           | False           | False        | False            |            498.59   | passed           |         0 | passed       |         0 | passed       |          0.0166426 |          0.00268396 |        0.00173034 |        0.000282046 |
|      16384 |           16 |         16 |           192 |          128 | torch.float8_e4m3fn | torch.float8_e4m3fn |            1 | False    | False       |        8 | False      | False           | False           | False        | False            |            402.445  | passed           |         0 | passed       |         0 | skipped      |        nan         |        nan          |      nan          |      nan           |
|      16384 |           16 |         16 |           192 |          128 | torch.float8_e4m3fn | torch.float8_e4m3fn |            1 | False    | False       |        8 | True       | False           | False           | False        | False            |            366.012  | passed           |         0 | passed       |         0 | passed       |          0.0146084 |          0.00263505 |        0.00142689 |        0.000258073 |
|      16384 |           16 |         16 |           192 |          128 | torch.float8_e4m3fn | torch.float8_e4m3fn |            1 | False    | False       |       64 | False      | False           | False           | False        | False            |            450.385  | passed           |         0 | passed       |         0 | skipped      |        nan         |        nan          |      nan          |      nan           |
|      16384 |           16 |         16 |           192 |          128 | torch.float8_e4m3fn | torch.float8_e4m3fn |            1 | False    | False       |       64 | True       | False           | False           | False        | False            |            453.313  | passed           |         0 | passed       |         0 | passed       |          0.0203066 |          0.0036046  |        0.00196871 |        0.000353056 |
|      16384 |           16 |         16 |           192 |          128 | torch.float8_e4m3fn | torch.float8_e4m3fn |            1 | False    | False       |      512 | False      | False           | False           | False        | False            |            978.053  | passed           |         0 | passed       |         0 | skipped      |        nan         |        nan          |      nan          |      nan           |
|      16384 |           16 |         16 |           192 |          128 | torch.float8_e4m3fn | torch.float8_e4m3fn |            1 | False    | False       |      512 | True       | False           | False           | False        | False            |           1085.58   | passed           |         0 | passed       |         0 | passed       |          0.0164118 |          0.00293098 |        0.00159988 |        0.000287096 |
[aiter] Output: passed 18/18(100.00%) warning 0/18(0.00%) failed 0/18(0.00%)
[aiter] LSE: passed 9/9(100.00%) warning 0/9(0.00%) failed 0/9(0.00%)
[aiter] mla_prefill_ps_fwd: passed 18/18(100.00%) warning 0/18(0.00%) failed 0/18(0.00%)

Huge 100k context + 512-token extend still fine:

python3 op_tests/test_mla_prefill_ps.py -qkh 192 -vh 128 -n 1 -c 102400 -b 1 --causal false --qo_len 512
|   ctx_lens |   batch_size |   num_head |   qk_head_dim |   v_head_dim | dtype               | kv_dtype            |   block_size | varlen   | is_causal   |   qo_len | need_lse   | load_metadata   | dump_metadata   | profile_ps   | skip_reference   |   us_mla_prefill_ps | wrapper result   |   err fp8 | acc result   |   err lse | lse result   |   lse max_abs_diff |   lse mean_abs_diff |   lse max_rel_err |   lse mean_rel_err |
|-----------:|-------------:|-----------:|--------------:|-------------:|:--------------------|:--------------------|-------------:|:---------|:------------|---------:|:-----------|:----------------|:----------------|:-------------|:-----------------|--------------------:|:-----------------|----------:|:-------------|----------:|:-------------|-------------------:|--------------------:|------------------:|-------------------:|
|     102400 |            1 |          1 |           192 |          128 | torch.float8_e4m3fn | torch.float8_e4m3fn |            1 | False    | False       |      512 | False      | False           | False           | False        | False            |             94.3355 | passed           |         0 | passed       |         0 | skipped      |        nan         |        nan          |     nan           |      nan           |
|     102400 |            1 |          1 |           192 |          128 | torch.float8_e4m3fn | torch.float8_e4m3fn |            1 | False    | False       |      512 | True       | False           | False           | False        | False            |             93.2969 | passed           |         0 | passed       |         0 | passed       |          0.0102844 |          0.00255029 |       0.000846114 |        0.000211807 |
[aiter] Output: passed 2/2(100.00%) warning 0/2(0.00%) failed 0/2(0.00%)
[aiter] LSE: passed 1/1(100.00%) warning 0/1(0.00%) failed 0/1(0.00%)
[aiter] mla_prefill_ps_fwd: passed 2/2(100.00%) warning 0/2(0.00%) failed 0/2(0.00%)

MLA reduce kernel

OK:

python3 op_tests/test_mla_reduce.py
| splits         |   nhead |   dv | dtype    |   qo_len |     us |   GB/s | pass   |
|:---------------|--------:|-----:|:---------|---------:|-------:|-------:|:-------|
| [2]            |       1 |  128 | bfloat16 |        1 |   3.17 |    0.4 | True   |
| [3, 2]         |       1 |  128 | bfloat16 |        1 |   3.94 |    0.8 | True   |
| [300]          |       1 |  128 | bfloat16 |        1 |  82.34 |    1.9 | True   |
| 40x[6]         |       1 |  128 | bfloat16 |        1 |   7.96 |   17   | True   |
| [300]          |     128 |  512 | bfloat16 |        1 | 108.62 |  726.7 | True   |
| [2, 4, 16, 64] |     128 |  512 | bfloat16 |        1 |  29.75 |  776.9 | True   |
| 40x[6]         |     128 |  512 | bfloat16 |        1 |  65.46 | 1043.4 | True   |
| [8, 4]         |      16 |  128 | bfloat16 |        3 |  19.68 |   16.4 | True   |
| [8, 4]         |      16 |  512 | bfloat16 |        3 |  14.75 |   86.8 | True   |
...
...
ALL PASSED

@valarLip valarLip left a comment

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.

LGTM

@simondanielsson

Copy link
Copy Markdown
Contributor Author

CI errors look transient, can we re-run? Thanks

e2e validation

Also validated e2e in vLLM running DeepSeek-V3 with this causal and non-causal prefill kernel (with FP8 KV cache) in 8xMI350.

VLLM_ROCM_USE_AITER_MLA=1 \
vllm serve deepseek-ai/DeepSeek-V3-0324 \
    --tensor-parallel-size 8 \
    --enable-expert-parallel \
    --kv-cache-dtype fp8 \
    --gpu-memory-utilization 0.8 \
    --max-model-len 16K

GSM8k

GSM8k accuracy unchanged:

PR vllm-project/vllm#44544 with aiter built in this branch:

Tasks Version Filter n-shot Metric Value Stderr
gsm8k 3 flexible-extract 5 exact_match ↑ 0.9447 ± 0.0063
strict-match 5 exact_match ↑ 0.9454 ± 0.0063

vllm main

Tasks Version Filter n-shot Metric Value Stderr
gsm8k 3 flexible-extract 5 exact_match ↑ 0.9484 ± 0.0061
strict-match 5 exact_match ↑ 0.9492 ± 0.0060

Traces

Zooming in on a mixed batch with chunked prefills:

Causal works as prefill as expected (causal ps kernel + reduce)
image

Followed by a non-causal prefill + reduction
image

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants