Skip to content

[FlyDSL] pa_decode: MXFP4 K/V in the shared PA tile kernel (gfx950, query_length 1) - #7056

Merged
valarLip merged 38 commits into
mainfrom
ganyi/flydsl-pa-decode-mxfp4
Nov 4, 2026
Merged

valarLip merged 38 commits into
mainfrom
ganyi/flydsl-pa-decode-mxfp4

Conversation

@ganyi1996ppo

@ganyi1996ppo ganyi1996ppo commented Oct 28, 2026 •

Copy link
Copy Markdown
Contributor

Ready for review once the pending items under "Not validated" are settled.

Summary

MXFP4 (e2m1 + e8m0 scale per 32) K/V decode on gfx950 is now a mode of the existing fp8/bf16 compile_pa_decode_tile (kv_dtype="mxfp4"), not a separate kernel. This replaces the dedicated kernel this PR carried before (pa_decode_mxfp4_kernel.py, deleted). pa_decode takes the MXFP4 cache directly; the separate pa_decode_mxfp4 entry was removed (review asked to merge it into pa_decode), and ATOM#2770 calls pa_decode.

Size against origin/main, 9 files: source +857/-51, tests +716/-50 (the previous head 13a5814 was +1637/-0, three new files). The additions land inside the original fp8 files: pa_decode_kernel.py, pa_decode/{context,traits,op_lds,op_gemm,op_epilog,pipeline}.py (+579/-47 with the kernel file), pa_decode.py (+278/-4), and the MXFP4 cases in the existing op_tests/test_flydsl_pa_decode.py.

Input: key_cache/value_cache are uint8 data views [pages, kv_heads, 128, 64], key_scale/value_scale uint8 e8m0 views [pages, kv_heads, 128, 4] of the same pages (shared page/head strides, multiples of 16 B). query is float8_e4m3fn (used as stored) or bf16 (quantized to e4m3 per head row in the kernel); output is bf16. work_plan=None (MXFP4 only) runs one task per sequence and writes the row directly; a plan with max_partitions == 1 is served the same way.

Supported: head_dim 128, block size 128, query_length 1, up to 16 query heads per KV head, scale bytes other than 0/255 in valid rows.
Refused with ValueError/NotImplementedError/TypeError: block size 16/64, fp16 output, other head dims, more than 16 query heads per KV head, query_length > 1, sliding window, sinks, plan-free output with strides other than the query's, a task over 4096 pages (pass a smaller max_context_length), plan-free max_partitions other than 1, a query or output spanning more than 2**31 - 1 bytes. Also not offered, unlike the previous head: tile_depth, exact bf16 Q, fp16 output, plan-free multi-partition. ATOM#2770 and vLLM use none of these.

Dependencies

Pages come from the MXFP4 KV write kernel in #7057; the index-score kernels are #7060 (decode) and #7061 (prefill). No shared kernel files; each PR adds its own lazy-export lines. ATOM integration: ROCm/ATOM#2770 (draft).

PR Self-Review

Reviewed revision

f2a0579

Behavior and intent

Before: the fp8/bf16 PA could not read an MXFP4 cache, and this PR added a second 660-line kernel plus wrapper and test file for it. After: one tile kernel with an MXFP4 mode. Each wave owns 64 tokens of the 256-token tile and all 128 dims, so softmax, P (registers) and O are wave-private, the tile loop has no barrier, and the four waves merge once after it. QK is one scaled MFMA (fp4 K x e4m3 Q); V is widened to bf16 through a wave-private LDS tile and read back transposed for the bf16 PV MFMA. The fp8/bf16 paths are not changed. Kernel name carries the dtype, direct-output and staged-page values.

Validation and unverified scope

MI355X (gfx950), image rocm/atom-dev:nightly_202610261558 (FlyDSL 0.4.0), FlyDSL cache off, 2026-10-29/30. Aiter tree at this head's kernel sources over origin/main cf831b2 unless noted.

  • python3 -m pytest op_tests/test_flydsl_pa_decode.py on gfx950 (one idle card, aiter tree = this head over a 0dd2716 container tree; FlyDSL 0.4.1): 265 passed, 16 skipped (16 MXFP4 unowned-row geometries filtered by design), 4 min 20 s cold. Not run on gfx942 or gfx1250.
  • Deliberate breaks are caught: one output element off by 0.05 (bf16, fp8, mxfp4), a NaN, a wrong fp8 value_scale, rolled MXFP4 K block scales, unowned NaN rows with mask_unowned_kv=False, a corrupted plan record, a refusal that raises nothing or the wrong error. With the K scale byte selection shifted 15 of the 30 MXFP4 cases failed (earlier run).
  • fp8/bf16 ISA: the 85 original specializations dump byte-identical to origin/main (combined sha256 107a1be7ca6f, base and this head).
  • Accuracy against an fp64 reference on the same e4m3 Q, bf16 output, rel-L2: 'mid' data 2.24e-3 (ctx 2048), 2.26e-3 (2000), 2.15e-3 (16384); random data 0.9e-3 to 1.1e-3. The same 'mid' number as the dedicated kernel.
  • ATOM end to end (ganyi/m31-mono-fp4-pr f328ca296, TP4, MXFP4 band, real acceptance, one run, aiter tree combo2 = origin/main 2db75fc + [HIP] fused_qknorm_idxrqknorm: write MXFP4 index-K and main KV caches, emit an fp8 main Q #7057/[FlyDSL] MiniMax-M3 index score: MXFP4 index-cache decode scorer #7060/[FlyDSL] MiniMax-M3 index score: MXFP4 index-cache prefill scorer #7061 + this PA): GSM8K 1319, 5-shot, c32: flexible 0.9439 +- 0.0063, strict 0.8954 +- 0.0084 (previous 0.9416/0.8757 on the dedicated PA).
  • vLLM TP4 on the first version of this replacement (b2febdaa15, same kernel sources, the then-standalone wrapper): GSM8K 1319 flexible 95.30 +- 0.58, strict 89.76 +- 0.83 (reference 95.38/89.76); fixed-B decode p50 at about 130k context B=16 9.48 ms (reference 9.50). One run each.

Not validated: the final dispatch form (pa_decode taking the MXFP4 cache) has not been run in vLLM; the vLLM numbers above are from the earlier standalone wrapper. The ATOM throughput A/B (c16 AgentX, same session, dedicated vs this PA) is not reported here; it is pending and does not gate this push. gfx942 and block size 16/64 are refused, not tested. CI has not run these tests: the PR is a draft.

Microbench, same card, CUDA graph, ctx 2048, group 16, 3 interleaved runs, median us per call, rows 8/32/64/128/256/512/4096:

path dedicated (13a5814) this head
planned 8.59 / 9.37 / 11.83 / 14.90 / 20.95 / 33.46 / 240.93 8.00 / 9.17 / 12.16 / 15.21 / 20.92 / 32.95 / 239.03
plan-free (max_partitions 1) 18.56 / 19.02 / 19.22 / 19.61 / 20.48 / 29.40 / 214.25 15.36 / 15.76 / 15.95 / 16.44 / 17.77 / 29.24 / 214.87

At 64 and 128 rows planned is 2.8% and 2.1% slower than the dedicated kernel; everything else is equal or faster. The existing fp8 flydsl PA is unchanged (origin/main vs this head, 3 runs: 7.71/9.27/11.47/18.70/28.77/52.86/412.94 vs 7.72/9.28/11.48/18.63/28.82/52.85/413.92). Fold resources: 132 VGPR, 75,728 B LDS, no spills.

Bandwidth (TB/s)

Same card, CUDA graph, head bc2b541. Cell = FP8 flydsl / MXFP4 planned, both with a bf16 query. Query is [rows, 16, 128], one query token per row, 16 query heads, 1 KV head, page 128 (GQA 16); rows = num_q.

num_q \ ctx 512 1024 2048 8192
8 0.112 / 0.056 0.222 / 0.111 0.451 / 0.219 0.968 / 0.616
128 1.573 / 0.807 2.629 / 1.270 3.426 / 2.122 5.192 / 4.170
512 3.474 / 2.884 4.448 / 3.660 5.200 / 4.636 5.965 / 5.659

TB/s is the nominal KV payload per call (rows x ctx x the KV bytes the cache layout holds for that dtype, MXFP4 block scales included) divided by the median per-call rocprofv3 --kernel-trace GPU-timestamped dispatch time of tile kernel plus reducer. It is not an HBM counter measurement, and the nominal KV bytes differ per arm (MXFP4 holds about half of FP8's), so equal TB/s does not mean equal time. I draw no speedup from this table.

Notes and limits:

  • Both arms share one plan from the old benchmark policy get_recommended_splits(rows, 1), which caps max partitions at 8/4/1 for rows 8/128/512. This is not the ATOM default plan; the numbers are for this benchmark's plan, not a deployment.
  • Short shapes are latency and reducer dominated (rows 8 and 128 at ctx 512/1024 take about 10 to 14 us, of which the reducer is about 4 us), so their TB/s is not a bandwidth statement. At ctx 512/1024 the plan has fewer tiles per sequence than its cap, so columns are not a pure ctx scaling.
  • Rows 512: MXFP4 runs the direct-output kernel with no reducer; FP8 still runs tile plus a one-partition reducer (about 4.3 to 4.6 us of its time). That reducer is part of the FP8 vs MXFP4 gap there. Elsewhere both arms launch tile plus reducer.
  • ctx 8192 is a generic kernel shape, not the MiniMax M3.1 sparse-attention deployment shape.
  • One card, one container, one sweep, gfx950; single run per cell, 10 CUDA-graph replays, no repeat-round claim. Median over all calls of the cell (320 to 7680). Not cold-cache, no lower-bound claim.
  • Raw rocprofv3 traces and per-cell audits are on the author's machine only, not attached here: /shared/amdgpu/home/gyu_qle/ganyi/task-pa-replace/r7056-bw-runs/ctx2d_1103_000249/ (main_audit.csv, summary.md). Scripts: .../r7056-bw-runs/scripts/prof_cmp.py, prof_audit.py.

PR-specific question

The MXFP4 cases are added to the existing test_flydsl_pa_decode.py, whose test_pa_decode already compares against an fp32 reference over logical K/V. The cases that MXFP4 adds and the existing ones cannot express: the e2m1/e8m0 page packing and dequantization reference, unequal 32-element scale blocks (a block/scale mix-up), NaN/Inf and e8m0 255 garbage in rows no sequence owns, plan-free versus one-partition-plan bitwise equality, empty rows, strided output, and the refusals listed above. None of these is covered by the fp8/bf16 cases.

Changed op tests

op_tests/test_flydsl_pa_decode.py keeps the existing pytest structure and its three test functions (test_pa_decode_plan, test_pa_decode, test_pa_decode_unowned_kv_rows); the MXFP4 cases are new parametrized cases and helpers in it, and the file is run with pytest. .github is unchanged; op_tests/test_flydsl_pa_decode_mxfp4.py stays deleted.

MXFP4 operand validation

Review found the MXFP4 branch of pa_decode skipped checks the generic path makes. Confirmed on GPU against the previous head: a non-contiguous block_tables, a windowed work_plan (with one partition the plan is ignored, with more it is used) and a query/output with a strided head_dim axis gave wrong output or an illegal memory access; a context_lengths/block_tables batch different from the query was not refused; key_scale=None raised an AttributeError; an output or user scratch (exp_sums, max_logits, temporary_output, used with more than one partition) on another device reached the kernel as a device pointer. Now refused, with the generic path's checks and messages: batch mismatch, non-contiguous or off-device block_tables/context_lengths, non-unit head_dim stride, non-tensor scales, output/scratch on another device, work_plan.sliding_window != 0. Eleven regression cases in the refused-input table (they fail on c57f106, pass here). pa_decode.py is otherwise unchanged and the generic path is not touched.

🤖 Generated with Claude Code

@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 (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
ci:windows Windows JIT op smoke test on the gfx1201 ROCm runner
ci:multi-gpu 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: DeepSeek-V4-Pro, MiniMax-M3-MXFP4
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 7056 --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.

ganyi1996ppo and others added 9 commits October 28, 2026 21:20
…length 1)

pa_decode_mxfp4 reads K and V as e2m1 data + e8m0 scales (one per 32 elements,
along head_dim), each as two uint8 views with their own page/head strides, so a
caller may use two tensors or one single-region page
[block_size x 64 B data][block_size x 4 B scale]. It shares pa_decode's work plan
and partition reducer and leaves pa_decode itself untouched.

Per 16-token tile and wave: QK is one mixed fp4(A) x fp8(B)
v_mfma_scale_f32_16x16x128_f8f6f4 with the K block's e8m0 byte as scaleA and Q
used as stored (query_scale, a [1] fp32, multiplies the logits); a bf16 Q takes a
reference path that widens K with v_cvt_scalef32_pk_bf16_fp4. V is widened to
bf16 (exact) into a wave-private LDS tile and read back transposed with
ds_read_b64_tr_b16 as the PV operand; P stays bf16. Invalid tokens get a zero V
scale and a -inf score, so tail garbage (e8m0 0/255 included) cannot leak.

The fp8 B operand of the 16x16x128 MFMA is not contiguous per lane: lane (g, s)
holds Q head s elements 16g..16g+15 in bytes 0..15 and 64+16g.. in bytes 16..31
(measured on gfx950; A lane group g holds K elements 32g..32g+31).

tile_depth defaults to 2: with independent blocks (2048 tokens/row, 16 q heads)
it is 0.2-2.2 us faster than 4 for 1-512 rows and equal at 4096. Arithmetic is
unchanged (a test pins default == depth 4 bitwise).

Tests: rel-L2 ~1e-3 vs an fp32 reference over the dequantized K/V (the bf16
output rounding floor), ctx 1..2048, block_size 16/64/128, groups 1..16, several
KV heads, plan tasks of 1..N tiles, garbage tails, query_scale.

Co-Authored-By: Claude <[email protected]>
… one task

With a plan of max_partitions == 1 each sequence is a single task, so the kernel
normalizes and stores the output row itself and the reduce kernel, its scratch and
the pmax/psum/pout partials disappear (direct_output, auto on for that plan).
Bitwise equal to split + reduce (tested for rows 1/8/64/512, bf16/f16, strided
output, graph replay). A context-0 row has no task and is left unwritten on this
path; the reduce path zero-fills it.

Co-Authored-By: Claude <[email protected]>
Tasks follow from the block index (CTA slot = sequence * P + part, P tiles-per-task
chosen on the host from max_partitions, default the planner's 2 * CU task budget),
so no plan_pa_decode launch and no work_info read: the context length, block-table
entries and Q are loaded in parallel. The kernel writes the reduce info itself and
zero-fills context-0 rows on both the reduce and the direct (P == 1) path.
Bitwise equal to the planned path wherever the two splits coincide; tested for
ragged contexts (1..5000, tasks of several tiles), block sizes 16/64/128, empty
rows, the default-split switch at 255/256/257 rows, graph replay.

Co-Authored-By: Claude <[email protected]>
…ew checks

Generated ISA is unchanged (82 specializations, identical hash).

Co-Authored-By: Claude <[email protected]>
Module-level gfx950 skip, checkAllclose + TFLOPS in the benchmark, and run the
pytest checks from main() so `python3 op_tests/...` (what CI runs) tests it.

Co-Authored-By: Claude <[email protected]>
…equences

The test no longer queries the GPU at import.

Co-Authored-By: Claude <[email protected]>
…ved)

launch_pa_decode_ps_reduce now takes the bound as max_partitions; same value
as before: min(parts, capacity, tiles).

Co-Authored-By: Claude <[email protected]>
@ganyi1996ppo
ganyi1996ppo force-pushed the ganyi/flydsl-pa-decode-mxfp4 branch from 8efda80 to 765c6cc Compare October 29, 2026 02:28
Removes the bf16-query reference path, the tile_depth and direct_output
arguments, multi-partition plan-free and the fp8 comparison in the test
benchmark. Generated ISA and outputs are unchanged for what remains.

Co-Authored-By: Claude <[email protected]>
… pytest

Plain check functions with asserts, a case table and a pandas summary, try/except
for the rejection cases (expect_error), one PA_DECODE name for the implementation
under test. Same 39 correctness cases and the same timing sweep.

Co-Authored-By: Claude <[email protected]>
@aiter-bot

aiter-bot commented Oct 30, 2026 •

Copy link
Copy Markdown

NOT READY FOR HUMAN REVIEW

PR Self-Review

Revision 8e06e6fe328b · mode shadow

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

  1. What behavior does this PR change, and why is the existing behavior insufficient?
  2. What did you validate, and what remains unverified? Include commands, hardware/configuration and results.
  3. What behavior would each changed op test fail on before this PR, and why is that coverage not already provided by an existing canonical test?
  4. For every changed op_tests/ file, what behavior does it cover and why is it not redundant? Write None if no op test changed.

Edit the PR Self-Review section in the PR description. Include the current revision SHA; this comment refreshes automatically.

Missing or invalid answers

  • FAIL — Reviewed revision must contain at least the first 7 characters of the current head SHA

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

@ganyi1996ppo

ganyi1996ppo commented Oct 30, 2026 •

Copy link
Copy Markdown
Contributor Author

Pushed e90aed1: the op test is rewritten in the aiter script style, with no pytest. Plain test_* check functions with asserts, a case table, a pandas summary printed before the timing table, try/except (expect_error) instead of pytest.raises, and one module-level name PA_DECODE for the implementation under test. Same 39 correctness cases as before (6 ctx_sweep, 2 garbage_tail, 4 heads, 4 task_shapes, 8 one_task_per_row, 3 plan_free_vs_reference, 4 plan_free_bitwise, 8 single cases) and the same timing sweep; a mismatch raises and the script exits non-zero. No kernel or wrapper code changed in this commit. Ran on an MI355 card with a fresh FlyDSL cache: python3 op_tests/test_flydsl_pa_decode_mxfp4.py exits 0 from the repo root and from /tmp.

…ode_mxfp4 directly

Replace the custom rel_l2/assert_rel with assertAllclose (rtol=atol=1e-2, at
most 1% of elements outside; the measured worst case is 0.1%), drop the
PA_DECODE alias, and make the timing section header say what is timed.
Same 39 cases and timing sweep.

Co-Authored-By: Claude <[email protected]>
@ganyi1996ppo

Copy link
Copy Markdown
Contributor Author

Current head: 13a5814. Read this one: SHAs quoted in my older replies on this PR belong to history that a rebase rewrote.

New at this head, test file only (no kernel or wrapper change): the custom rel_l2/assert_rel are replaced by assertAllclose (rtol=atol=1e-2, at most 1% of the elements outside; the worst of the 39 cases is 0.098%); the PA_DECODE alias is gone and pa_decode_mxfp4 is called directly; the timing section header now says what is timed (MXFP4 only). The per-row slice checks are dropped because the whole-tensor elementwise check covers every row at the same tolerance.

Ran on an MI355 card from a fresh tree with FlyDSL cache off: python3 op_tests/test_flydsl_pa_decode_mxfp4.py exits 0 from the repo root (26 s wall-clock) and from /tmp (14 s), 39 cases then the timing table. With the reference scaled by 1.05 (not committed) it exits 1. CI has not run this file (draft). The PR description now has the PR Self-Review sections, and the "0.3-1.2 us slower" statement is corrected to the table (0.29-0.91 us vs fp8 page 16).

r and others added 2 commits October 29, 2026 23:11
…e dedicated kernel

Fold MXFP4 K/V (e2m1 data + e8m0 scale per 32) into the fp8/bf16
compile_pa_decode_tile (kv_dtype="mxfp4"); pa_decode dispatches a uint8 key
cache to it and pa_decode_mxfp4 stays as a thin entry. Delete
pa_decode_mxfp4_kernel.py; the MXFP4 cases move into test_flydsl_pa_decode.py.

Co-Authored-By: Claude <[email protected]>
@ganyi1996ppo ganyi1996ppo changed the title [FlyDSL] Add an MXFP4 KV-cache paged-attention decode (gfx950, query_length 1) [FlyDSL] pa_decode: MXFP4 K/V in the shared PA tile kernel (gfx950, query_length 1) Oct 30, 2026
@ganyi1996ppo

Copy link
Copy Markdown
Contributor Author

Pushed 356de44: the dedicated MXFP4 kernel is replaced by an MXFP4 mode of the existing fp8/bf16 compile_pa_decode_tile, entered through pa_decode. pa_decode_mxfp4 stays as a thin entry with the same signature, so ATOM#2770 and vLLM are unchanged. Why: the fold reuses the fp8 pipeline (plan, reducer, page-id staging) and needs 761 source lines inside original files instead of a 989-line second kernel and wrapper; the tests move into test_flydsl_pa_decode.py (+345/-40) and the separate op test is gone.

Narrower than the previous head: block size 128, head_dim 128, bf16 output, no sliding window, query_length 1 only. fp8/bf16 ISA is byte-identical to main, the existing file passes 226 tests, ATOM GSM8K flexible 0.9439 / strict 0.8954. The final dispatch form has not been run in vLLM and the ATOM throughput A/B is pending. Numbers and scope are in the PR body.

Copilot AI balanced review requested due to automatic review settings November 3, 2026 07:29

Copilot AI 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.

🟡 Changes recommended

The promised MXFP4 compatibility entry point is missing, stored e4m3 queries are rejected, and unchecked query address spans can cause offset wraparound and incorrect loads.

4 open issues

Review effort: Balanced

Comment thread aiter/ops/flydsl/pa_decode.py Resolved
Comment thread aiter/ops/flydsl/pa_decode.py Outdated
Comment on lines +215 to +216
if query.dtype != torch.bfloat16:
raise TypeError(f"MXFP4 pa_decode needs a bf16 query, got {query.dtype}")

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in f73e934, which is newer than the commit this was reviewed on (74fc9d5). _pa_decode_mxfp4 accepts torch.float8_e4m3fn or bf16, passes query_dtype="fp8" or "bf16" from the tensor dtype, and the query loader copies stored e4m3 bytes with unit scale (output stays bf16). Both dispatch modes have e4m3 cases in test_pa_decode: mxfp4-g16-e4m3-q, mxfp4-g8-e4m3-q (planned) and mxfp4-plan-free-e4m3-q. They pass in the full run on gfx950 at c47551a (265 passed, 16 skipped). ATOM#2770 sparse_attn_mxfp4.py requires torch.float8_e4m3fn and passes it straight to pa_decode. Only e4m3fn is accepted, not fnuz: MXFP4 is gfx950-only, where e4m3 is OCP.

Comment thread aiter/ops/flydsl/pa_decode.py Resolved
Re-add the stored e4m3 query path removed in 491b929 (accepted by
ROCm/ATOM#2770's sparse_pa_mxfp4), selected by a Q_IN_DTYPE trait rather
than a bool. The in-kernel BF16 query to FP8 quantization and the BF16
MXFP4 path are unchanged.

Co-Authored-By: Claude Code <[email protected]>
Copilot AI balanced review requested due to automatic review settings November 3, 2026 08:01

Copilot AI 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.

🔵 Needs a closer look

Accepted Q/O layouts can overflow the kernel’s signed 32-bit offset arithmetic, causing output stores to overwrite other rows or access memory outside the allocation.

4 open issues

Review effort: Balanced

The kernel adds query row/head offsets in i32, so a query whose last head_dim
chunk ends past 2 GiB wrapped to an earlier row, and a direct output store did
the same. Refuse such query and output views before launch; two refused-input
cases in test_pa_decode cover them.

Co-Authored-By: Claude <[email protected]>
Copilot AI balanced review requested due to automatic review settings November 3, 2026 08:31

Copilot AI 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.

🔵 Needs a closer look

Human assessment is needed because fixed probability scaling can discard a finite attention contribution even when cache scales are valid and values fit BF16.

2 open issues
2 resolved since last review

Review effort: Balanced

akii96 pushed a commit to akii96/vllm that referenced this pull request Nov 3, 2026
Serve MiniMax-M3.1 with `--kv-cache-dtype mxfp4` and
`indexer_kv_dtype="mxfp4"` on gfx950, TP4 (one KV head per rank):

- the fused QK-norm / RoPE kernel writes MXFP4 K, V and index-K pages and
  hands back the main q as e4m3 (new `fused_qknorm_idxrqknorm_mxfp4` wrapper);
- the index scores come from AITER's FlyDSL MXFP4 scorers, the forced
  init/local blocks are pinned with AITER's sentinels, and the top-k is the
  one the NVFP4 indexer uses;
- the attend turns each query token's top-k into a one-block-per-page table
  and runs AITER's `pa_decode_mxfp4` on it, for decode and prefill.

The sparse block-table builders gain a `pages_per_block` argument (1 for a
page-128 cache). Needs an AITER with the MXFP4 FlyDSL ops (ROCm/aiter#7056,
vllm-project#7057, vllm-project#7060, vllm-project#7061). Mono, indexer CP, other TP sizes and the draft layers
are not covered.

Signed-off-by: ganyi <[email protected]>
Co-Authored-By: Claude <[email protected]>
Resolve conflicts in pa_decode_kernel.py and test_flydsl_pa_decode.py:
keep the MXFP4 stage_pages/direct_output support next to main's gfx1250
merge_partitions/cluster_merge, and keep both test skips and case keys.

Co-Authored-By: Claude Code <[email protected]>
Copilot AI balanced review requested due to automatic review settings November 3, 2026 11:06

Copilot AI 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.

🟡 Changes recommended

Critical issues remain because post-accumulation softmax scaling can produce FP32 overflow, while 32-bit block-table offsets can wrap and read incorrect page IDs.

4 open issues

Review effort: Balanced

Comment on lines +705 to +706
scale_b = fx.full(4, self.ctx.scale_qk * q_mantissa, fx.Float32)
scores = [frag_Ss[a] * scale_b for a in range_constexpr(t.NCHUNK)]
raise ValueError(f"{name} must be contiguous on the query device ({dev})")
if num_seqs == 0:
return
max_blocks_per_seq = block_tables.shape[1]
@valarLip

valarLip commented Nov 4, 2026

Copy link
Copy Markdown
Collaborator

@valar-cop review

@valar-cop valar-cop left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

some changes needed..

ci green.

for a in range_constexpr(t.NCHUNK):
self.kv.mxfp4_stage_v_bf16(v_raw, a, tile_valid)
scale_b = fx.full(4, self.ctx.scale_qk * q_mantissa, fx.Float32)
scores = [frag_Ss[a] * scale_b for a in range_constexpr(t.NCHUNK)]

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

scale applied after mfma can saturate the acc, byte 249 -> inf. fold it into the q e8m0 byte? otherwise fix the docstring and add a byte-249 case with fp64 ref

("context_lengths", context_lengths),
):
if t.device != dev or not t.is_contiguous():
raise ValueError(f"{name} must be contiguous on the query device ({dev})")

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

block_tables not bounded here, int32 index wraps past 2**31. same bound as query/output, or widen to i64


from .. import dpp_utils
from ..kernels_common import create_llvm_ptr
from ..moe_2stage_a16wmix.utils import _e8m0_byte_to_f32

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

why import from moe utils? move _e8m0_byte_to_f32 into mxfp4_gemm_common, it's already the home for e8m0 helpers

@valarLip
valarLip merged commit 5469555 into main Nov 4, 2026
@valarLip
valarLip deleted the ganyi/flydsl-pa-decode-mxfp4 branch November 4, 2026 01:37
fsx950223 added a commit that referenced this pull request Nov 4, 2026
Resolve conflicts with the gfx1250 in-kernel partition merges (#7079),
MXFP4 K/V (#7056) and the D64 BF16 wave-pair pipeline (#7384):

- Gfx1250Traits keeps context_partition_size alongside merge_partitions
  and cluster_merge; the per-wave FP8 and BF16 pipelines from main size
  their token ranges by the plan's partition, not KV_COMPUTE_BLOCK.
- Batched FP8 softmax now covers two or three query tiles; four tiles
  take main's per-wave pipeline, which is 7-20% faster on gfx1250
  (D128/page128/MTP4/GQA16, CUDA graphs). BF16 four-tile plain-V caches
  likewise take main's wave-pair pipeline (20-45% faster than the packed
  pipeline).
- PADecodePlan keeps arrival_counters and context_partition_size, passed
  by keyword; gfx1250-strict supports the same partition sizes as gfx1250.
- pa_decode bounds in-kernel merges and the reducer by the plan's
  partition size; MXFP4 accepts only 256-token partitions.
- Tests take main's new merge, split-group and MXFP4 cases; the plan test
  stays removed as on main.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
valarLip pushed a commit to ROCm/ATOM that referenced this pull request Nov 13, 2026
…ype fp4, --kv-cache-dtype fp4) (#2962)

* [MiniMax-M3.1] MXFP4 sparse KV pool and index-cache declaration

ATOM_M3_SPARSE_KV_MXFP4=1 with --kv_cache_dtype fp8 --index-cache-dtype mxfp4
declares the MXFP4 caches the aiter kernels read and write: one 8704 B field
(128 x 64 B e2m1 data, 128 x 4 B e8m0 scales) per (page, kv head) for K and for
V, and a single 8704 B field per block for the index key (136 + 68 B a token).

The sparse layers get a pool of their own: KvGeometry and MhaKvPool gain a
kv_format field ("" keeps every existing pool unchanged), so the MXFP4 pages sit
beside any dense layers' SHUFFLE pool.

Startup refuses plugin mode, a block size other than 128 and non-gfx950. Mono
declines MXFP4 KV, and indexer CP falls back with a warning. This commit only
declares the pool and the switches; the write and read paths follow.

Co-Authored-By: Claude Code <[email protected]>

* [MiniMax-M3.1] MXFP4 write path: one fused kernel writes K, V and the index key

rope_cache with the MXFP4 switches calls fused_qknorm_idxrqknorm with
kv_cache_dtype="mxfp4" straight onto the pool pages (no staging buffer and no
separate store kernel). The main q comes back as e4m3: one float8_e4m3fn q_out
is passed and the kernel writes the unit-scale saturating cast with no bf16 q
row (the final aiter API, ROCm/aiter#7057). A layer that reuses another layer's
top-k writes K and V only and passes skip_index_branch.

Adds dequantize_pages, the oracle the write test compares the cache against.
Needs aiter's fused_qknorm_idxrqknorm with kv_cache_dtype="mxfp4"
(ROCm/aiter#7057, merged).

Co-Authored-By: Claude Code <[email protected]>

* [MiniMax-M3.1] Score the MXFP4 index cache with aiter's FlyDSL scorers; page-128 block table

index_topk's decode and prefill take index_mxfp4: the scores come from aiter's
score_flydsl_fp4 / score_prefill_flydsl_fp4 over the two views (data and scale)
of the pool page, in the layout the Triton scorers produce, so the selection
and the emit after them are unchanged. pages_per_block is a parameter of the
emit now (8 for the page-16 SHUFFLE cache, 1 for page-128 caches), which makes
the block table one page a block for the MXFP4 KV.

The decode scorer's work map is built once per step into a persistent buffer
(capacity over every step width, bound = max_model_len / 128) by
make_sparse_decode_metadata, outside the graph. The decode scorer's fp32 score
buffer is persistent too: without an out the aiter scorer runs a torch.full(-inf)
in every layer. The metadata refills the buffer's view once per step and every
layer passes it as out. Where the scorer lays scores out transposed (S*H >= 16,
not TP4) the view is None and nothing changes.

Tests: scorers against a dequantised oracle; replay of a captured decode against
a refilled work map; the persistent score buffer equals a fresh -inf buffer bit
for bit over permuted, shortened and smaller steps. Needs aiter's
score_flydsl_fp4 and score_prefill_flydsl_fp4 (ROCm/aiter#7060, #7061, merged).

Co-Authored-By: Claude Code <[email protected]>

* [MiniMax-M3.1] MXFP4 KV attention through aiter pa_decode; ATOM_M3_INDEX_Q_FP8

sparse_pa_mxfp4 folds (token, kv head) into rows, hands the e4m3 q and the pool's
K and V pages (data and scale views of one 8704 B page) to aiter's pa_decode and
bypasses run_pa_decode's fp8 and ASM gates. attention_mha routes the sparse
prefill and decode through it, and asks the selection for a page-128 block table
(one page a block) and the MXFP4 scorer, with the step's work map and score
buffer on decode.

Decode keeps the planned path (the captured shapes are fixed): rows past the
planner's batch limit run in segments, each with a plan of its own, refreshed
once a step as the tail page is always selected. Prefill is plan-free
(work_plan=None): plan_pa_decode JIT-compiles a kernel specialised on the batch
size for every row count not seen before, and a prefill chunk has a new row
count almost every forward. One task and one direct write per row means one JIT
specialisation whatever the rows.

ATOM_M3_INDEX_Q_FP8 (off by default, refused without --index-cache-dtype mxfp4)
has the fused writer emit the indexer query as e4m3 and the scorer read it as
such.

Tests: decode and prefill against the dequantised oracle (Hkv 1 and 2); any row
count 1..700; plan-free bit for bit the planned kernel with a one-partition
plan; no new planner or PA kernel build across 12 new row counts.
Needs aiter's pa_decode with MXFP4 K/V (ROCm/aiter#7056, merged).

Co-Authored-By: Claude Code <[email protected]>

* [MiniMax-M3.1] MXFP4 review fixes: padded replay, TBO plans, FP8-q reuse key, TP2 scores

Build the MXFP4 work map and score view from the captured batch on a padded graph
replay; key the pa_decode plan by TBO ubatch; record the FP8 index-query dtype in
the top-k reuse key; leave a transposed score to the Triton selector; check
sparse_local_block at startup; stub the arch query in the CPU cache test; document
the two env vars; drop the unused require_supported and the personal-branch hint.

Co-Authored-By: Claude Code <[email protected]>

* [MiniMax-M3.1] Build the selector bounds from the captured batch on a padded replay

n_valid_column_per_row is head-major, so with more than one index head its head
offsets depend on the batch the graph was captured at, like the work map and the
score view. Build it from the padded lengths when they are given (MXFP4 index only).

Co-Authored-By: Claude Code <[email protected]>

* [MiniMax-M3.1] MXFP4 round 4: per-ubatch TBO score buffers, padded scorer batch, runtime gfx check

- Decode TBO gets its own MXFP4 index work map and score buffer per ubatch, so each
  ubatch builds them once a step instead of every layer.
- The padded decode scorer batch comes from the query rows (index_batch); sparse
  seq_lens, block table and context lens are sliced to it.
- The gfx950 startup check uses get_gfx_runtime(), called once.

Co-Authored-By: Claude <[email protected]>

* [MiniMax-M3.1] MXFP4: size each TBO ubatch's score buffers for its half of the batch

A split of up to max_bs requests gives each ubatch at most the larger half, so the
per-ubatch score buffer and its work map no longer need max_bs rows.

Co-Authored-By: Claude Code <[email protected]>

* [MiniMax-M3.1] MXFP4: select the KV cache with --kv-cache-dtype mxfp4, default the index query to FP8

--kv-cache-dtype mxfp4 replaces ATOM_M3_SPARSE_KV_MXFP4. Config derives kv_mxfp4 from
it and keeps kv_cache_dtype at fp8 for the non-MXFP4 layers, so the index cache still
defaults to fp8 and --index-cache-dtype mxfp4 stays independent. kv_mxfp4 keys the
compile hash and the offload page namespace, and mono refuses it.

With --index-cache-dtype mxfp4 the indexer query is always FP8 (e4m3, cast as is);
ATOM_M3_INDEX_Q_FP8 and its startup guard are removed.

Co-Authored-By: Claude Code <[email protected]>

* [MiniMax-M3.1] MXFP4: take the public cache dtype as fp4, not mxfp4

--kv-cache-dtype fp4 / --index-cache-dtype fp4 select MiniMax-M3's MXFP4 caches. Config maps
them to the internal kv_mxfp4 (+ fp8 storage) and index "mxfp4" once the architecture is
known, before the indexer-CP fallback and the index default, and only for MiniMax-M3.
Other models keep their fp4 index layout; a KV fp4 is refused except on DeepSeek-V4.1.
The parser no longer accepts mxfp4.

Co-Authored-By: Claude Code <[email protected]>

* [MiniMax-M3.1] MXFP4: drop pass-through aliases and duplicate index-dtype state

Pass k_cache/v_cache/slot_mapping/index_cache straight to fused_qknorm_idxrqknorm instead
of through same-valued fused_* aliases. Read the index MXFP4 mode from index_cache_dtype and
the spec's uint8 dtype instead of storing a second bool. Compute is_deepseek_v41 and the
text/sparse config once in Config.__post_init__. No behaviour change intended.

Co-Authored-By: Claude Code <[email protected]>

* [MiniMax-M3.1] config: keep the literal deepseek_v41_text check the geometry parity test scans for

test_the_hardcoded_index_plane_still_matches_what_the_config_resolves reads the index-default
branch's condition from the AST. Restore the literal there; behaviour is unchanged.

Co-Authored-By: Claude Code <[email protected]>

* [MiniMax-M3.1] MXFP4 tests: cover KV-only and index-only fp4 writes and the page-16 block table

KV-only (MXFP4 KV, fp8 index [pages,128,128]) and index-only (MXFP4 index, fp8 SHUFFLE KV
with per-token scales) writer cases beside the both-on one; the index-only run is pinned
byte-for-byte to the same write with a bf16 index. One MXFP4-index decode selection case with
8 pages a block. Test-only; GPU (gfx950) tests, not run on CPU.

Co-Authored-By: Claude Code <[email protected]>

* [MiniMax-M3.1] MXFP4: resolve the index cache dtype through aiter's fp4x2

_resolve_index_cache_dtype maps the internal "mxfp4" to d_dtypes["fp4x2"] like
bf16/fp8. fp4x2 is only the logical label: the entry stays one 8704 B uint8
page of E2M1 data and E8M0 scales (EntryField and field_view are unchanged).
Where torch has no float4 (or fp8 is uint8) the registry's fp8 and fp4x2 are
both uint8, so _IndexCacheSpec carries an explicit mxfp4 flag from the config
string and the two branches read that instead of comparing dtypes.

The new test needs aiter like the other aiter_attention builder tests, so the
no-aiter CPU CI job skips it; run with aiter present (96 passed there).

Co-Authored-By: Claude Code <[email protected]>

* [MiniMax-M3.1] MXFP4: hold the index cache as "fp4x2" from init, resolve it through aiter's registry

For MiniMax-M3 the public --index_cache_dtype fp4 becomes "fp4x2" at Config
init (other models keep "fp4"), and _resolve_index_cache_dtype takes it through
the same d_dtypes lookup as bf16/fp8. This replaces the special mxfp4 branch,
the name helper and the spec flag of 1aacf2cd9.

fp4x2 is only the name: the entry stays one 8704 B uint8 page of E2M1 data and
E8M0 scales, and the two branches that lay it out key on the config string, not
the dtype (fp8 and fp4x2 are both uint8 where torch lacks float4). The AITER
fused writer still takes "mxfp4", so attention_mha translates it at that call.
The Mooncake namespace keeps "fp4x2" as is, so it does not change with the
torch build. Config checks, docs and tests follow the new string.

The aiter-gated test (test_aiter_index_cache_dtype.py) is skipped by the
no-aiter CPU CI job; writer tests need gfx950. Not run on GPU at this head.

Co-Authored-By: Claude Code <[email protected]>

* [MiniMax-M3.1] MXFP4: keep the index cache "fp4" inside ATOM, name it fp4x2 only for aiter

Undo the "fp4x2" config string of 9f424857d: MiniMax-M3's index cache stays
"fp4" in the config, and ATOM translates it only where aiter needs another
name -- d_dtypes["fp4x2"] in _resolve_index_cache_dtype, "mxfp4" on the fused
writer call.

_resolve_fp4_caches no longer takes or returns the index dtype (it only mapped
the KV now). Because "fp4" is also the DeepSeek-V4 / GLM index layout,
_check_m3_mxfp4 gates the index check on the model being MiniMax-M3, so those
models' fp4 index is not refused. The two page branches still key on the config
string, not the dtype, since fp8 and fp4x2 are both uint8 where torch lacks
float4; the entry stays one 8704 B uint8 page. The Mooncake namespace special
case goes: aiter's registry has no "fp4" key, so it stands as it is.

Tests follow the string; new cases cover the MiniMax-M3 index-only refusal and
a DeepSeek-V4 fp4 index that is not refused. The aiter-gated test
(test_aiter_index_cache_dtype.py) is skipped by the no-aiter CPU CI job. Not
run on GPU at this head.

Co-Authored-By: Claude Code <[email protected]>

* [MiniMax-M3.1] MXFP4: name the sparse KV pool format "fp4", not "mxfp4"

KvGeometry.kv_format / MhaKvPool.kv_format is ATOM-internal (aiter has no such
name) and is per row space: only MiniMax-M3's indexed sparse layers carry it,
dense layers keep "". It now reads "fp4" like the index cache, so the geometry
is named h8d128fp4 and its transfer-region role mha.h8d128fp4.<role>; peers on
different builds would see different role names for MXFP4 KV (the roles are
only logged and compared against the MLA constants).

The aiter writer literal kv_cache_dtype="mxfp4", kv_mxfp4 and config
kv_cache_dtype are unchanged. Pins the new geometry name in test_kv_pool_contract.

Not run on GPU at this head.

Co-Authored-By: Claude Code <[email protected]>

* [MiniMax-M3.1] MXFP4: review follow-ups -- docs, error wording, M3 gate, drop duplicate dequant

Small, verified items from the 12-point review:
- docs: the 64-block FP4 text is scoped to DeepSeek-V4, M3's MXFP4 caches are
  128 (refused at startup otherwise, no FP8 fallback), add the kv_mxfp4 row;
  index_topk comments say 8 / 1 pages per block (16 only for the plugin's
  fused-K/V cache).
- config: the fp4 KV error names DeepSeek-V4.1 too; the MiniMax-M3 test is
  _is_minimax_m3_config (architecture or model_type, also on text_config), once,
  for the KV mapping and the MXFP4 gate, so it agrees with the attention builder
  and the offload layout.
- index_mxfp4 docstring: the pinned aiter's MXFP4 prefill scorer keeps pages
  MXFP4 through LDS (scaled MFMA); it does not stage them as fp8.
- kv_mxfp4: drop _E2M1 / dequantize_pages (tests only); tests call
  dequantize_mxfp4(*page_views(pages)), bit-exact on every data byte and e8m0
  0..254 (they differ only at 0xFF: inf there, NaN in mono, the e8m0 NaN).

Not addressed here: items 1, 2, 3, 6, 7, 8, 11 and the structural parts of 4, 5,
9. The index/attention/write tests are GPU-gated and skipped on CPU; not run on
GPU at this head.

Co-Authored-By: Claude Code <[email protected]>

* [MiniMax-M3.1] DSpark calibration identity: tell MXFP4 KV from fp8 KV

--kv-cache-dtype fp4 on MiniMax-M3 is held as kv_cache_dtype="fp8" plus
kv_mxfp4=True, so calibration_identity() gave an fp8 deployment and a KV-MXFP4
one the same identity (and index-only vs both-MXFP4), and a speed table
calibrated for one format validated for the other.

The identity now carries kv_mxfp4 when it is set. It is left out otherwise, so
every identity and profile that does not use MXFP4 KV is unchanged and keeps
matching. Test covers the collisions, the unchanged plain identity and a config
without the attribute.

Not run on GPU.

Co-Authored-By: Claude Code <[email protected]>

* [MiniMax-M3.1] MXFP4: M3's startup checks move to models/minimax_m3/config.py; stale cache text

The MiniMax-M3-specific refusals of _check_m3_mxfp4 (vLLM/SGLang bridges, block
size 128, sparse_local_block, gfx950) become validate_runtime_config in
models/minimax_m3/config.py, called from Config.__post_init__ at the same point
as before and the way DeepSeek-V4.1's are. The generic refusal of kv_mxfp4 on
another model stays in Config with the same message. Same checks, order and
errors; tests call the hook, plus a Config-level test for the generic refusal.

attention_mha: the rope_cache docstring and comments, the _cache_format comment
and the dispatch_backend docstring no longer say the cache is always SHUFFLE
with scale planes (the MXFP4 pages are not).

Not run on GPU.

Co-Authored-By: Claude Code <[email protected]>

* [MiniMax-M3.1] MXFP4 KV needs a bf16 model: refuse an fp16 one at startup

aiter's MXFP4 pa_decode raises "needs a bf16 output" (flydsl/pa_decode.py), and
the sparse attention output takes the model dtype (rope_cache stores qkv.dtype),
so --kv-cache-dtype fp4 on a MiniMax-M3 checkpoint with an fp16 torch_dtype died
in its first forward. validate_runtime_config now refuses it at startup. The
MXFP4 index alone does not reach that kernel and is not restricted. The fp16 case
is refused, not made to run: a bf16 output plus cast would change the kernel call
and was not validated.

Tests: hook-level (fp16 refused, bf16 accepted, index-only fp16 accepted) and
Config-level on an hf dtype of float16.

Not run on GPU.

Co-Authored-By: Claude Code <[email protected]>

* [MiniMax-M3.1] MXFP4 index score buffer: size rows for the step widths that read it; CP-gate test

The persistent index score buffer had max_bs * max_qlen rows, but
fresh_index_score hands it out only when S * H < TRANSPOSE_MIN_F; wider
steps (TP1 S>=4, TP2 S>=8) take the scorer's own allocation and never read it.
index_score_rows sizes it for the widths that do. Sizing only: the transposed
path still allocates and fills per layer. Not run on a GPU, graph replay or TP2.

Also pins that --kv-cache-dtype fp4 alone (index stays fp8) still falls back
from the CP scorer, and drops stale size figures from a builder comment.

Co-Authored-By: Claude Code <[email protected]>

* [MiniMax-M3.1] Address review: single fp4 dtype source, shared plan cache, score-buffer step

- Drop Config.kv_mxfp4; kv_cache_dtype stays "fp4" and Config.kv_storage_dtype
  gives the dtype of non-MXFP4 pages. Config.draft_config() builds draft
  configs with the storage dtype.
- Rename kv_mxfp4.py to mxfp4_pages.py and add Mxfp4KvLayout / ShuffleLayout so
  MhaKvPool carries no model name.
- Index score: persistent buffer matches aiter's transposed layout, fill is
  bounded to the batch block count, eager steps use the batch width; carried in
  one IndexScoreStep on the sparse metadata.
- MXFP4 decode uses the shared flydsl plan cache (plan_segment key) and the
  sparse_local_block>=1 startup refusal is removed.
- Index cache spec, direct aiter.ops.flydsl imports, tests restructured.

Not done: unifying the skip-index writer (Triton path kept). Not run on this
head: TP2, real-runner TBO/graph, e2e accuracy.

Co-Authored-By: Claude Code <[email protected]>

* Fix RUF028: keep the fmt: skip on a statement in the eager-width index test

The `# fmt: skip` sat inside an `outs.append(...)` argument list, which ruff
rejects as an invalid suppression comment (Pre Checkin ruff job).

Co-Authored-By: Claude Code <[email protected]>

* Simplify MiniMax-M3 FP4 KV dtype routing

Derive dense KV page dtype from kv_cache_dtype and remove redundant sparse and pool state.

Co-Authored-By: Claude Code <[email protected]>

* WIP: route MiniMax-M3 paged KV through MXFP4

Wire dense and draft page paths, preserve independent index dtype, and isolate the new page namespace. Keep EAGLE3 and DSpark disabled pending GPU and AITER validation.

Co-Authored-By: Claude Code <[email protected]>

* Skip DSpark MXFP4 tests when aiter is unavailable

Keep the no-AITER CPU test job collecting successfully.

Co-Authored-By: Claude Code <[email protected]>

* Revert unvalidated all-layer MiniMax-M3 MXFP4 expansion

Revert commits 6c790ca96 and 6ffa5541b7; preserve the earlier #2962 sparse MXFP4 implementation.

Co-Authored-By: Claude Code <[email protected]>

* Reject MiniMax-M3 --kv-cache-dtype fp4; keep the MXFP4 index cache only

--kv-cache-dtype fp4 on MiniMax-M3 made the indexed sparse layers' KV MXFP4
while dense/sliding/draft layers silently used FP8. Refuse it at startup
(only DeepSeek-V4.1 takes an FP4 KV) and remove the code the guard makes
unreachable: the sparse MXFP4 KV reader/writer, Mxfp4KvLayout and the pool
layout abstraction, dense_kv_dtype and the draft FP8 override, and their
KV-only tests. --index-cache-dtype fp4 (index page ABI, writer, scorer) is
unchanged. The MXFP4 decode index batch sizing now applies only to that cache.

Co-Authored-By: Claude <[email protected]>

* Skip the MXFP4 index tests on an aiter without the FP4 index ops

An older aiter lacks minimax_m3_index_score_fp4_flydsl: the index test failed
with ImportError and the write test aborted the process in the fused writer.
Both skipif conditions now probe that op, so they skip there and still run on
an aiter that ships the MXFP4 index.

Co-Authored-By: Claude Code <[email protected]>

* Drop the thin FlyDSL wrappers around the MXFP4 index scorers

index_work_map_capacity, build_index_work_map, index_score_buffer,
decode_score_mxfp4 and prefill_score_mxfp4 only forwarded to aiter. The
callers now call aiter directly. The page_views check, the lazy aiter imports
and the empty-batch behaviour stay: alloc sizes a zero batch as zero rows
without asking aiter, and begin_step returns None before building a map.

Co-Authored-By: Claude Code <[email protected]>

* Add MiniMax-M3.1 MXFP4 KV cache with separate DSpark draft dtype

Co-Authored-By: Claude Code <[email protected]>

* Restore the MiniMax-M3.1 MXFP4 KV tree; port only the M3 gate and draft dtype back

Return the working tree to the earlier real-FP4 implementation (8704-byte
pages, fused writer, sparse_pa_mxfp4 reader, FP4 index scorer) and keep from
the current head only what it still needs: the all-indexed-sparse M3.1 gate
(dense attention, fp16, KV offload / --kv-transfer-config and FP4 drafts are
refused), the DSpark draft's own KV dtype (--spec-decode-kv-cache-dtype,
fp8 by default, bf16 allowed, fp4 refused), compile and calibration identity,
and the non-M3 DSpark / EAGLE3 behaviour. The thin FlyDSL wrappers around the
index scorers are gone, and the tests are trimmed of duplicated matrices.

Co-Authored-By: Claude Code <[email protected]>

* Review 5797687431: one decode row rule for every index cache, draft KV default, offload parser

- decode_rows_batch: the requests whose rows the sparse decode runs (scorer,
  selector, attention), for every index cache; replaces the MXFP4-only
  index_batch that raised on DP prefill padding. _sparse_decode slices q/idx_q
  to those rows and zeroes the output past them (fp8 index + fp4 KV no longer
  reads unwritten page ids).
- resolve_draft_kv_dtype defaults an own-pool draft to the target's dtype (fp8
  only under an fp4 target); calibration identity adds the draft dtype only
  when it differs from the target's.
- The offload refusal checks the model's own fp4/offload refusal first and no
  longer suggests a flag that then fails.
- The draft's pool/dtype is decided once in Config (spec.kv_cache_dtype) and
  read everywhere; DraftKvBuilder binds scales by pool.scale_fields.
- kv_offload_requested -> kv_pages_leave_pool, reading config.kv_transfer_config
  only.
- Docs: --method lists mtp/eagle3/dspark; compute_hash comment lists the MXFP4
  fallback.

Not run on a GPU.

Co-Authored-By: Claude <[email protected]>

* Review 5781200929 B14/B15: read index_cache_dtype directly, fix the mxfp4 sparse docstring

- aiter_attention: config.index_cache_dtype, as the same builder reads it at the
  other site (B14).
- sparse_attn_mxfp4: the module docstring named a nonexistent plan_owner=None and
  had a broken sentence (B15).

The other B-series items need aiter-side or GPU work and are tracked for a
follow-up PR.

Co-Authored-By: Claude <[email protected]>

* Resolve duplicate kv_cache_dtype entries left by merging origin/main

Both main and this PR added kv_cache_dtype="fp8" to the same stand-in configs
at different positions, so the merge produced a repeated keyword (a
SyntaxError at collection) in test_compile_hash_spec and test_indexer_cp_gate,
and a repeated dict key in test_config_compile_hash. Keep one of each.

Co-Authored-By: Claude <[email protected]>

* Review 5797687431 items 1/2: refuse fp4 KV beside a non-fp4 index; scope the row rule to the MXFP4 index

- Item 2: --kv-cache-dtype fp4 now defaults the M3 index to fp4, and
  validate_runtime_config refuses an explicit other index (sparse_pa_mxfp4
  walks every row of q; only the MXFP4 scorer is sized to those rows).
- Item 1: decode_rows_batch and the q / idx_q slicing in _sparse_decode apply only
  under the MXFP4 index; every other index cache is back to running_bs and the
  unsliced q, as before the review. Tests and docs follow.

Not run on a GPU.

Co-Authored-By: Claude <[email protected]>

* MiniMax-M3: an unspecified dtype stays bf16, fp4 only when asked for

- --kv-cache-dtype fp4 no longer defaults the index cache to fp4: the index is
  left at bf16 and validate_runtime_config refuses it ("--kv-cache-dtype fp4
  needs --index-cache-dtype fp4, got bf16").
- An unspecified draft under an fp4 target is bf16, not fp8; an explicit
  --spec-decode-kv-cache-dtype fp8 is still honoured.
- Help text, docs and tests follow.

Not run on a GPU.

Co-Authored-By: Claude <[email protected]>

* Copilot review: calibration without a draft, fill_blocks=0, KvLayout.tag, head-count check, draft default help

- calibration_identity: no AttributeError when speculative_config is None.
- fresh_index_score: fill_blocks=0 fills nothing; only None means every column.
- KvLayout declares tag (ShuffleLayout's is ""), which KvGeometry.__str__ reads.
- sparse_pa_mxfp4: a clear ValueError when num_kv_heads does not match the pages.
- --spec-decode-kv-cache-dtype help: the default is the target's dtype (bf16
  under an fp4 target), not fp8.

Not run on a GPU.

Co-Authored-By: Claude <[email protected]>

* MXFP4 index scorer: allocate the scores per call, keep only the work map persistent

Drop the persistent score storage of IndexScoreBuffers (alloc, the strided view,
the per-step -inf fill, the per-ubatch offset views). The scorer, given no out,
allocates the scores filled with its -inf sentinel (aiter alloc_score), as the
Triton scorers allocate theirs per call. The work map, whose pointer a captured
graph bakes and which is built outside the graph each step, stays persistent, per
TBO ubatch as before. Tests follow.

Not run on a GPU.

Co-Authored-By: Claude <[email protected]>

* MXFP4 index scorer: the work map is a builder attribute, not a forward_vars entry

Nothing reads forward_vars['sparse_attention_index_score'] (or its ub<i>_ copies)
but the builder that put it there, and it now holds only the scorer's work map.
Keep it as builder-owned self._index_work_maps (by ubatch prefix) and rename
IndexScoreBuffers/IndexScoreStep/index_score(_buffers/_eager) to
IndexWorkMap/IndexWorkMapStep/index_work_map(_eager). Tests follow.

Not run on a GPU.

Co-Authored-By: Claude <[email protected]>

* Drop IndexWorkMap/IndexWorkMapStep and the eager block-count shrink

The two classes only wrapped aiter's work-map builder: the builder now keeps
a {prefix: int32 buffer} dict (one per TBO ubatch) and make_sparse_decode_metadata
calls aiter's minimax_m3_index_score_work_map straight into it. The metadata
carries just the map tensor; the layer takes the model-length block bound from
its own max_model_len.

Eager steps used to build the map at the batch's own block count, which is what
threaded use_cudagraph through the shared build() contract
(backends.py, model_runner.py, _step_use_cudagraph). Eager steps now use the
model-length bound like graph steps, so all of that goes, together with the
test that covered the shrink.

Co-Authored-By: Claude <[email protected]>

* Inline decode_rows_batch at its only call site

The standalone function and its tests existed only to compute
min(running_bs, running_tokens // q) for the MXFP4 index decode. Inline that
one line in the metadata builder and keep the guard that mattered: refuse a
step whose rows cannot cover the scheduled requests. The non-divisible-rows
error is dropped (floor division is enough). _sparse_decode's row slicing and
zeroing of the rest is unchanged. Docstrings that named the function now
describe the behaviour directly.

Co-Authored-By: Claude <[email protected]>

* Decide "does the draft own a KV pool" once, off the selector in plugin mode

Config.__post_init__ asked `_config_has_own_pool_draft` for every speculative
config, and for a DSpark draft that went through attn_family/get_attn_backend.
A V4.1 DSpark draft is CSA2, which the selector refuses under vLLM/SGLang, so a
supported plugin deployment (V4.1 + DSpark) crashed at Config construction.

The decision is now the public `spec_decode.draft_kv.draft_owns_kv_pool(config)`;
`Config` and the offload deployment check both call it, and the private offload
helper is gone. Under a plugin it answers False without asking the selector (the
draft pool builder only exists in the native runner). Native answers are unchanged.

Test: a plugin-mode Config with a V4.1 DSpark draft built without touching the
selector (it raised NotImplementedError before the fix), plus the native cases of
`draft_owns_kv_pool`.

Not touched: SpeculativeConfig.kv_cache_dtype semantics, the index dtype default.

Co-Authored-By: Claude <[email protected]>

* Key the MXFP4 row rule on the index cache, not on a kwargs dict's truth

valarLip's item 2: `index_bs` was MXFP4-only but selected by the truthiness of
`_index_work_map_kwargs()`, and the "do not cover the scheduled requests"
ValueError sat outside that branch, where for bf16/fp8 (`index_bs == running_bs`
>= scheduled) it cannot fire.

The rule now reads `self._index_work_map_blocks` (non-zero exactly when the index
cache is MXFP4; set beside the work map) and the ValueError moves inside that
branch. Behaviour is unchanged for every index dtype. Not done, on purpose:
making the row rule uniform for bf16/fp8 (reviewer's 11-05 B6 objected to changing
their row count in this PR).

Test: the row rule for MXFP4 (ragged DP step, uncovered requests) and the padded
batch kept for the other index caches, driven through `finish_decode`.

Co-Authored-By: Claude <[email protected]>

* Carry the work map's block bound on the sparse metadata instead of recomputing it

valarLip's item 4: the decode work map was built at cdiv(config.max_model_len, 128)
in the builder (`make_sparse_decode_metadata` already receives that bound), and the
impl recomputed -(-impl.max_model_len // 128) for the scorer, which checks the two
for exact equality. They agreed only because both read the same config value.

`MiniMaxM3SparseMetadata.index_work_map_max_block` now sits beside `index_work_map`
(0 when no map was built) and `_mxfp4_select_kwargs` passes it through. No fallback
path remains: the impl only passes a map, and thereby a bound, when the metadata
holds one. `impl.max_model_len` (set by the builder's bind and initialised on main)
is left as it is; this change just stops reading it.

Test: the scorer kwargs take the bound off the metadata even when the impl's own
max_model_len says otherwise.

Co-Authored-By: Claude <[email protected]>

* Give sparse_pa_mxfp4 an out= and zero the DP pad tail once, like SHUFFLE

valarLip's item 5 (and the Copilot note on the same lines): on the MXFP4 KV decode
branch `sparse_pa_mxfp4` allocated its own output and `nn.functional.pad` then
allocated and copied the whole thing again on every DP-padded step and layer,
while the SHUFFLE branch wrote into `output[:rows]` of an empty_like and zeroed
`output[rows:]`.

`sparse_pa_mxfp4(..., out=)` takes the caller's contiguous [rows, H, 128] tensor of
`out_dtype` (checked: the query is e4m3, so it is never `empty_like(q)`), on the
planned and the plan-free path alike, and returns it; `out_dtype` keeps its meaning
(output dtype and plan-scratch dtype). `_sparse_decode` now allocates one output
(value dtype for the MXFP4 KV, q's otherwise), zeroes the tail once and hands
`output[:rows]` to whichever kernel runs. The prefill call is unchanged.

Tests: CPU doubles for pa_decode prove the segment views land in the caller's
buffer, pad rows untouched, wrong dtype refused. GPU (gfx950, aiter main 5469555096):
`out=` equals the allocated result bit for bit, planned and plan-free, rows past it
untouched; test_minimax_m3_mxfp4_attention.py passes there.

Co-Authored-By: Claude <[email protected]>

* Drop the redundant fp4 factor from compute_hash and read spec.kv_cache_dtype directly

valarLip's item 7: `factors.append(self.kv_cache_dtype == "fp4")` is implied by
`factors.append(self.kv_cache_dtype)` further down the same function, yet it changed
every model's compile-cache key. Deleted. `getattr(spec, "kv_cache_dtype", None)`
read a field this PR declares on SpeculativeConfig; it is now `spec.kv_cache_dtype`
(the SimpleNamespace spec in test_compile_hash_spec gets the field a real one has).

Unavoidable, not addressed: the speculative tuple's third element still changes the
hash of every speculative-decoding model against main.

Co-Authored-By: Claude <[email protected]>

* Say which dtype and which cause the DSpark q_out dtype warning is about

valarLip's item 8: the warning named `--kv_cache_dtype`, but the value it prints is
`speculative_config.kv_cache_dtype`, the draft's resolved dtype (the target's
--kv-cache-dtype, or --spec-decode-kv-cache-dtype for a draft with a pool of its
own, settled once by Config), and said the draft binds into the pool allocated
"from that same flag". Text only: it now names the field and where it comes from,
and that the pool is allocated at that resolved dtype. No behaviour change.

Co-Authored-By: Claude <[email protected]>

* Delete the empty index_mxfp4.py and bring the stale docs and leftovers in line

valarLip's item 10. `index_mxfp4.py` was 19 lines of docstring with no code and no
importer, while index_topk.py, aiter_attention.py and sparse_attn.py still sent
readers there for the scorer; and its "same [heads, rows, max_block] scores" is wrong
for the transposed layout (S*H >= 16).

- Deleted it; the useful sentences (e4m3 query, the page_views, the per-step work map
  and the exact max_block it must be given, scores allocated per call and filled with
  -inf, the transposed layout) are now in `minimax_m3_index_topk_decode`'s docstring,
  and the three pointers name aiter's scorer instead.
- `index_topk.py` module docstring no longer says Triton-only / bf16 layout; the
  `sparse_bt` docs say `topk * pages_per_block` (8 for SHUFFLE, 1 for MXFP4 KV).
- Removed the fp4 comment block in `SparseMHAPagedAttentionImpl.__init__` (documents
  no field). `_cache_format = "SHUFFLE"` is now set only on the SHUFFLE branch: its
  one reader (`attention_mha.py` cp gather) already defaults to SHUFFLE, and the MXFP4
  pages are read only by `sparse_pa_mxfp4`, so nothing changes.
- The `kv_pools` comment/annotation said keyed by (num_kv_heads, head_dim); it is keyed
  by KvGeometry.

Comment/doc changes only apart from the `_cache_format` move.

Co-Authored-By: Claude <[email protected]>

* Pass the MXFP4 decode scorer a persistent, unfilled, contiguous out=

valarLip's item 1 (and the Copilot note on the same call): the scorer was called
without `out=`, so aiter's `alloc_score` allocated and -inf-filled a model-width
[H, rows, max_block] fp32 buffer on every sparse layer of every step (the fill is
recorded into the graph), and for S*H >= 16 laid it out transposed, which made
`_select_with_aiter` decline on `not score.is_contiguous()` and every such step take
the Triton selector.

Now the builder allocates the score storage once, beside each work map ("" and the
two TBO ubatches, so two ubatches never share one), at the map's width; the sparse
metadata carries it (`index_score_out`) and `minimax_m3_index_topk_decode` hands the
scorer a contiguous [H, rows, max_block] view of its head as `out=`. Never filled:
read from the code, the Triton selector masks `idx < valid_blocks` (other=-1e30) and
aiter's `topk_per_row_small_k` replaces any column past the row's length with a
select, and the scorer writes every column below a row's valid blocks each step. The
-inf sentinel in aiter's `alloc_score` docstring is owed only to a consumer that
reads past them. The layout is page-contiguous by construction, so the aiter
selector stays eligible at any S*H.

Not done: "the step's width on eager steps". The scorer requires the work map and
`max_block` to match exactly and the map is built at the model length since 7bbdd0766
removed the eager shrink (reviewer B10), so eager steps stay at model width here;
narrowing them needs that shrink back.

Tests: GPU (gfx950, aiter main 5469555096): selections, block tables and contexts
bit for bit equal between the allocated and the junk-filled persistent buffer
(NaN/+-inf), ragged lengths, pad rows, a second shorter step reusing the buffer,
S*H 1..16 and 70 / 2100 blocks (2100 is where the aiter selector takes the
persistent one; the default path is Triton at S*H=16). CPU: the wiring and the
too-small-buffer refusal, per-ubatch buffers.

Co-Authored-By: Claude <[email protected]>

* Score the MXFP4 decode index into the indexers' LogitsWorkspace

Follow-up to the previous commit (persistent, unfilled scorer `out=`): the hand-made
flat fp32 buffer, `_alloc_index_scores`, and the manual slice-and-capacity-check in
`minimax_m3_index_topk_decode` are replaced by `sparse_indexer_chunk.LogitsWorkspace`,
the persistent logits plane the other indexer models (aiter_mla, deepseek_v4) already
allocate, so every indexer's persistent score buffer is one mechanism.

- The builder makes one `LogitsWorkspace(H * max_rows * index_work_map_blocks)` per
  work map ("" and the two TBO ubatches, which therefore still never share one), by
  the explicit-capacity constructor: `for_rows` bands the plane to a budget, which a
  scorer that writes the whole grid cannot use.
- `MiniMaxM3SparseMetadata.index_score_out` (a tensor) becomes
  `index_score_workspace` (the workspace); `minimax_m3_index_topk_decode` takes the
  scorer's `out=` from `workspace.logits(H * total_q, width).view(H, total_q, width)`.
  `logits` is a contiguous [rows, width] view, so the 3-D view is free, and it raises
  when the step outgrows the workspace (no silent truncation). Without a workspace
  the scorer still allocates its own scores, as before.
- Allocation time: unchanged and already right. The builder is constructed in
  `ModelRunner.__init__` before `warmup_model`, and KV sizing reads the allocator's
  current/peak after it, so the workspace is counted in the KV budget.

Not changed: the scorer's layout/fill behaviour (selections stay bit for bit equal to
the allocated scores), eager-step width, and nothing of the KvLayout, index-dtype
default or SpeculativeConfig.kv_cache_dtype items.

Tests: capacity and bytes of the main and the per-ubatch workspaces, ubatches do not
share storage, a workspace too small for the step raises, wiring through the
metadata; GPU: persistent-vs-allocated equality as before, plus a CUDA graph captured
into the workspace and replayed with a padded step (pointer unchanged, selection
equal to the allocated scores').

Co-Authored-By: Claude <[email protected]>

* Decide "the draft owns a KV pool" from the attention family, not by resolving a backend

valarLip's round-3 item 3: `draft_owns_kv_pool` answered through `get_attn_backend`,
and every backend module imports aiter, so building `Config` in the API process
(`LLMEngine`) loaded aiter (and initialised CUDA) for every native DSpark launch,
which `config.py` keeps out of `import atom.config` on purpose.

`selector.DRAFT_POOL_FAMILIES` (today MHA: an MHA draft keeps its own K and V; an
MLA / CSA draft's latent is the target's) is now the one answer. `draft_owns_kv_pool`
and `draft_kv_builder` both read it; the `DRAFT_OWNS_KV_POOL` class flag on
`AttentionBackend` / `AiterBackend` is gone, so the two cannot disagree. The plugin
answer (False, no lookup) is unchanged.

Test: `test_kv_pool_contract.py` pins the table to the backends: every listed family's
backend defines `make_kv_pool`, and every backend that defines it is listed. The
plugin V4.1 + DSpark regression test is kept (it now also asserts no backend is
resolved natively); the draft-builder and offload tests drive the family instead of
a stubbed backend.

Not changed: which methods ask (still DSpark only; the EAGLE3 question is the next
commit), SpeculativeConfig.kv_cache_dtype semantics.

Co-Authored-By: Claude <[email protected]>

* Settle DeepSeek-V4's fp8 -> bf16 KV fallback in Config, before the draft's dtype resolves

valarLip's round-3 item 1: V4's builder lowered the target's KV dtype to bf16 on a GPU
other than gfx950 / gfx1250 (aiter's fp8 2buff path runs only there) and rewrote
`config.kv_cache_dtype` after `Config.__post_init__` had already resolved
`spec.kv_cache_dtype`. A V4 DSpark draft shares the target's pool, so on gfx942 its
resolved dtype stayed fp8 against a bf16 pool: `_resolve_dtype_q` warned on every run,
`calibration_identity` gained `draft_kv_cache_dtype=fp8` (existing profiles stopped
matching), and the draft config was handed fp8.

The fallback is now a `Config` decision, made where the V4 block size is, with the
builder's own probe (`aiter.jit.utils.chip_info.get_gfx`: rocminfo, no CUDA init, and
already imported there for V4's indexer default). Native only (`plugin_config is
None`), as before: the builder never ran under a plugin. The builder's rewrite is
removed; it reads the settled dtype.

Tests: gfx950 / gfx1250 keep fp8 and gfx942 gets bf16, for the target and for a V4
DSpark draft resolved after it; a plugin config is left alone and never probed. The
existing indexer-default tests count arch probes, so their helper now asks for a bf16
KV (the probe those tests count is the indexer default's, not this one).

Co-Authored-By: Claude <[email protected]>

* Answer "the draft owns a KV pool" for EAGLE3 as well as DSpark

valarLip's round-3 item 2: `draft_owns_kv_pool` said True only for DSpark, but its
docstring says it is what `draft_kv_builder` answers, and `eagle_proposer.py` calls
`draft_kv_builder` for `--method eagle3` too: an MHA EAGLE3 draft gets a pool of its
own. So M3 with an fp8 target, EAGLE3 and `--spec-decode-kv-cache-dtype bf16` was
refused with "this draft caches in the target's KV pool", and M3.1 fp4 + EAGLE3 with
"the draft would have FP4 KV" although that draft has its own SHUFFLE pool.

The methods that build a draft pool are named once (`DRAFT_POOL_METHODS`: eagle3,
dspark; MTP runs the target's layers), and the family table decides. The M3 comment
that repeated the wrong premise, and the three doc sentences that put EAGLE3 in the
target's pool, are corrected.

Tests: an MHA EAGLE3 draft takes bf16 / fp8 / the target's dtype and runs bf16 under
fp4 KV; an EAGLE3 draft with an MLA family and MTP still share the target's pool.
Not run on a GPU: whether an MHA EAGLE3 draft actually runs beside M3.1 fp4 KV (this
only stops Config refusing it).

Co-Authored-By: Claude <[email protected]>

* Carry the MXFP4 index scorer's map, bound and workspace as one record; share the workspace

valarLip's round-3 items 8, 5 and 6, which all touch the same state.

Item 8: the work map, the block bound it is built at and its scores were three parallel
dicts/fields (`_index_work_maps`, `_index_score_workspaces`, `_index_work_map_blocks`),
split into three kwargs by the builder, three metadata fields, three kwargs again in
the impl, any missing one silently falling back to per-layer allocation. They are now
one frozen `IndexScoreBuffers(scores, work_map, max_block)` per prefix (the bound stays
beside the map): the builder's capacity record, and, on the step's metadata
(`index_scorer`), the same record with the map built for the step.

Item 5: the TBO ubatches no longer get score workspaces of their own. Read from
`atom/utils/tbo/`: both ubatches run on the one compute stream (`make_tbo_contexts`
gives every context the same `compute_stream`), CPU hand-off between them happens only
at explicit yield points, and a layer's scorer writes the workspace and its selector
reads it inside one `index_topk` call that contains none (the only `tbo_yield` in the
attention is after the prefill output). So the ubatches use the step's workspace; only
their work maps stay per ubatch (both ubatches' metadata are alive at once).

Item 6: `prepare_mtp_decode` now passes the same record, so the decode scorer has one
path: `minimax_m3_index_topk_decode` requires the record (a missing one, or a context
wider than its bound, raises) and the "no workspace -> aiter allocates, transposed at
S*H >= 16" branch is gone, with `_select_with_aiter`'s `not score.is_contiguous()`
exit (every scorer writes a contiguous table now) and the stale comment in the builder.

Not done here: the prefill scorer (next commit), eager-step width.

Tests: ubatch records share the workspace and have distinct maps; metadata builds the
map into the record's buffer at its bound; scorer view/too-small/missing-record
refusals; GPU tests compare the workspace path against aiter's own allocated scores
via a wrapper that drops `out=` (bit for bit; CUDA graph with a stable pointer).

Co-Authored-By: Claude <[email protected]>

* Give the MXFP4 prefill scorer the shared, unfilled score workspace too

valarLip's round-3 item 4 (the user reversed an earlier "do not change"): the prefill
call `minimax_m3_index_score_prefill_fp4_flydsl(...)` passed no `out`, so aiter's
prefill `alloc_score` did `torch.full(-inf)` of `[H, chunk rows, cdiv(max_seq_len,
128)]` fp32 on every sparse layer of every chunk (the Triton path it replaces used
`torch.empty`). The pinned aiter (5469555096) supports `out=` there (shape
[H, total_q, max_block], page-contiguous).

The prefill scorer now writes into a contiguous view of the same `LogitsWorkspace` the
decode scorer uses, never filled: `minimax_m3_index_topk` takes the step's
`IndexScoreBuffers` (required for the MXFP4 index), the prefill metadata carries the
record without a map, and `_mxfp4_select_kwargs` passes it for both phases. Not filled
for the same reason as decode: the selector reads a row only up to its valid blocks
(`n_valid_column_per_row`), and the prefill scorer writes every page inside a row's
causal window, which is exactly that range.

One workspace, shared: a step is prefill or decode (`dispatch_backend` picks one on
`is_prefill`), and within either the scorer and selector of a layer run back to back
on one stream. The builder sizes it for the larger of a decode step (`max_bs *
max_qlen`) and a prefill chunk (`max_num_batched_tokens`) rows, at the work map's
width, in the constructor, so the memory profile counts it. Memory, fp32:
4 * H * rows * ceil(max_model_len / 128). MiniMax-M3.1 (index heads 4, so H = 1 at
TP4), 16384 rows: 64 MiB at --max-model-len 128K, 512 MiB at 1M (the model's 1M
default); at TP1 (H = 4) four times that. Decode-only would be 8 / 64 MiB at q = 4,
512 seqs.

Tests: GPU (run only when a card is available, see the report): the prefill scorer
into a junk-filled workspace, reused by a second chunk, selects bit for bit what aiter's
own allocated, -inf-filled scores give (ragged chunks, prefixes, lengths off a block
boundary, H 1 to 4, 70 and 2100 blocks). CPU: the prefill scorer view and the missing-
record refusal, the prefill metadata keeping the workspace only, the builder's sizing.

Co-Authored-By: Claude <[email protected]>

* Offer only the draft KV dtypes a draft can have: --spec-decode-kv-cache-dtype bf16|fp8

valarLip's round-3 item 10: `--spec-decode-kv-cache-dtype fp4` could never take effect.
A draft with a pool of its own refuses it, and a draft in the target's pool takes it
only when it equals the target's dtype, i.e. the same as omitting the flag. The
choice existed to produce one error and was documented in three places.

`choices=["bf16", "fp8"]`; the fp4 error in `resolve_draft_kv_dtype`, its test, and the
doc / help lines that described it are gone (`resolve_draft_kv_dtype`'s docstring is now
its contract; the wider help / docs trimming is round-3 item 14). The `else` branch's
"needs --method" fired for `--method X --num-speculative-tokens 0` too, where the method
was given; it now names both conditions, and a test pins both ways speculation is off.

Not touched: `SpeculativeConfig.kv_cache_dtype` semantics (one field, requested then
resolved), as agreed.

Co-Authored-By: Claude <[email protected]>

* One source for M3's 128-token block, and one geometry check of an MXFP4 page

valarLip's round-3 item 11: `PAGE_TOKENS = 128` redefined `SPARSE_BLOCK_SIZE` (which was
itself defined in both `index_topk.py` and `sparse_attn.py`), `validate_runtime_config`
checked a literal 128, and the "128 wide, one block an entry" rule was checked in
`_index_cache_spec` and again in `Mxfp4KvLayout.check`; they agreed only because the
numbers match.

`SPARSE_BLOCK_SIZE` is defined once in the new import-free `model_ops/minimax_m3/
geometry.py` (not in `index_topk` / `sparse_attn`: `Config`'s startup checks and
`mxfp4_pages`, which no-aiter CI imports, must not pull aiter / triton), and imported
by `index_topk`, `sparse_attn`, `mxfp4_pages` (where `PAGE_TOKENS` is gone), the M3
startup check and the fused-write call. The MXFP4 index spec now goes through
`Mxfp4KvLayout.check`, the one place that checks the geometry of an MXFP4 page; its
message now says "an MXFP4 page" (the check serves K, V and the index key).

The page-geometry contract test reads constants with `ast`, so it is seeded with the
new module. `sglang`'s plugin keeps its own literal (it does not import atom kernels).

Co-Authored-By: Claude <[email protected]>

* Revert diff noise: moved test lines and a split one-line import

valarLip's round-3 item 12: `tests/test_config_compile_hash.py` and
`tests/test_compile_hash_spec.py` moved a `kv_cache_dtype="fp8"` line without changing
it, and `aiter_attention.py` split a one-line `forward_context` import that fits in 88
columns. The test_config_compile_hash.py hunk is reverted to main; test_compile_hash_spec.py
keeps only the `kv_cache_dtype` default its stub spec needs; the import is one line again.

Co-Authored-By: Claude <[email protected]>

* Say how the M3 K/V binding covers fp4 in its comment

valarLip's round-3 item 13: the comment on the sparse binding still said the standard
binding sets k_scale / v_scale and is page-128 SHUFFLE re-viewed to page-16; under
--kv-cache-dtype fp4 it binds scale-less MXFP4 pages. The same sentence was already
fixed in attention_mha.py. Comment only.

Co-Authored-By: Claude <[email protected]>

* State M3's fp4 rules once: in validate_runtime_config and the configuration guide

valarLip's round-3 item 14: the M3 fp4 rules were written five times and disagreed: the
--kv-cache-dtype help left out the vLLM/SGLang bridge refusal and the requirement that
the index be fp4 too, which validate_runtime_config and the guide have.

The rule list now lives in validate_runtime_config's docstring (the source) and the
configuration guide's kv_cache_dtype / index_cache_dtype rows; the two help texts, the
two CLI-table rows and _check_fp4_kv's docstring point there. resolve_draft_kv_dtype's
docstring was already cut to its contract with the draft-dtype flag change.

Co-Authored-By: Claude <[email protected]>

* Give IndexScoreBuffers an import-free home so the non-GPU suite can build it

The non-GPU CI job (no aiter, no triton) failed three tests of
tests/test_minimax_m3_mxfp4_decode_batch.py at `from atom.model_ops.minimax_m3.
sparse_attn import IndexScoreBuffers`: sparse_attn.py imports aiter at the top, and the
record is plain data. It now lives in `model_ops/minimax_m3/index_buffers.py`, which
imports only torch and `LogitsWorkspace`; `sparse_attn.py`, `aiter_attention.py` and the
tests import it from there (no re-export).

The three tests drive `minimax_m3_index_topk[_decode]`, which needs aiter, so without
it they skip like the rest of that file (their `importorskip` was never reached, the import
above failed first). A new test that needs no aiter checks the record itself: frozen,
and a step's record is the builder's with its map replaced.

Checked with the full tests/ run under a plugin that blocks aiter, triton, flydsl, vllm
and friends (outside the repo): on the pushed head it reproduces exactly CI's three
failures; with this commit none of them remains, and nothing fails that does not also
fail on the previous head fd64ce3ef.

Co-Authored-By: Claude <[email protected]>

* Build the EAGLE3 draft at the dtype its pool was allocated at

The draft's attention reads its cache dtype off the config it is built with,
and `_build_draft_model` copied the target's config without setting it. Once
an EAGLE3 draft owns its pool (`--spec-decode-kv-cache-dtype`, and bf16 under
an fp4 target), the pool was allocated at `speculative_config.kv_cache_dtype`
while the attention kept the target's dtype: an fp8 target with a bf16 draft
wrote bf16 pages through fp8 cache semantics, and the inverse mismatched too.
Set it from the same resolved value, as DSpark already does.

Co-Authored-By: Claude <[email protected]>

* Skip the whole-batch MXFP4 scorer map on a decode that splits

A decode TBO step is cut into micro-batches before the builder runs, and its
forward runs only their metadata, each with its own work map. `finish_decode`
(and the graph capture of a split bucket) still built the whole batch's map: a
launch on every step, and on every replay, that no layer reads. Both now build
the whole batch's sparse metadata without the scorer record when the step
splits; an unsplit step is unchanged, and a layer that did read a record-less
decode metadata would raise as before.

Co-Authored-By: Claude <[email protected]>

* Address the 4cc42e7ed review: scorer allocation out of the MHA builder, one row rule, direct imports

- The MXFP4 index scorer's allocation (work map, score workspace, per-ubatch maps)
  moves from AiterAttentionMetadataBuilder to index_buffers.allocate_index_scorers;
  "" in builder._index_scorers is the switch, _index_work_map_blocks is gone.
- index_topk takes index_scorer alone (index_mxfp4 removed); the layer raises when an
  MXFP4 index has no record. The kwargs-dict helpers are deleted, the page constants
  and sparse_pa_mxfp4 are bound once in the impl's __init__.
- Prefill takes the rows its metadata covers, as decode does (one _metadata_rows).
- index_topk, sparse_attn and sparse_attn_mxfp4 import their aiter / FlyDSL functions
  at the top; the topk_per_row_small_k import has one path and no ImportError fallback.
- draft_owns_kv_pool reads config.speculative_config; the lmcache test stub gets it.
- Configuration guide: no history in the draft KV dtype row.

Co-Authored-By: Claude <[email protected]>

* Test that another index cache allocates no scorer, without aiter

Co-Authored-By: Claude <[email protected]>

* Import FlyDSL where it is selected; ask the plugin question before reading native fields

index_topk and sparse_attn took aiter.ops.flydsl names at module level, and
aiter.ops.flydsl imports flydsl, so every deployment that loads the shared MHA
backend needed FlyDSL, MXFP4 index or not. The MXFP4 scorers, their work map and
aiter's small-k selector are now imported once, by a cached loader, on the first
step that selects them; a deployment that selects one without FlyDSL fails there,
with no probe and no fallback.

draft_owns_kv_pool read the native speculative-config fields before the plugin
check, but the vLLM offload adapter hands over vLLM's own SpeculativeConfig, which
has no draft_model_hf_config: plugin mode is now asked first.

Co-Authored-By: Claude <[email protected]>

* Clamp a pad row's causal length where the block-table emission takes it (B12)

_emit_sparse_block_table_row computed self_blk and the tail token count from a
raw causal_len, which is <= 0 for a pad row (seq_len 0, Q > 1); only the final
store of the context was clamped. Clamp causal_len where it enters, give a row
with no key self_blk = -1 so no selected id can be valid, and drop the store-side
clamp. The helper is shared by the bf16/fp8 Triton selectors, the MXFP4 one and
the candidate exchange, so every index cache gets it.

The new test runs the helper on its own with a non-empty selection for pad rows:
on the CPU under Triton's interpreter (it fails on the old helper: a pad row
emitted page 100), and as a compiled kernel on gfx950 (GPU-pending, not run).

Co-Authored-By: Claude <[email protected]>

* Drop two tests that repeat a stricter test or the stdlib

test_every_family_that_owns_a_draft_pool_has_a_backend_that_builds_it asserts a
subset of what the next test asserts; the scorer-record test checks
dataclasses.replace and FrozenInstanceError, and the aiter-free construction is
pinned by test_another_index_cache_allocates_no_scorer_and_imports_no_aiter.

Co-Authored-By: Claude <[email protected]>

* Inline kv_pages_leave_pool, a one-line wrapper over bool(kv_transfer_config)

Co-Authored-By: Claude <[email protected]>

* Shorten the MXFP4 decode scorer docstring to what the buffers' docstring leaves out

Co-Authored-By: Claude <[email protected]>

* Record the aiter minimum the MiniMax-M3 index paths need (valarLip: bump the requirement)

The repo records no aiter minimum, and the selector import in index_topk.py has
no fallback since 224ae84bc: a bf16/fp8 row of 131072+ tokens on an aiter without
topk_per_row_small_k raises ImportError where main fell back to Triton. Say which
aiter builds the paths need (#7014 selector, #7060/#7061 MXFP4 index scorers,
#7056 MXFP4 K/V pa_decode) in the configuration guide, the repo's usual form
("Needs aiter with #NNNN"), and point the selector's docstring at it.

Whether bf16/fp8 should instead fall back to Triton on an older aiter is a policy
choice between valarLip's "no probe" rule and Copilot's review; the alternative is
kept as FALLBACK_ALTERNATIVE.patch beside this branch, not applied.

Co-Authored-By: Claude <[email protected]>

* Name aiter's writer formats from one table (B15, the mapping half)

The fused writer's "mxfp4" spelling of ATOM's fp4 was written twice, once for the
KV cache and once, after the fact, for the index cache. One table, used for both.
Behaviour-preserving: every (kv dtype, index dtype, skip-index) combination gives
the string it gave before (checked exhaustively by hand); the gfx950 write tests
that exercise the call (tests/test_minimax_m3_mxfp4_write.py) are GPU-pending.

Co-Authored-By: Claude <[email protected]>

* Name aiter#7057, the fused MXFP4 writer, in the minimum-aiter note

Co-Authored-By: Claude <[email protected]>

* Move --spec-decode-kv-cache-dtype out of this PR (valarLip 11-12 item 6)

The draft-KV dtype flag, its EngineArgs plumbing, the "requested" half of
SpeculativeConfig.kv_cache_dtype and resolve_draft_kv_dtype, the offload refusal
on a draft dtype that differs from the target's, the docs row and the flag tests
go to their own PR (branch ganyi/m31-draft-kv-flag, based on main).

What stays is what an fp4 target needs of it: a draft with a pool of its own is
bf16 under --kv-cache-dtype fp4 (an fp4 draft has no layout), a draft in the
target's pool keeps the target's dtype (M3.1's validator refuses fp4 there), and
every reader (draft pool, proposers, calibration identity, compile hash) reads the
one settled field, now named SpeculativeConfig.draft_kv_dtype so that both
branches share lines. The draft-pool decision from the attention family and V4's
fp8 -> bf16 fallback in Config stay: removing them needs the flag PR to land first
(SPLIT.txt, order A).

Co-Authored-By: Claude <[email protected]>

* MiniMax-M3.1: --kv-cache-dtype fp4 defaults the index cache to fp4; name M3.1 in the guard

valarLip (11-10 #6): the bf16 index default left by `--kv-cache-dtype fp4` existed
only to be refused. An omitted --index-cache-dtype now follows the KV dtype (fp4),
as for every other model; an explicit bf16 / fp8 is still refused by
validate_runtime_config. This reverses 4e4dca9bd ("fp4 only when asked for").

The _check_fp4_kv message and docstring now say MiniMax-M3.1 (the scope of this PR),
and that M3's dense-attention checkpoints are refused by the model's own validator.

Co-Authored-By: Claude <[email protected]>

* Trim the tests this PR adds: one test per behaviour, no plumbing or duplicate tests

Roughly halves the test code the PR adds. Merged near-duplicates into parametrized
cases (padded eager / graph / workspace rows, the startup refusals as one table, the
row rule for decode, prefill and a split TBO step), and removed tests that only
asserted mocks, private-helper plumbing or a second copy of another test
(test_aiter_index_cache_spec.py, the draft-pool agreement tests, a repr pin, ...).
Every deleted or merged test is listed with the review thread that asked for it in
TRIM_*.txt, and the thread is told. The B12 pad-row test, the FlyDSL-optional test
(now one subprocess test), the refusals, the row rules and the real-kernel
(gfx950, GPU-pending) tests each keep a case.

Co-Authored-By: Claude <[email protected]>

* Shorten comments and docstrings that restate the code (no code change)

Comment and docstring trims only in index_topk, index_buffers, sparse_attn_mxfp4,
sparse_attn, attention_mha, aiter_attention, models/minimax_m3/config, draft_kv and
config; comments that a review thread asked for are kept.

Co-Authored-By: Claude <[email protected]>

* Keep the test that pins the draft-pool family table to the backends that build a pool

It guards a silent failure (a backend with make_kv_pool missing from DRAFT_POOL_FAMILIES
leaves its draft sharing the target's rows); it replaced main's flag-agreement test.

Co-Authored-By: Claude <[email protected]>

* Refuse the MXFP4 caches under decode context parallelism

M3 has no DCP gather/merge: with DCP > 1 the writer stores only a rank's own
tokens while the sparse readers take global lengths, so a read can reach rows
nobody wrote. validate_runtime_config now refuses decode_context_parallel_size > 1
when either MXFP4 cache is on; tests cover the FP4-KV and index-only cases.

Co-Authored-By: Claude <[email protected]>

* Let the sparse impl declare its KV layout; type KvGeometry.layout; document the DCP and in-pool-draft refusals

The shared MHA builder no longer imports the MXFP4 layout or tests the
dtype: SparseMHAPagedAttentionImpl.kv_layout says how its pages are laid out.
KvGeometry.layout is a KvLayout, not object. The configuration guide now lists
the decode-context-parallel and in-pool-draft refusals, and three comments that
still described the removed backend flag are corrected.

Co-Authored-By: Claude <[email protected]>

* Test: a graph capture must not allocate the scorer buffers it already passes

_run built the buffers even when the caller handed it the metadata, so the
captured variant of the padded-step index test allocated inside the capture
(hipErrorStreamCaptureUnsupported on gfx950).

Co-Authored-By: Claude <[email protected]>

* Type KvGeometry.layout inside pool_layout; trim the comment and docs edits of the last commit

pool_layout/ may not import atom (tests/test_layout_packages.py), so the layout
annotation is a one-attribute Protocol defined beside KvGeometry instead of an
import of mha_kv_pool.KvLayout. The three comment corrections that belong to the
draft-KV PR are dropped here, and the docs wording and the impl's kv_layout
comment are shorter.

Co-Authored-By: Claude <[email protected]>

* Declare kv_layout once on the impl base; refuse MXFP4 KV under sequence parallelism; test leftovers

PagedAttentionImpl.kv_layout = None, read as module.impl.kv_layout by the shared
builder (no getattr); the test stub gets an impl. The fused MXFP4 writer checks
the qkv row width including the index columns, which Ulysses drops for a top-k
reusing layer, so fp4 KV is refused with --sequence-parallel-size > 1 (docs and
test row). Add the refusal test for a third model; the emit_pad_row docstring no
longer says the gfx950 variant is unrun.

Co-Authored-By: Claude <[email protected]>

---------

Co-authored-by: Claude Code <[email protected]>
shantipriya-amd pushed a commit to shantipriya-amd/aiter that referenced this pull request Nov 18, 2026
…uery_length 1) (ROCm#7056)

* [FlyDSL] Add an MXFP4 KV-cache paged-attention decode (gfx950, query_length 1)

pa_decode_mxfp4 reads K and V as e2m1 data + e8m0 scales (one per 32 elements,
along head_dim), each as two uint8 views with their own page/head strides, so a
caller may use two tensors or one single-region page
[block_size x 64 B data][block_size x 4 B scale]. It shares pa_decode's work plan
and partition reducer and leaves pa_decode itself untouched.

Per 16-token tile and wave: QK is one mixed fp4(A) x fp8(B)
v_mfma_scale_f32_16x16x128_f8f6f4 with the K block's e8m0 byte as scaleA and Q
used as stored (query_scale, a [1] fp32, multiplies the logits); a bf16 Q takes a
reference path that widens K with v_cvt_scalef32_pk_bf16_fp4. V is widened to
bf16 (exact) into a wave-private LDS tile and read back transposed with
ds_read_b64_tr_b16 as the PV operand; P stays bf16. Invalid tokens get a zero V
scale and a -inf score, so tail garbage (e8m0 0/255 included) cannot leak.

The fp8 B operand of the 16x16x128 MFMA is not contiguous per lane: lane (g, s)
holds Q head s elements 16g..16g+15 in bytes 0..15 and 64+16g.. in bytes 16..31
(measured on gfx950; A lane group g holds K elements 32g..32g+31).

tile_depth defaults to 2: with independent blocks (2048 tokens/row, 16 q heads)
it is 0.2-2.2 us faster than 4 for 1-512 rows and equal at 4096. Arithmetic is
unchanged (a test pins default == depth 4 bitwise).

Tests: rel-L2 ~1e-3 vs an fp32 reference over the dequantized K/V (the bf16
output rounding floor), ctx 1..2048, block_size 16/64/128, groups 1..16, several
KV heads, plan tasks of 1..N tiles, garbage tails, query_scale.

Co-Authored-By: Claude <[email protected]>

* [FlyDSL] pa_decode_mxfp4: write the output directly when every row is one task

With a plan of max_partitions == 1 each sequence is a single task, so the kernel
normalizes and stores the output row itself and the reduce kernel, its scratch and
the pmax/psum/pout partials disappear (direct_output, auto on for that plan).
Bitwise equal to split + reduce (tested for rows 1/8/64/512, bf16/f16, strided
output, graph replay). A context-0 row has no task and is left unwritten on this
path; the reduce path zero-fills it.

Co-Authored-By: Claude <[email protected]>

* [FlyDSL] pa_decode_mxfp4: plan-free form (work_plan=None)

Tasks follow from the block index (CTA slot = sequence * P + part, P tiles-per-task
chosen on the host from max_partitions, default the planner's 2 * CU task budget),
so no plan_pa_decode launch and no work_info read: the context length, block-table
entries and Q are loaded in parallel. The kernel writes the reduce info itself and
zero-fills context-0 rows on both the reduce and the direct (P == 1) path.
Bitwise equal to the planned path wherever the two splits coincide; tested for
ragged contexts (1..5000, tasks of several tiles), block sizes 16/64/128, empty
rows, the default-split switch at 255/256/257 rows, graph replay.

Co-Authored-By: Claude <[email protected]>

* [FlyDSL] pa_decode_mxfp4: reuse shared constants and ceildiv, fold view checks

Generated ISA is unchanged (82 specializations, identical hash).

Co-Authored-By: Claude <[email protected]>

* [Test] pa_decode_mxfp4: follow op_test conventions

Module-level gfx950 skip, checkAllclose + TFLOPS in the benchmark, and run the
pytest checks from main() so `python3 op_tests/...` (what CI runs) tests it.

Co-Authored-By: Claude <[email protected]>

* [FlyDSL] Export pa_decode_mxfp4 lazily; derive default-split test rows from the CU count

Co-Authored-By: Claude <[email protected]>

* [FlyDSL] pa_decode_mxfp4: check output device, return early on zero sequences

The test no longer queries the GPU at import.

Co-Authored-By: Claude <[email protected]>

* [FlyDSL] pa_decode_mxfp4: drop query_scale (the fp8 query is used as stored)

Co-Authored-By: Claude <[email protected]>

* [FlyDSL] pa_decode_mxfp4: follow main's reducer (partition_bound removed)

launch_pa_decode_ps_reduce now takes the bound as max_partitions; same value
as before: min(parts, capacity, tiles).

Co-Authored-By: Claude <[email protected]>

* [FlyDSL] pa_decode_mxfp4: drop the routes no caller uses

Removes the bf16-query reference path, the tile_depth and direct_output
arguments, multi-partition plan-free and the fp8 comparison in the test
benchmark. Generated ISA and outputs are unchanged for what remains.

Co-Authored-By: Claude <[email protected]>

* [Test] pa_decode_mxfp4: rewrite the op_test in aiter script style, no pytest

Plain check functions with asserts, a case table and a pandas summary, try/except
for the rejection cases (expect_error), one PA_DECODE name for the implementation
under test. Same 39 correctness cases and the same timing sweep.

Co-Authored-By: Claude <[email protected]>

* [Test] pa_decode_mxfp4: assertAllclose instead of rel-L2, call pa_decode_mxfp4 directly

Replace the custom rel_l2/assert_rel with assertAllclose (rtol=atol=1e-2, at
most 1% of elements outside; the measured worst case is 0.1%), drop the
PA_DECODE alias, and make the timing section header say what is timed.
Same 39 cases and timing sweep.

Co-Authored-By: Claude <[email protected]>

* [FlyDSL] pa_decode: MXFP4 K/V in the shared tile kernel, replacing the dedicated kernel

Fold MXFP4 K/V (e2m1 data + e8m0 scale per 32) into the fp8/bf16
compile_pa_decode_tile (kv_dtype="mxfp4"); pa_decode dispatches a uint8 key
cache to it and pa_decode_mxfp4 stays as a thin entry. Delete
pa_decode_mxfp4_kernel.py; the MXFP4 cases move into test_flydsl_pa_decode.py.

Co-Authored-By: Claude <[email protected]>

* [Test] pa_decode: drop an unused unpacked name (ruff RUF059)

Co-Authored-By: Claude <[email protected]>

* [Test] pa_decode: rewrite the UT as an aiter script, no pytest

Follow the aiter-op-test style (test_quant.py, test_flydsl_dcp_topk_merge.py):
@benchmark tests swept from main(), run_perftest for us/TFLOPS/TB/s, an
FP32 reference compared with assertAllclose, markdown summary tables, a
__main__ guard, and exit 1 listing every failed case. Arch and shape skips
filter the sweep up front instead of pytest.skip. The same 242 cases are
enumerated (226 run on gfx950, 16 MXFP4 unowned-row cases are filtered by
design). Rejected inputs are checked with a small expect-error helper.

CI runs the file with plain `python3 "$file"`: drop the pytest special case
in aiter_test.sh and the pytest invocation in ffm-bringup.yaml, which would
otherwise collect nothing from the script.

Co-Authored-By: Claude Code <[email protected]>

* [FlyDSL] pa_decode: MXFP4 validates the operands the generic path already checks

The MXFP4 branch reached the kernel with a non-contiguous block table, a
context_lengths/block_tables batch that differs from the query, operands on
another device, a query or output with a strided head_dim axis, key_scale=None,
or a windowed work_plan. Those gave wrong output, illegal memory accesses or an
AttributeError. Refuse them with the generic path's checks and messages, and
add one regression case per refusal to the UT's MXFP4 rejected-input table.

Co-Authored-By: Claude Code <[email protected]>

* [FlyDSL] pa_decode: MXFP4 checks the device of the output and user scratch

The generic path refuses an output or scratch tensor on another device; the
MXFP4 branch checked only dtype, shape and contiguity, so a CPU output or
exp_sums reached the kernel as a device pointer. Refuse both, and add one
regression case each to the refused-input table.

Co-Authored-By: Claude Code <[email protected]>

* [Test] pa_decode: collectable zero-arg test_* for CI pytest, restore .github

CI dispatches this file with `python3 -m pytest -q`. Rename the arg-taking
@benchmark sweeps to run_* and add zero-arg test_pa_decode_{plan,fp8,bf16,mxfp4}
that run the same sweeps and assert no failures (unittest.SkipTest when the
arch/FlyDSL cannot run). The script route keeps its CLI and summary tables.
No pytest import or API. Restore .github/ to the PR base so the PR no longer
changes CI dispatch.

Co-Authored-By: Claude Code <[email protected]>

* [FlyDSL] pa_decode MXFP4: validate scale page count and base alignment, fix test reference

- Require key/value cache and scale views to share the key cache's page count,
  so a block-table page cannot index past a shorter scale allocation.
- Reject data views that are not 16 B aligned and scale views that are not 4 B
  aligned, the contract mx_init declares for its loads.
- Test: add scale-pages-mismatch, misaligned-key and misaligned-scale reject
  cases; compare an e4m3 query as stored and re-round only a bf16 query.
- Test: check torch.cuda.is_available() before probing the GPU arch so a
  CPU-only host skips instead of raising.

Co-Authored-By: Claude <[email protected]>

* [FlyDSL] pa_decode MXFP4: keep tiny bf16 queries from flushing to zero

quantize_row floored q_scale at 1e-20 before taking its reciprocal, so a bf16
query below ~4e-18 was scaled into the e4m3 subnormal range and rounded to
zero even when large e8m0 K scales make its logits significant. For MXFP4 the
floor is now the smallest normal f32; it only guards the all-zero row, and the
published q_scale is unchanged so the restoration still matches. The FP8 KV
path keeps 1e-20.

Test: run_pa_decode_mxfp4_tiny_query (Q = 2**-80, K = +-2**80, V = +-1) gave 0
instead of 1 before the change.

Co-Authored-By: Claude <[email protected]>

* [FlyDSL] pa_decode MXFP4: keep the QK accumulator at logit scale

The query is normalized to e4m3 (|q| up to 448) and its scale restored after the
scaled MFMA, so a tiny query against a large e8m0 K scale (Q = 2**-80, K =
2**120) put ~448 * the logit in the f32 accumulator: inf, then inf - inf in the
softmax, although the logit is finite. The exponent of the published q_scale now
rides on the MFMA's e8m0 scale of Q (otherwise 1.0) and only its mantissa in
[1, 2) is applied afterwards, so the accumulator never exceeds the logit.
q_scale is floored at the smallest normal f32 and published floored, which also
keeps a bf16 subnormal row (2**-133) in e4m3 instead of mis-scaling it. FP8 KV
and e4m3 queries (q_scale 1.0) are unchanged.

Test: the tiny-query case is now a sweep of extreme query/K-scale pairs against
the FP32 reference: Q = 2**-80 with K = 2**120 and Q = 1 with K = 2**120 gave
inf, Q = 2**-133 with K = 2**127 gave 0 instead of 0.175 before the change; the
rest pass before and after. Full pa_decode suite and the MXFP4 timings are
unchanged on gfx950.

Co-Authored-By: Claude Code <[email protected]>

* [FlyDSL] pa_decode MXFP4: block-table fallback past the staged pages, name the rejected argument

- mx_pages read the LDS page ids with no bound, while the generic path falls back to
  the block table past the staged window. A planned task longer than the 256 staged
  pages (max_context_length below the context) read LDS past the ids and used the
  garbage as a page. It now takes the block-table entry there, as _staged_page does;
  the in-window read is unchanged (MXFP4 timings within 1%).
- pa_decode: the MXFP4 NotImplementedError was one message for four conditions and
  never named compute_type. Each condition now says which one failed and its value.
- pa_decode_mxfp4: the removed tile_depth and direct_output knobs gave pa_decode's
  "unexpected keyword argument"; they now raise NotImplementedError saying so.

Test: run_pa_decode_mxfp4_short_bound (313 pages, bound 128, one-partition plan with
a strided output) gave 0 instead of 0.18 before the change; the reject cases cover
compute_type and the two removed knobs.

Co-Authored-By: Claude Code <[email protected]>

* [FlyDSL] pa_decode_mxfp4: one-line reason for the removed direct_output knob (ruff ISC004)

Co-Authored-By: Claude Code <[email protected]>

* [FlyDSL] pa_decode MXFP4: bound PV accumulation before normalization

Scale probabilities for the PV MFMA so a large finite output cannot overflow the intermediate FP32 sum, then restore the scale in the epilogue. Cover the low-value and maximum-context bounds with exact-output tests.

Co-Authored-By: Claude Code <[email protected]>

* [FlyDSL] pa_decode MXFP4: address review (merge entry, split flags, gate, tests)

- Delete the standalone pa_decode_mxfp4 entry; pa_decode takes the MXFP4 views
  (key_scale / value_scale) and accepts dtypes.fp4x2 / dtypes.fp8_e8m0 views.
- Remove the direct-path clamp to the staged page window: page ids past it come
  from the block table, so a stale max_context_length no longer drops tokens.
- Split is_bf16_kv into is_bf16_kv / PV_BF16 / MXFP4; MXFP4 requires gfx950 in
  select(), has its own LDS check, QP_ELEM_BYTES is 1 (Q is e4m3 in LDS), and an
  fp8 query is refused unless KV is MXFP4.
- Rename mx_* to mxfp4_* in the kernel modules.
- Tests: fold the MXFP4 PV-range, extreme-scale, short-bound, one-task-per-row
  and rejection cases into run_pa_decode (no new run_* functions), add 128k
  peaked-softmax cases against an fp64 reference, use dtypes.fp4x2/fp8_e8m0.

Co-Authored-By: Claude Code <[email protected]>

* [FlyDSL] pa_decode MXFP4: do not bound the reducer by max_context_length

The reducer's partition count was capped by ceil(max_context_length / 256), but a
task may own more tokens than the bound (max_context_length only sizes the staged
page ids). A two-partition plan over 1024 tokens with max_context_length=128 then
merged only the first partial. Bound it by the plan and its capacity only.

Add mxfp4-short-bound-np2 (fails before: 22% of elements off).

Co-Authored-By: Claude Code <[email protected]>

* [FlyDSL] pa_decode MXFP4: document the V range, inline the select rejection checks

- State in the pa_decode docstring and the traits shortcut note that V is staged as
  bf16, so an MXFP4 V above the bf16 maximum (e8m0 byte 254 with e2m1 >= 2, byte 253
  with >= 4) widens to inf even when the normalized output is finite.
- Drop the _check_unsupported_select helper: the three PaDecodeSchedule.select
  rejection cases are dispatched inline in run_pa_decode.

Co-Authored-By: Claude Code <[email protected]>

* [FlyDSL] pa_decode MXFP4: convert test_flydsl_pa_decode.py to pytest

Replace the custom sweep runner with pytest parametrization
(test_pa_decode_plan, test_pa_decode, test_pa_decode_unowned_kv_rows).

Co-Authored-By: Claude Code <[email protected]>

* test(flydsl_pa_decode): use valid V e8m0 scale byte 1 in MXFP4 pool specs

Three MXFP4 pool specs set the V scale e8m0 byte to 0, which the kernel
does not support. Use byte 1 (2**-127) and rename the cases and comment
to match.

Co-Authored-By: Claude Code <[email protected]>

* Simplify MXFP4 PA comments

Co-Authored-By: Claude Code <[email protected]>

* flydsl pa_decode: trim comments in traits.py

Comment-only change; AST is identical to the previous commit.

Co-Authored-By: Claude Code <[email protected]>

* flydsl pa_decode: use explicit dtypes for FP8/MXFP4 pointers

Label Q FP8, gfx1250 KV, and MXFP4 K/V data and scale pointers with their
real element types instead of fx.Uint8. Byte-addressed fx.Uint8 bases in
op_lds.py are intentionally unchanged.

Co-Authored-By: Claude Code <[email protected]>

* flydsl pa_decode: clean up FP8 input-query handling

Co-Authored-By: Claude Code <[email protected]>

* flydsl pa_decode: restore FP8 input-query support for MXFP4 KV

Re-add the stored e4m3 query path removed in 491b929 (accepted by
ROCm/ATOM#2770's sparse_pa_mxfp4), selected by a Q_IN_DTYPE trait rather
than a bool. The in-kernel BF16 query to FP8 quantization and the BF16
MXFP4 path are unchanged.

Co-Authored-By: Claude Code <[email protected]>

* flydsl pa_decode: refuse MXFP4 query/output spans over 2**31 - 1 bytes

The kernel adds query row/head offsets in i32, so a query whose last head_dim
chunk ends past 2 GiB wrapped to an earlier row, and a direct output store did
the same. Refuse such query and output views before launch; two refused-input
cases in test_pa_decode cover them.

Co-Authored-By: Claude <[email protected]>

---------

Co-authored-by: Claude <[email protected]>
Co-authored-by: r <r@x>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

7 participants