Repository navigation
[HIP] [OPUS] [JIT] [MLA] gfx950 fp8 flat-row MTP decode: host planner, stage 1 and bf16 merge - #7415
Conversation
…d bf16 merge
Adds a decode path for fp8 MLA (576 / 512) with several query tokens per
request (MTP) at head counts the existing kernels pack poorly: 96 heads per
rank under 8-way round-robin context parallelism, and 12 or 16 heads without.
A request's rows are flat (token * H + head), so its tokens and heads together
fill 128-row chunks at any head count.
It has three parts, launched in this order every step:
- A host planner (opus_mla_decode_flat_plan) builds one int32 plan on the CPU:
per-workgroup item ranges, the work items {request, partial slot, rows, KV
range}, and the merge units. Each request's KV is cut into pieces balanced
over the XCDs and all their workgroups. Without CP the planner lets only an
XCD's last workgroup absorb a remainder and keeps every row of a piece seeing
at least one key (stage 1 is built with -ffast-math, so a row with no key
would produce NaN).
- Stage 1 (opus_mla_decode_a8w8_flat_32mx4_kernel, 256 threads, one
workgroup per CU) runs the items. A chunk that has a single piece writes out
and LSE directly; the others write a 128-row bf16 partial slot and LSE.
- A merge combines the partial slots of each split chunk by LSE, loading 4
partials per round trip with CP and 16 without (few rows, many splits per
chunk at 12 or 16 heads).
OpusMlaFlatDecode (aiter/ops/opus/mla_flat.py) keeps the plan, partial and
staging buffers at fixed addresses, so a CUDA graph captured around the decode
call replays with each later plan. The plan is built outside the graph and
copied from one of two pinned buffers on the current stream.
Requirements: gfx950, fp8 Q / KV with per-tensor descales, page size 1, one KV
head, a KV cache below 4 GiB, causal decode with the same query length for
every request, at most 1024 work items and 1024 rows per request.
op_tests/test_mla_opus_flat_decode.py checks the plan invariants (exact KV
coverage of every chunk, no row without a key, unique partial slots, merge units
that match the split chunks), checks the output and LSE against an fp32
reference at 96 heads with and without round-robin CP and at 12 and 16 heads,
over batch sizes 1-64 and mixed, short, and tail contexts (a last KV tile
shorter than the query), checks CUDA graph
replay with plans that change between replays, and checks the input checks.
Co-authored-by: Cursor <[email protected]>
🏷️ CI GuideRuns automatically on every PR:
Extended tests (opt-in via labels):
One backend per PR: PR title tags & labels: |
WAITING ON AUTHORPR Self-ReviewRevision Waiting for the PR author. The readiness report will appear after the self-review answers are complete for this revision. Questions to answer in the PR description
Edit the Missing or invalid answers
Shadow mode reports what would block but keeps the status successful. Set |
The flat-row decode planned one query length for the whole batch, but the kernel already reads a request's causal span from q_indptr and its rows from the work item, so only the host planner stood in the way of a ragged step. Give the planner a q_indptr instead of a q_len: a request's chunk count, row base and valid rows all come from its own token count. Add a second layout that groups an XCD's requests by chunk depth and apportions its workgroups between the groups, since the column layout sizes every column by the deepest request and leaves a worker idle above every shallower one. On a batch of 64 requests where every eighth verifies 8 tokens and the rest verify 1, the columns light up 74 of 256 workgroups and the buckets light up all 256. Both are reachable through build_plan_ragged; build_plan keeps its uniform signature for existing callers and still takes the column layout, which plans a single depth identically. 720 uniform configurations across head counts, batch sizes, query lengths, worker counts and the balance flag produce byte-identical plans before and after. Ported from the kimi-k3 endpoint patches by Rita Brugarolas Brufau.
|
Commit SummaryLets the requests of one call have different query lengths, and adds a depth-bucketed workgroup layout for such batches. A caller that passes a single query length gets the same plan as before, bit for bit. MotivationA speculative decode step accepts a different number of draft tokens for each request, so the requests of one step have different query lengths. The planner took one query length for the whole batch, so such a step had to be padded to its deepest request and the extra tokens computed and discarded. With 7 draft tokens and an acceptance rate of 0.8, a batch of 128 carries 481 real query tokens out of the 1024 the padded plan computes. Over half the stage-1 work is thrown away. At an acceptance rate of 0.5 it is 270 out of 1024. Padding also hides the imbalance from the planner: it sees one depth for the whole batch and cannot tell a request that needs 8 chunks from one that needs 1. Changes
This makes the Requirements bullet that reads "Causal decode with the same query length for every request in a call" no longer apply; the limit is now 1024 rows for the widest request rather than for every request. PerformanceSame protocol as the microbenchmark in the description: stage 1 plus merge, timed as CUDA graph replays, in µs. Each value is the median of 200 replays, before and after interleaved so that clock and thermal drift hit both alike, then averaged over three separate processes (run-to-run spread at most 3.9%). MI355X, fp8 Q / KV, 96 heads under 8-way round-robin CP, lognormal contexts with a median of 66k. Query lengths are drawn per request for 7 draft tokens plus one bonus token.
A batch whose requests all verify the same number of tokens measures 1.00x at every batch size, so no existing caller changes. Depth grouping carries most of the gain above batch 16. Below it the groups get more workgroups than they can use, over-split the KV, and cost 0.7-0.9x against the plain column layout; both still stay ahead of padding, so the floor is unchanged either way. Testing
Measured on gfx950 at 96 heads with CP only; 12 and 16 heads are covered by the op test but not benchmarked ragged. |
|
@aiter-bot review |
|
clean code : merge cu and op test |
@yhl-amd — please take a look. Triage: if GLM serves but its output is malformed it may be the ATOM framework (@valarLip); if the box, GPU, disk or network is unhealthy it may be the machine (@gyohuangxin). Re-comment |
1 similar comment
@yhl-amd — please take a look. Triage: if GLM serves but its output is malformed it may be the ATOM framework (@valarLip); if the box, GPU, disk or network is unhealthy it may be the machine (@gyohuangxin). Re-comment |
Co-authored-by: Cursor <[email protected]>
Keep one ctypes translation unit for opus MLA decode, and run the gfx950 flat-row cases from test_mla.py with the rest of the MLA op tests. Co-authored-by: Cursor <[email protected]>
|
@zufayu folded both in 9f8ba3b:
The kernel header, |
|
hi @zufayu, @fangche123, @amd-ruitang3 - can you please help review this pr. thanks |
|
@nehmathe2 does your PR need to work with ROCm 10? |
|
Thanks for the detailed write-up. I reproduced this on MI355X (single GPU, PR head 1. Wrong results on ROCm 7.2 without any error (blocking)Built in
With Since the kernel compiles and runs without error on the older toolchain, a user would get silently wrong attention. Could you either:
2. The test added to
|
| shape | batch | upstream opus | flat |
|---|---|---|---|
| 96 heads, CP, q_len 6 | 1 | 36.2 µs | 43.8 µs |
| 12 heads, no CP, q_len 6 | 1 | 36.2 µs | 54.6 µs |
This looks like the planner splitting a single short chunk across all workgroups, so the merge carries a large fixed cost. I haven't profiled it to confirm.
12/16/32 heads with CP at batch 16: up to about 20% slower.
q_len = 1 at 12/16 heads with short contexts: 10–35% slower.
Where the path clearly wins is batch ≥ 16 with q_len ≥ 2. Without CP, no shape regressed (median 1.12–1.38x). With CP, 64/96/128 heads never regressed, and 12/16/32 heads regressed by at most 18% on a few shapes.
Suggestions:
- Cap the split count for small batches or short local KV in the planner, or fall back to
mla_decode_fwdwhen the plan would be merge-dominated. - Document the shapes where callers should keep using the existing path.
- Add batch 1–2 to the performance table, since low-concurrency serving hits those.
4. Minor
- The PR description lists
csrc/kernels/mla/opus_mla_decode_flat.cuandop_tests/test_mla_opus_flat_decode.py. After9f8ba3b9, that code lives inopus_mla_decode_fwd.cuandtest_mla.py, so please update the description. - For 128 heads × q_len 8 × batch 128 with CP,
opus_mla_decode_flat_planthrows because it exceeds the 1024 work-item cap. That matches the documented limit, but a clearer Python-side error that names the cap would help callers pick a fallback.
Repro notes
Timing setup:
- Metadata from
get_mla_metadata_v1withfast_mode=True,kv_granularity=16,max_split_per_batch=-1,return_lse=True. - Page size 1, contiguous
kv_indices, CP rank 3 of 8. - Each path in its own process, because capturing the default and opus
mla_decode_fwdgraphs in one process faults on replay.
I'm happy to share the sweep script and the raw CSV.
…t cap, host planner buffers - Build module_mla_decode_opus with --amdgpu-mfma-vgpr-form. ROCm 7.2 clang put the compiler's MFMA results in AccVGPRs, so O (all 256 AccVGPRs) was spilled next to the inline-asm PV MFMAs and the flat kernel returned wrong output. Validated on ROCm 7.2.4 and 10.1. - Planner: cap an XCD's columns at what the merge chain pays for, so a small batch is not cut into ~200+ pieces per chunk (96 heads CP q1 b1: 92.5 -> 34.7 us). Plans the cap does not bind are unchanged. - Planner host buffers are created on the CPU whatever the default device is. - A plan past item_cap raises a ValueError naming the need and the cap, and publishes an empty plan. - Document where callers should keep mla_decode_fwd. Co-authored-by: Cursor <[email protected]>
|
Thanks for the quick turnaround on 1. Wrong results on ROCm 7.2: resolved ✅
2.
|
15a64af7 |
d4c20908 |
|
|---|---|---|
| shapes >5% slower | 138 | 90 |
| shapes >2x slower | 32 | 0 |
- Target shapes (q_len 6, lognormal 66k context):
- 96 heads with CP: 1.30–1.63x over opus at batch 4–128.
- 12 heads without CP: 1.15–1.20x at batch 16–64.
- 96 heads, CP, q_len 6, batch 1 is now on par with opus: about 40 µs for flat vs. 40.7 µs for opus.
The remaining slow region is 12/16 heads at batch ≤ 4 and q_len 1–3, with and without CP. Some examples:
| shape | batch | best existing | flat | ratio |
|---|---|---|---|---|
| 16 heads, CP, q_len 1 | 4 | 23.3 µs (opus) | 42.0 µs | 0.56x |
| 16 heads, CP, q_len 1 | 1 | 22.1 µs (opus) | 35.9 µs | 0.62x |
| 16 heads, no CP, q_len 1 | 1 | 29.3 µs (opus) | 46.0 µs | 0.64x |
| 12 heads, CP, q_len 1 | 1 | 24.4 µs (opus) | 35.3 µs | 0.69x |
| 12 heads, CP, q_len 2–4 | 4 | 31.3–34.1 µs (opus) | 41.9–43.5 µs | 0.75–0.79x |
The mla_flat.py docstring already says to keep mla_decode_fwd for these shapes, and I think that is acceptable. Could you:
- add this residual small-batch range to the PR description (the "When to use it" guidance plus a few batch 1–4 rows in the performance table), and
- confirm that the caller you deploy with (ATOM / the serving integration) actually falls back to
mla_decode_fwdfor these shapes, rather than relying on users reading the docstring? If the dispatch rule lives outside this PR, a pointer to it would be enough.
4. PR description: still outdated
The description still lists csrc/kernels/mla/opus_mla_decode_flat.cu and op_tests/test_mla_opus_flat_decode.py, including the "62 passed" test command. Since 9f8ba3b9, that code lives in opus_mla_decode_fwd.cu and test_mla.py. Could you please update the file list and test instructions, and also mention the --amdgpu-mfma-vgpr-form build flag and the minimum validated ROCm versions (7.2.4 and 10.1)?
Once 3 and 4 are addressed, I'm fine with this from my side.
Setup: one MI355X, CUDA-graph replays, 2 passes per path, min of the two passes. The node is shared and occasionally showed single-pass spikes, so a regression was counted only if it appeared in both passes.
…la_flat.py docstring Docstring only, no code change. The ranges are now the flat path's speedup over the faster of the two mla_decode_fwd paths (default asm or AITER_MLA_USE_OPUS=1), per request class and batch range, from the same MI355X measurement as the "When to use it" section of the PR description (66k tokens of context per request, batch 1-64). The shapes that should stay on mla_decode_fwd are listed in one sentence. Co-authored-by: Cursor <[email protected]>
Thanks for re-running everything on One docstring-only commit, 3. Residual small-batch rangeDescription. There is now a "When to use it" section: a grid of new opus against the faster existing path (34 shapes, batch 1-64, three context sets), the guidance that follows from it, and a table of the residual cells in µs. The microbenchmark tables now have batch 1 and 2 rows. Your slow region reproduces: 12/16 heads at batch 1-4 with 1-3 tokens is 0.55-0.92x under CP and 0.61-1.00x without CP on ROCm 10.1, and 0.61-0.93x and 0.67-0.99x on ROCm 7.2.4. Dispatch. The rule lives in ATOM, in ROCm/ATOM#2961 (open, opt-in with One part of the residual range is not gated there: 12/16 heads without CP and q_len 2 or more take the flat path from batch 1. On ROCm 10.1, at batch 1-2 that is 0.73-1.04x the speed of upstream opus. ATOM's fallback is the default path unless the deployment sets I will keep 16 heads with 3-4 tokens on 4. DescriptionUpdated: the file list ( The microbenchmark and accuracy tables are re-measured at
|
…tokens Test only (check_opus_flat_decode in op_tests/test_mla.py); no kernel or planner change. - long contexts now log-uniform between 8192 and 262144 tokens. Its merge chains are as long as before: up to 34 pieces per split chunk with CP and 78 without (32 and 72 before). - Split-cap check, one request of 131072 tokens: 24 work items at 96 heads with CP and 168 at 12 heads without CP, within the same bounds. - Drop the unused `import math`. python3 op_tests/test_mla.py passes on the default path and with AITER_MLA_USE_OPUS=1, on ROCm 10.1 and 7.2.4 (MI355X). Co-authored-by: Cursor <[email protected]>
6c89823 to
56db871
Compare
…rts; default on Addresses the review of ROCm#2961 on top of main (merged in the previous commit) and aiter's merged OpusMlaFlatDecode (ROCm/aiter#7415). Needs the aiter follow-up that adds aiter.ops.opus.mla_flat.supports / min_batch / unsupported_reason and sizes the decoder from its widest request. - What the kernel can run and where it is the faster one are aiter's: opus_mla.py keeps only what ATOM knows (aiter backend, unshuffled dense KV, the gathered head width under DCP) and asks aiter for the rest, once, at builder construction. The 20-condition wanted() and the module-global plan buffer are gone; aiter is imported directly, with no ImportError probe. - ATOM_OPUS_MLA is on by default. The decode buckets that take the kernel are aiter's: 2 or more query tokens a request, and under round-robin DCP 96 or more rows a request, or without DCP 48 or 96 heads at any batch and 12 or 16 heads from batch 4. Every other decode keeps mla_decode_fwd. A refusal is logged once, at debug level unless ATOM_OPUS_MLA is set. - ATOM_OPUS_MLA_MAX_BS is removed: the builder's decoder is sized from max_bs and num_spec_tokens + 1. - finish_decode publishes the step's plan over the scheduled requests at their own query lengths; build_for_cudagraph_capture publishes an empty one. Both ask the same helper with the replay key (running_bs, max_seqlen_q), so a replayed graph finds a plan for the kernel it recorded. A TBO-split bucket keeps mla_decode_fwd; unsplit buckets of a TBO run take the kernel. - The KV cache's row width and size are checked on the first decode bucket after the pool exists. - AttentionMetaData declares opus_plan. _forward_decode runs it where the call is the decode it was built for (causal, the plan's query length and head width, inputs aiter takes), so a drafter's own decodes on the target's metadata, and a draft KV cache of another dtype, keep mla_decode_fwd. Tests: tests/test_opus_mla_dispatch.py (ATOM's gates, sizing, the layer call site) and tests/model_ops/test_opus_mla_gpu.py (gfx950: the kernel against mla_decode_fwd and an fp32 reference, graph replay with later plans, short contexts merged across the DCP group, and a real AiterMLAMetadataBuilder's prepare_decode / build_for_cudagraph_capture feeding a real MLAAttention._forward_decode, with the switch on, off and at its default).
…ks in supports Review of ROCm#9178: - min_batch now takes one token per request from batch 8 at 96 or more heads with CP and at 48 or more without, as the "When to use it" table says; it returned None for every q_len below 2, which contradicted the table. check_opus_flat_decode gains one-token shapes (96 and 128 heads with CP, 48 and 96 without) against the reference. - min_batch keeps 16 heads at 3-4 tokens without CP on mla_decode_fwd below batch 8 (0.92-1.00x of the default path at batch 4, 1.05-1.11x at batch 8), as committed in the review of ROCm#7415; the docstring's table now lists it. - supports() passes max_chunks to unsupported_reason, so it answers for a decoder built with a non-default max_chunks. - min_batch's docstring says the boundaries were measured on MI355X and are unmeasured on other gfx950 parts.
Summary
Adds
OpusMlaFlatDecode, an opt-in fp8 MLA decode path for MTP on gfx950 (MI355X). It has three parts: a CPU planner, a stage-1 kernel and a merge of bf16 partials. Rows are flat (token * H + head), so a request's query tokens and heads together fill 128-row chunks at any head count, and the requests of one call may have different query lengths. The code is part of the existingmodule_mla_decode_opus, which is now built with--amdgpu-mfma-vgpr-form. No existing decode path, planner or default changes.Motivation
MTP decode sends several query tokens per request. At some head counts the existing gfx950 kernels pack those rows poorly: 96 heads per rank under 8-way round-robin context parallelism (CP), and 12 heads per rank without CP. At query length 6 and batch 4 or more, with 8k and 131k tokens of context per request, this path is:
AITER_MLA_USE_OPUS=1) at 96 heads with CP, and 1.09-1.23x faster at 12 heads without CP;mla_decode_fwdpath.At batch 1-2 it is 1.05-1.36x the speed of upstream opus at 96 heads and 0.80-1.26x at 12 heads. The gain is not specific to that query length: at 96 heads with CP and 2-8 query tokens it is 1.00-3.54x the speed of upstream opus from batch 8 and 0.97-2.90x at batch 1-4. "When to use it" below lists the shapes that should stay on
mla_decode_fwd.This is the decode path we run in deployment for these shapes. The first revision of this PR (
d10965ef) compiled to the same device code as the deployed build: stage 1 (causal and non-causal) and both merges were compared instruction by instruction, with the same register, scratch and LDS usage. With every workgroup active, its planner produced the same plans as the deployed one on 4000 random batches, andout/ LSE were bit-identical on the shapes benchmarked then. The reviewed revision adds the split cap and per-request query lengths (see Changes).Why a separate path instead of the existing metadata and reduce
We first ran this kernel through the existing pipeline: flat-row tiles in
get_mla_metadata_v1, bf16 partials inmla_reduce_v1, and dispatch frommla_decode_fwd. That version, with an earlier build of the same stage-1 kernel, already got most of the gain at 96 heads. It got little of it at 12 heads with small batches, where this PR's planner and 16-deep merge matter. It also had to changeget_mla_metadata_v1,mla_reduce_v1andmla_decode_fwd, which every MLA decode caller goes through. This PR leaves all three untouched. The comparison was made at the first revision (d10965ef) and is not repeated here.Changes
Three parts, launched in this order every step:
opus_mla_decode_flat_plan, runs on the CPU and fills one int32 plan: per-workgroup item ranges, then the work items{request, partial slot, row range, KV range}, then the merge units{first slot, end slot, first row, rows}.q_lenis one token count or a per-request array. With mixed lengths, each XCD's requests are grouped by chunk depth (bucketed=True), so no workgroup idles above a shallow request. A uniform batch gets the same plan either way.-ffast-math, so a row with no key in its piece would produce NaN. Without CP the planner checks every piece and fails the plan otherwise. With CP see Requirements.kItemTiles,kXcdSplit,kMergePieceTiles,kMergePieceTilesDeep) have one value each, and the policy differs only between CP and no CP, as above. Swept one at a time on a scratch build at 8k and 131k tokens of context, each value costs under 5% in mean time against the best single value for that context: the item cost 4.9% at 8k and 1.6% at 131k, the 4-deep merge cost 3.5% at 8k, the others at most 0.4%.opus_mla_decode_a8w8_flat_32mx4_kernel(256 threads, one workgroup per CU), runs the items. A chunk with a single piece writesoutand LSE directly; the other chunks write a 128-row bf16 partial slot plus LSE.OpusMlaFlatDecode(aiter/ops/opus/mla_flat.py) keeps the plan, partial and staging buffers at fixed addresses, so a CUDA graph captured around the decode call replays with every later plan. The plan is built outside the graph and copied from one of two pinned buffers on the current stream.Requirements:
q_len * num_heads): up to 10 tokens at 96 heads, 64 at 16 heads and 85 at 12 heads. The row limit is128 * max_chunks(default 8; larger values are not tested). Without CP,planraises on some batches with more than 33 query tokens per request ("a piece would have rows that see no key").cp_rank + q_lentokens (query included) has query rows that see no key on this rank.mla_decode_fwdwrites 0 and an LSE of -inf for them; this path writes NaN and -3e38, so the caller has to mask those rows.max_batchrequests anditem_capwork items (default 1024) per step. When a step needs more (128 heads x 8 tokens x batch 128 under CP needs 1216),planraises aValueErrorthat names both numbers and publishes an empty plan.Build flag:
module_mla_decode_opusis built with-mllvm --amdgpu-mfma-vgpr-form. Stage 1 keeps O in all 256 AccVGPRs and issues its PV MFMAs as inline asm. Without the flag, ROCm 7.2's clang put its own MFMA results in AccVGPRs and spilled O next to the PV MFMAs, and the output was wrong. The flag applies to the whole module. On ROCm 10.1 the module's device code is the same with and without it. On ROCm 7.2.4 it also changes the code of the existingopus_mla_decode_a8w8_16mx1_32nx4kernels, whichop_tests/test_mla.pycovers withAITER_MLA_USE_OPUS=1.Files:
csrc/kernels/mla/opus/mla_decode_a8w8_flat_32mx4_64nx1.hpp(stage 1) andaiter/ops/opus/mla_flat.py(OpusMlaFlatDecode).csrc/kernels/mla/opus_mla_decode_fwd.cu: planner, both merges and the two ctypes entry points, added after the existing launchers. The existing code changes only in its header comment.aiter/ops/opus/mla.py: ctypes declarations of the two entry points;aiter/ops/attention.pyexports them next to the other opus ops.aiter/jit/optCompilerConfig.json: adds the stage-1 header to the sources ofmodule_mla_decode_opus, and the build flag.op_tests/test_mla.py:check_opus_flat_decode(), run bymain()on gfx950.Performance (if applicable)
Microbenchmark: upstream opus vs this PR
Three decode paths on the same inputs:
mla_decode_fwdwithoutAITER_MLA_USE_OPUS(the asm kernels).mla_decode_fwdwithAITER_MLA_USE_OPUS=1, the faster of the two existing paths.OpusMlaFlatDecode.Default and upstream opus are called with
return_lse=True, with plans fromget_mla_metadata_v1(fast_mode=True,kv_granularity=16,max_split_per_batch=-1). New opus plans withopus_mla_decode_flat_plan. All plans are built outside the timed region.Stage 1 plus merge, timed as CUDA graph replays, in µs. Each value is the median of 200 replays, interleaved across the three paths so that clock and thermal drift hit all three alike, then averaged over three separate runs (run-to-run spread at most 6.8%). MI355X, ROCm 10.1, at
484364f0, fp8 Q / KV, q_len 6, softmax scale 192^-0.5. Every request of a batch has the same context, 8k (8192) or 131k (131072) tokens. With CP, each rank holds a round-robin eighth of the context, and one rank is timed.Query length, 96 heads with 8-way CP: speedup of new opus over upstream opus, the faster existing path in every cell, as the min-max over batch 1-64. Timed as above, except that each path runs in its own process, averaged over two runs.
The 5 cells below 1.00x are at batch 1-4 with 131k contexts.
The other setups of a 96-head model at the same contexts, with 2, 4, 6 and 8 query tokens, against the faster existing path: 0.97-2.73x from batch 8 and 0.91-2.87x at batch 1-4 with 2- or 4-way CP; 1.03-2.23x at every batch without CP at 96 or 48 heads per rank; 1.07-1.32x from batch 4 at 12 heads per rank. At 24 heads per rank, and at 48 heads with 2 tokens, neither
mla_decode_fwdpath has an fp8 kernel to compare with.With ROCm 7.2.4 (PyTorch 2.10.0, on a second MI355X of the same node) a replay takes about 9 µs longer on every path. The microbenchmark then gives 1.05-1.60x over upstream opus at 96 heads and 1.04-1.18x at 12 heads from batch 4, and the query-length table 0.97-3.05x with 2-8 tokens.
These numbers replace those of the earlier revisions of this description, which were measured at other context lengths.
When to use it
Measured as the query-length table, against the faster existing path, at 8k and 131k tokens of context. Rows per request are
q_len * num_heads.mla_decode_fwd:OpusMlaFlatDecodedoes not choose between the paths; the caller does.Accuracy of the timed outputs
outand LSE are checked against an fp32 reference on the same inputs (Q and KV are standard normal values cast to fp8, with descales 1.0): every request of every cell behind the numbers above, 913 cells. By the checks of aiter's MLA decode tests (op_tests/test_mla_persistent.py), every cell passes:cal_diff(1 - cosine similarity to the reference)checkAllclose(rtol = atol = 1e-2): elements outsideEvery path's LSE is within 5.1e-5 of the reference. The RMS error relative to the reference's RMS is 0.0045-0.0242 for new opus, 0.0032-0.0229 for upstream opus and 0.0029-0.0148 for default: both opus paths feed the softmax probabilities to the PV product as fp8, and the asm kernels do not. ROCm 7.2.4 gives the same numbers.
New opus's RMS error is 0.46-2.24x upstream opus's from batch 8 (median 1.01x) and 0.75-4.17x at batch 1-4 (median 1.25x). The error of both opus paths rises as a request's KV is cut into fewer, longer pieces, and at small batches new opus cuts fewer: 5 against 64 for a one-chunk request at batch 1 under 8-way CP at 8k. The gap depends on how peaked the attention is: with descales of 0.37 and 0.61 on the same Q and KV (logits 4.4 times smaller, ROCm 10.1), new opus's RMS error is 0.98-1.14x upstream opus's and 1.00-1.11x default's, and no path has an element outside
checkAllclose's tolerance.At 1024 tokens of context, 4 of 455 new-opus cells are above the 5% bound with descales 1.0 (5.0-6.0%): 12 or 16 heads with 1-2 tokens under 8-way CP at batch 1-4, shapes that stay on
mla_decode_fwdabove. With the smaller descales none of them is.Testing
gfx950 only (MI355X).
python3 op_tests/test_mla.pyrunscheck_opus_flat_decode()on gfx950 and logsopus flat-row decode: passed; see "Validation and unverified scope".Documentation
aiter/ops/opus/mla_flat.pydocuments usage, the plan layout, the requirements, the build flag and when to keepmla_decode_fwd.Dependencies
Breaking Changes
None. The path is new and opt-in; no existing op, signature or default changes.
PR Self-Review
Reviewed revision
484364f0Behavior and intent
This adds a new opt-in decode path and changes no existing behavior. A caller builds a plan each step with
OpusMlaFlatDecode.planand runsOpusMlaFlatDecode.__call__.mla_decode_fwd,get_mla_metadata_v1andmla_reduce_v1are untouched and never dispatch to it. The only change that reaches existing code is the build flag ofmodule_mla_decode_opus(see Changes).The existing paths are insufficient for MTP decode at 96 heads with round-robin CP and at 12 heads without CP: they pack query rows per token or per fixed head tile. The flat-row layout with this planner and merge is 1.06-1.81x faster than the faster of them at query length 6 from batch 4, at 8k and 131k tokens of context (see Performance). At batch 1-2 and on other shapes it can be slower, and "When to use it" says where callers should keep
mla_decode_fwd.Validation and unverified scope
On MI355X (gfx950) at
d4c20908, with ROCm 10.1 (PyTorch 2.13.0) and with ROCm 7.2.4 (PyTorch 2.10.0), same results on both:module_mla_decode_opus;--amdgpu-mfma-vgpr-formis in the generatedbuild.ninja.python3 op_tests/test_mla.py: exit code 0 andopus flat-row decode: passed, on the default path and withAITER_MLA_USE_OPUS=1. Each run also prints 16 non-fatalcheckAllclosefailed!lines from the existing bf16 checkmla_decode-absorb [golden vs aiter_asm](nhead 128, decode_qlen 2, ctx_lens 21 and 64).python3 op_tests/test_mla.py -n 128,2 -c 21 64prints the same 16 on main at the merge base44301b66, so they do not come from this PR.python3 -m pytest -q op_tests/test_mla_shape_support.py op_tests/test_mla_decode_gate.py: 25 passed, 1 skipped (gfx1250 only).GPU_ARCHS="gfx942;gfx950"build of the module passescheck_opus_flat_decode()on gfx950. Plans andout/ LSE were compared withd10965efon the benchmark cells of the earlier description: bit-identical from batch 4 at 96 heads and from batch 2 at 12 heads; in the smaller batches the split cap cuts fewer pieces.The reviewed revision differs from
d4c20908only in the module docstring ofaiter/ops/opus/mla_flat.py, so the results above hold for it.check_opus_flat_decode()was run again with that change on both toolchains and passes.At the reviewed revision, with the module built at
d4c20908: the microbenchmark, the query-length grid and the accuracy pass under Performance, on both toolchains. The descale pass and the planner-constant sweeps ran on ROCm 10.1 only, the sweeps on a scratch build that reads the constants from the environment.Unverified:
max_chunksabove 8, are not tested.OpusMlaFlatDecode, and is not tested.d10965efand not run again at this revision.PR-specific question
Which architecture, dtype and shape boundaries select the changed kernel path, and what invariant prevents unsupported inputs from reaching it?
Nothing in aiter selects this path.
mla_decode_fwdnever dispatches to it; it runs only when a caller builds anOpusMlaFlatDecodeand calls it. Unsupported inputs are rejected before any kernel launches:opus_mla_decode_flat_fwdraises unless the device is gfx950, and the stage-1 body is compiled only for gfx950.[total_q, H, 576]tensor and KV a contiguous fp8[tokens, 576]tensor (page size 1, one KV head) below 4 GiB, with fp32 descales, bf16out, int32 index tensors and plan buffers of the expected sizes.planraises aValueErrorfor a batch abovemax_batch, a request wider than128 * max_chunksrows, aq_lenarray that does not match the batch or has a negative entry, and a step that needs more thanitem_capwork items. When the planner itself fails, as onitem_cap,planpublishes an empty plan, so a later call cannot run the previous step's plan on this step's tensors.-ffast-math, so a row that sees no key in its piece would produce NaN. Without CP the planner verifies every piece and fails the plan otherwise, andcheck_opus_flat_decode()asserts it on each no-CP plan it checks against the reference. With CP the planner's cut rule never cuts within one work item's cost of a request's end, so a row lacks a key only when the request is shorter thancp_rank + q_lentokens; those rows are not rejected and get NaN (see Requirements).Which shapes should take the path is the caller's decision; "When to use it" gives the measured boundaries.
Changed op tests
op_tests/test_mla.pygainscheck_opus_flat_decode(), whichmain()runs on gfx950. It is the only test of this path; the rest of the file testsmla_decode_fwdand does not reach it. It covers:outand LSE against an fp32 reference: 96 heads with 8-way round-robin CP at q_len 2, 4, 5, 6 and 8, and without CP at 4 and 6; 12 and 16 heads without CP at q_len 2, 4, 6 and 8; batch sizes 1-64; mixed, short and tail contexts (a last KV tile shorter than the query).q_lenentries, non-fp8 Q), and theitem_caperror with its empty plan.Profiling Data KIMI-K3, TP8 DCP8 c128 + Accuracy
ATOM nightly:
rocm/atom-dev:nightly_202610261615-rocm10.0(ROCm 10.0.0, PyTorch 2.11.0+rocm10.0.0, bundled aiter0.1.28.dev9+g41d4d8d7e.d20261026)Standalone Swebench accuracy test for c128 with opus mla kernel: resolved 188 / 200 = 94.00%
Profiling Data at 81920/1024 ISL/OSL, one mla layer comparison at decode[bs=128 tok=768 d=128 spec=5]
One MLA layer's decode is 2.07x faster than with the default asm kernel.