Skip to content

[HIP] [JIT] Split mla_reduce launcher instantiation across TUs (121.6s -> 7.7s) - #5481

Merged
yhl-amd merged 1 commit into
mainfrom
perf/mla-reduce-split-tu
Oct 7, 2026
Merged

yhl-amd merged 1 commit into
mainfrom
perf/mla-reduce-split-tu

Conversation

@valarLip

@valarLip valarLip commented Sep 13, 2026 •

Copy link
Copy Markdown
Collaborator

Problem

module_mla_reduce takes 121.6 s to JIT-build, the slowest non-CK module in the repo. Its wall is one translation unit:

csrc/kernels/mla/reduce.cu 121.5 s
├ host pass 5.1 s
└ device codegen 116.2 s (96%)
header parsing (Total Source) 0.95 s

This is not a header problem. reduce.cu defines only 3 __global__ functions, but DISPATCH_MLA_REDUCE_KERNEL instantiates dispatch_mla_reduce_v1 23 × 7 × 2 = 322 times (support-matrix rows × NUM_WG_PER_BH × output type), emitting 630 kernels from that single TU — all serialised through one clang process.

The module's ninja parallelism is 1.0× on a 256-core host: adding compile workers cannot help, because the wall is one TU.

Why sharding works

Device codegen is strictly linear in instantiation count. Keeping the first R of the 23 router rows and timing --cuda-device-only:

router rows instantiations device ms/inst vs linear
23 322 117.32 s 364 1.00×
12 168 61.75 s 368 1.01×
6 84 30.38 s 362 0.99×
3 42 15.36 s 366 1.00×
1 14 5.61 s 401 1.10×

