Skip to content

[HIP] getPaddedM: fall back to the M=16 row for M<16 when no power-of-two row is tuned - #7552

Open
afriedri-amd wants to merge 5 commits into
ROCm:mainfrom
afriedri-amd:fix-padded-m-r16-fallback
Open

afriedri-amd wants to merge 5 commits into
ROCm:mainfrom
afriedri-amd:fix-padded-m-r16-fallback

Conversation

@afriedri-amd

@afriedri-amd afriedri-amd commented Nov 6, 2026 •

Copy link
Copy Markdown
Contributor

Summary

getPaddedM(gl=1) now returns 16 for 0 < M < 16. The tuned-config walk (exact → gl=0 → gl=1) used to stop at nextPow2(M) for small M. It is now exact → nextPow2(M) → 16, so a tuned M=4/8 row is still preferred (as #6079 intended), and the M=16 row still serves M=2..8 when no power-of-two row exists.

Motivation

#6079 changed gl=0 for 0 < M < 16 from "round up to 16" to nextPow2(M). gl=1 was already nextPow2(M), so for small M both levels give the same value, and nothing in the walk reaches an M=16 row any more. Any tuned table with M=1/16 rows but no M=2/4/8 rows misses at decode batch 2..8 and silently falls back to the untuned default.

Most gfx950 tables in 0.1.26 have that shape: bf16, a8w8 (+ blockscale/bpreshuffle) and a4w4, across the llama70B/405B, qwen, dsv3/dsv4, glm, kimi and minimax model_configs.

End-to-end example: vLLM v0.33.0 (aiter 0.1.26) running BF16 Llama-3.3-70B-Instruct at TP8, conc 8, 1k/1k on MI355X loses 13% throughput vs vLLM v0.32.0 (aiter 0.1.24.post1). llama70B_bf16_tuned_gemm.csv is identical in both. The decode GEMMs move from FlyDSL hgemm_bf16_* to hipBLASLt.

Changes

  • csrc/py_itfs_cu/gemm_common.cu: getPaddedM(gl=1) returns 16 for 0 < M < 16. gl=0 and every M >= 16 are unchanged.
  • op_tests/test_padded_m_lookup.py (new): covers the level table and the a16w16 walk against the real compiled op.

Performance

Hardware Workload/configuration Before After Change
MI355X (gfx950, 256 CU) ×8 vLLM v0.33.0, BF16 Llama-3.3-70B-Instruct, TP8, conc 8, 1024/1024, 80 prompts 802 tok/s, TPOT 9.70 ms 940–943 tok/s, TPOT 8.22 ms +17.4%
same vLLM v0.33.0-rocm72 image (ROCm 7.2.3) 843–845 tok/s 930–932 tok/s +10.3%

Reference: vLLM v0.32.0 + aiter 0.1.24.post1 = 925 tok/s.

The "After" rows were measured with the equivalent Python-side change: an M→16 candidate appended to the walk in tuned_gemm.get_GEMM_A16W16_tuned_config. It produces the same lookup sequence as this C++ change for the bf16 path. Each figure is 2 server restarts × 2 runs; TTFT is flat.

Testing

  • Unit tests added or updated: python3 op_tests/test_padded_m_lookup.py. With the fix: 3/3 pass, run against aiter 0.1.26 with this gemm_common.cu JIT-rebuilt. Without the fix: 15 sub-test failures (M = 1..8 levels, M = 2..8 fallback).
  • Performance benchmarks run (see above)
  • Tested on MI250X
  • Tested on MI300X: not run. The change is arch-independent integer logic.

Documentation

  • No documentation change is needed: an internal lookup-order fix, with the code comment updated.

Dependencies

  • No new third-party dependencies added

Breaking Changes

None. Shapes that hit an exact or power-of-two row resolve exactly as before. Shapes that previously fell to the default at M = 2..8 now use their M=16 row, which is how they resolved before #6079.

PR Self-Review

Reviewed revision

3a92b87b477d

Behavior and intent

Restores the pre-#6079 reachability of M=16 rows for small M, while keeping #6079's preference for finer power-of-two rows.

Validation and unverified scope

The gemm_common.cu change is unchanged since 770e9931de62. Later commits merge main, and cd5aaf827 updates the test: main replaced tuned_gemm.get_gfx with explicit gfx= / cu_num= arguments, so the test now passes those instead of patching module globals. main still has gl=0 and gl=1 both returning nextPow2(M) for 0 < M < 16, and find_padded_m_row still walks exact → gl=0 → gl=1.

  • Validated: the unit test (real compiled op), the bf16 lookup for the four Llama-70B TP8 decode shapes (M=8 → flydsl again), and e2e vLLM throughput with the Python-equivalent change on bf16.
  • Unverified: e2e perf for the a8w8 / a4w4 / opus / CK paths. They share this function and walk order, but no model was benchmarked on them. MI300X was not run.

PR-specific question

Boundaries. No arch or dtype condition is involved. getPaddedM is arch-independent integer logic shared by every tuned-GEMM lookup: the C++ CK and cktile a8w8 bpreshuffle lookups, and the Python a16w16 (tuned_gemm), a8w8, a4w4, opus and a8w4 lookups. The only change is at gl=1 with 0 < M < 16, and that level is reached only after the exact-M and gl=0 (nextPow2(M)) keys have both missed. For M >= 16, and for any shape that has an exact or power-of-two row, the selected row is unchanged.

Invariant. The padded M is used only as a lookup key. Every caller runs the GEMM at the real M, and inputs and outputs are not padded (see the gemm_op_a8w4 docstring). A row is used only when (gfx, cu_num, padded M, N, K, plus the dtype/bias/preshuffle key fields) matches exactly, so the change never selects a kernel for a different arch, dtype or N/K. It only lets an M=16 row serve M in 1..15. That is the pre-#6079 behavior: gl=0 rounded M < 16 up to 16, so these rows served M=1..15 through aiter 0.1.24. a8w4 also re-checks each row against the actual shape before using it. When no row matches, the default path is unchanged.

Changed op tests

op_tests/test_padded_m_lookup.py (new). Existing lookup tests mock get_padded_m to the identity, so none of them covers the real level table. This test does, and it fails on current main.

Prepared with AI assistance (Claude Code); reviewed and validated by the submitter.

Signed-off-by: Andy Friedrich <[email protected]>
@afriedri-amd
afriedri-amd requested a review from a team November 6, 2026 06:52
@github-actions

github-actions Bot commented Nov 6, 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
ci:windows Windows JIT op smoke test on the gfx1201 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 7552 --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.

@github-actions github-actions Bot added the HIP label Nov 6, 2026
@aiter-bot

aiter-bot commented Nov 6, 2026 •

Copy link
Copy Markdown

READY FOR HUMAN REVIEW

PR Self-Review

Revision 3a92b87b477d · 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

Restores the pre-#6079 reachability of M=16 rows for small M, while keeping #6079's preference for finer power-of-two rows.

Validation and unverified scope

The `gemm_common.cu` change is unchanged since `770e9931de62`. Later commits merge `main`, and `cd5aaf827` updates the test: `main` replaced `tuned_gemm.get_gfx` with explicit `gfx=` / `cu_num=` arguments, so the test now passes those instead of patching module globals. `main` still has `gl=0` and `gl=1` both returning `nextPow2(M)` for `0 < M < 16`, and `find_padded_m_row` still walks exact → `gl=0` → `gl=1`.
- Validated: the unit test (real compiled op), the bf16 lookup for the four Llama-70B TP8 decode shapes (M=8 → flydsl again), and e2e vLLM throughput with the Python-equivalent change on bf16.
- Unverified: e2e perf for the a8w8 / a4w4 / opus / CK paths. They share this function and walk order, but no model was benchmarked on them. MI300X was not run.

PR-specific question

**Boundaries.** No arch or dtype condition is involved. `getPaddedM` is arch-independent integer logic shared by every tuned-GEMM lookup: the C++ CK and cktile a8w8 bpreshuffle lookups, and the Python a16w16 (`tuned_gemm`), a8w8, a4w4, opus and a8w4 lookups. The only change is at `gl=1` with `0 < M < 16`, and that level is reached only after the exact-M and `gl=0` (`nextPow2(M)`) keys have both missed. For `M >= 16`, and for any shape that has an exact or power-of-two row, the selected row is unchanged.

**Invariant.** The padded M is used only as a lookup key. Every caller runs the GEMM at the real M, and inputs and outputs are not padded (see the `gemm_op_a8w4` docstring). A row is used only when (gfx, cu_num, padded M, N, K, plus the dtype/bias/preshuffle key fields) matches exactly, so the change never selects a kernel for a different arch, dtype or N/K. It only lets an M=16 row serve M in 1..15. That is the pre-#6079 behavior: `gl=0` rounded `M < 16` up to 16, so these rows served M=1..15 through aiter 0.1.24. a8w4 also re-checks each row against the actual shape before using it. When no row matches, the default path is unchanged.

Changed op tests

`op_tests/test_padded_m_lookup.py` (new). Existing lookup tests mock `get_padded_m` to the identity, so none of them covers the real level table. This test does, and it fails on current main.

_Prepared with AI assistance (Claude Code); reviewed and validated by the submitter._

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.

@yelkhamra

Copy link
Copy Markdown
Contributor

Thanks for this — the gl = 1 fallback looks right to me, and I reproduced the lookup loss independently on CPU.

At current main (ef0a5a26b8cb38ea1308f827985e36cde964a6ab), getPaddedM returns nextPow2(M) for 0 < M < 16 at both granularities: gl = 0 (csrc/py_itfs_cu/gemm_common.cu:20-26) and gl = 1 (:43-49). find_padded_m_row (aiter/ops/gemm_op_common.py:13-23) tries exact M, then gl = 0, then gl = 1, so for M1–8 both padded attempts repeat the same key; when a table has an M16 row and no smaller one, that row is never reached. M9–15 still reach it because nextPow2 returns 16 there.

The reproducer below imports nothing from AITER and needs no GPU. Run it from a checkout root with Python 3 and a host C++ compiler; it reads the tuned tables for one E8M0 key (N=7168, K=21504, w_scale_block=128x128), compiles csrc/py_itfs_cu/gemm_common.cu, and calls that checkout's find_padded_m_row:

"""Run from an unpatched AITER checkout; needs Python 3 and a host C++ compiler."""
import ast
import csv
import ctypes
from pathlib import Path
import subprocess
import tempfile

root = Path.cwd()
family = "a8w8_blockscale_mxscale_bpreshuffle_tuned_gemm"
configs = root / "aiter/configs"
paths = [configs / f"{family}.csv"] + sorted(
    p for p in (configs / "model_configs").glob(f"*{family}*.csv")
    if "untuned" not in p.name
)
# Only M <= 16 can be reached by this example. This key has no duplicates
# in the canonical-plus-model input tables, so no merge tie-break is needed.
rows = {}
for path in paths:
    with path.open() as stream:
        for row in csv.DictReader(stream):
            if (row.get("gfx"), row["cu_num"], row["N"], row["K"],
                    row.get("w_scale_block") or "128x128") != (
                    "gfx950", "256", "7168", "21504", "128x128"):
                continue
            m = int(row["M"])
            if m <= 16:
                assert m not in rows, "Duplicate key: inspect the merge policy"
                rows[m] = row
assert sorted(rows) == [16]
print("Available M <= 16:", sorted(rows))

# Extract the real finder without importing AITER or loading GPU libraries.
common = root / "aiter/ops/gemm_op_common.py"
finder = next(node for node in ast.parse(common.read_text()).body
              if isinstance(node, ast.FunctionDef)
              and node.name == "find_padded_m_row")
with tempfile.TemporaryDirectory(prefix="padded-m-repro-", dir=root) as scratch:
    scratch = Path(scratch)
    cpp = scratch / "helper.cpp"
    cpp.write_bytes((root / "csrc/py_itfs_cu/gemm_common.cu").read_bytes())
    library = scratch / "helper.so"
    subprocess.run(["c++", "-shared", "-fPIC", "-O0", str(cpp),
                    "-o", str(library)], check=True)
    padded = ctypes.CDLL(str(library)).getPaddedM
    padded.argtypes = [ctypes.c_int] * 4
    padded.restype = ctypes.c_int
    namespace = {"get_padded_m": padded}
    exec(compile(ast.Module(body=[finder], type_ignores=[]), str(common), "exec"),
         namespace)
    for m in (1, 8, 9, 15):
        row, selected_m = namespace["find_padded_m_row"](
            rows, lambda pm: pm, m, 7168, 21504
        )
        print(f"M={m}: " + ("MISS" if row is None else f"padded_M={selected_m}"))

Without the change it reports M=1: MISS, M=8: MISS, M=9: padded_M=16, M=15: padded_M=16. With your gl = 1 change applied to the same tree, M1 and M8 report padded_M=16 (M9 and M15 were already reachable at 16).

One thing for reviewers to weigh, not a blocker: restoring the M16 fallback also makes BF16 split-K M16 rows reachable for the small M that currently miss them. Those rows are implicated in the nondeterminism tracked in #6114, and the open drafts #7053 and #5362 propose fp32 reduction for them. The newly restored small-M points inherit that behaviour until it is fixed, so it may be worth deciding explicitly whether to take the full fallback or restrict it to non-split-K rows.

afriedri-amd and others added 4 commits November 20, 2026 15:23
… patching

main replaced tuned_gemm.get_gfx with get_gfx_runtime and gave
get_GEMM_A16W16_tuned_config explicit gfx= / cu_num= arguments, so the
mock.patch of tuned.get_gfx raised AttributeError after the merge.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
// 16-row bucket. Tables tuned only at M = 1 / 16 keep serving 2..15.
if (M > 0 && M < 16) {
padded_m = 16;
} else if (M > 8192 && N > 4096) {

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.

why we need n>4096? m>8192 should be fine?

@afriedri-amd afriedri-amd Nov 30, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

That logic was pre-existing, I just moved it below the 0 < M < 16 branch that I added. Not sure of the original reasoning; making the change here would change behavior on main so inclined not to change in this PR.

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 don't think add padded_m=16 is a good idea since every m will probably make great effort when conc is low.

@afriedri-amd
afriedri-amd requested a review from demonsan December 3, 2026 15:39
@demonsan

demonsan commented Dec 4, 2026

Copy link
Copy Markdown
Contributor

@aiter-bot review

@aiter-bot

Copy link
Copy Markdown

aiter-bot — queued behind 6 review(s); expect to start in about 73 min. The box reviews up to 4 PRs 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 #7552 — [HIP] getPaddedM: fall back to the M=16 row for M<16 when no power-of-two row is tuned

Review (advisory): ⚠️ NEEDS WORK
Validation (deterministic): NOT RUN — target op_tests/test_padded_m_lookup.py exists, but this review box has no usable GPU (rocminfo cannot open /dev/kfd, torch is CPU-only, all 8 GPUs at 96% use) and auto-validation is disabled (REVIEW_AUTO_VALIDATE=0); the run was attempted in a /tmp sandbox and blocked by the environment — an environment gap, not a PR defect
Perf (advisory): NOT RUN — target op_tests/test_padded_m_lookup.py exposes no benchmark entry point, and the PR's e2e numbers (802 → 940 tok/s, +17.4%) were measured with a Python-equivalent of this change, not this C++ diff
Size: 77 lines / 2 files
Design (advisory): whether the restored gl=1 M=16 fallback for 0<M<16 should also serve split-K tuned rows — the class open issue #6114 tracks as nondeterministic bf16 split-K accumulation — or be restricted to non-split-K rows
Human: recommend valarLip review whether PR #7552's restored getPaddedM M=16 fallback at gl=1 should include the split-K rows that #6114 tracks as nondeterministic, given valarLip's #6079 chose nextPow2(M) at gl=0 for small M

📝 [verified] The e2e gain (+17.4%, 802 → 940 tok/s) was measured with a Python-side equivalent of this change rather than this C++ diff, and the a8w8/a4w4/opus/CK lookups that share getPaddedM are unmeasured — the PR discloses both, but no base-vs-head timing of this diff exists and op_tests/test_padded_m_lookup.py ships no benchmark entry point. Reviewer should ask for one e2e or lookup-level run with the actual C++ build to confirm the Python-equivalence claim.

1 finding(s) posted inline, on the lines they are about:

  • csrc/py_itfs_cu/gemm_common.cu:46 — restores M=16-row reachability for M=2..8 in every tuned-GEMM walk, and the motivating table…

if (M > 8192 && N > 4096) {
// M < 16: gl = 0 already tried nextPow2(M), so fall back to the
// 16-row bucket. Tables tuned only at M = 1 / 16 keep serving 2..15.
if (M > 0 && M < 16) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ [verified] csrc/py_itfs_cu/gemm_common.cu:46 restores M=16-row reachability for M=2..8 in every tuned-GEMM walk, and the motivating table aiter/configs/model_configs/llama70B_bf16_tuned_gemm.csv has gfx950 M=16 rows with splitK 2/4/8 (e.g. N=1280/K=8192 flydsl ...ks8) and no M=2/4/8 rows — so decode batches 2..8 re-select split-K FlyDSL bf16 kernels, the class open issue #6114 measures as nondeterministic (run-to-run varying, ~50% of outputs one bf16 ULP off PyTorch), a consequence the PR's "Breaking Changes: None" section never discloses. Author must either restrict the small-M fallback to non-split-K rows or state on the PR that inheriting #6114's behavior at M=2..8 is accepted.

This branch has not been deployed

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

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants