Skip to content

[Perf] [AMD] dsv4: Use the aiter MegaMoE small- and large-input paths - #47065

Open
IzacharyI wants to merge 1 commit into
sgl-project:mainfrom
IzacharyI:sglang/perf/use_megamoe_one_launch
Open

IzacharyI wants to merge 1 commit into
sgl-project:mainfrom
IzacharyI:sglang/perf/use_megamoe_one_launch

Conversation

@IzacharyI

@IzacharyI IzacharyI commented Oct 28, 2026 •

Copy link
Copy Markdown
Contributor

Title: [Perf] [AMD] dsv4: Use the aiter MegaMoE small- and large-input paths

Opt-in switches for the two aiter MegaMoEV2 paths (needs ROCm/aiter#6881):

  • SGLANG_OPT_USE_AITER_MEGA_SMALL_M: steps whose DP-global max token count fits the small-input runtimes (up to 512 tokens per rank) call forward_small_m(), one kernel for quant, dispatch, GEMM1, GEMM2 and combine.
  • SGLANG_OPT_USE_AITER_MEGA_LARGE_M: extend steps with at least SGLANG_OPT_AITER_MEGA_LARGE_M_MIN_TOKENS (default 1024) tokens on some DP rank run the persistent large-input kernel.

Each MoE layer gets its own protocol slot on the shared operator, and the choice of path depends only on DP-gathered counts, so every EP rank takes the same path.

Motivation

DeepSeek-V4-Pro served with TP8 DP8(attn) EP8 and --moe-a2a-backend megamoe on MI355X runs every MoE call through aiter MegaMoEV2. ROCm/aiter#6881 adds two faster MegaMoEV2 paths for this layout; this PR lets SGLang use them. Both are opt-in and the default path does not change.

Depends on ROCm/aiter#6881; merge that one first. Without it, the new switches raise an error at startup and nothing else changes.

Modifications

  • New switches in environ.py, all off by default: SGLANG_OPT_USE_AITER_MEGA_SMALL_M, SGLANG_OPT_USE_AITER_MEGA_LARGE_M and SGLANG_OPT_AITER_MEGA_LARGE_M_MIN_TOKENS (default 1024). Smaller extend steps stay on the main path; the large-input path is turned on per step with set_large_m_enabled().
  • The path choice uses only DP-gathered counts (original_global_num_tokens_cpu, get_dp_global_num_tokens()), and require_mlp_tp_gather returns true when the small-input switch is on, so captured graphs get DP-synchronized buckets.
  • Each MoE layer gets its own protocol slot on the shared operator (bind_layer); the draft model's layers get their own slots too.
  • Works with SGLANG_AMD_FLYDSL_MEGA_MOE_DECODE_MTPR: the large-input path is used only on the full-capacity instance.
  • Only layers/moe/mega_moe_flydsl.py (the AMD MegaMoE adapter), environ.py and one branch in require_mlp_tp_gather that runs only with the MegaMoE backend change. CUDA paths cannot reach this code.
  • CPU unit test test/registered/unit/layers/moe/test_mega_moe_small_large_m.py: with the switches off the main path is untouched; with them on, every rank picks the same path from the DP-gathered counts (the small-input and extend thresholds), each MoE layer keeps its own slot, and a switch without the aiter path fails at first use.

Related open PRs: none change the AMD MegaMoE adapter (mega_moe_flydsl.py). The open MegaMoE PRs (#46056, #45905, #45613, #44359) are on the NVIDIA / FlashInfer MegaMoE path.

Accuracy Tests

GSM8K, 1319 questions, 5-shot, real speculative verification (no acceptance simulation), c384 server setup; measured with ROCm/aiter#6881 before its review changes, to be re-measured on the final aiter code:

accuracy
MegaMoEV2 (both switches off) 0.932–0.938
this PR (both switches on) 0.926–0.948

Speed Tests and Profiling

Setup:

  • Workload: InferenceX AgentX (aiperf --scenario agentx, dataset semianalysis_cc_traces_weka_062126), 3600 s per run, concurrency 128 / 256 / 384, two runs per arm.
  • Model and server: DeepSeek-V4-Pro-0813, TP8 DP8(attn) EP8, MegaMoE a8w4 with MTPR 8192, DSPARK speculative decoding with the InferenceX acceptance simulation (SGLANG_SIMULATE_ACC_LEN=3.77, the same accept length on both arms), sglang-router cache_aware + dp-aware. Server, router and client flags are those of InferenceX run 37608671586.
  • Hardware and image: one node, 8 × MI355X, lmsysorg/sglang-rocm:v0.5.21-rocm720-mi35x-20261007.
  • Baseline: the image as is (MegaMoEV2). This PR: the same image and flags with the aiter small- and large-input paths and these switches turned on. Measured before the rebase onto current main and before the review changes in [FlyDSL] [CI] MegaMoEV2: fuse Dispatch, GEMM1, GEMM2 and Combine into one kernel ROCm/aiter#6881 (skewed-routing fixes); the SGLang code path is unchanged by either. To be re-measured on the final aiter code.

Total token throughput = all input tokens (including prefix-cache hits) plus output tokens, per second per GPU (tok/s/GPU); run 1 / run 2, gain of the means:

conc baseline this PR gain
128 42,810 / 43,060 47,137 / 47,425 +10.1%
256 65,795 / 67,857 73,217 / 73,796 +10.0%
384 76,192 / 73,603 78,880 / 79,776 +5.9%

Run-to-run spread: ≤1.1% with this PR, ≤3.4% for the baseline. Below c128 the InferenceX recipe uses TP8 without EP, so this PR does not apply there.

Checklist

Review and Merge Process

  1. Ping Merge Oncalls to start the process. See the PR Merge Process.
  2. Get approvals from CODEOWNERS and other reviewers.
  3. Trigger CI tests with comments or contact authorized users to do so.
    • Common commands include /tag-and-rerun-ci, /tag-run-ci-label, /rerun-failed-ci
  4. After green CI and required approvals, ask Merge Oncalls or people with Write permission to merge the PR.

CI States

Latest PR Test (Base): ❌ Run #40682799849
Latest PR Test (Extra): ❌ Run #40682799962
Latest PR Test (AMD ROCm 10): ❌ Run #40682799895

Opt-in switches for the two aiter MegaMoEV2 paths (needs
ROCm/aiter#6881):

- SGLANG_OPT_USE_AITER_MEGA_SMALL_M: steps whose DP-global max token
  count fits the small-input runtimes call forward_small_m(), one kernel
  for quant, dispatch, GEMM1, GEMM2 and combine.
- SGLANG_OPT_USE_AITER_MEGA_LARGE_M: extend steps with at least
  SGLANG_OPT_AITER_MEGA_LARGE_M_MIN_TOKENS (default 1024) tokens on some
  DP rank run the persistent large-input kernel.

Each MoE layer gets its own protocol slot on the shared operator, and
the choice of path depends only on DP-gathered counts, so every EP rank
takes the same path.
GwilliamHu added a commit to ROCm/aiter that referenced this pull request Nov 10, 2026
SGLang (sgl-project/sglang#47065) drives the fused routes through main's
interface: forward_small_m(max_tokens=) for decode steps, and
set_large_m_enabled(True/False) followed by forward() without max_tokens
for extend steps. With calls without max_tokens pinned to the staged route,
set_large_m_enabled(True) no longer reached the large-input kernel.

The switch is now three-state: never called, a call without max_tokens
stays staged (unchanged default); True sends such calls to the large-input
route, as on main; False keeps the large-input route out of every call.
Calls with max_tokens still choose through route_for.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
GwilliamHu added a commit to ROCm/aiter that referenced this pull request Nov 15, 2026
SGLang (sgl-project/sglang#47065) drives the fused routes through main's
interface: forward_small_m(max_tokens=) for decode steps, and
set_large_m_enabled(True/False) followed by forward() without max_tokens
for extend steps. With calls without max_tokens pinned to the staged route,
set_large_m_enabled(True) no longer reached the large-input kernel.

The switch is now three-state: never called, a call without max_tokens
stays staged (unchanged default); True sends such calls to the large-input
route, as on main; False keeps the large-input route out of every call.
Calls with max_tokens still choose through route_for.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
GwilliamHu added a commit to ROCm/aiter that referenced this pull request Nov 16, 2026
SGLang (sgl-project/sglang#47065) drives the fused routes through main's
interface: forward_small_m(max_tokens=) for decode steps, and
set_large_m_enabled(True/False) followed by forward() without max_tokens
for extend steps. With calls without max_tokens pinned to the staged route,
set_large_m_enabled(True) no longer reached the large-input kernel.

The switch is now three-state: never called, a call without max_tokens
stays staged (unchanged default); True sends such calls to the large-input
route, as on main; False keeps the large-input route out of every call.
Calls with max_tokens still choose through route_for.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
GwilliamHu added a commit to ROCm/aiter that referenced this pull request Nov 19, 2026
SGLang (sgl-project/sglang#47065) drives the fused routes through main's
interface: forward_small_m(max_tokens=) for decode steps, and
set_large_m_enabled(True/False) followed by forward() without max_tokens
for extend steps. With calls without max_tokens pinned to the staged route,
set_large_m_enabled(True) no longer reached the large-input kernel.

The switch is now three-state: never called, a call without max_tokens
stays staged (unchanged default); True sends such calls to the large-input
route, as on main; False keeps the large-input route out of every call.
Calls with max_tokens still choose through route_for.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
coderfeli pushed a commit to ROCm/aiter that referenced this pull request Nov 24, 2026
…, and the DeepSeek-V4.1-Flash EP2 / EP4 / EP8 fused routes (#7788)

* refactor(mega_moe): reuse identical fused GEMM helpers and drop dead config

mega_moe_fused_gemm.py carried private copies of helpers that already exist
in gemm1/gemm2/gemm_util/mega_moe_config. Import those instead:
_LdsF32View, scale_view, scale_mma_atoms, mma_one_j, _resolve_g2_knobs,
_PACK, wait_lds_barrier, REFERENCE_EXPERTS_PER_RANK, _fixed_dispatch_cu.

Remove expert_config_class/_scale_dispatch_cu: experts_per_rank is limited to
<= 64, so both were identities that only widened the config cache key.
Remove the unreferenced _spart_output_tile_index.

Verified: gfx950 ISA of all 88 kernels built for MTPR 8192 (staged, small-M
and large-M; ranks 0 and 7) is byte-identical to main.

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

* refactor(mega_moe): one plan selects every route; drop SMALL_M/LARGE_M envs

MegaMoEV2 had three routing systems: AITER_MEGA_SMALL_M with an explicit
forward_small_m(max_tokens), AITER_MEGA_LARGE_M that sent every forward to
the large-input kernel once built, and the staged path otherwise. Each had
its own eligibility function (v2, small_m and large_m runtimes).

The bundle plan now owns the routes:
- fused_layout_supported()/small_m_cu_supported() in mega_moe_config are the
  single eligibility rule; MegaMoEV2 and both runtimes use them.
- build_mega_moe_bundle_plan(small_m_mtprs=, large_m=) records the fused
  routes; capacities above the first small bank that covers the instance
  MTPR are unreachable and no longer built.
- MegaMoEBundlePlan.route_for(max_tokens) picks small-input (smallest bank
  >= max_tokens), large-input (>= 513 rows, the measured crossover) or
  staged. forward(..., max_tokens=) takes the EP-wide row bound; without it
  the plan assumes the instance capacity, never the local row count, so all
  ranks take the same route. forward_prequant excludes the bf16-only
  small-input route.
- Routes are built whenever the layout supports them (no env switches);
  small_m_mtprs=() / large_m_enabled=False leave one out.
- forward_small_m and set_large_m_enabled stay as thin wrappers over the
  same selector; tests pin a route through _forward_route.
- The weight attributes (_s1_w1, _s1_w1_scale, w2, w2_scale) are properties
  that rebind every route, and the small-input W2 dispatch table follows the
  current w2 per call, so callers that assign them directly per layer (ATOM)
  no longer leave the fused routes on the construction weights.
- AITER_MEGA_MOE_BOUNDS_CHECK is read through envs; the AOT build drops its
  MTPR-8192 env hack and gets the fused kernels from the plan.

Verified: gfx950 ISA and kernel set of the MTPR 8192 AOT build (88 kernels,
ranks 0/7) byte-identical to main; tests/test_mega_moe_route_plan.py.

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

* fix(mega_moe): run every launch of a call on the caller's stream

forward(stream=s) ran prepare/Stage1/Stage2 on s but quantize (fixed-slot)
and the staged combine on torch.cuda.current_stream(), so with s != current
the combine could read the P2P input before Stage2 wrote it. An fx.Stream
or raw handle also crashed in Stage2 (stream.cuda_stream). forward and
forward_prequant now make the caller's stream current for the whole call,
as the large-input route already did; torch_stream() moves to tensor_shim.

test_mega_moe_v2 checks every route with a held-back caller stream for a
torch stream, an fx.Stream and a raw handle.

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

* refactor(mega_moe): routes of one instance share payload and GEMM1-output arenas

Each route owned a complete copy of the heavy per-call data: the staged
op, the large-input runtime and every small-input bank allocated their own
symmetric payload (activations, scales, route weights, source map) and their
own GEMM1 output. An instance has one call in flight, and every route
rewrites or masks this data before reading it and finishes reading it
before its call's closing all-rank barrier, so one copy sized for the
largest route serves all of them. Counters, epochs, ready flags and the
combine buffers stay per route.

- group_major_capacity() is the single capacity formula of a group-major
  op; GroupMajorPayloadArena allocates the shared symmetric payload and
  FlyDSLDispatchGroupMajorOp/FlyDSLDispatchCombineIntraNodeOp view it.
- stage1_output_buffers() replaces three copies of the GEMM1 output/scale
  allocation and views a shared arena when given one.
- MegaMoEV2 sizes both arenas from its plan's routes (staged, large-input,
  small-input banks) and passes them to the runtimes; a staged-only
  instance allocates exactly as before.

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

* feat(mega_moe): large-input route for MTPR 1024..16384, not 8192 only

The large-input kernel was gated to instances of exactly 8192 tokens per
rank. Nothing in its protocol or geometry depends on that capacity: the
source-encoding (W*mt <= 2^24) and P2P/offset ABI checks that do bound it
stay in place. LARGE_M_MTPRS now lists 1024..16384 and is the one place the
capacity is gated (plan, runtime and fused selector read it).

32768 stays on the staged route: the large-input kernel is slower there
(+11.7% E2E at 32768 uniform tokens per rank) and its route-major payload
would need 10.5 GiB per GPU against the staged indexed payload's 1.75 GiB.

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

* refactor(mega_moe): share GEMM1 loaders and MFMA atoms with the fused kernels

The fused small-/large-input runtimes kept private copies of TileScheduler,
ATileLoader, AS2RLoader, BWeightLoader, BScaleLoader, AScaleLoader and
MfmaScaleGU. Use the gemm_util ones instead. The two options only the fused
path needs become opt-in keywords whose defaults keep the staged code path:
ATileLoader.for_tile(valid_rows_i32) clamps the tile descriptor so padding
rows read back as zero, and BScaleLoader.load_step(cache_modifier) sets the
B-scale cache policy.

The fused kernels now build their GEMM1 weight, scale and routing
descriptors with tensor_shim.ptr_buf_tensor (same base, alignment and
max-size num_records as before) so the shared classes can index them.

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

* refactor(mega_moe): share SiluQuantEpilogue with the fused kernels

Drop the fused copy of the SwiGLU + FP8 quant epilogue. The gemm_util one
gains the three options the fused path needs, all off by default:
out_cache_modifier (large-M stores with sc0|sc1 = 17 so GEMM2 on other CUs
of the same kernel sees the GEMM1 output), a per-call store_cm override and
valid_rows_i32, which clamps the tile output descriptor and drops padding-row
output and scale stores. The fused kernels keep the 2-column store pass
(evec=2) and now build their output descriptors with ptr_buf_tensor.

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

* refactor(mega_moe): build fused GEMM1 tiles with gemm1.build_fused_gemm1

Drop the fused copies of do_tile and build_fused_gemm1 and move the
lookahead K-loop do_tile_la next to gemm1.do_tile. build_fused_gemm1 gains
rows_rsrc/lookahead (small-M runs do_tile_la, clamped to each tile's row
count), out_cache_modifier (forwarded to the epilogue) and tile_zero, which
makes the tail A ds_read offset opaque per tile so it is not hoisted and
spilled (large-M). All default to the staged behaviour.

do_tile's rows_rsrc argument is dropped: only do_tile_la was ever given one.

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

* refactor(mega_moe): run fused GEMM2 tiles through gemm2.gemm2_compute_v2

Drop the fused copies of issue_a_load_lds_dt and gemm2_compute_v2. The
gemm2 versions gain the options the fused kernels use, defaulting to the
staged behaviour: NW (CTA wave count; the 1-stage B path is now selected by
a 64-column per-wave slab, BN // NW == 64, which is BN == 256 at NW=4),
valid_rows (bounds the A tile descriptor to the tile's real rows) and
early_b_load (1-stage path: issue the K-tile's B and A-scale loads before
the barrier and the next A-tile DMA).

The fused path now uses gemm2's padded B load (offset 0, then select zero)
instead of load_at(mask=), whose out-of-range offset was not past
num_records 0xFFFFFFFF and so read real memory. It was dead (has_pad is
False in both fused kernels); load_at loses the mask argument.

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

* refactor(mega_moe): fused routes take their configs from mega_moe_config

mega_moe_fused_gemm.py still carried a second config system for the small-
and large-input kernels: its own Stage1Config/Stage2Config/MegaMoEConfig
(field subsets of mega_moe_config's), TOKEN_BUCKETS, nearest_token_bucket,
SMALL_M_FIXED_SLOT_MAX_MTPR and a select_mega_moe_config that shadowed the
staged selector's name.

The fused kernels now use mega_moe_config's types. Their tuning rules move
there unchanged as select_fused_config (small-input per-bucket fixed-slot
configs, one large-input config per capacity); FUSED_TOKEN_BUCKETS keeps
their bucket set (no 2-token variant), nearest_token_bucket takes the bucket
set, and SMALL_M_MAX_MTPR is the one small-input bound. The file keeps only
the buffer helpers of the fused dispatch/combine code (2107 -> 86 lines over
the series).

Verified: ISA of the MTPR 8192 AOT build (ranks 0/7) and of the MTPR 16384
build (rank 0) unchanged by this commit.

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

* docs(aot): MegaMoE fused kernels come from the instance plan

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

* fix(mega_moe): forward allocates nothing; document the unsliced output

The fixed-slot staged route and the large-input route quantized the input
into freshly allocated tensors on every forward, so each call (and each
captured graph) allocated. per_1x32_mx_quant takes an ``out`` pair; the
fixed-slot route writes into the instance's existing quant buffers (only
compact prepare used them) and the large-input runtime into its own,
allocated once. quantize() still returns new tensors for callers that keep
them across calls (forward_prequant).

forward() now states the output contract: a view of the route's combine
buffer, valid until the next call; slice_output=False returns the route's
capacity rows, the rows past this rank's own undefined.

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

* refactor(mega_moe): fused routes share the combine input and quant buffers

The large-input runtime and each small-input bank still allocated their own
symmetric combine input (8 * MTPR rows of 2*H bytes: 0.88 GiB per GPU at
MTPR 8192, 1.75 GiB at 16384) and the large-input runtime its own quant
buffers. Every route writes a peer's combine input only after that peer has
entered the same call and reads its own before the call ends (with every
launch on the caller's stream), so they view the staged op's buffers; the
large-input route quantizes into the staged quant buffers. Combine outputs
stay per route: they are the returned views.

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

* refactor(mega_moe): one fused selector, one input check, one output view

Review follow-ups:
- The small-input kernel's overrides (non-persistent NT GEMM2, 64-row tiles
  from bucket 256) live in mega_moe_config's _small_m_stage1/_small_m_stage2
  instead of a second layer (small_m_config) in the runtime; the shape
  branches no supported fused layout reaches are gone. A golden test pins
  every fused launch config to its value before the move.
- check_forward_inputs (weights.py) replaces the three per-entry input
  checks (MegaMoEV2 now also checks the shapes, as the small-input runtime
  did); combine_output() on the dispatch/combine op replaces three copies of
  the output view; stage2_p2p_row_nbytes moves to mega_moe_stage2 and replaces
  the inline row-size formulas in MegaMoEV2 and the large-input kernel.
- Assigning w2_scale builds the small-input W2 dispatch table outside graph
  capture, so a capture right after a direct assignment finds it.
- test_mega_moe_small_m compares against the staged route explicitly and
  checks the large-input route's epoch wrap through that route; docstrings
  and comments describe the shared arenas, forward_prequant's route set and
  the staged-only bench.

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

* refactor(mega_moe): one p2p_scatter_epilog for the staged and fused GEMM2 tiles

The small- and large-input kernels carried their own copies of the GEMM2 ->
P2P scatter epilogue. Keep the staged one in mega_moe_stage2 and give it the
fused callers' knobs: NW (wave count), store_cm / fp8_store_cm (peer store
cache policies), p2p_quant_type="dynamic" with fp8_rows, and
elem_view_stores (address peer stores through store_at's element-stride
view). Defaults reproduce the staged kernel; final ISA is byte-identical for
all 88 MTPR 8192 kernels (ranks 0, 7) and 46 MTPR 16384 kernels (rank 0).

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

* refactor(mega_moe): share the 1x32 FP8 lane-group quantization of the P2P scatters

p2p_scatter_epilog and the aligned-pair Stage2 scatter each inlined the same
lane-group |max| reduction, leader E8M0 scale broadcast and FP8 packing.
Move it into mega_moe_stage2._fp8_quant_1x32; group_lane / leader_gate keep
the aligned-pair half-lane, active-gated leader. Final ISA is byte-identical
(MTPR 8192 ranks 0/7: 88 kernels; MTPR 16384 rank 0: 46 kernels).

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

* refactor(mega_moe): large-input dispatch plan reuses dispatch._increment_i32

The large-input kernel kept its own copy of the tile-expected increment over
an AddrBuffer; index a ptr_buf_tensor view with the dispatch helper instead.
Final ISA is byte-identical (MTPR 8192 ranks 0/7: 88 kernels; MTPR 16384
rank 0: 46 kernels).

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

* fix(mega_moe): size the shared combine input for the largest route

The fused routes viewed the staged op's combine input, sized for the
instance MTPR. A small-input bank can exceed it (an MTPR-128 instance builds
the 256 bank), and construction failed ("the shared combine input is smaller
than this op needs"). MegaMoEV2 now allocates one combine input for the
largest capacity among its routes and every op, the staged one included,
views it; combine_input_numel() is the single sizing formula.

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

* perf(mega_moe): without max_tokens, plan without the large-input route

Paired 8-GPU timing (3x10 graph replays, ABBA against main) showed the
large-input kernel 10-40% slower than the staged path below ~512 rows per
rank (e.g. MTPR 8192, 1 row: 308.5 vs 194.4 us) and faster from 512 rows
up. A call without the EP-wide row bound cannot tell the two apart, so it
now keeps main's route for instances above the small-input capacities (the
staged path); instances whose capacity fits a small-input bank still take
it, as it is faster at every size. Callers that pass max_tokens get the
large-input route from 513 rows per rank.

test_mega_moe_v2 passes the instance capacity as max_tokens, so its staged
and --expect-large-m runs keep their routes.

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

* feat(mega_moe): log the routes an instance builds

One line per instance (rank 0) names the staged layout and the fused routes
the plan built, so a serving log shows which kernels a deployment can take.

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

* perf(mega_moe): a call without max_tokens takes the staged route

Without the EP-wide row bound a call now runs exactly main's route: the
staged path, fixed-slot or compact by capacity. Instances whose capacity
fits a small-input bank used to take it unhinted (e.g. a framework's
MTPR-128 decode instance); the fused routes now need the caller's
max_tokens, so callers that do not pass it see no change in kernels,
numerics or speed.

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

* fix(mega_moe): set_large_m_enabled keeps main's per-call meaning

SGLang (sgl-project/sglang#47065) drives the fused routes through main's
interface: forward_small_m(max_tokens=) for decode steps, and
set_large_m_enabled(True/False) followed by forward() without max_tokens
for extend steps. With calls without max_tokens pinned to the staged route,
set_large_m_enabled(True) no longer reached the large-input kernel.

The switch is now three-state: never called, a call without max_tokens
stays staged (unchanged default); True sends such calls to the large-input
route, as on main; False keeps the large-input route out of every call.
Calls with max_tokens still choose through route_for.

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

* feat(mega_moe): fused-kernel knobs of the EP4 V4.1-Flash tune in the shared GEMM code

Port the shared parts of 28ee7fcd ("Speed up the fused MegaMoE kernel for
DeepSeek-V4.1 Flash on 4 GPUs") onto the deduplicated GEMM modules, every
knob off by default:

- gemm_util: srcmap-mapped A rows and scales (dedup_rows), inline-asm A
  operand reads, packed LDS A scales, and the fused evec 8 epilogue
  (valid rows, cache policy, short tiles, lean/fast-SiLU variants) next to
  the staged one, which stays as it was.
- gemm1: row_map / plan_lookup / a_ahead in do_tile(_la), and the short,
  fold and mid tile runners of the large-input kernel.
- gemm2: the BM64 1-stage knobs (uniform A copies, LDS A scales, folded
  tail rows) and their two copy helpers.
- mega_moe_stage2.p2p_scatter_epilog: lane-fed row ids / peers, per-token
  completion counts, BF16 head tokens, staged scales, the lean FP8 / int8
  route quantizer.
- mega_moe_config: FusedStage1Knobs / FusedStage2Knobs on MegaMoEConfig
  instead of new Stage1Config / Stage2Config fields, so the staged configs
  and the fused config digest are unchanged.

gfx950 ISA of EP8 V4-Pro a8w4 (MTPR 128/1024/8192/16384, ranks 0 and 7,
280 kernels) is byte-identical to the previous commit.

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

* feat(mega_moe): small-input route for EP4 DeepSeek-V4.1-Flash

Port the small-input part of 28ee7fcd: the single kernel accepts the EP4
layout (4 ranks, 5120/2304, 96 experts a rank) and runs it with the
measured tune -- one dispatch row per (token, destination), every CTA
building its own plan, direct source flags for 1-2 producers, per-token
completion counts for 1-4 tokens, SGPR pointers, the lean GEMM1 epilogue
and register-fed A rows, early GEMM2 CTAs at 512 tokens.

The protocol state the commit changed for every layout stays EP8-neutral:
the epoch step, the per-token counters and their reset, and the BF16 rows
of the first tokens follow FusedStage1Knobs (direct_done, tok_counters,
bf16_head_tokens), which only the EP4 tune sets; SmallMRuntime asserts that
every bucket of a runtime agrees on them. The debug-only row_poll mode is
not ported (it read environment variables at trace time and relied on
combine-input rows the other routes now share).

The token-row regions of dedup_rows live in the shared payload arena past
the runtime's fixed slots (payload_capacity grows by world * mtpr rows on
such a layout), so their u32 offsets are fixed instead of depending on
where the symmetric heap put a separate allocation.

fused_layout_supported() admits FUSED_LAYOUTS (EP8 V4-Pro, EP4 V4.1-Flash);
large_m_mtprs_for() keeps the large-input route on EP8 only for now.
select_fused_config() takes the layout.

gfx950 ISA (AOT dry-run):
- EP8 V4-Pro, MTPR 128/1024/8192/16384, ranks 0 and 7: 280/280 kernels
  byte-identical to the previous commit.
- EP4 V4.1-Flash, MTPR 8192, ranks 0 and 3, against 28ee7fcd: the 58
  staged / quant / combine kernels are byte-identical; the 34 small-input
  kernels have the same instructions and resources, in a different order
  only (GEMM2 B loads through the shared gemm2 buffer view instead of the
  commit's element view; the t64x128 ones: the v_lshlrev move the branch
  already has on EP8).

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

* feat(mega_moe): large-input route for EP4 DeepSeek-V4.1-Flash at MTPR 8192

Port the large-input part of 28ee7fcd: the persistent kernel runs the EP4
layout with the measured tune (8-12 payload producers per destination over
192 dispatch CUs, deduplicated token rows with arrival stamps, a parallel
lean plan with tagged count words and bucketed pair order, presend, short /
mid / folded GEMM1 tail tiles, XCD-affine grouped GEMM2 claims with early
GEMM2 CTAs, staged row scales, LDS A scales, the lean epilogue with int8
route rows, and per-token combine waits).

Every new kernel path sits behind a FusedStage1Knobs / FusedStage2Knobs
flag that only _tune_v41_flash_ep4_large sets and that enters the kernel
spec only when on, so EP8 compile keys and kernel names are unchanged. The
spots where the commit changed the default path stay in their old form
(the payload's peer-row loads keep their order when not hoisted, the
combine's int8 scale sum exists only with route_i8). The epilogue changes
went into the shared mega_moe_stage2.p2p_scatter_epilog in the previous
commits; load_at takes its mask back for the new staged-scale reads.

Host side: the bucketed pair order and the row-arrival / sent-row buffers
are allocated only when the config uses them (on EP8 they keep their old
sizes), and the staged-scale buffer is allocated at init, not in forward.
large_m_mtprs_for() gives EP4 the capacity the tune was measured at (8192).

gfx950 ISA (AOT dry-run):
- EP8 V4-Pro, MTPR 128/1024/8192/16384, ranks 0 and 7: 280/280 kernels
  byte-identical to the previous commit.
- EP4 V4.1-Flash, MTPR 8192, ranks 0 and 3, against 28ee7fcd: same kernel
  set and names; staged kernels byte-identical; the large-input kernel has
  the same instructions and resources with one s_mul moved, and the
  small-input kernels as before. Loading GEMM2's B weights through
  load_at's element view (the commit's form) instead of the shared gemm2
  buffer view makes every one of them byte-identical.

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

* test(mega_moe): EP4 V4.1-Flash fused routes in the route-plan and small-input tests

- tests/test_mega_moe_route_plan.py: the fused layout gate admits EP4
  V4.1-Flash (and no mix of the two shapes); large_m_mtprs_for() gives EP4
  only 8192; every EP8 fused config keeps its fused knobs off, and the EP8
  config digest is unchanged; a golden digest of the EP4 configs (checked
  field by field against 28ee7fcd's small_m_config / select_mega_moe_config
  for 38 (mtpr, tokens) cases: no difference); every EP4 small-input bucket
  runs one launch protocol; EP4 dispatch CUs cover two expert waves; the
  dedup token rows fit in the payload arena below the u32 offset limit.
- op_tests/multigpu_tests/test_mega_moe_small_m.py: --network v41_flash
  (run it on 4 ranks) and --check-time-acc, which checks every timed route
  and the large-input one against the fp32 reference at the timed count.
- aiter/aot/flydsl/README.md: the EP4 AOT profile.

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

* fix(mega_moe): EP4 fused runtimes that end before their peers keep their own payload

_build_route_arenas lets every route share one payload arena because each
route finishes reading it before its call's closing all-rank barrier. The
EP4 V4.1-Flash tune drops that barrier: the large-input combine waits only
for this rank's tokens (comb_tok_wait) and the small-input tok_done buckets
reduce a token once its own rows are counted. A rank can then leave and
dispatch its next call (the small-input route has no launch handshake) into
a peer that still runs GEMM1/GEMM2 on the shared arena: a large -> small or
small 256 <-> small 512 switch overwrites rows, srcmap and weights the peer
is reading.

A runtime whose launch can end that way (LargeMRuntime / SmallMRuntime
.ends_all_ranks) now keeps its own payload, as in 28ee7fcd; the small-input
runtimes also keep their own combine input, which their combine leaves
poisoned for the first tokens (bf16_head_tokens), so the staged and
large-input routes no longer read those rows. The large-input runtime keeps
sharing the combine input (a peer writes it only after this rank entered
the same call) and every route keeps sharing the rank-local GEMM1 output.
EP8 reaches none of this: its fused runtimes still share every arena, and
its allocations are unchanged. Host-only: no kernel changes.

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

* feat(aot): DeepSeek-V4.1-Flash EP4 profile in the MegaMoE production build

production_jobs() built only the EP8 profiles, so every EP4 V4.1-Flash
kernel (staged, small-input and large-input) compiled online on first use,
and a cache-only run failed. Add the EP4 profile (world 4, epr 96,
5120/2304, a8w4) at the MTPRs of ATOM's instances: 128 (decode: staged +
small-input 256), 8192 (prefill: staged + small-input + large-input) and
16384 (staged + small-input). An explicit --mtpr applies to it as well.
The default build grows from 192 to 204 jobs.

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

* fix(mega_moe): one large-input pair order for every layer slot

The pair order is rank-local, and a launch reads only the entries its own
routes wrote (rows below this launch's per-expert counts), so the layer
state slots share one copy. With bucket_pairs (EP4 V4.1-Flash) it holds
total_experts x mtpr routes: 12.6 MB a slot at MTPR 8192, about 768 MB at
the 61 slots of a DeepSeek model, now 12.6 MB. EP8 saves its 196 KB a
slot as well. Host-only: no kernel changes.

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

* fix(mega_moe): small-input protocol assert covers the tok_done GEMM2 block_n

A tok_done reducer waits until a token's counter reaches its valid routes x
its own GEMM2 n-blocks, while every tok_done sender adds one per n-block of
its own bucket. Ranks of a launch may pick different buckets, so the
tok_done buckets must split model_dim alike; it held only because buckets
1 and 4 both use block_n 256. SmallMRuntime now asserts it, and the EP4
route-plan test checks it.

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

* test(mega_moe): one multi-GPU MegaMoEV2 test for every route

test_mega_moe_small_m.py moves into test_mega_moe_v2.py as --suite routes:
the instance production builds (staged, small-input 256/512 and, at its
MTPRs, large-input routes side by side), each call's route picked by
forward(max_tokens=...) and checked against the plan. Its scenarios are
unchanged: accuracy against the fp32 reference and the pinned staged route
on uneven, idle and padded ranks, empty ranks with -1 slots (through
forward_small_m), skewed routes, layer rebinding with interleaved staged
calls, the epoch wrap with zero rows, graph replay against eager, and
paired timing (--check-time-acc / --time-only / --time-bs). Timing now also
times the large-input route when max_tokens selects it, and --check-time-acc
checks the routed call at every timed size.

The per-size checks stay the default (--suite size), flags unchanged. The
routes suite keeps its flags; --mtpr and --slots alias --max-tok-per-rank
and --large-m-state-slots, and --seed / --rtol / the slot count keep each
suite's former default. --network v4_pro|v41_flash picks EP8 or EP4.

The duplicated helpers are gone: one _rel_l2 (now casting the reference),
_all_ranks for the rank-wide flags, and _moe_reference for the instance's
layout. The large-input edge check gates the instance's own layout, so it
also holds on EP4. The helpers external harnesses import keep their names.

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

* test(mega_moe): name the route-plan test after gfx950

tests/test_mega_moe_route_plan.py becomes test_mega_moe_gfx950_route_plan.py,
next to test_mega_moe_gfx1250_recipe.py.

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

* test(mega_moe): runnable same-MTPR timing example in the MegaMoEV2 test docstring

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

* fix(mega_moe): double-buffer the small-input expert counters by launch parity

With plan_local the last WG of the combine zeroes the per-expert receive
counters, relying on peers adding to them only after its flag. A tok_done
reducer skips the flags, so a rank can finish launch N and its N+1
producers can add to a peer's counters before that peer's launch-N combine
zeroes them (the route is lost and the reducer falls back to a poisoned row:
NaN), or before the peer's launch-N plan reads them (the peer counts an N+1
route).

A runtime with tok_counters now keeps two halves of the counters by the
entry-epoch parity: launch N counts into, plans from and zeroes half N & 1.
The next launch a peer can add to that half from is N + 2, which needs this
rank's launch N + 1 sources, so launch N is complete. Runtimes without
tok_counters (EP8) keep the combine op's single counter set.

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

* test(mega_moe): EP4 tok_counters buckets zero their expert counters in the combine

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

* fix(mega_moe): double-buffer the small-input srcmap and weight slots by launch parity

On an EP4 small-input runtime a tok_done rank can start launch N+1 while a
peer still runs launch N's GEMM1/GEMM2. Since the expert counters are
double-buffered, launch N+1 slot offsets restart at 0, so its producers
overwrote the srcmap/weight slots of launch N routes the peer had not
consumed yet. The peer then scattered that route to the wrong token, and the
victim token's reducer fell back to the flags and summed a poisoned row
(NaN).

The srcmap and weight slots now live in two fz_epr * fz_cap halves
(runtime-owned symmetric buffers) selected by the same launch parity as the
counters. Gated on tok_counters (EP4 small only); EP8 is unchanged.

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

* fix(mega_moe): assert the layout the double-buffered small-input slots rely on

A runtime with tok_done buckets must send dedup token rows (its slot-indexed
payload rows are single-buffered), and its srcmap / weight halves need the
non-compact slot layout.

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

* test(mega_moe): layer-slot stress holds tuned large-input layouts to rtol

EP4 V4.1-Flash's large-input route sums in another order than the staged
route (FP8 combine rows, BF16 head tokens), so it cannot match it bit for
bit; EP8 V4-Pro (default fused knobs) still must.

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

* feat(mega_moe): EP4 V4.1-Flash large-input route at MTPR 1024..16384

large_m_mtprs_for() gives the EP4 layout the EP8 capacities. Its large-input
tune (measured at 8192) is reused unchanged: its thresholds count a launch's
rows a rank and the payload geometry comes from the plan, so the capacity only
sizes buffers. LargeMRuntime now checks the pair order and GEMM2 scale staging
against the 32-bit buffer offsets. The AOT EP4 profile keeps its MTPRs
(128/8192/16384); the 16384 instance now builds the large-input kernel too.

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

* test(mega_moe): EP4 large-input route and buffer limits at every capacity

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

* docs(aot): the default EP4 profile leaves the 1024..4096 large-input kernels to --mtpr

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

* fix(mega_moe): EP4 V4.1-Flash large-input route at MTPR 8192 and 16384 only

On MI355X the EP4 large-input kernel faults (illegal memory access) at MTPR
1024, 2048 and 4096; at 8192 and 16384 it passes the size, routes and
61-slot suites and runs 1.1-2.1x faster than staged for 513+ rows a rank
(zipf at 16384 x 16384 rows ties). Those two capacities are the ones ATOM's
prefill instances use. The skewed route-switch check needs a source rank to
saturate five destinations, so it is skipped below five ranks.

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

* style(mega_moe): black-format the MegaMoE route files

Formatting only (black stable); the code's AST is unchanged, docstrings
only re-wrapped.

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

* refactor(mega_moe): drop the MegaMoE environment variables

Every knob in mega_moe/envs.py is hard-wired to its default, and the module
is gone:

- AITER_MEGA_FIXED_SLOT_MAX_MTPR: FIXED_SLOT_MAX_MTPR is the constant 255.
- AITER_MEGA_COMBINE_MASK: forward(mask_invalid_slots=None) leaves the -1
  slot check off; callers that pad with -1 pass True.
- AITER_MEGA_MOE_PRELOAD: building an instance never preloads; callers use
  preload_aot_bundles().
- AITER_MEGA_S1_EPI_EVEC, AITER_MEGA_S1_FIXED_KPAIR,
  AITER_MEGA_DISPATCH_FAST_COPY: Stage1 always takes the 8-column epilogue,
  the paired fixed-slot K loop and the two-row compact payload copy. The
  Int16 Stage1 output view and the row-at-a-time payload copy only the
  fallbacks reached are removed; the evec 2 epilogue and the unpaired K loop
  stay, as FP4 output, the small-input kernels and compact Stage1 use them.
- AITER_MEGA_MOE_BOUNDS_CHECK: the Stage1 bounds_check parameter and its
  bounded V# extents are removed (default off).

Kernel names keep their _ev8b / _fc suffixes, so names and AOT caches are
unchanged.

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

* feat(mega_moe): DeepSeek-V4.1-Flash EP2 on the fused small- and large-input routes

EP2 V4.1-Flash (192 experts a rank, d5120 / i2304, topk 6, a8w4) joins
FUSED_LAYOUTS next to EP8 V4-Pro and EP4 V4.1-Flash: the small-input route at
MTPR 256 / 512 and the large-input route at MTPR 8192 / 16384.

- Config: V41_FLASH_EP2_LAYOUT, V41_FLASH_EP2_LARGE_M_MTPRS, up to 256 experts
  a rank, and EP2 small / large tunes starting from the EP4 ones: 32-row expert
  tiles at every bucket and 96 producer CTAs (3 x 96 would leave no consumers).
- Small-input kernel: the EP2 fixed-slot layout; the plan finalize scans up to
  4 64-expert chunks (the combine resets one expert counter a thread, asserted).
- Small-input kernel: FusedStage1Knobs.stream_w keeps the streaming GEMM bodies
  at any routed-row count (only a hot expert takes the cached ones).
- Large-input dispatch: bounded_scales bounds the batched token-scale reads by
  the scale buffer. Their masked lanes read 2 GiB past an unbounded buffer,
  which faults on EP2 at every token count (illegal memory access in the
  presend / batched payload copy, found with rocm-debug-agent and bisected to
  batch_rows). EP4 and EP8 keep their kernels.
- AOT: the EP2 profile (MTPR 128, 8192, 16384) in the default build.
- Tests: EP2 admission, capacities, protocol, tile and producer limits, payload
  sharing, route plan and config digest; the EP8 / EP4 digests are unchanged.

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

* tune(mega_moe): DeepSeek-V4.1-Flash EP2 small-input buckets 256 and 512

Measured on 2 MI355X GPUs (MTPR 512; uniform, Zipf and hot-expert routing),
against the EP4-derived EP2 kernel of the previous commit:

- 256 and 512 tokens: tile_n 256 (half the GEMM1 n-tiles, each streaming a
  longer W1 slab) and GEMM2's dispatch-table pointers in SGPRs (g2_uniform; the
  32-row tiles leave the registers the EP4 64-row tiles spilled): -3% uniform,
  -8% Zipf, -12% hot at 256.
- 512 tokens: stream_w. The 3072 routed rows pass the cached-weight threshold
  measured on EP8 / EP4, but each of the 192 experts has ~16 rows in one
  m-tile, so no tile rereads its weights: -8% uniform, -3% Zipf, -3.5% hot
  with the above.

Left out after measuring: tok_done at 8 tokens and tile_n 256 at 32-64 (win
uniform, lose 6-14% hot), producer counts 32-224, direct_done, block_n, early
GEMM2, FP8-row thresholds, cached weights at 128-256; on the large-input
kernel presend_experts 24 (-2..-6% uniform at 4096-16384 tokens, +5..30%
Zipf at 3072-6144), early_p 5-6 (+3-5% at 3072), payload producer counts,
presend_rows, early_p_mid, m_group, xcd_chunk and early_k.

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

* fix(mega_moe): bound the EP4 V4.1-Flash large-input token-scale reads

The EP4 V4.1-Flash large-input route (MTPR 8192 / 16384, the production
prefill route) batches its dispatch rows (batch_rows), whose token-scale reads
(presend and payload copy) use masked loads. On an unbounded buffer a masked
lane's load_at index is 0x7FFFFFFF // 4, so it reads about 2 GiB past the scale
buffer and faults wherever nothing is mapped there. EP2 hit it at every token
count; EP4 has the same reads and only survives where the memory map happens to
back that address, so a different allocation can take it down.

bounded_scales (added with EP2) bounds those reads by the scale buffer
(mtpr * scale_n_i32 * 4 bytes, at least the real (tokens, model_dim // 32)
tensor): valid lanes read the same values, masked lanes read 0. It moves from
the EP2 large tune into the EP4 one, which EP2 inherits, so the EP2 config and
kernels are unchanged. EP8 V4-Pro does not batch its rows and keeps its kernels.

Only the EP4 large-input kernel changes (the EP4 config digest is re-pinned;
the table differs only in bounded_scales at MTPR 8192). The EP4 faults at MTPR
1024..4096 are not shown to be this, so those capacities stay staged.

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

* test(mega_moe): name EP2 V4.1-Flash in the MegaMoEV2 test's fused layouts

The docstring, the layout comment and the small-input route assertion of
test_mega_moe_v2.py listed only EP8 V4-Pro and EP4 V4.1-Flash. They now point
at FUSED_LAYOUTS and name V4.1-Flash by rank count (4 or 2), with an EP2
routes-suite command, so a further layout only extends that list. The size
suite's skewed route switch is marked as needing 5+ ranks (it skips itself on
EP4 and EP2).

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

* fix(mega_moe): keep AITER_MEGA_FIXED_SLOT_MAX_MTPR

Serving recipes raise the fixed-slot MTPR limit with it (SGLang's and
ATOM's DeepSeek-V4 MegaMoE recipes set 1023 / 2047 so their 512- and
1024-row decode instances dispatch fixed-slot), and vLLM's DeepSeek-V4
MegaMoE reads FIXED_SLOT_MAX_MTPR. Dropping the variable silently moved
those instances to the compact dispatch. It is read once at import with the
same default (255), so default behaviour and codegen are unchanged.

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

* feat(mega_moe): admit DeepSeek-V4.1-Flash EP8 to the fused routes

EP8 DeepSeek-V4.1-Flash (8 ranks, 5120/2304, 384 experts, topk 6, a8w4) has
V4-Pro EP8's rank / expert geometry (48 experts a rank) with V4.1-Flash's dims,
inside the fused kernels' limits. Add it to FUSED_LAYOUTS with the V4-Pro EP8
fused config (every fused knob off), and ship its decode (128) and prefill
(8192, 16384) instances in the default AOT build.

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

* perf(mega_moe): tune the DeepSeek-V4.1-Flash EP8 fused routes

Measured on gfx950 with 8 ranks (uniform, zipf 1.2 and one-rank-skewed
routes) against the V4-Pro EP8 config the layout took on admission.

Small input: EP4's tune carries over (its dedup rows, LDS plan, direct done,
GEMM2 SGPR pointers and the tok_done head), plus the 1-token GEMM1 schedule
at 4 tokens, 256-wide GEMM1 tiles at 32 and 64, later early GEMM2 CTAs at 512,
and the 128-wide tiles kept at 16. As at EP4, tok_done gives the small-input
runtime its own payload and combine buffers.

Large input: EP4's tune except its XCD-affine, m-group GEMM2 claims with
early CTAs (one claim counter per work shard instead, which the hot experts
of a skewed launch need), its streamed W1 loads and its per-token combine
wait (under 1.6% from 4096 tokens a rank, for 3.9 GiB of private payload a
GPU at MTPR 16384): the large-input runtime keeps sharing the payload arena.

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

* fix(mega_moe): V4.1-Flash EP8 large-input route at MTPR 8192 and 16384 only

The EP8 V4.1-Flash large-input tune builds on EP4's, and like it the
kernel faulted with an illegal memory access at MTPR 1024 (1 of 2 runs,
first call at 513 tokens a rank) on gfx950. Build the large-input route
at 8192 and 16384 only, as for EP4; 1024..4096 keep the staged route.
ATOM's DEP8 instances (128 and 16384) are unaffected.

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

* test(mega_moe): route-switch check of a tuned large-input layout

The skewed route-switch check expects the large-input route to match the
staged one bit-for-bit, which holds for the untuned V4-Pro EP8 kernels. The
tuned V4.1-Flash EP8 route sends other bytes (dedup rows, int8 transport),
so there it counts a row as corrupted only when it is off by a quarter of
its own norm (a stale pair order corrupts whole rows); transport rounding
stays near 0.03 relL2.

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

* test(mega_moe): EP8 V4.1-Flash large-input token-scale reads are bounded

Its large-input tune builds on EP4's, so it inherits the batched dispatch and the bounded token-scale reads.

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

* refactor(mega_moe): kernel-code-cleanup pass over the fused routes

Behavior-preserving cleanup from a kernel-code-cleanup scan of this branch:
- The batched dispatch always bounds its token-scale reads (bounded_scales knob
  removed: every batch_rows config set it), plan_direct removed (never compiled:
  its branch needs plan_local off, and its only config sets plan_local).
- Unreachable large-input paths removed: dedup without batch_rows (and its
  SENT_ROW slot / sent_row buffer), the in-group bucket histogram without
  early_hist; specs assert the couplings they rely on.
- Shared helpers reused: comm_ops.wave_uniform_i64, act.sigmoid_f32, one
  sc0|sc1 store-policy constant, the launch-ready handshake helpers.
- Stale docstrings and comments fixed; layout constants used for the fused
  layouts and their large-input capacities; unused helper / parameters dropped.

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

* style(mega_moe): clear the ruff 0.16.0 findings in the MegaMoE changes

SIM102 on the 13 nested ifs whose outer test is a const_expr (a compile-time
branch around a runtime scf.if; they cannot be merged), suppressed on the
outer line as the other FlyDSL kernels do; B023 by binding the loop values
(test lambdas) or moving the suppression to the line it covers (gemm_util);
C408 dict() calls as literals; RUF059 unused unpacked value; RUF100 unused
suppressions removed.

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

* feat(mega_moe): build the fused routes only for callers that route their calls

MegaMoEV2(routed=True) is a caller that passes forward(max_tokens=...): the
small-input and large-input routes its layout supports are built and the plan
picks one per call. Without it (every caller before this branch) the instance
holds the staged route only, as on main: measured per GPU at construction,
V4.1-Flash EP4 at MTPR 16384 needs 3.10 GiB of symmetric heap instead of 6.78,
V4.1-Flash EP8 5.32 instead of 7.04, V4-Pro EP8 7.44 instead of 7.67.
small_m_mtprs and large_m_enabled still pin a route in or out either way. The
AOT replay builds every profile with routed=True, so the fused kernels stay
prebuilt.

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

* feat(mega_moe): size the large-input payload by source token under dedup_rows

With dedup_rows the large-input dispatch writes a token's row to a destination
once, at row rank * mtpr + token, and GEMM1 reads rows [0, npes * mtpr) only,
so the route-major rows past them were allocated and never touched. The
payload is now sized as the staged route's source-indexed one (npes * mtpr + 1
rows); the kernels take the rows by pointer, so their code is unchanged.
V4.1-Flash EP4 / EP2 keep their own payload and shrink with it.

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

* MegaMoE gemm1: typed vector type and ir_value at the A value-barrier asm

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

* MegaMoE gemm2: typed struct/i32 types, ir_value and default lds_dma_dst args

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

* MegaMoE gemm_util: typed types and ir_value at the in-flight LDS read asm

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

* MegaMoE large_m: typed readfirstlane results and plain i32 ptr_load

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

* MegaMoE small_m: drop redundant wraps/unwraps around readfirstlane, ballot and store_at

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

* MegaMoE stage2: typed readlane/readfirstlane results, Vec store_at, raw-op comments

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

* MegaMoE stage2: fx.shuffle_idx for the 1x32 quant scale broadcast

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

* MegaMoE stage2: fx.coop.warp_max for the 1x32 quant group |max|

Replace the two rocdl.ds_bpermute xor exchanges (xor 1, 2) in _fp8_quant_1x32
with the stable fx.coop.warp_max(width=32 // scatter_vec). On gfx950 it lowers
to v_mov_b32_dpp quad_perm + v_maximum3_f32: no LDS round trips, no lane-address
VGPRs, no lgkmcnt waits (offline ISA: stage2_compact t64x256 sbm128 s_waitcnt
138 -> 92, VGPR -2; never more VGPRs). Same maximumf op and operands, so values
are bit-identical.

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

* MegaMoE gemm_util: fx.shuffle_idx for the row-map subgroup broadcast

Replace the raw fx.rocdl.ds_bpermute in _load_row_map_subgroup with the stable
fx.shuffle_idx(packed, source_lane, 64). Width 64 and source_lane in [0, 64)
lower to the same ds_bpermute (addr = lane * 4): byte-identical gfx950 ISA in
every kernel at mtpr 16384 and 32768 (indexed_payload, the only user).

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

* MegaMoE: name the slower/missing API at the kept raw LDS-read and cvt sites

Comment-only. AS2RLoader.load_operand_in_flight keeps its inline-asm
ds_read_b128 pair: every compiler-visible LDS read form drains the in-flight A
LDS DMA (vmcnt(0) vs vmcnt(7)). The stage2 fp8/u8 quant keeps the raw
cvt_scalef32_pk_fp8_f32 op and the cvt.pk.u8.f32 intrinsic: the typed/fx
alternatives either do not lower or add VALU per pair/byte (offline gfx950 ISA).

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

* MegaMoE gemm1: drop the inline-asm value barrier on the a_ahead>1 A queue

The empty "=v,0" asm claimed LLVM would otherwise fold the queued A load + LDS
write into an LDS DMA; on FlyDSL 0.5.3 it does not (offline gfx950: buffer_load
... lds count 36 = 36, ds_write_b128 84 = 84). The asm itself was an over-wait:
reading the registers forced s_waitcnt vmcnt at the start of the consuming
step, so 190-198 MFMA / 560-592 ds_read / ~195 buffer_load issued behind A-load
completion; without it the wait lands right before each ds_write (0 / 0 / 0).
rocdl.sched_barrier(0) over-waits more; sched_barrier(0x78F) equals plain removal.

Only the la2_ga2 small_stage1 kernels change (v41 EP4 bucket 1, EP8 bucket 4):
10625 -> 10613 / 10448 -> 10366 / 12855 -> 12789 instrs, v_mov -42..-62, VGPR
439..443, occupancy unchanged. The a_ahead=2 depth is kept (72/84 A loads still
cross one barrier). Kept as a separate commit: the la2/ga2 tunes in
mega_moe_config.py were timed with the asm, so A/B on MI355 before merging.

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

* MegaMoE stage2: fx.coop.warp_max for the lean 1x32 quant group |max|

Replace the two dpp_xor_f32 steps (xor 1, 2) in _fp8_quant_1x32_lean with the
stable fx.coop.warp_max(width=4), as already done for _fp8_quant_1x32, and drop
the now-unused dpp_xor_f32 import. FlyDSL lowers width 4 to the same
quad_perm[1,0,3,2] / quad_perm[2,3,0,1] DPP moves and maximumf; only the DPP
`old` operand becomes a -inf constant (never read with an exact quad xor), so
values are bit-identical. Offline gfx950 ISA: only the s2bm64 large_stage1
kernels change, same non-nop instruction count / waitcnt / VGPR / spills,
4 fewer hazard s_nop.

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

* MegaMoE gemm2: say why the A-scale LDS reads stay inline asm

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

* MegaMoE gemm1: async LDS DMA A copies instead of inline-asm A reads

Replace AS2RLoader.load_operand_in_flight (two inline-asm ds_read_b128 +
s_waitcnt lgkmcnt(0), unpacked with llvm.extractvalue) by the plain
load_operand view load, and copy A to LDS with the async LDS DMA atom
fx.rocdl.cdna4.BufferLoadAsyncLDS128b (as gemm/mxscale_preshuffle.py does).
The compiler does not make LDS reads wait for async copies, so a K-step's first
A read no longer drains the next step's A copy into the other buffer; every
read of a copied buffer already follows an explicit fx.rocdl.s_waitcnt +
barrier (prologue / closing wait_lds_barrier). The flag goes to all three
ATileLoaders (main, short, fold). Knob a_asm_reads -> a_async_lds, spec key
g1_a_asm -> g1_a_async; the three V4.1-Flash fused-config digests in
test_mega_moe_gfx950_route_plan change only by that field name.

Offline gfx950 ISA (v41_ep4/ep2 large_stage1): same buffer_load...lds issue
order, no new vmcnt on in-flight A copies (99 = 99 LDS reads under an
in-flight copy), K-loops 212/234/138/102 -> 198/219/132/98 instructions,
s_waitcnt 25/28/16/10 -> 19/22/12/7; VGPR/spills/scratch unchanged (ep8 VGPR
spills 55 -> 57, outside the hot loops). Other kernels ISA-identical.

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

* MegaMoE gemm2: typed LDS loads for the A-scale reads instead of inline asm

Replace the inline-asm ds_read_b32 scale reads, the tied-operand
s_waitcnt lgkmcnt asm and the llvm.StructType / llvm.extractvalue unpacking of
the a_scale_lds path with lds_vec_load (fx.ptr_load on the LDS pointer); the
compiler now counts lgkmcnt for them itself. Two rocdl.sched_barrier(0) pin the
order: scale reads ahead of the A operand reads, and the next A LDS DMA issued
before the first MFMA's wait (the round-1 API version issued it after, 0.5-1.6%
slower on V4.1-Flash EP8). unroll=1 keeps the K loop rolled (otherwise fully
unrolled, VGPR spills 51 -> 62).

Offline gfx950 ISA (s2bm64 large_stage1, v41_ep2/ep4/ep8): order after the
barrier S S A*20 DMA*3 wait MFMA as with asm; GEMM2 K-loop 154 -> 141
instructions (151 on ep8), s_waitcnt 11 -> 10; first-MFMA wait vmcnt(6)
lgkmcnt(13) vs vmcnt(4) lgkmcnt(13); VGPR spills -1, scratch -4 B.

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

* MegaMoE stage2: typed fx.rocdl converts for the 1x32 FP8 / u8 quant packing

Replace the raw ODS rocdl.cvt_scalef32_pk_fp8_f32 (no fx wrapper in FlyDSL
0.5.3) in _fp8_quant_1x32 / _fp8_quant_1x32_lean and the
llvm.call_intrinsic("llvm.amdgcn.cvt.pk.u8.f32") of the route_i8 path:
- FP8: multiply by the exact power-of-two inverse scale 2^(127 - e8m0), then
  fx.rocdl.cvt_pk_fp8_f32 (one RNE, bit-identical for finite inputs); the
  low-half convert seeds its tied `old` with its own input bits, so no zero
  seed is materialized.
- u8: x = v * inv + 128 as before, round-to-nearest-even via + 2^23, low bytes
  gathered with two fx.rocdl.perm_b32 (selector 0x0C0C0400) + v_lshl_or. The
  scale bounds x to [1, 255], so the v_cvt_pk_u8_f32 clamp never triggers.

Offline gfx950 ISA: only scatter-epilogue VALU grows (v41 large_stage1 +24,
v4pro large_stage1 +36, stage2_compact +31..+112 instructions); MFMA K-loops,
s_waitcnt counts, VGPR, VGPR spills and scratch unchanged.

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

* MegaMoE gemm: const_expr/ceildiv cleanup, srcmap and A-row DMA via buffer views

C1: drop redundant fx.Int32 wraps in gemm_util, const_expr on the
compile-time ternaries in gemm1/gemm2, a_scale_lds_rounds() helper for the
A-scale DMA round count.
C3: load_row_map indexes a flat ptr_buf_tensor srcmap (row_map["srcmap"] =
ptr_buf_tensor(addr, fx.Int32) in large_m/small_m); gemm_util no longer
imports the fused_gemm raw buffer helpers.
C5: _store_quant_vec8_fused builds its ptr_buf_tensor directly (no dummy
tile_view). The d0..d5 shifts stay: fx.crd2idx emits div/mod (+40..+360
instrs).
C7: issue_a_fold_rows_dt / issue_a_scale_lds_dt read through a structured
(1, rows, 16B-chunk) buffer view. The LDS destination keeps lds_dma_dst: a
typed LDS pointer adds an s_waitcnt vmcnt inside the GEMM2 K-loop.
C8 (K-loop scale reads) unchanged: a typed i32 pointer adds a v_add per step.

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

* MegaMoE large_m/stage2: buffer views, Stage2Meta LDS tables, cached stage1 launch

C1: ceildiv for the manual ceil-divisions, fx.block_idx.x >> 3 without the
extra wrap, torch_stream instead of the _torch_stream alias,
fx.rocdl.s_waitcnt spelling in stage2; large_m uses gemm2's
a_scale_lds_rounds().
C3: large_m loads/stores go through ptr_buf_tensor + buf_copy_load/store
(cache modifiers kept) instead of _buffer_load/_buffer_store/_make_buffer*.
C4: presend/batch_rows token-row copies index a 16-byte-unit _token_row view.
C5: offset_is_bytes removed: stage2 peer stores index units (element stride
with elem_view_stores), the scale-stage store is an Int8 view, and
_send_staged_scales moves whole 16-byte groups (ceildiv(nbytes, 16) OOB
sentinels; asserts N_OUT and p2p_row_nbytes are 16-byte multiples).
C6: Stage2Meta carries the packed/weight/peer/flag LDS tables as i32 byte
offsets from the pool base (typed pointer offsets regressed BM64 stage2:
+98 instrs, +30 waits, 9 sgpr spills); control words are named CTL_*
indices off recast_iter(Int32, A_scale.ptr); send_cnt/send_slots are
recast_iter(Int32, pool) + 4 / + 16 with fx.atomic_add(workgroup).
C9: bind_mega_moe_stage1() compiles and builds the fixed launch args;
LargeMRuntime caches the bound launch per (config, layer slot), cleared by
bind_weights; the per-call path only adds x/topk_ids/wts/scales/cur_tok.

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

* MegaMoE small_m: buffer views, typed plan arrays, prebuilt launchers

C1: block_idx shift without the extra wrap; const_expr on the plan_wt and
cut_tiles ternaries.
C3: every _make_buffer_from_addr/_buffer_load/_buffer_store use (dispatch
table, parity/expected loads with SC0_SC1, work_head/group_done resets,
g2_peer_base) is a ptr_buf_tensor index or buf_copy_load/store with the
same cache modifier.
C4: dedup and non-dedup token-row copies index a 16-byte-unit row view;
route prefetch, payload, plan-count, finalize and combine-tail views are
built once.
C6: plan_tab becomes typed plan_incl / plan_count arrays (same offsets and
LDS bytes, no hand-written plan_chunks*256). Access still goes through
lds_typed_ptr: indexing the arrays regressed the hu_la2 tok_done kernels
(+21 instrs, +15..17 waits, GEMM1 MFMA layout changed). p2p_scatter_epilog
takes meta=Stage2Meta(pool base, ...); the legacy absolute lds_*_off
keywords and _absolute_lds_meta are removed from stage2.
C9: SmallMRuntime builds its per-config launchers once and calls
_run_compiled / _preload_compiled directly; the module-level
run_mega_moe_stage1 wrapper and _s1_mega are gone.

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

* MegaMoE host: ceildiv, trim tuning history, drop op._sym, resolve stream once

C1: ceildiv in group_major_capacity, FlyDSLDispatchGroupMajorOp.max_blocks
and stage1_output_nbytes.
C2: mega_moe_config tuning-history comments (percentages, per-bucket
measurements) reduced to one-line rationale per knob; FusedStage1Knobs /
FusedStage2Knobs stay the single knob reference. FlyDSLDispatchGroupMajorOp
._sym removed; op, v2, large_m and small_m call _zeroed_sym directly. The
duplicate check_forward_inputs in v2._forward_route only runs on the staged
route (the fused runtimes check their own inputs).
C9: v2 _forward_route / forward_prequant resolve the stream once; with
stream=None they pass torch.cuda.current_stream() without entering a
stream context, and the staged route hands the resolved stream to
_run_joint and compact prepare.

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

* MegaMoE: drop the unused raw buffer helpers from mega_moe_fused_gemm

C3 tail: _make_buffer, _make_buffer_from_addr, _buffer_load and
_buffer_store have no callers left after the gemm, large_m and small_m
buffer-view migrations.

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

* Revert "MegaMoE gemm2: typed LDS loads for the A-scale reads instead of inline asm"

This reverts commit 8c2e19cb69e9732c1b922d4d1bd618bd15d1f152.

* Revert "MegaMoE gemm1: async LDS DMA A copies instead of inline-asm A reads"

This reverts commit 775fbc0e3480a955f65c023fe34403769ff5dc76.

* MegaMoE stage2: one fused multiply-add per pair for the offset-u8 scaling

v * inv_scale is an exact power-of-two scaling below 128 in magnitude, so
fma(v, inv_scale, 128) rounds once where the separate add rounded.

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

* MegaMoE: sort imports for ruff 0.16 (I001)

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

* MegaMoE gemm1: async LDS DMA A copies instead of inline-asm A reads

The compiler does not make an LDS read wait for an async LDS DMA, so the
K-step's A operand reads go through the plain load_operand without
draining the next step's copy. Bitwise-identical output; V4.1-Flash
large-input kernel within 1% on EP4/EP8, up to 3% slower on EP2 at
4096+ rows a rank (different compiler schedule).

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

* MegaMoE gemm2: typed LDS loads for the A-scale reads instead of inline asm

lds_vec_load plus sched_barrier pins replace the ds_read_b32 / s_waitcnt
inline asm; the K loop stays rolled. Bitwise-identical output.

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

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
GwilliamHu added a commit to ROCm/aiter that referenced this pull request Nov 26, 2026
…e route switch

Remove MegaMoEV2.set_large_m_enabled(), the large_m_enabled constructor argument and the _large_m_choice state.
forward(max_tokens=...) already picks the route of every call (MegaMoEBundlePlan.route_for): on a routed instance
a call with max_tokens takes a fused route on every fused layout, and a call without it keeps main's staged route
(fixed-slot or compact), as it did while set_large_m_enabled() had not been called. routed=True builds the
large-input route wherever the layout and capacity support it; routed=False keeps the staged instance of main.
A second switch could only send a call with max_tokens to the staged route; MegaMoEBundlePlan.route_for drops its
large_m exclusion with it.

The only external user was the unmerged SGLang PR sgl-project/sglang#47065, written against an older interface.
The multi-GPU tests take their staged reference from a call without max_tokens, and the size suite and the
benchmark pin their plan through routed / small_m_mtprs.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
GwilliamHu added a commit to ROCm/aiter that referenced this pull request Nov 27, 2026
…e route switch

Remove MegaMoEV2.set_large_m_enabled(), the large_m_enabled constructor argument and the _large_m_choice state.
forward(max_tokens=...) already picks the route of every call (MegaMoEBundlePlan.route_for): on a routed instance
a call with max_tokens takes a fused route on every fused layout, and a call without it keeps main's staged route
(fixed-slot or compact), as it did while set_large_m_enabled() had not been called. routed=True builds the
large-input route wherever the layout and capacity support it; routed=False keeps the staged instance of main.
A second switch could only send a call with max_tokens to the staged route; MegaMoEBundlePlan.route_for drops its
large_m exclusion with it.

The only external user was the unmerged SGLang PR sgl-project/sglang#47065, written against an older interface.
The multi-GPU tests take their staged reference from a call without max_tokens, and the size suite and the
benchmark pin their plan through routed / small_m_mtprs.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
coderfeli pushed a commit to ROCm/aiter that referenced this pull request Nov 29, 2026
…nce optimizations, capacity 32768, rank-shared AOT (#8623)

* tune(mega_moe): 256-wide small-input GEMM1/GEMM2 tiles for EP8 V4.1-Flash at 16 and 32 tokens

Half the GEMM1 tiles and GEMM2 blocks, each streaming a longer weight slab.
Measured on 8x MI355X (EP8 V4.1-Flash a8w4, MTPR 1024, one CUDA graph per
distinct input, max over ranks): -2..-8% per call at 16-32 rows a rank
under uniform, zipf and hot routing. Bitwise identical outputs (asmval, 142
points). The EP8 fused-config digest follows.

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

* perf(mega_moe): send a dedup row before its expert-counter atomic

A deduplicated token row goes to its destination's token-row region, whose
place does not depend on the expert offset the counter atomic returns, so the
row push is issued first and overlaps the atomic's remote round trip.
Bitwise identical outputs (asmval, 142 points: decode MTPR 128 and prefill
MTPR 16384, uniform / zipf / hot / invalid-slot routing, uneven and idle
ranks). Measured with the next three commits: 1-8% per call at 16-512 rows a
rank (EP8 V4.1-Flash a8w4, MTPR 1024; e.g. 512 rows 355.9 -> 344.4 us
uniform, 618.0 -> 587.9 zipf, 1487.4 -> 1417.6 hot).

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

* perf(mega_moe): quantize each token row once in the small-input dispatch

With dedup_rows a producer wave takes a token instead of a route: it loads
and quantizes the row once and pushes it to each distinct destination rank
of its top-k (one lane a route; v_readlane keeps the remote pointers
scalar), and the top-k counter atomics go out from one instruction. Before,
each route's wave quantized the row again. Bitwise identical outputs
(asmval, 142 points); part of the 1-8% measured with the neighbouring
dispatch and entry changes.

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

* perf(mega_moe): interleave an expert's slots over its small-input m-tiles

m-tile t of an expert with nt m-tiles takes its slots t, t + nt, ..., so the
rows of a GEMM2 tile come from many source ranks and its returns spread over
their links instead of one. A row's GEMM math and the combine's fixed top-k
order are unchanged, and the slot order within an expert was already decided
by racing atomics: bitwise identical outputs (asmval, 142 points); part of
the 1-8% measured with the neighbouring dispatch and entry changes.

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

* perf(mega_moe): small-input entry without the ticket atomic and epoch gate

Protocol change: a launch no longer takes an entry ticket (one atomic per
CTA) or waits at an epoch gate. Roles go by block id (owner, producers,
consumers), and every CTA reads the entry state past L2: the previous
launch's epoch (DispatchSlot.LAUNCH_EPOCH), parity and expected source
value, and advances them itself. The last WG of a launch (the combine's last
ticket, when every CTA is past its reads) zeroes the work and producer
counters and stores this launch's epoch, parity and expected value for the
next one; stream order puts those stores before the next launch's loads.
Cross-rank buffers written before the plan stay parity double-buffered, so
no handshake is needed. The names follow (launch_epoch, cta).

The op test's epoch-wrap case now presets the runtime's launch-epoch word
(the entry ticket counter it preset is gone); the next launches still cross
the 32-bit wrap. Bitwise identical outputs (asmval, 142 points); part of the
1-8% measured with the dispatch changes before it.

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

* feat(mega_moe): EP8 small-input GEMM1 pairs an expert's 32-row m-tiles into 64-row units

On a rank that reads W1 through the cache (a hot expert or many routed rows), each GEMM1 unit of an expert
with more than one m-tile runs a pair of its interleaved m-tiles (2j, 2j + 1) as one 64-row tile, so its W1
slab is read once per 64 rows instead of once per 32. The local plan keeps a per-expert unit-group table
next to its m-tile table; a unit's plan comes from one ballot lookup over it (shared with the m-tile lookup).
The XCD slices of the GEMM1 unit space stay equal in m-tile units (a pair's units weigh two m-tiles'), so an
XCD holding a paired hot expert does not take more rows than the others; a rank that does not pair skips
those lookups. GEMM2 keeps its m-tile units and slices.

V4.1-Flash EP8 configs: pair_tiles at 64 and 128 tokens. Measured on 8x MI355X (a8w4, MTPR 1024, 3 ABBA
rounds against the parent): hot -11.7% at 64 rows a rank and -17.3% at 128, zipf -1.0% / -4.2%, uniform and
the other sizes within +-0.2%. Bitwise identical outputs (asmval, 142 points; MFMA order per accumulator
unchanged).

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

* feat(mega_moe): EP8 V4.1-Flash large-input route at every capacity

V41_FLASH_EP8_LARGE_M_MTPRS lists every large-input capacity (1024..16384).
The fault that kept capacities 1024-4096 on the staged route came from
another process's kernels sharing the GPUs, not from the kernel: on exclusive
GPUs the large-input route at 1024, 2048 and 4096 passes the asmval large
points three times each without a fault. An EP8 instance below 8192 now
serves prefill through the fused route (768 rows a rank at capacity 1024:
354 us vs 518 us staged, uniform). The config docstring and the AOT README
follow.

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

* feat(mega_moe): serve A4W4 decode calls through the fused small-input route

An A4W4 MegaMoEV2(routed=True) on a FUSED_LAYOUTS layout (EP8 DeepSeek-V4-Pro,
EP8 / EP4 / EP2 DeepSeek-V4.1-Flash) now builds the small-input runtimes and
sends calls of up to 512 rows a rank through the fused dispatch + GEMM1 +
GEMM2 + combine kernel; above that A4W4 takes the staged route. The
large-input route stays A8W4 (LARGE_M_QUANTS).

- The producers quantize each bf16 row to MXFP4 (E2M1 + E8M0 per 32 values),
  bit-identical to per_1x32_mx_quant(quant_mode="fp4") of the staged route,
  with the MXFP8 lane mapping (16 values a lane, a scale group per lane pair):
  a lane stores 8 payload bytes per 1024-value chunk, so rows of 5120 / 7168
  values tile exactly. The dedup_rows producers (one quantization a token)
  take the same path.
- GEMM1 reads FP4 A (128-byte K-steps), also through the dedup_rows srcmap.
- The GEMM1 output stays FP8, so GEMM2 and the combine are unchanged; the
  shared GEMM1-output arena is sized per route dtype.
- Kernel names gain _afp4 for A4W4 only; the A8W4 kernels are unchanged.
- The V4.1-Flash AOT profiles ship A4W4 as well.

The A4W4 small-input kernels use the A8W4 small-input tunes unchanged.

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

* test(mega_moe): run the routes suite with --quant a4w4

The routes suite builds the instance with --quant (A4W4: small-input and
staged routes, gated at relL2 0.25 against the fp32 reference and the staged
route).

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

* refactor(mega_moe): share the MX quant helpers with the fused small-input producers

Review follow-ups on the A4W4 small-input route:
- The E8M0 scale comes from quant_utils.emit_mx_e8m0_scale (RoundUp) in
  per_1x32_mx_quant and in the fused producers' _quantize_row_mx; quant.py
  gains pack_mx_fp4_words, which both use for the FP4 words.
- The payload store derives a lane's word count from the quantized row; the dead
  fz_n_i32 argument of emit_direct_fixed_slot_payload and TILE_K_BYTES go.
- SmallMRuntime / LargeMRuntime gate on FUSED_QUANTS / LARGE_M_QUANTS; the
  small-input payload capacity takes the A dtype (MegaMoEV2 drops _quant).
- The route-plan test covers MTPR 128 and 8192, pins the payload-arena size, the
  staged A4W4 row bytes and the FP8 GEMM1 output, and reuses the shape dicts.
- README: fused small-input route a8w4 or a4w4, large-input a8w4 only; the
  V4.1-Flash defaults build both quants.

ISA: the small-input kernels (a8w4 and a4w4) are byte-identical to the parent's
(offline gfx950 build of every token bucket).

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

* refactor(mega_moe): let the fused GEMM1 short and fold tiles read FP4 A

Prepares the A4W4 large-input route, whose GEMM1 runs the short, mid and
fold tiles (dedup_rows srcmap, async A copies) on packed FP4 rows:

- ATileLoader: an async A copy may end on a partial round (an FP4 fold tile
  of 128 + 32 rows is 1280 16-byte chunks, 2.5 rounds of 512 threads); the
  round runs on its leading waves, and load_row_map points the idle threads'
  rows past the tile at its last row, so the row-arrival wait never spins on
  another tile's rows. Every existing tile copies whole rounds and keeps
  its code.
- build_fused_gemm1: the short / fold tile loaders and MFMAs take the A
  dtype and its row bytes; the row_map path no longer requires 256-byte
  K-steps.

No kernel changes: the A8W4 tiles pass the same values.

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

* feat(mega_moe): serve A4W4 prefill calls through the fused large-input route

An A4W4 MegaMoEV2(routed=True) on a FUSED_LAYOUTS layout now also builds the
large-input persistent kernel at the capacities large_m_mtprs_for() gives the
layout (1024..16384 for EP8 DeepSeek-V4-Pro and EP8 DeepSeek-V4.1-Flash, 8192
and 16384 for EP4 / EP2 DeepSeek-V4.1-Flash), so a call of 513 rows a rank up
to the capacity is fused like A8W4 instead of taking the staged route.
LARGE_M_QUANTS goes: both fused routes take FUSED_QUANTS.

- The input quant kernel writes MXFP4 rows (model_dim / 2 bytes, the same
  E8M0 scales); the dispatch moves them in 64-lane column blocks of 1024
  values, a dwordx2 a lane (dwordx4 for FP8), in the presend and batched
  payload copies; the route-major copy takes any dwordx4-aligned row.
- GEMM1 reads FP4 A (128-byte K-steps) in every tile shape: main, short,
  mid and fold, also through the dedup_rows srcmap (x_bytes from the FP4
  row size).
- The GEMM1 output stays FP8, so GEMM2 and the combine are unchanged; the
  shared GEMM1-output arena is sized for the large-input route's FP8 rows.
- LargeMRuntime sizes its payload, quant buffers, input checks and AOT
  preload by the A dtype; _dispatch_dtype moves to mega_moe_stage1 for both
  fused runtimes.
- Kernel names gain _afp4 for A4W4 only; the A8W4 kernels are unchanged.

The A4W4 large-input kernels use the A8W4 large-input tunes unchanged. The
route-plan test follows: A4W4 routed instances of the four fused layouts take
the large-input route at MTPR 8192 and 16384 (FP4 payload rows, uint8 quant
buffer, FP8 GEMM1 output held by the shared arena), the large-input buffers
fit 32-bit offsets for both quants, and the A4W4 large-input kernel runs the
A8W4 config and Stage2 spec with row copies and GEMM1 tiles of whole column
blocks and waves.

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

* test(mega_moe): cover the A4W4 large-input route

- AOT: the V4.1-Flash EP4 / EP2 / EP8 A4W4 jobs include the large-input
  MTPRs (8192, 16384).
- Multi-GPU: the A4W4 large-input route is compared with the staged route
  to --rtol (FP8 vs FP4 GEMM1 output), in the main comparison, layer-slot
  stress and skewed route switch; the SiLU gate checks the instance's quant.
  The fused-vs-staged gates of the size suite's main comparison and the
  routes suite also fail on any row off by more than half its norm (a
  corrupted row the tensor's relative L2 would hide).

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

* feat(mega_moe): per-quant fused configs for A4W4 tuning

select_fused_config takes the quant: A4W4 starts from a layout's A8W4
config and goes through _tune_a4w4_small / _tune_a4w4_large (identity for
now), so the A4W4 small- and large-input routes can take tunes of their own.
The runtimes select their configs with their quant, and the payload-sharing
classmethods (indexed_payload, payload_capacity, ends_all_ranks) take the
activation dtype, since a tune may change the protocol knobs they read.
No kernel changes.

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

* feat(mega_moe): per-bucket large-input configs and a small-input split-tail knob for A4W4 tuning

Large-input route: a call launches the config of its EP-wide max_tokens
(MegaMoEV2.forward / forward_prequant pass it through; None keeps the
capacity's config), so _tune_a4w4_large takes the token bucket and can
change the launch geometry per row count, as the staged path does. The
knobs that size the runtime's buffers or set what the routes share
(large_m_runtime_knobs: P2P quant, dedup rows, bucket pairs, combine token
wait, row alignment, scale staging) must agree across the buckets of a
capacity; LargeMRuntime checks it, sizes the scale staging buffer for the
largest bucket config and preloads every distinct bucket config. A8W4
still runs one config per capacity.

Small-input route, FusedStage1Knobs.g1_split_tail (off by default): with
tile_n 256, up to N units of an XCD slice's partial last GEMM1 round run as
two tile_n / 2 halves, as many as that round leaves CTAs idle; GEMM2
readiness counts half units. It enters the small-input kernel name only when
set (not with pair_tiles). The kernel's GEMM1 builds share one argument list.
The small-input kernels are byte-identical to the parent's (offline gfx950
build); on 8x MI355X per-bucket large configs (V4-Pro EP8) and g1_split_tail
(V4-Pro EP8 small-input kernel) run correctly (--check-time-acc).

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

* feat(mega_moe): A4W4 tune for EP8 DeepSeek-V4-Pro fused routes

A4W4 on EP8 V4-Pro now takes its own small- and large-input tunes instead of
the A8W4 ones (A8W4 configs and every other layout are unchanged).

Large input (routes suite, MTPR 16384, speedup = staged / fused):
  rows      513   1024  2048  4096  8192  16384
  before   0.871 0.935 0.995 0.953 1.013 0.982
  after    1.307 1.365 1.384 1.283 1.246 1.182
The EP4 V4.1-Flash knob set without the parts V4-Pro's dims cannot take
(fold_tail / mid_tail_rows, GEMM2 fold_tail / nt_single / ascale_lds /
early_p_mid), cached W1, payload_min_blocks 4, and early_p 2 from the
8192-row bucket.

Small input (MTPR 512):
  tokens     1     16    64    128   256   512
  before   1.538 1.584 1.614 1.628 1.295 1.083
  after    1.749 1.621 1.637 1.646 1.304 1.124
The EP8 V4.1-Flash small tune (with its 256-wide GEMM1/GEMM2 n-tiles at 16
tokens) without the parts measured on V4.1-Flash only (its 256-wide GEMM2
tiles at 32 tokens and its GEMM1 m-tile pairs), cached W1 at 1 token, and
256-wide GEMM1 n-tiles with g1_split_tail 64 at 256/512.

The A4W4 large-input test now checks the A4W4 config and compares the payload
geometry with A8W4 only while the runtime-sizing knobs agree (the V4-Pro A4W4
tune dedups dispatch rows).

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

* feat(mega_moe): A4W4 tune for EP8 DeepSeek-V4.1-Flash fused routes

A4W4 on the EP8 V4.1-Flash layout takes its own small- and large-input
tunes (_tune_v41_flash_ep8_a4w4_small / _large) on top of the A8W4 ones,
selected from the A4W4 hooks; A8W4 configs are unchanged.

Small input: bucket 1 cached W1; bucket 16 256-wide GEMM1/GEMM2 tiles with
g1_split_tail 64; buckets 256/512 256-wide GEMM1 tiles; the A8W4 tune's
GEMM1 m-tile pairs at 64 / 128 tokens and 256-wide GEMM2 tiles at 32 carry
over. Large input: buckets >= 2048 payload_min_blocks 4; 512/1024 keep the
A8W4 tune.

Measured on gfx950, 8 ranks, routes suite, MTPR 16384 (staged/routed,
uniform; measured before this series carried the A8W4 small-input
changes): small 1.31-2.37x -> 1.37-2.49x, large 1.22-1.66x ->
1.25-1.68x; zipf 1.0 and all-to-rank-0 routing do not regress.

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

* tune(mega_moe): A4W4 EP4 V4.1-Flash fused small/large configs

Small: tile_n 256 + g1_split_tail 64 at 64/256 tokens, stream_w + early_p 6
at 512. Large: cached W1, 64 producer CTAs and early_p 2 from 4096 tokens.
Measured on gfx950 (4 ranks, routes suite, MTPR 16384); A8W4 unchanged.

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

* tune(mega_moe): A4W4 EP2 DeepSeek-V4.1-Flash fused small- and large-input configs

Small-input: cached W1 at 1 token, 256-wide GEMM1 tiles at 64 tokens.
Large-input: presend over 16 local experts. A8W4 configs unchanged.

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

* test(mega_moe): A4W4 fused-config digests and quant-parametrized protocol checks

- A4W4 fused-config digests for EP8 DeepSeek-V4-Pro and EP8 / EP4 / EP2
  DeepSeek-V4.1-Flash: every small-input bucket at MTPR 256 and 512 and every
  large-input capacity of the layout at each of its token buckets.
- The *_small_m_buckets_share_one_protocol tests run for a8w4 and a4w4.
- EP8 V4.1-Flash pairs an expert's 32-row m-tiles at 64 and 128 tokens for
  either quant (the A4W4 tune keeps the A8W4 one there), on the interleaved
  local plan the pairing needs.
- The A4W4 large-input config geometry is checked at every capacity a layout's
  large-input route serves (1024..16384 on EP8).

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

* feat(mega_moe): V4.1-Flash EP4 / EP2 large-input route at every capacity

Every fused layout now builds the large-input kernel at every capacity in
LARGE_M_MTPRS (1024..16384), as EP8 V4.1-Flash already did since 6420f64;
large_m_mtprs_for() and the per-layout V41_FLASH_EP*_LARGE_M_MTPRS lists go.
EP4 and EP2 reuse their existing large-input tunes unchanged: the tunes do not
depend on the capacity (A4W4 varies by token bucket only), so a capacity below
8192 launches, at each bucket, the config the 16384 capacity launches there.

The EP4 fault once seen at 1024-4096 is believed to be the same co-residency
misdiagnosis as EP8's (another process's kernels sharing the GPUs); GPU
revalidation of EP4 / EP2 at 1024, 2048 and 4096 is pending.

Offline: the AOT replay builds EP4 and EP2 at MTPR 1024 / 2048 / 4096 for a8w4
and a4w4 (36 jobs ok, --check 36 ok). Rank-0 large-input kernel spills vs the
16384 kernels: a8w4 keeps sgpr 47 / vgpr 50 / scratch 188 everywhere; a4w4
keeps sgpr 47 / vgpr 31 / scratch 112 at EP4 2048 / 4096, but EP4 1024 and EP2
1024 / 2048 / 4096 spill one more vgpr (vgpr 32, scratch 116 vs 31 / 112).
The shipped AOT MTPR list is unchanged; its comment and the README follow.

Tests: the capacity tests run every layout over LARGE_M_MTPRS, a new test pins
that each capacity's configs equal 16384's, the A4W4 digests stay over the
capacities they pinned, and the offline routed instance adds MTPR 1024 / 4096.

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

* feat(mega_moe): send every call the small-input route cannot take to the large-input route

MegaMoEBundlePlan.route_for drops the max_tokens >= LARGE_M_MIN_TOKENS bound
of the large-input route: on an instance that builds it, a call the
small-input route does not take (forward_prequant, a part without 256 CUs, a
max_tokens above the reduced small_m_mtprs) runs fused instead of staged. With
the large-input route at every capacity of every fused layout, a routed
instance at a power-of-two MTPR up to 16384 now stages no call that passes
max_tokens.

Such a call of fewer than LARGE_M_MIN_TOKENS rows launches the
LARGE_M_MIN_TOKENS config, which large_m_buckets() already builds, so no new
kernel is compiled; every large-input tune keeps that config up to 1024 rows
(a test pins it), so it is also the config of the call's own bucket. Calls of
513 rows or more take the same route and config as before.

Tests: an exhaustive sweep (4 fused layouts x a8w4 / a4w4 x MTPR 1..16384 x
every max_tokens) asserts no routed call stages and every large-input call
launches a built bucket, and that without the small-input route the
large-input route takes every call from MTPR 1024; the route-exclusion and
routed-instance tests cover prequant and reduced small capacities.

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

* fix(mega_moe): keep the large-input 8-bit combine offset off the gfx950 packed high-dword read

The combine tail of a route_i8 large-input kernel subtracts 128 x the scale
sum from each unit's four accumulators. Written as a vector product, the
compiler packed two units' offsets into one register pair and subtracted the
second one with v_pk_add_f32 op_sel:[0,1]: the low half reads src1's high
dword, the pattern that reads 0 in lanes 48-63 on gfx950 while another wave of
the SIMD runs MFMA (#7818). Each unit's offset is now one scalar
product subtracted value by value, so it sits in the low dword of its own
register and the packed subtract broadcasts it with op_sel_hi only.

Same operations in the same order: bitwise identical results. Offline gfx950
ISA of the V4.1-Flash EP8 (1024, 16384), EP4 and EP2 (16384) large-input
kernels, A8W4 and A4W4: 4 -> 0 op_sel:[x,1] packed-f32 instructions each,
same VGPR/SGPR counts, 3-5 fewer instructions. Found in BinDing's
0055824 (AITER_MEGA_LARGE_V3=qf), which used inline v_sub_f32 instead.

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

* perf(mega_moe): spread a few-token launch's dedup sends over each producer's waves

With dedup_rows one producer wave takes a token: it quantizes the row once and sends it to every destination
of its top-k. At 1-4 tokens a rank that leaves the other waves of each producer CTA idle and puts all of a
token's remote rows behind one wave. A launch of at most _SPREAD_MAX_TOKENS (4) tokens a rank now has every
wave of the token's producer CTA quantize it and send, count and publish the routes of its own top-k slots
(slot j: wave j % num_waves). The writes each destination sees, and the protocol (one producer CTA a token,
the same done counts), are unchanged; the choice is rank-local.

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

* perf(mega_moe): fused small-input GEMM2 stores BF16 P2P rows with every lane of the workgroup

The fused small-input kernel's GEMM2 epilogue scattered one weighted BF16 row per wave store with
BN // 8 lanes active (32 of 64 at BN 256), each row behind a readfirstlane chain for its route,
weight and peer base. On BF16 launches (fp8_rows == 0) every lane now stores 16 bytes of one row,
64 // (BN // 8) rows per store (as amd-kernels PR #12's fused EP8 return path), through a global
store at its own peer address; the route/weight/peer/value LDS reads of all passes are issued
before the first store. FP8 launches (with their BF16 head rows) keep the per-wave rows.

Each element is still f32(acc) * f32(weight) rounded once to BF16 at the same destination byte,
so the P2P rows and the combine output are bitwise unchanged. Lean / tok_done epilogues are
untouched (wide_bf16 is off for them).

V4.1-Flash EP8 decode (MTPR 512, ABBA, 1-512 rows x uniform/zipf/hot): 0 points slower;
8 rows uniform/zipf 1.7-2.2% faster and 192/256 rows uniform 1.1-2.4% faster, both quants.

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

* tune(mega_moe): EP8 V4.1-Flash 8-column GEMM1 epilogue from 16 small-input tokens

Both quants, from the 16-token bucket: the per-tile output resource with the 8-column GEMM1 quantize/store pass
(epi_evec 8) and its no-serial-wait form (epi_lean 1; the IEEE SiLU stays, so outputs are bitwise-identical).
ATT of the hot rank at 128 zipf tokens: the 2-column pass costs 49k cycles a wave, 16k of them on its 2-byte
stores. Applied in _tune_v41_flash_ep8_small_both after the A8W4 / A4W4 tunes of the V4.1-Flash EP8 layout only.
Offline gfx950 ISA: 236-248 VGPRs; the a8w4 pair-tile body (64 / 128 tokens) spills 4 SGPRs.

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

* perf(mega_moe): small-input 64-row GEMM2 issues its B loads ahead of the barrier and the A copy

The fused small-input kernel's BM64 / BN256 GEMM2 tiles (256 and 512 tokens) take gemm2_compute_v2's
early_b_load with a_dma_uniform: each K-step's W2 and scale loads go before the barrier and an unconditional
A copy, so the first MFMA waits for them with vmcnt(4) (the copy stays in flight). Before, the A copy was issued
first and the MFMAs waited vmcnt(2) behind it. ATT at 192 uniform tokens: that wait (gemm2.py:92) is
41.1k / 40.5k cycles a wave (9.7% / 9.4%, A8W4 / A4W4). Both quants (GEMM2 reads FP8 A for either).
Offline gfx950 ISA: no new spills; the 32-row tiles (and EP2) compile byte-identical.

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

* refactor(mega_moe): clamp-SwiGLU of the GEMM1 epilogue as a module function

SiluQuantEpilogue's silu(gate) * up with the swiglu_limit clamps becomes gemm_util.silu_mul_f32, so a GEMM1
body with its own epilogue computes the same values. Same operations in the same order: every offline gfx950
small-input kernel (EP8 / EP4 / EP2 V4.1-Flash, EP8 V4-Pro, A8W4 / A4W4, 1-512 tokens) compiles byte-identical.

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

* perf(mega_moe): ring GEMM cores for the fused small-input kernel (ring_core knob, off)

The small-input GEMM1 / GEMM2 K-loops wait on loads they just issued: at 192 uniform tokens ATT shows 66.2k
(GEMM1) and 45.1k (GEMM2) cycles a wave of vmcnt waits against 10.8k / 5.6k in amd-kernels PR #12, whose
loops are issue-bound instead. The new gemm_ring module ports that PR's GEMM core as one unit:

- the K loop is unrolled at trace time (no back-edge register copies), the FP4 weights are the scaled MFMA's
  operand A, and step k + pf's weight loads are spread over step k's MFMAs in the order they are emitted;
- the activation rows reach LDS by async DMA (BufferLoadAsyncLDS128b, asyncmark groups) through an nbuf-stage
  ring of 128-K steps in MFMA fragment order, nbuf - 2 >= pf steps ahead, so a weight wait never drains it;
- GEMM1 runs clamp-SwiGLU and the 1x32 MXFP8 quant in registers (no C-shuffle) and stores its output in the
  fragment order GEMM2's ring copies, with one scale dword per row and K step;
- GEMM2 reads its first pf weight steps and its rows' route ids before the m-tile's ready wait (the first read
  of the ready word goes ahead of them), and drops the CU's L1 at the unit claim, before any of its loads.

FusedStage1Knobs.ring_core = (pf1, nbuf1, pf2, nbuf2) turns it on (kernel name _rc...). It needs 64-row
interleaved m-tiles, 64 GEMM1 columns a wave (tile_n 256) and 256-wide GEMM2 tiles; each wave owns 64 rows x 32
intermediate / 64 hidden columns. Dispatch, plan, unit claims, ready epochs and combine are unchanged; GEMM2
takes its m-tile's expert and rows from the CTA's own plan. The GEMM2 scatter epilogue gains acc_t (transposed
accumulators, 16-byte LDS writes, rows BN + 4 floats apart). Both quants share the code: only GEMM1's activation
differs (FP4 rows: one slot a row tile and step).

No config sets ring_core yet: every offline gfx950 small-input kernel compiles byte-identical.

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

* tune(mega_moe): EP8 V4.1-Flash small-input ring GEMM cores from 64 tokens

Both quants, buckets 64-512 (_tune_v41_flash_ep8_small_both): ring_core (2, 4, 2, 6) on 64-row m-tiles,
256-wide GEMM1 units and 256-wide GEMM2 tiles; 64 and 128 tokens leave their 32-row m-tile pairs (amd-kernels
PR #12 runs its 64-row tier from 49 tokens). GEMM2 weights go 2 steps ahead: with 4 weight loads a step and wave
that is more bytes in flight per CU than the PR's 3 steps of 2 (3 steps spill 12 VGPRs).

Offline gfx950 ISA (FlyDSL 0.5.3), A8W4 / A4W4: 252-256 VGPRs (128 arch + AGPRs), no scratch, LDS 67728 B
(2 CTAs a CU: 135 KiB of 160), 1856 MFMAs (2 x 640 GEMM1 + 2 x 288 GEMM2, unrolled), steady K-loop waits
vmcnt(7-16) where the 64-row bodies they replace wait vmcnt(0-2). Every other layout and bucket compiles
byte-identical. Config digests updated for EP8 V4.1-Flash.

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

* perf(mega_moe): half-height ring GEMM bodies for m-tiles of at most 32 rows

With interleaved m-tiles an m-tile of at most half the 64 rows is its expert's only one. Its GEMM1 unit and GEMM2
tiles run 32-row ring bodies (streamed weights) instead of the 64-row ones: half the MFMAs, activation DMA slots and
epilogue rows. The GEMM2 epilogue takes zero accumulators for the masked upper rows.

EP8 V4.1-Flash on MI350X against the parent of the ring commits (ABBA x2, MTPR 512): 142/142 asmval points bitwise
for both quants; 1-32 tokens within noise; 64-512 tokens zipf / hot -2~-17%. Uniform routing loses at 64-128 tokens
(A4W4 +1.7~2.4%, A8W4 +0.6~1.3%) and wins from 192. Bucket rule: a bucket keeps the ring core when its zipf / hot
gain exceeds its uniform loss (serving routing is skewed, the hot expert takes ~49% of the tokens); that holds for
every bucket of both quants (worst: A4W4 64 tokens, uniform +2.4% against zipf -12.5% / hot -4.0%), so both quants
share the 64-512 ring buckets.

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

* perf(mega_moe): large-input GEMM2 claims ahead and reads m-block classes from LDS

The large-input kernel's GEMM2 loop paid two serial thread-0 chains per
(m, n) unit between its barriers: the claim RMW and, with g2_skip_pad, a
chain of dependent srcmap / tile-row / expert loads that classifies the
claimed m-block (skip, fold its tail, single m-block).

- Every CTA classifies all m-blocks once at GEMM2 entry, one m-block per
  thread, into one LDS byte each in the A-scale bytes GEMM2 leaves unused;
  a claim then reads its m-block's byte. The class reads only plan-final
  rows, so it equals the per-claim result.
- A unit's publish takes the CTA's next claim before its drain, so the
  claim RMW returns while the peer stores retire; the loop head uses it
  (or claims itself after a skipped unit).

Each unit is still claimed once and run by its claimer with unchanged
per-row math, scatter and close protocol, so outputs stay bitwise equal.

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

* refactor(mega_moe): drop the large-input on/off API; max_tokens is the route switch

Remove MegaMoEV2.set_large_m_enabled(), the large_m_enabled constructor argument and the _large_m_choice state.
forward(max_tokens=...) already picks the route of every call (MegaMoEBundlePlan.route_for): on a routed instance
a call with max_tokens takes a fused route on every fused layout, and a call without it keeps main's staged route
(fixed-slot or compact), as it did while set_large_m_enabled() had not been called. routed=True builds the
large-input route wherever the layout and capacity support it; routed=False keeps the staged instance of main.
A second switch could only send a call with max_tokens to the staged route; MegaMoEBundlePlan.route_for drops its
large_m exclusion with it.

The only external user was the unmerged SGLang PR sgl-project/sglang#47065, written against an older interface.
The multi-GPU tests take their staged reference from a call without max_tokens, and the size suite and the
benchmark pin their plan through routed / small_m_mtprs.

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

* fix(mega_moe): small-input co-residency check covers the whole LDS and the pair tiles

The small-input fused kernel needs its whole grid resident (2 CTAs a CU): the combine
reducers spin until every CTA took its ticket. The LDS check counted only the pool, not
the A scales, the work word and the plan tables, and pair_tiles at 64-row m-tiles
(128-row pairs) needs 87440 bytes of LDS and 264 registers (one CTA a CU, a hang).
Check the whole SharedStorage at compile time and reject pair_tiles off 32-row m-tiles
in the config. The check equals the compiled LDS size of every offline gfx950 small-input kernel
(V4.1-Flash EP8 / EP4 / EP2, V4-Pro EP8, both quants, 1-512 tokens, 30608-81040 bytes) except the ring-core
kernels, which it bounds 16 bytes high (67744 vs 67728: their A-scale words are unused). No kernel changes
(the 72 kernels compile byte-identical).

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

* perf(mega_moe): ring GEMM cores for every small-input layout and bucket

Every small-input config (EP8 V4-Pro and EP8 / EP4 / EP2 V4.1-Flash, A8W4 and
A4W4, token buckets 1..512) runs the gemm_ring GEMM1 / GEMM2 cores on 64-row
interleaved m-tiles of the local plan, 256-wide GEMM1 units and 256-wide GEMM2
tiles; an m-tile of at most 32 rows (most of them at the small buckets) runs
the half-height bodies. V4-Pro A8W4 takes the dedup rows and local plan the
ring reads; at V4-Pro's dims the GEMM2 weights go one step ahead (two spill).

To fit every layout without scratch: the kernel allocates no AGPRs (with them
the registers split 128 / 128 and the K loops spill VGPRs or copy operands
between the halves), the pointers and epoch the consumer loops hold across
the GEMMs are SGPRs and GEMM2's other dispatch-table pointers and the combine
peer base are loaded past GEMM1 (held through it as VGPRs, they spill the K
loops), grids of one CTA a CU hint one wave a SIMD (the EP4 4-token kernel
spilled), and the 16-token grids of two CTAs a CU no longer hint one.

Offline gfx950 ISA (FlyDSL 0.5.3), all 144 small kernels (4 layouts x 2 quants
x 9 buckets x MTPR 256 / 512): no scratch, at most 256 VGPRs, at most 68.7 KiB
LDS a CTA (two CTAs a CU fit).

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

* refactor(mega_moe): the small-input kernel keeps only the ring GEMM cores

Every small-input config runs the ring cores (previous commit), so the old
GEMM bodies of compile_mega_moe_stage1 go: the streamed / cached / paired /
split-tail GEMM1 builds, the gemm2_compute_v2 tile runner, their LDS (A-scale
tile, C-shuffle) and resources, the m-tile pair plan and the split-tail work
encoding. What the ring requires becomes the kernel itself: dedup token rows
(the per-route payload dispatch goes) and the CTA-local interleaved plan.

Knobs that no config reads any more go with them: FusedStage1Knobs plan_local,
g2_uniform, g1_lookahead, g1_a_ahead, g1_split_tail, pair_tiles and ring_core
(the ring depths are the kernel's: GEMM2 weights one step ahead at V4-Pro's
model dim), and the small kernel's tile_k, pipe_weights, mfma_amajor,
swizzle_a, async_a_copy, use_tile_resource, epi_evec, epi_lean and
ascale_packed (large-input only now). The small-input tunes keep what still
changes a kernel; the protocol tuple is direct_done, tok_counters,
bf16_head_tokens. The launch drops the unused sorted-id / expert-id / token
count / input-scale arguments, and the fixed slots are 64 rows (the m-tile).

Offline gfx950 ISA, all 144 small kernels vs the previous commit: the same
MFMA and memory instructions (kernel-argument loads and register allocation
differ), no scratch, LDS <= 68.7 KiB a CTA. Math order unchanged.

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

* refactor(mega_moe): drop the shared GEMM helpers' small-input-only paths

With the small-input kernel on the ring cores, the staged Stage1 and the
large-input kernel are the only users of build_fused_gemm1 and its helpers,
and both run do_tile. do_tile_la, the paired-tile runner and _PairEpilogue
go, with build_fused_gemm1's rows_rsrc / lookahead / plan_lookup / a_ahead /
pair_tiles; the A loaders' paired / tx modes, their row_stride and valid-rows
clamps, the epilogue's valid-rows / store-policy overrides, the B-scale load
cache policy and gemm2's valid_rows. _LA_CM moves to gemm_ring, its last user.

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

* perf(mega_moe): 32-row ring m-tiles for the small-input buckets up to 128 tokens an EP group

Up to 128 tokens an EP group (EP8 16, EP4 32, EP2 64 tokens a rank) the
small-input kernel plans 32-row m-tiles and runs only the 32-row ring bodies
(the 64-row kernels carry both heights). The kernel is half the size, and the
experts that hold every token of a skewed launch get twice the GEMM1 / GEMM2
units while those still fit one round of the grid. Per-row math order is
unchanged. The plan CTA's m-tile metadata, sized by 64-row m-tiles, holds the
32-row m-tiles of these buckets too (asserted).

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

* refactor(mega_moe): drop the ring cores' fixed knobs and stale small-input notes

What: make_ring_gemm1 takes no sw_cm / q_cm (every caller passed the same
sc0|nt policy, now gemm_ring's _G1_CM) and _lane_ids no unused wave count;
the small-input finalize drops interleave / keep_running (its only caller
passes True for both) and the non-interleaved metadata branch;
SiluQuantEpilogue's fused vec8 store reads its own cache policy instead of
a pass-through argument; comments that named the removed la2 bodies or
64-row-only tiles are corrected.

Why: dead parameters and branches left by the ring-core switch.

Effect: no code generation change: the small-input final ISA of 42 kernels
(EP8 / EP4 / EP2 V4.1-Flash and EP8 V4-Pro, a8w4 and a4w4, 1..512 tokens)
is byte-identical to the previous commit's (FlyDSL 0.5.3, gfx950).

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

* refactor(mega_moe): small-input plan CTA publishes only the plan flag

What: the small-input finalize keeps the source wait, the expert counts and
the plan-flag store, and drops the per-m-tile metadata it wrote (sorted
expert ids, tile row bases, tile rows, num_valid / overflow words), the
plan_wt knob that only set those stores' cache policy and the release
before the flag, and the dispatch-table slots and workspace that only the
removed bodies read (SORTED_EXPERT, TILE_ROW_BASE, NUM_VALID, TILE_ROWS,
G2_EIDS, G2_TRB, G2_MAX_M_BLOCKS, XCD_ACQ). The remaining slots keep their
indices. Fused-config digests move only by the removed plan_wt field (the
old tables without it hash to the new digests).

Why: every CTA builds the plan in its own LDS since the ring cores
replaced the old GEMM bodies; nothing reads the plan CTA's metadata.

Effect: the 42 small-input kernels checked (EP8 / EP4 / EP2 V4.1-Flash and
EP8 V4-Pro, a8w4 and a4w4, 1..512 tokens) keep their VGPR / SGPR / LDS
and have no scratch; the plan CTA's code is about 600 ISA lines shorter.

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

* [CI] Run the MegaMoE V2 routes suite in the multi-GPU job

op_tests/multigpu_tests/test_mega_moe_v2.py has been in skip_tests since
MegaMoE landed (#4439), so no automated flow runs MegaMoE: changes to its
kernels or launch path merge without a single GPU run. #8600, which moved
every MegaMoE launcher onto the FlyDSL AOT cache, is an example: it was
only validated by hand afterwards.

Run the routes suite (staged, small-input and large-input routes as
production builds them; accuracy against the fp32 reference and the
staged route, per-layer rebinding, epoch wrap, CUDA graph replay) for
DeepSeek-V4-Pro and DeepSeek-V4.1-Flash EP8 on 8 ranks. Like
test_mega_moe_tp.py it skips unless the job has 8 gfx950 GPUs, and it
also skips without mori. Under the job's AITER_FLYDSL_AOT_CACHE=verify it
re-traces each MegaMoE launcher the wheel's AOT prebuild covers and
compares it with the cached object.

Measured on 8x MI355X: 182 s for both networks, with an empty FlyDSL
cache and with the AOT cache in verify mode alike. The suite's timing
section is informational only; pass/fail comes from the accuracy gates
with fixed seeds.

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

* ci: run the MegaMoE V2 routes suite for V4.1-Flash EP8 A4W4 too

The multi-GPU case added in the previous commit runs the routes suite for
DeepSeek-V4-Pro and V4.1-Flash EP8 with the default A8W4; this PR adds the
fused A4W4 routes, so the case also runs --network v41_flash --quant a4w4
(about 1.5 min on 8x MI355X).

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

* feat(mega_moe): large-input route at MTPR 32768 on every fused layout

Add 32768 to LARGE_M_MTPRS, so a 32768-capacity instance (ATOM's prefill
max_num_batched_tokens) builds the large-input route and every call that
passes max_tokens takes a fused route (small-input up to 512 rows a rank,
large-input above) instead of staging 513..32768 rows.

At 32768 every layout's large-input config sends a token row to a
destination once (dedup_rows, indexed payload). The V4.1-Flash tunes and
the V4-Pro A4W4 tune already do; V4-Pro A8W4 (all fused knobs off,
route-major payload: a 15.29 GiB/GPU symmetric heap) takes the V4-Pro
A4W4 large-input tune at 32768 only, renamed _tune_v4_pro_large
(8.04 GiB/GPU). Its 1024..16384 configs are unchanged. 65536 stays out
of reach: the tagged count words hold 16-bit counts.

The AOT default V4.1-Flash MTPRs gain 32768 (+28 jobs per quant set);
V4-Pro's 32768 jobs build the large-input kernel through LARGE_M_MTPRS.
Tests: the never-staged exhaustive check covers pow2 capacities up to
32768, the 32-bit offset test also bounds the GEMM1 out-scale view and
the GEMM1 output (per-tile resources past 2^31), every 32768 config is
checked to use dedup_rows, and the A4W4 digests stay pinned to the
pre-existing capacities.

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

* MegaMoE gfx950: map global expert IDs to W1/W2 indices without the rank

The GEMM1 tile scheduler and GEMM2 subtracted a compile-time rank * experts
offset from the global expert IDs the dispatch plan writes. A rank's IDs
modulo its expert count are the same indices, so the GEMMs no longer need
the rank: expert_offset becomes experts_per_rank. The aligned-pair Stage2
passes its pair's local experts directly.

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

* MegaMoE gfx950: pass the rank to the staged kernels at launch

The staged Stage1 bundle, prepare, Stage2 and aligned-pair Stage2 kernels
took the rank as a compile-time constant, so the AOT cache built every
kernel once per rank. They now take it as an i32 kernel argument: the
compile functions and their AOT keys drop rank, and the run/preload
helpers pass it at launch. Rank-dependent index math becomes a few scalar
ops; the source < rank prefix sums become select chains over the running
sums. Outputs are unchanged.

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

* FlyDSL intranode combine: take the rank as a kernel argument

make_combine_kernel baked the rank into its P2P slot offsets, its
cross-device barrier word and the invalid-slot peer, so MegaMoE's fused
combine (mega_moe_combine) was compiled once per rank. The kernel now
takes an i32 rank argument, which the op passes on every launch; the
generic dispatch/combine path shares the same kernel.

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

* MegaMoE gfx950: pass the rank to the small-input kernel at launch

The small-input persistent kernel takes the rank as an i32 kernel
argument instead of a compile-time constant, so one AOT entry serves
every rank. The fused combine publishes its flag at a byte offset
(rank * 8) read from the runtime's dispatch table where it is used,
rather than keeping the rank live across the GEMMs.

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

* MegaMoE gfx950: pass the rank to the large-input kernel at launch

The large-input persistent kernel takes the rank as an i32 kernel
argument. large_m_kernel_specs drops ("rank", rank) from the fused Stage2
spec, so the kernel name hash (S2_KEY) and the AOT key no longer depend on
the rank; the skew boost of the payload geometry tests the destination
against the rank at run time, and the plan writes its counts through the
base of its own row in each destination's count matrix.

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

* AOT MegaMoE: build one job per profile instead of one per rank

Every MegaMoE kernel now takes the rank at launch and no AOT key holds
it, so rank 0's replay builds the kernels of every rank. default_jobs
yields one job per (MTPR, experts per rank, quant): the default build
drops from 276 jobs and 8898 AOT entries to 42 jobs and 1333 entries.

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

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>

This branch has not been deployed

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant