Skip to content

Commit 7f40b1b

Browse files
committed
Fix FSDP SDMA output allocation and stream ordering
Standalone outputs could be allocator subblocks even though IPC imports use the allocation base. Share private-pool allocation between standalone outputs and pool arenas, and preserve old views when standalone storage grows. A local consumer event cannot protect remote readers. Add a standalone SDMA readiness exchange before data writes, including the first write. Order writes across backend instances and pools on the same process group with a weakly held completion event, and reuse that event for asynchronous Work completion. Cover standalone allocation growth, pooled and standalone output reuse, and cross-backend ordering. Document the ownership, readiness, and ordering rules. Test Plan: Using the isolated runtime verified byte-for-byte against the reviewed sources, with unchanged PyTorch and MORI binaries, from /tmp inside sdma-test1: ```bash HIP_VISIBLE_DEVICES= PYTHONPATH=/home/yangwu/.codex/fsdp-mori-code-review-20260920/runtime /opt/conda/envs/py_3.10/bin/python -m pytest -q /root/wuyl/mori-jeff/tests/python/ccl/test_torch_fsdp.py HIP_VISIBLE_DEVICES= PYTHONPATH=/home/yangwu/.codex/fsdp-mori-code-review-20260920/runtime /opt/conda/envs/py_3.10/bin/python /root/wuyl/pytorch-jeff-input-hook/test/distributed/_composable/fsdp/test_fully_shard_comm.py TestAllGatherLayouts TestParamContiguousEligibility -v /opt/conda/envs/py_3.10/bin/python /home/yangwu/.codex/fsdp-mori-code-review-20260920/stage.py /home/yangwu/.codex/fsdp-mori-code-review-20260920/gpu-suite-ordered.json ``` 45 MORI CPU tests, 51 matching PyTorch CPU tests, and all 3 GPU suite entries passed. GPU coverage includes stream reuse, two- and four-rank training, exact losses, gradients, and optimizer parameters, FP32/BF16, sync/async completion, integer reshard, and fallback. The GPU suites completed in 82.49 seconds. From the MORI repository root: ```bash /opt/conda/envs/py_3.10/bin/python -m ruff check python/mori/ccl/torch_fsdp.py tests/python/ccl/test_torch_fsdp.py tests/python/ccl/test_torch_fsdp_pool.py tests/python/ccl/test_torch_fsdp_streams.py git diff --check ``` Both checks passed. No new performance benchmark was run; standalone readiness adds a collective and small control buffer, and private allocator segment rounding can increase reserved memory. Authored with assistance from OpenAI Codex.
1 parent 3798f26 commit 7f40b1b

5 files changed

Lines changed: 183 additions & 27 deletions

File tree

‎docs/FSDP-SDMA-GUIDE.md‎

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -79,8 +79,18 @@ performance measurements.
7979

8080
FSDP does not manage MORI reuse events or pool state. The non-pooled adapter
8181
also records its last consumer on release and waits before subsequent packing
82-
and communication. FSDP retains its native post-forward shard synchronization
83-
and the generic parameter identity/version-counter protections.
82+
and communication. Before writing a registered output, it performs the same
83+
cross-rank readiness handshake using a small, separately registered control
84+
buffer. This prevents a faster peer from overwriting a slower peer's consumers;
85+
the handshake adds latency without a host completion wait. FSDP retains its
86+
native post-forward shard synchronization and parameter identity/version-counter
87+
protections.
88+
89+
MORI instances on the same process group also order complete writes with a
90+
shared stream event because their SDMA transport state is shared. This applies
91+
across independent backends and pools, without a host completion wait. Async
92+
work reuses that completion event. Weak process-group keys do not retain a
93+
destroyed group, and the usual single-pool path reuses its existing event wait.
8494

8595
Release is idempotent. Failed input preparation releases a lease on a stream
8696
ordered after the queued input work. If a collective may have partially started
@@ -93,6 +103,13 @@ arena base is registered: the compatible MORI IPC path does not compensate for
93103
an ordinary caching-allocator suballocation's offset from its allocation base.
94104
Slot offsets are fixed, identical across ranks, and aligned to 16 bytes.
95105

