Skip to content

gemm_ar: fused GEMM + reduce-scatter for sequence parallelism - #802

Merged
yangyuhuiling merged 4 commits into
mainfrom
xiangch/gemm-rs
Nov 3, 2026
Merged

yangyuhuiling merged 4 commits into
mainfrom
xiangch/gemm-rs

Conversation

@yangyuhuiling

@yangyuhuiling yangyuhuiling commented Oct 19, 2026 •

Copy link
Copy Markdown
Contributor

Adds GemmReduceScatterOp to mori.ops.gemm_ar: the fused GEMM + all-reduce
pipeline stopped before the gather, for a sequence-parallel layer that keeps only
its own rows after a RowParallelLinear. Rank r gets [M/P, N] -- rows r*M/P
onward of the summed GEMM, the dim-0 split reduce_scatter_tensor makes.

This is the AMD counterpart of vllm-project/vllm#57428, which fuses
DeepSeek-V4.1's wo_b with its SP reduce-scatter on SM100. That kernel is built
on NVLink multicast (multimem.ld_reduce) and tcgen05, so none of it carries
over; the pipeline here already existed in gemm_ar minus a way to stop early.

No kernel is new. build_sdma_phases gains rs_order / fused_rs_order
(drain -> reduce -> rs_barrier), and GemmAllReduceOp's two hard-coded
choices -- the phase order and the output view -- become hooks the subclass
overrides. The all-reduce's behaviour is unchanged.

Results

Re-measured after merging main (2026-10-28). DeepSeek-V4.1-Flash wo_b,
[M, 5120] K=2048 mxfp8, 4x MI355X, bench_gemm_ar.py --collective rs --sdma-queues 1, graph replay, max over ranks, median of 3 interleaved rounds on
an idle box (spread <= 4.7% at M=2048, <= 2.7% above). split-rccl is the GEMM
followed by reduce_scatter_tensor -- what a serving stack runs today.

M gemm-only split-rccl split-sdma fused-sdma vs rccl vs split-sdma
2048 39.6 161.7 152.8 156.6 -3.2% +2.5%
4096 66.4 295.4 269.9 262.9 -11.0% -2.6%
8192 104.4 540.5 484.2 460.2 -14.9% -5.0%
16384 174.9 1065.3 917.3 834.5 -21.7% -9.0%

Two effects: the copy engines alone beat RCCL by 5-14%, and fusing then hides
about 83 of the 175us of GEMM at M=16384. At M=2048 there are only two chunks
per destination and fusing loses to the split path, so a caller should keep the
split form there. The full table and its reading are in the gemm_ar README.

This is a different box and stack from the first measurement (ROCm 7.2 /
FlyDSL 0.4.0 here, ROCm 7.14 / FlyDSL 0.3.4.1 then): the collectives, RCCL
included, run 3-8% slower in absolute terms, while the bare GEMM matches at
M >= 8192. The ordering and the fused path's margin hold: -21.7% against RCCL
at M=16384 (was -21.2%), -9.0% against the split SDMA path (was -11.2%).

Worth a reviewer's attention

  • rs_barrier is load-bearing. The gather used to end in a cross-rank
    barrier, and dropping the gather dropped it. The reduce reads recv slots the
    peers fill and the next call's epilogue refills them, so a rank one call ahead
    overwrote a slower peer's slot mid-reduce: intermittent in the alternating-M
    test (relL2 0.71), deterministic with one rank held between drain and reduce
    (0.99 / 1.01), 2.4e-3 with the barrier. test_reduce_scatter_survives_a_slow_reader
    holds a rank deliberately and is the regression test.
  • The padding decides the bands. M must be a multiple of
    world_size * block_m (1024 for mxfp8 at TP4) and the rows are split after
    that padding. main's fitted schedule="wo_b" plans (which pad some M to a
    non-band multiple) and scatter_dtype="fp8" are not exposed on this op, so
    the bands stay even; the benchmark rejects --collective rs with
    --scatter-dtype fp8. An SP layer that pads only to a multiple of world_size has to
    pad to this granule before it shards, or the two disagree on which rows each
    rank holds. Not addressed here.
  • The window is the all-reduce's, so it still carries a whole [m_max, N]
    output region of which this op writes 1/P. Shrinking it moves every region
    after it; left until the memory is shown to matter.
  • split-rccl validates at 3.15e-3 against everything else's 2.37e-3. RCCL
    adds the partials in bf16 hop by hop where the SDMA reduce accumulates in fp32;
    its benchmark gate is 6e-3 for that reason. The benchmark now also asks for a
    cuda:nccl backend alongside gloo, created lazily, so modes that never call
    RCCL do not pay for it.

Test plan

MORI_ENABLE_SDMA=1 pytest -q tests/python/cco/test_gemm_ar_op.py \
    tests/python/cco/test_gemm_ar.py tests/python/cco/test_gemm_ar_bench.py
MORI_ENABLE_SDMA=1 MORI_SOCKET_IFNAME=lo torchrun --standalone --nproc_per_node=4 \
    benchmark/cco/flydsl/gemm_ar/bench_gemm_ar.py --mode fused-sdma --collective rs \
    -m 16384 -n 5120 -k 2048 --quant mxfp8 --sdma-queues 1

118 passed on MI355X (gfx950), ROCm 7.2, FlyDSL 0.4.0, after merging main.
black clean; ruff adds nothing over main in the touched files.

Not in this PR

The vLLM / SGLang integration and its padding change, fp8 on the scatter leg,
TP8 and DeepSeek-V4-Pro shapes.

🤖 Generated with Claude Code

Xiang.Chen and others added 3 commits October 18, 2026 23:40
GemmReduceScatterOp: the fused GEMM + all-reduce pipeline stopped before
the gather. Rank r keeps rows [r*M/P, (r+1)*M/P) of the summed GEMM, the
dim-0 split reduce_scatter_tensor makes -- what a sequence-parallel layer
keeps after a RowParallelLinear. No kernel is new: build_sdma_phases gains
rs_order / fused_rs_order, and GemmAllReduceOp's two hard-coded choices
(phase order, output view) become hooks the subclass overrides.

The orders end in rs_barrier, a barrier-only push kernel standing in for
the one the gather used to provide. Without it a rank one call ahead
pushes into a slower peer's recv slot mid-reduce: intermittent in the
alternating-M test (relL2 0.71), deterministic with one rank held between
drain and reduce (0.99/1.01), 2.4e-3 with the barrier.

bench_gemm_ar.py gains --collective rs and a split-rccl mode (the GEMM
followed by RCCL all_reduce / reduce_scatter_tensor). DeepSeek-V4.1-Flash
wo_b, [M, 5120] K=2048 mxfp8, 4x MI355X, median of 3 interleaved rounds:
fused-sdma RS is 1.9/11.1/14.2/21.2% under split-rccl at
M=2048/4096/8192/16384, and 2.4% *over* split-sdma at M=2048, where only two
chunks per destination exist.

Co-Authored-By: Claude <[email protected]>
Conflicts: GemmAllReduceOp's self_test now pads a logical M (main) and
keeps the subclass-named close error (this branch); the worker runs both
mxfp8_raw and reduce-scatter cases; the README keeps main's wo_b schedule
notes ahead of the reduce-scatter section. The benchmark rejects
--collective rs with --scatter-dtype fp8, which main added and the
reduce-scatter op does not take.

Co-Authored-By: Claude <[email protected]>
ROCm 7.2 / FlyDSL 0.4.0 on 4x MI355X, same sweep as before: fused-sdma
stays -21.7% against GEMM + reduce_scatter_tensor at M=16384.

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.

I tested this on 8x MI355X (gfx950, ROCm 7.14, FlyDSL 0.4.0), with the PR merged onto current main. The op itself checks out. The regression test for rs_barrier no longer tests anything since the merge with main, and that should be fixed before this lands.

Your table reproduces. These are 4 ranks, --collective rs --sdma-queues 1, [M, 5120] K=2048 mxfp8, median of 3 interleaved rounds. The spread is 2% or less, and every mode validated.

M gemm-only split-rccl split-sdma fused-sdma vs rccl vs split-sdma
2048 35.2 155.6 145.6 149.0 -4.3% +2.3%
4096 63.4 290.9 266.5 253.0 -13.0% -5.1%
8192 103.9 537.2 485.1 452.0 -15.9% -6.8%
16384 179.2 1044.5 915.6 825.7 -20.9% -9.8%

What passed:

  • Test suites: test_gemm_ar_op.py (82 passed) and test_gemm_ar_bench.py (4 passed).

  • Reduce-scatter validation:

    • at 8 ranks;
    • with --quant blockscale;
    • in fused-lsa mode.
  • The all-reduce timing is unchanged from main.

  • A CUDA graph test that I added:

    • GemmReduceScatterOp.__call__ captured once and replayed 12 times with fresh operands;
    • a different rank started 50M cycles late on each replay;
    • eager calls at another M were mixed in.

    Every replay landed at the fp8 floor on all 4 ranks.

1. test_reduce_scatter_survives_a_slow_reader never holds a rank

gemm_ar_op_worker.py:403 and :409 write the held plan to op._cache[m] with an int key. Since #748, which this branch picked up when it merged main, _cache has been keyed by _RowPlan, and _compiled looks plans up with self._cache.get(row_plan). So the held tail is stored under a key nothing reads, and torch.cuda._sleep never runs.

I measured this with 2 ranks, the test's shape, and two runs per row. I counted the sleep calls and printed slow0..3 on every rank:

worker rs_barrier sleeps per rank slow0..3
as in the PR kept 0 all 2e-3
as in the PR removed 0 all 2e-3 (test passes)
key fixed removed 2 rank0: 0.99, 2e-3, 1.01, 2e-3; rank1: 2e-3, 1.04, 2e-3, 2e-3
key fixed kept 2 all 2e-3

So the test that the PR body and README name as the guard for this barrier passes without it. With the key fixed it catches the race exactly as you described (0.99 / 1.01). The fix is the pattern gemm_ar_schedule_worker.py already uses:

key = op._row_plan(m)
op._cache[key] = plan._replace(tail=tuple(held) if slow else fast)
...
op._cache[key] = plan

It would also help to have the inserted lambda count its calls, and to assert that the count is non-zero on the slow rank, so the test cannot quietly go vacuous again.

2. The reduce-scatter test only asserts rank 0

_emit prints only on rank 0, and rank 0's band offset (self.rank * cfg.slice_bytes) is always 0. That leaves out the part the case's docstring says it guards ("a wrong offset would still return at the right shape"). Rank 1 computes call*, vs_other_band and its own slow1/slow3, then drops them. Reducing the metrics across ranks before _emit would cover it: MAX for the errors, MIN for the booleans.

Smaller points

  • window_bytes_for drops quant and k. GemmReduceScatterOp.window_bytes_for accepts neither, and it defaults block_m to 128.
    • For an mxfp8 op it therefore sizes a blockscale window, which is smaller whenever m_max is not a multiple of world*256.
    • The README's recipe of passing the constructor's settings (quant=..., k=...) raises TypeError here.
    • Forwarding quant/k with block_m=None (the parent's default), or dropping the override, fixes both.
  • The README's M=2048 advice. It says to "keep the split form" at M=2048. split-sdma has no public op, though. The split form a caller actually has is GEMM + reduce_scatter_tensor, and the fused op beats that at every M measured here, M=2048 included.
  • A silently ignored bench flag. --collective rs --fuse-reduce-push runs the plain reduce but records fuse_reduce_push: true. It could be rejected the same way --gather-dtype fp8 is. The pinning loop also covers only order/fused_order, so rs_barrier runs unpinned under --eager.
  • A misleading error message. For an M that is not a granule multiple, the inherited _row_plan error tells the caller to "pass the original logical_m", which this op's __call__ does not accept.

Review follow-up for the reduce-scatter op.

- test_reduce_scatter_survives_a_slow_reader stored its held plan under
  op._cache[m], but since #748 the cache is keyed by the row plan, so the
  hold never ran and the test passed with rs_barrier removed. Key it by
  op._row_plan(m), count the holds and assert each rank's count, and rerun
  the same schedule without rs_barrier as a negative control that must
  corrupt a held rank's band.
- The reduce-scatter case only reported rank 0, whose band offset is 0.
  Fold every rank's verdicts before emitting: worst error, all booleans,
  smallest *_vs_other_band, per-rank counts.
- GemmReduceScatterOp.window_bytes_for takes k and quant and defaults
  block_m to None, so an mxfp8 op is sized for its own tile.
- An M off the granule now says to pad to padded_m(M), not to pass a
  logical_m this op does not take.
- bench: reject --collective rs --fuse-reduce-push instead of ignoring it,
  and pin the rs orders' phases too.
- README: the fused op beats GEMM + reduce_scatter_tensor at every M
  measured, M=2048 included; split-sdma has no public op.

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

Copy link
Copy Markdown
Contributor Author

Thanks for the careful review, and for pinning down the cache key. All of it is addressed in e94071e, as a commit on top of the branch.

1. The slow-reader test holds a rank again.

  • The held plan is now stored under op._row_plan(m).
  • The inserted hold counts its calls, and the test asserts each rank's count: [2, 2] at 2 ranks, [1, 1, 1, 1] at 4.
  • The same schedule is then rerun without rs_barrier as a negative control, and the test requires it to corrupt at least one call. This runs last in the case, because it leaves the recv slots in an unknown state.

Measured on 8x MI355X (ROCm 7.14, FlyDSL 0.4.0):

ranks slow0..3 (with barrier) unbarriered0..3
2 2.4e-3, 2.4e-3, 2.5e-3, 2.4e-3 0.99, 1.04, 1.01, 2.4e-3
4 all 2.4e-3 1.21, 1.25, 1.24, 2.4e-3

The last call is clean in both runs because nobody runs a call after it.

2. Every rank is checked. The reduce-scatter case folds all ranks' verdicts before rank 0 prints:

  • errors take the worst rank;
  • booleans must hold on every rank;
  • *_vs_other_band takes the smallest value, since it has to be large everywhere;
  • hold counts stay per rank.

Smaller points:

  • GemmReduceScatterOp.window_bytes_for now takes k and quant, with block_m=None. For mxfp8 it now matches GemmAllReduceOp.window_bytes_for exactly, checked at m_max = 1000, 2048 and 3000.
  • README: the M=2048 advice is gone. It now says the fused op beats GEMM + reduce_scatter_tensor at every M measured, and that split-sdma has no public op. It also shows window_bytes_for with the constructor's settings.
  • bench: --collective rs --fuse-reduce-push now exits with an error. Pinning covers rs_order / fused_rs_order too, so rs_barrier is pinned under --eager.
  • An M that is not a granule multiple now gets a reduce-scatter-specific error: pad to padded_m(M) before sharding.

test_gemm_ar_op.py (82 passed) and test_gemm_ar_bench.py (4 passed) pass on the same node.

@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 e94071eb, merged onto current main, on MI355X (ROCm 7.14, FlyDSL 0.4.0), at 4 and 8 ranks. Every point is addressed. LGTM.

  • Tests. test_gemm_ar_op.py passes (82 tests), and so does test_gemm_ar_bench.py on 8 GPUs (4 tests).

  • The slow-reader case now really holds a rank. The worker's reduce_scatter record, folded over all ranks:

    4 ranks (M = 512 / 1024) 8 ranks (M = 2048 / 4096)
    slow0..3 2.37e-3 each 2.35e-3 each
    unbarriered control 1.21 / 1.25 / 1.24 / 2.4e-3 1.32 / 1.34 / 1.33 / 2.4e-3
    vs_other_band ≈ 1.41 ≈ 1.41

    So the negative control does catch a missing rs_barrier, and each band is checked against the next rank's band too.

  • The smaller points are fixed: window_bytes_for takes k/quant, the RS-specific padding error, --collective rs --fuse-reduce-push is rejected, the rs orders are pinned, and the README's M=2048 advice is gone.

@yangyuhuiling
yangyuhuiling merged commit 5ba750b into main Nov 3, 2026
14 checks passed
yangyuhuiling pushed a commit that referenced this pull request Nov 4, 2026
- test_gemm_ar.py, through the benchmark on 2 ranks: gemm-only, split and
  fused at an odd K step count (K=192), K_ITERS == 2 (K=128), Kimi-K3's
  K per rank (768, 1536), the 128-row tile, reduce-scatter only, and the
  fp8 gather over LSA. The bench validates every row against fp32.
- The op worker: GemmAllReduceOp(quant="bf16") over two M with fresh
  operands, the fp8 gather, and the operand checks; and the reduce-scatter
  case -- self-test and its teeth, band ownership, the slow reader and its
  no-barrier negative control -- run for quant="bf16" as well as
  blockscale. GemmReduceScatterOp(quant="bf16") takes the BF16 path with
  no scales.
- The merge with main dropped GemmAllReduceOp.reduce_scatter() in favour of
  main's GemmReduceScatterOp (#802), which runs the same tail, along with
  the now-duplicate rs_barrier / fused_rs_order; these tests cover it.

Co-Authored-By: Claude <[email protected]>
yangyuhuiling added a commit that referenced this pull request Nov 9, 2026
… in BF16 (#872)

* feat(gemm-ar): BF16 GEMM + all-reduce for layers the checkpoint keeps in BF16

The fused GEMM only compiles against an fp8 contract (ptpc, blockscale,
mxfp8), so a layer kept in BF16 -- Kimi-K3 quantises only its routed
experts, leaving attention o_proj and the shared experts BF16 -- could not
use it without quantising weights the checkpoint deliberately left alone.

kernels_fused_bf16.compile_fused_gemm_scatter_bf16 builds the same operator
at BF16: the mainloop is the a16w16 quad-subtile pipeline (the same opus
template the fp8 kernel renders, v_mfma_f32_16x16x32_bf16, BLOCK_K=64, no
scales); the tile order and epilogue tail -- destination-rotated chunk-major
walk, per-(dest, chunk) counter, locked elected SDMA put -- are
kernels_fused.py's. C is BF16 either way, so build_sdma_phases is reused
unchanged. Default fused-SDMA shape only (no chunk_bands, relaxed_rows, FP8
scatter or LSA transport). The launch keeps the fp8 signature; the scale
arguments are accepted and unread.

_gemm_a16w16_8wave holds the BF16 building blocks from gemm_ag (#807),
copied unchanged. bench_gemm_ar.py gains --quant bf16.

8x MI355X, N=7168 (K3 TP8), 2 rounds, median of max-over-ranks, against a
BF16 hipBLASLt GEMM + RCCL all-reduce (sglang's ROCm path at these sizes):

  K/rank   M       baseline   bf16 fused       + fp8 gather
  1536     2048     243us     206 (-15.2%)     183 (-24.8%)
  1536     4096     438       346 (-21.0%)     293 (-33.1%)
  1536     8192     761       612 (-19.5%)     509 (-33.1%)
  1536    16384    1421      1150 (-19.1%)     938 (-34.0%)
   768     2048     227       191 (-15.7%)     168 (-25.9%)
   768     4096     410       329 (-19.8%)     277 (-32.5%)
   768     8192     700       598 (-14.5%)     491 (-29.8%)
   768    16384    1309      1134 (-13.4%)     921 (-29.6%)

Validated every run: GEMM-only relL2 1.66e-3 and all-reduce 2.35e-3 (the
BF16 output rounding floor) at K=128/192/768/1536 including K_ITERS=2 and
odd, three repeats identical to 0.8us; fp8 gather 2.49e-2 as expected.

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

* feat(gemm-ar): quant='bf16' in GemmAllReduceOp

The op owns the window, the per-M compile cache, the row padding and the
self-test; with quant='bf16' it compiles kernels_fused_bf16 and takes BF16 A
and a row-major BF16 B with no scales. Constraints follow the BF16 mainloop
(K % 64, K >= 128, block_m 128 or 256, bf16 scatter only).

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

* feat(gemm-ar): reduce-scatter-only BF16 GEMM, for callers that keep rows sharded

GemmAllReduceOp.reduce_scatter() runs the fused GEMM and the reduce, and stops:
each rank gets its reduced [M / world_size, N] row band, and nothing is
all-gathered. A caller whose next stage reads only its own token shard
(sglang's SP-MoE: EP a2a with attention TP) then pays for half the all-reduce.

The gather's barrier stays, as a push kernel with no puts on the gather's
signal row: without it the next call's epilogue puts can land in a peer's
recv slot while that peer is still reducing this call's. The tail is
compiled with the rest of the phases (parts["fused_rs_order"]) and pinned
next to the all-reduce one, so one op serves both on the same window.

BF16, bf16 wire only. 8x MI355X, M=16384 N=7168 K=1536 (Kimi-K3 o_proj):
GEMM + RS 636 us vs torch.mm + RCCL reduce_scatter 885 us (GEMM + AR 1145 us).
300 calls at ragged M, interleaving reduce-scatter and full all-reduce on
the same op, all within relL2 1.7e-3 of GEMM + RCCL.

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

* gemm_ar, gemm_ag: one copy of the BF16 GEMM's building blocks

gemm_ar/_gemm_a16w16_8wave.py and gemm_ag/_gemm_a16w16_8wave.py (#807)
carried the same ~590 lines: LDS swizzle, S2R loader, MFMA, C store and
tile constants. They now live once, in gemm_ar, which gemm_ag already
depends on; gemm_ag's file keeps compile_bf16_gemm_ag and the measured
tile and chunk rules, and imports the rest. gemm_ag's account of the port
moves with the code it describes.

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

* gemm_ar: black and ruff

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

* gemm_ar: test the BF16 GEMM + all-reduce and reduce-scatter

- test_gemm_ar.py, through the benchmark on 2 ranks: gemm-only, split and
  fused at an odd K step count (K=192), K_ITERS == 2 (K=128), Kimi-K3's
  K per rank (768, 1536), the 128-row tile, reduce-scatter only, and the
  fp8 gather over LSA. The bench validates every row against fp32.
- The op worker: GemmAllReduceOp(quant="bf16") over two M with fresh
  operands, the fp8 gather, and the operand checks; and the reduce-scatter
  case -- self-test and its teeth, band ownership, the slow reader and its
  no-barrier negative control -- run for quant="bf16" as well as
  blockscale. GemmReduceScatterOp(quant="bf16") takes the BF16 path with
  no scales.
- The merge with main dropped GemmAllReduceOp.reduce_scatter() in favour of
  main's GemmReduceScatterOp (#802), which runs the same tail, along with
  the now-duplicate rs_barrier / fused_rs_order; these tests cover it.

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

---------

Co-authored-by: Xiang.Chen <[email protected]>
Co-authored-by: Claude <[email protected]>
@QizhouZhang97
QizhouZhang97 deleted the xiangch/gemm-rs branch November 10, 2026 13:19
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