Skip to content

[HIP] Fix out-of-bounds read in MLA metadata planner when head-folding - #6188

Closed
simondanielsson wants to merge 4 commits into
ROCm:mainfrom
simondanielsson:fix/qostate-fold
Closed

simondanielsson wants to merge 4 commits into
ROCm:mainfrom
simondanielsson:fix/qostate-fold

Conversation

@simondanielsson

@simondanielsson simondanielsson commented Oct 6, 2026 •

Copy link
Copy Markdown
Contributor

Motivation

When the MLA metadata planner "head-folds" with 128 heads it reads garbage/OOB from one its input tensors. This leads to garbage propagating to the attention output and increasing the probability of corrupt and gibberish output.

This PR fixes it by making the planner correctly "unfolding" the index back before using it.

Intuitively

DSv3 shapes with TP1 (and DP8) is not natively_supported by the MLA kernel on gfx942 (i.e. 128 heads). In these cases, it "folds" the heads into the batch dimension so it runs with 16 heads. Before you can correctly access the input after folding, one needs to unfold it.

So if you're on 128 heads, it converts it from

before:  1 batch  x 128 heads
after:   8 "pseudo"-batches x  16 heads

and there's a mapping

real batch 0  ->  pseudo-batches 0..7
real batch 1  ->  pseudo-batches 8..15

E.g. to get real batch bid you hence have to compute it as bid = pseudo_bid / folds

p_seqlens_qo_indptr is not folded, so if you try to access this with these folded "pseudo-batches" you will read out of bounds. This is done in several places in the code already, but not in all places.

Test Plan

1. Unit test

Run ok on this branch

cd op_tests
python3 -c 'import test_metadata as t; t.test_qo_fold_nonuniform()'

It should fail on main:

git checkout main -- csrc/kernels/mla/metadata/
rm -rf aiter/jit/module_mla_metadata.so aiter/jit/build/module_mla_metadata
cd op_tests && python3 -c 'import test_metadata as t; t.test_qo_fold_nonuniform()'

Full sweep should be ok:

python3 op_tests/test_metadata.py -b 4 16 64 -c 2048 8192

2. e2e test in vllm

We can see increased gibberish by running SpeedBench with a very large max-output-tokens value set, as gibberish generation often leads to long tail generations (due to not properly generating eos)

Run DPA:

# using vLLM v0.30.0
VLLM_ROCM_USE_AITER=1 \
VLLM_ROCM_USE_AITER_FP8BMM=0 \ 
vllm serve deepseek-ai/DeepSeek-V3-0324     --port 8000     --data-parallel-size 8     --tensor-parallel-size 1     --gpu-memory-utilization 0.8 --max-num-batched-tokens 8K 

Run Speedbench with max output tokens 16k;

vllm bench serve \
  --model deepseek-ai/DeepSeek-V3-0324 \
  --dataset-name speed_bench \
  --dataset-path '/root/speedbench/' \
  --num-prompts 300 \
  --speed-bench-dataset-subset throughput_16k \
  --speed-bench-output-len 16384 \
  --max-concurrency 64 \
  --save-result --save-detailed \
  --result-filename /root/results/out.json

Print out the longest generations and check quality of output:

python3 - <<'PY'
import json, gzip, re, collections
p='/root/results/out.json'
d=json.load(open(p))
ol=d['output_lens']; gt=d['generated_texts']
CAP=16384
# check any generations hitting the cap
caps=[i for i,x in enumerate(ol) if x>=CAP]
def gzratio(s):
    b=s.encode('utf-8','ignore'); return len(gzip.compress(b))/max(1,len(b))
def top_line_rep(s):
    lines=[l.strip() for l in s.splitlines() if l.strip()]
    if not lines: return 0,''
    c=collections.Counter(lines); l,n=c.most_common(1)[0]
    return n, l[:70]
for i in caps:
    t=gt[i] or ''
    n,line=top_line_rep(t)
    print('=== req idx %d | out_tokens=%d | gzip=%.3f ==='%(i,ol[i],gzratio(t)))
    print('  most-repeated line x%d: %r'%(n,line))
    print('  --- TAIL (last 400 chars) ---')
    print('  '+t[-400:].replace(chr(10),' '))
    print()
PY

Test Result

1. Unit test

  1. test_qo_fold_nonuniform:

This branch: succeeds

Main: errors

  File "op_tests/test_metadata.py", line 431, in test_qo_fold_nonuniform
    check_qo_fold(uni_seqlen_qo, qo_lens, label)
  File "op_tests/test_metadata.py", line 374, in check_qo_fold
    assert not bool(bad.any()), (
AssertionError: [non-uniform] 1 of 32 active reduce_final_map rows are
outside [0, 32] or non-monotone: [[4, 0]]
  1. Sweep:
 batch_size  ctx_len                 dtype                kvtype  nhead  jitter  seed  num_iters  batch_chunk    gfx  chunk  num_works  num_split_groups  serial us  serial GB/s  parallel us  parallel GB/s  parallel err  match  speedup
          4     2048 torch.float8_e4m3fnuz torch.float8_e4m3fnuz     16   False     0        101            0 gfx942   4096         60                 4     46.519         0.05        4.557           0.50             0   True   10.207
         16     2048 torch.float8_e4m3fnuz torch.float8_e4m3fnuz     16   False     0        101            0 gfx942   4096        240                16     88.364         0.10        7.965           1.14             0   True   11.094
         64     2048 torch.float8_e4m3fnuz torch.float8_e4m3fnuz     16   False     0        101            0 gfx942   4096        320                64    123.096         0.11       23.450           0.56             0   True    5.249
          4     8192 torch.float8_e4m3fnuz torch.float8_e4m3fnuz     16   False     0        101            0 gfx942   4096         64                 4     47.230         0.05        4.489           0.54             0   True   10.520
         16     8192 torch.float8_e4m3fnuz torch.float8_e4m3fnuz     16   False     0        101            0 gfx942   4096        256                16     91.570         0.11        7.971           1.21             0   True   11.488
         64     8192 torch.float8_e4m3fnuz torch.float8_e4m3fnuz     16   False     0        101            0 gfx942   4096        341                64    126.496         0.11       23.518           0.59             0   True    5.379
gfx=gfx942 cu=304 | Kimi-K2.5-MXFP4 decode | nhead=16 nhead_kv=1 dtype=torch.float8_e4m3fnuz kv=torch.float8_e4m3fnuz page_size=1 kv_gran=16 max_split_per_batch=16 jitter=False

2. e2e test in vllm

Without fix: lots of random gibberish

=== req idx 34 | out_tokens=16384 | gzip=0.210 ===
  most-repeated line x2: '::'
  --- TAIL (last 400 chars) ---
  , and the, and the and the in the also, in. in,. 1, 1,,  and the\xala, and the, and, and, and, and, and, and, and, and, and, and,ాన, and a. a. a. a. and a. and ( the in space and a, a, and a, and a, and a and a and a and a and a and a and a and a and  and a and a and a and a and a and a and a and a and a and  and a and a and setTimeout,Wely 2, 2.03,,,  and the. This and an such as a, a, a, a, a:

=== req idx 52 | out_tokens=16384 | gzip=0.194 ===
  most-repeated line x360: 'and'
  --- TAIL (last 400 chars) ---
   [ the , the, the,  if,This in the, in a in,This and this and the, while the, the, the,  if and if and and and and after, and, and, and, and, and;         2,   , and, and, and, and to, to.Something with a, in a,  ead-         with a;  {, and, and/ and = and. Use a, in a, in on to the, to a #from, to, to.If a in and, and, and, and, and in, in, in, in the,  osition, in. and, and, and, kasar ( in, in

=== req idx 71 | out_tokens=16384 | gzip=0.387 ===
  most-repeated line x2: '_For the r—r—rough and r—r—ready Johnny Bull_,'
  --- TAIL (last 400 chars) ---
 of Flush of Gold—the same, yet not the same.  The difference I could eyes

=== req idx 72 | out_tokens=16384 | gzip=0.084 ===
  most-repeated line x608: '}'
  --- TAIL (last 400 chars) ---
  牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰 牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰�詐 {     and牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰� and牰牰牰牰牰牰牰牰牰�, in this case牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰牰

=== req idx 129 | out_tokens=16384 | gzip=0.066 ===
  most-repeated line x1317: '}'
  --- TAIL (last 400 chars) ---
  } /* and */ } /* and */ } /* and */ } /* and */ } /* and */ ం /* and */ } /* and */ } /*ానorms and andానorms and and and and and and and and and and and and and and and and and and and and and and and and andం /* and */ } /* and */ } /* and */ } /* and */ } /* and */ } /* and */ } /* and */ } /* and */ } /* and */ } /* and */ } /* and */ } /* and */ ం /* and */ } /* and */ } /* and */ ం /* and */

=== req idx 147 | out_tokens=16384 | gzip=0.141 ===
  most-repeated line x6238: '}'
  --- TAIL (last 400 chars) ---
  nd} } } } } and anys amounts. } and} } } } and} } } } } } and} } } } } } and} } } } } } Please. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 为中国  amounts tomography amount} } } } } } and} } } } } } Please. . . . . . . . . . . . . .  preparationiques amounts. } } } } } } Please. . . . . . . . . . . . . .

...

With this branch: just non-english languages.

=== req idx 25 | out_tokens=16384 | gzip=0.408 ===
  most-repeated line x1: 'tauluja seinille, mutta omistajat asettavat lisää tuhansia'
  --- TAIL (last 400 chars) ---
 suostutte. Meillä on toinenkin kirstu. Se sisältää saman verran, mikolia

=== req idx 131 | out_tokens=16384 | gzip=0.416 ===
  most-repeated line x1: 'Blätter, und jede'
  --- TAIL (last 400 chars) ---
 „ach Booten ausschaue. Es scheine dort etwas los zu sein.n und jetzt,

=== req idx 160 | out_tokens=16384 | gzip=0.333 ===
  most-repeated line x1: 'the campaign, which concluded with the _peace of Ryswick_.'
  --- TAIL (last 400 chars) ---
 served in the warank of captain and lieutenant-colonel in 1743. Heal

Submission Checklist

Signed-off-by: simondanielsson <[email protected]>
@github-actions

github-actions Bot commented Oct 6, 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 6188 --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.

@simondanielsson simondanielsson changed the title fix: gibberish bug for DPA [HIP] Fix out-of-bounds qo_indptr read in MLA metadata planner when head-folding Oct 6, 2026
@simondanielsson simondanielsson changed the title [HIP] Fix out-of-bounds qo_indptr read in MLA metadata planner when head-folding [HIP] Fix out-of-bounds read in MLA metadata planner when head-folding Oct 6, 2026
Signed-off-by: simondanielsson <[email protected]>
@simondanielsson simondanielsson changed the title [HIP] Fix out-of-bounds read in MLA metadata planner when head-folding [HIP] Fix out-of-bounds read in MLA metadata planner when head-folding Oct 7, 2026
@simondanielsson
simondanielsson marked this pull request as ready for review October 7, 2026 01:05
@simondanielsson
simondanielsson requested a review from a team October 7, 2026 01:05
@github-actions github-actions Bot changed the title [HIP] Fix out-of-bounds read in MLA metadata planner when head-folding [HIP] Fix out-of-bounds read in MLA metadata planner when head-folding Oct 7, 2026
@github-actions github-actions Bot added the HIP label Oct 7, 2026
@zufayu
zufayu requested a review from amd-ruitang3 October 8, 2026 02:09
@zufayu

zufayu commented Oct 13, 2026

Copy link
Copy Markdown
Contributor

@aiter-bot review

@aiter-bot

Copy link
Copy Markdown

aiter-bot — queued behind 1 review(s); expect to start in about 50 min. The box reviews one PR at a time.

@aiter-bot

Copy link
Copy Markdown

[ROCm/aiter] PR #6188 — [HIP] Fix out-of-bounds read in MLA metadata planner when head-folding

Teaches the MLA metadata planner's per-batch q/o helper to map head-folded pseudo-batch ids back through the fold before indexing the caller's unfolded qo_indptr, so non-uniform decode on a folded shape (e.g. DSv3 TP1/DP8 bf16, 128 heads on gfx942) stops reading past the tensor's end and emits row offsets in the folded space the decode kernel consumes.

Review (advisory): 🔴 HIGH RISK
Validation (deterministic): NOT RUN — REVIEW_AUTO_VALIDATE=0 (auto-validation disabled on this box) and no idle GPU (all 8 at ~98% use); the triaged target op_tests/test_metadata.py existed, so this is an environment gap, not a PR defect — the PR reports its new test_qo_fold_nonuniform failing on main and passing on head (author-run, not re-run here).
Perf (advisory): NOT RUN — REVIEW_AUTO_VALIDATE=0 and no idle GPU; the target ships a timing harness (the op_tests/test_metadata.py sweep) but no base-vs-head pair could be run, and the PR's own sweep table is head-only and pins uni_seqlen_qo=1, a path where the changed branch is compile-time discarded.

