Skip to content

Return an empty result for a zero batch/row count in batched GEMMs - #8996

Merged
yifehuan merged 1 commit into
ROCm:mainfrom
zufayu:fix/zero-m-batched-gemm
Dec 3, 2026
Merged

yifehuan merged 1 commit into
ROCm:mainfrom
zufayu:fix/zero-m-batched-gemm

Conversation

@zufayu

@zufayu zufayu commented Dec 1, 2026 •

Copy link
Copy Markdown
Contributor

Context

What changed

  • batched_gemm_bf16_CK (aiter/ops/batched_gemm_op_bf16.py), batched_gemm_a8w8_CK (aiter/ops/batched_gemm_op_a8w8.py): guard added right after the output buffer Y is allocated (b, m, n are already known at that point), before get_CKBatchedGEMM_config and the kernel launch.
  • batched_gemm_a8w8_mxscale / batched_gemm_a8w8_mxscale_bpreshuffle (via their shared _impl bodies): guard added right after m, g, n, k are read, before the tuned lookup and the opus/flydsl libtype dispatch.
  • Left out of scope: batched_gemm_a8w8_mxscale_bpreshuffle_fused_quant, which has a distinct (fp8, e8m0-scale) tuple return contract rather than a single [M, G, N] tensor -- flagging it as a follow-up rather than guessing at its empty-result shape.

Testing

  • Verified on an MI300X (gfx942) machine: with this change, batched_gemm_bf16_CK/batched_gemm_a8w8_CK return a correctly-shaped empty result for both batch=0 and M=0, and batched_gemm_a8w8_mxscale/batched_gemm_a8w8_mxscale_bpreshuffle do for M=0, all without reaching a backend.
  • On origin/main (before this change), both batched_gemm_bf16_CK(B=0, ...) and batched_gemm_bf16_CK(M=0, ...) reach get_CKBatchedGEMM_config, JIT-build the kernel, and then fail the actual launch with HIP runtime error: invalid configuration argument -- a real bad kernel launch, not a clean Python exception, matching this issue's "never hang/fail at the backend" premise directly.
  • Added op_tests/test_batched_gemm_zero_m.py with one pytest case per fixed entry point (batch=0 and M=0 where both are meaningful). All 5 pass locally.

Related: #8984, #8958, #8960, #8995

PR Self-Review

Reviewed revision

6549940

Behavior and intent

Before this PR, batched_gemm_bf16_CK/batched_gemm_a8w8_CK call get_CKBatchedGEMM_config and launch a kernel unconditionally, and batched_gemm_a8w8_mxscale/batched_gemm_a8w8_mxscale_bpreshuffle (via their _impl bodies) do the same with their tuned lookup, for batch=0 or M=0. Issue #8984 states the zero-size no-op rule explicitly extends to "batched A (A.dim()>=3) with a zero leading dim", but the original scope list only named dense GEMM entries, so these batched entries were an unflagged gap. The PR adds an if b == 0 or m == 0: return Y (or the m == 0 or g == 0 equivalent for the mxscale pair, where the batch dimension is named g) short-circuit before the tuned lookup and kernel launch in all four.

Validation and unverified scope

Verified on an MI300X (gfx942) machine by calling all four entries directly with batch=0 (where applicable) and M=0, on origin/main (f7c6089) and this PR's head:

  • origin/main: batched_gemm_bf16_CK(B=0, ...) and batched_gemm_bf16_CK(M=0, ...) both reach get_CKBatchedGEMM_config, JIT-build the kernel for the shape, and then fail the actual launch with RuntimeError('HIP runtime error: invalid configuration argument. ...') -- a real bad kernel launch, matching this issue's premise directly. batched_gemm_a8w8_CK/batched_gemm_a8w8_mxscale/batched_gemm_a8w8_mxscale_bpreshuffle were exercised but their full origin/main failure trace was not captured with the same depth as the bf16 case (they were observed to reach their own tuned-lookup/build path for the untested shape, consistent with the same risk, but I did not let each one run to a terminal error/hang the way I did for bf16 before moving to verifying the fix).
  • This PR's head: all four return a correctly-shaped empty result ((0, M, N) / (B, 0, N) / (0, G, N) as applicable), no backend reached.
    Unverified: batched_gemm_a8w8_mxscale_bpreshuffle_fused_quant, a related function with a distinct (fp8, e8m0-scale) tuple return contract, is explicitly left out of this PR (see below) rather than guessed at.

PR-specific question

Why does batched_gemm_a8w8_mxscale_bpreshuffle_fused_quant not get the same fix in this PR? It shares the same tuned-lookup-before-kernel-launch shape as the four fixed functions, but its return type is a (fp8 tensor, e8m0 scale tensor) pair rather than a single [M, G, N] tensor, and its scale-tensor shape ((m, g * n // 32)) is derived differently than the other four. I did not want to guess at the right empty-result shape for an untested return contract and ship it unverified; flagging it as a follow-up instead.

Changed op tests

  • op_tests/test_batched_gemm_zero_m.py (new file): one pytest case per fixed entry point covering batch=0 (bf16, a8w8) and M=0 (bf16, a8w8 mxscale, a8w8 mxscale_bpreshuffle). Not redundant with the existing test_batched_gemm_bf16.py, test_batched_gemm_a8w8.py, or test_batched_gemm_a8w8_mxscale_bpreshuffle.py, which are correctness/benchmark scripts exercising non-zero shapes against a numeric reference and have no zero-size case; the new file only asserts shape/dtype, which is the right check for an empty result and would not fit those files' numeric-comparison structure.

M=0 (and, for a batched GEMM, batch=0) happens in production when an
idle data-parallel rank runs a dummy step to stay in its group's
collectives (ROCm#8958). This extends the no-op convention already applied
to gemm_a16w16 (ROCm#8960) and the a8w8 family (ROCm#8995) to the batched GEMM
entry points flagged in ROCm#8984:

- batched_gemm_bf16_CK / batched_gemm_a8w8_CK: guard added right after
  the output buffer Y is allocated (b, m, n are already known at that
  point), before the tuned-config lookup (get_CKBatchedGEMM_config)
  and the kernel launch.
- batched_gemm_a8w8_mxscale (_batched_gemm_a8w8_mxscale_impl) and
  batched_gemm_a8w8_mxscale_bpreshuffle
  (_batched_gemm_a8w8_mxscale_bpreshuffle_impl): guard added right
  after m, g, n, k are read, before the tuned lookup and the
  opus/flydsl libtype dispatch.

batched_gemm_a8w8_mxscale_bpreshuffle_fused_quant (a distinct
(fp8, e8m0-scale) tuple return contract) is left out of this PR's scope;
flagging it as a follow-up.

Verified on MI300X (gfx942): with this change all four entries return
a correctly-shaped empty result for batch=0 or M=0 without reaching a
backend. On origin/main (before this change), batched_gemm_bf16_CK(B=0)
reaches get_CKBatchedGEMM_config and a JIT kernel build/launch for an
untested shape.

Added op_tests/test_batched_gemm_zero_m.py covering all four entries.

Related: ROCm#8984, ROCm#8958, ROCm#8960, ROCm#8995
@zufayu
zufayu requested a review from a team December 1, 2026 09:07
@github-actions

github-actions Bot commented Dec 1, 2026

Copy link
Copy Markdown
Contributor

🏷️ CI Guide

Runs automatically on every PR:

  • ✅ Pre-checks (submodule verification, code formatting)
  • ✅ Aiter standard tests on MI35X
  • ✅ Triton tests on MI35X (only when aiter/ops/triton/** or related paths are changed)

Extended tests (opt-in via labels):

Label Tests
ci:mi300x Run Aiter standard tests on MI300X in PRs; main branch always runs them
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
ci:windows Windows JIT op smoke test on the Radeon R9700 ROCm runner
ci:multi-gpu 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: DeepSeek-V4-Pro, MiniMax-M3-MXFP4
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 8996 --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.

Reviews:
A reviewer is usually assigned within one working day after the PR is ready for review (see Code Review Process). If nobody has responded for about a week, mention the area contact listed in CONTACTS.md. Want to help review? See REVIEWERS.md.

@aiter-bot

aiter-bot commented Dec 1, 2026 •

Copy link
Copy Markdown

READY FOR HUMAN REVIEW

PR Self-Review

Revision 6549940c6a98 · mode shadow

Author self-review accepted. Readiness report:

Author answers

  • PASS — current-SHA answers are present and structurally specific
Show the author's self-review answers

Behavior and intent

Before this PR, `batched_gemm_bf16_CK`/`batched_gemm_a8w8_CK` call `get_CKBatchedGEMM_config` and launch a kernel unconditionally, and `batched_gemm_a8w8_mxscale`/`batched_gemm_a8w8_mxscale_bpreshuffle` (via their `_impl` bodies) do the same with their tuned lookup, for `batch=0` or `M=0`. Issue #8984 states the zero-size no-op rule explicitly extends to "batched A (A.dim()>=3) with a zero leading dim", but the original scope list only named dense GEMM entries, so these batched entries were an unflagged gap. The PR adds an `if b == 0 or m == 0: return Y` (or the `m == 0 or g == 0` equivalent for the mxscale pair, where the batch dimension is named `g`) short-circuit before the tuned lookup and kernel launch in all four.

Validation and unverified scope

Verified on an MI300X (gfx942) machine by calling all four entries directly with `batch=0` (where applicable) and `M=0`, on `origin/main` (f7c60896) and this PR's head:
- `origin/main`: `batched_gemm_bf16_CK(B=0, ...)` and `batched_gemm_bf16_CK(M=0, ...)` both reach `get_CKBatchedGEMM_config`, JIT-build the kernel for the shape, and then fail the actual launch with `RuntimeError('HIP runtime error: invalid configuration argument. ...')` -- a real bad kernel launch, matching this issue's premise directly. `batched_gemm_a8w8_CK`/`batched_gemm_a8w8_mxscale`/`batched_gemm_a8w8_mxscale_bpreshuffle` were exercised but their full origin/main failure trace was not captured with the same depth as the bf16 case (they were observed to reach their own tuned-lookup/build path for the untested shape, consistent with the same risk, but I did not let each one run to a terminal error/hang the way I did for bf16 before moving to verifying the fix).
- This PR's head: all four return a correctly-shaped empty result (`(0, M, N)` / `(B, 0, N)` / `(0, G, N)` as applicable), no backend reached.
Unverified: `batched_gemm_a8w8_mxscale_bpreshuffle_fused_quant`, a related function with a distinct `(fp8, e8m0-scale)` tuple return contract, is explicitly left out of this PR (see below) rather than guessed at.

PR-specific question

Why does `batched_gemm_a8w8_mxscale_bpreshuffle_fused_quant` not get the same fix in this PR? It shares the same tuned-lookup-before-kernel-launch shape as the four fixed functions, but its return type is a `(fp8 tensor, e8m0 scale tensor)` pair rather than a single `[M, G, N]` tensor, and its scale-tensor shape (`(m, g * n // 32)`) is derived differently than the other four. I did not want to guess at the right empty-result shape for an untested return contract and ship it unverified; flagging it as a follow-up instead.

Changed op tests

- `op_tests/test_batched_gemm_zero_m.py` (new file): one pytest case per fixed entry point covering `batch=0` (bf16, a8w8) and `M=0` (bf16, a8w8 mxscale, a8w8 mxscale_bpreshuffle). Not redundant with the existing `test_batched_gemm_bf16.py`, `test_batched_gemm_a8w8.py`, or `test_batched_gemm_a8w8_mxscale_bpreshuffle.py`, which are correctness/benchmark scripts exercising non-zero shapes against a numeric reference and have no zero-size case; the new file only asserts shape/dtype, which is the right check for an empty result and would not fit those files' numeric-comparison structure.

PR state

  • PASS — pull request is marked ready for review

Copilot findings

  • PASS — no active Copilot finding lacks a substantive author reply
  • ADVISORY — Copilot did not review the current head SHA

Code and op-test hygiene

  • PASS — no committed artifact or conflict marker detected

Required CI

  • PASS — Black: passed
  • PASS — Ruff: passed
  • PASS — Repository dependency: passed
  • PASS — Aiter Test Gate: passed

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

@zufayu

zufayu commented Dec 1, 2026

Copy link
Copy Markdown
Contributor Author

@aiter-bot review

@aiter-bot

Copy link
Copy Markdown

aiter-bot — queued behind 31 review(s); expect to start in about 0 min. The box reviews one PR at a time.

@aiter-bot aiter-bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ROCm/aiter PR #8996 — Return an empty result for a zero batch/row count in batched GEMMs

Review (advisory): ⚠️ NEEDS WORK
Validation (deterministic): NOT RUN — REVIEW_AUTO_VALIDATE=0 (auto-validation disabled on this box); the target op_tests/test_batched_gemm_zero_m.py exists and CI's Aiter Test Gate ran it green on the head SHA, but no head-matched validation report was produced
Perf (advisory): NOT RUN — the target op_tests/test_batched_gemm_zero_m.py ships no benchmark entry point (no --scenario bench, no perftest/@benchmark harness); the non-degenerate path only moves the Y allocation and adds no work
Size: 93 lines / 3 files
Design (advisory): NONE — the zero-size no-op pattern the dense GEMM family already established (#8960, #8995) under #8984's "zero leading dim" rule: allocate the output, return it empty before the tuned lookup and the launch
Human: N/A — the design is NONE: the diff implements an existing pattern and decides nothing new; the scope it leaves open (zero n/k, the Triton entry, the fused_quant sibling) is reported as findings below

⚠️ [verified] The four guarded entry points in aiter/ops/batched_gemm_op_a8w8.py and aiter/ops/batched_gemm_op_bf16.py are public API star-imported into aiter/init.py, and the mxscale bpreshuffle entry is the gfx950 DeepSeek-V4/V4.1 BMM path its own docstring names, yet the PR carries no ci: label, so the ATOM/SGLang/vLLM jobs are skipped and only Aiter Test on MI35X ran — a downstream-consumed GEMM contract change merging on aiter-only CI, though the change is behavior-preserving for every non-zero shape. Author must add ci:all (DeepSeek is exercised by atom+sglang+vllm) and require it green before merge.

📝 [verified] The guards cover only the leading dims (b==0 or m==0; m==0 or g==0), so a zero n (WQ.shape[1]==0) or zero k still reaches get_CKBatchedGEMM_config and the launch in all four fixed entries in aiter/ops/batched_gemm_op_a8w8.py — against #8984's "never fail at the backend" premise, and the dense family is itself split on the form (gemm_op_a8w8.py guards M==0 at one entry but numel()==0 at gemm_a8w8_bpreshuffle_out). Reviewer should ask whether the sweep should short-circuit on numel()==0 so a zero N or K is covered too.

📝 [verified] batched_gemm_a8w8_mxscale_bpreshuffle_fused_quant (aiter/ops/batched_gemm_op_a8w8.py:462) is excluded with a stated reason (its (fp8, e8m0) tuple return contract) but no follow-up issue is linked, and aiter/aot/flydsl/gemm.py:242 calls it — so that path still reaches the launch for m==0 and the exclusion lives only in this PR's description. Reviewer should ask for the follow-up issue number so the gap is tracked rather than remembered.

def batched_gemm_a8w8_mxscale_bpreshuffle_fused_quant(

@zufayu
zufayu requested a review from yifehuan December 2, 2026 01:27
zufayu added a commit to zufayu/aiter that referenced this pull request Dec 3, 2026
Zero tokens happens in production when an idle data-parallel rank runs
a dummy step to stay in its group's collectives (ROCm#8958). This extends
the no-op convention already applied to the GEMM entry points (ROCm#8960,

- fused_moe_dp_share_expert (aiter/fused_moe_dp_shared_expert.py):
  already had an `if M == 0: return moe_buf` guard, but it sat after
  the get_2stage_cfgs tuned lookup, so a zero-token call was still
  doing a config lookup it never used. Moved the guard (and the
  moe_buf allocation it depends on) before that lookup; nothing else
  on this path reads `metadata` before the lookup, so the reorder is
  safe.
- fused_moe_2stages (aiter/fused_moe.py): had no guard at all. Added
  one right after `token_num` and the `moe_out` buffer are resolved
  (the existing `moe_out.numel() == 0` check right above it is a
  different thing -- a reduce-mode workspace placeholder, not a
  token-count check), before get_2stage_cfgs.
- fused_moe_1stage (aiter/fused_moe.py): had no guard. Its first branch
  (pure bf16) dispatches straight into aiter.fmoe before `token_num` is
  even read, so the guard has to sit above all three branches, right
  after the kernelName validation block.

Verified on MI300X (gfx942): on origin/main, fused_moe_2stages and
fused_moe_1stage both reach their real kernel entry point for
token_num=0 (confirmed by a TypeError demanding non-None sorting
metadata tensors that a token_num=0 caller has no reason to build).
fused_moe_dp_share_expert already worked correctly on origin/main, just
with the wasted lookup this change removes. With this change all three
return a correctly-shaped empty bf16 result without reaching a kernel,
and without requiring real sorted_ids/sorted_weights/etc. for the
token_num=0 case.

fused_moe / fused_moe_ / _fused_moe_impl (the main public MoE entry,
layered above fused_moe_1stage/2stages) are left out of this PR's
scope: the real first-dispatch point in _fused_moe_impl was not
pinned down, and guessing at it risks a guard that looks right but
never executes. Flagging as a follow-up.

Added op_tests/test_fused_moe_zero_tokens.py covering all three.

Related: ROCm#8984, ROCm#8958, ROCm#8960, ROCm#8992, ROCm#8995, ROCm#8996

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

LGTM

@yifehuan
yifehuan merged commit bc7a7e8 into ROCm:main Dec 3, 2026
61 checks passed
AndreasKaratzas added a commit that referenced this pull request Dec 3, 2026
Conflicts in aiter/ops/batched_gemm_op_a8w8.py and
aiter/ops/batched_gemm_op_bf16.py: keep main's early return for b == 0
or m == 0 (#8996) before the tuned lookup, and keep this
branch's XQ.device.index argument to get_CKBatchedGEMM_config.

The merge also brings main's spec_verify_pick and moves the
3rdparty/composable_kernel pin to 39483cc9.

Co-authored-by: Claude <[email protected]>
Signed-off-by: Andreas Karatzas <[email protected]>
zufayu added a commit to zufayu/aiter that referenced this pull request Dec 4, 2026
Zero tokens happens in production when an idle data-parallel rank runs
a dummy step to stay in its group's collectives (ROCm#8958). This extends
the no-op convention already applied to the GEMM entry points (ROCm#8960,

- fused_moe_dp_share_expert (aiter/fused_moe_dp_shared_expert.py):
  already had an `if M == 0: return moe_buf` guard, but it sat after
  the get_2stage_cfgs tuned lookup, so a zero-token call was still
  doing a config lookup it never used. Moved the guard (and the
  moe_buf allocation it depends on) before that lookup; nothing else
  on this path reads `metadata` before the lookup, so the reorder is
  safe.
- fused_moe_2stages (aiter/fused_moe.py): had no guard at all. Added
  one right after `token_num` and the `moe_out` buffer are resolved
  (the existing `moe_out.numel() == 0` check right above it is a
  different thing -- a reduce-mode workspace placeholder, not a
  token-count check), before get_2stage_cfgs.
- fused_moe_1stage (aiter/fused_moe.py): had no guard. Its first branch
  (pure bf16) dispatches straight into aiter.fmoe before `token_num` is
  even read, so the guard has to sit above all three branches, right
  after the kernelName validation block.

Verified on MI300X (gfx942): on origin/main, fused_moe_2stages and
fused_moe_1stage both reach their real kernel entry point for
token_num=0 (confirmed by a TypeError demanding non-None sorting
metadata tensors that a token_num=0 caller has no reason to build).
fused_moe_dp_share_expert already worked correctly on origin/main, just
with the wasted lookup this change removes. With this change all three
return a correctly-shaped empty bf16 result without reaching a kernel,
and without requiring real sorted_ids/sorted_weights/etc. for the
token_num=0 case.

fused_moe / fused_moe_ / _fused_moe_impl (the main public MoE entry,
layered above fused_moe_1stage/2stages) are left out of this PR's
scope: the real first-dispatch point in _fused_moe_impl was not
pinned down, and guessing at it risks a guard that looks right but
never executes. Flagging as a follow-up.

Added op_tests/test_fused_moe_zero_tokens.py covering all three.

Related: ROCm#8984, ROCm#8958, ROCm#8960, ROCm#8992, ROCm#8995, ROCm#8996
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.

3 participants