Repository navigation
[CK] [FlyDSL] Add FlyDSL FP8 MoE kernels (decode weight-decompression + prefill) for MI308 — Qwen3.5-35B/397B, Hunyuan3 - #3987
Conversation
🏷️ CI GuideRuns automatically on every PR:
Extended tests (opt-in via labels):
|
dd12beb to
64eb0c0
Compare
There was a problem hiding this comment.
Pull request overview
Adds a gfx942-specific FlyDSL implementation of fused MoE that performs on-the-fly FP8→BF16 weight decompression to reduce decode-time overhead, and integrates it into the existing tuning/config selection pipeline so tuned CSVs can select the new implementation.
Changes:
- Introduces FlyDSL JIT kernels for 2-stage MoE GEMMs on gfx942 with FP8 weight decompression.
- Adds a gfx942 “stage0” dispatch path in
fused_moeto route tuned configs to the new end-to-end implementation. - Extends the tuning script with
--e2e_tuneand optional extra bf16-reference comparison; adds tuned/untuned model config CSVs for Qwen3.5 and Hunyuan3.
Reviewed changes
Copilot reviewed 9 out of 9 changed files in this pull request and generated 4 comments.
Show a summary per file
| File | Description |
|---|---|
| csrc/ck_gemm_moe_2stages_codegen/gemm_moe_tune.py | Adds --e2e_tune flow, target_fused_moe injection, and optional extra reference checking. |
| aiter/utility/base_tuner.py | Adds --e2e_tune CLI flag to the common tuner argument set. |
| aiter/ops/flydsl/kernels/moe_gemm_2stage_gfx942.py | New FlyDSL kernels implementing split-k/batch1 MoE GEMMs with FP8 weight decompression. |
| aiter/fused_moe.py | Adds MOEMetadata.stage0 and dispatch logic for fused_moe_gfx942__* tuned configs. |
| aiter/fused_moe_gfx942.py | New end-to-end gfx942 implementation that compiles/launches FlyDSL kernels and handles small-batch paths. |
| aiter/configs/model_configs/qwen3_5_397b_fp8_ptpc_untuned_fmoe.csv | Adds untuned shape list for Qwen3.5 fp8 ptpc. |
| aiter/configs/model_configs/qwen3_5_397b_fp8_ptpc_tuned_fmoe.csv | Adds tuned selections pointing to fused_moe_gfx942__16_False for decode batch sizes. |
| aiter/configs/model_configs/hunyuan3_fp8_per_tensor_untuned_fmoe.csv | Adds untuned shape list for Hunyuan3 fp8 per-tensor. |
| aiter/configs/model_configs/hunyuan3_fp8_per_tensor_tuned_fmoe.csv | Adds tuned selections pointing to fused_moe_gfx942__16_False for decode batch sizes. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
64eb0c0 to
f70ee08
Compare
7852723 to
f90419c
Compare
f90419c to
83faaba
Compare
a4791c0 to
b7ac1a2
Compare
7fcf82a to
d67f011
Compare
There was a problem hiding this comment.
🟡 Changes recommended
Unresolved kernel-loop, dispatch validation, output-buffer, and tuner eligibility issues require fixes.
Get a fresh assessment by requesting another Copilot review.
Review details
Suppressed comments (4)
aiter/fused_moe.py:1284
- This whole-graph branch always allocates
full_outputinside the FlyDSL backend and then_return_outputperformsoutput.copy_(full_output)when the caller suppliesoutput. That adds an allocation and device copy on every tuned FlyDSL call, defeating the publicoutputcontract (which is intended to let the caller avoid a copy). Pass the destination through the whole-graph request/backend and write into it, or explicitly handle this path as an unsupported output-buffer case instead of silently taking the slower path.
return _return_output(full_output, output)
aiter/fused_moe.py:3063
- [verified] This FlyDSL dispatch gate rejects several unsupported options but never checks
a1_scaleora2_scale, even thoughrun_flydsl_moe_gfx942_implraisesNotImplementedErrorfor either ataiter/ops/flydsl/fused_moe_gfx942.py:621. For a matching gfx942 FP8 per-tensor row, a caller can legally provide static activation scales with BF16 hidden states; the new whole-graph path is then selected and raises instead of falling back to the existing quantized implementation. Author must add these scale fields to the metadata validation (or pass them into a shared validator) before returningfull_impl.
elif gate_mode is not GateMode.SEPARATED:
unsupported = f"gate mode {gate_mode.value!r}"
elif activation not in (ActivationType.Silu, ActivationType.Swiglu):
unsupported = f"activation {activation}"
aiter/ops/flydsl/fused_moe_gfx942.py:624
- These backend checks occur after metadata selection, but
get_2stage_cfgsdoes not receivea1_scale/a2_scaleor an explicitblock_size_Mwhen deciding whether to returnfull_impl. A valid call with one of those options can therefore select this implementation and raise here instead of falling back to the normal dispatch. Add these capability checks to the metadata gate (or pass the options into selection) before returningfull_impl.
if request.a1_scale is not None or request.a2_scale is not None:
raise NotImplementedError(
"gfx942 FlyDSL whole-graph backend does not support prequantized activations"
)
csrc/ck_gemm_moe_2stages_codegen/gemm_moe_tune.py:5990
- The prefill eligibility check is weaker than the compiler constraint:
compile_gemmrequires an even number ofK // TILE_Ktiles, but this admits anymodel_dimdivisible by 128. For a valid input such asmodel_dim=384, each prefill candidate reaches JIT compilation and is rejected, so the tuner spends time on guaranteed failures and can miss all prefill candidates. Use the same2 * config.BLOCK_Kdivisibility constraint (or a sharedunsupported_reasoncheck) here.
and int(row["inter_dim"]) % 64 == 0
and int(row["model_dim"]) % 128 == 0
- Files reviewed: 16/17 changed files
- Comments generated: 1
- Review effort level: Lite
There was a problem hiding this comment.
🟡 Changes recommended
One or more issues must be addressed before approval.
Get a fresh assessment by requesting another Copilot review.
Review details
Suppressed comments (6)
aiter/configs/model_configs/hunyuan3_fp8_per_tensor_tuned_fmoe.csv:2
- [verified] This tuned file contains 6144/384/E=128/topk=4 rows, which do not match the Hunyuan3 input (4096/192/E=192/topk=8). The runtime lookup is keyed by these dimensions, so Hunyuan3 requests will not select these FlyDSL entries and the file can expose unrelated tuned rows under the Hunyuan3 config path. Author must regenerate this CSV from the matching untuned input and verify the model-specific dimensions before committing it.
gfx942,80,1,4096,192,192,8,ActivationType.Silu,torch.bfloat16,torch.float8_e4m3fnuz,torch.float8_e4m3fnuz,QuantType.per_Tensor,1,0,16,0,16.676653061224552,impl__flydsl_gfx942__16_16_16_False,74.63%,0.0,,0%,16.676653061224552,0,0,0,0.0,0.0,
aiter/configs/model_configs/minimax_m3_fp8_ptpc_tuned_fmoe.csv:2
- [verified] This tuned file contains 2048/128/E=257/topk=9 rows, which are the Qwen3.5-35B shapes, not the Minimax M3 input (6144/384/E=128/topk=4). The runtime lookup is keyed by these dimensions, so Minimax requests will not select these FlyDSL entries and the file can expose unrelated tuned rows under the Minimax config path. Author must regenerate this CSV from the matching untuned input and verify the model-specific dimensions before committing it.
gfx942,80,1,6144,384,128,4,ActivationType.Swiglu,torch.bfloat16,torch.float8_e4m3fnuz,torch.float8_e4m3fnuz,QuantType.per_Token,1,0,16,0,21.59386999999993,impl__flydsl_gfx942__16_16_16_False,80.19%,0.0,,0%,21.59386999999993,0,0,0,0.0,0.0,
aiter/configs/model_configs/qwen3_5_35b_fp8_ptpc_tuned_fmoe.csv:2
- [verified] This tuned file contains 4096/128/E=513/topk=11 rows, which are the Qwen3.5-397B shapes, not the Qwen3.5-35B shapes declared by the filename (the matching untuned file is 2048/128/E=257/topk=9). The runtime lookup is keyed by these dimensions, so Qwen3.5-35B requests will not select these FlyDSL entries. Author must regenerate this CSV from the matching untuned input and verify the model-specific dimensions before committing it.
gfx942,80,1,2048,128,257,9,ActivationType.Silu,torch.bfloat16,torch.float8_e4m3fnuz,torch.float8_e4m3fnuz,QuantType.per_Token,1,0,16,0,11.453785714285916,impl__flydsl_gfx942__16_16_16_False,46.53%,0.0,,0%,11.453785714285916,0,0,0,0.0,0.0,
aiter/configs/model_configs/qwen3_5_397b_fp8_ptpc_tuned_fmoe.csv:2
- [verified] This tuned file contains 4096/192/E=192/topk=8 rows, which are the Hunyuan3 shapes, not the Qwen3.5-397B shapes declared by the filename (the matching untuned file is 4096/128/E=513/topk=11). The runtime lookup is keyed by these dimensions, so Qwen3.5-397B requests will not select these FlyDSL entries. Author must regenerate this CSV from the matching untuned input and verify the model-specific dimensions before committing it.
gfx942,80,1,4096,128,513,11,ActivationType.Silu,torch.bfloat16,torch.float8_e4m3fnuz,torch.float8_e4m3fnuz,QuantType.per_Token,1,0,16,0,15.652304347826007,impl__flydsl_gfx942__16_16_16_False,68.26%,0.0,,0%,15.652304347826007,0,0,0,0.0,0.0,
aiter/fused_moe.py:1284
- The whole-graph implementation has no destination-buffer argument, so this return path always copies its newly allocated result into
outputwhen callers use the documentedoutput=parameter. That defeats the zero-copy output-buffer behavior of the legacy paths and adds a full[M, model_dim]device copy for every tuned FlyDSL call with an output buffer. Forward the destination throughFusedMoeRequest/the backend (or avoid selecting this implementation whenoutputis supplied).
return _return_output(full_output, output)
op_tests/tuning_tests/test_online_tune.py:452
- [verified] This test only resolves metadata with
_whole_graph_test_impl, whose body returnsrequest.hidden_states; it never executesrun_flydsl_moe_gfx942or a real decode/prefill FP8 kernel. Consequently, registration can pass while the new backend's argument contract or numerical behavior is broken, and the added test provides no automated coverage for the runtime path this PR ships. Author must add an independent gfx942 runtime test for at least one decode and one prefill configuration, or explicitly gate the dispatch until such coverage exists.
def test_whole_graph_kernel_name_is_stripped(self):
from aiter import ActivationType, QuantType, dtypes
from aiter.fused_moe_registry import (
make_fused_moe_impl_kernel_name,
register_fused_moe_impl,
)
fused_moe = importlib.import_module("aiter.fused_moe")
implementation_name = "test_whitespace"
register_fused_moe_impl(
implementation_name, f"{__name__}:_whole_graph_test_impl"
- Files reviewed: 16/17 changed files
- Comments generated: 2
- Review effort level: Lite
There was a problem hiding this comment.
🟡 Changes recommended
Unresolved critical and moderate issues must be addressed before approval.
Get a fresh assessment by requesting another Copilot review.
Review details
Suppressed comments (3)
aiter/ops/flydsl/fused_moe_gfx942.py:238
_run_prefillhard-codes the sorting policy to0, so any request with a nonzeromoe_sorting_dispatch_policyis silently routed through the wrong sorting implementation. The public entry point already receives this policy and the decode path forwards it; pass it through the prefill signature/call and use it here, or reject nonzero policies in the whole-graph capability gate.
0,
csrc/ck_gemm_moe_2stages_codegen/gemm_moe_tune.py:3253
- [verified] The exclusion helper is not applied to the
ck_stage1_kernelsloop above this CK stage-2 filter (and the separate one-stage generators also add candidates without checking it). A pattern that names a CK/one-stage stage-1 kernel therefore still leaves that candidate eligible, contradicting the new environment variable's documented "kernel-name substrings" contract and allowing a known-bad kernel to be selected. Author must apply the exclusion predicate consistently to every stage-1/stage-2 candidate generator or narrow/document the variable's scope.
if _is_tune_excluded_kernel(kernel.name):
continue
csrc/ck_gemm_moe_2stages_codegen/gemm_moe_tune.py:7086
- [verified] This dispatch accepts
--e2e_tuneforGroupedFmoeTunerandMxfp4FlydslTuneras well as the standard tuner, but both subclasses inherit this FP8-specifice2e_tune()implementation. It imports the gfx942 FP8 tuning space and later builds rows using the standard FMoE result layout, so those modes can either benchmark the wrong backend or fail while constructing the output instead of running their own tuning path. Author must reject--e2e_tunefor the grouped and MXFP4 modes (or provide mode-specific implementations) before entering this branch.
if args.e2e_tune:
tuner.pre_process(args)
tuner.e2e_tune(args)
- Files reviewed: 16/17 changed files
- Comments generated: 2
- Review effort level: Lite
There was a problem hiding this comment.
🟡 Changes recommended
One or more issues must be addressed before approval.
Get a fresh assessment by requesting another Copilot review.
Review details
Suppressed comments (5)
aiter/fused_moe.py:3055
- The guard only rejects non-BF16
input_dtype, but it does not reject an outputdtypedifferent from the input. A valid call with BF16 hidden states anddtype=torch.float16can therefore select this full-graph implementation, after whichrun_flydsl_moe_gfx942_implraisesNotImplementedErrorfor output conversion instead of falling back to the existing path. Filter this case here so unsupported output conversion does not turn dispatch into a runtime failure.
elif input_dtype is not None and input_dtype != dtypes.bf16:
unsupported = f"activation dtype {input_dtype}"
aiter/fused_moe.py:3052
- The FlyDSL eligibility check also ignores the caller's
block_size_Moverride. Metadata is resolved without that argument, and_fused_moe_implpreserves a non-Noneoverride before constructing the request; a mismatch therefore reachesrun_flydsl_moe_gfx942_impl, which raisesNotImplementedErrorinstead of falling back. Reject the whole-graph candidate whenblock_size_Mis set to a value other thanmetadata.block_m(or include it in the resolver key).
if not weights_shuffled:
unsupported = "both w1 and w2 must be marked is_shuffled=True"
elif has_stage1_bias or has_stage2_bias:
unsupported = "per-expert bias"
elif doweight_stage1:
aiter/ops/flydsl/fused_moe_gfx942.py:76
- The prefill down kernel processes
N / 128output tiles in pairs and its epilogue assumes that count is even, but this gate only rejectsmodel_dim % 128. For a valid-looking shape such asmodel_dim=384, it can load tilen+3past the weight tensor and produce a duplicated/wrong output. Requiremodel_dim % 256 == 0here, and apply the same constraint in the tuner eligibility check.
if self.use_prefill and problem.model_dim % 128 != 0:
return (
f"model_dim={problem.model_dim} is not divisible by 128; "
"the prefill down kernel processes paired 64-wide tiles"
aiter/ops/flydsl/fused_moe_gfx942.py:311
sorted_expert_idsis allocated by_flydsl_moe_sortingat the maximum padded block count, so this allocatessorted_expert_ids.shape[0] * BLOCK_Mroute rows rather than the actualnum_valid_ids. For example, Hunyuan3 at M=512/E=192 allocates 16,384 rows for 4,096 real routes (4x), and the corresponding BF16 buffer is about 128 MiB; this extra allocation and memory traffic can cause avoidable VRAM pressure and erase the prefill speedup. Use a compact valid-block count or avoid materializing the padded per-route output buffer.
[sorted_expert_ids.shape[0] * config.BLOCK_M, problem.model_dim],
dtype=hidden_states.dtype,
device=hidden_states.device,
)
csrc/ck_gemm_moe_2stages_codegen/gemm_moe_tune.py:4871
- The validation gate still accepts a candidate when
err_ratiois below the allowed threshold even if the output contains NaNs:torch.isclosecounts NaNs as mismatches (which may be a small fraction), whilelogits_diffbecomes NaN. That allows a partially-NaN kernel to receivestatus == "ok"and win tuning. Reject non-finite output/reference tensors before applying the error/cosine pass condition.
f"logits_diff={logits_diff:.6g}(>{cos_tol}),"
f"diagnostics={diag}"
- Files reviewed: 16/17 changed files
- Comments generated: 2
- Review effort level: Lite
There was a problem hiding this comment.
🟡 Changes recommended
Critical dispatch, batch-1 launch, and e2e tuning issues remain unresolved.
Get a fresh assessment by requesting another Copilot review.
Review details
Suppressed comments (2)
aiter/ops/flydsl/init.py:112
- This is the only registration of
flydsl_gfx942, but importingaiteroraiter.fused_moedoes not importaiter.ops.flydsl; production callers can therefore read a tunedimpl__flydsl_gfx942__...row before this package is imported, resolve it as an unknown implementation, and fail the exact-config path instead of dispatching. Register the implementation from the fused-MoE dispatch initialization (or explicitly import this module before resolving tuned rows).
_fused_moe_impl_path = "aiter.ops.flydsl.fused_moe_gfx942:run_flydsl_moe_gfx942_impl"
register_fused_moe_impl("flydsl_gfx942", _fused_moe_impl_path)
csrc/ck_gemm_moe_2stages_codegen/gemm_moe_tune.py:6022
- When
eligible_indicesis a filtered subset (for example, an input containing anydoweight_stage1rows),self.untunedfhas already been restored to the full dataframe in thefinallyblock, but this indexes it with the original full-dataframe indexi. The row used to buildself.calculate(...)can therefore belong to a different shape and produce incorrect metadata in the tuned CSV. Use the result's row (k["row"]) or index the eligible subset byresult_indexinstead.
row = self.untunedf.iloc[i]
- Files reviewed: 17/18 changed files
- Comments generated: 3
- Review effort level: Lite
Motivation
FP8 MoE on MI308X (gfx942) has overhead from
moe_sortingand inter-stagequantization. This PR adds FlyDSL JIT kernels that dequantize FP8 weights
on-the-fly to BF16 for the GEMM, covering both the decode (small-batch,
weight-decompression) and prefill (large-batch) paths. Based on the approach
from #3309, reimplemented as FlyDSL JIT kernels instead of pre-compiled AOT
binaries.
What's included
aiter/ops/flydsl/kernels/moe_gemm_2stage_gfx942.py) withon-the-fly FP8→BF16 weight decompression for the decode and prefill MoE GEMM.
aiter/fused_moe_gfx942.py+aiter/fused_moe.py(
MOEMetadata.stage0routing offused_moe_gfx942configs).csrc/ck_gemm_moe_2stages_codegen/gemm_moe_tune.py(
--e2e_tune), plus anAITER_FMOE_TUNE_EXCLUDE_KERNELSknob (comma-separatedkernel-name substrings) to keep a known-bad kernel out of a model's tuned
config.
Performance (MI308X, gfx942)
Baseline = pre-PR aiter default dispatch; FlyDSL = best tuned config per shape.
End-to-end latency (μs), measured by the tuner harness.
Qwen3.5-35B — geomean 1.22x
Qwen3.5-397B — geomean 1.17x
Hunyuan3 — geomean 1.75x
† For a few batch sizes (35B: 256/512; 397B: 256/512/1024; Hunyuan3: 256) the
FlyDSL kernel is slower than baseline; the tuner auto-selects the faster CK/asm
kernel there, so end-to-end dispatch never regresses below baseline.
Correctness: all tuned shapes pass
op_tests/test_moe_2stage.py(cosine-similarity accuracy gate); the FlyDSL kernels are the selected dispatch
for the tuned shapes. For Qwen3.5-397B, one ASM stage1 kernel
(
fmoe_stage1_bf16_pertokenFp8_g1u1_16x64_5tg_pf3) passes per-stage tuning butemits NaN end-to-end at E=513 — it leaves the padded sorted-token rows
unwritten, which a CK stage2 then reads. It is kept out of the candidate set via
AITER_FMOE_TUNE_EXCLUDE_KERNELSso the tuner falls back to an accurate CK2-stage combo (scoped to the 397B tune; other models are unaffected).
Tune & Test
Run from the repository root on an idle MI308X/gfx942 GPU 2.
Results are written directly to the corresponding model tuned CSVs.
Explicitly select staged FlyDSL v2, CK, and FlyDSL candidates. ASM is excluded
because large-token stage1 launches may exceed the
grid.ylimit of 65535.Verification
[fused_moe] using ... for (...)to confirm the selected kernels.impl__flydsl_gfx942__...identifies a whole-graph FlyDSL configuration;kernelName1/kernelName2identify staged kernels.OK, with noERROR,MISMATCH, orSKIP.A zero exit code alone does not guarantee correctness.
The Qwen3.5-397B exclusion records its known NaN-producing ASM kernel.
It only affects searches that enable ASM; it does not filter whole-graph
e2e candidates.
Limitations
Co-authors: [email protected]