±1 % across a 23× range (the 1.10× outlier is hipcc's fixed ~0.3 s startup). Link cost is flat at 0.09 s throughout.

Approach

This applies the pattern module_moe_topk already uses (csrc/include/topk_gating_kernels.cuh + csrc/kernels/topk_gating/*.cu):

file role
csrc/include/mla_reduce_kernels.cuh (new) device code and dispatch_mla_reduce_v1, moved verbatim, plus extern template declarations for every launcher (336 after the rebase)
csrc/kernels/mla/reduce_instances/nh<N>_hd<D>.cu (new, one 7-line TU per row; 24 after the rebase) one TU per support-matrix row
csrc/kernels/mla/reduce.cu (1281 → 222 lines on current main) the router only; it calls launchers it no longer instantiates
aiter/jit/optCompilerConfig.json one directory entry added to module_mla_reduce.srcs (2-line diff)

_AITER_MLA_REDUCE_FOR_EACH_ROW is the single source of truth for both MLA_REDUCE_ROUTER and the extern template block, so the two lists cannot drift. A row added there without a matching TU in reduce_instances/ is not a silent fallback to a slow build: the .so still links (a shared object may leave symbols undefined), but the module then fails to import with an undefined dispatch_mla_reduce_v1 symbol.

MLA_REDUCE_CASE_IF is removed: every row is now an else if behind a leading if(false) {} so one table can drive them uniformly. That costs nothing — the host object disassembles with no dead compare, and -Wall -Wextra is silent on it.

No kernel logic, launch configuration, or exported signature changes.

Results

MI355X (gfx950), ROCm 7.1.52802, cold build:

before after
module wall 121.6 s 7.68 s (15.8×)
reduce.cu TU 121.5 s 2.1 s
slowest TU 121.5 s 7.6 s
TUs / parallelism 2 / 1.0× 25 / 21.6×
link 0.09 s 0.09 s
total CPU 127 s 165 s (+30 %)
.so 17.81 MB 18.05 MB (+1.3 %)

The router TU lands at 2.1 s, matching the 2.07 s of topk_gating_kernels.cu under the same pattern.

Verification

check result
op_tests/test_mla_reduce.py 74/74 PASS, identical case by case to the pre-change build
kernel symbols in the gfx950 code object the same 630 mangled symbols, diff empty
per-kernel codegen metadata all 630 identical across agpr/sgpr/vgpr counts, sgpr/vgpr spill counts, LDS and private segment sizes, kernarg size, max_flat_workgroup_size, dynamic-stack use, wavefront size
move fidelity of 836 device and 112 host statement lines, the only one not reproduced verbatim is { return (x + y - 1) >> y_log2; }, which clang-format expanded to three lines
op_tests/test_flydsl_mla_reduce.py unaffected (skips on gfx950)
clang-format --dry-run -Werror clean

Notes for review

  • .so now carries 24 fat-binary sections instead of 1 (23 before the rebase) (+1.3 % size). This is inherent to sharding and is existing production behaviour: module_moe_topk.so already ships 3, one per instantiation TU.
  • Total CPU is up 30 % — each TU reparses the headers (measured 1.82 s fixed per TU, from t(n) = 1.82 s + n × 373 ms). On a many-core host that buys 15.8× wall; under CI contention the speedup is smaller, but the module previously occupied one core for 122 s, so it is a net win under any contention.
  • mla_reduce_kernels.cuh is 1117 lines, over the 800-line guideline. It is the device half of a file that was already 1281 lines; this change reduces the largest single file rather than growing it, and adds no logic.
  • Further sharding was evaluated and deliberately not taken. At 46 shards (7 instantiations each) a shard costs 4.43 s, but mla_reduce_pybind.cu at 4.94 s then becomes the wall, so the module lands at 4.94 s for +42 s CPU and 23 more files; at 161 shards the wall does not move at all. The pybind TU is floored by <pybind11/pybind11.h> (2.98 s) and <pybind11/stl.h> (3.14 s) on their own, not by the size of rocm_ops.hpp.
  • Extracting warpReduce out of the 5707-line custom_all_reduce.cuh into a minimal header was prototyped: it saves only 0.21 s per TU (1.69 s → 1.48 s), because the floor is aiter_hip_common.h at 1.38 s and the rest of that header is uninstantiated templates. Not worth touching a header shared by many modules for 4 %.
  • A precompiled header would remove the per-TU fixed cost, but hipcc rejects both -x hip-header (language not recognised) and -x c++-header (cannot use -o with HIP's dual host/device output).

Rebased onto main (e4ceb9d)

Two commits landed on main after this branched, both in reduce.cu, and both are carried into the split:

main commit what it changed where it lives now
#5698: lift the 2 GiB limit on the final output / LSE device: seq/head folded into an int64 descriptor base (make_final_output / make_final_lse); host: kMaxSpanBytes check removed its 16 device hunks are applied to mla_reduce_kernels.cuh; the host check stays removed in reduce.cu
#5695: nhead 12 PS decode (12, 512) row in MLA_REDUCE_ROUTER F(12, 512) in _AITER_MLA_REDUCE_FOR_EACH_ROW (main's router order) plus reduce_instances/nh12_hd512.cu

Why this needed care: mla_reduce_kernels.cuh is a new file, so git reports no conflict in it, while main's removal of the 2 GiB host check merges cleanly. Resolving the one kernel-body conflict in reduce.cu the obvious way builds without a warning and leaves the old int32 final_out_byte_offset_base path unguarded. On such a tree a bf16 [32769, 128, 512] reduce never writes row 32768 and corrupts row 0, and an exactly-4 GiB [32768, 128, 512] one drops the last two elements of row 32767. #5698's own -b 16384 repro still passes there, so it would not have caught this.

The support matrix is now 24 rows: 336 launcher instantiations, 658 kernels, 24 instance TUs. The measurements above were taken at 23 rows.

Re-verified after the rebase against a build of main (MI355X / gfx950, ROCm 7.2.4):

check result
kernels vs main's single-TU build all 658 have the same mangled symbol, AMDGPU metadata and disassembly (2,605,182 instructions compared)
module_mla_reduce cold build 126.1 s on main → 7.9 s
undefined dispatch_mla_reduce_v1 symbols in the .so 0 (336 defined)
op_tests/test_mla_reduce.py 74/74 PASS
(12, 512) in bf16 and fp16, plus fp16 on (128, 512) and (16, 128) (run_case, 9 cases each) 36/36 PASS
bf16 [32769, 128, 512] reduce (4 GiB) rows 0, 32767 and 32768 all correct, as on main

clang-format was not re-run for the rebase; the only hand-edited lines are comments and the clang-format off row table.

Test plan

🤖 Generated with Claude Code

@valarLip
valarLip requested a review from a team September 13, 2026 07:02
@github-actions

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; main branch always runs both MI35X and MI300X
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 5481 --add-label <label>

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 opt this PR out.

@github-actions github-actions Bot changed the title [HIP] [Build] Split mla_reduce launcher instantiation across TUs (121.6s -> 7.7s) [HIP] [JIT] Split mla_reduce launcher instantiation across TUs (121.6s -> 7.7s) Sep 13, 2026
@github-actions

github-actions Bot commented Oct 7, 2026

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.

@github-actions github-actions Bot added the stale The PR hasn't been updated in 2 weeks label Oct 7, 2026
….6s -> 7.7s)

module_mla_reduce took 121.6 s to build, the slowest non-CK module in the
repo. Its wall was one translation unit: csrc/kernels/mla/reduce.cu at
121.5 s, of which 116.2 s (96%) was AMDGPU device codegen in a single clang
process. Header parsing was 0.95 s, so this was never a header problem.

reduce.cu defines only 3 __global__ functions, but DISPATCH_MLA_REDUCE_KERNEL
instantiates dispatch_mla_reduce_v1 23 x 7 x 2 = 322 times (support-matrix
rows x NUM_WG_PER_BH x output type), emitting 630 kernels from that one TU.
Device codegen is strictly linear in instantiation count (364-368 ms each,
+-1% across a 23x range), so the work shards cleanly.

This applies the pattern module_moe_topk already uses
(csrc/include/topk_gating_kernels.cuh + csrc/kernels/topk_gating/*.cu):

  - csrc/include/mla_reduce_kernels.cuh: the device code and
    dispatch_mla_reduce_v1, moved verbatim, plus extern template
    declarations for every launcher.
  - csrc/kernels/mla/reduce_instances/nh<N>_hd<D>.cu: one TU per
    support-matrix row, each instantiating its own row.
  - csrc/kernels/mla/reduce.cu: now the router only. It calls the
    launchers it no longer instantiates.
  - _AITER_MLA_REDUCE_FOR_EACH_ROW is the single source of truth for both
    MLA_REDUCE_ROUTER and the extern template block, so the two lists
    cannot drift. MLA_REDUCE_CASE_IF is gone: every row is an else-if
    behind a leading `if(false) {}` so one table drives them all. That
    compiles to nothing -- the host object disassembles with no dead
    compare, and -Wall -Wextra is silent on it.

No kernel logic, launch configuration or exported signature changes.

Measured on MI355X (gfx950), ROCm 7.1.52802, cold build:

  module wall        121.6 s -> 7.68 s   (15.8x)
  reduce.cu TU       121.5 s -> 2.1 s
  slowest TU         121.5 s -> 7.6 s
  link                0.09 s -> 0.09 s
  total CPU           127 s  -> 165 s    (+30%, headers reparsed per TU)
  .so                17.81 MB -> 18.05 MB (+1.3%, 23 fat binaries not 1)

Verified:
  - op_tests/test_mla_reduce.py: 74/74 PASS, identical case by case to the
    pre-change build.
  - All 630 kernels carry identical agpr/sgpr/vgpr counts, spill counts,
    LDS and private segment sizes, kernarg size, max_flat_workgroup_size,
    dynamic stack use and wavefront size. Codegen is untouched.
  - The move is verbatim: of 836 device and 112 host statement lines, the
    only one not reproduced is `{ return (x + y - 1) >> y_log2; }`, which
    clang-format expanded to three lines.
  - op_tests/test_flydsl_mla_reduce.py unaffected (skips on gfx950).

Rebased onto main e4ceb9d. Two main commits changed reduce.cu after the
branch point, and both are carried into the split:

  - #5698 (64-bit final output/LSE addressing): its device hunks are
    applied to mla_reduce_kernels.cuh, and its removal of the 2 GiB
    kMaxSpanBytes host check is kept in reduce.cu. The header is a new
    file, so a plain conflict resolution would have kept the old int32
    final_out_byte_offset_base code with the guard gone; a bf16
    [32769, 128, 512] reduce then never writes row 32768 and corrupts row 0.
  - #5695 (nhead 12 PS decode): (12, 512) is added to
    _AITER_MLA_REDUCE_FOR_EACH_ROW in main's router order, with
    reduce_instances/nh12_hd512.cu.

The row-table comment no longer says a missing TU fails the link: the .so
links with undefined symbols allowed and only fails at import.

Verified against a build of main on gfx950, ROCm 7.2.4:
  - all 658 kernels have the same symbols, AMDGPU metadata and
    disassembly (2,605,182 instructions) as main's single-TU build
  - module_mla_reduce cold build: 126.1 s on main -> 7.9 s
  - op_tests/test_mla_reduce.py 74/74; (12, 512) in bf16 and fp16, plus
    fp16 on (128, 512) and (16, 128): 36/36
  - a bf16 [32769, 128, 512] reduce writes rows 0, 32767 and 32768
    correctly, as on main

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@amd-ruitang3
amd-ruitang3 force-pushed the perf/mla-reduce-split-tu branch from 9ba588f to 095947a Compare October 7, 2026 05:01
@yhl-amd
yhl-amd merged commit bca9957 into main Oct 7, 2026
@yhl-amd
yhl-amd deleted the perf/mla-reduce-split-tu branch October 7, 2026 15:22
okorzh-amd added a commit to okorzh-amd/aiter that referenced this pull request Oct 12, 2026
…_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]>
okorzh-amd added a commit to okorzh-amd/aiter that referenced this pull request Oct 20, 2026
…_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]>
okorzh-amd added a commit to okorzh-amd/aiter that referenced this pull request Oct 20, 2026
…_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]>
okorzh-amd added a commit that referenced this pull request Oct 23, 2026
…acked by shared C++ head-fold/backend rules (#6107)

* [MLA] A1: move decode head-count planning into mla_decode_shape.h

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 #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]>

* [MLA] A2: move the mla_reduce (heads, head_dim) table into mla_reduce_cases.h

Move the _AITER_MLA_REDUCE_FOR_EACH_ROW support matrix (#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]>

* [MLA] A3: factor the ASM decode remap into mla_asm_decode_config

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
(#5844) moves verbatim into mla_ps1_fp8_asm_config(), which returns
nullptr on a miss; the entry point keeps its AITER_CHECK. #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]>

* [MLA] A4: expose the decode shape query and drive mla_decode_fwd from it

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 #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]>

* [MLA] A5: size metadata info and occupancy from the C++ planner rules

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.

#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]>

* [MLA] A6: take decode_update_mla_metadata_v1's head fold from the planner

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: #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] Group mla_reduce_v1_supports with the compile_ops shape-query ops

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]>

* [MLA] Shape query: take cp_world_size, model HK and the gfx1250 page64 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: #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] gfx1250 stage 1: reject round-robin CP instead of running unmasked

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]>

* [MLA] test_mla_persistent: add --metadata_mode to cover planner v1_1

-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]>

* [MLA] Add a numerical regression for decode_update_mla_metadata_v1

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]>

* [MLA] Cut the host cost of the decode gate and of get_mla_metadata_info_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]>

* [MLA] test_mla_persistent: take the reference's head fold from the planner

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]>

* [MLA] Shape query: report opus CP launches that abort

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]>

* [MLA] test_mla_shape_support: pin #6563's FlyDSL PS1 rules

#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]>

---------

Signed-off-by: Oxana Korzh <[email protected]>
Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants