Skip to content

[FlyDSL] MiniMax-M3 index score: MXFP4 index-cache decode scorer - #7060

Merged
valarLip merged 11 commits into
mainfrom
ganyi/m3-index-score-decode-fp4
Nov 2, 2026
Merged

valarLip merged 11 commits into
mainfrom
ganyi/m3-index-score-decode-fp4

Conversation

@ganyi1996ppo

@ganyi1996ppo ganyi1996ppo commented Oct 28, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Adds a MiniMax-M3 index-score decode kernel that reads an MXFP4 index K cache (e2m1 data plus one e8m0 scale per 32 elements), taking a bf16 or an e4m3 query. M3.1 can keep its index cache in MXFP4, which halves the index-cache bytes per token (and so raises the KV pool capacity); this kernel is the decode reading side. The fp8 index-score builder gains an mxfp4 specialisation; the generated code (LLVM IR and ISA) of the existing fp8 kernels is unchanged.

Files: aiter/ops/flydsl/kernels/minimax_m3_index_score.py (1474 to 1928 lines), op_tests/test_flydsl_minimax_m3_index_score.py (2169 to 2605 lines, the MXFP4 tests added), and two lazy exports in aiter/ops/flydsl/__init__.py: minimax_m3_index_score_fp4_flydsl (score_flydsl_fp4) and minimax_m3_index_score_fp4_flydsl_supported (index_score_supported_fp4). No new files, no C++.

Split from #7058, the earlier combined version that this PR and its prefill sibling #7061 replace (whether #7058 gets closed is pending the author's decision).

Format

  • MXFP4: e2m1 data, one e8m0 scale per 32 elements.
  • Page of 128 tokens = [128 x 64 B data][128 x 4 B scale] = 8704 B. The kernels take two views, k_data [pages,128,64] and k_scale [pages,128,4], each with its own page stride, so the layout is the caller's choice (separate tensors or the single-region page above both work; a test checks the two agree bitwise).
  • e8m0 bytes 0 and 255 are outside the contract. e2m1 x 2^e is exact in e4m3 for biased e8m0 in [119, 133], so widening an MXFP4 cache to the unit-scale fp8 index cache (the baseline in bench_score_mxfp4) saturates outside that window. The MXFP4 scorers apply the scale themselves. Values outside the window were not measured on real tensors; the tests cover wide scale ranges against the oracle.

Kernel

score_flydsl_fp4 uses the same work map, geometry, Q loading, causal cutoff and score store as the fp8 scorer: MXFP4 is a compile-time specialisation (mxfp4, plus q_fp8 for an e4m3 Q) of build_index_score, and only the K data+scale loads and the dequant/MFMA step are MXFP4-specific. The kernel signature differs (two cache views), so the shared body is a closure called from two thin kernels. Generated LLVM IR and ISA of the fp8 kernels are unchanged, and the MXFP4 kernels match the earlier separate MXFP4 kernel (checked at the fold, outputs bit-equal; unchanged since: 31 specialisations, 13 fp8 and 18 MXFP4, byte-identical before and after the last cleanup). The MXFP4 entry points take no q_scale and no CP shard (no caller needs them); score_flydsl and index_score_supported gain an optional k_scale that selects the MXFP4 cache.

  • bf16 Q: K is expanded to bf16 with v_cvt_scalef32_pk_bf16_fp4 and fed to the bf16 16x16x32 MFMA, so the numerics contract (K lifted to Q's precision) is unchanged.
  • e4m3 Q: one v_mfma_scale_f32_16x16x128_f8f6f4 per 16-token tile, A = fp4 K with its e8m0 byte, B = Q as e4m3; products are exact in fp32.
  • K tiles in flight = 6 (the fp8 scorer uses 3; an MXFP4 tile is half the bytes). In a 2/3/4/6/8 sweep, 6 was 15-35% faster than 3 on small batch x context cells.

Performance

Measured on gfx950 (MI355X), one GPU, FlyDSL 0.4.0, image rocm/atom-dev:nightly_202610261558. Method: CUDA-graph replay of K calls (K = 2..16 decode) over disjoint regions of a 300k-page pool to defeat the MALL, median of 25 replays, same card and process, every cell run in two rounds with the arm order reversed (the table reports the mean of the two rounds). Random K data, e8m0 in [122,127], uniform context per batch, no padding bound beyond the context. Times are microseconds per call. The fp8 baseline is the existing fp8 kernel with a bf16 Q. Ratios below 1 mean MXFP4 is faster.

S = queries per request, H = index heads, B = batch. Range over the 9 cells below: bf16 Q / fp8 = 0.48-0.65, e4m3 Q / fp8 = 0.47-0.59. Kernel-level numbers only. The table was taken with the earlier separate MXFP4 kernel; the folded kernel has identical ISA, and a base-vs-folded re-run of the same protocol (A-B-B-A) was within noise (geomean 1.003 fp8, 1.008 MXFP4 bf16 Q, 1.006 e4m3 Q, worst cell 1.021, run-to-run spread up to 3%). Cells measured with a CP4 shard were dropped with the CP kwarg.

Decode table (9 cells)
shape B ctx fp8 (us) MXFP4 bf16 Q (us) MXFP4 e4m3 Q (us) bf16 Q / fp8 e4m3 Q / fp8
S4 H1 8 32768 9.65 6.24 5.71 0.65 0.59
S4 H1 8 100000 24.09 13.48 12.29 0.56 0.51
S4 H1 8 131072 26.72 14.59 13.47 0.55 0.50
S4 H1 16 32768 15.25 8.88 8.39 0.58 0.55
S4 H1 16 100000 40.33 20.88 19.99 0.52 0.50
S4 H1 16 131072 48.79 24.83 23.55 0.51 0.48
S4 H1 32 32768 26.65 14.38 13.52 0.54 0.51
S4 H1 32 100000 78.49 38.35 36.67 0.49 0.47
S4 H1 32 131072 93.79 45.37 44.20 0.48 0.47

Tests

python op_tests/test_flydsl_minimax_m3_index_score.py                     # 90 MXFP4 correctness cases (PASS/FAIL table, exit 1 on any failure), then the decode, MXFP4 and prefill perf tables
pytest op_tests/test_flydsl_minimax_m3_index_score.py                     # main's existing pytest suite, unchanged: 269 passed, 4 skipped

Run on one MI355X (gfx950), image rocm/atom-dev:nightly_202610261558, with this branch's aiter/ops/flydsl/ and op_tests/ overlaid on the image's aiter (41d4d8d), because main's full Python tree does not import against the image's csrc. The pre-existing fp8 tests in that file are unchanged and give 269 passed, 4 skipped (as before).

The tests are standalone: the cache is built with aiter's per_1x32_f4_quant and dequantized with fp4_utils, with no dependency on any writer kernel. Scores are judged against the fp8 test's own oracle. They cover decode geometries, CUDA-graph buffers, split vs single-region views, alignment and rejection rules (including a non-positive or NaN sm_scale), and e8m0 extremes.

Mutation check: swapping the decode nibble order failed 60 tests when measured on the earlier combined branch; not re-run after the split or the later cleanups.

Known limits / not measured

  • Only gfx950 was tested.
  • Kernel numerics on real M3 tensors were not measured; the tests use synthetic caches quantized with aiter's quantizer.
  • e8m0 values outside [119, 133] are the saturating range of the fp8-cache widening used as the baseline; they have no real-data measurement.
  • End-to-end numbers are not part of this PR; they belong to the ATOM integration PR.
  • black 26.10.1 and ruff 0.16.0 are clean on the two changed Python files at this head; the whole-repo ruff check . / black --check . was not re-run at this head.

PR Self-Review

Reviewed revision

827441b

Behavior and intent

Adds score_flydsl_fp4 / index_score_supported_fp4 (and an optional k_scale on score_flydsl / index_score_supported): the MiniMax-M3 decode block scorer reading an MXFP4 index K cache (e2m1 data plus one e8m0 byte per 32 elements, 68 B per token against 128 B for fp8), with a bf16 or an e4m3 query. The existing decode scorer takes only an fp8 index cache, so an MXFP4 cache could not be scored without first expanding it to fp8; M3.1 can keep the cache in MXFP4, which halves its bytes; the decode kernel takes 0.47-0.65 of the fp8 kernel's time in the table above (measured at an earlier head). Behaviour of the fp8 path is unchanged.

Validation and unverified scope

Measured at this head (827441b), on one MI355X (gfx950), image rocm/atom-dev:nightly_202610261558 with this branch's aiter/ops/flydsl/ and op_tests/ overlaid on the image's aiter (see Tests), FlyDSL cache disabled and the aiter JIT cache removed:

  • python op_tests/test_flydsl_minimax_m3_index_score.py run from the repo root and again from /tmp: both exit 0, 90 of 90 MXFP4 correctness cases PASS, and the decode, MXFP4 and prefill perf tables are printed.
  • LLVM IR and final ISA, before vs after this head's commit, for 8 fp8 kernels (4 decode, 4 prefill compiled from the same tree) and 8 MXFP4 decode kernels (4 shapes, bf16 and e4m3 Q): all byte-identical.
  • black 26.10.1 and ruff 0.16.0 are clean on the two changed Python files.
    Unverified scope: other GPUs than gfx950; real M3 tensors; end-to-end use (ATOM integration PR); the pytest run of main's existing fp8 suite (269 passed, 4 skipped, quoted above) was done at an earlier head and not repeated at this one; the performance table is from an earlier head; the mutation check quoted under Tests was not re-run; CI results at this head.

PR-specific question

The self-review bot lists only the four generic questions on this PR, no PR-specific one. Its question 3, what each changed op test would fail on before this PR and why existing canonical coverage does not already provide it: before this PR score_flydsl_fp4 and index_score_supported_fp4 do not exist, so every MXFP4 case fails with an attribute error. The pre-existing pytest cases in this file cover fp8 caches only (they build no MXFP4 cache, never pass k_scale) and are unchanged.

Changed op tests

op_tests/test_flydsl_minimax_m3_index_score.py (the only op test changed): the existing fp8 pytest cases are untouched; this PR adds an MXFP4 section driven from main(), 90 cases, each of which would fail as follows:

  • matches_oracle_* and every_geometry_*: scores against an independent oracle on the dequantised cache, over the decode matrix and every geometry the selector reaches, bf16 and e4m3 Q. Catches a wrong nibble order, k-axis map or scale byte.
  • wide_scale_range_*: scale bytes across 2^+-20, so each lane group must pick its own byte.
  • graph_buffers_*: preallocated score buffers and work map captured once in a CUDA graph and replayed with different lengths and block tables.
  • split_and_single_region_views_agree_bitwise, e4m3_q_rows_must_be_16_byte_aligned, invalid_cache_rejected_*, metadata_rejects_cpu, supported_accepts_valid_inputs: layout and rejection contract (dtypes, shapes, strides, overlap, misalignment).
  • sm_scale_must_be_positive_finite (added at this head): sm_scale of -1, 0 and NaN must raise a ValueError, because the epilogue takes the page max before multiplying by the scale and a non-positive scale would pick the wrong block silently. The existing test_scale_fp32_range covers only 1e-50 and 1e39.
  • default_score_buffer_reads_as_minus_inf: with the default (kernel-allocated) score buffer, slots past a request's end read as -inf and the rest are finite.
  • bench_score_mxfp4: the perf sweep (us, TFLOPS, TB/s for MXFP4 against the fp8 scorer), each result compared with the oracle.
    These are not redundant with the fp8 cases in the same file: none of them builds an MXFP4 cache.

Related work

Independent of the other MXFP4 index/KV PRs: this one builds and passes its tests on main alone. Siblings, each reviewable on its own:

Both index-score halves add their own export lines to aiter/ops/flydsl/__init__.py; they merge in either order without conflict (checked by merging both branches in both orders).

🤖 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 7060 --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.

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 benchmark unfairly includes full-cache conversion in every timed fp8 invocation while using precomputed fp4 inputs, inflating fp8 latency with work omitted from its reported byte count.

1 open issue
What changed in this PR

Adds MXFP4 index-cache decode scoring for MiniMax-M3, extending the existing FP8 scorer with a lower-storage cache format. This PR covers decode; prefill is handled separately in #7061.

Changes:

  • Specializes the shared scorer for MXFP4 caches with BF16 or E4M3 queries and optional query scaling.
  • Exposes lazy-loaded MXFP4 scoring and support-check APIs.
  • Adds correctness, cache-layout, graph-replay, input-validation, and performance tests.
File Description
op_tests/​test_flydsl_minimax_m3_index_score.py Adds MXFP4 tests and benchmarks; runs correctness checks before script-mode benchmarks.
aiter/​ops/​flydsl/​kernels/​minimax_m3_index_score.py Adds MXFP4 specialization, cache validation, and public wrappers to the shared scorer.
aiter/​ops/​flydsl/​__init__.py Exports the MXFP4 scorer and support predicate through lazy imports.

Review effort: Balanced

Copilot AI balanced review requested due to automatic review settings October 28, 2026 08:34

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

Negative query scales can bypass validation, score tests can miss infinity-sign mismatches, and FP8 benchmarks include conversion overhead absent from the FP4 path.

1 open issue
2 previously missed issues

In code that hasn't changed since last review

Medium severity Reject negative query scale independently of folded multiplier

aiter/​ops/​flydsl/​kernels/​minimax_m3_index_score.py:1876

With sm_scale=-1.0 and q_scale=-1.0, the folded multiplier is positive, so both the entry point and support predicate accept a query scale that violates the documented contract. Validate q_scale > 0 independently in _score and _supported (line 1733), while retaining the combined multiplier's finite FP32 range check.

Medium severity Use check_scores to validate negative-infinity entries

op_tests/​test_flydsl_minimax_m3_index_score.py:2125

This helper accepts +inf where the top-k reference contains -inf: both finite masks are false, so those entries are excluded from the error check. Replace the local comparison with check_scores(a, b) to check the negative-infinity mask and use the required checkAllclose path with standard mismatch diagnostics.

Review effort: Balanced

@ganyi1996ppo

Copy link
Copy Markdown
Contributor Author

Review items handled in bc2caf4:

  • Negative query scale (kernels/minimax_m3_index_score.py): valid, fixed. q_scale <= 0 or NaN is now refused on its own in _score and _supported (the folded-multiplier FP32 range check stays); sm_scale = q_scale = -1 is rejected by both, with a new test.
  • Infinity-sign mismatch in the top-k check (op_tests): valid, fixed. assert_topk_agrees now calls check_scores, which compares the -inf mask and runs checkAllclose; a new test covers a +inf where the reference has -inf.
  • fp8 baseline timing: same as the inline thread (fixed there).

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

The gfx950 FP4/scaled-MFMA paths and shared fp8 refactor require exact-head GPU correctness, generated-code equivalence, and paired performance validation that this source-only review cannot independently verify.

No open issues 🎉

1 resolved since last review

Review effort: Balanced

ganyi1996ppo and others added 6 commits October 28, 2026 21:20
New kernel `score_flydsl_fp4` scores an MXFP4 index cache (e2m1 data plus one
e8m0 scale per 32 elements) given as two views, k_data [pages,128,64] and
k_scale [pages,128,4], each with its own page stride, so separate tensors and
a single-region 8704 B page both work.

Query dtype selects the K path:
- bf16 Q: K is widened to bf16 with v_cvt_scalef32_pk_bf16_fp4 and fed to the
  same bf16 16x16x32 MFMA as the fp8 scorer; the numerics contract (K lifted to
  Q's precision) is unchanged.
- e4m3 Q: one v_mfma_scale_f32_16x16x128_f8f6f4 per 16-token tile, A = the
  lane's 16 B of fp4 K plus its e8m0 byte, B = Q as e4m3 (unit scale). Products
  are exact in fp32, so scores are those of dequantize(K) against Q as stored.
  An optional q_scale (default 1.0, positive) is folded into the score
  multiplier.

K tiles in flight is 6 rather than the fp8 scorer's 3: an MXFP4 tile is half
the bytes, and 6 was 15-35% faster than 3 on small batch*context cells in a
2/3/4/6/8 sweep.

Work map, geometry and CP shard are imported from the fp8 scorer. The builder
is a copy of `build_index_score` with the K side replaced, not a
parameterisation of it, so the two can drift and an epilogue or work-map change
must be mirrored. e8m0 bytes 0 and 255 are outside the contract.

Only exports are added to aiter/ops/flydsl/__init__.py; the fp8 path is
untouched.

Co-Authored-By: Claude <[email protected]>
Generated LLVM IR and ISA are byte-identical across 14 specialisations.

Co-Authored-By: Claude <[email protected]>
The sweep used checkAllclose, which only logs, so CI (python3 file)
could not fail on a wrong kernel; use the fp8 test's check_scores.
Import the fp8 test as siblings do and build the case matrix once.

Co-Authored-By: Claude <[email protected]>
python3 op_tests/<file> now runs the pytest matrix before the perf sweep
(as test_flydsl_hc_mix.py does), so CI can fail on a wrong kernel. Import
the fp8 test with a script-mode fallback, hoist torch, fix the docstring
about e8m0 scale clamping. ruff 0.16.0 (ruff check .) and black are clean.

Co-Authored-By: Claude <[email protected]>
One builder and one test file now cover both index caches: the MXFP4 cache
is an `mxfp4` specialisation of build_index_score, and score_flydsl_fp4 /
index_score_supported_fp4 are thin wrappers over the shared host path.
Generated LLVM IR and ISA are byte-identical to the separate kernels for 39
specialisations (13 fp8, 26 MXFP4); outputs are bit-equal on 54 cases.
python3 op_tests/<file> runs the pytest checks before the perf sweeps.

Co-Authored-By: Claude <[email protected]>
Replaces the internal ASTRewriter.transform call, so a FlyDSL bump cannot
break the import. q_scale's docstring now says it scales a bf16 Q too (the
code always did) and a test checks it. LLVM IR and ISA are byte-identical
for 39 specialisations.

Co-Authored-By: Claude <[email protected]>
@zufayu
zufayu removed the request for review from yadaish October 29, 2026 10:16
The MXFP4 tests this PR added used pytest fixtures, parametrize, skip, raises
and a pytest.main call in __main__. They are now plain check functions driven
from main() by a case table (PASS/FAIL table, exit 1 on any failure), like the
sibling flydsl op_tests, and __main__ is main's again. The same 89 cases run.
They compare with check_scores instead of the local compare. The pytest code
that was already on main is untouched.

Co-Authored-By: Claude <[email protected]>
Copilot AI balanced review requested due to automatic review settings October 30, 2026 02:16
@aiter-bot

aiter-bot commented Oct 30, 2026 •

Copy link
Copy Markdown

NOT READY FOR HUMAN REVIEW

PR Self-Review

Revision 3c019db0daf1 · 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.

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 to resolve the mismatch between the documented e4m3 saturation contract and the directly scaled MXFP4 decode path, which can produce different scores.

No open issues 🎉

1 resolved since last review

Review effort: Balanced

…tion check

Kernel: use fx.rocdl for the scaled MFMA like the rest of the file, name the
0x7F7F7F7F unit e8m0 scale UNIT_SCALE, say why the MFMA is raw. No change to
the generated code.
Test: add a check that sm_scale <= 0 and NaN are refused by score_flydsl_fp4.

Co-Authored-By: Claude <[email protected]>
Copilot AI balanced review requested due to automatic review settings October 30, 2026 02:39
@ganyi1996ppo

ganyi1996ppo commented Oct 30, 2026 •

Copy link
Copy Markdown
Contributor Author

Current head: 827441b. Any other SHA quoted in my older replies on this PR belongs to history that was rewritten by a rebase; read this head.

What changed since accbe63:

  • kernel: fx.rocdl. used consistently (the bare rocdl import is gone); the unit e8m0 scale 0x7F7F7F7F is the named constant UNIT_SCALE; one comment says the scaled MFMA is called raw on dword vectors (I did not try the fx.gemm MFMA_Scale atom here). Generated code unchanged: LLVM IR and ISA byte-identical before/after for 8 fp8 and 8 MXFP4 decode kernels.
  • op test: new sm_scale_must_be_positive_finite check, score_flydsl_fp4 must raise ValueError for sm_scale of -1, 0 and NaN (my earlier comment of 2026-10-29 02:16 said sm_scale = q_scale = -1 is rejected by both with a new test; q_scale has since been removed and no test of sm_scale <= 0 or NaN was in the tree at the previous head, so this adds it).
  • Run on gfx950: python op_tests/test_flydsl_minimax_m3_index_score.py from the repo root and from /tmp, exit 0, 90/90 MXFP4 checks PASS, perf tables printed.
  • PR description updated (stale numbers, the PR Self-Review sections).

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 to determine how buffer initialization included in benchmark timing but excluded from throughput accounting affects the reported performance results.

No open issues 🎉

Review effort: Balanced

@yhl-amd

yhl-amd commented Oct 30, 2026

Copy link
Copy Markdown
Contributor

@valar-cop review this pr

@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

any perf number? and confirm the MI35X shard actually ran the 90 mxfp4 checks

ci green.

…m0 255 doc

- every-geometry check now runs the CP points (cp_world>1 with k_scale) against
  the oracle; MXFP4 + CP works, so it is covered rather than rejected.
- q_for keeps q's strides, so the qslice e4m3 case reaches load_q8's strided path.
- bench_score_mxfp4 allocates the score buffer once, outside the timed region.
- Docs: e8m0 byte 255 is +inf as f32 (bf16-Q path) and NaN in the scaled MFMA
  (e4m3-Q path); measured, the score is NaN on both.

Co-Authored-By: Claude Code <[email protected]>
Copilot AI balanced review requested due to automatic review settings October 30, 2026 09:54

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

The shared-kernel refactor and new gfx950 FP4 scaled-MFMA paths require target-GPU correctness, generated-code equivalence, graph-replay, and paired performance checks that this source-only review cannot perform.

No open issues 🎉

Review effort: Balanced

@valarLip
valarLip merged commit 514c7cd into main Nov 2, 2026
64 checks passed
@valarLip
valarLip deleted the ganyi/m3-index-score-decode-fp4 branch November 2, 2026 03:08
solinzby1 pushed a commit that referenced this pull request Nov 2, 2026
* [FlyDSL] M3 index score: MXFP4 index-cache decode scorer

New kernel `score_flydsl_fp4` scores an MXFP4 index cache (e2m1 data plus one
e8m0 scale per 32 elements) given as two views, k_data [pages,128,64] and
k_scale [pages,128,4], each with its own page stride, so separate tensors and
a single-region 8704 B page both work.

Query dtype selects the K path:
- bf16 Q: K is widened to bf16 with v_cvt_scalef32_pk_bf16_fp4 and fed to the
  same bf16 16x16x32 MFMA as the fp8 scorer; the numerics contract (K lifted to
  Q's precision) is unchanged.
- e4m3 Q: one v_mfma_scale_f32_16x16x128_f8f6f4 per 16-token tile, A = the
  lane's 16 B of fp4 K plus its e8m0 byte, B = Q as e4m3 (unit scale). Products
  are exact in fp32, so scores are those of dequantize(K) against Q as stored.
  An optional q_scale (default 1.0, positive) is folded into the score
  multiplier.

K tiles in flight is 6 rather than the fp8 scorer's 3: an MXFP4 tile is half
the bytes, and 6 was 15-35% faster than 3 on small batch*context cells in a
2/3/4/6/8 sweep.

Work map, geometry and CP shard are imported from the fp8 scorer. The builder
is a copy of `build_index_score` with the K side replaced, not a
parameterisation of it, so the two can drift and an epilogue or work-map change
must be mirrored. e8m0 bytes 0 and 255 are outside the contract.

Only exports are added to aiter/ops/flydsl/__init__.py; the fp8 path is
untouched.

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

* Trim MXFP4 decode scorer dead indirection and docstring

Generated LLVM IR and ISA are byte-identical across 14 specialisations.

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

* Make MXFP4 index-score sweep assert like the fp8 sweep

The sweep used checkAllclose, which only logs, so CI (python3 file)
could not fail on a wrong kernel; use the fp8 test's check_scores.
Import the fp8 test as siblings do and build the case matrix once.

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

* Run MXFP4 index-score checks from main() and fix import/lint

python3 op_tests/<file> now runs the pytest matrix before the perf sweep
(as test_flydsl_hc_mix.py does), so CI can fail on a wrong kernel. Import
the fp8 test with a script-mode fallback, hoist torch, fix the docstring
about e8m0 scale clamping. ruff 0.16.0 (ruff check .) and black are clean.

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

* Fold the MXFP4 decode scorer into the fp8 index-score builder

One builder and one test file now cover both index caches: the MXFP4 cache
is an `mxfp4` specialisation of build_index_score, and score_flydsl_fp4 /
index_score_supported_fp4 are thin wrappers over the shared host path.
Generated LLVM IR and ISA are byte-identical to the separate kernels for 39
specialisations (13 fp8, 26 MXFP4); outputs are bit-equal on 54 cases.
python3 op_tests/<file> runs the pytest checks before the perf sweeps.

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

* Use public flyc.jit for the shared index-score body

Replaces the internal ASTRewriter.transform call, so a FlyDSL bump cannot
break the import. q_scale's docstring now says it scales a bf16 Q too (the
code always did) and a test checks it. LLVM IR and ISA are byte-identical
for 39 specialisations.

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

* Address review: validate q_scale on its own, fair fp8 baseline, sign-aware top-k check

q_scale was only checked through the folded multiplier, so sm_scale = q_scale = -1
passed; reject q_scale <= 0 in the entry point and the predicate. The perf sweep
now converts the fp8 cache once outside the timed callable. assert_topk_agrees
uses check_scores, which also compares the -inf mask (a +inf slot slipped through).

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

* Drop MXFP4 scorer routes nothing calls

q_scale and the CP kwargs have no caller in ATOM#2770 or vLLM#64198, so the
MXFP4 entry points lose them, and score_flydsl / index_score_supported take an
optional k_scale instead of a parallel private core. Remove the tests that only
re-checked other tests' logic (top-k, fp8 cross-check, bf16-vs-e4m3 gap,
quantizer rule) and the CP and q-dtype multiples of graph and view tests.
IR and ISA are byte-identical for all 31 remaining specialisations.

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

* Run the MXFP4 decode op tests from main() instead of pytest

The MXFP4 tests this PR added used pytest fixtures, parametrize, skip, raises
and a pytest.main call in __main__. They are now plain check functions driven
from main() by a case table (PASS/FAIL table, exit 1 on any failure), like the
sibling flydsl op_tests, and __main__ is main's again. The same 89 cases run.
They compare with check_scores instead of the local compare. The pytest code
that was already on main is untouched.

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

* MXFP4 decode: fx.rocdl consistently, named unit scale, sm_scale rejection check

Kernel: use fx.rocdl for the scaled MFMA like the rest of the file, name the
0x7F7F7F7F unit e8m0 scale UNIT_SCALE, say why the MFMA is raw. No change to
the generated code.
Test: add a check that sm_scale <= 0 and NaN are refused by score_flydsl_fp4.

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

* MXFP4 decode tests: CP shards, strided e4m3 Q, prealloc bench; fix e8m0 255 doc

- every-geometry check now runs the CP points (cp_world>1 with k_scale) against
  the oracle; MXFP4 + CP works, so it is covered rather than rejected.
- q_for keeps q's strides, so the qslice e4m3 case reaches load_q8's strided path.
- bench_score_mxfp4 allocates the score buffer once, outside the timed region.
- Docs: e8m0 byte 255 is +inf as f32 (bf16-Q path) and NaN in the scaled MFMA
  (e4m3-Q path); measured, the score is NaN on both.

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

---------

Co-authored-by: Claude <[email protected]>
Co-authored-by: r <r@x>
wanzhenchn added a commit to ROCm/ATOM that referenced this pull request Nov 12, 2026
The MXFP4 CP decode hands aiter's scorer k_scale and the shard (cp_world /
cp_rank), and its work map and capacity calls the shard. A new GPU-free
test runs those three calls and binds each to the installed aiter's
signature, so an aiter older than ROCm/aiter#7060 (no k_scale) fails at
test time rather than at the first MXFP4 CP decode. It skips where
aiter.ops.flydsl does not import.

Co-authored-by: Cursor <[email protected]>
wanzhenchn added a commit to ROCm/ATOM that referenced this pull request Nov 12, 2026
The MXFP4 CP decode hands aiter's scorer k_scale and the shard (cp_world /
cp_rank), and its work map and capacity calls the shard. A new GPU-free
test runs those three calls and binds each to the installed aiter's
signature, so an aiter older than ROCm/aiter#7060 (no k_scale) fails at
test time rather than at the first MXFP4 CP decode. It skips where
aiter.ops.flydsl does not import.

Co-authored-by: Cursor <[email protected]>
wanzhenchn added a commit to ROCm/ATOM that referenced this pull request Nov 12, 2026
The MXFP4 CP decode hands aiter's scorer k_scale and the shard (cp_world /
cp_rank), and its work map and capacity calls the shard. A new GPU-free
test runs those three calls and binds each to the installed aiter's
signature, so an aiter older than ROCm/aiter#7060 (no k_scale) fails at
test time rather than at the first MXFP4 CP decode. It skips where
aiter.ops.flydsl does not import.

