Skip to content

[FlyDSL] [CI] mega_moe_tp: decode-shape (1-32 row) router GEMM split-K partials - #8551

Closed
ganyi1996ppo wants to merge 7 commits into
ROCm:mainfrom
ganyi1996ppo:ganyi/mega-moe-tp-router-gemm-small
Closed

ganyi1996ppo wants to merge 7 commits into
ROCm:mainfrom
ganyi1996ppo:ganyi/mega-moe-tp-router-gemm-small

Conversation

@ganyi1996ppo

@ganyi1996ppo ganyi1996ppo commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

Motivation

MiniMax-M3.1 decode MoE (E128 top-4, H6144, 1-128 rows) starts every layer with a router GEMM whose fp32 gate must be summed in a fixed split-K order so the top-4 ids match the reference bit for bit. aiter has no such kernel for the decode row range; the production path got it from the amd-kernels package. This PR is the first of three stacked PRs that move that router front end into aiter (next: #8548 primitives -> this -> 33-128 rows -> top-4 + input-quant chain), so the decode MoE can run on aiter alone.

Change

New under aiter/ops/flydsl/kernels/mega_moe_tp/ (633 added lines, does not depend on #8548):

  • decode_router_gemm_direct.py: bf16x3 split-K router GEMM (MFMA 16x16x32, no LDS) for 1-16 rows, split-48 partials.
  • decode_router_gemm_lines.py: the same for 17-32 rows from the line-layout gate copy (two waves).
  • decode_router_gemm.py: router_gemm_partials tier dispatch (FP32 partials [m, split_k, 128], token-major) and router_line_layout (one-time gate permutation at weight loading).
  • decode_router_common.py: the bf16x3 weight split helper.
  • op_tests/test_decode_router_gemm.py: partials sum to x @ W.T (fp64 reference), rows 1-32.

Ported from amd-kernels' moe/mxfp4_h6144_i768_e128_top4/{router_gemm_direct,router_gemm_nblocks_lines,router_gemm}.py (Apache-2.0, "Copyright contributors to the amd-kernels project"); kernel bodies unchanged, imports moved to aiter.ops.flydsl.kernels.buffer_ops / tensor_shim._run_compiled, the warm-up decorator and the private compile cache dropped. No amd_kernels import.

Verification (MI355X gfx950, ROCm 7.2 atom-dev container)

  • Partials bit-identical (torch.equal) to amd-kernels' router_gemm_partials for every row count 1..32 with three input kinds (randn, randn*30, identical rows): 96/96.
  • pytest op_tests/test_decode_router_gemm.py: 7 passed.
  • GPU time (CUDA-graph replay of 50 calls, min of 2): 2.00 / 2.07 / 2.11 / 2.33 / 2.35 / 2.40 us at 1 / 8 / 16 / 17 / 24 / 32 rows, equal to amd-kernels within +-0.01 us. Eager-mode host time is +0.2..0.4 us/call (the _run_compiled bookkeeping), irrelevant under graphs.

The bit-identity harness imports amd-kernels and is not part of this PR.

Merge order

Stack: #8548 -> #8551 -> #8552 -> #8553 -> #8555. Merge after #8548. The branch contains #8548's commits (merged, not rebased), so after #8548 lands its diff against main shrinks to this PR's own content; until then GitHub shows the parents' files too. This PR's own delta now: ganyi1996ppo/aiter@ganyi/mega-moe-tp-decode-primitives...ganyi/mega-moe-tp-router-gemm-small

🤖 Generated with Claude Code

ganyi1996ppo and others added 2 commits November 24, 2026 01:44
…MM tile primitives

Adds two new, self-contained helper modules to aiter's existing
mega_moe_tp family:

- decode_id_routing.py: in-kernel canonical expert-block routing for the
  small-M decode shape (<=128 rows, E128 top4) -- one workgroup resolves
  its 16-row expert block straight from topk_ids via an LDS-atomic
  histogram and a DPP wave scan, no sort launch and no global atomics.
- decode_tile_primitives.py: per-tile building blocks for the same shape's
  GEMM1/GEMM2 compute at H6144/I768 -- scaled-MFMA wrappers (MXFP4 A4W4 and
  MXFP8 A8W8), the SwiGLU activation, and MXFP4/MXFP8 row quantization.

Both are ports of the technique in amd-kernels'
moe/mxfp4_h6144_i768_e128_top4/{routing_ids.py,gemm1_a4w4_id_rows.py,
shared_gemm1_a8w8.py,shared_quant.py} (Apache-2.0, "Copyright contributors
to the amd-kernels project") -- same algorithm, reimplemented against
aiter's own aiter.ops.flydsl.kernels.buffer_ops instead of amd-kernels'
private copy of the same buffer-op wrappers. Neither file imports
amd_kernels; each file's docstring credits the specific amd-kernels source
module it is ported from.

mega_moe_tp already carries the epoch-flag / XCD-affinity / loader-wave
LDS-DMA primitives a fused decode GEMM1->GEMM2 kernel needs, but only at
128/256-row prefill tile shapes; this adds the small-M (8-128 row)
in-kernel routing and tile primitives it is missing for a decode-shape
fusion, generalized over the pair/row count (no model-specific constant
beyond the E128/top4/16-row-block shape a call site fixes).

This is a primitives-only PR: the tile loop, prefetch ring and LDS layout
that assemble these into a full fused kernel currently live in a
model-side integration (MiniMax-M3.1 decode MoE) that is not yet upstream
in ATOM, so no aiter op_test exercises the full assembled kernel here.
Correctness was verified through that integration instead: 72/72
adversarial-input bit-identical results against the original
amd_kernels-based kernel, and 12/12 matches against an independent
production reference, on real MI355X hardware (node 035, gpurun lease).
Perf (200 iters, same hardware): the assembled kernel using these
primitives measured -21.3/-12.1/-13.4 us vs production at n=16/24/32 rows,
within +0.2..+1.7 us (noise) of the pre-port amd_kernels version -- no
regression from the port itself.

Follow-up: land the model-side integration (currently
atom/models/minimax_m3/moe_one_launch_aiter.py in a private tree) as its
own ATOM-side PR once the file it extends is upstream, and add a native
aiter op_test once there is a complete in-aiter kernel to test against.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
…tials

bf16x3 split-K router GEMM (E128 x H6144, MFMA 16x16x32) for 1-32 rows: a no-LDS
direct kernel for 1-16 rows and a line-layout two-wave kernel for 17-32 rows, plus
the tier dispatch (router_gemm_partials) and the one-time gate permutation
(router_line_layout). Ported from amd-kernels' moe/mxfp4_h6144_i768_e128_top4
(router_gemm_direct / router_gemm_nblocks_lines / router_gemm dispatch, Apache-2.0),
bodies unchanged, imports moved to aiter's buffer_ops / tensor_shim.

Verified on gfx950: partials bit-identical to amd-kernels for rows 1..32 (3 input
kinds), graph-replayed GPU time equal to +-0.01 us.

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

Copy link
Copy Markdown
Contributor

🏷️ CI Guide

Runs automatically on every PR:

  • ✅ Pre-checks (submodule verification, code formatting)
  • ✅ Aiter standard tests on MI35X
  • ✅ Triton tests on MI35X (only when aiter/ops/triton/** or related paths are changed)

Extended tests (opt-in via labels):

Label Tests
ci:mi300x Run Aiter standard tests on MI300X in PRs; main branch always runs them
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 Radeon R9700 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 8551 --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.

Reviews:
A reviewer is usually assigned within one working day after the PR is ready for review (see Code Review Process). If nobody has responded for about a week, mention the area contact listed in CONTACTS.md. Want to help review? See REVIEWERS.md.

@aiter-bot

aiter-bot commented Nov 24, 2026 •

Copy link
Copy Markdown

WAITING ON AUTHOR

PR Self-Review

Revision f52dbe196268 · 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 permissions and untrusted-input boundary does this CI change have, and can fork PR code or text reach a privileged execution path?
  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 — missing ### Reviewed revision in the PR description
  • FAIL — missing ### Behavior and intent in the PR description
  • FAIL — missing ### Validation and unverified scope in the PR description
  • FAIL — missing ### PR-specific question in the PR description
  • FAIL — missing ### Changed op tests in the PR description
  • FAIL — Reviewed revision must contain at least the first 7 characters of the current head SHA
  • FAIL — Behavior and intent has no substantive answer
  • FAIL — Validation and unverified scope has no substantive answer
  • FAIL — PR-specific question has no substantive answer
  • FAIL — changed op test not explained in Changed op tests: op_tests/flydsl_tests/test_decode_id_routing.py
  • FAIL — changed op test not explained in Changed op tests: op_tests/test_decode_router_gemm.py
  • FAIL — Changed op tests must explain why each changed op test is necessary and non-redundant

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.

🟡 Changes recommended

Unresolved critical buffer-sizing, architecture-gating, and device/stream handling defects can send accepted inputs into unsafe GPU launches.

6 open issues
What changed in this PR

This PR adds FlyDSL router GEMM kernels for MiniMax-M3.1 decode MoE with 1–32 rows, moving another part of the router front end into aiter without an amd_kernels runtime dependency. It complements the primitives work in #8548 but does not depend on it.

Changes:

  • Adds bf16x3 split-K kernels for 1–16 and 17–32 rows, producing 48 FP32 partials per token and expert.
  • Adds row-count dispatch, a one-time router-weight permutation, and shared weight-splitting helpers.
  • Adds seven numerical test cases comparing summed partials against an FP64 matrix-multiplication reference.
File Description
op_tests/​test_decode_router_gemm.py Adds numerical checks across both dispatch tiers.
aiter/​ops/​flydsl/​kernels/​mega_moe_tp/​decode_router_gemm.py Adds dispatch and router-weight layout conversion.
aiter/​ops/​flydsl/​kernels/​mega_moe_tp/​decode_router_gemm_lines.py Adds the two-wave kernel for 17–32 rows.
aiter/​ops/​flydsl/​kernels/​mega_moe_tp/​decode_router_gemm_direct.py Adds the shared-memory-free kernel for 1–16 rows.
aiter/​ops/​flydsl/​kernels/​mega_moe_tp/​decode_router_common.py Adds bf16x3 weight decomposition and shared compile hints.

Review effort: Balanced

(split_k, m, E), dtype=torch.float32, device=hidden_states.device
)
result = partials.view(m, split_k, E) if token_major else partials.permute(1, 0, 2)
stream = torch.cuda.current_stream()
arg_w, num_records_bytes=E * H * 4
)
xr = buffer_ops.create_buffer_resource_from_addr(
arg_x, num_records_bytes=fx.Int64(i32_m) * fx.Int64(i32_sx * 2)
Comment thread op_tests/test_decode_router_gemm.py Outdated
Comment on lines +20 to +21
@pytest.mark.parametrize("n", [1, 4, 8, 16, 17, 24, 32])
def test_partials_sum_is_the_logits(n):
Comment thread op_tests/test_decode_router_gemm.py Resolved
ganyi1996ppo and others added 3 commits November 24, 2026 03:36
…use rocdl cvt wrappers; add routing test

Co-Authored-By: Claude <[email protected]>
…fails without the id-range guard)

Co-Authored-By: Claude <[email protected]>
…rch/strides, per-GPU launcher, CI runs the test

Review findings on ROCm#8551:
- router_gemm_partials launched on the current device with whatever pointers it
  was given: a CPU or foreign-GPU gate / hidden state became an invalid GPU
  address, gfx942 reached an MFMA form it lacks, and one cached compiled handle
  served every GPU. It now returns None unless every tensor is CUDA storage on
  one gfx950 device, launches under that device with its stream and keeps one
  launcher per GPU (kernels/topk/topk_launch._launcher_on).
- An expanded row (stride(0) == 0) gave the kernels an empty buffer descriptor
  and silently zero partials (max error 10.46 = |logits| on 8 rows, reproduced
  on gfx950). Rows must not overlap, and m * stride * 2 must fit the 32-bit
  descriptor extent; both return None.
- _get_kernel took a hard-coded (48, 64) beside split_config; it uses the tier.
- The test had no per-split oracle (permuted split slots passed), no stride or
  rejection case, and CI runs op_tests with `python3 file` (collects nothing):
  add per-chunk reference, padded-stride and rejection cases, a gfx950 skip, and
  list the file in aiter_test.sh's pytest dispatch.

Verified on gfx950: 14 passed.

Co-Authored-By: Claude <[email protected]>
Copilot AI balanced review requested due to automatic review settings November 24, 2026 13:46
@github-actions github-actions Bot changed the title [FlyDSL] mega_moe_tp: decode-shape (1-32 row) router GEMM split-K partials [FlyDSL] [CI] mega_moe_tp: decode-shape (1-32 row) router GEMM split-K partials Nov 24, 2026
@github-actions github-actions Bot added the CI label Nov 24, 2026

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

Scalar inputs raise IndexError instead of using the documented fallback, and the tests lack bit-exact FP32 regression coverage and the required performance benchmark harness.

6 open issues
2 previously missed issues

In code that hasn't changed since last review

Medium severity Check tensor rank before indexing shape

aiter/​ops/​flydsl/​kernels/​mega_moe_tp/​decode_router_gemm.py:57

A zero-dimensional tensor raises IndexError at shape[0] before the rank check can return None. This breaks the documented unsupported-shape fallback, including for a CPU scalar. Check hidden_states.dim() before indexing its shape so unsupported ranks are declined consistently.

Low severity Replace legacy buffer_ops with buffer tensors and fx.copy

aiter/​ops/​flydsl/​kernels/​mega_moe_tp/​decode_router_gemm_direct.py:113

This new load/store path uses legacy buffer_ops, although aiter/ops/flydsl/AGENTS.md:32–36 requires buffer tensors and fx.copy for new code. Use those APIs, or document the specific missing API or scheduling requirement with supporting instruction or timing evidence for retaining this boundary. Same issue in decode_router_gemm_lines.py:155–163.

1 resolved since last review

Review effort: Balanced

xd, wd = x.double(), w.double()
for s in range(split_k):
ref = xd[:, s * kc : (s + 1) * kc] @ wd[:, s * kc : (s + 1) * kc].T
torch.testing.assert_close(p[:, s].double(), ref, rtol=1e-4, atol=1e-5)
@ganyi1996ppo

Copy link
Copy Markdown
Contributor Author

ROCm/aiter PR #8551 — [FlyDSL] mega_moe_tp: decode-shape (1-32 row) router GEMM split-K partials

Adds a bf16x3 split-K router GEMM (E128, H6144, 1-32 rows) that returns fixed-order fp32 partials so the following top-4 matches the reference bit for bit.

Review (advisory): ⚠️ NEEDS WORK — the findings below were fixed in e04969e (pushed to the PR branch); not independently refuted
Validation (deterministic): NOT RUN — the auto-run had no GPU on the review host (INCONCLUSIVE, and the report was rejected for a missing jsonschema); by hand on MI355X gfx950 (node 035 GPU 0) the post-fix tree passes op_tests/test_decode_router_gemm.py 14/14 and the original tree reproduces finding 1
Perf (advisory): NOT RUN — the target has no benchmark entry point and adds new kernels (no base to time against); the PR's 2.0-2.4 us / "equal to amd-kernels within 0.01 us" figures come from a harness that imports amd-kernels and is not in the tree, so they are [unverified]
Size: 633 lines / 5 files
Design (advisory): NONE — one more kernel family in aiter/ops/flydsl/kernels/mega_moe_tp/ ported from amd-kernels with the existing _run_compiled launch idiom; the only decision is the fixed 48-way split-K order, which is amd-kernels' contract
Human: N/A — design is NONE: the change sits inside the existing mega_moe_tp FlyDSL kernel pattern, and its one decision (the fixed split-K order) is amd-kernels' contract, not a new aiter choice

🔴 [verified] decode_router_gemm.py router_gemm_partials accepts a row-expanded hidden state: x.expand(8, 6144) has stride(0) == 0, so decode_router_gemm_direct.py:92 sizes the x buffer descriptor at m * i32_sx * 2 = 0 bytes and every load returns zero. Reproduced on gfx950: partials sum minus [email protected] has max error 10.46, equal to max|logits| (and 9.95 at 24 rows through the lines kernel; the contiguous copy is exact to 7e-7). Impact: silently all-zero router logits, so top-4 picks the bias-only experts. Author must reject non-overlapping-violating strides (return None) or size the descriptor from the addressed span. Fixed: rows must have stride(0) >= 6144 and m * stride * 2 must fit the 32-bit descriptor extent, otherwise None; test_unsupported_inputs_return_none covers it.
⚠️ [verified] router_gemm_partials launches without checking device or arch: a CPU gate copy or a tensor on another GPU is handed to the kernel as a raw address, the stream comes from torch.cuda.current_stream() of the current device, and a gfx942 or gfx1250 device reaches mfma_f32_16x16x32_bf16 (gfx950 only). Impact: invalid GPU address / wrong-stream ordering / illegal instruction instead of the None fallback the function already uses for other unsupported inputs. Author must return None unless every tensor is CUDA storage on one gfx950 device and launch under that device with its stream. Fixed with on_supported_device / run_on_device in decode_router_common.py.
⚠️ [inferred] decode_router_gemm_direct.py _get_kernel and decode_router_gemm_lines.py _get_kernel are functools.cached on kernel constants and _run_compiled is called without a specialization key, so the same kernel called on cuda:0 then cuda:1 reuses one compiled handle (aiter/ops/flydsl/AGENTS.md: such a handle does not launch on the other device and the error is printed, not raised). Impact: unwritten partials in a single-process multi-GPU run (tests, tuners). Author must keep one launcher per GPU. Fixed by routing through kernels/topk/topk_launch._launcher_on; a second GPU was not available for the check, the single-GPU path is verified.
⚠️ [verified] op_tests/test_decode_router_gemm.py is run by CI as python3 file (.github/scripts/aiter_test.sh), which collects no pytest case, and its only check (fp64 sum of the partials) passes when the 48 split slots are permuted although the fixed order is the contract. Impact: the claimed bit-order contract is untested and the file never runs. Author must add the file to the script's pytest dispatch and a per-split oracle. Fixed: aiter_test.sh pytest list, test_each_split_is_its_k_chunk, a padded-stride case, the rejection cases and a gfx950 skip.
📝 [verified] aiter/ops/flydsl/kernels/mega_moe_tp/decode_router_gemm.py router_gemm_partials validates router_weight but never reads it (the kernels read router_weight_lines), so a gate that differs from its line-layout copy is silently ignored. Reviewer should ask whether the pair should collapse to one argument; documented in the docstring for now.

Triage of the existing Copilot comments: CPU/cross-device gate, missing arch gate, current-device stream and shared per-device handle: real, fixed in e04969e. Expanded input (stride 0): real (reproduced), fixed by returning None for overlapping rows instead of sizing the descriptor from the span, since a broadcast row is not a supported layout for this kernel. Test not run by CI: real, fixed by the pytest dispatch in aiter_test.sh rather than a main() sweep (a script entry would duplicate the pytest cases). Exact-partials regression: addressed with a per-split fp64 oracle (a permutation of the split slots now fails) instead of committed golden outputs.

🤖 Generated with Claude Code

ganyi1996ppo added a commit to ganyi1996ppo/aiter that referenced this pull request Nov 24, 2026
Keeps this branch's own content; the parent's older copies of shared files are superseded by this branch's versions.

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

# Conflicts:
#	aiter/ops/flydsl/kernels/mega_moe_tp/decode_router_common.py
#	aiter/ops/flydsl/kernels/mega_moe_tp/decode_router_gemm.py
#	op_tests/test_decode_router_gemm.py
Copilot AI balanced review requested due to automatic review settings November 24, 2026 14:16

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 router reads hidden_states.shape[0] before validating rank, causing zero-dimensional inputs to raise IndexError instead of returning None for the documented fallback.

4 open issues
1 previously missed issue

In code that hasn't changed since last review

Medium severity Check tensor rank before accessing its row count

aiter/​ops/​flydsl/​kernels/​mega_moe_tp/​decode_router_gemm.py:57

The rank check happens after hidden_states.shape[0], so a zero-dimensional tensor raises IndexError instead of returning None for an unsupported shape. This prevents callers from taking the documented fallback. Please reject non-2D inputs before reading the row count.

2 resolved since last review

Review effort: Balanced

@zufayu
zufayu requested a review from GwilliamHu November 25, 2026 01:09
@ganyi1996ppo

Copy link
Copy Markdown
Contributor Author

Merged into #8548 (same router GEMM files, now one branch). Closing in favour of #8548.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants