Skip to content

[FlyDSL] MegaMoEV2 V4.1-Flash small-input: shared expert inside the kernel (opt-in), EP4 / EP8 tunes (into #7788) - #8491

Closed
zhiding512 wants to merge 83 commits into
mainfrom
zhiding512/mega-ep4-v41-small-input-fusions
Closed

zhiding512 wants to merge 83 commits into
mainfrom
zhiding512/mega-ep4-v41-small-input-fusions

Conversation

@zhiding512

@zhiding512 zhiding512 commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

Stacked on #7788 (base ghu/mega_ep4_port_20261109). The branch starts at 69b0135, which is an ancestor of the base's current head 454435a. The main merge in between touches none of these files, so the diff here is only these 24 commits. This PR does not depend on #7867, which sits on an older head of the base branch.

Everything is scoped to the DeepSeek-V4.1-Flash layouts. Apart from the tune-table entries in the next section, everything new is opt-in.

Default-on: V4.1-Flash tune tables

EP4 (4 ranks x 96 experts), large-input route:

  • GEMM2 claims in groups of 256 m-blocks (m_group 256).
  • 96 dispatch CUs; the large-input kernel takes 96 producers.
  • GEMM1 weight loads without the non-temporal hint (b_nt 0).

EP8 (8 ranks x 48 experts):

  • Large-input: no GEMM2 fold.
  • Small-input bucket 32: 256-wide GEMM2 n-blocks.
  • Small-input buckets 64/128/256: dispatch and flag ordering without redundant system fences (new knob FusedStage1Knobs.disp_order), and sync_lean 1 (new knob: GEMM2-ready epochs and the plan flag without an L2 writeback). Both knobs default to 0, which keeps the kernel unchanged.
  • Draft-MoE buckets 64/128. These only apply with AITER_MEGA_FUSED_DRAFT_LAYOUT=1, below.

tests/test_mega_moe_gfx950_route_plan.py updates the EP4, EP8 V4.1-Flash and EP2 fused-config digests for these entries and for the two new knob fields. It also updates the EP4 large-input producer count.

Opt-in: new small-input kernel variants (default off)

These are reached through new keyword arguments, MegaMoEV2.forward(..., shared_add=None, shared_in=None), together with the switches below. With the arguments left at None, every call is unchanged.

  • AITER_MEGA_SHARED_ADD=1: the small-input combine adds the shared expert's output (shared_add) itself.
  • AITER_MEGA_SHARED_IN=1|2: the shared expert runs inside the small-input kernel on its MXFP8 weights.
    • 1 applies to the target (verify) layers. 2 also applies to the draft layers; that mode has not been validated on a GPU.
    • The tile bodies are in the new mega_moe/shared_expert.py, built on the new silu_mul_quant_epilogue.py.
    • GEMM1's K split follows the dense gate_up / down kernels that AITER's tuned table picks for the same row count, so the fused path reproduces the dense launches. Row counts the table cannot match keep the dense shared expert.
    • The kernel uses one consumer workgroup per unit of the call's own rows, and is prepared at eager calls.
  • AITER_MEGA_SHARED_IN_OPT, a bit field (0..31) that picks how the shared pre-phase runs:
    • bit 1: the halves of a split GEMM1 unit run on two workgroups.
    • bit 2: the pre-phase runs before the gate.
    • bit 4: the units of one weight slab stay on one XCD.
    • bit 8: the routed unit loop runs without the observing round trips.
    • bit 16: bit 4's later m-tiles start a beat behind.
  • AITER_MEGA_FUSED_DRAFT_LAYOUT=1: the DSpark draft MoE (128 experts, top-3) takes the small-input fused route, with 16 experts per rank on EP8 and 32 per rank on EP4. It is small-input only, and the large-input kernel is never built for these layouts.
  • Tuning and experiment switches. They are read at import or at launch-config time and must be equal on every rank:
    • AITER_MEGA_SMALL_M_OVERRIDE replaces fields of a bucket's small-input launch config.
    • AITER_MEGA_FUSED_BUCKET_MAP
    • AITER_MEGA_SMALL_M2
    • AITER_MEGA_SMALL_EXPERT_CACHED_W
    • AITER_MEGA_SMALL_FP8_ROWS_MIN
    • AITER_MEGA_SMALL_G2_B2STAGE
    • AITER_MEGA_SMALL_PROBE, and the null / hm / hm2 probes. These are for benchmarks only and give wrong output.

Tests

Check Result
CPU, no GPU visible, GPU_ARCHS=gfx950: tests/test_mega_moe_gfx950_{route_plan,shared_in,shared_expert,dep8}.py 123 passed
EP4 on 4x MI355X with FlyDSL 0.5.0, op_tests/multigpu_tests/test_mega_moe_v2.py --suite routes --network v41_flash --check-time-acc, this branch with defaults ALL PASS
Same, with AITER_MEGA_SMALL_M_OVERRIDE, AITER_MEGA_SMALL_M2=st+ad+tl and AITER_MEGA_FUSED_DRAFT_LAYOUT=1 ALL PASS
Same, on 69b0135, for reference ALL PASS
black 26.10.1 clean
ruff 0.16.0 (the CI pin) no new findings against 69b0135

The routes suite covers the staged route, the small-input route at MTPR 256 and 512, and the large-input route at MTPR 8192. Each is checked against the FP32 reference, plus graph replay.

The GPU runs were made before the last two rewrites of this branch. Those rewrites changed only comments, one test name, and black/ruff formatting. The kernel modules' ASTs are identical apart from import order and __all__. They were also made before AITER_MEGA_TOPK_IN (the V4.1 router's top-6 inside the kernel) was dropped from this PR, since it hard-codes the V4.1 router. Everything it added sat behind const_expr(topk_in) or was an equivalent form of code that was there before, so the kernels built without it, their names and their cache keys are unchanged.

Not covered:

  • test_mega_moe_v2.py does not pass shared_add / shared_in, so those kernel variants have CPU tests only here.
  • EP8 was not run on GPUs.
  • FlyDSL 0.5.3, the pin on the base's new head, was not tested.

Related: #8358 / #8360 work toward a similar goal on main's small-M kernel, where the shared expert runs as an extra expert slot.

GwilliamHu and others added 30 commits November 19, 2026 06:28
…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]>
…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]>
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]>
…tput 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]>
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]>
… 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]>
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]>
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]>
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]>
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]>
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]>
…ffers

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]>
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]>
…EMM2 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]>
… 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]>
…ent_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]>
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]>
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]>
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]>
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]>
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]>
…shared GEMM code

Port the shared parts of 28ee7fc ("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]>
Port the small-input part of 28ee7fc: 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 28ee7fc: 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]>
… 8192

Port the large-input part of 28ee7fc: 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 28ee7fc: 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]>
…ll-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 28ee7fc'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]>
…eir 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 28ee7fc; 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]>
…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]>
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]>
…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]>
…e and #8600

#7788 (the base of this branch) was squash-merged into main as 49ec5a3, and
main has since moved the MegaMoE small-input launcher onto the FlyDSL AOT cache
(#8600) and its buffer helpers onto ptr_buf_tensor / buf_copy_*. The branch
still carried #7788's pre-squash history, so a plain merge conflicted in 15
files. Resolution: every file outside this PR's own 24 commits takes main's
version; the 13 files those commits touch were 3-way merged with base 69b0135
(this PR's starting point) instead of the old merge base, so only this PR's
delta is replayed onto main.

Hand-resolved, mega_moe_small_m.py:
- source_done / arg_running / work_head stores: main's ptr_buf_tensor /
  buf_copy_store forms, with this PR's disp_order, M2 "tl" and "xt" branches.
- LDS plan table: main's plan_incl / plan_count (Int32) plus this PR's
  sh_partial and lean_tab; plan_multi_tile reads them through plan_ptr like
  plan_lookup does.
- shared_in pre-phase and lean table read the dispatch table through main's
  disp_t (main removed _buffer_load / _make_buffer_from_addr).
- run_mega_moe_stage1 is gone on main: _launcher(config, **variant) caches one
  launcher per (config, shared_add / shared_in / shared_in_opt variant), and
  _launch runs it through _run_compiled / _preload_compiled with this PR's
  shared_in tensors and dispatch table.
- gemm1.build_fused_gemm1: main's a_async_lds rename plus this PR's
  mfma_m_active.

aiter/aot/flydsl/sources.py: the small-input cache declares the two new kernel
files it imports (mega_moe/shared_expert.py, silu_mul_quant_epilogue.py) and
the variables its sources now read; the stage1 bundle and large-input caches
declare the three mega_moe_config.py variables (AITER_MEGA_FUSED_BUCKET_MAP,
AITER_MEGA_FUSED_DRAFT_LAYOUT, AITER_MEGA_SMALL_M_OVERRIDE). Without this the
AOT cache (on by default) refuses to build these kernels.

tests/test_mega_moe_gfx950_route_plan.py: EP4 / EP8 / EP2 digests recomputed
on the merged tables. Every knob of every (MTPR, tokens) entry equals this
PR's value where the PR changed it (69b0135 -> 8e2813c) and main's value
otherwise; no knob was changed by both sides.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Copilot AI balanced review requested due to automatic review settings November 27, 2026 23:55
@yhl-amd

yhl-amd commented Nov 28, 2026

Copy link
Copy Markdown
Contributor

Hi @zhiding512, this PR had become CONFLICTING after #7788 was squash-merged into main, so I added one merge commit on top of your branch to bring it up to date: 7aebbe3 (parents: your 8e2813c and main 9da5928). It is a plain fast-forward push. Your commits are untouched and nothing was force-pushed, so you can keep working on the branch as before (please pull first). GitHub now reports the PR as mergeable.

How it was merged

  • The base is already main, so it did not need to change. The conflicts came from the 58 pre-squash [FlyDSL] [CI] MegaMoEV2: one route plan for every path, shared arenas, and the DeepSeek-V4.1-Flash EP2 / EP4 / EP8 fused routes #7788 commits still on the branch.

  • Files outside this PR's own 24 commits take main's version. The 13 files those commits touch were 3-way merged against 69b0135, the PR's starting point, so only this PR's delta is replayed onto main.

  • Resolved by hand:

    • mega_moe_small_m.py:
      • The source_done, arg_running and work_head stores use main's ptr_buf_tensor / buf_copy_store forms, with your disp_order, M2 tl and xt branches.
      • The LDS plan uses main's plan_incl / plan_count plus your sh_partial and lean_tab. plan_multi_tile reads through plan_ptr.
      • The shared_in pre-phase and the lean table read the dispatch table through main's disp_t. Main removed _buffer_load and _make_buffer_from_addr.
      • run_mega_moe_stage1 is gone on main ([FlyDSL] Launch the planner, GDN, conv3d, FP8 attention and MegaMoE launchers through the AOT cache #8600). _launcher(config, **variant) now caches one launcher per config and shared_add / shared_in / shared_in_opt variant, and _launch runs it through _run_compiled / _preload_compiled.
    • gemm1.build_fused_gemm1: main's a_async_lds rename plus your mfma_m_active.
  • aiter/aot/flydsl/sources.py: with the AOT cache on by default, the small-input cache now has to declare everything it reads:

    • the two kernel files it imports (mega_moe/shared_expert.py, silu_mul_quant_epilogue.py);
    • the variables its sources read.

    The stage1-bundle and large-input caches now declare the three mega_moe_config.py variables. Without this, the cache refuses to build these kernels.

  • test_mega_moe_gfx950_route_plan.py: I recomputed the EP4 / EP8 / EP2 digests and checked them knob by knob. Each knob of each (MTPR, tokens) entry equals your value where this PR changes it and main's value otherwise. No knob was changed on both sides.

Tests (MI355X, FlyDSL 0.5.3)

Check Result
CPU, no GPU visible: tests/test_mega_moe_gfx950_{route_plan,shared_in,shared_expert,dep8}.py all pass
tests/test_flydsl_aot_cache.py, test_flydsl_aot_launch.py, test_import_without_gpu.py 35 passed, 1 skipped (same as main)
EP4, 4 GPUs: test_mega_moe_v2.py --suite routes --network v41_flash --check-time-acc ALL PASS
Same, with AITER_MEGA_SMALL_M2=st+ad+tl and AITER_MEGA_FUSED_DRAFT_LAYOUT=1 ALL PASS
Same, on main 9da5928, for reference ALL PASS
black 26.10.1 / ruff 0.16.0 on the touched files clean

Not covered yet: an EP8 run on GPUs, and a GPU check of the shared_in kernel variants against the dense shared expert. The CPU tests cover them for now, and I'll post the GPU results here when I have them.

Please review the merge when you have a moment, especially the _launcher / _launch part of mega_moe_small_m.py. Thanks!

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 Changes recommended

Missing shared-weight device validation and launch-stream dependencies risk illegal GPU accesses and races with workspace initialization.

4 open issues
What changed in this PR

Extends #7788’s MegaMoEV2 routing with opt-in shared-expert fusion for DeepSeek-V4.1-Flash small inputs, alongside default EP4/EP8 tuning updates.

Changes:

  • Adds shared-expert input handling, MXFP8 GEMM bodies and a fused SiLU/quantization epilogue.
  • Adds draft-layout and tuning switches, with cache fingerprints covering the new variants.
  • Adds CPU tests for validation, addressing, launch configuration and synchronization models; updates route-plan expectations.
File Description
tests/​test_mega_moe_gfx950_shared_in.py Tests shared-input routing, preparation, launch arguments and counter models.
tests/​test_mega_moe_gfx950_shared_expert.py Checks kernel naming, lazy imports and weight/scale addressing.
tests/​test_mega_moe_gfx950_route_plan.py Updates tuning digests and EP4 producer-count expectations.
tests/​test_mega_moe_gfx950_dep8.py Tests tuning overrides and opt-in draft layouts.
aiter/​ops/​flydsl/​kernels/​silu_mul_quant_epilogue.py Adds clamped SiLU-multiply and group-32 MXFP8 quantization.
aiter/​ops/​flydsl/​kernels/​mega_moe/​weights.py Adds the shared-expert input container and metadata validation.
aiter/​ops/​flydsl/​kernels/​mega_moe/​shared_expert.py Implements shared-expert GEMM tiles, epilogues and standalone launchers.
aiter/​ops/​flydsl/​kernels/​mega_moe/​mega_moe_v2.py Routes shared-expert arguments through fusion or dense fallback.
aiter/​ops/​flydsl/​kernels/​mega_moe/​mega_moe_config.py Adds EP4/EP8 tunes, draft layouts and experiment switches.
aiter/​ops/​flydsl/​kernels/​mega_moe/​gemm2.py Adds an option to compute only the first row group.
aiter/​ops/​flydsl/​kernels/​mega_moe/​gemm1.py Passes active-row-group limits into GEMM1 matrix operations.
aiter/​ops/​flydsl/​kernels/​mega_moe/​gemm_util.py Supports limiting matrix operations to active row groups.
aiter/​aot/​flydsl/​sources.py Tracks new sources and environment switches in cache fingerprints.

Review effort: Balanced

Comment on lines +1164 to +1174
for runtime in getattr(self, "_small_m_runtimes", ()):
runtime.shared_in_prepare(shared_in)
if route[0] == ROUTE_SMALL_M and slice_output:
runtime = self._small_m_runtimes[self._bundle_plan.small_m_mtprs.index(route[1])]
if runtime.shared_in_ready(int(x_bf16.shape[0]), shared_in):
check_forward_inputs(
x_bf16, wts, topk_ids, max_rows=self.mtpr, model_dim=self.model_dim,
topk=self.topk, device=self.dev,
)
with torch.cuda.stream(torch_stream(stream)):
return runtime.forward(x_bf16, wts, topk_ids, slice_output=True, shared_in=shared_in)
Comment on lines +102 to +105
t.numel() == n
and t.element_size() == 1
and t.is_contiguous()
and t.data_ptr() % 16 == 0
Comment on lines +1189 to +1194
out = self._forward_route(
route, x_bf16, wts, topk_ids, stream=stream, slice_output=True,
mask_invalid_slots=mask_invalid_slots,
)
with torch.cuda.stream(torch_stream(stream)):
return out + shared_add
Comment on lines +1019 to +1020
@flyc.kernel(name=gemm1_name(k_dim, inter_dim, limit, ksplit, b_cache_modifier),
known_block_size=[THREADS, 1, 1])
@yhl-amd

yhl-amd commented Nov 28, 2026

Copy link
Copy Markdown
Contributor

Follow-up GPU results for the merge commit 7aebbe3 (8x MI355X, single node, image rocm/atom-dev:nightly_202611251520-perf, FlyDSL 0.5.3):

EP8 routes suite — torchrun --nproc-per-node 8 op_tests/multigpu_tests/test_mega_moe_v2.py --suite routes --network v41_flash --check-time-acc

tree result
PR head 7aebbe3, default ALL PASS (48 ACC + 36 timed-ACC, EDGE/ALT/WRAP/GRAPH pass)
PR head, AITER_MEGA_SMALL_M2=st+ad+tl AITER_MEGA_FUSED_DRAFT_LAYOUT=1 ALL PASS
main 9da5928 (reference) ALL PASS

small_m time (us, median of 15, max over ranks), bs/rank 7 / 56 / 168 / 336 / 448: PR default 123.1 / 165.7 / 187.8 / 246.1 / 300.5; opt-in 119.3 / 160.0 / 186.1 / 242.4 / 304.0; main 122.6 / 165.9 / 195.6 / 254.1 / 305.2.

shared_in vs shared_add, bitwise (AITER_MEGA_SHARED_IN=1): for 23 row counts (6 … 256) on every rank, the output with shared_in fused in the small-input kernel is bit-identical to the same rows with shared_add = standalone shared GEMM1+act, GEMM2. EP8: 168 fused cases, 0 mismatches; EP4: 84 fused cases, 0 mismatches (rows 192/256 fall back to the dense path as designed and also match). The standalone shared GEMM2 is also bit-identical to AITER's dense group-32 MXFP8 GEMM (_gemm_mxscale_bpreshuffle) for all cases.

No code changes were needed from these runs.

yhl-amd added a commit to yhl-amd/ATOM that referenced this pull request Dec 1, 2026
…er interface imported, eager x quant, CPU tests run in CI

- FusedMoE._shared_in_expert (class default None) is the one fact; MoE.__init__
  makes one attach_mega_shared_expert call (draft layer, TP, dual stream passed
  in) and single_stream_moe_forward branches on it. _shared_in_routed,
  _hand_shared_expert_to_routed and MoE.is_draft_layer are gone.
- SharedExpertInput is imported from aiter directly (ROCm/aiter#8491), built
  with keyword arguments; the capability probe and LazySharedExpertInput are
  gone and x is quantized once per attached call.
- The reduction clauses are FusedMoE.combine_output_is_reduced, shared with
  combine_accepts_shared. The layout check keeps only what aiter's
  weights_fit cannot see (preshuffled vs row-major, bias, scale, BF16 fallback).
- run_mega_moe: plain if / else around mega.forward, no dict per call.
- tests/model_ops/test_mega_shared_in.py runs under atom_under_stubs (CPU CI);
  gate_up / w2 and x_fp8 / x_scale are checked against distinct tensors.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@zhiding512 zhiding512 closed this Dec 2, 2026
yhl-amd added a commit to yhl-amd/aiter that referenced this pull request Dec 2, 2026
…ores

v41_shared_expert.py: the DeepSeek-V4.1-Flash shared expert with the
checkpoint's MXFP8 weights ((16, 16)-preshuffled E4M3, 32x32-block E8M0),
computed apart from the MXFP4 routed experts, in tiles that give the bits of
the model's dense launches:

- GEMM1 (x x [gate | up]) and GEMM2 (activation x down) run gemm_ring._Ring
  (weights as the scaled MFMA's operand A, zero-initialised accumulators, one
  16x16x128 MFMA per 128-K step, K ascending), with an FP8 weight loader and
  their own epilogues; a split-K 2 dense GEMM is reproduced as 0 + p0 + p1.
- GEMM1's epilogue rounds gate / up to BF16 and runs silu_mul_mxfp8's
  arithmetic (clamp, exp expansion, group-32 E8M0 = ceil_pow2(amax / 448)) with
  FP32 denormals flushed, and writes the MXFP8 activation in the order the
  GEMM2 ring copies it. GEMM2 writes BF16 rows.
- dense_gate_up_ksplit reads AITER's live tuned table for the split the dense
  launches run at a row count (0 where the tiles cannot reproduce it).
- v41_shared_in_layout: only the EP8 / EP4 / EP2 V4.1-Flash main-model
  layouts; AITER_MEGA_SHARED_IN=0 turns the in-kernel path off.

weights.SharedExpertInput: the shared_in contract (x's MXFP8 pair, the
weights and scales, dense()), with a device check.

The epilogue arithmetic and the dense split detection follow ROCm#8491.

Co-authored-by: zhiding512 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
yhl-amd added a commit to yhl-amd/aiter that referenced this pull request Dec 2, 2026
…pert in the MegaMoE kernels

forward(shared_in=S) returns routed + shared, bit for bit
routed + S.dense() on BF16 tensors:

- Small-input route: a v41_shared kernel variant computes the shared expert of
  the rank's rows before its routed work. Every CTA claims shared units from
  one rank-local counter (each m-tile's GEMM1 units, then its GEMM2 units,
  which wait for the m-tile's ready epoch), so any row count up to 512 fits;
  GEMM2 writes BF16 rows into the combine output and the combine reducers add
  the routed sum to them. The cross-rank protocol is unchanged. Tiles:
  32 rows x 64 / 128 columns below 128 rows, 64 rows x 128 / 256 columns from
  128 rows. Buckets with tok_done (at most 4 rows a rank) and row counts whose
  dense split the tiles do not reproduce run S.dense().
- Large-input route: the dense launches write their rows into a new output and
  the persistent kernel's combine adds the routed sum (_sha variant); with an
  FP8 route the kernel reads S's MXFP8 x instead of quantizing x again.
- Every other call (staged route, other models, DSpark draft layouts) runs
  S.dense() and adds it into the routed rows. AITER_MEGA_SHARED_IN=0 takes that
  path everywhere.
- Without shared_in nothing changes: the non-shared kernels keep their names
  and code. AOT: preload_aot_bundle also loads the shared variants; both
  MegaMoE caches declare v41_shared_expert.py and AITER_MEGA_SHARED_IN.

Based on ROCm#8491 (small-input shared_in) and the 64-row-tile and
large-input extensions of ROCm#8878.

Co-authored-by: zhiding512 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
yhl-amd added a commit to yhl-amd/aiter that referenced this pull request Dec 2, 2026
…ores

v41_shared_expert.py: the DeepSeek-V4.1-Flash shared expert with the
checkpoint's MXFP8 weights ((16, 16)-preshuffled E4M3, 32x32-block E8M0),
computed apart from the MXFP4 routed experts, in tiles that give the bits of
the model's dense launches:

- GEMM1 (x x [gate | up]) and GEMM2 (activation x down) run gemm_ring._Ring
  (weights as the scaled MFMA's operand A, zero-initialised accumulators, one
  16x16x128 MFMA per 128-K step, K ascending), with an FP8 weight loader and
  their own epilogues; a split-K 2 dense GEMM is reproduced as 0 + p0 + p1.
- GEMM1's epilogue rounds gate / up to BF16 and runs silu_mul_mxfp8's
  arithmetic (clamp, exp expansion, group-32 E8M0 = ceil_pow2(amax / 448)) with
  FP32 denormals flushed, and writes the MXFP8 activation in the order the
  GEMM2 ring copies it. GEMM2 writes BF16 rows.
- dense_gate_up_ksplit reads AITER's live tuned table for the split the dense
  launches run at a row count (0 where the tiles cannot reproduce it).
- v41_shared_in_layout: only the EP8 / EP4 / EP2 V4.1-Flash main-model
  layouts; AITER_MEGA_SHARED_IN=0 turns the in-kernel path off.

weights.SharedExpertInput: the shared_in contract (x's MXFP8 pair, the
weights and scales, dense()), with a device check.

The epilogue arithmetic and the dense split detection follow ROCm#8491.

Co-authored-by: zhiding512 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
yhl-amd added a commit to yhl-amd/aiter that referenced this pull request Dec 2, 2026
…pert in the MegaMoE kernels

forward(shared_in=S) returns routed + shared, bit for bit
routed + S.dense() on BF16 tensors:

- Small-input route: a v41_shared kernel variant computes the shared expert of
  the rank's rows before its routed work. Every CTA claims shared units from
  one rank-local counter (each m-tile's GEMM1 units, then its GEMM2 units,
  which wait for the m-tile's ready epoch), so any row count up to 512 fits;
  GEMM2 writes BF16 rows into the combine output and the combine reducers add
  the routed sum to them. The cross-rank protocol is unchanged. Tiles:
  32 rows x 64 / 128 columns below 128 rows, 64 rows x 128 / 256 columns from
  128 rows. Buckets with tok_done (at most 4 rows a rank) and row counts whose
  dense split the tiles do not reproduce run S.dense().
- Large-input route: the dense launches write their rows into a new output and
  the persistent kernel's combine adds the routed sum (_sha variant); with an
  FP8 route the kernel reads S's MXFP8 x instead of quantizing x again.
- Every other call (staged route, other models, DSpark draft layouts) runs
  S.dense() and adds it into the routed rows. AITER_MEGA_SHARED_IN=0 takes that
  path everywhere.
- Without shared_in nothing changes: the non-shared kernels keep their names
  and code. AOT: preload_aot_bundle also loads the shared variants; both
  MegaMoE caches declare v41_shared_expert.py and AITER_MEGA_SHARED_IN.

Based on ROCm#8491 (small-input shared_in) and the 64-row-tile and
large-input extensions of ROCm#8878.

Co-authored-by: zhiding512 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
yhl-amd added a commit to yhl-amd/aiter that referenced this pull request Dec 2, 2026
…ores

v41_shared_expert.py: the DeepSeek-V4.1-Flash shared expert with the
checkpoint's MXFP8 weights ((16, 16)-preshuffled E4M3, 32x32-block E8M0),
computed apart from the MXFP4 routed experts, in tiles that give the bits of
the model's dense launches:

- GEMM1 (x x [gate | up]) and GEMM2 (activation x down) run gemm_ring._Ring
  (weights as the scaled MFMA's operand A, zero-initialised accumulators, one
  16x16x128 MFMA per 128-K step, K ascending), with an FP8 weight loader and
  their own epilogues; a split-K 2 dense GEMM is reproduced as 0 + p0 + p1.
- GEMM1's epilogue rounds gate / up to BF16 and runs silu_mul_mxfp8's
  arithmetic (clamp, exp expansion, group-32 E8M0 = ceil_pow2(amax / 448)) with
  FP32 denormals flushed, and writes the MXFP8 activation in the order the
  GEMM2 ring copies it. GEMM2 writes BF16 rows.
- dense_gate_up_ksplit reads AITER's live tuned table for the split the dense
  launches run at a row count (0 where the tiles cannot reproduce it).
- v41_shared_in_layout: only the EP8 / EP4 / EP2 V4.1-Flash main-model
  layouts; AITER_MEGA_SHARED_IN=0 turns the in-kernel path off.

weights.SharedExpertInput: the shared_in contract (x's MXFP8 pair, the
weights and scales, dense()), with a device check.

The epilogue arithmetic and the dense split detection follow ROCm#8491.

Co-authored-by: zhiding512 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
yhl-amd added a commit to yhl-amd/aiter that referenced this pull request Dec 2, 2026
…pert in the MegaMoE kernels

forward(shared_in=S) returns routed + shared, bit for bit
routed + S.dense() on BF16 tensors:

- Small-input route: a v41_shared kernel variant computes the shared expert of
  the rank's rows before its routed work. Every CTA claims shared units from
  one rank-local counter (each m-tile's GEMM1 units, then its GEMM2 units,
  which wait for the m-tile's ready epoch), so any row count up to 512 fits;
  GEMM2 writes BF16 rows into the combine output and the combine reducers add
  the routed sum to them. The cross-rank protocol is unchanged. Tiles:
  32 rows x 64 / 128 columns below 128 rows, 64 rows x 128 / 256 columns from
  128 rows. Buckets with tok_done (at most 4 rows a rank) and row counts whose
  dense split the tiles do not reproduce run S.dense().
- Large-input route: the dense launches write their rows into a new output and
  the persistent kernel's combine adds the routed sum (_sha variant); with an
  FP8 route the kernel reads S's MXFP8 x instead of quantizing x again.
- Every other call (staged route, other models, DSpark draft layouts) runs
  S.dense() and adds it into the routed rows. AITER_MEGA_SHARED_IN=0 takes that
  path everywhere.
- Without shared_in nothing changes: the non-shared kernels keep their names
  and code. AOT: preload_aot_bundle also loads the shared variants; both
  MegaMoE caches declare v41_shared_expert.py and AITER_MEGA_SHARED_IN.

Based on ROCm#8491 (small-input shared_in) and the 64-row-tile and
large-input extensions of ROCm#8878.

Co-authored-by: zhiding512 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
valarLip pushed a commit that referenced this pull request Dec 2, 2026
…side the MegaMoE kernels (shared_in), standalone on main (#8878)

* feat(mega_moe): V4.1-Flash FP8 shared-expert tiles on the ring GEMM cores

v41_shared_expert.py: the DeepSeek-V4.1-Flash shared expert with the
checkpoint's MXFP8 weights ((16, 16)-preshuffled E4M3, 32x32-block E8M0),
computed apart from the MXFP4 routed experts, in tiles that give the bits of
the model's dense launches:

- GEMM1 (x x [gate | up]) and GEMM2 (activation x down) run gemm_ring._Ring
  (weights as the scaled MFMA's operand A, zero-initialised accumulators, one
  16x16x128 MFMA per 128-K step, K ascending), with an FP8 weight loader and
  their own epilogues; a split-K 2 dense GEMM is reproduced as 0 + p0 + p1.
- GEMM1's epilogue rounds gate / up to BF16 and runs silu_mul_mxfp8's
  arithmetic (clamp, exp expansion, group-32 E8M0 = ceil_pow2(amax / 448)) with
  FP32 denormals flushed, and writes the MXFP8 activation in the order the
  GEMM2 ring copies it. GEMM2 writes BF16 rows.
- dense_gate_up_ksplit reads AITER's live tuned table for the split the dense
  launches run at a row count (0 where the tiles cannot reproduce it).
- v41_shared_in_layout: only the EP8 / EP4 / EP2 V4.1-Flash main-model
  layouts; AITER_MEGA_SHARED_IN=0 turns the in-kernel path off.

weights.SharedExpertInput: the shared_in contract (x's MXFP8 pair, the
weights and scales, dense()), with a device check.

The epilogue arithmetic and the dense split detection follow #8491.

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

* feat(mega_moe): MegaMoEV2.forward(shared_in=), V4.1-Flash's shared expert in the MegaMoE kernels

forward(shared_in=S) returns routed + shared, bit for bit
routed + S.dense() on BF16 tensors:

- Small-input route: a v41_shared kernel variant computes the shared expert of
  the rank's rows before its routed work. Every CTA claims shared units from
  one rank-local counter (each m-tile's GEMM1 units, then its GEMM2 units,
  which wait for the m-tile's ready epoch), so any row count up to 512 fits;
  GEMM2 writes BF16 rows into the combine output and the combine reducers add
  the routed sum to them. The cross-rank protocol is unchanged. Tiles:
  32 rows x 64 / 128 columns below 128 rows, 64 rows x 128 / 256 columns from
  128 rows. Buckets with tok_done (at most 4 rows a rank) and row counts whose
  dense split the tiles do not reproduce run S.dense().
- Large-input route: the dense launches write their rows into a new output and
  the persistent kernel's combine adds the routed sum (_sha variant); with an
  FP8 route the kernel reads S's MXFP8 x instead of quantizing x again.
- Every other call (staged route, other models, DSpark draft layouts) runs
  S.dense() and adds it into the routed rows. AITER_MEGA_SHARED_IN=0 takes that
  path everywhere.
- Without shared_in nothing changes: the non-shared kernels keep their names
  and code. AOT: preload_aot_bundle also loads the shared variants; both
  MegaMoE caches declare v41_shared_expert.py and AITER_MEGA_SHARED_IN.

Based on #8491 (small-input shared_in) and the 64-row-tile and
large-input extensions of #8878.

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

* test(mega_moe): shared_in, CPU dispatch / contract tests and a GPU bit-exact check in the routes suite

tests/test_mega_moe_gfx950_shared_in.py (no GPU): which layouts take shared_in,
the env switch, SharedExpertInput's contract, the dense split detection, the
tiles' LDS, the AOT preload variants, the small / large readiness and
MegaMoEV2's dispatch between kernel and dense paths.

op_tests/multigpu_tests/test_mega_moe_v2.py --suite routes --network v41_flash:
[SHARED_IN] checks forward(shared_in=S) == forward() + S.dense() bit for bit on
uniform, uneven and idle ranks of both routes, with AITER_MEGA_SHARED_IN=1 and
0, and times it against routed + dense (--shared-in-only runs just that).

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

* fix(mega_moe): shared_in review fixes -- env out of the AOT key, dense-split whitelist, tile op test

- AITER_MEGA_SHARED_IN is read only by MegaMoEV2._forward_shared. It no longer
  keys the small/large stage1 AOT caches (setting it, even to 1, missed every
  prebuilt stage1 entry); it is listed in ENV_NOT_CODE. The runtimes' shared_in_ready
  and preload no longer read it; V4.1-Flash layouts always preload the shared variants.
- dense_kernel_ksplit: only kernel families whose split-K order the tiles reproduce
  (flydsl_mxpsh_*, flydsl_bmm_mxfp8_mfma_* by _sk<N>; flydsl_mxfp8_8w_* via its
  name parser, 0 with _ns<N>); anything else returns 0 (dense) and is logged once.
  Lookup errors are no longer swallowed (only ImportError).
- op_tests/test_mega_moe_v41_shared.py: the tiles against the dense launches, bit
  for bit, over every V4.1-Flash tuned M bucket to 512 rows and past it, both tiles;
  compile_v41_shared_test now has its caller, _TILE_OVERRIDE is gone.
- routes suite [SHARED_IN]: per-rank expected kernel path asserted; env restored
  after the check; --shared-in-only refuses configurations it would not check.
- comments: tile rows 32/64, per-wave columns.

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

---------

Co-authored-by: zhiding512 <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
yhl-amd added a commit to yhl-amd/ATOM that referenced this pull request Dec 2, 2026
…outed call (aiter shared_in)

DeepSeek-V4.1's shared expert (MXFP8 weights with 32x32-block scales) is not
fused into the MXFP4 routed experts by default, so a Mega layer ran it as its
own dense launches (quantize, gate_up GEMM, act, down GEMM) next to the
MegaMoE call. With ROCm/aiter#8491, MegaMoEV2.forward(shared_in=...)
computes it inside its small-input kernel where that kernel can, with the
same MXFP8 activations and the checkpoint's FP8 weights, and otherwise runs
it dense on the caller's stream; either way it returns routed + shared.

- attach_mega_shared_expert (flydsl_mega_experts): on a layer every routed
  call of which reaches run_mega_moe on the rank's own rows with nothing
  reduced after it (the Mega method; no comm-fused or SP MegaMoE, PCP merge,
  DP-logical split or experts reduction), run_mega_moe passes the shared
  expert as shared_in. DeepSeek-V4 MoE attaches it on its target layers
  (TP 1, single stream) and then adds no shared output of its own; the
  DSpark / MTP draft layers keep their dense shared expert.
- The MXFP8 copy of x is made only when AITER reads it, i.e. for a call it
  fuses; a call it cannot fuse runs the dense shared expert, which quantizes
  x itself, so x is quantized once a call either way.
- An AITER without shared_in (no weights.SharedExpertInput, which arrives
  with it) keeps today's path: the shared expert is computed apart.

No new switch or environment variable.

Tests: tests/test_mega_shared_in.py (lazy MXFP8 copy, where the shared
expert is attached, an AITER without shared_in); test_mega_decode_capacity
checks run_mega_moe passes shared_in exactly for an attached layer.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
yhl-amd added a commit to yhl-amd/ATOM that referenced this pull request Dec 2, 2026
…er interface imported, eager x quant, CPU tests run in CI

- FusedMoE._shared_in_expert (class default None) is the one fact; MoE.__init__
  makes one attach_mega_shared_expert call (draft layer, TP, dual stream passed
  in) and single_stream_moe_forward branches on it. _shared_in_routed,
  _hand_shared_expert_to_routed and MoE.is_draft_layer are gone.
- SharedExpertInput is imported from aiter directly (ROCm/aiter#8491), built
  with keyword arguments; the capability probe and LazySharedExpertInput are
  gone and x is quantized once per attached call.
- The reduction clauses are FusedMoE.combine_output_is_reduced, shared with
  combine_accepts_shared. The layout check keeps only what aiter's
  weights_fit cannot see (preshuffled vs row-major, bias, scale, BF16 fallback).
- run_mega_moe: plain if / else around mega.forward, no dict per call.
- tests/model_ops/test_mega_shared_in.py runs under atom_under_stubs (CPU CI);
  gate_up / w2 and x_fp8 / x_scale are checked against distinct tensors.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
yhl-amd added a commit to ROCm/ATOM that referenced this pull request Dec 3, 2026
…o the routed call (aiter shared_in) (#3894)

* perf(dsv41): Mega target layers hand their FP8 shared expert to the routed call (aiter shared_in)

DeepSeek-V4.1's shared expert (MXFP8 weights with 32x32-block scales) is not
fused into the MXFP4 routed experts by default, so a Mega layer ran it as its
own dense launches (quantize, gate_up GEMM, act, down GEMM) next to the
MegaMoE call. With ROCm/aiter#8491, MegaMoEV2.forward(shared_in=...)
computes it inside its small-input kernel where that kernel can, with the
same MXFP8 activations and the checkpoint's FP8 weights, and otherwise runs
it dense on the caller's stream; either way it returns routed + shared.

- attach_mega_shared_expert (flydsl_mega_experts): on a layer every routed
  call of which reaches run_mega_moe on the rank's own rows with nothing
  reduced after it (the Mega method; no comm-fused or SP MegaMoE, PCP merge,
  DP-logical split or experts reduction), run_mega_moe passes the shared
  expert as shared_in. DeepSeek-V4 MoE attaches it on its target layers
  (TP 1, single stream) and then adds no shared output of its own; the
  DSpark / MTP draft layers keep their dense shared expert.
- The MXFP8 copy of x is made only when AITER reads it, i.e. for a call it
  fuses; a call it cannot fuse runs the dense shared expert, which quantizes
  x itself, so x is quantized once a call either way.
- An AITER without shared_in (no weights.SharedExpertInput, which arrives
  with it) keeps today's path: the shared expert is computed apart.

No new switch or environment variable.

Tests: tests/test_mega_shared_in.py (lazy MXFP8 copy, where the shared
expert is attached, an AITER without shared_in); test_mega_decode_capacity
checks run_mega_moe passes shared_in exactly for an attached layer.

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

* fix(dsv41): shared_in review: weight layout check, layer-id draft test, capability check, tests

- attach_mega_shared_expert attaches only shared-expert weights in the layout
  AITER's shared_in reads: gate_up_proj and w2 both native 32x32-block FP8
  linears (no BF16 fallback, no bias) with their E8M0 scale, the weight held
  in the (16, 16) preshuffle (weight_is_stored_preshuffled, the load's own
  decision). Otherwise (e.g. ATOM_GROUP32_WEIGHT_PRESHUFFLE=0, row-major
  weights AITER would read as shuffled) the shared expert stays a dense pass
  and a warning is logged once per reason.
- Draft layers are told apart by layer id (MoE.is_draft_layer: layer_id >=
  n_layers, as MTPBlock(args.n_layers + i) and V4.1's topology number them),
  not by the "mtp." prefix. The attach decision is MoE._hand_shared_expert_to_routed.
- AITER capability: weights.SharedExpertInput and MegaMoEV2.forward taking
  shared_in, both required; an AITER missing either keeps the shared expert
  apart.
- Tests (CPU): layout refusals and the one-time warning, preshuffle on/off,
  AITER without shared_in in either form, target vs draft / TP / dual-stream /
  comm-fused layers, and the attached layer's forward never calling its shared
  expert or adding a shared output.

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

* refactor(dsv41): shared_in review: one owner and one attach call, aiter interface imported, eager x quant, CPU tests run in CI

- FusedMoE._shared_in_expert (class default None) is the one fact; MoE.__init__
  makes one attach_mega_shared_expert call (draft layer, TP, dual stream passed
  in) and single_stream_moe_forward branches on it. _shared_in_routed,
  _hand_shared_expert_to_routed and MoE.is_draft_layer are gone.
- SharedExpertInput is imported from aiter directly (ROCm/aiter#8491), built
  with keyword arguments; the capability probe and LazySharedExpertInput are
  gone and x is quantized once per attached call.
- The reduction clauses are FusedMoE.combine_output_is_reduced, shared with
  combine_accepts_shared. The layout check keeps only what aiter's
  weights_fit cannot see (preshuffled vs row-major, bias, scale, BF16 fallback).
- run_mega_moe: plain if / else around mega.forward, no dict per call.
- tests/model_ops/test_mega_shared_in.py runs under atom_under_stubs (CPU CI);
  gate_up / w2 and x_fp8 / x_scale are checked against distinct tensors.

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

* docs(dsv41): shared_in now comes from ROCm/aiter#8878

#8491 was closed; its shared_in is part of #8878 on aiter main with the same
interface (SharedExpertInput keyword constructor, forward(shared_in=),
used_dense). Only the references and the description of where aiter computes
the shared expert change.

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

* fix(dsv41): shared_in only with an AITER that has it

An AITER before ROCm/aiter#8878 has no SharedExpertInput, and its MegaMoE
call takes no shared_in. attach_mega_shared_expert now checks for it at
construction and otherwise leaves the shared expert a dense pass beside the
routed call (one warning), so such an AITER runs as before instead of
failing at the first routed call.

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

---------

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

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants