Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions docs/symmetric_memory/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,20 @@ The handle also carries `group_name`, the group it was rendezvoused on, as
torch's `hdl.group_name`. A buffer rendezvoused on two groups has two handles,
one per group. The handle holds its group weakly.

## CUDA graphs

Allocation and the first rendezvous of an allocation on a group cannot be
captured, and raise while the current stream is capturing a graph, as in torch.
Allocation maps the block, zeroes the signal pad and synchronizes the device.
`empty()` reaches it only on a pool miss. The first rendezvous exchanges
handles across ranks. Allocate and rendezvous before starting capture.

Later rendezvous calls on the same allocation and group reuse the cached peer
state and are capture-safe. That includes new views of the allocation. So are
`barrier`, `put_signal` and `wait_signal`. Every rank must replay a captured
graph the same number of times, because each replay performs that rank's side
of the synchronization.

## The handle contract

| accessor | returns | offset convention |
Expand Down
3 changes: 2 additions & 1 deletion docs/symmetric_memory/signal.md
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,7 @@ count as an arrival, and a later `wait_signal` would never see its value.
rank's pad, or a spin on a slot nobody will signal.
- **Stream-ordered.** All three are ordinary launches on the current stream, so
they order against surrounding work like any kernel and are safe to capture in
a CUDA graph. Rendezvous is not — it is collective and allocates.
a CUDA graph. A first rendezvous is not — it is collective and synchronizes
the device (see [`api.md`](api.md#cuda-graphs)).
- **No communicator involvement.** Peer pads are plain device pointers, so this
works the same on the CUDA-IPC and NCCL backends.
141 changes: 141 additions & 0 deletions tests/distributed/symmetric_memory/test_graph_capture.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,141 @@
# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.

from __future__ import annotations

import json
import os
import socket
from contextlib import closing
from typing import Any, TYPE_CHECKING


if TYPE_CHECKING:
import pathlib
from collections.abc import Callable

import pytest
import torch
import torch.distributed as dist
import torch.multiprocessing as mp

import torchpyimpl.distributed.symmetric_memory as symm
import torchpyimpl.distributed.symmetric_memory._symm_mem as sm


_N = 1024
_REPLAYS = 3


def _free_port() -> int:
with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as s:
s.bind(("127.0.0.1", 0))
return s.getsockname()[1]


def _init(rank: int, world_size: int, port: int, backend: str) -> torch.device:
os.environ.update(
MASTER_ADDR="127.0.0.1",
MASTER_PORT=str(port),
RANK=str(rank),
WORLD_SIZE=str(world_size),
LOCAL_RANK=str(rank),
)
device = torch.device(f"cuda:{rank}")
torch.cuda.set_device(device)
dist.init_process_group(
backend="nccl", rank=rank, world_size=world_size, device_id=device
)
symm.set_backend(backend)
return device


def _rejected_in_capture(fn: Callable[[], object], stream: torch.cuda.Stream) -> str:
graph = torch.cuda.CUDAGraph()
try:
with torch.cuda.graph(graph, stream=stream):
fn()
except RuntimeError as e:
return str(e)
return ""


def _capture_worker(
rank: int, world_size: int, port: int, out: str, backend: str
) -> None:
device = _init(rank, world_size, port, backend)
pg = dist.group.WORLD
peer = (rank + 1) % world_size
t = symm.empty(_N, dtype=torch.float32, device=device)
fresh = symm.empty(_N, dtype=torch.float32, device=device)
hdl = symm.rendezvous(t, pg)
stream = torch.cuda.Stream()
stream.wait_stream(torch.cuda.current_stream())
with torch.cuda.stream(stream):
hdl.barrier()
torch.cuda.synchronize()

r: dict[str, Any] = {"rank": rank}
r["alloc"] = _rejected_in_capture(
lambda: symm.empty(1 << 22, device=device), stream
)
r["standalone_alloc"] = _rejected_in_capture(lambda: sm.alloc(4096, device), stream)
r["first_rendezvous"] = _rejected_in_capture(
lambda: symm.rendezvous(fresh, pg), stream
)

graph = torch.cuda.CUDAGraph()
with torch.cuda.graph(graph, stream=stream):
cached = symm.rendezvous(t, pg)
view = symm.rendezvous(t[_N // 2 :], pg)
t.fill_(rank + 100.0)
cached.barrier()
r["cached_is_same"] = cached is hdl
r["view_offset_ok"] = view.offset == _N // 2 * 4
for _ in range(_REPLAYS):
graph.replay()
torch.cuda.synchronize()
got = symm.get_buffer(hdl, peer, (_N,), torch.float32)
r["replayed_peer_value_ok"] = bool((got == peer + 100.0).all())

symm.rendezvous(fresh, pg).barrier()
torch.cuda.synchronize()
r["fresh_rendezvous_after"] = True

gathered: list[Any] = [None] * world_size
dist.all_gather_object(gathered, r, group=pg)
if rank == 0:
with open(out, "w") as f:
json.dump({"reports": gathered}, f)
dist.barrier()
dist.destroy_process_group()


@pytest.mark.multi_gpu
@pytest.mark.peer_access
@pytest.mark.parametrize("backend", ["CUDA", "NCCL"])
def test_capture_rejects_setup_and_replays_cached_handles(
backend: str, tmp_path: pathlib.Path
) -> None:
world_size = min(torch.cuda.device_count(), 8)
out = str(tmp_path / "reports.json")
mp.spawn(
_capture_worker,
args=(world_size, _free_port(), out, backend),
nprocs=world_size,
)
with open(out) as f:
reports = json.load(f)["reports"]
assert len(reports) == world_size
for r in reports:
rank = r["rank"]
for op in ("alloc", "standalone_alloc", "first_rendezvous"):
assert "capturing a graph" in r[op], f"rank {rank}: {op} gave {r[op]!r}"
assert "before starting capture" in r["first_rendezvous"], rank
assert r["cached_is_same"], f"rank {rank}: cached rendezvous built a new handle"
assert r["view_offset_ok"], f"rank {rank}: wrong view offset in capture"
assert r["replayed_peer_value_ok"], f"rank {rank}: replay saw a stale peer"
assert r["fresh_rendezvous_after"], rank
20 changes: 20 additions & 0 deletions tests/distributed/symmetric_memory/test_symm_mem.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ def _unfrozen_signal_pad(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(sm, "_signal_pad_size", None)
monkeypatch.setattr(sm, "_pad_frozen", False)
monkeypatch.setattr(torch.cuda, "device", _fake_cuda_device)
monkeypatch.setattr(torch.cuda, "is_current_stream_capturing", lambda: False)


def test_front_region_matches_torch() -> None:
Expand Down Expand Up @@ -331,3 +332,22 @@ def test_rendezvous_rejects_uncovered_ptr(monkeypatch: pytest.MonkeyPatch) -> No
allocator, buf = _allocator_with_one_alloc(monkeypatch)
with pytest.raises(KeyError, match="no symmetric allocation covers"):
allocator.rendezvous(buf - 8, 11, 0, 1, torch.device("cpu"))


def test_capture_rejects_alloc_and_first_rendezvous(
monkeypatch: pytest.MonkeyPatch,
) -> None:
allocator, buf = _allocator_with_one_alloc(monkeypatch)
device = torch.device("cpu")
cached = allocator.rendezvous(buf, 11, 0, 1, device)
monkeypatch.setattr(torch.cuda, "is_current_stream_capturing", lambda: True)

with pytest.raises(RuntimeError, match="capturing a graph"):
allocator.alloc(_NBYTES, 0)
with pytest.raises(RuntimeError, match="before starting capture"):
allocator.rendezvous(buf, 12, 0, 1, device)

assert allocator.rendezvous(buf, 11, 0, 1, device) is cached
assert allocator.rendezvous(buf + 64, 11, 0, 1, device).offset == 64
stats = allocator.cache_stats()
assert stats["records"] == 1 and stats["peer_alloc_infos"] == 1
25 changes: 25 additions & 0 deletions torchpyimpl/distributed/symmetric_memory/_symm_mem.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,16 @@ def _device_index(device: torch.device | int | None) -> int:
return device.index if device.index is not None else torch.cuda.current_device()


def check_not_capturing(device: int, op: str, hint: str) -> None:
with torch.cuda.device(device):
capturing = torch.cuda.is_current_stream_capturing()
if capturing:
raise RuntimeError(
f"{op}: not supported while the current CUDA stream is capturing "
f"a graph. {hint}"
)


@dataclass
class _PeerAllocInfo:
window: object
Expand Down Expand Up @@ -178,6 +188,13 @@ def alloc(
stream: int | None = None,
) -> int:
idx = _device_index(device)
check_not_capturing(
idx,
"symmetric memory allocation",
"Allocation maps the block, zeroes the signal pad and synchronizes "
"the device. Allocate the buffer with empty() before starting "
"capture.",
)
global _signal_pad_size, _pad_frozen
_signal_pad_size = signal_pad_bytes()
_pad_frozen = True
Expand Down Expand Up @@ -450,6 +467,14 @@ def rendezvous(
with rec.reg_lock:
pai = rec.per_comm.get(comm_ptr)
if pai is None:
check_not_capturing(
rec.device,
"the first rendezvous of a symmetric allocation",
"It exchanges handles across ranks and synchronizes the "
"device. Call rendezvous(tensor, group) once before "
"starting capture; later calls on the same buffer reuse "
"the cached handle.",
)
pai = self.establish_peers(rec, comm_ptr, world_size, device, group)
rec.per_comm[comm_ptr] = pai
handle = self._make_handle(
Expand Down
Loading