diff --git a/docs/operations/install-reference.md b/docs/operations/install-reference.md index 951f8302..984bb684 100644 --- a/docs/operations/install-reference.md +++ b/docs/operations/install-reference.md @@ -838,6 +838,7 @@ flag, the profile's value applies. | `--save-cpu` | vLLM's shared-memory reader window (container variable `SPARKRING_SHM_BUSY_LOOP_S`) | a switch: readers poll 2 ms after a read instead of one second | | `--row-owned-prefill` | Eager prefill with replicated Engram projection and decode-only CUDA graphs | experimental [DeepSeek V4.1-Flash-1017 on a four-Spark SIRCL path](../../integrations/vllm/ds41_row_shard/README.md#install-on-a-four-spark-sircl-path), via `sparkring install` | | `--chain-all-gather` | Direct-link all-gather on a SIRCL chain | with `--row-owned-prefill` and no matching TP tuning table | +| `--expert-parallel` | Expert parallelism at the tensor width: `--enable-expert-parallel` with `--all2all-backend allgather_reducescatter`, vLLM's own weight loader, and the container variable `SIRCL_B12X_EP_MOE=1`. With `--row-owned-prefill` it also sets the libsircl link geometry measured on that deployment (1 MiB slot and pieces, 64 KiB one-shot ceiling) | experimental DeepSeek V4.1-Flash-1017 on `--transport libsircl`, via `sparkring install`, alone or with `--row-owned-prefill` ([record](../../performance/records/deepseek-v41-flash/row-owned-tp4-ep4-libsircl-20261121.md)) | | `--reasoning-effort LEVEL` | the model's default effort level, in `--default-chat-template-kwargs` on Node A | one of the model's [levels](#thinking) | | `--thinking off` | the model's default thinking, in `--default-chat-template-kwargs` on Node A | thinking stays off unless a request turns it on | | `--api-port N` | `--port` | the TCP port of the model's API, 1024 to 65535 ([API endpoint](#api-endpoint)) | diff --git a/integrations/vllm/ds41_row_shard/ds41_row_shard/__init__.py b/integrations/vllm/ds41_row_shard/ds41_row_shard/__init__.py index 3dd3acf9..e11838a4 100644 --- a/integrations/vllm/ds41_row_shard/ds41_row_shard/__init__.py +++ b/integrations/vllm/ds41_row_shard/ds41_row_shard/__init__.py @@ -233,15 +233,30 @@ def patch_attention(module) -> None: ) +def _ep_moe_deferral_allowed() -> bool: + return os.environ.get("SIRCL_B12X_EP_MOE", "").strip().lower() in ( + "1", + "true", + "on", + "yes", + ) + + # -- MoE deferral at TP8 ----------------------------------------------------- def _validate_moe_deferral(runner: Any) -> None: - """GLM's ``validate_moe_deferral`` with TP8 admitted beside TP2 and TP4.""" + """GLM's ``validate_moe_deferral`` with TP8 and TP+EP (no all2all) admitted.""" config = runner.moe_config parallel = config.moe_parallel_config + tp_only_ok = config.tp_size in SUPPORTED_WORLDS and config.ep_size == 1 + tp_ep_ok = ( + _ep_moe_deferral_allowed() + and config.ep_size in SUPPORTED_WORLDS + and config.tp_size * config.ep_size in SUPPORTED_WORLDS + and not parallel.use_all2all_kernels + ) if ( - config.tp_size not in SUPPORTED_WORLDS + not (tp_only_ok or tp_ep_ok) or config.dp_size != 1 - or config.ep_size != 1 or config.pcp_size != 1 or config.is_sequence_parallel or config.skip_final_all_reduce @@ -284,13 +299,14 @@ def _static_error(model, world: int) -> str | None: if ( get_pp_group().world_size != 1 or parallel.data_parallel_size != 1 - or parallel.enable_expert_parallel + or (parallel.enable_expert_parallel and not _ep_moe_deferral_allowed()) or getattr(parallel, "enable_eplb", False) or model.use_sequence_parallel or model.use_mega_moe ): raise RowShardRefused( - "row ownership requires PP1, DP1, no expert parallelism, " + "row ownership requires PP1, DP1, no expert parallelism " + "(unless SIRCL_B12X_EP_MOE=1 without all2all), " "no sequence parallelism and no mega-MoE" ) layers = owned_layers( @@ -317,8 +333,9 @@ def _static_error(model, world: int) -> str | None: if ffn.use_mega_moe: raise RowShardRefused(f"layer {index} uses mega-MoE") _validate_moe_deferral(ffn.experts) - if ffn.experts.moe_config.tp_size != world: - raise RowShardRefused(f"layer {index} MoE TP size differs") + moe_cfg = ffn.experts.moe_config + if moe_cfg.tp_size * moe_cfg.ep_size != world: + raise RowShardRefused(f"layer {index} MoE TP*EP size differs") engram = getattr(layer, "engram", None) if engram is not None: kind = type(engram.wkv).__name__ diff --git a/integrations/vllm/libsircl/sircl_ep_all2all.py b/integrations/vllm/libsircl/sircl_ep_all2all.py new file mode 100644 index 00000000..3d5643e3 --- /dev/null +++ b/integrations/vllm/libsircl/sircl_ep_all2all.py @@ -0,0 +1,956 @@ +"""Opt-in SIRCL-EP GPU-driven all-to-all manager for vLLM DP + EP. + +Activated when ``SIRCL_EP_ALL2ALL=1`` is set and the ``libsircl`` vLLM plugin +runs. Subclasses ``AgRsAll2AllManager`` so vLLM's existing +``MoEPrepareAndFinalizeNaiveDPEPModular`` pipeline runs ``sirclEpDispatch`` and +``sirclEpCombine`` directly over ``libsircl``'s point-to-point RDMA channels +(zero extra queue pairs), with an automatic fallback to ``AgRsAll2AllManager`` +for unsupported calls (extra tensors, non-linear expert maps, or capacities +above ``SIRCL_EP_MAX_TOKENS``). + +Two exchange paths, both on the same ``libsircl`` entry points: + +``dynamic`` + The exchange capacity is ``max`` over every rank's token count, learnt from + vLLM's ``_get_sizes`` collective once per layer, so it wastes no rows. That + collective returns a host-visible count, which is one host synchronization + per MoE layer and cannot be captured into a CUDA graph. + +``static`` (``SIRCL_EP_STATIC_A2A=1``) + The capacity is one constant for the whole run, ``SIRCL_EP_STATIC_A2A_MAX_TOKENS``, + so ``dispatch`` and ``combine`` make no collective, read no device result and + synchronize nothing: they are plain kernel launches into buffers reused from a + grow-only arena. The manager then contributes no host synchronization and no + allocation that a CUDA graph capture would refuse; whether vLLM captures the + layer is vLLM's decision. Rows a peer never routes stay in the padded tail of + every rank's slice; the kernel masks them with a non-local expert ID and a zero + weight, so they never reach an expert. + +Why the capacity is a constant rather than a per-step or per-graph value: the +capacity is also the row stride of every rank's slice, and ``combine`` strides with +it, so **all ranks of the group must pass the same value in the same layer**. Any +rule that reads this rank's own state (its token count, a bucket derived from that +count, its replay size) can differ from a peer's and breaks the channel with a size +mismatch. In particular the data-parallel ranks do not share a token count on eager steps - one +rank holds the request while the others hold none - and a rung derived from that +count made the first request fail at DP4. A constant is identical on every rank for +every eager step and for every captured graph, so graphs of different sizes can be +replayed against each other. + +Eligibility is decided from state that is already identical across ranks: + +- ``capturing``: vLLM captures the same sizes on every rank, so the constant + applies; a capture size above the cap takes its own size as the capacity, and + ``SIRCL_EP_STATIC_A2A_MAX_TOKENS`` must cover the largest capture size for every + graph to share one stride. +- eager: the bound comes from ``ForwardContext.dp_metadata``, which vLLM + synchronizes across the data-parallel ranks before the forward pass - the per-rank + counts and their maximum, as CPU tensors, so reading them costs no device + synchronization. Every rank then makes the same decision: static when the bound + fits the cap, dynamic when it does not, and dynamic when the metadata is absent + (a step whose bound cannot be proved common). +""" +from __future__ import annotations + +import atexit +import ctypes +import inspect +import logging +import os +import threading +import weakref +from dataclasses import dataclass +from typing import Any + +import torch + +_LOGGER_NAME = f"vllm.{__name__}" + +try: + from vllm.logger import init_logger as _init_logger + + logger = _init_logger(_LOGGER_NAME) +except ImportError: + logger = logging.getLogger(_LOGGER_NAME) + +try: + from vllm.distributed.device_communicators.all2all import ( + AgRsAll2AllManager as _AgRsAll2AllManager, + ) + + ALL2ALL_BASE_IS_STUB = False +except ImportError: # offline imports: install() refuses this base + + class _AgRsAll2AllManager: + """Placeholder for vLLM's manager so this module imports without vLLM.""" + + ALL2ALL_BASE_IS_STUB = True + +ENV_FLAG = "SIRCL_EP_ALL2ALL" +ENV_MAX_TOKENS = "SIRCL_EP_MAX_TOKENS" +ENV_PREALLOC_TOKENS = "SIRCL_EP_PREALLOC_TOKENS" +ENV_STATIC_A2A = "SIRCL_EP_STATIC_A2A" +ENV_STATIC_MAX_TOKENS = "SIRCL_EP_STATIC_A2A_MAX_TOKENS" +ENV_MAX_RETIRED_BUFFERS = "SIRCL_EP_MAX_RETIRED_BUFFERS" +ENV_MAX_RETIRED_BYTES = "SIRCL_EP_MAX_RETIRED_BYTES" +DEFAULT_STATIC_MAX_TOKENS = 96 +DEFAULT_MAX_RETIRED_BUFFERS = 16 +DEFAULT_MAX_RETIRED_BYTES = 256 * 1024 * 1024 + +# One greppable summary line per manager: first static dispatch, every STATS_INTERVAL +# dispatches, and at process exit, so a benchmark can read the counters out of a container log. +STATS_TAG = "SIRCL_EP_STATS" +STATS_INTERVAL = 5000 + +_INSTALLED = False +_ACTIVE_META = threading.local() +_LIVE_MANAGERS: "weakref.WeakSet[Any]" = weakref.WeakSet() +_ATEXIT_REGISTERED = False + +# NCCL datatype constants matching spark_transport/libsircl/include/nccl.h +_NCCL_FLOAT16 = 6 +_NCCL_FLOAT32 = 7 +_NCCL_BFLOAT16 = 9 +_TORCH_TO_NCCL_DTYPE = { + torch.float16: _NCCL_FLOAT16, + torch.float32: _NCCL_FLOAT32, + torch.bfloat16: _NCCL_BFLOAT16, +} + + +def enabled(environ=None) -> bool: + env = os.environ if environ is None else environ + return env.get(ENV_FLAG, "").strip().lower() in ("1", "true", "on", "yes") + + +def static_enabled(environ=None) -> bool: + env = os.environ if environ is None else environ + return env.get(ENV_STATIC_A2A, "").strip().lower() in ("1", "true", "on", "yes") + + +def _parse_int_env(name: str, default: int) -> int: + raw = os.environ.get(name, "").strip() + if not raw: + return default + try: + val = int(raw) + return val if val > 0 else default + except ValueError: + return default + + +def _shared_capacity(bound: int, cap: int) -> int: + """The exchange capacity for a step whose cross-rank token bound is ``bound``. + + ``cap`` when the bound fits it, ``0`` when it does not (the caller then takes the + dynamic path). The capacity is a constant, never a function of the bound: it is + also the stride every rank's slice is laid out with, so a value that differs + between ranks breaks the channel with a size mismatch. + """ + return cap if cap > 0 and 0 < bound <= cap else 0 + + +def _tokens_across_dp() -> int | None: + """vLLM's token bound for this step across the data-parallel ranks, or ``None``. + + ``ForwardContext.dp_metadata`` carries the per-rank token counts and their + maximum as CPU tensors, synchronized before the forward pass, so reading them + costs no device synchronization and every rank reads the same numbers. Both + fields are consulted because the DeepSeek-V4.1 CED hook rewrites the per-rank + counts without rewriting the maximum: the larger of the two is the safe bound. + ``None`` means this step cannot prove a bound every rank shares. + """ + try: + from vllm.forward_context import get_forward_context + + metadata = get_forward_context().dp_metadata + except Exception: + return None + if metadata is None: + return None + bound = 0 + for name in ("max_tokens_across_dp_cpu", "num_tokens_across_dp_cpu"): + value = getattr(metadata, name, None) + if value is None: + continue + if getattr(getattr(value, "device", None), "type", "cpu") != "cpu": + # A device-resident count would synchronize the device, and inside a capture it would + # be illegal: treat the step as having no provable bound instead. + return None + try: + bound = max(bound, int(value.max()) if hasattr(value, "max") else int(value)) + except Exception: + return None + return bound or None + + +def _stats_logger(): + """vLLM's logger for this module, resolved at call time so it carries vLLM's handlers. + + A process that imports this module before vLLM configures logging keeps a logger + with no handler, so the summary would never reach the container log; resolving it + per summary takes vLLM's configured logger. + """ + try: + from vllm.logger import init_logger + + return init_logger(_LOGGER_NAME) + except Exception: + return logger + + +def _log_at_exit() -> None: + """Write one ``SIRCL_EP_STATS`` summary per live manager when the process ends.""" + for manager in list(_LIVE_MANAGERS): + try: + manager.log_stats("atexit") + except Exception: + continue + + +def _register_for_exit(manager: Any) -> None: + """Track a manager for the exit summary, installing the single ``atexit`` handler once.""" + global _ATEXIT_REGISTERED + try: + _LIVE_MANAGERS.add(manager) + except TypeError: # no weak reference: the exit line is skipped, nothing else changes + return + if not _ATEXIT_REGISTERED: + _ATEXIT_REGISTERED = True + atexit.register(_log_at_exit) + + +def _last_error(lib: ctypes.CDLL, comm: Any) -> str: + if not hasattr(lib, "ncclGetLastError"): + return "" + try: + raw = lib.ncclGetLastError(comm) + if not raw: + return "" + return raw.decode("utf-8", errors="replace") if isinstance(raw, bytes) else str(raw) + except Exception: + return "" + + +class _EpArena: + """Device buffers for one exchange geometry: ``(world, hidden_dim, dtype, top_k, device)``. + + ``hidden``/``ids``/``weights`` hold the dispatch output, ``world * max_tokens`` + rows: every rank's slice, its routed rows first and its padded tail behind + them. ``combine_out`` holds ``max_tokens`` rows, the combine output for this + rank's own tokens. ``counts`` receives the per-peer row counts the kernel + writes (diagnostics only; nothing on the hot path reads it). + + Both row counts grow monotonically. A growth allocates new tensors and + returns the displaced ones so the caller can retire, not free, them: a CUDA + graph captured earlier has the old addresses baked in, so keeping every + retired allocation alive keeps every replay pointing at live memory. + """ + + __slots__ = ( + "world", + "hidden_dim", + "dtype", + "top_k", + "device", + "rows", + "combine_rows", + "hidden", + "ids", + "weights", + "combine_out", + "counts", + ) + + def __init__(self, world: int, hidden_dim: int, dtype: torch.dtype, top_k: int, device: torch.device): + self.world = world + self.hidden_dim = hidden_dim + self.dtype = dtype + self.top_k = top_k + self.device = device + self.rows = 0 + self.combine_rows = 0 + self.hidden: torch.Tensor | None = None + self.ids: torch.Tensor | None = None + self.weights: torch.Tensor | None = None + self.combine_out: torch.Tensor | None = None + self.counts = torch.empty((world,), dtype=torch.int32, device=device) + + def covers(self, rows: int, combine_rows: int) -> bool: + return rows <= self.rows and combine_rows <= self.combine_rows + + def grow(self, rows: int, combine_rows: int) -> list[torch.Tensor]: + """Allocate buffers covering these row counts; return the displaced tensors to retire.""" + displaced: list[torch.Tensor] = [] + if rows > self.rows: + displaced += [tensor for tensor in (self.hidden, self.ids, self.weights) if tensor is not None] + self.hidden = torch.empty((rows, self.hidden_dim), dtype=self.dtype, device=self.device) + self.ids = torch.empty((rows, self.top_k), dtype=torch.int32, device=self.device) + self.weights = torch.empty((rows, self.top_k), dtype=torch.float32, device=self.device) + self.rows = rows + if combine_rows > self.combine_rows: + if self.combine_out is not None: + displaced.append(self.combine_out) + self.combine_out = torch.empty((combine_rows, self.hidden_dim), dtype=self.dtype, device=self.device) + self.combine_rows = combine_rows + return displaced + + +def _is_linear_expert_map(expert_map: torch.Tensor, world: int, rank: int) -> bool: + if expert_map.ndim != 1 or expert_map.dtype != torch.int32: + return False + num_experts = int(expert_map.numel()) + if num_experts < world or (num_experts % world) != 0: + return False + per_rank = num_experts // world + expected = torch.full((num_experts,), -1, dtype=torch.int32, device=expert_map.device) + lo = rank * per_rank + expected[lo : lo + per_rank] = torch.arange(per_rank, dtype=torch.int32, device=expert_map.device) + return bool(torch.equal(expert_map, expected)) + + +@dataclass +class _ActiveEpCall: + used_sircl: bool + num_tokens: int = 0 + max_tokens: int = 0 + hidden_dim: int = 0 + dtype: torch.dtype = torch.bfloat16 + device: torch.device | None = None + lib: Any = None + comm: Any = None + arena: _EpArena | None = None + workspace: Any = None + workspace_bytes: int = 0 + static: bool = False + rank: int = 0 + + +class SirclEpAll2AllManager(_AgRsAll2AllManager): + """Drop-in ``AgRsAll2AllManager`` replacement backed by ``sirclEpDispatch``/``sirclEpCombine``.""" + + def __init__(self, cpu_group, tcp_store_group=None, device_comm=None): + super().__init__(cpu_group, tcp_store_group) + self._device_comm = device_comm + self._workspace: torch.Tensor | None = None + self._workspace_bytes: int = 0 + self._retired: list[torch.Tensor] = [] + self._retired_bytes: int = 0 + self._max_retired_buffers: int = _parse_int_env( + ENV_MAX_RETIRED_BUFFERS, DEFAULT_MAX_RETIRED_BUFFERS + ) + self._max_retired_bytes: int = _parse_int_env( + ENV_MAX_RETIRED_BYTES, DEFAULT_MAX_RETIRED_BYTES + ) + self._has_captured: bool = False + self.retired_evictions: int = 0 + self._arenas: dict[tuple[int, int, torch.dtype, int, torch.device], _EpArena] = {} + self._linear_map_cache: dict[tuple[int, int, int, int], bool] = {} + self._active_call: _ActiveEpCall | None = None + self._max_tokens_cap = _parse_int_env(ENV_MAX_TOKENS, 4096) + self._prealloc_tokens = _parse_int_env(ENV_PREALLOC_TOKENS, 512) + self._static_max_tokens = min( + _parse_int_env(ENV_STATIC_MAX_TOKENS, DEFAULT_STATIC_MAX_TOKENS), self._max_tokens_cap + ) if static_enabled() else 0 + self._logged_static_buckets: set[int] = set() + self._warned_oversized_captures: set[int] = set() + self._disabled_reason: str | None = None + self.sircl_dispatches: int = 0 + self.sircl_combines: int = 0 + self.agrs_fallbacks: int = 0 + self.static_dispatches: int = 0 + self.dynamic_dispatches: int = 0 + self.size_exchanges: int = 0 + self.arena_allocations: int = 0 + self.last_num_tokens: int = 0 + self.last_max_tokens: int = 0 + _register_for_exit(self) + + # -- device access, overridden by offline tests that have no CUDA device ------------------ + + def _capturing(self) -> bool: + """Whether this stream is inside a CUDA graph capture: no allocation may happen there.""" + return bool(torch.cuda.is_available() and torch.cuda.is_current_stream_capturing()) + + def _shared_tokens(self) -> int | None: + """The token bound every data-parallel rank agrees on for this step, or ``None``.""" + return _tokens_across_dp() + + def _on_device(self, tensor: torch.Tensor) -> bool: + """Whether the tensor lives in device memory, as ``libsircl`` requires.""" + return bool(tensor.is_cuda) + + def _stream_ptr(self, device: torch.device) -> ctypes.c_void_p: + return ctypes.c_void_p(torch.cuda.current_stream(device).cuda_stream) + + def _synchronize_device(self, device: torch.device) -> None: + if device.type == "cuda" and torch.cuda.is_available() and not self._capturing(): + torch.cuda.synchronize(device) + + def _retire_buffers(self, tensors: list[torch.Tensor]) -> None: + """Retire displaced buffers under a bounded count/byte budget so memory cannot grow unbounded.""" + if not tensors: + return + for tensor in tensors: + self._retired.append(tensor) + self._retired_bytes += int(tensor.numel()) * int(tensor.element_size()) + if self._capturing(): + return + evicted: list[torch.Tensor] = [] + while len(self._retired) > self._max_retired_buffers or ( + self._retired_bytes > self._max_retired_bytes and len(self._retired) > 1 + ): + oldest = self._retired.pop(0) + self._retired_bytes = max( + 0, self._retired_bytes - int(oldest.numel()) * int(oldest.element_size()) + ) + evicted.append(oldest) + if evicted: + synced_devices: set[torch.device] = set() + for tensor in evicted: + if tensor.device not in synced_devices: + self._synchronize_device(tensor.device) + synced_devices.add(tensor.device) + self.retired_evictions += len(evicted) + if self._has_captured: + logger.warning( + "SIRCL-EP evicted %d retired buffer(s) after CUDA graph capture to stay within " + "budget (%d buffers / %d bytes); recapture graphs if old shapes are replayed", + len(evicted), + self._max_retired_buffers, + self._max_retired_bytes, + ) + + def release_retired(self) -> int: + """Synchronize device streams and release all retired buffers (no-op during capture).""" + if self._capturing() or not self._retired: + return 0 + synced_devices: set[torch.device] = set() + for tensor in self._retired: + if tensor.device not in synced_devices: + self._synchronize_device(tensor.device) + synced_devices.add(tensor.device) + count = len(self._retired) + self._retired.clear() + self._retired_bytes = 0 + self.retired_evictions += count + return count + + def stats(self) -> dict[str, int]: + """Counters for a benchmark run: which path each call took and what it had to allocate.""" + return { + "dispatches": self.sircl_dispatches, + "combines": self.sircl_combines, + "static_dispatches": self.static_dispatches, + "dynamic_dispatches": self.dynamic_dispatches, + "size_exchanges": self.size_exchanges, + "agrs_fallbacks": self.agrs_fallbacks, + "arena_allocations": self.arena_allocations, + "retired_buffers": len(self._retired), + "retired_bytes": self._retired_bytes, + "retired_evictions": self.retired_evictions, + "last_num_tokens": self.last_num_tokens, + "last_max_tokens": self.last_max_tokens, + } + + def log_stats(self, reason: str) -> None: + """Write one ``SIRCL_EP_STATS`` line: the counters a benchmark reads out of a log.""" + counters = " ".join(f"{key}={value}" for key, value in self.stats().items()) + _stats_logger().info( + "%s reason=%s static_cap=%d %s", STATS_TAG, reason, self._static_max_tokens, counters + ) + + # -- setup ------------------------------------------------------------------------------ + + def _resolve_sircl(self, dist_group: Any): + if self._disabled_reason is not None: + return None, None, 0, 0 + comm_obj = None + if self._device_comm is not None: + comm_obj = getattr(self._device_comm, "pynccl_comm", None) + if comm_obj is None: + dcomm = getattr(dist_group, "device_communicator", None) + 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 + nccl_wrap = getattr(comm_obj, "nccl", None) + 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 + 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 + + def _ensure_workspace( + self, + lib: ctypes.CDLL, + world: int, + max_tokens: int, + hidden_bytes: int, + device: torch.device, + ) -> torch.Tensor | None: + need = int(lib.sirclEpWorkspaceBytes(world, max_tokens, hidden_bytes)) + if need <= 0: + return None + if self._workspace is not None and self._workspace_bytes >= need and self._workspace.device == device: + return self._workspace + if self._capturing(): + return None + alloc_tokens = max(max_tokens, min(self._prealloc_tokens, self._max_tokens_cap)) + alloc_bytes = int(lib.sirclEpWorkspaceBytes(world, alloc_tokens, hidden_bytes)) + if self._workspace is not None: + self._retire_buffers([self._workspace]) + self.arena_allocations += 1 + self._workspace = torch.empty((alloc_bytes,), dtype=torch.uint8, device=device) + self._workspace_bytes = alloc_bytes + return self._workspace + + def _ensure_arena( + self, + world: int, + max_tokens: int, + hidden_dim: int, + dtype: torch.dtype, + top_k: int, + device: torch.device, + ) -> _EpArena | None: + """Buffers for this geometry covering ``world * max_tokens`` and ``max_tokens`` rows.""" + rows = world * max_tokens + key = (world, hidden_dim, dtype, top_k, device) + arena = self._arenas.get(key) + if arena is None: + if self._capturing(): + return None + arena = _EpArena(world, hidden_dim, dtype, top_k, device) + self._arenas[key] = arena + if arena.covers(rows, max_tokens): + return arena + if self._capturing(): + return None + self._retire_buffers(arena.grow(rows, max_tokens)) + self.arena_allocations += 1 + return arena + + def _check_linear_map(self, expert_map: torch.Tensor | None, world: int, rank: int) -> bool: + if expert_map is None: + return False + key = (expert_map.data_ptr(), int(expert_map.numel()), world, rank) + cached = self._linear_map_cache.get(key) + if cached is not None: + return cached + if self._capturing(): + return False + ok = _is_linear_expert_map(expert_map, world, rank) + self._linear_map_cache[key] = ok + return ok + + # -- the pipeline's two calls ----------------------------------------------------------- + + def dispatch( + self, + hidden_states: torch.Tensor, + topk_weights: torch.Tensor, + topk_ids: torch.Tensor, + is_sequence_parallel: bool = False, + extra_tensors: list[torch.Tensor] | None = None, + ): + meta = getattr(_ACTIVE_META, "current", None) + dist_group = self._get_comm_group(is_sequence_parallel) + lib, comm, world, rank = self._resolve_sircl(dist_group) + can_use = ( + lib is not None + and extra_tensors is None + and meta is not None + and self._on_device(hidden_states) + and hidden_states.ndim == 2 + and hidden_states.dtype in _TORCH_TO_NCCL_DTYPE + and topk_ids.ndim == 2 + and topk_weights.ndim == 2 + ) + max_tokens = 0 + is_static = False + if can_use: + num_experts, expert_map = meta + num_tokens = int(hidden_states.shape[0]) + hidden_dim = int(hidden_states.shape[1]) + hidden_bytes = hidden_dim * hidden_states.element_size() + top_k = int(topk_ids.shape[1]) + capacity = 0 + if self._static_max_tokens: + if self._capturing(): + self._has_captured = True + # Every rank captures the same sizes in lockstep, so the constant capacity + # applies; a capture size above it keeps its own size so that graph can run. + capacity = max(num_tokens, self._static_max_tokens) + if num_tokens > self._static_max_tokens and num_tokens not in self._warned_oversized_captures: + self._warned_oversized_captures.add(num_tokens) + logger.warning( + "SIRCL-EP static capacity: capture size %d exceeds %s=%d; raise it to %d so every " + "captured graph shares one exchange stride", + num_tokens, + ENV_STATIC_MAX_TOKENS, + self._static_max_tokens, + num_tokens, + ) + else: + # Eager: the bound comes from metadata vLLM synchronized across the DP ranks, + # so every rank decides alike. Absent metadata means no provable common + # bound, and every rank takes the dynamic path. + bound = self._shared_tokens() + if bound is not None: + capacity = _shared_capacity(max(int(bound), num_tokens), self._static_max_tokens) + if capacity: + max_tokens, is_static = capacity, True + else: + sizes = self._get_sizes(num_tokens, dist_group) + self.size_exchanges += 1 + max_tokens = max(max(int(s) for s in sizes), 1) + is_linear = self._check_linear_map(expert_map, world, rank) + if ( + num_experts < world + or (num_experts % world) != 0 + or (hidden_bytes % 16) != 0 + or top_k < 1 + or top_k > 16 + or not is_linear + ): + can_use = False + elif max_tokens > self._max_tokens_cap: + if self._workspace is None and not self._capturing(): + self._ensure_workspace( + lib, + world, + min(self._prealloc_tokens, self._max_tokens_cap), + hidden_bytes, + hidden_states.device, + ) + can_use = False + + arena = None + if can_use: + ws = self._ensure_workspace(lib, world, max_tokens, hidden_bytes, hidden_states.device) + arena = ( + self._ensure_arena(world, max_tokens, hidden_dim, hidden_states.dtype, top_k, hidden_states.device) + if ws is not None + else None + ) + if ws is None or arena is None: + can_use = False + + if not can_use: + self.agrs_fallbacks += 1 + self._active_call = _ActiveEpCall(used_sircl=False) + return super().dispatch( + hidden_states, + topk_weights, + topk_ids, + is_sequence_parallel=is_sequence_parallel, + extra_tensors=extra_tensors, + ) + + h_in = hidden_states if hidden_states.is_contiguous() else hidden_states.contiguous() + ids_in = topk_ids if (topk_ids.dtype == torch.int32 and topk_ids.is_contiguous()) else topk_ids.to(torch.int32).contiguous() + wts_in = topk_weights if (topk_weights.dtype == torch.float32 and topk_weights.is_contiguous()) else topk_weights.to(torch.float32).contiguous() + + total_rows = world * max_tokens + h_out = arena.hidden[:total_rows] + ids_out = arena.ids[:total_rows] + wts_out = arena.weights[:total_rows] + stream_ptr = self._stream_ptr(hidden_states.device) + + rc = int( + lib.sirclEpDispatch( + ctypes.c_void_p(h_in.data_ptr() if num_tokens > 0 else 0), + ctypes.c_void_p(ids_in.data_ptr() if num_tokens > 0 else 0), + ctypes.c_void_p(wts_in.data_ptr() if num_tokens > 0 else 0), + ctypes.c_void_p(h_out.data_ptr()), + ctypes.c_void_p(ids_out.data_ptr()), + ctypes.c_void_p(wts_out.data_ptr()), + ctypes.c_void_p(arena.counts.data_ptr()), + ctypes.c_void_p(ws.data_ptr()), + ctypes.c_size_t(self._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), + comm, + stream_ptr, + ) + ) + if rc != 0: + err_text = _last_error(lib, comm) + if self.sircl_dispatches == 0: + self._disabled_reason = f"sirclEpDispatch returned rc={rc}" + ( + f" ({err_text})" if err_text else "" + ) + logger.warning( + "SirclEpAll2AllManager falling back to AgRs (%s)", self._disabled_reason + ) + self.agrs_fallbacks += 1 + self._active_call = _ActiveEpCall(used_sircl=False) + return super().dispatch( + hidden_states, + topk_weights, + topk_ids, + is_sequence_parallel=is_sequence_parallel, + extra_tensors=extra_tensors, + ) + raise RuntimeError( + f"sirclEpDispatch failed with rc={rc}" + f" (rank={rank} num_tokens={num_tokens} max_tokens={max_tokens} static={is_static}" + f" hidden_bytes={hidden_bytes} top_k={top_k}" + f" num_experts={num_experts} dispatches={self.sircl_dispatches}" + f" combines={self.sircl_combines}" + + (f" err={err_text!r}" if err_text else "") + + ")" + ) + + self.sircl_dispatches += 1 + self.last_num_tokens = num_tokens + self.last_max_tokens = max_tokens + if is_static: + self.static_dispatches += 1 + if max_tokens not in self._logged_static_buckets: + self._logged_static_buckets.add(max_tokens) + logger.info( + "SIRCL-EP static all-to-all: capacity %d tokens (%d exchange rows) for %d routed tokens", + max_tokens, + total_rows, + num_tokens, + ) + self.log_stats("first-static") + else: + self.dynamic_dispatches += 1 + if self.sircl_dispatches % STATS_INTERVAL == 0: + self.log_stats("interval") + self._active_call = _ActiveEpCall( + used_sircl=True, + num_tokens=num_tokens, + max_tokens=max_tokens, + hidden_dim=hidden_dim, + dtype=h_in.dtype, + device=hidden_states.device, + lib=lib, + comm=comm, + arena=arena, + workspace=ws, + workspace_bytes=self._workspace_bytes, + static=is_static, + rank=rank, + ) + return h_out, wts_out, ids_out + + def combine( + self, + hidden_states: torch.Tensor, + is_sequence_parallel: bool = False, + ) -> torch.Tensor: + call = self._active_call + self._active_call = None + if call is None or not call.used_sircl or call.arena is None or call.workspace is None: + return super().combine(hidden_states, is_sequence_parallel=is_sequence_parallel) + + h_in = hidden_states if hidden_states.is_contiguous() else hidden_states.contiguous() + h_out = call.arena.combine_out[: call.num_tokens] + nccl_dt = _TORCH_TO_NCCL_DTYPE[call.dtype] + stream_ptr = self._stream_ptr(call.device) + + rc = int( + call.lib.sirclEpCombine( + ctypes.c_void_p(h_in.data_ptr()), + ctypes.c_void_p(h_out.data_ptr() if call.num_tokens > 0 else 0), + ctypes.c_void_p(call.workspace.data_ptr()), + ctypes.c_size_t(call.workspace_bytes), + ctypes.c_int(call.num_tokens), + ctypes.c_int(call.max_tokens), + ctypes.c_size_t(call.hidden_dim), + ctypes.c_int(nccl_dt), + call.comm, + stream_ptr, + ) + ) + if rc != 0: + err_text = _last_error(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}" + f" static={call.static} hidden_dim={call.hidden_dim}" + f" dispatches={self.sircl_dispatches} combines={self.sircl_combines}" + + (f" err={err_text!r}" if err_text else "") + + ")" + ) + self.sircl_combines += 1 + return h_out + + +def _bind_ep_prototypes(lib: ctypes.CDLL) -> bool: + if not ( + hasattr(lib, "sirclEpWorkspaceBytes") + and hasattr(lib, "sirclEpDispatch") + and hasattr(lib, "sirclEpCombine") + ): + 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 + return True + + +def install_sircl_ep_all2all() -> bool: + """Install ``SirclEpAll2AllManager`` on vLLM's ``CudaCommunicator`` (fail-closed).""" + global _INSTALLED + if _INSTALLED: + return True + + if ALL2ALL_BASE_IS_STUB: + raise RuntimeError( + "SIRCL_EP_ALL2ALL requested but vllm.distributed.device_communicators.all2all." + "AgRsAll2AllManager could not be imported" + ) + + try: + from vllm.distributed.device_communicators.all2all import AgRsAll2AllManager + from vllm.distributed.device_communicators.cuda_communicator import ( + CudaCommunicator, + ) + from vllm.model_executor.layers.fused_moe.prepare_finalize.naive_dp_ep import ( + MoEPrepareAndFinalizeNaiveDPEPModular, + ) + except ImportError as exc: + raise RuntimeError( + f"SIRCL_EP_ALL2ALL requested but required vLLM all2all symbols are unavailable: {exc}" + ) from exc + + orig_prepare = getattr(MoEPrepareAndFinalizeNaiveDPEPModular, "prepare", None) + if orig_prepare is None: + raise RuntimeError( + "SIRCL_EP_ALL2ALL: MoEPrepareAndFinalizeNaiveDPEPModular.prepare is missing " + "(upstream API drift)" + ) + prep_sig = inspect.signature(orig_prepare) + prep_has_named = ( + "num_experts" in prep_sig.parameters and "expert_map" in prep_sig.parameters + ) + prep_has_varargs = any( + p.kind == inspect.Parameter.VAR_POSITIONAL for p in prep_sig.parameters.values() + ) + if not prep_has_named and not prep_has_varargs: + raise RuntimeError( + "SIRCL_EP_ALL2ALL: MoEPrepareAndFinalizeNaiveDPEPModular.prepare signature drifted; " + f"missing 'num_experts'/'expert_map' (found {list(prep_sig.parameters)!r})" + ) + + def _wrapped_prepare(self, *args, **kwargs): + if prep_has_named: + bound = prep_sig.bind(self, *args, **kwargs) + bound.apply_defaults() + num_experts = bound.arguments["num_experts"] + expert_map = bound.arguments["expert_map"] + else: + if "num_experts" in kwargs and "expert_map" in kwargs: + num_experts = kwargs["num_experts"] + expert_map = kwargs["expert_map"] + elif len(args) >= 5: + num_experts = args[3] + expert_map = args[4] + else: + raise RuntimeError( + "SIRCL_EP_ALL2ALL: MoEPrepareAndFinalizeNaiveDPEPModular.prepare called " + "without num_experts / expert_map" + ) + prev = getattr(_ACTIVE_META, "current", None) + _ACTIVE_META.current = (int(num_experts), expert_map) + try: + return orig_prepare(self, *args, **kwargs) + finally: + _ACTIVE_META.current = prev + + MoEPrepareAndFinalizeNaiveDPEPModular.prepare = _wrapped_prepare + + orig_cc_init = getattr(CudaCommunicator, "__init__", None) + if orig_cc_init is None: + raise RuntimeError("SIRCL_EP_ALL2ALL: CudaCommunicator.__init__ is missing") + cc_sig = inspect.signature(orig_cc_init) + cc_has_tcp = "tcp_store_group" in cc_sig.parameters + cc_has_varkw = any( + p.kind == inspect.Parameter.VAR_KEYWORD for p in cc_sig.parameters.values() + ) + if not cc_has_tcp and not cc_has_varkw: + raise RuntimeError( + "SIRCL_EP_ALL2ALL: CudaCommunicator.__init__ signature drifted; missing " + f"'tcp_store_group' parameter (found {list(cc_sig.parameters)!r})" + ) + + def _wrapped_cc_init(self, *args, **kwargs): + bound = cc_sig.bind(self, *args, **kwargs) + bound.apply_defaults() + tcp_store_group = ( + bound.arguments["tcp_store_group"] + if cc_has_tcp + else kwargs.get("tcp_store_group") + ) + orig_cc_init(*bound.args, **bound.kwargs) + if self.use_all2all and isinstance(self.all2all_manager, AgRsAll2AllManager): + self.all2all_manager = SirclEpAll2AllManager( + self.cpu_group, + tcp_store_group, + device_comm=self, + ) + logger.info( + "Replaced AgRsAll2AllManager with SirclEpAll2AllManager (max_tokens=%d, prealloc=%d, " + "static=%s)", + self.all2all_manager._max_tokens_cap, + self.all2all_manager._prealloc_tokens, + self.all2all_manager._static_max_tokens or "off", + ) + + CudaCommunicator.__init__ = _wrapped_cc_init + _INSTALLED = True + logger.info("Installed SIRCL-EP all2all manager hook (SIRCL_EP_ALL2ALL=1)") + return True diff --git a/integrations/vllm/libsircl/sircl_ep_b12x.py b/integrations/vllm/libsircl/sircl_ep_b12x.py new file mode 100644 index 00000000..10ec2074 --- /dev/null +++ b/integrations/vllm/libsircl/sircl_ep_b12x.py @@ -0,0 +1,1386 @@ +"""Opt-in b12x Expert-Parallel (EP) W4A8/W4A16 MoE integration for vLLM. + +Activated when ``SIRCL_B12X_EP_MOE=1`` is set and the ``libsircl`` vLLM plugin +runs. Enables ``B12xExperts`` to run with ``--enable-expert-parallel`` in both: + +- Stage 1 (TP + EP, replicated activations + ``expert_map`` + 1 AllReduce or + deferred reduce-scatter for ``ds41_row_shard``) +- Stage 3 (DP + EP with ``allgather_reducescatter`` or ``SirclEpAll2AllManager``) + +Supports: + +- **MXFP4 W4A8 (``w4a8_mx``)**: remaps global ``topk_ids`` through ``expert_map`` + on GPU (CUDA-graph safe, clamping out-of-range / ``-1`` padding slots to + ``-1``) and invokes ``b12x.moe.fused_moe`` directly (whose kernels skip + ``-1`` routes and write exact zeros for tokens with zero local experts). +- **MXFP4 W4A16 BF16 (``w4a16``)**: runs ``b12x.moe.ep_moe`` / + ``run_w4a16_moe`` with native ``expert_map``. +""" +from __future__ import annotations + +from collections.abc import Mapping +import dataclasses +import functools +import inspect +import logging +import math +import os +import sys +import threading +from typing import Any + +import torch + +try: + from vllm.logger import init_logger as _init_logger + + logger = _init_logger(__name__) +except ImportError: + logger = logging.getLogger(__name__) + +ENV_FLAG = "SIRCL_B12X_EP_MOE" +TRITON_REMAP_ENV = "SIRCL_EP_TRITON_REMAP" +ROUTER_SKIP_PADDING_ENV = "SIRCL_EP_ROUTER_SKIP_PADDING" +FORCE_GROUPED_ROUTING_ENV = "SIRCL_EP_FORCE_GROUPED_ROUTING" +_INSTALLED = False +_NEG_ONE_CACHE: dict[tuple[int, torch.dtype], torch.Tensor] = {} +_TRITON_REMAP_WARMED: set[tuple[int, torch.dtype, torch.dtype]] = set() + +try: + import triton + import triton.language as tl + + @triton.jit + def _remap_expert_ids_kernel( + ids_ptr, + map_ptr, + out_ptr, + n_elements, + global_num_experts, + BLOCK_SIZE: tl.constexpr, + ): + pid = tl.program_id(0) + offs = pid * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE) + mask = offs < n_elements + eid = tl.load(ids_ptr + offs, mask=mask, other=-1) + valid = (eid >= 0) & (eid < global_num_experts) + safe_eid = tl.where(valid, eid, 0) + mapped = tl.load(map_ptr + safe_eid, mask=mask & valid, other=-1) + out = tl.where(valid, mapped, -1) + tl.store(out_ptr + offs, out, mask=mask) + + _TRITON_AVAILABLE = True +except ImportError: + triton = None + _remap_expert_ids_kernel = None + _TRITON_AVAILABLE = False + + +def enabled(environ=None) -> bool: + env = os.environ if environ is None else environ + return env.get(ENV_FLAG, "").strip().lower() in ("1", "true", "on", "yes") + + +def _triton_remap_enabled(environ=None) -> bool: + if not _TRITON_AVAILABLE: + return False + env = os.environ if environ is None else environ + raw = env.get(TRITON_REMAP_ENV, "1").strip().lower() + return raw not in ("0", "false", "off", "no") + + +def _is_capturing() -> bool: + return bool(torch.cuda.is_available() and torch.cuda.is_current_stream_capturing()) + + +def _neg_one_scalar(device: torch.device, dtype: torch.dtype) -> torch.Tensor: + dev_idx = -1 if device.index is None else int(device.index) + key = (dev_idx, dtype) + cached = _NEG_ONE_CACHE.get(key) + if cached is not None and cached.device == device: + return cached + tensor = torch.tensor(-1, dtype=dtype, device=device) + _NEG_ONE_CACHE[key] = tensor + return tensor + + +def _warmup_triton_remap(device: torch.device, global_num_experts: int = 384) -> None: + """Compile Triton remap kernels before CUDA graph capture for int32 & int64 IDs.""" + if not _triton_remap_enabled() or device.type != "cuda": + return + dev_idx = -1 if device.index is None else int(device.index) + emap = torch.full((max(global_num_experts, 1),), -1, dtype=torch.int32, device=device) + for id_dtype in (torch.int32, torch.int64): + key = (dev_idx, id_dtype, torch.int32) + if key in _TRITON_REMAP_WARMED: + continue + dummy_ids = torch.zeros((6, 6), dtype=id_dtype, device=device) + _remap_expert_ids(dummy_ids, emap, max(global_num_experts, 1)) + _TRITON_REMAP_WARMED.add(key) + + +def _remap_expert_ids( + topk_ids: torch.Tensor, + expert_map: torch.Tensor, + global_num_experts: int, +) -> torch.Tensor: + """Map global ``topk_ids`` to rank-local IDs (``-1`` for non-local/padding). + + Guards against negative or out-of-range IDs (e.g. ``-1`` padding rows from + ``dsv4_topk`` or DP all2all dispatch) before indexing ``expert_map`` so + negative indices never wrap around to the last expert on rank ``EP-1``. + Uses a single fused Triton kernel on CUDA (eliminating 6-8 ATen ops/layer + under ``compilation_config.mode=NONE``) with an identical PyTorch fallback. + """ + if ( + _triton_remap_enabled() + and topk_ids.is_cuda + and expert_map.is_cuda + and topk_ids.is_contiguous() + and expert_map.is_contiguous() + ): + n_elements = int(topk_ids.numel()) + out = torch.empty(topk_ids.shape, dtype=expert_map.dtype, device=topk_ids.device) + if n_elements > 0: + block_size = 256 + grid = ((n_elements + block_size - 1) // block_size,) + _remap_expert_ids_kernel[grid]( + topk_ids, + expert_map, + out, + n_elements, + int(global_num_experts), + BLOCK_SIZE=block_size, + ) + return out + neg_one = _neg_one_scalar(expert_map.device, expert_map.dtype) + valid = (topk_ids >= 0) & (topk_ids < global_num_experts) + safe_ids = topk_ids.clamp(0, max(global_num_experts - 1, 0)) + return torch.where(valid, expert_map[safe_ids], neg_one).contiguous() + + +def _widen_workload_for_ep(workload: Any, ep_mult: int, cap: int = 32768) -> Any: + """Scale a ``B12xWorkload`` by ``ep_mult`` for DP+EP all2all dispatch.""" + if ep_mult <= 1: + return workload + max_base = int(workload.max_tokens) + max_target = min(max(max_base * ep_mult, max_base), cap) + fixed_set = {int(c) for c in workload.fixed_token_counts if 0 < int(c) < max_target} + for c in list(fixed_set): + scaled = c * ep_mult + if 0 < scaled < max_target: + fixed_set.add(scaled) + counts_set = {int(c) for c in workload.token_counts if 0 < int(c) <= max_target} + counts_set.update(fixed_set) + counts_set.add(max_target) + for c in list(counts_set): + scaled = c * ep_mult + if 0 < scaled <= max_target: + counts_set.add(scaled) + return dataclasses.replace( + workload, + max_tokens=max_target, + token_counts=tuple(sorted(counts_set)), + fixed_token_counts=tuple(sorted(fixed_set)), + ) + + +def _is_ep_parallel_supported(moe_parallel_config: Any) -> bool: + if getattr(moe_parallel_config, "enable_eplb", False): + return False + if not moe_parallel_config.use_ep: + return ( + moe_parallel_config.ep_size == 1 + and not moe_parallel_config.use_all2all_kernels + ) + if moe_parallel_config.ep_size <= 1: + return False + if not moe_parallel_config.use_all2all_kernels: + return True + return bool(moe_parallel_config.use_ag_rs_all2all_kernels) + + +def _require_attr(obj: Any, attr: str, context: str) -> Any: + value = getattr(obj, attr, None) + if value is None: + raise RuntimeError(f"{context}: expected symbol {attr!r} on {obj!r} is missing (upstream API drift)") + return value + + +def _require_signature(fn: Any, required_params: tuple[str, ...], context: str) -> inspect.Signature: + try: + sig = inspect.signature(fn) + except (TypeError, ValueError) as exc: + raise RuntimeError(f"{context}: cannot inspect signature of {fn!r}: {exc}") from exc + missing = [name for name in required_params if name not in sig.parameters] + if missing: + raise RuntimeError( + f"{context}: signature drift on {getattr(fn, '__qualname__', fn)!r}; " + f"missing required parameter(s) {missing!r} (found {list(sig.parameters)!r})" + ) + return sig + + +def install_b12x_ep_moe() -> bool: + """Patch vLLM's ``B12xExperts`` to support W4A8 and W4A16 EP (fail-closed when enabled).""" + global _INSTALLED + if _INSTALLED: + return True + + try: + from vllm.model_executor.layers.fused_moe import b12x as vllm_b12x + from vllm.model_executor.layers.fused_moe.b12x import B12xExperts + except ImportError as exc: + raise RuntimeError( + f"SIRCL_B12X_EP_MOE requested but vLLM b12x MoE module could not be imported: {exc}" + ) from exc + + try: + from b12x._lib.compile_plan import retain_compiled_programs + from b12x.moe._shared.kernels.w4a16.host import ( + route_pack_token_capacity, + route_pack_warmup_token_counts, + select_route_block_size_m, + ) + from b12x.moe._shared.kernels.w4a16.kernel import run_w4a16_moe + from b12x.moe.ep_moe._impl import ( + EPMoEScratchCaps, + _map_scratch_views, + _materialize_layout, + ) + from b12x.moe.fused_moe._impl import _prepared_payload_for_runtime + except ImportError as exc: + raise RuntimeError( + f"SIRCL_B12X_EP_MOE requested but required b12x EP symbols could not be imported: {exc}" + ) from exc + + orig_is_supported_config = _require_attr(B12xExperts, "is_supported_config", "install_b12x_ep_moe") + orig_get_prep_units = _require_attr(B12xExperts, "get_b12x_preparation_units", "install_b12x_ep_moe") + orig_workspace_shapes = _require_attr(B12xExperts, "workspace_shapes", "install_b12x_ep_moe") + orig_apply = _require_attr(B12xExperts, "apply", "install_b12x_ep_moe") + kMxfp4Static = _require_attr(vllm_b12x, "kMxfp4Static", "install_b12x_ep_moe") + kMxfp8Dynamic = _require_attr(vllm_b12x, "kMxfp8Dynamic", "install_b12x_ep_moe") + normalize_topk_weights = _require_attr(vllm_b12x, "_normalize_topk_weights", "install_b12x_ep_moe") + + def _use_ep(self: Any) -> bool: + return bool(self.moe_config.moe_parallel_config.use_ep) + + def _is_w4a8_ep(self: Any) -> bool: + return _use_ep(self) and getattr(self, "_quant_mode", None) != "w4a16" + + def _ep_layout_for(self: Any, tokens: int, activation: Any, route_ids_workspace: bool): + cache = getattr(self, "_sircl_ep_layout_cache", None) + if cache is None: + cache = {} + self._sircl_ep_layout_cache = cache + m = max(int(tokens), 1) + key = (m, activation, bool(route_ids_workspace)) + entry = cache.get(key) + if entry is not None: + return entry + prepared_impl = self._prepared()._impl + limit, alpha, beta = self._swiglu_params(activation) + caps = EPMoEScratchCaps( + max_tokens=m, + num_topk=int(self.moe_config.experts_per_token), + global_num_experts=int(self.moe_config.num_experts), + device=torch.device("cuda", torch.cuda.current_device()), + weight_plan=prepared_impl.plan, + apply_router_weight_on_input=bool(self._apply_router_weight_on_input), + swiglu_limit=limit, + swiglu_alpha=alpha, + swiglu_beta=beta, + ) + layout = _materialize_layout(caps, route_ids_workspace=bool(route_ids_workspace)) + entry = (caps, layout) + cache[key] = entry + return entry + + def _ep_runtime_payload(self: Any, dtype: torch.dtype, hidden_size: int): + cache = getattr(self, "_sircl_ep_rt_cache", None) + if cache is None: + cache = {} + self._sircl_ep_rt_cache = cache + prepared_impl = self._prepared()._impl + key = (id(prepared_impl), dtype, hidden_size) + rt = cache.get(key) + if rt is not None: + return rt + rt = _prepared_payload_for_runtime( + prepared_impl, + quant_mode="w4a16", + source_format=prepared_impl.source_format, + activation=prepared_impl.activation, + w13_layout=prepared_impl.w13_layout, + dtype=dtype, + hidden_size=hidden_size, + ) + if rt is None: + raise RuntimeError("b12x EP W4A16 weight representation was not materialized") + cache[key] = rt + return rt + + @staticmethod + def _supports_parallel_config(moe_parallel_config: Any) -> bool: + return _is_ep_parallel_supported(moe_parallel_config) + + @staticmethod + def is_supported_config( + cls: Any, + moe_config: Any, + weight_key: Any, + activation_key: Any, + activation_format: Any, + ) -> tuple[bool, str | None]: + if moe_config.moe_parallel_config.use_ep: + if (weight_key, activation_key) not in ( + (kMxfp4Static, kMxfp8Dynamic), + (kMxfp4Static, None), + ): + return ( + False, + "b12x EP MoE supports only MXFP4 W4A8/W4A16 BF16", + ) + if moe_config.in_dtype != torch.bfloat16: + return False, "b12x EP MoE requires bfloat16 activations" + return orig_is_supported_config( + cls, moe_config, weight_key, activation_key, activation_format + ) + + def supports_expert_map(self: Any) -> bool: + return _use_ep(self) + + _warmed_keys: set[tuple[Any, ...]] = set() + _retained_program_handles: list[Any] = [] + + def _warmup_ep_kernels(self: Any, activation: Any, counts: set[int]) -> None: + prepared_impl = self._prepared()._impl + dtype = self.moe_config.in_dtype + hidden_size = int(prepared_impl.plan.hidden_size) + num_experts = int(self.moe_config.num_experts) + local_experts = int(prepared_impl.plan.num_experts) + topk = int(self.moe_config.experts_per_token) + device = torch.device("cuda", torch.cuda.current_device()) + rt = _ep_runtime_payload(self, dtype, hidden_size) + use_swigluoai = prepared_impl.activation == "swigluoai_uninterleave" + + expert_map = torch.full((num_experts,), -1, dtype=torch.int32, device=device) + expert_map[:local_experts] = torch.arange(local_experts, dtype=torch.int32, device=device) + + max_m = max(counts, default=0) + if max_m <= 0: + return + max_nbytes = 0 + layouts_by_m: dict[int, tuple[Any, Any]] = {} + for m in sorted(counts): + if m <= 0: + continue + caps, layout = _ep_layout_for(self, m, activation, route_ids_workspace=(m <= 8)) + layouts_by_m[m] = (caps, layout) + nbytes = max((spec.offset_bytes + spec.nbytes for spec in layout._layout), default=0) + max_nbytes = max(max_nbytes, nbytes) + + # Check whether any (m, ids_dtype) pair still needs warming up. + todo: list[tuple[int, torch.dtype]] = [] + for m in sorted(layouts_by_m): + caps, _ = layouts_by_m[m] + dtypes = (torch.int32,) if m <= 8 else (torch.int32, torch.int64) + for ids_dt in dtypes: + wkey = ( + prepared_impl.plan, + prepared_impl.activation, + dtype, + hidden_size, + num_experts, + topk, + bool(self._apply_router_weight_on_input), + caps.swiglu_limit, + m, + ids_dt, + ) + if wkey not in _warmed_keys: + todo.append((m, ids_dt)) + _warmed_keys.add(wkey) + if not todo: + return + + hidden_buf = torch.zeros((max_m, hidden_size), dtype=dtype, device=device) + output_buf = torch.empty((max_m, hidden_size), dtype=dtype, device=device) + weights_buf = torch.full((max_m, topk), 1.0 / max(topk, 1), dtype=torch.float32, device=device) + ids_i32_buf = torch.arange(max_m * topk, dtype=torch.int32, device=device).remainder_(num_experts).view(max_m, topk) + ids_i64_buf = ids_i32_buf.to(torch.int64) + scratch_buf = torch.empty((max(max_nbytes, 1),), dtype=torch.uint8, device=device) + + with retain_compiled_programs() as retained: + _retained_program_handles.append(retained) + for m, ids_dt in todo: + caps, layout = layouts_by_m[m] + views = _map_scratch_views(scratch_buf, layout._layout) + ids_slice = ids_i32_buf[:m] if ids_dt == torch.int32 else ids_i64_buf[:m] + run_w4a16_moe( + hidden_buf[:m], + rt, + weights_buf[:m], + ids_slice, + activation=prepared_impl.activation, + intermediate_cache13=views["intermediate_cache13"], + intermediate_cache2=views["intermediate_cache2"], + output=output_buf[:m], + fc1_c_tmp=views["fc1_c_tmp"], + fc2_c_tmp=views["fc2_c_tmp"], + packed_route_indices=views["packed_route_indices"], + block_expert_ids=views["block_expert_ids"], + packed_route_count=views["packed_route_count"], + expert_offsets=views["expert_offsets"], + expert_counts=views["expert_counts"], + expert_map=expert_map, + apply_router_weight_on_input=bool(self._apply_router_weight_on_input), + fast_math=True, + swiglu_limit=caps.swiglu_limit, + swiglu_alpha=float(caps.swiglu_alpha) if use_swigluoai else None, + swiglu_beta=float(caps.swiglu_beta) if use_swigluoai else None, + fused_launch=None, + ) + torch.cuda.synchronize(device) + del hidden_buf, output_buf, weights_buf, ids_i32_buf, ids_i64_buf, scratch_buf, expert_map + torch.cuda.empty_cache() + + logger.info( + "SIRCL b12x EP warmup complete: local_E=%d global_E=%d topk=%d warmed=%d shapes (max_m=%d)", + local_experts, + num_experts, + topk, + len(todo), + max_m, + ) + + def _ep_warmup_token_counts(max_m: int, topk: int, num_experts: int) -> set[int]: + """Cover every (bucket, block_size_m, m_div16, numel_div16, small_m) Triton key.""" + seen: set[tuple[int, int, bool, bool, bool]] = set() + picked: set[int] = set(route_pack_warmup_token_counts(max_m)) + for m in range(1, max_m + 1): + key = ( + route_pack_token_capacity(m, topk), + select_route_block_size_m(m, topk, num_experts), + (m % 16) == 0, + ((m * topk) % 16) == 0, + m <= 8, + ) + if key not in seen: + seen.add(key) + picked.add(m) + return picked + + def get_b12x_preparation_units(self: Any, layer: Any, workload: Any): + if not _use_ep(self): + return orig_get_prep_units(self, layer, workload) + ep_cfg = self.moe_config.moe_parallel_config + if int(getattr(ep_cfg, "dp_size", 1)) > 1: + _patch_deepseek_v4_ced_dp_metadata() + _patch_dp_sync_cudagraph_num_reqs() + _patch_dp_speculator_propose_sync(require_loaded=True) + if _is_w4a8_ep(self): + # Pre-populate cached -1 scalar and compile Triton remap before CUDA graph capture. + if torch.cuda.is_available(): + dev = torch.device("cuda", torch.cuda.current_device()) + _neg_one_scalar(dev, torch.int32) + _warmup_triton_remap(dev, int(self.moe_config.num_experts)) + ep_mult = int(ep_cfg.ep_size) if ep_cfg.use_all2all_kernels else 1 + prep_workload = ( + _widen_workload_for_ep(workload, ep_mult) + if getattr(workload, "stage", None) == "weights" and ep_mult > 1 + else workload + ) + return orig_get_prep_units(self, layer, prep_workload) + # Pre-populate layout cache and eagerly compile b12x W4A16 EP kernels + # before vLLM freezes b12x kernel resolution for CUDA graph capture. + ep_mult = int(ep_cfg.ep_size) if ep_cfg.use_all2all_kernels else 1 + num_experts = int(self.moe_config.num_experts) + topk = int(self.moe_config.experts_per_token) + counts = {int(c) for c in workload.fixed_token_counts if int(c) > 0} + if int(workload.max_tokens) > 0: + counts.add(int(workload.max_tokens)) + max_base = max(counts, default=96) + max_target = max_base * ep_mult if ep_mult > 1 else max_base + # Cap DP+EP warmup target at 32768 rows (e.g. 4 ranks x 8192 batched tokens). + max_target = min(max_target, 32768) + counts.update(range(1, min(max_target, 16) + 1)) + counts.update(_ep_warmup_token_counts(max_target, topk, num_experts)) + if ep_mult > 1: + for c in list(counts): + if c <= max_base and c * ep_mult <= max_target: + counts.add(int(c) * ep_mult) + _warmup_ep_kernels(self, layer.activation, counts) + return () + + def workspace_shapes( + self: Any, + M: int, + N: int, + K: int, + topk: int, + global_num_experts: int, + local_num_experts: int, + expert_tokens_meta: Any, + activation: Any, + ): + if not _use_ep(self) or _is_w4a8_ep(self): + return orig_workspace_shapes( + self, M, N, K, topk, global_num_experts, local_num_experts, expert_tokens_meta, activation + ) + m = max(int(M), 1) + _, layout = _ep_layout_for(self, m, activation, route_ids_workspace=(m <= 8)) + required_nbytes = max( + (spec.offset_bytes + spec.nbytes for spec in layout._layout), + default=0, + ) + itemsize = self.moe_config.in_dtype.itemsize + return (0,), (max(1, (required_nbytes + itemsize - 1) // itemsize),), (M, K) + + def apply( + self: Any, + output: torch.Tensor, + hidden_states: torch.Tensor, + w1: torch.Tensor, + w2: torch.Tensor, + topk_weights: torch.Tensor, + topk_ids: torch.Tensor, + activation: Any, + global_num_experts: int, + expert_map: torch.Tensor | None, + a1q_scale: torch.Tensor | None, + a2_scale: torch.Tensor | None, + workspace13: torch.Tensor | None, + workspace2: torch.Tensor | None, + expert_tokens_meta: Any, + apply_router_weight_on_input: bool | None, + ) -> None: + if expert_map is None and not _use_ep(self): + return orig_apply( + self, + output, + hidden_states, + w1, + w2, + topk_weights, + topk_ids, + activation, + global_num_experts, + expert_map, + a1q_scale, + a2_scale, + workspace13, + workspace2, + expert_tokens_meta, + apply_router_weight_on_input, + ) + if expert_map is None: + raise ValueError("b12x EP MoE requires an expert_map tensor") + m = int(hidden_states.shape[0]) + if m == 0: + return + if _is_w4a8_ep(self): + local_topk_ids = _remap_expert_ids( + topk_ids, expert_map, int(global_num_experts) + ) + return orig_apply( + self, + output, + hidden_states, + w1, + w2, + topk_weights, + local_topk_ids, + activation, + global_num_experts, + None, + a1q_scale, + a2_scale, + workspace13, + workspace2, + expert_tokens_meta, + apply_router_weight_on_input, + ) + if bool(apply_router_weight_on_input) != self._apply_router_weight_on_input: + raise ValueError( + "apply_router_weight_on_input does not match the prepared b12x EP MoE plan" + ) + if ( + topk_ids.dtype not in (torch.int32, torch.int64) + or not topk_ids.is_contiguous() + ): + raise TypeError("b12x EP MoE topk_ids must be contiguous int32 or int64") + if workspace2 is None or not workspace2.is_contiguous(): + raise ValueError("b12x EP MoE requires contiguous caller-owned workspace2") + if not hidden_states.is_contiguous(): + hidden_states = hidden_states.contiguous() + + topk_weights = normalize_topk_weights(topk_weights) + route_ws = m <= 8 + caps, layout = _ep_layout_for(self, m, activation, route_ids_workspace=route_ws) + scratch = workspace2.view(-1).view(torch.uint8) + views = _map_scratch_views(scratch, layout._layout) + + launch_topk_ids = topk_ids + if route_ws and topk_ids.dtype == torch.int64: + route_count = topk_ids.numel() + i32_view = views["route_ids_i32"][:route_count].view_as(topk_ids) + i32_view.copy_(topk_ids) + launch_topk_ids = i32_view + + prepared_impl = self._prepared()._impl + rt = _ep_runtime_payload(self, hidden_states.dtype, int(hidden_states.shape[1])) + use_swigluoai = prepared_impl.activation == "swigluoai_uninterleave" + + run_w4a16_moe( + hidden_states, + rt, + topk_weights, + launch_topk_ids, + activation=prepared_impl.activation, + intermediate_cache13=views["intermediate_cache13"], + intermediate_cache2=views["intermediate_cache2"], + output=output, + fc1_c_tmp=views["fc1_c_tmp"], + fc2_c_tmp=views["fc2_c_tmp"], + packed_route_indices=views["packed_route_indices"], + block_expert_ids=views["block_expert_ids"], + packed_route_count=views["packed_route_count"], + expert_offsets=views["expert_offsets"], + expert_counts=views["expert_counts"], + expert_map=expert_map, + apply_router_weight_on_input=bool(apply_router_weight_on_input), + fast_math=True, + swiglu_limit=caps.swiglu_limit, + swiglu_alpha=float(caps.swiglu_alpha) if use_swigluoai else None, + swiglu_beta=float(caps.swiglu_beta) if use_swigluoai else None, + fused_launch=None, + ) + + B12xExperts._supports_parallel_config = _supports_parallel_config + B12xExperts.is_supported_config = is_supported_config + B12xExperts.supports_expert_map = supports_expert_map + B12xExperts.get_b12x_preparation_units = get_b12x_preparation_units + B12xExperts.workspace_shapes = workspace_shapes + B12xExperts.apply = apply + + _patch_b12x_dp_global_rank() + _patch_modular_kernel_dp_workspace() + _patch_dp_sync_cudagraph_num_reqs() + _patch_dp_speculator_propose_sync(require_loaded=False) + _patch_router_skip_padding() + _patch_ep_grouped_routing() + + _INSTALLED = True + logger.info("Installed SIRCL b12x EP W4A8/W4A16 MoE extension on B12xExperts") + return True + + +def _resize_dp_workspace( + fused_experts: Any, + workspace: tuple[torch.Tensor, torch.Tensor, torch.Tensor], + *, + in_dtype: torch.dtype, + device: torch.device, + m_full: int, + n_dim: int, + k_dim: int, + top_k: int, + global_num_experts: int, + local_num_experts: int, + expert_tokens_meta: Any, + activation: Any, +) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + """Expand an ``M_local`` workspace to ``m_full`` without re-leasing the shared arena. + + ``prepare_workspace`` leases routed workspace and ``shared_workspace`` from + the same ``WorkspaceManager`` arena so ``shared_experts`` can overlap on an + aux stream. Dropping ``workspace=None`` would force ``_allocate_buffers`` to + lease from that same arena a second time, colliding with or freeing + ``shared_workspace`` while the aux stream is executing. Instead, reuse any + already-large-enough routed slices (e.g. W4A8's pre-sized ``workspace2``) + and allocate only undersized tensors directly via ``torch.empty``. + """ + ws13, ws2, fused_out = workspace + ws_dtype = fused_experts.workspace_dtype(in_dtype) + out_dtype = fused_experts.output_dtype + ws13_shape, ws2_shape, out_shape = fused_experts.workspace_shapes( + m_full, + n_dim, + k_dim, + top_k, + global_num_experts, + local_num_experts, + expert_tokens_meta, + activation, + ) + + if ws13.shape != ws13_shape or ws13.dtype != ws_dtype: + need13 = math.prod(ws13_shape) + if ws13.dtype == ws_dtype and ws13.is_contiguous() and ws13.numel() >= need13: + ws13 = ws13.view(-1)[:need13].view(ws13_shape) + else: + ws13 = torch.empty(ws13_shape, dtype=ws_dtype, device=device) + + if ws2.shape != ws2_shape or ws2.dtype != ws_dtype: + need2 = math.prod(ws2_shape) + if ws2.dtype == ws_dtype and ws2.is_contiguous() and ws2.numel() >= need2: + ws2 = ws2.view(-1)[:need2].view(ws2_shape) + else: + ws2 = torch.empty(ws2_shape, dtype=ws_dtype, device=device) + + if fused_out.shape != out_shape or fused_out.dtype != out_dtype: + fused_out = torch.empty(out_shape, dtype=out_dtype, device=device) + + return ws13, ws2, fused_out + + +def _patch_modular_kernel_dp_workspace() -> None: + """Resize pre-allocated M_local workspace when DP all2all expands M_full.""" + try: + from vllm.model_executor.layers.fused_moe.modular_kernel import ( + FusedMoEKernelModularImpl, + ) + except ImportError as exc: + raise RuntimeError( + "SIRCL_B12X_EP_MOE: cannot import " + f"vllm.model_executor.layers.fused_moe.modular_kernel.FusedMoEKernelModularImpl: {exc}" + ) from exc + + orig_fe = _require_attr( + FusedMoEKernelModularImpl, + "_fused_experts", + "_patch_modular_kernel_dp_workspace", + ) + if getattr(orig_fe, "_sircl_dp_ws_patched", False): + return + + sig = _require_signature( + orig_fe, + ( + "in_dtype", + "a1q", + "w1", + "w2", + "topk_ids", + "activation", + "global_num_experts", + "local_num_experts", + "expert_tokens_meta", + "workspace", + ), + "_patch_modular_kernel_dp_workspace(FusedMoEKernelModularImpl._fused_experts)", + ) + + @functools.wraps(orig_fe) + def _wrapped_fused_experts(self, *args, **kwargs): + bound = sig.bind(self, *args, **kwargs) + bound.apply_defaults() + workspace = bound.arguments["workspace"] + if workspace is not None: + a1q = bound.arguments["a1q"] + w1 = bound.arguments["w1"] + w2 = bound.arguments["w2"] + topk_ids = bound.arguments["topk_ids"] + _, m_full, n_dim, k_dim, top_k = self.fused_experts.moe_problem_size( + a1q, w1, w2, topk_ids + ) + if m_full > 0 and workspace[2].shape[0] != m_full: + resized = _resize_dp_workspace( + self.fused_experts, + workspace, + in_dtype=bound.arguments["in_dtype"], + device=a1q.device, + m_full=m_full, + n_dim=n_dim, + k_dim=k_dim, + top_k=top_k, + global_num_experts=bound.arguments["global_num_experts"], + local_num_experts=bound.arguments["local_num_experts"], + expert_tokens_meta=bound.arguments["expert_tokens_meta"], + activation=bound.arguments["activation"], + ) + bound.arguments["workspace"] = resized + return orig_fe(*bound.args, **bound.kwargs) + + _wrapped_fused_experts._sircl_dp_ws_patched = True + FusedMoEKernelModularImpl._fused_experts = _wrapped_fused_experts + + +def _resolve_world_global_rank(world_group: Any) -> int | None: + if world_group is None: + return None + ranks = getattr(world_group, "ranks", None) + rank_in_group = getattr(world_group, "rank_in_group", None) + if ( + ranks is not None + and isinstance(rank_in_group, int) + and 0 <= rank_in_group < len(ranks) + ): + return int(ranks[rank_in_group]) + rank = getattr(world_group, "rank", None) + return int(rank) if isinstance(rank, int) else None + + +def _patch_b12x_dp_global_rank() -> None: + """Fix upstream b12x_prepare passing local TP worker.rank as global_rank under DP>1.""" + try: + from vllm.v1.worker.b12x_startup import B12xPreparationCoordinator + except ImportError as exc: + raise RuntimeError( + "SIRCL_B12X_EP_MOE: cannot import " + f"vllm.v1.worker.b12x_startup.B12xPreparationCoordinator: {exc}" + ) from exc + + orig_coord_init = _require_attr( + B12xPreparationCoordinator, "__init__", "_patch_b12x_dp_global_rank" + ) + if not getattr(orig_coord_init, "_sircl_dp_rank_patched", False): + coord_sig = _require_signature( + orig_coord_init, + ("global_rank", "world_group", "process_local_only"), + "_patch_b12x_dp_global_rank(B12xPreparationCoordinator.__init__)", + ) + + @functools.wraps(orig_coord_init) + def _wrapped_coord_init(self, *args, **kwargs): + bound = coord_sig.bind(self, *args, **kwargs) + bound.apply_defaults() + process_local_only = bound.arguments["process_local_only"] + world_group = bound.arguments["world_group"] + global_rank = bound.arguments["global_rank"] + if not process_local_only and world_group is not None: + actual = _resolve_world_global_rank(world_group) + if actual is not None and actual != int(global_rank): + logger.info( + "Fixing B12xPreparationCoordinator global_rank %d -> %d for DP world", + int(global_rank), + actual, + ) + bound.arguments["global_rank"] = actual + return orig_coord_init(*bound.args, **bound.kwargs) + + _wrapped_coord_init._sircl_dp_rank_patched = True + B12xPreparationCoordinator.__init__ = _wrapped_coord_init + + try: + from b12x.preparation import PreparationSession + except ImportError as exc: + raise RuntimeError( + f"SIRCL_B12X_EP_MOE: cannot import b12x.preparation.PreparationSession: {exc}" + ) from exc + + orig_configure_shard = _require_attr( + PreparationSession, "configure_tuning_shard", "_patch_b12x_dp_global_rank" + ) + if not getattr(orig_configure_shard, "_sircl_dp_rank_patched", False): + shard_sig = _require_signature( + orig_configure_shard, + ("rank", "ranks"), + "_patch_b12x_dp_global_rank(PreparationSession.configure_tuning_shard)", + ) + + @functools.wraps(orig_configure_shard) + def _wrapped_configure_shard(self, *args, **kwargs): + bound = shard_sig.bind(self, *args, **kwargs) + bound.apply_defaults() + rank = bound.arguments["rank"] + ranks = bound.arguments["ranks"] + if int(rank) not in ranks: + try: + from vllm.distributed.parallel_state import get_world_group + + actual = _resolve_world_global_rank(get_world_group()) + except Exception as exc: + raise RuntimeError( + f"SIRCL_B12X_EP_MOE: tuning shard rank {int(rank)} not in {ranks!r} " + f"and resolving world global rank failed: {exc}" + ) from exc + if actual is None or actual not in ranks: + raise RuntimeError( + f"SIRCL_B12X_EP_MOE: tuning shard rank {int(rank)} (resolved world " + f"global rank {actual!r}) is not in shard ranks {ranks!r}" + ) + logger.info( + "Fixing b12x tuning shard rank %d -> %d for DP world", + int(rank), + actual, + ) + bound.arguments["rank"] = actual + return orig_configure_shard(*bound.args, **bound.kwargs) + + _wrapped_configure_shard._sircl_dp_rank_patched = True + PreparationSession.configure_tuning_shard = _wrapped_configure_shard + + +def _patch_deepseek_v4_ced_dp_metadata() -> None: + """Sync DPMetadata token counts across DP ranks after DeepSeek-V4.1 CED compaction.""" + mod = sys.modules.get("vllm.models.deepseek_v4_1.nvidia.model") + if mod is None: + return + model_cls = _require_attr(mod, "DeepseekV4Model", "_patch_deepseek_v4_ced_dp_metadata") + orig_forward = _require_attr(model_cls, "forward", "_patch_deepseek_v4_ced_dp_metadata") + if getattr(orig_forward, "_sircl_ced_dp_patched", False): + return + try: + from vllm.distributed.parallel_state import get_dp_group + from vllm.forward_context import ( + get_forward_context, + is_forward_context_available, + ) + except ImportError as exc: + raise RuntimeError( + "SIRCL_B12X_EP_MOE: DeepSeek-V4.1 model is loaded but vLLM DP metadata " + f"symbols could not be imported: {exc}" + ) from exc + + def _ced_ffn_pre_hook(_module: Any, hook_args: tuple[Any, ...]) -> None: + if _is_capturing(): + return + if not hook_args or not isinstance(hook_args[0], torch.Tensor): + return + dp_group = get_dp_group() + if dp_group.world_size <= 1: + return + if not is_forward_context_available(): + return + dp_meta = get_forward_context().dp_metadata + if dp_meta is None: + return + dtype = dp_meta.num_tokens_across_dp_cpu.dtype + local_n = torch.tensor([int(hook_args[0].shape[0])], dtype=dtype) + gathered = [torch.empty((1,), dtype=dtype) for _ in range(dp_group.world_size)] + torch.distributed.all_gather(gathered, local_n, group=dp_group.cpu_group) + dp_meta.num_tokens_across_dp_cpu = torch.cat(gathered, dim=0) + + def _wrapped_model_forward(self: Any, *args: Any, **kwargs: Any): + ced_start = getattr(self, "ced_decoder_start", None) + if ced_start is not None and not getattr(self, "_sircl_ced_hook_installed", False): + sync_idx = max(int(ced_start), int(getattr(self, "start_layer", 0))) + end_layer = int(getattr(self, "end_layer", len(self.layers))) + if sync_idx < end_layer: + ffn = getattr(self.layers[sync_idx], "ffn", None) + if ffn is not None: + ffn.register_forward_pre_hook(_ced_ffn_pre_hook) + logger.info( + "Installed DeepSeek-V4.1 CED DP metadata sync hook on layer %d", + sync_idx, + ) + self._sircl_ced_hook_installed = True + + dp_meta = None + orig_tokens = None + if is_forward_context_available(): + dp_meta = get_forward_context().dp_metadata + if dp_meta is not None: + orig_tokens = dp_meta.num_tokens_across_dp_cpu + try: + return orig_forward(self, *args, **kwargs) + finally: + if dp_meta is not None and orig_tokens is not None: + dp_meta.num_tokens_across_dp_cpu = orig_tokens + + _wrapped_model_forward._sircl_ced_dp_patched = True + model_cls.forward = _wrapped_model_forward + logger.info("Patched DeepseekV4Model.forward for CED DP metadata synchronization") + + +def _patch_dp_sync_cudagraph_num_reqs() -> None: + """Ensure DP>1 FULL CUDA-graph dispatch agrees on ``num_reqs`` across ranks. + + Upstream ``dp_utils.sync_cudagraph_and_dp_padding`` passes each rank's local + ``num_reqs`` to ``cudagraph_manager.dispatch(...)``. With ``varlen_decode`` + (e.g. DSpark adaptive verification), multiple FULL graphs can share the same + ``synced_num_tokens`` with different ``num_reqs``; ranks with different local + ``num_reqs`` then select different descriptors and store divergent + ``DPSyncState.num_reqs`` values, causing downstream drafters (DSpark/DFlash) + to replay different batch sizes across DP ranks. + """ + try: + from vllm.config.compilation import CUDAGraphMode + from vllm.v1.worker.gpu import dp_utils + except ImportError as exc: + raise RuntimeError( + "SIRCL_B12X_EP_MOE: cannot import vLLM dp_utils / CUDAGraphMode for DP sync: " + f"{exc}" + ) from exc + + orig_sync = _require_attr( + dp_utils, "sync_cudagraph_and_dp_padding", "_patch_dp_sync_cudagraph_num_reqs" + ) + if getattr(orig_sync, "_sircl_dp_num_reqs_patched", False): + return + orig_dispatch = _require_attr( + dp_utils, "dispatch_cg_and_sync_dp", "_patch_dp_sync_cudagraph_num_reqs" + ) + orig_dist = _require_attr(dp_utils, "dist", "_patch_dp_sync_cudagraph_num_reqs") + _require_attr(CUDAGraphMode, "FULL", "_patch_dp_sync_cudagraph_num_reqs") + + sync_sig = _require_signature( + orig_sync, + ("num_reqs", "dp_size", "dp_rank"), + "_patch_dp_sync_cudagraph_num_reqs(dp_utils.sync_cudagraph_and_dp_padding)", + ) + sync_param_names = list(sync_sig.parameters) + if not sync_param_names: + raise RuntimeError( + "_patch_dp_sync_cudagraph_num_reqs: sync_cudagraph_and_dp_padding takes no parameters" + ) + sync_cm_param = sync_param_names[0] + + dispatch_sig = _require_signature( + orig_dispatch, + ("dp_sync",), + "_patch_dp_sync_cudagraph_num_reqs(dp_utils.dispatch_cg_and_sync_dp)", + ) + dispatch_param_names = list(dispatch_sig.parameters) + if not dispatch_param_names: + raise RuntimeError( + "_patch_dp_sync_cudagraph_num_reqs: dispatch_cg_and_sync_dp takes no parameters" + ) + dispatch_cm_param = dispatch_param_names[0] + + tls = threading.local() + + class _DistProxy: + def __getattr__(self, name: str) -> Any: + return getattr(orig_dist, name) + + def all_reduce(self, tensor: Any, *args: Any, **kwargs: Any) -> Any: + active = getattr(tls, "active", False) + if active: + expected_dp_size = int(tls.dp_size) + expected_dp_rank = int(tls.dp_rank) + expected_local_reqs = int(tls.local_num_reqs) + if ( + not isinstance(tensor, torch.Tensor) + or tensor.ndim != 2 + or tensor.dtype not in (torch.int32, torch.int64) + or tensor.shape[0] < 6 + or tensor.shape[1] != expected_dp_size + or not (0 <= expected_dp_rank < tensor.shape[1]) + ): + raise RuntimeError( + "SIRCL_B12X_EP_MOE: dp_utils.dist.all_reduce sync tensor contract drifted; " + f"expected 2D int32/int64 tensor with shape (>=6, {expected_dp_size}), " + f"got {type(tensor).__name__} " + f"shape={getattr(tensor, 'shape', None)} dtype={getattr(tensor, 'dtype', None)}" + ) + observed_local = int(tensor[5, expected_dp_rank].item()) + if observed_local != expected_local_reqs: + raise RuntimeError( + "SIRCL_B12X_EP_MOE: dp_utils.dist.all_reduce row 5 no longer carries local " + f"num_reqs (expected tensor[5, {expected_dp_rank}] == {expected_local_reqs}, " + f"observed {observed_local}); upstream DP sync buffer layout drifted" + ) + res = orig_dist.all_reduce(tensor, *args, **kwargs) + if active: + max_reqs = int(tensor[5].max().item()) + if max_reqs < int(tls.local_num_reqs): + raise RuntimeError( + "SIRCL_B12X_EP_MOE: dp_utils.dist.all_reduce post-condition failed: " + f"max(tensor[5])={max_reqs} < local num_reqs={int(tls.local_num_reqs)}" + ) + tls.max_num_reqs = max_reqs + return res + + class _SyncedNumReqsManagerProxy: + def __init__(self, manager: Any, get_min_num_reqs: Any) -> None: + self._manager = manager + self._get_min_num_reqs = get_min_num_reqs + + def __getattr__(self, name: str) -> Any: + return getattr(self._manager, name) + + def dispatch(self, num_reqs: int, *args: Any, **kwargs: Any) -> Any: + synced = self._get_min_num_reqs() + eff = max(int(num_reqs), int(synced)) if synced is not None else num_reqs + desc = self._manager.dispatch(eff, *args, **kwargs) + if ( + synced is not None + and desc.cg_mode != CUDAGraphMode.FULL + and desc.num_reqs is not None + and desc.num_reqs != num_reqs + ): + desc = dataclasses.replace(desc, num_reqs=num_reqs) + return desc + + @functools.wraps(orig_sync) + def _wrapped_sync(*args: Any, **kwargs: Any): + bound = sync_sig.bind(*args, **kwargs) + bound.apply_defaults() + cudagraph_manager = bound.arguments[sync_cm_param] + prev_active = getattr(tls, "active", False) + prev_max = getattr(tls, "max_num_reqs", None) + prev_local = getattr(tls, "local_num_reqs", None) + prev_dp_size = getattr(tls, "dp_size", None) + prev_dp_rank = getattr(tls, "dp_rank", None) + tls.active = True + tls.max_num_reqs = None + tls.local_num_reqs = int(bound.arguments["num_reqs"]) + tls.dp_size = int(bound.arguments["dp_size"]) + tls.dp_rank = int(bound.arguments["dp_rank"]) + if cudagraph_manager is not None: + bound.arguments[sync_cm_param] = _SyncedNumReqsManagerProxy( + cudagraph_manager, lambda: getattr(tls, "max_num_reqs", None) + ) + try: + return orig_sync(*bound.args, **bound.kwargs) + finally: + tls.active = prev_active + tls.max_num_reqs = prev_max + tls.local_num_reqs = prev_local + tls.dp_size = prev_dp_size + tls.dp_rank = prev_dp_rank + + @functools.wraps(orig_dispatch) + def _wrapped_dispatch(*args: Any, **kwargs: Any): + bound = dispatch_sig.bind(*args, **kwargs) + bound.apply_defaults() + dp_sync = bound.arguments["dp_sync"] + cudagraph_manager = bound.arguments[dispatch_cm_param] + if dp_sync is not None and cudagraph_manager is not None: + min_reqs = int(dp_sync.num_reqs) + bound.arguments[dispatch_cm_param] = _SyncedNumReqsManagerProxy( + cudagraph_manager, lambda: min_reqs + ) + return orig_dispatch(*bound.args, **bound.kwargs) + + _wrapped_sync._sircl_dp_num_reqs_patched = True + _wrapped_dispatch._sircl_dp_num_reqs_patched = True + dp_utils.dist = _DistProxy() + dp_utils.sync_cudagraph_and_dp_padding = _wrapped_sync + dp_utils.dispatch_cg_and_sync_dp = _wrapped_dispatch + + for mod_name in ( + "vllm.v1.worker.gpu.model_runner", + "vllm.v1.worker.gpu.spec_decode.dflash.speculator", + "vllm.v1.worker.gpu.spec_decode.autoregressive.speculator", + ): + mod = sys.modules.get(mod_name) + if mod is not None and getattr(mod, "dispatch_cg_and_sync_dp", None) is orig_dispatch: + mod.dispatch_cg_and_sync_dp = _wrapped_dispatch + + logger.info("Patched dp_utils CUDA-graph DP sync to agree on num_reqs across ranks") + + +def _patch_dp_speculator_propose_sync(*, require_loaded: bool = True) -> None: + """Keep DP>1 speculator ``propose()`` in lockstep when ``num_spec_tokens_to_schedule == 0``. + + Idle DP ranks in ``execute_dummy_batch()`` unconditionally call + ``speculator.propose(..., dummy_run=True)`` to stay synchronized on MoE + drafter collectives, whereas ``GPUModelRunner.sample_tokens()`` skips + ``propose()`` when ``num_spec_tokens_to_schedule == 0`` (e.g. intermediate + chunked-prefill steps or ``max_tokens=1`` requests). Under DP>1, force a + ``dummy_run=True`` propose call and discard its output so every DP rank + executes the same drafter collectives before entering the next step. + """ + mod = sys.modules.get("vllm.v1.worker.gpu.model_runner") + if mod is None: + if not require_loaded: + return + raise RuntimeError( + "SIRCL_B12X_EP_MOE: vllm.v1.worker.gpu.model_runner is not loaded when " + "installing DP>1 speculator propose sync" + ) + runner_cls = _require_attr(mod, "GPUModelRunner", "_patch_dp_speculator_propose_sync") + orig_sample_tokens = _require_attr( + runner_cls, "sample_tokens", "_patch_dp_speculator_propose_sync" + ) + if getattr(orig_sample_tokens, "_sircl_dp_spec_sync_patched", False): + return + + def _wrapped_sample_tokens(self: Any, *args: Any, **kwargs: Any): + state = getattr(self, "execute_model_state", None) + spec = getattr(self, "speculator", None) + dp_size = int(getattr(self, "dp_size", 1)) + if ( + dp_size > 1 + and spec is not None + and state is not None + and int(getattr(state, "num_spec_tokens_to_schedule", 1)) == 0 + and not getattr(state, "boundary_logits_only", False) + and hasattr(state, "_replace") + ): + self.execute_model_state = state._replace(num_spec_tokens_to_schedule=1) + orig_propose = spec.propose + orig_adaptive = getattr(self, "adaptive_verification", None) + + def _sync_only_propose(*p_args: Any, **p_kwargs: Any): + p_kwargs["dummy_run"] = True + out = orig_propose(*p_args, **p_kwargs) + return out[:, :0] + + spec.propose = _sync_only_propose + if orig_adaptive is not None: + self.adaptive_verification = None + try: + return orig_sample_tokens(self, *args, **kwargs) + finally: + spec.propose = orig_propose + if orig_adaptive is not None: + self.adaptive_verification = orig_adaptive + return orig_sample_tokens(self, *args, **kwargs) + + _wrapped_sample_tokens._sircl_dp_spec_sync_patched = True + runner_cls.sample_tokens = _wrapped_sample_tokens + logger.info("Patched GPUModelRunner.sample_tokens for DP>1 speculator propose sync") + + +def _patch_router_skip_padding() -> None: + """Forward ``is_padding`` in text-only ``dsv4_topk`` when ``SIRCL_EP_ROUTER_SKIP_PADDING=1``.""" + raw = os.environ.get(ROUTER_SKIP_PADDING_ENV, "1").strip().lower() + if raw in ("0", "false", "off", "no"): + return + try: + from vllm.model_executor.layers.fused_moe.router import ( + fused_topk_bias_router as router_mod, + ) + except ImportError as exc: + raise RuntimeError( + f"SIRCL_B12X_EP_MOE ({ROUTER_SKIP_PADDING_ENV}=1): cannot import " + f"fused_topk_bias_router: {exc}" + ) from exc + orig_dsv4 = _require_attr(router_mod, "dsv4_topk", "_patch_router_skip_padding") + get_pad = _require_attr(router_mod, "_get_padding_mask", "_patch_router_skip_padding") + if getattr(orig_dsv4, "_sircl_pad_patched", False): + return + dsv4_sig = inspect.signature(orig_dsv4) + has_var_kw = any( + p.kind == inspect.Parameter.VAR_KEYWORD for p in dsv4_sig.parameters.values() + ) + if "is_padding" not in dsv4_sig.parameters and not has_var_kw: + raise RuntimeError( + "_patch_router_skip_padding: fused_topk_bias_router.dsv4_topk no longer accepts " + f"'is_padding' (signature parameters: {list(dsv4_sig.parameters)!r})" + ) + + def _wrapped_dsv4_topk(gating_output: torch.Tensor, *args: Any, **kwargs: Any): + if kwargs.get("is_padding") is None: + pad = get_pad(gating_output.shape[0]) + if pad is not None: + kwargs["is_padding"] = pad + return orig_dsv4(gating_output, *args, **kwargs) + + _wrapped_dsv4_topk._sircl_pad_patched = True + router_mod.dsv4_topk = _wrapped_dsv4_topk + logger.info("Patched fused_topk_bias_router.dsv4_topk to forward is_padding mask") + + +def _force_grouped_moe_config(config: Any) -> Any: + """Normalize ``dynamic_route_mode='direct'`` -> ``'grouped'`` on dynamic MoE configs.""" + if ( + config is not None + and getattr(config, "backend", None) == "dynamic" + and getattr(config, "dynamic_route_mode", None) == "direct" + ): + return dataclasses.replace(config, dynamic_route_mode="grouped") + return config + + +def _wrap_grouped_moe_plan(plan_obj: Any) -> Any: + """Wrap a b12x ``Plan`` or ``_CompositePlan`` to normalize ``dynamic_route_mode``. + + Rewriting ``config.dynamic_route_mode`` from ``"direct"`` to ``"grouped"`` + before ``_compile_jobs`` encodes ``config_payload`` guarantees that both the + parent vLLM worker (planning) and unpatched ``b12x`` compilation subprocesses + (``compile_fused_moe``) see identical ``"grouped"`` configs and compute + identical program keys, while cached ``"direct"`` policy entries still + validate cleanly during ``_materialize_tuning``. + """ + variants = getattr(plan_obj, "variants", None) + if isinstance(variants, Mapping): + wrapped_variants = {k: _wrap_grouped_moe_plan(v) for k, v in variants.items()} + return dataclasses.replace(plan_obj, variants=wrapped_variants) + + orig_compile_jobs = getattr(plan_obj, "_compile_jobs", None) + orig_memory = getattr(plan_obj, "_memory_requirements", None) + orig_materialize = getattr(plan_obj, "_materialize", None) + if orig_compile_jobs is None or orig_materialize is None: + return plan_obj + + def _compile_jobs(config: Any, device: Any): + return orig_compile_jobs(_force_grouped_moe_config(config), device) + + def _materialize(selection: Any, device: Any): + cfg = getattr(selection, "config", None) + new_cfg = _force_grouped_moe_config(cfg) + if new_cfg is not cfg: + selection = dataclasses.replace(selection, config=new_cfg) + return orig_materialize(selection, device) + + updates: dict[str, Any] = { + "_compile_jobs": _compile_jobs, + "_materialize": _materialize, + } + if orig_memory is not None: + + def _memory_requirements(config: Any, device: Any): + return orig_memory(_force_grouped_moe_config(config), device) + + updates["_memory_requirements"] = _memory_requirements + + return dataclasses.replace(plan_obj, **updates) + + +def _patch_ep_grouped_routing() -> None: + """Prefer grouped over direct W4A8 dynamic routing on EP small batches (e.g. M=5). + + On EP4, 75% of routed slots are ``-1`` and consecutive speculative tokens share + hot experts; grouped routing compacts out ``-1`` slots and coalesces duplicate + expert loads into one tile, beating direct routing by ~0.9-1.6 ms/step at M=5. + + Normalizes ``dynamic_route_mode`` from ``"direct"`` to ``"grouped"`` in the + returned ``b12x`` ``Plan`` callbacks (``_compile_jobs``, ``_memory_requirements``, + ``_materialize``) and overrides ``_heuristic_dynamic_route_mode`` instead of + patching ``_dynamic_direct_routing_selected`` or zeroing + ``_DIRECT_ROUTING_MAX_ROUTED_ROWS``. That keeps parent planning and unpatched + ``b12x`` compilation subprocesses 100% consistent on program keys while + preserving validation of cached ``"direct"`` policy files. + """ + raw = os.environ.get(FORCE_GROUPED_ROUTING_ENV, "1").strip().lower() + if raw in ("0", "false", "off", "no"): + return + try: + from b12x.moe import fused_moe as fm_pkg + from b12x.moe.fused_moe import _impl as fm_impl + from b12x.moe.fused_moe import _preparation as fm_prep + except ImportError as exc: + raise RuntimeError( + f"SIRCL_B12X_EP_MOE ({FORCE_GROUPED_ROUTING_ENV}=1): cannot import " + f"b12x.moe.fused_moe symbols: {exc}" + ) from exc + + orig_heur = _require_attr( + fm_impl, "_heuristic_dynamic_route_mode", "_patch_ep_grouped_routing" + ) + orig_plan = _require_attr(fm_prep, "plan", "_patch_ep_grouped_routing") + + patched = False + + if not getattr(orig_heur, "_sircl_grouped_patched", False): + + def _always_grouped_heuristic(*_args: Any, **_kwargs: Any) -> str: + return "grouped" + + _always_grouped_heuristic._sircl_grouped_patched = True + fm_impl._heuristic_dynamic_route_mode = _always_grouped_heuristic + patched = True + + if not getattr(orig_plan, "_sircl_grouped_patched", False): + + def _wrapped_plan(*args: Any, **kwargs: Any): + return _wrap_grouped_moe_plan(orig_plan(*args, **kwargs)) + + _wrapped_plan._sircl_grouped_patched = True + fm_prep.plan = _wrapped_plan + if getattr(fm_pkg, "_canonical_plan_execution", None) is orig_plan: + fm_pkg._canonical_plan_execution = _wrapped_plan + elif getattr(fm_pkg, "plan_execution", None) is orig_plan: + fm_pkg.plan_execution = _wrapped_plan + patched = True + + if patched: + logger.info( + "Patched b12x MoE preparation plan + heuristic to force grouped EP routing" + ) diff --git a/integrations/vllm/libsircl/sparkring_libsircl.py b/integrations/vllm/libsircl/sparkring_libsircl.py index dde22e36..3ff1850c 100644 --- a/integrations/vllm/libsircl/sparkring_libsircl.py +++ b/integrations/vllm/libsircl/sparkring_libsircl.py @@ -130,6 +130,17 @@ def resolved_target(): "names") from None +def _register_ep_extensions(): + """Install opt-in b12x EP MoE and SIRCL-EP all2all hooks when requested by env.""" + for env_flag, module_name, fn_name in ( + ("SIRCL_B12X_EP_MOE", "sircl_ep_b12x", "install_b12x_ep_moe"), + ("SIRCL_EP_ALL2ALL", "sircl_ep_all2all", "install_sircl_ep_all2all"), + ): + if os.environ.get(env_flag, "").strip().lower() in ("1", "true", "on", "yes"): + mod = __import__(module_name) + getattr(mod, fn_name)() + + def register(): """Point vLLM's PyNccl at the checked libsircl library; vLLM may call this more than once.""" path = selected() @@ -140,3 +151,5 @@ def register(): if found is not None and found != path: raise LibsirclSelectionError(f"vLLM resolves {TARGET} to {found!r}, not {path}: it read its environment " "before the plugin set the variable, so PyNccl would load that library") + _register_ep_extensions() + diff --git a/integrations/vllm/libsircl/test_sircl_ep_all2all.py b/integrations/vllm/libsircl/test_sircl_ep_all2all.py new file mode 100644 index 00000000..9f78b5ba --- /dev/null +++ b/integrations/vllm/libsircl/test_sircl_ep_all2all.py @@ -0,0 +1,1037 @@ +"""The SIRCL-EP all-to-all manager: exchange paths, buffers and numerical parity, offline. + +vLLM's ``all2all`` module, its ``CudaCommunicator`` and ``libsircl`` are stand-ins +here: ``AgRsAll2AllManager`` records the size exchanges the pipeline would make, +and ``FakeLib`` models ``sirclEpDispatch``/``sirclEpCombine`` from their +published contract (``spark_transport/libsircl/kernels/sircl_p2p.cu``, +``namespace sircl_ep``): + +- every rank's slice of the dispatch output holds, per peer, the rows that peer + routed to this rank in that peer's token order, then a padded tail the kernel + masks with a non-local expert ID and a zero weight; +- a receiver fails the call when a peer routes more rows than ``max_tokens``; +- combine returns to each peer the expert output of the rows that peer sent, and + sums for every own token the one row each peer returns for it, indexed by the + token's slot in the rows this rank sent that peer. + +The model reads and writes the buffers through the pointers the manager passes, +as the kernel does, so a wrong pointer, row offset or stride shows up as a wrong +result rather than as a passing test. A layer runs on every rank before any +combine, as the pipeline runs it, and the model records every +``(rank, num_tokens, max_tokens)`` triple so a test can prove that the ranks agreed +on one exchange stride. +""" +import ctypes +import importlib.util +import logging +import sys +import types +from pathlib import Path + +import pytest + +torch = pytest.importorskip("torch") + +SOURCE = Path(__file__).with_name("sircl_ep_all2all.py") +NAME = "sircl_ep_all2all_under_test" + +ELEMENT_SIZE = { + torch.float32: 4, + torch.int32: 4, + torch.float16: 2, + torch.bfloat16: 2, +} + + +def _scalar(value): + """The integer a ctypes call argument carries.""" + return getattr(value, "value", value) + + +def _view(pointer, dtype, shape): + """The tensor a device pointer addresses, for the CPU memory these tests use.""" + count = 1 + for size in shape: + count *= size + nbytes = count * ELEMENT_SIZE[dtype] + if nbytes == 0: + return torch.empty(shape, dtype=dtype) + buffer = (ctypes.c_char * nbytes).from_address(pointer) + return torch.frombuffer(buffer, dtype=torch.uint8).view(dtype).view(shape) + + +# -- the stand-in library: the kernel's contract, one process ------------------------------- + + +class Cluster: + """Every rank's routing inputs, its dispatch slot map and the calls the library saw.""" + + def __init__(self, world=4, num_experts=32, top_k=4, hidden_dim=8, dtype=torch.bfloat16): + self.world = world + self.num_experts = num_experts + self.top_k = top_k + self.hidden_dim = hidden_dim + self.dtype = dtype + self.inputs = {} + self.expert_out = {} + self.send_slots = {} + self.counts_by_rank = {} + self.dispatches = [] + self.combines = [] + self.workspaces = [] + self.error = b"" + self.fail_next = 0 + + def local_experts(self): + return self.num_experts // self.world + + def mask_for(self, rank): + """The padded tail's expert ID: a local expert of the next rank, so it is never local.""" + return ((rank + 1) % self.world) * self.local_experts() + + def routes_to(self, rank, expert): + local = self.local_experts() + return local * rank <= expert < local * (rank + 1) + + def strides(self): + """The ``(rank, num_tokens, max_tokens)`` of every dispatch, in call order.""" + return list(self.dispatches) + + def max_tokens_by_rank(self): + return {rank: max_tokens for rank, _, max_tokens in self.dispatches} + + +class FakeLib: + """``libsircl`` as ctypes presents it: functions carrying ``argtypes`` and ``restype``.""" + + class _Fn: + def __init__(self, fn): + self._fn = fn + self.argtypes = None + self.restype = None + + def __call__(self, *args): + return self._fn(*args) + + def __init__(self, cluster, rank): + self.cluster = cluster + self.rank = rank + self.sirclEpWorkspaceBytes = FakeLib._Fn(_workspace_bytes) + self.sirclEpDispatch = FakeLib._Fn(self._dispatch) + self.sirclEpCombine = FakeLib._Fn(self._combine) + self.ncclGetLastError = FakeLib._Fn(lambda comm: cluster.error) + + def _dispatch(self, hidden_in, topk_ids_in, topk_weights_in, hidden_out, topk_ids_out, topk_weights_out, + recv_counts_out, workspace, workspace_bytes, num_tokens, max_tokens, hidden_bytes, top_k, + num_experts, comm, stream): + cluster = self.cluster + rank, world = self.rank, cluster.world + num_tokens, max_tokens = _scalar(num_tokens), _scalar(max_tokens) + hidden_bytes, top_k, num_experts = _scalar(hidden_bytes), _scalar(top_k), _scalar(num_experts) + cluster.dispatches.append((rank, num_tokens, max_tokens)) + cluster.workspaces.append((rank, "dispatch", workspace.value, _scalar(workspace_bytes))) + if cluster.fail_next: + refused, cluster.fail_next = cluster.fail_next, 0 + return refused + if num_tokens > max_tokens or num_experts % world or hidden_bytes % 16: + cluster.error = b"sirclEpDispatch: invalid capacity" + return 1 + if (num_tokens == 0) != (not hidden_in.value): + raise AssertionError("dispatch must pass a null input pointer exactly when it has no tokens") + + hidden_dim = hidden_bytes // ELEMENT_SIZE[cluster.dtype] + rows = world * max_tokens + h_out = _view(hidden_out.value, cluster.dtype, (rows, hidden_dim)) + ids_out = _view(topk_ids_out.value, torch.int32, (rows, top_k)) + wts_out = _view(topk_weights_out.value, torch.float32, (rows, top_k)) + + # The rows this rank receives: each peer's tokens routed to this rank, in the peer's order. + counts = [] + for peer in range(world): + hidden_p, ids_p, weights_p = cluster.inputs[peer] + selected = [ + token + for token in range(ids_p.shape[0]) + if any(cluster.routes_to(rank, int(expert)) for expert in ids_p[token]) + ] + if len(selected) > max_tokens: + cluster.error = ( + b"sirclEpDispatch: a peer routed more rows than max_tokens: received " + + str(len(selected)).encode() + + b" rows, the receive expected " + + str(max_tokens).encode() + ) + return 1 + counts.append(len(selected)) + base, keep = peer * max_tokens, len(selected) + if keep: + h_out[base:base + keep].copy_(hidden_p[selected]) + ids_out[base:base + keep].copy_(ids_p[selected]) + wts_out[base:base + keep].copy_(weights_p[selected]) + h_out[base + keep:base + max_tokens].zero_() + ids_out[base + keep:base + max_tokens].fill_(cluster.mask_for(rank)) + wts_out[base + keep:base + max_tokens].zero_() + + # The slot of every own token in the rows this rank sends to each peer. + _, ids_me, _ = cluster.inputs[rank] + if num_tokens != ids_me.shape[0]: + raise AssertionError("dispatch must describe exactly the tokens of its own rank") + slots = [[-1] * num_tokens for _ in range(world)] + for peer in range(world): + slot = 0 + for token in range(num_tokens): + if any(cluster.routes_to(peer, int(expert)) for expert in ids_me[token]): + slots[peer][token] = slot + slot += 1 + + cluster.send_slots[rank] = slots + cluster.counts_by_rank[rank] = counts + if recv_counts_out.value: + _view(recv_counts_out.value, torch.int32, (world,)).copy_(torch.tensor(counts, dtype=torch.int32)) + return 0 + + def _combine(self, expert_out_in, hidden_out, workspace, workspace_bytes, num_tokens, max_tokens, hidden_dim, + datatype, comm, stream): + cluster = self.cluster + rank, world = self.rank, cluster.world + num_tokens, max_tokens = _scalar(num_tokens), _scalar(max_tokens) + hidden_dim = _scalar(hidden_dim) + cluster.combines.append((rank, num_tokens, max_tokens)) + cluster.workspaces.append((rank, "combine", workspace.value, _scalar(workspace_bytes))) + if (num_tokens == 0) != (not hidden_out.value): + raise AssertionError("combine must pass a null output pointer exactly when it has no tokens") + own = cluster.expert_out[rank] + if expert_out_in.value != own.data_ptr(): + raise AssertionError("combine must read the expert output of its own slice") + if num_tokens == 0: + return 0 + slots = cluster.send_slots[rank] + out = _view(hidden_out.value, cluster.dtype, (num_tokens, hidden_dim)) + acc = out.float() + acc.zero_() + for peer in range(world): + # The rows this rank sent peer now sit in the peer's slice, in this rank's block of it. + sent = cluster.expert_out[peer][rank * max_tokens:] + for token in range(num_tokens): + slot = slots[peer][token] + if slot >= 0: + acc[token] += sent[slot].float() + out.copy_(acc.to(cluster.dtype)) + return 0 + + +def _workspace_bytes(world, max_tokens, hidden_bytes): + """``sirclEpWorkspaceBytes``: the layouts of ``sccl_engine_ep_workspace_bytes``, 64-byte aligned.""" + + def align(value): + return (value + 63) & ~63 + + indices = align(world * max_tokens * 4) + return 64 + 2 * indices + align(world * max_tokens * hidden_bytes) + + +# -- stand-ins for vLLM --------------------------------------------------------------------- + + +class AgRsAll2AllManager: + """vLLM's manager: the size exchange and the fallbacks the SIRCL-EP manager defers to.""" + + def __init__(self, cpu_group, tcp_store_group=None): + self.cpu_group = cpu_group + self.tcp_store_group = tcp_store_group + self.size_requests = [] + self.dispatch_calls = 0 + self.combine_calls = 0 + + def _get_comm_group(self, is_sequence_parallel=False): + return self.cpu_group + + def _get_sizes(self, num_tokens, group): + self.size_requests.append(num_tokens) + return group.sizes + + def dispatch(self, hidden_states, topk_weights, topk_ids, is_sequence_parallel=False, extra_tensors=None): + self.dispatch_calls += 1 + return ("agrs-dispatch", int(hidden_states.shape[0])) + + def combine(self, hidden_states, is_sequence_parallel=False): + self.combine_calls += 1 + return ("agrs-combine", int(hidden_states.shape[0])) + + +class MoEPrepareAndFinalizeNaiveDPEPModular: + @staticmethod + def prepare(*args, **kwargs): + return ("prepared", args, kwargs) + + +class CudaCommunicator: + def __init__(self, cpu_group, all2all_manager, use_all2all=True, *args, **kwargs): + self.cpu_group = cpu_group + self.all2all_manager = all2all_manager + self.use_all2all = use_all2all + + +def _module(name, **attributes): + module = sys.modules.get(name) + if module is None: + module = types.ModuleType(name) + sys.modules[name] = module + for key, value in attributes.items(): + setattr(module, key, value) + parent, _, leaf = name.rpartition(".") + if parent: + setattr(sys.modules[parent], leaf, module) + return module + + +@pytest.fixture +def ep(monkeypatch): + """The module under test, loaded against stand-ins for vLLM's all2all interface.""" + _module("vllm") + _module("vllm.logger", init_logger=lambda name: logging.getLogger(name)) + _module("vllm.distributed") + _module("vllm.distributed.device_communicators") + _module("vllm.distributed.device_communicators.all2all", AgRsAll2AllManager=AgRsAll2AllManager) + _module("vllm.distributed.device_communicators.cuda_communicator", CudaCommunicator=CudaCommunicator) + _module("vllm.model_executor") + _module("vllm.model_executor.layers") + _module("vllm.model_executor.layers.fused_moe") + _module("vllm.model_executor.layers.fused_moe.prepare_finalize") + _module( + "vllm.model_executor.layers.fused_moe.prepare_finalize.naive_dp_ep", + MoEPrepareAndFinalizeNaiveDPEPModular=MoEPrepareAndFinalizeNaiveDPEPModular, + ) + + spec = importlib.util.spec_from_file_location(NAME, SOURCE) + module = importlib.util.module_from_spec(spec) + sys.modules[NAME] = module + spec.loader.exec_module(module) + for registered in list(module._LIVE_MANAGERS): + module._LIVE_MANAGERS.discard(registered) + yield module + sys.modules.pop(NAME, None) + + +def _manager_class(module): + """The manager with the device and metadata seams of these CPU tests overridden.""" + + class TestManager(module.SirclEpAll2AllManager): + capturing = False + shared_tokens = None + + def _capturing(self): + return self.capturing + + def _shared_tokens(self): + return self.shared_tokens + + def _on_device(self, tensor): + return True + + def _stream_ptr(self, device): + return ctypes.c_void_p(0) + + return TestManager + + +class Node: + """One rank: its group, its ``libsircl`` stand-in and its manager. + + ``dp_bound`` models vLLM's ``ForwardContext.dp_metadata``: ``"auto"`` reports the + true maximum token count of the group, an integer reports a stale or partial + value, and ``None`` reports that no metadata is available. + """ + + def __init__(self, module, cluster, rank, *, static_cap=96, sizes=None, expert_map=None, device_comm=True, + dp_bound="auto"): + self.module = module + self.cluster = cluster + self.rank = rank + self.expert_map = expert_map + self.dp_bound = dp_bound + self.group = types.SimpleNamespace( + world_size=cluster.world, + rank_in_group=rank, + sizes=list(sizes) if sizes is not None else [0] * cluster.world, + device_communicator=None, + ) + self.lib = FakeLib(cluster, rank) + self.device_comm = None + if device_comm: + self.device_comm = types.SimpleNamespace( + pynccl_comm=types.SimpleNamespace( + nccl=types.SimpleNamespace(lib=self.lib), + comm=0x1000 + rank, + world_size=cluster.world, + rank=rank, + disabled=False, + ) + ) + self.manager = _manager_class(module)(self.group, None, device_comm=self.device_comm) + self.manager._static_max_tokens = static_cap if static_cap else 0 + + @property + def capturing(self): + """Whether the manager believes it is inside a CUDA graph capture.""" + return self.manager.capturing + + @capturing.setter + def capturing(self, value): + self.manager.capturing = value + + def dispatch(self, hidden=None, weights=None, ids=None, **kwargs): + if self.dp_bound == "auto": + counts = [tensor.shape[0] for tensor, _, _ in self.cluster.inputs.values()] + self.manager.shared_tokens = max(counts, default=0) or None + else: + self.manager.shared_tokens = self.dp_bound + if hidden is None: + hidden, ids, weights = self.cluster.inputs[self.rank] + self.module._ACTIVE_META.current = (self.cluster.num_experts, self.expert_map) + try: + return self.manager.dispatch(hidden, weights, ids, **kwargs) + finally: + self.module._ACTIVE_META.current = None + + def combine(self, hidden_states, **kwargs): + return self.manager.combine(hidden_states, **kwargs) + + +def _expert_map(cluster, rank): + """The rank's slice of a linear expert map: local IDs on this rank, ``-1`` elsewhere.""" + local = cluster.local_experts() + mapping = torch.full((cluster.num_experts,), -1, dtype=torch.int32) + mapping[rank * local:(rank + 1) * local] = torch.arange(local, dtype=torch.int32) + return mapping + + +def _inputs(cluster, counts, seed, target_ranks=None): + """Per-rank routing inputs with these token counts; ``target_ranks`` restricts expert IDs.""" + generator = torch.Generator().manual_seed(seed) + if target_ranks is None: + low, high = 0, cluster.num_experts + else: + low = min(target_ranks) * cluster.local_experts() + high = (max(target_ranks) + 1) * cluster.local_experts() + for rank, count in enumerate(counts): + hidden = torch.randn((count, cluster.hidden_dim), generator=generator).to(cluster.dtype).contiguous() + ids = torch.randint(low, high, (count, cluster.top_k), generator=generator, dtype=torch.int32).contiguous() + weights = torch.rand((count, cluster.top_k), generator=generator, dtype=torch.float32).contiguous() + cluster.inputs[rank] = (hidden, ids, weights) + + +def _expert(h_out, ids_out, wts_out): + """A row-independent expert: a row's output depends only on that row's content.""" + return (h_out.float() * (1.0 + wts_out.sum(dim=1, keepdim=True))).to(h_out.dtype).contiguous() + + +def _expected(hidden, ids, weights, cluster): + """Combine's result from which peers each token reaches: one contribution per peer.""" + value = (hidden.float() * (1.0 + weights.sum(dim=1, keepdim=True))).to(cluster.dtype).float() + out = torch.zeros((hidden.shape[0], hidden.shape[1]), dtype=torch.float32) + for token in range(hidden.shape[0]): + peers = {int(expert) // cluster.local_experts() for expert in ids[token]} + for _ in peers: + out[token] += value[token] + return out.to(cluster.dtype) + + +def _nodes(ep, cluster, **kwargs): + """One manager per rank, all with the same configuration, as the group is configured.""" + return { + rank: Node(ep, cluster, rank, expert_map=_expert_map(cluster, rank), **kwargs) + for rank in range(cluster.world) + } + + +def _layer(nodes): + """One MoE layer on every rank: dispatch, the row-local expert, then combine.""" + dispatched = {rank: node.dispatch() for rank, node in nodes.items()} + cluster = nodes[0].cluster + cluster.expert_out = { + rank: _expert(h_out, ids_out, wts_out) for rank, (h_out, wts_out, ids_out) in dispatched.items() + } + combined = {rank: node.combine(cluster.expert_out[rank]) for rank, node in nodes.items()} + return dispatched, combined + + +# -- the exchange itself -------------------------------------------------------------------- + + +@pytest.mark.parametrize("dtype", [torch.bfloat16, torch.float16, torch.float32]) +def test_the_static_path_matches_the_analytic_exchange(ep, dtype): + cluster = Cluster(dtype=dtype) + _inputs(cluster, [5, 5, 5, 5], seed=7) + nodes = _nodes(ep, cluster, static_cap=96) + dispatched, combined = _layer(nodes) + for rank in range(cluster.world): + hidden, ids, weights = cluster.inputs[rank] + assert torch.equal(combined[rank], _expected(hidden, ids, weights, cluster)) + # The exchange runs at the run's constant capacity, so every slice carries a padded tail. + assert dispatched[rank][0].shape == (cluster.world * 96, cluster.hidden_dim) + assert nodes[rank].manager.stats()["static_dispatches"] == 1 + assert nodes[rank].manager.stats()["size_exchanges"] == 0 + assert nodes[rank].manager.size_requests == [] + + +def test_unequal_token_counts_share_one_exchange_stride(ep): + """DP ranks holding 6, 5, 12 and 0 tokens must still agree on the stride.""" + cluster = Cluster() + counts = [6, 5, 12, 0] + _inputs(cluster, counts, seed=9) + nodes = _nodes(ep, cluster, static_cap=96) + _, combined = _layer(nodes) + strides = cluster.max_tokens_by_rank() + assert set(strides.values()) == {96}, strides + for rank in range(cluster.world): + hidden, ids, weights = cluster.inputs[rank] + assert torch.equal(combined[rank], _expected(hidden, ids, weights, cluster)) + assert nodes[rank].manager.stats()["static_dispatches"] == 1 + assert cluster.dispatches[rank][1] == counts[rank] + + +def test_without_dp_metadata_every_rank_takes_the_dynamic_path(ep): + cluster = Cluster() + counts = [6, 5, 12, 0] + _inputs(cluster, counts, seed=13) + nodes = _nodes(ep, cluster, static_cap=96, dp_bound=None, sizes=counts) + _, combined = _layer(nodes) + assert set(cluster.max_tokens_by_rank().values()) == {12} + for rank in range(cluster.world): + hidden, ids, weights = cluster.inputs[rank] + assert torch.equal(combined[rank], _expected(hidden, ids, weights, cluster)) + assert nodes[rank].manager.stats()["dynamic_dispatches"] == 1 + assert nodes[rank].manager.stats()["size_exchanges"] == 1 + + +def test_a_bound_above_the_cap_is_dynamic_on_every_rank(ep): + cluster = Cluster() + counts = [6, 5, 12, 0] + _inputs(cluster, counts, seed=17) + nodes = _nodes(ep, cluster, static_cap=8, sizes=counts) + _, combined = _layer(nodes) + assert set(cluster.max_tokens_by_rank().values()) == {12} + for rank in range(cluster.world): + hidden, ids, weights = cluster.inputs[rank] + assert torch.equal(combined[rank], _expected(hidden, ids, weights, cluster)) + assert nodes[rank].manager.stats()["static_dispatches"] == 0 + + +def test_the_static_path_agrees_with_the_dynamic_path_when_counts_are_equal(ep): + cluster = Cluster() + _inputs(cluster, [6, 6, 6, 6], seed=19) + results = {} + for static_cap in (0, 96): + cluster.dispatches.clear() + cluster.send_slots.clear() + nodes = _nodes(ep, cluster, static_cap=static_cap, sizes=[6, 6, 6, 6]) + _, combined = _layer(nodes) + results[static_cap] = combined + for rank, node in nodes.items(): + if static_cap: + assert node.manager.stats()["static_dispatches"] == 1 + else: + assert node.manager.stats()["size_exchanges"] == 1 + for rank in range(cluster.world): + assert torch.equal(results[0][rank], results[96][rank]), f"rank {rank} disagrees between paths" + + +def test_ranks_that_receive_nothing_still_combine_their_own_tokens(ep): + cluster = Cluster() + _inputs(cluster, [6, 6, 6, 6], seed=23, target_ranks=(0, 1)) + nodes = _nodes(ep, cluster, static_cap=96) + _, combined = _layer(nodes) + for rank in range(cluster.world): + hidden, ids, weights = cluster.inputs[rank] + assert torch.equal(combined[rank], _expected(hidden, ids, weights, cluster)) + # Every token targets ranks 0 and 1, so ranks 2 and 3 receive no rows at all. + for idle in (2, 3): + assert cluster.counts_by_rank[idle] == [0] * cluster.world + + +def test_a_masked_tail_never_contributes_to_combine(ep): + cluster = Cluster() + _inputs(cluster, [3, 3, 3, 3], seed=29) + nodes = _nodes(ep, cluster, static_cap=96) + dispatched, _ = _layer(nodes) + rank = 1 + h_out, wts_out, ids_out = dispatched[rank] + max_tokens = h_out.shape[0] // cluster.world + local = cluster.local_experts() + for peer in range(cluster.world): + base = peer * max_tokens + real = cluster.counts_by_rank[rank][peer] + assert real < max_tokens, "this test needs a padded tail on every slice" + tail_ids = ids_out[base + real:base + max_tokens] + assert torch.equal(tail_ids, torch.full_like(tail_ids, cluster.mask_for(rank))) + assert not wts_out[base + real:base + max_tokens].any() + # The mask names a local expert of the next rank, never one of this rank's own. + assert not ((tail_ids >= rank * local) & (tail_ids < (rank + 1) * local)).any() + + +def test_the_counts_buffer_reports_what_each_peer_routed(ep): + cluster = Cluster() + _inputs(cluster, [6, 6, 6, 6], seed=31) + nodes = _nodes(ep, cluster, static_cap=96) + rank = 2 + nodes[rank].dispatch() + arena = nodes[rank].manager._active_call.arena + assert torch.equal(arena.counts, torch.tensor(cluster.counts_by_rank[rank], dtype=torch.int32)) + + +def test_an_idle_step_dispatch_and_combine_are_no_ops(ep): + cluster = Cluster() + _inputs(cluster, [0, 0, 0, 0], seed=37) + nodes = _nodes(ep, cluster, static_cap=96, sizes=[0, 0, 0, 0]) + dispatched, combined = _layer(nodes) + for rank in range(cluster.world): + assert dispatched[rank][0].shape == (cluster.world, cluster.hidden_dim) + assert combined[rank].shape == (0, cluster.hidden_dim) + assert nodes[rank].manager.stats()["combines"] == 1 + + +# -- buffers, capture and synchronization --------------------------------------------------- + + +def test_steady_state_dispatch_and_combine_allocate_nothing(ep, monkeypatch): + cluster = Cluster() + _inputs(cluster, [4, 4, 4, 4], seed=41) + nodes = _nodes(ep, cluster, static_cap=96) + first_dispatched, first_combined = _layer(nodes) + + allocations = [] + real_empty, real_zeros = torch.empty, torch.zeros + + def counting_empty(*args, **kwargs): + allocations.append(("empty", args)) + return real_empty(*args, **kwargs) + + def counting_zeros(*args, **kwargs): + allocations.append(("zeros", args)) + return real_zeros(*args, **kwargs) + + monkeypatch.setattr(torch, "empty", counting_empty) + monkeypatch.setattr(torch, "zeros", counting_zeros) + second_dispatched, second_combined = _layer(nodes) + assert allocations == [] + for rank in range(cluster.world): + assert second_dispatched[rank][0].data_ptr() == first_dispatched[rank][0].data_ptr() + assert second_combined[rank].data_ptr() == first_combined[rank].data_ptr() + + +def test_combine_uses_the_workspace_its_dispatch_was_given(ep): + """The workspace is the kernel's cross-call state; combine must name the buffer dispatch used.""" + cluster = Cluster() + _inputs(cluster, [4, 4, 4, 4], seed=43) + nodes = _nodes(ep, cluster, static_cap=96) + _layer(nodes) + node = nodes[0] + node.dispatch() + dispatch_workspace = node.manager._workspace + # A growth elsewhere in the pipeline would leave a different current workspace; the combined + # call must still describe the one its own dispatch wrote. + node.manager._workspace = torch.empty_like(dispatch_workspace) + cluster.workspaces.clear() + node.combine(cluster.expert_out[0]) + assert [pointer for _, kind, pointer, _ in cluster.workspaces if kind == "combine"] == [ + dispatch_workspace.data_ptr() + ] + + +def test_the_static_path_reads_nothing_back_from_the_device(ep, monkeypatch): + cluster = Cluster() + _inputs(cluster, [5, 5, 5, 5], seed=43) + nodes = _nodes(ep, cluster, static_cap=96) + + def refuse(*args, **kwargs): + raise AssertionError("the static path must not read a result back to the host") + + for name in ("item", "tolist", "cpu", "numpy"): + monkeypatch.setattr(torch.Tensor, name, refuse) + monkeypatch.setattr(torch.cuda, "synchronize", refuse) + _layer(nodes) + for node in nodes.values(): + assert node.manager.stats()["static_dispatches"] == 1 + assert node.manager.size_requests == [] + + +def test_tokens_across_dp_reads_the_synchronized_metadata(ep, monkeypatch): + def with_metadata(metadata): + monkeypatch.setitem( + sys.modules, + "vllm.forward_context", + types.SimpleNamespace(get_forward_context=lambda: types.SimpleNamespace(dp_metadata=metadata)), + ) + + with_metadata( + types.SimpleNamespace( + max_tokens_across_dp_cpu=torch.tensor([12], dtype=torch.int32), + num_tokens_across_dp_cpu=torch.tensor([6, 0, 12, 5], dtype=torch.int32), + ) + ) + assert ep._tokens_across_dp() == 12 + + # The CED hook rewrites the per-rank counts without the maximum: the larger one bounds the step. + with_metadata( + types.SimpleNamespace( + max_tokens_across_dp_cpu=torch.tensor([64], dtype=torch.int32), + num_tokens_across_dp_cpu=torch.tensor([6, 0, 12, 5], dtype=torch.int32), + ) + ) + assert ep._tokens_across_dp() == 64 + + # Only the per-rank counts: their maximum is the bound. + with_metadata(types.SimpleNamespace(num_tokens_across_dp_cpu=torch.tensor([6, 0, 12, 5], dtype=torch.int32))) + assert ep._tokens_across_dp() == 12 + + # A scalar rather than a vector, and plain integers, are both accepted. + with_metadata(types.SimpleNamespace(max_tokens_across_dp_cpu=9)) + assert ep._tokens_across_dp() == 9 + + # No metadata, no bound. + with_metadata(None) + assert ep._tokens_across_dp() is None + + # A device-resident count would synchronize the device: no bound rather than a read. + with_metadata( + types.SimpleNamespace( + max_tokens_across_dp_cpu=torch.tensor([12], dtype=torch.int32, device="meta"), + num_tokens_across_dp_cpu=None, + ) + ) + assert ep._tokens_across_dp() is None + + # vLLM's forward context is not importable at all. + monkeypatch.setitem(sys.modules, "vllm.forward_context", None) + assert ep._tokens_across_dp() is None + + +def test_the_dynamic_path_makes_one_size_exchange_per_layer(ep): + cluster = Cluster() + _inputs(cluster, [3, 3, 3, 3], seed=47) + nodes = _nodes(ep, cluster, static_cap=0, sizes=[3, 3, 3, 3]) + for _ in range(3): + _layer(nodes) + for node in nodes.values(): + assert node.manager.size_requests == [3, 3, 3] + assert node.manager.stats()["size_exchanges"] == 3 + assert node.manager.stats()["static_dispatches"] == 0 + + +def test_growth_retires_buffers_instead_of_freeing_them(ep): + cluster = Cluster() + _inputs(cluster, [4, 4, 4, 4], seed=53) + nodes = _nodes(ep, cluster, static_cap=96, sizes=[256, 256, 256, 256]) + dispatched, _ = _layer(nodes) + captured = dispatched[1][0].untyped_storage().data_ptr() + assert nodes[1].manager.stats()["arena_allocations"] == 1 # the first call: workspace and arena + + for node in nodes.values(): + node.manager._static_max_tokens = 0 # a prefill-sized step takes the dynamic path + for rank in range(cluster.world): + cluster.inputs[rank] = ( + torch.zeros((256, cluster.hidden_dim), dtype=cluster.dtype), + torch.zeros((256, cluster.top_k), dtype=torch.int32), + torch.zeros((256, cluster.top_k), dtype=torch.float32), + ) + prefill, _ = _layer(nodes) + assert prefill[1][0].shape == (cluster.world * 256, cluster.hidden_dim) + retired = [tensor.untyped_storage().data_ptr() for tensor in nodes[1].manager._retired] + assert captured in retired, "the buffer a graph may point at must stay alive" + assert nodes[1].manager.stats()["arena_allocations"] == 2 + + +def test_capture_uses_reserved_buffers_and_refuses_to_allocate(ep, monkeypatch): + cluster = Cluster() + _inputs(cluster, [4, 4, 4, 4], seed=59) + nodes = _nodes(ep, cluster, static_cap=96) + _layer(nodes) # warm, as vLLM's per-bucket warmup does before capture + + def refuse(*args, **kwargs): + raise AssertionError("nothing may allocate inside a CUDA graph capture") + + for node in nodes.values(): + node.capturing = True + monkeypatch.setattr(torch, "empty", refuse) + _layer(nodes) + for node in nodes.values(): + assert node.manager.stats()["static_dispatches"] == 2 + + +def test_capture_ignores_the_dp_bound_and_uses_the_constant(ep): + """A capture runs the static path with the run's capacity even with no metadata at all.""" + cluster = Cluster() + _inputs(cluster, [6, 6, 6, 6], seed=61) + nodes = _nodes(ep, cluster, static_cap=96) + _layer(nodes) # warm: static at the constant capacity, so the arena covers it + for node in nodes.values(): + node.dp_bound = None # no metadata at capture time + node.capturing = True + cluster.dispatches.clear() + _layer(nodes) + assert set(cluster.max_tokens_by_rank().values()) == {96} + for rank, node in nodes.items(): + assert node.manager.stats()["static_dispatches"] == 2 + assert node.manager.size_requests == [] + + +def test_a_capture_size_above_the_cap_keeps_its_own_capacity(ep, caplog): + cluster = Cluster() + _inputs(cluster, [12, 12, 12, 12], seed=67) + nodes = _nodes(ep, cluster, static_cap=8, sizes=[12, 12, 12, 12]) + _layer(nodes) # the bound is above the cap, so this warm step is dynamic and sizes the arena + for node in nodes.values(): + node.capturing = True + cluster.dispatches.clear() + with caplog.at_level(logging.WARNING): + _layer(nodes) + assert set(cluster.max_tokens_by_rank().values()) == {12} + assert "capture size 12 exceeds" in caplog.text + + +def test_capture_without_warm_buffers_falls_back_to_the_pipeline_default(ep): + cluster = Cluster() + _inputs(cluster, [4, 4, 4, 4], seed=71) + nodes = _nodes(ep, cluster, static_cap=96) + nodes[0].capturing = True + assert nodes[0].dispatch()[0] == "agrs-dispatch" + assert nodes[0].manager.stats()["agrs_fallbacks"] == 1 + + +# -- the stats summary ---------------------------------------------------------------------- + + +def test_the_stats_summary_is_logged_on_first_static_interval_and_exit(ep, monkeypatch, caplog): + monkeypatch.setattr(ep, "STATS_INTERVAL", 2) + cluster = Cluster() + _inputs(cluster, [4, 4, 4, 4], seed=73) + node = Node(ep, cluster, 0, static_cap=96, expert_map=_expert_map(cluster, 0)) + with caplog.at_level(logging.INFO): + _layer({0: node, **{rank: Node(ep, cluster, rank, static_cap=96, + expert_map=_expert_map(cluster, rank)) + for rank in range(1, cluster.world)}}) + node.dispatch() # second dispatch of this manager reaches the interval + ep._log_at_exit() + lines = [record.getMessage() for record in caplog.records if ep.STATS_TAG in record.getMessage()] + assert any("reason=first-static" in line for line in lines) + assert any("reason=interval" in line for line in lines) + assert any("reason=atexit" in line for line in lines) + summary = next(line for line in lines if "reason=atexit" in line) + assert "static_cap=96" in summary + assert "static_dispatches=2" in summary + assert "size_exchanges=0" in summary + assert "dispatches=2" in summary + + +# -- eligibility and failure ----------------------------------------------------------------- + + +@pytest.mark.parametrize( + "bound, cap, expected", + [(0, 96, 0), (1, 96, 96), (12, 96, 96), (96, 96, 96), (97, 96, 0), (12, 8, 0), (5, 0, 0)], +) +def test_the_capacity_is_the_run_constant_or_zero(bound, cap, expected, ep): + assert ep._shared_capacity(bound, cap) == expected + + +def test_a_step_above_the_static_cap_takes_the_dynamic_path(ep): + cluster = Cluster() + _inputs(cluster, [0, 0, 0, 0], seed=79) + cluster.inputs[0] = ( + torch.zeros((97, cluster.hidden_dim), dtype=cluster.dtype), + torch.zeros((97, cluster.top_k), dtype=torch.int32), + torch.zeros((97, cluster.top_k), dtype=torch.float32), + ) + node = Node(ep, cluster, 0, static_cap=96, sizes=[97, 0, 0, 0], expert_map=_expert_map(cluster, 0)) + node.dispatch() + assert node.manager.stats()["dynamic_dispatches"] == 1 + assert node.manager.size_requests == [97] + + +def test_a_peer_routing_more_rows_than_the_capacity_fails_loudly(ep): + """Metadata that understates the group's bound is the residual risk, and it fails loudly.""" + cluster = Cluster() + _inputs(cluster, [2, 2, 2, 2], seed=83) + node = Node(ep, cluster, 0, static_cap=96, expert_map=_expert_map(cluster, 0), dp_bound=4) + node.dispatch() # capacity 96 covers this step + cluster.inputs[1] = ( + torch.zeros((100, cluster.hidden_dim), dtype=cluster.dtype), + torch.zeros((100, cluster.top_k), dtype=torch.int32), # every token routes to rank 0 + torch.full((100, cluster.top_k), 0.25, dtype=torch.float32), + ) + with pytest.raises(RuntimeError, match="sirclEpDispatch failed with rc=1"): + node.dispatch() + + +def test_the_first_failure_disables_the_exchange_and_falls_back(ep): + cluster = Cluster() + _inputs(cluster, [4, 4, 4, 4], seed=89) + node = Node(ep, cluster, 1, static_cap=96, expert_map=_expert_map(cluster, 1)) + cluster.fail_next = 1 + assert node.dispatch()[0] == "agrs-dispatch" + assert "sirclEpDispatch returned rc=1" in node.manager._disabled_reason + assert node.dispatch()[0] == "agrs-dispatch" + assert node.manager.stats()["agrs_fallbacks"] == 2 + assert node.manager.stats()["dispatches"] == 0 + + +def test_combine_without_a_dispatch_defers_to_the_pipeline_default(ep): + cluster = Cluster() + _inputs(cluster, [4, 4, 4, 4], seed=97) + node = Node(ep, cluster, 0, static_cap=96, expert_map=_expert_map(cluster, 0)) + assert node.combine(torch.zeros((4, cluster.hidden_dim), dtype=cluster.dtype))[0] == "agrs-combine" + + +@pytest.mark.parametrize("reason", ["extra_tensors", "non_linear_map", "two_ranks", "no_device_comm_group"]) +def test_unsupported_calls_take_the_pipeline_default(ep, reason): + world = 2 if reason == "two_ranks" else 4 + cluster = Cluster(world=world) + _inputs(cluster, [4] * world, seed=101) + mapping = _expert_map(cluster, 0) + node = Node( + ep, + cluster, + 0, + static_cap=96, + sizes=[4] * world, + expert_map=torch.zeros_like(mapping) if reason == "non_linear_map" else mapping, + device_comm=reason != "no_device_comm_group", + ) + extra = [torch.zeros(1)] if reason == "extra_tensors" else None + assert node.dispatch(extra_tensors=extra)[0] == "agrs-dispatch" + assert node.manager.stats()["agrs_fallbacks"] == 1 + + +# -- installation --------------------------------------------------------------------------- + + +def test_install_replaces_the_all2all_manager_on_the_cuda_communicator(ep, monkeypatch): + monkeypatch.setenv(ep.ENV_STATIC_A2A, "1") + monkeypatch.setenv(ep.ENV_STATIC_MAX_TOKENS, "64") + assert ep.install_sircl_ep_all2all() is True + cpu_group = types.SimpleNamespace(world_size=4, rank_in_group=0) + communicator = CudaCommunicator.__new__(CudaCommunicator) + CudaCommunicator.__init__(communicator, cpu_group, AgRsAll2AllManager(cpu_group)) + assert isinstance(communicator.all2all_manager, ep.SirclEpAll2AllManager) + assert communicator.all2all_manager._static_max_tokens == 64 + + +def test_install_leaves_a_different_all2all_manager_in_place(ep): + assert ep.install_sircl_ep_all2all() is True + cpu_group = types.SimpleNamespace(world_size=4, rank_in_group=0) + installed = object() + communicator = CudaCommunicator.__new__(CudaCommunicator) + CudaCommunicator.__init__(communicator, cpu_group, installed) + assert communicator.all2all_manager is installed + + +def test_install_fails_closed_when_all2all_base_is_stub(ep, monkeypatch): + monkeypatch.setattr(ep, "ALL2ALL_BASE_IS_STUB", True) + with pytest.raises(RuntimeError, match="AgRsAll2AllManager could not be imported"): + ep.install_sircl_ep_all2all() + + +def test_install_binds_tcp_store_group_by_parameter_name(ep, monkeypatch): + """tcp_store_group is bound via inspect.signature regardless of positional index.""" + sentinel_store = object() + + class ConcreteCudaComm: + def __init__(self, cpu_group, all2all_manager, tcp_store_group=None, use_all2all=True): + self.cpu_group = cpu_group + self.all2all_manager = all2all_manager + self.use_all2all = use_all2all + + class ConcretePrepare: + def prepare( + self, + a1, + topk_weights, + topk_ids, + num_experts, + expert_map, + apply_router_weight_on_input=False, + quant_config=None, + ): + return getattr(ep._ACTIVE_META, "current", None) + + monkeypatch.setattr( + sys.modules["vllm.distributed.device_communicators.cuda_communicator"], + "CudaCommunicator", + ConcreteCudaComm, + ) + monkeypatch.setattr( + sys.modules["vllm.model_executor.layers.fused_moe.prepare_finalize.naive_dp_ep"], + "MoEPrepareAndFinalizeNaiveDPEPModular", + ConcretePrepare, + ) + + assert ep.install_sircl_ep_all2all() is True + cpu_group = types.SimpleNamespace(world_size=4, rank_in_group=0) + comm = ConcreteCudaComm(cpu_group, AgRsAll2AllManager(cpu_group), sentinel_store) + assert isinstance(comm.all2all_manager, ep.SirclEpAll2AllManager) + assert comm.all2all_manager.tcp_store_group is sentinel_store + + emap = torch.tensor([0, 1, -1, -1], dtype=torch.int32) + observed = ConcretePrepare().prepare(None, None, None, 4, emap) + assert observed == (4, emap) + + +def test_install_fails_closed_on_cuda_communicator_signature_drift(ep, monkeypatch): + class DriftedCudaComm: + def __init__(self, cpu_group, all2all_manager, use_all2all=True): + self.cpu_group = cpu_group + self.all2all_manager = all2all_manager + self.use_all2all = use_all2all + + monkeypatch.setattr( + sys.modules["vllm.distributed.device_communicators.cuda_communicator"], + "CudaCommunicator", + DriftedCudaComm, + ) + with pytest.raises(RuntimeError, match="tcp_store_group"): + ep.install_sircl_ep_all2all() + + +def test_install_fails_closed_on_prepare_signature_drift(ep, monkeypatch): + class DriftedPrepare: + def prepare(self, a1, topk_weights, topk_ids): + return None + + monkeypatch.setattr( + sys.modules["vllm.model_executor.layers.fused_moe.prepare_finalize.naive_dp_ep"], + "MoEPrepareAndFinalizeNaiveDPEPModular", + DriftedPrepare, + ) + with pytest.raises(RuntimeError, match="num_experts"): + ep.install_sircl_ep_all2all() + + +def test_retired_buffers_are_bounded_and_releasable(ep): + cluster = Cluster() + _inputs(cluster, [4, 4, 4, 4], seed=103) + node = Node(ep, cluster, 0, static_cap=0, sizes=[4, 4, 4, 4], expert_map=_expert_map(cluster, 0)) + mgr = node.manager + mgr._max_retired_buffers = 4 + mgr._max_retired_bytes = 64 * 1024 + + # Repeatedly grow the arena across increasing shapes; _retired must stay within cap. + for size in (4, 16, 32, 64, 128, 256): + cluster.inputs[0] = ( + torch.zeros((size, cluster.hidden_dim), dtype=cluster.dtype), + torch.zeros((size, cluster.top_k), dtype=torch.int32), + torch.zeros((size, cluster.top_k), dtype=torch.float32), + ) + node.group.sizes = [size] * cluster.world + node.dispatch() + assert len(mgr._retired) <= mgr._max_retired_buffers + + stats = mgr.stats() + assert stats["retired_buffers"] <= 4 + assert stats["retired_evictions"] > 0 + assert stats["retired_bytes"] > 0 + + released = mgr.release_retired() + assert released == stats["retired_buffers"] + assert mgr.stats()["retired_buffers"] == 0 + assert mgr.stats()["retired_bytes"] == 0 diff --git a/integrations/vllm/libsircl/test_sircl_ep_b12x.py b/integrations/vllm/libsircl/test_sircl_ep_b12x.py new file mode 100644 index 00000000..00eeca07 --- /dev/null +++ b/integrations/vllm/libsircl/test_sircl_ep_b12x.py @@ -0,0 +1,257 @@ +"""Fail-closed contract and signature-binding tests for ``sircl_ep_b12x.py``.""" + +from __future__ import annotations + +import dataclasses +import enum +import importlib.util +import sys +import types +from pathlib import Path + +import pytest + +torch = pytest.importorskip("torch") + +SOURCE = Path(__file__).with_name("sircl_ep_b12x.py") + + +def _load_b12x(name: str): + spec = importlib.util.spec_from_file_location(name, SOURCE) + mod = importlib.util.module_from_spec(spec) + spec.loader.exec_module(mod) + return mod + + +def _install_module_tree(monkeypatch, full_name: str, leaf: types.ModuleType) -> None: + parts = full_name.split(".") + for idx in range(1, len(parts)): + prefix = ".".join(parts[:idx]) + if prefix not in sys.modules: + monkeypatch.setitem(sys.modules, prefix, types.ModuleType(prefix)) + monkeypatch.setitem(sys.modules, full_name, leaf) + for idx in range(len(parts) - 1, 0, -1): + parent = sys.modules[".".join(parts[:idx])] + child = sys.modules[".".join(parts[: idx + 1])] + monkeypatch.setattr(parent, parts[idx], child, raising=False) + + +def test_install_b12x_ep_moe_fails_closed_when_vllm_unavailable(monkeypatch): + mod = _load_b12x("sircl_ep_b12x_fail_import") + monkeypatch.setitem(sys.modules, "vllm.model_executor.layers.fused_moe.b12x", None) + with pytest.raises(RuntimeError, match="SIRCL_B12X_EP_MOE requested"): + mod.install_b12x_ep_moe() + + +def test_patch_modular_kernel_dp_workspace_binds_by_name_not_magic_index(monkeypatch): + mod = _load_b12x("sircl_ep_b12x_ws_name_bind") + received_workspaces = [] + + class FakeExperts: + output_dtype = torch.bfloat16 + + def moe_problem_size(self, a1q, w1, w2, topk_ids): + return (0, int(a1q.shape[0]), 64, int(a1q.shape[1]), int(topk_ids.shape[1])) + + def workspace_dtype(self, in_dtype): + return in_dtype + + def workspace_shapes(self, m, n, k, topk, ge, le, meta, act): + return (0,), (128,), (m, k) + + class FakeModularImpl: + def __init__(self): + self.fused_experts = FakeExperts() + + # Deliberately scrambled parameter order compared to upstream vLLM to prove + # inspect.signature binding works without magic positional indices. + def _fused_experts( + self, + workspace, + topk_ids, + w2, + w1, + a1q, + in_dtype, + activation, + local_num_experts, + global_num_experts, + expert_tokens_meta=None, + ): + received_workspaces.append(workspace) + return workspace + + fake_mk = types.ModuleType("vllm.model_executor.layers.fused_moe.modular_kernel") + fake_mk.FusedMoEKernelModularImpl = FakeModularImpl + _install_module_tree( + monkeypatch, "vllm.model_executor.layers.fused_moe.modular_kernel", fake_mk + ) + + mod._patch_modular_kernel_dp_workspace() + + impl = FakeModularImpl() + ws = ( + torch.empty((0,), dtype=torch.bfloat16), + torch.empty((128,), dtype=torch.bfloat16), + torch.empty((4, 32), dtype=torch.bfloat16), + ) + a1q = torch.empty((16, 32), dtype=torch.bfloat16) + topk_ids = torch.zeros((16, 2), dtype=torch.int32) + impl._fused_experts(ws, topk_ids, None, None, a1q, torch.bfloat16, "silu", 8, 32) + assert len(received_workspaces) == 1 + assert received_workspaces[0][2].shape == (16, 32) + + +def test_patch_modular_kernel_dp_workspace_fails_closed_on_signature_drift(monkeypatch): + mod = _load_b12x("sircl_ep_b12x_ws_drift") + + class DriftedModularImpl: + def _fused_experts(self, in_dtype, a1q, w1, w2): + return None + + fake_mk = types.ModuleType("vllm.model_executor.layers.fused_moe.modular_kernel") + fake_mk.FusedMoEKernelModularImpl = DriftedModularImpl + _install_module_tree( + monkeypatch, "vllm.model_executor.layers.fused_moe.modular_kernel", fake_mk + ) + + with pytest.raises(RuntimeError, match="signature drift"): + mod._patch_modular_kernel_dp_workspace() + + +def test_patch_b12x_dp_global_rank_fails_closed_when_missing(monkeypatch): + mod = _load_b12x("sircl_ep_b12x_rank_missing") + monkeypatch.setitem(sys.modules, "vllm.v1.worker.b12x_startup", None) + with pytest.raises(RuntimeError, match="B12xPreparationCoordinator"): + mod._patch_b12x_dp_global_rank() + + +def test_patch_dp_sync_fails_closed_on_drifted_all_reduce_tensor(monkeypatch): + mod = _load_b12x("sircl_ep_b12x_dp_sync_drift") + + class FakeCGMode(enum.IntEnum): + NONE = 0 + FULL = 2 + + @dataclasses.dataclass(frozen=True) + class FakeDesc: + cg_mode: FakeCGMode + num_tokens: int + num_reqs: int | None + + class FakeDist: + def all_reduce(self, tensor, group=None): + return None + + fake_comp = types.ModuleType("vllm.config.compilation") + fake_comp.CUDAGraphMode = FakeCGMode + fake_dp = types.ModuleType("vllm.v1.worker.gpu.dp_utils") + fake_dp.dist = FakeDist() + + # Upstream moved num_reqs from row 5 to row 4: row 5 now holds 0 instead of local num_reqs=3! + def drifted_sync(cm, desired_desc, num_tokens, num_reqs, uniform_tok, dp_size, dp_rank): + tensor = torch.zeros(6, dp_size, dtype=torch.int32) + tensor[4, dp_rank] = num_reqs + fake_dp.dist.all_reduce(tensor) + return cm.dispatch(num_reqs, num_tokens, uniform_tok), None + + def ok_dispatch(cm, dp_sync, num_reqs): + return cm.dispatch(num_reqs), dp_sync + + fake_dp.sync_cudagraph_and_dp_padding = drifted_sync + fake_dp.dispatch_cg_and_sync_dp = ok_dispatch + + _install_module_tree(monkeypatch, "vllm.config.compilation", fake_comp) + _install_module_tree(monkeypatch, "vllm.v1.worker.gpu.dp_utils", fake_dp) + + mod._patch_dp_sync_cudagraph_num_reqs() + + class FakeManager: + def dispatch(self, num_reqs, *args): + return FakeDesc(FakeCGMode.FULL, 6, num_reqs) + + with pytest.raises(RuntimeError, match="row 5 no longer carries local num_reqs"): + fake_dp.sync_cudagraph_and_dp_padding( + FakeManager(), FakeDesc(FakeCGMode.FULL, 6, 3), 6, 3, None, 4, 2 + ) + + # Unrelated float tensor during dp sync must also fail closed. + def wrong_dtype_sync(cm, desired_desc, num_tokens, num_reqs, uniform_tok, dp_size, dp_rank): + tensor = torch.zeros(6, dp_size, dtype=torch.float32) + fake_dp.dist.all_reduce(tensor) + return cm.dispatch(num_reqs, num_tokens, uniform_tok), None + + fake_dp.dist = FakeDist() + fake_dp.dispatch_cg_and_sync_dp = ok_dispatch + fake_dp.sync_cudagraph_and_dp_padding = wrong_dtype_sync + mod._patch_dp_sync_cudagraph_num_reqs() + with pytest.raises(RuntimeError, match="sync tensor contract drifted"): + fake_dp.sync_cudagraph_and_dp_padding( + FakeManager(), FakeDesc(FakeCGMode.FULL, 6, 3), 6, 3, None, 4, 2 + ) + + +def test_patch_dp_sync_fails_closed_on_missing_dp_sync_param(monkeypatch): + mod = _load_b12x("sircl_ep_b12x_dp_sync_sig_drift") + + class FakeCGMode(enum.IntEnum): + FULL = 2 + + fake_comp = types.ModuleType("vllm.config.compilation") + fake_comp.CUDAGraphMode = FakeCGMode + fake_dp = types.ModuleType("vllm.v1.worker.gpu.dp_utils") + fake_dp.dist = types.SimpleNamespace(all_reduce=lambda *_a, **_k: None) + fake_dp.sync_cudagraph_and_dp_padding = lambda cm, num_reqs, dp_size, dp_rank: None + fake_dp.dispatch_cg_and_sync_dp = lambda cm, num_reqs: None # missing dp_sync + + _install_module_tree(monkeypatch, "vllm.config.compilation", fake_comp) + _install_module_tree(monkeypatch, "vllm.v1.worker.gpu.dp_utils", fake_dp) + + with pytest.raises(RuntimeError, match="dp_sync"): + mod._patch_dp_sync_cudagraph_num_reqs() + + +def test_patch_router_skip_padding_fails_closed_and_respects_opt_out(monkeypatch): + mod = _load_b12x("sircl_ep_b12x_router_fail") + monkeypatch.setenv(mod.ROUTER_SKIP_PADDING_ENV, "0") + monkeypatch.setitem( + sys.modules, "vllm.model_executor.layers.fused_moe.router.fused_topk_bias_router", None + ) + mod._patch_router_skip_padding() # explicit opt-out succeeds without importing + + monkeypatch.setenv(mod.ROUTER_SKIP_PADDING_ENV, "1") + with pytest.raises(RuntimeError, match="fused_topk_bias_router"): + mod._patch_router_skip_padding() + + # Present module but drifted signature lacking is_padding must fail closed. + fake_router = types.ModuleType( + "vllm.model_executor.layers.fused_moe.router.fused_topk_bias_router" + ) + fake_router.dsv4_topk = lambda gating_output, top_k: gating_output + fake_router._get_padding_mask = lambda n: None + _install_module_tree( + monkeypatch, + "vllm.model_executor.layers.fused_moe.router.fused_topk_bias_router", + fake_router, + ) + with pytest.raises(RuntimeError, match="is_padding"): + mod._patch_router_skip_padding() + + +def test_patch_ep_grouped_routing_fails_closed_and_respects_opt_out(monkeypatch): + mod = _load_b12x("sircl_ep_b12x_grouped_fail") + monkeypatch.setenv(mod.FORCE_GROUPED_ROUTING_ENV, "0") + monkeypatch.setitem(sys.modules, "b12x.moe.fused_moe", None) + mod._patch_ep_grouped_routing() # opt-out respected + + monkeypatch.setenv(mod.FORCE_GROUPED_ROUTING_ENV, "1") + with pytest.raises(RuntimeError, match="b12x.moe.fused_moe"): + mod._patch_ep_grouped_routing() + + +def test_patch_dp_speculator_propose_sync_fails_closed_when_required(monkeypatch): + mod = _load_b12x("sircl_ep_b12x_spec_fail") + monkeypatch.delitem(sys.modules, "vllm.v1.worker.gpu.model_runner", raising=False) + mod._patch_dp_speculator_propose_sync(require_loaded=False) # deferred before import + with pytest.raises(RuntimeError, match="model_runner is not loaded"): + mod._patch_dp_speculator_propose_sync(require_loaded=True) diff --git a/integrations/vllm/libsircl/test_sparkring_libsircl.py b/integrations/vllm/libsircl/test_sparkring_libsircl.py index 275523b2..da513055 100644 --- a/integrations/vllm/libsircl/test_sparkring_libsircl.py +++ b/integrations/vllm/libsircl/test_sparkring_libsircl.py @@ -190,3 +190,504 @@ def test_register_confirms_vllm_resolves_the_library(tmp_path, monkeypatch, envs else: with pytest.raises(plugin.LibsirclSelectionError, match=message): plugin.register() + + +def test_register_invokes_opt_in_ep_extensions_only_when_enabled(tmp_path, monkeypatch): + path, digest = library(tmp_path) + monkeypatch.setenv(plugin.LIBRARY, str(path)) + monkeypatch.setenv(plugin.DIGEST, digest) + monkeypatch.setattr(plugin, "LOADER", lambda name: Library()) + monkeypatch.setattr(plugin, "pynccl_functions", lambda: ["ncclAllReduce"]) + monkeypatch.setattr(plugin, "resolved_target", lambda: str(path)) + called = [] + fake_b12x = types.ModuleType("sircl_ep_b12x") + fake_b12x.install_b12x_ep_moe = lambda: called.append("b12x") + fake_a2a = types.ModuleType("sircl_ep_all2all") + fake_a2a.install_sircl_ep_all2all = lambda: called.append("a2a") + monkeypatch.setitem(sys.modules, "sircl_ep_b12x", fake_b12x) + monkeypatch.setitem(sys.modules, "sircl_ep_all2all", fake_a2a) + + monkeypatch.delenv("SIRCL_B12X_EP_MOE", raising=False) + monkeypatch.delenv("SIRCL_EP_ALL2ALL", raising=False) + plugin.register() + assert called == [] + + monkeypatch.setenv("SIRCL_B12X_EP_MOE", "1") + plugin.register() + assert called == ["b12x"] + + monkeypatch.setenv("SIRCL_EP_ALL2ALL", "on") + plugin.register() + assert called == ["b12x", "b12x", "a2a"] + + +def test_sircl_ep_b12x_parallel_config_matrix(): + mod_path = Path(__file__).with_name("sircl_ep_b12x.py") + spec_b12x = importlib.util.spec_from_file_location("sircl_ep_b12x_test", mod_path) + try: + mod = importlib.util.module_from_spec(spec_b12x) + spec_b12x.loader.exec_module(mod) + except ImportError: + pytest.skip("torch not installed in local test env") + + def cfg(**kw): + defaults = { + "use_ep": False, + "ep_size": 1, + "use_all2all_kernels": False, + "use_ag_rs_all2all_kernels": False, + "enable_eplb": False, + } + defaults.update(kw) + return types.SimpleNamespace(**defaults) + + assert mod._is_ep_parallel_supported(cfg()) is True + assert mod._is_ep_parallel_supported(cfg(use_ep=True, ep_size=4)) is True + assert mod._is_ep_parallel_supported( + cfg(use_ep=True, ep_size=4, use_all2all_kernels=True, use_ag_rs_all2all_kernels=True) + ) is True + assert mod._is_ep_parallel_supported( + cfg(use_ep=True, ep_size=4, use_all2all_kernels=True, use_ag_rs_all2all_kernels=False) + ) is False + assert mod._is_ep_parallel_supported(cfg(use_ep=True, ep_size=4, enable_eplb=True)) is False + assert mod._is_ep_parallel_supported(cfg(use_ep=True, ep_size=1)) is False + + +def test_sircl_ep_b12x_remap_and_widen(): + import dataclasses + + mod_path = Path(__file__).with_name("sircl_ep_b12x.py") + spec_b12x = importlib.util.spec_from_file_location("sircl_ep_b12x_test_w4a8", mod_path) + try: + import torch + + mod = importlib.util.module_from_spec(spec_b12x) + spec_b12x.loader.exec_module(mod) + except ImportError: + pytest.skip("torch not installed in local test env") + + # Rank 3 of EP4 owns experts 6, 7 out of 8: negative -1 MUST stay -1, not wrap to expert_map[-1] == 1! + emap = torch.tensor([-1, -1, -1, -1, -1, -1, 0, 1], dtype=torch.int32) + ids = torch.tensor([[6, -1, 7, 8], [0, -5, 7, 6]], dtype=torch.int64) + remapped = mod._remap_expert_ids(ids, emap, global_num_experts=8) + assert remapped.dtype == torch.int32 + assert remapped.is_contiguous() + assert remapped.tolist() == [[0, -1, 1, -1], [-1, -1, 1, 0]] + + @dataclasses.dataclass(frozen=True) + class FakeWorkload: + stage: str + token_counts: tuple[int, ...] + fixed_token_counts: tuple[int, ...] + max_tokens: int + + wl = FakeWorkload(stage="weights", token_counts=(5, 6, 96, 8192), fixed_token_counts=(5, 6, 96), max_tokens=8192) + widened = mod._widen_workload_for_ep(wl, ep_mult=4, cap=32768) + assert widened.max_tokens == 32768 + assert widened.fixed_token_counts == (5, 6, 20, 24, 96, 384) + assert set(widened.fixed_token_counts) <= set(widened.token_counts) + assert widened.token_counts[-1] == 32768 + assert mod._widen_workload_for_ep(wl, ep_mult=1) == wl + + +def test_sircl_ep_b12x_resize_dp_workspace(): + mod_path = Path(__file__).with_name("sircl_ep_b12x.py") + spec_b12x = importlib.util.spec_from_file_location("sircl_ep_b12x_test_ws", mod_path) + try: + import torch + + mod = importlib.util.module_from_spec(spec_b12x) + spec_b12x.loader.exec_module(mod) + except ImportError: + pytest.skip("torch not installed in local test env") + + class FakeExperts: + def __init__(self, ws2_len_fn): + self._ws2_len_fn = ws2_len_fn + self.output_dtype = torch.bfloat16 + + def workspace_dtype(self, in_dtype): + return in_dtype + + def workspace_shapes(self, m, n, k, topk, ge, le, meta, act): + return (0,), (self._ws2_len_fn(m),), (m, k) + + # W4A8 case: workspace2 is already pre-sized for max_tokens (independent of M). + # Must reuse ws13 and ws2 in place and only allocate a disjoint fused_out. + ws13 = torch.empty((0,), dtype=torch.bfloat16) + ws2 = torch.empty((1024,), dtype=torch.bfloat16) + out_small = torch.empty((16, 64), dtype=torch.bfloat16) + new_ws13, new_ws2, new_out = mod._resize_dp_workspace( + FakeExperts(lambda _m: 1024), + (ws13, ws2, out_small), + in_dtype=torch.bfloat16, + device=torch.device("cpu"), + m_full=64, + n_dim=128, + k_dim=64, + top_k=6, + global_num_experts=384, + local_num_experts=96, + expert_tokens_meta=None, + activation="silu", + ) + assert new_ws13 is ws13 + assert new_ws2 is ws2 + assert new_out.shape == (64, 64) + assert new_out.dtype == torch.bfloat16 + assert new_out.data_ptr() != out_small.data_ptr() + + # W4A16 case: workspace2 grows with M. Must allocate fresh ws2 + fused_out. + new_ws13_b, new_ws2_b, new_out_b = mod._resize_dp_workspace( + FakeExperts(lambda m: m * 32), + (ws13, ws2, out_small), + in_dtype=torch.bfloat16, + device=torch.device("cpu"), + m_full=64, + n_dim=128, + k_dim=64, + top_k=6, + global_num_experts=384, + local_num_experts=96, + expert_tokens_meta=None, + activation="silu", + ) + assert new_ws13_b is ws13 + assert new_ws2_b is not ws2 + assert new_ws2_b.shape == (2048,) + assert new_out_b.shape == (64, 64) + + +def test_sircl_ep_b12x_dp_sync_num_reqs(monkeypatch): + torch = pytest.importorskip("torch") + import dataclasses + import enum + import types + + mod_path = Path(__file__).with_name("sircl_ep_b12x.py") + spec_b12x = importlib.util.spec_from_file_location("sircl_ep_b12x_test_dp_sync", mod_path) + mod = importlib.util.module_from_spec(spec_b12x) + spec_b12x.loader.exec_module(mod) + + class FakeCGMode(enum.IntEnum): + NONE = 0 + PIECEWISE = 1 + FULL = 2 + + @dataclasses.dataclass(frozen=True) + class FakeDesc: + cg_mode: FakeCGMode + num_tokens: int + num_reqs: int | None + + @dataclasses.dataclass(frozen=True) + class FakeDPSync: + num_reqs: int + + class FakeDist: + def all_reduce(self, tensor, group=None): + # Simulate rank 0 having num_reqs=2 and rank 3 having num_reqs=1. + tensor[5, 0] = 2 + tensor[5, 1] = 1 + tensor[5, 2] = 1 + tensor[5, 3] = 1 + + fake_comp = types.ModuleType("vllm.config.compilation") + fake_comp.CUDAGraphMode = FakeCGMode + fake_dp = types.ModuleType("vllm.v1.worker.gpu.dp_utils") + fake_dp.dist = FakeDist() + + def orig_sync(cm, desired_desc, num_tokens, num_reqs, uniform_tok, dp_size, dp_rank): + tensor = torch.zeros(6, dp_size, dtype=torch.int32) + tensor[5, dp_rank] = num_reqs + fake_dp.dist.all_reduce(tensor) + desc = cm.dispatch(num_reqs, 6, None) + return desc, FakeDPSync( + num_reqs=desc.num_reqs if desc.cg_mode == FakeCGMode.FULL else int(tensor[5].max()) + ) + + def orig_dispatch(cm, num_reqs, num_tokens, uniform_tok, dp_size, dp_rank, dp_sync=None): + desc = cm.dispatch(num_reqs, num_tokens, uniform_tok) + return desc, dp_sync + + fake_dp.sync_cudagraph_and_dp_padding = orig_sync + fake_dp.dispatch_cg_and_sync_dp = orig_dispatch + + for name, m in ( + ("vllm", types.ModuleType("vllm")), + ("vllm.config", types.ModuleType("vllm.config")), + ("vllm.config.compilation", fake_comp), + ("vllm.v1", types.ModuleType("vllm.v1")), + ("vllm.v1.worker", types.ModuleType("vllm.v1.worker")), + ("vllm.v1.worker.gpu", types.ModuleType("vllm.v1.worker.gpu")), + ("vllm.v1.worker.gpu.dp_utils", fake_dp), + ): + monkeypatch.setitem(sys.modules, name, m) + sys.modules["vllm.v1.worker.gpu"].dp_utils = fake_dp + + mod._patch_dp_sync_cudagraph_num_reqs() + + seen_full = [] + + class FakeFullManager: + def dispatch(self, num_reqs, num_tokens, uniform_tok): + seen_full.append((num_reqs, num_tokens)) + return FakeDesc(FakeCGMode.FULL, num_tokens, num_reqs) + + # Rank 3 has local num_reqs=1 while rank 0 has num_reqs=2; FULL graph must agree on 2. + desc_r3, sync_r3 = fake_dp.sync_cudagraph_and_dp_padding( + FakeFullManager(), FakeDesc(FakeCGMode.FULL, 6, 1), 6, 1, None, 4, 3 + ) + assert desc_r3.num_reqs == 2 + assert sync_r3.num_reqs == 2 + assert seen_full == [(2, 6)] + + # DSpark reuse path with dp_sync.num_reqs=2 must also dispatch with num_reqs=2 on rank 3. + seen_full.clear() + dspark_desc, _ = fake_dp.dispatch_cg_and_sync_dp( + FakeFullManager(), 1, 10, 5, 4, 3, dp_sync=FakeDPSync(num_reqs=2) + ) + assert dspark_desc.num_reqs == 2 + assert seen_full == [(2, 10)] + + # Eager (NONE) fallback must preserve local num_reqs=1 on the returned descriptor. + class FakeNoneManager: + def dispatch(self, num_reqs, num_tokens, uniform_tok): + return FakeDesc(FakeCGMode.NONE, num_tokens, num_reqs) + + desc_none, sync_none = fake_dp.sync_cudagraph_and_dp_padding( + FakeNoneManager(), FakeDesc(FakeCGMode.FULL, 6, 1), 6, 1, None, 4, 3 + ) + assert desc_none.num_reqs == 1 + assert sync_none.num_reqs == 2 + + +def test_sircl_ep_b12x_dp_speculator_propose_sync(monkeypatch): + torch = pytest.importorskip("torch") + import types + from typing import NamedTuple + + mod_path = Path(__file__).with_name("sircl_ep_b12x.py") + spec_b12x = importlib.util.spec_from_file_location("sircl_ep_b12x_test_spec_sync", mod_path) + mod = importlib.util.module_from_spec(spec_b12x) + spec_b12x.loader.exec_module(mod) + + class FakeExecState(NamedTuple): + num_spec_tokens_to_schedule: int + boundary_logits_only: bool = False + + propose_calls = [] + adaptive_calls = [] + + class FakeSpec: + def propose(self, dummy_run=False): + propose_calls.append(dummy_run) + return torch.ones((2, 5), dtype=torch.int32) + + class FakeAdaptive: + def record_confidences(self): + adaptive_calls.append(True) + + class FakeRunner: + def __init__(self, dp_size): + self.dp_size = dp_size + self.speculator = FakeSpec() + self.adaptive_verification = FakeAdaptive() + self.execute_model_state = None + + def sample_tokens(self, grammar_output): + st = self.execute_model_state + self.execute_model_state = None + if st.num_spec_tokens_to_schedule > 0: + draft = self.speculator.propose() + if self.adaptive_verification is not None: + self.adaptive_verification.record_confidences() + return draft + return torch.empty((2, 0), dtype=torch.int32) + + fake_mr = types.ModuleType("vllm.v1.worker.gpu.model_runner") + fake_mr.GPUModelRunner = FakeRunner + monkeypatch.setitem(sys.modules, "vllm.v1.worker.gpu.model_runner", fake_mr) + + mod._patch_dp_speculator_propose_sync() + + # DP=4, num_spec_tokens_to_schedule=0: must run propose(dummy_run=True), return 0 draft tokens, + # skip adaptive_verification, and restore speculator.propose + adaptive_verification afterwards. + r_dp4 = FakeRunner(dp_size=4) + r_dp4.execute_model_state = FakeExecState(num_spec_tokens_to_schedule=0) + out = r_dp4.sample_tokens(None) + assert out.shape == (2, 0) + assert propose_calls == [True] + assert adaptive_calls == [] + assert r_dp4.adaptive_verification is not None + + # Subsequent normal decode step (num_spec_tokens_to_schedule=5) runs normal propose + adaptive. + propose_calls.clear() + r_dp4.execute_model_state = FakeExecState(num_spec_tokens_to_schedule=5) + out2 = r_dp4.sample_tokens(None) + assert out2.shape == (2, 5) + assert propose_calls == [False] + assert adaptive_calls == [True] + + # DP=1, num_spec_tokens_to_schedule=0: must NOT force propose. + propose_calls.clear() + r_dp1 = FakeRunner(dp_size=1) + r_dp1.execute_model_state = FakeExecState(num_spec_tokens_to_schedule=0) + out3 = r_dp1.sample_tokens(None) + assert out3.shape == (2, 0) + assert propose_calls == [] + + +def test_sircl_ep_b12x_router_skip_padding(monkeypatch): + torch = pytest.importorskip("torch") + import types + + mod_path = Path(__file__).with_name("sircl_ep_b12x.py") + spec_b12x = importlib.util.spec_from_file_location("sircl_ep_b12x_test_pad", mod_path) + mod = importlib.util.module_from_spec(spec_b12x) + spec_b12x.loader.exec_module(mod) + + seen_kwargs = [] + pad_tensor = torch.tensor([False, False, True, True]) + + def fake_dsv4_topk(gating_output, *args, **kwargs): + seen_kwargs.append(kwargs.copy()) + return gating_output + + fake_router = types.ModuleType( + "vllm.model_executor.layers.fused_moe.router.fused_topk_bias_router" + ) + fake_router.dsv4_topk = fake_dsv4_topk + fake_router._get_padding_mask = lambda n: pad_tensor[:n] + + for name, m in ( + ("vllm", types.ModuleType("vllm")), + ("vllm.model_executor", types.ModuleType("vllm.model_executor")), + ("vllm.model_executor.layers", types.ModuleType("vllm.model_executor.layers")), + ( + "vllm.model_executor.layers.fused_moe", + types.ModuleType("vllm.model_executor.layers.fused_moe"), + ), + ( + "vllm.model_executor.layers.fused_moe.router", + types.ModuleType("vllm.model_executor.layers.fused_moe.router"), + ), + ( + "vllm.model_executor.layers.fused_moe.router.fused_topk_bias_router", + fake_router, + ), + ): + monkeypatch.setitem(sys.modules, name, m) + sys.modules["vllm.model_executor.layers.fused_moe.router"].fused_topk_bias_router = ( + fake_router + ) + + monkeypatch.setenv("SIRCL_EP_ROUTER_SKIP_PADDING", "1") + mod._patch_router_skip_padding() + + x = torch.zeros((4, 8)) + fake_router.dsv4_topk(x) + assert len(seen_kwargs) == 1 + assert torch.equal(seen_kwargs[0]["is_padding"], pad_tensor) + + # Explicit caller is_padding must be preserved. + custom = torch.tensor([True, False, False, False]) + fake_router.dsv4_topk(x, is_padding=custom) + assert torch.equal(seen_kwargs[1]["is_padding"], custom) + + +def test_sircl_ep_b12x_force_grouped_routing(monkeypatch): + pytest.importorskip("torch") + import dataclasses + import types + + mod_path = Path(__file__).with_name("sircl_ep_b12x.py") + spec_b12x = importlib.util.spec_from_file_location("sircl_ep_b12x_test_grp", mod_path) + mod = importlib.util.module_from_spec(spec_b12x) + spec_b12x.loader.exec_module(mod) + + @dataclasses.dataclass(frozen=True) + class FakeConfig: + backend: str + dynamic_route_mode: str | None = None + + @dataclasses.dataclass(frozen=True) + class FakeSelection: + config: FakeConfig + + @dataclasses.dataclass(frozen=True) + class FakePlan: + _compile_jobs: object + _memory_requirements: object + _materialize: object + + @dataclasses.dataclass(frozen=True) + class FakeCompositePlan: + variants: dict + + seen: dict[str, list[FakeConfig]] = {"compile": [], "memory": [], "materialize": []} + + def make_plan(): + leaf = FakePlan( + _compile_jobs=lambda cfg, dev: seen["compile"].append(cfg) or cfg.dynamic_route_mode, + _memory_requirements=lambda cfg, dev: seen["memory"].append(cfg) or cfg.dynamic_route_mode, + _materialize=lambda sel, dev: seen["materialize"].append(sel.config) or sel.config.dynamic_route_mode, + ) + return FakeCompositePlan(variants={5: leaf}) + + fake_impl = types.ModuleType("b12x.moe.fused_moe._impl") + fake_impl._DIRECT_ROUTING_MAX_ROUTED_ROWS = 32 + def orig_sel(*, route_mode, **_kw): + return route_mode == "direct" + + fake_impl._dynamic_direct_routing_selected = orig_sel + fake_impl._heuristic_dynamic_route_mode = lambda *_a, **_kw: "direct" + + fake_prep = types.ModuleType("b12x.moe.fused_moe._preparation") + fake_prep.plan = make_plan + + fake_fm = types.ModuleType("b12x.moe.fused_moe") + fake_fm._impl = fake_impl + fake_fm._preparation = fake_prep + fake_fm._canonical_plan_execution = make_plan + fake_fm.plan_execution = lambda **kw: fake_fm._canonical_plan_execution(**kw) + + for name, m in ( + ("b12x", types.ModuleType("b12x")), + ("b12x.moe", types.ModuleType("b12x.moe")), + ("b12x.moe.fused_moe", fake_fm), + ("b12x.moe.fused_moe._impl", fake_impl), + ("b12x.moe.fused_moe._preparation", fake_prep), + ): + monkeypatch.setitem(sys.modules, name, m) + + monkeypatch.setenv("SIRCL_EP_FORCE_GROUPED_ROUTING", "0") + mod._patch_ep_grouped_routing() + assert fake_impl._dynamic_direct_routing_selected is orig_sel + assert fake_impl._heuristic_dynamic_route_mode() == "direct" + unpatched_leaf = fake_fm.plan_execution().variants[5] + assert unpatched_leaf._compile_jobs(FakeConfig("dynamic", "direct"), None) == "direct" + + seen["compile"].clear() + monkeypatch.setenv("SIRCL_EP_FORCE_GROUPED_ROUTING", "1") + mod._patch_ep_grouped_routing() + # _dynamic_direct_routing_selected stays unpatched so parent planning and + # unpatched b12x compilation subprocesses agree on program keys. + assert fake_impl._dynamic_direct_routing_selected is orig_sel + assert fake_impl._DIRECT_ROUTING_MAX_ROUTED_ROWS == 32 + assert fake_impl._heuristic_dynamic_route_mode() == "grouped" + + leaf = fake_fm.plan_execution().variants[5] + direct_cfg = FakeConfig("dynamic", "direct") + assert leaf._compile_jobs(direct_cfg, None) == "grouped" + assert leaf._memory_requirements(direct_cfg, None) == "grouped" + assert leaf._materialize(FakeSelection(direct_cfg), None) == "grouped" + assert [c.dynamic_route_mode for c in seen["compile"]] == ["grouped"] + assert [c.dynamic_route_mode for c in seen["memory"]] == ["grouped"] + assert [c.dynamic_route_mode for c in seen["materialize"]] == ["grouped"] + + # Non-dynamic configs (e.g. w4a16) pass through untouched. + a16_cfg = FakeConfig("w4a16", None) + assert leaf._compile_jobs(a16_cfg, None) is None + + diff --git a/performance/records/deepseek-v41-flash/row-owned-tp4-ep4-libsircl-20261121.md b/performance/records/deepseek-v41-flash/row-owned-tp4-ep4-libsircl-20261121.md new file mode 100644 index 00000000..8229a634 --- /dev/null +++ b/performance/records/deepseek-v41-flash/row-owned-tp4-ep4-libsircl-20261121.md @@ -0,0 +1,365 @@ +# DeepSeek V4.1 expert parallelism beside row-owned prefill on a four-Spark libsircl ring + +Status: **research-only**. DeepSeek-V4.1-Flash-1017 ran with its experts +split across four Sparks (TP4+EP4) and with the whole expert set on every +Spark (TP4), on the same libsircl ring, image and checkpoint. Expert +parallelism raised the KV pool per Spark by 18.6%, lowered decode at every +concurrency that campaign measured, and raised 64K cold prefill by 5.8%. + +A libsircl link geometry of a 1 MiB slot and 1 MiB pieces, with a 64 KiB +one-shot ceiling, then raised the TP4+EP4 deployment's cold-prefill medians by +5.6%, 9.7% and 11.5% at 16,384, 65,536 and 131,072 tokens and left its decode at +parity. A follow-up Leg-2 decode optimization pass (`R1-leg2`) raised the +one-shot ceiling to 256 KiB, set a 64 KiB forwarding chunk, pinned libsircl's +progress thread to GB10 P-core CPU 9, enabled W4A8 shared input quantization +(`B12X_DYNAMIC_W4A8_SHARE_INPUT=1`), forwarded `is_padding` through text-only +`dsv4_topk` (`VLLM_MOE_SKIP_PADDING=1`), replaced eager `expert_map` indexing +with a fused Triton kernel, forced grouped EP MoE routing on small batches, and +set `OMP_NUM_THREADS=4`. On a 15-cell coding matrix (16K/64K/128K × C=1..16 plus +5×2000-token Coding Peak), `R1-leg2` raised Coding Peak by +9.0% median (76.0 → +82.8 tok/s, max 84.2 → 91.6), C=2 by +7.9% to +11.6%, and C=4 by +9.3% to +11.9% +(+13.8% to +15.2% steps/s) while keeping prefill at 6,408–6,810 tok/s and 18.5 +GiB of KV cache (7,093,220 tokens) at 256K context; that balanced configuration +is what `sparkring install --expert-parallel --row-owned-prefill` now renders. A +16,384-token prefill batch in place of the profile's 8,192 raised prefill +further and cost 10 to 17% of decode at one, four and sixteen requests, so it is +not rendered. + +The image's B12X weight loader reads an expert-parallel rank's shard of this +checkpoint correctly, cuts weight load from 116.36 s to 13.88 s and total +API-ready startup from 320 s to 239 s, and matches prefill throughput (6,418.0 +and 6,284.5 tok/s warm at 16K and 64K), at the cost of 2.15 GiB of KV cache +(15.62 against 17.77 GiB) and non-bit-identical greedy output; an +expert-parallel install therefore keeps vLLM's loader by default +(`EXPERT_LOADER_EP = False`). + +A separate data-parallel deployment (DP4+EP4 over SIRCL-EP's own all-to-all) +served about a third of the tensor-parallel prompt rate, and with DSpark5 and +the rewritten zero-allocation dynamic all-to-all reached 436.13 tok/s at 32 +concurrent requests (up from 410.35 tok/s). A fixed-stride static all-to-all +(`SIRCL_EP_STATIC_A2A=1`, cap 96) captures cleanly into CUDA graphs (3,816 +captured libsircl calls across 42 FULL graphs) and serves cleanly across all +concurrencies after fixing cross-rank capacity agreement, but its 96-row +padding lowers `cc=1` decode from 33.74 to 19.65 tok/s. + +## Conditions + +- Four DGX Sparks that SparkRing records as ring 4-7, running in rank order + 8, 7, 5 and 3, in one libsircl ring. Chain 0-3 was not touched. +- Installer image `dev-20261013-dcp2prefill-status038-sircl-tp6`, + `sha256:3cc9a81fd344fe52fe9cc261b46dc051e3c3f494e51b8142846a5f854835c502`; + checkpoint `deepseek-v41-flash-tp4` variant `1017`, + `deepseek-ai/DeepSeek-V4.1-Flash-1017@1bae0e1088993b9b82de08f59de5be5a34e42170`; + libsircl `0.6.0`, build `8005169b…`. +- The pinned profile's settings, which R0 and R1 ran: TP4, DP1, PP1, DCP1, a + 262,144-token context limit, 16 sequences (`--max-num-seqs`), 8,192-token + prefill chunks, W4A8 MXFP4 experts (`--moe-backend b12x`, + `--attention-backend B12X`), disk Engram. The D2 deployments' settings + beyond their parallel layout and SIRCL-EP's all-to-all are not recorded + here. +- Each rank reaches every peer over `rocep1s0f0` or `rocep1s0f1`, two 200 Gb/s + ports, 50 GB/s each. +- vLLM's PyNccl carries the collectives on libsircl. At the tensor width, + expert parallelism runs no all-to-all kernels: every rank keeps the batch's + tokens, gathers the rows its experts take and reduce-scatters the result, so + the grouped collectives are libsircl's all-gather and reduce-scatter + (`--all2all-backend allgather_reducescatter`). The live log names vLLM's + `MoEPrepareAndFinalizeNoDPEPModular`, which issues one all-gather and one + reduce-scatter per mixture-of-experts layer through `ncclAllGather` and + `ncclReduceScatter`. +- The decode and prefill rates follow the definitions of the earlier records + of this profile ([row-owned prefill on a SIRCL path](row-owned-sircl-path4-20261119.md)): + decode counts output tokens after the first token, and cold prefill counts + prompt tokens of a request that reports no cached prefix. +- Two readings exist of the TP4+EP4 deployment, and the tables keep them + apart. The campaign tables below hold one rate per measurement, from the + harness that measured R0 and the DP4 deployments too. The transport sweep + holds a median of seven consecutive cold requests per size and one run per + configuration, with 128 output tokens per decode request and no sample + count for decode. + +## Configurations + +| ID | Parallel layout | Rank settings | Speculation | +|---|---|---|---| +| R0 | TP4 | `ds41_row_shard` row-owned prefill | adaptive DSpark5 | +| R1 | TP4+EP4 | `ds41_row_shard` row-owned prefill, `SIRCL_B12X_EP_MOE=1`, `--load-format auto` | adaptive DSpark5 | +| R1-link | TP4+EP4 | R1 with `SIRCL_ONESHOT_MAX_BYTES=65536` and a 1 MiB link slot and 1 MiB gather, reduce and scatter pieces | adaptive DSpark5 | +| R1-leg2 | TP4+EP4 | R1-link with 256 KiB one-shot, 64 KiB forward chunk, `SIRCL_PROGRESS_CPU=9`, `B12X_DYNAMIC_W4A8_SHARE_INPUT=1`, `VLLM_MOE_SKIP_PADDING=1`, `OMP_NUM_THREADS=4`, plus plugin Triton ID remap, router padding skip and grouped EP routing | adaptive DSpark5 | +| R1-link-batch | TP4+EP4 | R1-link with `--max-num-batched-tokens 16384` | adaptive DSpark5 | +| D2 | DP4+EP4 | SIRCL-EP all-to-all (`SIRCL_EP_ALL2ALL=1`) | none | +| D2 + DSpark5 | DP4+EP4 | SIRCL-EP all-to-all | adaptive DSpark5 | + +`sparkring install` renders the rank settings of R0 and R1, and now renders +R1-leg2's balanced link geometry and decode tuning with R1 +(`serving.EXPERT_PARALLEL_LINK` in `runtime/common/serving.py`); the campaign's +R1 rows were measured before that tuning, so they are R1 without it. The +DP4 deployments have no installer option, so no `sparkring install` request +renders them. + +## Decode + +Output tokens per second at a given number of concurrent requests (`cc`): + +| Configuration | cc=1 | cc=4 | cc=8 | cc=16 | cc=32 | +|---|---:|---:|---:|---:|---:| +| R0 | 69.80 | 163.79 | 258.49 | 337.70 | not measured | +| R1 | 56.47 | 158.04 | 221.70 | 331.11 | not measured | +| D2 | 12.32 | 54.58 | 98.21 | 156.00 | 249.91 | +| D2 + DSpark5 | 34.55 | 64.51 | 110.72 | 258.11 | 410.35 | + +R1 is lower than R0 at every concurrency this campaign measured, by 19.1% at +one request and by 14.2% at eight. The gap narrows to 1.9% at sixteen, which +suggests the expert parallelism's per-step collectives are amortized by the +batch; no counter in these runs confirms it. In the DP4 deployments, DSpark5 +raises decode by 2.8x at one request and by 1.6x at 32, and D2 + DSpark5's +410.35 tok/s at 32 requests is the highest decode rate of the four +configurations. + +The sweep measured the same deployment at 86.55, 185.11, 255.41 and 418.76 +tok/s, up to 53% above this campaign's R1 rows (see Transport tuning), so the +two harnesses' rates do not compare; R1's ordering against R0 holds only +inside this table. + +## Cold prefill + +Prompt tokens per second of a cold request: + +| Configuration | 16,384 tokens | 65,536 tokens | 4 x 16,384 tokens | +|---|---:|---:|---:| +| R0 | 5,471.9 | 5,794.3 | not measured | +| R1 | 4,634.6 | 6,132.9 | not measured | +| D2 | 1,813.2 | 1,891.5 | 3,695.3 | +| D2 + DSpark5 | 1,953.5 | 2,086.5 | 4,005.2 | + +R1's 65,536-token rate is 5.8% above R0's. Its 16,384-token figure is a +first-hit cold request on a freshly started deployment, which R0's samples are +not, so the two 16K figures do not measure the same steady state; the 64K +figures do. The DP4 deployments serve less than half of R0's and R1's prompt +rate at both lengths, and their four concurrent 16K requests aggregate +3,695.3 and 4,005.2 tok/s. Both R1 figures lie inside the spread of the +sweep's seven samples at their length, whose medians supersede them +(Transport tuning). + +## KV cache + +| Configuration | KV cache per Spark (GiB) | Tokens | +|---|---:|---:| +| R0 | 15.76 | not recorded | +| R1 | 18.69 (+18.6%) | not recorded | +| R1, 262,144-token limit | 17.72 | 7,286,986 | +| D2 | 14.39 | not recorded | +| D2 + DSpark5 | 12.19 | not recorded | + +R1's 18.69 GiB is the pool at 131,072 tokens of context, the reading its 18.6% +compares; a start at the full 262,144-token limit reported 17.72 GiB, or +7,286,986 tokens. At the same 131,072-token reading, expert parallelism costs +2.93 GiB per Spark more than R0; the recorded runs do not separate the expert +slices from the row-owned prefill's buffers. D2 + DSpark5's pool is 2.20 GiB +smaller than D2's. The sweep's three rungs reported 17.72, 17.77 and 17.52 GiB +at the same 262,144-token limit (Transport tuning). + +## Transport tuning + +Three rungs of the same deployment, each one run of seven consecutive cold +requests per size: + +| Rung | 16,384-token prefill | 65,536-token prefill | 131,072-token prefill | +|---|---:|---:|---:| +| R1 | 5,980.8 (3,462.1–6,204.3) | 5,579.4 (4,582.9–6,271.5) | 5,184.0 (4,383.1–5,499.4) | +| R1-link | 6,317.7 (5,163–6,422) | 6,118.7 (5,892–6,143) | 5,782.8 (5,658–6,009) | +| R1-link-batch | 6,369.3 (6,341.1–6,379.0) | 6,219.1 (6,138.2–6,235.3) | 6,078.8 (6,035.4–6,097.7) | + +| Rung | decode cc=1 | cc=4 | cc=8 | cc=16 | KV cache (GiB) | API ready | +|---|---:|---:|---:|---:|---:|---:| +| R1 | 86.55 | 185.11 | 255.41 | 418.76 | 17.72 | 5 min 42 s | +| R1-link | 87.95 | 192.16 | 279.43 | 404.22 | 17.77 | 5 min 20 s | +| R1-link-batch | 77.07 | 167.09 | 293.16 | 347.77 | 17.52 | 5 min 35 s | + +The link geometry carries most of the prefill gain: 5.6%, 9.7% and 11.5% at +the three lengths. The 16,384-token batch adds 0.8, 1.6 and 5.1 points on top +of it, reaches 6.4 ktok/s at 16,384 tokens, and misses it at 65,536 (6,219.1) +and 131,072 (6,078.8). It is also what costs single-request decode: R1-link +holds 87.95 tok/s at one request where R1-link-batch falls to 77.07. + +R1's samples are bimodal at 64K, alternating between about 6.2 and about +5.2–5.6 ktok/s, and its worst three (3,462.1, 4,582.9, 4,383.1) are stalls +rather than throughput: one 65,536-token prefill ran 165 s and recovered on its +own inside libsircl's 600 s startup completion limit. R1-link's samples are +tight, so most of the median gain is the stalls disappearing, not a higher +ceiling. Where the ceiling is measurable it did move — at 131,072 tokens R1's +best sample (5,499.4) is below every R1-link-batch sample (6,035.4–6,097.7) — +while at 65,536 tokens the two rungs' peaks agree (6,271.5 against 6,235.3). + +The link is not what limits these rates. The libsircl receipt covering roughly +twelve minutes of this deployment — which also served 21 measured cold prefills +and the decode runs — reports 127,109 native operations and 2,988.5 GB, of +which 31,368 are `ring_gather` and the rest ring reduce and ring scatter, with +`healthy: true`, `error: null` and `transport: verbs`. Delivering 2,988.5 GB at +the ports' line rate costs 60 s, so the wire carried about 4 GB/s per rank, +under a tenth of what the two ports offer; the remaining wall time is the FP4 +expert GEMMs, attention over 8,192 rows and the tensor-parallel row-shard +collectives. Transport settings can therefore move this deployment's prefill +by a few percent, not past 6,400 tok/s at every length. + +Each configuration is one run, so the percentages carry no run-to-run error +estimate; the within-run spread is the only one available, and it is why the +0.8-point difference between R1-link and R1-link-batch at 16,384 tokens is not +separable from noise. The three rungs' KV pools span 0.25 GiB (17.77, 17.72 +and 17.52 GiB), which is the size of the link slots the transport reserves, not +a difference in what the engine holds. + +## Leg-2 decode optimizations (`R1-leg2`) + +A follow-up pass on Ring 4-7 kept `R1-link`'s 1 MiB link slot/pieces and 8,192-token +prefill batch while eliminating decode-path overheads: + +- `SIRCL_ONESHOT_MAX_BYTES=262144` (256 KiB one-shot ceiling, eliminating ~290K twoshot phases caused by 64 KiB) +- `SIRCL_FORWARD_CHUNK_BYTES=65536` and `SIRCL_PROGRESS_CPU=9` (GB10 Cortex-X925 P-core) +- `B12X_DYNAMIC_W4A8_SHARE_INPUT=1`, `VLLM_MOE_SKIP_PADDING=1`, and `OMP_NUM_THREADS=4` +- Plugin defaults in `integrations/vllm/libsircl/sircl_ep_b12x.py`: fused Triton `_remap_expert_ids_kernel`, text-only `dsv4_topk` `is_padding` forwarding, and EP grouped MoE routing override (`-1.71 ms/step` at `M=5` in isolated Host 8 GB10 CUDA-graph benchmarks, `18.58 -> 16.87 ms/40L`) + +Measured on the 15-cell coding matrix (16K, 64K and 128K contexts × `C=1..16`, +20 s windows, plus 5×2,000-token Coding Peak, 0 errors, 0 CJK runs, 18.5 GiB / +7,093,220-token KV pool at 256K context, rank-0 `libsircl` receipt 100% healthy +across 689 GB RDMA / 10.3M writes): + +| Metric / Cell | `R1-link` | `R1-leg2` | Delta | +|---|---:|---:|---:| +| Coding Peak median / max (5×2000 tok) | 76.0 / 84.2 tok/s | 82.8 / 91.6 tok/s | +9.0% / +8.8% | +| Prefill 16K / 64K / 128K | 4,945 / 6,186 / 6,595 tok/s | 6,810 / 6,722 / 6,408 tok/s | +37.7% / +8.7% / -2.8% | +| Decode `C=1` (16K / 64K / 128K) | 50.6 / 51.1 / 51.8 tok/s | 51.6 / 54.9 / 46.6 tok/s | +1.9% / +7.4% / -10.1% | +| Decode `C=2` (16K / 64K / 128K) | 75.9 / 76.2 / 73.5 tok/s | 84.6 / 82.2 / 80.0 tok/s | +11.6% / +7.9% / +8.8% | +| Decode `C=4` (16K / 64K / 128K) | 112.7 / 116.2 / 108.7 tok/s | 126.1 / 127.0 / 120.8 tok/s | +11.9% / +9.3% / +11.1% | +| Decode `C=4` step rate (16K / 64K / 128K) | 46.9 / 47.0 / 44.5 step/s | 53.5 / 53.5 / 51.3 step/s | +14.0% / +13.8% / +15.2% | +| Decode `C=8` (16K / 64K / 128K) | 158.4 / 162.6 / 149.2 tok/s | 173.4 / 159.0 / 159.3 tok/s | +9.4% / -2.2% / +6.8% | +| Decode `C=16` (16K / 64K / 128K) | 255.5 / 243.2 / 235.3 tok/s | 254.6 / 249.1 / 235.6 tok/s | -0.3% / +2.4% / +0.1% | + +`serving.EXPERT_PARALLEL_LINK` now renders this `R1-leg2` balanced configuration +whenever `--expert-parallel` and `--row-owned-prefill` are paired. + +## The B12X weight loader on an expert-parallel rank + +`b12x_loader` reads an expert-parallel rank's shard of this checkpoint +correctly. Its support check (`_has_b12x_loader_support()`) is true in the +container, both of its read paths apply vLLM's +`should_skip_weight(name, local_expert_ids)`, and the checkpoint names its +expert tensors `layers.N.ffn.experts.E.w{1,2,3}.weight`, which that filter +shards. Filtering the checkpoint's 96,085 tensors by each rank's local expert +set gives 61,237 tensors for rank 0 and 60,661, 60,373 and 60,373 for ranks 1 +to 3; the union covers all 96,085, 48,853 dense, shared, embedding and `.scale` +tensors are kept by all four ranks, and no expert weight is kept by two ranks. +That is an expert-parallel shard. + +With `--load-format b12x` and the container's `/cache` mount pointed at the +host's persistent compile cache, `R1-link` reached a serving API end to end: + +| Measurement | default loader (`auto`) | `b12x` loader | Delta | +|---|---:|---:|---:| +| target-model weight load | 116.36 s | 13.88 s | 8.4x faster | +| drafter weight load | 6.12 s | 1.08 s | 5.7x faster | +| `Model loading took` | 76.96 GiB / 153.88 s | 76.96 GiB / 32.07 s | -121.8 s | +| API ready (launch to `/v1/models` 200) | 320 s | 239 s | -81 s | +| `Available KV cache memory` | 17.77 GiB | 15.62 GiB | -2.15 GiB | + +Warm exact-token prefill on the `b12x`-loaded deployment measured 6,418.0 +tok/s median at 16,384 tokens (warm 6,432.7; samples 6,313.6 / 6,422.1 / +6,418.0) and 6,284.5 tok/s median at 65,536 tokens (warm 6,304.1; samples +6,284.5 / 6,289.1 / 6,177.5), matching `R1-link`'s default-loader peaks. +Greedy output is not bit-identical to vLLM's loader (different packed GEMM +reduction order; two of four probe continuations matched token for token, and +first-token log-probabilities differed by `1e-6` to `1e-3`). Because `b12x` +trades 2.15 GiB of KV cache (12% of the pool at 262,144 context) for 81 s of +startup time, `serving.EXPERT_LOADER_EP` stays `False` by default and remains +a single-line opt-in switch. + +## DP4+EP4 static all-to-all and CUDA-graph capture + +The rewritten `SirclEpAll2AllManager` (`integrations/vllm/libsircl/sircl_ep_all2all.py`) +reuses a grow-only per-geometry arena (retaining displaced buffers so captured +CUDA graphs stay valid) and adds an opt-in zero-host-sync static path +(`SIRCL_EP_STATIC_A2A=1`, constant cross-rank capacity +`SIRCL_EP_STATIC_A2A_MAX_TOKENS=96`, decided from shared +`ForwardContext.dp_metadata` CPU counts or capture sizes). Measured on Ring +4-7 with `D2 + DSpark5` (`DP4+EP4`, `max-model-len 131072`, `max-num-seqs 32`, +`B12X_AUTOTUNE=0`): + +| Measurement | Dynamic arena (`STATIC_A2A=0`) | Static fixed-stride (`STATIC_A2A=1`, cap 96) | +|---|---:|---:| +| startup to `/v1/models` | 599 s | 575 s | +| KV cache per Spark | 11.27 GiB | 11.36 GiB | +| decode `cc=1` | 33.74 tok/s | 19.65 tok/s (-42%) | +| decode `cc=4` | 77.13 tok/s | 68.72 tok/s (-11%) | +| decode `cc=8` | 128.67 tok/s | 160.60 tok/s (+25%) | +| decode `cc=16` | 215.93 tok/s | 242.64 tok/s (+12%) | +| decode `cc=32` | 436.13 tok/s | 376.76 tok/s (-14%) | +| prefill 16,384 (median) | 2,124.0 tok/s | 2,093.3 tok/s | +| prefill 65,536 (median) | 2,103.5 tok/s | 2,062.3 tok/s | +| 4 x 16,384 concurrent | 3,910.0 tok/s | 3,301.6 tok/s | +| rank-0 EP dispatches / receipt | 11,249 / healthy | 11,374 / healthy | + +Three findings from the DP4 runs: + +- **DP+EP MoE captures into FULL CUDA graphs with zero refusals:** the + `libsircl` receipt recorded 3,816 captured calls across 42 FULL CUDA graphs + on rank 0 with `SIRCL_EP_STATIC_A2A=1`. +- **Cap 96 penalizes `cc=1` decode:** padding a 6-token step to `world * 96` + (384) rows cuts single-request decode from 33.74 to 19.65 tok/s, while the + dynamic zero-allocation arena (`STATIC_A2A=0`) reached 436.13 tok/s at + `cc=32`. Lowering `SIRCL_EP_STATIC_A2A_MAX_TOKENS` to match the deployment's + actual decode ceiling (`max_num_seqs * (1 + num_speculative_tokens)`) is the + remaining lever for static A2A. +- **Cold `B12X_AUTOTUNE=1` does not converge inside a DP4 start:** tuning + progressed to 827 of 3,272 preparation units in 6.5 minutes before vLLM's + 60-second shared-memory broadcast watchdog closed the DP store + (`DistNetworkError`). Autotune caches must be populated outside a DP4 start + (or with raised store/shm timeouts) before enabling `B12X_AUTOTUNE=1` on D2. + +## What the installer renders + +`sparkring install --expert-parallel` with the pinned image and +`--transport libsircl` names the grouped all-to-all, loads the checkpoint with +vLLM's own loader, leaves the image's B12X weight loader plugin out, and sets +`SIRCL_B12X_EP_MOE=1` on every rank. With `--row-owned-prefill` (R1) it also +stages `integrations/vllm/ds41_row_shard` on `PYTHONPATH` and in +`VLLM_PLUGINS`, sets the `DS41_ROW_SHARD_*` switches, keeps the row-owned +command adjustments (compilation mode 0 with `FULL_DECODE_ONLY`, Engram +`projection_tp` off, adaptive verification on, a 262,144-token limit), and sets +the R1-leg2 link geometry and decode tuning. The offline checks are +`runtime/host/test_install_sircl.py` (the plan, the lock and every rank's +container), `runtime/common/test_libsircl.py` (the switch and the link +geometry survive the transport's replacement of `SIRCL_*` variables, and +libsircl's own checks pass on the command the deployment serves), and +`runtime/common/test_serving.py` (the geometry follows the pairing of the two +switches, which is what it was measured on). + +## Open items + +- The link geometry's effect on expert parallelism without `--row-owned-prefill` + is unmeasured, so `sparkring install` applies `EXPERT_PARALLEL_LINK` only + when both switches are set. +- A lower `SIRCL_EP_STATIC_A2A_MAX_TOKENS` cap and pre-warmed `B12X_AUTOTUNE=1` + cache remain to be benchmarked on D2. + +## Limitations + +- The per-sample records of these runs are not in this repository; the tables + hold the rates the runs reported. +- The campaign tables hold one rate per measurement and the transport sweep + one run of seven samples per configuration, so no percentage has a + run-to-run error estimate. On this ring a single-sample difference below + roughly 20% is not distinguishable from noise. +- The 16,384-token R1 figure is a first-hit cold request, so it is not + comparable with R0's steady-state samples (see Cold prefill). +- The DP4 deployments' expert parallelism runs SIRCL-EP's own all-to-all, a + different mechanism from R1's grouped all-gather and reduce-scatter; their + rates do not transfer to R1 or the reverse. +- The KV cache sizes are the starts' reported pools, which vLLM sizes from the + memory free at start under `--gpu-memory-utilization 0.83`; a different + allocation changes them without changing the configuration. +- The engine ran libsircl's startup wait regime while serving, with libsircl's + 600 s completion limit, and one 65,536-token prefill stalled 165 s before + recovering. `LIBSIRCL_WAIT_REGIME=serving` would bound a stall at 60 s; no + run here did. +- No NCCL receipt check covers these deployments: the libsircl transport does + not judge libsircl's per-communicator receipts. diff --git a/profiles/deepseek-v41-flash-tp4/compose/compose.rank0.yaml b/profiles/deepseek-v41-flash-tp4/compose/compose.rank0.yaml index 5914b3de..9b1130f4 100644 --- a/profiles/deepseek-v41-flash-tp4/compose/compose.rank0.yaml +++ b/profiles/deepseek-v41-flash-tp4/compose/compose.rank0.yaml @@ -149,7 +149,7 @@ services: VLLM_WORKER_MULTIPROC_METHOD: spawn XDG_CACHE_HOME: /cache/deepseek-v41-flash-f625053225d4-dba1be0a40aa labels: - io.sparkring.deployment: 980f76655827e051d74328d2c4927d2f4fa1f4b0beadc0855f7b0bb2df170fad + io.sparkring.deployment: e7dcab3481dd646a1abbaea173f71b2066b9bb388030086979904cd8f413c379 io.sparkring.rank: '0' network_mode: host ipc: host diff --git a/profiles/deepseek-v41-flash-tp4/compose/compose.rank1.yaml b/profiles/deepseek-v41-flash-tp4/compose/compose.rank1.yaml index b4b83926..e7b23145 100644 --- a/profiles/deepseek-v41-flash-tp4/compose/compose.rank1.yaml +++ b/profiles/deepseek-v41-flash-tp4/compose/compose.rank1.yaml @@ -150,7 +150,7 @@ services: VLLM_WORKER_MULTIPROC_METHOD: spawn XDG_CACHE_HOME: /cache/deepseek-v41-flash-f625053225d4-dba1be0a40aa labels: - io.sparkring.deployment: 980f76655827e051d74328d2c4927d2f4fa1f4b0beadc0855f7b0bb2df170fad + io.sparkring.deployment: e7dcab3481dd646a1abbaea173f71b2066b9bb388030086979904cd8f413c379 io.sparkring.rank: '1' network_mode: host ipc: host diff --git a/profiles/deepseek-v41-flash-tp4/compose/compose.rank2.yaml b/profiles/deepseek-v41-flash-tp4/compose/compose.rank2.yaml index 39295ce8..c4acea84 100644 --- a/profiles/deepseek-v41-flash-tp4/compose/compose.rank2.yaml +++ b/profiles/deepseek-v41-flash-tp4/compose/compose.rank2.yaml @@ -150,7 +150,7 @@ services: VLLM_WORKER_MULTIPROC_METHOD: spawn XDG_CACHE_HOME: /cache/deepseek-v41-flash-f625053225d4-dba1be0a40aa labels: - io.sparkring.deployment: 980f76655827e051d74328d2c4927d2f4fa1f4b0beadc0855f7b0bb2df170fad + io.sparkring.deployment: e7dcab3481dd646a1abbaea173f71b2066b9bb388030086979904cd8f413c379 io.sparkring.rank: '2' network_mode: host ipc: host diff --git a/profiles/deepseek-v41-flash-tp4/compose/compose.rank3.yaml b/profiles/deepseek-v41-flash-tp4/compose/compose.rank3.yaml index acc915da..f0e481d6 100644 --- a/profiles/deepseek-v41-flash-tp4/compose/compose.rank3.yaml +++ b/profiles/deepseek-v41-flash-tp4/compose/compose.rank3.yaml @@ -150,7 +150,7 @@ services: VLLM_WORKER_MULTIPROC_METHOD: spawn XDG_CACHE_HOME: /cache/deepseek-v41-flash-f625053225d4-dba1be0a40aa labels: - io.sparkring.deployment: 980f76655827e051d74328d2c4927d2f4fa1f4b0beadc0855f7b0bb2df170fad + io.sparkring.deployment: e7dcab3481dd646a1abbaea173f71b2066b9bb388030086979904cd8f413c379 io.sparkring.rank: '3' network_mode: host ipc: host diff --git a/profiles/deepseek-v41-flash-tp4/compose/selection.json b/profiles/deepseek-v41-flash-tp4/compose/selection.json index 15e98fa1..df6d8cc0 100644 --- a/profiles/deepseek-v41-flash-tp4/compose/selection.json +++ b/profiles/deepseek-v41-flash-tp4/compose/selection.json @@ -3,5 +3,5 @@ "profile": "deepseek-v41-flash-tp4", "checkpoint": "original", "image_lock": "runtime/releases/dev-20261016-sparkcache-4a17f1f5198e-status038/installer-image.json", - "deployment": "980f76655827e051d74328d2c4927d2f4fa1f4b0beadc0855f7b0bb2df170fad" + "deployment": "e7dcab3481dd646a1abbaea173f71b2066b9bb388030086979904cd8f413c379" } diff --git a/profiles/glm53-flash-nvfp4-spark-tp2/compose/compose.rank0.yaml b/profiles/glm53-flash-nvfp4-spark-tp2/compose/compose.rank0.yaml index 706385c1..e51d49a5 100644 --- a/profiles/glm53-flash-nvfp4-spark-tp2/compose/compose.rank0.yaml +++ b/profiles/glm53-flash-nvfp4-spark-tp2/compose/compose.rank0.yaml @@ -181,7 +181,7 @@ services: VLLM_WORKER_MULTIPROC_METHOD: spawn XDG_CACHE_HOME: /cache/glm53-flash-nvfp4-spark-f625053225d4-dec48abd33ef labels: - io.sparkring.deployment: 8b8ccdb3006f0780f1de86849c967136aa3d7cd1892a2e5ecfaee3ff11d867d4 + io.sparkring.deployment: 240aef8f6796c5c86f013a0b84193894f9d55beb3b77501e73d99cd3dc42b1af io.sparkring.rank: '0' network_mode: host ipc: host diff --git a/profiles/glm53-flash-nvfp4-spark-tp2/compose/compose.rank1.yaml b/profiles/glm53-flash-nvfp4-spark-tp2/compose/compose.rank1.yaml index f96e95ca..d5fc105b 100644 --- a/profiles/glm53-flash-nvfp4-spark-tp2/compose/compose.rank1.yaml +++ b/profiles/glm53-flash-nvfp4-spark-tp2/compose/compose.rank1.yaml @@ -180,7 +180,7 @@ services: VLLM_WORKER_MULTIPROC_METHOD: spawn XDG_CACHE_HOME: /cache/glm53-flash-nvfp4-spark-f625053225d4-dec48abd33ef labels: - io.sparkring.deployment: 8b8ccdb3006f0780f1de86849c967136aa3d7cd1892a2e5ecfaee3ff11d867d4 + io.sparkring.deployment: 240aef8f6796c5c86f013a0b84193894f9d55beb3b77501e73d99cd3dc42b1af io.sparkring.rank: '1' network_mode: host ipc: host diff --git a/profiles/glm53-flash-nvfp4-spark-tp2/compose/selection.json b/profiles/glm53-flash-nvfp4-spark-tp2/compose/selection.json index 5b6edb42..2ce70009 100644 --- a/profiles/glm53-flash-nvfp4-spark-tp2/compose/selection.json +++ b/profiles/glm53-flash-nvfp4-spark-tp2/compose/selection.json @@ -3,5 +3,5 @@ "profile": "glm53-flash-nvfp4-spark-tp2", "checkpoint": "csf", "image_lock": "runtime/releases/dev-20261016-sparkcache-4a17f1f5198e-status038/installer-image.json", - "deployment": "8b8ccdb3006f0780f1de86849c967136aa3d7cd1892a2e5ecfaee3ff11d867d4" + "deployment": "240aef8f6796c5c86f013a0b84193894f9d55beb3b77501e73d99cd3dc42b1af" } diff --git a/profiles/glm53-flash-nvfp4-spark-tp4/compose/compose.rank0.yaml b/profiles/glm53-flash-nvfp4-spark-tp4/compose/compose.rank0.yaml index dec0c2c6..f9663893 100644 --- a/profiles/glm53-flash-nvfp4-spark-tp4/compose/compose.rank0.yaml +++ b/profiles/glm53-flash-nvfp4-spark-tp4/compose/compose.rank0.yaml @@ -195,7 +195,7 @@ services: VLLM_WORKER_MULTIPROC_METHOD: spawn XDG_CACHE_HOME: /cache/glm53-flash-nvfp4-spark-f625053225d4-dec48abd33ef labels: - io.sparkring.deployment: 87d768b6f1e284c8045d7e082fb9434c891e2612857c290e247ba4ea5ad36aa0 + io.sparkring.deployment: d15cd274f5067e46b7121b3d9325ea67e02ba9b85db5af6b37c109c72a02793f io.sparkring.rank: '0' network_mode: host ipc: host diff --git a/profiles/glm53-flash-nvfp4-spark-tp4/compose/compose.rank1.yaml b/profiles/glm53-flash-nvfp4-spark-tp4/compose/compose.rank1.yaml index 09985c4d..15f8051a 100644 --- a/profiles/glm53-flash-nvfp4-spark-tp4/compose/compose.rank1.yaml +++ b/profiles/glm53-flash-nvfp4-spark-tp4/compose/compose.rank1.yaml @@ -194,7 +194,7 @@ services: VLLM_WORKER_MULTIPROC_METHOD: spawn XDG_CACHE_HOME: /cache/glm53-flash-nvfp4-spark-f625053225d4-dec48abd33ef labels: - io.sparkring.deployment: 87d768b6f1e284c8045d7e082fb9434c891e2612857c290e247ba4ea5ad36aa0 + io.sparkring.deployment: d15cd274f5067e46b7121b3d9325ea67e02ba9b85db5af6b37c109c72a02793f io.sparkring.rank: '1' network_mode: host ipc: host diff --git a/profiles/glm53-flash-nvfp4-spark-tp4/compose/compose.rank2.yaml b/profiles/glm53-flash-nvfp4-spark-tp4/compose/compose.rank2.yaml index 12a43d4b..9a20b9c8 100644 --- a/profiles/glm53-flash-nvfp4-spark-tp4/compose/compose.rank2.yaml +++ b/profiles/glm53-flash-nvfp4-spark-tp4/compose/compose.rank2.yaml @@ -194,7 +194,7 @@ services: VLLM_WORKER_MULTIPROC_METHOD: spawn XDG_CACHE_HOME: /cache/glm53-flash-nvfp4-spark-f625053225d4-dec48abd33ef labels: - io.sparkring.deployment: 87d768b6f1e284c8045d7e082fb9434c891e2612857c290e247ba4ea5ad36aa0 + io.sparkring.deployment: d15cd274f5067e46b7121b3d9325ea67e02ba9b85db5af6b37c109c72a02793f io.sparkring.rank: '2' network_mode: host ipc: host diff --git a/profiles/glm53-flash-nvfp4-spark-tp4/compose/compose.rank3.yaml b/profiles/glm53-flash-nvfp4-spark-tp4/compose/compose.rank3.yaml index 49ccfd0b..2f0d6849 100644 --- a/profiles/glm53-flash-nvfp4-spark-tp4/compose/compose.rank3.yaml +++ b/profiles/glm53-flash-nvfp4-spark-tp4/compose/compose.rank3.yaml @@ -194,7 +194,7 @@ services: VLLM_WORKER_MULTIPROC_METHOD: spawn XDG_CACHE_HOME: /cache/glm53-flash-nvfp4-spark-f625053225d4-dec48abd33ef labels: - io.sparkring.deployment: 87d768b6f1e284c8045d7e082fb9434c891e2612857c290e247ba4ea5ad36aa0 + io.sparkring.deployment: d15cd274f5067e46b7121b3d9325ea67e02ba9b85db5af6b37c109c72a02793f io.sparkring.rank: '3' network_mode: host ipc: host diff --git a/profiles/glm53-flash-nvfp4-spark-tp4/compose/selection.json b/profiles/glm53-flash-nvfp4-spark-tp4/compose/selection.json index 732bfeee..44a78e6d 100644 --- a/profiles/glm53-flash-nvfp4-spark-tp4/compose/selection.json +++ b/profiles/glm53-flash-nvfp4-spark-tp4/compose/selection.json @@ -3,5 +3,5 @@ "profile": "glm53-flash-nvfp4-spark-tp4", "checkpoint": "csf", "image_lock": "runtime/releases/dev-20261016-sparkcache-4a17f1f5198e-status038/installer-image.json", - "deployment": "87d768b6f1e284c8045d7e082fb9434c891e2612857c290e247ba4ea5ad36aa0" + "deployment": "d15cd274f5067e46b7121b3d9325ea67e02ba9b85db5af6b37c109c72a02793f" } diff --git a/profiles/mimo-v26-flash-mopd-tp2/compose/compose.rank0.yaml b/profiles/mimo-v26-flash-mopd-tp2/compose/compose.rank0.yaml index 076169d8..182de65c 100644 --- a/profiles/mimo-v26-flash-mopd-tp2/compose/compose.rank0.yaml +++ b/profiles/mimo-v26-flash-mopd-tp2/compose/compose.rank0.yaml @@ -149,7 +149,7 @@ services: VLLM_WORKER_MULTIPROC_METHOD: spawn XDG_CACHE_HOME: /cache/mimo-v26-flash-rl-f625053225d4-2479e2d0029e labels: - io.sparkring.deployment: ad63a67b504d3ecfa00cdd0505a532cd58724d510c25c072847ea91427a2e072 + io.sparkring.deployment: e8247dd424caebc4cdb5631c62de72f494f0a042d9d162ab1934bd7d22193e01 io.sparkring.rank: '0' network_mode: host ipc: host diff --git a/profiles/mimo-v26-flash-mopd-tp2/compose/compose.rank1.yaml b/profiles/mimo-v26-flash-mopd-tp2/compose/compose.rank1.yaml index 5c67c620..11490f3e 100644 --- a/profiles/mimo-v26-flash-mopd-tp2/compose/compose.rank1.yaml +++ b/profiles/mimo-v26-flash-mopd-tp2/compose/compose.rank1.yaml @@ -150,7 +150,7 @@ services: VLLM_WORKER_MULTIPROC_METHOD: spawn XDG_CACHE_HOME: /cache/mimo-v26-flash-rl-f625053225d4-2479e2d0029e labels: - io.sparkring.deployment: ad63a67b504d3ecfa00cdd0505a532cd58724d510c25c072847ea91427a2e072 + io.sparkring.deployment: e8247dd424caebc4cdb5631c62de72f494f0a042d9d162ab1934bd7d22193e01 io.sparkring.rank: '1' network_mode: host ipc: host diff --git a/profiles/mimo-v26-flash-mopd-tp2/compose/selection.json b/profiles/mimo-v26-flash-mopd-tp2/compose/selection.json index bedb0f49..b0871778 100644 --- a/profiles/mimo-v26-flash-mopd-tp2/compose/selection.json +++ b/profiles/mimo-v26-flash-mopd-tp2/compose/selection.json @@ -3,5 +3,5 @@ "profile": "mimo-v26-flash-mopd-tp2", "checkpoint": null, "image_lock": "runtime/releases/dev-20261016-sparkcache-4a17f1f5198e-status038/installer-image.json", - "deployment": "ad63a67b504d3ecfa00cdd0505a532cd58724d510c25c072847ea91427a2e072" + "deployment": "e8247dd424caebc4cdb5631c62de72f494f0a042d9d162ab1934bd7d22193e01" } diff --git a/profiles/mimo-v26-flash-mopd-tp4/compose/compose.rank0.yaml b/profiles/mimo-v26-flash-mopd-tp4/compose/compose.rank0.yaml index 996a047c..eeb80705 100644 --- a/profiles/mimo-v26-flash-mopd-tp4/compose/compose.rank0.yaml +++ b/profiles/mimo-v26-flash-mopd-tp4/compose/compose.rank0.yaml @@ -163,7 +163,7 @@ services: VLLM_WORKER_MULTIPROC_METHOD: spawn XDG_CACHE_HOME: /cache/mimo-v26-flash-rl-f625053225d4-2479e2d0029e labels: - io.sparkring.deployment: 937270f5d4f3734cad73bc63be20f45acafeae6a6af28dda8414514d0d6b8e09 + io.sparkring.deployment: 81405cce8764730eae0d4b36519dc88631ccb22a8a1fafc19b3ccb971768cecf io.sparkring.rank: '0' network_mode: host ipc: host diff --git a/profiles/mimo-v26-flash-mopd-tp4/compose/compose.rank1.yaml b/profiles/mimo-v26-flash-mopd-tp4/compose/compose.rank1.yaml index ca8e5acf..0951d9d6 100644 --- a/profiles/mimo-v26-flash-mopd-tp4/compose/compose.rank1.yaml +++ b/profiles/mimo-v26-flash-mopd-tp4/compose/compose.rank1.yaml @@ -164,7 +164,7 @@ services: VLLM_WORKER_MULTIPROC_METHOD: spawn XDG_CACHE_HOME: /cache/mimo-v26-flash-rl-f625053225d4-2479e2d0029e labels: - io.sparkring.deployment: 937270f5d4f3734cad73bc63be20f45acafeae6a6af28dda8414514d0d6b8e09 + io.sparkring.deployment: 81405cce8764730eae0d4b36519dc88631ccb22a8a1fafc19b3ccb971768cecf io.sparkring.rank: '1' network_mode: host ipc: host diff --git a/profiles/mimo-v26-flash-mopd-tp4/compose/compose.rank2.yaml b/profiles/mimo-v26-flash-mopd-tp4/compose/compose.rank2.yaml index 216f807c..4057ba4c 100644 --- a/profiles/mimo-v26-flash-mopd-tp4/compose/compose.rank2.yaml +++ b/profiles/mimo-v26-flash-mopd-tp4/compose/compose.rank2.yaml @@ -164,7 +164,7 @@ services: VLLM_WORKER_MULTIPROC_METHOD: spawn XDG_CACHE_HOME: /cache/mimo-v26-flash-rl-f625053225d4-2479e2d0029e labels: - io.sparkring.deployment: 937270f5d4f3734cad73bc63be20f45acafeae6a6af28dda8414514d0d6b8e09 + io.sparkring.deployment: 81405cce8764730eae0d4b36519dc88631ccb22a8a1fafc19b3ccb971768cecf io.sparkring.rank: '2' network_mode: host ipc: host diff --git a/profiles/mimo-v26-flash-mopd-tp4/compose/compose.rank3.yaml b/profiles/mimo-v26-flash-mopd-tp4/compose/compose.rank3.yaml index d3189d81..a79c9ed5 100644 --- a/profiles/mimo-v26-flash-mopd-tp4/compose/compose.rank3.yaml +++ b/profiles/mimo-v26-flash-mopd-tp4/compose/compose.rank3.yaml @@ -164,7 +164,7 @@ services: VLLM_WORKER_MULTIPROC_METHOD: spawn XDG_CACHE_HOME: /cache/mimo-v26-flash-rl-f625053225d4-2479e2d0029e labels: - io.sparkring.deployment: 937270f5d4f3734cad73bc63be20f45acafeae6a6af28dda8414514d0d6b8e09 + io.sparkring.deployment: 81405cce8764730eae0d4b36519dc88631ccb22a8a1fafc19b3ccb971768cecf io.sparkring.rank: '3' network_mode: host ipc: host diff --git a/profiles/mimo-v26-flash-mopd-tp4/compose/selection.json b/profiles/mimo-v26-flash-mopd-tp4/compose/selection.json index 16167f85..10cf1244 100644 --- a/profiles/mimo-v26-flash-mopd-tp4/compose/selection.json +++ b/profiles/mimo-v26-flash-mopd-tp4/compose/selection.json @@ -3,5 +3,5 @@ "profile": "mimo-v26-flash-mopd-tp4", "checkpoint": null, "image_lock": "runtime/releases/dev-20261016-sparkcache-4a17f1f5198e-status038/installer-image.json", - "deployment": "937270f5d4f3734cad73bc63be20f45acafeae6a6af28dda8414514d0d6b8e09" + "deployment": "81405cce8764730eae0d4b36519dc88631ccb22a8a1fafc19b3ccb971768cecf" } diff --git a/profiles/qwen38-flash-next-qad-tp4-sparkcache/compose/compose.rank0.yaml b/profiles/qwen38-flash-next-qad-tp4-sparkcache/compose/compose.rank0.yaml index b03bb9be..6af53336 100644 --- a/profiles/qwen38-flash-next-qad-tp4-sparkcache/compose/compose.rank0.yaml +++ b/profiles/qwen38-flash-next-qad-tp4-sparkcache/compose/compose.rank0.yaml @@ -170,7 +170,7 @@ services: VLLM_WORKER_MULTIPROC_METHOD: spawn XDG_CACHE_HOME: /cache/qwen-flash-next-bc16a9819d85-629bc3218833 labels: - io.sparkring.deployment: ba3aff276915e2279c9c3c61ca1d0fc5d198fcd98c68ef5fa76c271747e8430d + io.sparkring.deployment: ffec5a934cb82c1cabbcb63914039dc8f10f2105365a6af225a7bf058dca0da1 io.sparkring.rank: '0' network_mode: host ipc: host diff --git a/profiles/qwen38-flash-next-qad-tp4-sparkcache/compose/compose.rank1.yaml b/profiles/qwen38-flash-next-qad-tp4-sparkcache/compose/compose.rank1.yaml index 991deeac..a32dc27e 100644 --- a/profiles/qwen38-flash-next-qad-tp4-sparkcache/compose/compose.rank1.yaml +++ b/profiles/qwen38-flash-next-qad-tp4-sparkcache/compose/compose.rank1.yaml @@ -171,7 +171,7 @@ services: VLLM_WORKER_MULTIPROC_METHOD: spawn XDG_CACHE_HOME: /cache/qwen-flash-next-bc16a9819d85-629bc3218833 labels: - io.sparkring.deployment: ba3aff276915e2279c9c3c61ca1d0fc5d198fcd98c68ef5fa76c271747e8430d + io.sparkring.deployment: ffec5a934cb82c1cabbcb63914039dc8f10f2105365a6af225a7bf058dca0da1 io.sparkring.rank: '1' network_mode: host ipc: host diff --git a/profiles/qwen38-flash-next-qad-tp4-sparkcache/compose/compose.rank2.yaml b/profiles/qwen38-flash-next-qad-tp4-sparkcache/compose/compose.rank2.yaml index 0f13f8c7..bda78d0d 100644 --- a/profiles/qwen38-flash-next-qad-tp4-sparkcache/compose/compose.rank2.yaml +++ b/profiles/qwen38-flash-next-qad-tp4-sparkcache/compose/compose.rank2.yaml @@ -171,7 +171,7 @@ services: VLLM_WORKER_MULTIPROC_METHOD: spawn XDG_CACHE_HOME: /cache/qwen-flash-next-bc16a9819d85-629bc3218833 labels: - io.sparkring.deployment: ba3aff276915e2279c9c3c61ca1d0fc5d198fcd98c68ef5fa76c271747e8430d + io.sparkring.deployment: ffec5a934cb82c1cabbcb63914039dc8f10f2105365a6af225a7bf058dca0da1 io.sparkring.rank: '2' network_mode: host ipc: host diff --git a/profiles/qwen38-flash-next-qad-tp4-sparkcache/compose/compose.rank3.yaml b/profiles/qwen38-flash-next-qad-tp4-sparkcache/compose/compose.rank3.yaml index 39c53a2f..3916235b 100644 --- a/profiles/qwen38-flash-next-qad-tp4-sparkcache/compose/compose.rank3.yaml +++ b/profiles/qwen38-flash-next-qad-tp4-sparkcache/compose/compose.rank3.yaml @@ -171,7 +171,7 @@ services: VLLM_WORKER_MULTIPROC_METHOD: spawn XDG_CACHE_HOME: /cache/qwen-flash-next-bc16a9819d85-629bc3218833 labels: - io.sparkring.deployment: ba3aff276915e2279c9c3c61ca1d0fc5d198fcd98c68ef5fa76c271747e8430d + io.sparkring.deployment: ffec5a934cb82c1cabbcb63914039dc8f10f2105365a6af225a7bf058dca0da1 io.sparkring.rank: '3' network_mode: host ipc: host diff --git a/profiles/qwen38-flash-next-qad-tp4/compose/compose.rank0.yaml b/profiles/qwen38-flash-next-qad-tp4/compose/compose.rank0.yaml index cbf06e42..80932e13 100644 --- a/profiles/qwen38-flash-next-qad-tp4/compose/compose.rank0.yaml +++ b/profiles/qwen38-flash-next-qad-tp4/compose/compose.rank0.yaml @@ -176,7 +176,7 @@ services: VLLM_WORKER_MULTIPROC_METHOD: spawn XDG_CACHE_HOME: /cache/qwen-flash-next-f625053225d4-60215d26cf5e labels: - io.sparkring.deployment: 7c6a48072f6d3856e21a55c746922e84d1dbe1aeda101f65dc958ec63bebca68 + io.sparkring.deployment: 5ee7e345b245e4073b9d7a593bda5501a0060a5e244883b4acdd806c0989be66 io.sparkring.rank: '0' network_mode: host ipc: host diff --git a/profiles/qwen38-flash-next-qad-tp4/compose/compose.rank1.yaml b/profiles/qwen38-flash-next-qad-tp4/compose/compose.rank1.yaml index 238125fa..91ca32c0 100644 --- a/profiles/qwen38-flash-next-qad-tp4/compose/compose.rank1.yaml +++ b/profiles/qwen38-flash-next-qad-tp4/compose/compose.rank1.yaml @@ -177,7 +177,7 @@ services: VLLM_WORKER_MULTIPROC_METHOD: spawn XDG_CACHE_HOME: /cache/qwen-flash-next-f625053225d4-60215d26cf5e labels: - io.sparkring.deployment: 7c6a48072f6d3856e21a55c746922e84d1dbe1aeda101f65dc958ec63bebca68 + io.sparkring.deployment: 5ee7e345b245e4073b9d7a593bda5501a0060a5e244883b4acdd806c0989be66 io.sparkring.rank: '1' network_mode: host ipc: host diff --git a/profiles/qwen38-flash-next-qad-tp4/compose/compose.rank2.yaml b/profiles/qwen38-flash-next-qad-tp4/compose/compose.rank2.yaml index 5e5ba850..e04ff849 100644 --- a/profiles/qwen38-flash-next-qad-tp4/compose/compose.rank2.yaml +++ b/profiles/qwen38-flash-next-qad-tp4/compose/compose.rank2.yaml @@ -177,7 +177,7 @@ services: VLLM_WORKER_MULTIPROC_METHOD: spawn XDG_CACHE_HOME: /cache/qwen-flash-next-f625053225d4-60215d26cf5e labels: - io.sparkring.deployment: 7c6a48072f6d3856e21a55c746922e84d1dbe1aeda101f65dc958ec63bebca68 + io.sparkring.deployment: 5ee7e345b245e4073b9d7a593bda5501a0060a5e244883b4acdd806c0989be66 io.sparkring.rank: '2' network_mode: host ipc: host diff --git a/profiles/qwen38-flash-next-qad-tp4/compose/compose.rank3.yaml b/profiles/qwen38-flash-next-qad-tp4/compose/compose.rank3.yaml index 0292d389..f3814625 100644 --- a/profiles/qwen38-flash-next-qad-tp4/compose/compose.rank3.yaml +++ b/profiles/qwen38-flash-next-qad-tp4/compose/compose.rank3.yaml @@ -177,7 +177,7 @@ services: VLLM_WORKER_MULTIPROC_METHOD: spawn XDG_CACHE_HOME: /cache/qwen-flash-next-f625053225d4-60215d26cf5e labels: - io.sparkring.deployment: 7c6a48072f6d3856e21a55c746922e84d1dbe1aeda101f65dc958ec63bebca68 + io.sparkring.deployment: 5ee7e345b245e4073b9d7a593bda5501a0060a5e244883b4acdd806c0989be66 io.sparkring.rank: '3' network_mode: host ipc: host diff --git a/profiles/qwen38-flash-next-qad-tp4/compose/selection.json b/profiles/qwen38-flash-next-qad-tp4/compose/selection.json index e172af2b..1a5225f3 100644 --- a/profiles/qwen38-flash-next-qad-tp4/compose/selection.json +++ b/profiles/qwen38-flash-next-qad-tp4/compose/selection.json @@ -3,5 +3,5 @@ "profile": "qwen38-flash-next-qad-tp4", "checkpoint": "qad-step5500-ple1000", "image_lock": "runtime/releases/dev-20261016-sparkcache-4a17f1f5198e-status038/installer-image.json", - "deployment": "7c6a48072f6d3856e21a55c746922e84d1dbe1aeda101f65dc958ec63bebca68" + "deployment": "5ee7e345b245e4073b9d7a593bda5501a0060a5e244883b4acdd806c0989be66" } diff --git a/profiles/qwen38-flash-next-tp2-sparkcache/compose/compose.rank0.yaml b/profiles/qwen38-flash-next-tp2-sparkcache/compose/compose.rank0.yaml index 37a3069b..bd0f2838 100644 --- a/profiles/qwen38-flash-next-tp2-sparkcache/compose/compose.rank0.yaml +++ b/profiles/qwen38-flash-next-tp2-sparkcache/compose/compose.rank0.yaml @@ -147,7 +147,7 @@ services: VLLM_WORKER_MULTIPROC_METHOD: spawn XDG_CACHE_HOME: /cache/qwen-flash-next-bc16a9819d85-629bc3218833 labels: - io.sparkring.deployment: 42a0f8d70d4b03f7ca41ab5e9258ea280662fad53badac4b7600eb9697dec197 + io.sparkring.deployment: 11c053a21300c93a106cadf091fe9b2505d1b88772e86373d18c9056da749d84 io.sparkring.rank: '0' network_mode: host ipc: host diff --git a/profiles/qwen38-flash-next-tp2-sparkcache/compose/compose.rank1.yaml b/profiles/qwen38-flash-next-tp2-sparkcache/compose/compose.rank1.yaml index 73df4deb..e06f1bb5 100644 --- a/profiles/qwen38-flash-next-tp2-sparkcache/compose/compose.rank1.yaml +++ b/profiles/qwen38-flash-next-tp2-sparkcache/compose/compose.rank1.yaml @@ -148,7 +148,7 @@ services: VLLM_WORKER_MULTIPROC_METHOD: spawn XDG_CACHE_HOME: /cache/qwen-flash-next-bc16a9819d85-629bc3218833 labels: - io.sparkring.deployment: 42a0f8d70d4b03f7ca41ab5e9258ea280662fad53badac4b7600eb9697dec197 + io.sparkring.deployment: 11c053a21300c93a106cadf091fe9b2505d1b88772e86373d18c9056da749d84 io.sparkring.rank: '1' network_mode: host ipc: host diff --git a/profiles/qwen38-flash-next-tp2/compose/compose.rank0.yaml b/profiles/qwen38-flash-next-tp2/compose/compose.rank0.yaml index fa616579..8b913bce 100644 --- a/profiles/qwen38-flash-next-tp2/compose/compose.rank0.yaml +++ b/profiles/qwen38-flash-next-tp2/compose/compose.rank0.yaml @@ -160,7 +160,7 @@ services: VLLM_WORKER_MULTIPROC_METHOD: spawn XDG_CACHE_HOME: /cache/qwen-flash-next-f625053225d4-dc5b8ab2fa14 labels: - io.sparkring.deployment: f46afc82bc9f734602d24926aae4a3dc5d40862172874504d284ad3fc6a2cd75 + io.sparkring.deployment: 4817bacdbd5a3e9fbc9f52b097e72beb08a83ffe0b88022a07b7fc0ff90bcece io.sparkring.rank: '0' network_mode: host ipc: host diff --git a/profiles/qwen38-flash-next-tp2/compose/compose.rank1.yaml b/profiles/qwen38-flash-next-tp2/compose/compose.rank1.yaml index d7cdb54a..18c18e13 100644 --- a/profiles/qwen38-flash-next-tp2/compose/compose.rank1.yaml +++ b/profiles/qwen38-flash-next-tp2/compose/compose.rank1.yaml @@ -161,7 +161,7 @@ services: VLLM_WORKER_MULTIPROC_METHOD: spawn XDG_CACHE_HOME: /cache/qwen-flash-next-f625053225d4-dc5b8ab2fa14 labels: - io.sparkring.deployment: f46afc82bc9f734602d24926aae4a3dc5d40862172874504d284ad3fc6a2cd75 + io.sparkring.deployment: 4817bacdbd5a3e9fbc9f52b097e72beb08a83ffe0b88022a07b7fc0ff90bcece io.sparkring.rank: '1' network_mode: host ipc: host diff --git a/profiles/qwen38-flash-next-tp2/compose/selection.json b/profiles/qwen38-flash-next-tp2/compose/selection.json index 39af7859..943e2eb8 100644 --- a/profiles/qwen38-flash-next-tp2/compose/selection.json +++ b/profiles/qwen38-flash-next-tp2/compose/selection.json @@ -3,5 +3,5 @@ "profile": "qwen38-flash-next-tp2", "checkpoint": "csf", "image_lock": "runtime/releases/dev-20261016-sparkcache-4a17f1f5198e-status038/installer-image.json", - "deployment": "f46afc82bc9f734602d24926aae4a3dc5d40862172874504d284ad3fc6a2cd75" + "deployment": "4817bacdbd5a3e9fbc9f52b097e72beb08a83ffe0b88022a07b7fc0ff90bcece" } diff --git a/profiles/swift15-qwen38-flash-next-tp2/compose/compose.rank0.yaml b/profiles/swift15-qwen38-flash-next-tp2/compose/compose.rank0.yaml index 012bba03..7cd58e79 100644 --- a/profiles/swift15-qwen38-flash-next-tp2/compose/compose.rank0.yaml +++ b/profiles/swift15-qwen38-flash-next-tp2/compose/compose.rank0.yaml @@ -160,7 +160,7 @@ services: VLLM_WORKER_MULTIPROC_METHOD: spawn XDG_CACHE_HOME: /cache/swift15-qwen38-flash-next-f625053225d4-3ff0520224f2 labels: - io.sparkring.deployment: 245469862d6818374d7ef489f8584ad46bddcb4d31a28ca13ff7624bfc0e7744 + io.sparkring.deployment: 313487f33b845b9f78b9008b364ab5fbb7934eea9005fc4c4094cf92597dbf74 io.sparkring.rank: '0' network_mode: host ipc: host diff --git a/profiles/swift15-qwen38-flash-next-tp2/compose/compose.rank1.yaml b/profiles/swift15-qwen38-flash-next-tp2/compose/compose.rank1.yaml index 31038d41..02defdd8 100644 --- a/profiles/swift15-qwen38-flash-next-tp2/compose/compose.rank1.yaml +++ b/profiles/swift15-qwen38-flash-next-tp2/compose/compose.rank1.yaml @@ -161,7 +161,7 @@ services: VLLM_WORKER_MULTIPROC_METHOD: spawn XDG_CACHE_HOME: /cache/swift15-qwen38-flash-next-f625053225d4-3ff0520224f2 labels: - io.sparkring.deployment: 245469862d6818374d7ef489f8584ad46bddcb4d31a28ca13ff7624bfc0e7744 + io.sparkring.deployment: 313487f33b845b9f78b9008b364ab5fbb7934eea9005fc4c4094cf92597dbf74 io.sparkring.rank: '1' network_mode: host ipc: host diff --git a/profiles/swift15-qwen38-flash-next-tp2/compose/selection.json b/profiles/swift15-qwen38-flash-next-tp2/compose/selection.json index 74cca8b3..d9ad1ac5 100644 --- a/profiles/swift15-qwen38-flash-next-tp2/compose/selection.json +++ b/profiles/swift15-qwen38-flash-next-tp2/compose/selection.json @@ -3,5 +3,5 @@ "profile": "swift15-qwen38-flash-next-tp2", "checkpoint": null, "image_lock": "runtime/releases/dev-20261016-sparkcache-4a17f1f5198e-status038/installer-image.json", - "deployment": "245469862d6818374d7ef489f8584ad46bddcb4d31a28ca13ff7624bfc0e7744" + "deployment": "313487f33b845b9f78b9008b364ab5fbb7934eea9005fc4c4094cf92597dbf74" } diff --git a/profiles/swift15-qwen38-flash-next-tp4/compose/compose.rank0.yaml b/profiles/swift15-qwen38-flash-next-tp4/compose/compose.rank0.yaml index 415807c3..7f82dd3a 100644 --- a/profiles/swift15-qwen38-flash-next-tp4/compose/compose.rank0.yaml +++ b/profiles/swift15-qwen38-flash-next-tp4/compose/compose.rank0.yaml @@ -176,7 +176,7 @@ services: VLLM_WORKER_MULTIPROC_METHOD: spawn XDG_CACHE_HOME: /cache/swift15-qwen38-flash-next-f625053225d4-3ff0520224f2 labels: - io.sparkring.deployment: 89e774356850d9c51d1aca722f5fa6ae5ac91593177d9002b4ac26c643058bf8 + io.sparkring.deployment: 99ed0e4f978b24fd63ad4b33c019226eeeca743d3d8a1f32bd848990d64ff346 io.sparkring.rank: '0' network_mode: host ipc: host diff --git a/profiles/swift15-qwen38-flash-next-tp4/compose/compose.rank1.yaml b/profiles/swift15-qwen38-flash-next-tp4/compose/compose.rank1.yaml index 93cfa9a8..9734c750 100644 --- a/profiles/swift15-qwen38-flash-next-tp4/compose/compose.rank1.yaml +++ b/profiles/swift15-qwen38-flash-next-tp4/compose/compose.rank1.yaml @@ -177,7 +177,7 @@ services: VLLM_WORKER_MULTIPROC_METHOD: spawn XDG_CACHE_HOME: /cache/swift15-qwen38-flash-next-f625053225d4-3ff0520224f2 labels: - io.sparkring.deployment: 89e774356850d9c51d1aca722f5fa6ae5ac91593177d9002b4ac26c643058bf8 + io.sparkring.deployment: 99ed0e4f978b24fd63ad4b33c019226eeeca743d3d8a1f32bd848990d64ff346 io.sparkring.rank: '1' network_mode: host ipc: host diff --git a/profiles/swift15-qwen38-flash-next-tp4/compose/compose.rank2.yaml b/profiles/swift15-qwen38-flash-next-tp4/compose/compose.rank2.yaml index 22345220..f13fcb5c 100644 --- a/profiles/swift15-qwen38-flash-next-tp4/compose/compose.rank2.yaml +++ b/profiles/swift15-qwen38-flash-next-tp4/compose/compose.rank2.yaml @@ -177,7 +177,7 @@ services: VLLM_WORKER_MULTIPROC_METHOD: spawn XDG_CACHE_HOME: /cache/swift15-qwen38-flash-next-f625053225d4-3ff0520224f2 labels: - io.sparkring.deployment: 89e774356850d9c51d1aca722f5fa6ae5ac91593177d9002b4ac26c643058bf8 + io.sparkring.deployment: 99ed0e4f978b24fd63ad4b33c019226eeeca743d3d8a1f32bd848990d64ff346 io.sparkring.rank: '2' network_mode: host ipc: host diff --git a/profiles/swift15-qwen38-flash-next-tp4/compose/compose.rank3.yaml b/profiles/swift15-qwen38-flash-next-tp4/compose/compose.rank3.yaml index baa00d3f..f7e29ff0 100644 --- a/profiles/swift15-qwen38-flash-next-tp4/compose/compose.rank3.yaml +++ b/profiles/swift15-qwen38-flash-next-tp4/compose/compose.rank3.yaml @@ -177,7 +177,7 @@ services: VLLM_WORKER_MULTIPROC_METHOD: spawn XDG_CACHE_HOME: /cache/swift15-qwen38-flash-next-f625053225d4-3ff0520224f2 labels: - io.sparkring.deployment: 89e774356850d9c51d1aca722f5fa6ae5ac91593177d9002b4ac26c643058bf8 + io.sparkring.deployment: 99ed0e4f978b24fd63ad4b33c019226eeeca743d3d8a1f32bd848990d64ff346 io.sparkring.rank: '3' network_mode: host ipc: host diff --git a/profiles/swift15-qwen38-flash-next-tp4/compose/selection.json b/profiles/swift15-qwen38-flash-next-tp4/compose/selection.json index 90ba301b..6ca8cc38 100644 --- a/profiles/swift15-qwen38-flash-next-tp4/compose/selection.json +++ b/profiles/swift15-qwen38-flash-next-tp4/compose/selection.json @@ -3,5 +3,5 @@ "profile": "swift15-qwen38-flash-next-tp4", "checkpoint": null, "image_lock": "runtime/releases/dev-20261016-sparkcache-4a17f1f5198e-status038/installer-image.json", - "deployment": "89e774356850d9c51d1aca722f5fa6ae5ac91593177d9002b4ac26c643058bf8" + "deployment": "99ed0e4f978b24fd63ad4b33c019226eeeca743d3d8a1f32bd848990d64ff346" } diff --git a/runtime/common/compose.py b/runtime/common/compose.py index cf370da0..67598655 100644 --- a/runtime/common/compose.py +++ b/runtime/common/compose.py @@ -502,8 +502,14 @@ def specifications(profile_id, site, *, local_image_id=None, local_source_extens source_root=rank["repository"]) specs.append(replace(spec, name=f"sr-{site['name']}-r{rank['rank']}")) settings = serving_settings.effective(profile_id, serving, checkpoint) - if settings.get(serving_settings.ROW_OWNED_PREFILL): - raise ValueError(f"{serving_settings.option(serving_settings.ROW_OWNED_PREFILL)} requires sparkring install") + installed = [name for name in (serving_settings.ROW_OWNED_PREFILL, serving_settings.EXPERT_PARALLEL) + if settings.get(name)] + if installed: + # Both run only on the deployment `sparkring install` makes on a SIRCL ring + # session: the row-owned prefill mounts plugins from the retained source, + # and expert parallelism needs the libsircl transport a Compose deployment + # has no section for. + raise ValueError(f"{serving_settings.option(installed[0])} requires sparkring install") if settings: if local_source_extension is not None: raise ValueError("Serving settings apply to published images; a local source-extension trial " diff --git a/runtime/common/installer.py b/runtime/common/installer.py index 6fd5bdea..0c51e2ec 100644 --- a/runtime/common/installer.py +++ b/runtime/common/installer.py @@ -372,6 +372,7 @@ def make_lock(profile, raw_site, revision, bundle_sha256, variant=None, *, image raise ValueError(f"{card['profile']} runs only on SIRCL ring sessions; its deployment needs a transport " "section") serving.check_row_owned_prefill(settings, (profile, card["target_variant"]), image_runtime, value.get("transport")) + serving.check_expert_parallel(settings, (profile, card["target_variant"]), image_runtime, value.get("transport")) value["id"] = compose.digest(compose.encoded(value)) return value @@ -815,10 +816,15 @@ def export(directory, output, *, share=False): files["site.example.json"] = compose.encoded(example) files["profile.json"] = compose.encoded(lock["selection"]) if settings.get(serving.ROW_OWNED_PREFILL): + # Expert parallelism runs on libsircl, whose transport names the + # library and needs no --nccl; the tensor-parallel experiment runs + # on SIRCL's own sessions with NCCL off. + transport_flags = (" --transport libsircl" if settings.get(serving.EXPERT_PARALLEL) + else " --transport sircl --nccl never") files["README.txt"] = ( "Configure a four-Spark path with sparkring setup. Then run sudo sparkring install --profile " + lock["selection"]["profile"] + " --checkpoint " + lock["selection"]["target_variant"] - + " --image " + runtime["name"] + " --transport sircl --nccl never" + flags + ".\n" + + " --image " + runtime["name"] + transport_flags + flags + ".\n" "The installer stages the plugin and SIRCL adapter from its retained source checkout on every rank. " "The Compose files show the resulting rank settings with example paths.\n" ) diff --git a/runtime/common/serving.py b/runtime/common/serving.py index c0e43c1d..fb1148ad 100644 --- a/runtime/common/serving.py +++ b/runtime/common/serving.py @@ -81,6 +81,51 @@ # rather than hardcoding checkpoint/image constants inline in serving logic. ROW_OWNED_PREFILL = "row_owned_prefill" CHAIN_ALL_GATHER = "chain_all_gather" +# Expert parallelism holds each rank's experts whole beside the batch's tokens: +# every rank keeps a copy of the activations, gathers the rows its experts take +# and reduce-scatters the result, so its grouped collectives are all-gathers and +# reduce-scatters (integrations/vllm/libsircl/sircl_ep_b12x.py, which the +# libsircl vLLM plugin installs when SIRCL_B12X_EP_MOE is set). The image's B12X +# weight loader shards this checkpoint for an expert-parallel rank through +# vLLM's expert map and read the same target-model weights in 13.70 s against +# vLLM's own loader's 115.99 s on ring 4-7. Its effect on total startup and on +# the served outputs is unmeasured, so an expert-parallel deployment loads with +# vLLM's own loader and leaves that plugin out until a launch with +# EXPERT_LOADER_EP measures both +# (performance/records/deepseek-v41-flash/row-owned-tp4-ep4-libsircl-20261121.md). +EXPERT_PARALLEL = "expert_parallel" +EXPERT_ALL2ALL = "allgather_reducescatter" +EXPERT_LOADER_EP = False +EXPERT_LOADER_PLUGINS = ("b12x_loader",) +# The libsircl link geometry and Leg-2 decode tuning of the row-owned +# expert-parallel deployment on ring 4-7: a 1 MiB link slot and 1 MiB pieces +# for grouped all-gather, reduce-scatter and all-reduce; a 256 KiB one-shot +# ceiling (eliminating ~290K decode twoshot phases caused by 64 KiB); a 64 KiB +# forwarding chunk; P-core progress thread pinning (CPU 9 on GB10); W4A8 shared +# input quantization across experts; text-only MoE padding skip; and 4 OpenMP +# threads. The 1 MiB link geometry raised cold-prefill medians of seven samples +# by 5.6%, 9.7% and 11.5% at 16K, 64K and 128K tokens, and the Leg-2 decode +# tuning (paired with the plugin's Triton expert-ID remap, router padding skip, +# and EP grouped routing) raised 15-cell coding-matrix throughput by +9.0% on +# Coding Peak (76.0 -> 82.8 tok/s median, 84.2 -> 91.6 max), +7.9% to +11.6% at +# C=2, and +9.3% to +11.9% at C=4 (+13.8% to +15.2% steps/s) while keeping +# prefill at 6.4-6.8 ktok/s and 18.5 GiB KV headroom at 256K +# (performance/records/deepseek-v41-flash/row-owned-tp4-ep4-libsircl-20261121.md). +# A 16,384-token prefill batch on top of it measured 0.8 to 5.1 points higher +# but cost 10 to 17% of decode at one, four and sixteen requests, so the batch +# stays the profile's 8,192. +EXPERT_PARALLEL_LINK = { + "SIRCL_ONESHOT_MAX_BYTES": "262144", + "SIRCL_LINK_SLOT_BYTES": "1048576", + "SIRCL_GATHER_LINK_CHUNK_BYTES": "1048576", + "SIRCL_REDUCE_LINK_CHUNK_BYTES": "1048576", + "SIRCL_SCATTER_LINK_CHUNK_BYTES": "1048576", + "SIRCL_FORWARD_CHUNK_BYTES": "65536", + "SIRCL_PROGRESS_CPU": "9", + "B12X_DYNAMIC_W4A8_SHARE_INPUT": "1", + "VLLM_MOE_SKIP_PADDING": "1", + "OMP_NUM_THREADS": "4", +} @functools.lru_cache(maxsize=8) @@ -118,6 +163,12 @@ def _install_switches(): for companion_name, companion in (entry.get("companion_switches") or {}).items(): c_var, c_value = companion["switch_env"] switches[companion_name] = (c_var, c_value, companion["help"]) + switches[EXPERT_PARALLEL] = ( + "SIRCL_B12X_EP_MOE", + "1", + "experimental DeepSeek V4.1-Flash-1017 expert parallelism over libsircl's all-gather and " + "reduce-scatter, with or without --row-owned-prefill", + ) return switches @@ -323,17 +374,27 @@ def check_experimental_overrides(settings, model, image, transport): raise ValueError(f"{flag} requires --profile {entry['profile']} --checkpoint {entry['checkpoint']}") if not image or image["image_id"] != entry["image_id"]: raise ValueError(f"{flag} requires --image {entry['image_name']}") - req_transport = entry["transport"] - if (not transport or transport.get("backend") != req_transport["backend"] - or transport.get("nccl") != req_transport["nccl"] - or transport["group"]["name"] != req_transport["group_name"] - or transport["group"]["dcp"] != req_transport["dcp"]): - raise ValueError(f"{flag} requires --transport {req_transport['backend']} --nccl {req_transport['nccl']} " - "on a four-Spark path") - for companion_name, companion in companions.items(): - if settings.get(companion_name) and companion.get("forbid_tp_tuning_table"): - if any("tp" in row["sessions"] for row in transport["tuning"]["tables"]): - raise ValueError(f"{option(companion_name)} requires a SIRCL path without a TP tuning table") + if name == ROW_OWNED_PREFILL and settings.get(EXPERT_PARALLEL): + # Expert parallelism carries the row-owned MoE output's single reduction + # on libsircl's all-gather and reduce-scatter; SIRCL's own adapter, and + # its schedule and tuning table, run only the tensor-parallel experiment. + if (transport or {}).get("backend") != "libsircl": + raise ValueError(f"{flag} with {option(EXPERT_PARALLEL)} requires --transport libsircl") + if settings.get(CHAIN_ALL_GATHER): + raise ValueError(f"{option(CHAIN_ALL_GATHER)} selects SIRCL's own all-gather schedule, which a libsircl " + f"deployment does not run; leave it out with {option(EXPERT_PARALLEL)}") + else: + req_transport = entry["transport"] + if (not transport or transport.get("backend") != req_transport["backend"] + or transport.get("nccl") != req_transport["nccl"] + or transport["group"]["name"] != req_transport["group_name"] + or transport["group"]["dcp"] != req_transport["dcp"]): + raise ValueError(f"{flag} requires --transport {req_transport['backend']} --nccl {req_transport['nccl']} " + "on a four-Spark path") + for companion_name, companion in companions.items(): + if settings.get(companion_name) and companion.get("forbid_tp_tuning_table"): + if any("tp" in row["sessions"] for row in transport["tuning"]["tables"]): + raise ValueError(f"{option(companion_name)} requires a SIRCL path without a TP tuning table") max_ctx = entry["max_context_length"] if settings.get("context_length", max_ctx) > max_ctx: raise ValueError(f"{flag} supports --context-length up to {max_ctx} tokens") @@ -344,6 +405,27 @@ def check_row_owned_prefill(settings, model, image, transport): check_experimental_overrides(settings, model, image, transport) +def check_expert_parallel(settings, model, image, transport): + """Admit the expert-parallel MoE build for the measured image, model and transport.""" + if not settings.get(EXPERT_PARALLEL): + return + flag = option(EXPERT_PARALLEL) + override = experimental_override(ROW_OWNED_PREFILL) + if override is None: + raise ValueError(f"{flag} requires {ROW_OWNED_PREFILL} experimental override metadata") + if model != (override["profile"], override["checkpoint"]): + raise ValueError(f"{flag} requires --profile {override['profile']} " + f"--checkpoint {override['checkpoint']}") + if not image or image["image_id"] != override["image_id"]: + raise ValueError(f"{flag} requires --image {override['image_name']}") + if (transport or {}).get("backend") != "libsircl": + raise ValueError(f"{flag} requires --transport libsircl: the expert-parallel MoE build runs in libsircl's " + "vLLM plugin, and its all-gather and reduce-scatter carry the grouped collectives") + if settings.get(CHAIN_ALL_GATHER): + raise ValueError(f"{option(CHAIN_ALL_GATHER)} selects SIRCL's own all-gather schedule, which a libsircl " + f"deployment does not run; leave it out with {flag}") + + def choice(name, value): """A CHOICES value as the deployment records it: a lowercase word, or a whole number of at least 1. @@ -502,6 +584,11 @@ def container(spec, settings, *, rank, model=None, source_root=None): settings require. Without settings ``spec`` is returned unchanged. SparkCache debug logging and DeepSeek row-owned prefill mount their assets from the retained deployment checkout at ``source_root`` on each host. + Expert parallelism names the grouped all-to-all backend and, while the + image's B12X loader's total startup is unmeasured, loads with vLLM's loader + and leaves that plugin out (``_expert_parallel_arguments``); with + ``row_owned_prefill`` it also sets the link geometry measured on that + deployment (``EXPERT_PARALLEL_LINK``). """ if not settings: return spec @@ -521,6 +608,17 @@ def container(spec, settings, *, rank, model=None, source_root=None): if source_root is None: raise ValueError("SparkCache debug logging requires the deployment source directory") mounts = (*mounts, Bind(str(PurePosixPath(source_root) / sparkcache.DEBUG_SOURCE), sparkcache.DEBUG_TARGET, True)) + if settings.get(EXPERT_PARALLEL): + command = _expert_parallel_arguments(command) + if not EXPERT_LOADER_EP: + # The image's B12X loader reads a checkpoint for one tensor-parallel + # rank's experts, so expert parallelism leaves its plugin out. + names = [name for name in (env.get("VLLM_PLUGINS") or "").split(",") + if name and name not in EXPERT_LOADER_PLUGINS] + if names: + env["VLLM_PLUGINS"] = ",".join(names) + else: + env.pop("VLLM_PLUGINS", None) for name, entry in experimental_overrides().items(): if not settings.get(name): continue @@ -545,6 +643,28 @@ def container(spec, settings, *, rank, model=None, source_root=None): environment=env, health_command=health) +def _expert_parallel_arguments(command): + """Expert parallelism at the tensor width, on the grouped all-gather and reduce-scatter.""" + command = list(command) + if not EXPERT_LOADER_EP: + # vLLM's own loader stays in place until the image's B12X loader has a + # measured total startup on an expert-parallel rank; it already reads + # that rank's share of the checkpoint. + position = _position(command, "--load-format") + if position is None: + raise ValueError(f"{option(EXPERT_PARALLEL)} requires a profile that loads the image's B12X weights") + command[position] = "auto" + if "--enable-expert-parallel" not in command: + command.append("--enable-expert-parallel") + if _position(command, "--all2all-backend") is None: + # The grouped all-gather and reduce-scatter that libsircl carries, and the + # only all-to-all the row-owned MoE deferral admits: it runs no all-to-all + # kernels (integrations/vllm/ds41_row_shard). A version's own default is + # not recorded here, so the backend is always named. + command += ["--all2all-backend", EXPERT_ALL2ALL] + return tuple(command) + + def _apply_experimental_arguments(command, entry): """Apply declarative JSON flag overrides, context ceiling, and extra args from ``entry``.""" command = list(command) @@ -558,7 +678,8 @@ def _apply_experimental_arguments(command, entry): context = command.index("--max-model-len") + 1 command[context] = str(min(int(command[context]), max_ctx)) for arg in (entry.get("extra_args") or ()): - command.append(arg) + if arg not in command: + command.append(arg) return tuple(command) @@ -571,6 +692,10 @@ def environment(settings): for name, entry in experimental_overrides().items(): if settings.get(name): result.update(entry.get("extra_env") or {}) + if settings.get(EXPERT_PARALLEL) and settings.get(ROW_OWNED_PREFILL): + # The link geometry was measured on this pairing only; expert + # parallelism alone keeps libsircl's defaults until a run measures it. + result.update(EXPERT_PARALLEL_LINK) return result diff --git a/runtime/common/test_compose.py b/runtime/common/test_compose.py index ffa50415..d5fff0da 100644 --- a/runtime/common/test_compose.py +++ b/runtime/common/test_compose.py @@ -446,6 +446,21 @@ def test_save_cpu_is_refused_on_an_image_without_the_reader_window(): assert manifest["serving"] == {"save_cpu": True} +def test_the_installer_only_switches_are_refused_and_name_themselves(): + # The row-owned prefill and expert parallelism run only on the deployment + # `sparkring install` makes on a SIRCL ring session. + profile = "deepseek-v41-flash-tp4" + site = example_site(profile) + for settings, flag in (({"row_owned_prefill": True}, "--row-owned-prefill"), + ({"expert_parallel": True}, "--expert-parallel"), + ({"expert_parallel": True, "row_owned_prefill": True}, "--row-owned-prefill")): + with pytest.raises(ValueError, match=f"{flag} requires sparkring install"): + compose.build(profile, site, serving=settings) + # Either switch beside a setting Compose does render still names the switch first. + with pytest.raises(ValueError, match="--expert-parallel requires sparkring install"): + compose.build(profile, site, serving={"expert_parallel": True, "max_images": 2}) + + def test_profiles_without_checkpoint_choice_refuse_one(): profile = "mimo-v26-flash-mopd-tp2" with pytest.raises(ValueError, match="no checkpoint choice"): diff --git a/runtime/common/test_libsircl.py b/runtime/common/test_libsircl.py index c6a8f2ff..768870fe 100644 --- a/runtime/common/test_libsircl.py +++ b/runtime/common/test_libsircl.py @@ -14,7 +14,7 @@ import pytest -from runtime.common import fabric_document, image_lock, installer, libsircl, transport +from runtime.common import fabric_document, image_lock, installer, installer_image, libsircl, serving, transport from runtime.common.test_image_lock import libsircl_lock, sircl_lock from runtime.common.test_transport import TP2, TP4, document, install_site from spark_transport.sircl.sparkring_sircl.vllm.serve import plan as serve_plan @@ -252,6 +252,77 @@ def test_two_pipeline_stages_and_expert_parallelism_on_grouped_all_gathers_pass( "allgather_reducescatter"]) == [] +def pinned_image(): + """The v3 lock of the image the DeepSeek expert-parallel deployment is measured on.""" + return json.loads(installer_image.lock_path(serving.ROW_OWNED_PREFILL_IMAGE).read_text(encoding="utf-8")) + + +def test_the_expert_parallel_switch_reaches_the_container_beside_libsircls_own_settings(): + """R1: the pinned TP4+EP4 deployment keeps both plugins, vLLM's loader and every libsircl setting. + + ``libsircl.adapt`` drops a profile's ``SIRCL_*`` variables, since they + configure SIRCL's own adapter, which this transport does not run. The + expert-parallel switch is the libsircl plugin's (``SIRCL_B12X_EP_MOE``) and + the link geometry is libsircl's own, so the serving settings apply after the + transport and both survive beside the transport's route variables. + """ + value = pinned_image() + section = libsircl.section(value, document("path", 4), [0, 1, 2, 3], dcp=1) + model = (serving.ROW_OWNED_PREFILL_PROFILE, serving.ROW_OWNED_PREFILL_CHECKPOINT) + common = dict(image_runtime=image_lock.v2_view(value), transport=section) + plain = installer.make_lock(model[0], install_site(4), "1" * 40, "2" * 64, model[1], **common) + expert = installer.make_lock(model[0], install_site(4), "1" * 40, "2" * 64, model[1], + settings={"expert_parallel": True}, **common) + r1 = installer.make_lock(model[0], install_site(4), "1" * 40, "2" * 64, model[1], + settings={"expert_parallel": True, "row_owned_prefill": True}, **common) + assert len({plain["id"], expert["id"], r1["id"]}) == 3 and installer.validate(r1) == r1 + assert r1["serving"] == {"expert_parallel": True, "row_owned_prefill": True} + assert r1["selection"]["profile"] == model[0] and r1["selection"]["target_variant"] == model[1] + for rank, (base, only, both) in enumerate(zip(installer.specifications(plain), + installer.specifications(expert), + installer.specifications(r1), strict=True)): + assert "SIRCL_B12X_EP_MOE" not in base.environment and only.environment["SIRCL_B12X_EP_MOE"] == "1" + assert both.environment["SIRCL_B12X_EP_MOE"] == "1" + plugins = base.environment["VLLM_PLUGINS"].split(",") + assert plugins[0] == "b12x_loader" and plugins[-1] == libsircl.PLUGIN_NAME + assert only.environment["VLLM_PLUGINS"].split(",") == [name for name in plugins if name != "b12x_loader"] + assert both.environment["VLLM_PLUGINS"].split(",") == [ + *[name for name in plugins if name != "b12x_loader"], "ds41_row_shard"] + assert (only.command[only.command.index("--load-format") + 1], + base.command[base.command.index("--load-format") + 1]) == ("auto", "b12x") + for spec in (only, both): + assert spec.command.count("--enable-expert-parallel") == 1 + assert libsircl.argument(spec.command, "--all2all-backend") == serving.EXPERT_ALL2ALL + # The transport turns vLLM's custom all-reduce off, as the row-owned experiment does. + assert spec.command.count(libsircl.CUSTOM_ALL_REDUCE_OFF) == 1 + # libsircl's own checks pass on the command the experiment serves. + assert libsircl.refusals(spec.environment, spec.command) == [] + assert both.environment["PYTHONPATH"].split(":")[0] == serving.ROW_OWNED_PREFILL_TARGET + assert [(mount.target, mount.read_only) for mount in both.mounts][-2:] == [ + (serving.ROW_OWNED_PREFILL_TARGET, True), (serving.ROW_OWNED_SIRCL_TARGET, True)] + # libsircl's own settings are the transport's, and only the two serving + # settings differ from `common_settings`' containers. + block = section["libsircl"] + assert (both.environment["SPARKRING_LIBSIRCL_LIBRARY"], both.environment["SPARKRING_LIBSIRCL_SHA256"]) == ( + block["library"]["path"], block["library"]["sha256"]) + assert (both.environment["LIBSIRCL_TRANSPORT"], both.environment["LIBSIRCL_FAIL_STOP"], + both.environment["LIBSIRCL_NCCL_API_VERSION"]) == ("verbs", "1", "22705") + assert both.environment["SIRCL_BOOTSTRAP_ADDR"] == both.environment["VLLM_HOST_IP"] + assert {key for key in both.environment if key.startswith("SIRCL_") and key not in ROUTES} == { + "SIRCL_GID_INDEX", "SIRCL_BOOTSTRAP_ADDR", "SIRCL_ENABLED", "SIRCL_B12X_EP_MOE", + *(key for key in serving.EXPERT_PARALLEL_LINK if key.startswith("SIRCL_") and key not in ROUTES)} + # The link geometry and Leg-2 decode tuning of the measured deployment belong to + # the row-owned pairing; expert parallelism alone keeps base/libsircl defaults. + assert {name: both.environment[name] for name in serving.EXPERT_PARALLEL_LINK} == serving.EXPERT_PARALLEL_LINK + for name in serving.EXPERT_PARALLEL_LINK: + assert only.environment.get(name) == base.environment.get(name) + assert base.environment.get(name) != serving.EXPERT_PARALLEL_LINK[name] + assert (both.command[both.command.index("--max-model-len") + 1], + base.command[base.command.index("--max-model-len") + 1]) == (str(serving.ROW_OWNED_PREFILL_CONTEXT), + "1048576") + assert ("--headless" in both.command) == bool(rank) + + def test_the_lane_runs_in_the_startup_wait_regime_at_the_librarys_limit(): """The lane sets no wait variable, so every communicator runs in the startup regime at libsircl's default limit; the architecture document's fail-stop section states that regime and limit, so the document, the diff --git a/runtime/common/test_serving.py b/runtime/common/test_serving.py index e288fa5a..a4839bad 100644 --- a/runtime/common/test_serving.py +++ b/runtime/common/test_serving.py @@ -353,6 +353,98 @@ def test_without_thinking_settings_commands_compose_files_and_locks_are_unchange assert all(KWARGS not in spec.command for spec in installer.specifications(tuned)) +PINNED = {"image_id": serving.ROW_OWNED_PREFILL_IMAGE_ID} +EXPERIMENT = (serving.ROW_OWNED_PREFILL_PROFILE, serving.ROW_OWNED_PREFILL_CHECKPOINT) + + +def test_expert_parallel_is_a_switch_that_names_the_grouped_all_to_all(): + assert serving.normalized({"expert_parallel": True, "max_images": None}) == {"expert_parallel": True} + with pytest.raises(ValueError, match="--expert-parallel is a switch without a value"): + serving.normalized({"expert_parallel": 1}) + assert serving.environment({"expert_parallel": True, "max_images": 2}) == {"SIRCL_B12X_EP_MOE": "1"} + args = profile_args(DEEPSEEK) + assert serving.apply(args, {"expert_parallel": True}) == tuple(args) + assert serving.describe({"expert_parallel": True, "max_images": 2}, tuple(args)) == [ + "--expert-parallel (profile: off)", "--max-images 2 (profile: 4)"] + + +def test_the_row_owned_expert_parallel_pairing_sets_the_measured_link_geometry(): + # The balanced link geometry and Leg-2 decode tuning measured on ring 4-7: + # 1 MiB link slot/pieces, 256 KiB one-shot ceiling, 64 KiB forward chunk, + # P-core progress pinning, W4A8 shared input, MoE padding skip, and 4 OMP threads. + link = { + "SIRCL_ONESHOT_MAX_BYTES": "262144", + "SIRCL_LINK_SLOT_BYTES": "1048576", + "SIRCL_GATHER_LINK_CHUNK_BYTES": "1048576", + "SIRCL_REDUCE_LINK_CHUNK_BYTES": "1048576", + "SIRCL_SCATTER_LINK_CHUNK_BYTES": "1048576", + "SIRCL_FORWARD_CHUNK_BYTES": "65536", + "SIRCL_PROGRESS_CPU": "9", + "B12X_DYNAMIC_W4A8_SHARE_INPUT": "1", + "VLLM_MOE_SKIP_PADDING": "1", + "OMP_NUM_THREADS": "4", + } + assert serving.EXPERT_PARALLEL_LINK == link + assert {name: value for name, value in serving.environment( + {"expert_parallel": True, "row_owned_prefill": True}).items() if name in link} == link + # Each switch alone keeps libsircl's defaults: the sweep measured the pairing. + for settings in ({"expert_parallel": True}, {"row_owned_prefill": True}): + assert not set(serving.environment(settings)) & set(link) + + +def test_expert_parallel_needs_the_pinned_image_the_deepseek_checkpoint_and_libsircl(): + serving.check_expert_parallel({"expert_parallel": True}, EXPERIMENT, PINNED, {"backend": "libsircl"}) + # A deployment without the switch is not checked against the experiment's conditions. + serving.check_expert_parallel({"max_images": 2}, EXPERIMENT, PINNED, {"backend": "sircl"}) + for settings, model, image, transport, message in ( + ({"expert_parallel": True}, (serving.ROW_OWNED_PREFILL_PROFILE, "original"), PINNED, {"backend": "libsircl"}, + "--expert-parallel requires --profile deepseek-v41-flash-tp4 --checkpoint 1017"), + ({"expert_parallel": True}, EXPERIMENT, {"image_id": "sha256:" + "0" * 64}, {"backend": "libsircl"}, + f"--expert-parallel requires --image {serving.ROW_OWNED_PREFILL_IMAGE}"), + ({"expert_parallel": True}, EXPERIMENT, None, {"backend": "libsircl"}, "--expert-parallel requires --image"), + ({"expert_parallel": True}, EXPERIMENT, PINNED, {"backend": "sircl"}, + "--expert-parallel requires --transport libsircl: the expert-parallel MoE build runs in libsircl's vLLM " + "plugin"), + ({"expert_parallel": True}, EXPERIMENT, PINNED, None, "--expert-parallel requires --transport libsircl"), + ({"expert_parallel": True, "chain_all_gather": True}, EXPERIMENT, PINNED, {"backend": "libsircl"}, + "--chain-all-gather selects SIRCL's own all-gather schedule, which a libsircl deployment does not run"), + ): + with pytest.raises(ValueError, match=message): + serving.check_expert_parallel(settings, model, image, transport) + + +def test_expert_parallel_moves_the_row_owned_prefill_from_sircl_to_libsircl(): + path = {"backend": "sircl", "nccl": "never", "group": {"name": "path-4", "dcp": 1}, "tuning": {"tables": []}} + row_owned = {"row_owned_prefill": True} + expert = {"expert_parallel": True} + serving.check_row_owned_prefill(row_owned, EXPERIMENT, PINNED, path) + serving.check_row_owned_prefill({**row_owned, **expert}, EXPERIMENT, PINNED, {"backend": "libsircl"}) + for settings, transport, message in ( + ({**row_owned, **expert}, path, "--row-owned-prefill with --expert-parallel requires --transport libsircl"), + ({**row_owned, **expert, "chain_all_gather": True}, {"backend": "libsircl"}, + "--chain-all-gather selects SIRCL's own all-gather schedule, which a libsircl deployment does not run"), + ({**row_owned, **expert, "context_length": 262145}, {"backend": "libsircl"}, + "--row-owned-prefill supports --context-length up to 262144 tokens"), + ): + with pytest.raises(ValueError, match=message): + serving.check_row_owned_prefill(settings, EXPERIMENT, PINNED, transport) + + +def test_expert_parallel_is_an_install_option_and_not_a_compose_setting(): + import argparse + install = argparse.ArgumentParser() + serving.add_arguments(install, install=True) + assert serving.from_arguments(install.parse_args(["--expert-parallel"])) == {"expert_parallel": True} + assert serving.from_arguments(install.parse_args([])) == {} + with pytest.raises(SystemExit): + install.parse_args(["--expert-parallel", "yes"]) + # A deployment that does not run the installer takes no install switch. + rendered = argparse.ArgumentParser() + serving.add_arguments(rendered) + with pytest.raises(SystemExit): + rendered.parse_args(["--expert-parallel"]) + + def test_experimental_overrides_are_loaded_declaratively_with_backward_compatible_aliases(): overrides = serving.experimental_overrides() assert serving.ROW_OWNED_PREFILL in overrides @@ -370,4 +462,3 @@ def test_experimental_overrides_are_loaded_declaratively_with_backward_compatibl assert serving.engine_adapter("vllm").name == "vllm" assert serving.engine_adapter("sglang").name == "sglang" assert serving.engine_adapter("generic").name == "generic" - diff --git a/runtime/host/install_workflow.py b/runtime/host/install_workflow.py index 8fa30074..d7470edb 100644 --- a/runtime/host/install_workflow.py +++ b/runtime/host/install_workflow.py @@ -707,6 +707,8 @@ def select_deployment(args, cluster, state_root, *, mesh_hint="", placement=None try: serving_settings.check_row_owned_prefill(serving_settings.from_arguments(args), (profile, card["target_variant"]), view, choice["section"]) + serving_settings.check_expert_parallel(serving_settings.from_arguments(args), (profile, card["target_variant"]), + view, choice["section"]) except ValueError as error: raise NeedsInput(str(error), field="serving") from None notice = image_lock.checkpoint_notice(image, profile, card, @@ -1911,6 +1913,8 @@ def main(argv=None): parser.error("--row-owned-prefill requires a SparkRing installer image name") if stock and args.serving_chain_all_gather: parser.error("--chain-all-gather requires --row-owned-prefill on a SparkRing installer image") + if stock and args.serving_expert_parallel: + parser.error("--expert-parallel requires a SparkRing installer image name") if vllm_arguments and not stock: parser.error("arguments after -- are a stock image's vLLM arguments: use them with --image REF") if args.ring_only and args.transport != transports.LIBSIRCL: diff --git a/runtime/host/test_install_sircl.py b/runtime/host/test_install_sircl.py index b16b9245..347aaf17 100644 --- a/runtime/host/test_install_sircl.py +++ b/runtime/host/test_install_sircl.py @@ -141,7 +141,14 @@ def test_the_nccl_transport_installs_on_a_pair_without_sircl(machine, capsys): assert json.loads(capsys.readouterr().out)["field"] == "transport" -def test_row_owned_prefill_is_a_locked_deepseek_sircl_experiment(machine, sparks, monkeypatch, capsys, tmp_path): # noqa: F811 +def four_spark_path(shell, monkeypatch): + """The surveyed four-Spark path the DeepSeek experiment runs on, with its fabric document recorded. + + ``shell`` is the test's simulated Sparks SSH boundary (the ``sparks`` + fixture). Its two end Sparks have their closing link down, so the arc is a + path rather than a cycle; sparks 1 and 2 need the hairpin setting, and + every Spark joins the managed mesh the four-Spark profiles refer to. + """ found = nodes(4) for rank, direction in ((0, "ccw_"), (3, "cw_")): closing_link = {port["netdev"] for role, port in topology.endpoints(found[rank]).items() @@ -159,9 +166,14 @@ def test_row_owned_prefill_is_a_locked_deepseek_sircl_experiment(machine, sparks monkeypatch.setattr(controller, "collect", lambda _: value["plan"]["nodes"]) fabric_record, _ = fabric.prepare(value["plan"], cluster="test", marker=MARKER) (controller.STATE / "fabric.json").write_text(fabric_document.encoded(fabric_record)) - sparks.mesh = lambda rank: {"reference": {"site_path": "/etc/sparkring/managed-mesh/site.json", - "site_sha256": "c" * 64, "plan_sha256": "d" * 64}, - "host_ip": f"192.0.2.{110 + rank}", "interface": "eth0", "unit": "sparkring-mesh.service"} + shell.mesh = lambda rank: {"reference": {"site_path": "/etc/sparkring/managed-mesh/site.json", + "site_sha256": "c" * 64, "plan_sha256": "d" * 64}, + "host_ip": f"192.0.2.{110 + rank}", "interface": "eth0", + "unit": "sparkring-mesh.service"} + + +def test_row_owned_prefill_is_a_locked_deepseek_sircl_experiment(machine, sparks, monkeypatch, capsys, tmp_path): # noqa: F811 + four_spark_path(sparks, monkeypatch) request = ["install", "--profile", "deepseek-v41-flash-tp4", "--checkpoint", "1017", "--image", serving.ROW_OWNED_PREFILL_IMAGE, "--transport", "sircl", "--nccl", "never", "--plan", "--json"] @@ -264,6 +276,86 @@ def test_row_owned_prefill_is_a_locked_deepseek_sircl_experiment(machine, sparks assert len(sparks.surveys) == surveyed +def test_expert_parallel_is_a_locked_deepseek_libsircl_experiment(machine, sparks, monkeypatch, capsys, # noqa: F811 + tmp_path): + """TP4+EP4 runs on the pinned image's libsircl layer, alone and with the row-owned prefill (R1).""" + four_spark_path(sparks, monkeypatch) + request = ["install", "--profile", "deepseek-v41-flash-tp4", "--checkpoint", "1017", + "--image", serving.ROW_OWNED_PREFILL_IMAGE, "--transport", "libsircl", "--plan", "--json"] + + assert sparkring.main(request) == 0 + plain = json.loads(capsys.readouterr().out) + assert "expert_parallel" not in (plain.get("serving") or {}) + base = deployment(plain)["transport"] + assert base["backend"] == "libsircl" and base["group"]["name"] == "path-4" + + assert sparkring.main([*request, "--expert-parallel"]) == 0 + alone = json.loads(capsys.readouterr().out) + assert alone["serving"] == {"expert_parallel": True} and alone["deployment"] != plain["deployment"] + assert "--expert-parallel" in alone["checkpoint"]["command"] + plain_specs = installer.specifications(deployment(plain)) + for base_spec, spec in zip(plain_specs, installer.specifications(deployment(alone)), strict=True): + assert spec.command[spec.command.index("--load-format") + 1] == "auto" + assert base_spec.command[base_spec.command.index("--load-format") + 1] == "b12x" + assert spec.command[-3:] == ("--enable-expert-parallel", "--all2all-backend", "allgather_reducescatter") + assert spec.command.count("--disable-custom-all-reduce") == 1 + assert spec.environment["SIRCL_B12X_EP_MOE"] == "1" and "SIRCL_B12X_EP_MOE" not in base_spec.environment + assert spec.environment["VLLM_PLUGINS"].split(",") == [ + name for name in base_spec.environment["VLLM_PLUGINS"].split(",") if name != "b12x_loader"] + assert "DS41_ROW_SHARD_PREFILL" not in spec.environment + # Expert parallelism alone keeps base/libsircl defaults. + for name in serving.EXPERT_PARALLEL_LINK: + assert spec.environment.get(name) == base_spec.environment.get(name) + assert base_spec.environment.get(name) != serving.EXPERT_PARALLEL_LINK[name] + assert [mount.target for mount in spec.mounts] == [mount.target for mount in base_spec.mounts] + + assert sparkring.main([*request, "--expert-parallel", "--row-owned-prefill"]) == 0 + combined = json.loads(capsys.readouterr().out) + assert combined["serving"] == {"expert_parallel": True, "row_owned_prefill": True} + assert combined["deployment"] not in (plain["deployment"], alone["deployment"]) + r1 = deployment(combined) + assert "--expert-parallel" in combined["checkpoint"]["command"] and "--row-owned-prefill" in ( + combined["checkpoint"]["command"]) + for rank, (base_spec, spec) in enumerate(zip(plain_specs, installer.specifications(r1), strict=True)): + plugins = spec.environment["VLLM_PLUGINS"].split(",") + assert plugins == [*[name for name in base_spec.environment["VLLM_PLUGINS"].split(",") + if name != "b12x_loader"], "ds41_row_shard"] + assert plugins[-2:] == ["libsircl", "ds41_row_shard"] + assert "b12x_loader" not in plugins + assert spec.environment["PYTHONPATH"].split(":") == [ + "/opt/ds41_row_shard", "/opt/sparkring/toolchain/python", "/opt/sparkring/addons/python"] + for flag in ("DS41_ROW_SHARD_PREFILL", "DS41_ROW_SHARD_INDEXER", "DS41_ROW_SHARD_COMPACT_ROUTES", + "DS41_ROW_SHARD_LOCAL_QUERIES", "DS41_ROW_SHARD_KV_LATENTS", "DS41_ROW_SHARD_COMPRESSOR_LATENTS"): + assert spec.environment[flag] == "1" + # The link geometry the transport sweep measured on this deployment. + assert {name: spec.environment[name] for name in serving.EXPERT_PARALLEL_LINK} == serving.EXPERT_PARALLEL_LINK + assert (spec.mounts[-2].target, spec.mounts[-2].read_only) == ("/opt/ds41_row_shard", True) + assert spec.mounts[-1].target.endswith("sparkring_sircl/vllm/adapter.py") + # The libsircl layer's own settings survive the serving settings. + assert spec.environment["SPARKRING_LIBSIRCL_LIBRARY"] == r1["transport"]["libsircl"]["library"]["path"] + assert spec.environment["LIBSIRCL_FAIL_STOP"] == "1" + assert spec.command[spec.command.index("--max-model-len") + 1] == "262144" + assert json.loads(spec.command[spec.command.index("--compilation-config") + 1])["cudagraph_mode"] == "FULL_DECODE_ONLY" + + # A shareable template repeats the install command, with the transport the experiment runs on. + output = tmp_path / "template.zip" + installer.export(combined["deployment"], output, share=True) + with zipfile.ZipFile(output) as template: + readme = template.read("README.txt").decode() + assert "--transport libsircl --expert-parallel --row-owned-prefill" in readme + assert "sircl --nccl never" not in readme + + surveyed = len(sparks.surveys) + for extra, complaint in ((["--transport", "sircl", "--nccl", "never"], "requires --transport libsircl"), + (["--checkpoint", "original"], "requires --profile deepseek-v41-flash-tp4"), + (["--context-length", "262145"], "up to 262144 tokens"), + (["--chain-all-gather"], "which a libsircl deployment does not run")): + assert sparkring.main([*request, "--expert-parallel", "--row-owned-prefill", *extra]) == 3 + refused = json.loads(capsys.readouterr().out) + assert refused["field"] == "serving" and complaint in refused["message"] + assert len(sparks.surveys) == surveyed + + def test_a_failed_receipt_check_is_reported_and_the_model_keeps_serving(sircl, monkeypatch, capsys): events, lock, _ = sircl failing = dict(VERDICT, verdict="differs", problems=["rank 1 group tp:0: 14 calls reached NCCL (['all_gather'])"]) diff --git a/spark_transport/libsircl/CMakeLists.txt b/spark_transport/libsircl/CMakeLists.txt index e184e3cf..d75333e1 100644 --- a/spark_transport/libsircl/CMakeLists.txt +++ b/spark_transport/libsircl/CMakeLists.txt @@ -84,7 +84,7 @@ foreach(target transport_hw transport_emu) add_dependencies(${target} vendored_sources_guard) endforeach() -add_library(sircl SHARED src/api.c src/bootstrap.c src/stubs.c src/aliases.c src/device_api.c src/fabric.c src/engine.c +add_library(sircl SHARED src/api.c src/bootstrap.c src/stubs.c src/aliases.c src/device_api.c src/engine.c src/cuda_api.c src/kernelpack.c $ $ $) target_compile_features(sircl PRIVATE c_std_11) @@ -124,10 +124,6 @@ add_custom_target(kernel_entries DEPENDS ${CMAKE_CURRENT_BINARY_DIR}/entries.ok) add_dependencies(sircl kernel_entries) enable_testing() -add_executable(test_fabric tests/test_fabric.c src/fabric.c) -target_include_directories(test_fabric PRIVATE include tests) -target_compile_options(test_fabric PRIVATE -Wall -Wextra -Werror) -add_test(NAME fabric COMMAND test_fabric) add_executable(test_link_plan tests/test_link_plan.c) target_include_directories(test_link_plan PRIVATE src) target_compile_options(test_link_plan PRIVATE -Wall -Wextra -Werror) @@ -142,7 +138,7 @@ add_test(NAME kernelpack_cache COMMAND ${CMAKE_COMMAND} -E env foreach(name abi api lifecycle engine_cpu build_flags) add_test(NAME ${name} COMMAND ${Python3_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/tests/test_${name}.py --library $) endforeach() -foreach(name bootstrap shm_verbs vendored_sources p2p_native site_routes mpi_shim check_nccl_tests source_snapshot docs_consistency teardown_race) +foreach(name bootstrap shm_verbs vendored_sources p2p_native site_routes mpi_shim check_nccl_tests source_snapshot docs_consistency teardown_race libsircl_hardening) add_test(NAME ${name} COMMAND ${Python3_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/tests/test_${name}.py) endforeach() add_test(NAME kernel_entries COMMAND ${Python3_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/tests/test_kernel_entries.py diff --git a/spark_transport/libsircl/Makefile b/spark_transport/libsircl/Makefile index 94984f32..e37b7bb8 100644 --- a/spark_transport/libsircl/Makefile +++ b/spark_transport/libsircl/Makefile @@ -17,11 +17,11 @@ override CFLAGS += -fstack-protector-strong override CPPFLAGS += -U_FORTIFY_SOURCE -D_FORTIFY_SOURCE=2 HARDENING_LDFLAGS = -Wl,-z,relro,-z,now,-z,noexecstack -# The library: API layer, bootstrap, fabric arithmetic, session engine, CUDA +# The library: API layer, bootstrap, session engine, CUDA # driver loader and the embedded kernel packs, plus SIRCL's native proxy and # SIRCL's point-to-point native library, each twice: over the real libibverbs # (loaded at run time) and over the shared-memory verbs stand-in (emulation). -SOURCES = src/api.c src/bootstrap.c src/stubs.c src/aliases.c src/device_api.c src/fabric.c src/engine.c src/cuda_api.c \ +SOURCES = src/api.c src/bootstrap.c src/stubs.c src/aliases.c src/device_api.c src/engine.c src/cuda_api.c \ src/kernelpack.c TRANSPORT_HW = src/transport/proxy_hw.c src/transport/p2p_hw.c src/transport/verbs_dl.c TRANSPORT_EMU = src/transport/proxy_emu.c src/transport/p2p_emu.c src/transport/shm_verbs.c @@ -177,17 +177,14 @@ $(BUILD)/mpi-shim/lib/libmpi.so: tools/mpi-shim/mpi_shim.c tools/mpi-shim/includ cp tools/mpi-shim/include/mpi.h $(BUILD)/mpi-shim/include/mpi.h $(CC) -std=c11 -O2 -fPIC -Wall -Wextra -Werror -shared -pthread -Itools/mpi-shim/include -o $@ tools/mpi-shim/mpi_shim.c -$(BUILD)/test_fabric: tests/test_fabric.c $(BUILD)/fabric.o - $(CC) $(CPPFLAGS) $(CFLAGS) $^ -o $@ $(BUILD)/test_link_plan: tests/test_link_plan.c src/link_plan.h | $(BUILD) $(CC) $(CPPFLAGS) $(CFLAGS) $< -o $@ $(BUILD)/test_kernelpack_cache: tests/test_kernelpack_cache.c $(BUILD)/kernelpack.o $(BUILD)/cuda_api.o \ $(BUILD)/kernels_fatbin.o $(BUILD)/fold_fatbin.o $(BUILD)/links_fatbin.o \ $(BUILD)/p2p_fatbin.o $(CC) $(CPPFLAGS) $(CFLAGS) $^ -o $@ -ldl -check: all $(BUILD)/test_fabric $(BUILD)/test_link_plan $(BUILD)/test_kernelpack_cache +check: all $(BUILD)/test_link_plan $(BUILD)/test_kernelpack_cache @status=0; \ - $(BUILD)/test_fabric || status=1; \ $(BUILD)/test_link_plan || status=1; \ LD_LIBRARY_PATH=$(abspath $(BUILD)/fake-cuda) $(BUILD)/test_kernelpack_cache || status=1; \ $(PYTHON) tests/test_abi.py --library $(abspath $(BUILD)/libsircl.so) || status=1; \ @@ -204,6 +201,7 @@ check: all $(BUILD)/test_fabric $(BUILD)/test_link_plan $(BUILD)/test_kernelpack $(PYTHON) tests/test_kernel_entries.py --build $(BUILD) || status=1; $(PYTHON) tests/test_build_flags.py --library $(abspath $(BUILD)/libsircl.so) || status=1; $(PYTHON) tests/test_source_snapshot.py || status=1; \ $(PYTHON) tests/test_docs_consistency.py || status=1; \ $(PYTHON) tests/test_teardown_race.py || status=1; \ + $(PYTHON) tests/test_libsircl_hardening.py || status=1; \ exit $$status # The check suites against a host library built with AddressSanitizer and UndefinedBehaviorSanitizer in diff --git a/spark_transport/libsircl/README.md b/spark_transport/libsircl/README.md index 86997c74..b73abcf4 100644 --- a/spark_transport/libsircl/README.md +++ b/spark_transport/libsircl/README.md @@ -130,9 +130,18 @@ session's sequence, so pairs proceed independently while other ranks idle. Each has a stream of its own, so a receive waiting for its peer holds back only later items of its own channel; a group's sends are queued before its receives, each channel stream starts after the caller's stream reached the group, and the caller's stream then waits for every channel stream the group used. A buffer that is -not 16-byte aligned, or a size that is not whole 16-byte packs, goes through staging. Channel items are not -captured in CUDA graphs (a replay would reuse item numbers fixed at enqueue): such a call is refused with -`ncclInvalidUsage`. A pair has a channel when every lane between them in both directions is direct or +not 16-byte aligned, or a size that is not whole 16-byte packs, goes through staging. Channel items are +capturable in CUDA graphs: each channel direction advances its item counter in device memory at replay +time (via an atomic counter update on the GPU), so replays advance through the channel's slots without +reusing item numbers fixed at enqueue; unaligned or non-pack sizes under capture use stream-ordered +staging allocations on the channel stream (forked from and joined back to the capturing stream with +graph events). On communicators with point-to-point channels, the SIRCL-EP extension +(`sirclEpWorkspaceBytes`, `sirclEpDispatch`, `sirclEpCombine`) carries GPU-driven dynamic +variable-length MoE token dispatch and combine over the same RDMA channels and arena: dispatch computes +per-peer token counts on the GPU, sends variable-length payloads only to peers that receive tokens (with +zero RDMA payload bytes for local-only routing), and combine scatters expert outputs back to each source +rank with top-k weighted reduction, both capturable in CUDA graphs with routing that changes on every +replay; receipts record EP dispatch and combine counts under `channels.ep`. A pair has a channel when every lane between them in both directions is direct or has a point-to-point window (`LIBSIRCL_P2P_WINDOWS`, which `tools/site_routes.py` prints from SIRCL's point-to-point budget): relayed lanes post within their windows, and a pair without one is refused on both ranks, naming the lane. A kernel that times out or meets a message of another size, or a failure to enqueue @@ -362,7 +371,7 @@ all-gather and the fold pack, so the link and pair settings do not reach them. windows and ring plan from SIRCL's route planner for a layout such as `path:0-3` or `ring:8`. Extension API (`include/sircl.h`), exported by exact name: `sirclGetInfo`, `sirclSetWaitRegime`, -`sirclGetReceipt`. +`sirclGetReceipt`, `sirclEpWorkspaceBytes`, `sirclEpDispatch`, `sirclEpCombine`. ## Sources, licences and boundaries diff --git a/spark_transport/libsircl/STATUS.md b/spark_transport/libsircl/STATUS.md index cd6ef0e6..f51af2be 100644 --- a/spark_transport/libsircl/STATUS.md +++ b/spark_transport/libsircl/STATUS.md @@ -56,7 +56,7 @@ The interface follows NVIDIA's public `nccl.h.in` v2.32.3-1 and the user guide o | Component | Status | Evidence | |---|---|---| -| Symbol surface: 73 `ncclX` host functions and 73 `pnccl` twins of the 2.32.3 header, and the 16 host entry points of NCCL's device API (`nccl_device/core.h` and its barrier and LL all-to-all headers, NCCL 2.28 and later) with their twins, which programs built against current headers import (`src/device_api.c`: `ncclCommQueryProperties` and the team queries implemented, the device communicator, device pointers and requirement builders refused); SONAME `libnccl.so.2`, version 22705; only `nccl*`, `pnccl*` and the three extension functions `sirclGetInfo`, `sirclSetWaitRegime` and `sirclGetReceipt` exported, each by exact name; `tests/api_manifest.json` marks each function of the header implemented or not; `tools/check_exports.py` lists any function a header set declares or a program imports that the library lacks | implemented | ABI suite; engine suite's device-API test; generator check; `tools/check_exports.py`: 0 missing against the NCCL 2.29.7 headers and the nccl-tests v2.21.1 binaries built on the workstation; PyTorch and vLLM bind to it (`verification/framework-loading.json`) | +| Symbol surface: 73 `ncclX` host functions and 73 `pnccl` twins of the 2.32.3 header, and the 16 host entry points of NCCL's device API (`nccl_device/core.h` and its barrier and LL all-to-all headers, NCCL 2.28 and later) with their twins, which programs built against current headers import (`src/device_api.c`: `ncclCommQueryProperties` and the team queries implemented, the device communicator, device pointers and requirement builders refused); SONAME `libnccl.so.2`, version 22705; only `nccl*`, `pnccl*` and the six extension functions `sirclGetInfo`, `sirclSetWaitRegime`, `sirclGetReceipt`, `sirclEpWorkspaceBytes`, `sirclEpDispatch` and `sirclEpCombine` exported, each by exact name; `tests/api_manifest.json` marks each function of the header implemented or not; `tools/check_exports.py` lists any function a header set declares or a program imports that the library lacks | implemented | ABI suite; engine suite's device-API test; generator check; `tools/check_exports.py`: 0 missing against the NCCL 2.29.7 headers and the nccl-tests v2.21.1 binaries built on the workstation; PyTorch and vLLM bind to it (`verification/framework-loading.json`) | | Kernel-entry check: before the library links, its pack loader resolves every entry it names in the four embedded packs through a stand-in CUDA driver that reads every architecture's cubin offline (`tests/check_entries.c`, `tests/fake_cuda.c`; make and CMake) | implemented | kernel-entry suite (3 tests: every entry present; hiding one entry of each pack fails and names it; refused without the stand-in driver); a loader that names the two-pass ring all-reduce entries, built with link pack `5935b067...` (which has none), fails the build at `sircl_ring_reduce_two_pass_f32_u1` | | Loading: the library links only libc and the dynamic loader, has no constructor that touches CUDA, and opens `libcuda.so.1` only when a communicator is created | implemented | CPU test in an isolated interpreter, with a negative control that initializes CUDA in a constructor; `tools/probe_cuda_on_load.py` (`verification/cuda-on-load.json`) | | Bootstrap: unique id with root address, port, nonce and site hash; loopback, or a LAN address from `SIRCL_BOOTSTRAP_ADDR`, `SIRCL_BOOTSTRAP_IFNAME` or `NCCL_SOCKET_IFNAME`; all-gather rounds through the root; a rank leaving a complete group fails every later round at once | implemented | bootstrap suite; between the two Sparks of the pair (hardware evidence) | @@ -93,7 +93,8 @@ The interface follows NVIDIA's public `nccl.h.in` v2.32.3-1 and the user guide o | Fail-stop (`LIBSIRCL_FAIL_STOP=1` or `abort`, per process): at the first asynchronous error (a flag wait that timed out, a failed progress thread, a failed point-to-point channel) of a watched communicator of two or more ranks, found by the watcher thread (every `LIBSIRCL_FAIL_STOP_POLL_MS`, default 5) or by the first library call that would report it (`ncclCommGetAsyncError`, an enqueue's check, `ncclCommFinalize`, `ncclCommDestroy`, `ncclCommAbort`), the library writes the error, the time and what found it to stderr and the communicator's receipt, then ends the process, with `1` at once (exit status 70, no atexit handlers, no core dump), with `abort` by `abort()`; destroy and abort check once more, then take the communicator off the watch before releasing it, and library unload stops the watcher first | implemented | Conditions: the workstation, `tests/emulation/fail_stop.py`, two ranks, SIRCL_STARTUP_WAIT_S 2, rank 1 starting its second all-reduce 12 s late, rank 0 enqueuing its own at once, waiting for its stream, keeping the output and calling the library no more. Measurement (library `638cca1b...`, every time CLOCK_MONOTONIC): 15 runs of the exit and control cases and one of all three: with `1`, the fail-stop line 2.11 to 2.13 s and the process's end 2.43 to 2.53 s after the enqueue, exit status 70; with `abort`, the line 2.11 s after the enqueue and SIGABRT 20.8 s after it (WSL's crash capture ran first); without fail-stop, rank 0's stream wait returned 2.10 to 2.13 s after the enqueue with a wrong output, every call it made returned 0, and the process ran on past 7 s. With `LIBSIRCL_FAIL_STOP=1` the pair default's 533 library checks passed and no process ended; on a build of the same fail-stop code, so did the ring schedules' 989 checks on four ranks and 10 teardown rounds on four ranks. The wait limit itself (research build of this tree whose timed-out flag wait records its `%globaltimer` start and end and the limit it read): 34 timed-out 2 s waits lasted 2.00002 to 2.00095 s of `%globaltimer` with the limit read as 2,000,000 us; a 300 s kernel and five 10 s kernels that sampled `%globaltimer` every 1,024 polls showed no step beyond 11 ms (host-stamping jitter) and a rate of 0.943 to 0.948 of the workstation's CLOCK_MONOTONIC; the workstation's CLOCK_REALTIME stepped back by 1.2 to 1.7 s about every 30 s (WSL2's time synchronization), so two of 28 waits timed by the wall clock looked 0.40 s long while the kernel measured 2.0003 s; earlier runs of this check that used the wall clock showed the same. On the fabric (cabled pair at positions 6-7, snapshot 0f94c72b, 2026-10-09; `teardown_race.py`, rank 1 starting its child all-reduce 8 s late, SIRCL_STARTUP_WAIT_S 2): with `1`, rank 0 exited with status 70 3.9 s after it started, setup included, its fail-stop line naming the timed-out flag wait for the late rank; without fail-stop it exited 1 after 10.4 s with the round reported failed. Library calls (this tree, library `9776657f...`, GPU emulation, 2026-10-09, `verification/emulation/suite-s1/`): `fail_stop.py`'s cases in which rank 0 calls `ncclCommGetAsyncError`, `ncclCommDestroy` or `ncclCommAbort` right after its stream wait, with `LIBSIRCL_FAIL_STOP_POLL_MS=600000` so the watcher does not poll, end rank 0 with status 70 inside the call (2.31 to 2.38 s after the enqueue, the line 2.00 s after it, "found by a library call" or "found by ncclCommDestroy or ncclCommAbort"), the call never returning; against the library before this path the same cases had `ncclCommGetAsyncError` and `ncclCommAbort` return the error to rank 0, which ran on and exited 0. `teardown_race.py --expect fail-stop`, four ranks, rank 3's child all-reduce 8 s late, 2 s wait limit: every rank exited 70 in 6 of 6 runs; in 9 of the 15 non-late exits of 5 runs a library call found the error before the watcher (the gate's path of four lost one rank that way before this path). Conclusion: with fail-stop, a caller that checks only enqueue codes keeps a failed collective's output at most for the wait limit plus one poll; a read within that poll after its stream wait returns is not prevented | | `ncclCommSuspend` and `ncclCommResume` | unsupported | refused with `ncclInvalidUsage` (logged once); a communicator's arena and device memory stay allocated while it exists | | Point-to-point between two ranks of a communicator of three or more ranks on SIRCL's point-to-point channels (`LIBSIRCL_P2P_CHANNELS=on`, off by default; README.md, "Point-to-point channels"): SIRCL's native point-to-point library vendored byte-identical (`src/transport/sircl_p2p_proxy.c`, `c8ccfcb9...`, SIRCL 0.3.2's copy with change LF, checked by the build, its symbols prefixed per transport and not exported), created inside the communicator's setup exchanges (each rank's lanes and `LIBSIRCL_P2P_WINDOWS` give a channel table every rank derives alike; connection records validated together; lane check; windows of relayed lanes), first-in first-out matching per ordered pair, one stream per channel direction joined to the caller's stream, sends queued before receives, staging of messages not 16-byte aligned or not whole packs (stream-ordered allocation, or each channel's own buffer), refusal on both ranks of a pair without a channel, asynchronous errors and fail-stop on every rank after a kernel's timeout or size mismatch (abort notices), the channels' progress thread stopped in the teardown rounds and their verbs objects counted at destroy, receipts (`channels`) | implemented | GPU emulation on the workstation (below, "Point-to-point channels"): four and eight ranks, ring:8 under the route planner's settings, torch initialized eagerly, nccl-tests' sendrecv, hypercube and alltoallv on four processes; CPU: the native library across processes over the verbs stand-in. Sparks: the path of four and the cycle of eight with channels on, snapshot a3477af2 (hardware evidence below) | -| Point-to-point channel items under CUDA graph capture | unsupported | refused with `ncclInvalidUsage`: a replay would reuse the item numbers fixed at enqueue | +| Point-to-point channel items under CUDA graph capture: device-side atomic per-channel item counters advance on every replay without reusing enqueue-time item numbers; aligned buffers run zero-copy and unaligned/non-pack sizes use stream-ordered staging allocations on the channel stream joined to the capturing stream by graph events | implemented | Ring of four Sparks (positions 4-7, `libsircl.so.0.6.0` `8005169b...`): captured grouped `ncclSend`/`ncclRecv` replayed with mutated payloads bit-exact and `all_reduce.captured_calls` recorded in receipts; GPU emulation on GB10 (`tests/emulation/p2p_channels.py --world 4 --case graph`): 32/32 checks passed (0 failed, 10 replays with mutated inputs bit-exact) | +| SIRCL-EP dynamic variable-length MoE token dispatch and combine (`sirclEpWorkspaceBytes`, `sirclEpDispatch`, `sirclEpCombine`, in the point-to-point kernel pack `kernels/sircl_p2p.cu` over `LIBSIRCL_P2P_CHANNELS=on` and unmodified `sircl_p2p_proxy.c`): GPU-driven dynamic routing, variable-length per-peer payloads (zero RDMA payload bytes on all-local routing), top-k weighted combine reduction, CUDA graph capture with dynamic per-replay routing, and `channels.ep` receipt counters | implemented | Ring of four Sparks (positions 4-7, `libsircl.so.0.6.0` `8005169b...`): CUDA-graph microbenchmark (`H=5120, BF16, E=384, K=6`): `B=1` 71.07 us (1.63x vs fixed P2P), `B=64` 298.13 us (1.14x vs fixed P2P), `B=128` 489.60 us (1.09x faster than AgRs 536.08 us, 1.27x faster than fixed P2P 619.87 us), bit-exact across dynamic routing replays and 0 RDMA payload bytes on all-local routing inside frozen CUDA graphs; GPU emulation on GB10 (`tests/emulation/p2p_channels.py --world 4 --case ep`): 40/40 checks passed (0 failed; bf16/fp16/fp32 asymmetric, all-local, and 8 dynamic-routing CUDA graph replays); end-to-end vLLM serving on DeepSeek-V4.1-Flash-1017 (`DP4+EP4`, no-spec, `cudagraph_capture_sizes=[1,2,4,8,16]`, `SIRCL_B12X_EP_MOE=1`, `SIRCL_EP_ALL2ALL=1`): decode `cc=1/4/8/16` = 17.96 / 52.16 / 91.32 / 163.72 tok/s (+15.8% / +8.3% / +7.2% / +12.8% over DP4+EP4 `AgRs` at 15.51 / 48.17 / 85.22 / 145.12 tok/s), prefill `26.8K/111.2K` = 2,030.5 / 2,062.7 tok/s, exact sanity outputs, all 4 rank receipts `healthy=True`, `err=None`, `captured=1440`, `ep={dispatches: 2581, combines: 2580}`, 5.12 GB across 996,733 RDMA writes | | Point-to-point channels created at the first `ncclSend` or `ncclRecv` | unsupported | connecting the channels is collective over every rank, and a first send involves two; the channels are created with the communicator when `LIBSIRCL_P2P_CHANNELS=on`, and a communicator without them holds none of their memory, queue pairs or thread | | Point-to-point windows of the route planner (`tools/site_routes.py`, SIRCL's `p2p/budget.py`): `--p2p-reserve session` reserves the collective session's forward windows first, and its ring windows only with `--ring-schedules` (libsircl's ring lanes carry traffic only under the ring schedules); `--session-share F` (default 1) sizes the session's forward and ring windows against F of every relay queue's share and gives the channels the rest; a relayed pair without a window on every lane in both directions has no channel, named in the JSON output | implemented | CPU (`tests/test_site_routes.py`, 8 tests, with `SIRCL_PACKAGE` naming the SIRCL reference tree's `spark_transport/sircl`): path:4-7 gives all 6 relayed ordered pairs a window without `--ring-schedules` and leaves 3 without one with it (rank 3's 393,216-byte ring window reserved); ring:8 leaves all 40 without one at the default plan and gives all 40 one with `--max-window 32768` and with `--session-share` 0.95, 0.5 and 0.25 (at 0.95 every relayed session lane one 32 KiB chunk smaller, the channels' windows 32 KiB); a share of 1 prints the default's output; shares outside (0, 1] are refused; in every case no relay queue holds more than its 393,216-byte share (session plus channels), and `--p2p-reserve none` on ring:8, as the check's negative control, overfills one; the ring:8 files of `tests/data` equal the tool's output | | The setup check of the native proxy's local feature word (`roce_local_features`, SIRCL change LF): communicator setup fails on every rank, naming both bits, unless bit 0 (`roce_destroy` counts failed verbs calls) and bit 1 (flags-only own items, which the pair exchange without input uses) are set; the build refuses a vendored copy that differs from its recorded SHA-256 or does not define the word | implemented | CPU: the native probe reads bits 0 and 1 from the vendored copy (`tests/test_shm_verbs.py`); the library carries the check (`tests/test_engine_cpu.py`); a build against a modified copy, a copy with CRLF endings, or the copy before LF with its own hash, stops with the reason. GPU emulation: every communicator of the suite passed the check. Sparks: snapshots 0f94c72b and a3477af2 carry the check, and every communicator of their runs passed it (hardware evidence below) | diff --git a/spark_transport/libsircl/exports.map b/spark_transport/libsircl/exports.map index 958be5fd..42f1b5ae 100644 --- a/spark_transport/libsircl/exports.map +++ b/spark_transport/libsircl/exports.map @@ -1,4 +1,4 @@ { - global: nccl*; pnccl*; sirclGetInfo; sirclSetWaitRegime; sirclGetReceipt; + global: nccl*; pnccl*; sirclGetInfo; sirclSetWaitRegime; sirclGetReceipt; sirclEpWorkspaceBytes; sirclEpDispatch; sirclEpCombine; local: *; }; diff --git a/spark_transport/libsircl/include/sircl.h b/spark_transport/libsircl/include/sircl.h index e9bb596a..61b447dd 100644 --- a/spark_transport/libsircl/include/sircl.h +++ b/spark_transport/libsircl/include/sircl.h @@ -20,6 +20,18 @@ ncclResult_t sirclSetWaitRegime(ncclComm_t comm, const char *regime); * between a call that sizes it and the next: the output is whole only when * *needed <= length, and a caller retries with a larger buffer otherwise. */ ncclResult_t sirclGetReceipt(ncclComm_t comm, char *out, size_t length, size_t *needed); +/* SIRCL-EP: GPU-driven dynamic variable-length MoE token dispatch and combine over + * SIRCL's point-to-point channels. Zero CPU synchronization, zero wasted RDMA bytes, + * and CUDA-graph capturable. Requires a communicator of 3 to 8 ranks created with + * LIBSIRCL_P2P_CHANNELS=on and channels to every peer. */ +size_t sirclEpWorkspaceBytes(int world, int max_tokens, size_t hidden_bytes); +ncclResult_t sirclEpDispatch(const void *hidden_in, const int *topk_ids_in, const float *topk_weights_in, + void *hidden_out, int *topk_ids_out, float *topk_weights_out, int *recv_counts_out, + void *workspace, size_t workspace_bytes, int num_tokens, int max_tokens, + size_t hidden_bytes, int top_k, int num_experts, ncclComm_t comm, cudaStream_t stream); +ncclResult_t sirclEpCombine(const void *expert_out_in, void *hidden_out, void *workspace, size_t workspace_bytes, + int num_tokens, int max_tokens, size_t hidden_dim, ncclDataType_t datatype, + ncclComm_t comm, cudaStream_t stream); #ifdef __cplusplus } #endif diff --git a/spark_transport/libsircl/include/sircl_fabric.h b/spark_transport/libsircl/include/sircl_fabric.h deleted file mode 100644 index 637055f1..00000000 --- a/spark_transport/libsircl/include/sircl_fabric.h +++ /dev/null @@ -1,109 +0,0 @@ -#ifndef SIRCL_FABRIC_H -#define SIRCL_FABRIC_H - -/* Implemented offline planning. Hardware qualification is pending. */ -#include -#include - -#ifdef __cplusplus -extern "C" { -#endif - -#define SIRCL_FABRIC_MAX_WORLD 16 -#define SIRCL_FABRIC_MAX_LANES 2 -#define SIRCL_FABRIC_MAX_CABLES 16 -#define SIRCL_FABRIC_DEFAULT_MAX_RELAYS 3 -#define SIRCL_PROTOCOL_MAX_PHASES 8 -#define SIRCL_PROTOCOL_OP_BYTES_MASK UINT32_C(0x3fffffff) - -typedef struct { int code; char message[192]; } sircl_fabric_error; -enum { SIRCL_FABRIC_INVALID = 1, SIRCL_FABRIC_UNREACHABLE = 2, - SIRCL_FABRIC_MISMATCH = 3, SIRCL_FABRIC_LIMIT = 4 }; -/* The role value is port * 2 + secondary. Device names are case sensitive. */ -enum { SIRCL_CW_PRIMARY = 0, SIRCL_CW_SECONDARY = 1, - SIRCL_CCW_PRIMARY = 2, SIRCL_CCW_SECONDARY = 3 }; -typedef struct { int a, a_port, b, b_port; } sircl_cable; -typedef struct { int src, src_port, dst, dst_port; } sircl_fabric_step; -typedef struct { - int cable_count, node_count, world, cycle; - sircl_cable cables[SIRCL_FABRIC_MAX_CABLES]; - int nodes[SIRCL_FABRIC_MAX_WORLD], positions[SIRCL_FABRIC_MAX_WORLD]; -} sircl_fabric_layout; -typedef struct { - uint8_t count[SIRCL_FABRIC_MAX_WORLD]; - uint8_t role[SIRCL_FABRIC_MAX_WORLD][SIRCL_FABRIC_MAX_LANES]; -} sircl_route_map; -typedef struct { - int local_role, remote_role, hops; - sircl_fabric_step steps[SIRCL_FABRIC_MAX_WORLD]; -} sircl_lane_route; -typedef struct { - sircl_fabric_layout layout; - int lanes; - sircl_lane_route route[SIRCL_FABRIC_MAX_WORLD][SIRCL_FABRIC_MAX_WORLD][SIRCL_FABRIC_MAX_LANES]; -} sircl_fabric_routes; -typedef struct { - const char *local_error; - /* Canonical serialized shared settings only: no pointers, padding, or rank-local fields. */ - const void *shared_settings; - size_t shared_size; - sircl_route_map map; -} sircl_fabric_rank_record; -typedef struct { uint64_t first, count; } sircl_pack_range; -typedef struct { int first, end, peer, namespace_id; } sircl_phase; -enum { SIRCL_ALGORITHM_AUTO = -1, SIRCL_ALGORITHM_ONESHOT = 0, - SIRCL_ALGORITHM_TWOSHOT = 1, SIRCL_ALGORITHM_SWING = 2 }; - -/* Planning/encoding functions return 0 on success and -1 on error. Error is optional. - * Role getters return the role or name, or -1/NULL if unknown. Input bounds and - * wire encodings are checked. Output contents after an error are unspecified. */ -const char *sircl_fabric_role_device(int role); -int sircl_fabric_role_of(const char *device); -int sircl_fabric_layout_init(sircl_fabric_layout *out, const sircl_cable *cables, - int cable_count, const int *positions, int world, - sircl_fabric_error *error); -int sircl_fabric_layout_parse(const char *text, sircl_fabric_layout *out, sircl_fabric_error *error); -int sircl_fabric_derive(const sircl_fabric_layout *layout, int lanes, - sircl_fabric_routes *out, sircl_fabric_error *error); -int sircl_fabric_map(const sircl_fabric_routes *routes, int rank, - sircl_route_map *out, sircl_fabric_error *error); -int sircl_fabric_map_parse(const char *text, sircl_route_map *out, sircl_fabric_error *error); -int sircl_fabric_map_format(const sircl_route_map *map, int world, char *out, - size_t capacity, sircl_fabric_error *error); -int sircl_fabric_map_validate(const sircl_fabric_layout *layout, const sircl_route_map *map, - int rank, int world, int max_relays, sircl_fabric_error *error); -int sircl_fabric_complementary(const sircl_fabric_layout *layout, const sircl_route_map *maps, - sircl_fabric_error *error); -int sircl_fabric_agree(const sircl_fabric_layout *layout, int world, int lanes, - const sircl_fabric_rank_record *records, int max_relays, - sircl_fabric_error *error); -int sircl_fabric_post_order(const sircl_fabric_routes *routes, int rank, - const char *order, int *peers, sircl_fabric_error *error); -int sircl_fabric_relay_load(const sircl_fabric_routes *routes, int *busiest, - double *factor, sircl_fabric_error *error); -int sircl_fabric_forward_windows(const sircl_fabric_routes *routes, int rank, - uint64_t max_window, uint64_t chunk, uint64_t queue_bytes, - uint64_t out[SIRCL_FABRIC_MAX_WORLD][SIRCL_FABRIC_MAX_LANES], - sircl_fabric_error *error); -int sircl_fabric_chain_order(const sircl_fabric_routes *routes, int *order, - sircl_fabric_error *error); -int sircl_fabric_ring_window(const sircl_fabric_routes *routes, const int *order, - uint64_t chunk, uint64_t queue_bytes, uint64_t *window, - sircl_fabric_error *error); - -int sircl_protocol_stripe(uint64_t packs, int lanes, int lane, sircl_pack_range *out); -int sircl_protocol_chunk(uint64_t packs, int world, int index, sircl_pack_range *out); -int sircl_protocol_flag_index(int namespace_id, int source, int slot, int lane, - int world, int lanes, uint32_t *out); -int sircl_protocol_op_word(int op, uint32_t bytes, uint32_t *out); -int sircl_protocol_descriptor(const sircl_phase *phase, int world, uint32_t *out); -int sircl_protocol_swing(int world, int rank, int *owners, - sircl_phase phases[SIRCL_PROTOCOL_MAX_PHASES], int *phase_count); -int sircl_protocol_select(uint64_t bytes, int algorithm, int large_algorithm, - uint64_t oneshot_max, uint64_t swing_above, - unsigned available_mask, int *out); - -#ifdef __cplusplus -} -#endif -#endif diff --git a/spark_transport/libsircl/kernels/sircl_p2p.cu b/spark_transport/libsircl/kernels/sircl_p2p.cu index 4e8885ac..7a8803c7 100644 --- a/spark_transport/libsircl/kernels/sircl_p2p.cu +++ b/spark_transport/libsircl/kernels/sircl_p2p.cu @@ -59,13 +59,13 @@ constexpr uint32_t kNoLane = 255; constexpr uint32_t kLast = 1u << 31; constexpr uint32_t kPollsPerPoisonCheck = 64; -/* One launch: a message's packs, n % 16, the channel's first item, the message's items, the peer's block - * and the control line (device addresses), and the block offsets of the native layer's p2p_layout. Mirrors - * sccl_p2p_args of src/kernelpack.h (120 bytes). */ +/* One launch: a message's packs, n % 16, the message's items, the peer's block, the control line and the + * channel's device counter pair ({seq, arrival}, 8 bytes), and the block offsets of the native layer's + * p2p_layout. Mirrors sccl_p2p_args of src/kernelpack.h (120 bytes). */ struct P2PParams { - uint64_t data, block_base, ctrl_base, slot_bytes; + uint64_t data, block_base, ctrl_base, slot_bytes, counter_ptr; int32_t packs, tail, items, peer; - uint32_t first, slots, lanes, reserved; + uint32_t slots, lanes; uint64_t recv_off, send_off, flag_off, desc_off, ready_off, consumed_off, sent_off; }; static_assert(sizeof(P2PParams) == 120, "P2PParams must match sccl_p2p_args"); @@ -149,17 +149,37 @@ __device__ __forceinline__ uint32_t header_of(int32_t item, int32_t items, int32 return header; } +/* Advance the channel's device sequence counter once every block of this launch has finished reading it and + * completed its items, unless the context is poisoned. Each channel runs on its own stream, so successive + * launches (eager or CUDA-graph replayed) execute strictly in order. */ +__device__ __forceinline__ void advance_counter(int32_t thread, uint64_t counter_ptr, uint32_t first, int32_t items, + uint64_t poison) { + __syncthreads(); + if (thread == 0) { + fence_sc_gpu(); + const uint32_t done = atom_add_relaxed_gpu(counter_ptr + 4u, 1u) + 1u; + if (done == gridDim.x) { + st_release_gpu(counter_ptr + 4u, 0u); + if (ld_relaxed_sys(poison) == 0) st_release_gpu(counter_ptr, first + (uint32_t)items); + } + } +} + template __device__ __forceinline__ void send(const P2PParams &a) { __shared__ uint32_t poisoned; + __shared__ uint32_t s_first; const int32_t thread = (int32_t)threadIdx.x; const int32_t last_thread = (int32_t)blockDim.x - 1; + if (thread == 0) s_first = ld_acquire_gpu(a.counter_ptr); + __syncthreads(); + const uint32_t first = s_first; const uint64_t poison = a.ctrl_base + 4 * kPoison; const uint32_t limit_us = ld_relaxed_sys(a.ctrl_base + 4 * kWaitLimitUs); const int32_t slot_packs = (int32_t)(a.slot_bytes / kPackBytes); int32_t item = (int32_t)blockIdx.x; while (item < a.items) { - const uint32_t g = a.first + (uint32_t)item; + const uint32_t g = first + (uint32_t)item; const uint32_t m = g % a.slots; const uint32_t tag = g + 1u; if (thread == last_thread && @@ -184,18 +204,23 @@ __device__ __forceinline__ void send(const P2PParams &a) { } item += (int32_t)gridDim.x; } + advance_counter(thread, a.counter_ptr, first, a.items, poison); } template __device__ __forceinline__ void recv(const P2PParams &a) { __shared__ uint32_t poisoned; + __shared__ uint32_t s_first; const int32_t thread = (int32_t)threadIdx.x; + if (thread == 0) s_first = ld_acquire_gpu(a.counter_ptr); + __syncthreads(); + const uint32_t first = s_first; const uint64_t poison = a.ctrl_base + 4 * kPoison; const uint32_t limit_us = ld_relaxed_sys(a.ctrl_base + 4 * kWaitLimitUs); const int32_t slot_packs = (int32_t)(a.slot_bytes / kPackBytes); int32_t item = (int32_t)blockIdx.x; while (item < a.items) { - const uint32_t g = a.first + (uint32_t)item; + const uint32_t g = first + (uint32_t)item; const uint32_t m = g % a.slots; const uint32_t tag = g + 1u; const uint64_t line = a.block_base + a.flag_off + (uint64_t)m * a.lanes * kLine; @@ -227,6 +252,7 @@ __device__ __forceinline__ void recv(const P2PParams &a) { } item += (int32_t)gridDim.x; } + advance_counter(thread, a.counter_ptr, first, a.items, poison); } } // namespace sircl_p2p @@ -249,3 +275,599 @@ SIRCL_P2P_ENTRIES(5) SIRCL_P2P_ENTRIES(6) SIRCL_P2P_ENTRIES(7) SIRCL_P2P_ENTRIES(8) + +/* ====================================================================================================== + * SIRCL-EP: GPU-driven dynamic variable-length MoE token Dispatch & Combine over SIRCL's P2P channels. + * + * Uses the exact same wire protocol and unmodified sircl_p2p_proxy.c: + * - desc_off[m] holds `(chunk_bytes & kBytesMask) | (is_last ? kLast : 0)` + * - sircl_p2p_proxy.c RDMA-writes ONLY `chunk_bytes` (0 data bytes when chunk_bytes == 0!) plus + * the 4-byte header into peer's flag_line + 4 and the 4-byte tag into every lane's flag line. + * - Zero CPU synchronization, zero wasted RDMA bytes, 100% CUDA-graph capturable, single fused launch + * across all peers (no per-channel stream fork/join overhead). + * ====================================================================================================== */ +namespace sircl_ep { + +using namespace sircl; +using namespace sircl_p2p; + +constexpr int kMaxWorld = 8; +constexpr int kEpThreads = 256; +constexpr uint32_t kBytesMask = ((1u << 30) - 1u) & ~15u; + +struct EpParams { + uint64_t hidden_in; + uint64_t topk_ids_in; + uint64_t topk_weights_in; + uint64_t hidden_out; + uint64_t topk_ids_out; + uint64_t topk_weights_out; + uint64_t recv_counts_out; + uint64_t workspace; + uint64_t p2p_dev; + uint64_t p2p_counters; + uint64_t layout_control; + uint64_t layout_block; + uint64_t slot_bytes; + uint64_t recv_off; + uint64_t send_off; + uint64_t flag_off; + uint64_t desc_off; + uint64_t ready_off; + uint64_t consumed_off; + uint64_t sent_off; + int32_t world; + int32_t rank; + int32_t num_tokens; + int32_t max_tokens; + int32_t hidden_bytes; + int32_t top_k; + int32_t num_experts; + uint32_t slots; + uint32_t lanes; + uint32_t wire_row_bytes; +}; +static_assert(sizeof(EpParams) == 200, "EpParams must match sccl_ep_args"); + +__device__ __forceinline__ uint64_t align64(uint64_t v) { return (v + 63ull) & ~63ull; } +__device__ __forceinline__ uint64_t ws_recv_counts(const EpParams &a) { return a.workspace; } +__device__ __forceinline__ uint64_t ws_send_counts(const EpParams &a) { return a.workspace + 32ull; } +__device__ __forceinline__ uint64_t ws_send_indices(const EpParams &a) { return a.workspace + 64ull; } +__device__ __forceinline__ uint64_t ws_send_slot_of_tok(const EpParams &a) { + return ws_send_indices(a) + align64((uint64_t)a.world * (uint64_t)a.max_tokens * 4ull); +} +__device__ __forceinline__ uint64_t ws_combine_recv(const EpParams &a) { + return ws_send_slot_of_tok(a) + align64((uint64_t)a.world * (uint64_t)a.max_tokens * 4ull); +} + +__device__ __forceinline__ uint64_t peer_block(const EpParams &a, int32_t p) { + return a.p2p_dev + a.layout_control + (uint64_t)p * a.layout_block; +} +__device__ __forceinline__ uint64_t chan_counter(const EpParams &a, int32_t send_dir, int32_t p) { + return a.p2p_counters + (uint64_t)(send_dir * kMaxWorld + p) * 8ull; +} + +__device__ __forceinline__ void mask_unused_slots(const EpParams &a, int32_t p, int32_t start_k, int32_t dummy_e) { + const int32_t thread = (int32_t)threadIdx.x; + const int32_t threads = (int32_t)blockDim.x; + const int32_t unused = a.max_tokens - start_k; + if (unused <= 0) return; + const int32_t total_elems = unused * a.top_k; + int32_t *ids_out = (int32_t *)a.topk_ids_out + (int64_t)(p * a.max_tokens + start_k) * a.top_k; + float *wts_out = (float *)a.topk_weights_out + (int64_t)(p * a.max_tokens + start_k) * a.top_k; + for (int32_t idx = thread; idx < total_elems; idx += threads) { + ids_out[idx] = dummy_e; + wts_out[idx] = 0.0f; + } +} + +/* + * Co-scheduling invariant for sircl_ep_dispatch and sircl_ep_combine_xfer: + * Both kernels launch 2 * world CTAs in one grid — blocks [0, world) are senders and blocks + * [world, 2 * world) are receivers — sharing a bounded P2P pipe (slots * min(slot_bytes, 128 KiB)). + * Once a sender fills the pipe, it spins waiting for sent_off to advance, which requires the peer's + * receiver CTA to drain recv_off and return credits. Under a non-cooperative launch, concurrent GPU + * work (e.g. shared experts on an auxiliary stream) could let sender CTAs occupy the remaining SM + * slots while receiver CTAs sit queued, causing a cross-rank co-scheduling deadlock until timeout. + * + * Therefore, the host (engine.c) MUST verify at communicator setup that the device supports + * cooperative launch (CU_DEVICE_ATTRIBUTE_COOPERATIVE_LAUNCH) and that + * sm_count * max_active_blocks_per_sm >= 2 * world for both kernels (failing closed with + * ncclInvalidUsage otherwise), and MUST launch both kernels via cuLaunchCooperativeKernel. + * Cooperative launch guarantees atomic co-residency of all 2 * world CTAs before execution starts, + * eliminating the deadlock under both eager execution and CUDA graph capture/replay (supported on + * SM120/SM121 in CUDA 12+). + */ +__device__ __forceinline__ void ep_dispatch_impl(const EpParams &a) { + const int32_t bid = (int32_t)blockIdx.x; + const int32_t thread = (int32_t)threadIdx.x; + const int32_t last_thread = (int32_t)blockDim.x - 1; + const uint64_t ctrl = a.p2p_dev; + const uint64_t poison = ctrl + 4 * kPoison; + const uint32_t limit_us = (a.world > 1) ? ld_relaxed_sys(ctrl + 4 * kWaitLimitUs) : 0u; + const int32_t local_experts = a.num_experts / a.world; + const int32_t dummy_e = (a.world > 1) ? (((a.rank + 1) % a.world) * local_experts) : -1; + const int32_t hidden_packs = a.hidden_bytes / kPackBytes; + + if (bid < a.world) { + /* Sender + self-copy block for destination peer p = bid. */ + const int32_t p = bid; + const int32_t e_lo = p * local_experts; + const int32_t e_hi = e_lo + local_experts; + int32_t *send_indices = (int32_t *)ws_send_indices(a) + (int64_t)p * a.max_tokens; + int32_t *send_slot_of_tok = (int32_t *)ws_send_slot_of_tok(a) + (int64_t)p * a.max_tokens; + + __shared__ int32_t s_prefix[kEpThreads]; + __shared__ int32_t s_total; + __shared__ uint32_t s_poisoned; + __shared__ uint32_t s_seq; + if (thread == 0) { + s_total = 0; + s_poisoned = 0; + } + __syncthreads(); + + for (int32_t base = 0; base < a.num_tokens; base += kEpThreads) { + const int32_t t = base + thread; + int32_t hit = 0; + if (t < a.num_tokens) { + const int32_t *ids = (const int32_t *)a.topk_ids_in + (int64_t)t * a.top_k; + for (int32_t k = 0; k < a.top_k; ++k) { + const int32_t e = ids[k]; + if (e >= e_lo && e < e_hi) { + hit = 1; + break; + } + } + } + s_prefix[thread] = hit; + __syncthreads(); + for (int32_t stride = 1; stride < kEpThreads; stride <<= 1) { + const int32_t val = (thread >= stride) ? s_prefix[thread - stride] : 0; + __syncthreads(); + s_prefix[thread] += val; + __syncthreads(); + } + if (t < a.num_tokens) { + if (hit) { + const int32_t idx = s_total + s_prefix[thread] - 1; + send_indices[idx] = t; + send_slot_of_tok[t] = idx; + } else { + send_slot_of_tok[t] = -1; + } + } + __syncthreads(); + if (thread == 0) s_total += s_prefix[kEpThreads - 1]; + __syncthreads(); + } + + const int32_t n_send = s_total; + if (thread == 0) ((int32_t *)ws_send_counts(a))[p] = n_send; + + if (p == a.rank) { + /* Self copy: direct GPU-to-GPU copy into slice [rank * max_tokens ..] + mask unused slots. */ + for (int32_t i = 0; i < n_send; ++i) { + const int32_t t = send_indices[i]; + const int32_t out_row = p * a.max_tokens + i; + copy_packs<2, false>(a.hidden_in + (uint64_t)t * (uint64_t)a.hidden_bytes, + a.hidden_out + (uint64_t)out_row * (uint64_t)a.hidden_bytes, hidden_packs); + if (thread < a.top_k) { + ((int32_t *)a.topk_ids_out)[(int64_t)out_row * a.top_k + thread] = + ((const int32_t *)a.topk_ids_in)[(int64_t)t * a.top_k + thread]; + ((float *)a.topk_weights_out)[(int64_t)out_row * a.top_k + thread] = + ((const float *)a.topk_weights_in)[(int64_t)t * a.top_k + thread]; + } + } + mask_unused_slots(a, p, n_send, dummy_e); + if (thread == 0) { + ((int32_t *)ws_recv_counts(a))[p] = n_send; + if (a.recv_counts_out) ((int32_t *)a.recv_counts_out)[p] = n_send; + } + return; + } + + /* Remote send to peer p over P2P channel (dir = 1, peer = p). */ + const uint64_t bbase = peer_block(a, p); + const uint64_t cptr = chan_counter(a, 1, p); + if (thread == 0) s_seq = ld_acquire_gpu(cptr); + __syncthreads(); + uint32_t g = s_seq; + const uint64_t pipe_bytes = (a.slot_bytes < 131072ull) ? a.slot_bytes : 131072ull; + const int32_t toks_per_slot = max(1, (int32_t)(pipe_bytes / (uint64_t)a.wire_row_bytes)); + + if (n_send == 0) { + const uint32_t m = g % a.slots; + const uint32_t tag = g + 1u; + if (thread == last_thread && wait_ge_or_poison(bbase + a.sent_off, tag - a.slots, poison, limit_us) == 1) + fail(ctrl, p, kNoLane, kKindSlot, tag, 0, 0); + __syncthreads(); + if (thread == 0) s_poisoned = ld_relaxed_sys(poison); + __syncthreads(); + if (s_poisoned == 0) { + if (thread == 0) { + fence_sc_sys(); + st_relaxed_sys(bbase + a.desc_off + 4ull * m, kLast); + fence_sc_sys(); + st_relaxed_sys(bbase + a.ready_off + 4ull * m, tag); + } + g += 1u; + } + } else { + for (int32_t offset = 0; offset < n_send; offset += toks_per_slot) { + const int32_t chunk = min(toks_per_slot, n_send - offset); + const bool is_last = (offset + chunk) == n_send; + const uint32_t m = g % a.slots; + const uint32_t tag = g + 1u; + if (thread == last_thread && wait_ge_or_poison(bbase + a.sent_off, tag - a.slots, poison, limit_us) == 1) + fail(ctrl, p, kNoLane, kKindSlot, tag, 0, 0); + __syncthreads(); + if (thread == 0) s_poisoned = ld_relaxed_sys(poison); + __syncthreads(); + if (s_poisoned != 0) break; + + const uint64_t slot_base = bbase + a.send_off + (uint64_t)m * a.slot_bytes; + int32_t i = 0; + for (; i + 4 <= chunk; i += 4) { + const int32_t t0 = send_indices[offset + i]; + const int32_t t1 = send_indices[offset + i + 1]; + const int32_t t2 = send_indices[offset + i + 2]; + const int32_t t3 = send_indices[offset + i + 3]; + const uint64_t s0 = a.hidden_in + (uint64_t)t0 * (uint64_t)a.hidden_bytes; + const uint64_t s1 = a.hidden_in + (uint64_t)t1 * (uint64_t)a.hidden_bytes; + const uint64_t s2 = a.hidden_in + (uint64_t)t2 * (uint64_t)a.hidden_bytes; + const uint64_t s3 = a.hidden_in + (uint64_t)t3 * (uint64_t)a.hidden_bytes; + const uint64_t d0 = slot_base + (uint64_t)(i + 0) * (uint64_t)a.wire_row_bytes; + const uint64_t d1 = slot_base + (uint64_t)(i + 1) * (uint64_t)a.wire_row_bytes; + const uint64_t d2 = slot_base + (uint64_t)(i + 2) * (uint64_t)a.wire_row_bytes; + const uint64_t d3 = slot_base + (uint64_t)(i + 3) * (uint64_t)a.wire_row_bytes; + for (int32_t pk = thread; pk < hidden_packs; pk += kEpThreads) { + const uint64_t off = (uint64_t)pk * kPackBytes; + const uint4 v0 = ld_global_v4(s0 + off); + const uint4 v1 = ld_global_v4(s1 + off); + const uint4 v2 = ld_global_v4(s2 + off); + const uint4 v3 = ld_global_v4(s3 + off); + st_global_v4(d0 + off, v0); + st_global_v4(d1 + off, v1); + st_global_v4(d2 + off, v2); + st_global_v4(d3 + off, v3); + } + if (thread < a.top_k) { + const int32_t ts[4] = {t0, t1, t2, t3}; + const uint64_t ds[4] = {d0, d1, d2, d3}; +#pragma unroll + for (int r = 0; r < 4; ++r) { + const uint64_t meta = ds[r] + (uint64_t)a.hidden_bytes; + ((int32_t *)meta)[thread] = ((const int32_t *)a.topk_ids_in)[(int64_t)ts[r] * a.top_k + thread]; + ((float *)meta)[a.top_k + thread] = ((const float *)a.topk_weights_in)[(int64_t)ts[r] * a.top_k + thread]; + } + } + } + for (; i < chunk; ++i) { + const int32_t t = send_indices[offset + i]; + const uint64_t dst = slot_base + (uint64_t)i * (uint64_t)a.wire_row_bytes; + copy_packs<2, false>(a.hidden_in + (uint64_t)t * (uint64_t)a.hidden_bytes, dst, hidden_packs); + if (thread < a.top_k) { + const uint64_t meta = dst + (uint64_t)a.hidden_bytes; + const int32_t eid = ((const int32_t *)a.topk_ids_in)[(int64_t)t * a.top_k + thread]; + const float wt = ((const float *)a.topk_weights_in)[(int64_t)t * a.top_k + thread]; + ((int32_t *)meta)[thread] = eid; + ((float *)meta)[a.top_k + thread] = wt; + } + } + __syncthreads(); + if (thread == 0) { + const uint32_t hdr = ((uint32_t)chunk * a.wire_row_bytes) | (is_last ? kLast : 0u); + fence_sc_sys(); + st_relaxed_sys(bbase + a.desc_off + 4ull * m, hdr); + fence_sc_sys(); + st_relaxed_sys(bbase + a.ready_off + 4ull * m, tag); + } + g += 1u; + } + } + __syncthreads(); + if (thread == 0 && ld_relaxed_sys(poison) == 0) st_release_gpu(cptr, g); + } else { + /* Receiver block for source peer p = bid - world. */ + const int32_t p = bid - a.world; + if (p == a.rank) return; + + __shared__ uint32_t s_poisoned; + __shared__ uint32_t s_seq; + __shared__ uint32_t s_hdr; + const uint64_t bbase = peer_block(a, p); + const uint64_t cptr = chan_counter(a, 0, p); + if (thread == 0) { + s_seq = ld_acquire_gpu(cptr); + s_poisoned = 0; + } + __syncthreads(); + uint32_t g = s_seq; + int32_t received = 0; + + for (;;) { + const uint32_t m = g % a.slots; + const uint32_t tag = g + 1u; + const uint64_t line = bbase + a.flag_off + (uint64_t)m * a.lanes * kLine; + if (thread < (int32_t)a.lanes && wait_eq_or_poison(line + (uint64_t)thread * kLine, tag, poison, limit_us) == 1) + fail(ctrl, p, (uint32_t)thread, kKindFlag, tag, 0, 0); + __syncthreads(); + if (thread == 0) { + if (ld_relaxed_sys(poison) == 0) { + const uint32_t got = ld_relaxed_sys(line + 4); + const uint32_t cbytes = got & kBytesMask; + if (cbytes % a.wire_row_bytes != 0 || received + (int32_t)(cbytes / a.wire_row_bytes) > a.max_tokens) { + fail(ctrl, p, kNoLane, kKindSize, tag, (uint32_t)a.max_tokens * a.wire_row_bytes, got); + } + s_hdr = got; + } + s_poisoned = ld_relaxed_sys(poison); + } + __syncthreads(); + if (s_poisoned != 0) break; + + const uint32_t cbytes = s_hdr & kBytesMask; + const bool is_last = (s_hdr & kLast) != 0; + const int32_t chunk = (int32_t)(cbytes / a.wire_row_bytes); + const uint64_t slot_base = bbase + a.recv_off + (uint64_t)m * a.slot_bytes; + int32_t i = 0; + for (; i + 4 <= chunk; i += 4) { + const uint64_t s0 = slot_base + (uint64_t)(i + 0) * (uint64_t)a.wire_row_bytes; + const uint64_t s1 = slot_base + (uint64_t)(i + 1) * (uint64_t)a.wire_row_bytes; + const uint64_t s2 = slot_base + (uint64_t)(i + 2) * (uint64_t)a.wire_row_bytes; + const uint64_t s3 = slot_base + (uint64_t)(i + 3) * (uint64_t)a.wire_row_bytes; + const int32_t r0 = p * a.max_tokens + received + i; + const uint64_t d0 = a.hidden_out + (uint64_t)(r0 + 0) * (uint64_t)a.hidden_bytes; + const uint64_t d1 = a.hidden_out + (uint64_t)(r0 + 1) * (uint64_t)a.hidden_bytes; + const uint64_t d2 = a.hidden_out + (uint64_t)(r0 + 2) * (uint64_t)a.hidden_bytes; + const uint64_t d3 = a.hidden_out + (uint64_t)(r0 + 3) * (uint64_t)a.hidden_bytes; + for (int32_t pk = thread; pk < hidden_packs; pk += kEpThreads) { + const uint64_t off = (uint64_t)pk * kPackBytes; + const uint4 v0 = ld_relaxed_sys_v4(s0 + off); + const uint4 v1 = ld_relaxed_sys_v4(s1 + off); + const uint4 v2 = ld_relaxed_sys_v4(s2 + off); + const uint4 v3 = ld_relaxed_sys_v4(s3 + off); + st_global_v4(d0 + off, v0); + st_global_v4(d1 + off, v1); + st_global_v4(d2 + off, v2); + st_global_v4(d3 + off, v3); + } + if (thread < a.top_k) { + const uint64_t ss[4] = {s0, s1, s2, s3}; +#pragma unroll + for (int r = 0; r < 4; ++r) { + const uint64_t meta = ss[r] + (uint64_t)a.hidden_bytes; + const int32_t out_row = r0 + r; + ((int32_t *)a.topk_ids_out)[(int64_t)out_row * a.top_k + thread] = + (int32_t)ld_relaxed_sys(meta + 4ull * (uint64_t)thread); + ((float *)a.topk_weights_out)[(int64_t)out_row * a.top_k + thread] = + __uint_as_float(ld_relaxed_sys(meta + 4ull * (uint64_t)(a.top_k + thread))); + } + } + } + for (; i < chunk; ++i) { + const uint64_t src = slot_base + (uint64_t)i * (uint64_t)a.wire_row_bytes; + const int32_t out_row = p * a.max_tokens + received + i; + copy_packs<2, true>(src, a.hidden_out + (uint64_t)out_row * (uint64_t)a.hidden_bytes, hidden_packs); + if (thread < a.top_k) { + const uint64_t meta = src + (uint64_t)a.hidden_bytes; + const uint32_t eid_u = ld_relaxed_sys(meta + 4ull * (uint64_t)thread); + const uint32_t wt_u = ld_relaxed_sys(meta + 4ull * (uint64_t)(a.top_k + thread)); + ((int32_t *)a.topk_ids_out)[(int64_t)out_row * a.top_k + thread] = (int32_t)eid_u; + ((float *)a.topk_weights_out)[(int64_t)out_row * a.top_k + thread] = __uint_as_float(wt_u); + } + } + __syncthreads(); + if (thread == 0) { + fence_sc_sys(); + st_relaxed_sys(bbase + a.consumed_off + 4ull * m, tag); + } + received += chunk; + g += 1u; + if (is_last) break; + } + + if (s_poisoned == 0) { + mask_unused_slots(a, p, received, dummy_e); + __syncthreads(); + if (thread == 0 && ld_relaxed_sys(poison) == 0) { + ((int32_t *)ws_recv_counts(a))[p] = received; + if (a.recv_counts_out) ((int32_t *)a.recv_counts_out)[p] = received; + st_release_gpu(cptr, g); + } + } + } +} + +__device__ __forceinline__ void ep_combine_xfer_impl(const EpParams &a) { + const int32_t bid = (int32_t)blockIdx.x; + const int32_t thread = (int32_t)threadIdx.x; + const int32_t last_thread = (int32_t)blockDim.x - 1; + const uint64_t ctrl = a.p2p_dev; + const uint64_t poison = ctrl + 4 * kPoison; + const uint32_t limit_us = (a.world > 1) ? ld_relaxed_sys(ctrl + 4 * kWaitLimitUs) : 0u; + const int32_t hidden_packs = a.hidden_bytes / kPackBytes; + + if (bid < a.world) { + /* Return processed tokens from slice [p * max_tokens .. p * max_tokens + recv_counts[p] - 1] back to peer p. */ + const int32_t p = bid; + if (p == a.rank) return; + + __shared__ uint32_t s_poisoned; + __shared__ uint32_t s_seq; + __shared__ int32_t s_n_send; + const uint64_t bbase = peer_block(a, p); + const uint64_t cptr = chan_counter(a, 1, p); + if (thread == 0) { + s_seq = ld_acquire_gpu(cptr); + s_n_send = ((const int32_t *)ws_recv_counts(a))[p]; + s_poisoned = 0; + } + __syncthreads(); + uint32_t g = s_seq; + const int32_t n_send = s_n_send; + const uint64_t pipe_bytes = (a.slot_bytes < 131072ull) ? a.slot_bytes : 131072ull; + const int32_t toks_per_slot = max(1, (int32_t)(pipe_bytes / (uint64_t)a.hidden_bytes)); + + if (n_send == 0) { + const uint32_t m = g % a.slots; + const uint32_t tag = g + 1u; + if (thread == last_thread && wait_ge_or_poison(bbase + a.sent_off, tag - a.slots, poison, limit_us) == 1) + fail(ctrl, p, kNoLane, kKindSlot, tag, 0, 0); + __syncthreads(); + if (thread == 0) s_poisoned = ld_relaxed_sys(poison); + __syncthreads(); + if (s_poisoned == 0) { + if (thread == 0) { + fence_sc_sys(); + st_relaxed_sys(bbase + a.desc_off + 4ull * m, kLast); + fence_sc_sys(); + st_relaxed_sys(bbase + a.ready_off + 4ull * m, tag); + } + g += 1u; + } + } else { + for (int32_t offset = 0; offset < n_send; offset += toks_per_slot) { + const int32_t chunk = min(toks_per_slot, n_send - offset); + const bool is_last = (offset + chunk) == n_send; + const uint32_t m = g % a.slots; + const uint32_t tag = g + 1u; + if (thread == last_thread && wait_ge_or_poison(bbase + a.sent_off, tag - a.slots, poison, limit_us) == 1) + fail(ctrl, p, kNoLane, kKindSlot, tag, 0, 0); + __syncthreads(); + if (thread == 0) s_poisoned = ld_relaxed_sys(poison); + __syncthreads(); + if (s_poisoned != 0) break; + + const uint64_t src = a.hidden_in + (uint64_t)(p * a.max_tokens + offset) * (uint64_t)a.hidden_bytes; + const uint64_t dst = bbase + a.send_off + (uint64_t)m * a.slot_bytes; + copy_packs<4, false>(src, dst, chunk * hidden_packs); + __syncthreads(); + if (thread == 0) { + const uint32_t hdr = ((uint32_t)chunk * (uint32_t)a.hidden_bytes) | (is_last ? kLast : 0u); + fence_sc_sys(); + st_relaxed_sys(bbase + a.desc_off + 4ull * m, hdr); + fence_sc_sys(); + st_relaxed_sys(bbase + a.ready_off + 4ull * m, tag); + } + g += 1u; + } + } + __syncthreads(); + if (thread == 0 && ld_relaxed_sys(poison) == 0) st_release_gpu(cptr, g); + } else { + /* Receive returned partials from peer p into workspace.combine_recv[p * max_tokens ..]. */ + const int32_t p = bid - a.world; + if (p == a.rank) return; + + __shared__ uint32_t s_poisoned; + __shared__ uint32_t s_seq; + __shared__ uint32_t s_hdr; + const uint64_t bbase = peer_block(a, p); + const uint64_t cptr = chan_counter(a, 0, p); + const uint64_t dst_base = ws_combine_recv(a) + (uint64_t)p * (uint64_t)a.max_tokens * (uint64_t)a.hidden_bytes; + if (thread == 0) { + s_seq = ld_acquire_gpu(cptr); + s_poisoned = 0; + } + __syncthreads(); + uint32_t g = s_seq; + int32_t received = 0; + + for (;;) { + const uint32_t m = g % a.slots; + const uint32_t tag = g + 1u; + const uint64_t line = bbase + a.flag_off + (uint64_t)m * a.lanes * kLine; + if (thread < (int32_t)a.lanes && wait_eq_or_poison(line + (uint64_t)thread * kLine, tag, poison, limit_us) == 1) + fail(ctrl, p, (uint32_t)thread, kKindFlag, tag, 0, 0); + __syncthreads(); + if (thread == 0) { + if (ld_relaxed_sys(poison) == 0) { + const uint32_t got = ld_relaxed_sys(line + 4); + const uint32_t cbytes = got & kBytesMask; + if (cbytes % (uint32_t)a.hidden_bytes != 0 || + received + (int32_t)(cbytes / (uint32_t)a.hidden_bytes) > a.max_tokens) { + fail(ctrl, p, kNoLane, kKindSize, tag, (uint32_t)a.max_tokens * (uint32_t)a.hidden_bytes, got); + } + s_hdr = got; + } + s_poisoned = ld_relaxed_sys(poison); + } + __syncthreads(); + if (s_poisoned != 0) break; + + const uint32_t cbytes = s_hdr & kBytesMask; + const bool is_last = (s_hdr & kLast) != 0; + const int32_t chunk = (int32_t)(cbytes / (uint32_t)a.hidden_bytes); + if (chunk > 0) { + const uint64_t src = bbase + a.recv_off + (uint64_t)m * a.slot_bytes; + const uint64_t dst = dst_base + (uint64_t)received * (uint64_t)a.hidden_bytes; + copy_packs<4, true>(src, dst, chunk * hidden_packs); + } + __syncthreads(); + if (thread == 0) { + fence_sc_sys(); + st_relaxed_sys(bbase + a.consumed_off + 4ull * m, tag); + } + received += chunk; + g += 1u; + if (is_last) break; + } + + if (s_poisoned == 0 && thread == 0 && ld_relaxed_sys(poison) == 0) st_release_gpu(cptr, g); + } +} + +template +__device__ __forceinline__ void ep_combine_reduce_impl(const EpParams &a) { + const int32_t thread = (int32_t)threadIdx.x; + const int32_t threads = (int32_t)blockDim.x; + const int32_t hidden_packs = a.hidden_bytes / kPackBytes; + const int32_t *send_slot_of_tok = (const int32_t *)ws_send_slot_of_tok(a); + const uint64_t combine_recv = ws_combine_recv(a); + + __shared__ int32_t s_slot[kMaxWorld]; + + for (int32_t t = (int32_t)blockIdx.x; t < a.num_tokens; t += (int32_t)gridDim.x) { + if (thread < a.world) s_slot[thread] = send_slot_of_tok[(int64_t)thread * a.max_tokens + t]; + __syncthreads(); + + const uint64_t out_row = a.hidden_out + (uint64_t)t * (uint64_t)a.hidden_bytes; + for (int32_t pack = thread; pack < hidden_packs; pack += threads) { + float acc[DType::kElems]; +#pragma unroll + for (int i = 0; i < DType::kElems; ++i) acc[i] = 0.0f; + bool first = true; + for (int32_t p = 0; p < a.world; ++p) { + const int32_t slot = s_slot[p]; + if (slot < 0) continue; + const uint64_t base = (p == a.rank) ? a.hidden_in : combine_recv; + const uint64_t src = + base + (uint64_t)(p * a.max_tokens + slot) * (uint64_t)a.hidden_bytes + (uint64_t)pack * kPackBytes; + DType::accumulate(acc, ld_global_v4(src), first); + first = false; + } + st_global_v4(out_row + (uint64_t)pack * kPackBytes, DType::store(acc)); + } + __syncthreads(); + } +} + +} // namespace sircl_ep + +extern "C" __global__ void __launch_bounds__(256, 1) sircl_ep_dispatch(const sircl_ep::EpParams a) { + sircl_ep::ep_dispatch_impl(a); +} +extern "C" __global__ void __launch_bounds__(256, 1) sircl_ep_combine_xfer(const sircl_ep::EpParams a) { + sircl_ep::ep_combine_xfer_impl(a); +} +extern "C" __global__ void __launch_bounds__(256, 1) sircl_ep_combine_reduce_f32(const sircl_ep::EpParams a) { + sircl_ep::ep_combine_reduce_impl(a); +} +extern "C" __global__ void __launch_bounds__(256, 1) sircl_ep_combine_reduce_f16(const sircl_ep::EpParams a) { + sircl_ep::ep_combine_reduce_impl(a); +} +extern "C" __global__ void __launch_bounds__(256, 1) sircl_ep_combine_reduce_bf16(const sircl_ep::EpParams a) { + sircl_ep::ep_combine_reduce_impl(a); +} diff --git a/spark_transport/libsircl/src/api.c b/spark_transport/libsircl/src/api.c index 72a6a435..f62d5a69 100644 --- a/spark_transport/libsircl/src/api.c +++ b/spark_transport/libsircl/src/api.c @@ -903,13 +903,40 @@ static ncclResult_t collective_ready(struct ncclComm *comm, const char *what, nc return ncclSuccess; } +/* Ordering invariant for ncclGroupStart/ncclGroupEnd: + * ncclSend/ncclRecv inside a group are queued in p2p_queue and flushed at ncclGroupEnd, whereas + * collectives launch immediately on the caller's stream. Launching a collective while P2P calls are + * already queued on the same communicator or the same stream inside the active group would silently + * reorder the collective ahead of the earlier P2P calls, and eagerly flushing P2P before the group + * ends could deadlock if matching sends/recvs follow later in the group. Fail closed with + * ncclInvalidUsage instead. (Collectives issued *before* P2P in a group preserve stream submission + * order because they enqueue immediately and the P2P batch enqueues afterward at ncclGroupEnd.) */ +static ncclResult_t collective_enqueue_ready(struct ncclComm *comm, cudaStream_t stream, const char *what, + ncclDataType_t datatype, ncclRedOp_t op, char *message, size_t len) { + ncclResult_t result = collective_ready(comm, what, datatype, op, message, len); + if (result != ncclSuccess) return result; + if (group_depth && p2p_count) { + for (unsigned i = 0; i < p2p_count; ++i) { + if ((p2p_queue[i].comm == comm && p2p_queue[i].serial == comm->serial) || + p2p_queue[i].op.stream == stream) { + snprintf(message, len, + "%s: cannot launch a collective after queued ncclSend/ncclRecv calls on the same communicator " + "or stream inside one ncclGroupStart/ncclGroupEnd block; end the point-to-point group first", + what); + return ncclInvalidUsage; + } + } + } + return ncclSuccess; +} + ncclResult_t ncclAllReduce(const void *sendbuff, void *recvbuff, size_t count, ncclDataType_t datatype, ncclRedOp_t op, ncclComm_t handle, cudaStream_t stream) { CHECK_PROCESS(); struct ncclComm *comm = acquire(handle); if (!comm) return refuse(ncclInvalidArgument, "ncclAllReduce: unknown communicator handle"); char message[512] = {0}; - ncclResult_t result = collective_ready(comm, "ncclAllReduce", datatype, op, message, sizeof message); + ncclResult_t result = collective_enqueue_ready(comm, stream, "ncclAllReduce", datatype, op, message, sizeof message); if (result == ncclSuccess) result = sccl_engine_allreduce(comm->engine, sendbuff, recvbuff, count, datatype, op, stream, message, sizeof message); @@ -923,7 +950,7 @@ ncclResult_t ncclAllGather(const void *sendbuff, void *recvbuff, size_t sendcoun struct ncclComm *comm = acquire(handle); if (!comm) return refuse(ncclInvalidArgument, "ncclAllGather: unknown communicator handle"); char message[512] = {0}; - ncclResult_t result = collective_ready(comm, "ncclAllGather", datatype, ncclSum, message, sizeof message); + ncclResult_t result = collective_enqueue_ready(comm, stream, "ncclAllGather", datatype, ncclSum, message, sizeof message); if (result == ncclSuccess) result = sccl_engine_allgather(comm->engine, sendbuff, recvbuff, sendcount, datatype, stream, message, sizeof message); @@ -937,7 +964,7 @@ ncclResult_t ncclReduce(const void *sendbuff, void *recvbuff, size_t count, nccl struct ncclComm *comm = acquire(handle); if (!comm) return refuse(ncclInvalidArgument, "ncclReduce: unknown communicator handle"); char message[512] = {0}; - ncclResult_t result = collective_ready(comm, "ncclReduce", datatype, op, message, sizeof message); + ncclResult_t result = collective_enqueue_ready(comm, stream, "ncclReduce", datatype, op, message, sizeof message); if (result == ncclSuccess) result = sccl_engine_reduce(comm->engine, sendbuff, recvbuff, count, datatype, op, root, stream, message, sizeof message); @@ -951,7 +978,7 @@ ncclResult_t ncclBroadcast(const void *sendbuff, void *recvbuff, size_t count, n struct ncclComm *comm = acquire(handle); if (!comm) return refuse(ncclInvalidArgument, "ncclBroadcast: unknown communicator handle"); char message[512] = {0}; - ncclResult_t result = collective_ready(comm, "ncclBroadcast", datatype, ncclSum, message, sizeof message); + ncclResult_t result = collective_enqueue_ready(comm, stream, "ncclBroadcast", datatype, ncclSum, message, sizeof message); if (result == ncclSuccess) result = sccl_engine_broadcast(comm->engine, sendbuff, recvbuff, count, datatype, root, stream, message, sizeof message); @@ -970,7 +997,7 @@ ncclResult_t ncclReduceScatter(const void *sendbuff, void *recvbuff, size_t recv struct ncclComm *comm = acquire(handle); if (!comm) return refuse(ncclInvalidArgument, "ncclReduceScatter: unknown communicator handle"); char message[512] = {0}; - ncclResult_t result = collective_ready(comm, "ncclReduceScatter", datatype, op, message, sizeof message); + ncclResult_t result = collective_enqueue_ready(comm, stream, "ncclReduceScatter", datatype, op, message, sizeof message); if (result == ncclSuccess) result = sccl_engine_reducescatter(comm->engine, sendbuff, recvbuff, recvcount, datatype, op, stream, message, sizeof message); @@ -984,7 +1011,7 @@ ncclResult_t ncclAlltoAll(const void *sendbuff, void *recvbuff, size_t count, nc struct ncclComm *comm = acquire(handle); if (!comm) return refuse(ncclInvalidArgument, "ncclAlltoAll: unknown communicator handle"); char message[512] = {0}; - ncclResult_t result = collective_ready(comm, "ncclAlltoAll", datatype, ncclSum, message, sizeof message); + ncclResult_t result = collective_enqueue_ready(comm, stream, "ncclAlltoAll", datatype, ncclSum, message, sizeof message); if (result == ncclSuccess) result = sccl_engine_alltoall(comm->engine, sendbuff, recvbuff, count, datatype, stream, message, sizeof message); release(comm); @@ -997,7 +1024,7 @@ ncclResult_t ncclGather(const void *sendbuff, void *recvbuff, size_t count, nccl struct ncclComm *comm = acquire(handle); if (!comm) return refuse(ncclInvalidArgument, "ncclGather: unknown communicator handle"); char message[512] = {0}; - ncclResult_t result = collective_ready(comm, "ncclGather", datatype, ncclSum, message, sizeof message); + ncclResult_t result = collective_enqueue_ready(comm, stream, "ncclGather", datatype, ncclSum, message, sizeof message); if (result == ncclSuccess) result = sccl_engine_gather(comm->engine, sendbuff, recvbuff, count, datatype, root, stream, message, sizeof message); @@ -1011,7 +1038,7 @@ ncclResult_t ncclScatter(const void *sendbuff, void *recvbuff, size_t count, ncc struct ncclComm *comm = acquire(handle); if (!comm) return refuse(ncclInvalidArgument, "ncclScatter: unknown communicator handle"); char message[512] = {0}; - ncclResult_t result = collective_ready(comm, "ncclScatter", datatype, ncclSum, message, sizeof message); + ncclResult_t result = collective_enqueue_ready(comm, stream, "ncclScatter", datatype, ncclSum, message, sizeof message); if (result == ncclSuccess) result = sccl_engine_scatter(comm->engine, sendbuff, recvbuff, count, datatype, root, stream, message, sizeof message); @@ -1045,6 +1072,44 @@ ncclResult_t sirclGetReceipt(ncclComm_t handle, char *out, size_t length, size_t if (needed) *needed = need; return result == ncclSuccess ? result : fail(result, "sirclGetReceipt: no SIRCL session on this communicator"); } + +size_t sirclEpWorkspaceBytes(int world, int max_tokens, size_t hidden_bytes) { + return sccl_engine_ep_workspace_bytes(world, max_tokens, hidden_bytes); +} + +ncclResult_t sirclEpDispatch(const void *hidden_in, const int *topk_ids_in, const float *topk_weights_in, + void *hidden_out, int *topk_ids_out, float *topk_weights_out, int *recv_counts_out, + void *workspace, size_t workspace_bytes, int num_tokens, int max_tokens, + size_t hidden_bytes, int top_k, int num_experts, ncclComm_t handle, cudaStream_t stream) { + CHECK_PROCESS(); + struct ncclComm *comm = acquire(handle); + if (!comm) return refuse(ncclInvalidArgument, "sirclEpDispatch: unknown communicator handle"); + char message[512] = {0}; + ncclResult_t result = collective_enqueue_ready(comm, stream, "sirclEpDispatch", ncclUint8, ncclSum, message, + sizeof message); + if (result == ncclSuccess) + result = sccl_engine_ep_dispatch(comm->engine, hidden_in, topk_ids_in, topk_weights_in, hidden_out, topk_ids_out, + topk_weights_out, recv_counts_out, workspace, workspace_bytes, num_tokens, + max_tokens, hidden_bytes, top_k, num_experts, stream, message, sizeof message); + release(comm); + return result == ncclSuccess ? result : refuse(result, message); +} + +ncclResult_t sirclEpCombine(const void *expert_out_in, void *hidden_out, void *workspace, size_t workspace_bytes, + int num_tokens, int max_tokens, size_t hidden_dim, ncclDataType_t datatype, + ncclComm_t handle, cudaStream_t stream) { + CHECK_PROCESS(); + struct ncclComm *comm = acquire(handle); + if (!comm) return refuse(ncclInvalidArgument, "sirclEpCombine: unknown communicator handle"); + char message[512] = {0}; + ncclResult_t result = collective_enqueue_ready(comm, stream, "sirclEpCombine", datatype, ncclSum, message, + sizeof message); + if (result == ncclSuccess) + result = sccl_engine_ep_combine(comm->engine, expert_out_in, hidden_out, workspace, workspace_bytes, num_tokens, + max_tokens, hidden_dim, datatype, stream, message, sizeof message); + release(comm); + return result == ncclSuccess ? result : refuse(result, message); +} static ncclResult_t transition(ncclComm_t handle, int next) { CHECK_PROCESS(); struct ncclComm *comm = acquire(handle); diff --git a/spark_transport/libsircl/src/cuda_api.c b/spark_transport/libsircl/src/cuda_api.c index 56d9c5b7..745dbd1c 100644 --- a/spark_transport/libsircl/src/cuda_api.c +++ b/spark_transport/libsircl/src/cuda_api.c @@ -74,6 +74,13 @@ static void load(void) { table.MemAllocAsync = NULL; table.MemFreeAsync = NULL; } + *(void **)(&table.LaunchCooperativeKernel) = dlsym(handle, "cuLaunchCooperativeKernel"); + *(void **)(&table.OccupancyMaxActiveBlocksPerMultiprocessor) = + dlsym(handle, "cuOccupancyMaxActiveBlocksPerMultiprocessor"); + if (!table.LaunchCooperativeKernel || !table.OccupancyMaxActiveBlocksPerMultiprocessor) { + table.LaunchCooperativeKernel = NULL; + table.OccupancyMaxActiveBlocksPerMultiprocessor = NULL; + } sccl_CUresult result = table.Init(0); if (result != SCCL_CUDA_SUCCESS) { snprintf(load_error, sizeof load_error, "cuInit failed: %d", result); diff --git a/spark_transport/libsircl/src/cuda_api.h b/spark_transport/libsircl/src/cuda_api.h index 3454ac98..65f14ddf 100644 --- a/spark_transport/libsircl/src/cuda_api.h +++ b/spark_transport/libsircl/src/cuda_api.h @@ -19,10 +19,12 @@ typedef struct sccl_CUevent_st *sccl_CUevent; enum { SCCL_CUDA_SUCCESS = 0, + SCCL_CU_DEVICE_ATTRIBUTE_MULTIPROCESSOR_COUNT = 16, SCCL_CU_DEVICE_ATTRIBUTE_COMPUTE_CAPABILITY_MAJOR = 75, SCCL_CU_DEVICE_ATTRIBUTE_COMPUTE_CAPABILITY_MINOR = 76, SCCL_CU_DEVICE_ATTRIBUTE_UNIFIED_ADDRESSING = 41, SCCL_CU_DEVICE_ATTRIBUTE_CAN_USE_HOST_POINTER_FOR_REGISTERED_MEM = 91, + SCCL_CU_DEVICE_ATTRIBUTE_COOPERATIVE_LAUNCH = 95, SCCL_CU_DEVICE_ATTRIBUTE_MEMORY_POOLS_SUPPORTED = 115, SCCL_CU_MEMHOSTALLOC_PORTABLE = 1, SCCL_CU_MEMHOSTALLOC_DEVICEMAP = 2, @@ -81,6 +83,11 @@ typedef struct sccl_cuda { * capture adds allocation and free nodes to the graph. */ sccl_CUresult (*MemAllocAsync)(sccl_CUdeviceptr *, size_t, sccl_CUstream); sccl_CUresult (*MemFreeAsync)(sccl_CUdeviceptr, sccl_CUstream); + /* Optional (NULL when the driver lacks them): cooperative launch and occupancy query for kernels + * whose sender and receiver CTAs must co-reside to avoid co-scheduling deadlock (SIRCL-EP). */ + sccl_CUresult (*LaunchCooperativeKernel)(sccl_CUfunction, unsigned, unsigned, unsigned, unsigned, unsigned, + unsigned, unsigned, sccl_CUstream, void **); + sccl_CUresult (*OccupancyMaxActiveBlocksPerMultiprocessor)(int *, sccl_CUfunction, int, size_t); } sccl_cuda; /* The process's driver table, loaded once; NULL when libcuda.so.1 or one of diff --git a/spark_transport/libsircl/src/engine.c b/spark_transport/libsircl/src/engine.c index 4112fc1c..b3cc96b9 100644 --- a/spark_transport/libsircl/src/engine.c +++ b/spark_transport/libsircl/src/engine.c @@ -174,6 +174,8 @@ enum { CTRL_MISSING_PEER = 3, CTRL_MISSING_LANE = 6, CTRL_WAIT_LIMIT_US = 7, + CTRL_ABORT = 30, + ROCE_STAT_ABORT_FROM = 30, MAX_PHASES = 8, MAX_DEVICES = 4, MAX_LANES = 2, @@ -353,12 +355,12 @@ typedef struct { /* One direction of the channel with one peer on this rank: its own stream (a receive waits on its stream * until the peer sends, so no other work may queue behind it), the event that joins the stream back to the - * caller's, the channel's next item, whether the group being issued uses it, its staging buffer (drivers - * without stream-ordered allocation) and its counts. */ + * caller's, whether the group being issued uses it, its staging buffer (drivers without stream-ordered + * allocation) and its counts. The channel's item sequence counter lives on the device (e->p2p_counters), so + * CUDA graphs captured on the channel advance it on every replay. */ typedef struct { sccl_CUstream stream; sccl_CUevent done; - uint32_t next; int joined; sccl_CUdeviceptr stage; uint64_t stage_bytes; @@ -458,6 +460,10 @@ struct sccl_engine { struct sccl_engine *quarantine_next; uint64_t stop_ns, stopped_ns; int have_last; + /* Sticky flag set whenever any collective, P2P, or EP op enters CUDA graph capture on this + * communicator (accessed via GCC atomics). On ncclCommAbort, a captured communicator cannot + * be proved idle via StreamQuery(last_stream) because graphs may replay on any stream. */ + int ever_captured; sccl_CUevent order_event; unsigned long long capture_id; sccl_CUstream capture_stream; @@ -468,15 +474,17 @@ struct sccl_engine { int watched; struct sccl_engine *watch_next; /* Point-to-point channels (see "point-to-point channels" below): the native library and context, the - * arena (host and device addresses, bytes, p2p_layout words, control line), every rank's p2p_out mask and - * this rank's channels, the windows of this rank's lanes (LIBSIRCL_P2P_WINDOWS), the kernels, the - * channels by direction (0: receive, 1: send) and peer, the event that orders a group's channels after - * the caller's stream, the lane check's duration, a failure to enqueue (which poisons the channels), the - * messages staged and the calls refused (no channel with the peer, or under CUDA graph capture). */ + * arena (host and device addresses, bytes, p2p_layout words, control line), the per-channel device + * counters ({seq, arrival} pairs, 2 * MAX_WORLD * 8 bytes), every rank's p2p_out mask and this rank's + * channels, the windows of this rank's lanes (LIBSIRCL_P2P_WINDOWS), the kernels, the channels by direction + * (0: receive, 1: send) and peer, the event that orders a group's channels after the caller's stream, the + * lane check's duration, a failure to enqueue (which poisons the channels), the messages staged and the + * calls refused (no channel with the peer, or graph staging without stream-ordered allocation). */ const p2p_ops *p2p_transport; void *p2p; uint8_t *p2p_host; sccl_CUdeviceptr p2p_dev; + sccl_CUdeviceptr p2p_counters; uint64_t p2p_bytes, p2p_layout[P2P_LAYOUT_WORDS]; int p2p_host_registered, p2p_host_emulated; volatile uint32_t *p2p_ctrl; @@ -484,11 +492,17 @@ struct sccl_engine { uint32_t p2p_window[MAX_WORLD][MAX_LANES]; int p2p_windowed; sccl_CUfunction p2p_fn[2]; + sccl_CUfunction ep_dispatch_fn, ep_combine_xfer_fn, ep_combine_reduce_fn[SCCL_DT_COUNT]; + /* Cooperative co-residency verification for SIRCL-EP (computed once in p2p_open with e->ctx current). */ + int ep_coop_ok; + char ep_coop_reason[256]; p2p_channel p2p_ch[2][MAX_WORLD]; sccl_CUevent p2p_ready; uint64_t p2p_check_ns; + /* Lock-free safe publication of p2p_fault: 0=empty, 1=writing, 2=published (GCC atomics). */ + int p2p_fault_state; char p2p_fault[300]; - _Atomic uint64_t p2p_staged, p2p_refused; + _Atomic uint64_t p2p_staged, p2p_refused, ep_dispatches, ep_combines; /* receipts */ _Atomic uint64_t ops[SCCL_ALG_COUNT][SCCL_DT_COUNT]; _Atomic uint64_t gather_calls, gather_ops, gather_bytes, gather_padded; @@ -987,8 +1001,9 @@ static int read_settings(sccl_engine *e, int emulation, char *err, size_t len) { put_error(err, len, "LIBSIRCL_WAIT_REGIME=%s: startup or serving", regime); return -1; } - e->serving = regime && !strcmp(regime, "serving"); - s->wait_regime = (uint32_t)e->serving; + int serving = regime && !strcmp(regime, "serving"); + __atomic_store_n(&e->serving, serving, __ATOMIC_RELAXED); + s->wait_regime = (uint32_t)serving; const char *stop = sccl_env("LIBSIRCL_FAIL_STOP"); if (stop && *stop && strcmp(stop, "0") && strcmp(stop, "1") && strcmp(stop, "abort")) { put_error(err, len, "LIBSIRCL_FAIL_STOP=%s: 0, 1 or abort", stop); @@ -1004,7 +1019,7 @@ static int read_settings(sccl_engine *e, int emulation, char *err, size_t len) { /* The list variables are parsed from 1,024-byte copies: a longer value is refused, not cut. */ static const char *const lists[] = {"SIRCL_PEER_ROUTES", "LIBSIRCL_FORWARD_WINDOWS", "LIBSIRCL_P2P_WINDOWS", "LIBSIRCL_RELAYED_LANES", "LIBSIRCL_CHAIN_ORDER", "SIRCL_GID_INDEX", - "SIRCL_PROGRESS_CPU", "LIBSIRCL_LINK_BLOCKS_CYCLE"}; + SCCL_ENV_PROGRESS_CPU, SCCL_ENV_P2P_PROGRESS_CPU, "LIBSIRCL_LINK_BLOCKS_CYCLE"}; for (size_t i = 0; i < sizeof lists / sizeof lists[0]; ++i) { const char *text = sccl_env(lists[i]); if (text && strlen(text) >= 1024) { @@ -1371,7 +1386,7 @@ static void format_cpus(const cpu_set_t *set, char *out, size_t len) { * under that set and this thread's own affinity is restored afterwards. Returns 0, 1 when the transport's * thread failed to start and 2 when the channels' thread did. */ static int start_progress(sccl_engine *e) { - const char *pinned = getenv("SIRCL_PROGRESS_CPU"); + const char *pinned = sccl_env(SCCL_ENV_PROGRESS_CPU); const char *policy = sccl_env("LIBSIRCL_CPU_POLICY"); snprintf(e->progress_cpus, sizeof e->progress_cpus, "%s", pinned && *pinned ? pinned : "unpinned"); cpu_set_t mine, fast; @@ -1873,8 +1888,10 @@ static void release_memory(sccl_engine *e) { for (int i = 0; i < e->retired; ++i) cu->MemFree(e->retired_stage[i]); free(e->retired_stage); e->retired_stage = NULL; - e->link_counters = e->piece_counters = e->link_scratch = e->stage = 0; - e->retired = e->retired_room = 0; + e->link_counters = e->piece_counters = e->link_scratch = 0; + __atomic_store_n(&e->stage, (sccl_CUdeviceptr)0, __ATOMIC_RELEASE); + __atomic_store_n(&e->retired, 0, __ATOMIC_RELEASE); + e->retired_room = 0; for (int i = 0; i < 2; ++i) if (e->scratch[i]) cu->MemFree(e->scratch[i]); if (e->host) { @@ -1925,6 +1942,8 @@ static int p2p_close(sccl_engine *e, int free_memory) { } if (e->p2p_ready) cu->EventDestroy(e->p2p_ready); e->p2p_ready = NULL; + if (e->p2p_counters) cu->MemFree(e->p2p_counters); + e->p2p_counters = 0; if (e->p2p_host) { if (e->p2p_host_registered) cu->MemHostUnregister(e->p2p_host); if (e->p2p_host_emulated) { @@ -1956,6 +1975,18 @@ static void p2p_stop_with_notices(sccl_engine *e, const char *why) { e->p2p_transport->stop(e->p2p); } +/* Stop the collective proxy so every peer learns of a local abort or fatal failure: write this rank's + * abort word (rank + 1) into the control line, wait up to P2P_NOTICE_WAIT_NS for the progress thread + * to post peer abort notices and fail, then stop it. */ +static void roce_stop_with_notices(sccl_engine *e) { + if (!e->proxy || !e->ctrl || e->stopped) return; + __atomic_store_n((uint32_t *)&e->ctrl[CTRL_ABORT], (uint32_t)e->rank + 1u, __ATOMIC_RELEASE); + uint64_t until = monotonic_ns() + P2P_NOTICE_WAIT_NS; + const struct timespec pause = {0, 100000}; + while (!e->transport->failed(e->proxy) && monotonic_ns() < until) nanosleep(&pause, NULL); + e->transport->stop(e->proxy); +} + /* After the first setup exchange gave every rank's p2p_out: ranks a and b have a channel when each one's lanes * toward the other can carry items, so every rank derives the same table. A rank without a channel still * opens a context (every rank's connection record is validated together); when no pair of the group has one, @@ -1999,16 +2030,79 @@ static int p2p_open(sccl_engine *e, const route_table *routes, char *err, size_t if (cuda_check(cu->MemHostGetDevicePointer(&e->p2p_dev, e->p2p_host, 0), "mapping the point-to-point arena", err, len)) return -1; + uint32_t counter_zeros[2 * MAX_WORLD * 2] = {0}; + if (cuda_check(cu->MemAlloc(&e->p2p_counters, sizeof counter_zeros), "allocating the point-to-point counters", err, + len) || + cuda_check(cu->MemcpyHtoD(e->p2p_counters, counter_zeros, sizeof counter_zeros), + "zeroing the point-to-point counters", err, len)) + return -1; e->p2p_ctrl = (volatile uint32_t *)e->p2p_host; - e->p2p_ctrl[P2P_C_WAIT_LIMIT_US] = e->serving ? s->serving_wait_us : s->startup_wait_us; + uint32_t p2p_wait = __atomic_load_n(&e->serving, __ATOMIC_ACQUIRE) ? s->serving_wait_us : s->startup_wait_us; + __atomic_store_n((uint32_t *)&e->p2p_ctrl[P2P_C_WAIT_LIMIT_US], p2p_wait, __ATOMIC_RELEASE); if (sccl_kp_p2p_function(e->ctx, 1, (int)s->p2p_unroll, &e->p2p_fn[1]) || - sccl_kp_p2p_function(e->ctx, 0, (int)s->p2p_unroll, &e->p2p_fn[0])) { + sccl_kp_p2p_function(e->ctx, 0, (int)s->p2p_unroll, &e->p2p_fn[0]) || + sccl_kp_ep_functions(e->ctx, &e->ep_dispatch_fn, &e->ep_combine_xfer_fn, e->ep_combine_reduce_fn)) { put_error(err, len, "%s", sccl_kp_error()); return -1; } + /* Verify cooperative launch and full-grid co-residency (2 * world CTAs) once here while e->ctx is + * current, so sirclEpDispatch and sirclEpCombine can fail closed if the device cannot co-schedule + * all sender and receiver CTAs simultaneously without risking co-scheduling deadlock. */ + e->ep_coop_ok = 0; + if (!cu->LaunchCooperativeKernel || !cu->OccupancyMaxActiveBlocksPerMultiprocessor) { + snprintf(e->ep_coop_reason, sizeof e->ep_coop_reason, + "CUDA driver lacks cuLaunchCooperativeKernel or cuOccupancyMaxActiveBlocksPerMultiprocessor"); + } else { + int coop = 0, sm_count = 0, max_dispatch = 0, max_combine = 0; + sccl_CUresult r1 = cu->DeviceGetAttribute(&coop, SCCL_CU_DEVICE_ATTRIBUTE_COOPERATIVE_LAUNCH, e->device); + sccl_CUresult r2 = cu->DeviceGetAttribute(&sm_count, SCCL_CU_DEVICE_ATTRIBUTE_MULTIPROCESSOR_COUNT, e->device); + sccl_CUresult r3 = + cu->OccupancyMaxActiveBlocksPerMultiprocessor(&max_dispatch, e->ep_dispatch_fn, SCCL_EP_THREADS, 0); + sccl_CUresult r4 = + cu->OccupancyMaxActiveBlocksPerMultiprocessor(&max_combine, e->ep_combine_xfer_fn, SCCL_EP_THREADS, 0); + unsigned need_ctas = (unsigned)(2 * e->world); + if (r1 != SCCL_CUDA_SUCCESS || r2 != SCCL_CUDA_SUCCESS || r3 != SCCL_CUDA_SUCCESS || r4 != SCCL_CUDA_SUCCESS) { + snprintf(e->ep_coop_reason, sizeof e->ep_coop_reason, + "querying cooperative launch occupancy failed (%s)", + sccl_cuda_result_text(r1 != SCCL_CUDA_SUCCESS ? r1 + : r2 != SCCL_CUDA_SUCCESS ? r2 + : r3 != SCCL_CUDA_SUCCESS ? r3 + : r4)); + } else if (!coop) { + snprintf(e->ep_coop_reason, sizeof e->ep_coop_reason, + "device %d does not support cooperative kernel launch (CU_DEVICE_ATTRIBUTE_COOPERATIVE_LAUNCH=0)", + e->device); + } else if (sm_count <= 0 || max_dispatch <= 0 || max_combine <= 0 || + (uint64_t)sm_count * (uint64_t)max_dispatch < need_ctas || + (uint64_t)sm_count * (uint64_t)max_combine < need_ctas) { + snprintf(e->ep_coop_reason, sizeof e->ep_coop_reason, + "device %d (%d SMs, dispatch=%d blocks/SM, combine=%d blocks/SM) cannot guarantee co-residency of " + "%u cooperative CTAs required for deadlock-free SIRCL-EP", + e->device, sm_count, max_dispatch, max_combine, need_ctas); + } else { + e->ep_coop_ok = 1; + } + } if (cuda_check(cu->EventCreate(&e->p2p_ready, SCCL_CU_EVENT_DISABLE_TIMING), "creating the point-to-point " "order event", err, len)) return -1; + /* Eagerly create every enabled channel's stream and join event here (outside CUDA graph capture), so a + * first send or receive inside a CUDA graph capture never creates CUDA objects. */ + for (int d = 0; d < 2; ++d) + for (int p = 0; p < e->world; ++p) { + if (!(e->p2p_channels >> p & 1u)) continue; + p2p_channel *ch = &e->p2p_ch[d][p]; + if (cuda_check(cu->StreamCreate(&ch->stream, SCCL_CU_STREAM_NON_BLOCKING), + "creating a point-to-point channel stream", err, len)) { + ch->stream = NULL; + return -1; + } + if (cuda_check(cu->EventCreate(&ch->done, SCCL_CU_EVENT_DISABLE_TIMING), + "creating a point-to-point channel event", err, len)) { + ch->done = NULL; + return -1; + } + } const char *names[MAX_DEVICES]; for (int d = 0; d < routes->n_devices; ++d) names[d] = routes->devices[d]; int lane_devices[MAX_WORLD * MAX_LANES], channels[MAX_WORLD]; @@ -2149,9 +2243,10 @@ static void fail_stop(sccl_engine *e, const char *found_by, const char *message) (void)pthread_create(&backstop, &attributes, fail_stop_backstop, NULL); pthread_attr_destroy(&attributes); } - /* Before the process ends, the channels' progress thread posts its abort notices, so the peers' channels - * stop now instead of at their wait limits (bounded; see p2p_stop_with_notices). */ + /* Before the process ends, both progress threads post their abort notices, so peers stop + * now instead of waiting out their wait limits (bounded; see p2p_stop_with_notices / roce_stop_with_notices). */ p2p_stop_with_notices(e, message); + roce_stop_with_notices(e); char line[1200]; uint64_t now = realtime_ns(), mono = monotonic_ns(); int n = snprintf(line, sizeof line, @@ -2437,7 +2532,9 @@ int sccl_engine_create(sccl_bootstrap *bootstrap, int nranks, int rank, int posi break; } if (allocate(e, local, sizeof local)) break; - e->ctrl[CTRL_WAIT_LIMIT_US] = e->serving ? e->shared.serving_wait_us : e->shared.startup_wait_us; + uint32_t wait_us = __atomic_load_n(&e->serving, __ATOMIC_ACQUIRE) ? e->shared.serving_wait_us + : e->shared.startup_wait_us; + __atomic_store_n((uint32_t *)&e->ctrl[CTRL_WAIT_LIMIT_US], wait_us, __ATOMIC_RELEASE); const char *names[MAX_DEVICES]; for (int d = 0; d < routes.n_devices; ++d) names[d] = routes.devices[d]; int lane_devices[MAX_WORLD * MAX_LANES]; @@ -2663,12 +2760,13 @@ static int grid_class(unsigned grid) { static int timed_out(const sccl_engine *e, char *message, size_t len) { uint32_t seq = __atomic_load_n(&e->ctrl[CTRL_ERROR_SEQ], __ATOMIC_ACQUIRE); if (!seq) return 0; + int serving = __atomic_load_n(&e->serving, __ATOMIC_ACQUIRE); put_error(message, len, "rank %d: a flag wait for rank %u lane %u timed out at sequence %u (wait limit %.6g s, %s regime); " "the session is poisoned", e->rank, e->ctrl[CTRL_MISSING_PEER], e->ctrl[CTRL_MISSING_LANE], seq, - (e->serving ? e->shared.serving_wait_us : e->shared.startup_wait_us) / 1e6, - e->serving ? "serving" : "startup"); + (serving ? e->shared.serving_wait_us : e->shared.startup_wait_us) / 1e6, + serving ? "serving" : "startup"); return 1; } @@ -2695,8 +2793,10 @@ static ncclResult_t p2p_health(sccl_engine *e, char *message, size_t len) { if (!tag && !poison && !failed) return ncclSuccess; char kernel[400] = {0}; ncclResult_t code = ncclRemoteError; - double limit = (e->serving ? e->shared.serving_wait_us : e->shared.startup_wait_us) / 1e6; - const char *regime = e->serving ? "serving" : "startup"; + int serving = __atomic_load_n(&e->serving, __ATOMIC_ACQUIRE); + double limit = (serving ? e->shared.serving_wait_us : e->shared.startup_wait_us) / 1e6; + const char *regime = serving ? "serving" : "startup"; + int has_fault = __atomic_load_n(&e->p2p_fault_state, __ATOMIC_ACQUIRE) == 2; if (tag) { uint32_t kind = e->p2p_ctrl[P2P_C_ERROR_KIND], peer = e->p2p_ctrl[P2P_C_ERROR_PEER]; uint32_t lane = e->p2p_ctrl[P2P_C_ERROR_LANE], item = tag - 1u; @@ -2716,12 +2816,12 @@ static ncclResult_t p2p_health(sccl_engine *e, char *message, size_t len) { } else { snprintf(kernel, sizeof kernel, "a kernel stopped (error kind %u)", kind); } - } else if (e->p2p_fault[0]) { + } else if (has_fault) { snprintf(kernel, sizeof kernel, "a channel op could not be enqueued: %s", e->p2p_fault); code = ncclUnhandledCudaError; } if (failed) { - if (!tag && !e->p2p_fault[0] && !e->p2p_transport->stat(e->p2p, P2P_STAT_ABORT_FROM)) code = ncclSystemError; + if (!tag && !has_fault && !e->p2p_transport->stat(e->p2p, P2P_STAT_ABORT_FROM)) code = ncclSystemError; put_error(message, len, "rank %d: point-to-point channels failed: %s%s%s", e->rank, e->p2p_transport->error(e->p2p), kernel[0] ? "; on this rank " : "", kernel); } else { @@ -2743,7 +2843,7 @@ static ncclResult_t session_error(sccl_engine *e, char *message, size_t len) { put_error(message, len, "rank %d: native progress thread failed: %s%s%s", e->rank, e->transport->error(e->proxy), timeout ? "; then " : "", timeout ? waited : ""); if (!atomic_exchange(&e->link_dumped, 1)) dump_links(e, "the native progress thread failed", 0); - return ncclSystemError; + return e->transport->stat(e->proxy, ROCE_STAT_ABORT_FROM) ? ncclRemoteError : ncclSystemError; } if (timeout) { put_error(message, len, "%s", waited); @@ -3029,8 +3129,11 @@ static ncclResult_t stage_buffer(sccl_engine *e, uint64_t bytes, int capturing, sccl_CUdeviceptr fresh = 0; if (cuda_check(cu->MemAlloc(&fresh, size), "allocating the link staging buffer", err, len)) return ncclUnhandledCudaError; - if (e->stage) e->retired_stage[e->retired++] = e->stage; - e->stage = fresh; + if (e->stage) { + e->retired_stage[e->retired] = e->stage; + __atomic_store_n(&e->retired, e->retired + 1, __ATOMIC_RELEASE); + } + __atomic_store_n(&e->stage, fresh, __ATOMIC_RELEASE); e->stage_bytes = size; } atomic_fetch_add_explicit(&e->link_staged, 1, memory_order_relaxed); @@ -3248,9 +3351,11 @@ static ncclResult_t begin_call(sccl_engine *e, const char *what, sccl_CUstream s len)) { result = ncclUnhandledCudaError; } else if (status == SCCL_CU_STREAM_CAPTURE_STATUS_INVALIDATED) { + __atomic_store_n(&e->ever_captured, 1, __ATOMIC_RELEASE); put_error(err, len, "%s: the stream's capture is invalidated", what); result = ncclInvalidUsage; } else if (status == SCCL_CU_STREAM_CAPTURE_STATUS_ACTIVE) { + __atomic_store_n(&e->ever_captured, 1, __ATOMIC_RELEASE); call->capturing = 1; if (capture != e->capture_id) { e->capture_id = capture; @@ -4304,7 +4409,11 @@ static const char *p2p_refusal(const sccl_engine *e, int peer, char *out, size_t * later message land in the wrong receive. */ static void p2p_fault(sccl_engine *e, const char *why) { if (!e->p2p_ctrl) return; - if (!e->p2p_fault[0]) snprintf(e->p2p_fault, sizeof e->p2p_fault, "%s", why && *why ? why : "unknown failure"); + int expected = 0; + if (__atomic_compare_exchange_n(&e->p2p_fault_state, &expected, 1, 0, __ATOMIC_ACQ_REL, __ATOMIC_RELAXED)) { + snprintf(e->p2p_fault, sizeof e->p2p_fault, "%s", why && *why ? why : "unknown failure"); + __atomic_store_n(&e->p2p_fault_state, 2, __ATOMIC_RELEASE); + } __atomic_store_n((uint32_t *)&e->p2p_ctrl[P2P_C_POISON], 1u, __ATOMIC_RELEASE); } @@ -4328,9 +4437,11 @@ static ncclResult_t p2p_channel_ready(sccl_engine *e, p2p_channel *ch, char *err /* A staging buffer of `bytes` on the channel's stream, for a message that is not 16-byte aligned or not whole * packs (SIRCL's session stages these too): a stream-ordered allocation that the caller frees on the stream * after the launch where the driver and device have them (`*ordered` set), else the channel's own buffer, - * grown when too small (the old one is kept until destroy: work queued on the stream may still use it). */ -static ncclResult_t p2p_stage(sccl_engine *e, p2p_channel *ch, uint64_t bytes, sccl_CUdeviceptr *out, int *ordered, - char *err, size_t len) { + * grown when too small (the old one is kept until destroy: work queued on the stream may still use it). Under + * CUDA graph capture without stream-ordered allocation, a size larger than the channel's existing buffer is + * refused until an eager call grows it. */ +static ncclResult_t p2p_stage(sccl_engine *e, p2p_channel *ch, uint64_t bytes, int capturing, sccl_CUdeviceptr *out, + int *ordered, char *err, size_t len) { *ordered = 0; if (e->shared.graph_staging) { if (cuda_check(cu->MemAllocAsync(out, bytes, ch->stream), "allocating point-to-point staging", err, len)) @@ -4339,12 +4450,21 @@ static ncclResult_t p2p_stage(sccl_engine *e, p2p_channel *ch, uint64_t bytes, s return ncclSuccess; } if (bytes > ch->stage_bytes) { + if (capturing) { + put_error(err, len, "a point-to-point channel op on unaligned or non-pack-multiple buffers needs %" PRIu64 + " bytes of staging, and this driver or device has no stream-ordered allocation for CUDA graph " + "capture; issue one such call eagerly before capturing", bytes); + return ncclInvalidUsage; + } if (ch->stage && reserve_retired(e, err, len)) return ncclSystemError; uint64_t size = ch->stage_bytes * 2 > bytes ? ch->stage_bytes * 2 : bytes; sccl_CUdeviceptr fresh = 0; if (cuda_check(cu->MemAlloc(&fresh, size), "allocating point-to-point staging", err, len)) return ncclUnhandledCudaError; - if (ch->stage) e->retired_stage[e->retired++] = ch->stage; + if (ch->stage) { + e->retired_stage[e->retired] = ch->stage; + __atomic_store_n(&e->retired, e->retired + 1, __ATOMIC_RELEASE); + } ch->stage = fresh; ch->stage_bytes = size; } @@ -4352,11 +4472,11 @@ static ncclResult_t p2p_stage(sccl_engine *e, p2p_channel *ch, uint64_t bytes, s return ncclSuccess; } -/* One message on its channel's stream: items(n) items from the channel's next item (SIRCL's protocol.items), - * one launch of min(SIRCL_P2P_BLOCKS, items) blocks; a buffer that is not 16-byte aligned or not whole packs - * goes through staging (a send copies into it first, a receive lands in it and copies out). The channel's - * counter advances only when the launch was enqueued. */ -static ncclResult_t p2p_launch(sccl_engine *e, int send, const sccl_p2p_op *op, char *err, size_t len) { +/* One message on its channel's stream: items(n) items from the channel's device sequence counter (SIRCL's + * protocol.items), one launch of min(SIRCL_P2P_BLOCKS, items) blocks; a buffer that is not 16-byte aligned or + * not whole packs goes through staging (a send copies into it first, a receive lands in it and copies out). + * The kernel reads and advances the channel's device counter on every execution (eager or CUDA-graph replay). */ +static ncclResult_t p2p_launch(sccl_engine *e, int send, const sccl_p2p_op *op, int capturing, char *err, size_t len) { const shared_settings *s = &e->shared; p2p_channel *ch = &e->p2p_ch[send][op->peer]; uint64_t n = op->bytes, padded = round_up(n, PACK); @@ -4365,7 +4485,7 @@ static ncclResult_t p2p_launch(sccl_engine *e, int send, const sccl_p2p_op *op, int ordered = 0, direct = n == 0 || (buffer % PACK == 0 && n % PACK == 0); ncclResult_t result = ncclSuccess; if (!direct) { - result = p2p_stage(e, ch, padded, &stage, &ordered, err, len); + result = p2p_stage(e, ch, padded, capturing, &stage, &ordered, err, len); if (result != ncclSuccess) return result; if (send && cuda_check(copy_async(e, stage, buffer, n, ch->stream), "staging a channel send", err, len)) result = ncclUnhandledCudaError; @@ -4378,11 +4498,11 @@ static ncclResult_t p2p_launch(sccl_engine *e, int send, const sccl_p2p_op *op, a.block_base = e->p2p_dev + e->p2p_layout[P2P_L_CONTROL] + (uint64_t)op->peer * e->p2p_layout[P2P_L_BLOCK]; a.ctrl_base = e->p2p_dev; a.slot_bytes = s->p2p_slot_bytes; + a.counter_ptr = e->p2p_counters + (uint64_t)(send * MAX_WORLD + op->peer) * 8u; a.packs = (int32_t)(padded / PACK); a.tail = (int32_t)(n % PACK); a.items = (int32_t)items; a.peer = op->peer; - a.first = ch->next; a.slots = s->p2p_slots; a.lanes = (uint32_t)e->lanes; a.recv_off = e->p2p_layout[P2P_L_RECV]; @@ -4399,7 +4519,6 @@ static ncclResult_t p2p_launch(sccl_engine *e, int send, const sccl_p2p_op *op, send ? "launching a channel send" : "launching a channel receive", err, len)) { result = ncclUnhandledCudaError; } else { - ch->next += (uint32_t)items; atomic_fetch_add_explicit(&ch->messages, 1, memory_order_relaxed); atomic_fetch_add_explicit(&ch->bytes, n, memory_order_relaxed); atomic_fetch_add_explicit(&ch->items, items, memory_order_relaxed); @@ -4421,9 +4540,10 @@ static ncclResult_t p2p_launch(sccl_engine *e, int send, const sccl_p2p_op *op, * issue order on its channel's stream after `stream` reached the group (so a receive waiting for its peer holds * back nothing but later items of its own channel, and every send of the group is queued ahead of the group's * receives); then `stream` waits for every channel stream the group used, so later work on it, and the - * stream's completion, follow the group's transfers. A failure to enqueue poisons the channels. */ -static ncclResult_t p2p_group(sccl_engine *e, const sccl_p2p_op *ops, unsigned count, sccl_CUstream stream, char *err, - size_t len) { + * stream's completion, follow the group's transfers. Under CUDA graph capture, the event fork/join captures + * every channel stream's work into `stream`'s graph. A failure to enqueue poisons the channels. */ +static ncclResult_t p2p_group(sccl_engine *e, const sccl_p2p_op *ops, unsigned count, int capturing, + sccl_CUstream stream, char *err, size_t len) { if (cuda_check(cu->EventRecord(e->p2p_ready, stream), "recording the point-to-point order event", err, len)) { p2p_fault(e, err); return ncclUnhandledCudaError; @@ -4441,7 +4561,7 @@ static ncclResult_t p2p_group(sccl_engine *e, const sccl_p2p_op *ops, unsigned c else ch->joined = 1; } - if (result == ncclSuccess) result = p2p_launch(e, send, op, err, len); + if (result == ncclSuccess) result = p2p_launch(e, send, op, capturing, err, len); } for (int d = 0; d < 2; ++d) for (int p = 0; p < e->world; ++p) { @@ -4522,18 +4642,28 @@ ncclResult_t sccl_engine_p2p(sccl_engine *e, const sccl_p2p_op *ops, unsigned co call_state call; ncclResult_t result = begin_call(e, ops[0].send ? "ncclSend" : "ncclRecv", stream, &call, err, len); if (result != ncclSuccess) return result; - /* Communicators of more than two ranks: the calls to other ranks as channel items (not under CUDA graph - * capture: a replay would reuse the item numbers fixed at enqueue), the sends to the rank itself as copies. */ + /* Communicators of more than two ranks: the calls to other ranks as channel items (eager or CUDA-graph + * captured; each channel advances its device sequence counter on every launch/replay), the sends to the + * rank itself as copies. Pre-check graph staging without stream-ordered allocation before touching any + * channel stream so a refusal never poisons the communicator. */ if (e->world > 2 && nsend[0] + nrecv[0]) { - if (call.capturing) { - atomic_fetch_add_explicit(&e->p2p_refused, 1, memory_order_relaxed); - put_error(err, len, "%s: point-to-point channel items cannot be captured in a CUDA graph (a replay would reuse " - "the item numbers fixed at enqueue); issue them outside the capture", ops[0].send ? "ncclSend" - : "ncclRecv"); - result = ncclInvalidUsage; - } else { - result = p2p_group(e, ops, count, stream, err, len); + if (call.capturing && !e->shared.graph_staging) { + for (unsigned i = 0; i < count && result == ncclSuccess; ++i) { + const sccl_p2p_op *op = &ops[i]; + if (op->peer == e->rank) continue; + uint64_t n = op->bytes, padded = round_up(n, PACK); + sccl_CUdeviceptr buffer = (sccl_CUdeviceptr)(uintptr_t)op->buff; + int direct = n == 0 || (buffer % PACK == 0 && n % PACK == 0); + if (!direct && padded > e->p2p_ch[op->send][op->peer].stage_bytes) { + atomic_fetch_add_explicit(&e->p2p_refused, 1, memory_order_relaxed); + put_error(err, len, "a point-to-point channel op on unaligned or non-pack-multiple buffers needs %" PRIu64 + " bytes of staging, and this driver or device has no stream-ordered allocation for CUDA graph " + "capture; issue one such call eagerly before capturing", padded); + result = ncclInvalidUsage; + } + } } + if (result == ncclSuccess) result = p2p_group(e, ops, count, call.capturing, stream, err, len); } /* The all-to-all of two ranks as point-to-point calls (torch's pattern, and nccl-tests' below NCCL API * level 22800): one send to and one receive from the peer and one send to and receive from this rank @@ -4586,6 +4716,222 @@ ncclResult_t sccl_engine_p2p(sccl_engine *e, const sccl_p2p_op *ops, unsigned co return end_call(e, &call, result, err, len); } +/* -- SIRCL-EP: GPU-driven dynamic variable-length MoE dispatch & combine ------------------------------- */ + +size_t sccl_engine_ep_workspace_bytes(int world, int max_tokens, size_t hidden_bytes) { + if (world < 1 || world > MAX_WORLD || max_tokens < 1 || hidden_bytes < PACK || (hidden_bytes % PACK) != 0) return 0; + uint64_t w = (uint64_t)world, m = (uint64_t)max_tokens, h = (uint64_t)hidden_bytes; + if (m > UINT64_MAX / w / 4u) return 0; + uint64_t idx_bytes = round_up(w * m * 4u, 64u); + if (h > (UINT64_MAX - 64u - 2u * idx_bytes) / (w * m)) return 0; + uint64_t recv_bytes = round_up(w * m * h, 64u); + return (size_t)(64u + 2u * idx_bytes + recv_bytes); +} + +static ncclResult_t ep_check_ready(sccl_engine *e, const char *what, char *err, size_t len) { + if (e->world < 3 || !e->shared.p2p_on || !e->p2p) { + put_error(err, len, "%s: requires a communicator of 3 to %d ranks created with LIBSIRCL_P2P_CHANNELS=on", what, + MAX_WORLD); + return ncclInvalidUsage; + } + if (!e->ep_coop_ok) { + put_error(err, len, "%s: cooperative co-scheduling unavailable: %s", what, + e->ep_coop_reason[0] ? e->ep_coop_reason : "unknown reason"); + return ncclInvalidUsage; + } + for (int p = 0; p < e->world; ++p) { + if (p == e->rank) continue; + char why[400]; + if (p2p_refusal(e, p, why, sizeof why)) { + atomic_fetch_add_explicit(&e->p2p_refused, 1, memory_order_relaxed); + put_error(err, len, "%s: rank %d: %s", what, p, why); + return ncclInvalidUsage; + } + } + char message[400]; + ncclResult_t health = sccl_engine_async_error(e, message, sizeof message); + if (health != ncclSuccess) { + put_error(err, len, "%s", message); + return health; + } + return ncclSuccess; +} + +static void ep_fill_common(const sccl_engine *e, sccl_ep_args *a, void *workspace, int num_tokens, int max_tokens, + size_t hidden_bytes, int top_k, int num_experts, uint32_t wire_row_bytes) { + memset(a, 0, sizeof *a); + a->workspace = (sccl_CUdeviceptr)(uintptr_t)workspace; + a->p2p_dev = e->p2p_dev; + a->p2p_counters = e->p2p_counters; + a->layout_control = e->p2p_layout[P2P_L_CONTROL]; + a->layout_block = e->p2p_layout[P2P_L_BLOCK]; + a->slot_bytes = e->shared.p2p_slot_bytes; + a->recv_off = e->p2p_layout[P2P_L_RECV]; + a->send_off = e->p2p_layout[P2P_L_SEND]; + a->flag_off = e->p2p_layout[P2P_L_FLAG]; + a->desc_off = e->p2p_layout[P2P_L_DESC]; + a->ready_off = e->p2p_layout[P2P_L_READY]; + a->consumed_off = e->p2p_layout[P2P_L_CONSUMED]; + a->sent_off = e->p2p_layout[P2P_L_SENT]; + a->world = e->world; + a->rank = e->rank; + a->num_tokens = num_tokens; + a->max_tokens = max_tokens; + a->hidden_bytes = (int32_t)hidden_bytes; + a->top_k = top_k; + a->num_experts = num_experts; + a->slots = e->shared.p2p_slots; + a->lanes = (uint32_t)e->lanes; + a->wire_row_bytes = wire_row_bytes; +} + +ncclResult_t sccl_engine_ep_dispatch(sccl_engine *e, const void *hidden_in, const int *topk_ids_in, + const float *topk_weights_in, void *hidden_out, int *topk_ids_out, + float *topk_weights_out, int *recv_counts_out, void *workspace, + size_t workspace_bytes, int num_tokens, int max_tokens, size_t hidden_bytes, + int top_k, int num_experts, cudaStream_t stream_handle, char *err, size_t len) { + ncclResult_t ready = ep_check_ready(e, "sirclEpDispatch", err, len); + if (ready != ncclSuccess) return ready; + if (max_tokens < 1 || num_tokens < 0 || num_tokens > max_tokens) { + put_error(err, len, "sirclEpDispatch: invalid num_tokens=%d max_tokens=%d", num_tokens, max_tokens); + return ncclInvalidArgument; + } + if (hidden_bytes < PACK || (hidden_bytes % PACK) != 0 || hidden_bytes > (size_t)INT32_MAX) { + put_error(err, len, "sirclEpDispatch: hidden_bytes=%zu must be a positive multiple of 16", hidden_bytes); + return ncclInvalidArgument; + } + if (top_k < 1 || top_k > SCCL_EP_MAX_TOPK) { + put_error(err, len, "sirclEpDispatch: top_k=%d must be in 1..%d", top_k, SCCL_EP_MAX_TOPK); + return ncclInvalidArgument; + } + if (num_experts < e->world || (num_experts % e->world) != 0) { + put_error(err, len, "sirclEpDispatch: num_experts=%d must be a positive multiple of world=%d", num_experts, + e->world); + return ncclInvalidArgument; + } + uint64_t wire_row = round_up((uint64_t)hidden_bytes + (uint64_t)top_k * 8u, PACK); + if (wire_row > e->shared.p2p_slot_bytes || wire_row > UINT32_MAX) { + put_error(err, len, "sirclEpDispatch: wire row (%" PRIu64 " bytes) exceeds SIRCL_P2P_SLOT_BYTES (%" PRIu64 ")", + wire_row, e->shared.p2p_slot_bytes); + return ncclInvalidArgument; + } + size_t need = sccl_engine_ep_workspace_bytes(e->world, max_tokens, hidden_bytes); + if (!workspace || workspace_bytes < need || ((uintptr_t)workspace % PACK) != 0) { + put_error(err, len, "sirclEpDispatch: workspace must be 16-byte aligned and at least %zu bytes (got %zu)", need, + workspace_bytes); + return ncclInvalidArgument; + } + if (!hidden_out || !topk_ids_out || !topk_weights_out || ((uintptr_t)hidden_out % PACK) != 0) { + put_error(err, len, "sirclEpDispatch: output buffers must be non-NULL and hidden_out 16-byte aligned"); + return ncclInvalidArgument; + } + if (num_tokens > 0 && + (!hidden_in || !topk_ids_in || !topk_weights_in || ((uintptr_t)hidden_in % PACK) != 0)) { + put_error(err, len, "sirclEpDispatch: input buffers must be non-NULL and hidden_in 16-byte aligned"); + return ncclInvalidArgument; + } + sccl_CUstream stream = (sccl_CUstream)stream_handle; + call_state call; + ncclResult_t result = begin_call(e, "sirclEpDispatch", stream, &call, err, len); + if (result != ncclSuccess) return result; + sccl_ep_args a; + ep_fill_common(e, &a, workspace, num_tokens, max_tokens, hidden_bytes, top_k, num_experts, (uint32_t)wire_row); + a.hidden_in = (sccl_CUdeviceptr)(uintptr_t)hidden_in; + a.topk_ids_in = (sccl_CUdeviceptr)(uintptr_t)topk_ids_in; + a.topk_weights_in = (sccl_CUdeviceptr)(uintptr_t)topk_weights_in; + a.hidden_out = (sccl_CUdeviceptr)(uintptr_t)hidden_out; + a.topk_ids_out = (sccl_CUdeviceptr)(uintptr_t)topk_ids_out; + a.topk_weights_out = (sccl_CUdeviceptr)(uintptr_t)topk_weights_out; + a.recv_counts_out = (sccl_CUdeviceptr)(uintptr_t)recv_counts_out; + if (cuda_check(sccl_kp_launch_ep_cooperative(e->ep_dispatch_fn, &a, (unsigned)(2 * e->world), SCCL_EP_THREADS, + stream), + "launching sircl_ep_dispatch", err, len)) { + p2p_fault(e, err); + result = ncclUnhandledCudaError; + } else { + atomic_fetch_add_explicit(&e->ep_dispatches, 1, memory_order_relaxed); + if (call.capturing) atomic_fetch_add_explicit(&e->captured_calls, 1, memory_order_relaxed); + } + return end_call(e, &call, result, err, len); +} + +ncclResult_t sccl_engine_ep_combine(sccl_engine *e, const void *expert_out_in, void *hidden_out, void *workspace, + size_t workspace_bytes, int num_tokens, int max_tokens, size_t hidden_dim, + ncclDataType_t datatype, cudaStream_t stream_handle, char *err, size_t len) { + ncclResult_t ready = ep_check_ready(e, "sirclEpCombine", err, len); + if (ready != ncclSuccess) return ready; + int dt = -1; + size_t elem_bytes = 0; + if (datatype == ncclFloat32) { + dt = SCCL_DT_F32; + elem_bytes = 4; + } else if (datatype == ncclFloat16) { + dt = SCCL_DT_F16; + elem_bytes = 2; + } else if (datatype == ncclBfloat16) { + dt = SCCL_DT_BF16; + elem_bytes = 2; + } else { + put_error(err, len, "sirclEpCombine: unsupported datatype %d (expected float32, float16, or bfloat16)", + (int)datatype); + return ncclInvalidArgument; + } + if (max_tokens < 1 || num_tokens < 0 || num_tokens > max_tokens) { + put_error(err, len, "sirclEpCombine: invalid num_tokens=%d max_tokens=%d", num_tokens, max_tokens); + return ncclInvalidArgument; + } + if (hidden_dim == 0 || hidden_dim > (size_t)INT32_MAX / elem_bytes) { + put_error(err, len, "sirclEpCombine: invalid hidden_dim=%zu", hidden_dim); + return ncclInvalidArgument; + } + size_t hidden_bytes = hidden_dim * elem_bytes; + if (hidden_bytes < PACK || (hidden_bytes % PACK) != 0 || hidden_bytes > e->shared.p2p_slot_bytes) { + put_error(err, len, "sirclEpCombine: hidden_bytes=%zu must be a positive multiple of 16 within slot bytes", + hidden_bytes); + return ncclInvalidArgument; + } + size_t need = sccl_engine_ep_workspace_bytes(e->world, max_tokens, hidden_bytes); + if (!workspace || workspace_bytes < need || ((uintptr_t)workspace % PACK) != 0) { + put_error(err, len, "sirclEpCombine: workspace must be 16-byte aligned and at least %zu bytes (got %zu)", need, + workspace_bytes); + return ncclInvalidArgument; + } + if (!expert_out_in || ((uintptr_t)expert_out_in % PACK) != 0) { + put_error(err, len, "sirclEpCombine: expert_out_in must be non-NULL and 16-byte aligned"); + return ncclInvalidArgument; + } + if (num_tokens > 0 && (!hidden_out || ((uintptr_t)hidden_out % PACK) != 0)) { + put_error(err, len, "sirclEpCombine: hidden_out must be non-NULL and 16-byte aligned"); + return ncclInvalidArgument; + } + sccl_CUstream stream = (sccl_CUstream)stream_handle; + call_state call; + ncclResult_t result = begin_call(e, "sirclEpCombine", stream, &call, err, len); + if (result != ncclSuccess) return result; + sccl_ep_args a; + ep_fill_common(e, &a, workspace, num_tokens, max_tokens, hidden_bytes, 0, 0, (uint32_t)hidden_bytes); + a.hidden_in = (sccl_CUdeviceptr)(uintptr_t)expert_out_in; + a.hidden_out = (sccl_CUdeviceptr)(uintptr_t)hidden_out; + if (cuda_check(sccl_kp_launch_ep_cooperative(e->ep_combine_xfer_fn, &a, (unsigned)(2 * e->world), SCCL_EP_THREADS, + stream), + "launching sircl_ep_combine_xfer", err, len)) { + p2p_fault(e, err); + result = ncclUnhandledCudaError; + } else if (num_tokens > 0) { + unsigned grid = num_tokens < 64 ? (unsigned)num_tokens : 64u; + if (cuda_check(sccl_kp_launch_ep(e->ep_combine_reduce_fn[dt], &a, grid, SCCL_EP_THREADS, stream), + "launching sircl_ep_combine_reduce", err, len)) { + p2p_fault(e, err); + result = ncclUnhandledCudaError; + } + } + if (result == ncclSuccess) { + atomic_fetch_add_explicit(&e->ep_combines, 1, memory_order_relaxed); + if (call.capturing) atomic_fetch_add_explicit(&e->captured_calls, 1, memory_order_relaxed); + } + return end_call(e, &call, result, err, len); +} + ncclResult_t sccl_engine_teardown_sync(sccl_engine *e) { if (!e || !cu) return ncclSuccess; pthread_mutex_lock(&e->lock); @@ -4605,7 +4951,8 @@ ncclResult_t sccl_engine_teardown_sync(sccl_engine *e) { } int sccl_engine_wait_limit_ms(const sccl_engine *e) { - uint64_t us = e->serving ? e->shared.serving_wait_us : e->shared.startup_wait_us; + int serving = __atomic_load_n(&e->serving, __ATOMIC_ACQUIRE); + uint64_t us = serving ? e->shared.serving_wait_us : e->shared.startup_wait_us; uint64_t ms = (us + 999) / 1000; return ms < 1 ? 1 : ms > INT32_MAX ? INT32_MAX : (int)ms; } @@ -4616,11 +4963,12 @@ ncclResult_t sccl_engine_finalize(sccl_engine *e) { ncclResult_t sccl_engine_set_wait_regime(sccl_engine *e, const char *regime) { if (!regime || (strcmp(regime, "startup") && strcmp(regime, "serving"))) return ncclInvalidArgument; - e->serving = !strcmp(regime, "serving"); - /* A plain host store: the next launch's kernels read it, eager or replayed. */ - if (e->ctrl) e->ctrl[CTRL_WAIT_LIMIT_US] = e->serving ? e->shared.serving_wait_us : e->shared.startup_wait_us; - if (e->p2p_ctrl) - e->p2p_ctrl[P2P_C_WAIT_LIMIT_US] = e->serving ? e->shared.serving_wait_us : e->shared.startup_wait_us; + int serving = !strcmp(regime, "serving"); + uint32_t limit = serving ? e->shared.serving_wait_us : e->shared.startup_wait_us; + __atomic_store_n(&e->serving, serving, __ATOMIC_RELEASE); + /* Atomic release store: the next launch's kernels read it, eager or replayed. */ + if (e->ctrl) __atomic_store_n((uint32_t *)&e->ctrl[CTRL_WAIT_LIMIT_US], limit, __ATOMIC_RELEASE); + if (e->p2p_ctrl) __atomic_store_n((uint32_t *)&e->p2p_ctrl[P2P_C_WAIT_LIMIT_US], limit, __ATOMIC_RELEASE); return ncclSuccess; } @@ -4668,167 +5016,269 @@ static uint64_t realtime_ns(void) { return (uint64_t)t.tv_sec * 1000000000ull + (uint64_t)t.tv_nsec; } +/* Growable JSON string builder for receipts: never truncates mid-object in a fixed intermediate buffer, + * and falls back cleanly to valid minimal JSON on OOM. */ +typedef struct { + char *data; + size_t len, cap; + int oom; +} json_buf; + +static void jb_init(json_buf *b) { + b->data = NULL; + b->len = 0; + b->cap = 0; + b->oom = 0; +} + +static void jb_free(json_buf *b) { + free(b->data); + b->data = NULL; + b->len = b->cap = 0; +} + +static int jb_reserve(json_buf *b, size_t extra) { + if (b->oom) return -1; + if (extra > SIZE_MAX - b->len - 1) { + b->oom = 1; + return -1; + } + size_t need = b->len + extra + 1; + if (need <= b->cap) return 0; + size_t cap = b->cap ? b->cap : 4096; + while (cap < need) { + if (cap > SIZE_MAX / 2) { + cap = need; + break; + } + cap *= 2; + } + char *grown = realloc(b->data, cap); + if (!grown) { + b->oom = 1; + return -1; + } + b->data = grown; + b->cap = cap; + return 0; +} + +static void jb_appendf(json_buf *b, const char *fmt, ...) __attribute__((format(printf, 2, 3))); +static void jb_appendf(json_buf *b, const char *fmt, ...) { + if (b->oom) return; + va_list ap, copy; + va_start(ap, fmt); + va_copy(copy, ap); + int n = vsnprintf(NULL, 0, fmt, copy); + va_end(copy); + if (n < 0) { + va_end(ap); + b->oom = 1; + return; + } + if (jb_reserve(b, (size_t)n) == 0) { + vsnprintf(b->data + b->len, b->cap - b->len, fmt, ap); + b->len += (size_t)n; + } + va_end(ap); +} + +static void jb_append_json_string(json_buf *b, const char *text) { + if (b->oom) return; + if (!text) { + jb_appendf(b, "null"); + return; + } + jb_appendf(b, "\""); + for (const unsigned char *c = (const unsigned char *)text; *c && !b->oom; ++c) { + if (*c == '"' || *c == '\\') { + jb_appendf(b, "\\%c", (char)*c); + } else if (*c < 0x20) { + jb_appendf(b, "\\u%04x", *c); + } else if (jb_reserve(b, 1) == 0) { + b->data[b->len++] = (char)*c; + b->data[b->len] = 0; + } + } + jb_appendf(b, "\""); +} + /* The receipt's "channels" object: the setting, geometry and arena, this rank's channel peers and the windows * of its lanes toward them, the lane check, per peer the messages, bytes and items sent and received, the * messages staged, the calls refused, and the native counters (SIRCL's p2p_stat). */ -static void p2p_receipt(sccl_engine *e, char *out, size_t len) { +static void p2p_receipt_append(sccl_engine *e, json_buf *b) { if (!e->shared.p2p_on) { - snprintf(out, len, "{\"on\":false,\"refused\":%" PRIu64 "}", atomic_load(&e->p2p_refused)); + jb_appendf(b, "{\"on\":false,\"refused\":%" PRIu64 "}", atomic_load(&e->p2p_refused)); return; } - char peers[64] = {0}, windows[256] = {0}, flows[2][768]; - size_t used = 0, wused = 0; + void *c = e->p2p; + const p2p_ops *t = e->p2p_transport; + jb_appendf(b, "{\"on\":true,\"context\":%s,\"peers\":[", c ? "true" : "false"); + int first = 1; + for (int p = 0; p < e->world; ++p) { + if (!(e->p2p_channels >> p & 1u)) continue; + jb_appendf(b, "%s%d", first ? "" : ",", p); + first = 0; + } + jb_appendf(b, "],\"slots\":%u,\"slot_bytes\":%" PRIu64 ",\"blocks\":%u,\"threads\":%u,\"unroll\":%u," + "\"chunk_bytes\":%u,\"arena_bytes\":%" PRIu64 ",\"windows\":{", + e->shared.p2p_slots, e->shared.p2p_slot_bytes, e->shared.p2p_blocks, e->shared.p2p_threads, + e->shared.p2p_unroll, e->shared.p2p_chunk, e->p2p_bytes); + first = 1; for (int p = 0; p < e->world; ++p) { if (!(e->p2p_channels >> p & 1u)) continue; - used += (size_t)snprintf(peers + used, sizeof peers - used, "%s%d", used ? "," : "", p); - if (used >= sizeof peers) used = sizeof peers - 1; if (e->p2p_window[p][0] || (e->lanes > 1 && e->p2p_window[p][1])) { - wused += (size_t)snprintf(windows + wused, sizeof windows - wused, "%s\"%d\":[%u,%u]", wused ? "," : "", p, - e->p2p_window[p][0], e->lanes > 1 ? e->p2p_window[p][1] : 0); - if (wused >= sizeof windows) wused = sizeof windows - 1; + jb_appendf(b, "%s\"%d\":[%u,%u]", first ? "" : ",", p, e->p2p_window[p][0], + e->lanes > 1 ? e->p2p_window[p][1] : 0); + first = 0; } } - for (int d = 0; d < 2; ++d) { - size_t fused = 0; - flows[d][0] = 0; + jb_appendf(b, "},\"lane_check_s\":%.4f,\"staged\":%" PRIu64 ",\"refused\":%" PRIu64 ",\"sent\":{", + e->p2p_check_ns / 1e9, atomic_load(&e->p2p_staged), atomic_load(&e->p2p_refused)); + for (int pass = 0; pass < 2; ++pass) { + int d = pass == 0 ? 1 : 0; + if (pass == 1) jb_appendf(b, "},\"received\":{"); + first = 1; for (int p = 0; p < e->world; ++p) { const p2p_channel *ch = &e->p2p_ch[d][p]; uint64_t messages = atomic_load_explicit(&ch->messages, memory_order_relaxed); if (!messages) continue; - fused += (size_t)snprintf(flows[d] + fused, sizeof flows[d] - fused, - "%s\"%d\":{\"messages\":%" PRIu64 ",\"bytes\":%" PRIu64 ",\"items\":%" PRIu64 "}", - fused ? "," : "", p, messages, atomic_load_explicit(&ch->bytes, memory_order_relaxed), - atomic_load_explicit(&ch->items, memory_order_relaxed)); - if (fused >= sizeof flows[d]) fused = sizeof flows[d] - 1; + jb_appendf(b, "%s\"%d\":{\"messages\":%" PRIu64 ",\"bytes\":%" PRIu64 ",\"items\":%" PRIu64 "}", + first ? "" : ",", p, messages, atomic_load_explicit(&ch->bytes, memory_order_relaxed), + atomic_load_explicit(&ch->items, memory_order_relaxed)); + first = 0; } } - void *c = e->p2p; - const p2p_ops *t = e->p2p_transport; - snprintf(out, len, - "{\"on\":true,\"context\":%s,\"peers\":[%s],\"slots\":%u,\"slot_bytes\":%" PRIu64 ",\"blocks\":%u," - "\"threads\":%u,\"unroll\":%u,\"chunk_bytes\":%u,\"arena_bytes\":%" PRIu64 ",\"windows\":{%s}," - "\"lane_check_s\":%.4f,\"staged\":%" PRIu64 ",\"refused\":%" PRIu64 - ",\"sent\":{%s},\"received\":{%s},\"native\":{" - "\"items_posted\":%" PRIu64 ",\"bytes_posted\":%" PRIu64 ",\"items_released\":%" PRIu64 - ",\"credits_sent\":%" PRIu64 ",\"writes_completed\":%" PRIu64 ",\"window_waits\":%" PRIu64 - ",\"window_wait_max_ns\":%" PRIu64 ",\"window_max_unacked_bytes\":%" PRIu64 ",\"proven_bytes\":%" PRIu64 - ",\"abort_from_rank\":%d}}", - c ? "true" : "false", peers, e->shared.p2p_slots, e->shared.p2p_slot_bytes, e->shared.p2p_blocks, - e->shared.p2p_threads, e->shared.p2p_unroll, e->shared.p2p_chunk, e->p2p_bytes, windows, - e->p2p_check_ns / 1e9, atomic_load(&e->p2p_staged), atomic_load(&e->p2p_refused), flows[1], flows[0], - c ? t->stat(c, 0) : 0, - c ? t->stat(c, 1) : 0, c ? t->stat(c, 2) : 0, c ? t->stat(c, 3) : 0, c ? t->stat(c, 4) : 0, - c ? t->stat(c, 5) : 0, c ? t->stat(c, 7) : 0, c ? t->stat(c, 8) : 0, c ? t->stat(c, 9) : 0, - c ? (int)t->stat(c, P2P_STAT_ABORT_FROM) - 1 : -1); + jb_appendf(b, "},\"ep\":{\"dispatches\":%" PRIu64 ",\"combines\":%" PRIu64 "},\"native\":{" + "\"items_posted\":%" PRIu64 ",\"bytes_posted\":%" PRIu64 ",\"items_released\":%" PRIu64 + ",\"credits_sent\":%" PRIu64 ",\"writes_completed\":%" PRIu64 ",\"window_waits\":%" PRIu64 + ",\"window_wait_max_ns\":%" PRIu64 ",\"window_max_unacked_bytes\":%" PRIu64 + ",\"proven_bytes\":%" PRIu64 ",\"abort_from_rank\":%d}}", + atomic_load(&e->ep_dispatches), atomic_load(&e->ep_combines), + c ? t->stat(c, 0) : 0, c ? t->stat(c, 1) : 0, c ? t->stat(c, 2) : 0, c ? t->stat(c, 3) : 0, + c ? t->stat(c, 4) : 0, c ? t->stat(c, 5) : 0, c ? t->stat(c, 7) : 0, c ? t->stat(c, 8) : 0, + c ? t->stat(c, 9) : 0, c ? (int)t->stat(c, P2P_STAT_ABORT_FROM) - 1 : -1); } /* The bytes quarantined engines hold (see quarantine_reclaim), reported in every receipt. */ static _Atomic uint64_t quarantined_bytes; size_t sccl_engine_receipt(sccl_engine *e, char *out, size_t len) { static const char *const dt[SCCL_DT_COUNT] = {"float32", "float16", "bfloat16"}; - char ops[512] = {0}; - size_t used = 0; + char health[900] = {0}; + ncclResult_t status = session_error(e, health, sizeof health); + int serving = __atomic_load_n(&e->serving, __ATOMIC_ACQUIRE); + int stage_buffers = __atomic_load_n(&e->retired, __ATOMIC_ACQUIRE) + + (__atomic_load_n(&e->stage, __ATOMIC_ACQUIRE) != 0); + json_buf jb; + jb_init(&jb); + jb_appendf(&jb, + "{\"schema\":\"libsircl-receipt/v1\",\"library\":\"libsircl " LIBSIRCL_VERSION "\",\"pid\":%d," + "\"communicator\":%d,\"rank\":%d,\"world\":%d,\"position\":%d,\"lanes\":%d," + "\"device\":%d,\"quarantined_bytes\":%" PRIu64 "," + "\"transport\":\"%s\",\"kernel_pack\":\"%s\",\"fold_pack\":\"%s\",\"links_pack\":\"%s\"," + "\"slot_bytes\":%" PRIu64 ",\"capacity\":%" PRIu64 ",\"large_piece_bytes\":%" PRIu64 + ",\"oneshot_max_bytes\":%" PRIu64 ",\"wait_regime\":\"%s\",\"fail_stop\":%s," + "\"progress_cpus\":\"%s\",\"pair_exchange\":{\"ops\":%" PRIu64 ",\"bytes\":%" PRIu64 + "},\"pair_plan\":%s,\"cycle_plan\":%s,\"ring_only\":%s,\"link_blocks\":{\"session\":%u,\"reduce\":%u," + "\"gather\":%u,\"scatter\":%u,\"ops_by_blocks\":{", + (int)getpid(), e->receipt_id, e->rank, e->world, e->position, e->lanes, e->device, + atomic_load_explicit(&quarantined_bytes, memory_order_relaxed), + e->world == 1 ? "none" : e->transport->name, sccl_kp_hash(), sccl_kp_fold_hash(), sccl_kp_links_hash(), + e->shared.slot_bytes, e->shared.capacity, e->shared.large_piece, e->shared.oneshot_max, + serving ? "serving" : "startup", e->fail_stop ? "true" : "false", + e->progress_cpus[0] ? e->progress_cpus : "none", atomic_load(&e->exchange_ops), + atomic_load(&e->exchange_bytes), e->shared.pair_plan ? "true" : "false", + e->shared.cycle_plan ? "true" : "false", e->shared.ring_only ? "true" : "false", e->shared.link_blocks, + e->shared.coll_blocks[COLL_REDUCE], e->shared.coll_blocks[COLL_GATHER], + e->shared.coll_blocks[COLL_SCATTER]); + int first = 1; + for (int b = 1; b <= 64; ++b) { + uint64_t n = atomic_load_explicit(&e->ops_by_blocks[b], memory_order_relaxed); + if (!n) continue; + jb_appendf(&jb, "%s\"%d\":%" PRIu64, first ? "" : ",", b, n); + first = 0; + } + jb_appendf(&jb, "}},\"all_reduce\":{\"calls\":%" PRIu64 ",\"captured_calls\":%" PRIu64 ",\"bytes\":%" PRIu64 + ",\"ops\":{", + atomic_load(&e->calls), atomic_load(&e->captured_calls), atomic_load(&e->bytes)); + first = 1; for (int a = 0; a < SCCL_ALG_COUNT; ++a) for (int d = 0; d < SCCL_DT_COUNT; ++d) { uint64_t n = atomic_load_explicit(&e->ops[a][d], memory_order_relaxed); if (!n) continue; - used += (size_t)snprintf(ops + used, sizeof ops - used, "%s\"%s/%s\":%" PRIu64, used ? "," : "", - a == SCCL_ALG_ONESHOT ? "oneshot" : "twoshot", dt[d], n); - if (used >= sizeof ops) used = sizeof ops - 1; + jb_appendf(&jb, "%s\"%s/%s\":%" PRIu64, first ? "" : ",", a == SCCL_ALG_ONESHOT ? "oneshot" : "twoshot", dt[d], n); + first = 0; } - char folds[2048] = {0}; - size_t fused = 0; + jb_appendf(&jb, "},\"padded_tails\":%" PRIu64 ",\"unaligned_staged\":%" PRIu64 ",\"local_copies\":%" PRIu64 + "},\"all_gather\":{\"calls\":%" PRIu64 ",\"ops\":%" PRIu64 ",\"bytes\":%" PRIu64 + ",\"padded\":%" PRIu64 "},\"reduce_scatter\":{\"calls\":%" PRIu64 ",\"ops\":%" PRIu64 + ",\"bytes\":%" PRIu64 ",\"padded\":%" PRIu64 "},\"broadcast\":{\"calls\":%" PRIu64 + "},\"reduce\":{\"calls\":%" PRIu64 "},\"all_to_all\":{\"calls\":%" PRIu64 ",\"ops\":%" PRIu64 + ",\"bytes\":%" PRIu64 ",\"padded\":%" PRIu64 "},\"gather\":{\"calls\":%" PRIu64 + "},\"scatter\":{\"calls\":%" PRIu64 "},\"fold\":{\"ops\":{", + atomic_load(&e->padded_tails), atomic_load(&e->staged_unaligned), atomic_load(&e->local_copies), + atomic_load(&e->gather_calls), atomic_load(&e->gather_ops), atomic_load(&e->gather_bytes), + atomic_load(&e->gather_padded), atomic_load(&e->scatter_calls), atomic_load(&e->scatter_ops), + atomic_load(&e->scatter_bytes), atomic_load(&e->scatter_padded), atomic_load(&e->broadcast_calls), + atomic_load(&e->reduce_calls), atomic_load(&e->alltoall_calls), atomic_load(&e->alltoall_ops), + atomic_load(&e->alltoall_bytes), atomic_load(&e->alltoall_padded), atomic_load(&e->gather_root_calls), + atomic_load(&e->scatter_root_calls)); + first = 1; for (int d = 0; d < SCCL_FOLD_DTYPES; ++d) for (int o = 0; o < SCCL_FOLD_OPS; ++o) { uint64_t n = atomic_load_explicit(&e->folds[d][o], memory_order_relaxed); if (!n) continue; - fused += (size_t)snprintf(folds + fused, sizeof folds - fused, "%s\"%s/%s\":%" PRIu64, fused ? "," : "", - type_names[d], op_names[o], n); - if (fused >= sizeof folds) fused = sizeof folds - 1; + jb_appendf(&jb, "%s\"%s/%s\":%" PRIu64, first ? "" : ",", type_names[d], op_names[o], n); + first = 0; } - char links[256] = {0}; - size_t lused = 0; + jb_appendf(&jb, "}},\"chain\":{\"on\":%s,\"index\":%d,\"ops\":%" PRIu64 ",\"bytes\":%" PRIu64 + "},\"links\":{\"on\":%s,\"ring\":%s,\"ring_reduce_passes\":%d,\"ops\":{", + e->chain_on ? "true" : "false", e->chain_index, + atomic_load(&e->chain_ops[0]) + atomic_load(&e->chain_ops[1]) + atomic_load(&e->chain_ops[2]), + atomic_load(&e->chain_bytes), e->link_on ? "true" : "false", + e->shared.ring_on && e->link_on ? "true" : "false", e->ring_reduce_passes); + first = 1; for (int k = 0; k < SCCL_LINK_KINDS; ++k) { uint64_t n = atomic_load_explicit(&e->link_ops[k], memory_order_relaxed); if (!n) continue; - lused += (size_t)snprintf(links + lused, sizeof links - lused, "%s\"%s\":%" PRIu64, lused ? "," : "", - link_kind_names[k], n); - if (lused >= sizeof links) lused = sizeof links - 1; - } - char by_blocks[256] = {0}; - size_t bused = 0; - for (int b = 1; b <= 64; ++b) { - uint64_t n = atomic_load_explicit(&e->ops_by_blocks[b], memory_order_relaxed); - if (!n) continue; - bused += (size_t)snprintf(by_blocks + bused, sizeof by_blocks - bused, "%s\"%d\":%" PRIu64, bused ? "," : "", b, n); - if (bused >= sizeof by_blocks) bused = sizeof by_blocks - 1; - } - char health[900] = {0}, health_json[1000], channels[3072]; - ncclResult_t status = session_error(e, health, sizeof health); - p2p_receipt(e, channels, sizeof channels); - json_string(health_json, sizeof health_json, status == ncclSuccess ? NULL : health); - return (size_t)snprintf( - out, len, - "{\"schema\":\"libsircl-receipt/v1\",\"library\":\"libsircl " LIBSIRCL_VERSION "\",\"pid\":%d," - "\"communicator\":%d,\"rank\":%d,\"world\":%d,\"position\":%d,\"lanes\":%d," - "\"device\":%d,\"quarantined_bytes\":%" PRIu64 "," - "\"transport\":\"%s\",\"kernel_pack\":\"%s\",\"fold_pack\":\"%s\",\"links_pack\":\"%s\"," - "\"slot_bytes\":%" PRIu64 - ",\"capacity\":%" PRIu64 - ",\"large_piece_bytes\":%" PRIu64 ",\"oneshot_max_bytes\":%" PRIu64 ",\"wait_regime\":\"%s\",\"fail_stop\":%s," - "\"progress_cpus\":\"%s\",\"pair_exchange\":{\"ops\":%" PRIu64 ",\"bytes\":%" PRIu64 "},\"pair_plan\":%s,\"cycle_plan\":%s,\"ring_only\":%s,\"link_blocks\":{\"session\":%u,\"reduce\":%u," - "\"gather\":%u,\"scatter\":%u,\"ops_by_blocks\":{%s}}," - "\"all_reduce\":{\"calls\":%" PRIu64 ",\"captured_calls\":%" PRIu64 ",\"bytes\":%" PRIu64 - ",\"ops\":{%s},\"padded_tails\":%" PRIu64 ",\"unaligned_staged\":%" PRIu64 ",\"local_copies\":%" PRIu64 - "},\"all_gather\":{\"calls\":%" PRIu64 ",\"ops\":%" PRIu64 ",\"bytes\":%" PRIu64 ",\"padded\":%" PRIu64 - "},\"reduce_scatter\":{\"calls\":%" PRIu64 ",\"ops\":%" PRIu64 ",\"bytes\":%" PRIu64 ",\"padded\":%" PRIu64 - "},\"broadcast\":{\"calls\":%" PRIu64 "},\"reduce\":{\"calls\":%" PRIu64 - "},\"all_to_all\":{\"calls\":%" PRIu64 ",\"ops\":%" PRIu64 ",\"bytes\":%" PRIu64 ",\"padded\":%" PRIu64 - "},\"gather\":{\"calls\":%" PRIu64 "},\"scatter\":{\"calls\":%" PRIu64 "},\"fold\":{\"ops\":{%s}" - "},\"chain\":{\"on\":%s,\"index\":%d,\"ops\":%" PRIu64 ",\"bytes\":%" PRIu64 - "},\"links\":{\"on\":%s,\"ring\":%s,\"ring_reduce_passes\":%d,\"ops\":{%s},\"bytes\":%" PRIu64 - ",\"staged\":%" PRIu64 ",\"stage_buffers\":%d,\"graph_staging\":%s,\"graph_staged\":%" PRIu64 - ",\"native_ops\":%" PRIu64 ",\"native_items\":%" PRIu64 - "},\"forward_windows\":{\"lanes\":%u,\"chunk_bytes\":%u,\"chunks_posted\":%" PRIu64 - ",\"ring_window_bytes\":%u,\"ring_window_chunks\":%" PRIu64 - "},\"point_to_point\":{\"sends\":%" PRIu64 ",\"receives\":%" PRIu64 ",\"exchanges\":%" PRIu64 - ",\"ops\":%" PRIu64 ",\"bytes_sent\":%" PRIu64 ",\"bytes_received\":%" PRIu64 "},\"channels\":%s,\"refused\":{\"op\":%" PRIu64 ",\"capture_stream\":%" PRIu64 - "},\"forwarded\":0,\"native\":{\"ops_posted\":%" PRIu64 ",\"writes_completed\":%" PRIu64 - ",\"phases_posted\":%" PRIu64 "},\"healthy\":%s,\"error\":%s}", - (int)getpid(), e->receipt_id, e->rank, e->world, e->position, e->lanes, e->device, - atomic_load_explicit(&quarantined_bytes, memory_order_relaxed), - e->world == 1 ? "none" : e->transport->name, - sccl_kp_hash(), - sccl_kp_fold_hash(), sccl_kp_links_hash(), - e->shared.slot_bytes, e->shared.capacity, e->shared.large_piece, e->shared.oneshot_max, - e->serving ? "serving" : "startup", e->fail_stop ? "true" : "false", - e->progress_cpus[0] ? e->progress_cpus : "none", - atomic_load(&e->exchange_ops), atomic_load(&e->exchange_bytes), - e->shared.pair_plan ? "true" : "false", e->shared.cycle_plan ? "true" : "false", - e->shared.ring_only ? "true" : "false", e->shared.link_blocks, e->shared.coll_blocks[COLL_REDUCE], - e->shared.coll_blocks[COLL_GATHER], e->shared.coll_blocks[COLL_SCATTER], by_blocks, - atomic_load(&e->calls), atomic_load(&e->captured_calls), - atomic_load(&e->bytes), ops, atomic_load(&e->padded_tails), atomic_load(&e->staged_unaligned), - atomic_load(&e->local_copies), atomic_load(&e->gather_calls), atomic_load(&e->gather_ops), - atomic_load(&e->gather_bytes), atomic_load(&e->gather_padded), atomic_load(&e->scatter_calls), - atomic_load(&e->scatter_ops), atomic_load(&e->scatter_bytes), atomic_load(&e->scatter_padded), - atomic_load(&e->broadcast_calls), atomic_load(&e->reduce_calls), atomic_load(&e->alltoall_calls), - atomic_load(&e->alltoall_ops), atomic_load(&e->alltoall_bytes), atomic_load(&e->alltoall_padded), - atomic_load(&e->gather_root_calls), atomic_load(&e->scatter_root_calls), folds, - e->chain_on ? "true" : "false", e->chain_index, - atomic_load(&e->chain_ops[0]) + atomic_load(&e->chain_ops[1]) + atomic_load(&e->chain_ops[2]), - atomic_load(&e->chain_bytes), e->link_on ? "true" : "false", e->shared.ring_on && e->link_on ? "true" : "false", - e->ring_reduce_passes, links, atomic_load(&e->link_bytes), atomic_load(&e->link_staged), - e->retired + (e->stage != 0), e->shared.graph_staging ? "true" : "false", atomic_load(&e->graph_staged), - e->proxy ? e->transport->stat(e->proxy, 16) : 0, e->proxy ? e->transport->stat(e->proxy, 17) : 0, - e->forward_lanes, e->forward_chunk, e->proxy ? e->transport->stat(e->proxy, 10) : 0, e->ring_window, - e->proxy ? e->transport->stat(e->proxy, 24) : 0, atomic_load(&e->p2p_sends), - atomic_load(&e->p2p_recvs), atomic_load(&e->p2p_exchanges), atomic_load(&e->p2p_ops), - atomic_load(&e->p2p_bytes_sent), atomic_load(&e->p2p_bytes_received), channels, - atomic_load(&e->refused_op), - atomic_load(&e->refused_capture), e->proxy ? e->transport->stat(e->proxy, 0) : 0, - e->proxy ? e->transport->stat(e->proxy, 1) : 0, e->proxy ? e->transport->stat(e->proxy, 5) : 0, - status == ncclSuccess ? "true" : "false", health_json); + jb_appendf(&jb, "%s\"%s\":%" PRIu64, first ? "" : ",", link_kind_names[k], n); + first = 0; + } + jb_appendf(&jb, "},\"bytes\":%" PRIu64 ",\"staged\":%" PRIu64 ",\"stage_buffers\":%d,\"graph_staging\":%s," + "\"graph_staged\":%" PRIu64 ",\"native_ops\":%" PRIu64 ",\"native_items\":%" PRIu64 + "},\"forward_windows\":{\"lanes\":%u,\"chunk_bytes\":%u,\"chunks_posted\":%" PRIu64 + ",\"ring_window_bytes\":%u,\"ring_window_chunks\":%" PRIu64 + "},\"point_to_point\":{\"sends\":%" PRIu64 ",\"receives\":%" PRIu64 ",\"exchanges\":%" PRIu64 + ",\"ops\":%" PRIu64 ",\"bytes_sent\":%" PRIu64 ",\"bytes_received\":%" PRIu64 "},\"channels\":", + atomic_load(&e->link_bytes), atomic_load(&e->link_staged), stage_buffers, + e->shared.graph_staging ? "true" : "false", atomic_load(&e->graph_staged), + e->proxy ? e->transport->stat(e->proxy, 16) : 0, e->proxy ? e->transport->stat(e->proxy, 17) : 0, + e->forward_lanes, e->forward_chunk, e->proxy ? e->transport->stat(e->proxy, 10) : 0, e->ring_window, + e->proxy ? e->transport->stat(e->proxy, 24) : 0, atomic_load(&e->p2p_sends), + atomic_load(&e->p2p_recvs), atomic_load(&e->p2p_exchanges), atomic_load(&e->p2p_ops), + atomic_load(&e->p2p_bytes_sent), atomic_load(&e->p2p_bytes_received)); + p2p_receipt_append(e, &jb); + jb_appendf(&jb, ",\"refused\":{\"op\":%" PRIu64 ",\"capture_stream\":%" PRIu64 + "},\"forwarded\":0,\"native\":{\"ops_posted\":%" PRIu64 ",\"writes_completed\":%" PRIu64 + ",\"phases_posted\":%" PRIu64 "},\"healthy\":%s,\"error\":", + atomic_load(&e->refused_op), atomic_load(&e->refused_capture), + e->proxy ? e->transport->stat(e->proxy, 0) : 0, e->proxy ? e->transport->stat(e->proxy, 1) : 0, + e->proxy ? e->transport->stat(e->proxy, 5) : 0, status == ncclSuccess ? "true" : "false"); + jb_append_json_string(&jb, status == ncclSuccess ? NULL : health); + jb_appendf(&jb, "}"); + if (jb.oom || !jb.data) { + jb_free(&jb); + return (size_t)snprintf(out, len, "{\"schema\":\"libsircl-receipt/v1\",\"healthy\":false," + "\"error\":\"out of memory formatting receipt\"}"); + } + size_t need = jb.len; + if (out && len) { + size_t copy = need < len - 1 ? need : len - 1; + memcpy(out, jb.data, copy); + out[copy] = 0; + } + jb_free(&jb); + return need; } /* A diagnostic file of this library: created by open(2) with O_NOFOLLOW (a symbolic link at the path is @@ -5033,6 +5483,11 @@ static void quarantine_reclaim(void) { for (sccl_engine **at = &quarantined; *at;) { sccl_engine *e = *at; int pushed = cu->CtxPushCurrent(e->ctx) == SCCL_CUDA_SUCCESS, done = 1; + if (pushed && __atomic_load_n(&e->ever_captured, __ATOMIC_ACQUIRE)) { + /* Captured CUDA graphs hold raw pointers to this engine's arenas and device control + * counters and may replay on any stream while e->ctx lives; wait until context destruction. */ + done = 0; + } for (int i = 0; pushed && done && i < e->quarantine_events; ++i) done = cu->EventQuery(e->quarantine_done[i]) == SCCL_CUDA_SUCCESS; if (!done) { @@ -5067,19 +5522,21 @@ static void quarantine_reclaim(void) { * launch and every channel stream) and put the engine on the quarantine list. 0 when an event could not be * made: the engine then stays allocated without a retry. */ static int quarantine_add(sccl_engine *e) { - int n = 0; - sccl_CUstream streams[1 + 2 * MAX_WORLD]; - if (e->have_last) streams[n++] = e->last_stream; - for (int d = 0; d < 2; ++d) - for (int p = 0; p < e->world && p < MAX_WORLD; ++p) - if (e->p2p_ch[d][p].stream) streams[n++] = e->p2p_ch[d][p].stream; e->quarantine_events = 0; - for (int i = 0; i < n; ++i) { - if (cu->EventCreate(&e->quarantine_done[i], SCCL_CU_EVENT_DISABLE_TIMING) != SCCL_CUDA_SUCCESS) return 0; - e->quarantine_events = i + 1; - if (cu->EventRecord(e->quarantine_done[i], streams[i]) != SCCL_CUDA_SUCCESS) return 0; + if (!__atomic_load_n(&e->ever_captured, __ATOMIC_ACQUIRE)) { + int n = 0; + sccl_CUstream streams[1 + 2 * MAX_WORLD]; + if (e->have_last) streams[n++] = e->last_stream; + for (int d = 0; d < 2; ++d) + for (int p = 0; p < e->world && p < MAX_WORLD; ++p) + if (e->p2p_ch[d][p].stream) streams[n++] = e->p2p_ch[d][p].stream; + for (int i = 0; i < n; ++i) { + if (cu->EventCreate(&e->quarantine_done[i], SCCL_CU_EVENT_DISABLE_TIMING) != SCCL_CUDA_SUCCESS) return 0; + e->quarantine_events = i + 1; + if (cu->EventRecord(e->quarantine_done[i], streams[i]) != SCCL_CUDA_SUCCESS) return 0; + } } - e->quarantine_bytes = e->region_bytes + e->shared.slot_bytes * (uint64_t)(1 + e->world); + e->quarantine_bytes = e->region_bytes + e->p2p_bytes + e->shared.slot_bytes * (uint64_t)(1 + e->world); atomic_fetch_add_explicit(&quarantined_bytes, e->quarantine_bytes, memory_order_relaxed); pthread_mutex_lock(&quarantine_lock); e->quarantine_next = quarantined; @@ -5105,16 +5562,23 @@ ncclResult_t sccl_engine_destroy(sccl_engine *e, int abort, char *err, size_t le result = ncclUnhandledCudaError; put_error(err, len, "waiting for the communicator's context failed; its arena stays allocated"); } - /* Abort stops the channels first: their kernels return once they see the poison word, and every peer gets - * the abort notice instead of waiting out its wait limit. A channel kernel still running at the idle check - * below keeps the arena allocated (quarantined). */ - if (abort) p2p_stop_with_notices(e, "ncclCommAbort"); + /* Abort stops the channels and collective proxy first with peer abort notices so peers fail fast + * instead of waiting out their wait limits. Any still-running kernel (or any communicator that + * ever captured a CUDA graph, whose replay stream is unknown) keeps its arenas quarantined. */ + if (abort) { + p2p_stop_with_notices(e, "ncclCommAbort"); + roce_stop_with_notices(e); + } if (pushed && abort) { - if (e->have_last) idle = cu->StreamQuery(e->last_stream) == SCCL_CUDA_SUCCESS; - for (int d = 0; d < 2; ++d) - for (int p = 0; p < e->world && p < MAX_WORLD; ++p) - if (e->p2p_ch[d][p].stream) - idle = idle && cu->StreamQuery(e->p2p_ch[d][p].stream) == SCCL_CUDA_SUCCESS; + if (__atomic_load_n(&e->ever_captured, __ATOMIC_ACQUIRE)) { + idle = 0; + } else { + if (e->have_last) idle = cu->StreamQuery(e->last_stream) == SCCL_CUDA_SUCCESS; + for (int d = 0; d < 2; ++d) + for (int p = 0; p < e->world && p < MAX_WORLD; ++p) + if (e->p2p_ch[d][p].stream) + idle = idle && cu->StreamQuery(e->p2p_ch[d][p].stream) == SCCL_CUDA_SUCCESS; + } } if (!stopped) { dump_links(e, "destroy", pushed && idle); diff --git a/spark_transport/libsircl/src/engine.h b/spark_transport/libsircl/src/engine.h index a8e71f97..a0ecbc50 100644 --- a/spark_transport/libsircl/src/engine.h +++ b/spark_transport/libsircl/src/engine.h @@ -78,6 +78,16 @@ typedef struct { * itself in order and are local copies. */ ncclResult_t sccl_engine_p2p(sccl_engine *engine, const sccl_p2p_op *ops, unsigned count, char *err, size_t err_len); +/* SIRCL-EP: GPU-driven dynamic variable-length MoE token dispatch and combine over point-to-point channels. */ +size_t sccl_engine_ep_workspace_bytes(int world, int max_tokens, size_t hidden_bytes); +ncclResult_t sccl_engine_ep_dispatch(sccl_engine *engine, const void *hidden_in, const int *topk_ids_in, + const float *topk_weights_in, void *hidden_out, int *topk_ids_out, + float *topk_weights_out, int *recv_counts_out, void *workspace, + size_t workspace_bytes, int num_tokens, int max_tokens, size_t hidden_bytes, + int top_k, int num_experts, cudaStream_t stream, char *err, size_t err_len); +ncclResult_t sccl_engine_ep_combine(sccl_engine *engine, const void *expert_out_in, void *hidden_out, void *workspace, + size_t workspace_bytes, int num_tokens, int max_tokens, size_t hidden_dim, + ncclDataType_t datatype, cudaStream_t stream, char *err, size_t err_len); /* Bytes per element of an NCCL datatype; 0 for an invalid one. */ size_t sccl_engine_type_size(ncclDataType_t datatype); /* ncclMemAlloc and ncclMemFree: device memory of the calling thread's current CUDA context (cuMemAlloc), diff --git a/spark_transport/libsircl/src/env_names.h b/spark_transport/libsircl/src/env_names.h index 1782fea6..fd2c6643 100644 --- a/spark_transport/libsircl/src/env_names.h +++ b/spark_transport/libsircl/src/env_names.h @@ -8,6 +8,10 @@ #include #include +#define SCCL_ENV_LOOKUP 1 +#define SCCL_ENV_PROGRESS_CPU "SIRCL_PROGRESS_CPU" +#define SCCL_ENV_P2P_PROGRESS_CPU "SIRCL_P2P_PROGRESS_CPU" + static inline const char *sccl_env(const char *name) { const char *value = getenv(name); if (value || strncmp(name, "LIBSIRCL_", 9) != 0) return value; diff --git a/spark_transport/libsircl/src/fabric.c b/spark_transport/libsircl/src/fabric.c deleted file mode 100644 index 33f70302..00000000 --- a/spark_transport/libsircl/src/fabric.c +++ /dev/null @@ -1,510 +0,0 @@ -#include "sircl_fabric.h" -#include -#include -#include -#include -#include -#include -#include - -#define FW SIRCL_FABRIC_MAX_WORLD -#define FL SIRCL_FABRIC_MAX_LANES - -static int fail(sircl_fabric_error *e, int code, const char *fmt, ...) { - if (e) { va_list ap; e->code = code; va_start(ap, fmt); - vsnprintf(e->message, sizeof e->message, fmt, ap); va_end(ap); } - return -1; -} -static void clear_error(sircl_fabric_error *e) { if (e) memset(e, 0, sizeof *e); } -static const char *devices[4] = {"rocep1s0f0", "roceP2p1s0f0", "rocep1s0f1", "roceP2p1s0f1"}; -const char *sircl_fabric_role_device(int role) { return role >= 0 && role < 4 ? devices[role] : NULL; } -int sircl_fabric_role_of(const char *device) { - int i; if (!device) return -1; - for (i = 0; i < 4; i++) if (!strcmp(device, devices[i])) return i; - return -1; -} -static int node_at(const sircl_fabric_layout *l, int position) { - int i; for (i = 0; i < l->node_count; i++) if (l->nodes[i] == position) return i; - return -1; -} -static int cross(const sircl_fabric_layout *l, int position, int port, sircl_fabric_step *s) { - int i; for (i = 0; i < l->cable_count; i++) { - const sircl_cable *c = &l->cables[i]; - if (c->a == position && c->a_port == port) { - *s = (sircl_fabric_step){position, port, c->b, c->b_port}; return 1; - } - if (c->b == position && c->b_port == port) { - *s = (sircl_fabric_step){position, port, c->a, c->a_port}; return 1; - } - } return 0; -} -static int walk(const sircl_fabric_layout *l, int a, int port, int b, - sircl_fabric_step steps[FW]) { - int n, here = a, out = port; - for (n = 0; n < l->node_count; n++) { - if (!cross(l, here, out, &steps[n])) return 0; - if (steps[n].dst == b) return n + 1; - here = steps[n].dst; out = 1 - steps[n].dst_port; - } return 0; -} -static int layout_valid(const sircl_fabric_layout *l) { - sircl_fabric_layout checked; - if (!l || l->world < 2 || l->world > FW || l->node_count < l->world || - l->node_count > FW || l->cable_count < 1 || l->cable_count > FW) return 0; - if (sircl_fabric_layout_init(&checked, l->cables, l->cable_count, l->positions, l->world, NULL)) return 0; - return l->node_count == checked.node_count && l->cycle == checked.cycle && - !memcmp(l->nodes, checked.nodes, (size_t)l->node_count * sizeof l->nodes[0]); -} -static int routes_valid(const sircl_fabric_routes *r) { - int rank, peer, lane; - if (!r || !layout_valid(&r->layout) || r->lanes < 1 || r->lanes > FL) return 0; - for (rank = 0; rank < r->layout.world; rank++) for (peer = 0; peer < r->layout.world; peer++) if (rank != peer) - for (lane = 0; lane < r->lanes; lane++) { - const sircl_lane_route *route = &r->route[rank][peer][lane]; - int k, here = r->layout.positions[rank], port; - if (route->hops < 1 || route->hops > r->layout.node_count || route->local_role < 0 || - route->local_role > 3 || route->remote_role < 0 || route->remote_role > 3) return 0; - port = route->local_role / 2; - for (k = 0; k < route->hops; k++) { - sircl_fabric_step expected; - const sircl_fabric_step *step = &route->steps[k]; - if (!cross(&r->layout, here, port, &expected) || step->src != expected.src || - step->src_port != expected.src_port || step->dst != expected.dst || step->dst_port != expected.dst_port) return 0; - here = step->dst; port = 1 - step->dst_port; - } - if (here != r->layout.positions[peer] || route->remote_role != - route->steps[route->hops - 1].dst_port * 2 + route->local_role % 2) return 0; - } - return 1; -} -int sircl_fabric_layout_init(sircl_fabric_layout *out, const sircl_cable *cables, - int cable_count, const int *positions, int world, sircl_fabric_error *e) { - sircl_fabric_layout t; int i, j, degree[FW] = {0}, reached[FW] = {0}; - clear_error(e); - if (!out || !cables || !positions || world < 2 || world > FW || cable_count < 1 || cable_count > FW) - return fail(e, SIRCL_FABRIC_INVALID, "a fabric needs 2-16 ranks and 1-16 cables"); - memset(&t, 0, sizeof t); t.world = world; t.cable_count = cable_count; - for (i = 0; i < cable_count; i++) { - const sircl_cable *c = &cables[i]; int ends[2] = {c->a, c->b}; - if (c->a < 0 || c->b < 0 || c->a == c->b || c->a_port < 0 || c->a_port > 1 || c->b_port < 0 || c->b_port > 1) - return fail(e, SIRCL_FABRIC_INVALID, "cable %d has invalid endpoints or ports", i); - for (j = 0; j < i; j++) { - const sircl_cable *d = &cables[j]; - if ((c->a == d->a && c->a_port == d->a_port) || (c->a == d->b && c->a_port == d->b_port) || - (c->b == d->a && c->b_port == d->a_port) || (c->b == d->b && c->b_port == d->b_port)) - return fail(e, SIRCL_FABRIC_INVALID, "cable %d reuses a fabric port", i); - } - t.cables[i] = *c; - for (j = 0; j < 2; j++) if (node_at(&t, ends[j]) < 0) { - if (t.node_count == FW) return fail(e, SIRCL_FABRIC_LIMIT, "fabric exceeds 16 positions"); - t.nodes[t.node_count++] = ends[j]; - } - } - for (i = 0; i < t.node_count; i++) for (j = i + 1; j < t.node_count; j++) - if (t.nodes[j] < t.nodes[i]) { int p = t.nodes[i]; t.nodes[i] = t.nodes[j]; t.nodes[j] = p; } - for (i = 0; i < cable_count; i++) { degree[node_at(&t, cables[i].a)]++; degree[node_at(&t, cables[i].b)]++; } - t.cycle = 1; for (i = 0; i < t.node_count; i++) if (degree[i] != 2) t.cycle = 0; - reached[0] = 1; - for (i = 0; i < t.node_count; i++) for (j = 0; j < cable_count; j++) { - int a = node_at(&t, cables[j].a), b = node_at(&t, cables[j].b); - if (reached[a] || reached[b]) reached[a] = reached[b] = 1; - } - for (i = 0; i < t.node_count; i++) if (!reached[i]) - return fail(e, SIRCL_FABRIC_UNREACHABLE, "fabric contains disconnected position %d", t.nodes[i]); - for (i = 0; i < world; i++) { - if (node_at(&t, positions[i]) < 0) return fail(e, SIRCL_FABRIC_INVALID, "rank %d position %d is not on fabric", i, positions[i]); - for (j = 0; j < i; j++) if (positions[j] == positions[i]) return fail(e, SIRCL_FABRIC_INVALID, "ranks need distinct fabric positions"); - t.positions[i] = positions[i]; - } - *out = t; return 0; -} -static void skip_space(const char **p) { while (isspace((unsigned char)**p)) (*p)++; } -static int number(const char **p, int *out) { - char *end; long value; skip_space(p); if (!isdigit((unsigned char)**p)) return -1; - errno = 0; value = strtol(*p, &end, 10); if (errno || value > INT_MAX) return -1; - *p = end; *out = (int)value; skip_space(p); return 0; -} -static int token(const char **p, const char *text) { - size_t n = strlen(text); skip_space(p); if (strncmp(*p, text, n)) return -1; - *p += n; skip_space(p); return 0; -} -static int parse_cable(const char **p, sircl_cable *c) { - if (number(p, &c->a) || token(p, ".port") || (**p != '0' && **p != '1')) return -1; - c->a_port = *(*p)++ - '0'; - if (token(p, "-") || number(p, &c->b) || token(p, ".port") || (**p != '0' && **p != '1')) return -1; - c->b_port = *(*p)++ - '0'; skip_space(p); - return 0; -} -static int parse_positions(const char **p, int positions[FW], int *count) { - *count = 0; - do { - if (*count == FW || number(p, &positions[(*count)++])) return -1; - if (**p != ',') break; - (*p)++; - } while (1); - return **p ? -1 : 0; -} -int sircl_fabric_layout_parse(const char *text, sircl_fabric_layout *out, sircl_fabric_error *e) { - sircl_cable cables[FW]; int positions[FW], count = 0, world = 0, i, first, last; const char *p = text; - clear_error(e); if (!text || !out) return fail(e, SIRCL_FABRIC_INVALID, "layout is required"); - skip_space(&p); - if (!strncmp(p, "cables=", 7)) { - p += 7; - do { if (count == FW || parse_cable(&p, &cables[count++])) goto malformed; - if (*p != ',') break; - p++; - } while (1); - if (token(&p, ";positions=") || parse_positions(&p, positions, &world)) goto malformed; - } else if (!strncmp(p, "ring:", 5)) { - p += 5; if (number(&p, &count) || count < 2 || count > FW) goto malformed; - for (i = 0; i < count; i++) { cables[i] = (sircl_cable){i, 0, (i + 1) % count, 1}; positions[i] = i; } - world = count; - if (*p == ':') { p++; if (parse_positions(&p, positions, &world)) goto malformed; } - else if (*p) goto malformed; - } else if (!strncmp(p, "path:", 5)) { - p += 5; if (number(&p, &first) || token(&p, "-") || number(&p, &last) || last <= first || last - first >= FW) goto malformed; - count = last - first; world = count + 1; - for (i = 0; i < world; i++) positions[i] = first + i; - for (i = 0; i < count; i++) cables[i] = (sircl_cable){first + i, 0, first + i + 1, 1}; - if (*p == ':') { p++; if (parse_positions(&p, positions, &world)) goto malformed; } - else if (*p) goto malformed; - } else goto malformed; - return sircl_fabric_layout_init(out, cables, count, positions, world, e); -malformed: return fail(e, SIRCL_FABRIC_INVALID, "malformed layout; use ring:, path:, or cables=...;positions=..."); -} -int sircl_fabric_derive(const sircl_fabric_layout *l, int lanes, sircl_fabric_routes *out, sircl_fabric_error *e) { - int rank, peer, lane; clear_error(e); - if (!layout_valid(l) || !out || lanes < 1 || lanes > FL) return fail(e, SIRCL_FABRIC_INVALID, "invalid layout or lane count"); - /* Revalidate public structures, including port uniqueness and connectivity. */ - { sircl_fabric_layout checked; - if (sircl_fabric_layout_init(&checked, l->cables, l->cable_count, l->positions, l->world, e)) return -1; - out->layout = checked; - } - out->lanes = lanes; memset(out->route, 0, sizeof out->route); l = &out->layout; - for (rank = 0; rank < l->world; rank++) for (peer = 0; peer < l->world; peer++) if (rank != peer) { - sircl_fabric_step paths[2][FW]; int n[2], chosen[2]; - n[0] = walk(l, l->positions[rank], 0, l->positions[peer], paths[0]); - n[1] = walk(l, l->positions[rank], 1, l->positions[peer], paths[1]); - if (!n[0] && !n[1]) return fail(e, SIRCL_FABRIC_UNREACHABLE, "rank %d cannot reach rank %d", rank, peer); - if (!n[1] || (n[0] && n[0] < n[1])) chosen[0] = chosen[1] = 0; - else if (!n[0] || n[1] < n[0]) chosen[0] = chosen[1] = 1; - else { - /* Path A leaves the numerically smaller endpoint through port 0. */ - int a = l->positions[rank] < l->positions[peer] ? 0 : (paths[0][n[0]-1].dst_port == 0 ? 0 : 1); - chosen[0] = a; chosen[1] = 1 - a; - } - for (lane = 0; lane < lanes; lane++) { - int which = chosen[lane]; sircl_lane_route *r = &out->route[rank][peer][lane]; - r->hops = n[which]; memcpy(r->steps, paths[which], (size_t)r->hops * sizeof r->steps[0]); - r->local_role = r->steps[0].src_port * 2 + lane; - r->remote_role = r->steps[r->hops - 1].dst_port * 2 + lane; - } - } return 0; -} -int sircl_fabric_map(const sircl_fabric_routes *r, int rank, sircl_route_map *out, sircl_fabric_error *e) { - int peer, lane; clear_error(e); - if (!routes_valid(r) || !out || rank < 0 || rank >= r->layout.world) return fail(e, SIRCL_FABRIC_INVALID, "invalid routes or rank"); - memset(out, 0, sizeof *out); - for (peer = 0; peer < r->layout.world; peer++) if (peer != rank) { - out->count[peer] = (uint8_t)r->lanes; - for (lane = 0; lane < r->lanes; lane++) out->role[peer][lane] = (uint8_t)r->route[rank][peer][lane].local_role; - } return 0; -} -int sircl_fabric_map_parse(const char *text, sircl_route_map *out, sircl_fabric_error *e) { - sircl_route_map t; const char *p = text; int seen[FW] = {0}; clear_error(e); - if (!text || !out) return fail(e, SIRCL_FABRIC_INVALID, "route map is required"); - memset(&t, 0, sizeof t); skip_space(&p); if (!*p) return fail(e, SIRCL_FABRIC_INVALID, "route map is empty"); - while (*p) { - int peer, lane = 0; - if (number(&p, &peer) || peer >= FW || token(&p, "=")) return fail(e, SIRCL_FABRIC_INVALID, "malformed route map entry"); - if (seen[peer]++) return fail(e, SIRCL_FABRIC_INVALID, "route map names rank %d twice", peer); - do { - const char *start; size_t len; char device[64]; int role; - skip_space(&p); start = p; while (*p && *p != '/' && *p != ',' && !isspace((unsigned char)*p)) p++; - len = (size_t)(p - start); skip_space(&p); - if (!len || len >= sizeof device || lane == FL) return fail(e, SIRCL_FABRIC_INVALID, "invalid lane list of rank %d", peer); - memcpy(device, start, len); device[len] = 0; role = sircl_fabric_role_of(device); - if (role < 0) return fail(e, SIRCL_FABRIC_INVALID, "device %s has no known role", device); - t.role[peer][lane++] = (uint8_t)role; - if (*p != '/') break; - p++; - } while (1); - t.count[peer] = (uint8_t)lane; - if (!*p) break; - if (*p != ',') return fail(e, SIRCL_FABRIC_INVALID, "malformed route map separator"); - p++; skip_space(&p); if (!*p) return fail(e, SIRCL_FABRIC_INVALID, "route map has an empty entry"); - } *out = t; return 0; -} -int sircl_fabric_map_format(const sircl_route_map *map, int world, char *out, size_t cap, sircl_fabric_error *e) { - int peer, lane, entries = 0; size_t used = 0; clear_error(e); - if (!map || !out || !cap || world < 2 || world > FW) return fail(e, SIRCL_FABRIC_INVALID, "invalid route formatter arguments"); - out[0] = 0; - for (peer = 0; peer < world; peer++) if (map->count[peer]) { - int n; if (map->count[peer] > FL) return fail(e, SIRCL_FABRIC_INVALID, "unsupported lane count"); - n = snprintf(out + used, cap - used, "%s%d=", entries++ ? "," : "", peer); - if (n < 0 || (size_t)n >= cap - used) goto too_small; - used += (size_t)n; - for (lane = 0; lane < map->count[peer]; lane++) { - const char *device = sircl_fabric_role_device(map->role[peer][lane]); - if (!device) return fail(e, SIRCL_FABRIC_INVALID, "invalid device role"); - n = snprintf(out + used, cap - used, "%s%s", lane ? "/" : "", device); - if (n < 0 || (size_t)n >= cap - used) goto too_small; - used += (size_t)n; - } - } return 0; -too_small: return fail(e, SIRCL_FABRIC_LIMIT, "route text buffer is too small"); -} -int sircl_fabric_map_validate(const sircl_fabric_layout *l, const sircl_route_map *map, - int rank, int world, int max_relays, sircl_fabric_error *e) { - int peer, lane, lanes = 0; clear_error(e); - if (!map || world < 2 || world > FW || rank < 0 || rank >= world || max_relays < 0 || - (l && (!layout_valid(l) || l->world != world))) return fail(e, SIRCL_FABRIC_INVALID, "invalid route validation arguments"); - if (map->count[rank]) return fail(e, SIRCL_FABRIC_INVALID, "rank %d's map names its own rank", rank); - for (peer = 0; peer < FW; peer++) if (peer != rank) { - if (peer >= world) { if (map->count[peer]) return fail(e, SIRCL_FABRIC_INVALID, "rank %d is outside session", peer); continue; } - if (!map->count[peer]) return fail(e, SIRCL_FABRIC_INVALID, "rank %d's map has no entry for rank %d", rank, peer); - if (map->count[peer] > FL || (lanes && map->count[peer] != lanes)) return fail(e, SIRCL_FABRIC_INVALID, "rank %d has different or unsupported lane counts", rank); - lanes = map->count[peer]; - if (lanes == 2 && map->role[peer][0] == map->role[peer][1]) return fail(e, SIRCL_FABRIC_INVALID, "rank %d's entry for rank %d names device twice", rank, peer); - for (lane = 0; lane < lanes; lane++) { - int role = map->role[peer][lane]; sircl_fabric_step steps[FW]; int hops; - if (role > 3) return fail(e, SIRCL_FABRIC_INVALID, "rank %d has unknown role", rank); - if (!l) continue; - hops = walk(l, l->positions[rank], role / 2, l->positions[peer], steps); - if (!hops) return fail(e, SIRCL_FABRIC_UNREACHABLE, "rank %d lane %d to rank %d leaves the group's fabric", rank, lane, peer); - if (hops - 1 > max_relays) return fail(e, SIRCL_FABRIC_LIMIT, "rank %d lane %d to rank %d crosses %d relays; limit is %d", rank, lane, peer, hops - 1, max_relays); - } - } return 0; -} -int sircl_fabric_complementary(const sircl_fabric_layout *l, const sircl_route_map *maps, sircl_fabric_error *e) { - int rank, peer, lane; clear_error(e); - if (!layout_valid(l) || !maps) return fail(e, SIRCL_FABRIC_INVALID, "layout and maps are required"); - for (rank = 0; rank < l->world; rank++) if (sircl_fabric_map_validate(l, &maps[rank], rank, l->world, FW, e)) return -1; - for (rank = 0; rank < l->world; rank++) for (peer = 0; peer < l->world; peer++) if (peer != rank) { - if (maps[rank].count[peer] != maps[peer].count[rank]) return fail(e, SIRCL_FABRIC_MISMATCH, "ranks %d and %d disagree on lanes", rank, peer); - for (lane = 0; lane < maps[rank].count[peer]; lane++) { - int mine = maps[rank].role[peer][lane]; sircl_fabric_step steps[FW]; - int hops = walk(l, l->positions[rank], mine / 2, l->positions[peer], steps); - int expected = steps[hops - 1].dst_port * 2 + mine % 2; - if (maps[peer].role[rank][lane] != expected) return fail(e, SIRCL_FABRIC_MISMATCH, - "rank %d lane %d arrives on rank %d port %d (%s); peer lists %s", rank, lane, peer, - steps[hops - 1].dst_port, devices[expected], devices[maps[peer].role[rank][lane]]); - } - } return 0; -} -int sircl_fabric_agree(const sircl_fabric_layout *l, int world, int lanes, - const sircl_fabric_rank_record *records, int max_relays, sircl_fabric_error *e) { - sircl_route_map maps[FW]; int rank, peer, lane; clear_error(e); - if (!records || world < 2 || world > FW || lanes < 1 || lanes > FL || (l && (!layout_valid(l) || l->world != world))) - return fail(e, SIRCL_FABRIC_INVALID, "invalid setup agreement arguments"); - for (rank = 0; rank < world; rank++) if (records[rank].local_error) - return fail(e, SIRCL_FABRIC_MISMATCH, "rank %d: %s", rank, records[rank].local_error); - for (rank = 0; rank < world; rank++) { - if (records[rank].shared_size && !records[rank].shared_settings) return fail(e, SIRCL_FABRIC_INVALID, "rank %d lacks shared settings", rank); - if (records[rank].shared_size != records[0].shared_size || (records[0].shared_size && - memcmp(records[rank].shared_settings, records[0].shared_settings, records[0].shared_size))) - return fail(e, SIRCL_FABRIC_MISMATCH, "rank %d shared settings differ from rank 0", rank); - maps[rank] = records[rank].map; - for (peer = 0; peer < world; peer++) if (maps[rank].count[peer] != (peer == rank ? 0 : lanes)) - return fail(e, SIRCL_FABRIC_MISMATCH, "rank %d has incorrect lane count toward rank %d", rank, peer); - if (sircl_fabric_map_validate(l, &maps[rank], rank, world, max_relays, e)) return -1; - } - if (l) return sircl_fabric_complementary(l, maps, e); - for (rank = 0; rank < world; rank++) for (peer = 0; peer < world; peer++) if (peer != rank) - for (lane = 0; lane < lanes; lane++) if (maps[rank].role[peer][lane] % 2 != maps[peer].role[rank][lane] % 2) - return fail(e, SIRCL_FABRIC_MISMATCH, "rank %d and rank %d lane %d use different function classes", rank, peer, lane); - return 0; -} -int sircl_fabric_post_order(const sircl_fabric_routes *r, int rank, const char *order, int *peers, sircl_fabric_error *e) { - int world, i, n = 0, seen[FW] = {0}; const char *p = order; char text[256]; size_t len; clear_error(e); - if (!routes_valid(r) || !peers || rank < 0 || rank >= r->layout.world) return fail(e, SIRCL_FABRIC_INVALID, "invalid posting order arguments"); - world = r->layout.world; - if (!p) p = "rank"; - skip_space(&p); len = strlen(p); while (len && isspace((unsigned char)p[len-1])) len--; - if (len >= sizeof text) return fail(e, SIRCL_FABRIC_INVALID, "posting order is too long"); - memcpy(text, p, len); text[len] = 0; p = text; - if (!len || !strcmp(p, "rank")) { for (i = 0; i < world; i++) if (i != rank) peers[n++] = i; return 0; } - if (!strcmp(p, "ring-farthest")) { - for (i = world / 2; i >= 1; i--) { - int a = (rank + i) % world, b = (rank + world - i) % world; peers[n++] = a; if (a != b) peers[n++] = b; - } return 0; - } - if (!strcmp(p, "farthest")) { - int distances[FW] = {0}, max = 0, d, port; - for (i = 0; i < world; i++) if (i != rank) { int lane; - for (lane = 0; lane < r->lanes; lane++) if (r->route[rank][i][lane].hops - 1 > distances[i]) distances[i] = r->route[rank][i][lane].hops - 1; - if (distances[i] > max) max = distances[i]; - } - for (d = max; d >= 0; d--) { - int next[2] = {0, 0}, queues[2][FW], count[2] = {0, 0}; - for (i = 0; i < world; i++) if (i != rank && distances[i] == d) { port = r->route[rank][i][0].local_role / 2; queues[port][count[port]++] = i; } - while (next[0] < count[0] || next[1] < count[1]) for (port = 0; port < 2; port++) - if (next[port] < count[port]) peers[n++] = queues[port][next[port]++]; - } return 0; - } - while (*p) { int peer; - if (number(&p, &peer) || peer >= world || peer == rank || seen[peer]++ || n == world - 1) - return fail(e, SIRCL_FABRIC_INVALID, "posting order must name every peer exactly once"); - peers[n++] = peer; if (!*p) break; if (*p != ',') return fail(e, SIRCL_FABRIC_INVALID, "malformed posting order"); p++; - skip_space(&p); if (!*p) return fail(e, SIRCL_FABRIC_INVALID, "posting order ends in an empty peer"); - } - return n == world - 1 ? 0 : fail(e, SIRCL_FABRIC_INVALID, "posting order must name every peer exactly once"); -} -static int queue_loads(const sircl_fabric_routes *r, const int *order, int load[FW][2][2]) { - int rank, peer, lane, k; memset(load, 0, sizeof(int) * FW * 2 * 2); - for (rank = 0; rank < r->layout.world; rank++) for (peer = 0; peer < r->layout.world; peer++) if (peer != rank) { - if (order) { int i, enabled = 0; - for (i = 0; i < r->layout.world; i++) { - if (order[i] == rank && order[(i + 1) % r->layout.world] == peer) enabled = 1; - } - if (!enabled) continue; - } - for (lane = 0; lane < r->lanes; lane++) { - const sircl_lane_route *route = &r->route[rank][peer][lane]; - if (route->hops < 1 || route->hops > r->layout.node_count || route->local_role < 0 || route->local_role > 3) return -1; - for (k = 0; k < route->hops - 1; k++) { - int node = node_at(&r->layout, route->steps[k].dst), port = route->steps[k].dst_port; - if (node < 0 || port < 0 || port > 1) return -1; - load[node][route->local_role % 2][1 - port]++; - } - } - } return 0; -} -int sircl_fabric_relay_load(const sircl_fabric_routes *r, int *busiest, double *factor, sircl_fabric_error *e) { - int load[FW][2][2], i, p, f, max = 0; clear_error(e); - if (!routes_valid(r) || !busiest || !factor || queue_loads(r, NULL, load)) return fail(e, SIRCL_FABRIC_INVALID, "invalid relay routes"); - for (i = 0; i < r->layout.node_count; i++) for (p = 0; p < 2; p++) for (f = 0; f < 2; f++) if (load[i][f][p] > max) max = load[i][f][p]; - *busiest = max; *factor = (double)max / r->lanes; return 0; -} -static uint64_t queue_share(uint64_t bytes) { return (bytes / 4) * 3 + (bytes % 4) * 3 / 4; } -int sircl_fabric_forward_windows(const sircl_fabric_routes *r, int rank, uint64_t max_window, - uint64_t chunk, uint64_t queue_bytes, uint64_t out[FW][FL], sircl_fabric_error *e) { - int load[FW][2][2], peer, lane; clear_error(e); - if (!routes_valid(r) || !out || rank < 0 || rank >= r->layout.world) return fail(e, SIRCL_FABRIC_INVALID, "invalid forward window arguments"); - memset(out, 0, sizeof(uint64_t) * FW * FL); if (!max_window) return 0; - if (!chunk || chunk % 16 || max_window < chunk) return fail(e, SIRCL_FABRIC_INVALID, "forward chunk must be a positive multiple of 16 within window"); - if (queue_loads(r, NULL, load)) return fail(e, SIRCL_FABRIC_INVALID, "invalid relay routes"); - for (peer = 0; peer < r->layout.world; peer++) if (peer != rank) for (lane = 0; lane < r->lanes; lane++) { - const sircl_lane_route *route = &r->route[rank][peer][lane]; int k, sharing = 0; - for (k = 0; k < route->hops - 1; k++) { int q = load[node_at(&r->layout, route->steps[k].dst)][route->local_role % 2][1 - route->steps[k].dst_port]; if (q > sharing) sharing = q; } - if (sharing) { uint64_t limit = queue_share(queue_bytes) / (uint64_t)sharing; - /* Fail closed if one chunk already exceeds the queue budget. */ - if (limit < chunk) return fail(e, SIRCL_FABRIC_LIMIT, "relay queue budget cannot hold one chunk per lane"); - if (max_window < limit) limit = max_window; - out[peer][lane] = limit / chunk * chunk; - } - } return 0; -} -int sircl_fabric_chain_order(const sircl_fabric_routes *r, int *order, sircl_fabric_error *e) { - const sircl_fabric_layout *l; int nodes[FW], visited[FW] = {0}, i, start, previous = -1; clear_error(e); - if (!routes_valid(r) || !order) return fail(e, SIRCL_FABRIC_INVALID, "invalid chain arguments"); - l = &r->layout; - if (l->world != l->node_count) return fail(e, SIRCL_FABRIC_UNREACHABLE, "chain requires a rank at every fabric position"); - start = l->positions[0]; - if (!l->cycle) for (i = 0; i < l->node_count; i++) { - sircl_fabric_step s; if (!cross(l, l->nodes[i], 0, &s) || !cross(l, l->nodes[i], 1, &s)) { start = l->nodes[i]; break; } - } - nodes[0] = start; visited[node_at(l, start)] = 1; - for (i = 1; i < l->world; i++) { - int port, found = 0; sircl_fabric_step step; - for (port = 0; port < 2; port++) if (cross(l, nodes[i-1], port, &step) && - step.dst != previous && !visited[node_at(l, step.dst)]) { - nodes[i] = step.dst; visited[node_at(l, step.dst)] = 1; found = 1; break; - } - if (!found) return fail(e, SIRCL_FABRIC_UNREACHABLE, "fabric has no complete chain"); - previous = nodes[i-1]; - } - for (i = 0; i < l->world; i++) { int rank; for (rank = 0; rank < l->world && l->positions[rank] != nodes[i]; rank++) { } - order[i] = rank; - } - for (i = 0; i < l->world - 1; i++) { int lane; for (lane = 0; lane < r->lanes; lane++) - if (r->route[order[i]][order[i+1]][lane].hops != 1 || r->route[order[i+1]][order[i]][lane].hops != 1) - return fail(e, SIRCL_FABRIC_UNREACHABLE, "chain edge has a relayed lane"); - } return 0; -} -int sircl_fabric_ring_window(const sircl_fabric_routes *r, const int *order, uint64_t chunk, - uint64_t queue_bytes, uint64_t *window, sircl_fabric_error *e) { - int load[FW][2][2], seen[FW] = {0}, i, f, p, any = 0; clear_error(e); - if (!routes_valid(r) || !order || !window || !chunk || chunk % 16) return fail(e, SIRCL_FABRIC_INVALID, "invalid ring window arguments"); - for (i = 0; i < r->layout.world; i++) if (order[i] < 0 || order[i] >= r->layout.world || seen[order[i]]++) - return fail(e, SIRCL_FABRIC_INVALID, "ring order must name every rank exactly once"); - if (queue_loads(r, order, load)) return fail(e, SIRCL_FABRIC_INVALID, "invalid relay routes"); - for (i = 0; i < r->layout.node_count; i++) for (f = 0; f < 2; f++) for (p = 0; p < 2; p++) { - if (load[i][f][p] > 1) return fail(e, SIRCL_FABRIC_LIMIT, "relay %d function %d port %d carries multiple ring lanes", r->layout.nodes[i], f, p); - if (load[i][f][p]) any = 1; - } - *window = any ? queue_share(queue_bytes) / chunk * chunk : 0; - return any && *window < chunk ? fail(e, SIRCL_FABRIC_LIMIT, "relay queue holds less than one chunk") : 0; -} -int sircl_protocol_stripe(uint64_t packs, int lanes, int lane, sircl_pack_range *out) { - uint64_t base, rest; if (!out || lanes < 1 || lanes > FL || lane < 0 || lane >= lanes) return -1; - base = packs / (uint64_t)lanes; rest = packs % (uint64_t)lanes; - out->first = (uint64_t)lane * base + ((uint64_t)lane < rest ? (uint64_t)lane : rest); - out->count = base + ((uint64_t)lane < rest); return 0; -} -int sircl_protocol_chunk(uint64_t packs, int world, int index, sircl_pack_range *out) { - uint64_t base, rest, lo, hi; if (!out || world < 2 || world > FW || index < 0 || index >= world) return -1; - /* Division before multiplication preserves floor(i*P/W) without overflow. */ - base = packs / (uint64_t)world; rest = packs % (uint64_t)world; - lo = (uint64_t)index * base + (uint64_t)index * rest / (uint64_t)world; - hi = (uint64_t)(index + 1) * base + (uint64_t)(index + 1) * rest / (uint64_t)world; - out->first = lo; out->count = hi - lo; return 0; -} -int sircl_protocol_flag_index(int ns, int source, int slot, int lane, int world, int lanes, uint32_t *out) { - /* The reference permits lane 1 with one active lane for reserved flag indexing. */ - if (!out || ns < 0 || ns > 1 || world < 2 || world > FW || source < 0 || source >= world || - slot < 0 || slot > 1 || lanes < 1 || lanes > FL || lane < 0 || lane >= FL) return -1; - *out = (uint32_t)(ns * world * 2 * lanes + (source * 2 + slot) * lanes + lane); return 0; -} -int sircl_protocol_op_word(int op, uint32_t bytes, uint32_t *out) { - if (!out || op < 0 || op > 3 || !bytes || bytes % 16 || bytes > SIRCL_PROTOCOL_OP_BYTES_MASK) return -1; - *out = (uint32_t)op << 30 | bytes; return 0; -} -int sircl_protocol_descriptor(const sircl_phase *p, int world, uint32_t *out) { - if (!p || !out || p->first < 0 || p->first > p->end || p->end > 31 || p->peer < 0 || p->peer > 15 || - p->namespace_id < 0 || p->namespace_id > 1 || world < 0 || world > FW || - (world && (p->end > world || p->peer >= world))) return -1; - *out = UINT32_C(0x80000000) | (uint32_t)p->namespace_id << 14 | (uint32_t)p->peer << 10 | - (uint32_t)p->end << 5 | (uint32_t)p->first; return 0; -} -static int swing_peer(int world, int rank, int step) { - static const int offsets[4] = {1, -1, 3, -5}; int p; - if (step < 0 || step >= 4) return rank; - p = rank + (rank % 2 ? -offsets[step] : offsets[step]); - return (p + world) % world; -} -static uint32_t reach(int world, int steps, int rank, int step) { - if (step >= steps) return UINT32_C(1) << rank; - return reach(world, steps, rank, step + 1) | reach(world, steps, swing_peer(world, rank, step), step + 1); -} -static int first_bit(uint32_t bits) { int i; for (i = 0; i < FW; i++) if (bits & (UINT32_C(1) << i)) return i; return FW; } -static void owners_walk(int world, int steps, int rank, int step, int *owners, int *count) { - uint32_t a, b; int x, y; - if (step >= steps) { owners[(*count)++] = rank; return; } - a = reach(world, steps, rank, step + 1); b = reach(world, steps, swing_peer(world, rank, step), step + 1); - x = first_bit(a); y = first_bit(b); - if (y < x) { int t = x; x = y; y = t; } - owners_walk(world, steps, x, step + 1, owners, count); owners_walk(world, steps, y, step + 1, owners, count); -} -static void phase_span(uint32_t bits, const int *owners, int world, sircl_phase *phase) { - int i; phase->first = world; phase->end = 0; - for (i = 0; i < world; i++) if (bits & (UINT32_C(1) << owners[i])) { if (i < phase->first) phase->first = i; phase->end = i + 1; } -} -int sircl_protocol_swing(int world, int rank, int *owners, sircl_phase phases[SIRCL_PROTOCOL_MAX_PHASES], int *phase_count) { - int steps = 0, i, count = 0, n = 0; - if (!owners || !phases || !phase_count || world < 2 || world > FW || (world & (world - 1)) || rank < 0 || rank >= world) return -1; - for (i = world; i > 1; i >>= 1) steps++; - owners_walk(world, steps, 0, 0, owners, &count); - for (i = 0; i < steps; i++) { sircl_phase *p = &phases[n++]; p->peer = swing_peer(world, rank, i); p->namespace_id = 0; phase_span(reach(world, steps, p->peer, i + 1), owners, world, p); } - for (i = steps - 1; i >= 0; i--) { sircl_phase *p = &phases[n++]; p->peer = swing_peer(world, rank, i); p->namespace_id = 1; phase_span(reach(world, steps, rank, i + 1), owners, world, p); } - *phase_count = n; return 0; -} -int sircl_protocol_select(uint64_t bytes, int algorithm, int large, uint64_t oneshot_max, - uint64_t swing_above, unsigned available, int *out) { - if (!out || algorithm < -1 || algorithm > 2 || large < 1 || large > 2) return -1; - if (algorithm >= 0) { *out = algorithm; return 0; } - if (bytes <= oneshot_max || !(available & (1u << large))) *out = SIRCL_ALGORITHM_ONESHOT; - else if (swing_above && bytes > swing_above && (available & (1u << SIRCL_ALGORITHM_SWING))) *out = SIRCL_ALGORITHM_SWING; - else *out = large; - return 0; -} diff --git a/spark_transport/libsircl/src/kernelpack.c b/spark_transport/libsircl/src/kernelpack.c index e7454f3c..4ee3f777 100644 --- a/spark_transport/libsircl/src/kernelpack.c +++ b/spark_transport/libsircl/src/kernelpack.c @@ -37,6 +37,7 @@ typedef struct { sccl_CUfunction ring_exchange[SCCL_CHAIN_MAX_UNROLL + 1]; sccl_CUfunction ring_exchange_reduce[SCCL_DT_COUNT][SCCL_CHAIN_MAX_UNROLL + 1]; sccl_CUfunction p2p[2][SCCL_P2P_MAX_UNROLL + 1]; + sccl_CUfunction ep_dispatch, ep_combine_xfer, ep_combine_reduce[SCCL_DT_COUNT]; } loaded_pack; static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; @@ -202,6 +203,28 @@ int sccl_kp_load(sccl_CUcontext ctx) { sccl_cuda_result_text(r)); } } + if (!failed) { + static const char *const ep_names[2] = {"sircl_ep_dispatch", "sircl_ep_combine_xfer"}; + sccl_CUfunction *ep_dst[2] = {&p->ep_dispatch, &p->ep_combine_xfer}; + for (int i = 0; !failed && i < 2; ++i) { + r = cu->ModuleGetFunction(ep_dst[i], p->p2p_module, ep_names[i]); + if (r != SCCL_CUDA_SUCCESS) { + failed = 1; + snprintf(error_text, sizeof error_text, "point-to-point pack has no entry %s: %s", ep_names[i], + sccl_cuda_result_text(r)); + } + } + for (int d = 0; !failed && d < SCCL_DT_COUNT; ++d) { + char name[64]; + snprintf(name, sizeof name, "sircl_ep_combine_reduce_%s", dt_names[d]); + r = cu->ModuleGetFunction(&p->ep_combine_reduce[d], p->p2p_module, name); + if (r != SCCL_CUDA_SUCCESS) { + failed = 1; + snprintf(error_text, sizeof error_text, "point-to-point pack has no entry %s: %s", name, + sccl_cuda_result_text(r)); + } + } + } if (failed && p->p2p_module) cu->ModuleUnload(p->p2p_module); if (failed && p->links_module) cu->ModuleUnload(p->links_module); if (failed && p->fold_module) cu->ModuleUnload(p->fold_module); @@ -396,6 +419,40 @@ sccl_CUresult sccl_kp_launch_p2p(sccl_CUfunction function, const sccl_p2p_args * return cu->LaunchKernel(function, grid, 1, 1, threads, 1, 1, 0, stream, params, NULL); } +int sccl_kp_ep_functions(sccl_CUcontext ctx, sccl_CUfunction *dispatch, sccl_CUfunction *combine_xfer, + sccl_CUfunction reduce[SCCL_DT_COUNT]) { + pthread_mutex_lock(&lock); + loaded_pack *p = find(ctx); + if (p) { + *dispatch = p->ep_dispatch; + *combine_xfer = p->ep_combine_xfer; + for (int d = 0; d < SCCL_DT_COUNT; ++d) reduce[d] = p->ep_combine_reduce[d]; + } + pthread_mutex_unlock(&lock); + if (!p) { + snprintf(error_text, sizeof error_text, "the kernel packs are not loaded in this context"); + return -1; + } + return 0; +} + +sccl_CUresult sccl_kp_launch_ep(sccl_CUfunction function, const sccl_ep_args *args, unsigned grid, unsigned threads, + sccl_CUstream stream) { + const sccl_cuda *cu = sccl_cuda_get(); + sccl_ep_args a = *args; + void *params[] = {&a}; + return cu->LaunchKernel(function, grid, 1, 1, threads, 1, 1, 0, stream, params, NULL); +} + +sccl_CUresult sccl_kp_launch_ep_cooperative(sccl_CUfunction function, const sccl_ep_args *args, unsigned grid, + unsigned threads, sccl_CUstream stream) { + const sccl_cuda *cu = sccl_cuda_get(); + if (!cu || !cu->LaunchCooperativeKernel) return 801; /* CUDA_ERROR_NOT_SUPPORTED */ + sccl_ep_args a = *args; + void *params[] = {&a}; + return cu->LaunchCooperativeKernel(function, grid, 1, 1, threads, 1, 1, 0, stream, params); +} + sccl_CUresult sccl_kp_launch_fold(sccl_CUfunction function, uint64_t rows, int64_t pitch, uint64_t out, int64_t count, int32_t world, unsigned grid, unsigned threads, sccl_CUstream stream) { const sccl_cuda *cu = sccl_cuda_get(); diff --git a/spark_transport/libsircl/src/kernelpack.h b/spark_transport/libsircl/src/kernelpack.h index 5f7df5eb..84b813d4 100644 --- a/spark_transport/libsircl/src/kernelpack.h +++ b/spark_transport/libsircl/src/kernelpack.h @@ -110,18 +110,33 @@ _Static_assert(sizeof(sccl_link_args) == 176, "sccl_link_args must match the lin * for at most SCCL_P2P_MAX_THREADS threads per block. */ enum { SCCL_P2P_MAX_UNROLL = 8, SCCL_P2P_MAX_THREADS = 512, SCCL_P2P_MIN_THREADS = 64 }; /* One point-to-point launch: the message (`data`, a 16-byte-aligned device address; `packs` 16-byte packs; - * `tail` its bytes modulo 16), the channel's first item and the message's items, the peer's block and the - * control line of the channel arena (device addresses), the peer, the slot geometry and the block offsets of - * the native layer's p2p_layout (receive, send, flag, desc, ready, consumed, sent). Mirrors the device-side + * `tail` its bytes modulo 16), the message's items, the peer's block, the control line and the channel's + * device counter pair ({seq, arrival}, 8 bytes), the peer, the slot geometry and the block offsets of the + * native layer's p2p_layout (receive, send, flag, desc, ready, consumed, sent). Mirrors the device-side * P2PParams (120 bytes). */ typedef struct { - uint64_t data, block_base, ctrl_base, slot_bytes; + uint64_t data, block_base, ctrl_base, slot_bytes, counter_ptr; int32_t packs, tail, items, peer; - uint32_t first, slots, lanes, reserved; + uint32_t slots, lanes; uint64_t recv_off, send_off, flag_off, desc_off, ready_off, consumed_off, sent_off; } sccl_p2p_args; _Static_assert(sizeof(sccl_p2p_args) == 120, "sccl_p2p_args must match the point-to-point pack's P2PParams"); +/* SIRCL-EP kernels in the point-to-point pack (kernels/sircl_p2p.cu): GPU-driven dynamic variable-length + * MoE dispatch, combine transfer, and rank-ordered combine reduction. Mirrors sircl_ep::EpParams (200 bytes). */ +enum { SCCL_EP_THREADS = 256, SCCL_EP_MAX_TOPK = 16 }; +typedef struct { + uint64_t hidden_in, topk_ids_in, topk_weights_in; + uint64_t hidden_out, topk_ids_out, topk_weights_out; + uint64_t recv_counts_out, workspace; + uint64_t p2p_dev, p2p_counters; + uint64_t layout_control, layout_block, slot_bytes; + uint64_t recv_off, send_off, flag_off, desc_off, ready_off, consumed_off, sent_off; + int32_t world, rank, num_tokens, max_tokens, hidden_bytes, top_k, num_experts; + uint32_t slots, lanes, wire_row_bytes; +} sccl_ep_args; +_Static_assert(sizeof(sccl_ep_args) == 200, "sccl_ep_args must match the point-to-point pack's EpParams"); + /* Load every pack into `ctx` once (pushing it current for the load); later calls for the same context * return at once. Each successful call holds a reference on the context's entry, which sccl_kp_release * drops; at most 16 contexts hold entries at once. 0 on success. */ @@ -169,6 +184,16 @@ sccl_CUresult sccl_kp_launch_link(sccl_CUfunction function, const sccl_link_args int sccl_kp_p2p_function(sccl_CUcontext ctx, int send, int unroll, sccl_CUfunction *out); sccl_CUresult sccl_kp_launch_p2p(sccl_CUfunction function, const sccl_p2p_args *args, unsigned grid, unsigned threads, sccl_CUstream stream); +/* SIRCL-EP entries (from the point-to-point pack). */ +int sccl_kp_ep_functions(sccl_CUcontext ctx, sccl_CUfunction *dispatch, sccl_CUfunction *combine_xfer, + sccl_CUfunction reduce[SCCL_DT_COUNT]); +sccl_CUresult sccl_kp_launch_ep(sccl_CUfunction function, const sccl_ep_args *args, unsigned grid, unsigned threads, + sccl_CUstream stream); +/* Cooperative launch of an EP transfer kernel (sircl_ep_dispatch, sircl_ep_combine_xfer): guarantees + * all 2 * world sender and receiver CTAs co-reside simultaneously, eliminating co-scheduling deadlock + * under both eager execution (with concurrent aux-stream kernels) and CUDA graph replay. */ +sccl_CUresult sccl_kp_launch_ep_cooperative(sccl_CUfunction function, const sccl_ep_args *args, unsigned grid, + unsigned threads, sccl_CUstream stream); /* SHA-256 of the embedded transport, fold, link and point-to-point fatbins, hexadecimal; part of the setup * agreement. */ const char *sccl_kp_hash(void); diff --git a/spark_transport/libsircl/src/transport/proxy_names.h b/spark_transport/libsircl/src/transport/proxy_names.h index fbc1022e..53197198 100644 --- a/spark_transport/libsircl/src/transport/proxy_names.h +++ b/spark_transport/libsircl/src/transport/proxy_names.h @@ -5,6 +5,10 @@ * renamed too (the stand-in's definitions and the emu proxy's calls). */ #ifndef SCCL_PROXY_NAMES_H #define SCCL_PROXY_NAMES_H +#ifndef _GNU_SOURCE +#define _GNU_SOURCE +#endif +#include "../env_names.h" #define SCCL_CAT2(a, b) a##b #define SCCL_CAT(a, b) SCCL_CAT2(a, b) #define SCCL_PN(name) SCCL_CAT(SCCL_CAT(sccl_, SCCL_PROXY_TAG), SCCL_CAT(_, name)) diff --git a/spark_transport/libsircl/src/transport/sircl_p2p_proxy.c b/spark_transport/libsircl/src/transport/sircl_p2p_proxy.c index e7d5e325..c2c1200c 100644 --- a/spark_transport/libsircl/src/transport/sircl_p2p_proxy.c +++ b/spark_transport/libsircl/src/transport/sircl_p2p_proxy.c @@ -50,7 +50,9 @@ * test-only verbs stand-in in sparkring_sircl/testing/fake_verbs. */ +#ifndef _GNU_SOURCE #define _GNU_SOURCE +#endif #include #include #include @@ -160,8 +162,8 @@ typedef struct { uint32_t lane_bytes[P2P_MAX_LANES]; /* bytes of that item's stripe the lane posted */ int lane_header[P2P_MAX_LANES]; /* lane 0: the item's header is posted */ uint32_t lane_done[P2P_MAX_LANES]; /* items whose flag write completed, per lane */ - uint32_t done; /* items complete on every lane (the sent word) */ - uint32_t credit_seen; /* the newest credit read from the peer */ + _Atomic uint32_t done; /* items complete on every lane (the sent word) */ + _Atomic uint32_t credit_seen; /* the newest credit read from the peer */ /* inbound */ uint32_t released; /* items the kernel consumed, contiguous */ uint32_t credited; /* credit last written to the peer */ @@ -838,9 +840,9 @@ static int service_out(p2p_ctx_t *c, int p) { uint32_t slots = (uint32_t)c->slots; uint32_t credit = __atomic_load_n(block_word(c, p, L_CREDIT, 0), __ATOMIC_ACQUIRE); int work = 0; - if (credit != ch->credit_seen) { + if (credit != atomic_load_explicit(&ch->credit_seen, memory_order_relaxed)) { prove(c, p, credit); - ch->credit_seen = credit; + atomic_store_explicit(&ch->credit_seen, credit, memory_order_release); work = 1; } uint64_t mine = block_off(c, c->rank); /* this rank's block in the peer's arena */ @@ -916,8 +918,8 @@ static int service_out(p2p_ctx_t *c, int p) { for (int lane = 1; lane < c->lane_count; lane++) { if ((int32_t)(ch->lane_done[lane] - done) < 0) done = ch->lane_done[lane]; } - if (done != ch->done) { - ch->done = done; + if (done != atomic_load_explicit(&ch->done, memory_order_relaxed)) { + atomic_store_explicit(&ch->done, done, memory_order_release); __atomic_store_n(block_word(c, p, L_SENT, 0), done, __ATOMIC_RELEASE); work = 1; } @@ -1181,7 +1183,11 @@ int p2p_start(p2p_ctx_t *c) { } pthread_attr_t attr; pthread_attr_t *use = NULL; +#ifdef SCCL_ENV_LOOKUP + const char *cpus = sccl_env(SCCL_ENV_P2P_PROGRESS_CPU); +#else const char *cpus = getenv("SIRCL_P2P_PROGRESS_CPU"); +#endif if (cpus != NULL && *cpus != '\0') { cpu_set_t set; if (parse_cpu_list(cpus, &set) != 0) { @@ -1258,8 +1264,8 @@ uint64_t p2p_peer_stat(p2p_ctx_t *c, int peer, int which) { case 1: return atomic_load_explicit(&ch->bytes_posted, memory_order_relaxed); case 2: return atomic_load_explicit(&ch->items_released, memory_order_relaxed); case 3: return atomic_load_explicit(&ch->credits_sent, memory_order_relaxed); - case 4: return ch->credit_seen; - case 5: return ch->done; + case 4: return atomic_load_explicit(&ch->credit_seen, memory_order_acquire); + case 5: return atomic_load_explicit(&ch->done, memory_order_acquire); default: return 0; } } @@ -1280,7 +1286,9 @@ int p2p_test_set_base(p2p_ctx_t *c, uint32_t base) { if (atomic_load(&c->running)) return -1; for (int p = 0; p < c->world; p++) { p2p_channel_t *ch = &c->ch[p]; - ch->next_post = ch->done = ch->released = ch->credited = ch->credit_seen = base; + ch->next_post = ch->released = ch->credited = base; + atomic_store_explicit(&ch->done, base, memory_order_relaxed); + atomic_store_explicit(&ch->credit_seen, base, memory_order_relaxed); for (int l = 0; l < P2P_MAX_LANES; l++) { ch->lane_item[l] = base; ch->lane_done[l] = base; diff --git a/spark_transport/libsircl/src/transport/sircl_p2p_proxy.c.sha256 b/spark_transport/libsircl/src/transport/sircl_p2p_proxy.c.sha256 index f4eba589..1fd9e159 100644 --- a/spark_transport/libsircl/src/transport/sircl_p2p_proxy.c.sha256 +++ b/spark_transport/libsircl/src/transport/sircl_p2p_proxy.c.sha256 @@ -1 +1 @@ -c8ccfcb93ffa2d6a9baa85728126c1c157327573a3b99c6db4340616734310ff +c9bbd9637f68ea47369c5cd429fd11a675bbf6f14ca47541efef3cd5424f1a06 diff --git a/spark_transport/libsircl/src/transport/sircl_roce_proxy.c b/spark_transport/libsircl/src/transport/sircl_roce_proxy.c index 6441f37b..9448d3fb 100644 --- a/spark_transport/libsircl/src/transport/sircl_roce_proxy.c +++ b/spark_transport/libsircl/src/transport/sircl_roce_proxy.c @@ -112,7 +112,9 @@ * the test-only verbs stand-in in sparkring_sircl/testing/fake_verbs. */ +#ifndef _GNU_SOURCE #define _GNU_SOURCE +#endif #include #include #include @@ -179,6 +181,7 @@ enum { ROCE_CTRL_PHASE = 9, ROCE_CTRL_WAIT_LIMIT_US = 7, ROCE_CTRL_DESC = 17, + ROCE_CTRL_ABORT = 30, ROCE_CTRL_LANE_CHECK = 31, }; @@ -187,7 +190,7 @@ enum { ROCE_OP_ONESHOT = 0, ROCE_OP_TWOSHOT = 1, ROCE_OP_DESCRIBED = 2, ROCE_OP_ /* Work-request ids: peer in bits 0-7, lane in 8-15, kind in 16-23, chain stream in * 24-31, sequence (or global chain chunk) in 32-63. */ enum { ROCE_WR_OP = 0, ROCE_WR_CHECK = 1, ROCE_WR_CHAIN = 2, ROCE_WR_CREDIT = 3, ROCE_WR_LINK = 4, - ROCE_WR_LINK_CREDIT = 5, ROCE_WR_LINK_DATA = 6 }; + ROCE_WR_LINK_CREDIT = 5, ROCE_WR_LINK_DATA = 6, ROCE_WR_ABORT = 7 }; #define ROCE_CHAIN_STREAMS 4 #define ROCE_CHAIN_MAX_SLOTS 32 @@ -450,6 +453,8 @@ typedef struct roce_ctx { uint64_t trace_taken; uint64_t test_link_delay_ns; /* tests: a link op is taken this long after its doorbell is seen */ uint64_t test_link_seen_ns; /* tests: when the pending link doorbell was first seen */ + int aborted; /* the peer abort notices were posted */ + _Atomic uint64_t abort_from; /* rank + 1 of a rank whose abort notice arrived (or local abort) */ char err[512]; } roce_ctx_t; @@ -1136,6 +1141,7 @@ static int drain_device(roce_ctx_t *c, int d) { int kind = (int)((wc[i].wr_id >> 16) & 0xFFu); int stream = (int)((wc[i].wr_id >> 24) & 0xFFu); uint32_t seq = (uint32_t)(wc[i].wr_id >> 32); + if (kind == ROCE_WR_ABORT) continue; if (wc[i].status != IBV_WC_SUCCESS) { if (kind == ROCE_WR_CHAIN || kind == ROCE_WR_CREDIT) { FAIL(c, "RDMA write of chain %s %u of stream %d to rank %d lane %d on %s failed: %s " @@ -2657,12 +2663,68 @@ static void note_cpu(roce_ctx_t *c) { } } +/* Write an abort notice naming the rank where the failure happened (`origin`) into every connected + * peer's control abort word (best effort, once), so peers fail fast instead of waiting out their + * serving/startup timeout. Backwards-compatible: word ROCE_CTRL_ABORT (30) sits inside the + * zero-initialized 128-byte control line and is unused by earlier peers. */ +static void post_aborts(roce_ctx_t *c, int origin) { + if (c->aborted) return; + c->aborted = 1; + uint32_t value[ROCE_MAX_PEERS]; + int posted = 0; + for (int p = 0; p < c->world; p++) { + if (p == c->rank || c->lane_device[p][0] < 0) continue; + int d = c->lane_device[p][0]; + roce_dev_t *dev = &c->dev[d]; + if (dev->qp[p] == NULL || dev->ack_count[p] >= ROCE_SEND_DEPTH - 1) continue; + value[p] = (uint32_t)origin + 1u; + struct ibv_sge sge = {.addr = (uint64_t)(uintptr_t)&value[p], .length = 4, .lkey = 0}; + struct ibv_send_wr wr; + memset(&wr, 0, sizeof(wr)); + wr.wr_id = make_wr_id(p, 0, ROCE_WR_ABORT, 0); + wr.sg_list = &sge; + wr.num_sge = 1; + wr.opcode = IBV_WR_RDMA_WRITE; + wr.send_flags = IBV_SEND_SIGNALED | IBV_SEND_INLINE; + wr.wr.rdma.remote_addr = c->peer_addr[p] + c->ctrl_off + 4u * (uint64_t)ROCE_CTRL_ABORT; + wr.wr.rdma.rkey = c->peer_rkey[0][p]; + struct ibv_send_wr *bad = NULL; + if (ibv_post_send(dev->qp[p], &wr, &bad) == 0) posted = 1; + } + if (!posted) return; + /* Give the notices a moment to leave before the thread stops polling. */ + uint64_t until = monotonic_ns() + 2000000ull; + while (monotonic_ns() < until) { + for (int d = 0; d < c->n_dev; d++) { + struct ibv_wc wc[32]; + (void)ibv_poll_cq(c->dev[d].cq, 32, wc); + } + } +} + static void *progress_main(void *arg) { roce_ctx_t *c = (roce_ctx_t *)arg; volatile uint32_t *ctrl = ctrl_words(c); uint64_t idle = 0; const struct timespec nap = {0, ROCE_NAP_NS}; while (atomic_load_explicit(&c->running, memory_order_relaxed)) { + uint32_t abort_word = __atomic_load_n(&ctrl[ROCE_CTRL_ABORT], __ATOMIC_ACQUIRE); + if (abort_word != 0) { + atomic_store(&c->abort_from, abort_word); + if (abort_word == (uint32_t)c->rank + 1u) { + FAIL(c, "session aborted on rank %d", c->rank); + } else { + FAIL(c, "session stopped after a failure on rank %u (that rank's error names it)", + abort_word - 1u); + } + atomic_store(&c->failed, 1); + post_aborts(c, (int)(abort_word - 1u)); + return NULL; + } + if (__atomic_load_n(&ctrl[ROCE_CTRL_ERROR_SEQ], __ATOMIC_ACQUIRE) != 0) { + post_aborts(c, c->rank); + return NULL; + } int work = 0; if (c->chain_slots) { int moved = chain_service(c); @@ -2710,6 +2772,7 @@ static void *progress_main(void *arg) { return NULL; failed: atomic_store(&c->failed, 1); + post_aborts(c, c->rank); return NULL; } @@ -2820,7 +2883,11 @@ int roce_start(roce_ctx_t *c) { link_set_windowed(c); pthread_attr_t attr; pthread_attr_t *use = NULL; +#ifdef SCCL_ENV_LOOKUP + const char *cpus = sccl_env(SCCL_ENV_PROGRESS_CPU); +#else const char *cpus = getenv("SIRCL_PROGRESS_CPU"); +#endif if (cpus != NULL && *cpus != '\0') { cpu_set_t set; if (parse_cpu_list(cpus, &set) != 0) { @@ -2965,6 +3032,7 @@ uint64_t roce_stat(roce_ctx_t *c, int which) { case 27: return atomic_load_explicit(&c->fwd_wait_max_ns, memory_order_relaxed); case 28: return atomic_load_explicit(&c->fwd_proven_bytes, memory_order_relaxed); case 29: return (uint64_t)c->fwd_proof; + case 30: return atomic_load_explicit(&c->abort_from, memory_order_relaxed); default: return 0; } } diff --git a/spark_transport/libsircl/src/transport/sircl_roce_proxy.c.sha256 b/spark_transport/libsircl/src/transport/sircl_roce_proxy.c.sha256 index 6b9eb7a5..aa775315 100644 --- a/spark_transport/libsircl/src/transport/sircl_roce_proxy.c.sha256 +++ b/spark_transport/libsircl/src/transport/sircl_roce_proxy.c.sha256 @@ -1 +1 @@ -6b367e194b9f6b58c96544be8b1159ed8d5d2f7b9e5b69eb9b7a4cef475611ea +24c43a2e8231a6c42ce0262675e772463303f07d6cfd85ead77dd26d7b70bfdc diff --git a/spark_transport/libsircl/tests/emulation/p2p_channels.py b/spark_transport/libsircl/tests/emulation/p2p_channels.py index 44ffb5f6..405c6f75 100644 --- a/spark_transport/libsircl/tests/emulation/p2p_channels.py +++ b/spark_transport/libsircl/tests/emulation/p2p_channels.py @@ -44,7 +44,13 @@ within 5 s, and ranks 0, 2 and 3 report the channels' failure naming rank 1 within 20 s, long before the wait limit, because the abort poisons the channels and their progress thread posts abort notices. ``--case setup``: three groups of three ranks whose setup must fail on every rank, naming the reason: LIBSIRCL_P2P_CHANNELS on rank 0 only, SIRCL_P2P_THREADS=1024 on rank 1 (the pack runs at most 512), -and a malformed LIBSIRCL_P2P_WINDOWS on rank 2. +and a malformed LIBSIRCL_P2P_WINDOWS on rank 2. ``--case graph``: CUDA graph capture of grouped +ncclSend/ncclRecv across channel peers (aligned multi-slot and unaligned/staged), 10 replays with mutated +inputs plus eager traffic before and after, checking every byte and the receipt's captured_calls. +``--case ep``: GPU-driven dynamic MoE token dispatch and combine (sirclEpWorkspaceBytes, sirclEpDispatch, +sirclEpCombine) across asymmetric eager rounds (BF16/FP16/FP32 and all-local routing) plus CUDA graph +capture and 8 dynamic-routing replays including an all-local toggle, checking bit-exactness against a +PyTorch reference and the receipt's ep counters. Status: research-only test infrastructure (the emulation gives every pair a shared-memory lane; relays are modeled by the windows' chunked posting, not by relay queues). @@ -71,7 +77,7 @@ # rank's settings, path:0-3's closing edge (position 3 to 0) crosses relays, and without a layout no rank # has a ring plan. CYCLE_PLAN = {"ring8": True, "ring8-alone": True, "path4": False, "none": False} -U8, F32 = 1, 7 +U8, F16, F32, BF16 = 1, 6, 7, 9 SLOT_BYTES = 512 << 10 INVALID_USAGE = 5 SIZES = (0, 1, 15, 4096, 65539, 1000003, 5 << 20, (8 << 20) + 16) @@ -94,6 +100,20 @@ def bind(lib): lib.ncclCommGetAsyncError.argtypes = [ctypes.c_void_p, ctypes.POINTER(ctypes.c_int)] lib.ncclCommDestroy.argtypes = [ctypes.c_void_p] lib.ncclCommAbort.argtypes = [ctypes.c_void_p] + if hasattr(lib, "sirclEpWorkspaceBytes"): + 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, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p, + ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_size_t, ctypes.c_int, + ctypes.c_int, ctypes.c_size_t, ctypes.c_int, ctypes.c_int, ctypes.c_void_p, ctypes.c_void_p, + ] + lib.sirclEpDispatch.restype = ctypes.c_int + lib.sirclEpCombine.argtypes = [ + ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_size_t, ctypes.c_int, + ctypes.c_int, ctypes.c_size_t, ctypes.c_int, ctypes.c_void_p, ctypes.c_void_p, + ] + lib.sirclEpCombine.restype = ctypes.c_int def channel_peers(layout: str, world: int, rank: int) -> set: @@ -237,6 +257,263 @@ def count(table, peer, n): report("channels on, context open, peers as the layout gives them", channels["on"] and channels["context"] and set(channels["peers"]) == peers, json.dumps({k: channels[k] for k in ("on", "context", "peers")})) + if args.case == "graph": + def run_eager(tag): + keep_e, calls_e, expect_e = [], [], [] + for peer in sorted(peers): + n_out = 4096 if (rank + peer) % 2 == 0 else 1029 + off_out = 0 if (rank + peer) % 2 == 0 else 3 + whole, view = placed(payload(rank, peer, tag, n_out), off_out) + keep_e.append(whole) + calls_e.append((True, view, peer)) + n_in = 4096 if (peer + rank) % 2 == 0 else 1029 + off_in = 0 if (peer + rank) % 2 == 0 else 5 + whole, view = empty(n_in, off_in) + keep_e.append(whole) + calls_e.append((False, view, peer)) + expect_e.append((view, payload(peer, rank, tag, n_in))) + torch.cuda.synchronize() + codes = [lib.ncclGroupStart()] + [call(*c) for c in calls_e] + [lib.ncclGroupEnd()] + stream.synchronize() + bad = [i for i, (view, want) in enumerate(expect_e) if not torch.equal(view.cpu(), want)] + return not any(codes) and not bad, f"codes {codes}, {len(bad)} differ; {last_error() if any(codes) else ''}" + + ok, detail = run_eager(500) + report("eager grouped exchange before CUDA graph capture", ok, detail) + + # Mix aligned multi-slot ((1 MiB) + 16), aligned small (4096), and unaligned/staged (1029 @ offset 3). + graph_sizes = (4096, (1 << 20) + 16, 1029) + keep_g, send_views, recv_views, graph_calls = [], [], [], [] + for peer in sorted(peers): + idx_out = (rank * 3 + peer * 5) % len(graph_sizes) + n_out = graph_sizes[idx_out] + off_out = 3 if idx_out == 2 else 0 + whole, sview = placed(payload(rank, peer, 600, n_out), off_out) + keep_g.append(whole) + send_views.append((peer, n_out, sview)) + graph_calls.append((True, sview, peer)) + + idx_in = (peer * 3 + rank * 5) % len(graph_sizes) + n_in = graph_sizes[idx_in] + off_in = 5 if idx_in == 2 else 0 + whole, rview = empty(n_in, off_in) + keep_g.append(whole) + recv_views.append((peer, n_in, rview)) + graph_calls.append((False, rview, peer)) + + torch.cuda.synchronize() + graph = torch.cuda.CUDAGraph() + with torch.cuda.graph(graph, stream=stream): + codes = [lib.ncclGroupStart()] + [call(*c) for c in graph_calls] + [lib.ncclGroupEnd()] + stream.synchronize() + report("grouped P2P channel calls capture into a CUDA graph", not any(codes), + f"codes {codes}; {last_error() if any(codes) else ''}") + + bad_replays = [] + for rep in range(10): + for peer, n_out, sview in send_views: + sview.copy_(payload(rank, peer, 1000 + rep, n_out).cuda()) + for _, _, rview in recv_views: + rview.fill_(0x5A) + torch.cuda.synchronize() + with torch.cuda.stream(stream): + graph.replay() + stream.synchronize() + for peer, n_in, rview in recv_views: + want = payload(peer, rank, 1000 + rep, n_in) + if not torch.equal(rview.cpu(), want): + bad_replays.append(f"replay {rep} from rank {peer}") + report("10 CUDA graph replays with mutated inputs are bit-exact", not bad_replays, "; ".join(bad_replays[:4])) + + ok, detail = run_eager(700) + report("eager grouped exchange after CUDA graph replays", ok, detail) + + barrier = torch.full((16,), float(rank + 1), dtype=torch.float32, device="cuda") + torch.cuda.synchronize() + bcode = lib.ncclAllReduce(ctypes.c_void_p(barrier.data_ptr()), ctypes.c_void_p(barrier.data_ptr()), + barrier.numel(), F32, 0, comm, handle) + stream.synchronize() + report("all-reduce barrier after graph replays", bcode == 0, last_error() if bcode else "") + + receipt = receipt_of(lib, comm) + captured = receipt["all_reduce"]["captured_calls"] + report("receipt records captured P2P channel calls and healthy state", + captured >= len(graph_calls) and receipt["healthy"], + f"captured_calls={captured}, healthy={receipt['healthy']}, error={receipt.get('error')}") + report("ncclCommDestroy", lib.ncclCommDestroy(comm) == 0, last_error()) + save() + return 0 if all(ok for _, ok, _ in checks) else 1 + + if args.case == "ep": + num_experts = world * 8 + local_e = num_experts // world + top_k = 4 + hidden_dim = 256 + + def make_ep_inputs(seed, n_tok, td, all_local=False): + g = np.random.default_rng(seed) + if n_tok == 0: + h = torch.empty((0, hidden_dim), dtype=td, device="cuda") + ids = torch.empty((0, top_k), dtype=torch.int32, device="cuda") + wts = torch.empty((0, top_k), dtype=torch.float32, device="cuda") + return h, ids, wts + h_np = g.normal(0.0, 1.0, (n_tok, hidden_dim)).astype(np.float32) + h = torch.from_numpy(h_np).to(dtype=td, device="cuda").contiguous() + if all_local: + lo = rank * local_e + ids_np = np.stack([g.choice(local_e, size=top_k, replace=False) + lo for _ in range(n_tok)]).astype( + np.int32 + ) + else: + ids_np = np.stack([g.choice(num_experts, size=top_k, replace=False) for _ in range(n_tok)]).astype( + np.int32 + ) + wts_np = g.uniform(0.1, 1.0, (n_tok, top_k)).astype(np.float32) + wts_np /= wts_np.sum(axis=1, keepdims=True) + return h, torch.from_numpy(ids_np).cuda().contiguous(), torch.from_numpy(wts_np).cuda().contiguous() + + def ref_combine(h_in, ids_in, wts_in, td): + n_tok = h_in.shape[0] + if n_tok == 0: + return torch.empty((0, hidden_dim), dtype=td, device="cuda") + acc = torch.zeros((n_tok, hidden_dim), dtype=torch.float32, device="cuda") + h_f = h_in.float() + for dst in range(world): + lo, hi = dst * local_e, (dst + 1) * local_e + mask = (ids_in >= lo) & (ids_in < hi) + active = mask.any(dim=1) + if active.any(): + scale = (wts_in * mask.to(torch.float32)).sum(dim=1, keepdim=True) * (1.0 + 0.25 * dst) + contrib = (h_f * scale).to(td).float() + acc += torch.where(active.unsqueeze(1), contrib, torch.zeros_like(contrib)) + return acc.to(td) + + def run_expert(h_out, ids_out, wts_out, td): + lo, hi = rank * local_e, (rank + 1) * local_e + mask = (ids_out >= lo) & (ids_out < hi) + scale = (wts_out * mask.to(torch.float32)).sum(dim=1, keepdim=True) * (1.0 + 0.25 * rank) + return (h_out.float() * scale).to(td).contiguous() + + # 1. Asymmetric eager rounds across BF16, FP16, FP32 + all-local round. + eager_specs = [ + (BF16, torch.bfloat16, "bf16-asym", [0, 3, 7, 1], False), + (F16, torch.float16, "fp16-asym", [5, 0, 2, 6], False), + (F32, torch.float32, "fp32-asym", [4, 2, 1, 3], False), + (BF16, torch.bfloat16, "bf16-all-local", [4, 4, 4, 4], True), + ] + for idx, (nccl_dt, td, label, counts, all_local) in enumerate(eager_specs): + n_tok = counts[rank % len(counts)] + max_tok = max(counts) + hidden_bytes = hidden_dim * torch.empty((), dtype=td).element_size() + ws_bytes = int(lib.sirclEpWorkspaceBytes(world, max_tok, hidden_bytes)) + ws = torch.empty(ws_bytes, dtype=torch.uint8, device="cuda") + h_in, ids_in, wts_in = make_ep_inputs(2000 + idx * 100 + rank, n_tok, td, all_local=all_local) + total_rows = world * max_tok + h_out = torch.empty((total_rows, hidden_dim), dtype=td, device="cuda") + ids_out = torch.empty((total_rows, top_k), dtype=torch.int32, device="cuda") + wts_out = torch.empty((total_rows, top_k), dtype=torch.float32, device="cuda") + recv_counts = torch.full((world,), -1, dtype=torch.int32, device="cuda") + comb_out = torch.empty((n_tok, hidden_dim), dtype=td, device="cuda") + torch.cuda.synchronize() + c1 = lib.sirclEpDispatch( + ctypes.c_void_p(h_in.data_ptr() if n_tok else 0), + ctypes.c_void_p(ids_in.data_ptr() if n_tok else 0), + ctypes.c_void_p(wts_in.data_ptr() if n_tok else 0), + ctypes.c_void_p(h_out.data_ptr()), + ctypes.c_void_p(ids_out.data_ptr()), + ctypes.c_void_p(wts_out.data_ptr()), + ctypes.c_void_p(recv_counts.data_ptr()), + ctypes.c_void_p(ws.data_ptr()), + ws_bytes, n_tok, max_tok, hidden_bytes, top_k, num_experts, comm, handle, + ) + with torch.cuda.stream(stream): + expert_out = run_expert(h_out, ids_out, wts_out, td) + c2 = lib.sirclEpCombine( + ctypes.c_void_p(expert_out.data_ptr()), + ctypes.c_void_p(comb_out.data_ptr() if n_tok else 0), + ctypes.c_void_p(ws.data_ptr()), + ws_bytes, n_tok, max_tok, hidden_dim, nccl_dt, comm, handle, + ) + stream.synchronize() + want = ref_combine(h_in, ids_in, wts_in, td) + rc_list = recv_counts.cpu().tolist() + local_ok = (not all_local) or all(rc_list[s] == (n_tok if s == rank else 0) for s in range(world)) + exact = (c1 == 0 and c2 == 0 and local_ok and torch.equal(comb_out, want)) + report(f"SIRCL-EP eager {label}", exact, + f"codes=({c1},{c2}) recv_counts={rc_list}; {last_error() if (c1 or c2) else ''}") + + # 2. CUDA graph capture of dispatch -> expert -> combine, 8 dynamic-routing replays including all-local toggle. + g_tok = 8 + g_td, g_dt = torch.bfloat16, BF16 + g_hbytes = hidden_dim * 2 + g_ws_bytes = int(lib.sirclEpWorkspaceBytes(world, g_tok, g_hbytes)) + g_ws = torch.empty(g_ws_bytes, dtype=torch.uint8, device="cuda") + g_hin = torch.zeros((g_tok, hidden_dim), dtype=g_td, device="cuda") + g_ids = torch.zeros((g_tok, top_k), dtype=torch.int32, device="cuda") + g_wts = torch.full((g_tok, top_k), 1.0 / top_k, dtype=torch.float32, device="cuda") + g_hout = torch.empty((world * g_tok, hidden_dim), dtype=g_td, device="cuda") + g_idsout = torch.empty((world * g_tok, top_k), dtype=torch.int32, device="cuda") + g_wtsout = torch.empty((world * g_tok, top_k), dtype=torch.float32, device="cuda") + g_rc = torch.empty((world,), dtype=torch.int32, device="cuda") + g_comb = torch.empty((g_tok, hidden_dim), dtype=g_td, device="cuda") + + torch.cuda.synchronize() + ep_graph = torch.cuda.CUDAGraph() + with torch.cuda.graph(ep_graph, stream=stream): + gc1 = lib.sirclEpDispatch( + ctypes.c_void_p(g_hin.data_ptr()), ctypes.c_void_p(g_ids.data_ptr()), + ctypes.c_void_p(g_wts.data_ptr()), ctypes.c_void_p(g_hout.data_ptr()), + ctypes.c_void_p(g_idsout.data_ptr()), ctypes.c_void_p(g_wtsout.data_ptr()), + ctypes.c_void_p(g_rc.data_ptr()), ctypes.c_void_p(g_ws.data_ptr()), + g_ws_bytes, g_tok, g_tok, g_hbytes, top_k, num_experts, comm, handle, + ) + g_exp = run_expert(g_hout, g_idsout, g_wtsout, g_td) + gc2 = lib.sirclEpCombine( + ctypes.c_void_p(g_exp.data_ptr()), ctypes.c_void_p(g_comb.data_ptr()), + ctypes.c_void_p(g_ws.data_ptr()), g_ws_bytes, g_tok, g_tok, hidden_dim, g_dt, comm, handle, + ) + stream.synchronize() + report("SIRCL-EP dispatch + expert + combine captures into a CUDA graph", gc1 == 0 and gc2 == 0, + f"codes=({gc1},{gc2}); {last_error() if (gc1 or gc2) else ''}") + + bad_ep = [] + for rep in range(8): + all_local = rep in (2, 5) + h_s, ids_s, wts_s = make_ep_inputs(4000 + rep * 100 + rank, g_tok, g_td, all_local=all_local) + g_hin.copy_(h_s) + g_ids.copy_(ids_s) + g_wts.copy_(wts_s) + g_comb.zero_() + torch.cuda.synchronize() + with torch.cuda.stream(stream): + ep_graph.replay() + stream.synchronize() + want = ref_combine(g_hin, g_ids, g_wts, g_td) + rc_list = g_rc.cpu().tolist() + if all_local and any(rc_list[s] != (g_tok if s == rank else 0) for s in range(world)): + bad_ep.append(f"replay {rep} all-local recv_counts={rc_list}") + elif not torch.equal(g_comb, want): + bad_ep.append(f"replay {rep} mismatch") + report("8 SIRCL-EP CUDA graph replays with dynamic routing (including all-local toggle) are bit-exact", + not bad_ep, "; ".join(bad_ep[:4])) + + barrier = torch.full((16,), float(rank + 1), dtype=torch.float32, device="cuda") + torch.cuda.synchronize() + bcode = lib.ncclAllReduce(ctypes.c_void_p(barrier.data_ptr()), ctypes.c_void_p(barrier.data_ptr()), + barrier.numel(), F32, 0, comm, handle) + stream.synchronize() + report("all-reduce barrier after SIRCL-EP", bcode == 0, last_error() if bcode else "") + + receipt = receipt_of(lib, comm) + ep_rec = receipt["channels"]["ep"] + captured = receipt["all_reduce"]["captured_calls"] + report("receipt records SIRCL-EP dispatches, combines, captured calls and healthy state", + ep_rec["dispatches"] >= 5 and ep_rec["combines"] >= 5 and captured >= 2 and receipt["healthy"], + json.dumps({"ep": ep_rec, "captured_calls": captured, "healthy": receipt["healthy"]})) + report("ncclCommDestroy", lib.ncclCommDestroy(comm) == 0, last_error()) + save() + return 0 if all(ok for _, ok, _ in checks) else 1 + # 1. Every ordered pair with a channel at once. for round_ in range(args.rounds): def size(src, dst): @@ -519,7 +796,8 @@ def main(argv=None) -> int: parser.add_argument("--world", type=int, default=4) parser.add_argument("--lanes", type=int, default=2) parser.add_argument("--layout", choices=("none", "ring8", "ring8-alone", "path4"), default="none") - parser.add_argument("--case", choices=("traffic", "size", "gone", "abort", "setup"), default="traffic") + parser.add_argument("--case", choices=("traffic", "size", "gone", "abort", "setup", "graph", "ep"), + default="traffic") parser.add_argument("--rounds", type=int, default=3) parser.add_argument("--timeout", type=float, default=1200) parser.add_argument("--env", action="append", default=[], metavar="NAME=VALUE", diff --git a/spark_transport/libsircl/tests/emulation/shm_verbs_probe.c b/spark_transport/libsircl/tests/emulation/shm_verbs_probe.c index fd8046d6..b02e46e0 100644 --- a/spark_transport/libsircl/tests/emulation/shm_verbs_probe.c +++ b/spark_transport/libsircl/tests/emulation/shm_verbs_probe.c @@ -30,6 +30,7 @@ int sccl_emu_roce_lane_check(void *, int); int sccl_emu_roce_start(void *); int sccl_emu_roce_failed(void *); const char *sccl_emu_roce_error(void *); +uint64_t sccl_emu_roce_stat(void *, int); void sccl_emu_roce_destroy(void *); static void fail(const char *what, const char *detail) { @@ -68,6 +69,7 @@ int main(int argc, char **argv) { const char *mode = argc == 7 ? argv[6] : "mesh"; int ring_only = !strcmp(mode, "ring-only"); int asymmetric = !strcmp(mode, "asymmetric"); + int abort_mode = !strcmp(mode, "abort"); char err[512] = {0}; if (sccl_emu_attach(err, sizeof err)) fail("attach", err); /* SIRCL change LF + sparse neighbor-only peers: bits 0, 1 and 2. */ @@ -139,6 +141,31 @@ int main(int argc, char **argv) { if (sccl_emu_roce_lane_check(proxy, 20000)) fail("lane check", sccl_emu_roce_error(proxy)); if (sccl_emu_roce_start(proxy)) fail("start", sccl_emu_roce_error(proxy)); volatile uint32_t *ctrl = (volatile uint32_t *)(arena + layout[3]); + if (abort_mode) { + /* Rank 1 triggers a local fatal protocol error (oversized op word); every peer must receive + * the ROCE_WR_ABORT notice in word 30 and stop immediately naming rank 1. */ + if (rank == 1) { + ctrl[1] = (uint32_t)(slot + 16); + ctrl[4 + 1] = (uint32_t)(slot + 16); + __atomic_thread_fence(__ATOMIC_SEQ_CST); + __atomic_store_n((uint32_t *)&ctrl[0], 1u, __ATOMIC_RELEASE); + } + time_t start = time(NULL); + while (!sccl_emu_roce_failed(proxy)) { + if (time(NULL) - start > 10) fail("expected peer abort propagation", NULL); + usleep(1000); + } + uint64_t abort_from = sccl_emu_roce_stat(proxy, 30); + printf("rank %d: failed=1 abort_from=%llu err=%s\n", rank, (unsigned long long)abort_from, + sccl_emu_roce_error(proxy)); + int done = 1, dones[64]; + barrier_file(dir, "done", world, rank, &done, sizeof done, dones); + sccl_emu_roce_destroy(proxy); + sccl_emu_segment_free(arena); + free(blob); + free(blobs); + return 0; + } if (ring_only) { /* Triggering an arena one-shot op on a sparse ring-only proxy must fail cleanly via post_lane_write. */ ctrl[1] = 16; diff --git a/spark_transport/libsircl/tests/fake_cuda.c b/spark_transport/libsircl/tests/fake_cuda.c index 5159d84f..b6e4b1d8 100644 --- a/spark_transport/libsircl/tests/fake_cuda.c +++ b/spark_transport/libsircl/tests/fake_cuda.c @@ -211,10 +211,45 @@ EXPORT int cuModuleUnload(void *module) { #define UNUSED_ENTRY(name) \ EXPORT int name(void) { return 0; } EXPORT int cuCtxGetDevice(int *device) { *device = 0; return 0; } -static int context_syncs; +static int context_syncs, coop_launches, capture_active; EXPORT int cuCtxSynchronize(void) { ++context_syncs; return 0; } EXPORT int sccl_fake_cuda_context_syncs(void) { return context_syncs; } -UNUSED_ENTRY(cuDeviceGetAttribute) +EXPORT int sccl_fake_cuda_coop_launches(void) { return coop_launches; } +EXPORT void sccl_fake_cuda_set_capture(int on) { capture_active = on; } +EXPORT int cuDeviceGetAttribute(int *pi, int attrib, int dev) { + (void)dev; + if (!pi) return 1; + if (attrib == 16 /* MULTIPROCESSOR_COUNT */) { + const char *v = getenv("FAKE_CUDA_SM_COUNT"); + *pi = v ? atoi(v) : 48; + } else if (attrib == 95 /* COOPERATIVE_LAUNCH */) { + const char *v = getenv("FAKE_CUDA_COOPERATIVE_LAUNCH"); + *pi = v ? atoi(v) : 1; + } + return 0; +} +EXPORT int cuOccupancyMaxActiveBlocksPerMultiprocessor(int *numBlocks, void *func, int blockSize, + size_t dynamicSMemSize) { + (void)func; (void)blockSize; (void)dynamicSMemSize; + if (!numBlocks) return 1; + const char *v = getenv("FAKE_CUDA_MAX_ACTIVE_BLOCKS"); + *numBlocks = v ? atoi(v) : 2; + return 0; +} +EXPORT int cuLaunchCooperativeKernel(void *f, unsigned gx, unsigned gy, unsigned gz, unsigned bx, unsigned by, + unsigned bz, unsigned smem, void *stream, void **params) { + (void)f; (void)gx; (void)gy; (void)gz; (void)bx; (void)by; (void)bz; (void)smem; (void)stream; (void)params; + ++coop_launches; + return 0; +} +EXPORT int cuStreamGetCaptureInfo(void *stream, int *status, unsigned long long *id) { + (void)stream; + const char *env = getenv("FAKE_CUDA_CAPTURE"); + int active = capture_active || (env && !strcmp(env, "1")); + if (status) *status = active ? 1 : 0; + if (id) *id = active ? 42ull : 0ull; + return 0; +} UNUSED_ENTRY(cuLaunchKernel) UNUSED_ENTRY(cuMemAlloc_v2) UNUSED_ENTRY(cuMemFree_v2) @@ -228,7 +263,6 @@ UNUSED_ENTRY(cuMemFreeHost) UNUSED_ENTRY(cuMemHostGetDevicePointer_v2) UNUSED_ENTRY(cuMemHostRegister_v2) UNUSED_ENTRY(cuMemHostUnregister) -UNUSED_ENTRY(cuStreamGetCaptureInfo) UNUSED_ENTRY(cuStreamCreate) UNUSED_ENTRY(cuStreamDestroy_v2) UNUSED_ENTRY(cuStreamSynchronize) diff --git a/spark_transport/libsircl/tests/test_abi.py b/spark_transport/libsircl/tests/test_abi.py index c9ad1578..e2e5a126 100644 --- a/spark_transport/libsircl/tests/test_abi.py +++ b/spark_transport/libsircl/tests/test_abi.py @@ -63,9 +63,10 @@ def test_exported_symbol_set(self): expected |= {"p" + name for name in expected} self.assertEqual({name for name in exported if name.startswith(("nccl", "pnccl"))}, expected) self.assertFalse({name for name in exported if name.startswith("sccl_")}, "Internal helpers must be hidden") - # Beyond the NCCL API, exactly the three extension functions, by name (no sircl_fabric_* helpers). + # Beyond the NCCL API, the libsircl extension functions, by name (no sircl_fabric_* helpers). self.assertEqual({name for name in exported if not name.startswith(("nccl", "pnccl"))}, - {"sirclGetInfo", "sirclSetWaitRegime", "sirclGetReceipt"}) + {"sirclGetInfo", "sirclSetWaitRegime", "sirclGetReceipt", + "sirclEpWorkspaceBytes", "sirclEpDispatch", "sirclEpCombine"}) def test_soname_and_runtime_dependencies(self): dynamic = run("readelf", "-d", str(LIBRARY)) diff --git a/spark_transport/libsircl/tests/test_fabric.c b/spark_transport/libsircl/tests/test_fabric.c deleted file mode 100644 index e3cc2242..00000000 --- a/spark_transport/libsircl/tests/test_fabric.c +++ /dev/null @@ -1,268 +0,0 @@ -#include "sircl_fabric.h" -#include -#include -#include -#include -#include "data/reference_vectors.h" - -#define LENGTH(a) (sizeof(a) / sizeof((a)[0])) -static unsigned checks; -static const char *case_name; -#define CHECK(expr) do { checks++; if (!(expr)) { \ - fprintf(stderr, "%s:%d: %s: %s\n", __FILE__, __LINE__, case_name ? case_name : "test", #expr); \ - exit(1); } } while (0) -static sircl_fabric_routes group; -static sircl_fabric_error error; - -static void load(const char *text, int lanes) { - sircl_fabric_layout layout; - case_name = text; - CHECK(sircl_fabric_layout_parse(text, &layout, &error) == 0); - CHECK(sircl_fabric_derive(&layout, lanes, &group, &error) == 0); -} - -static void reference_routes(void) { - size_t i; - for (i = 0; i < LENGTH(route_layouts); i++) { - const layout_vector *v = &route_layouts[i]; - sircl_fabric_layout layout; - sircl_route_map maps[16]; - int rank, j; - case_name = v->name; - CHECK(sircl_fabric_layout_init(&layout, v->cables, v->cable_count, v->positions, v->world, &error) == 0); - CHECK(sircl_fabric_derive(&layout, v->lanes, &group, &error) == 0); - for (rank = 0; rank < v->world; rank++) { - sircl_route_map parsed; - char text[512]; - CHECK(sircl_fabric_map(&group, rank, &maps[rank], &error) == 0); - CHECK(sircl_fabric_map_format(&maps[rank], v->world, text, sizeof text, &error) == 0); - CHECK(strcmp(text, v->texts[rank]) == 0); - CHECK(sircl_fabric_map_parse(v->texts[rank], &parsed, &error) == 0); - CHECK(memcmp(&parsed, &maps[rank], sizeof parsed) == 0); - CHECK(sircl_fabric_map_validate(&layout, &parsed, rank, v->world, 16, &error) == 0); - } - CHECK(sircl_fabric_complementary(&layout, maps, &error) == 0); - for (j = 0; j < v->count; j++) { - const lane_vector *expected = &route_lanes[v->start + j]; - const sircl_lane_route *actual = &group.route[expected->rank][expected->peer][expected->lane]; - int k; - CHECK(actual->hops == expected->hops); - CHECK(actual->local_role == expected->local_role); - CHECK(actual->remote_role == expected->remote_role); - for (k = 0; k < expected->hops; k++) { - CHECK(actual->steps[k].src == expected->steps[k].src); - CHECK(actual->steps[k].src_port == expected->steps[k].src_port); - CHECK(actual->steps[k].dst == expected->steps[k].dst); - CHECK(actual->steps[k].dst_port == expected->steps[k].dst_port); - } - } - if (!strcmp(v->name, "ring-of-8-tp6-0-5")) { - CHECK(sircl_fabric_map_validate(&layout, &maps[0], 0, v->world, 3, &error) == -1); - CHECK(error.code == SIRCL_FABRIC_LIMIT); - } - } -} - -static void reference_numeric(void) { - size_t i; - case_name = "numeric reference vectors"; - for (i = 0; i < LENGTH(numeric_ranges); i++) { - const range_vector *v = &numeric_ranges[i]; sircl_pack_range actual; - CHECK((v->kind == 0 ? sircl_protocol_stripe(v->packs, v->parts, v->index, &actual) : - sircl_protocol_chunk(v->packs, v->parts, v->index, &actual)) == 0); - CHECK(actual.first == v->first && actual.count == v->count); - } - for (i = 0; i < LENGTH(numeric_flags); i++) { - const flag_vector *v = &numeric_flags[i]; uint32_t word; - CHECK(sircl_protocol_flag_index(v->ns, v->source, v->slot, v->lane, v->world, v->lanes, &word) == 0); - CHECK(word == v->expected); - } - for (i = 0; i < LENGTH(numeric_ops); i++) { - uint32_t word; CHECK(sircl_protocol_op_word(numeric_ops[i].op, numeric_ops[i].bytes, &word) == 0); - CHECK(word == numeric_ops[i].expected); - } - for (i = 0; i < LENGTH(numeric_descriptors); i++) { - uint32_t word; CHECK(sircl_protocol_descriptor(&numeric_descriptors[i].phase, 0, &word) == 0); - CHECK(word == numeric_descriptors[i].expected); - } - for (i = 0; i < LENGTH(numeric_posting); i++) { - const post_vector *v = &numeric_posting[i]; int peers[16], j; char layout[32]; - snprintf(layout, sizeof layout, "ring:%d", v->world); load(layout, 2); - CHECK(sircl_fabric_post_order(&group, v->rank, "ring-farthest", peers, &error) == 0); - for (j = 0; j < v->world - 1; j++) CHECK(peers[j] == v->peers[j]); - CHECK(sircl_fabric_post_order(&group, v->rank, "farthest", peers, &error) == 0); - for (j = 0; j < v->world - 1; j++) CHECK(peers[j] == v->peers[j]); - } - for (i = 0; i < LENGTH(numeric_owners); i++) { - const owner_vector *v = &numeric_owners[i]; int owners[16], count, j; sircl_phase phases[8]; - CHECK(sircl_protocol_swing(v->world, 0, owners, phases, &count) == 0); - CHECK(count == v->phase_count); - for (j = 0; j < v->world; j++) CHECK(owners[j] == v->owners[j]); - } - for (i = 0; i < LENGTH(numeric_phases); i++) { - const phase_vector *v = &numeric_phases[i]; int owners[16], count; sircl_phase phases[8], *p; - CHECK(sircl_protocol_swing(v->world, v->rank, owners, phases, &count) == 0); - CHECK(count > v->phase_index); p = &phases[v->phase_index]; - CHECK(p->first == v->phase.first && p->end == v->phase.end && p->peer == v->phase.peer && p->namespace_id == v->phase.namespace_id); - } - for (i = 0; i < LENGTH(numeric_selection); i++) { - const selection_vector *v = &numeric_selection[i]; int algorithm; - unsigned available = (v->world & (v->world - 1)) ? 3u : 7u; - CHECK(sircl_protocol_select(v->bytes, -1, 1, 28672, v->swing_above, available, &algorithm) == 0); - CHECK(algorithm == v->algorithm); - } -} - -static void posting_and_windows(void) { - uint64_t windows[16][2], ring_window; - int peers[16], order[16], busiest, rank, peer, lane; - double factor; - const int path_orders[4][3] = {{3,2,1}, {3,2,0}, {0,3,1}, {0,1,2}}; - load("path:0-3", 2); - for (rank = 0; rank < 4; rank++) { - CHECK(sircl_fabric_post_order(&group, rank, "farthest", peers, &error) == 0); - CHECK(memcmp(peers, path_orders[rank], sizeof path_orders[rank]) == 0); - } - CHECK(sircl_fabric_relay_load(&group, &busiest, &factor, &error) == 0); - CHECK(busiest == 2 && factor == 1); - CHECK(sircl_fabric_forward_windows(&group, 0, 131072, 32768, 524288, windows, &error) == 0); - CHECK(windows[0][0] == 0 && windows[1][0] == 0 && windows[2][0] == 131072 && windows[3][1] == 131072); - CHECK(sircl_fabric_chain_order(&group, order, &error) == 0); - for (rank = 0; rank < 4; rank++) CHECK(order[rank] == rank); - CHECK(sircl_fabric_ring_window(&group, order, 32768, 524288, &ring_window, &error) == 0); - CHECK(ring_window == 393216); - CHECK(sircl_fabric_ring_window(&group, order, 32768, 1, &ring_window, &error) == -1); - /* Deliberately model duplicate ring lanes on one function; its queue is overloaded. */ - group.route[3][0][1] = group.route[3][0][0]; - CHECK(sircl_fabric_ring_window(&group, order, 32768, 524288, &ring_window, &error) == -1); - CHECK(error.code == SIRCL_FABRIC_LIMIT); - load("ring:8", 2); - CHECK(sircl_fabric_relay_load(&group, &busiest, &factor, &error) == 0); - CHECK(busiest == 6 && factor == 3); - CHECK(sircl_fabric_forward_windows(&group, 0, 131072, 32768, 524288, windows, &error) == 0); - CHECK(windows[1][0] == 0 && windows[7][1] == 0 && windows[4][0] == 65536 && windows[4][1] == 65536); - CHECK(sircl_fabric_forward_windows(&group, 0, 0, 0, 0, windows, &error) == 0); - for (peer = 0; peer < 8; peer++) for (lane = 0; lane < 2; lane++) CHECK(windows[peer][lane] == 0); - CHECK(sircl_fabric_forward_windows(&group, 0, 131072, 1000, 524288, windows, &error) == -1); - CHECK(sircl_fabric_forward_windows(&group, 0, 131072, 32768, 16, windows, &error) == -1); - CHECK(sircl_fabric_chain_order(&group, order, &error) == 0); - CHECK(sircl_fabric_ring_window(&group, order, 32768, 524288, &ring_window, &error) == 0 && ring_window == 0); - load("ring:8:0,2,4,6", 2); - CHECK(sircl_fabric_chain_order(&group, order, &error) == -1); - CHECK(sircl_fabric_post_order(&group, 0, "farthest", peers, &error) == 0); - CHECK(peers[0] == 2 && peers[1] == 1 && peers[2] == 3); - load("cables=0.port0-1.port1,1.port0-2.port1;positions=2,1,0", 2); - CHECK(sircl_fabric_chain_order(&group, order, &error) == 0); - CHECK(order[0] == 2 && order[1] == 1 && order[2] == 0); -} - -static void agreement_and_invalid(void) { - sircl_fabric_rank_record records[16]; - sircl_route_map maps[16], map; - sircl_fabric_layout l; - uint32_t shared[3] = {1, 131072, 512}, different[3] = {1, 131072, 256}; - int i, peers[16]; char text[8]; - static const char *bad_layouts[] = {"", "star:4", "ring:x", "ring:1", "ring:17", "path:3-0", "path:0-3:0,0,1,2", "cables=0.port0-1.port0", "cables=0.port01-1.port0;positions=0,1", "ring:4:0,9", "ring:4:", "ring:4:0,1,", "ring:2147483648"}; - static const char *bad_maps[] = {"", "1", "x=rocep1s0f0", "1=rocep1s0f0,,2=rocep1s0f1", "1=rocep1s0f0,", "1=", "16=rocep1s0f0", "1=rocep1s0f0/rocep1s0f1/roceP2p1s0f0", "1=mlx5_9", "1=rocep1s0f0,1=rocep1s0f1"}; - case_name = "invalid inputs"; - for (i = 0; i < (int)LENGTH(bad_layouts); i++) CHECK(sircl_fabric_layout_parse(bad_layouts[i], &l, &error) == -1); - for (i = 0; i < (int)LENGTH(bad_maps); i++) CHECK(sircl_fabric_map_parse(bad_maps[i], &map, &error) == -1); - { sircl_cable disconnected[] = {{0,0,1,1}, {2,0,3,1}}, reused[] = {{0,0,1,1}, {0,0,2,1}}; - int positions[] = {0,1}; - CHECK(sircl_fabric_layout_init(&l, disconnected, 2, positions, 2, &error) == -1); - CHECK(sircl_fabric_layout_init(&l, reused, 2, positions, 2, &error) == -1); - } - load("ring:4", 2); memset(records, 0, sizeof records); - for (i = 0; i < 4; i++) { - CHECK(sircl_fabric_map(&group, i, &maps[i], &error) == 0); - records[i].map = maps[i]; records[i].shared_settings = shared; records[i].shared_size = sizeof shared; - } - CHECK(sircl_fabric_agree(&group.layout, 4, 2, records, 3, &error) == 0); - CHECK(sircl_fabric_agree(NULL, 4, 2, records, 3, &error) == 0); - records[2].shared_settings = different; - CHECK(sircl_fabric_agree(&group.layout, 4, 2, records, 3, &error) == -1); - CHECK(strstr(error.message, "rank 2 shared settings")); - records[2].shared_settings = shared; records[1].local_error = "inactive RDMA device"; - CHECK(sircl_fabric_agree(&group.layout, 4, 2, records, 3, &error) == -1); - CHECK(strstr(error.message, "rank 1: inactive")); records[1].local_error = NULL; - records[0].map.count[2] = 1; - CHECK(sircl_fabric_agree(&group.layout, 4, 2, records, 3, &error) == -1); - records[0].map = maps[0]; records[2].map.role[0][0] = SIRCL_CW_PRIMARY; - CHECK(sircl_fabric_agree(&group.layout, 4, 2, records, 3, &error) == -1); - CHECK(strstr(error.message, "arrives on rank")); - map = maps[0]; map.count[2] = 0; - CHECK(sircl_fabric_map_validate(&group.layout, &map, 0, 4, 3, &error) == -1); - map = maps[0]; map.count[0] = 1; - CHECK(sircl_fabric_map_validate(&group.layout, &map, 0, 4, 3, &error) == -1); - map = maps[0]; map.role[1][1] = map.role[1][0]; - CHECK(sircl_fabric_map_validate(&group.layout, &map, 0, 4, 3, &error) == -1); - CHECK(sircl_fabric_map_format(&maps[0], 4, text, sizeof text, &error) == -1); - CHECK(sircl_fabric_map_parse(" 1 = rocep1s0f0 / roceP2p1s0f0 , 2=rocep1s0f1 ", &map, &error) == 0); - CHECK(map.count[1] == 2 && map.count[2] == 1 && map.role[2][0] == SIRCL_CCW_PRIMARY); - CHECK(sircl_fabric_post_order(&group, 1, " 3,0,2 ", peers, &error) == 0 && peers[0] == 3 && peers[1] == 0 && peers[2] == 2); - CHECK(sircl_fabric_post_order(&group, 1, NULL, peers, &error) == 0 && peers[0] == 0 && peers[1] == 2 && peers[2] == 3); - CHECK(sircl_fabric_post_order(&group, 1, "0,2", peers, &error) == -1); - CHECK(sircl_fabric_post_order(&group, 1, "0,2,2", peers, &error) == -1); - CHECK(sircl_fabric_post_order(&group, 1, "0,2,3,", peers, &error) == -1); - CHECK(sircl_fabric_post_order(&group, 1, "nearest", peers, &error) == -1); - load("path:0-3", 2); CHECK(sircl_fabric_map(&group, 0, &map, &error) == 0); - map.role[3][0] = SIRCL_CCW_PRIMARY; - CHECK(sircl_fabric_map_validate(&group.layout, &map, 0, 4, 16, &error) == -1); - group.route[0][1][0].local_role = 255; - CHECK(sircl_fabric_post_order(&group, 0, "farthest", peers, &error) == -1); - load("path:0-3", 2); group.layout.nodes[0] = -1; - CHECK(sircl_fabric_chain_order(&group, peers, &error) == -1); - load("path:0-3", 2); group.route[0][1][0].steps[0].dst_port = 9; - CHECK(sircl_fabric_post_order(&group, 0, "rank", peers, &error) == -1); -} - -static void numeric_limits(void) { - uint32_t word; - sircl_pack_range range; - sircl_phase phases[8], p = {0, 4, 1, 0}; - int owners[16], count, world, rank, i, algorithm; - case_name = "numeric bounds and conservation"; - CHECK(sircl_protocol_stripe(1, 0, 0, &range) == -1); - CHECK(sircl_protocol_stripe(1, 2, 2, &range) == -1); - CHECK(sircl_protocol_chunk(1, 1, 0, &range) == -1); - CHECK(sircl_protocol_chunk(1, 4, 4, &range) == -1); - CHECK(sircl_protocol_flag_index(2, 0, 0, 0, 4, 2, &word) == -1); - CHECK(sircl_protocol_flag_index(0, 4, 0, 0, 4, 2, &word) == -1); - CHECK(sircl_protocol_op_word(4, 16, &word) == -1); - CHECK(sircl_protocol_op_word(0, 0, &word) == -1); - CHECK(sircl_protocol_op_word(0, 15, &word) == -1); - CHECK(sircl_protocol_op_word(0, UINT32_C(0x40000000), &word) == -1); - CHECK(sircl_protocol_descriptor(&p, 2, &word) == -1); - p.end = 32; CHECK(sircl_protocol_descriptor(&p, 0, &word) == -1); - CHECK(sircl_protocol_swing(3, 0, owners, phases, &count) == -1); - for (world = 2; world <= 16; world++) { - uint64_t next = 0; - for (i = 0; i < world; i++) { - CHECK(sircl_protocol_chunk(UINT64_MAX, world, i, &range) == 0); - CHECK(range.first == next); next += range.count; - } - CHECK(next == UINT64_MAX); - if (world & (world - 1)) continue; - for (rank = 0; rank < world; rank++) { - unsigned mask = 0; - CHECK(sircl_protocol_swing(world, rank, owners, phases, &count) == 0); - for (i = 0; i < world; i++) { CHECK(owners[i] >= 0 && owners[i] < world); CHECK(!(mask & (1u << owners[i]))); mask |= 1u << owners[i]; } - CHECK(mask == (1u << world) - 1); - for (i = 0; i < count; i++) { - sircl_phase other[8]; int other_owners[16], other_count; - CHECK(sircl_protocol_descriptor(&phases[i], world, &word) == 0); - CHECK(sircl_protocol_swing(world, phases[i].peer, other_owners, other, &other_count) == 0); - CHECK(other_count == count && other[i].peer == rank && other[i].namespace_id == phases[i].namespace_id); - } - } - } - CHECK(sircl_protocol_select(1 << 20, -1, 1, 28672, 0, 1u, &algorithm) == 0 && algorithm == 0); - CHECK(sircl_protocol_select(16, 2, 1, 28672, 0, 1u, &algorithm) == 0 && algorithm == 2); - CHECK(sircl_protocol_select(16, 9, 1, 28672, 0, 7u, &algorithm) == -1); -} - -int main(void) { - reference_routes(); reference_numeric(); posting_and_windows(); agreement_and_invalid(); numeric_limits(); - printf("fabric: %zu supplied layouts, %zu lane routes, all numeric vectors; %u checks passed\n", LENGTH(route_layouts), LENGTH(route_lanes), checks); - return 0; -} diff --git a/spark_transport/libsircl/tests/test_kernel_entries.py b/spark_transport/libsircl/tests/test_kernel_entries.py index f069d5a5..907c54bc 100644 --- a/spark_transport/libsircl/tests/test_kernel_entries.py +++ b/spark_transport/libsircl/tests/test_kernel_entries.py @@ -38,7 +38,8 @@ def test_every_entry_the_loader_names_is_in_every_cubin(self): def test_a_missing_entry_fails_and_is_named(self): for name in ("sircl_twoshot_bf16_w8", "sircl_fold_d11_o4", "sircl_chain_f16_u3", "sircl_ring_gather_u8", - "sircl_ring_reduce_bf16_u8", "sircl_p2p_recv_u5", "sircl_p2p_send_u8"): + "sircl_ring_reduce_bf16_u8", "sircl_p2p_recv_u5", "sircl_p2p_send_u8", "sircl_ep_dispatch", + "sircl_ep_combine_reduce_bf16"): with self.subTest(name=name): result = run(hide=name) self.assertEqual(result.returncode, 1, result.stdout) diff --git a/spark_transport/libsircl/tests/test_libsircl_hardening.py b/spark_transport/libsircl/tests/test_libsircl_hardening.py new file mode 100644 index 00000000..c0d13ee6 --- /dev/null +++ b/spark_transport/libsircl/tests/test_libsircl_hardening.py @@ -0,0 +1,460 @@ +#!/usr/bin/env python3 +"""CPU hardening tests for libsircl P0 fixes (runs on Linux/WSL without nvcc or GPU). + +Builds a temporary host test shared library from the real libsircl C sources (api.c, +engine.c, bootstrap.c, cuda_api.c, transport/*) plus a minimal kernel-pack stub and +tests/fake_cuda.c, then exercises: + +1. CUDA-graph-only communicator abort quarantine (GPU UAF prevention: ever_captured). +2. ncclGroupStart/End mixed P2P + collective ordering guard (ncclInvalidUsage on + collective after queued P2P; collective before P2P still succeeds). +3. SIRCL-EP cooperative launch verification (cuLaunchCooperativeKernel used when + co-residency holds; fail-closed ncclInvalidUsage when cooperative launch is + unsupported or SM occupancy cannot co-schedule 2 * world CTAs). +4. Growable JSON receipt formatting and atomic wait-regime transitions. +""" + +from __future__ import annotations + +import os +import subprocess +import sys +import tempfile +import unittest +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] + +KP_STUB_C = r""" +#include "kernelpack.h" +#include + +static const char stub_hash[] = "0000000000000000000000000000000000000000000000000000000000000000"; +static int dummy_fn_tok; + +const char *sccl_kp_error(void) { return "no error"; } +const char *sccl_kp_hash(void) { return stub_hash; } +const char *sccl_kp_fold_hash(void) { return stub_hash; } +const char *sccl_kp_links_hash(void) { return stub_hash; } +const char *sccl_kp_p2p_hash(void) { return stub_hash; } + +int sccl_kp_load(sccl_CUcontext ctx) { (void)ctx; return 0; } +void sccl_kp_release(sccl_CUcontext ctx, int unload) { (void)ctx; (void)unload; } + +int sccl_kp_function(sccl_CUcontext ctx, int kind, int dtype, int world, sccl_CUfunction *out) { + (void)ctx; (void)kind; (void)dtype; (void)world; + *out = (sccl_CUfunction)&dummy_fn_tok; + return 0; +} +int sccl_kp_fold_function(sccl_CUcontext ctx, int datatype, int op, sccl_CUfunction *out) { + (void)ctx; (void)datatype; (void)op; + *out = (sccl_CUfunction)&dummy_fn_tok; + return 0; +} +int sccl_kp_chain_function(sccl_CUcontext ctx, int dtype, int unroll, sccl_CUfunction *out) { + (void)ctx; (void)dtype; (void)unroll; + *out = (sccl_CUfunction)&dummy_fn_tok; + return 0; +} +int sccl_kp_link_function(sccl_CUcontext ctx, int kind, int dtype, int unroll, sccl_CUfunction *out) { + (void)ctx; (void)kind; (void)dtype; (void)unroll; + *out = (sccl_CUfunction)&dummy_fn_tok; + return 0; +} +int sccl_kp_ring_reduce_two_pass_function(sccl_CUcontext ctx, int dtype, int unroll, sccl_CUfunction *out) { + (void)ctx; (void)dtype; (void)unroll; + *out = (sccl_CUfunction)&dummy_fn_tok; + return 0; +} +int sccl_kp_ring_exchange_function(sccl_CUcontext ctx, int unroll, sccl_CUfunction *out) { + (void)ctx; (void)unroll; + *out = (sccl_CUfunction)&dummy_fn_tok; + return 0; +} +int sccl_kp_ring_exchange_reduce_function(sccl_CUcontext ctx, int dtype, int unroll, sccl_CUfunction *out) { + (void)ctx; (void)dtype; (void)unroll; + *out = (sccl_CUfunction)&dummy_fn_tok; + return 0; +} +int sccl_kp_p2p_function(sccl_CUcontext ctx, int send, int unroll, sccl_CUfunction *out) { + (void)ctx; (void)send; (void)unroll; + *out = (sccl_CUfunction)&dummy_fn_tok; + return 0; +} +int sccl_kp_ep_functions(sccl_CUcontext ctx, sccl_CUfunction *dispatch, sccl_CUfunction *combine_xfer, + sccl_CUfunction reduce[SCCL_DT_COUNT]) { + (void)ctx; + *dispatch = (sccl_CUfunction)&dummy_fn_tok; + *combine_xfer = (sccl_CUfunction)&dummy_fn_tok; + for (int d = 0; d < SCCL_DT_COUNT; ++d) reduce[d] = (sccl_CUfunction)&dummy_fn_tok; + return 0; +} + +sccl_CUresult sccl_kp_launch_allreduce(sccl_CUfunction f, int alg, const sccl_allreduce_args *a, + unsigned g, unsigned t, sccl_CUstream s) { + (void)f; (void)alg; (void)a; (void)g; (void)t; (void)s; return 0; +} +sccl_CUresult sccl_kp_launch_allgather(sccl_CUfunction f, const sccl_allgather_args *a, + unsigned g, unsigned t, sccl_CUstream s) { + (void)f; (void)a; (void)g; (void)t; (void)s; return 0; +} +sccl_CUresult sccl_kp_launch_scatter(sccl_CUfunction f, const sccl_scatter_args *a, + unsigned g, unsigned t, sccl_CUstream s) { + (void)f; (void)a; (void)g; (void)t; (void)s; return 0; +} +sccl_CUresult sccl_kp_launch_fold(sccl_CUfunction f, uint64_t r, int64_t p, uint64_t o, + int64_t c, int32_t w, unsigned g, unsigned t, sccl_CUstream s) { + (void)f; (void)r; (void)p; (void)o; (void)c; (void)w; (void)g; (void)t; (void)s; return 0; +} +sccl_CUresult sccl_kp_launch_chain(sccl_CUfunction f, const sccl_chain_args *a, + unsigned g, unsigned t, sccl_CUstream s) { + (void)f; (void)a; (void)g; (void)t; (void)s; return 0; +} +sccl_CUresult sccl_kp_launch_link(sccl_CUfunction f, const sccl_link_args *a, + unsigned g, unsigned t, sccl_CUstream s) { + (void)f; (void)a; (void)g; (void)t; (void)s; return 0; +} +sccl_CUresult sccl_kp_launch_p2p(sccl_CUfunction f, const sccl_p2p_args *a, + unsigned g, unsigned t, sccl_CUstream s) { + (void)f; (void)a; (void)g; (void)t; (void)s; return 0; +} +sccl_CUresult sccl_kp_launch_ep(sccl_CUfunction f, const sccl_ep_args *a, + unsigned g, unsigned t, sccl_CUstream s) { + const sccl_cuda *cu = sccl_cuda_get(); + sccl_ep_args copy = *a; + void *params[] = {©}; + return cu->LaunchKernel(f, g, 1, 1, t, 1, 1, 0, s, params, NULL); +} +sccl_CUresult sccl_kp_launch_ep_cooperative(sccl_CUfunction f, const sccl_ep_args *a, + unsigned g, unsigned t, sccl_CUstream s) { + const sccl_cuda *cu = sccl_cuda_get(); + if (!cu || !cu->LaunchCooperativeKernel) return 801; + sccl_ep_args copy = *a; + void *params[] = {©}; + return cu->LaunchCooperativeKernel(f, g, 1, 1, t, 1, 1, 0, s, params); +} +""" + +WORKER_SCRIPT = r""" +import ctypes, json, os, sys +from pathlib import Path + +mode, world, rank, uid_file, lib_path, fake_cuda_path = sys.argv[1:] +world, rank = int(world), int(rank) + +fake_cuda = ctypes.CDLL(fake_cuda_path, mode=ctypes.RTLD_GLOBAL) +fake_cuda.sccl_fake_cuda_set_capture.argtypes = [ctypes.c_int] +fake_cuda.sccl_fake_cuda_coop_launches.restype = ctypes.c_int + +lib = ctypes.CDLL(lib_path) + +class UniqueId(ctypes.Structure): + _fields_ = [("internal", ctypes.c_ubyte * 128)] + +lib.ncclGetUniqueId.argtypes = [ctypes.POINTER(UniqueId)] +lib.ncclGetUniqueId.restype = ctypes.c_int +lib.ncclCommInitRank.argtypes = [ctypes.POINTER(ctypes.c_void_p), ctypes.c_int, UniqueId, ctypes.c_int] +lib.ncclCommInitRank.restype = ctypes.c_int +lib.ncclCommDestroy.argtypes = [ctypes.c_void_p] +lib.ncclCommDestroy.restype = ctypes.c_int +lib.ncclCommAbort.argtypes = [ctypes.c_void_p] +lib.ncclCommAbort.restype = ctypes.c_int +lib.ncclGetLastError.argtypes = [ctypes.c_void_p] +lib.ncclGetLastError.restype = ctypes.c_char_p +lib.ncclAllReduce.argtypes = [ + ctypes.c_void_p, ctypes.c_void_p, ctypes.c_size_t, ctypes.c_int, ctypes.c_int, ctypes.c_void_p, ctypes.c_void_p +] +lib.ncclAllReduce.restype = ctypes.c_int +lib.ncclSend.argtypes = [ctypes.c_void_p, ctypes.c_size_t, ctypes.c_int, ctypes.c_int, ctypes.c_void_p, ctypes.c_void_p] +lib.ncclSend.restype = ctypes.c_int +lib.ncclRecv.argtypes = [ctypes.c_void_p, ctypes.c_size_t, ctypes.c_int, ctypes.c_int, ctypes.c_void_p, ctypes.c_void_p] +lib.ncclRecv.restype = ctypes.c_int +lib.ncclGroupStart.argtypes = [] +lib.ncclGroupStart.restype = ctypes.c_int +lib.ncclGroupEnd.argtypes = [] +lib.ncclGroupEnd.restype = ctypes.c_int +lib.sirclSetWaitRegime.argtypes = [ctypes.c_void_p, ctypes.c_char_p] +lib.sirclSetWaitRegime.restype = ctypes.c_int +lib.sirclGetReceipt.argtypes = [ctypes.c_void_p, ctypes.c_char_p, ctypes.c_size_t, ctypes.POINTER(ctypes.c_size_t)] +lib.sirclGetReceipt.restype = ctypes.c_int +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, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p, + ctypes.c_void_p, ctypes.c_void_p, ctypes.c_size_t, ctypes.c_int, ctypes.c_int, ctypes.c_size_t, + ctypes.c_int, ctypes.c_int, ctypes.c_void_p, ctypes.c_void_p, +] +lib.sirclEpDispatch.restype = ctypes.c_int +lib.sirclEpCombine.argtypes = [ + ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_size_t, ctypes.c_int, ctypes.c_int, + ctypes.c_size_t, ctypes.c_int, ctypes.c_void_p, ctypes.c_void_p, +] +lib.sirclEpCombine.restype = ctypes.c_int + +uid = UniqueId() +uid_path = Path(uid_file) +if rank == 0: + rc = lib.ncclGetUniqueId(ctypes.byref(uid)) + assert rc == 0, f"GetUniqueId failed: {rc}" + tmp = uid_path.with_suffix(".tmp") + tmp.write_bytes(ctypes.string_at(ctypes.byref(uid), 128)) + tmp.replace(uid_path) +else: + import time + while not uid_path.exists(): + time.sleep(0.01) + raw_uid = uid_path.read_bytes() + assert len(raw_uid) == 128 + ctypes.memmove(ctypes.byref(uid), raw_uid, 128) + +comm = ctypes.c_void_p() +rc = lib.ncclCommInitRank(ctypes.byref(comm), world, uid, rank) +assert rc == 0, f"rank {rank} init failed: rc={rc} err={lib.ncclGetLastError(None)}" + +def read_receipt(handle): + need = ctypes.c_size_t(0) + assert lib.sirclGetReceipt(handle, None, 0, ctypes.byref(need)) == 0 + buf = ctypes.create_string_buffer(need.value) + assert lib.sirclGetReceipt(handle, buf, need.value, ctypes.byref(need)) == 0 + return json.loads(buf.value.decode("utf-8")) + +if mode == "capture_abort": + fake_cuda.sccl_fake_cuda_set_capture(1) + # Graph-only communicator: call AllReduce only while capturing (never eagerly). + rc = lib.ncclAllReduce(0x1000, 0x2000, 64, 7, 0, comm, 0x100) + assert rc == 0, f"captured AllReduce failed: {rc} {lib.ncclGetLastError(comm)}" + fake_cuda.sccl_fake_cuda_set_capture(0) + # Wait until every rank has captured before any rank triggers ncclCommAbort (which propagates + # a peer abort over the transport). + import time + (uid_path.parent / f"captured-{rank}").write_text("1") + for r in range(world): + while not (uid_path.parent / f"captured-{r}").exists(): + time.sleep(0.005) + rc = lib.ncclCommAbort(comm) + assert rc == 0, f"ncclCommAbort failed: {rc}" + # Create a single-rank communicator to inspect quarantined_bytes (triggers quarantine_reclaim too). + uid2 = UniqueId() + assert lib.ncclGetUniqueId(ctypes.byref(uid2)) == 0 + comm2 = ctypes.c_void_p() + assert lib.ncclCommInitRank(ctypes.byref(comm2), 1, uid2, 0) == 0 + receipt = read_receipt(comm2) + assert receipt["quarantined_bytes"] > 0, f"expected quarantined_bytes > 0, got {receipt}" + assert lib.ncclCommDestroy(comm2) == 0 + print(f"rank {rank}: capture_abort quarantined_bytes={receipt['quarantined_bytes']}") + +elif mode == "mixed_group": + # Order A: P2P queued first, then collective on same comm/stream -> MUST fail with ncclInvalidUsage (5). + peer = 1 - rank + assert lib.ncclGroupStart() == 0 + assert lib.ncclSend(0x1000, 16, 7, peer, comm, 0x100) == 0 + rc_coll = lib.ncclAllReduce(0x1000, 0x2000, 16, 7, 0, comm, 0x100) + err_coll = lib.ncclGetLastError(comm).decode("utf-8") + assert rc_coll == 5, f"expected ncclInvalidUsage(5), got {rc_coll} ({err_coll})" + assert "cannot launch a collective after queued ncclSend/ncclRecv" in err_coll, err_coll + rc_end = lib.ncclGroupEnd() + assert rc_end == 5, f"expected GroupEnd=5, got {rc_end}" + + # Order B: collective first, then P2P -> preserves submission order and succeeds. + assert lib.ncclGroupStart() == 0 + assert lib.ncclAllReduce(0x1000, 0x2000, 16, 7, 0, comm, 0x100) == 0 + assert lib.ncclSend(0x1000, 16, 7, peer, comm, 0x100) == 0 + assert lib.ncclRecv(0x2000, 16, 7, peer, comm, 0x100) == 0 + assert lib.ncclGroupEnd() == 0 + + # Also verify atomic wait-regime transitions + growable JSON receipt. + assert lib.sirclSetWaitRegime(comm, b"serving") == 0 + r_serving = read_receipt(comm) + assert r_serving["wait_regime"] == "serving" + assert lib.sirclSetWaitRegime(comm, b"startup") == 0 + r_startup = read_receipt(comm) + assert r_startup["wait_regime"] == "startup" + assert r_startup["healthy"] is True + + assert lib.ncclCommDestroy(comm) == 0 + print(f"rank {rank}: mixed_group ok") + +elif mode in ("ep_coop_ok", "ep_coop_disabled", "ep_coop_low_sm"): + ws_bytes = lib.sirclEpWorkspaceBytes(world, 16, 64) + assert ws_bytes > 0 + before = fake_cuda.sccl_fake_cuda_coop_launches() + rc_d = lib.sirclEpDispatch( + 0x1000, 0x2000, 0x3000, 0x4000, 0x5000, 0x6000, 0x7000, 0x8000, + ws_bytes, 4, 16, 64, 2, world * 2, comm, 0x100 + ) + err_d = lib.ncclGetLastError(comm).decode("utf-8") if rc_d else "" + rc_c = lib.sirclEpCombine( + 0x4000, 0x9000, 0x8000, ws_bytes, 4, 16, 32, 9, comm, 0x100 + ) + err_c = lib.ncclGetLastError(comm).decode("utf-8") if rc_c else "" + after = fake_cuda.sccl_fake_cuda_coop_launches() + if mode == "ep_coop_ok": + assert rc_d == 0, f"dispatch failed: {rc_d} {err_d}" + assert rc_c == 0, f"combine failed: {rc_c} {err_c}" + assert after - before == 2, f"expected 2 cooperative launches, got {after - before}" + elif mode == "ep_coop_disabled": + assert rc_d == 5 and "cooperative co-scheduling unavailable" in err_d, f"{rc_d} {err_d}" + assert rc_c == 5 and "cooperative co-scheduling unavailable" in err_c, f"{rc_c} {err_c}" + assert after == before + elif mode == "ep_coop_low_sm": + assert rc_d == 5 and "cannot guarantee co-residency" in err_d, f"{rc_d} {err_d}" + assert rc_c == 5 and "cannot guarantee co-residency" in err_c, f"{rc_c} {err_c}" + assert after == before + assert lib.ncclCommDestroy(comm) == 0 + print(f"rank {rank}: {mode} ok (coop_delta={after - before})") +""" + + +class LibsirclHardeningTests(unittest.TestCase): + @classmethod + def setUpClass(cls): + if sys.platform != "linux": + raise unittest.SkipTest("libsircl C library hardening tests run on Linux/WSL") + cls.tmp = tempfile.TemporaryDirectory(prefix="libsircl-hardening-") + tmp = Path(cls.tmp.name) + cls.fake_cuda_dir = tmp / "fake-cuda" + cls.fake_cuda_dir.mkdir() + cls.fake_cuda = cls.fake_cuda_dir / "libcuda.so.1" + cls.lib = tmp / "libsircl_test.so" + cls.worker = tmp / "worker.py" + cls.worker.write_text(WORKER_SCRIPT, encoding="utf-8") + + kp_stub = tmp / "kp_stub.c" + kp_stub.write_text(KP_STUB_C, encoding="utf-8") + + cc = os.environ.get("CC", "cc") + version = (ROOT / "VERSION").read_text(encoding="utf-8").strip() + cflags = [ + "-std=c11", "-O2", "-g", "-fPIC", "-Wall", "-Wextra", "-Werror", + "-Wno-format-truncation", "-pthread", + ] + cppflags = [ + f"-I{ROOT / 'include'}", f"-I{ROOT / 'src'}", + "-DLIBSIRCL_CPU_ONLY", "-DNCCL_OS_LINUX", + f'-DLIBSIRCL_VERSION="{version}"', "-DSCCL_P2P_LOCAL_FEATURES", + ] + + subprocess.run( + [cc, "-std=c11", "-O2", "-fPIC", "-Wall", "-Wextra", "-Werror", "-fvisibility=hidden", + "-shared", "-Wl,-soname,libcuda.so.1", "-o", str(cls.fake_cuda), str(ROOT / "tests/fake_cuda.c")], + check=True, + ) + + objs = [] + for src in ( + "src/api.c", "src/bootstrap.c", "src/stubs.c", "src/aliases.c", + "src/device_api.c", "src/engine.c", "src/cuda_api.c", + ): + obj = tmp / f"{Path(src).stem}.o" + subprocess.run([cc, *cppflags, *cflags, "-c", str(ROOT / src), "-o", str(obj)], check=True) + objs.append(str(obj)) + + kp_obj = tmp / "kp_stub.o" + subprocess.run([cc, *cppflags, *cflags, "-c", str(kp_stub), "-o", str(kp_obj)], check=True) + objs.append(str(kp_obj)) + + for src in ("src/transport/proxy_hw.c", "src/transport/p2p_hw.c", "src/transport/verbs_dl.c"): + obj = tmp / f"{Path(src).stem}.o" + subprocess.run([cc, *cflags, "-c", str(ROOT / src), "-o", str(obj)], check=True) + objs.append(str(obj)) + + for src in ("src/transport/proxy_emu.c", "src/transport/p2p_emu.c", "src/transport/shm_verbs.c"): + obj = tmp / f"{Path(src).stem}.o" + subprocess.run( + [cc, f"-I{ROOT / 'src/transport/fake_verbs'}", f"-I{ROOT / 'src/transport'}", + *cflags, "-c", str(ROOT / src), "-o", str(obj)], + check=True, + ) + objs.append(str(obj)) + + subprocess.run( + [cc, "-shared", "-pthread", f"-Wl,--version-script={ROOT / 'exports.map'}", + "-o", str(cls.lib), *objs, "-ldl"], + check=True, + ) + + @classmethod + def tearDownClass(cls): + if hasattr(cls, "tmp"): + cls.tmp.cleanup() + + def _run_group(self, mode: str, world: int, extra_env: dict[str, str] | None = None): + with tempfile.TemporaryDirectory(prefix=f"sircl-hard-{mode}-") as d: + uid_file = Path(d) / "uid.bin" + fabric = f"/sircl-emu-hard-{os.getpid()}-{mode}" + base_env = dict(os.environ) + base_env["LD_LIBRARY_PATH"] = f"{self.fake_cuda_dir}:{base_env.get('LD_LIBRARY_PATH', '')}" + base_env["LIBSIRCL_TRANSPORT"] = "emulation" + base_env["SIRCL_EMU_FABRIC"] = fabric + base_env["SIRCL_BOOTSTRAP_ADDR"] = "127.0.0.1" + if extra_env: + base_env.update(extra_env) + procs = [ + subprocess.Popen( + [sys.executable, str(self.worker), mode, str(world), str(rank), + str(uid_file), str(self.lib), str(self.fake_cuda)], + env=base_env, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + text=True, + ) + for rank in range(world) + ] + results = [p.communicate(timeout=30) for p in procs] + shm = Path("/dev/shm") / fabric.lstrip("/") + shm.unlink(missing_ok=True) + for rank, (p, (out, err)) in enumerate(zip(procs, results)): + self.assertEqual(p.returncode, 0, f"mode={mode} rank={rank} stdout={out!r} stderr={err!r}") + return [out for out, _ in results] + + def test_captured_communicator_abort_quarantines_memory(self): + outputs = self._run_group("capture_abort", world=2) + for out in outputs: + self.assertIn("capture_abort quarantined_bytes=", out) + + def test_mixed_group_p2p_and_collective_ordering_guard(self): + outputs = self._run_group("mixed_group", world=2) + for out in outputs: + self.assertIn("mixed_group ok", out) + + def test_ep_cooperative_launch_succeeds_and_fails_closed_when_unsupported(self): + out_ok = self._run_group( + "ep_coop_ok", + world=3, + extra_env={ + "LIBSIRCL_P2P_CHANNELS": "on", + "FAKE_CUDA_COOPERATIVE_LAUNCH": "1", + "FAKE_CUDA_SM_COUNT": "48", + "FAKE_CUDA_MAX_ACTIVE_BLOCKS": "2", + }, + ) + for out in out_ok: + self.assertIn("ep_coop_ok ok (coop_delta=2)", out) + + out_dis = self._run_group( + "ep_coop_disabled", + world=3, + extra_env={ + "LIBSIRCL_P2P_CHANNELS": "on", + "FAKE_CUDA_COOPERATIVE_LAUNCH": "0", + }, + ) + for out in out_dis: + self.assertIn("ep_coop_disabled ok (coop_delta=0)", out) + + out_low = self._run_group( + "ep_coop_low_sm", + world=3, + extra_env={ + "LIBSIRCL_P2P_CHANNELS": "on", + "FAKE_CUDA_COOPERATIVE_LAUNCH": "1", + "FAKE_CUDA_SM_COUNT": "2", + "FAKE_CUDA_MAX_ACTIVE_BLOCKS": "1", + }, + ) + for out in out_low: + self.assertIn("ep_coop_low_sm ok (coop_delta=0)", out) + + +if __name__ == "__main__": + unittest.main(verbosity=2) diff --git a/spark_transport/libsircl/tests/test_shm_verbs.py b/spark_transport/libsircl/tests/test_shm_verbs.py index 175d8d1a..0afe919c 100644 --- a/spark_transport/libsircl/tests/test_shm_verbs.py +++ b/spark_transport/libsircl/tests/test_shm_verbs.py @@ -124,6 +124,25 @@ def test_asymmetric_sparse_records_are_refused(self): self.assertEqual(process.returncode, 0, f"rank {rank}: {err}") self.assertIn("asymmetric rejected", out) + def test_roce_peer_abort_propagates_to_all_ranks(self): + with tempfile.TemporaryDirectory(prefix="sircl-shm-abort-") as directory: + env = dict(os.environ, SIRCL_EMU_FABRIC=f"/sircl-emu-abort-{os.getpid()}") + processes = [subprocess.Popen([str(self.probe), "4", str(rank), "1", "1", directory, "abort"], + env=env, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True) + for rank in range(4)] + results = [p.communicate(timeout=30) for p in processes] + fabric = Path("/dev/shm") / env["SIRCL_EMU_FABRIC"].lstrip("/") + if fabric.exists(): + fabric.unlink() + for rank, (process, (out, err)) in enumerate(zip(processes, results)): + self.assertEqual(process.returncode, 0, f"rank {rank}: {out}{err}") + self.assertIn("failed=1", out) + if rank == 1: + self.assertIn("abort_from=0", out) + else: + self.assertIn("abort_from=2", out) + self.assertIn("failure on rank 1", out) + if __name__ == "__main__": unittest.main(verbosity=2) diff --git a/spark_transport/sircl/sparkring_sircl/fabric/mesh_marker.c b/spark_transport/sircl/sparkring_sircl/fabric/mesh_marker.c index eb21e004..1ead5f79 100644 --- a/spark_transport/sircl/sparkring_sircl/fabric/mesh_marker.c +++ b/spark_transport/sircl/sparkring_sircl/fabric/mesh_marker.c @@ -277,12 +277,14 @@ int main(int argc, char **argv) struct mlx5dv_flow_action_attr action = {0}; const uint16_t ipv4_ethertype = htons(0x0800U); uint32_t words[2]; + uint64_t action_word = 0; words[0] = htonl((MLX5_MODIFICATION_TYPE_SET << 28) | ((uint32_t)MLX5_MODIFICATION_FIELD_OUTER_ETHERTYPE << 16) | 16U); words[1] = htonl((uint32_t)rule->ethertype); + memcpy(&action_word, words, sizeof(action_word)); rule->action = mlx5dv_create_flow_action_modify_header( - context, sizeof(words), (uint64_t *)(void *)words, MLX5DV_FLOW_TABLE_TYPE_RDMA_TX); + context, sizeof(action_word), &action_word, MLX5DV_FLOW_TABLE_TYPE_RDMA_TX); if (rule->action == NULL) { fprintf(stderr, "RDMA-TX EtherType rewrite action creation failed: %s\n", strerror(errno));