Skip to content

[HIP] [JIT] [Feature] Custom allreduce: fused residual add and row-selective RMSNorm - #6270

Merged
junhaha666 merged 6 commits into
ROCm:mainfrom
yuychang:k3/allreduce-residual-rmsnorm
Oct 30, 2026
Merged

junhaha666 merged 6 commits into
ROCm:mainfrom
yuychang:k3/allreduce-residual-rmsnorm

Conversation

@yuychang

@yuychang yuychang commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Adds custom_all_reduce_residual (all-reduce + residual add in one kernel) and fused AR+RMSNorm row options (num_norm_rows, skip_residual) for Kimi-K3.

Motivation

Kimi-K3's o_proj all-reduce is followed by a residual add, and its [latent | shared] all-reduce normalizes only the latent rows; both run as all-reduce plus separate kernels. SGLang side: sgl-project/sglang#43130.

Changes

  • AR + residual: HAS_RESIDUAL on the 1-stage, 2-stage, naive and write-mode kernels adds the residual after rounding, matching all-reduce then add.
  • Perf guard: returns None above _AR_RESIDUAL_MAX_BYTES (gfx942 TP2 10 MiB, TP4 14 MiB; other gfx942/gfx950 TPs unbounded) and for unlisted (arch, TP) pairs.
  • Row options: 2-stage only; keep to ≤80 rows (slower above). 2-stage AR+RMSNorm with ≤80 rows now runs as one kernel.
  • Build: new instances in custom_all_reduce_ext.cu (17.1 s vs. 17.2 s build wall).

Performance (if applicable)

bf16, n = 7168, µs per call: graph of 20 calls, slowest rank, median of 5; MI300X on 98d8275, MI355X at head (mean of two rounds).

Hardware TP fused vs. all-reduce + add, M = 1–4096 Bound
MI300X 8 faster at every M (M=8: 9.34 → 7.41 µs, M=4096: 402.49 → 336.02 µs) none
MI300X 6 faster at M = 6–4096 (M=1024: 221.44 → 201.89 µs) none
MI300X 4 faster up to 14 MiB; up to 6% slower above 14 MiB
MI300X 2 faster up to 10 MiB; up to 6% slower above 10 MiB
MI355X 8 1.07x–1.32x faster at every M (M=8: 8.99 → 7.17 µs) none
MI355X 6 1.07x–1.15x faster at M ≥ 6; at M ≤ 5 all-reduce faults, only fused runs none
MI355X 4 1.03x–1.29x faster at every M none
MI355X 2 1.004x–1.14x faster at every M (0.4–1.6% from 14 MiB) none (was: fall back)
Graph-loop timing script
# python bench_graph_loop.py <tp> <out.json> <m,n> ...   (PYTHONPATH=<aiter tree>)
import json
import statistics
import sys

import torch
import torch.distributed as dist

K, R, REPS, WARMUP = 20, 10, 5, 3


def capture(ca, fn):
    graph = torch.cuda.CUDAGraph()
    stream = torch.cuda.Stream()
    stream.wait_stream(torch.cuda.current_stream())
    with ca.capture(), torch.cuda.graph(graph, stream=stream):
        for _ in range(K):
            fn()
    torch.cuda.current_stream().wait_stream(stream)
    dist.barrier()
    return graph


def time_graph(graph):
    for _ in range(WARMUP):
        graph.replay()
    torch.cuda.synchronize()
    samples = []
    for _ in range(REPS):
        start = torch.cuda.Event(enable_timing=True)
        end = torch.cuda.Event(enable_timing=True)
        dist.barrier()
        start.record()
        for _ in range(R):
            graph.replay()
        end.record()
        end.synchronize()
        us = start.elapsed_time(end) * 1e3 / (R * K)
        worst = [None] * dist.get_world_size()
        dist.all_gather_object(worst, us)
        samples.append(max(worst))
    return samples


def worker(rank, tp, shapes, init_method, out_path):
    from aiter.dist.device_communicators.custom_all_reduce import CustomAllreduce

    torch.cuda.set_device(rank)
    dist.init_process_group("gloo", world_size=tp, rank=rank, init_method=init_method)
    ca = CustomAllreduce(dist.group.WORLD, torch.device(f"cuda:{rank}"))
    assert not ca.disabled
    fuses = ca.should_fuse_ar_residual
    ca.should_fuse_ar_residual = lambda inp: True
    keep, rows = [], []
    for m, n in shapes:
        x = torch.randint(-8, 9, (m, n), device="cuda").to(torch.bfloat16)
        res = torch.randint(-8, 9, (m, n), device="cuda").to(torch.bfloat16)
        row = {"tp": tp, "m": m, "n": n, "fuses": fuses(x)}
        for name, fn in (
            ("split", lambda: ca.custom_all_reduce(x) + res),
            ("fused", lambda: ca.custom_all_reduce_residual(x, res)),
        ):
            graph = capture(ca, fn)
            keep.append(graph)  # peer IPC addresses are cached by pointer
            row[name] = time_graph(graph)
        rows.append(row)
    if rank == 0:
        json.dump(rows, open(out_path, "w"))
    torch.cuda.synchronize()
    dist.barrier()
    ca.close()
    dist.destroy_process_group()


def main():
    from aiter.dist.utils import get_distributed_init_method, get_ip, get_open_port

    tp, out_path = int(sys.argv[1]), sys.argv[2]
    shapes = [tuple(int(v) for v in s.split(",")) for s in sys.argv[3:]]
    init_method = get_distributed_init_method(get_ip(), get_open_port())
    torch.multiprocessing.spawn(
        worker, args=(tp, shapes, init_method, out_path), nprocs=tp, join=True
    )
    for row in json.load(open(out_path)):
        s, f = statistics.median(row["split"]), statistics.median(row["fused"])
        print(
            f"tp={row['tp']} m={row['m']:5d} n={row['n']} fuses={row['fuses']!s:5} "
            f"split {s:8.2f} [{min(row['split']):.2f}-{max(row['split']):.2f}] "
            f"fused {f:8.2f} [{min(row['fused']):.2f}-{max(row['fused']):.2f}] "
            f"ratio {f / s:.3f}"
        )


if __name__ == "__main__":
    main()

Testing

  • Unit tests added or updated
  • Performance benchmarks run
  • Tested on MI250X
  • Tested on MI300X

Documentation

  • Docstrings updated
  • User guide updated
  • Performance guide updated
  • No documentation change is needed, with the reason stated below

Internal communicator API; its contract is in the docstrings.

Dependencies

  • No new third-party dependencies added
  • New dependencies are listed and justified below

Breaking Changes

None.

PR Self-Review

Reviewed revision

3e80e61

Behavior and intent

New fused entry points serve Kimi-K3; existing callers keep their kernels. custom_all_reduce_residual fuses only where measured faster, so a caller is never slower than its previous all-reduce + add.

Validation and unverified scope

  • op_tests/multigpu_tests/test_custom_allreduce_residual.py -t 8 6 4 2 -s 1,7168 ... 1,819208 on MI300X and MI355X → every err 0, eager and graph, incl. write mode and guard-declined shapes.
  • pytest tests/test_custom_ar_residual_guard.py tests/test_custom_ar_fused_rms_row_options.py → 25 passed.
  • Plain custom_all_reduce, TP6, MI355X → Memory access fault at M = 1, 2, 5 on main and head.
  • Unverified: hidden sizes other than 7168; MI250X. On main too: repeated graph replays of plain bf16 all-reduce and of AR+RMSNorm above 80 rows hang intermittently.

PR-specific question

Which architecture, dtype and shape boundaries select the changed kernel path, and what invariant prevents unsupported inputs from reaching it?

  • Arch: gfx942 and gfx950 (gfx1250 returns None); write mode only on gfx942 TP8 above 4 MiB.
  • Dtype: fp32, fp16, bf16; anything else throws.
  • Shape: must fill 16-byte packs; above the (arch, TP) bound the API returns None.
  • Invariants: residual identical on every rank (documented); contiguity, numel, dtype and device checked before launch; row options raise outside 2-stage, unpadded, non-quant kernels.

Changed op tests

  • op_tests/multigpu_tests/test_custom_allreduce_residual.py (new): new entry points vs. an exact reference, eager and graph, plus error paths; no existing test covers them.
  • op_tests/multigpu_tests/test_custom_allreduce_residual_perf.py (new): times fused vs. split and shows where the API falls back.

🤖 Generated with Claude Code

@github-actions

github-actions Bot commented Oct 8, 2026

Copy link
Copy Markdown
Contributor

🏷️ CI Guide

Runs automatically on every PR:

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

Extended tests (opt-in via labels):

Label Tests
ci:gfx1250-ffm-triton Run the five-shard gfx1250 FFM Triton test suite
ci:triton-300x Run an additional Triton test job on MI300X in PRs (added automatically when gfx942 configs change); main branch always runs both MI35X and MI300X
ci:triton-355 Run the full Triton test suite on MI35X, not only the tests the change affects
ci:multi-gpu Aiter multi-GPU tests on the 8-GPU runner
ci:sglang SGLang integration tests: DeepSeek-R1-MXFP4 accuracy, Qwen 3.5 accuracy
ci:atom ATOM benchmark: DeepSeek-R1-0528, GPT-OSS-120B
ci:atom_full ATOM accuracy suite for PR and main models from ATOM models_accuracy.json
ci:vllm vLLM benchmark: GPT-OSS-120B, DeepSeek-R1-0528, Kimi-K2.5
ci:all All standard extended tests (excludes ci:atom_full)

Only add ci:atom_full for FlyDSL or Triton upgrades.
Add labels via the sidebar or gh pr edit 6270 --add-label <label>

One backend per PR:
A PR changes one kernel backend: [Triton/Gluon] (Triton and Gluon count as one), [HIP], [ASM], [CK], [OPUS] or [FlyDSL]. If the title ends up with two backend tags, split the PR -- as stacked pull requests when one part cannot merge without the other.

PR title tags & labels:
Component tags ([Triton/Gluon], [HIP], [CK], [ASM], ...) are added to the PR title and as PR labels automatically from the changed files and re-synced on every push — change-type tags like [fix]/[Perf], op tags like [MLA], and human labels (ci:*) are left untouched. Add the no-auto-title label to stop the title rewrites; labels stay in sync either way.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 Changes recommended

TP6 dispatch can access memory out of bounds, and several new output-buffer paths lack required extent and device validation.

3 open findings
What changed in this PR

Adds fused custom all-reduce paths for residual addition and row-selective RMSNorm.

Changes:

  • Adds fused 1-stage/2-stage all-reduce plus residual kernels.
  • Adds selective RMSNorm rows and residual skipping.
  • Adds eager and CUDA graph correctness tests.
File Description
op_tests/​multigpu_tests/​test_custom_allreduce_residual.py Tests new fused operations.
csrc/​kernels/​custom_all_reduce.cu Adds native dispatch entry points.
csrc/​include/​rocm_ops.hpp Exposes operations through pybind.
csrc/​include/​custom_all_reduce.h Declares new native APIs.
csrc/​include/​custom_all_reduce.cuh Implements kernels and dispatch.
aiter/​ops/​custom_all_reduce.py Adds Python operation declarations.
aiter/​dist/​device_communicators/​custom_all_reduce.py Adds communicator APIs and option handling.

🧠 Review effort: Balanced


💡 Configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

Comment thread csrc/include/custom_all_reduce.cuh Resolved
Comment thread csrc/kernels/custom_all_reduce.cu Resolved
Comment thread csrc/include/custom_all_reduce.cuh Resolved
Copilot AI balanced review requested due to automatic review settings October 13, 2026 15:07

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 Changes recommended

Selective output bounds, uninitialized rows, numerical compatibility, and TP6 coverage need correction.

2 open findings
3 resolved since last review
Previously missed (1)

In code that hasn't changed since last review

Medium severity Fused path rounds residual sum before RMSNorm

csrc/​include/​custom_all_reduce.cuh:3200

The new single-kernel path changes existing fused-AR+RMSNorm numerics: this T-typed vec += res rounds the residual sum to bf16/fp16 before RMSNorm, while the previous local kernel upcasts both operands and normalizes the unrounded fp32 sum. For 2-stage calls with at most 80 rows this can change the returned norm (for example, a bf16 input can differ by one ULP), despite the PR describing existing API behavior as unchanged. Accumulate into acc in fp32, downcast only for residual_out, and pass the fp32 accumulator to the epilogue.

🧠 Review effort: Balanced

Comment thread csrc/kernels/custom_all_reduce.cu Resolved
Copilot AI balanced review requested due to automatic review settings October 13, 2026 15:21
@github-actions github-actions Bot changed the title [HIP] Custom allreduce: fused residual add and row-selective RMSNorm [HIP] [CI] Custom allreduce: fused residual add and row-selective RMSNorm Oct 13, 2026
@github-actions github-actions Bot added the CI label Oct 13, 2026

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 Changes recommended

Padded calls can silently ignore row options, and uses_1stage_ar reports incorrect results on gfx1250.

0 open findings

5 resolved since last review

🧠 Review effort: Balanced

@yuychang

Copy link
Copy Markdown
Contributor Author

Addressing the two points in Copilot's latest review summary (no inline threads were opened for them), fixed in 24e01d5:

  • Padded calls ignoring row options: fused_ar_rms checked the output width only when the caller passed out. With out=None and a padded out_hidden_dim, it allocated a padded output, took fused_allreduce_rmsnorm_pad, and silently dropped num_norm_rows/skip_residual. The check now uses the effective output width, so that call raises ValueError.
  • uses_1stage_ar on gfx1250: all_reduce_gfx1250 only runs one-shot kernels (the LL path and ar_gfx1250_naive_unroll4), so uses_1stage_ar now returns True there instead of applying the old-arch size thresholds.

Both have new checks in test_custom_allreduce_residual.py that fail on the previous commit. The gfx1250 case is simulated by setting _is_gfx1250, since I validated on MI355X. Results: TP8+TP6 (the CI command), TP2 and TP4 all pass.

Copilot AI balanced review requested due to automatic review settings October 13, 2026 15:36

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 Changes recommended

The new single-kernel path rounds before RMSNorm, changing existing fp16/bf16 results.

1 open finding

🧠 Review effort: Balanced

Comment thread csrc/include/custom_all_reduce.cuh Resolved
@zufayu
zufayu requested a review from junhaha666 October 14, 2026 01:29
Copilot AI balanced review requested due to automatic review settings October 14, 2026 10:04

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 Changes recommended

The new single-kernel path has shape and numerical correctness issues, while caller-provided output handling remains unsafe and inconsistent.

3 open findings

🧠 Review effort: Balanced

Comment thread csrc/include/custom_all_reduce.cuh Resolved
Comment thread csrc/kernels/custom_all_reduce.cu Resolved
Copilot AI balanced review requested due to automatic review settings October 14, 2026 10:11

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🔵 Needs a closer look

The new kernel path has RMSNorm reduction and precision errors, while exposed buffers and layouts need stronger validation.

3 open findings

🧠 Review effort: Balanced

Copilot AI balanced review requested due to automatic review settings October 14, 2026 13:46

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🔵 Needs a closer look

The default multi-GPU dispatch and quantization changes require hardware validation unavailable in this review environment to establish correctness, synchronization, graph replay, and latency, while reported graph/quant hangs remain unresolved.

No open issues 🎉

Review effort: Balanced

Copilot AI balanced review requested due to automatic review settings October 29, 2026 02:24
@yuychang
yuychang force-pushed the k3/allreduce-residual-rmsnorm branch from d1f6e2f to c3a5e21 Compare October 29, 2026 02:24

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🔵 Needs a closer look

Changes to the default multi-GPU RMSNorm dispatch and cross-device kernels lack independent GPU correctness, graph-replay synchronization, and base/head performance validation in this source-only review.

No open issues 🎉

Review effort: Balanced

@junhaha666

junhaha666 commented Oct 29, 2026 •

Copy link
Copy Markdown
Contributor

@yuychang Thanks for this work. I understand that this PR is primarily targeted and tuned for MI350 (gfx950). As an additional compatibility check, I tested it on 8x MI300X (gfx942), ROCm 7.2.4, and PyTorch 2.10.0. The new unit tests and targeted TP2/TP6/TP8 correctness tests passed, including eager mode and one CUDA Graph replay. The PR also merged cleanly into the latest origin/main available in the container.

I did, however, observe a significant TP8 performance regression in custom_all_reduce_residual:

Shape Fused residual Custom AR + add
M=8, N=7168 73.05 us 30.96 us
M=64, N=7168 73.03–73.31 us 32.05–32.62 us

The test reports eager end-to-end GPU time and sums all kernels in each path. Since the fused path is more than 2x slower for these common gfx942 TP8 shapes, could you please add a code-level performance guard or fallback? For example, custom_all_reduce_residual could return None for benchmarked non-beneficial configurations so the caller uses custom_all_reduce(input) + residual.

