Skip to content

[HIP] [MLA] Fix non-uniform query offsets after head folding - #6091

Merged
akii96 merged 11 commits into
ROCm:mainfrom
xaguilar-amd:fix/mla-nonuniform-folded-query-offsets
Nov 12, 2026
Merged

akii96 merged 11 commits into
ROCm:mainfrom
xaguilar-amd:fix/mla-nonuniform-folded-query-offsets

Conversation

@xaguilar-amd

@xaguilar-amd xaguilar-amd commented Oct 2, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Fix MLA metadata generation for non-uniform query lengths when an unsupported head count is folded onto the 16-head persistent kernel.

QoState::get_begin() and get_end() indexed seqlens_qo_indptr with the folded pseudo-batch id. That indptr has one entry per original request, not per pseudo-batch. On gfx942, 96 bf16 heads fold by 6, so an 8-request batch produces ids up to 47 while the indptr has only 9 entries.

Map the pseudo-batch back to its original request and head subgroup, then compute the offset in the folded Q layout:

original_batch = folded_batch / qk_batch_ratio
subgroup       = folded_batch % qk_batch_ratio
folded_begin   = (original_begin - base) * qk_batch_ratio
                 + subgroup * original_length
folded_end     = folded_begin + original_length

qk_batch_ratio <= 1 keeps the absolute indptr values, so native head counts are unchanged. The KV path already mapped folded ids this way. The sparse path is unchanged.

Problem

uni_seqlen_qo=-1 with a folded head count takes this lookup. An out-of-range indptr value is written into MlaWorkInfo.qo_start / qo_end. A large value faults the decode kernel (HSA_STATUS_ERROR_MEMORY_FAULT); a small one produces wrong attention.

We hit this on gfx942 during Kimi-K3 TP8/DCP8 decode with full graphs and --max-num-seqs 8. While all 8 requests have query length 1, uni_seqlen_qo=1 and the uniform path is fine. The tail of the run is 7 real tokens plus one empty graph-padding row, so vLLM correctly passes uni_seqlen_qo=-1 and the folded lookup goes out of range.

gfx950 bf16 does not fold 96 heads, so this particular shape does not take the bad path there. The lookup itself is shared.

Planner fixes for non-uniform batches with query tiles

Testing qo_len > 1 against a decode reference exposed two more bugs in kn_get_mla_metadata_v1_2. Both need uni_seqlen_qo=-1 with kQoSplits enabled, e.g. 96 heads with qo_len >= 2:

  • mla_v12_compute_sum_blocks read each batch's qo length from LDS before writing it, so the work split came from stale LDS. Depending on what was left there, the planner emitted no work, put every work on one CU, or wrote past work_info_set.
  • An empty padding request got zero qo tiles. The planner never moved past it: it emitted junk works with negative qo ranges and corrupted the reduce maps of the split requests before it.

mla_v12_num_qo_tiles now takes the qo length as an argument instead of reading it back through QoState. mla_v12_compute_sum_blocks computes it from seqlens_qo_indptr, passes it in, and still stores it in LDS for the later stages. Every request gets at least one tile, as the kQoSplits=false path already does.

vLLM's ROCm AITER MLA backend doesn't hit these in practice. It passes uni_seqlen_qo=-1 only for single-token decode or mixed query lengths, and pads spec-decode batches into uniform ones.

Test plan

All on gfx942 (MI325X).

  • op_tests/test_metadata.py (default sweep, run by CI): passes. Besides the existing parallel vs serial planner sweep, it now has a non-uniform bf16 sweep: 16 and 96 heads, query lengths [1,1,1,1,1,1,1,0], [2,1,3], [2,2,2,0], [4,4,4,0], uni_seqlen_qo=-1. Each work's query range must stay inside the folded Q and cover its pseudo-batch exactly. The serial and parallel planners must agree on every work that carries queries and on the reduce maps.
    • Against the pre-fix commit (3eca6e4a), every 96-head case fails the range check, [2,1,3] and [2,2,2,0] also diverge between planners, and [4,4,4,0] faults the GPU. The 16-head cases pass there too.
    • The serial planner gives an empty request one zero-length work and the parallel planner skips it. This predates this PR and is harmless, so zero-length works are not compared.
  • op_tests/test_mla_persistent.py with the new --pad_batches option, which turns the last N requests into CUDA-graph padding rows (no queries, no KV) and runs the planner with uni_seqlen_qo=-1. Checked against the existing torch decode and split-KV/reduce references:
    AITER_MLA_DECODE_PERSISTENT_MAX_BATCH=0 python3 op_tests/test_mla_persistent.py \
      -n 96,1 96,2 96,4 16,2 -b 4 8 -c 300 -d bf16 -kvd bf16 -pad 0 1 3
    
    All 24 cases give decode:err 0. Context 300 forces KV splits, so the reduce maps of the requests before the padding rows are exercised. Padding defaults to 0, so CI does not run these cases; the planner-level checks above cover the regression in CI.
  • Re-run the original TP8/DCP8 GSM8K 20-shot server with this build, after restoring upstream vLLM's uniform_qo_len <= 1 check (results below). Run before the mla_v12_num_qo_tiles refactor, which is not meant to change behaviour.
  • op_tests/test_mla_persistent.py sweep, with and without --varlen, compared against the pre-fix module: same results. fp8 KV at context 21 fails on gfx942 in both runs, so that failure predates this PR. Run before the mla_v12_num_qo_tiles refactor.
local-completions ({'model': 'kimi-k3', 'base_url': 'http://localhost:8000/v1/completions', 'num_concurrent': 32, 'max_retries': 10, 'max_gen_toks': 2048, 'tokenizer_backend': 'None', 'tokenized_requests': 'False'}), gen_kwargs: ({}), limit: None, num_fewshot: 20, batch_size: auto
Tasks Version Filter n-shot Metric Value Stderr
gsm8k 3 flexible-extract 20 exact_match ↑ 0.9629 ± 0.0052
strict-match 20 exact_match ↑ 0.9629 ± 0.0052

PR Self-Review

Reviewed revision

d07becc7f917956e0ee97c35a75af30942516a24

Behavior and intent

Head folding (qk_batch_ratio = num_heads / 16 > 1) makes the MLA metadata planners walk num_batches * qk_batch_ratio pseudo-batches. For non-uniform batches (uni_seqlen_qo = -1), QoState::get_begin/get_end indexed seqlens_qo_indptr, which has one entry per original request, with the pseudo-batch id. That read past the indptr table and emitted qo_start/qo_end ranges that do not match the folded Q layout built by aiter/mla.py. Folded decode with padded (empty) requests or mixed query lengths then reads the wrong Q rows or faults. On the pre-PR base 3eca6e4a, every folded 96-head case fails the range check and [4,4,4,0] hits a GPU memory access fault.

This PR:

  • Rebuilds the row range of pseudo-batch b * ratio + g in the folded layout ((indptr[b] - indptr[0]) * ratio + g * len_b). It keeps the original lookup when ratio <= 1 and on the sparse path.
  • In the v1_2 planner, computes the qo tile count from the request's qo length passed explicitly. Before, it read LDS before that length was stored.
  • Gives an empty request at least one qo tile under kQoSplits, so the serial and parallel planners advance past it identically.

Uniform (uni_seqlen_qo > 0) and unfolded paths produce the same metadata as before.

Validation and unverified scope

All runs below were on gfx942 (MI325X), at the reviewed revision d07becc7, with PYTHONPATH pointing at the checkout:

  • python3 op_tests/test_metadata.py (defaults): passed. All 8 non-uniform cases ([1]*7+[0], [2,1,3], [2,2,2,0], [4,4,4,0] with 16 and 96 heads, bf16) report 0 serial/parallel mismatches and 0 folded qo range errors. Upstream's intra-batch KV coverage check also passed.
  • AITER_MLA_DECODE_PERSISTENT_MAX_BATCH=0 python3 op_tests/test_mla_persistent.py -n 96,1 96,2 96,4 16,2 -b 4 8 -c 300 -d bf16 -kvd bf16 -pad 0 1 3: passed. All 24 combinations have decode:err = 0 against the torch reference, including 1 and 3 padded requests. The _fold_seqlen_indptr cuda-graph capture check passed.
  • v1_1 planner (fast_mode=False), using a throwaway script that applies folded_qo_range_errors from test_metadata.py: passed. Folded ranges are correct for 32/64/96/112 heads × [2,1,3], [1,3,2,4], [3,1], [1,2]*4, [4,1,4,2] (20 cases).
  • Pre-PR base 3eca6e4a: the same test_metadata.py cases fail (range errors on every folded 96-head case, planner divergence on [2,1,3]/[2,2,2,0], GPU memory access fault on [4,4,4,0]).
  • ruff and black are clean on the changed Python files.

Unverified:

  • gfx950 was only covered by upstream CI. In run 41119362534 (at 7cb1f00f), the MI35X shards running test_metadata.py and test_mla_persistent.py with default arguments passed. The -pad padded-decode sweep was not run on gfx950. There, bf16 never folds, and fp8 folds only for 48/80/112 heads, or 96 heads when max_seqlen_qo > 6.
  • fp8 folded shapes were not run end to end.
  • End-to-end decode through the v1_1 planner with padded requests is not covered. test_mla_persistent.py -mm v1_1 -pad 1 already fails for unfolded 16 heads, where the changed QoState code is a no-op. That is an existing v1_1 limitation with empty requests, not something this PR introduces.
  • The v1_2 PA planner never sets qk_batch_ratio, so it always takes the unchanged ratio <= 1 branch. It was not run.
  • Mixed query lengths above 1 (e.g. [2,1,3] folded) are validated at the planner level only. The host Q fold in aiter/mla.py for max_seqlen_q > 1 still assumes every non-empty request has max_seqlen_q tokens. That limitation is remaining and unchanged by this PR.
  • A model-level accuracy run (GSM8K) was done before the test refactor, not on this revision.

PR-specific question

The changed get_begin/get_end branch runs only when three things hold at the same time:

  • The batch is non-uniform: uni_seqlen_qo = -1, i.e. kUniSeqlenQo <= -1.
  • The path is dense: !kIsSparse.
  • The head plan folds: qk_batch_ratio > 1.

The ratio comes from mla_decode_head_plan_v1_2 / _v1_1 in csrc/include/mla_decode_shape.h:

  • v1_2 on gfx942 bf16 folds every multiple of 16 except 16 itself.
  • v1_2 on gfx942 fp8 keeps 128 native, and 64 native only for qlen 1.
  • v1_2 on gfx950 bf16 is always native.
  • v1_2 on gfx950 fp8 keeps 32/64/128 native, and 96 native when max_seqlen_qo <= 6.
  • v1_1 folds 32..112 heads in steps of 16 on every arch.
  • v1_0 does not use QoState. The v1_2 PA planner leaves qk_batch_ratio unset, so it stays on the unchanged branch.

The new tile minimum only applies under kQoSplits (packed qo length > kPackedQoLenPerWg), and only changes the result for empty requests.

Invariants that keep unsupported inputs out:

  • The head plan folds only when num_heads % 16 == 0. Any other head count is rejected by AITER_CHECK on an unaccepted plan.
  • ratio <= 1 returns the exact original indptr values, so unfolded callers are bit-identical.
  • The folded row formula matches the layout produced by _fold_seqlen_indptr (repeat_interleave) and the host Q fold. test_metadata.py checks every work range against it, so a layout drift fails the test.

Changed op tests

  • op_tests/test_metadata.py: adds test_nonuniform_metadata (-q/--qo-lens, --qo-nhead). It builds non-uniform batches with empty requests and checks two things:

    • The serial and parallel v1_2 planners agree on non-empty works.
    • Every work's [qo_start, qo_end) exactly covers its pseudo-batch in the folded Q layout, with no range past the folded tensor.

    This is the cheapest direct check of the indptr lookup and fails on the pre-PR base. The existing tests here use uniform uni_seqlen_qo and never reach the non-uniform folded branch.

  • op_tests/test_mla_persistent.py: adds -pad/--pad_batches, which turns trailing requests into graph padding (qo and kv length 0, so uni_seqlen_qo = -1). It also makes the torch references skip empty requests and works.

    This is the only end-to-end check that the folded metadata produces correct decode output and that padded requests don't fault. The existing sweeps use uniform qlen, so they never hit the changed path. The deleted op_tests/test_mla_folded_qo_metadata.py had no __main__ and never ran in CI; its coverage moved into the two files above.

QoState indexed seqlens_qo_indptr with the folded pseudo-batch id.
That table has one entry per original request, so a 96-to-16 head
fold read past it and the decode kernel faulted.
@github-actions

github-actions Bot commented Oct 2, 2026

Copy link
Copy Markdown
Contributor

🏷️ CI Guide

Runs automatically on every PR:

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

Extended tests (opt-in via labels):

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

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

One backend per PR:
A PR changes one kernel backend: [Triton/Gluon] (Triton and Gluon count as one), [HIP], [ASM], [CK], [OPUS] or [FlyDSL]. If the title ends up with two backend tags, split the PR -- as stacked pull requests when one part cannot merge without the other.

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

Cover the padded 96-head decode shape that indexed past qo_indptr, plus a non-uniform length case and the 16-head path that must stay unfolded.
@xaguilar-amd
xaguilar-amd marked this pull request as ready for review October 2, 2026 14:43
@xaguilar-amd
xaguilar-amd requested a review from a team October 2, 2026 14:43
@github-actions github-actions Bot changed the title [MLA] Fix non-uniform query offsets after head folding [HIP] [MLA] Fix non-uniform query offsets after head folding Oct 2, 2026
@github-actions github-actions Bot added the HIP label Oct 2, 2026
@zufayu

zufayu commented Oct 7, 2026

Copy link
Copy Markdown
Contributor

@aiter-bot review


Trying the review bot on a few representative PRs across different areas, so the team can see what it actually produces on real diffs.

How to use it — just comment on any PR:

  • @aiter-bot review — first pass
  • @aiter-bot re-review — after you push fixes

What it is: advisory only. It surfaces hints for a human reviewer — perf regressions, silent correctness bugs, dispatch-gate holes, AI-generated code patterns. Its judgement is stochastic, it never blocks a merge, and every verdict (✅ / ⚠️ / 🔴) is posted so the reviewer who asked for it sees the result.

It runs on a self-hosted box against a local model, so a pass takes roughly 25–30 min.

Who can trigger it: the logins in authorized.txt — the aiter review roster. Details in SKILL.md.

@aiter-bot

Copy link
Copy Markdown

ROCm/aiter PR #6091 — [HIP] [MLA] Fix non-uniform query offsets after head folding

Maps folded pseudo-batch ids back to their original request inside QoState::get_begin/get_end, so a non-uniform batch no longer indexes seqlens_qo_indptr past its end (faulting the decode kernel) when an unsupported head count such as gfx942 bf16 96 heads is folded onto the 16-head persistent kernel.

Review (advisory): ⚠️ NEEDS WORK
Validation (deterministic): NOT RUN — REVIEW_AUTO_VALIDATE=0 (auto-validation disabled in this environment); the required target op_tests/test_mla_folded_qo_metadata.py exists but no run happened, an environment gap, not a PR defect.
Perf (advisory): NOT RUN — the target exposes no benchmark entry point (no --scenario bench, no perftest/@benchmark harness) and the PR adds that target itself, so base has nothing to compare against.

⚠️ [verified] v1_2_device.cuh:608 and v1_2_device.cuh:761 still compute the causal trim as num_qo_tiles - (qo_start / qk_batch_ratio) % ori_seqlen_qo - 1, which assumes the uniform case where ori_seqlen_qo is a per-request length — on the non-uniform branch this PR fixes, ori_seqlen_qo is the caller's uni_seqlen_qo = -1, x % -1 is 0, and every qo tile of a folded batch gets batch_tail = num_qo_tiles - 1 instead of num_qo_tiles - 1 - tile_idx, so for any request with more than 8 query tokens (num_qo_tiles > 1 at 16 folded heads, e.g. qo_lens=[9,9,9,0] on gfx942 bf16 96 heads, causal, page_size=1) the last tile's kv_end would be trimmed past what its final query attends and silently drop attention mass, a regime the new tests never reach (they stop at qo_len 3). Author must recover the tile index the way dense_folded_range recovers the batch (or gate the trim to the uniform case) and add a >8-query non-uniform case.
⚠️ [verified] The metadata planner this PR changes (csrc/kernels/mla/metadata/v1_2_device.cuh and its shared QoState header v1_comm.cuh) serves every vLLM MLA decode, but the PR carries no ci:* label, so the label-gated downstream jobs stay skipped — and those rosters run MI350X/gfx950 (kimi-downstream.yaml, vllm_benchmark.yaml) where bf16 head counts are natively supported, meaning they would exercise only the ratio==1 preservation while the folded branch's sole downstream evidence is the author's manual Kimi-K3 gfx942 GSM8K run. Author must add ci:vllm (the minimal Kimi label) and let it run green before merge, or state on the PR that the manual run is the accepted downstream gate.
⚠️ [inferred] No base-vs-head timing exists for the changed planner: the metadata kernel runs once per decode step in the critical path and now does an integer divide plus multiply per get_begin/get_end call, which my code reading says is negligible at ~48 folded batches for the reported shape, but no measurement backs that and the only target this PR ships has no benchmark entry point. Author must time a decode step (or the metadata call) base vs head on gfx942, or state that the planner's added integer work is accepted without measurement.
📝 [verified] The [2,1,3] and 16-head cases in op_tests/test_mla_folded_qo_metadata.py assert query ranges against _expected_ranges, a host-side mirror of the kernel's own formula, so a layout mistake shared by both would pass, and the independent fp32 decode oracle runs only at qo_len 1 where the folded view of a contiguous (T, 96, D) Q coincides with the permuted layout (I verified the formula reproduces _fold_seqlen_indptr and the uniform path exactly, which is why this is a note). Reviewer should ask for a decode-level qo_len>1 oracle once aiter/mla.py's fold supports non-uniform lengths above 1.

@xaguilar-amd

Copy link
Copy Markdown
Contributor Author

Thanks for the review. Going through the points in order:

1. Causal trim at v1_2_device.cuh:608/761. You're right that the folded formula is wrong once a request has more than one query tile, but it isn't specific to the non-uniform path, and this PR didn't introduce it. It dates back to #1665 and is wrong for uniform batches too. With 96 heads folded to 16 and qo_lens=[9]*4, uni_seqlen_qo=9: subgroup 0 of each request trims both
tiles by 1, which over-trims the last tile, and subgroups 1-5 trim neither, which under-trims tile 0. With uni_seqlen_qo=-1 every tile is trimmed by 1, as you describe.

On gfx942 it can't be reached: the persistent 16-head kernels stop at qSeqLen=4, so a folded request never has more than one tile, and the trim is clamped to 0. It can be reached on gfx950 fp8 with folded heads (48/80/112, or 96 with max_seqlen_q > 6) and 9 or more queries, where qlen > 4 maps onto the 32-head qseqlen4 kernel. The fix is to use
num_qo_tiles - 1 - curr_qo_tile_idx for folded batches as well, which needs gfx950 hardware to validate. This should be sent as a separate follow-up PR rather than widen this one.

2. Downstream label. Added ci:vllm. As you note, those jobs run on gfx950, where bf16 96 heads is native, so they only cover the ratio == 1 path. The folded path is covered by the gfx942 Kimi-K3 TP8/DCP8 GSM8K run in the description and by op_tests/test_mla_folded_qo_metadata.py.

3. Planner perf. The new arithmetic in get_begin/get_end is inside if constexpr (Traits::kUniSeqlenQo <= -1), so the uniform instantiations, which are what vLLM uses for normal decode and padded spec decode, compile to the same code as before. ratio <= 1 returns early with the original lookup.
The non-uniform folded path adds one integer divide and multiply per call, on a single-wavefront kernel. The new commit only reorders an LDS write and adds a max per tile count. I haven't measured base against head, and I consider this negligible.

4. Independent decode oracle for qo_len > 1. Fair point, though aiter/mla.py already supports what's needed: its fold reshape is correct whenever the empty rows come last, which is exactly the vLLM graph-padding shape ([k, k, k, 0]). Running that oracle on gfx942 (96 bf16 heads, causal, against an fp32 reference) found two more planner bugs on non-uniform batches with query tiles, both fixed in the new commit:

  • mla_v12_compute_sum_blocks read the qo length from LDS before writing it, so the work split was built from stale LDS. This is why [2,1,3] could produce no work, and in one run it faulted.
  • An empty padding request got zero qo tiles, and the planner never moved past it, corrupting the reduce maps of the split requests before it.

After the fix, [2,1,3], [2,2,2,0], [4,4,4,0], [4]*7+[0] and the
16-head and 32-head equivalents all match the reference.
test_metadata.py (parallel vs serial planner) passes, and a
test_mla_persistent.py sweep shows the same results as the pre-fix module.

I'll add [2,2,2,0] and [4,4,4,0] as decode-vs-reference cases to test_mla_folded_qo_metadata.py.

Two bugs in kn_get_mla_metadata_v1_2 when uni_seqlen_qo=-1 and the
packed query length enables kQoSplits (e.g. 96 heads, qo_len >= 2):

- mla_v12_compute_sum_blocks read each batch's qo length back from LDS
  (mla_v12_num_qo_tiles -> QoState::get_seqlen) before writing it, so
  sum_blocks was built from stale LDS. Depending on what was left there,
  the planner emitted no work, put every work on one CU, or wrote past
  work_info_set and faulted the decode kernel.
- An empty request (graph padding) got zero qo tiles. The tile loop
  never advanced past it: it emitted one junk work per remaining CU with
  negative qo ranges and overwrote the reduce maps, corrupting the
  split requests before it.

Write the LDS slot before reading it, and give every request at least
one tile, which is what the kQoSplits=false path already does.

On gfx942 with 96 bf16 heads, causal, qo_lens [2,1,3] produced no work
and [2,2,2,0] / [4,4,4,0] did not match an fp32 reference. All of them
match after this change. Uniform batches and qo_len 1 are unaffected.

Signed-off-by: Xavier Aguilar <[email protected]>
…decode tests, with a causal fp32 reference for qo_len > 1. KV length 300 forces splits so the reduce maps of requests before the empty row are checked. Also apply black, which the Checks workflow was failing on.

Signed-off-by: Xavier Aguilar <[email protected]>
@xaguilar-amd

Copy link
Copy Markdown
Contributor Author

@fangche123 I addressed the comments from the review bot, when you have some time could you please check? This bug is crashing Kimi-K3 on gfx942 when using DSpark + DCP.

@samremes

Copy link
Copy Markdown
Contributor

@aiter-bot re-review

Comment thread op_tests/test_mla_folded_qo_metadata.py Resolved
mla_v12_num_qo_tiles read the qo length through QoState::get_seqlen,
which on non-uniform batches comes from an LDS slot that
mla_v12_compute_sum_blocks has to write first. Take the length as an
argument instead: mla_v12_compute_sum_blocks computes it from
seqlens_qo_indptr, passes it in, and still stores it in LDS for the later
stages. The other callers pass qo_state.get_seqlen().

No functional change.

Signed-off-by: Xavier Aguilar <[email protected]>
CI runs op_tests as scripts, and test_mla_folded_qo_metadata.py had only
pytest functions and no __main__, so it never ran there. Fold its cases
into the existing suites instead.

test_metadata.py: add a non-uniform bf16 sweep (16 and 96 heads,
[1]*7+[0], [2,1,3], [2,2,2,0], [4,4,4,0]) with its own summary table.
Every work's qo range must stay inside the folded Q layout and cover
each pseudo-batch exactly, and the serial and parallel planners must
agree on all works that carry queries plus the reduce maps. The serial
planner gives an empty request one zero-length work and the parallel
planner skips it, so zero-length works are not compared. Runs by
default.

test_mla_persistent.py: add -pad/--pad_batches (default 0), which turns
the last N requests into CUDA-graph padding rows with no queries and no
KV and runs the planner with uni_seqlen_qo=-1. The torch references skip
empty requests and zero-length works.

Signed-off-by: Xavier Aguilar <[email protected]>
Conflicts in the tests only:
- op_tests/test_metadata.py: keep both the non-uniform qo sweep and
  upstream's intra-batch KV coverage check.
- op_tests/test_mla_persistent.py: build metadata with upstream's
  _make_mla_metadata, passing uni_seqlen_qo=-1 when --pad_batches is
  non-zero, and add the padding axis to the sweep in main().

Signed-off-by: Xavier Aguilar <[email protected]>
@xaguilar-amd

Copy link
Copy Markdown
Contributor Author

@samremes thanks for the great feedback! I already addressed your comments.

@samremes

Copy link
Copy Markdown
Contributor

@xaguilar-amd thanks, I checked the earlier points (test placement moved into test_metadata.py / test_mla_persistent.py, and mla_v12_num_qo_tiles now takes the qo length explicitly) and they look good.

Two things before this can go in:

  1. The PR description is missing the PR Self-Review section from the PR template (reviewed revision, behavior and intent, validation and unverified scope, PR-specific question, changed op tests). Please fill it in, using the head SHA and the path-specific question from the automated PR Self-Review comment.
  2. Please merge current main into the branch, so the self-review is done against the final head and CI runs on top of the latest main.

@aiter-bot

aiter-bot commented Oct 30, 2026 •

Copy link
Copy Markdown

READY FOR HUMAN REVIEW

PR Self-Review

Revision d07becc7f917 · mode shadow

Author self-review accepted. Readiness report:

Author answers

  • PASS — current-SHA answers are present and structurally specific
Show the author's self-review answers

Behavior and intent

Head folding (`qk_batch_ratio = num_heads / 16 > 1`) makes the MLA metadata planners walk `num_batches * qk_batch_ratio` pseudo-batches. For non-uniform batches (`uni_seqlen_qo = -1`), `QoState::get_begin`/`get_end` indexed `seqlens_qo_indptr`, which has one entry per original request, with the pseudo-batch id. That read past the indptr table and emitted `qo_start`/`qo_end` ranges that do not match the folded Q layout built by `aiter/mla.py`. Folded decode with padded (empty) requests or mixed query lengths then reads the wrong Q rows or faults. On the pre-PR base `3eca6e4a`, every folded 96-head case fails the range check and `[4,4,4,0]` hits a GPU memory access fault.

This PR:

- Rebuilds the row range of pseudo-batch `b * ratio + g` in the folded layout (`(indptr[b] - indptr[0]) * ratio + g * len_b`). It keeps the original lookup when `ratio <= 1` and on the sparse path.
- In the v1_2 planner, computes the qo tile count from the request's qo length passed explicitly. Before, it read LDS before that length was stored.
- Gives an empty request at least one qo tile under `kQoSplits`, so the serial and parallel planners advance past it identically.

Uniform (`uni_seqlen_qo > 0`) and unfolded paths produce the same metadata as before.

Validation and unverified scope

All runs below were on gfx942 (MI325X), at the reviewed revision `d07becc7`, with `PYTHONPATH` pointing at the checkout:

- `python3 op_tests/test_metadata.py` (defaults): passed. All 8 non-uniform cases (`[1]*7+[0]`, `[2,1,3]`, `[2,2,2,0]`, `[4,4,4,0]` with 16 and 96 heads, bf16) report 0 serial/parallel mismatches and 0 folded qo range errors. Upstream's intra-batch KV coverage check also passed.
- `AITER_MLA_DECODE_PERSISTENT_MAX_BATCH=0 python3 op_tests/test_mla_persistent.py -n 96,1 96,2 96,4 16,2 -b 4 8 -c 300 -d bf16 -kvd bf16 -pad 0 1 3`: passed. All 24 combinations have `decode:err = 0` against the torch reference, including 1 and 3 padded requests. The `_fold_seqlen_indptr` cuda-graph capture check passed.
- v1_1 planner (`fast_mode=False`), using a throwaway script that applies `folded_qo_range_errors` from `test_metadata.py`: passed. Folded ranges are correct for 32/64/96/112 heads × `[2,1,3]`, `[1,3,2,4]`, `[3,1]`, `[1,2]*4`, `[4,1,4,2]` (20 cases).
- Pre-PR base `3eca6e4a`: the same `test_metadata.py` cases fail (range errors on every folded 96-head case, planner divergence on `[2,1,3]`/`[2,2,2,0]`, GPU memory access fault on `[4,4,4,0]`).
- `ruff` and `black` are clean on the changed Python files.

Unverified:

- gfx950 was only covered by upstream CI. In [run 41119362534](https://github.com/ROCm/aiter/actions/runs/41119362534) (at `7cb1f00f`), the MI35X shards running `test_metadata.py` and `test_mla_persistent.py` with default arguments passed. The `-pad` padded-decode sweep was not run on gfx950. There, bf16 never folds, and fp8 folds only for 48/80/112 heads, or 96 heads when `max_seqlen_qo > 6`.
- fp8 folded shapes were not run end to end.
- End-to-end decode through the v1_1 planner with padded requests is not covered. `test_mla_persistent.py -mm v1_1 -pad 1` already fails for unfolded 16 heads, where the changed `QoState` code is a no-op. That is an existing v1_1 limitation with empty requests, not something this PR introduces.
- The v1_2 PA planner never sets `qk_batch_ratio`, so it always takes the unchanged `ratio <= 1` branch. It was not run.
- Mixed query lengths above 1 (e.g. `[2,1,3]` folded) are validated at the planner level only. The host Q fold in `aiter/mla.py` for `max_seqlen_q > 1` still assumes every non-empty request has `max_seqlen_q` tokens. That limitation is remaining and unchanged by this PR.
- A model-level accuracy run (GSM8K) was done before the test refactor, not on this revision.

PR-specific question

The changed `get_begin`/`get_end` branch runs only when three things hold at the same time:

- The batch is non-uniform: `uni_seqlen_qo = -1`, i.e. `kUniSeqlenQo <= -1`.
- The path is dense: `!kIsSparse`.
- The head plan folds: `qk_batch_ratio > 1`.

The ratio comes from `mla_decode_head_plan_v1_2` / `_v1_1` in `csrc/include/mla_decode_shape.h`:

- v1_2 on gfx942 bf16 folds every multiple of 16 except 16 itself.
- v1_2 on gfx942 fp8 keeps 128 native, and 64 native only for qlen 1.
- v1_2 on gfx950 bf16 is always native.
- v1_2 on gfx950 fp8 keeps 32/64/128 native, and 96 native when `max_seqlen_qo <= 6`.
- v1_1 folds 32..112 heads in steps of 16 on every arch.
- v1_0 does not use `QoState`. The v1_2 PA planner leaves `qk_batch_ratio` unset, so it stays on the unchanged branch.

The new tile minimum only applies under `kQoSplits` (packed qo length > `kPackedQoLenPerWg`), and only changes the result for empty requests.

Invariants that keep unsupported inputs out:

- The head plan folds only when `num_heads % 16 == 0`. Any other head count is rejected by `AITER_CHECK` on an unaccepted plan.
- `ratio <= 1` returns the exact original indptr values, so unfolded callers are bit-identical.
- The folded row formula matches the layout produced by `_fold_seqlen_indptr` (`repeat_interleave`) and the host Q fold. `test_metadata.py` checks every work range against it, so a layout drift fails the test.

Changed op tests

- `op_tests/test_metadata.py`: adds `test_nonuniform_metadata` (`-q/--qo-lens`, `--qo-nhead`). It builds non-uniform batches with empty requests and checks two things:
  - The serial and parallel v1_2 planners agree on non-empty works.
  - Every work's `[qo_start, qo_end)` exactly covers its pseudo-batch in the folded Q layout, with no range past the folded tensor.

  This is the cheapest direct check of the indptr lookup and fails on the pre-PR base. The existing tests here use uniform `uni_seqlen_qo` and never reach the non-uniform folded branch.
- `op_tests/test_mla_persistent.py`: adds `-pad/--pad_batches`, which turns trailing requests into graph padding (qo and kv length 0, so `uni_seqlen_qo = -1`). It also makes the torch references skip empty requests and works.

  This is the only end-to-end check that the folded metadata produces correct decode output and that padded requests don't fault. The existing sweeps use uniform qlen, so they never hit the changed path. The deleted `op_tests/test_mla_folded_qo_metadata.py` had no `__main__` and never ran in CI; its coverage moved into the two files above.

PR state

  • PASS — pull request is marked ready for review

Copilot findings

  • PASS — no active Copilot finding lacks a substantive author reply
  • ADVISORY — Copilot did not review the current head SHA

Code and op-test hygiene

  • PASS — no committed artifact or conflict marker detected

Required CI

  • PASS — Black: passed
  • PASS — Ruff: passed
  • PASS — Repository dependency: passed
  • PASS — Aiter Test Gate: passed

Shadow mode reports what would block but keeps the status successful. Set AITER_PR_SELF_REVIEW_MODE=enforce only after reviewing real false positives.

@xaguilar-amd

xaguilar-amd commented Nov 2, 2026 •

Copy link
Copy Markdown
Contributor Author

@samremes Done!

We got a red test on CI over the weekend, but the only red check was MI35X Standard Tests shard 4, the known timeout also hitting main (stale split times; fixed by #7290). I've merged main to pick that up. Both changed tests already passed on MI35X in the earlier run.

@amd-ruitang3
amd-ruitang3 removed their request for review November 3, 2026 05:28
@xaguilar-amd

Copy link
Copy Markdown
Contributor Author

@samremes ping.

@xaguilar-amd

Copy link
Copy Markdown
Contributor Author

@fangche123 could you please have a look at this when you have some time? Kimi-K3 (DSpark + DCP) does not work on gfx942 without this fix. It would be really good if we can get the fix into the next AITER cut.

@akii96
akii96 merged commit 20c9ddb into ROCm:main Nov 12, 2026
vpietila-amd pushed a commit that referenced this pull request Nov 12, 2026
* [MLA] Fix non-uniform query offsets after head folding

QoState indexed seqlens_qo_indptr with the folded pseudo-batch id.
That table has one entry per original request, so a 96-to-16 head
fold read past it and the decode kernel faulted.

* [MLA] Test non-uniform query offsets after head folding

Cover the padded 96-head decode shape that indexed past qo_indptr, plus a non-uniform length case and the 16-head path that must stay unfolded.

* [MLA] Fix metadata planner on non-uniform batches with query tiles

Two bugs in kn_get_mla_metadata_v1_2 when uni_seqlen_qo=-1 and the
packed query length enables kQoSplits (e.g. 96 heads, qo_len >= 2):

- mla_v12_compute_sum_blocks read each batch's qo length back from LDS
  (mla_v12_num_qo_tiles -> QoState::get_seqlen) before writing it, so
  sum_blocks was built from stale LDS. Depending on what was left there,
  the planner emitted no work, put every work on one CU, or wrote past
  work_info_set and faulted the decode kernel.
- An empty request (graph padding) got zero qo tiles. The tile loop
  never advanced past it: it emitted one junk work per remaining CU with
  negative qo ranges and overwrote the reduce maps, corrupting the
  split requests before it.

Write the LDS slot before reading it, and give every request at least
one tile, which is what the kQoSplits=false path already does.

On gfx942 with 96 bf16 heads, causal, qo_lens [2,1,3] produced no work
and [2,2,2,0] / [4,4,4,0] did not match an fp32 reference. All of them
match after this change. Uniform batches and qo_len 1 are unaffected.

Signed-off-by: Xavier Aguilar <[email protected]>

* Add [2,2,2,0] and [4,4,4,0] (96 heads) to the folded query-range and decode tests, with a causal fp32 reference for qo_len > 1. KV length 300 forces splits so the reduce maps of requests before the empty row are checked. Also apply black, which the Checks workflow was failing on.

Signed-off-by: Xavier Aguilar <[email protected]>

* [MLA] Pass qo length explicitly to mla_v12_num_qo_tiles

mla_v12_num_qo_tiles read the qo length through QoState::get_seqlen,
which on non-uniform batches comes from an LDS slot that
mla_v12_compute_sum_blocks has to write first. Take the length as an
argument instead: mla_v12_compute_sum_blocks computes it from
seqlens_qo_indptr, passes it in, and still stores it in LDS for the later
stages. The other callers pass qo_state.get_seqlen().

No functional change.

Signed-off-by: Xavier Aguilar <[email protected]>

* [MLA] Move folded non-uniform qo tests into existing op_tests

CI runs op_tests as scripts, and test_mla_folded_qo_metadata.py had only
pytest functions and no __main__, so it never ran there. Fold its cases
into the existing suites instead.

test_metadata.py: add a non-uniform bf16 sweep (16 and 96 heads,
[1]*7+[0], [2,1,3], [2,2,2,0], [4,4,4,0]) with its own summary table.
Every work's qo range must stay inside the folded Q layout and cover
each pseudo-batch exactly, and the serial and parallel planners must
agree on all works that carry queries plus the reduce maps. The serial
planner gives an empty request one zero-length work and the parallel
planner skips it, so zero-length works are not compared. Runs by
default.

test_mla_persistent.py: add -pad/--pad_batches (default 0), which turns
the last N requests into CUDA-graph padding rows with no queries and no
KV and runs the planner with uni_seqlen_qo=-1. The torch references skip
empty requests and zero-length works.

Signed-off-by: Xavier Aguilar <[email protected]>

---------

Signed-off-by: Xavier Aguilar <[email protected]>
Co-authored-by: amd-ruitang3 <[email protected]>
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.

7 participants