Repository navigation
[FlyDSL] [MoE] gfx950 a8w4 routed-experts op for H5120/I2304 top-6/top-3 - #8381
Fangzhou-Ai wants to merge 2 commits into
Conversation
…-3 (gfx950) Add flydsl_moe_a8w4_experts: the routed experts of one expert-parallel rank with MXFP8 activations and MXFP4 weights, hidden 5120, intermediate 2304, top-6 (e.g. 48 local experts of 384) or top-3 (16 of 128), up to 63 local experts and 1024 tokens per call. Two launches per call: a sort launch (with the bf16 -> MXFP8 quant when the input is bf16) and one fused launch in which GEMM1 + clamp-SwiGLU + MXFP8 requant, GEMM2 + route weight and the slot-ordered top-k combine are ordered by per-block ready counters. Every output element has one writer (no atomics), so outputs are bitwise repeatable. - aiter/ops/flydsl/kernels/moe_a8w4_experts.py: kernels - aiter/ops/flydsl/moe_a8w4_experts.py: op wrapper, token-count dispatch, moe_a8w4_experts_supported() eligibility check, warm-up, an entry for rows already sorted by expert (flydsl_moe_a8w4_experts_rows) - op_tests/flydsl_tests/test_flydsl_moe_a8w4_experts.py: pytest against a torch reference (added to the CI file lists) - op_tests/flydsl_tests/bench_flydsl_moe_a8w4_experts.py: graph-replay A/B against aiter.fused_moe a8w4 Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> Signed-off-by: Fangzhou Ai <[email protected]>
🏷️ CI GuideRuns automatically on every PR:
Extended tests (opt-in via labels):
One backend per PR: PR title tags & labels: Reviews: |
…sts with new inputs, fx atomics / LDS pointers Op wrapper: - ready_counters= (flydsl_moe_a8w4_experts_workspace) lets calls that may overlap on one device use their own counter workspace; the docstring states that sharing one corrupts every later call on it, and AITER_FLYDSL_MOE_A8W4_CHECK=1 raises on a non-zero workspace before or after an eager call. - Validate x / x_scales dtypes and the weights' device; assert the combine covers every token; zero tokens or rows return an empty tensor. - The block-expert table gets one more entry: a tile also reads the next block's expert, which read one int32 past the end at a sort tier's count. - Rows entry: rows from expert_offsets[-1] on are documented as undefined. Kernels: the counters use fx.atomic_add / fx.atomic_xchg, the LDS typed fx pointers with fx.generic_load / generic_store, the requant fx.rocdl.cvt_scalef32_pk_fp8_f32 and the sort's scan fx.rocdl.update_dpp. The final gfx950 ISA of all 63 kernels the op dispatches (sort, block table, GEMM1, GEMM2, combine and the 16 fused launches) is unchanged. Each remaining raw op has a comment at its helper. Tests: graph replays with new activations, ids, weights and offsets copied into the captured buffers (top-6 and top-3, token and rows entries, bf16 input), one graph alternating both layer shapes, all ids invalid, duplicate ids / int64 ids / bf16 weights, two streams with their own workspaces, the counter check, the sort alone, GEMM1 alone over 13 configs, the weight layouts against shuffle_weight_a16w4, and from_shuffled on the tensors fused_moe holds compared with fused_moe. Outputs are also graded with checkAllclose (overall and per row); a @benchmark sweep with a markdown table runs as python3 <file>. Benchmark: the fused_moe tuned-row key comes from get_gfx_runtime() and get_cu_num(); agreement with fused_moe is the worst cosine over all calls. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> Signed-off-by: Fangzhou Ai <[email protected]>
Summary
This PR adds a FlyDSL op for the routed experts of one expert-parallel rank. It uses MXFP8 activations and MXFP4 weights (a8w4) and runs on gfx950. It covers hidden 5120 and intermediate 2304 with two routings:
Each call is two launches:
bf16(route weight * y)to its own (token, slot) row.There are no output atomics: every output element has one writer. Outputs are bitwise repeatable, and graph replay gives the same bits as eager.
Motivation
At decode token counts this layer is bound by weight streaming: one call reads 0.9 GB of MXFP4 weights and scales for 48 experts. The current a8w4
fused_moepath runs the sort, stage 1 and an atomic stage 2 as separate launches. The fused launch overlaps the end of GEMM1 with the start of GEMM2. It also keeps the requantized intermediate in GEMM2's layout and drops the atomics.The callers this op is meant for are the ones that do not run MegaMoE at this shape:
fused_moe(a8w4,swiglu_limit=10) at this shape, throughflydsl_moe_a8w4_experts;flydsl_moe_a8w4_experts_rows.It does not replace MegaMoE (see Related).
Changes
aiter/ops/flydsl/kernels/moe_a8w4_experts.pyholds the kernels: sort / block table, GEMM1, GEMM2, combine, and the fused GEMM1 + GEMM2 + combine launch.aiter/ops/flydsl/moe_a8w4_experts.pyis the op wrapper:moe_a8w4_experts_supported;flydsl_moe_a8w4_experts_workspace.Everything is exported lazily from
aiter.ops.flydsl.op_tests/flydsl_tests/test_flydsl_moe_a8w4_experts.pyhas two parts. The pytest correctness suite is added to the CI file lists in.github/scripts/{split_tests,aiter_test}.sh. The@benchmarksweep runs aspython3 <file>.op_tests/flydsl_tests/bench_flydsl_moe_a8w4_experts.pyis a graph-replay A/B againstaiter.fused_moe. It is not collected by pytest.API:
x. Either MXFP8 (e4m3[n, 5120]plus row-major e8m0x_scales[n, 160]) or bf16[n, 5120]withx_scales=None. Other dtypes (int8, fnuz) are rejected.topk_idsholds local expert ids. An id outside[0, E), such as-1padding or another rank's expert, contributes zero.return_slots=True. Returns the weighted slots[n, topk, 5120]instead of their sum.flydsl_moe_a8w4_experts_rows(x, x_scales, w, row_weights, expert_offsets, topk)takes rows already sorted by expert. Rowr < expert_offsets[-1]isbf16(row_weights[r] * expert(x[r])). The rows fromexpert_offsets[-1]on are undefined: they are not written, and the output is allocated uninitialized.n == 0(orR == 0) returns an empty tensor and launches nothing.ready_counters=. Takes a workspace fromflydsl_moe_a8w4_experts_workspace(); see Breaking Changes / limitations.Supported shapes and dispatch rule.
moe_a8w4_experts_supported(hidden, inter, num_local_experts, topk, num_tokens=None, swiglu_limit=10.0)returns True only when all of these hold:get_gfx_runtime());swiglu_limitis 10, i.e.silu(min(gate, 10)) * clamp(up, -10, 10).Callers fall back to
fused_moeotherwise. Within the range, the token count picks one of four tile tiers per top-k (16-, 32-, 64- or 128-row blocks;_DISPATCHin the wrapper).Performance (if applicable)
Setup:
aiter.fused_moeon upstream main at this PR's base (9569fb31a): a8w4,QuantType.per_1x32,swiglu_limit=10,quant_dtype_a=fp8. It uses its own dispatch, i.e. the tuned rows inmodel_configs/dsv41_fp8fp4_tuned_fmoe.csv, and reads identical weight bytes. Between the base and current main there are 9 commits, and none of them touchesfused_moe, the a8w4 kernels or that CSV.--baseline best).E = 48, top-6 (
bench_flydsl_moe_a8w4_experts.py --experts 48 --topk 6 --baseline default best)E = 16, top-3, 4 weight sets (
--experts 16 --topk 3 --layers 4 --tokens 16 40 80 160 320 640 1024 --baseline default best)(1) With no tuned row for E=16/top-3 at padded M=16,
fused_moefalls back to a CK stage 1, which raisesNotImplementedError: CK MoE stage1 cannot apply swiglu_limit=10.0 for QuantType.per_1x32 with weight dtype torch.float4_e2m1fn_x2.Spot check at this revision (
3662841e9). The final ISA of all kernels is unchanged; the re-run is on another GPU of the shared node. Here the agreement withfused_moeis the worst cosine over all 100 calls of each graph.Both sides moved by up to about 4 % between the two sessions; the ordering and gaps are the same.
Roofline / limit (E = 48, uniform). The bytes per call count:
The intermediate and slot traffic is not counted because it mostly stays in L2/MALL, so these fractions are conservative. The ceiling is the 7.15 TB/s HBM read rate this machine reaches with a non-temporal dwordx4 stream (8 TB/s peak).
Cold start.
flydsl_moe_a8w4_experts_warmupcompiles 13 (top-6) or 14 (top-3) token counts per mode. Measured in sequence on one process:There is no AOT prebuild entry yet (
aiter/aot/flydsl/); it is left to a follow-up. The expert count is a compile-time constant, so the entry needs the deployed counts (48, 16 and the EPLB counts).Testing
moe_a8w4_experts_supporteddeclines other archsDocumentation
Dependencies
requirements.txtpins.Breaking Changes
None. The op is new, and no existing op, config or dispatch changes.
Known limitations:
ready_counters=, all calls on a device share one workspace. Two calls that run at the same time on one workspace (e.g. from two streams) add into the same counters. A consumer can then pass its wait early, giving silent wrong outputs. The counters can also be left non-zero, which corrupts or hangs every later call on that workspace, not only the overlapping ones. To avoid this, give each stream that may overlap another its own workspace:ready_counters=flydsl_moe_a8w4_experts_workspace(), allocated before capture.AITER_FLYDSL_MOE_A8W4_CHECK=1synchronizes around each eager call and raises on a non-zero workspace. Sequential calls on one stream are fine, for example all layers of a forward pass, or a target model followed by its draft model.flydsl_moe_a8w4_experts_warmupbefore capturing a graph.fused_moe. Outputs differ only through rounding order: this op sums the bf16 slots in a fixed order instead of with atomics.PR Self-Review
Reviewed revision
3662841
Behavior and intent
The PR adds a new, opt-in op. Nothing calls it until a caller checks
moe_a8w4_experts_supportedand switches to it.swiglu_limit=10, on gfx950.fused_moepath runs sort, stage 1 and an atomic stage 2 as separate launches. At these shapes this op takes 4-50 % less time per call (tables above), and at E16/top-3 with 16 tokensfused_moeraises without a tuned row.Validation and unverified scope
All runs used MI355X (gfx950), FlyDSL 0.5.0, and
PYTHONPATH=<worktree>:<flydsl 0.5.0>.Tests and benchmarks
python3 -m pytest -q op_tests/flydsl_tests/test_flydsl_moe_a8w4_experts.py: 153 passed in 39 s. The suite covers:shuffle_weight_a16w4;from_shuffledon the tensorsfused_moeholds: no copy, cosine >= 0.9999 againstfused_moeitself;Outputs are graded three ways:
checkAllclose(atol scaled per row; at most 0.1 % of elements and 5 % of any row outside it), whole-output cosine >= 0.99999, and per-row cosine >= 0.9999. For scale, one zeroed output row puts 98 % of that row outside the tolerance.python3 op_tests/flydsl_tests/test_flydsl_moe_a8w4_experts.py: the@benchmarksweep (tokens x {E48/top-6, E16/top-3} x {mxfp8, bf16} x {uniform, skew}). It prints the markdown table with us, TFLOPS, TB/s and thecheckAllcloseerror.bench_flydsl_moe_a8w4_experts.py: the tables above.The review's adversarial script ran too: 33 checks of replay with new inputs, counters, bf16 and rows replays, invalid ids and mixed graphs. All passed.
ISA identity
The kernels now use
fx.atomic_*, typed LDS pointers withfx.generic_load/generic_store,fx.rocdl.cvt_scalef32_pk_fp8_f32andfx.rocdl.update_dpp. A CPU-only compile (COMPILE_ONLY=1,FLYDSL_COMPILE_ARCH=gfx950,FLYDSL_DUMP_IR=1) of all 63 kernels the op dispatches gives the same final ISA as before the change. Those kernels are the sort and block-table tiers, GEMM1, GEMM2, combine, and the 16 fused launches.Not verified / remaining
_mfma,_hold): the accumulators must stay in AGPRs, and LLVM's hazard recognizer does not see the inline asm;_poll: at the 0.5.0 pin the ROCDL dialect has no i32 buffer atomic add, andBufferAtomicAddis anfx.copyatom without a return value;buffer_opsglobal loads / stores and the async LDS DMA (_load8,_dma): these are gathered by token with a per-load cache policy. Moving them tofx.make_buffer_tensor+fx.copy(BufferCopy128b,BufferLoadAsyncLDS128b) is not done in this PR. It needs the same ISA-identity check, or a benchmark showing no loss.PR-specific question
What permissions and untrusted-input boundary does this CI change have, and can fork PR code or text reach a privileged execution path?
The CI change only adds this PR's test file to two existing file lists:
.github/scripts/split_tests.sh;.github/scripts/aiter_test.shthat runs a file withpython3 -m pytest -qinstead ofpython3 <file>.It adds no workflow, job, secret, token, permission or label trigger. It reads no PR title, body or branch name. The file it names already runs inside the existing aiter test job with that job's permissions. So no fork PR code or text reaches a more privileged path than the test job already gives every PR's op tests.
Changed op tests
op_tests/flydsl_tests/test_flydsl_moe_a8w4_experts.py(new). This is the only test of this op; no canonical test covers it. Each group would fail on a specific bug:fused_moecomparison fails iffrom_shuffledmisreadfused_moe's layout;CI runs it with pytest (as
test_gemm2_valid_token_count.pyis run). Itsmain()is the perf sweep for manual runs.op_tests/flydsl_tests/bench_flydsl_moe_a8w4_experts.py(new). This is the graph-replay A/B againstfused_moe(default dispatch or the best of 40 tuned pairs) behind the tables above. It is not collected by pytest.Related
[FlyDSL] MegaMoE small-M: DeepSeek-V4.1-Flash, any experts per rank / top-k, fused shared-expert slots #8358 (open, MegaMoE small-M) admits DeepSeek-V4.1-Flash 5120/2304 at 384 experts/top-6 and 128/top-3, i.e. the same model and shapes, on the served DEP8 MoE backend. MegaMoE runs dispatch, experts and combine across the 8 ranks in one persistent kernel. This PR covers only the single-rank / rows-entry path:
fused_moethat do not use MegaMoE;flydsl_moe_a8w4_experts_rows.No per-rank comparison against MegaMoE was measured. Its time includes the cross-rank dispatch and combine, so an equal-footing comparison needs an 8-rank run.
MegaMoE EP: [FlyDSL] MegaMoE EP: expert-parallel MoE as one persistent kernel #7859, [FlyDSL] [DSV41] MegaMoE improvements for DEP8 #8186, [FlyDSL] MegaMoEV2: enable the small and large routes for DeepSeek-V4-1-Flash EP8 #7968.
[FlyDSL] Fused expert-parallel MoE in one launch per rank for DeepSeek-V4.1-Flash EP8 a8w4 (gfx950) #8368 (draft) fuses dispatch, these expert tiles and combine into one launch per rank for EP8 at the same shape. This PR is the standalone single-rank experts op, usable with any dispatch.
The tuned a8w4 rows for this shape are in
aiter/configs/model_configs/dsv41_fp8fp4_tuned_fmoe.csv; they are the "Before" baseline above.A vLLM draft PR will add the call site behind a flag and depend on this one.
E2E status
End-to-end DeepSeek-V4.1-Flash DEP8 AgentX results pending.
AI assistance (Claude Code) was used to write this change; Fangzhou Ai is the human owner and will review/defend it end-to-end.
🤖 Generated with Claude Code