Co-authored-by: Cursor <[email protected]>
wanzhenchn added a commit to ROCm/ATOM that referenced this pull request Nov 12, 2026
The MXFP4 CP decode hands aiter's scorer k_scale and the shard (cp_world /
cp_rank), and its work map and capacity calls the shard. A new GPU-free
test runs those three calls and binds each to the installed aiter's
signature, so an aiter older than ROCm/aiter#7060 (no k_scale) fails at
test time rather than at the first MXFP4 CP decode. It skips where
aiter.ops.flydsl does not import.

Co-authored-by: Cursor <[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]>
valarLip pushed a commit to ROCm/ATOM that referenced this pull request Nov 13, 2026
The MXFP4 CP decode hands aiter's scorer k_scale and the shard (cp_world /
cp_rank), and its work map and capacity calls the shard. A new GPU-free
test runs those three calls and binds each to the installed aiter's
signature, so an aiter older than ROCm/aiter#7060 (no k_scale) fails at
test time rather than at the first MXFP4 CP decode. It skips where
aiter.ops.flydsl does not import.

Co-authored-by: Cursor <[email protected]>
valarLip pushed a commit to ROCm/ATOM that referenced this pull request Nov 14, 2026
…ranks on the MXFP4 index cache (MiniMax-M3.1 first) (#3104)

* minimax_m3: read each indexer-CP shard row in one tile, filtered

The step's local top-k waited on its longest row, which walked its shard
512 blocks at a time. Each row now stops at its own shard length and takes
one tile of the narrowest width covering it (512/1024/2048), and a wide
tile sorts only the keys at or above its group-max bound. Output is
unchanged; batch 24-60 drops from 8.8-15.8 to 6.0-10.0 us a layer.

merge_candidate_keys takes the emitted page geometry (pages_per_block,
block_page_stride), defaulting to the page-16 SHUFFLE cache's 8 / 8 as
before, so a page-128 KV can be merged into its own block table.

Co-authored-by: Cursor <[email protected]>

* minimax_m3: run the indexer-CP decode on the MXFP4 index cache

Under indexer CP each TP rank scores every index head over its 1/W of the
blocks. With the MXFP4 index cache that scorer is aiter's FlyDSL decode
scorer, which already takes the shard (cp_world / cp_rank with k_scale):

- IndexScoreBuffers carries the rank's shard; allocate_index_scorers sizes
  the work map at the shard's bound ceil(blocks / W) over every index head,
  and the workspace for that as well as for a prefill chunk (which stays
  TP). Unsharded, every call is the one it was.
- make_sparse_decode_metadata builds the step's map for the shard.
- indexer_context_scores_mxfp4 scores into a contiguous view of the shared
  workspace on that map; _cp_index_topk_decode runs it for the MXFP4 index
  and merges with the KV's page geometry (1 / 1 for the MXFP4 KV).
- indexer_cp_unsupported_reason no longer refuses the MXFP4 caches.

tests/test_minimax_m3_mxfp4_indexer_cp.py pins the wiring on CPU, and on
gfx950 emulates the 4 ranks against minimax_m3_index_topk_decode: the merged
top-k, sparse block table and context must equal the TP path's bit for bit,
for both page geometries, on a never-filled workspace.

Co-authored-by: Cursor <[email protected]>

* minimax_m3: check the indexer-CP FlyDSL calls against aiter's signatures

The MXFP4 CP decode hands aiter's scorer k_scale and the shard (cp_world /
cp_rank), and its work map and capacity calls the shard. A new GPU-free
test runs those three calls and binds each to the installed aiter's
signature, so an aiter older than ROCm/aiter#7060 (no k_scale) fails at
test time rather than at the first MXFP4 CP decode. It skips where
aiter.ops.flydsl does not import.

Co-authored-by: Cursor <[email protected]>

* minimax_m3: give the local top-k tile choice without its timings

The comment on the shard-row tile widths and the full-grid threshold
quoted per-layer latencies from one deployment. Keep the reasons alone:
one tile of the narrowest covering width, and four warps with an
unfiltered narrow tile below the threshold, two warps and the filter at
or above it.

Co-authored-by: Cursor <[email protected]>

* minimax_m3: leave the indexer-CP shard top-k as on main

The one-tile rewrite of `_local_topk` also changed the selector the
BF16/FP8 indexer-CP path runs, and #3116 rewrites the same kernel for the
same goal. Restore main's kernel and its tests so the change lands once,
with #3116. The MXFP4 wiring does not depend on it: main's selector
already masks the lanes past a row's blocks.

Co-authored-by: Cursor <[email protected]>

* minimax_m3: say what the shard top-k does past a row's blocks

`local_candidate_keys` loads each row up to the shard's block bound and
masks the lanes past the row's blocks, but the MXFP4 scorer's docstring
said it read none of them. The test's workspace docstring said the
workspace was filled and then never filled; it now says what the junk
is for.

Co-authored-by: Cursor <[email protected]>

* minimax_m3: keep the merge's page geometry for the MXFP4 KV

871b053 restored main's whole exchange file, and with it main's
`merge_candidate_keys`, which always emits the page-16 SHUFFLE geometry.
The MXFP4 CP decode passes `pages_per_block` / `block_page_stride` (1, 1),
so it raised a TypeError at its first merge. Bring the two arguments
back; the shard top-k stays main's.

Co-authored-by: Cursor <[email protected]>

* recipe(minimax_m3): say what indexer CP measured on the MXFP4 caches

The CONC >= 15 paragraph and its table are back to main's text: that table
was measured with the FP8 KV of the server command and does not carry over.
A paragraph after it gives the MXFP4 A/B on one aggregated TP4 server (lower
tok/s/GPU in all six cells, median ITL down only at 128K and CONC 64), says
the throughput gain was measured only on 1P2D decode nodes, which need MXFP4
KV under P/D and are not on main yet, and says to leave CP off on an
aggregated MXFP4 server.

Co-authored-by: Cursor <[email protected]>

* recipe(minimax_m3): median ITL fell in all three 128K cells

The MXFP4 paragraph said median ITL fell only at 128K and CONC 64, but
the A/B shows it falling in every 128K cell (0.8-4.7%, most at CONC 64)
and rising at 32K (5.1% at CONC 32, none at 128). The test module's
docstring called its kernel-free tests CPU tests; like every test in the
file they need aiter installed.

Co-authored-by: Cursor <[email protected]>

---------

Co-authored-by: Cursor <[email protected]>
shantipriya-amd pushed a commit to shantipriya-amd/aiter that referenced this pull request Nov 18, 2026
…m#7060)

* [FlyDSL] M3 index score: MXFP4 index-cache decode scorer

New kernel `score_flydsl_fp4` scores an MXFP4 index cache (e2m1 data plus one
e8m0 scale per 32 elements) given as two views, k_data [pages,128,64] and
k_scale [pages,128,4], each with its own page stride, so separate tensors and
a single-region 8704 B page both work.

Query dtype selects the K path:
- bf16 Q: K is widened to bf16 with v_cvt_scalef32_pk_bf16_fp4 and fed to the
  same bf16 16x16x32 MFMA as the fp8 scorer; the numerics contract (K lifted to
  Q's precision) is unchanged.
- e4m3 Q: one v_mfma_scale_f32_16x16x128_f8f6f4 per 16-token tile, A = the
  lane's 16 B of fp4 K plus its e8m0 byte, B = Q as e4m3 (unit scale). Products
  are exact in fp32, so scores are those of dequantize(K) against Q as stored.
  An optional q_scale (default 1.0, positive) is folded into the score
  multiplier.

K tiles in flight is 6 rather than the fp8 scorer's 3: an MXFP4 tile is half
the bytes, and 6 was 15-35% faster than 3 on small batch*context cells in a
2/3/4/6/8 sweep.

Work map, geometry and CP shard are imported from the fp8 scorer. The builder
is a copy of `build_index_score` with the K side replaced, not a
parameterisation of it, so the two can drift and an epilogue or work-map change
must be mirrored. e8m0 bytes 0 and 255 are outside the contract.

Only exports are added to aiter/ops/flydsl/__init__.py; the fp8 path is
untouched.

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

* Trim MXFP4 decode scorer dead indirection and docstring

Generated LLVM IR and ISA are byte-identical across 14 specialisations.

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

* Make MXFP4 index-score sweep assert like the fp8 sweep

The sweep used checkAllclose, which only logs, so CI (python3 file)
could not fail on a wrong kernel; use the fp8 test's check_scores.
Import the fp8 test as siblings do and build the case matrix once.

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

* Run MXFP4 index-score checks from main() and fix import/lint

python3 op_tests/<file> now runs the pytest matrix before the perf sweep
(as test_flydsl_hc_mix.py does), so CI can fail on a wrong kernel. Import
the fp8 test with a script-mode fallback, hoist torch, fix the docstring
about e8m0 scale clamping. ruff 0.16.0 (ruff check .) and black are clean.

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

* Fold the MXFP4 decode scorer into the fp8 index-score builder

One builder and one test file now cover both index caches: the MXFP4 cache
is an `mxfp4` specialisation of build_index_score, and score_flydsl_fp4 /
index_score_supported_fp4 are thin wrappers over the shared host path.
Generated LLVM IR and ISA are byte-identical to the separate kernels for 39
specialisations (13 fp8, 26 MXFP4); outputs are bit-equal on 54 cases.
python3 op_tests/<file> runs the pytest checks before the perf sweeps.

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

* Use public flyc.jit for the shared index-score body

Replaces the internal ASTRewriter.transform call, so a FlyDSL bump cannot
break the import. q_scale's docstring now says it scales a bf16 Q too (the
code always did) and a test checks it. LLVM IR and ISA are byte-identical
for 39 specialisations.

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

* Address review: validate q_scale on its own, fair fp8 baseline, sign-aware top-k check

q_scale was only checked through the folded multiplier, so sm_scale = q_scale = -1
passed; reject q_scale <= 0 in the entry point and the predicate. The perf sweep
now converts the fp8 cache once outside the timed callable. assert_topk_agrees
uses check_scores, which also compares the -inf mask (a +inf slot slipped through).

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

* Drop MXFP4 scorer routes nothing calls

q_scale and the CP kwargs have no caller in ATOM#2770 or vLLM#64198, so the
MXFP4 entry points lose them, and score_flydsl / index_score_supported take an
optional k_scale instead of a parallel private core. Remove the tests that only
re-checked other tests' logic (top-k, fp8 cross-check, bf16-vs-e4m3 gap,
quantizer rule) and the CP and q-dtype multiples of graph and view tests.
IR and ISA are byte-identical for all 31 remaining specialisations.

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

* Run the MXFP4 decode op tests from main() instead of pytest

The MXFP4 tests this PR added used pytest fixtures, parametrize, skip, raises
and a pytest.main call in __main__. They are now plain check functions driven
from main() by a case table (PASS/FAIL table, exit 1 on any failure), like the
sibling flydsl op_tests, and __main__ is main's again. The same 89 cases run.
They compare with check_scores instead of the local compare. The pytest code
that was already on main is untouched.

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

* MXFP4 decode: fx.rocdl consistently, named unit scale, sm_scale rejection check

Kernel: use fx.rocdl for the scaled MFMA like the rest of the file, name the
0x7F7F7F7F unit e8m0 scale UNIT_SCALE, say why the MFMA is raw. No change to
the generated code.
Test: add a check that sm_scale <= 0 and NaN are refused by score_flydsl_fp4.

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

* MXFP4 decode tests: CP shards, strided e4m3 Q, prealloc bench; fix e8m0 255 doc

- every-geometry check now runs the CP points (cp_world>1 with k_scale) against
  the oracle; MXFP4 + CP works, so it is covered rather than rejected.
- q_for keeps q's strides, so the qslice e4m3 case reaches load_q8's strided path.
- bench_score_mxfp4 allocates the score buffer once, outside the timed region.
- Docs: e8m0 byte 255 is +inf as f32 (bf16-Q path) and NaN in the scaled MFMA
  (e4m3-Q path); measured, the score is NaN on both.

Co-Authored-By: Claude Code <[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