Source code for mstar.communication.arena

"""Tensor transport over a shared-memory arena.

``ArenaShmCommunicationManager`` replaces the file transport's per-tensor
open/write/read/unlink with a Rust segmented ``/dev/shm`` arena (persistent
mmaps + first-fit coalescing allocator, vendored in ``rust/``). Producer:
``register_for_send`` reserves a slot and D2H-copies into the segment on the
copy stream; the ``(segment, offset)`` rides the existing descriptors.
Consumer: ``start_read_tensors`` maps the named segment once, reads
zero-copy, H2D-copies on the copy stream; the producer reclaims on ACK,
gated by a CUDA-event future so an edge is never ACKed before its copies
land. Segments are mapped once and never move, so the one-time
``cudaHostRegister`` per segment (within ``MSTAR_SHM_ARENA_PIN_MAX_MB``)
holds for its lifetime and keeps the side-stream copies truly async.

Capacity degrades in layers: grow by segments up to
``MSTAR_SHM_ARENA_MAX_SEGMENTS`` (or until /dev/shm cannot back another
segment: segments commit their pages when created); at the cap, briefly
backpressure for consumer ACKs; then spill the tensor to the per-uuid file protocol
(``MSTAR_SHM_ARENA_SPILL``, default on) — slower, never fails, like the old
transport at saturation. ``stats_summary()`` exposes occupancy and the
fragmentation gauge (largest contiguous free block); ``--log-stats`` logs it
periodically.

Ceilings are PER-ENTITY and multiply across a node: with E entities
(workers + the api-server data worker), /dev/shm demand can reach
``MAX_SEGMENTS x SEGMENT_MB x E`` and pinned host RAM approx
``PIN_MAX_MB x E`` (consumers pin peer segments too, so one process can pin
more than its own arena holds). With neither ``MAX_SEGMENTS`` nor
``SEGMENT_MB`` set, the API server sizes every arena of its deployment once,
before any exists (``export_arena_plan``): /dev/shm's free space split among
the deployment's arenas plus one share kept for spill files. Each entity
measuring free space for itself would give the ones that start later less,
since a first segment's pages are committed when it is created. An entity
started without that plan falls back to its own measurement. Set by hand,
construction fails fast when one entity's ceiling already exceeds /dev/shm.
Either way it warns when the ceiling exceeds current free space or when the
pin budget is an outsized share of physical RAM.

An entity can also run without an arena of its own: when its first segment
cannot be created (or /dev/shm is too small for a 16 MiB share), and on
devices other than CPU and CUDA (``_arena_supported``), which use the file
path until the arena is measured there. It then sends every tensor as a per-uuid file and
still reads its peers' arenas, so it mixes with entities that have one.

Selection: ``create_tensor_communication_manager`` builds this manager for
the SHM protocol; the file transport it extends is its spill path. See
:doc:`environment_variables` for the knobs.
"""

from __future__ import annotations

import logging
import os
import queue
import threading
import time
import weakref
from concurrent.futures import Future
from typing import NamedTuple

import numpy as np
import torch

from mstar.communication.communicator import BaseCommunicator
from mstar.communication.tensors import (
    FutureAndPointers,
    Rid,
    SharedMemoryCommunicationManager,
    _default_shm_dir,
    _deserialize_tensor,
    _nullcontext,
    _serialize_tensor,
    _sweep_dead_namespaces,
)
from mstar.graph.base import GraphEdge, TensorPointerInfo
from mstar.platforms import current_platform
from mstar.utils.containers import ParallelList
from mstar.utils.host_copy import HostCopier
from mstar.utils.threads import Thread

logger = logging.getLogger(__name__)

_CUDA_HOST_ALREADY_REGISTERED = 712
_sizing_logged = False

#: ``<segment MiB>x<max segments>`` for every arena of one deployment, ``0x0``
#: for none; set by ``export_arena_plan`` and inherited by the processes the
#: API server starts.
ARENA_PLAN_ENV = "MSTAR_SHM_ARENA_PLAN"
#: Without a plan an entity takes a quarter of the free space it finds: its
#: arena and two others, plus the spill share.
_UNPLANNED_ENTITIES = 3


def _default_sizing(budget: int, entities: int) -> tuple[int, int] | None:
    """(segment MiB, max segments) for each of ``entities`` arenas sharing
    ``budget`` bytes, with one more share left for the files sends spill to:
    256 MiB segments, 1 to 32 of them, or where a share is under 256 MiB, one
    segment of the largest power-of-two MiB that fits. None where a share is
    under 16 MiB: the entities send by files."""
    share_mb = (budget >> 20) // (entities + 1)
    if share_mb < 16:
        return None
    segment_mb = 256 if share_mb >= 256 else 1 << (share_mb.bit_length() - 1)
    return segment_mb, min(32, share_mb // segment_mb)


def _shm_space() -> tuple[int | None, int | None]:
    """/dev/shm's total and free bytes, or Nones where it cannot be read."""
    try:
        st = os.statvfs("/dev/shm")
    except OSError:
        return None, None
    return st.f_frsize * st.f_blocks, st.f_frsize * st.f_bavail


def _sweep_orphan_segments() -> None:
    """A SIGKILLed server never runs Drop, orphaning up to its full
    arena in /dev/shm until reboot. Names embed the owning pid, so a
    startup sweep can reclaim any segment whose owner is gone. Files we
    cannot judge (foreign naming) or cannot remove (another user's)
    are left with a debug note."""
    try:
        names = os.listdir("/dev/shm")
    except OSError:
        return
    for name in names:
        if not name.startswith("mstar_arena_"):
            continue
        parts = name.split(".")[0].rsplit("_", 2)
        if len(parts) != 3 or not parts[1].isdigit():
            continue   # pre-uniquification or foreign naming: skip
        if os.path.exists(f"/proc/{parts[1]}"):
            continue   # owner alive
        try:
            os.unlink(f"/dev/shm/{name}")
            logger.info("ARENA: swept orphaned segment %s "
                        "(owner pid %s is gone)", name, parts[1])
        except OSError as e:
            logger.debug("ARENA: cannot sweep %s: %s", name, e)


[docs] def export_arena_plan(worker_devices: list[str] | None) -> None: """Size every arena of this deployment once, from /dev/shm's free space before any of them exists, and hand the sizes to the processes the caller starts (``ARENA_PLAN_ENV``). Called by the API server, which holds one arena itself, for its workers on ``worker_devices``; None (no deployment config) drops a plan an earlier server in this process left.""" os.environ.pop(ARENA_PLAN_ENV, None) if worker_devices is not None: # a dead run's segments and files count against the free space until # they are gone, and a restart would size itself around them _sweep_orphan_segments() _sweep_dead_namespaces(_default_shm_dir(), "") _, avail = _shm_space() if worker_devices is None or avail is None: return entities = 1 + sum(map(_arena_supported, worker_devices)) sizes = _default_sizing(avail, entities) or (0, 0) os.environ[ARENA_PLAN_ENV] = f"{sizes[0]}x{sizes[1]}" logger.info( "ARENA: /dev/shm has %d MiB free for %d arenas and their spill files; " "each arena grows to %d segments of %d MiB (MSTAR_SHM_ARENA_MAX_SEGMENTS " "and _SEGMENT_MB override)", avail >> 20, entities, sizes[1], sizes[0])
def _arena_sizing() -> tuple[int, int, int | None, int | None]: """Segment MiB, max segments, and /dev/shm's total and free bytes. Knobs the user set are taken as given (the constructor fails fast if they do not fit); with neither set the deployment's plan applies, and without one the sizes come from /dev/shm's free space now. Either way a small or busy tmpfs (a Kubernetes pod gets 64 MiB) runs a small arena, or none (0 segments of 0 MiB), and spills to files instead of refusing to start.""" global _sizing_logged total, avail = _shm_space() segment_env = os.environ.get("MSTAR_SHM_ARENA_SEGMENT_MB") max_env = os.environ.get("MSTAR_SHM_ARENA_MAX_SEGMENTS") if segment_env or max_env: segment_mb, max_segments = int(segment_env or 256), int(max_env or 32) if segment_mb < 1 or max_segments < 1: raise ValueError("MSTAR_SHM_ARENA_SEGMENT_MB and _MAX_SEGMENTS " "must be at least 1") return segment_mb, max_segments, total, avail if plan := os.environ.get(ARENA_PLAN_ENV): segment_mb, _, max_segments = plan.partition("x") return int(segment_mb), int(max_segments), total, avail if avail is None: return 256, 32, total, avail sizes = _default_sizing(avail, _UNPLANNED_ENTITIES) if sizes is None: return 0, 0, total, avail segment_mb, max_segments = sizes if not _sizing_logged: _sizing_logged = True logger.info( "ARENA: /dev/shm has %d MiB free; each entity's arena grows " "to %d segments of %d MiB (MSTAR_SHM_ARENA_MAX_SEGMENTS and " "_SEGMENT_MB override)", avail >> 20, max_segments, segment_mb) return segment_mb, max_segments, total, avail def _arena_supported(device) -> bool: """Whether an entity on ``device`` stages its sends in an arena: CPU, and CUDA. ROCm (``_pin`` loads libcudart), XPU (no copy streams) and the rest send by per-uuid files until the arena is ported and measured there.""" kind = torch.device(device).type return kind == "cpu" or (kind == "cuda" and current_platform.is_cuda()) class _Placements(NamedTuple): """Where a batch's staged tensors landed, as columns. Index-parallel, one entry per staged tensor, in the layout ``set_shm_placement`` takes -- so staging fills three lists rather than minting an object per tensor that ``_write_back`` then takes apart again. The segment is its INDEX, not its name: the store learned the names once, as the arena grew into them. Empty is ``not p.uuids``, not ``not p`` -- this is a 3-tuple, so it is always truthy. ``ParallelList`` does NOT share that edge: it defines ``__len__``, which ``bool`` falls back on, so an empty one is falsey. """ uuids: list[int] segment_idxs: list[int] offsets: list[int] @classmethod def empty(cls) -> "_Placements": return cls([], [], []) def add(self, uuid: int, segment_idx: int, offset: int) -> None: """All three at once: they mean nothing out of lockstep.""" self.uuids.append(uuid) self.segment_idxs.append(segment_idx) self.offsets.append(offset) class _CudaEventFuture: """Future-shaped CUDA event. An edge whose H2D copies ride behind this event reports ready only once the copies have completed on the device — so the ACK that lets the producer reclaim the arena slot is deferred by ``get_ready_tensors``'s existing future polling instead of a blocking host synchronize.""" def __init__(self, stream): # blocking=True: `synchronize` SLEEPS until the event fires. The # default (False) busy-waits — the watcher thread that turns these # into wake futures would burn a full core per wait. self._event = torch.cuda.Event(blocking=True) self._event.record(stream) def done(self) -> bool: return self._event.query() def result(self) -> None: self._event.synchronize() _CUDART = None def _cudart(): """libcudart via ctypes: unlike the torch binding, a ctypes call RELEASES the GIL, so registering a 256 MiB segment (tens of ms) on the send path cannot stall the process's other Python threads (serve loop, stream relays, the wake watcher). Loaded by the soname of torch's CUDA major, which reaches the copy torch already loaded even where it is not on the loader path (a pip install of torch).""" global _CUDART if _CUDART is None: import ctypes if not torch.version.cuda: raise OSError("torch is not built with CUDA") lib = ctypes.CDLL(f"libcudart.so.{torch.version.cuda.split('.')[0]}") lib.cudaHostRegister.argtypes = [ ctypes.c_void_p, ctypes.c_size_t, ctypes.c_uint] lib.cudaHostRegister.restype = ctypes.c_int lib.cudaHostUnregister.argtypes = [ctypes.c_void_p] lib.cudaHostUnregister.restype = ctypes.c_int _CUDART = lib return _CUDART def _unlink_paths(paths: list) -> None: """Exit-time segment unlink (weakref.finalize target — must not reference the manager). Workers exit with the manager still alive, so the interpreter never garbage-collects it and the Rust Drop (which unlinks) never runs; without this, every worker run leaks its full segments in /dev/shm until swept by a later start.""" for path in paths: try: os.unlink(path) except OSError: pass def _unpin(ptr: int) -> bool: """cudaHostUnregister a previously pinned mapping (GIL released via ctypes). Returns success.""" if not torch.cuda.is_available(): return False try: lib = _cudart() except OSError: return False rc = lib.cudaHostUnregister(ptr) if rc != 0: # Left set, the thread's next torch kernel launch raises it. lib.cudaGetLastError() return rc == 0 def _unpin_live(own_pinned: list, peers: dict) -> None: """Unregister every pinned own and peer segment (weakref.finalize target -- must not reference the manager). Runs before the arena objects unmap: a mapping torn down while still registered leaves the registration behind, and a later mapping at the same address then gets ``cudaHostRegister`` rc 712.""" for ptr in own_pinned: if not _unpin(ptr): logger.warning("ARENA: cudaHostUnregister failed for own " "segment %#x", ptr) own_pinned.clear() for name, (arena, view, pinned) in list(peers.items()): if pinned: if not _unpin(arena.ptr_len()[0]): logger.warning("ARENA: cudaHostUnregister failed for peer " "%s", name) peers[name] = (arena, view, 0) def _pin(ptr: int, nbytes: int) -> bool: """cudaHostRegister a mapped segment (idempotent). Returns success. GIL released for the duration (see ``_cudart``).""" if not torch.cuda.is_available(): return False try: lib = _cudart() except OSError as e: logger.warning("ARENA: cannot load libcudart (%s); copies fall back " "to pageable bandwidth", e) return False rc = lib.cudaHostRegister(ptr, nbytes, 0) if rc != 0: # Set by an already-registered range (accepted below) too. lib.cudaGetLastError() ok = rc in (0, _CUDA_HOST_ALREADY_REGISTERED) if not ok: logger.warning("cudaHostRegister(%#x, %d) failed rc=%d — copies fall " "back to pageable bandwidth", ptr, nbytes, rc) return ok def _gather(view, starts: list[int], nbytes: int, dst: np.ndarray, *, words_max_bytes: int) -> None: """``nbytes`` from each of ``starts`` in ``view``, back to back into ``dst``.""" if ( nbytes <= words_max_bytes and nbytes % 8 == 0 and len(view) % 8 == 0 and all(s % 8 == 0 for s in starts) ): words = np.frombuffer(view, dtype=np.int64) w = nbytes // 8 at = np.asarray(starts, dtype=np.int64) // 8 np.take(words, (at[:, None] + np.arange(w)).ravel(), out=dst.view(np.int64)) return seg = np.frombuffer(view, dtype=np.uint8) for i, s in enumerate(starts): dst[i * nbytes:(i + 1) * nbytes] = seg[s:s + nbytes]
[docs] class ArenaShmCommunicationManager(SharedMemoryCommunicationManager): """Tensor transport via the Rust shared-memory arena (``mstar_rust``). ``_arena`` is None when this entity has none of its own (see the module docstring): every send then spills to a per-uuid file. """ _namespace_file_dirs = ("/dev/shm",) # Staging writes the segment and offset onto the descriptor the store # holds, which routing may already have copied -- so every outgoing edge # has to be refreshed from the store before it is sent. See # ``TensorCommunicationManager.refresh_shm_placement``. stamps_shm_placement = True def __init__( self, my_entity_id: str, hostname: str, device: str, communicator: BaseCommunicator, shm_dir: str | None = None, enable_prof: bool = False, copy_workers: int = 1, ): super().__init__( my_entity_id=my_entity_id, hostname=hostname, device=device, communicator=communicator, shm_dir=shm_dir, enable_prof=enable_prof, ) from mstar_rust import SegmentedShmArena, ShmArena # A CPU consumer's reads (the API server's outputs) copy on these. self._host_copier = HostCopier(copy_workers) self._ShmArena = ShmArena supported = _arena_supported(device) segment_mb, max_segments, shm_total, shm_avail = ( _arena_sizing() if supported else (0, 0, None, None)) self._full_timeout_s = float( os.getenv("MSTAR_SHM_ARENA_FULL_TIMEOUT_S", "30")) self._pin_segments = ( os.getenv("MSTAR_SHM_ARENA_PIN", "1") == "1" and torch.cuda.is_available() and str(device) != "cpu" and supported ) # Pinned host memory is a system-wide resource (pages come out of the # OS's pageable pool), so it gets its own budget, distinct from the # segment cap. Segments past the budget stay unpinned — copies still # work, they just lose async overlap. Oversized dedicated segments # (single allocations larger than a segment) are never pinned: a # one-shot transfer doesn't amortize the registration cost. self._pin_budget = int( os.getenv("MSTAR_SHM_ARENA_PIN_MAX_MB", "4096")) << 20 # _read_many_from_arena's gather limits: the crossovers depend on the host self._gather_item_bytes = int( os.getenv("MSTAR_SHM_ARENA_GATHER_MAX_BYTES", "16384")) self._gather_words_bytes = int( os.getenv("MSTAR_SHM_ARENA_GATHER_WORDS_MAX_BYTES", "512")) self._pinned_bytes = 0 self._pin_budget_warned = False self._segment_bytes = segment_mb << 20 # Arena saturation spills to the per-uuid file transport (the old # protocol) instead of failing: bursty or oversized workloads degrade # to file-copy speed, matching the prior manager's "slower, never # fails" behavior. MSTAR_SHM_ARENA_SPILL=0 restores strict # backpressure + timeout. self._spill = os.getenv("MSTAR_SHM_ARENA_SPILL", "1") == "1" # Default 0: on a worker, TENSOR_RECEIVED ACKs (which free slots) # are processed by the SAME thread that would sit in this grace # wait, so waiting is pure dead time there — spill immediately. # Deployments where another thread drains the communicator (the # threaded api_server) can set a small grace to ride out bursts. self._spill_after_s = float( os.getenv("MSTAR_SHM_ARENA_SPILL_AFTER_S", "0")) self._frag_warned = False self._spill_warned = False # h2d completion watcher: turns a CUDA event into a real Future so # the worker's eventfd wakes the moment reads finish (no 10 ms tick). self._wake_q: queue.Queue | None = None self._wake_lock = threading.Lock() # Serializes pin accounting and peer-map insertion: _pin releases # the GIL (ctypes), so unlocked read-modify-write of _pinned_bytes # tears, and check-then-insert on _peer_segments can map+pin the # same segment twice (the loser leaking forever). self._pin_lock = threading.Lock() # Concurrent start_read_tensors calls (threaded api-server): used to # keep eviction from unmapping a segment another thread is copying # from before its future lands in `pending`. self._reads_active = 0 # Periodic occupancy/fragmentation logging, tied to --log-stats # (enable_prof) and time-gated. self._stats_interval_s = float( os.getenv("MSTAR_SHM_ARENA_STATS_INTERVAL_S", "60")) self._stats_last = 0.0 # CEILINGS ARE PER-ENTITY and multiply across a node: every entity # (workers + the api-server data worker) creates its own arena, so # node /dev/shm demand can reach # MAX_SEGMENTS x SEGMENT_MB x num_entities # and node pinned RAM approx PIN_MAX_MB x num_entities (a consumer # pins peer segments too, so one process's pinned bytes can exceed # its own arena). Check the static tmpfs ceiling NOW instead of # surfacing as ENOSPC on a growth mid-run. per_entity_max = (segment_mb << 20) * max_segments self._shm_total = shm_total if shm_total is not None: if per_entity_max > shm_total: raise RuntimeError( f"SHM arena ceiling for ONE entity " f"({per_entity_max >> 20} MiB = " f"MSTAR_SHM_ARENA_MAX_SEGMENTS x _SEGMENT_MB) exceeds " f"/dev/shm ({shm_total >> 20} MiB) — and every entity " f"multiplies this. Lower the knobs or grow tmpfs.") if per_entity_max > shm_avail: logger.warning( "ARENA: this entity's ceiling (%d MiB) exceeds current " "/dev/shm free space (%d MiB); ceilings are per-entity " "and multiply across workers — growth may hit ENOSPC " "under load", per_entity_max >> 20, shm_avail >> 20) try: phys = os.sysconf("SC_PHYS_PAGES") * os.sysconf("SC_PAGE_SIZE") except (ValueError, OSError): phys = None if (self._pin_segments and phys is not None and self._pin_budget > phys // 4): logger.warning( "ARENA: MSTAR_SHM_ARENA_PIN_MAX_MB (%d MiB) exceeds a " "quarter of physical RAM (%d MiB) FOR ONE ENTITY; pinned " "budgets multiply across entities and come out of the OS's " "pageable pool", self._pin_budget >> 20, phys >> 20) # INSTANCE-UNIQUE base name: a fixed per-entity name in the global # /dev/shm namespace collides across servers (a second server's # create() truncates the first's live segments — silent corruption) # and across users (permission-denied at startup). pid + random # token makes each instance's names unique; wire-compatibility is # free because consumers open whatever segment name the descriptor # carries. Under a deployment namespace the segments are named like # its tensor files, so its lock marks them live and the dead- # namespace sweep reclaims them; a pid cannot, since /proc is per # PID namespace and containers can share /dev/shm. Without one, the # pid in the name drives the orphan sweep below. import secrets _sweep_orphan_segments() ns = self._shm_namespace base = (f"mstar_{ns}_arena_{my_entity_id}_{secrets.token_hex(4)}" if ns else f"mstar_arena_{my_entity_id}_{os.getpid()}_" f"{secrets.token_hex(4)}") self._arena = None if not supported: logger.info( "ARENA: not used on %s (%s); this entity sends by per-uuid " "files and reads its peers' arenas", device, current_platform.name) elif not segment_mb: logger.warning( "ARENA: /dev/shm has %s MiB free, too little for a 16 MiB " "arena per entity and room for spill files; this entity sends " "by per-uuid files", "?" if shm_avail is None else shm_avail >> 20) else: try: self._arena = SegmentedShmArena.create( base, segment_mb << 20, max_segments) except (RuntimeError, OSError) as e: logger.warning( "ARENA: cannot create this entity's first segment (%s); " "its sends spill to per-uuid files", e) # Guaranteed exit-time unlink: weakref.finalize runs at interpreter # shutdown even when the manager is still referenced (the worker # case — no explicit cleanup path runs there, so the Rust Drop # never fires). The callback captures only the mutable name list, # which _sync_segments extends as the arena grows. self._own_segment_paths: list[str] = [] self._finalizer = weakref.finalize( self, _unlink_paths, self._own_segment_paths) # Producer-side segment views (memoryviews are stable: segments # never move or resize) + how many segments are already pinned. self._seg_views: list[memoryview] = [] # Index -> name, so staging never calls back into the arena for a # name it would only hand straight to the store. self._seg_names: list[str] = [] # The store we last named our segments to. The table lives in the # bookkeeper, so a store swapped in after construction starts empty # and has to be re-told -- otherwise placement cites an index it # cannot resolve. self._segments_named_to = None self._pinned_segments = 0 # Base pointers of own segments that are registered, for the # unregister finalizer below. self._own_pinned: list[int] = [] self._sync_segments() # uuid -> (segment_idx, offset) for sender-side reclaim. # (register_for_send receives the TensorPointerInfos directly and # stamps them in place — no side-table needed.) self._arena_locs: dict[int, tuple[int, int]] = {} # uuid -> stage time, for the TTL backstop: a request aborted after # staging but before every consumer ACKs defers reclaim forever # (cleanup_request waits for ACKs that will never come). A slot # older than the REQUEST timeout cannot have a legitimate reader — # the request is dead by contract — so freeing past a bound safely # above it cannot race a real consumer. Default OFF pending review # discussion; enable with MSTAR_SHM_ARENA_SLOT_TTL_S (recommend # >= 2x the request timeout). self._arena_ts: dict[int, float] = {} self._slot_ttl_s = float( os.getenv("MSTAR_SHM_ARENA_SLOT_TTL_S", "0")) self._ttl_reclaimed_total = 0 # Consumer-side: peer segment name -> (arena, memoryview, # pinned_nbytes) — pinned_nbytes 0 when the segment wasn't pinned. # Entries are EVICTED (unpin + unmap) once the backing file is gone # (producer finished or restarted): with instance-unique names a # restarting producer mints new names every generation, so a # never-evicting cache would grow mappings and pinned bytes without # bound on any long-lived consumer. self._peer_segments: dict[str, tuple[object, memoryview, int]] = {} self._peer_evict_last = 0.0 # Unregister before the arenas unmap (close(), or when the manager # is collected). Not at interpreter exit: the driver drops every # registration with the process. self._unpin_finalizer = weakref.finalize( self, _unpin_live, self._own_pinned, self._peer_segments) self._unpin_finalizer.atexit = False # -- segments -------------------------------------------------------- def _maybe_pin(self, ptr: int, nbytes: int) -> int: """Pin an own segment within budget; returns the bytes actually pinned (0 if skipped/failed). Runs under _pin_lock: _pin releases the GIL, so budget check + register + accounting must be one atomic unit, and close() must see the segment either unpinned or tracked.""" # Oversized dedicated segments ARE pinned (within budget): freed # segments are reused for later large tensors, so the registration # amortizes over the segment's lifetime, not one transfer. if not self._pin_segments: return 0 with self._pin_lock: if not self._pin_segments: return 0 pinned = self._pin_locked(ptr, nbytes) if pinned: self._own_pinned.append(ptr) return pinned def _pin_locked(self, ptr: int, nbytes: int) -> int: if self._pinned_bytes + nbytes > self._pin_budget: if not self._pin_budget_warned: logger.warning( "ARENA: pinned-memory budget reached (%d MiB, " "MSTAR_SHM_ARENA_PIN_MAX_MB); further segments stay " "unpinned — copies work but lose async overlap", self._pin_budget >> 20) self._pin_budget_warned = True return 0 if _pin(ptr, nbytes): self._pinned_bytes += nbytes self._pinned_segments += 1 return nbytes return 0 def _sync_segments(self) -> None: if self._arena is None: return grew = False old_len = len(self._seg_views) while len(self._seg_views) < self._arena.num_segments: i = len(self._seg_views) seg = self._arena.segment(i) name = self._arena.segment_name(i) self._own_segment_paths.append(f"/dev/shm/{name}") self._seg_names.append(name) self._seg_views.append(memoryview(seg)) self._maybe_pin(*seg.ptr_len()) grew = True if grew: # Once per segment ever created, so placement can cross as the # index the reserve already returned. self._name_segments_to_store(start_idx=old_len) total, free, largest = self._arena.stats() if (self._shm_total is not None and total > self._shm_total * 0.8): logger.warning( "ARENA: this entity's segments now total %d MiB — over " "80%% of /dev/shm (%d MiB). Oversized dedicated " "segments grow past the static ceiling; other entities " "multiply this further.", total >> 20, self._shm_total >> 20) logger.info( "ARENA: grew to %d segments (%d MiB total, %d MiB free, " "largest free block %d MiB, %d MiB pinned)", self._arena.num_segments, total >> 20, free >> 20, largest >> 20, self._pinned_bytes >> 20)
[docs] def stats_summary(self) -> dict: """Occupancy/fragmentation snapshot (named apart from the raw ``SegmentedShmArena.stats`` tuple). The fragmentation signature is `largest_free_block` collapsing while `free_bytes` stays high.""" arena = self._arena total, free, largest = arena.stats() if arena is not None else (0, 0, 0) return { "segments": arena.num_segments if arena is not None else 0, "total_bytes": total, "free_bytes": free, "largest_free_block": largest, "pinned_bytes": self._pinned_bytes, }
def _reclaim_expired(self) -> int: """TTL backstop for abort-orphaned slots (see _arena_ts). Returns the number of slots/files reclaimed.""" if not self._slot_ttl_s: return 0 now = time.monotonic() n = 0 for uuid, ts in list(self._arena_ts.items()): if now - ts < self._slot_ttl_s: continue self._arena_ts.pop(uuid, None) if (loc := self._arena_locs.pop(uuid, None)) is not None: self._arena.free(*loc) n += 1 if (path := self._shm_files.pop(uuid, None)) is not None: try: os.unlink(path) n += 1 except FileNotFoundError: pass if n: self._ttl_reclaimed_total += n logger.warning( "ARENA: TTL-reclaimed %d slot(s)/file(s) older than %.0fs " "(%d total) — requests aborted without consumer ACKs; " "the ACK path is leaking", n, self._slot_ttl_s, self._ttl_reclaimed_total) return n def _maybe_log_stats(self) -> None: """Under ``--log-stats`` (enable_prof), log the snapshot at most once per MSTAR_SHM_ARENA_STATS_INTERVAL_S so a long soak leaves an occupancy/fragmentation time series in the logs.""" if not self.enable_prof: return now = time.monotonic() if now - self._stats_last < self._stats_interval_s: return self._stats_last = now self._reclaim_expired() st = self.stats_summary() # live_slots/spill_files climbing while requests finish = reclaim # being deferred (e.g. aborts without ACKs) — the soak's leak canary. st["live_slots"] = len(self._arena_locs) st["spill_files"] = len(self._shm_files) logger.info("ARENA stats: %s", st) def _peer_view(self, segment_name: str) -> memoryview: entry = self._peer_segments.get(segment_name) if entry is None: with self._pin_lock: entry = self._peer_segments.get(segment_name) if entry is None: # lost the race: another thread mapped it arena = self._ShmArena.open(segment_name) pinned = (self._pin_locked(*arena.ptr_len()) if self._pin_segments else 0) entry = self._peer_segments[segment_name] = ( arena, memoryview(arena), pinned) return entry[1] def _evict_dead_peers(self) -> None: """Drop cached peer segments whose backing file is gone. Gated on `self.pending` being empty: an mmap must outlive any in-flight h2d copy that reads from it, and pending futures are exactly those copies. Time-gated to keep the existence checks off the hot path.""" now = time.monotonic() # _reads_active > 1: another thread may have queued an async H2D # copy whose future hasn't reached `pending` yet — unmapping under # it would be a use-after-free. Only the sole active reader evicts. if (self.pending or self._reads_active > 1 or now - self._peer_evict_last < 10.0): return self._peer_evict_last = now for name in list(self._peer_segments): if os.path.exists(f"/dev/shm/{name}"): continue with self._pin_lock: arena, view, pinned = self._peer_segments[name] if pinned: # Unregister BEFORE unmapping: tearing down a mapping # CUDA still holds registered leaves a dangling pinned # range. On failure keep the entry (retry next sweep) # so accounting stays truthful. ptr, _len = arena.ptr_len() if not _unpin(ptr): logger.warning( "ARENA: cudaHostUnregister failed for dead peer " "%s; keeping mapping until it succeeds", name) continue self._pinned_bytes -= pinned del self._peer_segments[name] view.release() logger.debug("ARENA: evicted dead peer segment %s " "(%d MiB pinned released)", name, pinned >> 20) # -- producer --------------------------------------------------------- def _reserve(self, nbytes: int) -> tuple[int, int] | None: """Reserve with layered degradation. At the segment cap: wait briefly for consumer ACKs to free space; then (default) return None so the caller SPILLS this tensor to the per-uuid file transport — slower, never fails, exactly the old manager's saturation behavior. MSTAR_SHM_ARENA_SPILL=0 keeps strict backpressure for the full timeout, then raises. Without an arena, every tensor spills.""" if self._arena is None: return None grace = self._spill_after_s if self._spill else self._full_timeout_s deadline = time.monotonic() + grace warned = False while True: try: seg, off = self._arena.reserve(max(nbytes, 1)) # Both the segment cap and a failed growth (no room in # /dev/shm for a new segment) land here as "full". except RuntimeError as e: if self._reclaim_expired(): continue # expired slots freed: retry the reserve total, free, largest = self._arena.stats() if free >= nbytes and not self._frag_warned: # The fragmentation signature: enough TOTAL free space, # but no contiguous block large enough. logger.warning( "ARENA: fragmentation — need %d bytes with %d free " "but largest free block is %d (of %d total). " "Consider larger MSTAR_SHM_ARENA_SEGMENT_MB.", nbytes, free, largest, total) self._frag_warned = True if time.monotonic() > deadline: if self._spill: if not self._spill_warned: logger.warning( "ARENA: spilling sends to the file " "transport (%s)", e) self._spill_warned = True return None raise RuntimeError( f"SHM arena full for >{self._full_timeout_s}s " f"({self._arena.num_segments} segments: {e}); raise " "MSTAR_SHM_ARENA_MAX_SEGMENTS / _SEGMENT_MB, free " "/dev/shm space, or check for consumers not " "ACKing") from None if not warned: logger.warning( "SHM arena at capacity; backpressuring sends until " "consumers ACK%s", " (then spilling to file)" if self._spill else "") warned = True time.sleep(0.002) continue self._sync_segments() return seg, off def _d2h_ctx(self): return ( torch.cuda.stream(self._d2h_stream) if self._d2h_stream is not None else _nullcontext() ) def _name_segments_to_store(self, start_idx: int = 0) -> None: """Tell the store what each segment index is called. Idempotent, and once per segment rather than once per tensor -- the whole point of placement crossing as an index. ``start_idx`` skips the segments already named, so a grow names only what it added; re-naming the whole list each grow is quadratic in segment count. It must slice as well as renumber -- enumerating the full list from ``start_idx`` would file every existing name under the wrong index.""" store = self.tensor_store for i, name in enumerate(self._seg_names[start_idx:], start=start_idx): store.register_shm_segment(i, name) self._segments_named_to = store def _stage_one( self, request_id: Rid, uuid: int, info_arg: TensorPointerInfo | None, placements: _Placements, ) -> bool: """Stage one tensor into the arena. Returns whether a D2H was queued. The caller owns the CUDA sync, the ``_d2h_ctx`` context and the trailing stream sync, so a batch pays for each of those once -- and the writeback of ``placements``, which is why they are collected here rather than stored one at a time. """ if self.tensor_store.is_registered(uuid): return False tensor = self._send_source(uuid) t0 = time.perf_counter() t = tensor.detach().contiguous() nbytes = t.numel() * t.element_size() loc = self._reserve(nbytes) if loc is not None and self.tensor_store.is_registered(uuid): # Lost a concurrent-duplicate race: another thread registered this # uuid while our reserve released the GIL. Return our slot instead # of orphaning it. self._arena.free(*loc) return False if loc is None: # Arena saturated: spill THIS tensor to the per-uuid file protocol # (infos keep shm_segment=None — the consumer falls back to the # file read for exactly those). data = _serialize_tensor(t) path = self._shm_path(self.my_entity_id, uuid) self._write_shm_file(path, data) self._shm_files[uuid] = path self._arena_ts[uuid] = time.monotonic() self.tensor_store.set_metadata(uuid, mem_registered=True) if self.enable_prof: self._record_tx(request_id, uuid, len(data), time.perf_counter() - t0) logger.debug("ARENA: spilled %s to %s (%d bytes)", uuid, path, len(data)) return False seg, off = loc queued = False try: if nbytes: flat = torch.frombuffer( self._seg_views[seg][off:off + nbytes], dtype=torch.uint8, ) # Async D2H into the pinned segment when a copy stream exists # (the caller's single sync covers the batch); blocking # otherwise, so the descriptor can never ship ahead of the bytes. if t.is_cuda: flat.view(t.dtype).reshape(t.shape).copy_( t, non_blocking=self._d2h_stream is not None) queued = True elif t.device.type == "cpu": # A stored host copy: one memcpy, nothing for the stream # sync to wait on. numpy, not Tensor.copy_: torch splits a # CPU copy of more than 32K elements over its intra-op # OpenMP pool, whose threads then spin on the cores the # worker's own threads need. np.copyto(flat.numpy(), t.reshape(-1).view(torch.uint8).numpy()) else: flat.view(t.dtype).reshape(t.shape).copy_(t) self._arena_locs[uuid] = (seg, off) self._arena_ts[uuid] = time.monotonic() except BaseException: # Anything that unwinds between reserve and the _arena_locs record # would orphan the slot forever (cleanup can only free what is # recorded). self._arena.free(seg, off) raise # A list index, not a call back into the arena: this used to mint a # Python str per tensor that the store then interned straight back # down to an id it already had. seg_name = self._seg_names[seg] # Still stamped in place when the caller handed one in: that contract # is relied on (test_descriptor_survives_register_for_send). The # uuid-driven path has no caller object and needs none. if info_arg is not None: info_arg.shm_segment = seg_name info_arg.shm_offset = off # The store must learn the segment, not just the caller's object. With # the Python bookkeeper those are the same object and this is a # re-assign; with the Rust one the descriptor was COPIED in, so without # this the stamp dies on a throwaway and the tensor ships with # shm_segment=None -- which the consumer reads as "spilled to a file" # and goes looking for a file that was never written. # # Only the two fields travel, not the descriptor: rebuilding one for # Python and marshalling it back costs ~3.5us per tensor to write two # integers the store already holds. The segment goes as its INDEX -- # the store learned the name once, at the grow. placements.add(uuid, seg, off) self.tensor_store.set_metadata(uuid, mem_registered=True) if self.enable_prof: self._record_tx(request_id, uuid, nbytes, time.perf_counter() - t0) logger.debug("ARENA: staged %s at %s+%d (%d bytes)", uuid, seg_name, off, nbytes) return queued def _write_back(self, placements: _Placements): """One crossing for the batch, not one per tensor.""" if not placements.uuids: return if self.tensor_store is not self._segments_named_to: # Swapped store: it has never heard of our segments, and an index # it cannot resolve is an error it would raise here. self._name_segments_to_store() # The columns go straight across, already in the callee's layout. self.tensor_store.set_shm_placement( placements.uuids, placements.segment_idxs, placements.offsets, )
[docs] def register_for_send( self, request_id: Rid, tensor_infos: list[TensorPointerInfo], skip_cuda_sync: bool = False, ): if not skip_cuda_sync and self._on_cuda: torch.cuda.default_stream().synchronize() queued = False placements = _Placements.empty() self._maybe_log_stats() with self._d2h_ctx(): for info_arg in tensor_infos: queued |= self._stage_one( request_id, info_arg.uuid, info_arg, placements) self._write_back(placements) if queued and self._d2h_stream is not None: # The control message referencing these bytes is sent after we # return; the consumer must never observe a partial copy. self._d2h_stream.synchronize()
[docs] def register_for_send_uuids( self, per_request: ParallelList[Rid, list[int]], skip_cuda_sync: bool = False, ): """Uuid-driven staging: no descriptor is rebuilt to be read for its uuid, and placement goes back as two columns rather than a whole descriptor. The whole batch stages inside one stream context and syncs once at the end, rather than one host-blocking sync per request.""" if not skip_cuda_sync and self._on_cuda: torch.cuda.default_stream().synchronize() queued = False placements = _Placements.empty() self._maybe_log_stats() with self._d2h_ctx(): for request_id, uuids in per_request: for uuid in uuids: queued |= self._stage_one(request_id, uuid, None, placements) self._write_back(placements) if queued and self._d2h_stream is not None: self._d2h_stream.synchronize()
# -- consumer ---------------------------------------------------------
[docs] def start_read_tensors( self, request_id: Rid, graph_edges: list[GraphEdge], graph_walk: str | None = None, ): return self._start_reads([(request_id, graph_edges)], graph_walk)
[docs] def start_read_tensors_multi(self, reads): """One stream context, peer sweep, event and wake for every request's reads, not one each.""" return self._start_reads(reads, None)
def _start_reads(self, requests, graph_walk): # Increment races are benign here: a torn count can only make # eviction OVER-cautious (skip a sweep), never unsafe. self._reads_active += 1 try: if not any(e.tensor_info for _rid, edges in requests for e in edges): # signal-only edges: no stream context to pay for, but the # (time-gated) sweep of dead peers' segments still runs here self._evict_dead_peers() return [] return self._start_read_tensors(requests, graph_walk) finally: self._reads_active -= 1 def _start_read_tensors(self, requests, graph_walk): self._evict_dead_peers() h2d_did_work = False stats = self.transfer_stats # one per edge read; the future is filled in once every copy is queued reads: list[FutureAndPointers] = [] ctx = ( torch.cuda.stream(self._h2d_stream) if self._h2d_stream is not None else _nullcontext() ) # arena items are read and stored together after the loop; one met # again before then takes the extra reference after the put staged: list[tuple] = [] taken: dict[int, TensorPointerInfo] = {} again: list[int] = [] t0 = time.perf_counter() with ctx: for request_id, graph_edges in requests: for graph_edge in graph_edges: if len(graph_edge.tensor_info) == 0: continue fp = FutureAndPointers( future=None, graph_edges=[graph_edge], request_id=request_id, ) for info in graph_edge.tensor_info: if info.source_entity == self.my_entity_id: self._slice_existing_tensor( request_id=request_id, name=graph_edge.name, next_node=graph_edge.next_node, graph_walk=graph_walk, info=info, ) self.tensor_store.increment_ref(info.uuid, 1) continue producer_uuid = info.uuid if self._take_cached_read(request_id, info, taken, again): continue if info.shm_segment is None: # Spilled at the producer (arena saturated): read the # per-uuid file, the old protocol's path. path = self._shm_path(info.source_entity, producer_uuid) with open(path, "rb") as f: f.seek(info.offset) data = f.read(info.nbytes) tensor = _deserialize_tensor( data, self.device, tensor_info=info) h2d_did_work = h2d_did_work or tensor.numel() > 0 self.tensor_store.put_tensor( request_id, info.uuid, tensor, info) self.tensor_store.set_metadata(info.uuid, mem_registered=False) self.tensor_store.increment_ref(info.uuid, 2) else: staged.append((request_id, info)) taken[info.uuid] = info if stats is not None: fp.count_read(info) reads.append(fp) if staged: infos = [info for _, info in staged] uuids = [info.uuid for info in infos] tensors = self._read_many_from_arena(infos) h2d_did_work = h2d_did_work or any(t.numel() > 0 for t in tensors) self.tensor_store.put_tensor_batch_multi( [rid for rid, _ in staged], uuids, tensors, infos, ) # +1 transit (released by get_ready_tensors), +1 usage # (released by _cleanup_consumed_inputs). self.tensor_store.increment_ref_batch_uniform(uuids, 2) if again: self.tensor_store.increment_ref_batch_uniform(again, 1) # profiling attributes the call's time to its reads evenly rx = (time.perf_counter() - t0) / max(len(reads), 1) for fp in reads: fp.rx_time = rx future = None if h2d_did_work and self._h2d_stream is not None: # Downstream kernels see the data (device-side ordering only). torch.cuda.default_stream(self.device).wait_stream( self._h2d_stream) # The producer reclaims the slot when an edge is ACKed, and the # source is its live mapping — so the edge must not report ready # until its copies have completed (the file path's f.read() made # this implicit). One event covers the batch: all copies were # queued on the h2d stream in program order. get_ready_tensors # polls it — no host block here. future = _CudaEventFuture(self._h2d_stream) for fp in reads: fp.future = future self.pending.extend(reads) if future is None: return [] # A real Future for the worker's eventfd (EventWakeup.register_ # futures needs add_done_callback): completed by the watcher thread # the moment the h2d copies finish, so an otherwise-idle worker # re-checks get_ready_tensors immediately instead of on its next # poll tick. return [self._wake_when_done(future)] def _wake_when_done(self, cuda_future) -> Future: with self._wake_lock: # two callers must not race the create if self._wake_q is None: self._wake_q = queue.Queue() # staticmethod target closing over ONLY the queue: a bound # method would pin the whole manager (and its arena — so # segments never unlink) for the daemon thread's lifetime. Thread( target=self._watch_wakes, args=(self._wake_q,), daemon=True, name=f"arena-h2d-wake-{self.my_entity_id}").start() fut: Future = Future() self._wake_q.put((cuda_future, fut)) return fut @staticmethod def _watch_wakes(q: queue.Queue) -> None: # Events are queued in stream order, so sequential waits are exact. # None is the close() sentinel. while True: item = q.get() if item is None: return cuda_future, fut = item try: cuda_future.result() # event.synchronize (GIL released) fut.set_result(None) except Exception: # noqa: BLE001 — wake best-effort; # a cancelled/already-resolved future must not kill the # watcher (its death silently downgrades every later wake # to the poll tick and grows the queue unboundedly). if not fut.done(): try: fut.set_result(None) except Exception: # noqa: BLE001 pass # Small items of one shape, dtype and segment (a step's streamed tokens) # are gathered on the host into one pinned buffer, copied once and split # on the device: one copy call instead of a copy per item (~7 us each). # The default limits were measured on an H200 host, reading k items of n # bytes: the gather wins from k=2 up to n=16 KB and breaks even at 64 KB. # Up to 512 B an index of 8-byte words is fastest; above it, one slice # copy per item. def _read_many_from_arena(self, infos: list[TensorPointerInfo]) -> list[torch.Tensor]: out: list[torch.Tensor | None] = [None] * len(infos) if self.device != "cpu": groups: dict[tuple, list[int]] = {} for k, info in enumerate(infos): if 0 < info.nbytes <= self._gather_item_bytes: key = (info.shm_segment, info.nbytes, info.dtype, tuple(info.dims)) groups.setdefault(key, []).append(k) for (segment, nbytes, dtype, dims), ks in groups.items(): if len(ks) < 2: continue starts = [infos[k].shm_offset + infos[k].offset for k in ks] # pinned, so the copy is a true async DMA; the caching host # allocator holds the block until the copy is done host = torch.empty(len(ks) * nbytes, dtype=torch.uint8, pin_memory=True) _gather(self._peer_view(segment), starts, nbytes, host.numpy(), words_max_bytes=self._gather_words_bytes) rows = host.to(self.device, non_blocking=True).view(dtype).reshape(len(ks), *dims) for k, t in zip(ks, rows.unbind(0), strict=True): out[k] = t return [t if t is not None else self._read_from_arena(i) for t, i in zip(out, infos, strict=True)] def _read_from_arena(self, info: TensorPointerInfo) -> torch.Tensor: if info.nbytes == 0: t = torch.empty( info.dims, dtype=info.dtype) return t.to(self.device) if self.device != "cpu" else t view = self._peer_view(info.shm_segment) start = info.shm_offset + info.offset # offset = TP-shard read offset if self.device == "cpu": # A CPU consumer owns a copy past reclaim. clone() would split it # over torch's intra-op pool, sized for small ops; the copier keeps # an image one memcpy and slices a video over threads of its own. flat = self._host_copier.copy( np.frombuffer(view, dtype=np.uint8, count=info.nbytes, offset=start)) return flat.view(info.dtype).reshape(info.dims) flat = torch.frombuffer( view[start:start + info.nbytes], dtype=torch.uint8) t = flat.view(info.dtype).reshape(info.dims) # Async only when the h2d stream's event gates the ACK: with no copy # stream (XPU) nothing would wait for the copy before the slot is freed. return t.to(self.device, non_blocking=self._h2d_stream is not None) # -- reclaim ----------------------------------------------------------
[docs] def close(self) -> None: """Stop the wake watcher and unregister every pinned segment (the segments themselves unmap with the arena's Drop once the manager is garbage collected). Segments mapped after this stay unpinned.""" with self._wake_lock: if self._wake_q is not None: self._wake_q.put(None) self._wake_q = None with self._pin_lock: self._pin_segments = False self._unpin_finalizer() self._pinned_bytes = 0 self._pinned_segments = 0
[docs] def cleanup_collectable( self, collectable: list[int], registered: list[bool], ): """``_cleanup_by_uuid`` for a batch, inlined: a decode step frees one tensor per request here, and the three-level call chain per uuid was most of the cost. Same steps in the same order as the per-uuid form.""" if not collectable: return del registered # no transfer engine to unregister from store = self.tensor_store store.mark_forgotten(collectable) shard_dims = self.uuid_to_shard_dim edge_names = self.uuid_to_edge_name arena_ts = self._arena_ts arena_locs = self._arena_locs shm_files = self._shm_files present = store.check_uuid_presence remove = store.remove_tensor for uuid in collectable: try: shard_dims.pop(uuid, None) edge_names.pop(uuid, None) if present(uuid): remove(uuid) else: logger.warning( "Trying to cleanup tensor %s, but uuid not found", uuid, ) arena_ts.pop(uuid, None) if (loc := arena_locs.pop(uuid, None)) is not None: self._arena.free(*loc) if (path := shm_files.pop(uuid, None)) is not None: try: os.unlink(path) except FileNotFoundError: pass except Exception as e: logger.error( "Error cleaning up tensor uuid %d: %s, skipping.", uuid, e, )
def _cleanup_by_uuid(self, uuid: int, registered: bool | None = None): # Grandparent cleanup (refcounts): skip the file manager's unlink. super(SharedMemoryCommunicationManager, self)._cleanup_by_uuid( uuid, registered, ) self._arena_ts.pop(uuid, None) if (loc := self._arena_locs.pop(uuid, None)) is not None: self._arena.free(*loc) logger.debug("ARENA: freed %s at %s", uuid, loc) if (path := self._shm_files.pop(uuid, None)) is not None: try: os.unlink(path) # spilled tensor: reclaim the file except FileNotFoundError: pass if not self.tensor_store.check_uuid_presence(uuid): return self.tensor_store.remove_tensor(uuid)