Skip to content
Merged
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
199 changes: 141 additions & 58 deletions integrations/vllm/libsircl/sircl_ep_all2all.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@
import threading
import weakref
from dataclasses import dataclass
from pathlib import Path
from typing import Any

import torch
Expand Down Expand Up @@ -87,6 +88,7 @@ class _AgRsAll2AllManager:
ALL2ALL_BASE_IS_STUB = True

ENV_FLAG = "SIRCL_EP_ALL2ALL"
ENV_EP_LIB = "SIRCL_EP_LIB"
ENV_MAX_TOKENS = "SIRCL_EP_MAX_TOKENS"
ENV_PREALLOC_TOKENS = "SIRCL_EP_PREALLOC_TOKENS"
ENV_STATIC_A2A = "SIRCL_EP_STATIC_A2A"
Expand Down Expand Up @@ -318,6 +320,7 @@ class _ActiveEpCall:
dtype: torch.dtype = torch.bfloat16
device: torch.device | None = None
lib: Any = None
nccl_lib: Any = None
comm: Any = None
arena: _EpArena | None = None
workspace: Any = None
Expand All @@ -329,9 +332,10 @@ class _ActiveEpCall:
class SirclEpAll2AllManager(_AgRsAll2AllManager):
"""Drop-in ``AgRsAll2AllManager`` replacement backed by ``sirclEpDispatch``/``sirclEpCombine``."""

def __init__(self, cpu_group, tcp_store_group=None, device_comm=None):
def __init__(self, cpu_group, tcp_store_group=None, device_comm=None, ep_lib=None):
super().__init__(cpu_group, tcp_store_group)
self._device_comm = device_comm
self._ep_lib = ep_lib
self._workspace: torch.Tensor | None = None
self._workspace_bytes: int = 0
self._retired: list[torch.Tensor] = []
Expand Down Expand Up @@ -464,7 +468,7 @@ def log_stats(self, reason: str) -> None:

def _resolve_sircl(self, dist_group: Any):
if self._disabled_reason is not None:
return None, None, 0, 0
return None, None, None, 0, 0
comm_obj = None
if self._device_comm is not None:
comm_obj = getattr(self._device_comm, "pynccl_comm", None)
Expand All @@ -473,21 +477,28 @@ def _resolve_sircl(self, dist_group: Any):
if dcomm is not None:
comm_obj = getattr(dcomm, "pynccl_comm", None)
if comm_obj is None or getattr(comm_obj, "disabled", False):
return None, None, 0, 0
return None, None, None, 0, 0
nccl_wrap = getattr(comm_obj, "nccl", None)
lib = getattr(nccl_wrap, "lib", None) if nccl_wrap is not None else None
nccl_lib = getattr(nccl_wrap, "lib", None) if nccl_wrap is not None else None
comm = getattr(comm_obj, "comm", None)
if lib is None or comm is None:
return None, None, 0, 0
if not _bind_ep_prototypes(lib):
self._disabled_reason = "libsircl lacks sirclEpDispatch/sirclEpCombine"
logger.warning("SirclEpAll2AllManager disabled: %s", self._disabled_reason)
return None, None, 0, 0
if nccl_lib is None or comm is None:
return None, None, None, 0, 0
world = int(getattr(comm_obj, "world_size", dist_group.world_size))
rank = int(getattr(comm_obj, "rank", dist_group.rank_in_group))
if world < 3 or world > 8 or world != int(dist_group.world_size):
return None, None, 0, 0
return lib, comm, world, rank
return None, None, None, 0, 0
ep_lib = self._ep_lib
if ep_lib is None:
if not isinstance(nccl_lib, ctypes.CDLL) and _has_ep_symbols(nccl_lib):
ep_lib = nccl_lib
else:
ep_lib = load_ep_library(nccl_lib)
self._ep_lib = ep_lib
if not _bind_ep_prototypes(ep_lib, nccl_lib=nccl_lib):
raise RuntimeError(
"SIRCL-EP companion library lacks sirclEpWorkspaceBytes/sirclEpDispatch/sirclEpCombine"
)
return ep_lib, nccl_lib, comm, world, rank

def _ensure_workspace(
self,
Expand Down Expand Up @@ -564,7 +575,7 @@ def dispatch(
):
meta = getattr(_ACTIVE_META, "current", None)
dist_group = self._get_comm_group(is_sequence_parallel)
lib, comm, world, rank = self._resolve_sircl(dist_group)
lib, nccl_lib, comm, world, rank = self._resolve_sircl(dist_group)
can_use = (
lib is not None
and extra_tensors is None
Expand Down Expand Up @@ -687,7 +698,7 @@ def dispatch(
)
)
if rc != 0:
err_text = _last_error(lib, comm)
err_text = _last_error(nccl_lib, comm)
if self.sircl_dispatches == 0:
self._disabled_reason = f"sirclEpDispatch returned rc={rc}" + (
f" ({err_text})" if err_text else ""
Expand Down Expand Up @@ -740,6 +751,7 @@ def dispatch(
dtype=h_in.dtype,
device=hidden_states.device,
lib=lib,
nccl_lib=nccl_lib,
comm=comm,
arena=arena,
workspace=ws,
Expand Down Expand Up @@ -779,7 +791,7 @@ def combine(
)
)
if rc != 0:
err_text = _last_error(call.lib, call.comm)
err_text = _last_error(call.nccl_lib or call.lib, call.comm)
raise RuntimeError(
f"sirclEpCombine failed with rc={rc}"
f" (rank={call.rank} num_tokens={call.num_tokens} max_tokens={call.max_tokens}"
Expand All @@ -792,53 +804,124 @@ def combine(
return h_out


def _bind_ep_prototypes(lib: ctypes.CDLL) -> bool:
if not (
def _has_ep_symbols(lib: Any) -> bool:
return bool(
hasattr(lib, "sirclEpWorkspaceBytes")
and hasattr(lib, "sirclEpDispatch")
and hasattr(lib, "sirclEpCombine")
):
)


def _ep_library_candidates(nccl_lib: Any = None) -> list[str]:
candidates: list[str] = []
seen: set[str] = set()
raw_name = getattr(nccl_lib, "_name", "") if nccl_lib is not None else ""
if isinstance(raw_name, str) and raw_name:
lib_path = Path(raw_name)
if lib_path.parent != Path(".") or os.sep in raw_name:
for base in (lib_path, Path(os.path.realpath(raw_name))):
sibling = str(base.with_name("libsircl_ep.so"))
if sibling not in seen:
seen.add(sibling)
candidates.append(sibling)
if "libsircl_ep.so" not in seen:
candidates.append("libsircl_ep.so")
return candidates


def load_ep_library(nccl_lib: Any = None, environ=None, loader=ctypes.CDLL) -> Any:
"""Load companion ``libsircl_ep.so`` (fail-closed if missing or incomplete).

Resolution order:
1. ``SIRCL_EP_LIB`` when set (exact path; fails closed if missing/unloadable).
2. Sibling ``libsircl_ep.so`` next to the loaded ``libsircl.so`` (and its realpath).
3. Dynamic linker search path (``libsircl_ep.so``).
"""
env = os.environ if environ is None else environ
explicit = env.get(ENV_EP_LIB, "").strip()
if explicit:
try:
ep_lib = loader(explicit)
except OSError as exc:
raise RuntimeError(
f"SIRCL-EP companion library {ENV_EP_LIB}={explicit!r} could not be loaded: {exc}"
) from exc
if not _bind_ep_prototypes(ep_lib, nccl_lib=nccl_lib):
raise RuntimeError(
f"SIRCL-EP companion library {ENV_EP_LIB}={explicit!r} lacks "
"sirclEpWorkspaceBytes/sirclEpDispatch/sirclEpCombine"
)
return ep_lib

errors: list[str] = []
candidates = _ep_library_candidates(nccl_lib)
for candidate in candidates:
if candidate != "libsircl_ep.so" and not Path(candidate).exists():
errors.append(f"{candidate} (not found)")
continue
try:
ep_lib = loader(candidate)
except OSError as exc:
errors.append(f"{candidate} ({exc})")
continue
if not _bind_ep_prototypes(ep_lib, nccl_lib=nccl_lib):
raise RuntimeError(
f"SIRCL-EP companion library {candidate!r} lacks "
"sirclEpWorkspaceBytes/sirclEpDispatch/sirclEpCombine"
)
return ep_lib

searched = ", ".join(errors) if errors else ", ".join(candidates)
raise RuntimeError(
"SIRCL-EP requires companion library libsircl_ep.so (split from libnccl.so.2), "
f"but it could not be loaded (searched: {searched}); set {ENV_EP_LIB}=/path/to/libsircl_ep.so "
"or place libsircl_ep.so beside libsircl.so"
)


def _bind_ep_prototypes(lib: Any, nccl_lib: Any = None) -> bool:
if not _has_ep_symbols(lib):
return False
if getattr(lib, "_sircl_ep_bound", False):
return True
lib.sirclEpWorkspaceBytes.argtypes = [ctypes.c_int, ctypes.c_int, ctypes.c_size_t]
lib.sirclEpWorkspaceBytes.restype = ctypes.c_size_t
lib.sirclEpDispatch.argtypes = [
ctypes.c_void_p, # hidden_in
ctypes.c_void_p, # topk_ids_in
ctypes.c_void_p, # topk_weights_in
ctypes.c_void_p, # hidden_out
ctypes.c_void_p, # topk_ids_out
ctypes.c_void_p, # topk_weights_out
ctypes.c_void_p, # recv_counts_out
ctypes.c_void_p, # workspace
ctypes.c_size_t, # workspace_bytes
ctypes.c_int, # num_tokens
ctypes.c_int, # max_tokens
ctypes.c_size_t, # hidden_bytes
ctypes.c_int, # top_k
ctypes.c_int, # num_experts
ctypes.c_void_p, # comm
ctypes.c_void_p, # stream
]
lib.sirclEpDispatch.restype = ctypes.c_int
lib.sirclEpCombine.argtypes = [
ctypes.c_void_p, # expert_out_in
ctypes.c_void_p, # hidden_out
ctypes.c_void_p, # workspace
ctypes.c_size_t, # workspace_bytes
ctypes.c_int, # num_tokens
ctypes.c_int, # max_tokens
ctypes.c_size_t, # hidden_dim
ctypes.c_int, # datatype
ctypes.c_void_p, # comm
ctypes.c_void_p, # stream
]
lib.sirclEpCombine.restype = ctypes.c_int
if hasattr(lib, "ncclGetLastError"):
lib.ncclGetLastError.argtypes = [ctypes.c_void_p]
lib.ncclGetLastError.restype = ctypes.c_char_p
lib._sircl_ep_bound = True
if not getattr(lib, "_sircl_ep_bound", False):
lib.sirclEpWorkspaceBytes.argtypes = [ctypes.c_int, ctypes.c_int, ctypes.c_size_t]
lib.sirclEpWorkspaceBytes.restype = ctypes.c_size_t
lib.sirclEpDispatch.argtypes = [
ctypes.c_void_p, # hidden_in
ctypes.c_void_p, # topk_ids_in
ctypes.c_void_p, # topk_weights_in
ctypes.c_void_p, # hidden_out
ctypes.c_void_p, # topk_ids_out
ctypes.c_void_p, # topk_weights_out
ctypes.c_void_p, # recv_counts_out
ctypes.c_void_p, # workspace
ctypes.c_size_t, # workspace_bytes
ctypes.c_int, # num_tokens
ctypes.c_int, # max_tokens
ctypes.c_size_t, # hidden_bytes
ctypes.c_int, # top_k
ctypes.c_int, # num_experts
ctypes.c_void_p, # comm
ctypes.c_void_p, # stream
]
lib.sirclEpDispatch.restype = ctypes.c_int
lib.sirclEpCombine.argtypes = [
ctypes.c_void_p, # expert_out_in
ctypes.c_void_p, # hidden_out
ctypes.c_void_p, # workspace
ctypes.c_size_t, # workspace_bytes
ctypes.c_int, # num_tokens
ctypes.c_int, # max_tokens
ctypes.c_size_t, # hidden_dim
ctypes.c_int, # datatype
ctypes.c_void_p, # comm
ctypes.c_void_p, # stream
]
lib.sirclEpCombine.restype = ctypes.c_int
lib._sircl_ep_bound = True
err_lib = nccl_lib if nccl_lib is not None else lib
if hasattr(err_lib, "ncclGetLastError"):
err_lib.ncclGetLastError.argtypes = [ctypes.c_void_p]
err_lib.ncclGetLastError.restype = ctypes.c_char_p
return True


Expand Down
81 changes: 81 additions & 0 deletions integrations/vllm/libsircl/test_sircl_ep_all2all.py
Original file line number Diff line number Diff line change
Expand Up @@ -1035,3 +1035,84 @@ def test_retired_buffers_are_bounded_and_releasable(ep):
assert released == stats["retired_buffers"]
assert mgr.stats()["retired_buffers"] == 0
assert mgr.stats()["retired_bytes"] == 0


def test_load_ep_library_prefers_sircl_ep_lib_env(ep, tmp_path):
cluster = Cluster()
fake_ep = FakeLib(cluster, 0)
custom = tmp_path / "custom_ep.so"
custom.write_bytes(b"")
seen = []

def fake_loader(path):
seen.append(path)
return fake_ep

loaded = ep.load_ep_library(environ={"SIRCL_EP_LIB": str(custom)}, loader=fake_loader)
assert loaded is fake_ep
assert seen == [str(custom)]


def test_load_ep_library_resolves_sibling_next_to_libsircl(ep, tmp_path):
cluster = Cluster()
fake_ep = FakeLib(cluster, 0)
nccl_path = tmp_path / "libsircl.so"
ep_path = tmp_path / "libsircl_ep.so"
nccl_path.write_bytes(b"")
ep_path.write_bytes(b"")
fake_nccl = types.SimpleNamespace(_name=str(nccl_path), ncclGetLastError=FakeLib._Fn(lambda comm: b"ok"))
seen = []

def fake_loader(path):
seen.append(path)
return fake_ep

loaded = ep.load_ep_library(nccl_lib=fake_nccl, environ={}, loader=fake_loader)
assert loaded is fake_ep
assert seen == [str(ep_path)]


def test_load_ep_library_fails_closed_when_missing(ep, tmp_path):
nccl_path = tmp_path / "libsircl.so"
nccl_path.write_bytes(b"")
fake_nccl = types.SimpleNamespace(_name=str(nccl_path))

def missing_loader(path):
raise OSError(f"{path}: cannot open shared object file")

with pytest.raises(RuntimeError, match="libsircl_ep\\.so"):
ep.load_ep_library(nccl_lib=fake_nccl, environ={}, loader=missing_loader)

with pytest.raises(RuntimeError, match="SIRCL_EP_LIB"):
ep.load_ep_library(environ={"SIRCL_EP_LIB": str(tmp_path / "nope.so")}, loader=missing_loader)


def test_load_ep_library_fails_closed_when_symbols_missing(ep, tmp_path):
bad = types.SimpleNamespace()
ep_path = tmp_path / "libsircl_ep.so"
ep_path.write_bytes(b"")
with pytest.raises(RuntimeError, match="lacks sirclEpWorkspaceBytes"):
ep.load_ep_library(environ={"SIRCL_EP_LIB": str(ep_path)}, loader=lambda _: bad)


def test_split_ep_and_nccl_libraries_report_nccl_last_error(ep):
cluster = Cluster()
_inputs(cluster, [4, 4, 4, 4], seed=107)
full_fake = FakeLib(cluster, 0)
ep_only = types.SimpleNamespace(
sirclEpWorkspaceBytes=full_fake.sirclEpWorkspaceBytes,
sirclEpDispatch=full_fake.sirclEpDispatch,
sirclEpCombine=full_fake.sirclEpCombine,
)
nccl_only = types.SimpleNamespace(
ncclGetLastError=full_fake.ncclGetLastError,
)
node = Node(ep, cluster, 0, static_cap=0, sizes=[4, 4, 4, 4], expert_map=_expert_map(cluster, 0))
node.manager._device_comm.pynccl_comm.nccl.lib = nccl_only
node.manager._ep_lib = ep_only
cluster.error = b"bridge-reported error"
cluster.fail_next = 5
# First dispatch failure falls back with ncclGetLastError fetched from nccl_only (not ep_only).
node.dispatch()
assert "bridge-reported error" in (node.manager._disabled_reason or "")

2 changes: 1 addition & 1 deletion runtime/common/test_libsircl.py
Original file line number Diff line number Diff line change
Expand Up @@ -332,7 +332,7 @@ def test_the_lane_runs_in_the_startup_wait_regime_at_the_librarys_limit():
assert not {"LIBSIRCL_WAIT_REGIME", "SIRCL_STARTUP_WAIT_S", "SIRCL_SERVING_WAIT_S",
"LIBSIRCL_SETUP_TIMEOUT_MS"} & set(environment)
root = Path(__file__).resolve().parents[2]
engine = (root / "spark_transport/libsircl/src/engine.c").read_text(encoding="utf-8")
engine = (root / "spark_transport/libsircl/src/engine_internal.h").read_text(encoding="utf-8")
limit = re.search(r"#define DEFAULT_STARTUP_WAIT_S (\d+)\.0", engine).group(1)
text = (root / "docs/architecture/libsircl.md").read_text(encoding="utf-8")
fail_stop = text[text.index("### Fail-stop"):text.index("### Container settings")]
Expand Down
2 changes: 1 addition & 1 deletion runtime/images/test_libsircl_layer.py
Original file line number Diff line number Diff line change
Expand Up @@ -330,4 +330,4 @@ def test_the_committed_source_holds_the_pack_sources_and_architectures_the_layer
assert not [path for path in files if path.endswith(".fatbin")]
# The fail-stop mode the transport requires: the engine reads LIBSIRCL_FAIL_STOP, so a library built from
# the tree names it, NUL-terminated, among its strings (libsircl.has_fail_stop).
assert b'sccl_env("LIBSIRCL_FAIL_STOP")' in files["src/engine.c"]
assert b'sccl_env("LIBSIRCL_FAIL_STOP")' in files["src/engine_env.c"]
Loading
Loading