106+
Non-pooled outputs also use a fresh private allocator pool for each allocation
107+
or capacity growth, so even small buffers begin at their IPC allocation base.
108+
An index-less device is resolved before checking buffer reuse. Existing output
109+
views remain valid when capacity grows. The small non-pooled control buffer
110+
has its own private allocator pool; allocator reservation can exceed its tensor
111+
size due to segment rounding.
112+
96113
The arena and its single IPC registration survive lease release. The
97114
steady-state arena size is the sum of 16-byte-rounded slot capacities plus a
98115
16-byte-rounded `4 * world_size` control region, rather than the sum

‎python/mori/ccl/torch_fsdp.py‎

Lines changed: 58 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@
2727
from collections.abc import Sequence
2828
from dataclasses import dataclass
2929
from typing import Any
30+
from weakref import WeakKeyDictionary
3031

3132
import torch
3233
import torch.distributed as dist
@@ -42,6 +43,8 @@
4243

4344

4445
_POOLED_RANK_MAJOR = object()
46+
# Backend instances share SDMA transport state within a process group.
47+
_LAST_WRITE_EVENTS: WeakKeyDictionary[dist.ProcessGroup, torch.Event] = WeakKeyDictionary()
4548

4649

4750
@dataclass
@@ -88,16 +91,11 @@ def __init__(
8891
self._failed = False
8992
self._members: tuple[int, ...] = ()
9093
self._subgroups: set[dist.ProcessGroup] = set()
91-
# MORI imports IPC allocation bases, not PyTorch suballocation offsets.
92-
# A fresh private pool makes this arena its allocation's first address.
9394
capacities = [(size + 15) // 16 * 16 for size in buffer_sizes]
9495
ready_bytes = (group.size() * 4 + 15) // 16 * 16
95-
with torch.cuda.device(self._device):
96-
self._mem_pool = torch.cuda.MemPool()
97-
with torch.cuda.use_mem_pool(self._mem_pool, device=self._device):
98-
self._buffer = torch.empty(
99-
sum(capacities) + ready_bytes, dtype=torch.uint8, device=self._device
100-
)
96+
self._mem_pool, self._buffer = _allocate_registered_output(
97+
(sum(capacities) + ready_bytes,), dtype=torch.uint8, device=self._device
98+
)
10199
self._slots = []
102100
offset = 0
103101
for size, capacity in zip(buffer_sizes, capacities):
@@ -203,9 +201,10 @@ def _before_write(self, comm, stream) -> None:
203201
collective = self._collective_for(comm, self._group)
204202
collective.enqueue(self._ready_input, self._ready_output, 1, stream=stream)
205203

206-
def _after_write(self, stream) -> None:
204+
def _after_write(self, stream) -> torch.Event:
207205
# One collective/arena is shared, including when callers change streams.
208206
self._last_write_event = stream.record_event()
207+
return self._last_write_event
209208

210209
def _release(self, comm) -> None:
211210
slot = self._slots[comm._buffer_index]
@@ -241,11 +240,11 @@ def close(self) -> None:
241240

242241

243242
class _MoriSdmaAllGatherWork(dist.Work):
244-
def __init__(self, collective: Any, stream: torch.Stream) -> None:
243+
def __init__(self, collective: Any, stream: torch.Stream, event: torch.Event) -> None:
245244
super().__init__()
246245
self._collective = collective
247246
self._device = stream.device
248-
self._event = stream.record_event()
247+
self._event = event
249248

250249
def wait(self, timeout: object | None = None) -> bool:
251250
torch.cuda.current_stream(self._device).wait_event(self._event)
@@ -382,6 +381,9 @@ def __init__(
382381
self.layout = _MoriSdmaAllGatherLayout(self)
383382
self._collective: Any | None = None
384383
self._process_group: dist.ProcessGroup | None = None
384+
self._mem_pool: torch.cuda.MemPool | None = None
385+
self._ready_mem_pool: torch.cuda.MemPool | None = None
386+
self._ready_buffer: torch.Tensor | None = None
385387
self._output_buffer: torch.Tensor | None = None
386388
self._output_active = False
387389
self._last_use_event: torch.Event | None = None
@@ -407,6 +409,9 @@ def allocate(
407409
dtype: torch.dtype,
408410
device: torch.device,
409411
) -> torch.Tensor:
412+
device = torch.device(device)
413+
if device.type == "cuda" and device.index is None:
414+
device = torch.device("cuda", torch.cuda.current_device())
410415
if self._output_pool is not None:
411416
self._output_pool._check_ready()
412417
if self._native_fallback:
@@ -431,7 +436,9 @@ def allocate(
431436
self._output_active = True
432437
return output
433438
self._deregister_output_buffer_if_needed()
434-
self._output_buffer = torch.empty(*size, dtype=dtype, device=device)
439+
self._mem_pool, self._output_buffer = _allocate_registered_output(
440+
size, dtype=dtype, device=device
441+
)
435442
self._output_buffer_nbytes = _tensor_nbytes(self._output_buffer)
436443
self._registered_output_ptr = None
437444
self._output_active = True
@@ -466,11 +473,16 @@ def __call__(
466473
self._clear_prepared_output()
467474

468475
def _call_full_group(self, output_tensor, input_tensor, group, async_op):
476+
stream = torch.cuda.current_stream(input_tensor.device)
477+
previous = _LAST_WRITE_EVENTS.get(group)
478+
if previous is not None and (
479+
self._output_pool is None or previous is not self._output_pool._last_write_event
480+
):
481+
stream.wait_event(previous)
469482
if self._output_pool is not None:
470-
stream = torch.cuda.current_stream(input_tensor.device)
471483
self._output_pool._before_write(self, stream)
472484
elif self._last_use_event is not None:
473-
torch.cuda.current_stream(input_tensor.device).wait_event(self._last_use_event)
485+
stream.wait_event(self._last_use_event)
474486
if _tensor_nbytes(input_tensor) % 4 != 0:
475487
self._warn_unaligned_fallback(
476488
"MORI SDMA allgather requires 4-byte-aligned input; falling "
@@ -482,13 +494,16 @@ def _call_full_group(self, output_tensor, input_tensor, group, async_op):
482494
group=group,
483495
async_op=async_op,
484496
)
485-
if self._output_pool is not None:
497+
_LAST_WRITE_EVENTS[group] = (
486498
self._output_pool._after_write(stream)
499+
if self._output_pool is not None else stream.record_event()
500+
)
487501
return work
488502
collective = self._get_collective(group)
489-
stream = torch.cuda.current_stream(input_tensor.device)
490503
count = input_tensor.numel()
491504
self._ensure_output_registered(collective, output_tensor)
505+
if self._output_pool is None:
506+
self._wait_for_peer_consumers(collective, group, stream)
492507
if self._can_call_param_contiguous(input_tensor):
493508
split_sizes = self._param_contiguous_split_sizes
494509
split_offsets = self._param_contiguous_split_offsets
@@ -512,12 +527,25 @@ def _call_full_group(self, output_tensor, input_tensor, group, async_op):
512527
# MORI uses raw pointers, so the allocator cannot track these uses.
513528
input_tensor.record_stream(stream)
514529
output_tensor.record_stream(stream)
515-
if self._output_pool is not None:
530+
event = (
516531
self._output_pool._after_write(stream)
532+
if self._output_pool is not None else stream.record_event()
533+
)
534+
_LAST_WRITE_EVENTS[group] = event
517535
if async_op:
518-
return _MoriSdmaAllGatherWork(collective, stream)
536+
return _MoriSdmaAllGatherWork(collective, stream, event)
519537
return None
520538

539+
def _wait_for_peer_consumers(self, collective, group, stream) -> None:
540+
if self._ready_buffer is None:
541+
self._ready_mem_pool, self._ready_buffer = _allocate_registered_output(
542+
(group.size() + 1,), dtype=torch.int32, device=stream.device
543+
)
544+
self._ready_buffer.zero_()
545+
collective.register_output_buffer(self._ready_buffer)
546+
# Local consumer events alone cannot prevent writes from a faster peer.
547+
collective.enqueue(self._ready_buffer[:1], self._ready_buffer[1:], 1, stream=stream)
548+
521549
def release_output(self) -> None:
522550
self._clear_prepared_output()
523551
if self._output_pool is not None:
@@ -653,6 +681,18 @@ def _deregister_output_buffer_if_needed(self) -> None:
653681
self._registered_output_ptr = None
654682

655683

684+
def _allocate_registered_output(size, *, dtype, device):
685+
if device.type != "cuda":
686+
return None, torch.empty(size, dtype=dtype, device=device)
687+
# MORI imports IPC allocation bases, not PyTorch suballocation offsets.
688+
# Use a fresh pool even on growth: old parameter views may still be alive.
689+
with torch.cuda.device(device):
690+
mem_pool = torch.cuda.MemPool()
691+
with torch.cuda.use_mem_pool(mem_pool, device=device):
692+
output = torch.empty(size, dtype=dtype, device=device)
693+
return mem_pool, output
694+
695+
656696
def _tensor_nbytes(tensor: torch.Tensor) -> int:
657697
return tensor.numel() * tensor.element_size()
658698

‎tests/python/ccl/test_torch_fsdp.py‎

Lines changed: 37 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -228,6 +228,9 @@ def test_persistent_release_orders_packing_and_collective(self) -> None:
228228
device = torch.device("cpu")
229229
output = comm.allocate((4,), dtype=torch.float32, device=device)
230230
consumer, packer, gather = MagicMock(), MagicMock(), MagicMock()
231+
gather.device = device
232+
group = MagicMock()
233+
group.size.return_value = 2
231234
with patch.object(torch.cuda, "current_stream", return_value=consumer):
232235
comm.release_output()
233236
comm.release_output()
@@ -240,15 +243,18 @@ def test_persistent_release_orders_packing_and_collective(self) -> None:
240243
order = []
241244
gather.wait_event.side_effect = lambda e: order.append("wait")
242245
collective = MagicMock()
243-
collective.enqueue.side_effect = lambda *a, **kw: order.append("write")
246+
collective.enqueue.side_effect = lambda source, *a, **kw: order.append(
247+
"ready" if source.numel() == 1 else "write"
248+
)
244249
with (
245250
patch.object(torch.cuda, "current_stream", return_value=gather),
246251
patch.object(comm, "_get_collective", return_value=collective),
247252
patch.object(comm, "_validate_tensors"),
248253
patch.object(torch.Tensor, "record_stream"),
249254
):
250-
comm(reused, torch.ones(2), MagicMock())
251-
self.assertEqual(order, ["wait", "write"])
255+
comm(reused, torch.ones(2), group)
256+
self.assertEqual(order, ["wait", "ready", "write"])
257+
collective.register_output_buffer.assert_called_once_with(comm._ready_buffer)
252258
gather.wait_event.assert_called_once_with(event)
253259
packer.synchronize.assert_not_called()
254260
gather.synchronize.assert_not_called()
@@ -259,6 +265,28 @@ def test_release_before_allocation_is_noop(self) -> None:
259265
comm.release_output()
260266
current_stream.assert_not_called()
261267

268+
def test_backends_order_writes_on_the_same_process_group(self):
269+
group = MagicMock()
270+
streams = [MagicMock(), MagicMock()]
271+
order = []
272+
for index, stream in enumerate(streams):
273+
comm = MoriSdmaAllGather()
274+
collective = MagicMock()
275+
stream.wait_event.side_effect = lambda event: order.append("wait")
276+
collective.enqueue.side_effect = lambda *args, **kwargs: order.append("write")
277+
with (
278+
patch.object(comm, "_get_collective", return_value=collective),
279+
patch.object(comm, "_wait_for_peer_consumers"),
280+
patch.object(comm, "_validate_tensors"),
281+
patch.object(torch.cuda, "current_stream", return_value=stream),
282+
patch.object(torch.Tensor, "record_stream"),
283+
):
284+
comm(torch.empty(4), torch.empty(2), group)
285+
stream.record_event.assert_called_once()
286+
if index:
287+
stream.wait_event.assert_called_once_with(streams[0].record_event.return_value)
288+
self.assertEqual(order, ["write", "wait", "write"])
289+
262290
def test_sync_call_uses_original_enqueue_path(self) -> None:
263291
comm = MoriSdmaAllGather(zero_copy_output=False)
264292
collective = MagicMock()
@@ -268,6 +296,7 @@ def test_sync_call_uses_original_enqueue_path(self) -> None:
268296
stream = MagicMock()
269297
with (
270298
patch.object(comm, "_get_collective", return_value=collective),
299+
patch.object(comm, "_wait_for_peer_consumers"),
271300
patch.object(comm, "_validate_tensors"),
272301
patch.object(torch.cuda, "current_stream", return_value=stream),
273302
patch.object(torch.Tensor, "record_stream", autospec=True),
@@ -285,6 +314,7 @@ def test_unaligned_input_uses_process_group_fallback(self) -> None:
285314
work = MagicMock()
286315
with (
287316
patch.object(comm, "_validate_tensors"),
317+
patch.object(torch.cuda, "current_stream"),
288318
patch.object(
289319
torch.distributed, "all_gather_into_tensor", return_value=work
290320
) as fallback,
@@ -309,6 +339,7 @@ def test_param_contiguous_call_preserves_stream_lifetimes(self) -> None:
309339
stream = MagicMock()
310340
with (
311341
patch.object(comm, "_get_collective", return_value=collective),
342+
patch.object(comm, "_wait_for_peer_consumers"),
312343
patch.object(comm, "_validate_tensors"),
313344
patch.object(torch.cuda, "current_stream", return_value=stream),
314345
patch.object(torch.Tensor, "record_stream") as record_stream,
@@ -340,6 +371,7 @@ def rank_major(input, output, count, *, stream):
340371
collective.enqueue.side_effect = rank_major
341372
with (
342373
patch.object(comm, "_get_collective", return_value=collective),
374+
patch.object(comm, "_wait_for_peer_consumers"),
343375
patch.object(comm, "_validate_tensors"),
344376
patch.object(torch.cuda, "current_stream", return_value=stream),
345377
patch.object(torch.Tensor, "record_stream"),
@@ -370,6 +402,7 @@ def test_async_work_orders_each_consumer_after_completion(self) -> None:
370402
order.attach_mock(stream.record_event, "record_event")
371403
with (
372404
patch.object(comm, "_get_collective", return_value=collective),
405+
patch.object(comm, "_wait_for_peer_consumers"),
373406
patch.object(comm, "_validate_tensors"),
374407
patch.object(
375408
torch.cuda, "current_stream",
@@ -402,6 +435,7 @@ def test_param_contiguous_async_call_returns_event_work(self) -> None:
402435
consumer = MagicMock()
403436
with (
404437
patch.object(comm, "_get_collective", return_value=collective),
438+
patch.object(comm, "_wait_for_peer_consumers"),
405439
patch.object(comm, "_validate_tensors"),
406440
patch.object(torch.Tensor, "record_stream"),
407441
patch.object(torch.cuda, "current_stream", side_effect=[stream, consumer]),

‎tests/python/ccl/test_torch_fsdp_pool.py‎

Lines changed: 19 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
"""Distributed correctness and fixed-storage checks for shared FSDP outputs."""
22

33
import copy
4+
import gc
45
import os
56
import socket
67
from datetime import timedelta
@@ -133,12 +134,16 @@ def delayed_consumer(module, args):
133134
pool.close()
134135

135136

136-
def _stream_reuse_case(rank, world_size):
137+
def _stream_reuse_case(rank, world_size, pooled=True):
137138
device = torch.device("cuda", rank)
138139
count = 4096
139-
pool = MoriSdmaAllGatherPool([count * world_size * 4] * 2, group=dist.group.WORLD, device=device)
140+
pool = (
141+
MoriSdmaAllGatherPool([count * world_size * 4] * 2, group=dist.group.WORLD, device=device)
142+
if pooled else None
143+
)
140144
comms = [MoriSdmaAllGather(output_pool=pool, buffer_index=i) for i in range(2)]
141-
pool.initialize()
145+
if pool is not None:
146+
pool.initialize()
142147
gathers = [torch.cuda.Stream(), torch.cuda.Stream()]
143148
consumer = torch.cuda.Stream()
144149
results = []
@@ -164,7 +169,11 @@ def _stream_reuse_case(rank, world_size):
164169
for peer in range(world_size)
165170
])
166171
torch.testing.assert_close(result, expected, rtol=0, atol=0)
167-
pool.close()
172+
if pool is not None:
173+
pool.close()
174+
else:
175+
for comm in comms:
176+
comm._deregister_output_buffer_if_needed()
168177

169178

170179
def _device_case(rank, world_size):
@@ -296,6 +305,12 @@ def _worker(rank, world_size, port):
296305
_configuration_case(rank)
297306
_subgroup_case(rank, world_size)
298307
_persistent_packing_case(rank)
308+
gc.collect()
309+
dist.barrier()
310+
_stream_reuse_case(rank, world_size, pooled=False)
311+
# Release private allocators before launching another case's collectives.
312+
gc.collect()
313+
dist.barrier()
299314
_stream_reuse_case(rank, world_size)
300315
for dtype in (torch.float32, torch.bfloat16):
301316
for async_op in (False, True):

0 commit comments

Comments
 (0)