Skip to content

[ASM] [HIP] [CK] Add persistent gfx950 f4gemm 256x256 kernel (_ps) - #6067

Merged
yzhou103 merged 16 commits into
ROCm:mainfrom
moonmath-ai:mxfp4-gemm-persistent
Nov 19, 2026
Merged

yzhou103 merged 16 commits into
ROCm:mainfrom
moonmath-ai:mxfp4-gemm-persistent

Conversation

@tarik-sarac

@tarik-sarac tarik-sarac commented Oct 1, 2026 •

Copy link
Copy Markdown
Contributor

Summary

This PR adds a persistent 256x256 MXFP4 GEMM kernel for gfx950, f4gemm_bf16_per1x32Fp4_BpreShuffle_256x256_ps, next to the existing BpreShuffle_256x256 kernel. It follows the mla_v4 convention for persistent kernels: its own _ps .co and symbol, and a documented ps column in the manifest. The tuned a4w4 configs that picked the 256x256 kernel now pick the _ps one.

  • Same inputs: BpreShuffle B, e8m0-shuffled scales, K % 64 == 0.
  • Same semantics: alpha is applied in fp32 before rounding. Split-K adds partial tiles into the zeroed C with bf16 atomics.
  • No bias/beta: the launcher rejects bias or beta != 0 for ps kernels instead of ignoring them. The heuristic skips ps kernels for such calls.
  • Faster on all 26 shapes below: geomean 0.882 (1.134x), up to 39%.

Changes

file change
hsa/gfx950/f4gemm/f4gemm_bf16_per1x32Fp4_BpreShuffle_256x256_ps.co new kernel, symbol _ZN5aiter45f4gemm_bf16_per1x32Fp4_BpreShuffle_256x256_psE
hsa/gfx950/f4gemm/f4gemm_bf16_per1x32Fp4.csv new ps column (0 on every existing row) with a one-line comment, plus a note that ps=1 kernels read num_cu at kernarg offset 372; new _ps row
csrc/py_itfs_cu/asm_gemm_a4w4.cu separate PsKernelArgs with num_cu for ps=1 kernels, static_assert on both layouts, ps_supported() checks, persistent launch, heuristic fallback
csrc/ck_gemm_a4w4_blockscale/gemm_a4w4_blockscale_tune.py reads the manifest without // comments; tunes ps and non-ps kernels as separate candidates
aiter/configs/a4w4_blockscale_tuned_gemm.csv, aiter/configs/model_configs/*a4w4_blockscale_tuned_gemm.csv the 364 rows on BpreShuffle_256x256 now name the _ps kernel (kernel name only)
op_tests/test_gemm_a4w4.py runs the ps kernel by name where ps_supported() holds; new split-K test, including single-tile shapes

hsa/ stays binary-only: no source or build script in this PR. See "Provenance" below.

Kernel arguments

  • ps=0 kernels: the legacy KernelArgs struct is unchanged (372 bytes, log2_k_split at offset 368). They get the same 372 bytes as before this PR.
  • ps=1 kernels: get a separate PsKernelArgs { KernelArgs args; unsigned int num_cu; } (376 bytes, num_cu at offset 372). This follows the separate persistent structs in asm_mla.cu and asm_pa.cu, and mla_v4's MlaV4PsKernelArgs.
  • A static_assert in asm_gemm_a4w4.cu pins both layouts. The CSV comment notes the num_cu offset.
  • KernelArgs is now zero-initialized (KernelArgs args{}).

Launcher

  • Explicit kernel name: a ps kernel that does not support the call fails loudly. bias/beta give bias/beta not supported. Other limits give a message listing them.
  • Heuristic: ps_supported() decides per call. A ps kernel that supports the call replaces its ps=0 twin (same tile). One that doesn't is skipped, so the heuristic falls back to the ps=0 kernel instead of throwing. The cache key includes this bit.
  • ps_supported() limits:
    • B preshuffled and contiguous;
    • K % 64 == 0, N % 16 == 0, A row stride % 16 bytes;
    • scales padded to whole tiles;
    • A and B under 4 GiB each, one C tile under 2 GiB (32-bit buffer sizes and offsets);
    • no bias, beta == 0.
  • The test mirrors ps_supported() instead of approximating it.
  • Split-K plan: the kernel uses fewer K slices until every (tile, K slice) work item has its own CU. The launcher now applies the same rule before launching, so the grid equals the work and no workgroup starts without a work item. C is zeroed only when more than one slice remains.

Fixes from review

  • Split-K with a single output tile (M <= 256 and N <= 256, log2_k_split >= 1) returned wrong results. The magic divisor for tiles == 1 wraps to 0, so every workgroup computed K slice 0. Fixed in the kernel the same way as the existing size == 1 case: slice = umulhi(work_item, tiles_magic) + (split && tiles == 1 ? work_item : 0). The non-split path is unchanged.
  • bias/beta are rejected for ps kernels (see Launcher).

Accuracy

Relative error (Frobenius norm) against an fp32 reference, gemm_a4w4_asm by name, ps=0 kernel vs the new ps=1 kernel:

M N K tiles log2_k_split 256x256 256x256_ps
256 256 8192 1 0 / 1 / 2 / 3 1.65e-3 / 2.47e-3 / 3.17e-3 / 4.07e-3 1.65e-3 / 2.47e-3 / 3.15e-3 / 4.05e-3
256 256 16384 1 0 / 1 / 2 / 3 1.66e-3 / 2.47e-3 / 3.18e-3 / 4.08e-3 1.66e-3 / 2.47e-3 / 3.17e-3 / 4.05e-3
128 128 16384 1 0 / 1 / 2 / 3 6.78e-1 / 2.46e-3 / 3.15e-3 / 4.06e-3 1.68e-3 / 2.46e-3 / 3.15e-3 / 4.07e-3
32 256 8192 1 0 / 1 / 2 / 3 1.66e-3 / 2.47e-3 / 3.17e-3 / 4.12e-3 1.66e-3 / 2.47e-3 / 3.17e-3 / 4.09e-3
256 512 8192 2 0 / 1 / 2 / 3 1.66e-3 / 2.46e-3 / 3.17e-3 / 4.04e-3 1.66e-3 / 2.46e-3 / 3.16e-3 / 4.08e-3
512 512 8192 4 0 / 1 / 2 / 3 1.66e-3 / 2.46e-3 / 3.16e-3 / 4.05e-3 1.66e-3 / 2.46e-3 / 3.17e-3 / 4.06e-3
2048 2048 8192 64 0 / 1 / 2 / 3 1.66e-3 / 2.46e-3 / 3.17e-3 / 4.06e-3 1.66e-3 / 2.46e-3 / 3.17e-3 / 3.17e-3
  • The error grows with the slice count because of the bf16 atomic adds. That is the same for both kernels.
  • 2048x2048 with log2_k_split = 3 runs with 4 slices on the ps kernel: 64 tiles x 8 slices > 256 CUs.
  • Existing issue, not changed by this PR: the ps=0 256x256 kernel is wrong for 128x128x16384 without split-K (bold).
  • bias: max|out - ref| = 1.0 (bf16 rounding) for the ps=0 kernel with a bias of scale 10 and beta = 1, i.e. it also drops bias today. The ps kernel raises instead.

Performance

Measured on an MI350X VF (gfx950, 256 CUs, 1000 W cap). run_perftest with 51 iterations and 5 warmup (rotated buffers), both kernels by name in one process, 3 alternating runs, median. Times in us. Ratio = ps / ps=0.

M N K 256x256 256x256_ps ratio
16384 7168 3584 262.90 229.74 0.874
32768 3584 7168 458.96 419.14 0.913
4096 7168 3584 74.04 64.33 0.869
16384 16384 2048 365.98 322.87 0.882
16384 16384 512 180.90 153.61 0.849
16384 8192 1024 134.28 110.68 0.824
8192 16384 5120 372.27 349.65 0.939
8192 8192 8192 290.46 273.86 0.943
4096 12288 1536 69.84 57.40 0.822
2048 12288 1536 46.76 36.20 0.774
768 547328 2048 653.14 563.14 0.862
8192 51200 5120 1136.24 1070.39 0.942
32768 9216 16384 2262.04 2160.77 0.955
16384 16384 26624 3152.81 3097.85 0.983
1600 16384 13312 209.37 201.88 0.964
512 106496 16384 505.89 497.98 0.984
512 32768 512 21.39 13.12 0.613
4096 4096 8192 78.62 73.21 0.931
8192 5120 4352 125.70 108.98 0.867
2880 5120 1280 22.46 17.73 0.789
2880 5120 6400 59.04 49.91 0.845
2048 8192 1024 29.39 26.38 0.897
2048 8192 7168 67.53 67.27 0.996
1024 16384 6656 68.42 62.57 0.914
1024 14336 8192 70.70 65.97 0.933
8 26624 16384 85.09 72.82 0.856
  • Geomean 0.882 (1.134x), faster on 26/26, worst 0.996.
  • The previous table (geomean 0.877) was measured on an MI355X at 1400 W with a different timing harness. The gain at a given shape depends on the power cap, so small shapes vary most between machines. On this machine 2048x8192x1024 is 0.897 and 4096x4096x8192 is 0.931.
  • The single-tile fix doesn't change the non-split path: same MFMA count (528), same .text size, and only register numbering changed.

Testing

python3 op_tests/test_gemm_a4w4.py
  • Default shape list: 138 checks pass, none catastrophic.

  • Split-K (new -mnk_splitk list, log2_k_split 1-3, both 256x256 kernels): single-tile 256x256 and 128x128 shapes, multi-tile 256x512, 512x512 and 2048x2048. None catastrophic. The ps kernel's mismatch ratio at 1e-2 equals the ps=0 kernel's on every row (5-16%, from the bf16 atomic adds).

  • Rejection paths: an explicit _ps name with bias raises bias/beta not supported. The same call through the heuristic (no kernel name) runs on a ps=0 kernel, as before.

  • Unit tests updated (op_tests/test_gemm_a4w4.py)

  • Performance benchmarks run

  • Tested on gfx950 (MI350X). gfx950 only; no other architecture's files change.

Provenance of the .co

  • Compiler: HIP 7.14.60850, AMD clang 23.0.0git (ROCm/llvm-project 46fcb339fb61119b337f973c7ca9e710a319fdd0).
  • Command:
    hipcc -std=c++20 -O3 --offload-arch=gfx950 -mllvm -amdgpu-spill-vgpr-to-agpr=0 -mllvm -pragma-unroll-threshold=1000000 \
      -mllvm -max-bytes-for-alignment=28 --genco --no-gpu-bundle-output f4gemm_256x256_ps.hip \
      -o f4gemm_bf16_per1x32Fp4_BpreShuffle_256x256_ps.co
    
  • sha256 (.co): 8b541b78bff2de71f3cb48db89572f1eb4adc403e09a675be9a8a546a60ff938 (30480 bytes)
  • sha256 (.text): 91864066e8826818faff395eb15145ad65d5911c53cbc6659e1863e0283e27f7. A rebuild reproduces the .text exactly. Only the build-metadata note differs, so compare .text.
  • HIP source: https://github.com/moonmath-ai/amd-kernels/tree/afe77f1ab81d11fee85671a0e3b39d40346b60b5/csrc/mxfp4_gemm_gfx950 (build.sh there runs the command above).

Dependencies

No new dependencies.

Breaking Changes

None. The ps=0 BpreShuffle_256x256 kernel and its .co are unchanged and still selectable by name.

@tarik-sarac
tarik-sarac requested review from a team and a balanced review from Copilot October 1, 2026 21:16

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.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@github-actions github-actions Bot changed the title Replace gfx950 f4gemm 256x256 kernel with a persistent one [ASM] [HIP] Replace gfx950 f4gemm 256x256 kernel with a persistent one Oct 1, 2026
@github-actions

github-actions Bot commented Oct 1, 2026

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 on MI35X (only when aiter/ops/triton/** or related paths are changed)

Extended tests (opt-in via labels):

Label Tests
ci:gfx1250-ffm-triton Run the five-shard gfx1250 FFM Triton test suite
ci:triton-300x Run an additional Triton test job on MI300X in PRs (added automatically when gfx942 configs change); main branch always runs both MI35X and MI300X
ci:triton-355 Run the full Triton test suite on MI35X, not only the tests the change affects
multigpu Aiter multi-GPU tests on the 8-GPU runner
ci:sglang SGLang integration tests: DeepSeek-R1-MXFP4 accuracy, Qwen 3.5 accuracy
ci:atom ATOM benchmark: DeepSeek-R1-0528, GPT-OSS-120B
ci:atom_full ATOM accuracy suite for PR and main models from ATOM models_accuracy.json
ci:vllm vLLM benchmark: GPT-OSS-120B, DeepSeek-R1-0528, Kimi-K2.5
ci:all All standard extended tests (excludes ci:atom_full)

Only add ci:atom_full for FlyDSL or Triton upgrades.
Add labels via the sidebar or gh pr edit 6067 --add-label <label>

One backend per PR:
A PR changes one kernel backend: [Triton/Gluon] (Triton and Gluon count as one), [HIP], [ASM], [CK], [OPUS] or [FlyDSL]. If the title ends up with two backend tags, split the PR -- as stacked pull requests when one part cannot merge without the other.

PR title tags & labels:
Component tags ([Triton/Gluon], [HIP], [CK], [ASM], ...) are added to the PR title and as PR labels automatically from the changed files and re-synced on every push — change-type tags like [fix]/[Perf], op tags like [MLA], and human labels (ci:*) are left untouched. Add the no-auto-title label to stop the title rewrites; labels stay in sync either way.

Copilot AI balanced review requested due to automatic review settings October 1, 2026 23:36
@tarik-sarac
tarik-sarac force-pushed the mxfp4-gemm-persistent branch from a986eaf to 9e6c0da Compare October 1, 2026 23:36

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.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@zufayu
zufayu requested a review from yzhou103 October 2, 2026 00:32
Copilot AI balanced review requested due to automatic review settings October 2, 2026 20:25
@tarik-sarac
tarik-sarac force-pushed the mxfp4-gemm-persistent branch from 9e6c0da to bd7e387 Compare October 2, 2026 20:25

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.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

Copilot AI balanced review requested due to automatic review settings October 2, 2026 20:56

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.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@yzhou103

yzhou103 commented Oct 15, 2026 •

Copy link
Copy Markdown
Contributor

Thanks for this — I reproduced the speedup on a gfx950 (256 CU) box and it holds up across the board. I also found one silent correctness regression that I think blocks the
merge, plus a few requests about how the persistent flag and the kernel sources are landed.

What I verified

A/B on the same machine, same process settings (run_perftest, 51 iters + 5 warmup), forcing kernelName="_ZN5aiter42f4gemm_bf16_per1x32Fp4_BpreShuffle_256x256E", baseline = main,
new = this PR.

Performance reproduces: 26/26 shapes faster, no regressions. Geomean ratio 0.9015 (1.109x) vs the 0.8768 (1.140x) in the PR description. Large shapes match within 0.5%:

     M       N       K   cur(us)   new(us)   my ratio   PR ratio
   2048   12288    1536      35.2      25.5      0.724      0.703
  16384    8192    1024     111.0      86.7      0.781      0.711
  16384   16384     512     155.5     127.5      0.820      0.803
   8192   51200    5120     919.6     855.0      0.930      0.930
  32768    9216   16384    1819.1    1729.3      0.951      0.953
  16384   16384   26624    2513.1    2469.2      0.983      0.984
   2048    8192    1024      16.0      15.9      0.997      0.938   <- no gain here
   4096    4096    8192      59.5      59.3      0.998      0.945   <- no gain here

geomean: 0.9015 (1.109x) PR description: 0.8768 (1.140x)

Two small-shape rows (2048x8192x1024, 4096x4096x8192) show essentially no gain on my box while the PR table claims 5–6%. Worth a re-measure — likely iteration count / clock
state, but please confirm.

Accuracy on the normal path is fine: the added test passes on M=1/127/129 (unaligned rows) with err=0, and output checksums across the 26 benchmark shapes differ from baseline by
6e-5…1.5e-3 relative, i.e. bf16 rounding.

Blocking 1: split-K is broken when the output is a single tile

   M       N       K   tiles   log2_k_split   rel.err (PR)   baseline
 256     256    8192       1              0       0.00e+00         OK
 256     256    8192       1              1       7.26e-01         OK   <- WRONG
 256     256    8192       1              2       9.04e-01         OK   <- WRONG
 256     256   16384       1            1-3   0.73 .. 1.00         OK   <- WRONG
 128     128   16384       1            1-3   0.69 .. 0.92         OK   <- WRONG
 256     512    8192       2            1-3       ~5.0e-03         OK
 512     256    8192       2            1-3       ~5.0e-03         OK
 512     512    8192       4            1-3       ~5.0e-03         OK
2048    2048    8192      64            1-3       ~5.0e-03         OK

Reverting the PR makes every one of these pass, so it is introduced here. The trigger is exactly tiles == 1 (M ≤ 256 and N ≤ 256) with log2_k_split >= 1. No error is raised — it
silently returns wrong data.

Root cause, mxfp4_gemm_4w.hip:

uint32_t tiles_magic = split ? 0xFFFFFFFFu / tiles + 1 : 0;
...
const uint32_t slice = __umulhi(work_item, tiles_magic), tile = work_item - slice * all_tiles;

For tiles == 1, 0xFFFFFFFFu / 1 + 1 wraps to 0 in uint32, so slice is always 0 and tile = work_item. Every CTA computes K slice 0, and three of the four address tiles that do not
exist:

tiles=1 slices=4 tiles_magic=0x00000000
work_item=0 -> slice=0 tile=0
work_item=1 -> slice=0 tile=1 <- no such tile
work_item=2 -> slice=0 tile=2 <- no such tile
work_item=3 -> slice=0 tile=3 <- no such tile

tiles=2 slices=4 tiles_magic=0x80000000 (correct)
work_item=0 -> slice=0 tile=0
work_item=1 -> slice=0 tile=1
work_item=2 -> slice=1 tile=0
work_item=3 -> slice=1 tile=1
...

The same divisor-of-1 hazard is already handled a few lines below, so the fix can mirror it:

// existing, a few lines below:
const uint32_t across = __umulhi(in_group, magic) + (size == 1 ? in_group : 0);

// proposed:
const uint32_t slice = __umulhi(work_item, tiles_magic) + (all_tiles == 1 ? work_item : 0);

Reachability: today's heuristic does not auto-enable split-K for these shapes (I checked the unified aiter.gemm_a4w4 path on M=64/128/192/256 x N=256 x K=16384/32768, all exact),
but log2_k_split is a public argument of gemm_a4w4_asm and the CSV marks this row splitK=1, so a tuner or a threshold change turns it into a production bug.

Repro:

out = torch.zeros((256, 256), dtype=torch.bfloat16)
aiter.gemm_a4w4_asm(xq, wsh, xs, ws, out,
"_ZN5aiter42f4gemm_bf16_per1x32Fp4_BpreShuffle_256x256E",
log2_k_split=2) # rel err ~0.9

Please also add a tiles == 1 split-K case to test_gemm_a4w4.py — the split-K path has no coverage at all right now.

Blocking 2: bias / beta are silently ignored

max|out - (ref + bias)| = 35.4993
max|out - ref| = 0.0000 -> bias dropped, no error raised
256 512 8192 2 1-3 ~5.0e-03 OK
512 256 8192 2 1-3 ~5.0e-03 OK
512 512 8192 4 1-3 ~5.0e-03 OK
2048 2048 8192 64 1-3 ~5.0e-03 OK

Reverting the PR makes every one of these pass, so it is introduced here. The trigger is exactly tiles == 1 (M ≤ 256 and N ≤ 256) with log2_k_split >= 1. No error is raised — it
silently returns wrong data.

Root cause, mxfp4_gemm_4w.hip:

uint32_t tiles_magic = split ? 0xFFFFFFFFu / tiles + 1 : 0;
...
const uint32_t slice = __umulhi(work_item, tiles_magic), tile = work_item - slice * all_tiles;

For tiles == 1, 0xFFFFFFFFu / 1 + 1 wraps to 0 in uint32, so slice is always 0 and tile = work_item. Every CTA computes K slice 0, and three of the four address tiles that do not
exist:

tiles=1 slices=4 tiles_magic=0x00000000
work_item=0 -> slice=0 tile=0
work_item=1 -> slice=0 tile=1 <- no such tile
work_item=2 -> slice=0 tile=2 <- no such tile
work_item=3 -> slice=0 tile=3 <- no such tile

tiles=2 slices=4 tiles_magic=0x80000000 (correct)
work_item=0 -> slice=0 tile=0
work_item=1 -> slice=0 tile=1
work_item=2 -> slice=1 tile=0
work_item=3 -> slice=1 tile=1
...

The same divisor-of-1 hazard is already handled a few lines below, so the fix can mirror it:

// existing, a few lines below:
const uint32_t across = __umulhi(in_group, magic) + (size == 1 ? in_group : 0);

// proposed:
const uint32_t slice = __umulhi(work_item, tiles_magic) + (all_tiles == 1 ? work_item : 0);

Reachability: today's heuristic does not auto-enable split-K for these shapes (I checked the unified aiter.gemm_a4w4 path on M=64/128/192/256 x N=256 x K=16384/32768, all exact),
but log2_k_split is a public argument of gemm_a4w4_asm and the CSV marks this row splitK=1, so a tuner or a threshold change turns it into a production bug.

Repro:

out = torch.zeros((256, 256), dtype=torch.bfloat16)
aiter.gemm_a4w4_asm(xq, wsh, xs, ws, out,
"_ZN5aiter42f4gemm_bf16_per1x32Fp4_BpreShuffle_256x256E",
log2_k_split=2) # rel err ~0.9

Please also add a tiles == 1 split-K case to test_gemm_a4w4.py — the split-K path has no coverage at all right now.

Blocking 2: bias / beta are silently ignored

max|out - (ref + bias)| = 35.4993
max|out - ref| = 0.0000 -> bias dropped, no error raised

The code comment says this matches the previous 256x256 kernel, but a comment is not a guard. Please add to the persistent branch:

AITER_CHECK(bias == nullptr && beta == 0.f, func, " ", kname, ": bias/beta not supported");

Request 1: please drop hsa/gfx950/f4gemm/src/**

We'd like hsa/ to keep containing binaries only, consistent with every other kernel there — no .hip sources and no build.sh in this PR. Ship just the rebuilt .co.

Two consequences to handle once the source is out of tree:

  • The static_assert(offsetof(KernelArgs, log2_k_split) == 368 && sizeof(KernelArgs) == 376) currently living in f4gemm_256x256.hip disappears, so the kernarg contract will only
    be asserted on the host side. Please keep the static_assert in asm_gemm_a4w4.cu and document the layout (and the num_cu slot) in the CSV header comment.
  • Please record the provenance of the binary in the PR description: the ROCm/hipcc version used and the sha256 of the .co, so the blob can be rebuilt later.

Request 2: follow the mla_v4 convention for the persistent flag

Please align the CSV and the dispatch with hsa/gfx950/mla_v4/mla_v4_asm.csv (and hsa/gfx950/mla/mla_asm.csv), which already model exactly this case:

                        mla_v4 (existing convention)        this PR
column name             ps  (0/1)                           persistent
column documented       yes, // header block per column     no
.co name                mla_..._nm.co / mla_..._nm_ps.co    same name, overwritten
kernel symbol           ..._nm   /   ..._nm_ps              unchanged
kernarg struct          separate MlaV4PsKernelArgs          shared struct + new field
dispatch                dedicated mla_decode_v4_ps_asm      shared heuristic

Concretely:

  1. Name the column ps, not persistent. Both MLA manifests use ps. It also avoids a semantic clash: asm_f4gemm.cu states "Every f4gemm .co is a persistent shader" for a different
    meaning of persistent, and hsa/codegen.py unions columns into one shared f4gemmConfig struct across both manifests.
  2. Document the column in the CSV header. hsa/codegen.py strips // comments; mla_v4_asm.csv has a full per-column block. One line for ps, plus a note that ps=1 kernels read
    num_cu at kernarg offset 372, would be ideal.
  3. Give the persistent kernel its own .co name and its own symbol, with a ps suffix. mla_v4 ships mla_a8w8...nm.co and mla_a8w8..._nm_ps.co with symbols ..._nm and ..._nm_ps.
    This matters here concretely: I hit a stale JIT build where the old host (no persistent branch, uninitialized num_cu) loaded the new .co, and the result was an all-zero output
    at 13 us instead of 200 us — no error, silently wrong. A new symbol name turns that class of host/blob mismatch into a loud "kernel not found".
  4. Consider not growing the shared KernelArgs. mla_v4 defines a separate MlaV4PsKernelArgs for the persistent variant instead of appending to the legacy struct. If you keep the
    shared struct, at least pass the short size for non-persistent kernels, e.g. arg_size = cfg.ps ? sizeof(args) : offsetof(KernelArgs, num_cu).
  5. mla_v4 also reaches its persistent kernel through a dedicated entry point (mla_decode_v4_ps_asm) rather than through the shared heuristic. Not strictly required here, but see
    the next point.

Non-blocking

  • KernelArgs args; is uninitialized. num_cu is stack garbage on the non-persistent path (as are stride_D0/D1/C1/A1/B1/ScaleA1/ScaleB1, pre-existing). Please use KernelArgs args{}
    — asm_f4gemm.cu already does. Side note: BpreShuffle_128x512.co declares a 384 B kernarg while we pass 376 B; worth a separate look.
  • Constraints are a hard throw on the auto-selected path. get_heuristic_kernel() knows nothing about the new AITER_CHECK preconditions (contiguous B, scales padded to 256 rows,
    A/B < 4 GiB), so an unsupported shape now aborts instead of falling back to another tile. Prefer filtering those rows out during heuristic selection and keeping the hard failure
    only for an explicitly requested kernelName.
  • Two sources of truth for the size limits. The host checks against 1 << 32 while the standalone mxfp4_gemm() entry still uses Oob == 0x80000000 (2 GiB); the overflow fix only
    updated one side. Moot once the sources are removed from the PR, but please make sure the host-side limits are the correct ones.
  • Host and device each derive the split-K plan independently. The device loop keeps decrementing log2_split while tiles * slices > cus; the host does not, so the grid can be
    larger than the work and the surplus CTAs run the whole prologue (out-of-bounds window DMAs plus a barrier) before exiting. Harmless but fragile — worth a comment stating the
    invariant.
  • Test gating. max(M, N) * K // 2 < 2**32 is not equivalent to the three host-side checks. Mirror the host conditions, or skip explicitly.
  • Please put the perf table and the accuracy numbers into the PR description / commit body — the commits are currently one-liners.

tarik-sarac added a commit to moonmath-ai/aiter that referenced this pull request Oct 15, 2026
Address review on ROCm#6067:
- The persistent kernel gets its own .co and symbol,
  f4gemm_bf16_per1x32Fp4_BpreShuffle_256x256_ps; the ps=0 256x256 kernel is
  restored unchanged. The manifest gets a ps column (mla_v4 convention) and a
  comment noting that ps=1 kernels read num_cu at kernarg offset 372.
- Fix split-K with a single output tile (M, N <= 256): the slice divisor
  wrapped to 0 for tiles == 1, so every workgroup computed K slice 0.
- ps=1 kernels get a separate PsKernelArgs (KernelArgs + num_cu, 376 B);
  ps=0 kernels get the unchanged 372 B KernelArgs. static_assert on both
  layouts; KernelArgs is zero-initialized.
- bias/beta raise for ps kernels instead of being ignored.
- ps_supported() gates the ps kernel per call: a supported ps kernel
  replaces its ps=0 twin in the heuristic, an unsupported one is skipped;
  an explicitly named ps kernel still fails loudly.
- The host applies the kernel's split-K rule (fewer K slices until every
  work item has a CU), so the grid equals the work.
- hsa/ stays binary-only: the HIP source and build script are removed.
- Tuner: reads the manifest with comment="#" and tunes ps and ps=0 kernels
  as separate candidates.
- test_gemm_a4w4.py: the ps kernel runs where ps_supported() holds, plus a
  split-K test on both 256x256 kernels, including single-tile shapes.

Accuracy (rel. err vs fp32, log2_k_split 0/1/2/3, ps kernel):
  256x256x8192    1.65e-3 / 2.47e-3 / 3.15e-3 / 4.05e-3
  128x128x16384   1.68e-3 / 2.46e-3 / 3.15e-3 / 4.07e-3
  2048x2048x8192  1.66e-3 / 2.46e-3 / 3.17e-3 / 3.17e-3 (8 slices > CUs -> 4)
Same as the ps=0 kernel on every row, except that the ps=0 kernel is wrong at
128x128x16384 without split K (N % 256 != 0, pre-existing).
test_gemm_a4w4.py default list: 138 checks pass.

Perf vs the ps=0 256x256, MI350X (gfx950, 256 CUs, 1000 W), run_perftest
51 iters + 5 warmup, both kernels by name, median of 3 alternating runs:
26/26 PR shapes faster, geomean 0.882 (1.134x), best 0.613
(512x32768x512), worst 0.996 (2048x8192x7168).

.co: hipcc 7.14.60850, AMD clang 23.0.0git (llvm-project 46fcb339),
sha256 8b541b78bff2de71f3cb48db89572f1eb4adc403e09a675be9a8a546a60ff938,
.text sha256 91864066e8826818faff395eb15145ad65d5911c53cbc6659e1863e0283e27f7.
Copilot AI balanced review requested due to automatic review settings October 15, 2026 11:51

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.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@github-actions github-actions Bot changed the title [ASM] [HIP] Replace gfx950 f4gemm 256x256 kernel with a persistent one [ASM] [HIP] [CK] Replace gfx950 f4gemm 256x256 kernel with a persistent one Oct 15, 2026
@github-actions github-actions Bot added the CK label Oct 15, 2026
@tarik-sarac

Copy link
Copy Markdown
Contributor Author

Thank you @yzhou103 for the thorough review. Everything is addressed in fdd726c and e55dfa7:

Blocking

  1. Split-K, tiles == 1: fixed as you proposed, gated on split so the non-split path is unchanged. It matches the baseline error on every row of your table. test_gemm_a4w4.py now has split-K cases (-mnk_splitk), including the 256x256 and 128x128 single-tile shapes. The fixed kernel is ..._256x256_psE; the symbol in your repro is now the unchanged old kernel.
  2. bias/beta: your AITER_CHECK is in the ps branch. The heuristic also skips the ps kernel when bias or beta is set.

Requests

  1. hsa/ binary only: src/ is removed. The source is now at https://github.com/moonmath-ai/amd-kernels/tree/afe77f1ab81d11fee85671a0e3b39d40346b60b5/csrc/mxfp4_gemm_gfx950 in case you want to review. The kernarg static_assert lives in asm_gemm_a4w4.cu. The PR description has the hipcc version and the sha256 of the .co and of its .text, which rebuilds identically.

  2. mla_v4 convention:

    • a ps column, with a one-line comment noting num_cu at offset 372;
    • a separate _ps .co and symbol, with the old 256x256 restored byte-identical to main;
    • a separate PsKernelArgs { KernelArgs args; unsigned num_cu; }, so the legacy struct is unchanged and ps=0 kernels get 372 B as on main;
    • the tuned configs now point to _ps (second commit, kernel name only).

    I kept the shared entry point because the ps kernel takes the same inputs and the tuned configs reach it by name. Instead, ps_supported() gates it per call in the heuristic: an unsupported call falls back to the ps=0 256x256, and the hard error remains only for an explicit kernel name.

Non-blocking

  • KernelArgs args{} added.
  • The host applies the device's split-K rule, so the grid equals the work.
  • The test gate mirrors the host checks.
  • Perf and accuracy are in the commit body and the PR description.
  • The host size limits are the authoritative ones (A/B < 4 GiB, C tile < 2 GiB).
  • 128x512's 384 B kernarg predates this PR and is untouched.
  • The tuner now reads the manifest with comment="#" and tunes ps and ps=0 kernels as separate candidates.

The two small shapes: 2048x8192x1024 and 4096x4096x8192 are exactly 256 tiles, a single round, so the only gain is the epilogue overlap. That makes them sensitive to the board's power cap and clocks. On our MI350X (1000 W) they measure 0.93 and 0.92 in separate processes, in both orders. Could you share the power cap and clocks of your run (rocm-smi --showpower --showclocks)? In any case PR should be fine since tuner can select between old and new kernels.

Also found while testing: the existing ps=0 BpreShuffle_256x256 kernel returns wrong results, intermittently, whenever N % 256 != 0 (e.g. 32x128, 16384x896, 32768x384 with K=4096, rel. err 0.06–0.85). On main, get_heuristic_kernel() selects it for some untuned shapes like these; with this PR they go to the ps kernel instead. The kernel itself isn't touched here; worth a separate issue.

@tarik-sarac tarik-sarac changed the title [ASM] [HIP] [CK] Replace gfx950 f4gemm 256x256 kernel with a persistent one [ASM] [HIP] [CK] Add persistent gfx950 f4gemm 256x256 kernel (_ps) Oct 15, 2026
Copilot AI balanced review requested due to automatic review settings October 15, 2026 17:10

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.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

Copilot AI balanced review requested due to automatic review settings October 22, 2026 13:18

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.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

Copilot AI balanced review requested due to automatic review settings October 22, 2026 13:20

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.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@tarik-sarac

Copy link
Copy Markdown
Contributor Author

889c02b fixes the Atom CI failures caused by this PR. ATOM's dense MXFP4 linear still calls gemm_a4w4(x, weight, x_scale, weight_scale, y) (atom/model_ops/linear.py#L322-L328) from before #1679 removed the out parameter. Its output buffer therefore lands in the bias slot with beta 0, and the bias/beta guard from blocking 2 rejected that. The f4gemm asm kernels ignore bias, so with beta == 0 the result is exact (D = alpha·A·B + beta·C). The guard now rejects only bias with beta != 0, both for an explicit kernel name and in ps_supported(), and there's a test for the ATOM call pattern. The ATOM call site is probably worth updating separately.

@yzhou103

Copy link
Copy Markdown
Contributor

It seems there are conflicts, please resolve the conflicts, thanks!

Copilot AI balanced review requested due to automatic review settings October 26, 2026 13:59

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.

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota.

@tarik-sarac

Copy link
Copy Markdown
Contributor Author

@yzhou103 Thanks! Resolved & merged the latest main

Copilot AI balanced review requested due to automatic review settings October 28, 2026 00:10

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.

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota.

Copilot AI balanced review requested due to automatic review settings November 2, 2026 08:48

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.

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

@aiter-bot

aiter-bot commented Nov 2, 2026 •

Copy link
Copy Markdown

WAITING ON AUTHOR

PR Self-Review

Revision 2ca6b9b97e37 · mode shadow

Waiting for the PR author. The readiness report will appear after the self-review answers are complete for this revision.

Questions to answer in the PR description

  1. What behavior does this PR change, and why is the existing behavior insufficient?
  2. What did you validate, and what remains unverified? Include commands, hardware/configuration and results.
  3. Which architecture, dtype and shape boundaries select the changed kernel path, and what invariant prevents unsupported inputs from reaching it?
  4. For every changed op_tests/ file, what behavior does it cover and why is it not redundant? Write None if no op test changed.

Edit the PR Self-Review section in the PR description. Include the current revision SHA; this comment refreshes automatically.

Missing or invalid answers

  • FAIL — missing ### Reviewed revision in the PR description
  • FAIL — missing ### Behavior and intent in the PR description
  • FAIL — missing ### Validation and unverified scope in the PR description
  • FAIL — missing ### PR-specific question in the PR description
  • FAIL — missing ### Changed op tests in the PR description
  • FAIL — Reviewed revision must contain at least the first 7 characters of the current head SHA
  • FAIL — Behavior and intent has no substantive answer
  • FAIL — Validation and unverified scope has no substantive answer
  • FAIL — PR-specific question has no substantive answer
  • FAIL — changed op test not explained in Changed op tests: op_tests/test_gemm_a4w4.py
  • FAIL — Changed op tests must explain why each changed op test is necessary and non-redundant

Shadow mode reports what would block but keeps the status successful. Set AITER_PR_SELF_REVIEW_MODE=enforce only after reviewing real false positives.

@yzhou103

yzhou103 commented Nov 9, 2026 •

Copy link
Copy Markdown
Contributor

Hi @tarik-sarac please resolve conflicts

Copilot AI balanced review requested due to automatic review settings November 16, 2026 10:33

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.

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

@yzhou103 yzhou103 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.

I validated head 2ca6b9b on gfx950 with 256 CUs, using PyTorch 2.10.0+rocm7.2.4 and HIP 7.2.53211.

  • Ran the unmodified python3 op_tests/test_gemm_a4w4.py. All 373 normal-path comparisons passed. The 18 split-K configurations also ran for both kernels. Both implementations still log failed! at the default elementwise tolerance, consistent with the documented BF16 atomic accumulation behavior; no catastrophic failures occurred, and the script exited with code 0.
  • Tested all 364 changed CSV rows, comparing the previous and new kernel selections with identical quantized inputs. All these rows use splitK=0. All 728 comparisons passed, with finite outputs and err_ratio=0, against an FP32 dequantized GEMM reference rounded to BF16.
  • For performance, used run_perftest with automatic buffer rotation, 5 warmup calls and 51 measured calls per round, taking medians over three alternating old/new rounds. Quantization and preshuffle were outside the timing. The 357 persistent-kernel replacements reduced geometric-mean latency by 7.9%. The single 160x128 replacement reduced latency by 45.8%; the six unchanged-kernel rows were approximately flat.
  • Repeated all seven initially slower persistent configurations with reversed execution order, together with the six unchanged-kernel controls. Four became faster; the remaining three were only 0.27–0.91% slower, comparable to the approximately ±1% variation observed in the controls. I did not reproduce a clear, stable performance regression.

Based on this validation, I do not see a remaining correctness or performance blocker for merging on gfx950. The earlier stale-timing issue is addressed, so that discussion can be resolved.

As a follow-up, please make the expected BF16 split-K tolerance explicit and assert the acceptance criterion while retaining catastrophic_check=True, so ordinary accuracy regressions cannot merely print failed! and still pass CI.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants