Skip to content

kimi a16wi4 moe support - #2863

Merged
coderfeli merged 51 commits into
mainfrom
dev/a16wi4_a8w4_refactor
May 6, 2026
Merged

coderfeli merged 51 commits into
mainfrom
dev/a16wi4_a8w4_refactor

Conversation

@yadaish

@yadaish yadaish commented Apr 22, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Adds a16wi4 MoE support for Kimi-K2: bf16 activations × packed int4 weights with per-1x32 bf16 groupwise scale. Includes new FlyDSL int4_bf16 stage1/stage2 kernels, a fused swiglu_and_mul FlyDSL kernel, and tuned configs for Kimi-K2 i4 / fp8fp4.

@github-actions

Copy link
Copy Markdown
Contributor

🏷️ CI Guide

Runs automatically on every PR:

  • ✅ Pre-checks (submodule verification, code formatting)
  • ✅ Aiter op tests (gfx942 + gfx950)
  • ✅ Triton tests (only when aiter/ops/triton/** or related paths are changed)

Extended tests (opt-in via labels):

Label Tests
ci:triton-355 Run Triton tests on MI355 in addition to MI325
ci:sglang SGLang integration tests
ci:atom ATOM benchmark (DeepSeek-R1 + GPT-OSS)
ci:vllm vLLM benchmark
ci:all All of the above

Add labels via the sidebar or gh pr edit 2863 --add-label <label>

@github-actions github-actions Bot 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.

Remaining comments which cannot be posted as a review comment to avoid GitHub Rate Limit

ruff

⚠️ [ruff] <F841> reported by reviewdog 🐶
Local variable c_k0 is assigned to but never used

https://github.com/ROCm/aiter/blob/d1b7d509227408a23a42beaf9c4011f8ea7bf813/aiter/ops/flydsl/kernels/moe_gemm_2stage.py#L2335-L2335


⚠️ [ruff] <F841> reported by reviewdog 🐶
Local variable layout_lin_rowcol is assigned to but never used

https://github.com/ROCm/aiter/blob/d1b7d509227408a23a42beaf9c4011f8ea7bf813/aiter/ops/flydsl/kernels/moe_gemm_2stage.py#L2352-L2352


⚠️ [ruff] <F841> reported by reviewdog 🐶
Local variable layout_x_div4 is assigned to but never used

https://github.com/ROCm/aiter/blob/d1b7d509227408a23a42beaf9c4011f8ea7bf813/aiter/ops/flydsl/kernels/moe_gemm_2stage.py#L2482-L2482


⚠️ [ruff] <F841> reported by reviewdog 🐶
Local variable c_n0 is assigned to but never used

https://github.com/ROCm/aiter/blob/d1b7d509227408a23a42beaf9c4011f8ea7bf813/aiter/ops/flydsl/kernels/moe_gemm_2stage.py#L2603-L2603


⚠️ [ruff] <F841> reported by reviewdog 🐶
Local variable c2_tile_k is assigned to but never used

https://github.com/ROCm/aiter/blob/d1b7d509227408a23a42beaf9c4011f8ea7bf813/aiter/ops/flydsl/kernels/moe_gemm_2stage.py#L3127-L3127


⚠️ [ruff] <F841> reported by reviewdog 🐶
Local variable gpu_arch is assigned to but never used

https://github.com/ROCm/aiter/blob/d1b7d509227408a23a42beaf9c4011f8ea7bf813/aiter/ops/flydsl/kernels/moe_gemm_2stage.py#L3628-L3628


⚠️ [ruff] <F841> reported by reviewdog 🐶
Local variable DYN is assigned to but never used

https://github.com/ROCm/aiter/blob/d1b7d509227408a23a42beaf9c4011f8ea7bf813/aiter/ops/flydsl/kernels/moe_gemm_2stage.py#L3629-L3629


⚠️ [ruff] <F841> reported by reviewdog 🐶
Local variable USE_NONTEMPORAL is assigned to but never used

https://github.com/ROCm/aiter/blob/d1b7d509227408a23a42beaf9c4011f8ea7bf813/aiter/ops/flydsl/kernels/moe_gemm_2stage.py#L3634-L3634


⚠️ [ruff] <F841> reported by reviewdog 🐶
Local variable VEC_ALIGN is assigned to but never used

https://github.com/ROCm/aiter/blob/d1b7d509227408a23a42beaf9c4011f8ea7bf813/aiter/ops/flydsl/kernels/moe_gemm_2stage.py#L3635-L3635


⚠️ [ruff] <F841> reported by reviewdog 🐶
Local variable masked is assigned to but never used

https://github.com/ROCm/aiter/blob/d1b7d509227408a23a42beaf9c4011f8ea7bf813/aiter/ops/flydsl/kernels/moe_gemm_2stage.py#L3637-L3637


⚠️ [ruff] <E731> reported by reviewdog 🐶
Do not assign a lambda expression, use a def

https://github.com/ROCm/aiter/blob/d1b7d509227408a23a42beaf9c4011f8ea7bf813/aiter/ops/flydsl/kernels/moe_gemm_2stage.py#L3647-L3647


⚠️ [ruff] <E731> reported by reviewdog 🐶
Do not assign a lambda expression, use a def

https://github.com/ROCm/aiter/blob/d1b7d509227408a23a42beaf9c4011f8ea7bf813/aiter/ops/flydsl/kernels/moe_gemm_2stage.py#L3648-L3648


⚠️ [ruff] <F841> reported by reviewdog 🐶
Local variable i32_type is assigned to but never used

https://github.com/ROCm/aiter/blob/d1b7d509227408a23a42beaf9c4011f8ea7bf813/aiter/ops/flydsl/kernels/moe_gemm_2stage.py#L3648-L3648


⚠️ [ruff] <E731> reported by reviewdog 🐶
Do not assign a lambda expression, use a def

https://github.com/ROCm/aiter/blob/d1b7d509227408a23a42beaf9c4011f8ea7bf813/aiter/ops/flydsl/kernels/moe_gemm_2stage.py#L3649-L3649


⚠️ [ruff] <F405> reported by reviewdog 🐶
rearrange_4bit_elements may be undefined, or defined from star imports

https://github.com/ROCm/aiter/blob/d1b7d509227408a23a42beaf9c4011f8ea7bf813/op_tests/test_moe_2stage.py#L227-L227


⚠️ [ruff] <F405> reported by reviewdog 🐶
convert_int8_to_uint32_int4 may be undefined, or defined from star imports

https://github.com/ROCm/aiter/blob/d1b7d509227408a23a42beaf9c4011f8ea7bf813/op_tests/test_moe_2stage.py#L228-L228

@yadaish
yadaish requested a review from valarLip April 24, 2026 12:54
coderfeli and others added 5 commits April 28, 2026 08:13
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]>
@coderfeli
coderfeli merged commit 7ac56af into main May 6, 2026
30 checks passed
@coderfeli
coderfeli deleted the dev/a16wi4_a8w4_refactor branch May 6, 2026 02:32
@sunway513

Copy link
Copy Markdown
Collaborator

Cherry-pick audit for v0.1.13 release branch

Evaluated this PR for cherry-pick onto release/v0.1.13. Result: NOT SAFE to cherry-pick as-is.

Critical findings

  1. bf16_fp8_bound default changed from 256 → 512 (fused_moe.py): This threshold controls activation dtype dispatch for ALL MoE models, not just int4/Kimi. Cherry-picking this would change behavior for GLM-5, Qwen3-235B, MiniMax, and any other MoE model on the release branch.

  2. split_k dispatch rewrite introduced a bug: The CK split_k activation dispatch was completely rewritten. PR Fix CK MoE split-k dispatch for blockscale FP8 #3050 ("Fix CK MoE split-k dispatch for blockscale FP8") was needed as a follow-up to fix a QuantType comparison bug that causes wrong-sized buffer allocation and memory access faults when split_k kernels are selected from tuned configs.

  3. Catch-all else changed to explicit elif + raise in compile_flydsl_moe_stage1/2: Any existing code path that relied on the catch-all would now raise instead of silently proceeding.

  4. Merge conflict in op_tests/test_moe_2stage.py against the release branch.

Recommendation

If int4 MoE support is needed for v0.1.13, request a separate backport PR that isolates the additive-only changes (new per_1x32_i4_quant(), new shuffle functions, new config CSVs) without the bf16_fp8_bound default change or the split_k rewrite. Otherwise defer to v0.1.14.

cc @valarLip @yadaish

sunway513 pushed a commit that referenced this pull request May 6, 2026
* 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
Liang-jianhao97 pushed a commit that referenced this pull request May 7, 2026
* 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]>
sunway513 added a commit that referenced this pull request May 7, 2026
inkcherry added a commit that referenced this pull request May 25, 2026
* 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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants