Skip to content

[HIP] [JIT] [Feature] MLA decode: add get_mla_decode_shape_support, backed by shared C++ head-fold/backend rules - #6107

Merged
okorzh-amd merged 15 commits into
ROCm:mainfrom
okorzh-amd:okorzh/mla-decode-shape-query
Oct 23, 2026
Merged

okorzh-amd merged 15 commits into
ROCm:mainfrom
okorzh-amd:okorzh/mla-decode-shape-query

Conversation

@okorzh-amd

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

Copy link
Copy Markdown
Contributor

Summary

Persistent MLA decode decides in several places whether a head count is native or gets folded into N/16 pseudo-batches of 16 heads, and those copies have drifted apart. This PR moves that rule, the mla_reduce_v1 (heads, head_dim) table and the asm-kernel remap/lookup into shared host-side C++ helpers. The planners, the reducer router, asm stage 1, mla_decode_fwd's fold/backend gate, the dense path of get_mla_metadata_info_v1 and decode_update_mla_metadata_v1 all use them.

It adds one public query, aiter.get_mla_decode_shape_support(...), which tells a caller before launch whether a shape is native, how far it folds, which backend runs it and whether a kernel exists. It also fixes two latent bugs off the vLLM path: get_mla_metadata_info_v1 under-sized its buffers in some modes, so the planner wrote past their end (commit A5), and decode_update_mla_metadata_v1 applied folds the planner never made (commit A6).

No kernel code changes. On gfx950 the fast_mode paths vLLM uses (fp8/fp8, and bf16/bf16 for the default KV-cache dtype) give byte-identical metadata and decode output on the captured grid (batch 1-2, short KV). The one exception is bf16 with 10 heads, which used to assert in get_mla_metadata_info_v1 and is now sized. The sparse sizing path, and a floor that keeps dense buffers from shrinking, still use the old Python rule (follow-up).

The first consumer is vLLM #54899, which today greps AITER source files to make this decision.

Motivation

  • A fold re-reads the KV cache. When the v1_2 planner does not treat N heads as native and N % 16 == 0, it emits N/16 pseudo-batches of 16 heads per request. Each pseudo-batch reads the request's whole KV range. vLLM decode-context-parallel (DCP) multiplies the per-rank head count by the DCP size. For example, a 96-head model at TP8 with DCP4 gathers 48 heads, which folds 3x. Padding Q to a native head count with replicated heads reads the KV cache once (table below).
  • The caller must know before CUDA-graph capture. The padded head count is a per-run constant: it sizes the get_mla_metadata_info_v1 buffers, goes into every get_mla_metadata_v1 build and sets the Q pad / O slice, all frozen into graphs. It cannot be found by trial. A planner or reducer miss is an AITER_CHECK that aborts the process (SIGABRT); an asm miss raises RuntimeError, but only at the first decode launch, after the buffers are sized and possibly inside graph capture. The answer also depends on the AITER version: since v0.1.21 ([HIP] FIX MLA the nhead fold error for cp round robin #4964), 96 heads is native on gfx950 fp8 at max_seqlen_qo <= 6, so padding 96 to 128 now costs 2-7% (measured on 0.1.21.post1) instead of saving time.
  • No AITER function answers this today. vLLM #54899 string-greps three source artifacts instead: the natively_supported initializer in v1_2_device.cuh, the MLA_REDUCE_CASE_EF list in reduce.cu, and hsa/<arch>/mla/mla_asm.csv (whose Gqa column is a post-remap tile id, not the model head count, and which can disagree with the arch-filtered build).
  • Inside AITER the rule is copied in six places, and the copies have drifted: the v1_0, v1_1 and v1_2 planners, mla_decode_fwd's Python gate, the get_mla_metadata_info_v1 sizing mirror and decode_update_mla_metadata_v1 (plus get_mla_decode_fwd_occupancy, which mirrors mla_metadata_cluster_multiplier).
    • The Python gate reads the arch with get_gfx() where the planner uses get_gpu_arch(), folds only range(32, 129, 16), asserts above 128 heads and handles fp16 differently.
    • decode_update_mla_metadata_v1 is a latent silent-correctness bug (nothing in AITER or vLLM main calls it). Its native set is a stale subset of the planner's, so it can apply a fold the planner did not make and rewrite the request and KV-range columns of the planned work_info without raising. gfx950 fp8 with 64 heads is one such shape; the new regression test covers it.

What padding saves downstream (MI355X, gfx950, fp8/fp8). The table compares the kernel time of mla_decode_fwd at the folded head count with the kernel time at the native head count it would be padded to. This is the padding #54899 would choose with this query. It was measured standalone, not on this branch.

Heads: folded -> padded Folded: fold ratio, time Native time at padded count (separate run) Speed-up AITER
48 -> 64 3x, 349.0 us 171.4 us 2.04x 0.1.21.post1
80 -> 96 (microbenchmark shape only) 5x, 440.1 us 231.7 us 1.90x 0.1.21.post1
112 -> 128 (microbenchmark shape only) 7x, 658.2 us 247.2 us 2.66x 0.1.21.post1
96 -> 128 (historical: 96 is native since 0.1.21) 6x, 464.1 us 185.3 us 2.50x 0.1.19
Benchmark setup
  • Benchmark: a single-GPU microbenchmark of mla_decode_fwd that mirrors vLLM's DCP decode call. Batch 52, qlen 1, 16384 KV tokens per request (one DCP-8 rank's shard of a 131072-token context), return_lse=True, persistent metadata.
  • Timing: kernel identity comes from rocprofv3. Times are kernel time only; they exclude the Q replicate and O slice.
  • Process drift: each head count ran in its own process. Absolute times varied by up to about 18% between sweeps (96 heads: 206.5-231.7 us; 128 heads: 210.3-247.2 us), so the three 0.1.21.post1 rows come from a single sweep.
  • Fold ratio: the fold ratio is the planner's. The KV re-read was measured directly (rocprofv3 FETCH_SIZE) only for 96 heads on 0.1.19, at 6.05x.
  • Shapes: no in-tree vLLM model gathers 80 or 112 heads.
  • End-to-end (historical, AITER 0.1.19, an earlier env-gated vLLM padding patch): a 96-head MLA model at TP8 with DCP8 (96 gathered heads), 52 concurrent requests, ISL 131072. MLA went from 459 to 169 us/layer and median ITL from 52.7 to 43.3 ms (-17.7%).

Changes

Commits:

  • A1: new host-only csrc/include/mla_decode_shape.h. The v1_0/v1_1/v1_2 head-count planning (native set, fold, hk_mtp_experimental, the gfx1250 FlyDSL PS1 route, acceptance, kPackedQoLenPerWg) moves unchanged into mla_decode_head_plan_v1_{0,1,2}(), together with mla_metadata_cluster_multiplier. The planners call the new functions; AITER_CHECK messages are unchanged.
  • A2: new csrc/include/mla_reduce_cases.h. The 24 reducer (heads, head_dim) cases become one X-macro that feeds both MLA_REDUCE_ROUTER and the new mla_reduce_v1_supports(heads, head_dim).
  • A3 (asm_mla.cu): the stage 1 and gfx1250 remap and kernel lookup move into a non-throwing mla_asm_decode_config() that returns Ok, RemapReject, NoKernel or ArchNotBuilt. On a miss, dispatch raises the same AITER_CHECK text as before. The stage 1 "cannot find suitable kernel" check, which could never fire, is removed.
  • A4: new pybinds get_mla_decode_head_plan_v1 and mla_reduce_v1_supports; new C entry points mla_decode_asm_query and mla_ps1_fp8_asm_query in module_mla_asm; new C++ mla_decode_backend() holding the former Python predicates in priority order FlyDSL PS1 (its 96/128-head PS1 FP8 asm sub-route, MlaBackend.PS1_FP8_ASM, first, unless AITER_MLA_DECODE_PS1_ASM=0) > opus > HK > asm; new Python get_mla_decode_shape_support and its result types. The backend rule takes two inputs [ASM] [HIP] [FlyDSL] Add pin gpr(nhead96/128) and round-robin DCP to persistent MLA PS1 FP8 decode for GFX1250 #5844 added: cp_round_robin (g_kv_indptr is not None, which lets FlyDSL PS1 run with round-robin CP) and use_ps1_asm. mla_decode_fwd takes its fold and backend from the C++ plan, and gains fast_mode=True.
  • A5: get_mla_decode_fwd_occupancy / _max_splits call the new pybind mla_metadata_cluster_multiplier_v1. get_mla_metadata_info_v1 (dense path) sizes its buffers from the C++ head plan, taking the max of the new and old size so no buffer shrinks. This fixes out-of-bounds metadata writes: for fast_mode=False folds, fp16 at qlen 5-7, and fast_mode with intra_batch_mode, the old sizing was smaller than what the planner writes. A sentinel-guarded sweep found 1,725 overflowing cases with the base sizing and 0 with A5's (none on the fp8/fp8 fast_mode path; run on the pre-review A5, and sizes have only grown since).
  • A6: decode_update_mla_metadata_v1 takes its fold from the planner instead of a private copy, with a regression test.
  • [ASM] [HIP] [FlyDSL] Add pin gpr(nhead96/128) and round-robin DCP to persistent MLA PS1 FP8 decode for GFX1250 #5844 (gfx1250 PS1 FP8 decode, already in main): its rules are moved into the shared helpers, not kept as separate copies: the 96-head FlyDSL PS1 clause into mla_decode_head_plan_v1_2 (A1), the cfg_mla_dsl lookup into mla_ps1_fp8_asm_config() (A3), and the round-robin CP gate and PS1 FP8 asm route into mla_decode_backend (A4). decode_update_mla_metadata_v1 picks up the 96-head clause through the planner (A6).

Design notes

  1. C++, not Python: a Python helper would be a seventh copy of a rule that has already drifted, and only module_mla_asm knows which asm kernels were built (GPU_ARCHS-filtered table).
  2. Raw ctypes.CDLL for mla_decode_asm_query: the compile_ops ctypes path always passes the current HIP stream, so it needs a device. The query takes a NULL stream and never launches, so arch= works without a GPU. It reuses build_ctypes_module, factored out of _ctypes_call.
  3. NONE_WRAPPED_OP for the 3 scalar pybinds: otherwise torch_compile_guard wraps them as custom ops and allocates a dummy device tensor per call.
  4. One backend per PR: no kernel, hsa/, optCompilerConfig.json or CI changes; host code only (auto-tags [HIP], [JIT]). The FlyDSL PS1 (JIT and PS1 FP8 asm), opus, HK and asm routes are selected, not changed.

Public API.

  • New: get_mla_decode_shape_support, MlaDecodeShapeSupport, MlaBackend, MlaAsmStatus.
  • Also exposed: aiter.ops.attention has no __all__ and is star-imported, so get_mla_decode_head_plan_v1, mla_reduce_v1_supports, mla_metadata_cluster_multiplier_v1, mla_decode_asm_query, mla_ps1_fp8_asm_query and env_flag_atoi also become aiter.* attributes. I can underscore-prefix them if maintainers prefer.
  • New keyword arguments: mla_decode_fwd(fast_mode=), and mla_version=, q_rope_dtype=, kv_rope_dtype= on get_mla_decode_fwd_occupancy / _max_splits.

Build impact. No new JIT module. The new symbols go into module_mla_metadata (3 pybinds) and module_mla_asm (2 C entry points). module_mla_reduce, module_pa_metadata and module_ps_metadata also recompile from shared sources, with no new symbols. JIT checks only that a .so exists, so a module_mla_metadata.so cached from before this PR makes mla_decode_fwd and get_mla_metadata_info_v1 fail with AttributeError: rebuild with AITER_REBUILD=1.

Usage

import torch, aiter

fp8 = torch.float8_e4m3fn  # gfx950
s = aiter.get_mla_decode_shape_support(48, 1, fp8, fp8)
# MI355X, at head: planner='v1_2', native=False, fold_factor=3, kernel_num_heads=16,
#   backend=MlaBackend.ASM, asm_status=MlaAsmStatus.OK,
#   asm_kernel='gfx950_ZN5aiter36mla_a8w8_qh16_qseqlen1_gqaratio16_psE', supported=True

def pad_target(n, qlens, q_dtype, kv_dtype, **kw):
    """Smallest head count >= n that is native, with a kernel, at every launched qlen."""
    def ok(p, q):
        s = aiter.get_mla_decode_shape_support(p, q, q_dtype, kv_dtype, **kw)
        return s.native and s.supported is True
    for p in [n, *range((n + 15) // 16 * 16, 129, 16)]:
        if all(ok(p, q) for q in qlens):
            return p
    return n

pad_target(48, [1], fp8, fp8, return_lse=True)  # vLLM DCP decode -> 64 on MI355X
  • How vLLM uses it (planned change for #54899). It calls the query once per run at builder init, because the result sizes CUDA-graph-captured buffers, and checks every (qlen, return_lse, causal, cp_round_robin) combination it can launch: nativeness is not monotone in qlen (96 heads is native at qlen <= 6 and folds 6x at qlen 7-8). vLLM will gate this on the AITER release that contains this PR.
  • Keyword arguments describe the call the caller will make: num_heads_k (must be 1), v_head_dim, return_lse, causal, persistent, cp_round_robin, page_size, fast_mode, intra_batch_mode. arch= answers for that arch without a device (the JIT modules must still be built); enable_experimental= and flydsl_ps1= override the env flags. Results are cached (get_mla_decode_shape_support.cache_clear()).
  • Fields: natively_supported is the planner's native set. native also requires fold_factor == 1 and seqlen_fold == 1 (no head fold, and no v1_0 qlen fold of 128 heads), so the KV cache is read once. planner_accepts is False where get_mla_metadata_v1 would abort. arch, enable_experimental and flydsl_ps1 echo the values used.
  • supported is True, False, or None when it cannot be determined: the opus and FlyDSL PS1 JIT backends, or a failed asm query (asm_status=UNKNOWN). The ps1_fp8_asm backend is checked against its code-object table (mla_ps1_fp8_asm_query), so it answers True or False. A FlyDSL PS1 or PS1 FP8 asm route on a planner that folds the heads (fast_mode=False) is False, because those kernels read unfolded heads. reasons explains every "no".
  • Errors: bad arguments raise TypeError (a non-int or bool count, or a non-torch.dtype) or ValueError.

Performance

N/A: no kernel change.

  • Host cost: mla_decode_fwd's gate now parses 4 env vars (the same 4 flags main's gate reads), calls torch.cuda.current_device() and does 2 cached lookups. When num_kv_splits is None, get_mla_decode_fwd_max_splits adds one more of each, and the old code called that function too. This runs in eager mode and at graph capture, not on graph replay. Its cost was not timed.
  • Memory: no change on the vLLM path. In fast_mode=False, fp16 qlen 5-7, and fast_mode with intra_batch_mode, the metadata buffers grow to the size the planner already writes, and so does mla_decode_fwd's fp32 logits scratch (Breaking Change 2).

Testing

Setup

  • Comparison: head d89e7bcdfa against main e78e5a49f0. Both trees are clean.
  • Hardware and stack: MI355X (gfx950). torch 2.12.0+rocm10.0.0, HIP 7.15.26333, ROCm 10.0.0.
  • Image: vllm/vllm-openai-rocm@sha256:bdf0a71d472fe1ea32ec02f1cb74146c80036176f985c3cd8035b455bde1ff54 (tag nightly-rocm100-36768d1bfd39094681cdbc8cb37d4b31c0729c89).
  • Install and env:
    • The image's aiter is uninstalled, and each tree is mounted at /work.
    • Each tree gets its own fresh AITER_JIT_DIR.
    • GPU_ARCHS=gfx950, AITER_MLA_DECODE_PERSISTENT_MAX_BATCH=0.
  • Artifacts: scripts, raw logs, the GPU used for each run, and the launch command are in the [evidence tarball] and the [review reply].

test_mla_persistent.py matrix

The matrix runs 31 invocations, 2,587 configs per tree, on GPU 0 (main first, then head). It covers:

  • the full default matrix;
  • native and folded heads 8–144 at qlen 1/2/4;
  • planners fast, -nps (v1_0), v1_0 with LSE checks, and -mm v1_1;
  • -lse, causal and non-causal, and varlen;
  • page 16/64 and split limits 1/4/16/64;
  • LEGACY, 3BUFFER, DS32_OPUS, HK (experimental), opus, and the default batch gate.

Results per tree:

tree pass fail unsupported error crash
main e78e5a49f0 1875 302 177 24 209
head d89e7bcdfa 2063 283 213 12 16

There are 236 status changes between the trees:

change count what
crash → pass 181 v1_0/v1_1 memory faults on main
fail/error → unsupported 32 bf16-Q/fp8-KV nh128 under v1: main gave 85–98% wrong O or IndexError; head raises "no kernel"
crash → unsupported 12 fp8 nh32/64 ql2 under v1 with LSE
unsupported → pass 8 fp8-KV 144 heads now folds
error → pass 1 main's reference fold
pass → fail 2 fp8 nh16 ql2 ctx256 at 0.0506/0.0504 vs 0.05

The 2 pass → fail configs are fp8 kernel non-determinism, not a regression:

  • The planner maps are bit-identical between the trees.
  • The output sha changes on every repeat on both trees.
  • A full 01_default re-run gives main 161 fails and head 161.

What remains on head:

  • Crashes: 16. All also crash on main.
  • Errors: 12. The test's split reference raises IndexError on v1_0 nh128 ql2. The same keys error on main.

Accuracy:

  • O: 1,873 configs pass on both trees. 1,798 have bitwise-identical O. The 75 that differ are all fp8, in non-deterministic families.
  • LSE: of the 183 configs that check LSE on both trees, 179 are bit-identical. The other 4 hit the pre-existing v1_0 nh128 ql2 unwritten-row bug, which also reproduces on main.

Known on both trees:

  • page size > 1 fails, in test_mla.py as well;
  • 3BUFFER has no gfx950 byte-KV kernel (93 configs unsupported);
  • DS32_OPUS is 24/24 pass.

New and updated unit tests (head)

test result
test_mla_shape_support.py (gfx950 GPU) 11 passed, 1 skipped
same, host-only, GPU_ARCHS=gfx942;gfx950;gfx1250 9 passed, 3 skipped (need a GPU); 5/5 mutants caught
test_mla_decode_update_metadata.py 46 passed, 28 skipped, 6 xfailed
  • xfails: the 6 are a pre-existing qh32 lse_ps bug that leaves the LSE of unsplit work unwritten. It reproduces on main.
  • Mutant check: restoring main's fold rule fails 32 cases.

Existing tests, head vs main

test head main
test_mla_reduce.py 74 PASS, 0 FAIL same
pytest test_mla_decode_gate.py test_ps_metadata_sizing.py 88 passed same
test_metadata.py 27 shapes, all match same
test_pa_ps.py 192 passed, 24 warnings, 0 failed same
test_mla_sparse.py, seeded (pass/warn/fail) 530 / 317 / 113 529 / 318 / 113
test_mla_v40_persistent.py, experimental 8 passed, 38 warnings, 1 failed same
test_mla_persistent.py --softmax-underflow, CP=2 + -lse and non-CP output identical same

Behaviour capture and OOB sweep

Behaviour capture, head vs main:

  • 0 unexpected changes. Planner work plans are unchanged.
  • Sizes only grow.

Sentinel / OOB sweep, 6,144 keys per tree:

tree ok OOB writes planner raise crash
main 3756 234 2154 0
head 4086 0 2058 0

Host, graph and memory bench

The bench compares head against main in ABBA order. It covers 264 cases: fp8/bf16 × 16/48/128 heads × qlen 1/4 × batch 1/128 × KV 8192 × fast/fast_intra/v1_0/v1_1 × lse 0/1 × causal 1/0. Values are head/main geomeans.

metric fast fast_intra v1_0 v1_1
mla_decode_fwd eager CPU 1.007 0.992 1.020 1.009
eager GPU 1.000 0.996 1.008 1.003
graph replay 1.002 0.999 1.003 1.001
metadata bytes 1.000 2.138 1.000 1.000
logits+LSE scratch 1.000 2.536 1.000 1.000
  • get_mla_metadata_info_v1: 0.61–0.72 µs → about 1.25 µs per call.
  • get_mla_metadata_v1: CPU 1.000, GPU 0.996.
  • fp8 nh48 v1 with LSE: an 8-run ABBA repeat gives eager CPU 0.981–1.033 and replay 0.985–1.011.
  • fast_intra memory: the growth, up to 128 → 1024 MiB of scratch at nh128 ql4 bs1, sizes fast+intra like fast mode. That matches the v1_2 planner it actually runs, which can exceed main's v1_0-style bound when max_split_per_batch=-1.

Not covered

  • gfx1250: no hardware. Only host-side query/launch agreement was checked.

  • gfx942: PR CI only. CI on d89e7bcdfa is green, including the MI300X shards.

  • fast_intra: no O/LSE accuracy check.

  • LSE: not checked for bf16-Q/fp8-KV, -nps, varlen, or page > 1.

  • Page size > 1: accuracy is broken on main as well.

  • HK experimental N=144 msq=4: memory faults, the same fault class as main's existing faults at N=48/80/112. The query reports it unsupported.

  • Unit tests added/updated: test_mla_shape_support.py, test_mla_decode_update_metadata.py, test_mla_persistent.py -mm.

  • Same-environment A/B vs main: matrix, capture, OOB sweep, host/graph/memory bench.

  • MI355X (gfx950) GPU.

Breaking Changes

No public function, keyword or pybind is removed or renamed. External callers could notice these behaviour changes:

  1. Env flags are parsed like C++ atoi (the C++ planner reads the first two this way; AITER_MLA_USE_OPUS is Python-only and now uses the same parse).
    • AITER_ENABLE_EXPERIMENTAL: "1.0" and "1abc" now turn it on, and "0_1" turns it off. This affects everything gated by is_experimental_enabled(), including the JIT module build.
    • AITER_MLA_DECODE_PS1_FLYDSL and AITER_MLA_USE_OPUS used to require exactly "1"; "2", "01" and " 1" now also enable them.
    • AITER_MLA_DECODE_PS1_ASM (new in main with [ASM] [HIP] [FlyDSL] Add pin gpr(nhead96/128) and round-robin DCP to persistent MLA PS1 FP8 decode for GFX1250 #5844, default "1"): main enables it only for exactly "1"; the branch parses it with atoi and the same default, so "2" and " 1" also enable it, and "1abc" does too.
    • Migration: set these flags to exactly 0 or 1.
  2. Device requirement and buffer sizes.
    • get_mla_metadata_info_v1 (all paths, sparse included), get_mla_decode_fwd_occupancy and get_mla_decode_fwd_max_splits now need a HIP device and build or load module_mla_metadata on first use. Before, they were pure Python and honoured GPU_ARCHS; now the arch comes from the current device (the CU count still comes from get_cu_num()). Migration: tooling that sized buffers on a GPU-less host must now run on a device.
    • Dense buffers grow to the size the planner already writes (the A5 out-of-bounds fix): up to 7x per buffer for fast_mode=False folds (e.g. bf16, 112 heads), up to 2x for fp16 at qlen 5-7, and for fast_mode with intra_batch_mode up to 32x per buffer at batch 1 in the captured grid (num_kv_splits=16, 256 CUs; 13x in total metadata bytes). mla_decode_fwd's fp32 logits scratch is sized from reduce_partial_map and grows with it.
    • The num_head_qo % 4 assert now fires only where the planner rejects the shape.
  3. decode_update_mla_metadata_v1 no longer folds shapes the planner treats as native: gfx950 fp8 with 32 heads at qlen != 4 and with 64 heads; gfx950 bf16/fp16 at every multiple of 16 above 16; gfx942 fp8 with 64 heads at qlen 1; the HK experimental shapes; gfx1250 fp8 with 96 heads and AITER_MLA_DECODE_PS1_FLYDSL on, which [ASM] [HIP] [FlyDSL] Add pin gpr(nhead96/128) and round-robin DCP to persistent MLA PS1 FP8 decode for GFX1250 #5844 made native in the planner but not in this copy. It also asserts max_seqlen_qo >= 1. Migration: pass the same max_seqlen_qo and dtypes that the metadata was built with.
  4. mla_decode_fwd:
    • fp8 with more than 128 heads and N % 16 == 0 (e.g. 144) now folds and runs.
    • Shapes that still have no kernel now raise RuntimeError ("cannot get heuristic kernel"), or AttributeError on the HK route, instead of AssertionError.
    • The fold follows the C++ arch and rule:
      • fp16 on gfx950 no longer folds. Persistent fp16 still has no kernel, so it still fails, just at a different point.
      • gfx1250 with 32/64/128 heads at qlen 1, and 96 heads at any qlen, no longer folds when FlyDSL is on but not taken (for example DCP without round-robin). The planner treats these shapes as native, so main folded Q against unfolded metadata. Either way the decode then reaches persistent gfx1250 asm, which raises on main and on the branch.
      • A byte (int8/uint8) KV buffer is planned as fp8 and always sent to asm. Its split upper bound also uses fp8, so it doubles with experimental on, gfx950 and heads x qlen == 64.
    • Migration: callers that build metadata with fast_mode=False should pass fast_mode=False here too.
  5. get_mla_decode_fwd_occupancy / _max_splits: with default arguments the results are the same, apart from the device requirement in item 2. Both fp8 variants (e4m3fn and e4m3fnuz) count as fp8.
  6. Raw ctypes callers of asm stage 1: causal is now a bool, so any nonzero value selects the causal kernel. Before, a value other than 0 or 1 was a kernel miss.

@okorzh-amd
okorzh-amd requested a review from a team October 2, 2026 19:40
@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 6107 --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.

@github-actions github-actions Bot changed the title [Feature] MLA decode: add get_mla_decode_shape_support, backed by shared C++ head-fold/backend rules [HIP] [JIT] [Feature] MLA decode: add get_mla_decode_shape_support, backed by shared C++ head-fold/backend rules Oct 2, 2026
@zufayu
zufayu requested a review from amd-ruitang3 October 3, 2026 00:34
@zufayu
zufayu requested review from shengnxu and removed request for amd-ruitang3 October 9, 2026 05:50
@zufayu zufayu assigned shengnxu and unassigned amd-ruitang3 Oct 9, 2026
@okorzh-amd
okorzh-amd force-pushed the okorzh/mla-decode-shape-query branch from 24e4513 to 72871e7 Compare October 12, 2026 22:28
okorzh-amd added a commit to okorzh-amd/vllm that referenced this pull request Oct 13, 2026
AITER's persistent MLA decode folds a head count it does not run natively
into num_heads/16 pseudo-batches of 16 heads, and each pseudo-batch reads its
request's KV range again. DCP gathers counts such as 48, 80 and 112 that fold
on gfx950 fp8, so the decode reads the KV cache 3, 5 or 7 times. Padding the
query to 64, 96 or 128 heads reads it once; on MI355X the MLA decode kernel is
2.04x, 1.90x and 2.66x faster.

Add VLLM_ROCM_AITER_MLA_PAD_TO_NATIVE_SHAPE (off|auto|force, default off).
With auto or force, the metadata builder resolves one padded head count per
run at init: the smallest multiple of 16 from the aligned count up that
aiter.get_mla_decode_shape_support (ROCm/aiter#6107) reports native and
supported at every (qlen, return_lse, causal) the non-cprr persistent decode
can reach. auto caps the pad at twice the aligned count unless the aligned
count has no kernel; force drops the cap. If the aligned count has no kernel
and no target fits, init raises with AITER's reasons. The persistent
schedule is planned at that count, carried on the decode metadata, and the
backend pads q and unpads o and lse with it. cprr keeps its own count.

This replaces the AITER source greps of the earlier version of this change
with the AITER query. auto and force need an AITER that has
get_mla_decode_shape_support and fail at init otherwise; off never calls it,
so the current AITER pin keeps working.

Size the shared persistent buffers for the elementwise max over every head
count and qlen planned into them. With cprr on, the plain decode plans its
own count into the cprr-sized buffers, and a folded count can need more
reduce entries than cprr's; the cprr-only sizing let it write past
reduce_indptr and reduce_final_map. This applies with off as well.

Signed-off-by: Oxana Korzh <[email protected]>
Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@shengnxu

Copy link
Copy Markdown
Collaborator

Thanks for the detailed baseline/head accuracy tables, known-failure analysis and test commands. Please complete the reproducibility/performance evidence for this host-path change:

  • Confirm or refresh the results for current head 72871e7 (the posted capture/test table cites 92c0037). Share the behavior-capture and sentinel/OOB sweep scripts and raw results, plus the exact container image tag/digest and copy-paste launch/build/env commands.
  • Add same-environment baseline/current-head measurements for eager host overhead, metadata/decode latency, graph capture/replay and scratch/metadata memory on representative modes. The historical padding benchmarks do not measure this PR, and the new host gate/buffer growth can affect performance.
  • Add gfx942 and gfx1250 coverage for the changed dispatch/backend rules, or link matching hardware CI results and state the remaining gaps.
  • Please also cover CP>1 without round-robin: the query passes 2 if cp_round_robin else 1 as cp_world_size (attention.py:1490), while mla_decode_fwd passes the actual value. On gfx1250 this can select PS1 in the query when the launch gate excludes it. Expose the actual CP world size or constrain the query contract, with a query-vs-launch regression.

Please retain the existing accuracy comparisons and include any failures/skips in the reproducible results.

@shengnxu

Copy link
Copy Markdown
Collaborator

Following up on my earlier review comment, please extend the persistent MLA regression coverage. Every valid case entering test_mla() in op_tests/test_mla_persistent.py goes through the changed metadata sizing/planner, even when run directly on one GPU without vLLM. Keeping the same .co does not establish that routing, metadata interpretation, workspace size, or performance is unchanged.

Please run the full existing default matrix on the current head, and cover the non-default paths separately:

  • Both the default fast planner and -nps. In this script, -nps still supplies work metadata and selects fast_mode=False, intra_batch_mode=True (v1_0); it does not bypass the changed persistent metadata path. Please also cover v1_1 separately with fast_mode=False, intra_batch_mode=False, which -nps does not exercise.
  • The supported Q/KV dtype combinations, native and folded head counts, single- and multi-token queries, --varlen, relevant page sizes/split limits, and LEGACY, 3BUFFER, and DS32_OPUS layouts. Explicitly identify unsupported configurations and skips.
  • --return_lse and supported causal/non-causal cases, comparing both O and LSE against the reference and the same-environment baseline. The new test_decode_agreement checks launch acceptance, not numerical correctness. Please include per-configuration accuracy and decode performance comparisons, together with the metadata/workspace and host-cost measurements requested above.
  • A separate regression for decode_update_mla_metadata_v1, including native/folded heads, multiple requests with different KV lengths, and the resulting O/LSE after an update. Its existing test block in test_mla_persistent.py is commented out, so running that script does not exercise this fix.

The posted 72-configuration run at 92c0037 is useful, but does not cover all of these modes. Please attach the current-head commands/environment, raw logs, and pass/fail/skip results, as requested in the earlier comment.

There also appears to be a concrete DS32_OPUS test regression at current head 72871e7: the call now passes fast_mode, but mla_decode_fwd_ds32 has neither that parameter nor **kwargs, and run_perftest forwards the keyword arguments unchanged. Binding the test call to that signature raises TypeError: unexpected keyword argument 'fast_mode'; removing the newly added keyword makes the binding succeed. This is a source/signature check, not a GPU run. Please remove the invalid keyword from this call or implement the intended interface semantics, then include a supported DS32_OPUS GPU regression in the results.

@okorzh-amd
okorzh-amd force-pushed the okorzh/mla-decode-shape-query branch from 72871e7 to 953af4b Compare October 20, 2026 00:50
okorzh-amd and others added 14 commits October 20, 2026 11:20
Add the host-only pure header csrc/include/mla_decode_shape.h with
MlaPlanner, MlaHeadPlan, MlaPlannerFlags, MlaDecodeHeadPlan and
mla_decode_head_plan() (per-planner v1_0/v1_1/v1_2 bodies). The bodies
are literal moves of the inline head-fold / native-support / acceptance
logic from the v1_0, v1_1 and v1_2 metadata planners, which now call the
header; get_gpu_arch() and the env reads stay at the call sites and the
AITER_CHECK messages are unchanged. mla_metadata_cluster_multiplier also
moves into the header. The v1_2 text is moved as of ROCm#5844, whose gfx1250
FlyDSL PS1 clause also covers 96 heads at any max_seqlen_qo.

No behavior change: planner/reduce/decode golden capture on gfx950 is
bit-identical to the pre-change baseline.

Signed-off-by: Oxana Korzh <[email protected]>
Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…_cases.h

Move the _AITER_MLA_REDUCE_FOR_EACH_ROW support matrix (ROCm#5481) out of
mla_reduce_kernels.cuh into the preprocessor-only
csrc/include/mla_reduce_cases.h, with the same 24 rows in the same order;
mla_reduce_kernels.cuh includes it, so MLA_REDUCE_ROUTER, the extern
template block and reduce_instances/ are unchanged. The one edit to the
moved text: the comment's "the extern template block below" now reads
"the extern template block in mla_reduce_kernels.cuh", so it stays true
in the new file.

Add mla_reduce_v1_supports(num_heads, head_dim) to mla_decode_shape.h.
It expands the same table, and it does not check dtype or work-group
count.

Signed-off-by: Oxana Korzh <[email protected]>
Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Move the stage1 head/qseqlen remap into a pure
mla_asm_decode_config(arch, q_type, kv_type, num_heads, nhead_kv,
max_seqlen_q, persistent, causal, has_lse, has_cprr) that returns an
MlaAsmDecodeCfg with a status (Ok=0, RemapReject=1, NoKernel=2,
ArchNotBuilt=3), a reason and the table key. The remap block is moved
literally; its three AITER_CHECKs become RemapReject with the same text.
gfx1250 gets its own remap (persistent/lse/cprr -> NoKernel; the
supported_variant list moved verbatim). Add
try_get_heuristic_kernel_mla() returning "" on miss;
get_heuristic_kernel_mla wraps it with the identical AITER_CHECK. Stage1
and the gfx1250 dispatch call the new function and throw the same
messages as before. The provably dead stage1 "cannot find suitable
kernel" check is removed. The cfg_mla_dsl lookup of mla_ps1_fp8_asm_fwd
(ROCm#5844) moves verbatim into mla_ps1_fp8_asm_config(), which returns
nullptr on a miss; the entry point keeps its AITER_CHECK. ROCm#6132's gfx950
non-persistent fp8 gqa64 qlen1 clause moves with the remap; its
total_q * kv_split <= 32768 check needs launch sizes, so the remap records
the bound in MlaAsmDecodeCfg::max_q_x_kv_split and stage1 raises the same
AITER_CHECK right after the remap.

Notes: status is enum class MlaAsmStatus : int (doc types it as int; a
ctypes packer must cast). A gfx1250 variant miss is RemapReject and
gfx1250 has_cprr is NoKernel (both unspecified in the doc). causal is
now bool, so a raw caller passing a value other than 0/1 gets the causal
kernel instead of a miss. The equally dead gfx1250 "cannot find suitable
gfx1250 kernel" check is kept.

No behaviour change: golden compare.py 0 unexpected diffs (gfx950),
device-free old-vs-new sweep identical for gfx942/gfx950/gfx1250.

Signed-off-by: Oxana Korzh <[email protected]>
Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Add get_mla_decode_head_plan_v1 / mla_reduce_v1_supports pybinds in
module_mla_metadata, the mla_decode_asm_query ctypes entry in module_mla_asm
(bound with ctypes.CDLL, NULL stream, device-free with an explicit arch), and
the public aiter.get_mla_decode_shape_support query (design doc §5.2-5.4).
The CDLL path is build_ctypes_module, factored out of _ctypes_call with
main's JIT_LIB_EXT (.pyd on Windows); the entry points export via AITER_C_ITFS.

mla_decode_fwd's native/fold gate and FlyDSL/opus/HK backend selection now
come from the same C++ helpers the planner uses (C++ arch, atoi env parse),
with a new fast_mode keyword (default True, today's behaviour) so the fold
follows the planner mode the caller ran. Intended changes: >128-head folds
(fp8 144 now runs), fp16, the gfx1250 fallthrough, the arch source, and
"2"-style env values. A byte KV buffer (3-buffer layout) is planned as fp8
like its callers plan it; non-native fp8 variants and byte KV always take
asm. is_experimental_enabled and the PS1 FlyDSL parses use atoi semantics.
AITER_MLA_USE_OPUS now uses atoi semantics too (previously only "1").

also takes 96 heads at any max_seqlen_qo and round-robin CP (new
cp_round_robin input), and 96/128 heads go to the new
MlaBackend.PS1_FP8_ASM (mla_ps1_fp8_asm_fwd) unless
AITER_MLA_DECODE_PS1_ASM (atoi, default 1) is 0; the query checks that
route against cfg_mla_dsl through the new mla_ps1_fp8_asm_query entry.
The query reports a FlyDSL PS1 or PS1 asm route as unsupported when the
planner folds the heads (fast_mode=False), since those kernels read
unfolded heads; mla_decode_fwd's dispatch is unchanged there. With
persistent=False the planner and reducer verdicts do not gate supported,
since that path never plans; launch-size bounds such as ROCm#6132's
total_q * kv_split <= 32768 are not checked.

Adds op_tests/test_mla_shape_support.py (device-free planner verdict,
asm LSE, non-persistent asm and gfx1250 PS1 backend checks, GPU planner
and decode agreement) and passes fast_mode at test_mla_persistent's
mla_decode_fwd call sites.

Signed-off-by: Oxana Korzh <[email protected]>
Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
get_mla_metadata_info_v1 (dense path) now takes qk_batch_ratio,
kernel_num_heads and packed_qo_len_per_wg from the C++ head plan
(get_mla_decode_head_plan_v1) instead of its Python mirror of the planner.
For now each buffer is the max of the plan-derived size and the former
mirror size, so no size shrinks on any shape (doc 5.5 rows 3-4; the shrink
the doc's 2.4 row 6 allows is left to a follow-up). The sizes grow where
the mirror under-sized the planner (v1_0/v1_1 folds, fp16 at msq 5-7).
The num_head_qo % 4 assert now fires only where the planner rejects the
shape, so N=10 bf16/fp16 fast_mode is sized instead of asserting. The
sparse path stays on the moved mirror (_mla_legacy_max_qo_tiles_per_batch,
which still resolves the arch with get_gfx()); it could not be proven to
match the head plan.

ROCm#5844's gfx1250 FlyDSL PS1 96-head sizing clause is honored by the
plan-based dense sizing (the head plan makes 96 heads native, so
max_seqlen_qo tiles per batch); the moved mirror keeps the clause, with
the atoi parse, for the floor and the sparse path.

get_mla_decode_fwd_occupancy / _max_splits call the new pybind
mla_metadata_cluster_multiplier_v1 with the C++ arch and env parse, and
gain mla_version and rope dtype parameters with backward-compatible
defaults. mla_decode_fwd passes fp8 for a byte KV buffer, the dtype the
planner is given.

Separate fix: with fast_mode and intra_batch_mode both on, the dense
work_info_set and reduce_partial_map are now at least the v1_2 (non-intra)
bounds; tile_cnt * num_kv_splits under-counts the v1_2 planner, which
num_kv_splits does not cap. The sparse path has the same under-count and
is left unchanged.

Signed-off-by: Oxana Korzh <[email protected]>
Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…nner

decode_update_mla_metadata_v1 kept a hand-written copy of the v1_2 head
fold rule, resolved with get_gfx() and an exact dtypes.fp8 check, which had
drifted from metadata.cu. Where it disagreed it mapped works to the wrong
request (e.g. gfx950 bf16 N=32: request 1's KV range became request 0's)
without raising. It now asks the C++ head plan (get_mla_decode_head_plan_v1
via _mla_metadata_head_plan: C++ get_gpu_arch(), atoi env parse, original
max_seqlen_qo, fast_mode=True) for qk_batch_ratio and the kernel head count.

Changelog (behavior change for external callers):
- The fold now matches what get_mla_metadata_v1 (fast_mode=True) planned.
  Shapes no longer folded: gfx950 fp8 N=32 at max_seqlen_qo != 4, gfx950
  fp8 N=64, gfx950 bf16/fp16 at any N > 16 with N % 16 == 0, gfx942 fp8
  N=64 at max_seqlen_qo == 1, and the AITER_ENABLE_EXPERIMENTAL HK
  (hk_mtp_experimental) shapes.
- gfx1250 fp8 N=96 with AITER_MLA_DECODE_PS1_FLYDSL is no longer folded
  either: ROCm#5844 made it native in the planner but not in this copy.
- float8_e4m3fnuz on gfx950 now counts as fp8, as in the planner.
- Callers must pass the max_seqlen_qo they planned with (>= 1, before the
  qlen > 1 -> 1 rewrite; now asserted) and the dtype_q_nope /
  dtype_kv_nope given to get_mla_metadata_v1. The commented-out caller in
  op_tests/test_mla_persistent.py that passes max_seqlen_qo=1 for
  decode_qlen > 1 is wrong under this contract.
- vLLM main (7e583e615c) does not call this function; it only uses
  get_mla_metadata_v1.
- The unused batch_size local is gone; the signature is unchanged.

Known limitations: only v1_2 (fast_mode=True) metadata is handled, as
before (v1_0's N=128 seqlen fold is not undone). The arch is resolved on
torch.cuda.current_device(), not the metadata tensors' device.

Test (op_tests/test_mla_shape_support.py): on the GPU the update leaves
the planner's work_info request/KV columns unchanged when no token is
added. It fails on the previous rule.

Signed-off-by: Oxana Korzh <[email protected]>
Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
mla_reduce_v1_supports is a pybind op bound through compile_ops, but in
NONE_WRAPPED_OP it sat after the ctypes.CDLL-bound mla_decode_asm_query.
Drop mla_decode_asm_query from the list: it is a plain Python function,
not a compile_ops op, so its entry was never consulted. The compile_ops
shape-query entries now form one group.

Signed-off-by: Oxana Korzh <[email protected]>
Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…4 rule

Review follow-ups on get_mla_decode_shape_support, so the query answers what
mla_decode_fwd does for the same inputs:

- New cp_world_size keyword (default 1, ValueError below 1). The planner used
  to get 2 if cp_round_robin else 1, while mla_decode_fwd passes the real
  value, so CP > 1 without g_kv_indptr showed the gfx1250 FlyDSL PS1 route
  that the launch rejects. The PS1 asm kernel lookup now keys cprr on
  cp_world_size > 1 as mla_ps1_fp8_asm_fwd does; stage-1 asm keeps keying it
  on g_kv_indptr (cp_round_robin).
- HK: ROCm#6455 made the route real (aiter.hk_mla_v32_decode_fwd), so it is no
  longer reported as undefined. It answers None, or False when the launch
  would be wrong: return_lse (no final LSE for unsplit work), causal=False at
  max_seqlen_qo > 1 (always masked) and round-robin CP (no g_kv_indptr). The
  reasons note that HK ignores q_scale/kv_scale.
- gfx1250 stage-1 asm needs page_size == 64. The rule moves into
  mla_asm_decode_remap_gfx1250 (NoKernel, so the dispatch keeps its own
  message), and mla_decode_asm_query takes page_size.
- gfx1250 A0: stage-1 asm routes answer False (require_gfx1250_asm raises).
- The gfx1250 LSE reason says LSE is valid only for gqa64 or kv_split > 1.
- Docstrings: only kv_layout="token_major" is described; fp8 Q is assumed
  to come with scales; persistent=True is the persistent route, and gfx950
  bf16 16-head qlen-1 decode can still downgrade at large batch.

Tests (op_tests/test_mla_shape_support.py, host-only): query vs the head
plan mla_decode_fwd actually requests, captured before launch, at
cp_world_size 1/4 with and without round-robin; PS1 cprr kernel choice;
HK verdicts; gfx1250 page size. Each new test fails when its fix is
reverted.

Signed-off-by: Oxana Korzh <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
mla_decode_gfx1250_dispatch takes no g_kv_indptr, so a round-robin CP call
ran without the global-position mask and returned wrong results. It now
fails with the same check mla_asm_decode_config (and so the shape query)
already applies.

Signed-off-by: Oxana Korzh <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
-nps selects fast_mode=False, intra_batch_mode=True (v1_0), and nothing ran
v1_1 (both flags off). -mm/--metadata_mode {fast,v1_0,v1_1} picks the
planner for get_mla_metadata_info_v1, get_mla_metadata_v1 and the
mla_decode_fwd calls; the default stays v1_0 with -nps, else fast.

Signed-off-by: Oxana Korzh <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
The function's block in test_mla_persistent.py is commented out, so nothing
checked the metadata it rewrites. The new test plans get_mla_metadata_v1
(fast_mode) for 4 requests with different KV lengths (1100, 37, 530, 2049),
moves them to new lengths with decode_update_mla_metadata_v1 (+1 each, and
+1/0/-1/0 through num_reject_tokens), and decodes with the updated plan:

- fp8/fp8 and bf16/bf16 at 16, 32, 48 (folded on gfx950 fp8), 64 and 128
  heads; planned max_seqlen_qo 1 and 2 (the qlen > 1 -> 1 rewrite); the
  parallel and the serial (AITER_MLA_META_USE_PARALLEL=0) planner fill;
- the updated works must tile every (pseudo-)request's new KV range, and at
  least one request must span several splits;
- O and LSE are compared with a fresh plan at the new lengths and with an
  fp32 torch reference.

On MI355X: 46 passed, 28 skipped (shapes the query does not report as
supported, serial fill on folded or qlen > 1 plans, and qlen-2 plans that
split per token), 6 xfailed. The xfails are fp8 with 32 heads: the
persistent qh32 qseqlen1 lse kernel leaves the final LSE of a request whose
work is not split unwritten, with fresh metadata as well, and on main too.
O is still checked for them. Restoring main's hand-written fold rule fails
30 of the cases.

Signed-off-by: Oxana Korzh <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
…fo_v1

An eager-mode A/B against main on MI355X (same image, same GPU, ABBA order)
showed what moving the gate into C++ cost on the host: mla_decode_fwd issued
about 8.7 us more per call (46.6 -> 55.3 us, fp8 16 heads, batch 32) and
get_mla_metadata_info_v1 went from 0.6 to 5.9 us. Graph replay, capture,
GPU kernel time and buffer sizes were unchanged. Most of the cost was five
env-flag reads parsed with a regex, two device-arch lookups and three
separate cache lookups per call.

- env_flag_atoi memoises the parse per raw value. The variable is still
  read on every call, so changing it at run time still takes effect.
- mla_decode_fwd's persistent gate is one call, _mla_decode_launch_plan. It
  reads the four flags as raw strings, and one cache keyed on them and on the
  device returns both the head plan and the split bound.
- get_mla_metadata_info_v1 caches its result on its arguments, the arch and
  the two env flags it depends on.
- The occupancy cache is keyed on torch dtypes rather than converted ids.

The issue time is now 47.9 us against main's 46.1. The rest is the four
env reads that main skips when it short-circuits. get_mla_metadata_info_v1
takes 1.2 us. The CP query-vs-launch test now captures
_mla_decode_launch_plan.

Signed-off-by: Oxana Korzh <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
…anner

torch_mla_extend_split_kv kept its own copy of the v1_2 head-fold rule to
undo the planner's 16-head pseudo-batches. Nothing else used that copy, and
it only matched fast_mode plans with 32..128 heads. With -mm v1_1, and with
the >128-head folds (144 heads, fold 9) that mla_decode_fwd now runs, the
reference read work_info batch ids it had not folded and raised IndexError.
That happened after the O check had already run, so the split-level
comparison was lost.

The reference now asks aiter.get_mla_decode_shape_support for the fold.
It passes the dtypes and the planner mode (fast_mode/intra_batch_mode) the
metadata was built with, which test_mla threads through. The 3-buffer
wrapper plans its byte KV as fp8, as mla_decode_fwd does. On MI355X the
fold the query reports matches the work_info batch ids for every
(dtype, heads, qlen, planner) combination probed.

Signed-off-by: Oxana Korzh <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
opus_mla_decode_fwd raises when cp_world_size > 1 and Q is not fp8, or when
it gets no g_kv_indptr. The query answered None (no availability table) for
both, the same as for a launch that runs. It now answers False with the
launcher's reason. The CP query-vs-launch test also asserts that CP without
round-robin on gfx1250 is unsupported, not only that it is routed to ASM.

Signed-off-by: Oxana Korzh <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
ROCm#6563 widened the gfx1250 FlyDSL PS1 route (32/64 heads at qlen <= 4 with
heads x qlen <= 128, bf16/bf16 on the FlyDSL JIT kernel, fp8 asm code
objects only) and narrowed 16 heads to qlen <= 4. On rebase those rules
were ported into mla_decode_head_plan_v1_2 and mla_decode_backend; these
asserts check the query reports them.

Signed-off-by: Oxana Korzh <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
@okorzh-amd
okorzh-amd force-pushed the okorzh/mla-decode-shape-query branch from 834eb48 to d89e7bc Compare October 20, 2026 16:26
@okorzh-amd

Copy link
Copy Markdown
Contributor Author

Following up on my earlier review comment, please extend the persistent MLA regression coverage. Every valid case entering test_mla() in op_tests/test_mla_persistent.py goes through the changed metadata sizing/planner, even when run directly on one GPU without vLLM. Keeping the same .co does not establish that routing, metadata interpretation, workspace size, or performance is unchanged.

Please run the full existing default matrix on the current head, and cover the non-default paths separately:

  • Both the default fast planner and -nps. In this script, -nps still supplies work metadata and selects fast_mode=False, intra_batch_mode=True (v1_0); it does not bypass the changed persistent metadata path. Please also cover v1_1 separately with fast_mode=False, intra_batch_mode=False, which -nps does not exercise.
  • The supported Q/KV dtype combinations, native and folded head counts, single- and multi-token queries, --varlen, relevant page sizes/split limits, and LEGACY, 3BUFFER, and DS32_OPUS layouts. Explicitly identify unsupported configurations and skips.
  • --return_lse and supported causal/non-causal cases, comparing both O and LSE against the reference and the same-environment baseline. The new test_decode_agreement checks launch acceptance, not numerical correctness. Please include per-configuration accuracy and decode performance comparisons, together with the metadata/workspace and host-cost measurements requested above.
  • A separate regression for decode_update_mla_metadata_v1, including native/folded heads, multiple requests with different KV lengths, and the resulting O/LSE after an update. Its existing test block in test_mla_persistent.py is commented out, so running that script does not exercise this fix.

The posted 72-configuration run at 92c0037 is useful, but does not cover all of these modes. Please attach the current-head commands/environment, raw logs, and pass/fail/skip results, as requested in the earlier comment.

There also appears to be a concrete DS32_OPUS test regression at current head 72871e7: the call now passes fast_mode, but mla_decode_fwd_ds32 has neither that parameter nor **kwargs, and run_perftest forwards the keyword arguments unchanged. Binding the test call to that signature raises TypeError: unexpected keyword argument 'fast_mode'; removing the newly added keyword makes the binding succeed. This is a source/signature check, not a GPU run. Please remove the invalid keyword from this call or implement the intended interface semantics, then include a supported DS32_OPUS GPU regression in the results.

@shengnxu Thanks for the review. I've updated the the and run additional tests on GPU. Testing part is the PR description is updated with new numbers.

zhiding512
zhiding512 previously approved these changes Oct 23, 2026

@zhiding512 zhiding512 left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Approving after an A/B of op_tests/test_mla_persistent.py default matrix, base e78e5a49f0 vs head d89e7bcdfa.

Setup: MI355X (gfx950), image vllm/vllm-openai-rocm@sha256:bdf0a71d472fe1ea32ec02f1cb74146c80036176f985c3cd8035b455bde1ff54, image's aiter uninstalled, each tree with its own AITER_JIT_DIR, GPU_ARCHS=gfx950, AITER_MLA_DECODE_PERSISTENT_MAX_BATCH=0. Each tree ran its own copy of the test script. 3 runs per tree on different GPUs (GPUs swapped between runs). Default matrix: nhead,qlen in 16,1 / 16,2 / 16,4 / 48,1 / 128,2 x Q/KV in {bf16,fp8} x 8 ctx x 8 batch = 960 configs (the fp8-Q/bf16-KV combination is unsupported and skipped by the script).

Accuracy: no regression.

  • bf16/bf16: 320/320 configs have decode:err == 0 in all runs on both trees.
  • err >= 0.05: 134-136 configs on base, 135-136 on head per run. All are fp8-KV configs (mostly ctx 21/64) and fail on base as well.
  • 3 configs flip across the 0.05 line only in one direction or the other (16,1 fp8/fp8 ctx64 b1; 16,2 fp8/fp8 ctx21 b5; 48,1 fp8/fp8 ctx64 b1). err varies 0.03-0.057 between repeat runs of the same tree, i.e. fp8 non-determinism, as already noted in the description.

Performance: no regression attributable to this PR. Geomean of mla_decode_fwd GPU time over 64 configs per row, min of 3 runs per config, speedup = base/head (>1 = head faster):

nhead,qlen Q/KV base us head us speedup
16,1 bf16/bf16 28.96 29.44 0.984
16,1 bf16/fp8 32.15 32.03 1.004
16,1 fp8/fp8 21.16 20.78 1.018
16,2 bf16/bf16 30.96 30.46 1.017
16,2 bf16/fp8 33.39 33.19 1.006
16,2 fp8/fp8 23.34 24.21 0.964
16,4 bf16/bf16 32.75 32.85 0.997
16,4 bf16/fp8 36.29 35.37 1.026
16,4 fp8/fp8 26.56 26.50 1.002
48,1 bf16/bf16 32.19 31.49 1.022
48,1 bf16/fp8 68.45 68.38 1.001
48,1 fp8/fp8 46.35 44.07 1.052
128,2 bf16/bf16 59.58 59.48 1.002
128,2 bf16/fp8 142.38 136.09 1.046
128,2 fp8/fp8 45.10 45.25 0.997

Overall geomean 1.009. Some individual configs differ by more than 10% in both directions (e.g. 48,1 fp8/fp8 small ctx ~+15-19%, 16,2 fp8/fp8 small ctx ~-8-10%). These are not tree-dependent: rocprofv3 shows the same stage-1 / reduce / metadata kernels in both trees, and same-GPU ABBA runs show the same tree flipping between two timing modes from process to process (e.g. 48,1 fp8/fp8 ctx21 b16: base 20.2 / 23.8 us, head 20.3 / 24.0 us; 128,2 bf16/fp8 ctx64 b3: both trees 35.1-35.8 or 39.4-39.6 us).

Not covered by this run: -nps, -mm v1_1, -lse, --varlen, 3BUFFER / DS32_OPUS layouts, host-side overhead, metadata/workspace size and CUDA-graph replay/capture. The earlier review requests for those remain with the author's data.

@zhiding512
zhiding512 dismissed their stale review October 23, 2026 03:52

Retracting my approval: the A/B run only covered the default test_mla_persistent matrix (no -nps/-mm v1_1/-lse/--varlen, host overhead, metadata size or graph checks).

@okorzh-amd
okorzh-amd merged commit bf38b91 into ROCm:main Oct 23, 2026
okorzh-amd added a commit to okorzh-amd/vllm that referenced this pull request Oct 23, 2026
AITER's persistent MLA decode folds a head count it does not run natively
into num_heads/16 pseudo-batches of 16 heads, and each pseudo-batch reads its
request's KV range again. DCP gathers counts such as 48, 80 and 112 that fold
on gfx950 fp8, so the decode reads the KV cache 3, 5 or 7 times. Padding the
query to 64, 96 or 128 heads reads it once; on MI355X the MLA decode kernel is
2.04x, 1.90x and 2.66x faster.

Add VLLM_ROCM_AITER_MLA_PAD_TO_NATIVE_SHAPE (off|auto|force, default off).
With auto or force, the metadata builder resolves one padded head count per
run at init: the smallest multiple of 16 from the aligned count up that
aiter.get_mla_decode_shape_support (ROCm/aiter#6107) reports native and
supported at every shape the plain (non-cprr) persistent decode launches:
qlen 1 with LSE under DCP, qlen 1..K without DCP, plus non-causal qlen 1..K
when the builder can see non-causal blocks. auto pads at most 2x and force
up to 128 heads. The aligned count is kept when nothing fits or when it is
16 or fewer. The plain persistent schedule is planned at the padded count,
the shared buffers are sized for the larger of it and cprr's count, and the
backend pads q and unpads o and lse with it. cprr keeps its own count.

The query merged in ROCm/aiter#6107 (bf38b9153a), after AITER v0.1.26, the
version vLLM pins. auto and force raise at init if AITER lacks
get_mla_decode_shape_support. off never calls it and leaves the backend as it
is, so the current AITER pin keeps working.

Signed-off-by: Oxana Korzh <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
okorzh-amd added a commit to okorzh-amd/vllm that referenced this pull request Nov 3, 2026
AITER's persistent MLA decode folds a head count it does not run natively
into num_heads/16 pseudo-batches of 16 heads, and each pseudo-batch reads its
request's KV range again. DCP gathers counts such as 48, 80 and 112 that fold
on gfx950 fp8, so the decode reads the KV cache 3, 5 or 7 times. Padding the
query to 64, 96 or 128 heads reads it once; on MI355X with AITER v0.1.27 the
MLA decode kernel is 2.43x, 2.00x and 3.16x faster (fp8, batch 52, 16K KV).

Add VLLM_ROCM_AITER_MLA_PAD_TO_NATIVE_SHAPE (auto|off|force, default auto).
With auto or force, the metadata builder resolves one padded head count per
run at init: the smallest multiple of 16 from the aligned count up that
aiter.get_mla_decode_shape_support reports native and supported at every
shape the plain (non-cprr) persistent decode launches: qlen 1 with LSE under
DCP, qlen 1..K without DCP, plus non-causal qlen 1..K when the builder can
see non-causal blocks. auto pads at most 2x and force up to 128 heads. The
aligned count is kept when nothing fits or when it is 16 or fewer. The plain
persistent schedule is planned at the padded count, the persistent buffers
are sized for both it and the unpadded (or cprr) count at every decode qlen,
and the backend pads q and unpads o and lse with it. cprr keeps its own count.
The fp8 non-causal qlen-2 guard checks the count the batch launches at, so a
padded 64/96/128 block is no longer refused for its unpadded 48/80/112.

The query is in AITER v0.1.27 (ROCm/aiter#6107), which vLLM pins. With an
older AITER, auto logs once and keeps the aligned count; force raises at
init. off never calls the query.

Signed-off-by: Oxana Korzh <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
yuychang added a commit to yuychang/sglang that referenced this pull request Nov 5, 2026
- Replace the reduce_instances/nh12_hd128.cu source-tree probe with aiter.ops.attention.mla_reduce_v1_supports
- A stale JIT-cached or prebuilt AITER no longer passes as having the 12-head reduce just because the source does
- An AITER without the query (older than ROCm/aiter#6107, e.g. the pinned one) keeps padding to 16 heads
- Test: force the padded 12-head path in one subtest so CI covers it whichever AITER is installed
okorzh-amd added a commit to okorzh-amd/vllm that referenced this pull request Nov 11, 2026
AITER's persistent MLA decode folds a head count it does not run natively
into num_heads/16 pseudo-batches of 16 heads, and each pseudo-batch reads its
request's KV range again. DCP gathers counts such as 48, 80 and 112 that fold
on gfx950 fp8, so the decode reads the KV cache 3, 5 or 7 times. Padding the
query to 64, 96 or 128 heads reads it once; on MI355X with AITER v0.1.27 the
MLA decode kernel is 2.43x, 2.00x and 3.16x faster (fp8, batch 52, 16K KV).

The metadata builder resolves one padded head count per run at init: the
smallest multiple of 16, from the aligned count up to twice it (at most 128),
that aiter.get_mla_decode_shape_support reports native and supported at every
shape the plain (non-cprr) persistent decode launches: qlen 1 with LSE under
DCP, qlen 1..K without DCP, plus non-causal qlen 1..K when the builder can see
non-causal blocks. The aligned count is kept when nothing fits or when it is
16 or fewer; a head count whose query raises is treated as unsupported. The
query is in AITER v0.1.27 and later (ROCm/aiter#6107). The plain persistent
schedule is planned at the padded count, the persistent buffers are sized for
both it and the unpadded (or cprr) count at every decode qlen, and the backend
pads q and unpads o and lse with it. cprr keeps its own count. The fp8
non-causal qlen-2 guard checks the count the batch launches at, so a padded
64/96/128 block is no longer refused for its unpadded 48/80/112.

Signed-off-by: Oxana Korzh <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
yuychang added a commit to yuychang/sglang that referenced this pull request Nov 18, 2026
…default launch

- Add _mla_decode_launch_schedule: decode and target verify take launch modes and splits from one place
- Opt-in: pass the planned fast_mode and intra_batch_mode, and None splits under SGLANG_AITER_MLA_AUTO_KV_SPLITS
- fast_mode is passed only when aiter's mla_decode_fwd accepts it (ROCm/aiter#6107; the gfx950-rocm720 pin lacks it)
- Opt-in off: module intra_batch_mode, no fast_mode, verify keeps forward_metadata.num_kv_splits (-1 under auto)
- Tests cover the opt-in schedule under both split modes, an aiter without fast_mode, and the unchanged default launch
yuychang added a commit to yuychang/sglang that referenced this pull request Nov 18, 2026
…utable persist flag

- Split _asm_cprr_verify_requested (asm verify backend, DCP, fp8 KV) out of _asm_cprr_verify_enabled
- _init_cprr_verify asks aiter on the request, so the persist block that runs later cannot leave it stale
- Pass kv_lora_rank to _init_cprr_verify instead of the whole ModelConfig
- Narrow the get_mla_decode_shape_support catch to its documented TypeError / ValueError; other errors raise
- State when _MLA_ASM_CPRR_NATIVE_QLENS loses its query lengths (sglang requiring ROCm/aiter#6107)
- Test the ask decision with persist off, the narrowed fallback, and that a broken aiter raises
yuychang added a commit to yuychang/sglang that referenced this pull request Nov 20, 2026
…th comments

- Turn the _is_gfx950 and is_zero_padded_h12_fp8_mla docstrings into comments above the def
- Drop the _fp8_q_asm_mla_skip_reason docstring
- State when to drop the fast_mode probe: once every pinned AITER includes ROCm/aiter#6107
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.

4 participants