🔴 [verified] The changed planner (csrc/kernels/mla/metadata/v1_comm.cuh) feeds the persistent mla_decode_fwd path that vLLM/SGLang/ATOM MLA decode consume — the PR's own reproducer is a vLLM DSv3-0324 DP8×TP1 bf16 run — yet the PR carries only the HIP label, so the label-gated vllm/atom/sglang downstream jobs all skip and only the in-repo unit test runs before merge. Author must add ci:vllm (or ci:all) and require the downstream job green before merge.
⚠️ [verified] The fold fix is exercised only at fold factor 8 (FOLD_NHEAD=128 in test_qo_fold_nonuniform, op_tests/test_metadata.py), but on gfx942 the v1_2 host gate also folds 64-head bf16 (Kimi-K2.5 TP=1, DSv3 TP=2 → factor 4) and 32-head bf16 (DSv3 TP=4 → factor 2), and no test in this PR runs those production shapes through the new get_folded_begin/get_folded_bid path in csrc/kernels/mla/metadata/v1_comm.cuh (the default sweep pins nhead=16 fp8, which never folds). Author must extend the fold test to nhead 32/64 so the smaller fold factors are exercised too.
⚠️ [verified] check_qo_fold asserts only that reduce_final_map rows are in-range/monotone and that every (row, head) of o is written — q and kv_buffer are torch.randn with no reference compared — so a wrong kv_end or kv offset that still writes every row passes; the pre-existing causal trim at csrc/kernels/mla/metadata/v1_2_device.cuh:604-610 even computes (qo_start / qk_batch_ratio) % ori_seqlen_qo with ori_seqlen_qo == -1 on this path (x % -1 == 0), collapsing the trim to num_qo_tiles - 1 and ignoring curr_qo_tile_idx — would a multi-tile non-uniform folded batch then over-trim its later tiles? Author must add a value oracle (e.g. the same q/kv run unfolded at 16 heads with 8× the batches, compared via checkAllclose) or state why bounds-plus-coverage is sufficient.
⚠️ [verified] No base-vs-head timing of the changed code path exists: the non-uniform branch of csrc/kernels/mla/metadata/v1_comm.cuh now runs 2–3 runtime int32 divides per get_begin/get_end call, and the PR's own sweep table pins uni_seqlen_qo=1 — a template instantiation where that branch is if-constexpr-discarded — so even the author's head-only numbers time code that never executes the new divides. Author must measure base vs head on a non-uniform folded shape (e.g. the new test's shape at a realistic cudagraph batch count) and confirm the planner cost did not move.
📝 [verified] The v1_1 planner's host gate (csrc/kernels/mla/metadata/v1_1_device.cuh:685-692) still excludes 128 heads from folding while mla_decode_fwd folds 128-head bf16 persistent decode on gfx942, so a fast_mode=False caller on that shape gets planner-unfolded metadata for a folded kernel — the same mismatch class this PR fixes, pre-existing and off the default path (fast_mode defaults True). Reviewer should ask whether that door is dead or needs the same fold gate.

@zufayu

zufayu commented Oct 13, 2026

Copy link
Copy Markdown
Contributor

Where that review came from — I ran the bot on your PR to show what it does. It is not an automatic hook; nothing reviews your PR unless somebody asks.

Any reviewer on the aiter allowlist can ask for one, on any PR including their own. The trigger is a comment containing the words below — shown quoted here, because quoted lines deliberately do not trigger it:

@aiter-bot review

  • Reviews the PR at its current head. Comment again after pushing fixes for a fresh pass; a repeat on the same commit is deduped.
  • One review runs at a time on one box, roughly 20 minutes. If work is ahead of you the bot replies with your place in the queue, and if the runner is down it says so rather than leaving you waiting for a review that will never start.
  • The card is advisory. It never blocks a merge, 🔴 included — it is there to be argued with.

Feedback on the review itself is welcome; it is how the rules get better.

@zufayu
zufayu requested review from fangche123 and removed request for amd-ruitang3 October 15, 2026 08:48
@zufayu zufayu assigned fangche123 and unassigned amd-ruitang3 Oct 15, 2026
@zufayu
zufayu requested a review from amd-ruitang3 October 15, 2026 08:48
@github-actions

Copy link
Copy Markdown
Contributor

No activity for 15 days, so this is now labelled stale. A push or a comment clears it; keep-open exempts it. Nothing is closed automatically.

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

Labels

HIP stale The PR hasn't been updated in 2 weeks

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants