Repository navigation
kimi a16wi4 moe support - #2863
Conversation
- force expert balanced distribution in test_moe_2stage.py - disable split_k for a8w4 (fp8 activation) in cktile moe 2stage - make bf16_fp8_bound configurable via AITER_BF16_FP8_BOUND env var Made-with: Cursor
…v/a16wi4_a8w4_merge
🏷️ CI GuideRuns automatically on every PR:
Extended tests (opt-in via labels):
|
There was a problem hiding this comment.
Remaining comments which cannot be posted as a review comment to avoid GitHub Rate Limit
ruff
Local variable c_k0 is assigned to but never used
Local variable layout_lin_rowcol is assigned to but never used
Local variable layout_x_div4 is assigned to but never used
Local variable c_n0 is assigned to but never used
Local variable c2_tile_k is assigned to but never used
Local variable gpu_arch is assigned to but never used
Local variable DYN is assigned to but never used
Local variable USE_NONTEMPORAL is assigned to but never used
Local variable VEC_ALIGN is assigned to but never used
Local variable masked is assigned to but never used
Do not assign a lambda expression, use a def
Do not assign a lambda expression, use a def
Local variable i32_type is assigned to but never used
Do not assign a lambda expression, use a def
rearrange_4bit_elements may be undefined, or defined from star imports
convert_int8_to_uint32_int4 may be undefined, or defined from star imports
The a16wi4 path requires block_m == kn1.tile_m == kn2.tile_m for
correctness. Make this constraint explicit in gen_flydsl_i4_2stages_task
and remove the now-unreachable _sbm{blockM} fallback. Also fix one stale
row in kimik2_i4_tuned_fmoe.csv (token=64) that paired block_m=16 with a
stage2 t32x... kernel and was failing op_tests/test_moe_2stage.
Co-Authored-By: Claude Opus 4 <[email protected]>
Cherry-pick audit for v0.1.13 release branchEvaluated this PR for cherry-pick onto Critical findings
RecommendationIf int4 MoE support is needed for v0.1.13, request a separate backport PR that isolates the additive-only changes (new |
* initial a16wi4 * update * moe benchmark patches for kimi poc --------- Co-authored-by: lalala-sh <[email protected]> Co-authored-by: Zzz9990 <[email protected]> Co-authored-by: Felix Li <[email protected]> Co-authored-by: Claude Opus 4 <[email protected]> # Conflicts: # op_tests/test_moe_2stage.py
* initial a16wi4 * update * moe benchmark patches for kimi poc --------- Co-authored-by: lalala-sh <[email protected]> Co-authored-by: Zzz9990 <[email protected]> Co-authored-by: Felix Li <[email protected]> Co-authored-by: Claude Opus 4 <[email protected]>
* perf(flydsl): MXFP4 fused-MoE stage2 optimization for EP4 prefill
Optimize the FlyDSL stage2 (down-projection) kernel for the production
fp4xfp4 EP4 DeepSeek prefill shape (tile_m=64, tile_n=128, tile_k=256,
M=49152) on MI355X.
## Summary of changes
aiter/ops/flydsl/moe_kernels.py
- Add new wrapper params (waves_per_eu, use_async_copy, cu_num_mul) and
plumb them through compile_flydsl_moe_stage2 -> compile_mixed_moe_gemm2.
- Register a production fp4xfp4 stage2 variant
`flydsl_moe2_afp4_wfp4_bf16_t64x128x256_atomic_persist_async_w4_cumul3`
with waves_per_eu=4, use_async_copy=True, cu_num_mul=3.
- Drop the defensive `out.fill_(0)` added in PR #2863: when accumulate=True
the standard fused_moe path already zeros moe_buf via
`moe_buf_set_zero_kernel_2d` inside `moe_sorting_*_fwd`. The extra
fill is a ~token_num*model_dim HBM write (~130 us per call at MI355X
HBM bw on this shape). Callers using flydsl_moe_stage2 directly with
accumulate=True remain responsible for zeroing `out` (documented).
aiter/ops/flydsl/kernels/mixed_moe_gemm_2stage.py
- compile_mixed_moe_gemm2 signature: add waves_per_eu, use_async_copy,
cu_num_mul. Drop unused legacy b_nt, xcd_swizzle on this path.
- cu_num_mul: multiplies persistent-mode grid_y (CU count) by an integer
factor; cu_num_mul>1 launches more persistent CTAs that each cover
fewer M tiles, increasing in-flight parallelism. cu_num_mul=3 is the
EP4-prefill sweet spot; cu_num_mul=4 regresses ~2.4% on the same shape.
- use_async_copy: enable raw_ptr_buffer_load_lds for the X (activation)
tile in the prologue so the X DMA overlaps with B/scale VMEM. Gated
to the production tile/dtype combo so other configs are unaffected.
- Asymmetric b_lo/b_hi split (b_lo loads 3/4 of K, b_hi loads 1/4): the
smaller b_hi burst frees VMEM issue slots right before s_setprio(1)
and the K-loop; the extra ku of b_lo is issued in the prologue where
it overlaps with the X DMA.
- Stage sorted topk weights into LDS once per M-tile and prefetch via
vec4 LDS reads in the cshuffle epilogue, eliminating per-mi VMEM
dwordx4 loads from the MFMA-heavy hot loop.
- Emit AMDGPU `disable_xdl_arb_stall` + `s_setprio(1)` around the
K-loop on gfx950 so the high-prio K-loop drains MFMAs back-to-back.
- Issue scales BEFORE B-VMEM in the steady-state K-loop so the
extract-time stalls in the first MFMA chunk are reduced.
- Defer the lds_tid prologue (sorted_idx/sorted_w VMEM dwords + LDS
stores) to AFTER the long-latency X DMA + B/scale loads, hiding the
lds_tid scalar load latency behind the dominant VMEM phase.
- Merge the lds_tid + lds_tw prologue store guards into a single
scf.IfOp so MLIR can co-schedule the two VMEM buffer_loads.
- For the buffer-atomic path: fast-path the cshuffle row token-index
load (move the AND + multiply + validity-mask into the lds_tid
preload site where it overlaps with B/scale/X VMEM loads).
- Balanced persistent tile distribution (`tD4balPersist`) and balanced
LDS-write hint accounting on the async path (`dswr_async`).
aiter/fused_moe.py
- `_flydsl_stage2_wrapper`: forward waves_per_eu, use_async_copy,
cu_num_mul from the parsed kernel-name config to flydsl_moe_stage2.
## Performance
Benchmark harness:
/home/mingzliu/sgl_opt/ep4_mxfp4_opt/coopt_loop/scripts/bench.sh
Workload:
/home/mingzliu/sgl_opt/test_fused_moe_ep4_mxfp4.py
(M=49152, model_dim=7168, inter_dim=2048, 64 local experts, topk=8,
QuantType.per_1x32, fp4x2 weights & activations, bf16 out)
Metric: 5-run median latency, 3 reps, MI355X (smci355-ccs-aus-n06-21).
baseline (kernel=_atomic_persist): 3438.8 us (3-rep avg)
this PR (kernel=_atomic_persist_async_w4_cumul3): 3173.6 us (3-rep avg)
delta: -265 us (-7.71%)
* compat(flydsl): wrap Python-compile-time conditions with const_expr
The strict flydsl in current aiter-main rejects bare `if X:` / `elif X:`
over Python-level booleans inside a kernel emit body -- it lowers them
into `scf.if` so any Python variable assigned in either branch is
trapped inside the scf.if scope and the outer reference raises
`NameError: name '<X>' is not defined`.
`compile_mixed_moe_gemm1` already wraps every such condition with
`const_expr(...)`. The stage2 emit body in the parent commit had ~98
bare-if conditions over compile-time identifiers (`accumulate`,
`_persistent`, `doweight_stage2`, `_b_split_enabled`, `is_f4_a`,
`use_async_copy`, `_r139_xdma_first`, `_r216_defer_tid`,
`_use_buf_atomic_pre`, ...). Wrap them with `const_expr(...)` so the
condition is evaluated at Python trace time and the variable binding
escapes to the enclosing scope, matching the stage1 convention.
No semantic change: only adds `const_expr(...)` around if/elif heads
inside compile_mixed_moe_gemm2; DSL/runtime conditions (those whose
sub-expressions reference `arith.`, `buffer_ops.`, `rocdl.`, ...) are
left as bare `if` so they remain runtime `scf.if`s.
Repro (without this commit) on aiter-main runtime:
File ".../mixed_moe_gemm_2stage.py", line 3096, in moe_gemm2
shape_lds = fx.make_shape(tile_m, _eff_lds_stride)
NameError: name '_eff_lds_stride' is not defined
After this commit the kernel compiles, the end-to-end fused_moe perf
is unchanged from the parent commit on the legacy flydsl, and is
restored on aiter-main flydsl.
* update
* style(flydsl): apply Black formatting
Re-flow a handful of long if-conditions, error message strings, and
multi-arg call sites in `aiter/ops/flydsl/moe_kernels.py` and
`aiter/ops/flydsl/kernels/mixed_moe_gemm_2stage.py` so they pass the
`psf/black@stable` check in `.github/workflows/pre-checks.yaml`.
No semantic change -- pure whitespace/line-wrap. `ruff check` on the
three changed files is also clean.
* review(flydsl): fix review comments
* review(flydsl): restore stage2 xcd_swizzle + format
Wire xcd_swizzle end-to-end through compile_mixed_moe_gemm2 so the
fp4xfp4 stage2 path actually consumes it (mirrors stage1):
- signature: drop the no-op `del xcd_swizzle`, keep b_nt as no-op
- module_name: append `_xcd{N}` tag when xcd_swizzle > 0
- kernel body: remap (bx_persist, by_outer) by NUM_XCDS=8 with the
same group-of-M scheme stage1 uses, so consecutive WGs hit the
same XCD and share L2 on MI355X
- _cache_tag: include xcd_swizzle so distinct values JIT separately
Also pick up the black reflow on the production-variants tuple in
moe_kernels.py.
* review(flydsl): fix a8w4 (fp8a + fp4w) microscale gating
The 2stage compile path was mis-classifying fp8 activations: only
is_f4_a triggered the e8m0 microscale buffer-resource setup, so
fp8xfp4 per_1x32 quantized inputs fell through to a wrong/empty
scale-buffer path. This produced large output mismatches in
op_tests/test_moe_2stage.py -q 7 (logits_diff ~0.98).
Widen the gate to (is_f4_a or is_f8_a) so fp8a + fp4w (a8w4)
correctly takes the e8m0 microscale buffer-descriptor branch,
matching the pre-perf-commit behaviour.
Verified locally on MI355X:
- q=7 (a8w4) all 100 configs now PASS, max logits_diff = 1.19e-3
(same magnitude as stock baseline, vs ~0.98 before)
- 42 xcd_swizzle=4 routed variants also pass
- no change to fp4xfp4 / bf16xint4 / fp16 paths (gate only
widens the scale-buffer branch for fp8a)
* fix(aot/flydsl): default waves_per_eu to None to match runtime cache_tag
This PR added `waves_per_eu` to the stage2 `_cache_tag` tuple, but
aot/flydsl/moe.py::_precompile_to_cache still defaulted it to `3`
while compile_mixed_moe_gemm2 defaults to `None`. AOT wrote the .pkl
keyed on (..., 3, ...), runtime looked up (..., None, ...) -> AOT
cache miss on every legacy stage2 kernel (test_moe_2stage.py first
fails at t32x128x256_atomic, token=4, fp4xfp4 per_1x32).
Align AOT default with runtime default. Stage1 and the new
`_persist_async_w4_cumul3` variant are unaffected because their
base_params always pin waves_per_eu explicitly.
Signed-off-by: inkcherry <[email protected]>
---------
Signed-off-by: inkcherry <[email protected]>
Co-authored-by: Felix Li <[email protected]>
Summary
Adds a16wi4 MoE support for Kimi-K2: bf16 activations × packed int4 weights with per-1x32 bf16 groupwise scale. Includes new FlyDSL
int4_bf16stage1/stage2 kernels, a fusedswiglu_and_mulFlyDSL kernel, and tuned configs for Kimi-K2 i4 / fp8fp4.