Skip to content

[HIP] feat(custom_ar): add torch.symm_mem transport(mori) for gfx1250 - #5431

Merged
valarLip merged 9 commits into
ROCm:mainfrom
kawhil-amd:symm_mem_custom_ar
Oct 13, 2026
Merged

valarLip merged 9 commits into
ROCm:mainfrom
kawhil-amd:symm_mem_custom_ar

Conversation

@kawhil-amd

@kawhil-amd kawhil-amd commented Sep 11, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Add torch.symm_mem (mori backend) as a peer-buffer transport for gfx1250
custom all-reduce, and extend gfx1250 kernels to world_size {2, 4, 6, 8}.

symm_mem transport (opt-in, gfx1250)

  • Enable with AITER_CUSTOM_AR_USE_SYMM_MEM=1; reuses the gfx1250 pointer-list ops.
  • 64 B collective probe: all ranks vote, then fall back to VMM/IPC together (no hang).
  • After the probe passes, allocation/rendezvous failures raise on every rank.
  • Cross-node and expandable_segments guards are evaluated after the transport is final.
  • register_*_buffer raises on this transport (would share a stale copy).

gfx1250 world_size 6/8

  • DISPATCH_NGPUS_1250 + check_ngpus() (init-time check); kMaxNgpus = 8.
  • LL scratch sized by world_size (32 MiB @ TP2, 128 MiB @ TP8).
  • AG rejects outputs past the int32 index range.
  • meta_size_gfx1250(world_size=8): backward compatible default.

Others

  • all2all: skip mori shmem init on gfx125x (EP uses cco there).
  • test: --transport {auto,symm} in test_custom_allreduce.py.

Test plan

  • test_custom_allreduce.py at ws=2/4/6/8, default and --transport symm
  • Fallback without mori: warning + VMM/IPC, no hang

@kawhil-amd
kawhil-amd requested a review from a team September 11, 2026 02:28
@github-actions

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; main branch always runs both MI35X and MI300X
multigpu 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 5431 --add-label <label>

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 opt this PR out.

@github-actions github-actions Bot changed the title feat(custom_ar): torch.symm_mem transport + world_size 6/8 for gfx1250 [HIP] feat(custom_ar): torch.symm_mem transport + world_size 6/8 for gfx1250 Sep 11, 2026
@github-actions github-actions Bot added the HIP label Sep 11, 2026
@kawhil-amd kawhil-amd changed the title [HIP] feat(custom_ar): torch.symm_mem transport + world_size 6/8 for gfx1250 [HIP] feat(custom_ar): add torch.symm_mem transport for gfx1250 Sep 11, 2026
@kawhil-amd kawhil-amd changed the title [HIP] feat(custom_ar): add torch.symm_mem transport for gfx1250 [HIP] feat(custom_ar): add torch.symm_mem transport(mori) for gfx1250 Sep 11, 2026
@kawhil-amd
kawhil-amd force-pushed the symm_mem_custom_ar branch 2 times, most recently from b64e379 to 97687ea Compare September 12, 2026 12:28

@TennyWang1223 TennyWang1223 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.

csrc/include/custom_all_reduce_gfx1250.cuh:122 — LL scratch buffer overflow at world_size 6/8

kLLMaxRanks is still 4, but this PR opens the LL fast path to world_size_ <= 8 (line ~1428). The shared meta buffer is sized meta_size() = kLLScratchOffset + llScratchBytes(), and llScratchBytes() = 2 * kLLMaxRanks * kLLPackCapacity * 16 only reserves 4 ranks of scratch. But ar_ll_gfx1250 writes at bankOffPkts + rankslot with bankOffPkts = (flag&1) * ngpus * slot, indexed by the template ngpus. For ngpus=8 the max write offset is (2ngpus-1)slot = 15slot, while only 2kLLMaxRanksslot = 8slot is allocated — a ~2x out-of-bounds write into every peer's meta buffer (ngpus=6 also overflows: 11slot > 8*slot). This corrupts adjacent device memory regardless of transport (symm_mem's meta tensor uses the same meta_size_gfx1250()).

Fix: bump kLLMaxRanks to 8 and update the stale world_size <= 4 comment on line 121.

csrc/include/custom_all_reduce_gfx1250.cuh:611 — ag_gfx1250_warpsplit_unroll4 out-of-bounds at world_size 6

tnum_gpu = 256 / ngpus doesn't divide evenly for ngpus=6 (= 42, 642=252). With blockDim=256, threads 252–255 compute warp_id = 6, then read ptrs[6] (valid range 0–5) and write result + 6size — both out of bounds. Since _SUPPORTED_WORLD_SIZES now includes 6, this all_gather kernel is broken at 6 GPUs (8 is fine: 256/8=32 divides evenly). The allreduce path (naive/LL) uses % ngpus and is unaffected.

Fix: guard the tail threads (if (warp_id >= ngpus) return;) or restrict this kernel's supported world sizes to powers of two that divide 256.

@kawhil-amd

Copy link
Copy Markdown
Contributor Author

csrc/include/custom_all_reduce_gfx1250.cuh:122 — LL scratch buffer overflow at world_size 6/8

kLLMaxRanks is still 4, but this PR opens the LL fast path to world_size_ <= 8 (line ~1428). The shared meta buffer is sized meta_size() = kLLScratchOffset + llScratchBytes(), and llScratchBytes() = 2 * kLLMaxRanks * kLLPackCapacity * 16 only reserves 4 ranks of scratch. But ar_ll_gfx1250 writes at bankOffPkts + rank_slot with bankOffPkts = (flag&1) * ngpus * slot, indexed by the template ngpus. For ngpus=8 the max write offset is (2_ngpus-1)_slot = 15_slot, while only 2_kLLMaxRanks_slot = 8_slot is allocated — a ~2x out-of-bounds write into every peer's meta buffer (ngpus=6 also overflows: 11_slot > 8*slot). This corrupts adjacent device memory regardless of transport (symm_mem's meta tensor uses the same meta_size_gfx1250()).

Fix: bump kLLMaxRanks to 8 and update the stale world_size <= 4 comment on line 121.

csrc/include/custom_all_reduce_gfx1250.cuh:611 — ag_gfx1250_warpsplit_unroll4 out-of-bounds at world_size 6

tnum_gpu = 256 / ngpus doesn't divide evenly for ngpus=6 (= 42, 6_42=252). With blockDim=256, threads 252–255 compute warp_id = 6, then read ptrs[6] (valid range 0–5) and write result + 6_size — both out of bounds. Since _SUPPORTED_WORLD_SIZES now includes 6, this all_gather kernel is broken at 6 GPUs (8 is fine: 256/8=32 divides evenly). The allreduce path (naive/LL) uses % ngpus and is unaffected.

Fix: guard the tail threads (if (warp_id >= ngpus) return;) or restrict this kernel's supported world sizes to powers of two that divide 256.

Could you help to check it again? The issue you mentioned have corrected .

TennyWang1223
TennyWang1223 previously approved these changes Sep 16, 2026

@TennyWang1223 TennyWang1223 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.

LGTM

@valarLip

Copy link
Copy Markdown
Collaborator

Reviewed this against the tree at head. Four findings I would treat as blocking;
each was traced to the line rather than inferred. Happy to post the remaining
non-blocking ones (world_size 6 silently dropped, a stream-ordered zero_()
before a host-side rendezvous, get_gfx() used for a runtime dispatch decision,
teardown/leak on the symm path, the unconditional meta-size doubling) if useful.


1. The world-size expansion is unreachable, and TP=8 now crashes at startup

csrc/kernels/custom_all_reduce_gfx1250.cu:40 and :67 still carry

if (world_size > 4)
    throw std::invalid_argument("gfx1250 custom allreduce: world size > 4 is not supported");

Python-side the gate is now open, so on gfx1250 TP=8 the constructor passes
_SUPPORTED_WORLD_SIZES, sets self.disabled = False, and calls
_ops_init_custom_ar — which throws, uncaught, out of CustomAllreduce.__init__.
Engine startup dies. Before this PR the same config hit the graceful
"unsupported world size" warning and fell back to RCCL.

The consequence for the PR itself: the new DISPATCH_AR case 8 and DISPATCH_AG
cases 16/32 can never execute, so the headline change is dead code until these
two guards move.

2. _SUPPORTED_WORLD_SIZES is arch-agnostic, so old archs lose their fallback

custom_all_reduce.py:766 is a ClassVar shared by every architecture:

_SUPPORTED_WORLD_SIZES: ClassVar[list[Any]] = [2, 4, 8, 16, 32]

The 16/32 entries are there for gfx1250 all-gather, but the gate at :873 is the
only thing standing between an old-arch rank and csrc/kernels/custom_all_reduce.cu:42:

if (world_size > 8)
    throw std::invalid_argument("world size > 8 is not supported");

So MI300 at TP=16 now passes the gate, sets disabled = False, enters _init_ipc,
and throws at startup where it previously logged and fell back. The new
should_custom_ar > 8 guard does not help — it gates dispatch, never
construction.

3. _SymmMemBufferProxy registers a one-time copy, so peers reduce stale data

custom_all_reduce.py:750-761:

buf = symm_mem.empty(size, dtype=torch.uint8, device=ca.device)
buf.copy_(tensor.reshape(-1).view(torch.uint8)[:size])   # once, at registration
hdl = symm_mem.rendezvous(buf, ca.group)
return list(hdl.buffer_ptrs)

The caller then passes the original inp.data_ptr() as the local pointer, and
custom_all_reduce_gfx1250.cuh:1149 (and :1160) binds the two differently:

data.ptrs[i] = (i != rank_) ? (void*)all_ptrs[i] : self;

Slot rank_ is the live input; every other slot is peer j's frozen
registration-time copy, and nothing re-copies afterwards. On a TP=4 decode, every
all-reduce past warm-up sums fresh local activations against iteration-0 peer
values: wrong logits, no crash, no warning — the worst failure shape of the
four.

The pre-existing _GFX1250BufferProxy has the identical structure, so whatever
fixes this needs to sweep both.

4. Three *_sync_latency entry points were missed by the macro conversion

Every other world_size_ == 2 ? 2 : 4 site in
csrc/kernels/custom_all_reduce_gfx1250.cu became DISPATCH_AR_NGPUS_1250.
These three did not — start_sync_latency (:468, dispatching at :475/:478),
end_sync_latency (:482, :489/:492) and two_sync_latency (:496,
:503/:506) still read:

int ws = fa->world_size_;
if (ws == 2) ...<2>... else ...<4>...

At world_size = 8 this launches the 4-rank barrier: each rank writes only
sg.signals[0..3], ranks 4..7 never have their Signal::start row set, and every
rank spins forever. A permanent GPU hang rather than a throw, which is
considerably harder to diagnose than #1.


On #1/#2 the shape of the fix matters as much as the fix: right now a world size
the C++ side rejects is discoverable only by catching its exception. A predicate
the Python gate can ask — per-arch, returning the reason it cannot serve — would
let both the constructor and should_custom_ar* read the same answer instead of
each carrying its own copy of the limits.

Related, and the reason I would put the cap in one place: the > 8 guard added to
should_custom_ar was not added to should_custom_ar_bytes, which shares
_fits_custom_ar_size. Putting it in _fits_custom_ar_size gives it to all four
predicates at once.

@kawhil-amd

kawhil-amd commented Sep 16, 2026 •

Copy link
Copy Markdown
Contributor Author

@valarLip Thanks for the thorough review. #1, #2, and #4 are fixed in the latest push (two separate commits).

Regarding #3 (get_external_ipc_meta one-time copy):

This is a pre-existing pattern shared by both the VMM and symm_mem paths — not introduced by this PR. The normal allreduce/allgather hot path does not go through get_external_ipc_meta:

  • The primary input buffer (_symm_input_tensor) is allocated via symm_mem.empty() + rendezvous() in _init_symm_mem. All ranks share the same live device memory directly. Data is copied into this buffer before each kernel launch, so peers always read fresh values.
  • get_external_ipc_meta is only called from register_input_buffer / register_output_buffer for additional external tensors (e.g. CUDA graph capture buffers). The IPC path does not have this issue — it takes a hipIpc handle on the original tensor's physical memory, no copy involved. The VMM and symm_mem paths copy into a new shared buffer because they cannot directly export an arbitrary tensor's backing memory.
  • A proper fix would require the caller to allocate external tensors on symm_mem/VMM from the start (avoiding the copy entirely), which is an allocator-level change beyond the scope of this PR.

Happy to hear if you see a scenario where the hot path actually hits get_external_ipc_meta — in that case this would need to be addressed here.

@kawhil-amd
kawhil-amd force-pushed the symm_mem_custom_ar branch 3 times, most recently from 7c18a87 to 0722b6d Compare September 16, 2026 10:58

@valarLip valarLip 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 at 12a4486.

Three things I chased and want to clear off the table so they don't get re-litigated: the AR kernel does not spill registers at ngpus=8 (measured ScratchSize=0 on gfx942/gfx1201 proxy targets); the symm_mem meta is not uncached memory (_init_gfx1250 was already plain VMM cached, so that's not something this PR introduced); and register_output_buffer does not lose writes, because the gfx1250 kernel never dereferences _output_dp.

The probe-and-fall-back design is the right shape. My concerns are that the probe is rank-local, that it validates an allocation seven orders of magnitude smaller than the one it commits to, and that falling back leaves two guards already evaluated against the wrong transport.

all2all.py breaks FlyDSL EP on gfx1250, and is unrelated to this PR

FlyDSLAll2AllManager._init_mori_shmem now returns early on gfx125x, but the FlyDSL EP op allocates every P2P buffer from mori's shmem heap: flydsl_dispatch_combine_intranode_op.py calls mori_shmem_create_tensor unconditionally at :438 and :696-712, ms.shmem_barrier_all() at :434/:573/:662, and ms.shmem_ptr_p2p() at :362. With shmem_torch_process_group_init never executed, this hits assert ptr != 0, "mori_shmem.shmem_malloc failed" in mori/shmem/tensor_utils.py:46, or libmori_shmem's "Shmem state is not initialized". So all2all_backend=flydsl is simply broken on gfx1250.

The MoriAll2AllManager half is fine — mori's _ep_comm() defaults to cco on gfx125x and genuinely doesn't need shmem. But the skip here keys on arch alone and doesn't follow mori's own MORI_EP_COMM variable, so a user setting MORI_EP_COMM=shmem falls back to the shmem backend while aiter has already skipped init, and hits the same assert. The FlyDSL class docstring at :128 and the assert text at :174 still say "FlyDSL still uses mori's shmem heap", which now contradicts the code — and the call-site comment that recorded the coupling was deleted in this PR.

I'd suggest splitting these two hunks into their own PR. They're a different subsystem from symm_mem custom AR, and leaving them here means that when someone bisects a gfx125x EP hang later, they land on a commit titled "symm_mem custom AR".

The probe is rank-local, so a single failing rank deadlocks startup

_probe_symm_mem wraps a collective rendezvous in a bare except Exception and returns a rank-local boolean with no cross-rank reduction — the docstring's claim that every step is collective so no rank can hang is exactly inverted. If rank 3's import mori.allocator fails, or set_backend raises, or symm_mem.empty(64) OOMs, the exception is swallowed, logged at debug level, and the rank returns False and proceeds to _init_ipc. Ranks 0-2 return True and block forever in _init_symm_mem's symm_mem.rendezvous(self._symm_meta_tensor, self.group). Startup deadlock with no visible diagnostic. all_peers_mapped is a purely local judgement too and splits the same way. An all_reduce(MIN) on the probe result before branching closes it.

The probe validates 64 bytes and commits to ~1.15 GiB, with no fallback

A successful symm_mem.empty(64) commits to the symm path, and then _init_symm_mem asks the mori symmetric heap for meta (~128 MiB) plus max_size (1 GiB by default) at :1043/:1049 — with no try/except. Heap exhaustion, a granularity or alignment rejection, or a rendezvous failure at that size propagates out of CustomAllreduce.__init__ and aborts engine startup, which is precisely the scenario the probe-and-fallback design exists to prevent. By then self.disabled is already False, so a caller that catches the exception holds a half-initialized object with no _pool and no _ptr, and the first all_reduce raises AttributeError. Either probe at the real size, or route _init_symm_mem through the same fallback path.

Two guards are evaluated against a transport that may not be the final one

The cross-node early exit is bypassed and never rechecked. At :857, not self._same_node and not self._use_symm_mem is false whenever AITER_CUSTOM_AR_USE_SYMM_MEM=1, so the group is not disabled and :932 sets disabled=False. On a non-gfx1250 target the probe returns False immediately at :1012, and :996-999 falls through to _init_ipc, which calls hipIpcOpenMemHandle on a handle exported by a different host — an error, or a garbage pointer. Before this PR the same combination printed "spans across nodes" and disabled cleanly. _same_node is stored and then never read again.

The expandable_segments IPC guard has the same shape. At :950-954, not self._use_symm_mem is false while _use_symm_mem is still True, so enable_register_for_capturing is not forced off; the probe then fails and we land in _init_ipc, and graph capture calls hipIpcGetMemHandle on an expandable-segment pointer — the exact failure that guard's comment describes, reintroducing #4174. gfx1250 is saved only incidentally, by the unconditional enable_register_for_capturing = False at :942. This has to be computed after the transport is finally decided.

Relatedly, symm_mem.set_backend("MORI") is a process-global switch flipped inside the probe and never restored when the probe fails and we fall back to VMM or IPC; _init_symm_mem at :1040 then sets it a second time. After any rank's probe failure, other symmetric-memory users in the same process silently get the MORI allocator. Same class of issue: _select_ops() is called twice, and the mori.allocator + set_backend lines are duplicated verbatim between probe and init — once those two copies drift, you probe one configuration and run another.

world_size: the gate, the C++ check, and the actual capability disagree

The new world_size > 8 limit lives only in _fits_custom_ar_size, but custom_fused_qknorm_ar (:2011) and custom_fused_qknorm_ar_rope (:2076) check only self.disabled and bypass it. Before this PR, ws=16/32 could not be constructed on gfx1250 at all — the deleted gcnArchName check raised. Now _SUPPORTED_WORLD_SIZES_GFX1250 admits 16 and 32, disabled stays False, and the fused qknorm path dispatches the kernel and throws RuntimeError mid-forward instead of falling back as the guard's comment ("larger world sizes use RCCL") promises. The root cause is that a dispatch capability limit was placed inside a predicate named _fits_custom_ar_SIZE, so it only covers one entry point.

More broadly, admitting 16/32 advertises support that isn't there: above ws=8, all_reduce and reduce_scatter silently return None and fall to RCCL (:1378, :1491) while the full meta and max_size pool are still allocated, and only all_gather runs a custom kernel. There's no warning anywhere — the only clue is a source comment. Note the RuntimeError this PR deletes said "RCCL fallback is also not available on this platform", which directly contradicts the new behaviour; the PR doesn't say which one is right. I'd either warn once at init or drop 16/32 from the list until AR/RS actually support them.

On the C++ side the init check moved from > 4 to > aiter::kMaxNgpus, and kMaxNgpus = kMaxNgpusAg = 32 is far wider than the {2,4,8} that AR/RS dispatch supports — so rejection moved from construction time to the first collective. Any even ws ≤ 32 (6, 10, 12, …) constructs successfully and then hits DISPATCH_AR_NGPUS_1250's default arm with std::runtime_error("unsupported world_size N"). The in-repo Python gate blocks this today (6 isn't in the whitelist), so it's latent rather than live — but torch.ops.aiter.init_custom_ar_gfx1250 is a public binding that downstream vLLM/SGLang call directly. The message is misleading too: it says "world size > 32 is not supported" when the usable AR set is {2,4,8}. The check should mirror the dispatch set (kMaxNgpusAr for AR).

Two unconditional memory increases, with the comments now wrong

kLLMaxRanks 4 → 8 doubles llScratchBytes() from 64 MiB to 128 MiB, and meta_size() applies it unconditionally at every world size — so TP=2 and TP=4 pay 64 MiB per GPU for nothing. The arithmetic is 2 * kLLMaxRanks * kLLPackCapacity(=524288) * 16 B, i.e. 67,108,864 → 134,217,728 independent of ws, and all three init paths allocate and zero that. An 8-GPU node goes 512 MiB → 1 GiB, while at ws=2 the kernel's bankOffPkts = (flag & 1) * ngpus * slot touches a quarter of it. meta_size() not taking world_size is the root cause. Three comments are now inaccurate and actively misleading: cuh:142's // 32768 (the real value is 524288 — this one misled one of my own verification passes into computing the total as 8 MiB), cuh:158-160's "4 MiB at the 256 KiB / 4-rank defaults", and custom_all_reduce.py:1171's "Signal (~34 KB) + LL staging scratch (~4 MiB)".

Separately, kMaxNgpus = kMaxNgpusAg = 32 is used to size Signal, RankData and RankSignals, though AR/RS top out at 8. Signal grows 34,816 B → 133,120 B, and RankData/RankSignals grow 64 B → 256 B — and those two are passed by value on every kernel launch. Every world size including ws=2 pays ~97 KiB of extra meta, plus 256 B of extra kernel arguments per AR/RS/AG launch, which is not free on a few-microsecond decode path. The 8 MiB rank_data arena also drops from 131072 registered tuples to 32768, while the comment at :964-968 still says "world_size is at most 8 … enough for 131072 such tuples". Only AG needs 32 lanes; the AR/RS structures should be sized by kMaxNgpusAr.

AG index arithmetic overflows now that ngpus can be 32

ag_gfx1250_scalar's result[gpu_idx * size + idx] (:488), ag_gfx1250_naive_vec's size * rank_idx + idx (:520) and ag_gfx1250_lastdim's (ngpus * y + rank_idx) * last_dim_size + x (:604) are all int and all scale with ngpus, and custom_all_reduce_gfx1250.cu:290 narrows an int64_t numel to int. Raising the ngpus ceiling from 4 to 32 shrinks the safe output size by 8x. should_custom_ag's max_size/(ws*2) limit protects the default pool, but custom_all_gather (:1589) and all_gather_reg (:1523) don't consult should_custom_ag at all — they don't even check disabled. At ws=32, total output elements exceed 2^31 at roughly 134 MB of bf16 input per GPU (where at ws=4 the threshold was ~1 GiB), giving negative offsets and silent out-of-bounds writes. size_t fixes it.

Also on that kernel: ag_gfx1250_warpsplit_unroll4's constexpr int tnum_gpu = 256 / ngpus leaves 8 lanes at ngpus=32 — less than a wave, so "warpsplit" stops being an accurate name — and there's no static_assert that blockDim == 256.

Benchmark-only kernels roughly double the JIT TU

Three sync-latency microbenchmark entry points were switched to the AG macro (2/4/8/16/32), but they measure the AR/RS-side synchronization primitives, whose macro tops out at 8. Together with AG's own 16/32 instantiations, template instances in the single JIT TU go from roughly 78 to 153 — nine pure-benchmark kernels get 16/32 instances compiled into the shipped module for code paths production can never reach. This module is JIT-compiled on first call, on the engine-init path of every rank, so ~2x instances shows up directly as a user-visible first-call compile wall and .so size. Switching those three back to the AR macro removes nine instances with no behavioural change.

While measuring that: on proxy targets the AG kernel at ngpus=32 shows 272 B/lane of ScratchSize, because the ptrs[32] pointer table gets demoted to scratch — so every peer load reads scratch first. That's the real performance cliff for AG at ws=32, and the PR carries no measured numbers at ws=8/16/32 at all.

Lifecycle

get_external_ipc_meta copies the user tensor into a freshly allocated symm buffer and returns peer pointers to that copy, while the local key remains inp.data_ptr(). The C++ register_input_buffer stores data.ptrs[i] = (i != rank_) ? all_ptrs[i] : self (cuh:1149) and the kernel re-reads those peer pointers every round, so each rank sees its own data fresh and every peer's as a snapshot taken at registration — divergent results across ranks, with no error. Each call also appends a fresh full-size buffer to ca._symm_ext_hdls that is only released at close(). And symm_mem.rendezvous is collective but sits inside a per-rank API, so any mismatch in registration order or count between ranks deadlocks — aiter/ops/communication.py:68 already records that the VMM version "deadlock[s] in its vmm_exchange rendezvous" for this reason. Most of this is inherited from the unchanged _GFX1250BufferProxy (:675) rather than introduced here, and nothing in-repo calls register_*_buffer today, so it's latent — but the new copy propagates it.

close() delattrs three handle attributes, but _symm_meta_tensor, _symm_input_tensor and the self._pool holding them stay alive, so the "peer mappings are torn down" in the comment doesn't happen. _SymmMemBufferProxy holds strong references to both tensors and back to ca, so after close the ~128 MiB meta and the max_size input and their peer mappings remain resident, plus a ca._pool._ca is ca cycle that defers GC. Repeated create/close in one process — multiple engines, TP reconfiguration, a test loop — leaks a full set each time until the symmetric heap is exhausted, which is exactly what the comment claims to prevent. Either drop both tensors and _pool in close(), or fix the comment.

Smaller

The new blank line at custom_all_reduce.py:130 fails black --check (I ran it: would reformat), and CONTRIBUTE.md requires pre-commit to pass.

There are no test changes in this PR. test_custom_allreduce.py's --tp-size choices=[2,4,6,8] still offers 6, which is no longer in the gfx1250 list, so -t 6 passes green while never touching custom AR at all.

On duplication: _SymmMemBufferProxy and _GFX1250BufferProxy are near-identical line for line; the two _init_mori_shmem methods carry a copy-pasted gfx125x guard whose docstrings have already drifted apart; and the probe-failure branch re-copies the transport elif chain below it. The "raw pointer transport" test _use_symm_mem or _use_vmm appears in four places. all2all.py introduces a third way of detecting gfx1250 (startswith("gfx125")), reading a different source than _detect_gfx1250(), which also means the AITER_CUSTOM_AR_DISABLE_GFX1250 escape hatch — documented as end-to-end — doesn't reach all2all. And AITER_CUSTOM_AR_USE_SYMM_MEM has no named constant or comment the way MAX_SIZE/MIN_SIZE do, and isn't documented anywhere.

Summary

I'd want the rank-local probe made collective and the two stale guards (cross-node, expandable_segments) recomputed after the transport is final, since between them a single unlucky rank turns into either a startup deadlock or a cross-node hipIpcOpenMemHandle. The 64-byte probe should validate what it's actually committing to. world_size 16/32 should either warn or wait. And I'd really like to see the all2all.py hunks split out — both because they break FlyDSL EP on gfx1250 as written, and because they don't belong to this change.

@kawhil-amd
kawhil-amd force-pushed the symm_mem_custom_ar branch 3 times, most recently from 99a2b3a to 5d1079b Compare September 23, 2026 11:20
Settle the transport before the guards that branch on it. The cross-node and
expandable_segments checks both read _use_symm_mem while it still held the
env-var value, so a probe failure reached _init_ipc with the cross-node exit
bypassed and ROCm#4174's guard skipped. The probe now runs ahead of both.

Make the probe collective. It returned a rank-local bool, so a rank whose
import or allocation failed fell back to IPC while its peers blocked in
rendezvous forever. Verdicts now go through _all_reduce_and (MIN over the
gloo group) before the next collective. It stays at 64 bytes: symm_mem.empty
draws from a MemPool that never returns a segment to the driver, so probing
at the real size would strand ~1 GiB per rank on every fallback. Restore the
process-global backend when it comes back empty, or an unrestored MORI
re-points every other symmetric-memory user.

Raise instead of falling back once the probe has passed. _init_symm_mem had
no try/except, so heap exhaustion escaped __init__ with disabled already
False and the first all_reduce hit AttributeError. Degrading would strand the
buffers and then ask IPC for as much again, so allocation and rendezvous
failures now raise on every rank, as on the VMM path. The buffer_ptrs length
and NULL test moved onto both rendezvous calls, since init_custom_ar takes
world_size from that list and never null-checks it.

Gate symm_mem on gfx1250: init_custom_ar_gfx1250 is the only op taking a
pointer list, which is all rendezvous hands back. symm_mem itself is not
arch-specific.

Let _SymmMemBufferProxy own every symm_mem object. torch exposes no free API
for them, so a dropped reference is the only release; the tensors and handles
are locals now and close() drops the proxy by refcount rather than leaving a
cycle for the gc. Not a subclass of _GFX1250BufferProxy: they own their
buffers differently. register_input/output_buffer raises there, since sharing
an external tensor needs a registration-time copy and peers would then reduce
a stale snapshot.

Size the LL scratch per group. kLLMaxRanks went 4 -> 8 for TP=8, but
meta_size() applied it at every world size. It now takes world_size, matching
what ar_ll_gfx1250 indexes (bankOffPkts peaks at (2*ngpus-1)*slot), so TP=2
reserves 32 MiB rather than the 64 MiB it reserved before this PR.

Reject unsupported world sizes at construction: init_custom_ar_gfx1250*
accepted any even size <= kMaxNgpus, so 6 built fine and then threw from a
dispatch default arm on the first collective. aiter::check_ngpus mirrors
DISPATCH_NGPUS_1250 instead.

Bound the allgather output index. Every AG kernel indexes its output with int
and that index scales with world_size, so the 4 -> 8 ceiling halved the safe
per-rank input; past it the offset goes negative. One guard in _all_gather,
where numel is still int64_t, covers all four kernels.

Skip mori's shmem init on gfx125x: that arch has no shmem support, which is
what CCO exists to work around, so the init is useless and can hang. Revert
FlyDSLAll2AllManager to main, which has no CCO backend to fall back on.

Move self.rank/self.world_size above `disabled = False`. Name the
AITER_CUSTOM_AR_USE_SYMM_MEM env var, and add a --transport flag to
test_custom_allreduce.py.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
kawhil-amd and others added 2 commits September 28, 2026 03:35
Conflicts:
- custom_all_reduce.py close(): keep main's pool.close() for the IPC pool,
  then drop the symm_mem proxy (neither proxy defines close()).
- test_custom_allreduce.py: keep main's --regression/--iterations and this
  branch's --transport.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…, symm_mem close()

Add 6 to DISPATCH_NGPUS_1250 and check_ngpus. The Python gate already admits
[2, 4, 6, 8], so on gfx1250 ws=6 passed it, set disabled=False, then threw
from check_ngpus at meta_size; the three now agree. Every kernel indexes peers
with % ngpus, so none assumes a power of two. All ws=6 instances compile for
gfx1250 with ScratchSize 0. ag_gfx1250_warpsplit_unroll4 is not dispatched,
but at ngpus=6 its tail threads would index ptrs[6]; a static_assert keeps it
from being enabled for a world size that does not divide 256.

meta_size_gfx1250 takes world_size = 8 by default, in the stub and in the
pybind binding. Downstream callers that pass nothing keep working and get the
max-size buffer, which is safe for every supported world size; aiter still
passes the real world_size, so TP=2 allocates only 32 MiB of LL scratch.

Release symm_mem buffers through pool.close(), the path main now uses for the
IPC pool, instead of an isinstance special case. torch has no free API for
symm_mem, so _SymmMemBufferProxy.close() drops its references, which are the
only ones: mori frees each buffer and deregisters its window on the last
reference. Clearing _ca breaks the ca -> _pool -> ca cycle.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@kawhil-amd

kawhil-amd commented Sep 28, 2026 •

Copy link
Copy Markdown
Contributor Author

all-gather and all-reduce 8-GPU ut test passed on gfx1250
image
image

@kawhil-amd

kawhil-amd commented Sep 28, 2026 •

Copy link
Copy Markdown
Contributor Author

@valarLip Thanks for the detailed review. Addressed in 47efc8b and 5add972; status per point below.

Fixed

  • Rank-local probe → deadlock: the probe verdict now goes through a group-wide vote (_all_reduce_and, MIN over the gloo group) before the next collective, so all ranks fall back together. Every rendezvous in _init_symm_mem is voted the same way.
  • Half-initialized object on full-size failure: once the probe passes, allocation/rendezvous failures raise on every rank instead of escaping from one; no disabled=False object without _ptr/_pool is left behind. Peer-pointer lists are length/NULL-checked before init_custom_ar.
  • Guards evaluated against the wrong transport: the probe now runs before the cross-node and expandable_segments ([Bug] custom_all_reduce.cu:397 hipIpcGetMemHandle fails when caller uses PYTORCH_HIP_ALLOC_CONF=expandable_segments:True #4174) checks, so both see the final transport.
  • set_backend("MORI") left global: the previous backend is restored when the probe fails; _init_symm_mem no longer sets it a second time.
  • zero_() vs host-side rendezvous: the stream is synchronized after meta.zero_() before peers can map it.
  • FlyDSL EP on gfx1250: the FlyDSL hunk is reverted; FlyDSL still inits mori shmem. Only MoriAll2AllManager skips it on gfx125x.
  • world_size gate vs C++ vs capability: 16/32 are gone. kMaxNgpus = 8, and check_ngpus() rejects at init exactly what DISPATCH_NGPUS_1250 can't dispatch. The supported set is now {2, 4, 6, 8} on both sides (ws=6 added in 5add972), so the qknorm paths can't reach an undispatchable size.
  • Unconditional memory increases: meta_size_gfx1250(world_size) sizes the LL scratch by world size (32 MiB @ TP2, 128 MiB @ TP8). Signal/RankData/RankSignals are back to 8 slots. Stale comments fixed. meta_size_gfx1250() keeps a world_size=8 default, so downstream callers that pass nothing still get a buffer that is safe for any world size.
  • JIT TU size: no 16/32 instances; the sync-latency benchmarks dispatch on the same {2, 4, 6, 8} set as AR.
  • AG overflow: _all_gather rejects outputs whose element count exceeds the int32 index range, covering all_gather_reg/custom_all_gather as well. ag_gfx1250_warpsplit_unroll4 (not dispatched) gets static_assert(256 % ngpus == 0).
  • Lifecycle / leak: _SymmMemBufferProxy is the sole owner of the symm_mem tensors and handles, and releases them in close() through the same pool.close() path main now uses for the IPC pool (the _ca cycle is broken there). On the symm_mem transport, register_*_buffer now raises instead of sharing a stale registration-time copy.
  • Smaller: black fixed; AITER_CUSTOM_AR_USE_SYMM_MEM is now a named constant with a comment; the test has --transport {auto,symm}, and -t 6 now really exercises custom AR on gfx1250.

Not changed, with reasoning

  • Probe size: still 64 B. A failure after the probe now raises cleanly on all ranks rather than half-initializing, so heap exhaustion is loud and consistent.
  • all2all in this PR: kept here because [reason]. The skip still keys on arch only; following MORI_EP_COMM (so MORI_EP_COMM=shmem on gfx125x still inits shmem) is tracked as a follow-up.
  • VMM get_external_ipc_meta stale copy: pre-existing, with no in-repo callers. Only the symm_mem path is closed off here; making VMM raise too is a follow-up so this PR doesn't change VMM behaviour.
  • Proxy duplication: _SymmMemBufferProxy stays separate from _GFX1250BufferProxy on purpose, since they own their buffers differently.
  • Cross-node over symm_mem: [validated on … / will disable until validated].

Follow-ups (listed in the PR description)

AG int32 → size_t indexing, MORI_EP_COMM handling, VMM external-buffer copy, VMM proxy close(), heap-capacity check, removing the dead warpsplit kernel.

MI450 results at ws=2/4/6/8 (default and --transport symm), plus perf numbers, will be added to the PR description.

AG world size 32/16 support. @TennyWang1223

amd-ruitang3
amd-ruitang3 previously approved these changes Oct 1, 2026
The probe only checks that mori loads and allocates locally; peer mapping
failures raise on every rank in _init_symm_mem. Drop the false claim that
symm_mem's MemPool never frees memory, and fix the comments on handle
lifetime, external-buffer registration, and the multi-node log.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@kawhil-amd

kawhil-amd commented Oct 5, 2026 •

Copy link
Copy Markdown
Contributor Author

@amd-ruitang3 Could you help review the PR again? Thanks! cc @valarLip

@kawhil-amd
kawhil-amd requested a review from JiaoliangYu October 8, 2026 03:08
backend there is CCO. Running this init would be useless and can hang.
"""
if _is_gfx125x():
return

@JiaoliangYu JiaoliangYu Oct 10, 2026 •

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.

just do not make a mori all2allmanager from upstream

@kawhil-amd kawhil-amd Oct 10, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

In the current upper-layer, MoriAll2AllManager from MORI v1 is created by default for EP8 inter-node scenarios, which causes failures on gfx1250. Therefore, this check was added.
If the upper layer no longer creates it, the check can be removed. I recommend keeping this change in the current PR and removing it in a follow-up PR once the logic is aligned with the upper-layer framework.

@TennyWang1223
TennyWang1223 self-requested a review October 12, 2026 06:46
TennyWang1223
TennyWang1223 previously approved these changes Oct 12, 2026

@TennyWang1223 TennyWang1223 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.

LGTM

…t mori errors

- register_input_buffer/register_output_buffer are no-ops on the symm_mem
  transport instead of raising. gfx1250 always reduces through the copy-in
  pool, so registered external tensors are never looked up. Keeps ATOM's
  signal-tensor registration (tp_group_reuse, rollout) from failing init.
  _SymmMemBufferProxy._Entry gains a `tensor` property for the same callers.
  _init_symm_mem asserts registered capture stays off, which this relies on.
- A cross-node group whose peers mori cannot map now disables custom
  allreduce on every rank (falls back to RCCL) instead of raising, as it did
  before symm_mem could span nodes. Same-node failures still raise.
- _rendezvous no longer catches mori's exceptions, same as vmm_exchange on
  the VMM path. mori runs its own collectives inside rendezvous, so a rank
  that failed there and moved on to the gloo vote left its peers blocked in
  mori. Docstrings now state what is and is not guaranteed.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@kawhil-amd

Copy link
Copy Markdown
Contributor Author

Fix report: symm_mem custom allreduce review findings (commit 2247dec)

All changes are in aiter/dist/device_communicators/custom_all_reduce.py.

Finding 2: ATOM calls register_input_buffer unconditionally

  • Problem: ATOM's tp_group_reuse.py and model_runner_ext.py register a signal tensor and then read _pool["input"].tensor. On symm_mem, get_external_ipc_meta raised NotImplementedError, and the proxy entry had no .tensor.
  • Fix: On symm_mem, register_input_buffer and register_output_buffer now log a warning and return without registering. _SymmMemBufferProxy._Entry gains a tensor property.
  • Why this is safe: gfx1250 always reduces through the copy-in pool, so it never looks up an externally registered buffer. An assertion in _init_symm_mem keeps enable_register_for_capturing off, which this relies on.

Finding 3: cross-node groups now fail at startup instead of falling back

  • Problem: If mori could not map peers on other nodes (null peer pointers), every rank raised and the server failed to start.
  • Fix: A cross-node group now votes on whether all peers were mapped. If any rank fails, every rank disables custom allreduce and uses RCCL, which is what happens when symm_mem is not enabled.
  • Unchanged: Same-node failures still raise. A same-node mapping failure means the setup is broken, so this matches the VMM and IPC paths.

Finding 4: possible hang when one rank fails inside mori

  • Problem: _rendezvous caught mori's exception and moved on to a gloo vote. Meanwhile the other ranks were blocked inside mori's own collectives (ccoCommCreate, ccoWindowRegister), whose socket reads have no timeout. Each side waited for the other.
  • Fix: mori's exceptions are no longer caught, following vmm_exchange on the VMM path. When the failing process exits, its sockets close, and the peers get EOF and raise too. The vote now happens only after mori returns on every rank.
  • Docs: The docstrings now say what is guaranteed and what is not.

@valarLip
valarLip merged commit 5d662fc into ROCm:main Oct 13, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants