Skip to content

gemm_a2a: fuse a column-sharded all-to-all into the fp8 GEMM epilogue - #695

Merged
yangyuhuiling merged 27 commits into
mainfrom
xiangch/gemm-a2a-flydsl
Nov 2, 2026
Merged

yangyuhuiling merged 27 commits into
mainfrom
xiangch/gemm-a2a-flydsl

Conversation

@yangyuhuiling

@yangyuhuiling yangyuhuiling commented Sep 22, 2026 •

Copy link
Copy Markdown
Contributor

Adds mori.ops.gemm_a2a: the column-sharded all-to-all fused into the epilogue
of mori's 8-wave fp8 GEMM, organised like gemm_ar (#662) and reusing its GEMM,
_compat and _shuffle rather than copying them.

Each rank computes the whole C = A @ B.T and sends column block j to rank
j; rank d ends up with a compact [world*M, shard_n]. The shape this is
aimed at is a QKV projection under Ulysses sequence parallelism, so M = S/P
and sweeping M is sweeping the sequence length.

Modes gemm-only, split-sdma, split-rccl and fused-sdma (plus the
gemm-staging / gemm-to-window controls). split-sdma, split-rccl and
fused-sdma share a GEMM byte for byte, so the differences between them are
transport and nothing else. All modes agree at fp8's own floor, 1.66e-3. The
transport is SDMA only: the two LSA transports were measured and removed (below).

Fusing wins in every cell measured, on both model shapes and at four
sequence lengths, against both split-sdma and RCCL. Fused-sdma vs
split-sdma, ptpc, one 8x MI355X node, 3 interleaved rounds (2026-10-28):

S=16k 32k 64k 128k
70B ptpc 16.6% 25.5% 28.8% 29.7%
405B ptpc 16.6% 17.9% 18.5% 21.6%
70B mxfp8 18.3% 20.6% 24.4% 23.6%
405B mxfp8 11.2% 11.9% 16.1% 17.6%

ptpc uses 256x256 whenever that gives at least two waves of tiles and
128x256 below that (only 70B at S=16k here), via layout.default_block_m. The
earlier 128x256 default came from gemm_ar's blockscale path and has no spill
reason under ptpc; 256x256 makes the fused path 6-35% faster at every cell
except 70B S=16k, where 128x256 is 3% faster. mxfp8 is always 256x256 and, at
the same tile, its GEMM is 13-22% slower than ptpc's (the scale loads stall the
tile prefetch; #857 fixes that for gemm_ar only).

Against aiter #6689 on its own target, MiniMax-M3's QKV under Ulysses SP4
(P=4, K=6144; dense N=9216 and indexer N=10240), same node and day, three
interleaved rounds, aiter at the better of the two configs its tuning profile
lists per shape:

aiter mori default mori best arm
dense M=2048 245.4 243.2 (-0.9%) 232.1 (-5.4%)
dense M=4096 439.7 431.6 (-1.8%) 404.2 (-8.1%)
dense M=8192 772.1 751.2 (-2.7%) 746.4 (-3.3%)
indexer M=2048 283.6 259.6 (-8.5%) 249.4 (-12.1%)
indexer M=4096 468.3 467.8 (-0.1%) 440.0 (-6.0%)
indexer M=8192 871.9 824.5 (-5.4%) 815.4 (-6.5%)

(us.) mori is ahead in every cell, although on the indexer case it computes IK
once per destination (+3.9% GEMM) where aiter computes it once. The best arm
is 128x256 at every M, and at M=2048 4 chunks rather than the default 8: both
default rules were fitted at P=8 and leave 1-7% on the table at P=4 (see
below) — noted in the doc, not changed here.

python/mori/ops/gemm_a2a/README.md has the full tables, the tile table, the
conditions and what is not measured.

Validated on FlyDSL 0.4.0 after the review fixes and the LSA removal:
test_gemm_a2a.py and test_gemm_a2a_op.py 48 passed on 8x MI355X, and every
remaining bench mode -- including --staging-store copy, mxfp8, --no-put and
--timeline -- validated every received slab at relL2 1.66e-3.

Worth a reviewer's attention

  • n % (world_size * block_n) != 0 is rejected, not just n % world_size.
    A destination's column run has to be a whole number of GEMM tiles or a tile
    straddles two destinations and its store cannot stay contiguous. This rules
    out Qwen3-235B at P=8 — which has fewer KV heads than ranks, so Ulysses would
    have to replicate KV there anyway; the layout rule is that condition showing
    up in the kernel.
  • LSA lost to SDMA here and was removed, unlike in the gcnasm experiment
    this follows. split-lsa (a copy kernel storing into the peers) reached ~60%
    of the 76.8 GB/s line rate where the copy engines reach ~75%, and fused-lsa
    (the epilogue storing into them) was the slowest mode at both shapes. Ruled
    out as causes: grid size, cache policy, local bandwidth and the read layout --
    the README keeps the ablations. Small M, where a copy engine's per-put cost
    dominates, was not measured; the removed kernels are in this branch's history.
  • The benchmark validates the received buffer per source rank. That is what
    caught both real bugs in this branch — a stranded self-slab, and a missing
    opsel_b_per_tile that looked like a transport failure until the per-source
    numbers showed local and remote equally wrong.
  • Two benchmark-side knobs, for finding where the tail goes rather than
    for production: --chunk-plan gives uneven chunks (row tiles
    per chunk, e.g. 16,…,8,4,4), and --timeline compiles s_memrealtime
    stamps into the fused epilogue and the drain kernel (off by default; on, it
    costs ~3%). The timeline is what showed the 405B tail is the last wave's
    chunk on the wire plus rank-to-rank GEMM skew, not the PUT path.
  • fence on compile_fused_gemm_a2a is gone, as gemm_ar: drop the fused epilogue's fence knob, which nothing selects #691 did for gemm_ar:
    nothing selected anything but the default.

Measurement protocol

The numbers above come from sweep_inproc.py: every case of a table in one
process on one communicator, CUDA graph replayed back to back with an event
between launches for at least 3-8 s, median launch gap, max over ranks;
rounds interleaved rather than grouped, on an otherwise idle node. Spread is
0.0-3.3% (ptpc) and 0.0-2.3% (mxfp8), and every sample validated. One process
per sweep also keeps the GPUs busy throughout, which the cluster's idle-GPU
reaper otherwise reads as idle. Interleaving is not ceremony — a neighbour on the box is worth 9% on a pure
GEMM
and changes the ranking, so a contaminated table cannot be rescued by
scaling it. One cell measured 5153us four times running and 3508us four times
running with a byte-identical kernel before this was in place.

GemmA2AOp and recv reuse

GemmA2AOp(comm, n=, k=, m_max=, quant="ptpc"|"mxfp8", mode="fused"|"split")
is the public wrapper: it owns the window, picks the tile and the chunk count per
M, serves several M on one instance, captures in CUDA graphs, and has
self_test() for a build whose puts move nothing.

The chunk count is a heuristic, not a tuned table: the largest count <= 8 that
divides the row tiles and keeps each put >= 1 MiB. Only c4 and c8 were
measured on the model cells. There it picks the faster of the two in 7 of 8
ptpc cells and 6 of 8 mxfp8 cells, and the misses are 0.5-1.4% (70B M=8192
ptpc; 70B M=4096/8192 mxfp8, where c4 wins). At P=4 it is further off:
MiniMax-M3's 2304-column shard reaches 1 MiB at ~228 rows, so the rule always
lands on 8, while c4 is 4.6% faster at M=2048 and, at the 256x256 tile, 2.7%
faster at M=4096. c2, c16 and uneven plans were not swept on these cells.
A rule that accounts for world size (or for rows per chunk rather than bytes)
is left for a follow-up.

The end-of-call barrier only says every rank has written the previous call. A
peer could pass it, start the next call and push into a recv its owner is still
reading. Each call now posts a credit (the window's call counter) to every peer
at its start, and a push to a peer waits for that peer's credit; starting a
call means the stream has finished whatever read the previous result. So the
result is safe to read as long as the reader is ordered before this rank's
next call
-- the one contract the op documents. On and off measured within
+-1% (no consistent sign) over three shapes.

test_gemm_a2a_op.py provokes the race: rank 0 reads call 1's result 50 ms
late while its peers run call 2. With the credit the read is intact in both
modes; with it switched off it is corrupted -- the negative control that shows
the race is real. Both files run in CI in their own step.

Not in this PR

--quant blockscale, fp8 on the wire, partial-N scatter, the reverse operator
(draft in #868), an LSA transport for small M, and a world-size-aware default
tile/chunk rule (review item 9).

🤖 Generated with Claude Code

yangyuhuiling and others added 13 commits September 22, 2026 02:28
…ffers

First piece of a FlyDSL GEMM + all-to-all, built like mori.ops.gemm_ar and on
the same fp8 GEMM. Every rank computes the whole [M,N] and sends column block
j to rank j, which lands it at rows [my_rank*M, (my_rank+1)*M) of a compact
[world*M, shard_n] receive buffer.

Layout only here -- pure arithmetic, no GPU, no kernels yet.

The interesting part is the dimension that gets sharded. ArConfig's docstring
warns that sharding along n "would make each slice m separate n/world*2-byte
pieces, which is fatal for SDMA", and this operation shards along n. Two things
answer it:

  * the receiver layout is compact, so a source's contribution is one
    contiguous range on arrival; and
  * the sender stages [dst][M][shard_n] instead of [M][N], which costs nothing
    because the GEMM epilogue computes a store address either way.

Staging is opt-in (`staged=`) because only the SDMA paths need it -- a copy
engine cannot gather -- and it is a second copy of the payload, 75 MiB per rank
at the model shape. The LSA paths store into the peer window directly.

One new shape rule, and it is not the obvious one: n must be a multiple of
world_size*block_n, not just of world_size. At world=8 n=2304 each destination
gets 288 columns, which is not a whole 256-wide GEMM tile, so a tile would
straddle two destinations and its store could not stay contiguous -- the exact
thing the compact receive layout exists to avoid. There is a test for that
shape specifically.

Carried over from gemm_ar deliberately: capacity_m pinning (so two m values
sharing a window cannot alias each other's regions), disjoint counter sets per
shape (the election residue problem), and the submit lock per destination.
Their rationale is in the field comments; the bugs they prevent were expensive.

27 host-only tests. The multi-rank half of the file is the spawn helper only
for now, and it has the settle-and-retry for anvil.cpp from the start -- PR
#685 exists because gemm_ar's equivalent was written without it.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
… output

The split baseline. The GEMM has written the whole [M,N] result; this moves
column block d into rank d's recv slot for this rank, over LSA.

Source and destination disagree about what is contiguous -- the read is M runs
of shard_n at row stride N, the write is one run of M*shard_n -- so the kernel
walks the *write* side's order, which is the compact one, and derives the read
address from it. That puts the contiguity on the side that crosses xGMI. The
div/mod are by a build-time constant, so they are a multiply-shift, not real
division.

gcnasm's opus_lsa_a2a_copy_kernel reads a pre-staged contiguous slab instead,
because its GEMM already wrote [dst][M][shard_n]. Doing the re-layout here is
what lets this path reuse a completely unmodified GEMM, which is the point of
having a split baseline at all -- if the baseline needed its own GEMM it would
not be measuring the same thing as the fused path.

The source is a pointer argument, not a window region: only the destination has
to be symmetric, and reserving another M*N*2 (75 MiB at the model shape) of
registered window for a buffer no peer ever reads would be waste. `src=` also
accepts "staging" for the pre-compacted layout, which is the slab the SDMA path
will need -- one kernel for both rather than two that drift.

Ends with gemm_ar's monotonic-flag barrier: signal every peer, spin on every
peer, flags never reset so graph replay is safe.

_compat's buffer primitives are imported from gemm_ar rather than copied.
_spin_until is not: it is nine lines, and importing a private helper out of the
all-reduce to save them would tie this file's correctness to refactors of an
unrelated one. That trade is stated at the definition.

Compiles at the model shape (world 8, M=2048 N=18432, shard_n=2304).

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
gemm-only and split-lsa, validated at 8 ranks on the shape gcnasm's
opus_gemm_a2a_lsa reports on (M=2048 N=18432 K=8192, shard_n=2304):

    gemm-only   329.4us   relL2 1.66e-3
    split-lsa   956.8us   relL2 1.66e-3

1.66e-3 is fp8's own floor at these operands, and the split number is measured
against what *arrived*: _validate_recv rebuilds each of the eight source ranks'
operands and checks that source's row block of recv. Checking this rank's own
contribution would pass with the transport doing nothing at all, which is the
shape of the BUILD_CCO_SDMA trap that cost a day on gemm_ar.

B is seeded identically on every rank and A is not. That is the one structural
difference from bench_gemm_ar and it is load-bearing: there each rank holds a
different K-shard and the collective sums them; here each rank computes the same
function of different rows and the collective only moves bytes. Seeding B
per-rank would still validate on every rank, against its own wrong reference.

compile_gemm_local is gemm_ar's compile_fused_gemm_scatter with fuse=False,
which compiles its whole epilogue tail out and leaves the unmodified 8-wave
GEMM. Reusing it rather than re-deriving is deliberate: gemm-only here and
gemm-only there have to be the same kernel or neither number means anything
beside the other. The ArConfig it needs is a documented placeholder -- with
fuse=False nothing survives that reads an offset from it.

kernels_fused.py otherwise only carries the note on how the two fused
destinations will work. Writing it down now because finding it is what decided
the file's size: _PermlaneStoreC._emit already computes its own flat index and
already takes the scales as separate arguments, so constructing the store with
c_cols=shard_n and passing a destination-local base column turns that one line
into the a2a address, with the bounds test and the oob sentinel both landing
correctly. A five-line override, not a 1500-line copy.

split-sdma, fused-lsa and fused-sdma report "not implemented yet" rather than
silently doing something else.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The GEMM stores each tile straight into the owning destination's window
instead of into a local [M,N] that a second kernel then reads and scatters.
Validated at 8 ranks on the model shape (M=2048 N=18432 K=8192, shard_n=2304):
relL2 0.0016595761784107884, *bit-identical* to split-lsa's, which is the
check that matters -- the fused epilogue produces the same bytes, not merely
similar ones.

The address map is the five-line override the previous commit predicted:
_PermlaneStoreC._emit already computes its own flat index and store() already
passes the scales separately, so constructing with c_cols=shard_n and handing
_emit a destination-local base column gives row*shard_n + local_col, with the
bounds test and the oob sentinel both landing right. elem_base is 0 here,
unlike gemm_ar's peer store, because the descriptor *is* the slab.

Two things that were not predicted:

  * StoreC sizes the B-scale descriptor from the same c_cols. Shrinking c_cols
    to shard_n silently clamps every per-channel scale past column shard_n to
    zero. The descriptor is rebuilt at the global width in __init__. Only ptpc
    reads it -- blockscale takes N explicitly and switches the epilogue's own
    loads off -- so this would have shipped looking fine on the quantisation
    the model runs and been wrong on the other.

  * The barrier kernel hit "Cannot extract IR values from CachedWindow", which
    is the trap CachedWindow's own docstring warns about: three MLIR values
    cannot be an scf.if's captured state. build_lsa_a2a avoided it by accident
    (it calls a closure), and the fix is to do the same deliberately. The
    comment at the helper says why it is a closure, so the next person does not
    inline it back.

fused-lsa needs no collective kernel but does need the agreement that peers
have *finished*, so build_lsa_barrier is that protocol on its own. The
producer's release stays in the GEMM: this kernel is one block, so its fence
reaches one XCD's L2 out of eight, and the rest would keep peer-homed lines
dirty while its system-scope atomic overtook them. gemm_ar learned that one the
hard way.

No timings recorded in this commit. The box has another tenant (9 GB on GPU 1),
and the same configuration measured 635.5us and 787.6us on two runs -- 24%
apart, which is wider than anything this change could be worth. Numbers when
the box is idle.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
split-sdma and fused-sdma. Both validate at 8 ranks on the model shape with
relL2 0.0016595761784107884 -- the same value the LSA modes and the split
baseline produce, so all five paths write identical bytes.

kernels_sdma is much smaller than gemm_ar's because there is no reduce and no
gather: one put per destination, drain, barrier. Both offsets are constants --
the destination offset is the same in every peer's window, which is what
indexing recv by source rather than destination buys. scatter and drain come
from one builder so the two cannot disagree about the queue map or the barrier
slots.

The GEMM gained transport="sdma": same store class, same index math, only the
base address differs. LSA writes the destination's slab in the destination's
window; SDMA writes the identically-shaped slab in this rank's staging, which
the copy engine then pushes. fuse=False gives the staging GEMM for the split
path, so the two SDMA modes differ in exactly one thing.

**The bug worth recording.** First run gave relL2 exactly 1.0 on both modes --
recv entirely wrong. Per-source reporting showed why:

    [rank 0] per-source relL2: 0*=1.00e+00 1=1.65e-03

Every *remote* slab arrived perfectly; only the rank's own was missing. The put
loop skips self -- a copy engine round trip to our own memory is pure cost --
so a self-destination tile written to staging is stranded there forever. The
fix is for the GEMM to store those tiles straight into its own recv slot, which
costs nothing since the tile already knows its destination.

What makes this one worth a paragraph is how it fails: the transport is
correct, every peer's data is correct, and seven eighths of the answer is
right. A check that sampled a remote slab, or that took a mean rather than a
max, would have passed it. The per-source line in _validate_recv is kept for
the same reason -- "everything is missing" and "only mine is missing" both
report 1.0 from the maximum and are entirely different bugs.

Timings are recorded in the log for orientation only (split-sdma 628.3us,
fused-sdma chunks=8 540.9us at 8 ranks) and are NOT a result: the box has
another tenant, and back-to-back launches still lose the anvil.cpp queue race
often enough that a sweep cannot complete. Measurement when it is idle.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
… has LSA

8x MI355X, M=2048 N=18432 K=8192 (gcnasm's 8-rank full-N shape), ptpc, graph
replay, median of 21 after 8 warmups, three independent launches per cell:

    gemm-only                      325.0us
    split-lsa                      952.4      comm 627.4
    split-sdma                     630.3      comm 305.3
    fused-lsa  (no rotation)       618.2      comm 293.2
    fused-sdma --chunks 4          522.3      comm 197.3   <- best

fused-sdma --chunks 4 is 45.2% under split-lsa and 17.1% under its own split
baseline; on the comm half alone, 305.3 -> 197.3us, -35.4%.

Spread between the three launches is 0.2-2.0% on every cell but one. The
earlier attempt on a shared box had the same configuration at 635.5 and 787.6us
-- 24% apart -- and those runs were discarded rather than averaged in. The box
was checked idle with rocm-smi --showpids first.

Three things the table says that are worth the reading:

**SDMA beats LSA on both halves, which is the opposite of gcnasm's result.**
Not a contradiction: its experiment is bf16 and this is fp8, so the GEMM is
about twice as fast and compute/comm is half. LSA wants compute to hide
CU-issued stores behind; SDMA wants the copy engines' independence. Halving the
compute moves the shape across that line -- the same mechanism gemm_ar recorded
at 0.22 against gcnasm's 2.8. The ratio decides, not the transport.

**Chunking is the whole of the fused-SDMA win.** At chunks=1 the fused path is
622.0us against split-sdma's 630.3, i.e. nothing: one put per destination
cannot start until that destination's last tile lands, which is near the end of
the GEMM either way. 2 and 4 are worth 100us. Past 4 it reverses -- at 16 each
put is 576 KiB, under the SDMA bandwidth knee.

**Destination rotation does not pay at this M.** fused-lsa is fastest with it
off. gcnasm measured it worth 17-27% but for M >= 8192; this is M = 2048, with
16 row tiles for a rotation to spread. The knob stays because the effect is
shape-dependent by construction, not because this shape wants it.

The sweep driver moves into the repo alongside the benchmark: back-to-back
launches lose the anvil.cpp queue race often enough that a bare loop over the
table cannot finish, so it settles between launches and retries a lost race
rather than recording it. Three cells in an earlier hand-run loop came back
"CRASHED" for exactly that reason and none of them were a defect.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The split-LSA copy kernel had its loop nesting backwards: destination outer,
pack index inner, so a thread finished destination 0's whole slab before
touching 1's and was therefore never driving more than one xGMI link. Swapping
them -- pack outer, all `world` destinations unrolled inner, every load issued
before any store -- takes it from 952.4us to 533.8us at the model shape, 44%
off, with relL2 unchanged to every digit.

gemm_ar's all-gather has this exact warning at its own loop:

    Issue every load before any store so the 8 links overlap; a load/store pair
    per peer would serialise on each s_waitcnt.

I read that comment, built on the file it is in, and wrote the other nesting
anyway.

The tell was in the numbers and I did not chase it: per link, split-lsa ran at
15.0 GB/s while fused-lsa -- *the same transport* -- ran at 32.2. A transport
being half as fast as itself is not a property of the transport.

Grid size turns out to be nearly irrelevant once the nesting is right: 24, 48
and 80 blocks land within 0.6% of each other. Before the fix the same sweep
spanned 1066 -> 923us, which is what a too-small grid looks like when each
thread is also stalling on a dependent load -- the parallelism was covering for
the dependency, not the other way round. LSA_BLOCK_CAP's comment says the
borrowed value "has to be measured on this one before it means anything"; it
now has been, and it does not matter here.

--copy-blocks is added to the benchmark so the sweep above is reproducible.

This invalidates the headline conclusions in MORI-GEMM-A2A-BENCHMARK.md, which
compared everything against an artificially slow split-lsa. The full table is
being re-measured; the document is corrected in the next commit rather than
left standing.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…race

The copy kernel stored to peer-homed memory with CM_CACHED and then published
arrival with a system-scope atomic, with no fence between them. A cached store
leaves the line dirty in whichever XCD's L2 the block ran on, and the atomic can
overtake it -- gemm_ar hit exactly this and its note sits at the equivalent
store. Validation passing until now was luck, not a guarantee; the window for it
is a peer reading its slab between our atomic and our writeback.

sc0|sc1 skips L1 and L2 entirely. The reason gemm_ar could not always use it is
that a 2-byte partial-line write over the fabric loses updates; this kernel
stores 16 bytes per lane and 1024 contiguous bytes per wave, so that does not
apply.

Worth 1.7% as well (531.6 -> 522.1us at the model shape, 8 ranks, median of
three), but that is not why it is in. Exposed as `uncached=` so the cached
behaviour stays measurable, defaulting on.

It does *not* explain why this path reaches only 61% of the 76.8 GB/s line rate
where the copy engines reach 94%. Ruled out so far: grid size (24/48/80 blocks
within 0.6%), local memory traffic (10.6us of an 88us gap), and byte count
(accounts for 26us of it). gemm_ar's ATT capture of the same kind of store found
99% of its time was stall and that coalescing bought nothing, so this looks like
a property of CU-issued fabric writes rather than of this kernel. The next
testable idea is that reusing one register set per iteration serialises them --
each iteration's loads wait on the previous iteration's stores reading their
data out -- which an unroll by two would settle.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…-> 456us

split-sdma is now 455.6us against split-lsa's 522.1, having been 624.2. The
whole of that is one line in the epilogue that should not have run.

    wait_barrier(0)
    raw_cco.cco_system_fence(fx.Int32(0))   # every lane, every block

cco_system_fence(0) is a whole-L2 writeback from every lane, so block k
redundantly writes back every tile blocks 1..k-1 already wrote. At 1152 blocks
that is quadratic -- gemm_ar's own comment calls it that at the equivalent line.
With fuse=False nothing is published from here at all: the separate scatter
kernel issues the puts and does its own ordering. The fence had no one to
release to. It is now gated on `fuse`, along with the counter atomic.

Effect, 8 ranks, model shape, median of three:

    gemm-staging   458.6 -> 324.4   (-29%, now level with gemm-only's 320.2)
    split-sdma     624.2 -> 455.6   (-27%)
    split-rccl     824.3 -> 564.1   (-32%)

At 76.8 GB/s per link, split-sdma's 131.2us of communication is 94% of line
rate and 107% of the 122.9us fabric floor -- i.e. essentially saturated.

**How it was found, because three wrong guesses came first.** The symptom was
that "split-sdma minus gemm-only" gave 30.9 GB/s per link and SDMA looked half
speed. Two things were wrong with that: the subtraction used the wrong baseline
(the staging GEMM is a different kernel from gemm-only's), and the staging GEMM
was itself slow for a reason unrelated to its address map. Three controls, each
eliminating one suspect:

  * `gemm-to-window` -- gemm-only's kernel with C pointed at the recv region,
    which is exactly M*N*2 bytes, so the same instructions and the same address
    map write cco's window instead of a tensor. 323 vs 320us: writing the
    symmetric window is not slower.
  * `--staging-store copy` -- the staging store through the inherited copy atom
    instead of a raw buffer_store, by folding the destination into the row index
    so one static descriptor spans every slab. 463 vs 463us: the store
    instruction is not the difference.
  * `--no-rotated` -- 1%. The tile order is not it either.

Only then was the epilogue worth reading line by line. The three controls stay
in: they are the evidence, and deleting them would leave the conclusion
unfalsifiable.

Also here, all in service of the above:

  * `gemm-staging` mode, so the split-sdma subtraction has an honest baseline.
  * `split-rccl` mode -- the same staging GEMM, the same bytes, the same layout
    (all_to_all_single's chunking is exactly staging -> recv, no re-layout), so
    the difference from split-sdma is the transport and nothing else. It is the
    slowest of the three at 39.4 GB/s per link.
  * `self_to_recv=`, off for RCCL: a collective that takes one input covering
    every destination would read a hole where the self-to-recv shortcut leaves
    one.

One FlyDSL trap worth the comment it now carries: the AST rewriter looks for
`const_expr(...)` *syntactically*, so `via_copy = const_expr(...)` followed by
`if via_copy:` is lowered to an scf.if and the names bound inside it do not
survive -- "NameError: name 'store_c' is not defined". It has to be
`if const_expr(via_copy):`.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…A/B needs

Adds what the measurements below needed, and the measurements found that most
of it does not matter -- which is the useful part.

**split-rccl.** The same staging GEMM, the same bytes, the same layout: torch's
all_to_all_single splits its input along dim 0 into world chunks, which is
exactly staging -> recv, so no re-layout is involved and the only difference
from split-sdma is the transport. It is the slowest communicating mode in all
eight shape/M cells measured, 10-33% behind the best fused path.

`self_to_recv=False` goes with it: a collective that takes one input covering
every destination would read a hole where the self-to-recv shortcut leaves one.

**--phase-split.** Times the GEMM alone in the same process, right after timing
the whole thing, instead of subtracting a separate run. A cross-run subtraction
charges the transport for the GEMM's clock ramp -- the same kernel measured
324.4us at warmup=8 and 291.8 at warmup=30, and that 27us was being reported as
communication. It made split-sdma look like 94% of line rate where it is 75%.

Note what this cannot do: on a fused path the transfer is inside the GEMM, so
`total - gemm` is the *unhidden tail*, not wire time. Read that column for
split modes only. It reports 325% of line rate otherwise, which is the tell.

**Knobs that turned out not to matter**, kept because each one is the evidence
that it does not:

  * `--fence none|leader|all` -- 3510.6 / 3505.7 / 3511.1us. The fused-sdma
    epilogue's release granularity is free. I had committed to "every-lane
    fence is the third instance of that bug" before measuring it.
  * `--staging-store buffer|copy` -- 463 / 463us. The store instruction is not
    the difference between the staging GEMM and the plain one.
  * `--no-put` -- prices the epilogue's bookkeeping without the transfer.
  * `gemm-to-window` -- gemm-only's kernel with C aimed at the recv region,
    which is exactly M*N*2 bytes. 323 vs 320us: writing the symmetric window is
    not slower than writing a tensor.
  * `split-lsa-staged` -- the LSA copy reading a compacted slab instead of a
    strided [M,N]. 519.9 vs 521.7us, with 12% fewer bytes read. The read side
    is entirely hidden; LSA's time is its peer stores and nothing else.

**--direct-fence, defaulting to leader.** This one does matter: fused-lsa was
fencing from every lane where gemm_ar's default is one wave per block, worth
618.2 -> 491.0us. gemm_ar's README already carried the measurement (434 -> 355)
and its default was already right; I hardcoded the expensive form when porting
the epilogue and then spent a while looking for the cost somewhere else.

**sweep_models.py** carries the protocol the numbers depend on: interleave the
configurations rather than grouping them, wait for an idle box before every
launch, discard any sample taken with a neighbour present, and record the clock
and junction temperature next to every measurement. A neighbour is worth 9% on
a *pure GEMM* and, worse, is not a uniform slowdown -- it moved 70B's best
chunk count from 4 to 2 and its margin from 9.2% to 4.3%, i.e. it changes the
ranking, so a contaminated table cannot be rescued by scaling.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…ngths

The previous version is retracted wholesale. It reported one shape with no
model behind it (gcnasm's N=18432 K=8192), at one M, measured by subtracting a
separate gemm-only run, on a box that turned out to be shared. Every headline
number in it was wrong, and in at least one case the *ranking* was.

This one is Llama-3.1-70B / Qwen2.5-72B (N=10240 K=8192) and Llama-3.1-405B
(N=18432 K=16384), at M = 2048/4096/8192/16384 -- which under Ulysses is
S = 16k/32k/64k/128k, the dimension this operator actually moves along.

    best fused-sdma vs split-sdma
              S=16k   32k    64k   128k
    70B        9.2%  11.5%  15.9%  11.3%
    405B       3.5%   6.8%   7.7%   8.6%

    vs RCCL's all_to_all_single: 9.9% to 33.2%

Fusing wins in all eight cells and the margin grows with sequence length, which
is the mechanism gcnasm reports for its own version -- more tiles per
persistent workgroup means an early PUT has more remaining compute to overlap
against. 70B's fall-back at 128k is recorded as unexplained rather than
smoothed over; --chunks past 8 was not measured and is the first thing to try.

Also here: the shape rule N % (world*block_n) == 0 checked against real QKV
widths, and why Qwen3-235B is rejected (4 KV heads < 8 ranks, so Ulysses would
have to replicate KV; the layout rule is that condition surfacing in this
kernel).

**The measurement protocol is now part of the document**, because skipping it
is what invalidated the last one. A neighbour on the box is worth 9% on a pure
GEMM and moves the ranking, not just the scale: with company 70B's best chunk
count reads as 2 with a 4.3% margin, alone it is 4 with 9.2%. So: interleave
configurations instead of grouping them, wait for an idle box before every
launch, discard any sample taken with company, and record the clock beside
every number. Spread is 0.0-2.9% on all 30 cells; grouped sweeps on a shared
box had 3.7-17.4% and one 47% swing that no code difference explained.

The fused rows' "comm" column is labelled as the unhidden tail rather than wire
time. It is not the same quantity as the split rows' and reads as 325% of line
rate if taken as one.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
ue8m0 scales fed to the scaled MFMA as instruction operands rather than applied
in the epilogue: exponent-only, so the dequantisation is lossless and there is
no second accumulator and no running rescale. _Mxfp8ScaleK is gemm_ar's, imported
like the rest of the C-store ladder.

Validated at 8 ranks, N=10240 K=8192 M=2048, relL2 1.66e-3 on every mode and
identical across them:

                    ptpc    mxfp8
    gemm-only      183.6    197.2
    split-sdma     268.0    294.4
    fused-sdma c4  245.6    249.8
    fused gain      8.3%    15.2%

The fused margin is nearly twice ptpc's, and the reason is in the phase split:
mxfp8's GEMM is 7% slower (197.2 vs 183.6, the scale operands are extra loads)
while its unhidden communication is *lower* (31.0 vs 35.6us), so there is both
more to hide behind and less left over.

Two things this needed beyond wiring the scale object:

  * **BLOCK_M=256.** Not a preference: the packed A scale puts a lane's four M
    tiles in one dword and picks the byte with the MFMA's opsel, which is four
    tiles only at BLOCK_M//64 == 4. layout.py grew TILE_M_GRANULE so 128 and
    256 are both legal and the granule rule is stated separately from the
    choice; the benchmark takes MXFP8_BLOCK_M automatically rather than making
    every caller pass it.

  * **opsel_b_per_tile.** Missing it gave relL2 0.58 -- all four B tiles read
    byte 0 of the packed dword. Worth recording how it presented: `gemm-only`
    validated at 1.66e-3 while every communicating mode failed, which reads
    exactly like a transport bug. It is not. `gemm-only` runs gemm_ar's own
    kernel through compile_gemm_local, so it had the flag; only this file's
    kernel did not. The per-source check is what ruled the transport out --
    local and remote slabs were wrong by the *same* 0.58, and a transport
    cannot corrupt the slab it never touches.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Sweeps both model shapes under --quant mxfp8. Fusing pays 11-25% there
against ptpc's 3.5-16%, and both shapes are monotone in sequence length --
70B's unexplained fall-back at S=128k does not survive the change of
quantisation, so it belongs to the ptpc kernel rather than to the slab size.

Split-path communication matches the ptpc table cell for cell (405B/M=16384:
1511us vs 1517us), as it should: same bytes, same transport, only the GEMM
differs.

The sweep driver treated torchrun's ChildFailedError as a lost SDMA queue
race. It reports every child failure that way, so an ImportError -- a missing
PYTHONPATH overlay -- was retried three times per cell and then skipped,
emptying a whole sweep without one error reaching the log. Retry only on a
real SDMA marker.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
yangyuhuiling pushed a commit that referenced this pull request Oct 19, 2026
Rebased off the gemm_a2a branch (#695) onto main: nothing in
gemm_ag imports gemm_a2a, and the 14 commits applied without conflict.

* tests: _gemm_ag_pull_worker runs bench_gemm_ag.py through runpy.run_path,
  which does not put the script's directory on sys.path, so the
  `_bench_utils` split (25d419b) left test_pull_initializes_recycled_window
  failing on every run with ModuleNotFoundError.
* mori.ops: register gemm_ag with the lazy FlyDSL submodules.
* ci_cco.yml: run the four gemm_ag test files, after the GEMM+AR steps. Their
  8-rank SDMA process groups leave queues that take seconds to come back;
  gemm_ag's tests settle and retry around that, gemm_ar's do not, and run
  right after this step six of them failed in hsaKmtCreateQueueExt
  (anvil.cpp:210) while passing on their own. As written the step passes
  here: 213 tests in 22m50s.
* .gitignore: drop the local experiments entry; that archive lives outside
  the repository.
* docs: BUILD_CCO_SDMA is a build flag and on by default since #710, so stop
  exporting it at run time; example paths no longer point at a private
  checkout.
* README tables re-measured on main 8ae8156 (with #603 and #711), 8x MI355X,
  ROCm 7.14 / PyTorch 2.12 / FlyDSL 0.3.4.1: 54 configurations, all
  validated, relL2 <= 9.95e-7. Conclusions hold: 128x128 + split SDMA leads
  the Pro shape (355.9us, 12.6% under Torch + RCCL), fusing pays only for
  the combined Flash N=1024 at M=16384 (4.3%). Host and stack changed with
  MORI, so the deltas against September are not attributed.

Co-Authored-By: Claude <[email protected]>
Xiang.Chen and others added 12 commits October 20, 2026 01:20
docs/MORI-GEMM-A2A-BENCHMARK.md becomes python/mori/ops/gemm_a2a/README.md,
where the code it describes lives, and leaves the docs toctree. Its commands
are repository-relative, so the Reproducing section now says to run them from
the repository root.

Co-Authored-By: Claude <[email protected]>
kernels_fused.py carries its own copy of gemm_ar's 8-wave mainloop, and the
merge of main brought #785 to gemm_ar only. Apply the same three changes here:
drain the peeled tail's producers with wait_barrier(0) before it reads the last
step's B0/A0, restore the loop's end-of-step count to 2A+B, and make the loop's
S0 a read_done_barrier(). The comment telling readers not to restore 2A+B is
replaced, since #785 reversed it.

The barrier sequence of the loop and the peeled steps now matches gemm_ar's
exactly. Validated on 8x MI355X after the merge: all six modes at
[2048, 10240] K=8192 under ptpc and mxfp8, and fused-sdma at K=256 -- where
the main loop runs zero times and only the tail drain covers the race -- 4/4
ptpc and 2/2 mxfp8, all at relL2 1.66e-3.

Co-Authored-By: Claude <[email protected]>
… tail

Uneven chunks. `A2aConfig.chunk_plan` gives the row tiles of each chunk in
order (e.g. 16,16,...,8,4,4); the fused epilogue looks the chunk, its tile
count, offset and byte size up from block_m with a compile-time select chain.
An even plan keeps the old constants, so `--chunks N` compiles to the same
kernel. bench: `--chunk-plan`.

Timeline. `timeline.py` + `stamp_off` on compile_fused_gemm_a2a and
build_sdma_phases: s_memrealtime stamps per block (start/end), per
(dest, chunk) (elected, lock held, put returned) and in the drain (quiet,
peer flag). Off by default; on, it costs ~3%. bench: `--timeline PATH`
writes the last timed replay's per-rank timeline.

sweep_chunk_plans.py runs interleaved, idle-gated sweeps over chunk plans
(`--suite plans`), 128x256 vs 256x256 (`tiles`) and ptpc vs mxfp8 at 256x256
(`quant`).

What the sweeps found (8x MI355X, 3 interleaved rounds, all validated):

* Chunk completion is quantised by GEMM waves (one tile per block, one block
  per CU), so a small first chunk does not move the first put. Tapering the
  last chunks to about one wave helps at 128x256 / large M (405B M=16384:
  5188.8 -> 5118.7us, +1.4%) and does nothing measurable at 256x256.
* ptpc at 256x256 is much faster than the 128x256 default inherited from
  gemm_ar's blockscale path: gemm-only -12..-32% for M>=8192 and 405B
  M=2048, fused -8..-32%. Only 70B M=2048 (1.25 waves) prefers 128.
* At the same 256x256 tile mxfp8 is 15-18% slower than ptpc everywhere, so
  the README's "mxfp8 is faster at large M" is the tile, not the format.
* The 405B M=16384 256x256 tail (~230us by phase split) is ~89us of per-rank
  push (the last wave's chunk at ~55 GB/s per link, matching a per-link FIFO
  model within ~10us; lock wait ~1us, post ~2.6us) plus up to ~270us of
  rank-to-rank GEMM speed skew (8% p50 spread, stable per GPU).

Co-Authored-By: Claude <[email protected]>
`layout.default_block_m(m, n, quant, num_cus=)` returns 256 for mxfp8 (as
before), 256 for ptpc when 256x256 gives at least two waves of tiles, and
128 otherwise; blockscale stays at 128 (256x256 spills there). The 128x256
ptpc default was inherited from gemm_ar's blockscale path and has no spill
reason under ptpc.

bench: `--block-m` defaults to 0 = pick from the shape, and RESULT_JSON
reports the tile. sweep_models: `--alt-tile` also runs gemm-only and
fused-sdma at the tile not picked, and records block_m per sample.

Co-Authored-By: Claude <[email protected]>
The ptpc tables are re-taken on one 8x MI355X node (crsuse2-m2m-v3-054,
3 interleaved rounds, all 192 samples validated, spread 0.1-3.6%) at the tile
default_block_m picks, with a new tile table that runs every cell at the other
tile too: the picked tile has the faster fused path in all eight cells.

Fused vs split-sdma is now 16-31% (70B) and 16-22% (405B), monotone in M on
both shapes. The mxfp8 and full-mode tables are kept but marked as from the
earlier node and 128x256 ptpc; the "mxfp8 is faster at large M" reading is
corrected — at the same 256x256 tile mxfp8's GEMM is 15-18% slower.

Co-Authored-By: Claude <[email protected]>
pre-commit's insert-license hook failed on them.

Co-Authored-By: Claude <[email protected]>
…m_ar

All three settings measured the same, and nothing selected anything but the
default: the bench passed it only to fused-lsa, whose epilogue never read it.
fused-sdma keeps the one-wave system fence it always used.

Co-Authored-By: Claude <[email protected]>
The end-of-call barrier says every rank has written call e-1, not that every
rank has read it: a peer could pass the barrier, start call e and push into a
recv slot whose owner was still reading call e-1. Each call now posts a credit
(the call number, from the window's existing call counter) to every peer at its
start, and a push to peer d waits for d's credit first:

* fused-sdma: block 0 posts at kernel entry; the elected poster waits before
  taking the destination lock, so a wait never holds it.
* split-sdma: each scatter lane posts to its peer, then waits for it.

Starting a call means the rank's stream has finished whatever read the previous
result, so the guarantee holds as long as that reader is ordered before the next
call. `war_credit=False` exists for the race test's negative control and for
pricing it (bench `--no-war-credit`): fused-sdma on and off measured within
+-1%, no consistent sign, over three shapes and three interleaved rounds.

Also: recv slots are packed by the call's own m inside the capacity-pinned recv
region, so the result is one contiguous [world*m, shard_n] block for every m an
instance serves; and `default_chunks` (largest count <= 8 that keeps each put
>= 1 MiB, which reproduces the measured best on every model cell).

Co-Authored-By: Claude <[email protected]>
`GemmA2AOp(comm, n=, k=, m_max=, quant="ptpc"|"mxfp8", mode="fused"|"split")`
owns the window, picks the tile and chunk count per M, serves several M on one
instance, captures in CUDA graphs, and has self_test() for an SDMA build that
moves nothing. The LSA paths are not offered: they lose to SDMA here, and the
fused one would need the credit checked in every GEMM block.

test_gemm_a2a_op.py on 8 ranks: every received block against fp32 for both
modes x both quantisations, with two M values alternating and graph replays;
the recv-reuse race provoked (rank 0 reads call 1 late while its peers run call
2), which stays intact with the credit and is corrupted without it -- the
negative control that shows the race is real.

CI runs test_gemm_a2a.py and test_gemm_a2a_op.py in their own step.

Co-Authored-By: Claude <[email protected]>
… #6689

bench_gemm_a2a.py splits a case into _plan_case/_run_case so a driver can run
many cases on one communicator, and gains two timing modes: --b2b (launches
back to back under one event pair, as aiter's standalone times) and
--timing stream (back to back with an event between each, for at least
--min-seconds; median launch gap).

sweep_inproc.py runs a whole table in one process: one communicator, window
and dev-comm, rounds interleaved, kernels built once and reused by later
rounds, and rows already in --out skipped so a stopped sweep resumes. The GPUs
stay busy from the first case to the last instead of idling behind a process
launch and a settle per case.

README: the ptpc, tile and mxfp8 tables re-measured that way on one node
(2026-10-28), and a new section against aiter #6689 on MiniMax-M3's QKV at
P=4, where mori is ahead in every cell (0-9% with GemmA2AOp's defaults, 3-12%
with the best arm) and 128x256 beats the P=8-fitted tile rule.

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

@jhchouuu jhchouuu left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Reviewed and tested on 8x MI355X (ROCm 7.14 CI image, FlyDSL 0.4.0), with this branch merged into current main.

Reproduced

  • Tests. test_gemm_a2a.py + test_gemm_a2a_op.py: 47 passed (268 s).

  • Performance. sweep_inproc.py --suite models --quant ptpc validated every case at 1.66e-3. Fused-sdma (best arm) beats split-sdma by the following, within about 2 points of your table:

    S 16k 32k 64k 128k
    70B 16.1% 25.8% 28.3% 31.5%
    405B 17.0% 16.8% 16.7% 19.5%

    Against RCCL it is 23-40% faster. Repeated cells differ by at most 0.8% between rounds.

  • Pinned main loop. The copy in kernels_fused.py matches gemm_ar after #785: read_done_barrier placement, the 2A+B wait, and both tail waits.

  • Cache key. The kernel bodies close over scalars only, so there is no FlyDSL cache-key collision of the kind #748 found.

GemmA2AOp can silently return wrong results

  1. K=128 is accepted.
    • op.py:128 only checks k % 128. The main loop needs K_ITERS ≥ 2, which is why gemm_ar enforces MIN_K = 256.
    • gemm_a2a_op_worker.py --case correct -k 128 gives relL2 ≈ 1.0 on every rank (K=256 gives 1.66e-3), and raises no error.
    • Please enforce the same MIN_K.
  2. Nothing checks that the SDMA queues exist.
    • cco fixes the queue count at the comm's first create_dev_comm; a later request only logs a warning. put and quiet_queue on an out-of-range queue are no-ops.
    • So fused-sdma and split-sdma silently return stale data when MORI_ENABLE_SDMA is unset, or when another op created fewer queues on the same comm.
    • The worker's correct case without MORI_ENABLE_SDMA gives relL2 1.0-1.42 on every rank. The only signal is cco's error log line.
    • Raising in the constructor when dev_comm.sdma_num_queue < sdma_queues (for the SDMA modes) would catch both cases. self_test catches them too, but only if someone calls it.
  3. The tile election breaks after about 2^31 increments of one counter (kernels_fused.py:969-975).
    • The counters are never reset, and the test is Int32(seq) % c_tiles == 0.
    • When the u32 crosses 2^31, and again at 2^32, the jump is not a multiple of c_tiles unless c_tiles is a power of two. From then on every call elects at the wrong tile and ships a chunk whose later tiles have not been written yet.
    • At the 70B shape (c_tiles 20-40) that takes 5e7-1e8 calls on one M slot: days for a per-layer op, hours if one op serves every layer.
    • gemm_ar has the same construction (gemm_ar/kernels_fused.py:1939), so this could be a shared follow-up. Having the elected thread subtract c_tiles would fix it in both, since all of this call's increments have landed by then.

Smaller points

  1. split-lsa can publish its flag before its payload. It publishes after a plain fgpu.barrier() (kernels_lsa.py:267-279), whereas gemm_ar has an all-lanes cco_system_fence(0) at the same point. Without that fence there is no vmcnt(0) before the system-scope flag store, so the flag can overtake the payload. The mode is bench-only, but it is one of the measured baselines.
  2. The window zeroing is not ordered before peers' first writes. The constructor zeroes the window on the current stream and returns without a sync or comm.barrier() (op.py:156), so a peer's first push, and its credit, can land before this rank's zero runs. The probability is low, and gemm_ar's op does the same.
  3. lsa_size == world_size is not checked. World ranks are used as LSA ranks, so a comm spanning nodes would give wrong results.
  4. Signal and buffer helpers come in through gemm_ar's private module.
    • _credit.py, timeline.py and the kernels import signal_ptr, signal_store_u32, local_load_u32 and create_buffer_resource_from_addr through gemm_ar._compat. Since #817 these are public in mori.cco.device.flydsl.signals and .buffer.
    • The GEMM pieces (_gemm_a8w8_8wave and the kernels_fused internals) reasonably stay as they are. But #857 will have to be mirrored into the pinned main loop by hand, which is worth a note next to it.

Against aiter #6689

  1. The README's aiter comparison is against an older revision, and it can't be reproduced.
    • It was measured against aiter's r11 kernels through a standalone fp8_a2a_sdma_* harness that is not in either PR. aiter's shipped profile now selects r13 for every large row.

    • I re-measured against aiter's current head (474128f), timing SpQkvLarge.run through its public plan API (profile-selected params, GEMM + SDMA exchange + quiet_ready).

    • Both sides used the same protocol: graph replay, stream timing, median launch gap, max over ranks, GPUs 0-3, 3 interleaved rounds. Spread was 0.4% or less, and every result validated at 1.66e-3. Times in us:

      M aiter r13 mori default mori best arm
      dense 2048 247.0 242.4 -1.8% 231.8 -6.2%
      dense 4096 439.3 431.0 -1.9% 404.4 -7.9%
      dense 8192 778.1 751.7 -3.4% 747.2 -4.0%
      indexer 2048 289.6 259.5 -10.4% 248.6 -14.2%
      indexer 4096 475.2 467.4 -1.6% 438.8 -7.7%
      indexer 8192 870.6 825.4 -5.2% 814.9 -6.4%
    • So the conclusion holds against r13. It would help to update that section to r13 and to describe how aiter's side was timed, so others can reproduce it.

  2. The default arms leave time on the table at P=4 (non-blocking). In the same runs the op default is up to 6.6% slower than the best arm: dense M=4096 is 431.0 vs 404.4 us, and indexer M=4096 is 467.4 vs 438.8 us. The README already notes this. Keying default_block_m / default_chunks on the world size, or simply using 128x256 at P=4, would recover most of it.

* GemmA2AOp rejects k < 256 (gemm_ar's MIN_K; the main loop needs two K
  steps), and so does compile_fused_gemm_a2a. K=128 used to construct and
  return relL2 ~1.0.
* The constructor raises when the dev-comm reports fewer SDMA queues than
  asked for -- SDMA off, or an earlier dev-comm on the comm fixed a smaller
  count -- instead of letting every put move nothing; and when lsa_size !=
  world_size, since world ranks are used as LSA ranks.
* The window's zeroing is synchronized and followed by comm.barrier(), so no
  peer's first push or credit can land before it.
* The election counter goes back to zero on every call (the elected tile
  subtracts c_tiles) and the test is seq == c_tiles. A counter left to run on
  and tested modulo c_tiles elects the wrong tile after 2^31 increments, or
  2^32 unless c_tiles is a power of two.
* split-lsa fences every lane before its block barrier and flag store, so the
  flag cannot overtake the payload.
* Signal and buffer helpers come from mori.cco.device.flydsl.signals/.buffer
  rather than through gemm_ar._compat; the pinned main loop notes that #857
  will need mirroring.
* README: the aiter comparison is against r13 (aiter head 474128f, timed
  through SpQkvLarge.run), from the review's measurements.

Tests: the op test checks every election counter is zero after its calls,
and a new case checks the constructor rejects k=128, two queues on a
one-queue comm, and a comm with MORI_ENABLE_SDMA=0. 49 passed on 8x MI355X.

Co-Authored-By: Claude <[email protected]>
@yangyuhuiling

Copy link
Copy Markdown
Contributor Author

Thanks for the thorough review and the r13 numbers. All addressed in fc726a1, except 9 (below):

  1. K=128 -- GemmA2AOp now rejects k < 256 with gemm_ar's MIN_K, and compile_fused_gemm_a2a does too.
  2. SDMA queues -- the constructor raises if dev_comm.sdma_num_queue < sdma_queues, which covers both SDMA off and an earlier dev-comm on the comm having fixed fewer queues. A new worker case checks k=128, two queues on a one-queue comm, and a comm with MORI_ENABLE_SDMA=0 are all refused.
  3. Election wrap -- the elected tile now subtracts c_tiles, so every counter is back at zero after each call, and the test is seq == c_tiles. The op test now asserts every counter is zero after its eager and graph-replayed calls. I'll do the same for gemm_ar in a separate PR.
  4. split-lsa publish -- every lane now runs cco_system_fence(0) before the block barrier, so the signalling lanes cannot store the flag until every lane's payload has drained.
  5. Window zeroing -- now followed by torch.cuda.synchronize() and comm.barrier() before the constructor returns.
  6. LSA -- the constructor raises unless lsa_size == world_size.
  7. Imports -- signal/buffer helpers come from mori.cco.device.flydsl.signals / .buffer; only wave_uniform_i64 and the atomics still come from gemm_ar._compat. The pinned main loop now carries a note that perf(gemm-ar): load mxfp8 scales one K step ahead at K >= 4096 #857 will need mirroring.
  8. aiter r13 -- the README's comparison now uses your r13 table, with the timing method you described, credited to this review. If you can share the script that drives SpQkvLarge.run, I'd like to add it next to sweep_inproc.py so the aiter side is reproducible from the repo too.
  9. P=4 defaults -- agreed; I'd rather do the world-size-aware tile/chunk rule in a follow-up, with its own sweep, than change the defaults in this PR.

Re-validated on 8x MI355X: test_gemm_a2a.py + test_gemm_a2a_op.py 49 passed. Spot checks are unchanged from the README: 70B M=4096 fused c8 328.5us (README 328.4), 405B M=16384 3663.9us (3678).

split-lsa (a copy kernel storing into the peers after the GEMM) and
fused-lsa (the epilogue storing into them itself) lost to the copy engines
on this operator -- split-lsa reaches ~60% of line rate against SDMA's ~75%,
and fused-lsa was the slowest mode at both model shapes -- and GemmA2AOp
never offered them. Removed: kernels_lsa.py, the direct-LSA branches and the
transport/direct_fence parameters of compile_fused_gemm_a2a, the LSA copy
grid in the layout, and the split-lsa/split-lsa-staged/fused-lsa bench modes
with their flags. _spin_until moves to _credit.py.

The README keeps the measurements that justify it, and notes that small M,
where a copy engine's per-put cost dominates, was not measured.

48 tests pass on 8x MI355X; every remaining bench mode validates.

Co-Authored-By: Claude <[email protected]>
@yangyuhuiling

Copy link
Copy Markdown
Contributor Author

Follow-up in 91b387a: the LSA transports (split-lsa, split-lsa-staged, fused-lsa) are removed from gemm_a2a altogether. They lost to SDMA at every measured shape and GemmA2AOp never offered them, so keeping them only kept a second set of kernels to maintain. That also removes the split-lsa publish path from item 4. The README keeps the measurements behind the decision, and notes that small M -- where a copy engine's per-put cost dominates -- was not measured. 48 tests pass (one fewer: the force_blocks layout check went with the LSA copy grid), and every remaining bench mode validates.

yangyuhuiling pushed a commit that referenced this pull request Oct 29, 2026
split-lsa-push, split-lsa-pull and fused-lsa go, with kernels_lsa.py, the
pull worker and its tests, as gemm_a2a (#695) did with its own. At the Pro
shape the best LSA path was 4.6% behind split SDMA and fused LSA 16-19%
behind; LSA led only on the smallest payload measured (Flash N=512, M=2048,
by 3%) and trailed by up to 2% on the other M=2048 shapes, which does not
pay for a second transport in the test matrix. The dated tables keep their
LSA rows, marked removed.

The SDMA barrier keeps its spin loop, now local to kernels_sdma. The fused
epilogues store into this rank's own slot only, so gemm_ar's _SwapABStoreC
no longer needs the peer_rsrcs list this PR added: it is back to main's, and
the PR no longer touches gemm_ar. The unfused bf16 GEMM's sc0|sc1 publication
existed for the pull baseline and is rejected now; peer_uncached remains for
the fused path's sc_release configuration.

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

@jhchouuu jhchouuu left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Re-tested at 91b387a8 merged onto current main, on 8x MI355X (ROCm 7.14, FlyDSL 0.4.0). All of the first-round points are addressed. Point 9 moving to a follow-up is fine with me.

  • The two silent-wrong-result cases now fail at construction, with clear messages:

    • gemm_a2a_op_worker.py --case correct -k 128 raises ValueError: k=128 is below the minimum 256.
    • Without MORI_ENABLE_SDMA it raises RuntimeError: GemmA2AOp needs 1 SDMA queue(s) per peer but the communicator has 0.

    At K=256 the worker validates every eager and graph call, with counters_left: 0.

  • Tests. test_gemm_a2a.py + test_gemm_a2a_op.py pass (48 tests).

  • The ptpc model sweep matches the first round. Every case validated. Best fused-sdma against split-sdma:

    • 70B: 16.9 / 24.2 / 29.2 / 30.1% at S = 16k / 32k / 64k / 128k;
    • 405B: 16.9 / 18.0 / 18.0 / 22.2%.

    Individual cells are within -4.9% to +1.0% of my first-round numbers.

  • The LSA removal is clean. Nothing in the op, benchmarks or tests still refers to the removed modes.

One nit, non-blocking. The credit and flag spins compare unsigned (cur < target: _credit.py:79, which kernels_sdma.py:150 also uses). On a window's 2^32nd call the epoch wraps to 0, so cur < 0 never holds and that call's waits pass without the peer having started it. For that one call the WAR guard is off. #868 just moved to (int32)(cur - target) < 0 for the same reason, and the same change here (and in gemm_ar) would close it.

LGTM.

@yangyuhuiling
yangyuhuiling merged commit 13596f1 into main Nov 2, 2026
14 of 15 checks passed
yangyuhuiling added a commit that referenced this pull request Nov 4, 2026
* gemm_ag: fp8 GEMM fused with an all-gather

A third fusion operator on gemm_ar's 8-wave fp8 GEMM, alongside gemm_ar's
all-reduce and gemm_a2a's all-to-all. Every rank computes its own [M, N] and
every rank ends up with all `world` of them concatenated along rows -- the
DeepSeek V4-Pro prefill-CP wkv_gate shape, where each context-parallel rank
scores its own tokens and then everyone needs every token's score.

Eight modes: gemm-only, gemm-to-window, split-rccl, split-lsa-{push,pull},
fused-lsa, split-sdma, fused-sdma. ptpc/blockscale/mxfp8 throughout.

All-gather shards nothing, so three things gemm_a2a needs are absent: the
staging region (the payload is already contiguous and already the same for
every destination), the per-(destination, chunk) counter (one chunk arms every
push at once), and the destination rotation (a broadcast tile belongs to
everyone). The layout's N rule reduces to `n % block_n`, which is what lets
this op run the ratio-128 wkv_gate shape at N=1024 -- a shape a2a_config
rejects at world_size=8.

Because the collective is a broadcast it can be driven from either end, so
both directions are implemented and compared. That is also the first thing the
measurements say: pull needs the producer to publish C with system scope,
since it reads a peer's HBM while the peer's GEMM left the line dirty in its
own L2. Without it split-lsa-pull validated at 1.66e-3 under ptpc and 2.05e-1
under blockscale -- a correctness bug visible in exactly one quantisation,
which is why the mode matrix is parametrised over all three.

gemm_ar's _SwapABStoreC gains a `peer_rsrcs` list alongside `peer_rsrc`. A
broadcast stores one tile to every peer, and doing that with `world` separate
store objects would repeat the scale loads, the convert and the permlane
shuffle with it. A single resource yields a one-element tuple and identical IR,
so gemm_ar and gemm_a2a are unchanged.

Measured on 8x MI355X: the split paths beat RCCL by 8-9%, and the fused paths
lose to their own split baselines. The fusion itself works -- at M=512
fused-sdma cuts exposed comm 50.9us -> 21.8us -- but the epilogue's per-block
publication roughly doubles the GEMM. See docs/MORI-GEMM-AG-BENCHMARK.md.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* docs(gemm_ag): the measured tables, and where the fused time goes

Two wkv_gate shapes x two sequence lengths x every mode, plus the full
quantisation matrix and the fused-sdma chunk ladder, on 8x MI355X.

Every mori transport beats RCCL by 10-25%, and push beats pull everywhere --
the opposite of gemm_ar's gather leg, which found pull worth 5.6-10.5% over a
*copy-engine* push. The GEMM phase is equal to within 0.5us across the pair, so
pull's mandatory sc0|sc1 C store is not the cause; a push is a fire-and-forget
store where a pull is a load that must round-trip. That is worth knowing beyond
the ranking, because pull is where a low-precision wire would want its
dequantize.

The fused paths lose, and --no-put and --fence none between them say why. The
overlap itself works: fused-sdma cuts exposed comm by 25-59%, a larger fraction
than gemm_ar's all-reduce absorbs. The release fence is free at these grid
sizes (32-128 blocks, against the 9216 where gemm_a2a calls it the most
expensive line in its epilogue) and the bookkeeping is 2-6us. What costs is
*issuing* the puts: 39-55us, nearly constant across four cells whose payloads
differ by 8x, which rules out bandwidth contention and lands on gemm_ar's own
constant of ~2us per SDMA packet regardless of size.

At --chunks 4 and world=8 that is 28 puts posted serially by one thread under
one lock, where gemm_a2a posts the same 28 from 28 different blocks -- its
counter elects per (destination, chunk), so each elected block owns one
destination. A broadcast chunk arms every destination at once, which is what
made the counter cheaper and the posting expensive. Fixing it is a change to
the epilogue, not to the design, and the doc says what it is.

Separately, the bound: all-gather's G0/C0 goes as K/(world-1) where both
siblings go as K, because they shard the payload by world and it does not. It
is the one operator in the family where scaling out makes fusion less
attractive, and the one where a narrower wire is worth more than any epilogue
tuning.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* gemm_ag: issue a chunk's packets from world-1 lanes, not one thread

The fused-SDMA epilogue was spending 39-55us of GEMM time issuing a chunk's
world-1 SDMA packets back to back from thread 0 -- nearly constant across four
cells whose payloads differ 8x, which is SDMA's ~2us per packet regardless of
size, the constant gemm_ar's layout already states.

--post lanes gives each of lanes 0..world-2 one packet. What made that awkward
is that a broadcast chunk arms every destination at once, so the natural counter
is one per chunk -- and the thread that wins a single counter then has to tell
world-2 other lanes, which costs a barrier and an LDS round trip for one dword.
So the counter goes back to one per (chunk, lane), gemm_a2a's shape for a
different reason: every block increments all world-1 in one instruction, they
cross the threshold together, and each lane learns from its own atomic. No
broadcast.

The submit lock had to go with it. world-1 lanes retire in lockstep, so two
waves each holding part of a lock set and spinning for the rest could never
reach their release. The same collision -- two chunks of one destination posting
at once -- is separated by queue instead (chunk % sdma_queues), hence the new
sdma_queues >= chunks requirement, which the benchmark derives rather than asks
for.

Measured, ptpc r4: the fused GEMM phase goes flat at 57.4-60.4us across c1..c8
at M=512 and 66.6-71.9 at M=2048, where serial climbs to 105.2 and 168.8. At
M=2048 c8 that is -96.9us of GEMM time. Best total 113.1 -> 105.5 (-6.7%) and
224.1 -> 217.2 (-3.1%). All twelve quant x chunk cells validate at the same
relL2 as every other mode.

It still does not beat split-sdma (105.5 against 104.1; 217.2 against 210.5),
and fixing it exposed that the first round's headline was wrong: serial's drain
shrank with chunk count not because the fusion absorbed communication but
because the GEMM was stalled posting and the copy engines got a head start,
which the phase split booked as absorbed comm. With the posting fixed the drain
grows with chunk count instead -- the ~2us per packet moves from the issue side
to the wire, and chunking an all-gather multiplies packets by world-1 per chunk
because every peer gets the same slab. --chunks 1 is now the best fused setting
everywhere, and the remaining gap is ~10us of bookkeeping against ~7.5us of real
early-start.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* gemm_ag: a bf16-in / fp32-or-bf16-out path

gemm_ag was built on gemm_ar's fp8 GEMM, and the layer it exists for is not
fp8: DeepSeek V4-Pro's wkv_gate goes through linear_bf16_fp32, and the planning
doc says in as many words that the first implementation must keep that input
precision and FP32 output convention rather than substituting the FP8 GEMM. So
the operator had the right shapes and the wrong precision, and its numbers could
not be put next to the FP32 baseline they are meant to replace.

_gemm_a16w16_8wave.py ports gcnasm's gemm_a16w16_quad_subtile_kernel_template
at its own instantiation <512, 256, 256, 64, bf16, bf16, bf16, float>. The port
is small because gemm_ar's _gemm_a8w8_8wave.py is already a FlyDSL rendering of
that same template with fp8 operands -- same 8 waves, same 2x2 half-tiles, same
swapped-AB MFMA, same permlane store. Four things change: the MFMA becomes
16x16x32 bf16, E_K goes 1 -> 2, VEC goes 16 -> 8, and there are no scales. The
LDS keeps mori's XOR swizzle restated in bytes (swizzle_row128b), asserted in
the tests to be the fp8 function value-for-value at elem_bytes=1.

The FP32 store turns out to be the cheap one. The A/B swap puts four
consecutive columns in each lane; at two bytes that is 8 B and needs a
permlane16_swap to pair two N-tiles into 16 B, and at four bytes it is already
a buffer_store_dwordx4 with no shuffle and no convert.

elem_bytes becomes load-bearing rather than decorative: layout validates it,
kernels_lsa derives its pack width from it, and the benchmark gains
--in-dtype {fp8,bf16} and --out-dtype {bf16,fp32}, both defaulting so every
existing number stays reproducible.

Measured, 8x MI355X, K=7168 N=2048. Accuracy first: relL2 9.9e-7 for fp32 out
against 1.66e-3 for bf16 out -- three orders of magnitude, and it shows the
1.66e-3 was always the bf16 *output* rounding rather than the fp8 inputs.

All 32 cells validate. Fusing now breaks even (fused-sdma within 0.5% of
split-sdma at every cell, with 4-9% of the transfer genuinely absorbed) where
under fp8 it lost by 3-7% -- the bf16 GEMM is 2.2x larger, which is exactly the
G0/C0 lever the bound section describes. fused-lsa gets worse, and fp32 makes it
much worse (616 against split-sdma's 428), because its epilogue pushes world
copies of every element through the CUs.

The honest headline: against the planning doc's FP32 baseline the collective leg
agrees to 3.4% (327.8 against 339.2) but our GEMM is 28% slower than
torch.matmul (137.6 against 107.2), so at the target shape this is not yet a win
and the whole deficit is in the multiply. BLOCK_K is pinned to the template's
64, xcd_swizzle is off and no tile sweep has been run; tuning that is worth more
than any further epilogue work.

Also recorded: FlyDSL caches compiled kernels keyed on the @flyc.jit wrapper's
name, not the kernel body, so a fixed bug can look unfixed. Here it produced a
thoroughly convincing false signal -- odd K_ITERS bit-exact, even K_ITERS broken
-- which looks exactly like a double-buffer parity bug and was not one.

One cell (fused-sdma bf16 M=2048) failed validation once and passed the next 13
runs. Left in the doc as unresolved rather than dismissed.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* gemm_ag: sweep the bf16 GEMM's tile, and find a bug instead of a speedup

The bf16 port landed 28% behind torch.matmul, called out as the largest number
on the table. The cause is not the mainloop: the template's 256x256 tile
launches ceil(M/256)*ceil(N/256) workgroups, which at the wkv_gate shape
(M=N=2048) is 64 against an MI355X's 256 CUs. Three quarters of the GPU idles
and nothing inside the loop can reach that.

Measured at M=2048 N=2048 K=7168, fp32 out, one GPU, torch.matmul at 84.8us:

    256/256 (template)   64 wg   176.0us   342 TF/s
    256/128             128 wg   139.6us   431 TF/s
    128/256             128 wg   134.2us   448 TF/s
    128/128             256 wg   116.5us   516 TF/s

waves_per_eu (1/2/4) and xcd_swizzle (0/1/4/8) are inert -- every cell within
1%. Across shapes the rule is not "maximise the grid" either: at M=4096,
128/128 gives 512 workgroups and 162.8us against 128/256's 256 workgroups at
155.2, so once there is one workgroup per CU the larger tile amortises better.
pick_tile takes the largest tile whose grid still covers the CUs, which
reproduces the measured best at all four shapes.

**Neither faster tile ships.** 128/128 races: one wrong fp32 C in 48 single-GPU
runs, and about half the ranks per 8-rank launch. 128/256 is worse than it first
looked -- gemm-to-window and split-rccl validated 4/4 and 3/3, then came back
1/2 on a later pass, while fused-lsa is 0/4 throughout. BLOCK_M=256 has not
failed once across every repeat run. So the failure rate at 128 is around a
third of launches, and the tidy "split paths are sound, fused paths are not"
story the first pass suggested did not survive repetition.

The obvious suspect is the release fence, since halving BLOCK_M doubles the
blocks that must publish. It is wrong: --fence all and --direct-fence all are
0/3 each.

Buying 24% for a wrong answer a third of the time is not a trade, so pick_tile
returns the template's tile and the speedup does not reach the default. What
ships is the knowledge: the tile is worth 24-34% and is the only knob that is,
the mechanism is grid occupancy rather than scheduling (so the next attempt is
split-K), and there is a latent correctness bug that halving BLOCK_M exposes
which was invisible at the template's tile. Finding it is worth 33% on the GEMM
and is now reproducible.

Also here: layout accepts block_n=128 under an fp32 C (a bf16 store pairs two N
tiles through permlane16_swap and cannot); the fused-SDMA C store moves to a
buffer resource at this rank's recv slot, matching gemm_ar, which fixed a wrong
answer at M=2048 fp32 (relL2 6.9e-3 -> 9.9e-7); and compile_bf16_gemm_ag now
rejects a tile that disagrees with its config, which would hang the completion
counter rather than corrupt it.

All eight modes validate at the shipped default.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* gemm_ag: the BLOCK_M=128 corruption is the mainloop's vmcnt, confirmed

The tile sweep left a bug it could not explain: BLOCK_M=128 is 24-33% faster
and corrupts about a third of 8-rank launches, including gemm-only, which has
no collective in it at all. This pins the cause.

`wait_barrier(N)` is `s_waitcnt vmcnt(N)` plus `s_barrier`, so it is the only
thing making a G2S load's LDS write visible before the next iteration's S2R
reads it. Sweeping that one number, BM=128 fp32 M=2048, gemm-only, six
launches each:

    vmcnt(2A+B) = 4   (inherited)   5/6    91us
    vmcnt(A+2B) = 5   (derived)     4/6    90us
    vmcnt(0)          (everything)  6/6   150us

So it is the waits, and `vmcnt(0)` is correct. A `--wait-policy` knob is added
to make that reproducible rather than a one-off.

It also shows the *derivation* is wrong, which matters more than the knob.
Walking the mainloop -- entering with A+2B outstanding, issuing A1@k+1, B0@k+2,
A0@k+2, B1@k+2, needing the 4th item retired -- gives a requirement of
wait <= A+2B, under which:

    256/256  A=2 B=2  in-flight 14  wait 6 -> retires 8, needs 8, margin 0
    128/256  A=1 B=2  in-flight 11  wait 4 -> retires 7, needs 6, margin 1

The tile with *zero* margin is the one that is clean and the tile with margin
is the one that fails, so the model does not describe the hardware. Something
is outstanding on vmcnt that this counting does not include -- the S2R reads
are the obvious suspect (16 per iteration at BM=128, 24 at BM=256) if they
lower to flat loads rather than ds_read, since flat counts against vmcnt.
Settling that needs the generated ISA, which the FlyDSL cache does not keep
(pickles, not objects).

Nothing about the shipped configuration changes: the default is still the
template's BLOCK_M=256 at wait_policy="tuned", which is what every mode
validates on. vmcnt(0) is not a fix worth taking either -- at 150us it is
slower than BLOCK_M=256's 137.6, so it spends more than the tile saves.

What this buys is a bounded next step. The question is no longer "why does a
smaller tile corrupt" but "how many vmem ops are actually in flight at that
one instruction", which the ISA answers directly.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* gemm_ag: the ISA clears the vmcnt counts, and the kernel with them

The wait-count hypothesis was confirmed by a sweep (vmcnt(0) is 6/6 where
vmcnt(4) is 5/6) and is refuted by the generated code. Both are worth having.

Dumping with GPU_DUMP_CODE_OBJECT=1 and llvm-objdump --mcpu=gfx950, at
M=2048 N=2048 K=7168 fp32:

* the S2R loads are `ds_read_b128` -- lgkmcnt, not vmcnt. They were never part
  of this accounting, which kills the leading theory outright: 16 per iteration
  at BM=128, 24 at BM=256;
* the G2S loads are `buffer_load_dwordx4`, exactly A+B per load call, 6 per
  iteration at BM=128 and 8 at BM=256;
* `vmcnt(4)` and `vmcnt(6)` each retire precisely one iteration's worth,
  leaving in flight exactly the k+2 prefetches. Both are correct;
* the two skeletons are structurally identical, 8 barriers per iteration in
  both, with `s_waitcnt lgkmcnt(0)` correctly between the barrier pair that
  guards the write-after-read on each LDS buffer;
* neither spills, and both get one workgroup per CU. The only asymmetry is
  152 VGPRs / 96 KiB LDS against 248 / 128 KiB, which is just the tile.

One more candidate came out of reading it and died the same way.
gemm_ar.wait_barrier puts s_waitcnt and s_barrier in a single inline-asm string
with constraints="" -- no memory clobber -- so the compiler is never told there
is a barrier in there and could legally move an LDS access across it, which
would be a write-after-read on the double-buffered LDS and would plausibly
depend on register pressure. Emitting the wait as asm and the barrier as
rocdl.s_barrier() produces byte-identical code. That option is therefore not
kept: an option that provably cannot differ is not an option.

So vmcnt(0) fixing the corruption is timing perturbation, not a corrected
count. Put beside the other end of the evidence -- 0 wrong in 64 single-GPU
runs at every tile, no collective in the loop -- the weight has moved off this
kernel. What reproduces it is eight concurrent processes; what never
reproduces it is one idle GPU running the same kernel on the same data.

Next place to look is the harness or the environment: whether the benchmark's
own fp32 reference can be corrupted under memory pressure, and whether the cco
window's VMM allocation interacts with a plain torch.empty C (ROCm 7.2.x is
known to route uncached VMM allocations to the coarse-grained pool). The
--wait-policy knob stays so the sweep is reproducible.

Nothing about the shipped configuration changes.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* gemm_ag: fix bf16 pipeline ordering and split-pull publication

Order LDS reads before buffer reuse and drain the final prefetches. Honor peer_uncached for unfused C stores and publish from every producer lane. Initialize the full benchmark window so stale arrival flags cannot bypass the first pull barrier.

Add pipeline dependency, exact numerical, graph replay, and dirty-window regressions. Validation: 151 related tests passed; BM=128/256 with BF16/FP32 output each passed five independent eight-rank benchmark launches.

* gemm_ag: drain all SDMA queues before publishing arrival

Chunked fused producers can submit through every queue to a peer. Wait for all of those queues before signalling completion, while retaining the existing split and single-queue waits.

Validate the publication contract with 24 queue-state cases. The corrected path also passed eight-rank BF16-to-FP32 graph replay checks with one, two, and four chunks.

* gemm_ag: keep direct benchmarks and reusable pipeline kernels

Expose split-K FP32 partials, serialized SDMA chunk posting and release-only
producer publication through the kernel API. Retain direct GEMM, transport
and pipeline benchmarks with shared graph timing and changed-input checks.
Preserve the FP8 wait-policy argument fix and reject nonfinite peer output.

Keep source generators, historical experiment plans and raw datasets out of
the branch. Document the supported commands and retain the measured findings.

Validation: 129 CPU checks; 54 gfx950 numerical/graph cases; 11 eight-rank
BF16/FP8 transport and MORI/split-K/Torch pipeline checks; eight-rank native
GEMM comparison; Black 25.1.0 and Ruff 0.12.0.

* docs(gemm_ag): keep benchmark reports alongside the operator

* docs(gemm_ag): consolidate benchmarks and trim experiment history

* gemm_ag: identify model shapes and benchmark V4.1 Flash

Label the Pro ratio-4 projection measurements and document Flash's separate
512-wide projections and combined 1024-wide candidate at K=5120. Record
8-GPU transport, M-sweep, pipeline and complete projection-order comparisons,
including interleave restoration and KV/gate materialization costs.

Use thread-local capture for RCCL to avoid HIP watchdog event queries
invalidating global graph capture, and destroy process groups on CLI exit.

Validation: 52 reported configurations/repeats on v2-015 passed initial and
changed-input checks; maximum relative L2 error 8.04e-7. Two benchmark CPU
checks, Black, Ruff, documentation links and numeric checks passed. Raw
plans, scripts, logs and excluded attempts are archived outside the repo.

* docs(gemm_ag): record smaller-tile fusion experiments

* gemm_ag: rebase onto main, fix the pull test, add CI, re-measure

Rebased off the gemm_a2a branch (#695) onto main: nothing in
gemm_ag imports gemm_a2a, and the 14 commits applied without conflict.

* tests: _gemm_ag_pull_worker runs bench_gemm_ag.py through runpy.run_path,
  which does not put the script's directory on sys.path, so the
  `_bench_utils` split (25d419b) left test_pull_initializes_recycled_window
  failing on every run with ModuleNotFoundError.
* mori.ops: register gemm_ag with the lazy FlyDSL submodules.
* ci_cco.yml: run the four gemm_ag test files, after the GEMM+AR steps. Their
  8-rank SDMA process groups leave queues that take seconds to come back;
  gemm_ag's tests settle and retry around that, gemm_ar's do not, and run
  right after this step six of them failed in hsaKmtCreateQueueExt
  (anvil.cpp:210) while passing on their own. As written the step passes
  here: 213 tests in 22m50s.
* .gitignore: drop the local experiments entry; that archive lives outside
  the repository.
* docs: BUILD_CCO_SDMA is a build flag and on by default since #710, so stop
  exporting it at run time; example paths no longer point at a private
  checkout.
* README tables re-measured on main 8ae8156 (with #603 and #711), 8x MI355X,
  ROCm 7.14 / PyTorch 2.12 / FlyDSL 0.3.4.1: 54 configurations, all
  validated, relL2 <= 9.95e-7. Conclusions hold: 128x128 + split SDMA leads
  the Pro shape (355.9us, 12.6% under Torch + RCCL), fusing pays only for
  the combined Flash N=1024 at M=16384 (4.3%). Host and stack changed with
  MORI, so the deltas against September are not attributed.

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

* docs(gemm_ag): re-measure the larger-M Pro study and refresh the summary

The README's opening summary still quoted the September figures, and its
strongest fusion claim (11% at M=16384) rested on a study the previous
re-measurement did not cover. Re-taken on the same stack: split SDMA against
sc_release c4 at N=2048, K=7168 gains 5.3% at M=8192 and 11.9% at M=16384,
and loses at M=4096 (c4 -4.8%, c2 -1.6%) -- September's v2-015 pairs gave
4.9-5.2%, 11.1% and -3.2%.

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

* gemm_ag: take #785's pipeline fix after merging main

kernels_fused.py carries its own copy of gemm_ar's 8-wave fp8 mainloop, and
the merge of main brought #785 to gemm_ar only. Apply the same three changes:
drain the peeled tail's producers with wait_barrier(0) before it reads the
last step's B0/A0, restore the loop's end-of-step count to 2A+B, and make the
loop's S0 a read_done_barrier(). The comment telling readers not to restore
2A+B goes, since #785 reversed it. The BF16 quad-subtile GEMM is a different
pipeline and is untouched.

The four gemm_ag test files pass as the CI step runs them (213), and at K=256
-- where the main loop runs zero times -- fp8 fused-sdma validates 3/3 under
ptpc and 1/1 under mxfp8, split-sdma 1/1, all at relL2 1.66e-3 on 8x MI355X.

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

* gemm_ag: bind the LSA kernel's receive-slot offsets outside its body

The copy kernel read cfg.recv_slot_off() inside @flyc.kernel. FlyDSL keys
its compile cache on scalar closure values, and those offsets depend on the
window's capacity, which nothing else in the key carries, so two configs
differing only there could share a cached kernel with the wrong offsets.
gemm_ar fixed the same thing in #748. Bind them to a tuple of ints instead.

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

* docs(gemm_ag): re-measure after merging main, and record #748's short tail

crsuse2 v3-054, ROCm 7.2 / FlyDSL 0.4.0: every conclusion holds -- split
SDMA 10.4% under Torch + RCCL at Pro M=2048, fusion paying from M=8192
(4.8%, 11.2% at M=16384), the combined Flash projection 4.8% at M=16384.
gemm_ar's short final chunk was ported and measured; no variant beat the
best even split, so it is recorded rather than kept.

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

* docs(gemm_ag): Torch + RCCL at every shape, and a GEMM / AG phase split

Against Torch + RCCL the best MORI path is 10-16% faster on V4-Pro and
6-11% on V4.1-Flash. A same-run phase split over all four GEMM x transport
combinations attributes it: SDMA's all-gather is 12.5-13.9% under RCCL's at
every shape, while the 128x128 BF16 GEMM is level or ahead only up to
M=4096 and 22-52% behind Torch's at larger M -- so Torch's GEMM followed by
SDMA is the strongest non-fused path, and fusion beats it only on Pro at
M >= 8192.

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

* docs(gemm_ag): retune the BF16 tile per shape, and why fusion does not follow

Sweeping all four tiles: the right one matches Torch's GEMM from M=8192 and
beats it by 23% at Pro M=4096, and pick_tile's rule names it at every
shape, but TILE_CANDIDATES holds only 256x256. The faster tile speeds the
split path, not the fused one: 256x256 launches a single round of
workgroups at Pro M=8192 and Flash M=16384, so every chunk completes at
once and there is nothing left to overlap. Best path per shape is now
11.7-16.1% under Torch + RCCL at M >= 4096.

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

* gemm_ag: SDMA only -- remove the LSA transports

split-lsa-push, split-lsa-pull and fused-lsa go, with kernels_lsa.py, the
pull worker and its tests, as gemm_a2a (#695) did with its own. At the Pro
shape the best LSA path was 4.6% behind split SDMA and fused LSA 16-19%
behind; LSA led only on the smallest payload measured (Flash N=512, M=2048,
by 3%) and trailed by up to 2% on the other M=2048 shapes, which does not
pay for a second transport in the test matrix. The dated tables keep their
LSA rows, marked removed.

The SDMA barrier keeps its spin loop, now local to kernels_sdma. The fused
epilogues store into this rank's own slot only, so gemm_ar's _SwapABStoreC
no longer needs the peer_rsrcs list this PR added: it is back to main's, and
the PR no longer touches gemm_ar. The unfused bf16 GEMM's sc0|sc1 publication
existed for the pull baseline and is rejected now; peer_uncached remains for
the fused path's sc_release configuration.

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

* gemm_ag: pick the BF16 tile per shape and per path, and the fused chunk count

TILE_CANDIDATES now holds all four tiles. pick_tile's unfused rule (largest
tile whose grid covers the CUs) names the fastest GEMM at all six measured
shapes. The fused path gets its own rule: the largest tile other than
256x256 whose grid runs at least two workgroup rounds, with one chunk per
round (pick_chunks) -- the best fused configuration at Pro M=8192 / 16384
and Flash M=16384, 3.9% / 7.4% / 2.2% under split SDMA and 1.9-3.4% under
the 128x128 fused runs. The benchmark uses both when --block-m, --block-n
and --chunks are left at 0 (--chunks now defaults to 0).

The smaller tiles were held back until the LDS ordering fix had broader
coverage; test_every_tile_validates_split_and_fused adds 8-rank coverage
for all four, split and fused.

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

* gemm_ag: benchmarks use the installed mori, not the checkout's source tree

_bench_utils.py put the checkout's python/ at the front of sys.path, which
shadows the installed package. CI installs mori non-editable, so the source
tree there has no compiled mori.cco.cco and every benchmark process the tests
spawn died on import: the GEMM+AG CI step has failed (24 tests) since it was
added. An editable install, where the extension sits in the tree, hid it.

Drop the insertion, and stop the benchmark README from exporting PYTHONPATH at
the checkout for the same reason.

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

* gemm_ag: add GemmAgOp, a recv-reuse credit, and fold the tests and docs

GemmAgOp is the public wrapper: it owns the window, picks tile and chunk
counts per M (with overrides), keeps one counter slot per shape, pads rows,
and has a self_test with teeth. supports()/shape_constraint() state the
shape rules up front.

The fused FP8 and BF16 epilogues and the split gather now wait for a
per-peer credit before pushing into that peer's recv: every rank posts its
call epoch at entry. Without it a rank a call ahead could overwrite a result
a slower rank was still reading; the benchmark replays identical operands,
so a stale read there was the right answer and nothing caught it. The
back-to-back case in the new op test fails with the credit off.

Tests: test_gemm_ag.py now holds everything that needs no process group
(layout, the LDS and SDMA models, the benchmark contract, single-GPU
numerics) plus the benchmark's two baselines; test_gemm_ag_op.py runs every
multi-rank case through GemmAgOp from one 8-rank spawn. EXPERIMENTS.md is
merged into README.md.

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

* gemm_ag: apply black

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

* gemm_ag: reset the election counters, add mode="auto", and wrap-safe waits

Review follow-up.

- The fused epilogue's election counters ran on and were tested modulo the
  chunk's tile count, which needed a counter set per M (GemmAgOp refused a
  ninth distinct M) and elects the wrong tile once a counter crosses 2^31,
  or 2^32 unless the count is a power of two. The tile that completes a
  chunk now puts its counter back to zero, as gemm_a2a does, in both the
  fp8 and the bf16 kernels; one counter set serves every M and chunk count,
  and max_shapes / the layout's shape slots are gone.
- _spin_until compares (int32)(cur - flag) < 0, like a2a_gemm's
  _spin_reach: the unsigned compare passed at once on the call whose epoch
  wraps to 0.
- GemmAgOp: mode="auto", now the default, fuses an M once even a 256x256
  tile's grid covers the CUs and splits below it. That fits every pair in
  the README's table, where the fused tile's round count (2 at both Pro
  M=4096 and 8192) does not; through the op at P=4 and P=8 it picks the
  faster path at M=2048, 4096 and 8192. fence and peer_uncached are
  exposed, defaulting to the README's sc_release. The CU count comes from
  the device. M pads to 128 (256 under mxfp8, or a pinned tile's BLOCK_M)
  instead of always 256; pick_tile already only picks tiles dividing M.
- Tests: one fused instance through ten distinct M with every counter back
  at zero afterwards; alternating M back to back with no host sync and a
  held reader on an auto instance that switches between fused and split,
  with the credit off as the negative control; the auto rule on the
  README's shapes; chunk-count and alternating cases pin mode="fused".

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

---------

Co-authored-by: xiangch <[email protected]>
Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
Co-authored-by: Xiang.Chen <x@x>
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