Skip to content

[gfx1250] Fix three gluon GEMM correctness bugs and tune the Kimi-K3 a16w16 shapes - #4537

Closed
XiaobingSuper wants to merge 5 commits into
mainfrom
xiaobing/gfx1250-gluon-gemm-pipeline-fix
Closed

XiaobingSuper wants to merge 5 commits into
mainfrom
xiaobing/gfx1250-gluon-gemm-pipeline-fix

Conversation

@XiaobingSuper

@XiaobingSuper XiaobingSuper commented Aug 3, 2026 •

Copy link
Copy Markdown
Contributor

Four commits, in dependency order: three correctness fixes in the gfx1250 gluon
GEMM kernels, then the tuned configs, which are only safe to ship on top of
them. Scope is a16w16 (basic + batched) only.

1. compute_bound prologue over-fills the TDM ring

The compute_bound pipelines issue NUM_BUFFERS async_load pairs into a ring
of NUM_BUFFERS slots, then read tile compute_idx + 1 -- one ahead of the
slot they are about to overwrite. So the write target load_idx % NUM_BUFFERS
is the slot the next iteration reads, and nothing orders the two: the LDS
reads go through gl.amd.cdna4.async_copy.load_shared_relaxed, which sets
ttg.amdg.syncedViaAsyncWait and suppresses the barrier MembarPass would
otherwise insert. A wave that has not drained its read sees the tile
overwritten under it. Wrong results, silently.

Fix: fill to NUM_BUFFERS - 1, leaving one slot free, and shift the
async_wait counts and trip counts to match.

a16w16 N=7168 K=3072 M=16384, random bf16 vs chunked fp32 at 2e-2, one variant
per process, 8 processes per config crossed over 4 GPUs, 10 trials each,
counting processes with any bad trial:

tile config before after
64-64-128-4-4 8/8 0/8
128-128-128-3-4 6/8 0/8
128-256-64-5-4 8/8 0/8
256-256-64-3-4 2/8 0/8

batched_gemm_bf16 compute_bound behaves identically (8/8, 8/8, 6/8, 6/8, 1/8
before; 0/8 after at all six configs tried).

This commit alone regressed 256-256-64-3-8 from 0/8 to 5-6/8. That was
originally filed here as an unexplained residual; it is the subject of commit 3
and is fixed.

Note on method, in case it saves someone else the trip: the sampling unit has
to be the process. A variant holds one behaviour for a process's lifetime
and draws again in the next -- the same variant/config gave 0/20, 8/20 and
7/20 in three processes, far wider than binomial. And variant must be
crossed with the physical GPU, not assigned one per device: on this box
GPU 1 suppresses these races, so a variant-per-device layout makes "depth
fails, shipped doesn't" and "GPU 3 fails, GPU 1 doesn't" the same measurement.
An earlier pass of this work got a conclusion backwards that way.

2. buffer_store drops C tiles past 2 GiB

gl.amd.gfx1250.buffer_store addresses through the 32-bit byte offset of a
buffer resource descriptor. The a16w16 and batched bf16 stores build offs_c
as a full linear index from the tile origin, so once C exceeds 2 GiB every tile
whose origin is past 2^31 bytes fails the bounds check and is discarded.
Nothing raises -- the output just comes back with a zero tail.

Fix: fold the tile origin into c_ptr in int64, keep only tile-local offsets
in offs_c. Those are bounded by the block shape, so the 32-bit fast path
stays valid at every size and nothing changes below the cap.

At N=40960 K=7168 M=32768 (C = 2.50 GiB), all-ones operands so every element
must equal K exactly:

kernel_type before after
bandwidth_bound 268435460 elements wrong, first bad row 26214, max rel err 1.0 0 wrong
compute_bound 0 wrong 0 wrong

Row 26214 is exactly the cap: 2^31 / (40960 * 2) = 26214.4. compute_bound is
unaffected because it stores through a TDM descriptor, whose base is 64-bit.

The same pattern exists at _gluon_kernels/gfx1250/moe/reduce.py:77 and
_gluon_kernels/gfx1250/attention/unified_attention_reduce.py:116. Left alone
here -- they need their own reachability analysis and test.

3. TDM ring wait counts ops instead of tiles

Every wait site gated compute on tdm.async_wait(N) -- s_wait_tensorcnt N,
"block until at most N TDM ops are outstanding" -- with N doubled to cover
the two ops (one A, one B) that make up a tile. That doubling is wrong.

A and B are issued from two different tensor descriptors and retire on two
independent in-order streams that share one counter
. With T tiles in flight
each stream holds T of its own ops, and "at most N outstanding" only implies
the oldest A and the oldest B have landed when N <= T-1: at any larger N
one stream can still hold all T of its ops while the other has drained. So
the argument counts tiles, not ops, and (T-1)*2 lets a wave read a ring
slot the DMA has not filled.

The defect predates this series. Commit 1 did not introduce the doubling -- it
only narrowed (NUM_BUFFERS-1)*2 to (NUM_BUFFERS-2)*2 -- but by dropping the
prologue from NUM_BUFFERS to NUM_BUFFERS-1 tiles it removed the one tile of
slack that had been hiding the hazard, which is why 256-256-64-3-8 regressed.

Established by sweeping a slack term D into every wait argument of the
compute_bound kernel and measuring 256-256-64-3-8 at 12 processes x 20 trials
over 4 devices, with the emitted s_wait_tensorcnt arguments read back from the
disassembly so the source change is confirmed to have reached the machine code:

slack emitted bad
D=0 0x2 8/12
D=1 0x1 0/12
D=2 0x0 0/12
D=99 0x0 0/12

Barrier count is 10 in every variant, so nothing was serialized by side effect,
and D=1 retains pipelining. That D=1 suffices refutes fully out-of-order
retirement; that D=0 fails refutes in-order retirement, under which waiting to 2
of 4 outstanding ops would provably have retired the oldest pair. Two in-order
streams keyed by descriptor is the only model consistent with both.

An operand-content discriminator identifies the hazard as a read of unfilled
LDS
, not a stale-but-valid tile: with both operands all ones every K tile is
byte-identical, so a wrong or stale slot cannot change the result, yet the
config still fails 9/12. A-only and B-only variants both fail, so either stream
can be the one that lags.

Verified after the fix, 12 processes x 20 trials over 4 devices:

kernel configs result
a16w16 compute_bound 256-256-64-3-8, 256-256-64-3-4, 64-64-128-4-4, 128-128-128-3-4, 128-256-64-5-4, 128-128-64-4-4 all 0/12
batched compute_bound same, plus 256-256-64-4-8 all 0/12

num_warps=8 on the batched kernel had no coverage before and is included.

bandwidth_bound is corrected on the same argument (T = NUM_BUFFERS there, so
the wait is NUM_BUFFERS-1) but on the model, not on a reproduced failure:
25 configs x 4 processes x 10 trials are 0 both before and after. Flagging that
explicitly -- if a reviewer would rather see bandwidth_bound left alone until it
can be made to fail, that hunk is separable.

Cost

Correctness is not free where the ring is shallow. At NUM_BUFFERS=3 the ring
holds 2 tiles = 4 TDM ops and the correct wait leaves 1 outstanding, which is
nearly a full drain. a16w16 compute_bound, M=16384 N=7168 K=3072, min of 5
alternating runs:

config before after delta
256-256-64-3-8 0.805 ms 1.003 ms +24.6%
256-256-64-3-4 0.700 0.881 +25.9%
128-128-128-3-4 0.985 1.108 +12.5%
128-256-64-5-4 0.826 0.885 +7.2%
128-128-64-4-4 0.984 0.989 +0.5%
64-64-128-4-4 1.594 1.572 -1.4%

bandwidth_bound is unaffected at the depths the tuned set uses (-0.7% at
256-256-64-3-8, +0.8% at 128-128-64-4-4, +4.3% at 256-128-64-4-8) and pays the
same shallow-ring cost only at NUM_BUFFERS=2 (+24.2%). compute_bound at
NUM_BUFFERS=2 is unchanged -- its wait was already 0.

Commit 4 re-picks the configs on top of this and gets most of it back; see
below.

4. Tuned a16w16 configs for the Kimi-K3 shapes

All 24 a16w16 shapes Kimi-K3 hits on gfx1250 tp4 were running the untuned
default tile (32/64/64, NUM_BUFFERS 5, num_warps 2, bandwidth_bound).
Tuned over M = 1, 2, 4 ... 32768.

Tuned on the kernel this PR ships, i.e. with the three preceding fixes applied.
That matters more than it sounds: an earlier revision of this PR carried configs
ranked against the pre-fix kernel and reported 3.59x over the default tile.
That kernel was not really waiting on its TDM ring, so tiles that skipped a wait
ranked as fast, and the number could not be carried forward.

Re-timed on the shipped kernel, every point in its own process with the three
config sources alternating inside it and the min taken over three rounds:

source total over 384 points
untuned default tile 440752us
configs ranked pre-fix 165392us 2.66x vs default
these configs 143433us 3.07x vs default

The pre-fix set still works -- it is 2.66x over the default -- but it lost
ground once the wait it had been ranked against became real. Re-tuning recovers
13.3% of that. 3.07x is the honest replacement for the earlier 3.59x.

Selection is deliberately conservative, because a tile holds one speed for a
process's lifetime and draws a different one in the next:

  • six independent tuner runs, one sample each, ranked on the median across
    runs, not on any single run;
  • ranked on median + spread/2, not the median alone -- a few tiles are bimodal
    and their median can win while their slow mode is worse than the default;
  • a candidate must beat the default at every M in the bucket, not on average.

Where nothing cleared that bar the default tile is kept: 18 of the 384
points
, in 10 buckets before collapsing. An untuned point costs nothing, a
regressed one costs real time. There are no points where the default is faster
than what is shipped here.

Every emitted config was then screened for correctness on the shipped kernel --
not on a patched copy -- at the largest M its bucket governs, with one operand
all ones so the expected result is an exact 1-D fp32 sum: no reference GEMM, and
no dependence on hipBLASLt, which was itself off by 5.3e-02 on one of these
shapes. Both operand roles are covered by running the pass twice with the roles
swapped, which matters here because the bug fixed in commit 3 is a two-stream
wait and a single-pattern screen would exercise one stream. 240/240 bucket
entries pass
, 3 trials each.

Two of the 24, N=2112 K=7168 and N=12440 K=7168 (the fused KDA in_proj GEMM),
reach the triton path only once they have a routing row in
kimik3_bf16_tuned_gemm.csv. Those 15 rows are #4552, split out so this PR
stays kernel fixes plus tuned config JSONs. Neither PR blocks the other: the
configs here sit unused for those two shapes until #4552 lands, and #4552 on its
own routes them to the default tile, which is the configuration its -24.7% TTFT
was measured in.

Not done yet

  • No perf-parity measurement of the commit-2 store change below the 2 GiB cap.
    It should be free -- the arithmetic moves out of the inner path -- but it is
    unmeasured.
  • The two buffer_store sites named in commit 2 (moe/reduce.py,
    attention/unified_attention_reduce.py) are untouched.
  • The bandwidth_bound half of commit 3 is model-backed only, as noted there, and
    is separable if a reviewer prefers.

Tested on gfx1250, 256 CU, SPX, 4 GPUs.

🤖 Generated with Claude Code

@github-actions

github-actions Bot commented Aug 3, 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:triton-300x Run an additional Triton test job on MI300X in PRs; main branch always runs both MI35X and MI300X
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 4537 --add-label <label>

XiaobingSuper and others added 2 commits August 4, 2026 04:41
…ring

The compute_bound pipelines issue NUM_BUFFERS async_load pairs in the prologue
into a ring of NUM_BUFFERS slots, then read tile compute_idx + 1 -- one tile
ahead of the slot they will next overwrite. The write target
load_idx % NUM_BUFFERS is therefore the slot the next iteration is about to
read, and nothing orders the two: the LDS reads use
gl.amd.cdna4.async_copy.load_shared_relaxed, which sets
ttg.amdg.syncedViaAsyncWait and so suppresses the barrier MembarPass would
otherwise insert. A wave that has not yet drained its read sees the tile
overwritten under it and the GEMM returns wrong results, silently.

Fill the prologue to NUM_BUFFERS - 1 instead, leaving one slot free so a TDM
write never lands on the tile being read this iteration, and shift the
async_wait counts and the main/epilogue trip counts to match. This is the depth
the bandwidth_bound kernel in the same file already uses; it needs one slot
fewer only because it has no register pre-load stage, so the compute_bound
variants were the outliers. Tile accounting is unchanged: both TDM loads and
WMMA issues still total num_k_tiles exactly.

Measured on gfx1250 (256 CU, SPX), a16w16 N=7168 K=3072 M=16384, random bf16
operands against a chunked fp32 reference at 2e-2, one variant per process,
8 processes per config crossed over all 4 GPUs, 10 trials each. Counting
processes with any bad trial:

  tile config      before    after
  64-64-128-4-4      8/8      0/8
  128-128-128-3-4    6/8      0/8
  128-256-64-5-4     8/8      0/8
  256-256-64-3-4     2/8      0/8

batched_gemm_bf16 compute_bound behaves the same (8/8, 8/8, 6/8, 6/8, 1/8
before at those configs plus 128-128-64-4-4; 0/8 after at all six).

The sampling unit is the process, not the trial: a variant holds one behaviour
for a process's lifetime and draws again in the next, so in-process trial
counts cannot rank variants. Variant and GPU are crossed rather than assigned
one per device -- on this box GPU 1 suppresses these races, so a
variant-per-device layout confounds the two completely.

This change alone regresses a16w16 256-256-64-3-8 compute_bound, which was
clean before it: shortening the epilogue by one iteration exposes a separate
write-after-read hazard on the C staging buffer. The next commit fixes that;
the two are split only to keep the mechanisms separable, and the pair should
land together.

Co-Authored-By: Claude Opus 5 <[email protected]>
gl.amd.gfx1250.buffer_store addresses through the 32-bit byte offset of a
buffer resource descriptor. The gluon a16w16 and batched bf16 stores build
offs_c as a full linear index from the tile origin, so once C exceeds 2 GiB
every tile whose origin lands past 2^31 bytes fails the descriptor's bounds
check and is discarded. Nothing raises: the output tensor simply comes back
with a zero-filled tail.

Fold the tile origin into c_ptr in int64 and keep only tile-local offsets in
offs_c. Those are bounded by BLOCK_M/BLOCK_N times the strides, so the 32-bit
fast path stays valid at every size and there is no change below the cap.

Reproduced on gfx1250 at N=40960 K=7168 M=32768 (C = 2.50 GiB) with all-ones
operands, where every output element must equal K exactly:

  kernel_type       before                        after
  bandwidth_bound   268435460 elements wrong,     0 wrong
                    first bad row 26214,
                    max relative error 1.0
  compute_bound     0 wrong                       0 wrong

Row 26214 is exactly the cap: 2^31 / (40960 * 2) = 26214.4. compute_bound is
unaffected because it stores through a TDM descriptor, whose base is 64-bit.

The same pattern is present in aiter/ops/triton/_gluon_kernels/gfx1250 at
moe/reduce.py:77 and attention/unified_attention_reduce.py:116; those are left
alone here as they need their own reachability analysis and test.

Co-Authored-By: Claude Opus 5 <[email protected]>
@zejunchen-zejun
zejunchen-zejun force-pushed the xiaobing/gfx1250-gluon-gemm-pipeline-fix branch 2 times, most recently from e68d5c6 to 949a00c Compare August 4, 2026 07:43
@XiaobingSuper

Copy link
Copy Markdown
Contributor Author

Repro scripts for the three fixes, so a reviewer can re-derive the claims rather than take the tables on trust. All of them are process-sampled and GPU-crossed for the reason in the PR body: a variant holds one behaviour for a process's lifetime, so trials within a process are not independent samples.

Run them from a checkout with this branch's kernels importable. --procs/--trials default to the values used for the tables.

script what it shows expected on this branch
verify_4537.py a16w16 compute_bound over the six configs, incl. 256-256-64-3-8 CLEAN, 0/12 everywhere
waitsweep_4537.py sweeps a slack term into every ring wait and prints the emitted s_wait_tensorcnt args D=0 fails on the pre-fix kernel, D>=1 clean
kind_4537.py operand-content discriminator: unfilled LDS vs stale-but-valid tile all three patterns fail pre-fix, incl. all-ones/all-ones
repro_4537_tdm_ring.py the original ring-depth repro from commit 1 0/12
repro_4537_store_2gib.py C past the 2 GiB buffer-descriptor cap (commit 2) 0 wrong elements

waitsweep_4537.py and kind_4537.py rewrite the kernel source in place and restore it in a finally; they are diagnostics for reproducing the pre-fix behaviour, not tests.

verify_4537.py
"""Correctness verification for the TDM wait-count fix.

Covers the config the PR regressed (256-256-64-3-8) plus the five configs the
ring-depth commit was originally measured on, so the fix is checked against both
the new failure and the ones it must not reintroduce.

Process-sampled and GPU-crossed: the sampling unit is the process, and a crashed
worker is reported rather than counted as a numerical failure.

Usage: python verify_4537.py [--procs 12] [--trials 20]
"""

import argparse
import os
import subprocess
import sys

M, N, K = 16384, 7168, 3072
EXIT_OK, EXIT_MISMATCH = 0, 2

CONFIGS = [
    (256, 256, 64, 3, 8),    # the config this PR regressed
    (256, 256, 64, 3, 4),
    (64, 64, 128, 4, 4),
    (128, 128, 128, 3, 4),
    (128, 256, 64, 5, 4),
    (128, 128, 64, 4, 4),
]


def cfg_of(c):
    bm, bn, bk, nb, nw = c
    return dict(BLOCK_M=bm, BLOCK_N=bn, BLOCK_K=bk, NUM_BUFFERS=nb,
                num_warps=nw, kernel_type="compute_bound")


def worker(c, trials):
    import torch

    from aiter.ops.triton.gemm.basic.gemm_a16w16 import gemm_a16w16

    torch.manual_seed(0)
    # w all ones => out[m,n] = sum_k x[m,k], an exact fp32 reference.
    x = torch.randn(M, K, dtype=torch.bfloat16, device="cuda") * 0.02
    w = torch.ones(N, K, dtype=torch.bfloat16, device="cuda")
    ref = x.float().sum(dim=1)[:, None]
    tol = 2e-2 * ref.abs().max().item()
    for _ in range(trials):
        out = gemm_a16w16(x, w, dtype=torch.bfloat16, config=cfg_of(c))
        torch.cuda.synchronize()
        if (out.float() - ref).abs().max().item() > tol:
            return EXIT_MISMATCH
    return EXIT_OK


if __name__ == "__main__":
    p = argparse.ArgumentParser()
    p.add_argument("--worker")
    p.add_argument("--procs", type=int, default=12)
    p.add_argument("--gpus", default="0,1,2,3")
    p.add_argument("--trials", type=int, default=20)
    a = p.parse_args()

    if a.worker:
        sys.exit(worker(tuple(int(v) for v in a.worker.split("-")), a.trials))

    gpus = [int(g) for g in a.gpus.split(",")]
    print(f"a16w16 compute_bound M={M} N={N} K={K}, {a.procs} procs over {gpus}, "
          f"{a.trials} trials each\n")
    print(f"  {'config':18s} {'bad':>8s}")
    worst = 0
    for c in CONFIGS:
        name = "-".join(str(v) for v in c)
        bad = crash = 0
        for i in range(a.procs):
            env = dict(os.environ, HIP_VISIBLE_DEVICES=str(gpus[i % len(gpus)]))
            r = subprocess.run(
                [sys.executable, os.path.abspath(__file__), "--worker", name,
                 "--trials", str(a.trials)], env=env,
                capture_output=True, text=True)
            if r.returncode == EXIT_MISMATCH:
                bad += 1
            elif r.returncode != EXIT_OK:
                crash += 1
                if crash == 1:
                    print(f"    {name}: worker crashed rc={r.returncode}: "
                          f"{(r.stderr.strip().splitlines() or [''])[-1][:160]}",
                          flush=True)
        worst = max(worst, bad)
        print(f"  {name:18s} {bad:>5d}/{a.procs:<3d}"
              f"{'  (' + str(crash) + ' crashed)' if crash else ''}", flush=True)
    print("\nCLEAN" if worst == 0 else f"\nSTILL FAILING (worst {worst}/{a.procs})")
waitsweep_4537.py
"""Is the TDM wait argument off by one, or does the counter not order at all?

wait0 (every async_wait -> 0) is the only mechanism-specific intervention that
fixed 256-256-64-3-8, but it is also the bluntest: it drains the whole TDM
pipeline.  Sweeping the *slack* tells the two hypotheses apart.

  D=0   control (HEAD~1)                      expect ~9/12 bad
  D=1   async_wait(max(n - 1, 0))             fixes it => the count is off by
                                              one; the real fix is a corrected
                                              argument, and pipelining survives
  D=2   async_wait(max(n - 2, 0))
  D=99  async_wait(0), full drain             ONLY this fixes it => the per-warp
                                              tensorcnt cannot order a cross-warp
                                              LDS read at all, and the fix has to
                                              be a barrier

Also prints the emitted s_wait_tensorcnt argument histogram, so the source-level
change is confirmed to have reached the machine code before any outcome is read.
"""

import os
import shutil
import subprocess
import sys

sys.path.insert(0, "/tmp")
from probe_4537 import (CFG, K, N, SRC, WAIT, body, calls,  # noqa: E402
                        drop_c_barrier, run)


def make(D):
    def t(text):
        h, b, r = body(text)
        out, pos, n = [], 0, 0
        for i, j in calls(b, WAIT):
            arg = b[i + len(WAIT):j - 1]
            out.append(b[pos:i])
            out.append(WAIT + "max((" + arg + ") - " + str(D) + ", 0))")
            pos, n = j, n + 1
        out.append(b[pos:])
        assert n == 6, "expected 6 async_wait sites, patched %d" % n
        return h + "".join(out) + r
    return t


TENS = r"""
import collections, re, torch
from aiter.ops.triton.gemm.basic.gemm_a16w16 import gemm_a16w16
from aiter.ops.triton._gluon_kernels.gfx1250.gemm.basic.gemm_a16w16 import _KERNEL_MAP
x = torch.randn(4096, %(K)d, dtype=torch.bfloat16, device="cuda") * 0.02
w = torch.randn(%(N)d, %(K)d, dtype=torch.bfloat16, device="cuda") * 0.02
gemm_a16w16(x, w, dtype=torch.bfloat16, config=%(cfg)r)
torch.cuda.synchronize()
k = _KERNEL_MAP["compute_bound"]; fn = getattr(k, "fn", k)
c = getattr(fn, "device_caches", None) or getattr(k, "device_caches", {})
for e in c.values():
    d = e[0] if isinstance(e, tuple) else e
    for ck in d.values():
        if "compute_bound" in getattr(ck, "name", "") and "amdgcn" in ck.asm:
            a = ck.asm["amdgcn"]
            h = collections.Counter(re.findall(r"s_wait_tensorcnt (\S+)", a))
            print("TENS", " ".join(f"{a2}:{n2}" for a2, n2 in sorted(h.items())),
                  "| barriers", len(re.findall(r"s_barrier_signal", a)))
"""


def tenscnt():
    r = subprocess.run([sys.executable, "-c", TENS % dict(K=K, N=N, cfg=CFG)],
                       capture_output=True, text=True)
    for ln in r.stdout.split("\n"):
        if ln.startswith("TENS"):
            return ln[5:]
    return "COMPILE-FAIL: " + ((r.stderr.strip().splitlines() or [""])[-1][:90])


if __name__ == "__main__":
    procs, gpus, trials = 12, [0, 1, 2, 3], 20
    orig = open(SRC).read()
    base = drop_c_barrier(orig)
    shutil.copy(SRC, SRC + ".ws.bak")
    print("256-256-64-3-8 compute_bound on HEAD~1, %d procs, %d trials\n"
          % (procs, trials))
    print("  %-6s %7s   emitted s_wait_tensorcnt args" % ("slack", "bad"))
    try:
        for D in (0, 1, 2, 99):
            open(SRC, "w").write(base if D == 0 else make(D)(base))
            t = tenscnt()
            bad = ("n/a" if t.startswith("COMPILE")
                   else "%d/%d" % (run(procs, gpus, trials), procs))
            print("  D=%-4d %7s   %s" % (D, bad, t), flush=True)
    finally:
        shutil.copy(SRC + ".ws.bak", SRC)
        os.remove(SRC + ".ws.bak")
        print("\nsource restored")
kind_4537.py
"""Stale-but-valid tile, or read of never-written LDS?

wait0 and ring-war both take 256-256-64-3-8 from 9/12 to 0/12, so added
serialization fixes it either way and barrier placement cannot say which hazard
it is.  Operand *content* can, with no source modification:

  x=rand w=ones   only the A tiles differ across K  -> sees A-ring staleness
  x=ones w=rand   only the B tiles differ across K  -> sees B-ring staleness
  x=ones w=ones   every LDS slot holds the same bytes for every K tile, so a
                  stale or wrong tile is *invisible*; only a read of LDS that
                  was never written (or written by a DMA still in flight) can
                  still produce a wrong sum, which must be exactly K=3072.

  ones/ones clean + the others bad  => stale-but-valid tile (WAR on slot reuse,
                                       or reading the wrong ring slot)
  ones/ones also bad                => reading LDS the DMA has not filled (RAW)

Runs each operand pattern process-sampled and GPU-crossed on the current tree.

Usage: python kind_4537.py --procs 12 --gpus 0,1,2,3 --trials 20
"""

import argparse
import os
import shutil
import subprocess
import sys

sys.path.insert(0, "/tmp")
from probe_4537 import SRC, drop_c_barrier  # noqa: E402

CFG = dict(BLOCK_M=256, BLOCK_N=256, BLOCK_K=64, NUM_BUFFERS=3, num_warps=8,
           kernel_type="compute_bound")
M, N, K = 16384, 7168, 3072
PATTERNS = ["rand_ones", "ones_rand", "ones_ones"]

EXIT_OK, EXIT_MISMATCH = 0, 2


def worker(pattern, trials):
    import torch

    from aiter.ops.triton.gemm.basic.gemm_a16w16 import gemm_a16w16

    torch.manual_seed(0)
    ones_x, ones_w = pattern.split("_")
    x = (torch.ones(M, K, dtype=torch.bfloat16, device="cuda") if ones_x == "ones"
         else torch.randn(M, K, dtype=torch.bfloat16, device="cuda") * 0.02)
    w = (torch.ones(N, K, dtype=torch.bfloat16, device="cuda") if ones_w == "ones"
         else torch.randn(N, K, dtype=torch.bfloat16, device="cuda") * 0.02)

    if ones_w == "ones" and ones_x == "ones":
        ref = torch.full((1, 1), float(K), device="cuda")
    elif ones_w == "ones":
        ref = x.float().sum(dim=1)[:, None]          # out[m,n] = sum_k x[m,k]
    else:
        ref = w.float().sum(dim=1)[None, :]          # out[m,n] = sum_k w[n,k]
    tol = 2e-2 * ref.abs().max().item()

    worst = 0.0
    for _ in range(trials):
        out = gemm_a16w16(x, w, dtype=torch.bfloat16, config=dict(CFG))
        torch.cuda.synchronize()
        d = (out.float() - ref).abs()
        worst = max(worst, d.max().item())
        if worst > tol:
            print(f"maxerr={worst:.4g} tol={tol:.4g} nbad={int((d > tol).sum())}",
                  file=sys.stderr)
            return EXIT_MISMATCH
    print(f"maxerr={worst:.4g} tol={tol:.4g}", file=sys.stderr)
    return EXIT_OK


if __name__ == "__main__":
    p = argparse.ArgumentParser()
    p.add_argument("--worker", action="store_true")
    p.add_argument("--pattern")
    p.add_argument("--procs", type=int, default=12)
    p.add_argument("--gpus", default="0,1,2,3")
    p.add_argument("--trials", type=int, default=20)
    a = p.parse_args()

    if a.worker:
        sys.exit(worker(a.pattern, a.trials))

    gpus = [int(g) for g in a.gpus.split(",")]
    print(f"256-256-64-3-8 compute_bound on HEAD~1 (placebo C barrier removed), "
          f"{a.procs} procs over {gpus}, {a.trials} trials each\n")
    print(f"  {'operands':12s} {'bad':>8s}   what a failure means")
    MEANING = {
        "rand_ones": "A tiles differ across K -- sees A-ring staleness",
        "ones_rand": "B tiles differ across K -- sees B-ring staleness",
        "ones_ones": "all tiles identical -- ONLY unfilled LDS can show",
    }
    # The shipped gl.barrier() is a codegen placebo that hides the failure, so
    # the discriminator has to run against the kernel without it.
    shutil.copy(SRC, SRC + ".kind.bak")
    try:
        open(SRC, "w").write(drop_c_barrier(open(SRC + ".kind.bak").read()))
        for pat in PATTERNS:
            bad = crash = 0
            for i in range(a.procs):
                env = dict(os.environ, HIP_VISIBLE_DEVICES=str(gpus[i % len(gpus)]))
                r = subprocess.run(
                    [sys.executable, os.path.abspath(__file__), "--worker",
                     "--pattern", pat, "--trials", str(a.trials)],
                    env=env, capture_output=True, text=True)
                if r.returncode == EXIT_MISMATCH:
                    bad += 1
                elif r.returncode != EXIT_OK:
                    crash += 1  # not a numerical failure
            print(f"  {pat:12s} {bad:>5d}/{a.procs:<3d}"
                  f"{'  (' + str(crash) + ' crashed)' if crash else '  '}"
                  f" {MEANING[pat]}", flush=True)
    finally:
        shutil.copy(SRC + ".kind.bak", SRC)
        os.remove(SRC + ".kind.bak")
        print("\nsource restored")
repro_4537_tdm_ring.py
"""Repro for aiter#4537 bug 1: gluon compute_bound GEMM over-fills the TDM ring.

The compute_bound kernel keeps one K-tile in registers (the pre-load stage) on
top of the tiles resident in LDS, but its prologue filled all NUM_BUFFERS LDS
slots.  That leaves zero slack: the async_load issued in iteration i targets the
very slot whose ds_read the workgroup is still draining, and
``load_shared_relaxed`` sets ``ttg.amdg.syncedViaAsyncWait``, which tells
MembarPass no barrier is needed -- so nothing orders the overwrite against the
read.  Filling NUM_BUFFERS-1 slots restores one slot of slack, which is the
convention the bandwidth_bound kernel in the same file already used.

This is a RACE, so a single run proves nothing.  Two things matter:

  * Sample PROCESSES, not trials.  Whether a given process races is decided
    largely at load/JIT time; a process that is going to be wrong tends to be
    wrong on most of its trials, and one that is clean stays clean.  Counting
    trials inside one process therefore ranks variants wrongly.
  * Cross variant with PHYSICAL GPU.  Some devices in a node suppress this
    race entirely, so a config that looks clean may just have drawn a quiet GPU.

Usage (driver spawns the workers itself):

    python repro_4537_tdm_ring.py --procs 8 --gpus 0,1,2,3

Expected, at N=7168 K=3072 M=16384, 8 processes crossed over 4 GPUs:

    config              before    after
    64-64-128-4-4        8/8       0/8
    128-128-128-3-4      6/8       0/8
    128-256-64-5-4       8/8       0/8
    256-256-64-3-4       2/8       0/8
    256-256-64-3-8       0/8       5-6/8   <-- residual, see below

The last row is a known residual documented in the PR: the C staging buffer is
allocated after the operand buffers die, so it aliases them, and the same
syncedViaAsyncWait flag suppresses the WAR barrier before the C store.  It
needs an ordering primitive rather than a depth change.  The tuned config set
shipped in this PR never selects that tile.

``w`` is all ones, so out[m, n] = sum_k x[m, k] -- an exact fp32 reference with
no second GEMM involved.
"""

import argparse
import os
import subprocess
import sys

CONFIGS = {
    # name: BLOCK_M, BLOCK_N, BLOCK_K, NUM_BUFFERS, num_warps
    "64-64-128-4-4": (64, 64, 128, 4, 4),
    "128-128-128-3-4": (128, 128, 128, 3, 4),
    "128-256-64-5-4": (128, 256, 64, 5, 4),
    "256-256-64-3-4": (256, 256, 64, 3, 4),
    "256-256-64-3-8": (256, 256, 64, 3, 8),
}

M, N, K = 16384, 7168, 3072


# Exit codes.  A worker that cannot run at all (no such GPU, bad install) must
# NOT be counted as a numerical failure -- that silently turns "device does not
# exist" into "the race reproduced".
EXIT_OK = 0
EXIT_MISMATCH = 2


def worker(name, trials):
    import torch

    from aiter.ops.triton.gemm.basic.gemm_a16w16 import gemm_a16w16

    bm, bn, bk, nb, nw = CONFIGS[name]
    cfg = dict(
        BLOCK_M=bm, BLOCK_N=bn, BLOCK_K=bk, NUM_BUFFERS=nb, num_warps=nw,
        kernel_type="compute_bound",
    )

    torch.manual_seed(0)
    x = torch.randn(M, K, dtype=torch.bfloat16, device="cuda") * 0.02
    w = torch.ones(N, K, dtype=torch.bfloat16, device="cuda")
    ref = x.float().sum(dim=1)
    tol = 2e-2 * ref.abs().max().item()

    worst = 0.0
    for _ in range(trials):
        out = gemm_a16w16(x, w, dtype=torch.bfloat16, config=dict(cfg))
        torch.cuda.synchronize()
        err = (out.float() - ref[:, None]).abs().max().item()
        worst = max(worst, err)
        if err > tol:
            print(f"    worker pid={os.getpid()} BAD max_abs_err={err:.4f} tol={tol:.4f}")
            return EXIT_MISMATCH
    print(f"    worker pid={os.getpid()} ok   max_abs_err={worst:.4f} tol={tol:.4f}")
    return EXIT_OK


def check_gpus(gpus):
    """Refuse to run against device indices that do not exist.

    Without this, HIP_VISIBLE_DEVICES=<nonexistent> makes every worker die during
    import and the driver reports a flawless 8/8 'race'.
    """
    r = subprocess.run(
        [sys.executable, "-c", "import torch; print(torch.cuda.device_count())"],
        capture_output=True, text=True,
    )
    n = int(r.stdout.strip().splitlines()[-1]) if r.returncode == 0 else 0
    missing = [g for g in gpus if g >= n]
    if missing:
        sys.exit(f"error: GPU index {missing} does not exist ({n} visible). "
                 f"Pass --gpus with indices in 0..{n - 1}.")
    return n


def drive(names, procs, gpus, trials):
    check_gpus(gpus)
    print(f"shape M={M} N={N} K={K}, {procs} processes/config over GPUs {gpus}, "
          f"{trials} trials/process\n")
    rows = []
    for name in names:
        bad = 0
        for i in range(procs):
            env = dict(os.environ, HIP_VISIBLE_DEVICES=str(gpus[i % len(gpus)]))
            r = subprocess.run(
                [sys.executable, os.path.abspath(__file__), "--worker", name,
                 "--trials", str(trials)],
                env=env, capture_output=True, text=True,
            )
            if r.returncode == EXIT_MISMATCH:
                bad += 1
            elif r.returncode != EXIT_OK:
                # Crash, OOM, bad install -- a measurement failure, not a result.
                sys.exit(f"error: worker for {name} exited {r.returncode} without "
                         f"producing a verdict:\n{r.stderr.strip()[-2000:]}")
        rows.append((name, bad))
        print(f"{name:>18s}  bad_processes = {bad}/{procs}")
    print()
    total = sum(b for _, b in rows)
    print("RACE REPRODUCED" if total else "clean on every sampled process")
    return 1 if total else 0


if __name__ == "__main__":
    p = argparse.ArgumentParser()
    p.add_argument("--worker", choices=sorted(CONFIGS), default=None,
                   help="internal: run one sampled process")
    p.add_argument("--config", action="append", choices=sorted(CONFIGS), default=None)
    p.add_argument("--procs", type=int, default=8)
    p.add_argument("--gpus", default="0,1,2,3")
    p.add_argument("--trials", type=int, default=10)
    a = p.parse_args()

    if a.worker:
        sys.exit(worker(a.worker, a.trials))
    names = a.config or list(CONFIGS)
    sys.exit(drive(names, a.procs, [int(g) for g in a.gpus.split(",")], a.trials))
repro_4537_store_2gib.py
"""Repro for aiter#4537 bug 2: gluon a16w16 buffer_store drops C tiles past 2 GiB.

Deterministic, single process, no race, ~1 minute on one gfx1250.

    python repro_4537_store_2gib.py

Why it works without a reference GEMM: ``w`` is all ones, so
``out[m, n] = sum_k x[m, k]`` for every n.  That gives an exact fp32
reference in one reduction, independent of hipBLASLt or any other GEMM.

What you should see before the fix: every element from row
``2**31 // (N * itemsize)`` onward is untouched (still the fill value), because
``gl.amd.gfx1250.buffer_store`` addresses through a 32-bit *byte* offset and
the hardware bounds check silently drops the store.  Nothing raises.

    N=40960, bf16  ->  2**31 / (40960*2) = 26214.4  ->  first bad row 26214

After the fix: 0 bad elements.

The compute_bound variant is unaffected either way -- it stores through a TDM
descriptor, which has a 64-bit base -- so it doubles as an in-script control.
"""

import argparse
import sys

import torch

from aiter.ops.triton.gemm.basic.gemm_a16w16 import gemm_a16w16

# C = 32768 x 40960 x 2 B = 2.50 GiB, i.e. the store crosses 2 GiB inside the
# tensor rather than at its very end, so there are correct rows to compare with.
M, N, K = 32768, 40960, 7168

CONFIGS = {
    # BLOCK_M-BLOCK_N-BLOCK_K-NUM_BUFFERS-num_warps
    "bandwidth_bound": dict(
        BLOCK_M=128, BLOCK_N=128, BLOCK_K=128, NUM_BUFFERS=3, num_warps=4,
        kernel_type="bandwidth_bound",
    ),
    # control: stores through TDM (64-bit base), so it should pass before and after
    "compute_bound": dict(
        BLOCK_M=128, BLOCK_N=128, BLOCK_K=128, NUM_BUFFERS=3, num_warps=4,
        kernel_type="compute_bound",
    ),
}

FILL = float("nan")  # sentinel: a dropped store leaves this behind


def run(name, cfg):
    torch.manual_seed(0)
    x = torch.randn(M, K, dtype=torch.bfloat16, device="cuda") * 0.02
    w = torch.ones(N, K, dtype=torch.bfloat16, device="cuda")
    ref = x.float().sum(dim=1)  # (M,) -- broadcast over n

    y = torch.full((M, N), FILL, dtype=torch.bfloat16, device="cuda")
    gemm_a16w16(x, w, dtype=torch.bfloat16, y=y, config=dict(cfg))
    torch.cuda.synchronize()

    got = y.float()
    tol = 2e-2 * ref.abs().max().item()
    bad = ~((got - ref[:, None]).abs() <= tol)  # NaN counts as bad
    n_bad = int(bad.sum())
    bad_rows = bad.any(dim=1).nonzero()
    first_bad = int(bad_rows[0]) if bad_rows.numel() else -1
    untouched = int(torch.isnan(got).sum())

    limit_row = 2**31 // (N * 2)
    print(
        f"[{name:16s}] bad_elems={n_bad:>12d}  first_bad_row={first_bad:>6d}  "
        f"never_written={untouched:>12d}  (2GiB boundary is row {limit_row})"
    )
    if first_bad >= 0:
        r = first_bad
        c = int(bad[r].nonzero()[0])
        byte_off = (r * N + c) * 2
        print(
            f"{'':18s}  first bad element [{r},{c}] -> byte offset {byte_off} "
            f"(2**31 = {2**31}); got={got[r, c].item():.5f} want={ref[r].item():.5f}"
        )
    del x, w, ref, y, got, bad
    torch.cuda.empty_cache()
    return n_bad


if __name__ == "__main__":
    p = argparse.ArgumentParser()
    p.add_argument("--only", choices=sorted(CONFIGS), default=None)
    a = p.parse_args()

    free, total = torch.cuda.mem_get_info()
    need = (M * K + N * K + M * N) * 2
    print(f"C tile = {M*N*2/2**30:.2f} GiB, needs ~{need/2**30:.1f} GiB device memory "
          f"({free/2**30:.1f} GiB free)")

    names = [a.only] if a.only else list(CONFIGS)
    fails = {n: run(n, CONFIGS[n]) for n in names}

    if fails.get("bandwidth_bound", 0):
        print("\nFAIL: bandwidth_bound dropped stores past 2 GiB (bug 2 present)")
        sys.exit(1)
    print("\nPASS: no dropped stores")

@zejunchen-zejun
zejunchen-zejun force-pushed the xiaobing/gfx1250-gluon-gemm-pipeline-fix branch from 949a00c to 395cff4 Compare August 4, 2026 09:15
@XiaobingSuper
XiaobingSuper marked this pull request as ready for review August 4, 2026 11:07
@XiaobingSuper
XiaobingSuper requested review from a team and a lite review from Copilot August 4, 2026 11:07
XiaobingSuper and others added 2 commits August 4, 2026 11:09
The gluon a16w16 and batched_bf16 kernels pipeline their A and B operand tiles
through an LDS ring fed by gfx1250 TDM, and gate each compute step on
tdm.async_wait(N), which lowers to s_wait_tensorcnt N -- "block until at most N
TDM ops are outstanding". Every wait site passed a count doubled to cover the
two ops (one A, one B) that make up a tile. That is wrong.

A and B are issued from two different tensor descriptors and retire on two
independent in-order streams that share one counter. With T tiles in flight each
stream holds T of its own ops, and "at most N outstanding" only implies the
oldest A *and* the oldest B have landed when N <= T-1: at any larger N one
stream can still hold all T of its ops while the other has drained. Doubling the
count to (T-1)*2 therefore lets a wave read a ring slot the DMA has not filled.

The defect predates this series. 8e40273 only narrowed (NUM_BUFFERS-1)*2 to
(NUM_BUFFERS-2)*2; it did not introduce the doubling, but by dropping the
prologue from NUM_BUFFERS to NUM_BUFFERS-1 tiles it removed the one tile of
slack that had been hiding the hazard, which is why 256-256-64-3-8 started
producing wrong results.

Established by sweeping a slack term D into every wait argument of the
compute_bound kernel and measuring 256-256-64-3-8 at 12 processes x 20 trials
over 4 gfx1250 devices, with the emitted s_wait_tensorcnt arguments read back
from the disassembly to confirm the source change reached the machine code:

    D=0  (emits 0x2)  8/12 processes wrong
    D=1  (emits 0x1)  0/12
    D=2  (emits 0x0)  0/12
    D=99 (emits 0x0)  0/12

Barrier count is 10 in every variant, so nothing was serialized by side effect,
and D=1 retains pipelining. That D=1 suffices refutes fully out-of-order
retirement; that D=0 fails refutes in-order retirement, under which waiting to 2
of 4 outstanding ops would provably have retired the oldest pair. Two in-order
streams keyed by descriptor is the only model consistent with both, and it gives
N <= T-1 counted in tiles.

An operand-content discriminator identifies the hazard as a read of unfilled
LDS rather than a stale-but-valid tile: with both operands all ones every K tile
is byte-identical, so a wrong or stale slot cannot change the result, yet
256-256-64-3-8 still fails 9/12. Both A-only and B-only variants fail, so either
stream can be the one that lags.

Fixed at all wait sites in both kernel variants of both files. Verified at 12
processes x 20 trials over 4 devices:

    a16w16 compute_bound   256-256-64-3-8, 256-256-64-3-4, 64-64-128-4-4,
                           128-128-128-3-4, 128-256-64-5-4, 128-128-64-4-4
                           all 0/12
    batched compute_bound  same shapes plus 256-256-64-4-8, all 0/12,
                           including num_warps=8 which was previously untested
    bandwidth_bound        25 configs x 4 processes x 10 trials, 0 before and
                           after; its wait is corrected on the same argument,
                           not on a reproduced failure

Correctness is not free where the ring is shallow. At NUM_BUFFERS=3 the ring
holds 2 tiles = 4 TDM ops and the correct wait leaves 1 outstanding, which is
nearly a full drain, so a16w16 compute_bound costs +24.6% at 256-256-64-3-8 and
+25.9% at 256-256-64-3-4. At NUM_BUFFERS>=4 it is free: +0.5% at 128-128-64-4-4
and -1.4% at 64-64-128-4-4. bandwidth_bound is unaffected at the depths in the
tuned configs (-0.7% at 256-256-64-3-8, +0.8% at 128-128-64-4-4) and pays the
same shallow-ring cost only at NUM_BUFFERS=2 (+24.2%).

This also replaces the C-staging barrier added in the previous revision of this
branch. That barrier did take 256-256-64-3-8 from 9/12 to 0/12, but the
disassembly shows it emits no s_barrier at all -- the WAR it claimed to close
was already ordered by s_wait_storecnt_dscnt -- so it was suppressing the real
race by perturbing scheduling, not by ordering anything. The dispatcher comment
correction from that commit is kept.

Co-Authored-By: Claude Opus 5 <[email protected]>
All 24 a16w16 shapes Kimi-K3 hits on gfx1250 tp4 were running the untuned
default tile (BLOCK 32/64/64, NUM_BUFFERS 5, num_warps 2, bandwidth_bound).
Tune them over M = 1, 2, 4 ... 32768, which is the range concurrency and input
length actually reach.

Tuned on the kernel this branch ships, i.e. with the three preceding fixes
applied. That matters more than it sounds: an earlier revision of this PR
carried configs ranked against the pre-fix kernel and reported 3.59x over the
default tile. That kernel was not really waiting on its TDM ring, so tiles that
skipped a wait ranked as fast, and the number could not be carried forward.

Re-timed on the shipped kernel, every point in its own process with the three
config sources alternating inside it and the min taken over three rounds:

  source                            total over 384 points
  untuned default tile              440752us
  configs ranked pre-fix            165392us    2.66x vs default
  these configs                     143433us    3.07x vs default

The pre-fix set still works -- it is 2.66x over the default -- but it lost
ground once the wait it had been ranked against became real. Re-tuning recovers
13.3% of that. 3.07x is the honest replacement for the earlier 3.59x.

Selection is deliberately conservative, because a tile holds one speed for a
process's lifetime and draws a different one in the next:

  * six independent tuner runs, one sample each, ranked on the median across
    runs rather than on any single run;
  * ranked on median + spread/2, not the median alone -- a few tiles are
    bimodal and their median can win while their slow mode is worse than the
    default;
  * a candidate must beat the default at *every* M in the bucket, not on
    average.

Where nothing cleared that bar the default tile is kept: 18 of the 384 points,
in 10 buckets before collapsing. An untuned point costs nothing; a regressed one
costs real time in production. There are no points where the default is faster
than what is shipped here.

Every emitted config was then screened for correctness on the shipped kernel --
not on a patched copy -- at the largest M its bucket governs, with one operand
all ones so the expected result is an exact 1-D fp32 sum: no reference GEMM, and
no dependence on hipBLASLt, which was itself off by 5.3e-02 on one of these
shapes. Both operand roles are covered by running the pass twice with the roles
swapped, which matters here because the bug fixed in the preceding commit is a
two-stream wait and a single-pattern screen would exercise one stream.
240/240 bucket entries pass, 3 trials each.

Two of the 24, N=2112 K=7168 and N=12440 K=7168 (the fused KDA in_proj GEMM),
reach the triton path only once they have a routing row in
kimik3_bf16_tuned_gemm.csv. Those rows are #4552; this commit is configs only.

Co-Authored-By: Claude Opus 5 <[email protected]>
@zejunchen-zejun
zejunchen-zejun force-pushed the xiaobing/gfx1250-gluon-gemm-pipeline-fix branch from ed97ad8 to b63a73b Compare August 4, 2026 11:10
Apply Black 26.5.1 formatting to the buffer-store fixes so the repository style check accepts the corrected kernels.

Co-authored-by: Cursor <[email protected]>

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.

🟡 Not ready to approve

The batched gluon compute_bound path this PR fixes is still skipped by existing tests, leaving the main corrected behavior unexercised in CI.

Once you've addressed the issues Copilot identified, you can request another Copilot review.

This review doesn't count toward merge requirements. Sign up for the private preview to control whether Copilot approvals count.

Pull request overview

This PR fixes correctness issues in the gfx1250 Gluon GEMM pipelines (TDM ring wait/prologue semantics and >2 GiB buffer_store addressing) and adds tuned gfx1250 a16w16 configuration JSONs for the Kimi-K3 shape set.

Changes:

  • Fix TDM ring wait counts (tiles vs ops) and adjust compute-bound prologue/loop/epilogue trip counts to avoid overwriting/reading unready LDS tiles.
  • Fix gl.amd.gfx1250.buffer_store addressing for large-C outputs by folding the tile origin into c_ptr (int64) and keeping only tile-local offsets in offs_c.
  • Add tuned gfx1250 a16w16 per-(N,K) config JSONs across the Kimi-K3 shapes.
File summaries
File Description
aiter/ops/triton/gemm/basic/gemm_a16w16.py Updates compute-bound depth/reach commentary to match the adjusted prologue depth model.
aiter/ops/triton/_gluon_kernels/gfx1250/gemm/basic/gemm_a16w16.py Fixes TDM async-wait semantics and large-output buffer_store offseting for the basic a16w16 Gluon kernel.
aiter/ops/triton/_gluon_kernels/gfx1250/gemm/batched/batched_gemm_bf16.py Fixes TDM async-wait semantics, compute-bound pipeline depth/trip counts, and large-output buffer_store offseting for the batched bf16 Gluon kernel.
aiter/ops/triton/configs/gemm/gfx1250-GEMM-A16W16-N=12-K=7168.json Adds tuned per-M bucket config for (N=12,K=7168) on gfx1250.
aiter/ops/triton/configs/gemm/gfx1250-GEMM-A16W16-N=24-K=7168.json Adds tuned per-M bucket config for (N=24,K=7168) on gfx1250.
aiter/ops/triton/configs/gemm/gfx1250-GEMM-A16W16-N=128-K=7168.json Adds tuned per-M bucket config for (N=128,K=7168) on gfx1250.
aiter/ops/triton/configs/gemm/gfx1250-GEMM-A16W16-N=576-K=7168.json Adds tuned per-M bucket config for (N=576,K=7168) on gfx1250.
aiter/ops/triton/configs/gemm/gfx1250-GEMM-A16W16-N=896-K=7168.json Adds tuned per-M bucket config for (N=896,K=7168) on gfx1250.
aiter/ops/triton/configs/gemm/gfx1250-GEMM-A16W16-N=1536-K=128.json Adds tuned per-M bucket config for (N=1536,K=128) on gfx1250.
aiter/ops/triton/configs/gemm/gfx1250-GEMM-A16W16-N=1536-K=7168.json Adds tuned per-M bucket config for (N=1536,K=7168) on gfx1250.
aiter/ops/triton/configs/gemm/gfx1250-GEMM-A16W16-N=2112-K=7168.json Adds tuned per-M bucket config for (N=2112,K=7168) on gfx1250.
aiter/ops/triton/configs/gemm/gfx1250-GEMM-A16W16-N=2304-K=1536.json Adds tuned per-M bucket config for (N=2304,K=1536) on gfx1250.
aiter/ops/triton/configs/gemm/gfx1250-GEMM-A16W16-N=3072-K=128.json Adds tuned per-M bucket config for (N=3072,K=128) on gfx1250.
aiter/ops/triton/configs/gemm/gfx1250-GEMM-A16W16-N=3072-K=512.json Adds tuned per-M bucket config for (N=3072,K=512) on gfx1250.
aiter/ops/triton/configs/gemm/gfx1250-GEMM-A16W16-N=3072-K=7168.json Adds tuned per-M bucket config for (N=3072,K=7168) on gfx1250.
aiter/ops/triton/configs/gemm/gfx1250-GEMM-A16W16-N=4608-K=1536.json Adds tuned per-M bucket config for (N=4608,K=1536) on gfx1250.
aiter/ops/triton/configs/gemm/gfx1250-GEMM-A16W16-N=6144-K=512.json Adds tuned per-M bucket config for (N=6144,K=512) on gfx1250.
aiter/ops/triton/configs/gemm/gfx1250-GEMM-A16W16-N=7168-K=768.json Adds tuned per-M bucket config for (N=7168,K=768) on gfx1250.
aiter/ops/triton/configs/gemm/gfx1250-GEMM-A16W16-N=7168-K=1536.json Adds tuned per-M bucket config for (N=7168,K=1536) on gfx1250.
aiter/ops/triton/configs/gemm/gfx1250-GEMM-A16W16-N=7168-K=3072.json Adds tuned per-M bucket config for (N=7168,K=3072) on gfx1250.
aiter/ops/triton/configs/gemm/gfx1250-GEMM-A16W16-N=7168-K=4224.json Adds tuned per-M bucket config for (N=7168,K=4224) on gfx1250.
aiter/ops/triton/configs/gemm/gfx1250-GEMM-A16W16-N=7168-K=8448.json Adds tuned per-M bucket config for (N=7168,K=8448) on gfx1250.
aiter/ops/triton/configs/gemm/gfx1250-GEMM-A16W16-N=8448-K=7168.json Adds tuned per-M bucket config for (N=8448,K=7168) on gfx1250.
aiter/ops/triton/configs/gemm/gfx1250-GEMM-A16W16-N=12440-K=7168.json Adds tuned per-M bucket config for (N=12440,K=7168) on gfx1250.
aiter/ops/triton/configs/gemm/gfx1250-GEMM-A16W16-N=16896-K=7168.json Adds tuned per-M bucket config for (N=16896,K=7168) on gfx1250.
aiter/ops/triton/configs/gemm/gfx1250-GEMM-A16W16-N=20480-K=7168.json Adds tuned per-M bucket config for (N=20480,K=7168) on gfx1250.
aiter/ops/triton/configs/gemm/gfx1250-GEMM-A16W16-N=40960-K=7168.json Adds tuned per-M bucket config for (N=40960,K=7168) on gfx1250.
Review details
  • Files reviewed: 27/27 changed files
  • Comments generated: 2
  • Review effort level: Lite

We're testing this review assessment. Please use 👍 or 👎 to tell us if it's correct.

Comment on lines 515 to 517
# TDM prologue: fill the pipeline
for _ in gl.static_range(NUM_BUFFERS):
for _ in gl.static_range(NUM_BUFFERS - 1):
gl.amd.gfx1250.tdm.async_load(
Comment on lines +388 to +394
# buffer_store addresses through a 32-bit byte offset, so a C tile starting
# past 2 GiB is dropped by the bounds check with nothing raised. Fold the
# origin into the base pointer in 64-bit and keep only tile-local offsets,
# which the block shape bounds, so the fast path holds at every size.
c_ptr += (pid_m * BLOCK_M).to(gl.int64) * stride_cm + (
pid_n * BLOCK_N
).to(gl.int64) * stride_cn
zejunchen-zejun pushed a commit that referenced this pull request Aug 4, 2026
get_GEMM_A16W16_config falls back to torch when the shape has no row, and
two of the shapes Kimi-K3 hits on gfx1250 tp4 have none: N=12440 K=7168 (the
fused KDA in_proj, what ATOM's _fuse_in_proj builds by concatenating
in_proj + b_proj + f_a_proj) and N=2112 K=7168. The CSV is tuned for the
unfused 12/24/128 x 7168 shapes, so the fused N is a miss rather than a
deliberate torch routing. It is the only untuned bf16 shape in the run:
hipBLASLt picks Cijk_..._MT32x16x32_MI16x16x1 at 5.3ms/layer for M=2048, and
69 KDA layers make that 367ms of a 1060ms prefill.

The row set is drawn from measurement rather than extended to the ends of the
ladder. Each point runs in its own process, triton and F.linear alternate
inside it, min over three rounds, and triton runs the config
_get_triton_config loads -- no explicit override -- so this measures what the
row will actually get once the tuned configs of #4537 are installed. A row is
kept only where triton wins by more than 2%: an unrouted shape costs nothing,
a mis-routed one costs real time.

  N=2112 K=7168                        N=12440 K=7168
    M      blas  triton         M       blas   triton
    1     60.80   79.05  0.77x  1      65.25    77.41  0.84x
    2     59.70   78.75  0.76x  2      66.91    76.52  0.87x
    4     59.97   77.31  0.78x  4      67.60    78.31  0.86x
    8     60.06   79.03  0.76x  8      68.87    74.76  0.92x
   16     61.35   77.21  0.79x  16     70.61    75.20  0.94x
   32     62.24   78.90  0.79x  32     79.12    79.77  0.99x
   64     64.35   78.41  0.82x  64     99.29    81.38  1.22x
  128     65.42   81.10  0.81x  128   350.13    85.01  4.12x
  256     71.56   81.21  0.88x  256   648.46    86.24  7.52x
  512    224.67   81.43  2.76x  512  1307.23   150.59  8.68x
 1024    409.96   85.93  4.77x  1024 2467.74   211.16 11.69x
 2048    609.94   84.62  7.21x  2048 5121.83   395.77 12.94x
 4096    969.13  194.53  4.98x  4096 10146.32  748.60 13.55x
 8192   1683.93  322.25  5.23x  8192 21037.98 1451.01 14.50x
16384   4350.58  657.50  6.62x  16384 40454.79 2751.31 14.70x

So 15 rows: N=2112 from M=512, N=12440 from M=64. The 15 points below those
crossovers keep going to hipBLASLt, which is the faster backend there. An
earlier revision of this branch routed N=12440 across the whole ladder; the
small-M half of that was extrapolated from a microbench on the untuned triton
path and is retracted here.

End to end, dummy weights (--load_dummy xavier), tp4, --max-num-seqs 8
--max-num-batched-tokens 2048, A/B by prepending an extra CSV through
AITER_CONFIG_GEMM_BF16=<default>:<model_configs/*>:<extra.csv> -- editing the
regenerated merge under /tmp/aiter_configs/*.csv does nothing, the colon list
is the only way to A/B this cleanly:

                torch/hipBLASLt   triton
  TTFT              810ms          611ms   -24.7%
  prefill      2526 tok/s     3352 tok/s
  TPOT             41.9ms         39.9ms
  output      130.7 tok/s     142.4 tok/s

That run carried routing rows for N=12440 at M >= 48 only, so it covers the
large-M side of this change and not the N=2112 rows, which rest on the table
above.

Tuned configs for both shapes are in #4537. Neither PR blocks the other: the
JSONs there sit unused for these two shapes until these rows exist, and these
rows without #4537 route to the default tile, which is the configuration the
-24.7% above was measured in.

Tested on gfx1250, 256 CU, SPX, 4 GPUs.

Co-Authored-By: Claude Opus 5 <[email protected]>
@XiaobingSuper XiaobingSuper changed the title [gfx1250] Fix two gluon GEMM pipeline bugs and tune the Kimi-K3 a16w16 shapes [gfx1250] Fix three gluon GEMM correctness bugs and tune the Kimi-K3 a16w16 shapes Aug 4, 2026
XiaobingSuper added a commit that referenced this pull request Aug 5, 2026
* [gfx1250] Route the two unrouted Kimi-K3 bf16 GEMM shapes to triton

get_GEMM_A16W16_config falls back to torch when the shape has no row, and
two of the shapes Kimi-K3 hits on gfx1250 tp4 have none: N=12440 K=7168 (the
fused KDA in_proj, what ATOM's _fuse_in_proj builds by concatenating
in_proj + b_proj + f_a_proj) and N=2112 K=7168. The CSV is tuned for the
unfused 12/24/128 x 7168 shapes, so the fused N is a miss rather than a
deliberate torch routing. It is the only untuned bf16 shape in the run:
hipBLASLt picks Cijk_..._MT32x16x32_MI16x16x1 at 5.3ms/layer for M=2048, and
69 KDA layers make that 367ms of a 1060ms prefill.

The row set is drawn from measurement rather than extended to the ends of the
ladder. Each point runs in its own process, triton and F.linear alternate
inside it, min over three rounds, and triton runs the config
_get_triton_config loads -- no explicit override -- so this measures what the
row will actually get once the tuned configs of #4537 are installed. A row is
kept only where triton wins by more than 2%: an unrouted shape costs nothing,
a mis-routed one costs real time.

  N=2112 K=7168                        N=12440 K=7168
    M      blas  triton         M       blas   triton
    1     60.80   79.05  0.77x  1      65.25    77.41  0.84x
    2     59.70   78.75  0.76x  2      66.91    76.52  0.87x
    4     59.97   77.31  0.78x  4      67.60    78.31  0.86x
    8     60.06   79.03  0.76x  8      68.87    74.76  0.92x
   16     61.35   77.21  0.79x  16     70.61    75.20  0.94x
   32     62.24   78.90  0.79x  32     79.12    79.77  0.99x
   64     64.35   78.41  0.82x  64     99.29    81.38  1.22x
  128     65.42   81.10  0.81x  128   350.13    85.01  4.12x
  256     71.56   81.21  0.88x  256   648.46    86.24  7.52x
  512    224.67   81.43  2.76x  512  1307.23   150.59  8.68x
 1024    409.96   85.93  4.77x  1024 2467.74   211.16 11.69x
 2048    609.94   84.62  7.21x  2048 5121.83   395.77 12.94x
 4096    969.13  194.53  4.98x  4096 10146.32  748.60 13.55x
 8192   1683.93  322.25  5.23x  8192 21037.98 1451.01 14.50x
16384   4350.58  657.50  6.62x  16384 40454.79 2751.31 14.70x

So 15 rows: N=2112 from M=512, N=12440 from M=64. The 15 points below those
crossovers keep going to hipBLASLt, which is the faster backend there. An
earlier revision of this branch routed N=12440 across the whole ladder; the
small-M half of that was extrapolated from a microbench on the untuned triton
path and is retracted here.

End to end, dummy weights (--load_dummy xavier), tp4, --max-num-seqs 8
--max-num-batched-tokens 2048, A/B by prepending an extra CSV through
AITER_CONFIG_GEMM_BF16=<default>:<model_configs/*>:<extra.csv> -- editing the
regenerated merge under /tmp/aiter_configs/*.csv does nothing, the colon list
is the only way to A/B this cleanly:

                torch/hipBLASLt   triton
  TTFT              810ms          611ms   -24.7%
  prefill      2526 tok/s     3352 tok/s
  TPOT             41.9ms         39.9ms
  output      130.7 tok/s     142.4 tok/s

That run carried routing rows for N=12440 at M >= 48 only, so it covers the
large-M side of this change and not the N=2112 rows, which rest on the table
above.

Tuned configs for both shapes are in #4537. Neither PR blocks the other: the
JSONs there sit unused for these two shapes until these rows exist, and these
rows without #4537 route to the default tile, which is the configuration the
-24.7% above was measured in.

Tested on gfx1250, 256 CU, SPX, 4 GPUs.

Co-Authored-By: Claude Opus 5 <[email protected]>

* [gfx1250] Restore the full fused KDA routing range

Keep N=2112 on its existing global route to avoid duplicate merge keys, and include the requested small-M N=12440 entries.

Co-authored-by: Cursor <[email protected]>

---------

Co-authored-by: Claude Opus 5 <[email protected]>
Co-authored-by: Cursor <[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.

2 participants