diff --git a/atom/ec_transfer/__init__.py b/atom/ec_transfer/__init__.py new file mode 100644 index 00000000000..210cafc52ec --- /dev/null +++ b/atom/ec_transfer/__init__.py @@ -0,0 +1,14 @@ +# SPDX-License-Identifier: MIT +# Copyright (C) 2026, Advanced Micro Devices, Inc. All rights reserved. +# Copyright (c) 2026 ATOM Project Contributors +"""Image embedding transfer from an encoder server to prefill (E/P/D).""" + +from atom.ec_transfer.base import ( + EcReader, + EcStoreFull, + EcWriter, + create_reader, + create_writer, +) + +__all__ = ["EcReader", "EcStoreFull", "EcWriter", "create_reader", "create_writer"] diff --git a/atom/ec_transfer/base.py b/atom/ec_transfer/base.py new file mode 100644 index 00000000000..6c283eb0ce1 --- /dev/null +++ b/atom/ec_transfer/base.py @@ -0,0 +1,98 @@ +# SPDX-License-Identifier: MIT +# Copyright (C) 2026, Advanced Micro Devices, Inc. All rights reserved. +# Copyright (c) 2026 ATOM Project Contributors +"""The interface image embeddings move from an encoder (E) to prefill (P) by. + +E's ``EcWriter.put`` stores a request's embedding rows and returns a handle; +the handle travels to P inside the request as ``ec_transfer_params``, and P's +``EcReader.get`` returns the rows, or None when P must run its own vision +tower. ATOMesh and the API carry the handle without reading it. + +A handle is a JSON object. Every backend fills the same top-level fields and +keeps its own under its name:: + + {"transport": "mooncake", "key": , "rows": 4, + "dtype": "bfloat16", "mooncake": {...}} +""" + +from __future__ import annotations + +from typing import Any, Protocol + +import torch + + +class EcStoreFull(RuntimeError): + """E has no room for the rows; the request goes on without a handle.""" + + +class EcWriter(Protocol): + def put(self, key: int, rows: torch.Tensor) -> dict[str, Any]: + """Store ``rows`` under ``key`` and return the handle P reads them by. + Raises ``EcStoreFull`` when there is no room.""" + ... + + +class EcReader(Protocol): + def get( + self, handle: dict[str, Any], key: int, dtype: torch.dtype + ) -> torch.Tensor | None: + """The rows ``handle`` names, or None if they cannot be read, are not + ``key``'s or not ``dtype``: P then encodes the images itself.""" + ... + + +def dtype_name(dtype: torch.dtype) -> str: + return str(dtype).removeprefix("torch.") + + +def handle_mismatch( + handle: Any, transport: str, key: int, dtype: torch.dtype +) -> str | None: + """Why ``handle``'s common fields do not name ``key``'s rows in ``dtype`` + on ``transport``, or None when they do. A handle from elsewhere may be + malformed: never raise.""" + if not isinstance(handle, dict): + return "malformed handle" + if handle.get("transport") != transport: + return f"transport {handle.get('transport')!r} is not {transport!r}" + if handle.get("key") != key: + return "key differs from this request's" + if handle.get("dtype") != dtype_name(dtype): + return f"stored as {handle.get('dtype')!r}, read as {dtype_name(dtype)!r}" + rows = handle.get("rows") + if ( + type(rows) is not int + or rows <= 0 + or not isinstance(handle.get(transport), dict) + ): + return "malformed handle" + return None + + +def _backends() -> dict[str, tuple[type, type]]: + # Imported on use: a backend's library is needed only where it runs. + from atom.ec_transfer.mooncake import MooncakeEcReader, MooncakeEcWriter + + return {"mooncake": (MooncakeEcWriter, MooncakeEcReader)} + + +def create_writer( + transport: str, size_bytes: int, device: torch.device | str, **options: Any +) -> EcWriter: + """E's writer on ``transport``, holding up to ``size_bytes``.""" + backend = _backends().get(transport) + if backend is None: + raise ValueError(f"unknown image embedding transport {transport!r}") + return backend[0](size_bytes, device, **options) + + +def create_reader( + transport: str, size_bytes: int, device: torch.device | str, **options: Any +) -> EcReader: + """P's reader on ``transport``. Raises when the transport is unknown or + cannot start here; the caller then encodes images itself.""" + backend = _backends().get(transport) + if backend is None: + raise ValueError(f"unknown image embedding transport {transport!r}") + return backend[1](size_bytes, device, **options) diff --git a/atom/ec_transfer/mooncake.py b/atom/ec_transfer/mooncake.py new file mode 100644 index 00000000000..fc391e79cdb --- /dev/null +++ b/atom/ec_transfer/mooncake.py @@ -0,0 +1,329 @@ +# SPDX-License-Identifier: MIT +# Copyright (C) 2026, Advanced Micro Devices, Inc. All rights reserved. +# Copyright (c) 2026 ATOM Project Contributors +"""The Mooncake image embedding transfer: P pulls E's rows over RDMA. + +E registers one region with a Mooncake TransferEngine: a slot table, then a +pool of rows. Each entry's rows sit in the pool, and its slot holds +``(generation, address, length, ack)``; rows never overlap a slot. E answers +with a handle naming the rows and the slot, and P reads the rows, then the +slot, with ``transfer_sync_read``. A slot whose three values differ from the +handle's means the rows may have been given up or overwritten, and P encodes +the images itself. + +E reuses pool space and slots oldest-first, and only once an entry's lease +has expired. Before writing over an entry it zeroes the entry's slot, and it +writes a new entry's slot after its rows. Generations only grow, so a slot +never matches a handle given out for another entry. ``ack`` is written 0 and +reserved for P to acknowledge a read, so that E can reclaim the entry before +its lease ends. + +Neither ``MooncakeEcWriter`` nor ``MooncakeEcReader`` locks: each is used by +one thread at a time (E's encoder thread puts, P's model runner reads). +""" + +from __future__ import annotations + +import logging +import os +import time +from collections import Counter, deque +from collections.abc import Callable +from dataclasses import dataclass +from typing import Any + +import torch + +from atom.ec_transfer.base import EcStoreFull, dtype_name, handle_mismatch +from atom.utils import envs, mooncake_hca +from atom.utils.network import get_ip +from atom.utils.pci_topology import gpu_pci_bdf + +logger = logging.getLogger("atom") + +try: + from mooncake.engine import TransferEngine + + MOONCAKE_AVAILABLE = True +except ImportError: + MOONCAKE_AVAILABLE = False + +TRANSPORT = "mooncake" +DEFAULT_PROTOCOL = "rdma" +_SLOT_FIELDS = 4 # generation, address, length, ack: int64 each +_SLOT = _SLOT_FIELDS * 8 # bytes of a slot +_ALIGN = 64 # entry start alignment in the pool +# One slot per this many pool bytes: an entry is at least one image's rows +# (hundreds of KiB), so space runs out before slots do; the table is 1/2048 +# of the region. +BYTES_PER_SLOT = 64 << 10 + + +def _open_engine( + device: torch.device, + protocol: str, + ib_device: str = "", + *, + enable_alternate_hca: bool = False, + hca_count: int = 8, +) -> tuple[Any, str]: + """A TransferEngine on the HCAs ``mooncake_hca`` picks, and its session. + ``ib_device`` names them; else ``ATOM_MOONCAKE_IB_DEVICE``; else the + HCA on the GPU's PCIe switch.""" + if not MOONCAKE_AVAILABLE: + raise RuntimeError( + "Mooncake is not installed; image embedding transport needs it" + ) + if envs.ATOM_MOONCAKE_MATCHED_RAILS: + logger.warning( + "ATOM_MOONCAKE_MATCHED_RAILS is set, but image embedding transport " + "does not pick a matched rail; on a rail-isolated fabric its reads " + "may fail and P encodes the images itself" + ) + configured = ib_device or envs.ATOM_MOONCAKE_IB_DEVICE + gpu_bdf = None + if protocol.strip().lower() != "tcp" and not configured and device.type == "cuda": + # The GPU this engine's memory is on, whatever *_VISIBLE_DEVICES masks it. + gpu_bdf = gpu_pci_bdf(device.index or 0) + devices = mooncake_hca.ib_device_filter( + protocol, + configured, + gpu_bdf, + enable_alternate_hca=enable_alternate_hca, + hca_count=hca_count, + ) + mooncake_hca.configure_transport(protocol) + ip = get_ip() + engine = TransferEngine() + ret = engine.initialize(ip, "P2PHANDSHAKE", protocol, devices) + if ret != 0: + raise RuntimeError( + f"Mooncake TransferEngine.initialize() failed (ret={ret}) on ip={ip}, " + f"protocol={protocol}, ib_device={devices}" + ) + return engine, f"{ip}:{engine.get_rpc_port()}" + + +def _register(engine: Any, buf: torch.Tensor) -> None: + ret = engine.register_memory(buf.data_ptr(), buf.numel()) + if ret != 0: + raise RuntimeError(f"Mooncake register_memory failed (ret={ret})") + + +def _sync(buf: torch.Tensor) -> None: + # A remote read sees GPU memory only once the stream that wrote it is done. + if buf.is_cuda: + torch.cuda.current_stream(buf.device).synchronize() + + +def _positive_int(value: Any) -> bool: + return type(value) is int and value > 0 + + +@dataclass +class _Entry: + start: int + end: int + slot: int + created: float + + +def default_slots(size_bytes: int) -> int: + """Slots for a region of ``size_bytes``: one per ``BYTES_PER_SLOT``.""" + return max(1, size_bytes // BYTES_PER_SLOT) + + +def slot_table_bytes(slots: int) -> int: + """Bytes the table of ``slots`` takes at the front of E's region.""" + return -(-slots * _SLOT // _ALIGN) * _ALIGN + + +class MooncakeEcWriter: + """E's registered region of ``size_bytes``: a slot table, then a pool that + stores rows under a key for P to read. ``slots`` defaults to one per + ``BYTES_PER_SLOT`` of the region.""" + + def __init__( + self, + size_bytes: int, + device: torch.device | str, + *, + protocol: str = DEFAULT_PROTOCOL, + slots: int | None = None, + clock: Callable[[], float] = time.monotonic, + ) -> None: + if slots is None: + slots = default_slots(size_bytes) + table = slot_table_bytes(slots) + if table >= size_bytes: + raise ValueError( + f"a {size_bytes} byte region leaves no pool after {slots} slots" + ) + # One registration of exactly size_bytes (E sizes it in whole GiB): + # the slot table, then the pool. + self._region = torch.zeros(size_bytes, dtype=torch.uint8, device=device) + self._slots = self._region[: slots * _SLOT].view(torch.int64).view(slots, -1) + self._buf = self._region[table:] + self._engine, self.session = _open_engine(self._region.device, protocol) + _register(self._engine, self._region) + self._lease_s = envs.ATOM_EC_LEASE_S + self._clock = clock + self._entries: deque[_Entry] = deque() + self._free_slots: deque[int] = deque(range(slots)) + # A random start: a restarted E never reissues a past generation. + self._generation = int.from_bytes(os.urandom(6), "little") + 1 + + def _slot_address(self, slot: int) -> int: + return self._region.data_ptr() + slot * _SLOT + + def _place(self, need: int) -> tuple[int, int]: + """Start of ``need`` free bytes and a free slot, evicting expired + entries oldest-first.""" + if need > self._buf.numel(): + raise EcStoreFull( + f"{need} bytes of embeddings exceed the {self._buf.numel()} byte pool" + ) + start = self._entries[-1].end if self._entries else 0 + if start + need > self._buf.numel(): + start = 0 + end = start + need + now = self._clock() + victims = [] + while not self._free_slots or any( + e.start < end and start < e.end for e in self._entries + ): + oldest = self._entries[0] + if now - oldest.created < self._lease_s: + self._entries.extendleft(reversed(victims)) + for e in victims: + self._free_slots.remove(e.slot) + raise EcStoreFull( + f"pool of {self._buf.numel()} bytes and " + f"{len(self._slots)} slots is full: every entry in the way " + f"is inside its {self._lease_s} s lease" + ) + victims.append(self._entries.popleft()) + self._free_slots.append(victims[-1].slot) + if victims: + for e in victims: + self._slots[e.slot].zero_() + _sync(self._region) + return start, self._free_slots.popleft() + + def put(self, key: int, rows: torch.Tensor) -> dict[str, Any]: + """Store ``rows`` and return the handle P reads them by. + Raises ``EcStoreFull`` when no space or slot is past its lease.""" + payload = rows.contiguous().view(-1).view(torch.uint8) + need = -(-payload.numel() // _ALIGN) * _ALIGN + start, slot = self._place(need) + self._generation += 1 + address = self._buf.data_ptr() + start + self._buf[start : start + payload.numel()].copy_(payload) + # The rows, then their slot: a slot P reads as matching names rows + # already written. Both land before the handle leaves E. + self._slots[slot].copy_( + torch.tensor([self._generation, address, payload.numel(), 0]) + ) + _sync(self._region) + self._entries.append(_Entry(start, start + need, slot, self._clock())) + return { + "transport": TRANSPORT, + "key": key, + "rows": rows.shape[0], + "dtype": dtype_name(rows.dtype), + TRANSPORT: { + "session": self.session, + "address": address, + "length": payload.numel(), + "generation": self._generation, + "slot": self._slot_address(slot), + }, + } + + +class MooncakeEcReader: + """P's side: reads rows from E's pool into a registered buffer. + + ``fallbacks`` counts the reads that returned None, by reason; each is + logged with its reason and the running counts.""" + + def __init__( + self, + size_bytes: int, + device: torch.device | str, + *, + protocol: str = DEFAULT_PROTOCOL, + kv_transfer_config: dict[str, Any] | None = None, + ) -> None: + """``kv_transfer_config``: this server's, whose ``ib_device``, + ``ib_enable_alternate_hca`` and ``ib_hca_count`` the reader's engine + takes as the KV connector's does.""" + kv = kv_transfer_config or {} + # The reread slot, then the rows. + self._buf = torch.zeros(size_bytes + _SLOT, dtype=torch.uint8, device=device) + self._engine, _ = _open_engine( + self._buf.device, + protocol, + kv.get("ib_device", ""), + enable_alternate_hca=bool(kv.get("ib_enable_alternate_hca", False)), + hca_count=int(kv.get("ib_hca_count", 8)), + ) + _register(self._engine, self._buf) + self.fallbacks: Counter[str] = Counter() + + def _fallback(self, reason: str, session: Any = None) -> None: + self.fallbacks[reason] += 1 + logger.warning( + "Image embeddings from %s unusable: %s; running the vision tower " + "(fallbacks so far: %s)", + session, + reason, + dict(self.fallbacks), + ) + + def get( + self, handle: dict[str, Any], key: int, dtype: torch.dtype + ) -> torch.Tensor | None: + """The rows E stored for ``key``, or None if P must encode itself.""" + reason = handle_mismatch(handle, TRANSPORT, key, dtype) + if reason is not None: + self._fallback(reason) + return None + where = handle[TRANSPORT] + session = where.get("session") + address, length = where.get("address"), where.get("length") + generation, slot = where.get("generation"), where.get("slot") + # A generation of 0 would match a given-up or never-written slot. + if not ( + isinstance(session, str) + and _positive_int(address) + and _positive_int(generation) + and _positive_int(length) + and _positive_int(slot) + and length % (handle["rows"] * dtype.itemsize) == 0 + ): + self._fallback("malformed handle", session) + return None + if length > self._buf.numel() - _SLOT: + self._fallback( + f"{length} bytes exceed the {self._buf.numel() - _SLOT} byte " + "read buffer", + session, + ) + return None + # Work queued on this buffer (its zero fill, the previous read's + # clone) must finish before the NIC writes into it. + _sync(self._buf) + ptr = self._buf.data_ptr() + ret = self._engine.transfer_sync_read(session, ptr + _SLOT, address, length) + if ret == 0: + ret = self._engine.transfer_sync_read(session, ptr, slot, _SLOT) + if ret != 0: + self._fallback(f"read failed (ret={ret})", session) + return None + seen = self._buf[:_SLOT].view(torch.int64).tolist() + if seen[:3] != [generation, address, length]: + self._fallback("entry given up or reused", session) + return None + rows = self._buf[_SLOT : _SLOT + length].view(dtype) + return rows.view(handle["rows"], -1).clone() diff --git a/atom/kv_transfer/disaggregation/mooncake/mooncake_connector.py b/atom/kv_transfer/disaggregation/mooncake/mooncake_connector.py index 2a3c2043468..51bcfdc3141 100644 --- a/atom/kv_transfer/disaggregation/mooncake/mooncake_connector.py +++ b/atom/kv_transfer/disaggregation/mooncake/mooncake_connector.py @@ -20,7 +20,6 @@ from collections import OrderedDict, deque from concurrent.futures import ThreadPoolExecutor from dataclasses import asdict, astuple, dataclass, field -from pathlib import Path from typing import Any import msgpack @@ -104,11 +103,11 @@ pair_units, produced_no_handoff, ) -from atom.kv_transfer.offload.mooncake_store.nic import gpu_pci_bdf, rail_rdma_device from atom.model_engine.sequence import Sequence, SequenceStatus from atom.models.utils import get_pp_indices -from atom.utils import envs, get_open_port, make_zmq_path, zmq_socket_ctx +from atom.utils import envs, get_open_port, make_zmq_path, mooncake_hca, zmq_socket_ctx from atom.utils.network import get_ip +from atom.utils.pci_topology import gpu_pci_bdf logger = logging.getLogger("atom") @@ -157,7 +156,6 @@ # Requests whose ready event aged out are remembered up to this many, oldest # dropped first, so a late transfer still finds that its prefill is complete. KV_CACHE_READY_EXPIRED_MAX = 1 << 16 -_IB_SYSFS_ROOT = Path("/sys/class/infiniband") class SlotPool: @@ -248,67 +246,6 @@ def _swa_ring_ids(seq) -> list[int]: return [int(slot)] if slot is not None and slot >= 0 else [] -def _ib_device_exists(device_name: str) -> bool: - return (_IB_SYSFS_ROOT / device_name).exists() - - -def _auto_select_ib_device(gpu_bdf: str) -> str: - """The ACTIVE HCA behind the GPU's PCIe switch (HIP's order is not PCI order).""" - try: - return rail_rdma_device(gpu_bdf) - except ValueError as exc: - raise ValueError(f"{exc}; set ib_device or ATOM_MOONCAKE_IB_DEVICE") from None - - -def _numbered_ib_device(index: int) -> str: - # Older environments expose HCAs as rdmaN. Spur MI350 fabric exposes them - # as ionic_N, so try ionic_N only when rdmaN is not present. - rdma_device = f"rdma{index}" - if _ib_device_exists(rdma_device): - return rdma_device - ionic_device = f"ionic_{index}" - if _ib_device_exists(ionic_device): - return ionic_device - return rdma_device - - -def _parse_ib_devices(configured_devices: str) -> list[str]: - """Normalize a comma-separated Mooncake RDMA device filter.""" - return list( - dict.fromkeys( - device.strip() for device in configured_devices.split(",") if device.strip() - ) - ) - - -def _select_ib_devices( - protocol: str, - configured_devices: str, - gpu_bdf: str | None, - *, - enable_alternate_hca: bool = False, - hca_count: int = 8, -) -> list[str]: - """Resolve the HCAs on which Mooncake registers this rank's GPU memory.""" - if protocol.strip().lower() == "tcp": - return [] - if configured_devices: - return _parse_ib_devices(configured_devices) - if gpu_bdf is None: - raise ValueError("the GPU's PCI address is required for RDMA device selection") - - primary = _auto_select_ib_device(gpu_bdf) - devices = [primary] - if enable_alternate_hca: - if hca_count <= 0: - raise ValueError("ib_hca_count must be a positive integer") - for idx in range(hca_count): - device = _numbered_ib_device(idx) - if device not in devices and _ib_device_exists(device): - devices.append(device) - return devices - - def _discover_active_matched_rails(primary_device: str) -> list[str]: """Discover active HCAs in the primary's numbered device-name family.""" family = re.fullmatch(r"(.*\D)(\d+)", primary_device) @@ -319,10 +256,10 @@ def _discover_active_matched_rails(primary_device: str) -> list[str]: ) pattern = re.compile(re.escape(family[1]) + r"(\d+)") try: - devices = list(_IB_SYSFS_ROOT.iterdir()) + devices = list(mooncake_hca.IB_SYSFS_ROOT.iterdir()) except OSError as exc: raise ValueError( - f"Cannot discover RDMA HCAs in {_IB_SYSFS_ROOT}; " + f"Cannot discover RDMA HCAs in {mooncake_hca.IB_SYSFS_ROOT}; " "set ATOM_MOONCAKE_MATCHED_RAILS to an explicit HCA list" ) from exc @@ -368,7 +305,7 @@ def _resolve_matched_rails( ) rails = _discover_active_matched_rails(ib_devices[0]) else: - rails = _parse_ib_devices(value) + rails = mooncake_hca.parse_ib_devices(value) _validate_matched_rails(protocol, ib_devices, rails) return rails @@ -386,38 +323,13 @@ def _validate_matched_rails( "disable ib_enable_alternate_hca and use at most one ib_device" ) if ib_devices[0] not in matched_rails or any( - not _ib_device_exists(device) for device in matched_rails + not mooncake_hca.ib_device_exists(device) for device in matched_rails ): raise ValueError( "Matched rails must name existing local HCAs including the primary HCA" ) -def _select_ib_device( - protocol: str, configured_device: str, gpu_bdf: str | None -) -> str: - """Resolve the Mooncake device filter without enabling RDMA for TCP. - - Mooncake's TCP transport requires an empty device list. Passing a usable - HCA alongside ``protocol=tcp`` allows the transfer engine to activate RDMA - as an alternate path, which violates the caller's explicit transport - choice. RDMA-family transports retain the existing configured/automatic - device selection. - """ - return ",".join(_select_ib_devices(protocol, configured_device, gpu_bdf)) - - -def _configure_mooncake_transport(protocol: str) -> None: - """Make Mooncake honor ATOM's explicit transport selection. - - Legacy TransferEngine builds auto-discover installed HCAs independently - of the device filter. ``MC_FORCE_TCP`` is Mooncake's supported override - for preventing that implicit RDMA transport from being installed. - """ - if protocol.strip().lower() == "tcp": - os.environ["MC_FORCE_TCP"] = "true" - - # ZMQ side-channel message types MSG_WRITE_REQUEST = b"write_request" MSG_WRITE_DONE = b"write_done" @@ -1151,10 +1063,10 @@ def __init__(self, config: Config) -> None: # By default, register only with the GPU's PCIe-local NIC. Alternate-HCA # mode registers a single engine on multiple NICs. On rail-isolated fabrics, # matched-rail mode instead selects a single-HCA engine per request. - _configure_mooncake_transport(self.protocol) - configured_ib_device = kv_transfer_config.get( - "ib_device", "" - ) or os.environ.get("ATOM_MOONCAKE_IB_DEVICE", "") + mooncake_hca.configure_transport(self.protocol) + configured_ib_device = ( + kv_transfer_config.get("ib_device", "") or envs.ATOM_MOONCAKE_IB_DEVICE + ) enable_alternate_hca = bool( kv_transfer_config.get("ib_enable_alternate_hca", False) ) @@ -1163,7 +1075,7 @@ def __init__(self, config: Config) -> None: if self.protocol.strip().lower() != "tcp" and not configured_ib_device: # The GPU this rank drives, whatever *_VISIBLE_DEVICES masks it. gpu_bdf = gpu_pci_bdf(torch.cuda.current_device()) - ib_devices = _select_ib_devices( + ib_devices = mooncake_hca.select_ib_devices( self.protocol, configured_ib_device, gpu_bdf, diff --git a/atom/kv_transfer/offload/mooncake_store/nic.py b/atom/kv_transfer/offload/mooncake_store/nic.py index 4c5479fae6e..2c0e7c1b73b 100644 --- a/atom/kv_transfer/offload/mooncake_store/nic.py +++ b/atom/kv_transfer/offload/mooncake_store/nic.py @@ -22,16 +22,14 @@ from __future__ import annotations import logging -import re -from pathlib import Path from typing import Any +# The GPU's PCIe-local NIC; re-exported for the Store's callers and tests. +from atom.utils.pci_topology import IB_SYSFS_ROOT, gpu_pci_bdf, rail_rdma_device + logger = logging.getLogger("atom") -_IB_SYSFS_ROOT = Path("/sys/class/infiniband") -_PCI_SYSFS_ROOT = Path("/sys/bus/pci/devices") -# The sysfs path component of a PCI host bridge, e.g. "pci0000:70". -_PCI_HOST_BRIDGE = re.compile(r"pci[0-9a-f]{4}:[0-9a-f]{2}") +_IB_SYSFS_ROOT = IB_SYSFS_ROOT def parse_device_list(value: str) -> list[str]: @@ -87,120 +85,3 @@ def requester_rdma_device(device_index: int, cfg: Any) -> str: origin, ) return device - - -def gpu_pci_bdf(device_index: int) -> str: - """PCI address of a CUDA/HIP device ordinal, as sysfs spells it.""" - import torch - - props = torch.cuda.get_device_properties(device_index) - return ( - f"{props.pci_domain_id:04x}:{props.pci_bus_id:02x}:" - f"{props.pci_device_id:02x}.0" - ) - - -def rail_rdma_device( - gpu_bdf: str, - *, - ib_root: Path = _IB_SYSFS_ROOT, - pci_root: Path = _PCI_SYSFS_ROOT, -) -> str: - """Return the ACTIVE RDMA device behind the GPU's own PCIe switch. - - On a rail-optimized node each GPU sits behind a PCIe switch with exactly - one NIC, which shares more of the sysfs device path with that GPU than - any other NIC does. The device must share the GPU's root port and the - switch's upstream port, and be no closer to another GPU (a PCI function of - this GPU's vendor and class): with the GPU's own NIC down or missing, the - closest ACTIVE one is a neighbour's. - - Raises: - ValueError: The GPU is not in sysfs, no ACTIVE device shares its PCIe - switch, several are equally close, or the closest is closer to - another GPU. - """ - gpu_node = pci_root / gpu_bdf - if not gpu_node.exists(): - raise ValueError(f"GPU {gpu_bdf} is not in {pci_root}") - gpu_path = gpu_node.resolve().parts - host_bridge = next( - (i for i, part in enumerate(gpu_path) if _PCI_HOST_BRIDGE.fullmatch(part)), - None, - ) - if host_bridge is None: - raise ValueError(f"no PCI host bridge in GPU {gpu_bdf}'s path {gpu_node}") - try: - devices = sorted(ib_root.iterdir()) - except OSError as exc: - raise ValueError(f"cannot list RDMA devices in {ib_root}") from exc - closeness: dict[str, int] = {} - nic_paths: dict[str, tuple[str, ...]] = {} - for device in devices: - if not _has_active_port(device): - continue - nic_paths[device.name] = (device / "device").resolve().parts - closeness[device.name] = _shared_depth(gpu_path, nic_paths[device.name]) - best = max(closeness.values(), default=0) - closest = [name for name, shared in closeness.items() if shared == best] - # Below the host bridge come the root port and the switch's upstream port; - # a NIC on another root port is another GPU's, even under one host bridge. - switch = host_bridge + 2 - if best <= switch or len(closest) != 1: - found = ", ".join(f"{n}:{s}" for n, s in sorted(closeness.items())) - raise ValueError( - f"cannot tell GPU {gpu_bdf}'s NIC from the PCI topology (ACTIVE " - f"devices and shared path depth: {found or 'none'})" - ) - # A NIC closer to another GPU is that GPU's, as when this GPU's own is gone. - for peer in _peer_gpu_paths(gpu_node, pci_root): - if _shared_depth(peer, nic_paths[closest[0]]) > best: - raise ValueError( - f"cannot tell GPU {gpu_bdf}'s NIC from the PCI topology: the " - f"closest ACTIVE device, {closest[0]}, is closer to GPU {peer[-1]}" - ) - return closest[0] - - -def _shared_depth(a: tuple[str, ...], b: tuple[str, ...]) -> int: - shared = 0 - for a_part, b_part in zip(a, b): - if a_part != b_part: - break - shared += 1 - return shared - - -def _peer_gpu_paths(gpu_node: Path, pci_root: Path) -> list[tuple[str, ...]]: - """sysfs paths of the node's other GPUs: PCI functions of this GPU's vendor - and class, so it assumes one GPU model per node.""" - kind = _pci_kind(gpu_node) - if kind is None: - raise ValueError(f"cannot read GPU {gpu_node.name}'s PCI vendor and class") - try: - nodes = list(pci_root.iterdir()) - except OSError as exc: - raise ValueError(f"cannot list PCI devices in {pci_root}") from exc - return [ - node.resolve().parts - for node in nodes - if node.name != gpu_node.name and _pci_kind(node) == kind - ] - - -def _pci_kind(node: Path) -> tuple[str, ...] | None: - try: - return tuple((node / f).read_text().strip() for f in ("vendor", "class")) - except OSError: - return None - - -def _has_active_port(device: Path) -> bool: - for state_file in device.glob("ports/*/state"): - try: - state = state_file.read_text().partition(":")[0].strip() - except OSError: - continue - if state == "4": # IB_PORT_ACTIVE, also used by RoCE devices - return True - return False diff --git a/atom/utils/envs.py b/atom/utils/envs.py index 1237b04af32..7c448986fbe 100644 --- a/atom/utils/envs.py +++ b/atom/utils/envs.py @@ -187,6 +187,13 @@ def _dp_sync_interval_env() -> int | None: "ATOM_TRACE_VERSION": lambda: os.getenv("ATOM_TRACE_VERSION", "unknown"), # Opt-in single-HCA engine pool: "auto" or explicit comma-separated HCAs. "ATOM_MOONCAKE_MATCHED_RAILS": lambda: os.getenv("ATOM_MOONCAKE_MATCHED_RAILS", ""), + # Mooncake HCAs this server's engines register on, comma-separated. Unset = + # each GPU's local HCA (rdmaN, else ionic_N). + "ATOM_MOONCAKE_IB_DEVICE": lambda: os.getenv("ATOM_MOONCAKE_IB_DEVICE", ""), + # E/P/D encoder: seconds an image embedding entry stays readable before its + # pool space may be reused. A full pool with every entry inside its lease + # refuses the encode. + "ATOM_EC_LEASE_S": lambda: _positive_float_env("ATOM_EC_LEASE_S", "60"), # Prefill (`kv_producer`, plain `mooncake`) only: gather the MLA tokens a # DCP decode rank owns into a GPU staging slot and send one RDMA descriptor # per run of adjacent destination pages instead of one per token. diff --git a/atom/utils/mooncake_hca.py b/atom/utils/mooncake_hca.py new file mode 100644 index 00000000000..71be53cfb07 --- /dev/null +++ b/atom/utils/mooncake_hca.py @@ -0,0 +1,118 @@ +# SPDX-License-Identifier: MIT +# Copyright (C) 2026, Advanced Micro Devices, Inc. All rights reserved. +# Copyright (c) 2026 ATOM Project Contributors +"""Which HCAs a Mooncake TransferEngine registers on, and its transport. + +Shared by every Mooncake user in ATOM: the KV connector +(``kv_transfer/disaggregation/mooncake``) and the image embedding transfer +(``atom/ec_transfer/mooncake.py``). +""" + +from __future__ import annotations + +import os +from pathlib import Path + +from atom.utils.pci_topology import rail_rdma_device + +IB_SYSFS_ROOT = Path("/sys/class/infiniband") + + +def ib_device_exists(device_name: str) -> bool: + return (IB_SYSFS_ROOT / device_name).exists() + + +def auto_select_ib_device(gpu_bdf: str) -> str: + """The ACTIVE HCA behind the GPU's PCIe switch (HIP's order is not PCI order).""" + try: + return rail_rdma_device(gpu_bdf) + except ValueError as exc: + raise ValueError(f"{exc}; set ib_device or ATOM_MOONCAKE_IB_DEVICE") from None + + +def numbered_ib_device(index: int) -> str: + # Older environments expose HCAs as rdmaN. Spur MI350 fabric exposes them + # as ionic_N, so try ionic_N only when rdmaN is not present. + rdma_device = f"rdma{index}" + if ib_device_exists(rdma_device): + return rdma_device + ionic_device = f"ionic_{index}" + if ib_device_exists(ionic_device): + return ionic_device + return rdma_device + + +def parse_ib_devices(configured_devices: str) -> list[str]: + """Normalize a comma-separated Mooncake RDMA device filter.""" + return list( + dict.fromkeys( + device.strip() for device in configured_devices.split(",") if device.strip() + ) + ) + + +def select_ib_devices( + protocol: str, + configured_devices: str, + gpu_bdf: str | None, + *, + enable_alternate_hca: bool = False, + hca_count: int = 8, +) -> list[str]: + """Resolve the HCAs on which Mooncake registers this rank's GPU memory.""" + if protocol.strip().lower() == "tcp": + return [] + if configured_devices: + return parse_ib_devices(configured_devices) + if gpu_bdf is None: + raise ValueError("the GPU's PCI address is required for RDMA device selection") + + primary = auto_select_ib_device(gpu_bdf) + devices = [primary] + if enable_alternate_hca: + if hca_count <= 0: + raise ValueError("ib_hca_count must be a positive integer") + for idx in range(hca_count): + device = numbered_ib_device(idx) + if device not in devices and ib_device_exists(device): + devices.append(device) + return devices + + +def ib_device_filter( + protocol: str, + configured_devices: str, + gpu_bdf: str | None, + *, + enable_alternate_hca: bool = False, + hca_count: int = 8, +) -> str: + """``select_ib_devices`` as the comma-separated filter + ``TransferEngine.initialize`` takes. + + Mooncake's TCP transport requires an empty device list. Passing a usable + HCA alongside ``protocol=tcp`` allows the transfer engine to activate RDMA + as an alternate path, which violates the caller's explicit transport + choice. RDMA-family transports retain the existing configured/automatic + device selection. + """ + return ",".join( + select_ib_devices( + protocol, + configured_devices, + gpu_bdf, + enable_alternate_hca=enable_alternate_hca, + hca_count=hca_count, + ) + ) + + +def configure_transport(protocol: str) -> None: + """Make Mooncake honor ATOM's explicit transport selection. + + Legacy TransferEngine builds auto-discover installed HCAs independently + of the device filter. ``MC_FORCE_TCP`` is Mooncake's supported override + for preventing that implicit RDMA transport from being installed. + """ + if protocol.strip().lower() == "tcp": + os.environ["MC_FORCE_TCP"] = "true" diff --git a/atom/utils/pci_topology.py b/atom/utils/pci_topology.py new file mode 100644 index 00000000000..8824edeaf69 --- /dev/null +++ b/atom/utils/pci_topology.py @@ -0,0 +1,138 @@ +# SPDX-License-Identifier: MIT +# Copyright (C) 2026, Advanced Micro Devices, Inc. All rights reserved. +# Copyright (c) 2026 ATOM Project Contributors +"""Which RDMA device sits behind a GPU's own PCIe switch, read from sysfs. + +Shared by every RDMA user in ATOM: the Mooncake Store offload's requesters +(``kv_transfer/offload/mooncake_store/nic.py``), the Mooncake P/D connector +and the image embedding transfer, through ``atom/utils/mooncake_hca.py``. +HIP numbers GPUs in KFD order, not PCI order, so a GPU's NIC is found from +its PCI address, not from its ordinal. +""" + +from __future__ import annotations + +import re +from pathlib import Path + +IB_SYSFS_ROOT = Path("/sys/class/infiniband") +PCI_SYSFS_ROOT = Path("/sys/bus/pci/devices") +# The sysfs path component of a PCI host bridge, e.g. "pci0000:70". +_PCI_HOST_BRIDGE = re.compile(r"pci[0-9a-f]{4}:[0-9a-f]{2}") + + +def gpu_pci_bdf(device_index: int) -> str: + """PCI address of a CUDA/HIP device ordinal, as sysfs spells it.""" + import torch + + props = torch.cuda.get_device_properties(device_index) + return ( + f"{props.pci_domain_id:04x}:{props.pci_bus_id:02x}:" + f"{props.pci_device_id:02x}.0" + ) + + +def rail_rdma_device( + gpu_bdf: str, + *, + ib_root: Path = IB_SYSFS_ROOT, + pci_root: Path = PCI_SYSFS_ROOT, +) -> str: + """Return the ACTIVE RDMA device behind the GPU's own PCIe switch. + + On a rail-optimized node each GPU sits behind a PCIe switch with exactly + one NIC, which shares more of the sysfs device path with that GPU than + any other NIC does. The device must share the GPU's root port and the + switch's upstream port, and be no closer to another GPU (a PCI function of + this GPU's vendor and class): with the GPU's own NIC down or missing, the + closest ACTIVE one is a neighbour's. + + Raises: + ValueError: The GPU is not in sysfs, no ACTIVE device shares its PCIe + switch, several are equally close, or the closest is closer to + another GPU. + """ + gpu_node = pci_root / gpu_bdf + if not gpu_node.exists(): + raise ValueError(f"GPU {gpu_bdf} is not in {pci_root}") + gpu_path = gpu_node.resolve().parts + host_bridge = next( + (i for i, part in enumerate(gpu_path) if _PCI_HOST_BRIDGE.fullmatch(part)), + None, + ) + if host_bridge is None: + raise ValueError(f"no PCI host bridge in GPU {gpu_bdf}'s path {gpu_node}") + try: + devices = sorted(ib_root.iterdir()) + except OSError as exc: + raise ValueError(f"cannot list RDMA devices in {ib_root}") from exc + closeness: dict[str, int] = {} + nic_paths: dict[str, tuple[str, ...]] = {} + for device in devices: + if not _has_active_port(device): + continue + nic_paths[device.name] = (device / "device").resolve().parts + closeness[device.name] = _shared_depth(gpu_path, nic_paths[device.name]) + best = max(closeness.values(), default=0) + closest = [name for name, shared in closeness.items() if shared == best] + # Below the host bridge come the root port and the switch's upstream port; + # a NIC on another root port is another GPU's, even under one host bridge. + switch = host_bridge + 2 + if best <= switch or len(closest) != 1: + found = ", ".join(f"{n}:{s}" for n, s in sorted(closeness.items())) + raise ValueError( + f"cannot tell GPU {gpu_bdf}'s NIC from the PCI topology (ACTIVE " + f"devices and shared path depth: {found or 'none'})" + ) + # A NIC closer to another GPU is that GPU's, as when this GPU's own is gone. + for peer in _peer_gpu_paths(gpu_node, pci_root): + if _shared_depth(peer, nic_paths[closest[0]]) > best: + raise ValueError( + f"cannot tell GPU {gpu_bdf}'s NIC from the PCI topology: the " + f"closest ACTIVE device, {closest[0]}, is closer to GPU {peer[-1]}" + ) + return closest[0] + + +def _shared_depth(a: tuple[str, ...], b: tuple[str, ...]) -> int: + shared = 0 + for a_part, b_part in zip(a, b): + if a_part != b_part: + break + shared += 1 + return shared + + +def _peer_gpu_paths(gpu_node: Path, pci_root: Path) -> list[tuple[str, ...]]: + """sysfs paths of the node's other GPUs: PCI functions of this GPU's vendor + and class, so it assumes one GPU model per node.""" + kind = _pci_kind(gpu_node) + if kind is None: + raise ValueError(f"cannot read GPU {gpu_node.name}'s PCI vendor and class") + try: + nodes = list(pci_root.iterdir()) + except OSError as exc: + raise ValueError(f"cannot list PCI devices in {pci_root}") from exc + return [ + node.resolve().parts + for node in nodes + if node.name != gpu_node.name and _pci_kind(node) == kind + ] + + +def _pci_kind(node: Path) -> tuple[str, ...] | None: + try: + return tuple((node / f).read_text().strip() for f in ("vendor", "class")) + except OSError: + return None + + +def _has_active_port(device: Path) -> bool: + for state_file in device.glob("ports/*/state"): + try: + state = state_file.read_text().partition(":")[0].strip() + except OSError: + continue + if state == "4": # IB_PORT_ACTIVE, also used by RoCE devices + return True + return False diff --git a/docs/environment_variables.md b/docs/environment_variables.md index 4dd2333ffa4..fc267017750 100644 --- a/docs/environment_variables.md +++ b/docs/environment_variables.md @@ -749,6 +749,13 @@ See `atom/utils/envs.py` for the full list of lazy-evaluated environment variabl See [Mooncake matched rails](mooncake_matched_rails.md) for independent P/D rank configuration, deployment requirements, and registration lifetime. +## Mooncake devices and E/P/D image embeddings + +| Variable | Type | Default | Description | +|----------|------|---------|-------------| +| **ATOM_MOONCAKE_IB_DEVICE** | str | "" | Comma-separated HCAs every Mooncake engine of this server registers on: the KV connector's (when `kv_transfer_config` names no `ib_device`) and the E/P/D image embedding pool and reader's. Unset selects each GPU's local HCA (`rdmaN`, else `ionic_N`). | +| **ATOM_EC_LEASE_S** | float | 60 | E/P/D encoder. Seconds an image embedding entry stays readable by P before its pool space may be reused. When every entry new embeddings would overwrite is inside its lease, the pool is full and the encode is refused; ATOMesh then sends the request to P without embeddings and P encodes. | + ## Mooncake PD MLA staging | Variable | Type | Default | Description | diff --git a/tests/test_ec_transfer.py b/tests/test_ec_transfer.py new file mode 100644 index 00000000000..3cb1f2752e3 --- /dev/null +++ b/tests/test_ec_transfer.py @@ -0,0 +1,483 @@ +# SPDX-License-Identifier: MIT +# Copyright (C) 2026, Advanced Micro Devices, Inc. All rights reserved. +# Copyright (c) 2026 ATOM Project Contributors +"""The image embedding transfer interface and its Mooncake backend: E's pool +and P's read, over a fake Mooncake TransferEngine.""" + +import ctypes +import os + +import pytest +import torch + +from atom.ec_transfer import EcStoreFull, create_reader, create_writer +from atom.ec_transfer import mooncake as ec +from atom.utils import mooncake_hca + +LEASE_S = 10.0 + + +class FakeEngine: + """Moves bytes between registered regions of engines in this process.""" + + def __init__(self, sessions): + self.sessions = sessions + self.regions = [] + self.init_args = None + self.fail_reads = False + + def initialize(self, ip, metadata, protocol, ib_device): + self.init_args = (ip, metadata, protocol, ib_device) + self.port = 17000 + len(self.sessions) + self.sessions[f"{ip}:{self.port}"] = self + return 0 + + def get_rpc_port(self): + return self.port + + def register_memory(self, ptr, length): + self.regions.append((ptr, length)) + return 0 + + def _registered(self, ptr, length): + return any(p <= ptr and ptr + length <= p + n for p, n in self.regions) + + def transfer_sync_read(self, session, dst, src, length): + peer = self.sessions.get(session) + if self.fail_reads or peer is None: + return -1 + assert self._registered(dst, length) and peer._registered(src, length) + ctypes.memmove(dst, src, length) + return 0 + + +class Clock: + def __init__(self): + self.now = 1000.0 + + def __call__(self): + return self.now + + +@pytest.fixture +def engines(monkeypatch): + sessions = {} + made = [] + + def make_engine(): + made.append(FakeEngine(sessions)) + return made[-1] + + monkeypatch.setattr(ec, "MOONCAKE_AVAILABLE", True) + monkeypatch.setattr(ec, "TransferEngine", make_engine, raising=False) + monkeypatch.setattr(ec, "get_ip", lambda: "192.0.2.7") + monkeypatch.setenv("ATOM_MOONCAKE_IB_DEVICE", "rocep139s0") + monkeypatch.setenv("ATOM_EC_LEASE_S", str(LEASE_S)) + # Set first so the TCP case's own write is undone too. + monkeypatch.setenv("MC_FORCE_TCP", "false") + monkeypatch.delenv("MC_FORCE_TCP") + return made + + +def writer(pool_bytes, slots=16, **kwargs): + """A writer whose pool is ``pool_bytes`` after a table of ``slots``.""" + region = ec.slot_table_bytes(slots) + pool_bytes + return ec.MooncakeEcWriter(region, "cpu", slots=slots, **kwargs) + + +def with_mooncake(params, **fields): + return {**params, "mooncake": {**params["mooncake"], **fields}} + + +def rows(seed, n=4, hidden=32): + g = torch.Generator().manual_seed(seed) + return torch.randn(n, hidden, generator=g).to(torch.bfloat16) + + +def test_p_reads_stored_rows_until_lease_expires_and_slot_is_reused(engines): + clock = Clock() + # Room for one 4 x 32 bf16 entry only: the next put must reuse its slot. + pool = writer(320, clock=clock) + reader = ec.MooncakeEcReader(1024, "cpu") + stored = rows(1) + params = pool.put(11, stored) + + got = reader.get(params, 11, torch.bfloat16) + assert torch.equal(got, stored) + + clock.now += LEASE_S + params2 = pool.put(12, rows(2)) + assert params2["mooncake"]["address"] == params["mooncake"]["address"] + assert reader.get(params, 11, torch.bfloat16) is None + assert torch.equal(reader.get(params2, 12, torch.bfloat16), rows(2)) + + +def test_read_racing_a_slot_reuse_sees_a_given_up_slot(engines, monkeypatch): + clock = Clock() + pool = writer(320, clock=clock) + reader = ec.MooncakeEcReader(1024, "cpu") + params = pool.put(11, rows(1)) + + # P reads the old entry at E's first sync of the reuse: the victim's slot + # is zeroed, its old rows not yet overwritten. + mid_overwrite = [] + + def sync(buf): + if buf is pool._region and not mid_overwrite: + mid_overwrite.append(reader.get(params, 11, torch.bfloat16)) + + monkeypatch.setattr(ec, "_sync", sync) + clock.now += LEASE_S + pool.put(12, rows(2)) + assert mid_overwrite[0] is None + + +def test_full_pool_raises_and_keeps_entries_inside_their_lease(engines): + clock = Clock() + pool = writer(320, clock=clock) + reader = ec.MooncakeEcReader(1024, "cpu") + params = pool.put(11, rows(1)) + + clock.now += LEASE_S - 0.5 + with pytest.raises(EcStoreFull): + pool.put(12, rows(2)) + with pytest.raises(EcStoreFull): + pool.put(13, rows(3, n=100)) + assert torch.equal(reader.get(params, 11, torch.bfloat16), rows(1)) + + +def test_space_is_reused_oldest_first(engines): + clock = Clock() + # Three 256-byte entries fill the pool. + pool = writer(768, clock=clock) + reader = ec.MooncakeEcReader(1024, "cpu") + first = pool.put(1, rows(1)) + clock.now += 1 + second = pool.put(2, rows(2)) + clock.now += 1 + third = pool.put(3, rows(3)) + + # Only the first entry is past its lease: it alone gives way. + clock.now = 1000.0 + LEASE_S + 0.5 + fourth = pool.put(4, rows(4)) + assert fourth["mooncake"]["address"] == first["mooncake"]["address"] + assert reader.get(first, 1, torch.bfloat16) is None + for params, seed in ((second, 2), (third, 3), (fourth, 4)): + assert torch.equal(reader.get(params, seed, torch.bfloat16), rows(seed)) + with pytest.raises(EcStoreFull): + pool.put(5, rows(5)) + + +def test_read_returns_none_on_foreign_seed_or_failed_read(engines): + pool = writer(1024, clock=Clock()) + reader = ec.MooncakeEcReader(1024, "cpu") + params = pool.put(11, rows(1)) + + assert reader.get(params, 99, torch.bfloat16) is None + assert ( + reader.get(with_mooncake(params, session="192.0.2.9:1"), 11, torch.bfloat16) + is None + ) + engines[-1].fail_reads = True + assert reader.get(params, 11, torch.bfloat16) is None + + +def test_reader_refuses_rows_larger_than_its_buffer(engines): + pool = writer(4096, clock=Clock()) + reader = ec.MooncakeEcReader(64, "cpu") + params = pool.put(11, rows(1)) + assert reader.get(params, 11, torch.bfloat16) is None + + +def test_pool_registers_on_the_configured_device(engines): + pool = writer(1024, clock=Clock()) + engine = engines[0] + assert engine.init_args == ("192.0.2.7", "P2PHANDSHAKE", "rdma", "rocep139s0") + # One registration: the slot table, then the pool. + assert engine.regions == [(pool._region.data_ptr(), 16 * 32 + 1024)] + assert pool.session == "192.0.2.7:17000" + + +def test_pool_registers_on_every_configured_device(engines, monkeypatch): + monkeypatch.setenv("ATOM_MOONCAKE_IB_DEVICE", "rocep139s0, rocep140s0,rocep139s0") + writer(1024, clock=Clock()) + assert engines[0].init_args[3] == "rocep139s0,rocep140s0" + + +def test_engine_without_configured_device_uses_the_gpu_local_hca(engines, monkeypatch): + # The HCA on the GPU's PCIe switch, found from its PCI address, as the KV + # connector picks it: HIP's ordinal is not PCI order. + monkeypatch.delenv("ATOM_MOONCAKE_IB_DEVICE") + monkeypatch.setattr(ec, "gpu_pci_bdf", {1: "0000:05:00.0"}.__getitem__) + monkeypatch.setattr( + mooncake_hca, "rail_rdma_device", {"0000:05:00.0": "rdma0"}.__getitem__ + ) + engine, _ = ec._open_engine(torch.device("cuda", 1), "rdma") + assert engine.init_args[3] == "rdma0" + + +def test_pool_on_tcp_registers_no_hca(engines, monkeypatch): + writer(1024, protocol="tcp", clock=Clock()) + assert engines[0].init_args[2:] == ("tcp", "") + assert os.environ["MC_FORCE_TCP"] == "true" + + +def test_read_returns_none_when_p_reads_another_dtype(engines): + pool = writer(1024, clock=Clock()) + reader = ec.MooncakeEcReader(1024, "cpu") + params = pool.put(11, rows(1)) + assert params["dtype"] == "bfloat16" + assert reader.get(params, 11, torch.float16) is None + + +def test_put_into_free_space_syncs_once(engines, monkeypatch): + pool = writer(1024, clock=Clock()) + syncs = [] + monkeypatch.setattr(ec, "_sync", syncs.append) + pool.put(11, rows(1)) + assert len(syncs) == 1 + + +def test_matched_rails_warn_that_reads_take_no_rail(engines, monkeypatch, caplog): + monkeypatch.setenv("ATOM_MOONCAKE_MATCHED_RAILS", "rocep139s0,rocep140s0") + with caplog.at_level("WARNING", logger="atom"): + writer(1024, clock=Clock()) + assert "ATOM_MOONCAKE_MATCHED_RAILS" in caplog.text + + +def test_handle_names_its_transport_and_keeps_mooncake_fields_apart(engines): + pool = writer(1024, clock=Clock()) + handle = pool.put(11, rows(1)) + assert {k: v for k, v in handle.items() if k != "mooncake"} == { + "transport": "mooncake", + "key": 11, + "rows": 4, + "dtype": "bfloat16", + } + assert set(handle["mooncake"]) == { + "session", + "address", + "length", + "generation", + "slot", + } + + +def test_read_refuses_generation_zero(engines): + # A given-up slot is all zero: a handle claiming generation 0 must not + # read it as a match. + pool = writer(1024, clock=Clock()) + reader = ec.MooncakeEcReader(1024, "cpu") + handle = pool.put(11, rows(1)) + pool._slots[0].zero_() + assert reader.get(with_mooncake(handle, generation=0), 11, torch.bfloat16) is None + + +@pytest.mark.parametrize( + "broken", + [ + None, + "not a dict", + {}, + {"transport": "other"}, + {"rows": "4"}, + {"rows": 0}, + {"mooncake": None}, + {"mooncake": {}}, + {"mooncake": {"length": -256}}, + {"mooncake": {"length": 250}}, + {"mooncake": {"address": "0x10"}}, + {"mooncake": {"session": 7}}, + {"mooncake": {"slot": 0}}, + ], +) +def test_malformed_handle_reads_none_without_raising(engines, broken): + pool = writer(1024, clock=Clock()) + reader = ec.MooncakeEcReader(1024, "cpu") + handle = pool.put(11, rows(1)) + if isinstance(broken, dict) and "mooncake" in broken and broken["mooncake"]: + bad = with_mooncake(handle, **broken["mooncake"]) + elif isinstance(broken, dict): + bad = {k: v for k, v in {**handle, **broken}.items() if broken or k != "key"} + else: + bad = broken + assert reader.get(bad, 11, torch.bfloat16) is None + assert torch.equal(reader.get(handle, 11, torch.bfloat16), rows(1)) + + +def test_factory_builds_mooncake_and_refuses_unknown_transports(engines): + writer = create_writer("mooncake", 1024, "cpu") + reader = create_reader("mooncake", 1024, "cpu") + handle = writer.put(11, rows(1)) + assert torch.equal(reader.get(handle, 11, torch.bfloat16), rows(1)) + with pytest.raises(ValueError, match="unknown image embedding transport"): + create_reader("nixl", 1024, "cpu") + with pytest.raises(ValueError, match="unknown image embedding transport"): + create_writer("nixl", 1024, "cpu") + + +def test_reader_without_mooncake_raises_on_construction(engines, monkeypatch): + monkeypatch.setattr(ec, "MOONCAKE_AVAILABLE", False) + with pytest.raises(RuntimeError, match="Mooncake is not installed"): + create_reader("mooncake", 1024, "cpu") + + +def test_reader_takes_the_kv_connectors_hca_options(engines, monkeypatch): + ec.MooncakeEcReader(1024, "cpu", kv_transfer_config={"ib_device": "rocep140s0"}) + assert engines[-1].init_args[3] == "rocep140s0" + + opened = [] + monkeypatch.setattr( + ec, "_open_engine", lambda *a, **kw: opened.append((a, kw)) or (engines[-1], "") + ) + kv = {"ib_device": "", "ib_enable_alternate_hca": True, "ib_hca_count": 3} + ec.MooncakeEcReader(1024, "cpu", kv_transfer_config=kv) + assert opened[0][0][2] == "" + assert opened[0][1] == {"enable_alternate_hca": True, "hca_count": 3} + + +def test_engine_registers_on_alternate_hcas(engines, monkeypatch): + monkeypatch.delenv("ATOM_MOONCAKE_IB_DEVICE") + monkeypatch.setattr(ec, "gpu_pci_bdf", {1: "0000:05:00.0"}.__getitem__) + monkeypatch.setattr( + mooncake_hca, "auto_select_ib_device", {"0000:05:00.0": "ionic_1"}.__getitem__ + ) + monkeypatch.setattr(mooncake_hca, "numbered_ib_device", lambda i: f"ionic_{i}") + monkeypatch.setattr(mooncake_hca, "ib_device_exists", lambda _: True) + ec._open_engine( + torch.device("cuda", 1), "rdma", enable_alternate_hca=True, hca_count=3 + ) + assert engines[-1].init_args[3] == "ionic_1,ionic_0,ionic_2" + + +def test_slot_holds_generation_address_length_and_a_zero_ack(engines): + pool = writer(1024, slots=4, clock=Clock()) + handle = pool.put(11, rows(1)) + where = handle["mooncake"] + slot = (where["slot"] - pool._region.data_ptr()) // 32 + assert pool._slots[slot].tolist() == [ + where["generation"], + where["address"], + where["length"], + 0, + ] + # Rows never overlap the slot table. + assert where["address"] >= pool._region.data_ptr() + 4 * 32 + + +def test_rows_equal_to_an_old_generation_never_revive_its_handle(engines): + # The old layout kept the word in front of the rows, where a later + # entry's rows could land and, by chance, equal it. + clock = Clock() + pool = writer(256, clock=clock) + reader = ec.MooncakeEcReader(1024, "cpu") + old = pool.put(11, rows(1)) + clock.now += LEASE_S + forged = torch.full((32,), old["mooncake"]["generation"], dtype=torch.int64) + pool.put(12, forged.view(torch.bfloat16).view(4, -1)) + assert reader.get(old, 11, torch.bfloat16) is None + + +def test_running_out_of_slots_evicts_only_past_the_lease(engines): + clock = Clock() + pool = writer(4096, slots=2, clock=clock) + reader = ec.MooncakeEcReader(1024, "cpu") + first = pool.put(1, rows(1)) + second = pool.put(2, rows(2)) + with pytest.raises(EcStoreFull, match="2 slots"): + pool.put(3, rows(3)) + assert torch.equal(reader.get(first, 1, torch.bfloat16), rows(1)) + + clock.now += LEASE_S + third = pool.put(3, rows(3)) + assert third["mooncake"]["slot"] == first["mooncake"]["slot"] + assert reader.get(first, 1, torch.bfloat16) is None + assert torch.equal(reader.get(second, 2, torch.bfloat16), rows(2)) + assert torch.equal(reader.get(third, 3, torch.bfloat16), rows(3)) + + +def test_reader_syncs_its_buffer_before_the_nic_writes_it(engines, monkeypatch): + pool = writer(1024, clock=Clock()) + reader = ec.MooncakeEcReader(1024, "cpu") + handle = pool.put(11, rows(1)) + events = [] + monkeypatch.setattr( + ec, "_sync", lambda buf: events.append("sync" if buf is reader._buf else "e") + ) + engine = reader._engine + read = engine.transfer_sync_read + monkeypatch.setattr( + engine, + "transfer_sync_read", + lambda *a: events.append("read") or read(*a), + ) + assert torch.equal(reader.get(handle, 11, torch.bfloat16), rows(1)) + assert events == ["sync", "read", "read"] + + +def test_every_fallback_is_logged_and_counted_by_reason(engines, caplog): + clock = Clock() + pool = writer(256, clock=clock) + reader = ec.MooncakeEcReader(1024, "cpu") + old = pool.put(11, rows(1)) + clock.now += LEASE_S + pool.put(12, rows(2)) + with caplog.at_level("WARNING", logger="atom"): + assert reader.get(old, 11, torch.bfloat16) is None + assert reader.get(old, 99, torch.bfloat16) is None + assert reader.get(old, 11, torch.float16) is None + assert reader.fallbacks == { + "entry given up or reused": 1, + "key differs from this request's": 1, + "stored as 'bfloat16', read as 'float16'": 1, + } + assert "entry given up or reused" in caplog.text + assert "192.0.2.7:17000" in caplog.text + + +def test_slots_follow_the_region_size(): + # 1 GiB: 16384 slots, a 512 KiB table. Past a 60 s lease that is ~273 + # puts/s before slots, not space, could refuse one. + assert ec.default_slots(1 << 30) == 16384 + assert ec.slot_table_bytes(16384) == 512 << 10 + assert ec.default_slots(1 << 20) == 16 and ec.default_slots(1000) == 1 + + +def test_whole_region_is_registered_with_derived_slots(engines): + pool = ec.MooncakeEcWriter(1 << 24, "cpu", clock=Clock()) + assert len(pool._slots) == 256 + # Exactly the region E sized (whole GiB in production), table included. + assert engines[0].regions == [(pool._region.data_ptr(), 1 << 24)] + assert pool._buf.numel() == (1 << 24) - ec.slot_table_bytes(256) + + +@pytest.mark.parametrize("entry_rows", [64, 512]) # 256 KiB, 2 MiB of bf16 +def test_space_runs_out_before_slots_at_image_sized_entries(engines, entry_rows): + pool = ec.MooncakeEcWriter(1 << 24, "cpu", clock=Clock()) + stored = 0 + with pytest.raises(EcStoreFull, match="inside its"): + while True: + pool.put(stored, torch.zeros(entry_rows, 2048, dtype=torch.bfloat16)) + stored += 1 + # The pool filled up with slots to spare. + assert stored == pool._buf.numel() // (entry_rows * 2048 * 2) + assert len(pool._free_slots) > 0 + + +def test_a_region_too_small_for_its_slots_is_refused(engines): + with pytest.raises(ValueError, match="leaves no pool"): + ec.MooncakeEcWriter(64, "cpu", slots=2) + + +def test_ec_transfer_imports_nothing_from_kv_transfer(): + import subprocess + import sys + + code = ( + "import sys, atom.ec_transfer.mooncake, atom.utils.mooncake_hca; " + "print(sorted(m for m in sys.modules if m.startswith('atom.kv_transfer')))" + ) + out = subprocess.run( + [sys.executable, "-c", code], capture_output=True, text=True, check=True + ) + assert out.stdout.strip() == "[]" diff --git a/tests/test_mooncake_ib_device_select.py b/tests/test_mooncake_ib_device_select.py index 394addcd776..c55babe3993 100644 --- a/tests/test_mooncake_ib_device_select.py +++ b/tests/test_mooncake_ib_device_select.py @@ -17,6 +17,7 @@ from aiter_stub import atom_without_aiter from atom.kv_transfer.offload.mooncake_store import nic +from atom.utils import mooncake_hca with atom_without_aiter() as load: mc = load("atom.kv_transfer.disaggregation.mooncake.mooncake_connector") @@ -58,7 +59,7 @@ def node(tmp_path, monkeypatch): def build(prefix="rdma", inactive=()): pci, ib = _node(tmp_path, prefix, inactive) monkeypatch.setattr( - mc, + mooncake_hca, "rail_rdma_device", lambda bdf: nic.rail_rdma_device(bdf, ib_root=ib, pci_root=pci), ) @@ -69,14 +70,16 @@ def build(prefix="rdma", inactive=()): @pytest.mark.parametrize("prefix", ["rdma", "ionic_"]) def test_auto_select_follows_the_pci_tree_not_the_hip_index(node, prefix): node(prefix) - picked = [mc._select_ib_devices("rdma", "", f"0000:{b}:00.0") for b in GPU_BUS] + picked = [ + mooncake_hca.select_ib_devices("rdma", "", f"0000:{b}:00.0") for b in GPU_BUS + ] assert picked == [[f"{prefix}{n}"] for n in LOCAL] def test_auto_select_refuses_a_guess_and_names_the_pd_override(node): node(inactive=("rdma3",)) with pytest.raises(ValueError) as refused: - mc._select_ib_devices("rdma", "", "0000:75:00.0") + mooncake_hca.select_ib_devices("rdma", "", "0000:75:00.0") message = str(refused.value) assert message.startswith("cannot tell GPU 0000:75:00.0's NIC") assert message.endswith("; set ib_device or ATOM_MOONCAKE_IB_DEVICE") diff --git a/tests/test_mooncake_rail_address.py b/tests/test_mooncake_rail_address.py index 5c9c09ef7ec..d30b7ec4a42 100644 --- a/tests/test_mooncake_rail_address.py +++ b/tests/test_mooncake_rail_address.py @@ -7,6 +7,8 @@ import pytest +from atom.utils import mooncake_hca + @pytest.mark.parametrize( "netdev_ip", @@ -25,7 +27,7 @@ def test_matched_rail_rpc_uses_host_address_and_preserves_hca_selection( monkeypatch.setattr(mc, "get_ip", lambda: "192.0.2.2") monkeypatch.setattr(mc, "get_open_port", lambda: 17000) monkeypatch.setattr(mc, "_MOONCAKE_AVAILABLE", True) - monkeypatch.setattr(mc, "_ib_device_exists", lambda device: True) + monkeypatch.setattr(mooncake_hca, "ib_device_exists", lambda device: True) monkeypatch.setattr(mc.torch.cuda, "current_device", lambda: 0) monkeypatch.setattr(mc, "ThreadPoolExecutor", Mock()) monkeypatch.setattr(mc.zmq, "Context", Mock()) diff --git a/tests/test_mooncake_store_offload.py b/tests/test_mooncake_store_offload.py index f9fd73d75cb..e5f7bb70aa2 100644 --- a/tests/test_mooncake_store_offload.py +++ b/tests/test_mooncake_store_offload.py @@ -1407,7 +1407,6 @@ def test_rail_rdma_device_refuses_two_equally_close_nics(tmp_path): def node(tmp_path, monkeypatch): pci, ib = _make_node(tmp_path) monkeypatch.setattr(nic, "_IB_SYSFS_ROOT", ib) - monkeypatch.setattr(nic, "_PCI_SYSFS_ROOT", pci) monkeypatch.setattr(nic, "gpu_pci_bdf", lambda index: f"0000:{GPU_BDF[index]}:00.0") real = nic.rail_rdma_device # Keyword defaults were bound at import; rebind to the fake tree. diff --git a/tests/test_pd_pp.py b/tests/test_pd_pp.py index 8ad1aa4d834..aa5ccf2d82d 100644 --- a/tests/test_pd_pp.py +++ b/tests/test_pd_pp.py @@ -14,6 +14,8 @@ import pytest +from atom.utils import mooncake_hca + # Ensure aiter.dist.parallel_state exposes symbols mooncake_connector needs. # The top-level name is taken back down below. _ps = sys.modules.get("aiter.dist.parallel_state") @@ -511,8 +513,10 @@ def test_mooncake_control_address_is_independent_of_rdma_device( monkeypatch.delenv("MC_FORCE_TCP", raising=False) monkeypatch.setattr(mc.torch.cuda, "current_device", lambda: 0) monkeypatch.setattr(mc, "gpu_pci_bdf", {0: "0000:65:00.0"}.__getitem__) - monkeypatch.setattr(mc, "rail_rdma_device", {"0000:65:00.0": "rdma2"}.__getitem__) - monkeypatch.setattr(mc, "_ib_device_exists", lambda name: True) + monkeypatch.setattr( + mooncake_hca, "rail_rdma_device", {"0000:65:00.0": "rdma2"}.__getitem__ + ) + monkeypatch.setattr(mooncake_hca, "ib_device_exists", lambda name: True) monkeypatch.setattr( mc, "get_tp_group", lambda: SimpleNamespace(rank_in_group=0, world_size=8) ) @@ -634,10 +638,12 @@ def _one_row_staging_consumer(monkeypatch, send): monkeypatch.delenv("MC_FORCE_TCP", raising=False) monkeypatch.setattr(mc.torch.cuda, "current_device", lambda: 0) monkeypatch.setattr(mc, "gpu_pci_bdf", {0: "0000:05:00.0"}.__getitem__) - monkeypatch.setattr(mc, "rail_rdma_device", {"0000:05:00.0": "rdma0"}.__getitem__) + monkeypatch.setattr( + mooncake_hca, "rail_rdma_device", {"0000:05:00.0": "rdma0"}.__getitem__ + ) monkeypatch.setattr(mc.torch.cuda, "synchronize", lambda *a: None) monkeypatch.setattr(mc.torch.cuda, "set_device", lambda *a: None) - monkeypatch.setattr(mc, "_ib_device_exists", lambda name: True) + monkeypatch.setattr(mooncake_hca, "ib_device_exists", lambda name: True) monkeypatch.setattr( mc, "get_tp_group", lambda: SimpleNamespace(rank_in_group=0, world_size=1) ) @@ -876,58 +882,44 @@ def test_consumer_refuses_a_producer_with_other_slot_sizes(monkeypatch): def test_mooncake_tcp_disables_rdma_device_even_when_configured(): - mc = pytest.importorskip( - "atom.kv_transfer.disaggregation.mooncake.mooncake_connector" - ) - assert mc._select_ib_device("tcp", "rdma0", None) == "" - assert mc._select_ib_device(" TCP ", "ionic_0", None) == "" + assert mooncake_hca.ib_device_filter("tcp", "rdma0", None) == "" + assert mooncake_hca.ib_device_filter(" TCP ", "ionic_0", None) == "" def test_mooncake_tcp_forces_transfer_engine_transport(monkeypatch): - mc = pytest.importorskip( - "atom.kv_transfer.disaggregation.mooncake.mooncake_connector" - ) monkeypatch.delenv("MC_FORCE_TCP", raising=False) - mc._configure_mooncake_transport(" TCP ") + mooncake_hca.configure_transport(" TCP ") assert os.environ["MC_FORCE_TCP"] == "true" def test_mooncake_rdma_preserves_explicit_device(): - mc = pytest.importorskip( - "atom.kv_transfer.disaggregation.mooncake.mooncake_connector" - ) - assert mc._select_ib_device("rdma", "ionic_3", None) == "ionic_3" + assert mooncake_hca.ib_device_filter("rdma", "ionic_3", None) == "ionic_3" def test_mooncake_rdma_normalizes_explicit_device_list(): - mc = pytest.importorskip( - "atom.kv_transfer.disaggregation.mooncake.mooncake_connector" - ) assert ( - mc._select_ib_device("rdma", " ionic_4, ionic_0,ionic_4 ", None) + mooncake_hca.ib_device_filter("rdma", " ionic_4, ionic_0,ionic_4 ", None) == "ionic_4,ionic_0" ) def test_mooncake_rdma_auto_selects_from_gpu_pci_address(monkeypatch): - mc = pytest.importorskip( - "atom.kv_transfer.disaggregation.mooncake.mooncake_connector" + monkeypatch.setattr( + mooncake_hca, "auto_select_ib_device", lambda bdf: f"auto-{bdf}" + ) + assert ( + mooncake_hca.ib_device_filter("rdma", "", "0000:85:00.0") == "auto-0000:85:00.0" ) - monkeypatch.setattr(mc, "_auto_select_ib_device", lambda bdf: f"auto-{bdf}") - assert mc._select_ib_device("rdma", "", "0000:85:00.0") == "auto-0000:85:00.0" def test_mooncake_rdma_registers_all_alternate_hcas_for_upper_rail_gpu(monkeypatch): - mc = pytest.importorskip( - "atom.kv_transfer.disaggregation.mooncake.mooncake_connector" - ) monkeypatch.setattr( - mc, "_auto_select_ib_device", {"0000:85:00.0": "ionic_4"}.__getitem__ + mooncake_hca, "auto_select_ib_device", {"0000:85:00.0": "ionic_4"}.__getitem__ ) - monkeypatch.setattr(mc, "_numbered_ib_device", lambda idx: f"ionic_{idx}") - monkeypatch.setattr(mc, "_ib_device_exists", lambda _device: True) + monkeypatch.setattr(mooncake_hca, "numbered_ib_device", lambda idx: f"ionic_{idx}") + monkeypatch.setattr(mooncake_hca, "ib_device_exists", lambda _device: True) - assert mc._select_ib_devices( + assert mooncake_hca.select_ib_devices( "rdma", "", "0000:85:00.0", @@ -941,16 +933,13 @@ def test_mooncake_rdma_registers_all_alternate_hcas_for_upper_rail_gpu(monkeypat def test_mooncake_rdma_registers_all_alternate_hcas_for_lower_rail_gpu(monkeypatch): - mc = pytest.importorskip( - "atom.kv_transfer.disaggregation.mooncake.mooncake_connector" - ) monkeypatch.setattr( - mc, "_auto_select_ib_device", {"0000:75:00.0": "ionic_3"}.__getitem__ + mooncake_hca, "auto_select_ib_device", {"0000:75:00.0": "ionic_3"}.__getitem__ ) - monkeypatch.setattr(mc, "_numbered_ib_device", lambda idx: f"ionic_{idx}") - monkeypatch.setattr(mc, "_ib_device_exists", lambda _device: True) + monkeypatch.setattr(mooncake_hca, "numbered_ib_device", lambda idx: f"ionic_{idx}") + monkeypatch.setattr(mooncake_hca, "ib_device_exists", lambda _device: True) - assert mc._select_ib_devices( + assert mooncake_hca.select_ib_devices( "rdma", "", "0000:75:00.0", @@ -966,20 +955,17 @@ def test_mooncake_rdma_registers_all_alternate_hcas_for_lower_rail_gpu(monkeypat def test_mooncake_rdma_skips_missing_alternate_hcas(monkeypatch): - mc = pytest.importorskip( - "atom.kv_transfer.disaggregation.mooncake.mooncake_connector" - ) monkeypatch.setattr( - mc, "_auto_select_ib_device", {"0000:75:00.0": "ionic_3"}.__getitem__ + mooncake_hca, "auto_select_ib_device", {"0000:75:00.0": "ionic_3"}.__getitem__ ) - monkeypatch.setattr(mc, "_numbered_ib_device", lambda idx: f"ionic_{idx}") + monkeypatch.setattr(mooncake_hca, "numbered_ib_device", lambda idx: f"ionic_{idx}") monkeypatch.setattr( - mc, - "_ib_device_exists", + mooncake_hca, + "ib_device_exists", lambda device: device in {"ionic_3", "ionic_0", "ionic_7"}, ) - assert mc._select_ib_devices( + assert mooncake_hca.select_ib_devices( "rdma", "", "0000:75:00.0", @@ -989,16 +975,13 @@ def test_mooncake_rdma_skips_missing_alternate_hcas(monkeypatch): def test_mooncake_rdma_rejects_nonpositive_hca_count(monkeypatch): - mc = pytest.importorskip( - "atom.kv_transfer.disaggregation.mooncake.mooncake_connector" - ) monkeypatch.setattr( - mc, "_auto_select_ib_device", {"0000:85:00.0": "ionic_4"}.__getitem__ + mooncake_hca, "auto_select_ib_device", {"0000:85:00.0": "ionic_4"}.__getitem__ ) - monkeypatch.setattr(mc, "_numbered_ib_device", lambda idx: f"ionic_{idx}") + monkeypatch.setattr(mooncake_hca, "numbered_ib_device", lambda idx: f"ionic_{idx}") with pytest.raises(ValueError, match="ib_hca_count"): - mc._select_ib_devices( + mooncake_hca.select_ib_devices( "rdma", "", "0000:85:00.0", @@ -1008,11 +991,8 @@ def test_mooncake_rdma_rejects_nonpositive_hca_count(monkeypatch): def test_mooncake_rdma_requires_gpu_address_without_explicit_device(): - mc = pytest.importorskip( - "atom.kv_transfer.disaggregation.mooncake.mooncake_connector" - ) with pytest.raises(ValueError, match="GPU's PCI address"): - mc._select_ib_device("rdma", "", None) + mooncake_hca.ib_device_filter("rdma", "", None) # --------------------------------------------------------------------------- @@ -2489,7 +2469,9 @@ def test_matched_rails_reject_invalid_transport_configuration( ): from atom.kv_transfer.disaggregation.mooncake import mooncake_connector as mc - monkeypatch.setattr(mc, "_ib_device_exists", lambda name: name.startswith("ionic_")) + monkeypatch.setattr( + mooncake_hca, "ib_device_exists", lambda name: name.startswith("ionic_") + ) with pytest.raises(ValueError, match=message): mc._validate_matched_rails(protocol, devices, rails) @@ -2499,7 +2481,7 @@ def test_matched_rails_disabled_preserves_tcp_and_multi_hca(monkeypatch): mc._validate_matched_rails("tcp", [], []) mc._validate_matched_rails("rdma", ["ionic_0", "ionic_1"], []) - monkeypatch.setattr(mc, "_ib_device_exists", lambda _: True) + monkeypatch.setattr(mooncake_hca, "ib_device_exists", lambda _: True) mc._validate_matched_rails("rdma", ["ionic_2"], ["ionic_2", "ionic_6"]) @@ -2507,7 +2489,7 @@ def test_matched_rails_disabled_preserves_tcp_and_multi_hca(monkeypatch): def matched_rail_sysfs(tmp_path, monkeypatch): from atom.kv_transfer.disaggregation.mooncake import mooncake_connector as mc - monkeypatch.setattr(mc, "_IB_SYSFS_ROOT", tmp_path) + monkeypatch.setattr(mooncake_hca, "IB_SYSFS_ROOT", tmp_path) def add(name, *states): device = tmp_path / name @@ -2571,7 +2553,7 @@ def test_matched_rails_auto_rejects_missing_primary(matched_rail_sysfs): def test_matched_rails_auto_reports_hidden_sysfs(matched_rail_sysfs, tmp_path): mc, _ = matched_rail_sysfs - mc._IB_SYSFS_ROOT = tmp_path / "not-mounted" + mooncake_hca.IB_SYSFS_ROOT = tmp_path / "not-mounted" with pytest.raises(ValueError, match="Cannot discover RDMA HCAs"): mc._resolve_matched_rails("rdma", ["ionic_2"], "auto") @@ -2614,7 +2596,7 @@ def test_matched_rails_explicit_list_and_unset_do_not_discover(matched_rail_sysf assert mc._resolve_matched_rails( "rdma", ["ionic_2"], " ionic_6, ionic_2,ionic_6, " ) == ["ionic_6", "ionic_2"] - mc._IB_SYSFS_ROOT = mc._IB_SYSFS_ROOT / "not-mounted" + mooncake_hca.IB_SYSFS_ROOT = mooncake_hca.IB_SYSFS_ROOT / "not-mounted" assert mc._resolve_matched_rails("tcp", [], " ") == [] assert mc._resolve_matched_rails("rdma", ["ionic_2", "ionic_6"], "") == []