A runtime warning alone would not prevent the regression and may add noise to inference logs. A short code comment documenting the guard and a small gfx942 TP8 size sweep to determine the crossover would be preferable.

I did not find a correctness blocker for the MI350-targeted change. My concern is specifically that, if this API is also enabled for MI300X, the TP8 performance regression should be guarded or documented in code.

@yuychang
yuychang force-pushed the k3/allreduce-residual-rmsnorm branch from c3a5e21 to d03e4ca Compare October 29, 2026 08:04
Copilot AI balanced review requested due to automatic review settings October 29, 2026 08:04
@github-actions github-actions Bot changed the title [HIP] [Feature] Custom allreduce: fused residual add and row-selective RMSNorm [HIP] [JIT] [Feature] Custom allreduce: fused residual add and row-selective RMSNorm Oct 29, 2026
@github-actions github-actions Bot added the JIT label Oct 29, 2026

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🔵 Needs a closer look

Registered graph capture with use_1stage=True can corrupt reductions when outputs overlap input, because writes occur before slower ranks finish reading the aliased input.

No open issues 🎉

Review effort: Balanced

- Add a HAS_RESIDUAL template flag to cross_device_reduce_1stage, _2stage and _2stage_naive; plain AR compiles as before
- The kernels round the reduced value to T before adding the residual, matching all-reduce followed by a separate add
- 1-stage adds in the reduce loop; the 2-stage kernels add in the all-gather write-back
- Factor the 1-/2-stage crossover into select_ar_stage, shared by allreduce and the new allreduce_residual
- allreduce_residual sends TP6 and 2-stage sizes whose packs do not split evenly across ranks to the naive kernel
- The residual kernels write only the local output, so no output buffer is looked up or registered
- New all_reduce_residual op (C++ entry point, pybind binding, Python stub) checks inp, out and residual layout
- CustomAllreduce gets all_reduce_residual, custom_all_reduce_residual and uses_1stage_ar
- custom_all_reduce_residual returns None when custom AR is disabled, on gfx1250 or for a non-contiguous input
- TP2 is always 1-stage (select_ar_stage), so allreduce_residual instantiates only the 1-stage kernel there
- all_reduce_residual lives in custom_all_reduce_ext.cu, a second module TU, so its kernels build in parallel

- A direct all_reduce_residual call on gfx1250, which has no such kernel, raises NotImplementedError
- fused_allreduce_rmsnorm takes num_norm_rows (normalize only the first N rows) and skip_residual (do not read res_inp)
- Every row still gets residual_out; num_norm_rows < 0 or >= m means every row, as before
- The options run on the 2-stage paths only; the 1-stage, padded and quant paths reject them
- Up to kFusedArRms2StageMaxRows (kMaxBlocks = 80) rows, 2-stage fused AR+RMSNorm runs as one kernel, one block per row
- The single kernel needs n / pack_size in whole 32-lane groups: ar_fusion_epilogue_block_reduce drops a partial one
- allreduce_fusion_kernel_2stage adds the residual in fp32 and rounds only residual_out, as the 1-stage kernel does
- The per-token-quant 2-stage path shares that kernel, so it now matches its 1-stage counterpart as well
- Above 80 rows the reduce-scatter + local RMSNorm path stays; its kernels get a ROW_OPTS flag for the row options
- Plain calls use ROW_OPTS=false, which compiles to main's code; the launch macros collapse into LAUNCH_LOCAL_RMSNORM
- Step 2 moves to CustomAllreduce::localRMSNorm<T, ROW_OPTS>, the single kernel to fusedAllReduceRMSNorm2Stage<T>
- Their ROW_OPTS=true and single-kernel instances are extern in the header and build in custom_all_reduce_ext.cu
- module_fused_ar_mhc, which also builds custom_all_reduce.cu, adds custom_all_reduce_ext.cu
- Drop the tnum=256 arms that never run: 64 <= n_packs < 256 always takes local_device_load_rmsnorm<T, 256, 1>
- fused_allreduce_rmsnorm and fused_allreduce_rmsnorm_pad check out/res_out/res_inp/w extent, dtype, device, contiguity
- Python: fused_ar_rms and custom_fused_ar_rms pass residual_out, out, num_norm_rows and skip_residual through
- custom_fused_ar_rms graph warmup returns the caller's out and residual_out, zeroed, instead of new full-size tensors
- Apply clang-format to the touched _fused_allreduce_rmsnorm and fused_allreduce_rmsnorm signatures and calls

- The gfx1250 fused_allreduce_rmsnorm op takes 11 arguments and has no num_norm_rows / skip_residual
- fused_ar_rms passes the two row options only on the other archs, so gfx1250 calls keep their 11 arguments
- On gfx1250 a caller asking for skip_residual or num_norm_rows < rows gets a ValueError
- can_fuse_ar_rms now checks out_dim, the width the call writes, including a caller-provided out
- A padded out on gfx1250 used to pass that check and reach fused_allreduce_rmsnorm_pad, which gfx1250 lacks
- Other archs are unchanged: can_fuse_ar_rms returns True there
- tests/test_custom_ar_fused_rms_row_options.py checks the 11/13-argument split with a fake op, GPU-free
- New op_tests/multigpu_tests/test_custom_allreduce_residual.py in the op_test format: @benchmark, checkAllclose
- all_reduce_residual vs. custom_all_reduce + add, with 1/64-multiple inputs that round in bf16, at 1- and 2-stage
- fused_ar_rms num_norm_rows / skip_residual vs. a torch reference; reduced values are exact and compared at atol=0
- Per-token-quant fused AR+RMSNorm 2-stage output, scales and residual_out must equal 1-stage bit for bit
- Every case runs eagerly and on one CUDA graph replay; tables report eager time with a gfx column
- Rejection cases: 1-stage, padded and quant row options, short, strided or wrong-dtype buffers, a bad out
- Capture paths: warmup returns the caller's zeroed buffers, and a non-exportable input raises at capture
- -t takes a list of TP sizes and defaults to 8 6, so a plain run covers TP6, which takes the naive kernel
- Ranks run under torch.multiprocessing.spawn; the script is gated on gfx942/gfx950
- New test_custom_allreduce_residual_perf.py times the fused residual AR and row-option paths vs. the split ones
- It also runs on trees without the fused ops (their columns stay empty), so one command times base and head
- Its tables give the fastest and slowest rank per candidate; -g 1 times graph replays instead of eager calls

- The caller-provided out is allocated once outside the timed call
…-mode switch

- Plain all-reduce on gfx942 TP8 takes the write-mode kernel above 4 MiB; the residual path had no such variant.
- cross_device_reduce_2stage_write_mode gets HAS_RESIDUAL: the reducing rank adds the residual before it sends.
- select_ar_write_mode() holds the switch for allreduce and allreduce_residual and reads the arch via get_gpu_arch().
- allreduce_residual writes peer outputs in graph mode like allreduce; all_reduce_residual checks out can be exported.
- MI300X TP8 M=1024-4096: fused goes from 1.04x-1.35x slower to 1.17x-1.20x faster than all-reduce + add.
…al is not faster

- custom_all_reduce_residual returns None above _AR_RESIDUAL_MAX_BYTES for its (arch, TP), and for pairs not listed.
- Bounds are timed end to end on CUDA graphs: gfx942 TP2 10 MiB and TP4 14 MiB; above them fused was up to 6% slower.
- gfx942 TP6/TP8 and gfx950 TP4/TP6/TP8 have no bound; at TP6 the fallback faults on 1-stage sizes, on main too.
- The correctness test also runs the kernel at sizes the API declines; the perf test adds a fuses column.
- New tests/test_custom_ar_residual_guard.py: bounds, declined calls, out export and the shared write-mode switch.
@yuychang
yuychang force-pushed the k3/allreduce-residual-rmsnorm branch from d03e4ca to 98d8275 Compare October 29, 2026 14:56
Copilot AI balanced review requested due to automatic review settings October 29, 2026 14:56
@aiter-bot

aiter-bot commented Oct 29, 2026 •

Copy link
Copy Markdown

READY FOR HUMAN REVIEW

PR Self-Review

Revision 3e80e61f3431 · mode shadow

Author self-review accepted. Readiness report:

Author answers

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

Behavior and intent

New fused entry points serve Kimi-K3; existing callers keep their kernels. `custom_all_reduce_residual` fuses only where measured faster, so a caller is never slower than its previous all-reduce + add.

Validation and unverified scope

- `op_tests/multigpu_tests/test_custom_allreduce_residual.py -t 8 6 4 2 -s 1,7168 ... 1,819208` on MI300X and MI355X → every `err` 0, eager and graph, incl. write mode and guard-declined shapes.
- `pytest tests/test_custom_ar_residual_guard.py tests/test_custom_ar_fused_rms_row_options.py` → 25 passed.
- Plain `custom_all_reduce`, TP6, MI355X → `Memory access fault` at M = 1, 2, 5 on main and head.
- Unverified: hidden sizes other than 7168; MI250X. On main too: repeated graph replays of plain bf16 all-reduce and of AR+RMSNorm above 80 rows hang intermittently.

PR-specific question

_Which architecture, dtype and shape boundaries select the changed kernel path, and what invariant prevents unsupported inputs from reaching it?_

- **Arch:** gfx942 and gfx950 (gfx1250 returns `None`); write mode only on gfx942 TP8 above 4 MiB.
- **Dtype:** fp32, fp16, bf16; anything else throws.
- **Shape:** must fill 16-byte packs; above the (arch, TP) bound the API returns `None`.
- **Invariants:** `residual` identical on every rank (documented); contiguity, numel, dtype and device checked before launch; row options raise outside 2-stage, unpadded, non-quant kernels.

Changed op tests

- `op_tests/multigpu_tests/test_custom_allreduce_residual.py` (new): new entry points vs. an exact reference, eager and graph, plus error paths; no existing test covers them.
- `op_tests/multigpu_tests/test_custom_allreduce_residual_perf.py` (new): times fused vs. split and shows where the API falls back.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

PR state

  • PASS — pull request is marked ready for review

Copilot findings

  • PASS — no active Copilot finding lacks a substantive author reply

Code and op-test hygiene

  • PASS — no committed artifact or conflict marker detected

Required CI

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

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

@yuychang

yuychang commented Oct 29, 2026 •

Copy link
Copy Markdown
Contributor Author

@junhaha666 Thanks for testing on MI300X. I reproduced on 8x MI300X (ROCm 7.2, torch 2.11) and pushed the fix in f9ce40c and 98d8275:

  • The M=8 / M=64 gap comes from eager kernel-time sums: each all-reduce kernel's time includes waiting for the other ranks, which varies up to 2x between runs at small M. Timed end to end over a CUDA graph of 20 calls, fused is faster at TP8: M=8 9.34 → 7.41 µs, M=64 16.76 → 15.95 µs.
  • There was a real regression above 4 MiB at TP8: on gfx942, plain all-reduce switches to the write-mode kernel there and the residual path did not (1.04x–1.35x slower). This revision adds a residual write-mode kernel; TP8 is now 1.17x–1.20x faster at M = 1024–4096.
  • As you suggested, custom_all_reduce_residual now returns None where fusing was not measured faster (_AR_RESIDUAL_MAX_BYTES: gfx942 TP2 above 10 MiB, TP4 above 14 MiB, and unmeasured arch/TP pairs), so callers run custom_all_reduce(input) + residual. The sweep and the timing script are in the PR description.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🔵 Needs a closer look

The new multi-GPU HIP kernels and fused-RMSNorm dispatch changes require hardware correctness and performance validation on gfx942 and gfx950, including registered graph capture and replay, which this review environment cannot run.

No open issues 🎉

Review effort: Balanced

…X measurements

- MI355X timing with the graph-loop script (20 calls per graph, slowest rank, median of 5), 2 rounds, n=7168, M=1-4096.
- gfx950 TP2: fused was 0.88x-0.996x of all-reduce + add at every size, so it now fuses with no bound.
- gfx950 TP4, TP6 and TP8 stay unbounded: fused was 0.78x-0.97x, 0.87x-0.94x and 0.76x-0.94x at every size.
- TP6 is now measured; its fallback, plain all-reduce, faults below 80 KiB on main and head, so only fused runs there.
- The guard test's unmeasured-pair example moves from gfx950 TP2 to gfx942 TP3.
Copilot AI balanced review requested due to automatic review settings October 29, 2026 15:53

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🔵 Needs a closer look

Human assessment is needed because an accepted TP8 input can read unwritten scratch and corrupt outputs, while benchmark input mutation undermines performance comparisons.

No open issues 🎉

Review effort: Balanced

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

Labels

ci:multi-gpu Trigger multi-GPU op tests on PR ci:sglang HIP JIT

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants