diff --git a/docs/operations/install-reference.md b/docs/operations/install-reference.md index 565f2a68..c3d609d9 100644 --- a/docs/operations/install-reference.md +++ b/docs/operations/install-reference.md @@ -824,6 +824,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 c8eee48b..2c9dcc0f 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..7928c356 --- /dev/null +++ b/integrations/vllm/libsircl/sircl_ep_all2all.py @@ -0,0 +1,853 @@ +"""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 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" +DEFAULT_STATIC_MAX_TOKENS = 96 + +# 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._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 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), + "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._retired.append(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._retired.extend(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(): + # 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``.""" + global _INSTALLED + if _INSTALLED: + return True + + if ALL2ALL_BASE_IS_STUB: + logger.warning("SIRCL_EP_ALL2ALL requested but vllm all2all is unavailable") + return False + + 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: + logger.warning("SIRCL_EP_ALL2ALL requested but vllm all2all is unavailable: %s", exc) + return False + + orig_prepare = MoEPrepareAndFinalizeNaiveDPEPModular.prepare + + def _wrapped_prepare( + self, + a1, + topk_weights, + topk_ids, + num_experts, + expert_map, + apply_router_weight_on_input, + quant_config, + defer_input_quant=False, + ): + prev = getattr(_ACTIVE_META, "current", None) + _ACTIVE_META.current = (int(num_experts), expert_map) + try: + return orig_prepare( + self, + a1, + topk_weights, + topk_ids, + num_experts, + expert_map, + apply_router_weight_on_input, + quant_config, + defer_input_quant=defer_input_quant, + ) + finally: + _ACTIVE_META.current = prev + + MoEPrepareAndFinalizeNaiveDPEPModular.prepare = _wrapped_prepare + + orig_cc_init = CudaCommunicator.__init__ + + def _wrapped_cc_init(self, *args, **kwargs): + orig_cc_init(self, *args, **kwargs) + if self.use_all2all and isinstance(self.all2all_manager, AgRsAll2AllManager): + tcp_store_group = kwargs.get("tcp_store_group") + if tcp_store_group is None and len(args) >= 7: + tcp_store_group = args[6] + 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..68b9b20c --- /dev/null +++ b/integrations/vllm/libsircl/sircl_ep_b12x.py @@ -0,0 +1,1246 @@ +"""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 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 install_b12x_ep_moe() -> bool: + """Patch vLLM's ``B12xExperts`` to support W4A8 and W4A16 EP.""" + 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: + logger.warning("SIRCL_B12X_EP_MOE requested but vllm b12x is unavailable: %s", exc) + return False + + 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 + + orig_is_supported_config = B12xExperts.is_supported_config + orig_get_prep_units = B12xExperts.get_b12x_preparation_units + orig_workspace_shapes = B12xExperts.workspace_shapes + orig_apply = B12xExperts.apply + kMxfp4Static = vllm_b12x.kMxfp4Static + kMxfp8Dynamic = vllm_b12x.kMxfp8Dynamic + normalize_topk_weights = vllm_b12x._normalize_topk_weights + + 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() + 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() + _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: + return + + if getattr(FusedMoEKernelModularImpl._fused_experts, "_sircl_dp_ws_patched", False): + return + + orig_fe = FusedMoEKernelModularImpl._fused_experts + sig = inspect.signature(orig_fe) + param_names = list(sig.parameters)[1:] # exclude self + ws_pos = param_names.index("workspace") if "workspace" in param_names else 14 + + def _get_arg(name: str, pos: int, args: tuple[Any, ...], kwargs: dict[str, Any]) -> Any: + if name in kwargs: + return kwargs[name] + return args[pos] + + def _wrapped_fused_experts(self, *args, **kwargs): + workspace = kwargs.get("workspace") + ws_in_args = False + if workspace is None and len(args) > ws_pos: + workspace = args[ws_pos] + ws_in_args = True + if workspace is not None: + a1q = _get_arg("a1q", 1, args, kwargs) + w1 = _get_arg("w1", 3, args, kwargs) + w2 = _get_arg("w2", 4, args, kwargs) + topk_ids = _get_arg("topk_ids", 6, args, kwargs) + _, 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: + in_dtype = _get_arg("in_dtype", 0, args, kwargs) + activation = _get_arg("activation", 7, args, kwargs) + global_num_experts = _get_arg("global_num_experts", 8, args, kwargs) + local_num_experts = _get_arg("local_num_experts", 9, args, kwargs) + expert_tokens_meta = _get_arg("expert_tokens_meta", 12, args, kwargs) + resized = _resize_dp_workspace( + self.fused_experts, + workspace, + in_dtype=in_dtype, + device=a1q.device, + m_full=m_full, + n_dim=n_dim, + k_dim=k_dim, + top_k=top_k, + global_num_experts=global_num_experts, + local_num_experts=local_num_experts, + expert_tokens_meta=expert_tokens_meta, + activation=activation, + ) + if ws_in_args: + args = (*args[:ws_pos], resized, *args[ws_pos + 1 :]) + else: + kwargs["workspace"] = resized + return orig_fe(self, *args, **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: + B12xPreparationCoordinator = None + + if B12xPreparationCoordinator is not None and not getattr( + B12xPreparationCoordinator.__init__, "_sircl_dp_rank_patched", False + ): + orig_coord_init = B12xPreparationCoordinator.__init__ + + def _wrapped_coord_init( + self, + session, + batches, + *, + global_rank: int, + world_group, + process_local_only: bool = False, + **kwargs, + ): + 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, + ) + global_rank = actual + return orig_coord_init( + self, + session, + batches, + global_rank=global_rank, + world_group=world_group, + process_local_only=process_local_only, + **kwargs, + ) + + _wrapped_coord_init._sircl_dp_rank_patched = True + B12xPreparationCoordinator.__init__ = _wrapped_coord_init + + try: + from b12x.preparation import PreparationSession + except ImportError: + PreparationSession = None + + if PreparationSession is not None and not getattr( + PreparationSession.configure_tuning_shard, "_sircl_dp_rank_patched", False + ): + orig_configure_shard = PreparationSession.configure_tuning_shard + + def _wrapped_configure_shard(self, rank: int, 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()) + if actual is not None and actual in ranks: + logger.info( + "Fixing b12x tuning shard rank %d -> %d for DP world", + int(rank), + actual, + ) + rank = actual + except Exception: + pass + return orig_configure_shard(self, rank, ranks) + + _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 = getattr(mod, "DeepseekV4Model", None) + if model_cls is None or getattr(model_cls.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: + return + + 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) + + orig_forward = model_cls.forward + + 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: + return + + if getattr(dp_utils.sync_cudagraph_and_dp_padding, "_sircl_dp_num_reqs_patched", False): + return + + tls = threading.local() + orig_dist = dp_utils.dist + + class _DistProxy: + def __getattr__(self, name: str) -> Any: + return getattr(orig_dist, name) + + def all_reduce(self, tensor: Any, *args: Any, **kwargs: Any) -> Any: + res = orig_dist.all_reduce(tensor, *args, **kwargs) + if ( + getattr(tls, "active", False) + and isinstance(tensor, torch.Tensor) + and tensor.ndim == 2 + and tensor.shape[0] >= 6 + ): + tls.max_num_reqs = int(tensor[5].max().item()) + 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 + + orig_sync = dp_utils.sync_cudagraph_and_dp_padding + orig_dispatch = dp_utils.dispatch_cg_and_sync_dp + dispatch_params = list(inspect.signature(orig_dispatch).parameters) + dp_sync_pos = ( + dispatch_params.index("dp_sync") - 1 if "dp_sync" in dispatch_params else 11 + ) + + def _wrapped_sync(cudagraph_manager: Any, *args: Any, **kwargs: Any): + prev_active = getattr(tls, "active", False) + prev_max = getattr(tls, "max_num_reqs", None) + tls.active = True + tls.max_num_reqs = None + cm = ( + _SyncedNumReqsManagerProxy( + cudagraph_manager, lambda: getattr(tls, "max_num_reqs", None) + ) + if cudagraph_manager is not None + else None + ) + try: + return orig_sync(cm, *args, **kwargs) + finally: + tls.active = prev_active + tls.max_num_reqs = prev_max + + def _wrapped_dispatch(cudagraph_manager: Any, *args: Any, **kwargs: Any): + dp_sync = kwargs.get("dp_sync") + if dp_sync is None and len(args) > dp_sync_pos: + dp_sync = args[dp_sync_pos] + if dp_sync is not None and cudagraph_manager is not None: + min_reqs = int(dp_sync.num_reqs) + cudagraph_manager = _SyncedNumReqsManagerProxy( + cudagraph_manager, lambda: min_reqs + ) + return orig_dispatch(cudagraph_manager, *args, **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() -> 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: + return + runner_cls = getattr(mod, "GPUModelRunner", None) + if runner_cls is None or getattr( + runner_cls.sample_tokens, "_sircl_dp_spec_sync_patched", False + ): + return + + orig_sample_tokens = runner_cls.sample_tokens + + 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 ``VLLM_MOE_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: + return + orig_dsv4 = getattr(router_mod, "dsv4_topk", None) + get_pad = getattr(router_mod, "_get_padding_mask", None) + if orig_dsv4 is None or get_pad is None or getattr(orig_dsv4, "_sircl_pad_patched", False): + return + + 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: + return + + patched = False + + orig_heur = getattr(fm_impl, "_heuristic_dynamic_route_mode", None) + if orig_heur is not None and 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 + + orig_plan = getattr(fm_prep, "plan", None) + if orig_plan is not None and 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..9f7f689b --- /dev/null +++ b/integrations/vllm/libsircl/test_sircl_ep_all2all.py @@ -0,0 +1,926 @@ +"""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 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 1a54d064..f5090a07 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: d4f418f91a9ebcf8b222ae6793349e15c8537f535da88d354aaa7a77189d4635 + io.sparkring.deployment: a191b6754307da5cd07bd6292f93e1192cccffaf13843e2ccd15777f90b6317a 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 7fb2b2f5..20f8def7 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: d4f418f91a9ebcf8b222ae6793349e15c8537f535da88d354aaa7a77189d4635 + io.sparkring.deployment: a191b6754307da5cd07bd6292f93e1192cccffaf13843e2ccd15777f90b6317a 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 24969a9a..27642294 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: d4f418f91a9ebcf8b222ae6793349e15c8537f535da88d354aaa7a77189d4635 + io.sparkring.deployment: a191b6754307da5cd07bd6292f93e1192cccffaf13843e2ccd15777f90b6317a 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 8ac25d0b..9682983b 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: d4f418f91a9ebcf8b222ae6793349e15c8537f535da88d354aaa7a77189d4635 + io.sparkring.deployment: a191b6754307da5cd07bd6292f93e1192cccffaf13843e2ccd15777f90b6317a 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 9b0717e1..7e35c451 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": "d4f418f91a9ebcf8b222ae6793349e15c8537f535da88d354aaa7a77189d4635" + "deployment": "a191b6754307da5cd07bd6292f93e1192cccffaf13843e2ccd15777f90b6317a" } 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 387a90c2..92d45dd8 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: dd06028efdf4cc20653a0ef7ddd932236f135e67bab4a400ef017fe604588333 + io.sparkring.deployment: 20bcd69b9f8305d51c2f4d84a9937e53b4690c0795f4d02ee8fcc30a2593e274 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 8e56e909..56a97594 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: dd06028efdf4cc20653a0ef7ddd932236f135e67bab4a400ef017fe604588333 + io.sparkring.deployment: 20bcd69b9f8305d51c2f4d84a9937e53b4690c0795f4d02ee8fcc30a2593e274 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 a40245ab..4bb9141c 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": "dd06028efdf4cc20653a0ef7ddd932236f135e67bab4a400ef017fe604588333" + "deployment": "20bcd69b9f8305d51c2f4d84a9937e53b4690c0795f4d02ee8fcc30a2593e274" } 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 9ce6f29d..dcda482e 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: 2483156c11e1e430ce46039c0bfc02f3bdf814b026565a5b22fbf30d2b7e0c7f + io.sparkring.deployment: 644ae88eb4c5603455898d15d1f282acec1ac2815e67990484ecc1ab0148be03 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 ea595c60..d548a713 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: 2483156c11e1e430ce46039c0bfc02f3bdf814b026565a5b22fbf30d2b7e0c7f + io.sparkring.deployment: 644ae88eb4c5603455898d15d1f282acec1ac2815e67990484ecc1ab0148be03 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 90e15343..e16bb9f7 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: 2483156c11e1e430ce46039c0bfc02f3bdf814b026565a5b22fbf30d2b7e0c7f + io.sparkring.deployment: 644ae88eb4c5603455898d15d1f282acec1ac2815e67990484ecc1ab0148be03 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 6e187fce..f88398d6 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: 2483156c11e1e430ce46039c0bfc02f3bdf814b026565a5b22fbf30d2b7e0c7f + io.sparkring.deployment: 644ae88eb4c5603455898d15d1f282acec1ac2815e67990484ecc1ab0148be03 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 a8de182c..41060a45 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": "2483156c11e1e430ce46039c0bfc02f3bdf814b026565a5b22fbf30d2b7e0c7f" + "deployment": "644ae88eb4c5603455898d15d1f282acec1ac2815e67990484ecc1ab0148be03" } 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 3423befd..c2af15af 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: 82f9d92a3a85d38a3b51512f3a591cc2bbfb474f93302696f1624aafd3d56de4 + io.sparkring.deployment: be78213baf7b635bc7239436d0695e52da10523afb08d087567ca8b15e52d3a5 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 503d741f..5870444b 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: 82f9d92a3a85d38a3b51512f3a591cc2bbfb474f93302696f1624aafd3d56de4 + io.sparkring.deployment: be78213baf7b635bc7239436d0695e52da10523afb08d087567ca8b15e52d3a5 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 b259fc57..cdd32d28 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": "82f9d92a3a85d38a3b51512f3a591cc2bbfb474f93302696f1624aafd3d56de4" + "deployment": "be78213baf7b635bc7239436d0695e52da10523afb08d087567ca8b15e52d3a5" } 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 c8a15277..7e6a5967 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: dacb6a2559a9d3f9b3072fcc277ebb98870a16f5a0a717a7ce11d1218952c473 + io.sparkring.deployment: 8cf8a803e837bfcf8a7ff7e8b6b816723f85dbb96ebd846614d53f9feedcc906 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 9cb7ee03..59a62330 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: dacb6a2559a9d3f9b3072fcc277ebb98870a16f5a0a717a7ce11d1218952c473 + io.sparkring.deployment: 8cf8a803e837bfcf8a7ff7e8b6b816723f85dbb96ebd846614d53f9feedcc906 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 39c13a2d..2e4e33cd 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: dacb6a2559a9d3f9b3072fcc277ebb98870a16f5a0a717a7ce11d1218952c473 + io.sparkring.deployment: 8cf8a803e837bfcf8a7ff7e8b6b816723f85dbb96ebd846614d53f9feedcc906 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 bc90dff6..4357ff74 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: dacb6a2559a9d3f9b3072fcc277ebb98870a16f5a0a717a7ce11d1218952c473 + io.sparkring.deployment: 8cf8a803e837bfcf8a7ff7e8b6b816723f85dbb96ebd846614d53f9feedcc906 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 c0476964..b3f5b4b9 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": "dacb6a2559a9d3f9b3072fcc277ebb98870a16f5a0a717a7ce11d1218952c473" + "deployment": "8cf8a803e837bfcf8a7ff7e8b6b816723f85dbb96ebd846614d53f9feedcc906" } 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 94e5bb7c..cdbf06e0 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: 60caff55848ee1648e9e6611d002d2d2801f9d7d69faed18b9a1dcbf3b03ac73 + io.sparkring.deployment: 29e0a60cf168ed84e3206d309a697dc7bbc24f428539eb6984ed6c935b111d6c 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 a10797e2..bf521227 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: 60caff55848ee1648e9e6611d002d2d2801f9d7d69faed18b9a1dcbf3b03ac73 + io.sparkring.deployment: 29e0a60cf168ed84e3206d309a697dc7bbc24f428539eb6984ed6c935b111d6c 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 cfadab9a..e2c2b5aa 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: 60caff55848ee1648e9e6611d002d2d2801f9d7d69faed18b9a1dcbf3b03ac73 + io.sparkring.deployment: 29e0a60cf168ed84e3206d309a697dc7bbc24f428539eb6984ed6c935b111d6c 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 ceabccd8..b8359269 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: 60caff55848ee1648e9e6611d002d2d2801f9d7d69faed18b9a1dcbf3b03ac73 + io.sparkring.deployment: 29e0a60cf168ed84e3206d309a697dc7bbc24f428539eb6984ed6c935b111d6c 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 cd7421cc..9fce2344 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: d9933be41fe5865980162aedbc5af1a51c9f648a2e26b2265e240cd7f1a17f0e + io.sparkring.deployment: 41e155e9347ec2b1ce66156f10174cd17ffa6695347d5acab65491726d2cd49d 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 be13d426..d2e47e4d 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: d9933be41fe5865980162aedbc5af1a51c9f648a2e26b2265e240cd7f1a17f0e + io.sparkring.deployment: 41e155e9347ec2b1ce66156f10174cd17ffa6695347d5acab65491726d2cd49d 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 bfe33746..083ef520 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: d9933be41fe5865980162aedbc5af1a51c9f648a2e26b2265e240cd7f1a17f0e + io.sparkring.deployment: 41e155e9347ec2b1ce66156f10174cd17ffa6695347d5acab65491726d2cd49d 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 d3057b4f..2e790b33 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: d9933be41fe5865980162aedbc5af1a51c9f648a2e26b2265e240cd7f1a17f0e + io.sparkring.deployment: 41e155e9347ec2b1ce66156f10174cd17ffa6695347d5acab65491726d2cd49d 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 02bdf781..06fd2669 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": "d9933be41fe5865980162aedbc5af1a51c9f648a2e26b2265e240cd7f1a17f0e" + "deployment": "41e155e9347ec2b1ce66156f10174cd17ffa6695347d5acab65491726d2cd49d" } 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 f0524433..fadce636 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: d200b01fbb52b1f1e7ca7c2c63ce50ae8f94c002080b0b9f33229688e586ebcd + io.sparkring.deployment: 0c4964bf197d9c884dfda7c499c460e35d7a466702aeedb452ac55bd63078f00 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 d44d94da..52d7e74d 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: d200b01fbb52b1f1e7ca7c2c63ce50ae8f94c002080b0b9f33229688e586ebcd + io.sparkring.deployment: 0c4964bf197d9c884dfda7c499c460e35d7a466702aeedb452ac55bd63078f00 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 0e94a6a9..48855d57 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: 69d8190bd56a9d464a054d8c40ddb959c56bb3a0f2b0ad55df421f6e8f85e494 + io.sparkring.deployment: 7a1a838530eb91bba096b35a2d86939be4259f28ded018592d931a6460ba297a 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 337e67a2..294917f6 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: 69d8190bd56a9d464a054d8c40ddb959c56bb3a0f2b0ad55df421f6e8f85e494 + io.sparkring.deployment: 7a1a838530eb91bba096b35a2d86939be4259f28ded018592d931a6460ba297a 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 435537fc..7cf5dfe5 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": "69d8190bd56a9d464a054d8c40ddb959c56bb3a0f2b0ad55df421f6e8f85e494" + "deployment": "7a1a838530eb91bba096b35a2d86939be4259f28ded018592d931a6460ba297a" } 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 6950b82f..d288fc6c 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: 6d2bf1706d5ac99e6a8ea3883934f1a71f80fa55e37b1d21c4beb2d643f8b680 + io.sparkring.deployment: d8ce5902f8e4b889f31a570604f6e049b22ac6f9c9dbf29716605f5e983567ea 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 4375a215..206772b6 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: 6d2bf1706d5ac99e6a8ea3883934f1a71f80fa55e37b1d21c4beb2d643f8b680 + io.sparkring.deployment: d8ce5902f8e4b889f31a570604f6e049b22ac6f9c9dbf29716605f5e983567ea 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 8fca993d..d150a910 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": "6d2bf1706d5ac99e6a8ea3883934f1a71f80fa55e37b1d21c4beb2d643f8b680" + "deployment": "d8ce5902f8e4b889f31a570604f6e049b22ac6f9c9dbf29716605f5e983567ea" } 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 31046773..a4cdd1f8 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: 2425f51e83084e7636ba2c630ca059b9ce0f2470536a3a419f92be5df396d015 + io.sparkring.deployment: c4af210a14fd19179b9a0e3427ba415dcbb2ac131eb19a6664489376a95da232 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 60b47ae6..08883865 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: 2425f51e83084e7636ba2c630ca059b9ce0f2470536a3a419f92be5df396d015 + io.sparkring.deployment: c4af210a14fd19179b9a0e3427ba415dcbb2ac131eb19a6664489376a95da232 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 a5472c79..0cbb9014 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: 2425f51e83084e7636ba2c630ca059b9ce0f2470536a3a419f92be5df396d015 + io.sparkring.deployment: c4af210a14fd19179b9a0e3427ba415dcbb2ac131eb19a6664489376a95da232 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 7c9ee907..7a96ca6e 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: 2425f51e83084e7636ba2c630ca059b9ce0f2470536a3a419f92be5df396d015 + io.sparkring.deployment: c4af210a14fd19179b9a0e3427ba415dcbb2ac131eb19a6664489376a95da232 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 e625a318..cc4fdd3d 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": "2425f51e83084e7636ba2c630ca059b9ce0f2470536a3a419f92be5df396d015" + "deployment": "c4af210a14fd19179b9a0e3427ba415dcbb2ac131eb19a6664489376a95da232" } diff --git a/runtime/common/compose.py b/runtime/common/compose.py index cac874d3..0b3257cf 100644 --- a/runtime/common/compose.py +++ b/runtime/common/compose.py @@ -438,8 +438,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 590c2eb4..abd697f2 100644 --- a/runtime/common/installer.py +++ b/runtime/common/installer.py @@ -375,6 +375,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 @@ -818,10 +819,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 df44d3dd..158f5945 100644 --- a/runtime/common/serving.py +++ b/runtime/common/serving.py @@ -76,6 +76,8 @@ # The experiment uses the pinned installer image and the deployment's retained source. ROW_OWNED_PREFILL = "row_owned_prefill" CHAIN_ALL_GATHER = "chain_all_gather" +ROW_OWNED_PREFILL_PROFILE = "deepseek-v41-flash-tp4" +ROW_OWNED_PREFILL_CHECKPOINT = "1017" ROW_OWNED_PREFILL_IMAGE = "dev-20261013-dcp2prefill-status038-sircl-tp6" ROW_OWNED_PREFILL_IMAGE_ID = "sha256:3cc9a81fd344fe52fe9cc261b46dc051e3c3f494e51b8142846a5f854835c502" ROW_OWNED_PREFILL_CONTEXT = 262144 @@ -83,6 +85,51 @@ ROW_OWNED_PREFILL_TARGET = "/opt/ds41_row_shard" ROW_OWNED_SIRCL_SOURCE = "spark_transport/sircl/sparkring_sircl/vllm/adapter.py" ROW_OWNED_SIRCL_TARGET = "/usr/local/lib/python3.12/dist-packages/sparkring_sircl/vllm/adapter.py" +# 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", +} # name: (container environment variable, value, help). save_cpu shortens the # time vLLM's shared-memory readers poll after a read from one second to 2 ms, # so between decode steps they sleep until notified instead of keeping CPU @@ -101,6 +148,9 @@ "experimental DeepSeek V4.1-Flash-1017 prefill with token rows split across four Sparks"), CHAIN_ALL_GATHER: ("SIRCL_GATHER_SCHEDULE", "chain", "use direct-link SIRCL all-gather with --row-owned-prefill"), + 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"), } # The installer image capability (installer_image.capabilities) that each # switch needs: on an image without it, the switch's variable would change nothing. @@ -262,19 +312,48 @@ def check_row_owned_prefill(settings, model, image, transport): raise ValueError(f"{option(CHAIN_ALL_GATHER)} requires {option(ROW_OWNED_PREFILL)}") return flag = option(ROW_OWNED_PREFILL) - if model != ("deepseek-v41-flash-tp4", "1017"): - raise ValueError(f"{flag} requires --profile deepseek-v41-flash-tp4 --checkpoint 1017") + if model != (ROW_OWNED_PREFILL_PROFILE, ROW_OWNED_PREFILL_CHECKPOINT): + raise ValueError(f"{flag} requires --profile {ROW_OWNED_PREFILL_PROFILE} " + f"--checkpoint {ROW_OWNED_PREFILL_CHECKPOINT}") if not image or image["image_id"] != ROW_OWNED_PREFILL_IMAGE_ID: raise ValueError(f"{flag} requires --image {ROW_OWNED_PREFILL_IMAGE}") - if (not transport or transport.get("backend") != "sircl" or transport.get("nccl") != "never" - or transport["group"]["name"] != "path-4" or transport["group"]["dcp"] != 1): - raise ValueError(f"{flag} requires --transport sircl --nccl never on a four-Spark path") - if chain and any("tp" in entry["sessions"] for entry in transport["tuning"]["tables"]): - raise ValueError(f"{option(CHAIN_ALL_GATHER)} requires a SIRCL path without a TP tuning table") + if 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 chain: + 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: + if (not transport or transport.get("backend") != "sircl" or transport.get("nccl") != "never" + or transport["group"]["name"] != "path-4" or transport["group"]["dcp"] != 1): + raise ValueError(f"{flag} requires --transport sircl --nccl never on a four-Spark path") + if chain and any("tp" in entry["sessions"] for entry in transport["tuning"]["tables"]): + raise ValueError(f"{option(CHAIN_ALL_GATHER)} requires a SIRCL path without a TP tuning table") if settings.get("context_length", ROW_OWNED_PREFILL_CONTEXT) > ROW_OWNED_PREFILL_CONTEXT: raise ValueError(f"{flag} supports --context-length up to {ROW_OWNED_PREFILL_CONTEXT} tokens") +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) + if model != (ROW_OWNED_PREFILL_PROFILE, ROW_OWNED_PREFILL_CHECKPOINT): + raise ValueError(f"{flag} requires --profile {ROW_OWNED_PREFILL_PROFILE} " + f"--checkpoint {ROW_OWNED_PREFILL_CHECKPOINT}") + if not image or image["image_id"] != ROW_OWNED_PREFILL_IMAGE_ID: + raise ValueError(f"{flag} requires --image {ROW_OWNED_PREFILL_IMAGE}") + 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. @@ -433,6 +512,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 @@ -452,6 +536,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) if settings.get(ROW_OWNED_PREFILL): if source_root is None: raise ValueError(f"{option(ROW_OWNED_PREFILL)} requires the deployment source directory") @@ -468,6 +563,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 _row_owned_prefill_arguments(command): """Keep prefill eager and capture uniform decode on the pinned profile.""" command = list(command) @@ -482,7 +599,9 @@ def _row_owned_prefill_arguments(command): command[index] = json.dumps(config, separators=(",", ":")) context = command.index("--max-model-len") + 1 command[context] = str(min(int(command[context]), ROW_OWNED_PREFILL_CONTEXT)) - command.append("--disable-custom-all-reduce") + if "--disable-custom-all-reduce" not in command: + # The libsircl transport turns vLLM's custom all-reduce off as well. + command.append("--disable-custom-all-reduce") return tuple(command) @@ -500,6 +619,10 @@ def environment(settings): DS41_ROW_SHARD_KV_LATENTS="1", DS41_ROW_SHARD_COMPRESSOR_LATENTS="1", ) + 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 b53ad349..96a7ab4e 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 31c40c22..43441738 100644 --- a/runtime/common/test_serving.py +++ b/runtime/common/test_serving.py @@ -351,3 +351,95 @@ def test_without_thinking_settings_commands_compose_files_and_locks_are_unchange # The other serving settings render as before. tuned = installer.make_lock(QWEN, site(), "1" * 40, "2" * 64, settings={"max_images": 8}) 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"]) diff --git a/runtime/host/install_workflow.py b/runtime/host/install_workflow.py index c0f92a0f..7a914b3b 100644 --- a/runtime/host/install_workflow.py +++ b/runtime/host/install_workflow.py @@ -694,6 +694,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, @@ -1898,6 +1900,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/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/kernels/sircl_p2p.cu b/spark_transport/libsircl/kernels/sircl_p2p.cu index 4e8885ac..2afdca73 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,582 @@ 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; + } +} + +__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..5e8b1c33 100644 --- a/spark_transport/libsircl/src/api.c +++ b/spark_transport/libsircl/src/api.c @@ -1045,6 +1045,42 @@ 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_ready(comm, "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_ready(comm, "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/engine.c b/spark_transport/libsircl/src/engine.c index 4112fc1c..16da3f25 100644 --- a/spark_transport/libsircl/src/engine.c +++ b/spark_transport/libsircl/src/engine.c @@ -353,12 +353,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; @@ -468,15 +468,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 +486,12 @@ 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]; p2p_channel p2p_ch[2][MAX_WORLD]; sccl_CUevent p2p_ready; uint64_t p2p_check_ns; 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; @@ -1925,6 +1928,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) { @@ -1999,16 +2004,40 @@ 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; 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; } 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]; @@ -4328,9 +4357,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,6 +4370,12 @@ 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; @@ -4352,11 +4389,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 +4402,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 +4415,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 +4436,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 +4457,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 +4478,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 +4559,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 +4633,215 @@ 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; + } + 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(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(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); @@ -4708,7 +4964,7 @@ static void p2p_receipt(sccl_engine *e, char *out, size_t 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\":{" + ",\"sent\":{%s},\"received\":{%s},\"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 @@ -4716,6 +4972,7 @@ static void p2p_receipt(sccl_engine *e, char *out, size_t len) { 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], + 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, 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/kernelpack.c b/spark_transport/libsircl/src/kernelpack.c index e7454f3c..38d35e7f 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,31 @@ 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_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..06ec49e4 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,11 @@ 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); /* 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/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/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_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)