Skip to content

[ASM] [HIP] [FlyDSL] feat: pad-row routing count, custom all_gatherv, MoE quant-sort race fix - #6916

Merged
valarLip merged 1 commit into
mainfrom
feat/routing-num-valid-rows-allgatherv
Oct 26, 2026
Merged

valarLip merged 1 commit into
mainfrom
feat/routing-num-valid-rows-allgatherv

Conversation

@valarLip

Copy link
Copy Markdown
Collaborator

Motivation

Under DP-gathered MoE, the CUDA-graph and DP padding rows went through routing as if they were real tokens. Callers then had to mask them after the fact. This PR lets routing drop those rows itself, adds a one-launch custom all-gatherv for the routed rows, and fixes a stage-1 race in the fused MX quant + sort kernel.

Changes

Pad-row routing count (num_valid_rows)

  • The following ops take an optional num_valid_rows: an int32 device tensor whose first element is the number of real rows.
    • topk_gating
    • topk_softmax and topk_softmax_fused_shared_gate
    • grouped_topk and biased_grouped_topk
    • moe_fused_gate
  • Rows at or past that count get routed id -1 and weight 0. MoE sorting and expert-parallel dispatch both skip id -1. Shared columns are written as for any other row.
  • The count is read on device, so a replayed graph follows each step's count without being recaptured.
  • Kernels that handle one row per block (grouped, opt-sort, register and wave32 variants) exit early on a pad row and skip scoring. Multi-row kernels mask at the write.
  • The helpers live in csrc/include/topk_pad_rows.h.
  • The biased_grouped_topk and fused_topk dispatchers pass the count through. When a count is given they skip the HERD, gfx1250 and asm paths, which do not accept one.

moe_fused_gate fixes

  • Rows are now read at input.stride(0) instead of num_experts. A strided gating tensor previously routed garbage: the last test_moeTopkSoftmax case, fp32 rows sliced out of a 260-column buffer, failed against the reference.
  • With n_share_experts_fusion > 0, the rescale loop overwrote the shared-expert weight with an uninitialized score. The weight is now 1 / routed_scaling_factor, which is what sglang's own test expects.

Custom all_gatherv

  • New op that gathers up to four tensors along the first dimension, with a different row count per rank, in one kernel launch with one rank barrier.
  • While capturing a graph it reads the registered inputs in place. Otherwise it copies them into the registered pool first.
  • CustomAllreduce.custom_all_gatherv uses it only while a rank gathers at most 2 MB × world_size bytes. Above that it returns None and the caller falls back to NCCL. The threshold comes from measured crossovers against NCCL in graph replay on MI355X: about 4.5 / 9 / 21 MB per rank at 2 / 4 / 8 ranks.
  • CudaCommunicator.all_gatherv tries this path before pynccl.
  • jit: develop=True ops now also convert tensors passed inside list arguments.

Fused MX quant + MoE sort race

  • fused_dynamic_mx_quant_moe_sort_hip now takes total_routes (token_num * topk) explicitly.
  • A zero-weight route's row is zeroed only when that route owns its row, which is the case at stage 2 and for top-1 routing.
  • At stage 1 all routes of a token share the token's single row. Zeroing that row for one zero-weight route raced the token's other routes, so the token was dropped at random.

Other

  • Mega MoE tuning entry for DeepSeek-V4.1-Flash at EP2.

Tests

  • op_tests/multigpu_tests/test_custom_allgatherv.py: uniform counts, ragged counts, an empty rank, and an 8-layer captured graph, plus timing.
  • op_tests/test_moe_sorting_mxfp4.py: zero-weight cases for fp8 and fp4, stage 1 and stage 2, bounded and unbounded launchers, each run over 20 launches.
  • op_tests/test_moe_topk_gating.py: a new pad-rows section.
  • All of the routing ops above were also checked on MI355X against their unmasked output. Real rows match bit for bit; pad rows hold -1 / 0 on the routed columns; every other column is unchanged.
  • No regressions in test_moeTopkSoftmax, test_topk_softmax (pytest), test_topk_softmax_shared_gate or test_moe_topk_gating.

Routing (num_valid_rows):
- topk_gating, topk_softmax, topk_softmax_fused_shared_gate, grouped_topk,
  biased_grouped_topk and moe_fused_gate take an optional int32 device
  tensor `num_valid_rows`. Rows at or past it get routed ids -1 (dropped
  by MoE sorting and expert-parallel dispatch) and weights 0; shared
  columns are written as for any row. It is read on device, so a replayed
  graph follows each step's count.
- One-row-per-block kernels (grouped / opt-sort / register / wave32) exit
  early on a pad row; multi-row kernels mask at the write.
- Shared helpers in csrc/include/topk_pad_rows.h.
- Dispatchers (biased_grouped_topk, fused_topk) pass the count through and
  skip the HERD / gfx1250 / asm paths, which take none.

moe_fused_gate fixes:
- Rows are read at input.stride(0) instead of num_experts, so a strided
  gating tensor routes like its contiguous copy.
- A fused shared expert weighs 1 / routed_scaling_factor (as in sglang);
  the rescale no longer overwrites it with an uninitialized score.

Custom all-gatherv:
- all_gatherv: first-dim all-gather of up to 4 tensors with per-rank row
  counts in one launch and one rank barrier, on the registered path in
  capture or through the registered pool otherwise.
- CustomAllreduce.custom_all_gatherv picks it while a rank gathers at most
  2 MB x world size bytes (MI355X crossover vs NCCL measured near 4.5 / 9 /
  21 MB a rank at 2 / 4 / 8 ranks), else returns None.
- CudaCommunicator.all_gatherv tries it before pynccl.
- jit: develop=True ops convert tensors inside list arguments.

Fused MX quant + MoE sort:
- Pass total_routes explicitly. A zero-weight route zeroes its row only
  when the route owns one (stage 2, top-1). At stage 1 a token's single
  row is shared by its routes, and zeroing it for one route raced the
  others and dropped the token at random.

Also: mega MoE tuning for DeepSeek-V4.1-Flash at EP2.

Tests: op_tests/multigpu_tests/test_custom_allgatherv.py, zero-weight
cases in test_moe_sorting_mxfp4.py, a pad-rows section in
test_moe_topk_gating.py.
@valarLip
valarLip requested a review from a team October 25, 2026 18:39
@github-actions github-actions Bot changed the title feat: pad-row routing count, custom all_gatherv, MoE quant-sort race fix [ASM] [HIP] [FlyDSL] feat: pad-row routing count, custom all_gatherv, MoE quant-sort race fix Oct 25, 2026
@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 6916 --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.

@valarLip
valarLip merged commit 5087367 into main Oct 26, 2026
59 checks passed
@valarLip
valarLip deleted the feat/routing-num-valid-rows-allgatherv branch October 26, 2026 01:08
ZLkanyo009 added a commit to ROCm/ATOM that referenced this pull request Oct 26, 2026
Add the optional num_valid_rows count of ROCm/aiter#6916 to
triton_topk_softmax and rocm_aiter_topk_softmax_impl: an int32 device
tensor whose first element is the count of real rows. Rows at or past it
get routed ids -1 and weights 0; shared columns are written as for any
row. The count is read on device, so a replayed graph follows each step's
count. Without it the kernel is compiled as before (constexpr switch).

The AITER topk_softmax path gets the count only when it is set, so an
AITER without #6916 keeps working for callers that do not pass it.

Co-authored-by: Cursor <[email protected]>
luocheng25 added a commit to luocheng25/aiter that referenced this pull request Oct 27, 2026
…tput

Since ROCm#6916, routing gives rows past num_valid_rows expert -1 and weight 0
and expects sorting to drop them.
- Batch-1 and direct-decoding kernels read topk_ids without sorting; they now
  skip -1 routes instead of reading weights and scales in front of expert 0.
- Per-tensor prefill zeroes the Gate/Up output: its Down absmax reads every
  route row, including routes sorting dropped (merged repeated IDs, -1 ids).

Tests: pad_rows routing (-1 ids, zero weights). Weights and scales sit behind
a NaN expert and the Gate/Up output starts as inf, so reading expert -1 or a
skipped row fails the check. New edge cases: per-tensor prefill and B2 direct
decoding with pad rows.
yhl-amd added a commit that referenced this pull request Oct 28, 2026
…under num_local_tokens (#7085)

* fix(quant): never write a sorting sentinel's row in the MX quant + MoE sort

Sorted with a real-row count (num_local_tokens), a block's padding slots hold
the sentinel `topk << 24 | count`: a real token id with an out-of-range slot.
fused_mx_quant_moe_sort_kernel only checks the token, so the sentinel passes;
its weight is 0, so it takes the zero-weight branch, and #6916 dropped the
`topk_id < topk` guard from store_zero_mx_quant_moe_sort_row. With count the
last real row, `count * topk + topk` is the row past `out`: a stage-2 call
zeroes one row of whatever follows `out` in device memory.

Since ROCm/ATOM#2725 passes num_local_tokens on every MXFP4 fused_moe call,
this fires on DeepSeek-V4.1-Flash TP2 (a8w4, topk 6): AgentX c16+ dies with
an intermittent illegal memory access, which surfaces in later kernels.

- A route is valid when topk == 1 or topk_id < topk. An invalid one zeroes
  its scale slot (indexed by its sorted row, always in range) and neither
  reads its input row nor writes an out row.
- op_tests/test_moe_sorting_mxfp4.py: padding sentinels under a count must
  leave rows past `out` untouched and the real routes byte-identical to an
  uncounted sort (fp8 / fp4x2, bounded and unbounded launchers).

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

* fix(moe_sorting): never load topk_ids past the tensor under num_local_tokens

With a device-side token count (LocalToken), the multi-phase sort kernels
run their vector loops to the count rounded up to the vector width. When the
count is the tensor's height and not a multiple of that width, the last
vector loads past the end of the [tokens, topk] ids. The ids are dropped by
the token check, so results are right, but the load faults when the tensor
ends right before an unmapped page -- intermittently, by allocator layout.

ROCm/ATOM#2725 passes num_local_tokens on every fused_moe call, so plain
prefill (count == tokens) hits it: DeepSeek-V4.1-Flash TP2 AgentX c64 died
about once per 17k requests after the quant-sort fix.

- The P0 v1 / v2 and P01 kernels read a vector that would pass the end id by
  id, ids past the end -1 (no expert); every other vector loads as before.
- Counted and uncounted sorts of the same real rows give the same routes for
  M in 1..16384 (checked as (expert, token, slot) multisets).

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

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
coderfeli pushed a commit that referenced this pull request Oct 29, 2026
* refactor: extract the legacy monolithic kernel into seperate files

* optimize down kernel and add qwen3.5 125b tuned csv

* apply review comments

* apply review comment

* opt batch2-8

* apply review comment

* apply review comments.

* apply review comments

* retune decoding csv: 1-8 tokens +24.3%

* avoid repeated expert IDs of a token

* use Opus aux sort for the sorted_sum route lookup to avoid call cost to `invert_sorted_ids`

* skip -1 pad-row routes in direct decoding; zero per-tensor Gate/Up output

Since #6916, routing gives rows past num_valid_rows expert -1 and weight 0
and expects sorting to drop them.
- Batch-1 and direct-decoding kernels read topk_ids without sorting; they now
  skip -1 routes instead of reading weights and scales in front of expert 0.
- Per-tensor prefill zeroes the Gate/Up output: its Down absmax reads every
  route row, including routes sorting dropped (merged repeated IDs, -1 ids).

Tests: pad_rows routing (-1 ids, zero weights). Weights and scales sit behind
a NaN expert and the Gate/Up output starts as inf, so reading expert -1 or a
skipped row fails the check. New edge cases: per-tensor prefill and B2 direct
decoding with pad rows.

* retune decoding csv on FlyDSL 0.4.0

Decoding rows (<= 256 tokens) start from main's selections. --e2e_tune ran with
TUNE_ONLY=flydslv2,cktile,flydsl,asm, AITER_FMOE_TUNE_EXCLUDE_KERNELS=fmoe_stage1
and AITER_FLYDSL_MOE_BF16_RTA_SIMPLIFIED=1 on MI308X with PTL enabled
(VECTOR,F8); each shape then keeps the lowest median of main's selection and
every eligible FlyDSL config over three interleaved rounds. Three picks that
are slower than main with the default rounding keep main's selection. 65 rows
change kernel versus main; rows above 256 tokens are main's.

* apply review comment

* skip the prefill output clear; batch 1 requires the 16_16_16 tile; 7 decoding rows keep main's selection
solinzby1 pushed a commit that referenced this pull request Nov 2, 2026
…under num_local_tokens (#7085)

* fix(quant): never write a sorting sentinel's row in the MX quant + MoE sort

Sorted with a real-row count (num_local_tokens), a block's padding slots hold
the sentinel `topk << 24 | count`: a real token id with an out-of-range slot.
fused_mx_quant_moe_sort_kernel only checks the token, so the sentinel passes;
its weight is 0, so it takes the zero-weight branch, and #6916 dropped the
`topk_id < topk` guard from store_zero_mx_quant_moe_sort_row. With count the
last real row, `count * topk + topk` is the row past `out`: a stage-2 call
zeroes one row of whatever follows `out` in device memory.

Since ROCm/ATOM#2725 passes num_local_tokens on every MXFP4 fused_moe call,
this fires on DeepSeek-V4.1-Flash TP2 (a8w4, topk 6): AgentX c16+ dies with
an intermittent illegal memory access, which surfaces in later kernels.

- A route is valid when topk == 1 or topk_id < topk. An invalid one zeroes
  its scale slot (indexed by its sorted row, always in range) and neither
  reads its input row nor writes an out row.
- op_tests/test_moe_sorting_mxfp4.py: padding sentinels under a count must
  leave rows past `out` untouched and the real routes byte-identical to an
  uncounted sort (fp8 / fp4x2, bounded and unbounded launchers).

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

* fix(moe_sorting): never load topk_ids past the tensor under num_local_tokens

With a device-side token count (LocalToken), the multi-phase sort kernels
run their vector loops to the count rounded up to the vector width. When the
count is the tensor's height and not a multiple of that width, the last
vector loads past the end of the [tokens, topk] ids. The ids are dropped by
the token check, so results are right, but the load faults when the tensor
ends right before an unmapped page -- intermittently, by allocator layout.

ROCm/ATOM#2725 passes num_local_tokens on every fused_moe call, so plain
prefill (count == tokens) hits it: DeepSeek-V4.1-Flash TP2 AgentX c64 died
about once per 17k requests after the quant-sort fix.

- The P0 v1 / v2 and P01 kernels read a vector that would pass the end id by
  id, ids past the end -1 (no expert); every other vector loads as before.
- Counted and uncounted sorts of the same real rows give the same routes for
  M in 1..16384 (checked as (expert, token, slot) multisets).

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

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
solinzby1 pushed a commit that referenced this pull request Nov 2, 2026
* refactor: extract the legacy monolithic kernel into seperate files

* optimize down kernel and add qwen3.5 125b tuned csv

* apply review comments

* apply review comment

* opt batch2-8

* apply review comment

* apply review comments.

* apply review comments

* retune decoding csv: 1-8 tokens +24.3%

* avoid repeated expert IDs of a token

* use Opus aux sort for the sorted_sum route lookup to avoid call cost to `invert_sorted_ids`

* skip -1 pad-row routes in direct decoding; zero per-tensor Gate/Up output

Since #6916, routing gives rows past num_valid_rows expert -1 and weight 0
and expects sorting to drop them.
- Batch-1 and direct-decoding kernels read topk_ids without sorting; they now
  skip -1 routes instead of reading weights and scales in front of expert 0.
- Per-tensor prefill zeroes the Gate/Up output: its Down absmax reads every
  route row, including routes sorting dropped (merged repeated IDs, -1 ids).

Tests: pad_rows routing (-1 ids, zero weights). Weights and scales sit behind
a NaN expert and the Gate/Up output starts as inf, so reading expert -1 or a
skipped row fails the check. New edge cases: per-tensor prefill and B2 direct
decoding with pad rows.

* retune decoding csv on FlyDSL 0.4.0

Decoding rows (<= 256 tokens) start from main's selections. --e2e_tune ran with
TUNE_ONLY=flydslv2,cktile,flydsl,asm, AITER_FMOE_TUNE_EXCLUDE_KERNELS=fmoe_stage1
and AITER_FLYDSL_MOE_BF16_RTA_SIMPLIFIED=1 on MI308X with PTL enabled
(VECTOR,F8); each shape then keeps the lowest median of main's selection and
every eligible FlyDSL config over three interleaved rounds. Three picks that
are slower than main with the default rounding keep main's selection. 65 rows
change kernel versus main; rows above 256 tokens are main's.

* apply review comment

* skip the prefill output clear; batch 1 requires the 16_16_16 tile; 7 decoding rows keep main's selection
valarLip pushed a commit to ROCm/ATOM that referenced this pull request Nov 3, 2026
* perf(moe): Triton softmax top-k routing for captured graphs

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

* test(moe): Triton softmax top-k matches AITER bit for bit

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

* perf(moe): route num_valid_rows pad rows in the Triton top-k softmax

Add the optional num_valid_rows count of ROCm/aiter#6916 to
triton_topk_softmax and rocm_aiter_topk_softmax_impl: an int32 device
tensor whose first element is the count of real rows. Rows at or past it
get routed ids -1 and weights 0; shared columns are written as for any
row. The count is read on device, so a replayed graph follows each step's
count. Without it the kernel is compiled as before (constexpr switch).

The AITER topk_softmax path gets the count only when it is set, so an
AITER without #6916 keeps working for callers that do not pass it.

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

* test(moe): Triton top-k follows select_experts' pass row count

Route through FusedMoE.select_experts, which reads the pass's real row count
from the forward context since #2725: the captured Triton route matches the
eager AITER one bit for bit on every replay as the count changes, and with a
fused shared expert writes the topk_meta_rows slice at the TBO offset.

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

* fix(moe): cap the Triton top-k at AITER's 512-expert fused kernel

AITER's fused topkGatingSoftmax dispatch stops at 512 experts; 1024 takes
moeSoftmax + moeTopK, which softmaxes the whole row before the top-k and
rounds the weights differently. Accepting 1024 made eager (AITER) and
captured (Triton) routing differ in the last bits.

The GPU test now covers every expert count / k / shared-expert count
triton_topk_softmax_supported() accepts, bit for bit against AITER, and
checks that 1024 experts route through AITER in eager and in a graph.

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

* fix(moe): Triton top-k clears picked experts to -inf like AITER

AITER clears each picked slot to -inf and picks with `>`, so once a row's
finite logits run out it picks expert 0 again (weight 0). The Triton
kernel cleared with a key below every value, so on rows with fewer than k
finite logits it moved on to the next index instead. Clear to -inf's key
(index kept, so ties still go to the lowest id). The row max is now the
first pick's value, as AITER's is.

NaN used to sort first. It now sorts below -inf and is never picked,
which AITER agrees with unless the NaN is the first element of one of
its per-thread vector loads; there AITER may pick it (every weight NaN)
or misorder the row, so NaN rows carry no bit-identity guarantee
(stated in the docstring).

Tests: rows with 1..k+1 finite logits (and none), and rows with NaNs off
AITER's vector-load first slots, bit for bit against AITER.

* fix(moe): Triton top-k requires unit last strides on its outputs

The kernel stores at w_ptr + row * stride_w + kk (and likewise for the
ids), but only the logits' last stride was checked. AITER honours any
stride, so a transposed output view would silently be written to the
wrong addresses. triton_topk_softmax_supported() now takes the outputs
too (same argument order as the launcher) and refuses a non-unit last
stride on either, so such calls stay on AITER; the launcher asserts it.

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

* refactor(moe): one shared tail for both top-k softmax kernels

The Triton branch returned early with its own copy of the function's
tail. Pick the kernel with if/else and share the tail, so a later change
to the returned layout cannot land in only one copy.

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

* test(moe): check the top-k softmax kernel choice on the GPU-less CI

The choice between the Triton kernel and AITER's topk_softmax was only
tested by the GPU test, which skips on a GPU-less runner, and lived in
modules that import Triton and AITER. Move it (triton_topk_softmax_supported
plus the switch / scoring-function checks, as use_triton_topk_softmax) to
topk_softmax_dispatch.py, which imports neither, and test it there: every
shape AITER's fused kernel takes is accepted, 1024 experts and other
shapes are not, nor non-unit output strides.

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

* perf(moe): run the Triton top-k softmax in eager passes too

Choosing the kernel on is_current_stream_capturing() routed a token
through AITER when its batch ran eagerly (prefill) and through Triton
when it was replayed from a graph (decode), so batch independence rested
on the two staying bit-identical -- expf, the renormalization's summation
order, tie rules, which expert counts take which AITER dispatch branch --
guarded only by a GPU test the GPU-less CI skips.

Use the Triton kernel for every pass whose shape it supports; other
shapes stay on AITER in both. ATOM_TRITON_TOPK_SOFTMAX=0 now puts every
pass on AITER. The eager warmup forward thus also compiles the kernel the
graphs capture.

The impl / select_experts tests run with the switch on and off and check
that eager and captured calls launch the same kernel.

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

* docs: ATOM_TRITON_TOPK_SOFTMAX and the Triton top-k routing kernel

Document the switch (default, what it changes, what 0 does) in
environment_variables.md; in model_ops_guide.md say which kernel
rocm_aiter_topk_softmax runs and list triton_topk_softmax.py and
topk_softmax_dispatch.py.

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

* perf(moe): send long top-k softmax launches to AITER

The Triton routing kernel runs one single-wave program per row and falls
behind AITER's topk_softmax past about 20 rows per CU: on MI355X (256 CUs)
the crossover is 20-28 rows per CU across the softmax top-k shapes ATOM's
models use (5120-7168 rows), with AITER up to 2x faster at 16K rows.

use_triton_topk_softmax now also requires
gating_output.shape[0] <= 20 * get_cu_num() (triton_topk_softmax_max_rows).
The choice still depends only on the launch, never on the capture state, so
a pass of a given size runs the same kernel eager or replayed; every default
CUDA graph (2048 decode rows with MTP 3, 3072-token prefill graphs) stays
below the cutoff and on Triton. The CU count comes from AITER's get_cu_num,
imported lazily so the dispatch module stays importable on the GPU-less CI.

Tests: the CPU test pins the cutoff (5120 rows at 256 CUs, 6080 at 304) for
each model shape on both sides, with the switch and for eager vs captured
passes; the GPU test runs the impl at the cutoff (Triton) and one row past
it (AITER), eager and replayed, with and without num_valid_rows, bit for bit
against both kernels.

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

* perf(moe): decide the top-k softmax kernel once per layer

Each routing call used to read ATOM_TRITON_TOPK_SOFTMAX (an os.getenv per
call) and rerun the shape, stride and expert-count checks, although all of
them but the row count are fixed once the layer is built.

FusedMoE now decides at construction: triton_topk_softmax_rows() takes the
layer's expert count, top-k, renormalize, fused shared experts and their
scoring func, reads the switch, and returns the row cutoff (20 rows per CU)
or None. The layer passes it down select_experts -> rocm_aiter_topk_softmax
as triton_max_rows, and the impl only compares the launch's row count.
Changing the switch after the layer is built no longer moves it.

The output buffers are the impl's own (unit last stride), and router logits
are a gate's output or a column slice of it, so no per-launch layout check
is kept; the Triton launcher still asserts a unit last stride. Under MoRI
all2all fusion the MXFP4 routing drops a scored shared column whose logit
stays in the router logits, so it passes None (AITER, as before).

_cu_num() loses its functools.cache: aiter's get_cu_num is already cached,
and the cutoff is now computed once per layer.

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

* perf(moe): take the Triton top-k softmax cutoff from a per-arch table

The 20 rows per CU crossover was measured on MI355X (gfx950) only, yet
gfx942 and gfx1250 inherited it. TRITON_TOPK_SOFTMAX_MAX_ROWS_PER_CU is
now a table keyed by AITER's get_gfx(), with the one measured entry,
gfx950: 20. On an architecture without an entry,
triton_topk_softmax_max_rows() is None, so no layer gets a cutoff and every
launch stays on AITER, as before the Triton kernel existed. The
architecture is read once per layer, with the switch and the CU count.

Tests (CPU): the gfx950 cutoff still follows the CU count; gfx942 (304
and 80 CUs) and gfx1250 give every model shape no cutoff; a decision reads
the switch, the architecture and the CU count once each; an unnormalized
layer gets no cutoff for any model shape. The GPU tests that need a cutoff
skip where there is none, and the hot-path test also counts _gfx calls.

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

* fix(moe): fail loud on Triton top-k softmax launches the layer did not decide

The Triton branch of rocm_aiter_topk_softmax_impl ignored renormalize and
num_routing_experts: triton_topk_softmax always renormalizes and takes the
routed width from the logits. A layer only gets a cutoff when it
renormalizes, so the branch now asserts renormalize, and that
num_routing_experts is the logits' width less the scored shared columns,
so a caller that pairs a layer's cutoff with another routing fails instead
of being routed differently. Two checks on the Triton branch only.

For that check to hold, FusedMoEMethodBase.select_experts and the Qwen3.8
single-token decode path now pass the layer's routed expert count
(expert_layout.num_routed, as Mxfp4MoEMethod already did) rather than
global_num_experts, the dispatch space, which grows with EPLB's redundant
experts. num_routing_experts reaches nothing else on these paths:
FusedMoE.select_experts only hands it to fused_topk, whose AITER branch
does not take it.

Test (GPU): an unnormalized launch without a cutoff matches
aiter.topk_softmax(need_renorm=False) bit for bit; with a cutoff, an
unnormalized launch and launches whose num_routing_experts is 0, the
logits' full width or half the experts all raise, and a matching one runs
Triton.

Also correct the triton_topk_softmax docstring: a row with no finite logit
gets NaN for every routed weight (as in AITER and as the test asserts), not
expert 0 with weight 0.

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

* test(moe): pin the routed expert count select_experts passes down

Both FusedMoEMethodBase.select_experts and Mxfp4MoEMethod.select_experts
must pass expert_layout.num_routed, the width the Triton launch checks the
logits against, not global_num_experts (the dispatch space, 10 in the test
layout).

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

* test(moe): use a routed width that is wrong with and without a shared expert

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

* perf(moe): count only a CU-masked stream's CUs in the Triton top-k softmax cutoff

On RapidServe's --disagg-constrained streams a launch gets half of
MI355X's CUs. There the Triton kernel is slower than AITER's from 26 rows
per CU, by up to 36% at the 40 rows per CU the full-GPU cutoff allows.
A layer that may run on such a stream now counts the fewest CUs one gets
(RapidServeModelRunner._CU_POOL_FRACTIONS), so its cutoff is 2560 rows.

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

* docs(moe): note the CU-masked Triton top-k softmax cutoff

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

* docs(moe): state the CU-masked crossover per measured row count

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

* fix(moe): decide the Triton top-k softmax cutoff on the GPU running

get_gfx() reports GPU_ARCHS' build target, so an MI300 running a
gfx942;gfx950 build took MI355X's cutoff; get_gfx_runtime() reads the
GPU itself. The kernel's docstring now states which expert a row out of
finite logits repeats, and that a NaN is picked only from a row of NaNs,
with GPU tests for rows without finite logits and rows of NaNs.

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

* fix(moe): iq2r routes with the routed width; link the fraction-move issue

Iq2rMoEMethod.apply passed global_num_experts (the dispatch space) as
num_routing_experts, unlike the other select_experts callers. Pass
layer.expert_layout.num_routed and pin it in the iq2r apply test, whose
fake layer now has a routed width that differs from global_num_experts.

Also link #2863 (move _CU_POOL_FRACTIONS to atom/config.py)
next to the lazy model-runner import, and name the AITER commit the NaN
vector-load behaviour was probed against.

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

* docs(moe): note the external CU mask and the NaN exception

The dispatch comment says get_cu_num() does not count an HSA_CU_MASK set
outside ATOM, and that AITER's CU_NUM covers that case. The kernel's module
docstring now names rows with NaN logits as the exception to bit-identity,
as the function docstring already does.

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

* docs(moe): note the external CU mask next to the routing table

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

* docs(moe): CU_NUM must be set before AITER caches the CU count

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

* refactor(moe): fold the top-k softmax kernel choice into topK.py

- Drop ATOM_TRITON_TOPK_SOFTMAX: the Triton kernel is bit-identical to
  AITER's, so it needs no off switch, and ATOM adds no env vars.
- Move triton_topk_softmax_rows into topK.py, which already imports AITER;
  the supported / max-rows helpers and the lazy AITER wrappers go. The
  RapidServe import stays local: model_runner imports topK.
- Shorten docstrings and comments; drop the num_valid_rows assert and the
  empty-launch guard (a zero grid launches nothing).
- Tests: the dispatch tests join the GPU test file, the NaN / -inf cases
  are one parametrized test, the full shape sweep covers fp16 and fp32
  logits too, and the switch / call-count tests go.

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

* perf(moe): keep top-1 / top-2 softmax routing on AITER

On MI355X, Triton is slower than AITER at top-1 past ~3K rows and at
top-2 near the 5120-row cutoff (results are still bit-identical), so the
Triton kernel now takes top-4 and up only; every model shape it served
before is top-4 or more. A shared column with scoring func "" is refused
too: AITER rejects that call, while the Triton kernel would sigmoid-score
it. No caller passes "".

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

* revert(moe): leave the existing top-k softmax lines as they were

- rocm_aiter_topk_softmax_impl allocates AITER's scratch where it did.
- Mxfp4MoEMethod.select_experts keeps its existing line; the new argument
  reads layout.uses_all2all_fusion directly.
- _select_logical's new argument defaults to None.
- docs/model_ops_guide.md: the routing table is unchanged; the Triton
  kernel is described in a paragraph below it.

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

* Test the Triton top-k softmax gate on CPU; drop FusedMoE class attribute

Move the shape, architecture and per-CU cutoff cases of
triton_topk_softmax_rows to tests/model_ops/test_triton_topk_softmax_rows.py,
which imports topK under test_comm_fused_moe's AITER / Triton stubs so
Pre Checkin runs them. The CU-masked cases stay in the GPU file.
Remove the triton_topk_softmax_max_rows class attribute; __init__ sets it.

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

* Decide the Triton top-k softmax kernel inside topK.py

rocm_aiter_topk_softmax_impl now derives the routed width, top-k and
shared columns from the launch and asks a cached triton_topk_softmax_rows,
which reads RapidServe's CU masking from the current config. moe.py,
qwen4_exp.py and the RTP-LLM topk_compat go back to main: no layer
attribute, no triton_max_rows argument, no num_routed change. With the
width taken from the launch, the renormalize and width asserts go too; a
MoRI all2all launch that keeps a scored shared logit is 2^n + 1 wide and
stays on AITER. The docstring says 32 experts is the fewest measured.

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
* refactor: extract the legacy monolithic kernel into seperate files

* optimize down kernel and add qwen3.5 125b tuned csv

* apply review comments

* apply review comment

* opt batch2-8

* apply review comment

* apply review comments.

* apply review comments

* retune decoding csv: 1-8 tokens +24.3%

* avoid repeated expert IDs of a token

* use Opus aux sort for the sorted_sum route lookup to avoid call cost to `invert_sorted_ids`

* skip -1 pad-row routes in direct decoding; zero per-tensor Gate/Up output

Since ROCm#6916, routing gives rows past num_valid_rows expert -1 and weight 0
and expects sorting to drop them.
- Batch-1 and direct-decoding kernels read topk_ids without sorting; they now
  skip -1 routes instead of reading weights and scales in front of expert 0.
- Per-tensor prefill zeroes the Gate/Up output: its Down absmax reads every
  route row, including routes sorting dropped (merged repeated IDs, -1 ids).

Tests: pad_rows routing (-1 ids, zero weights). Weights and scales sit behind
a NaN expert and the Gate/Up output starts as inf, so reading expert -1 or a
skipped row fails the check. New edge cases: per-tensor prefill and B2 direct
decoding with pad rows.

* retune decoding csv on FlyDSL 0.4.0

Decoding rows (<= 256 tokens) start from main's selections. --e2e_tune ran with
TUNE_ONLY=flydslv2,cktile,flydsl,asm, AITER_FMOE_TUNE_EXCLUDE_KERNELS=fmoe_stage1
and AITER_FLYDSL_MOE_BF16_RTA_SIMPLIFIED=1 on MI308X with PTL enabled
(VECTOR,F8); each shape then keeps the lowest median of main's selection and
every eligible FlyDSL config over three interleaved rounds. Three picks that
are slower than main with the default rounding keep main's selection. 65 rows
change kernel versus main; rows above 256 tokens are main's.

* apply review comment

* skip the prefill output clear; batch 1 requires the 16_16_16 tile; 7 decoding rows keep main's selection
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.

2 participants