diff --git a/integrations/vllm/ds41_row_shard/ds41_row_shard/__init__.py b/integrations/vllm/ds41_row_shard/ds41_row_shard/__init__.py index c8eee48b..3dd3acf9 100644 --- a/integrations/vllm/ds41_row_shard/ds41_row_shard/__init__.py +++ b/integrations/vllm/ds41_row_shard/ds41_row_shard/__init__.py @@ -624,11 +624,36 @@ def exec_module(self, module): class _PatchFinder(importlib.abc.MetaPathFinder): + def __init__(self): + self._resolving = threading.local() + + def _find_downstream_spec(self, name, path, target): + meta_path = list(sys.meta_path) + if self in meta_path: + candidates = meta_path[meta_path.index(self) + 1:] + else: + candidates = [f for f in meta_path if f is not self and not isinstance(f, type(self))] + for finder in candidates: + find_spec = getattr(finder, "find_spec", None) + if find_spec is None: + continue + spec = find_spec(name, path, target) + if spec is not None: + return spec + return None + def find_spec(self, name, path, target=None): patch = _PATCHES.get(name) if patch is None: return None - spec = importlib.machinery.PathFinder.find_spec(name, path) + active = self._resolving.__dict__.setdefault("names", set()) + if name in active: + return None + active.add(name) + try: + spec = self._find_downstream_spec(name, path, target) + finally: + active.discard(name) if spec is None or spec.loader is None: return None spec.loader = _PatchLoader(spec.loader, patch) diff --git a/integrations/vllm/ds41_row_shard/tests/test_meta_path_chaining.py b/integrations/vllm/ds41_row_shard/tests/test_meta_path_chaining.py new file mode 100644 index 00000000..a44bf943 --- /dev/null +++ b/integrations/vllm/ds41_row_shard/tests/test_meta_path_chaining.py @@ -0,0 +1,203 @@ +"""Regression tests verifying MetaPathFinder shims chain downstream finders instead of clobbering sys.meta_path.""" +from __future__ import annotations + +import hashlib +import importlib +import importlib.abc +import importlib.util +from pathlib import Path +import sys +import threading + +import ds41_row_shard + +ROOT = Path(__file__).resolve().parents[4] + + +def _make_recording_finder(target_name: str, marker: str, fired: list[str]) -> importlib.abc.MetaPathFinder: + """A second MetaPathFinder placed downstream of the shim under test.""" + + class _DownstreamLoader(importlib.abc.Loader): + def __init__(self, inner): + self._inner = inner + + def create_module(self, spec): + return self._inner.create_module(spec) + + def exec_module(self, module): + self._inner.exec_module(module) + fired.append(marker) + setattr(module, marker, True) + + class _DownstreamFinder(importlib.abc.MetaPathFinder): + def __init__(self): + self._resolving = threading.local() + + def find_spec(self, fullname, path=None, target=None): + if fullname != target_name: + return None + active = self._resolving.__dict__.setdefault("names", set()) + if fullname in active: + return None + active.add(fullname) + try: + meta = list(sys.meta_path) + start = meta.index(self) + 1 if self in meta else 0 + for finder in meta[start:]: + fn = getattr(finder, "find_spec", None) + if fn is None: + continue + spec = fn(fullname, path, target) + if spec is not None: + spec.loader = _DownstreamLoader(spec.loader) + return spec + finally: + active.discard(fullname) + return None + + return _DownstreamFinder() + + +def _write_temp_module(root: Path, dotted_name: str, body: str) -> Path: + parts = dotted_name.split(".") + current = root + for pkg in parts[:-1]: + current = current / pkg + current.mkdir(parents=True, exist_ok=True) + init = current / "__init__.py" + if not init.exists(): + init.write_text("", encoding="utf-8") + mod_file = current / f"{parts[-1]}.py" + mod_file.write_text(body, encoding="utf-8") + return mod_file + + +def test_ds41_row_shard_patch_finder_chains_with_downstream_meta_path_finder(tmp_path, monkeypatch): + target_name = "_sr_chain_ds41_pkg.target_mod" + _write_temp_module(tmp_path, target_name, "VALUE = 1\n") + fired: list[str] = [] + + def ds41_patch(module): + fired.append("ds41") + module.DS41_PATCHED = True + + monkeypatch.syspath_prepend(str(tmp_path)) + monkeypatch.setitem(ds41_row_shard._PATCHES, target_name, ds41_patch) + downstream = _make_recording_finder(target_name, "downstream", fired) + upstream = ds41_row_shard._PatchFinder() + monkeypatch.setattr(sys, "meta_path", [upstream, downstream, *sys.meta_path]) + for name in ("_sr_chain_ds41_pkg", target_name): + sys.modules.pop(name, None) + try: + mod = importlib.import_module(target_name) + assert mod.VALUE == 1 + assert getattr(mod, "downstream", False) is True + assert getattr(mod, "DS41_PATCHED", False) is True + assert fired == ["downstream", "ds41"] + finally: + for name in ("_sr_chain_ds41_pkg", target_name): + sys.modules.pop(name, None) + + +def test_qwen4_collectives_finder_chains_with_downstream_meta_path_finder(tmp_path, monkeypatch): + target_name = "_sr_chain_qwen4_coll_pkg.adapter_mod" + mod_file = _write_temp_module(tmp_path, target_name, "MARKER = 'orig'\n") + digest = hashlib.sha256(mod_file.read_bytes()).hexdigest() + fired: list[str] = [] + + monkeypatch.setenv("QWEN_DISPATCH_MODE", "both") + monkeypatch.setenv("QWEN_DISPATCH_AR_BYTES", "1024") + monkeypatch.setenv("QWEN_DISPATCH_TRACE", "0") + original_meta = list(sys.meta_path) + policy_path = ROOT / "integrations/vllm/qwen4_collectives/qwen38_collective_policy.py" + spec = importlib.util.spec_from_file_location("_qwen4_coll_chain_under_test", policy_path) + policy = importlib.util.module_from_spec(spec) + try: + spec.loader.exec_module(policy) + # Remove the auto-inserted finder and test an explicit stacked pair [policy.Finder, downstream]. + sys.meta_path[:] = original_meta + monkeypatch.setitem(policy.PATCHES, target_name, lambda mod: (fired.append("qwen4_coll"), setattr(mod, "QWEN_COLL", True))) + monkeypatch.setitem(policy.SOURCE_HASHES, target_name, digest) + monkeypatch.syspath_prepend(str(tmp_path)) + downstream = _make_recording_finder(target_name, "downstream", fired) + upstream = policy.Finder() + monkeypatch.setattr(sys, "meta_path", [upstream, downstream, *original_meta]) + for name in ("_sr_chain_qwen4_coll_pkg", target_name): + sys.modules.pop(name, None) + mod = importlib.import_module(target_name) + assert mod.MARKER == "orig" + assert getattr(mod, "downstream", False) is True + assert getattr(mod, "QWEN_COLL", False) is True + assert fired == ["downstream", "qwen4_coll"] + finally: + sys.meta_path[:] = original_meta + for name in ("_sr_chain_qwen4_coll_pkg", target_name): + sys.modules.pop(name, None) + + +def test_qwen4_prefill_finders_chain_with_downstream_meta_path_finders(tmp_path, monkeypatch): + for rel_path, env_flag, env_hash, tag in ( + ("integrations/vllm/qwen4_prefill/qwen4_hc_fusion.py", "QWEN_HC_FUSION", "QWEN_HC_SOURCE_SHA256", "hc"), + ("integrations/vllm/qwen4_prefill/qwen4_mtp_gemm.py", "QWEN_MTP_TORCH_PREFILL", "QWEN_MTP_SOURCE_SHA256", "mtp"), + ): + target_name = f"_sr_chain_qwen4_{tag}_pkg.target_mod" + mod_file = _write_temp_module(tmp_path, target_name, f"TAG = {tag!r}\n") + digest = hashlib.sha256(mod_file.read_bytes()).hexdigest() + fired: list[str] = [] + + monkeypatch.setenv(env_flag, "1") + monkeypatch.setenv(env_hash, digest) + original_meta = list(sys.meta_path) + mod_path = ROOT / rel_path + spec = importlib.util.spec_from_file_location(f"_qwen4_{tag}_chain_under_test", mod_path) + shim = importlib.util.module_from_spec(spec) + try: + spec.loader.exec_module(shim) + sys.meta_path[:] = original_meta + monkeypatch.setattr(shim, "TARGET", target_name) + monkeypatch.setattr(shim, "EXPECTED", digest) + monkeypatch.setattr(shim, "patch", lambda mod, _t=tag: (fired.append(_t), setattr(mod, f"PATCHED_{_t}", True))) + monkeypatch.syspath_prepend(str(tmp_path)) + downstream = _make_recording_finder(target_name, "downstream", fired) + upstream = shim.Finder() + monkeypatch.setattr(sys, "meta_path", [upstream, downstream, *original_meta]) + for name in (f"_sr_chain_qwen4_{tag}_pkg", target_name): + sys.modules.pop(name, None) + mod = importlib.import_module(target_name) + assert mod.TAG == tag + assert getattr(mod, "downstream", False) is True + assert getattr(mod, f"PATCHED_{tag}", False) is True + assert fired == ["downstream", tag] + finally: + sys.meta_path[:] = original_meta + for name in (f"_sr_chain_qwen4_{tag}_pkg", target_name): + sys.modules.pop(name, None) + + +def test_glm_patch_on_import_finders_chain_without_clobbering_or_reentering(tmp_path, monkeypatch): + from integrations.vllm.glm53full_speedups import glm53full_speedups + from integrations.vllm.glm_dcp_decode_comm import glm_dcp_decode_comm + from integrations.vllm.glm_dsa_indexer_split import glm_dsa_indexer_split + + target_name = "_sr_chain_glm_pkg.attention_mod" + _write_temp_module(tmp_path, target_name, "VALUE = 42\n") + fired: list[str] = [] + + f1 = glm53full_speedups.PatchOnImport({target_name: lambda m: (fired.append("speedups"), setattr(m, "F1", True))}) + f2 = glm_dcp_decode_comm.PatchOnImport({target_name: lambda m: (fired.append("dcp"), setattr(m, "F2", True))}) + f3 = glm_dsa_indexer_split.PatchOnImport({target_name: lambda m: (fired.append("indexer"), setattr(m, "F3", True))}) + monkeypatch.syspath_prepend(str(tmp_path)) + monkeypatch.setattr(sys, "meta_path", [f1, f2, f3, *sys.meta_path]) + for name in ("_sr_chain_glm_pkg", target_name): + sys.modules.pop(name, None) + try: + mod = importlib.import_module(target_name) + assert mod.VALUE == 42 + assert getattr(mod, "F1", False) is True + assert getattr(mod, "F2", False) is True + assert getattr(mod, "F3", False) is True + assert fired == ["indexer", "dcp", "speedups"] + finally: + for name in ("_sr_chain_glm_pkg", target_name): + sys.modules.pop(name, None) + diff --git a/integrations/vllm/glm53full_speedups/glm53full_speedups/__init__.py b/integrations/vllm/glm53full_speedups/glm53full_speedups/__init__.py index b13648d2..4b6a1756 100644 --- a/integrations/vllm/glm53full_speedups/glm53full_speedups/__init__.py +++ b/integrations/vllm/glm53full_speedups/glm53full_speedups/__init__.py @@ -416,7 +416,9 @@ def find_spec(self, fullname, path=None, target=None): active.add(fullname) try: spec = None - for finder in list(sys.meta_path): + meta_path = list(sys.meta_path) + start = meta_path.index(self) + 1 if self in meta_path else 0 + for finder in meta_path[start:]: find_spec = getattr(finder, "find_spec", None) if finder is self or find_spec is None: continue diff --git a/integrations/vllm/glm_dcp_decode_comm/glm_dcp_decode_comm/__init__.py b/integrations/vllm/glm_dcp_decode_comm/glm_dcp_decode_comm/__init__.py index 12d6588f..e4556430 100644 --- a/integrations/vllm/glm_dcp_decode_comm/glm_dcp_decode_comm/__init__.py +++ b/integrations/vllm/glm_dcp_decode_comm/glm_dcp_decode_comm/__init__.py @@ -682,7 +682,9 @@ def find_spec(self, fullname, path=None, target=None): active.add(fullname) try: spec = None - for finder in list(sys.meta_path): + meta_path = list(sys.meta_path) + start = meta_path.index(self) + 1 if self in meta_path else 0 + for finder in meta_path[start:]: find_spec = getattr(finder, "find_spec", None) if finder is self or find_spec is None: continue diff --git a/integrations/vllm/glm_dsa_indexer_split/glm_dsa_indexer_split/__init__.py b/integrations/vllm/glm_dsa_indexer_split/glm_dsa_indexer_split/__init__.py index cb5d51fb..be41562d 100644 --- a/integrations/vllm/glm_dsa_indexer_split/glm_dsa_indexer_split/__init__.py +++ b/integrations/vllm/glm_dsa_indexer_split/glm_dsa_indexer_split/__init__.py @@ -469,7 +469,9 @@ def find_spec(self, fullname, path=None, target=None): active.add(fullname) try: spec = None - for finder in list(sys.meta_path): + meta_path = list(sys.meta_path) + start = meta_path.index(self) + 1 if self in meta_path else 0 + for finder in meta_path[start:]: find_spec = getattr(finder, "find_spec", None) if finder is self or find_spec is None: continue diff --git a/integrations/vllm/qwen4_collectives/qwen38_collective_policy.py b/integrations/vllm/qwen4_collectives/qwen38_collective_policy.py index 58c86438..c8137edf 100644 --- a/integrations/vllm/qwen4_collectives/qwen38_collective_policy.py +++ b/integrations/vllm/qwen4_collectives/qwen38_collective_policy.py @@ -7,6 +7,7 @@ import json import os import sys +import threading from pathlib import Path MODE = os.environ.get("QWEN_DISPATCH_MODE") @@ -153,10 +154,35 @@ def exec_module(self, module): class Finder(importlib.abc.MetaPathFinder): + def __init__(self): + self._resolving = threading.local() + + def _find_downstream_spec(self, fullname, path, target): + meta_path = list(sys.meta_path) + if self in meta_path: + candidates = meta_path[meta_path.index(self) + 1:] + else: + candidates = [f for f in meta_path if f is not self and not isinstance(f, type(self))] + for finder in candidates: + find_spec = getattr(finder, "find_spec", None) + if find_spec is None: + continue + spec = find_spec(fullname, path, target) + if spec is not None: + return spec + return None + def find_spec(self, fullname, path=None, target=None): if fullname not in PATCHES: return None - spec = importlib.machinery.PathFinder.find_spec(fullname, path) + active = self._resolving.__dict__.setdefault("names", set()) + if fullname in active: + return None + active.add(fullname) + try: + spec = self._find_downstream_spec(fullname, path, target) + finally: + active.discard(fullname) if spec is None or spec.loader is None: raise SystemExit("Required Qwen dispatch module is missing: " + fullname) if ( diff --git a/integrations/vllm/qwen4_prefill/qwen4_hc_fusion.py b/integrations/vllm/qwen4_prefill/qwen4_hc_fusion.py index ab57cace..c469d307 100644 --- a/integrations/vllm/qwen4_prefill/qwen4_hc_fusion.py +++ b/integrations/vllm/qwen4_prefill/qwen4_hc_fusion.py @@ -6,6 +6,7 @@ import json import os import sys +import threading from pathlib import Path TARGET = "vllm.models.qwen4_exp.nvidia.hyperconnection" @@ -184,10 +185,35 @@ def exec_module(self, module): class Finder(importlib.abc.MetaPathFinder): + def __init__(self): + self._resolving = threading.local() + + def _find_downstream_spec(self, fullname, path, target): + meta_path = list(sys.meta_path) + if self in meta_path: + candidates = meta_path[meta_path.index(self) + 1:] + else: + candidates = [f for f in meta_path if f is not self and not isinstance(f, type(self))] + for finder in candidates: + find_spec = getattr(finder, "find_spec", None) + if find_spec is None: + continue + spec = find_spec(fullname, path, target) + if spec is not None: + return spec + return None + def find_spec(self, fullname, path=None, target=None): if fullname != TARGET: return None - spec = importlib.machinery.PathFinder.find_spec(fullname, path) + active = self._resolving.__dict__.setdefault("names", set()) + if fullname in active: + return None + active.add(fullname) + try: + spec = self._find_downstream_spec(fullname, path, target) + finally: + active.discard(fullname) if ( spec is None or spec.loader is None diff --git a/integrations/vllm/qwen4_prefill/qwen4_mtp_gemm.py b/integrations/vllm/qwen4_prefill/qwen4_mtp_gemm.py index 45a97a67..6708098b 100644 --- a/integrations/vllm/qwen4_prefill/qwen4_mtp_gemm.py +++ b/integrations/vllm/qwen4_prefill/qwen4_mtp_gemm.py @@ -6,6 +6,7 @@ import json import os import sys +import threading from pathlib import Path TARGET = "b12x.sequence.mtp_feedback._kernels" @@ -110,10 +111,35 @@ def exec_module(self, module): class Finder(importlib.abc.MetaPathFinder): + def __init__(self): + self._resolving = threading.local() + + def _find_downstream_spec(self, fullname, path, target): + meta_path = list(sys.meta_path) + if self in meta_path: + candidates = meta_path[meta_path.index(self) + 1:] + else: + candidates = [f for f in meta_path if f is not self and not isinstance(f, type(self))] + for finder in candidates: + find_spec = getattr(finder, "find_spec", None) + if find_spec is None: + continue + spec = find_spec(fullname, path, target) + if spec is not None: + return spec + return None + def find_spec(self, fullname, path=None, target=None): if fullname != TARGET: return None - spec = importlib.machinery.PathFinder.find_spec(fullname, path) + active = self._resolving.__dict__.setdefault("names", set()) + if fullname in active: + return None + active.add(fullname) + try: + spec = self._find_downstream_spec(fullname, path, target) + finally: + active.discard(fullname) if ( spec is None or spec.loader is None diff --git a/profiles/deepseek-v41-flash-tp4/compose/compose.rank0.yaml b/profiles/deepseek-v41-flash-tp4/compose/compose.rank0.yaml index 1a54d064..5914b3de 100644 --- a/profiles/deepseek-v41-flash-tp4/compose/compose.rank0.yaml +++ b/profiles/deepseek-v41-flash-tp4/compose/compose.rank0.yaml @@ -149,7 +149,7 @@ services: VLLM_WORKER_MULTIPROC_METHOD: spawn XDG_CACHE_HOME: /cache/deepseek-v41-flash-f625053225d4-dba1be0a40aa labels: - io.sparkring.deployment: d4f418f91a9ebcf8b222ae6793349e15c8537f535da88d354aaa7a77189d4635 + io.sparkring.deployment: 980f76655827e051d74328d2c4927d2f4fa1f4b0beadc0855f7b0bb2df170fad io.sparkring.rank: '0' network_mode: host ipc: host diff --git a/profiles/deepseek-v41-flash-tp4/compose/compose.rank1.yaml b/profiles/deepseek-v41-flash-tp4/compose/compose.rank1.yaml index 7fb2b2f5..b4b83926 100644 --- a/profiles/deepseek-v41-flash-tp4/compose/compose.rank1.yaml +++ b/profiles/deepseek-v41-flash-tp4/compose/compose.rank1.yaml @@ -150,7 +150,7 @@ services: VLLM_WORKER_MULTIPROC_METHOD: spawn XDG_CACHE_HOME: /cache/deepseek-v41-flash-f625053225d4-dba1be0a40aa labels: - io.sparkring.deployment: d4f418f91a9ebcf8b222ae6793349e15c8537f535da88d354aaa7a77189d4635 + io.sparkring.deployment: 980f76655827e051d74328d2c4927d2f4fa1f4b0beadc0855f7b0bb2df170fad io.sparkring.rank: '1' network_mode: host ipc: host diff --git a/profiles/deepseek-v41-flash-tp4/compose/compose.rank2.yaml b/profiles/deepseek-v41-flash-tp4/compose/compose.rank2.yaml index 24969a9a..39295ce8 100644 --- a/profiles/deepseek-v41-flash-tp4/compose/compose.rank2.yaml +++ b/profiles/deepseek-v41-flash-tp4/compose/compose.rank2.yaml @@ -150,7 +150,7 @@ services: VLLM_WORKER_MULTIPROC_METHOD: spawn XDG_CACHE_HOME: /cache/deepseek-v41-flash-f625053225d4-dba1be0a40aa labels: - io.sparkring.deployment: d4f418f91a9ebcf8b222ae6793349e15c8537f535da88d354aaa7a77189d4635 + io.sparkring.deployment: 980f76655827e051d74328d2c4927d2f4fa1f4b0beadc0855f7b0bb2df170fad io.sparkring.rank: '2' network_mode: host ipc: host diff --git a/profiles/deepseek-v41-flash-tp4/compose/compose.rank3.yaml b/profiles/deepseek-v41-flash-tp4/compose/compose.rank3.yaml index 8ac25d0b..acc915da 100644 --- a/profiles/deepseek-v41-flash-tp4/compose/compose.rank3.yaml +++ b/profiles/deepseek-v41-flash-tp4/compose/compose.rank3.yaml @@ -150,7 +150,7 @@ services: VLLM_WORKER_MULTIPROC_METHOD: spawn XDG_CACHE_HOME: /cache/deepseek-v41-flash-f625053225d4-dba1be0a40aa labels: - io.sparkring.deployment: d4f418f91a9ebcf8b222ae6793349e15c8537f535da88d354aaa7a77189d4635 + io.sparkring.deployment: 980f76655827e051d74328d2c4927d2f4fa1f4b0beadc0855f7b0bb2df170fad io.sparkring.rank: '3' network_mode: host ipc: host diff --git a/profiles/deepseek-v41-flash-tp4/compose/selection.json b/profiles/deepseek-v41-flash-tp4/compose/selection.json index 9b0717e1..15e98fa1 100644 --- a/profiles/deepseek-v41-flash-tp4/compose/selection.json +++ b/profiles/deepseek-v41-flash-tp4/compose/selection.json @@ -3,5 +3,5 @@ "profile": "deepseek-v41-flash-tp4", "checkpoint": "original", "image_lock": "runtime/releases/dev-20261016-sparkcache-4a17f1f5198e-status038/installer-image.json", - "deployment": "d4f418f91a9ebcf8b222ae6793349e15c8537f535da88d354aaa7a77189d4635" + "deployment": "980f76655827e051d74328d2c4927d2f4fa1f4b0beadc0855f7b0bb2df170fad" } diff --git a/profiles/glm53-flash-nvfp4-spark-tp2/compose/compose.rank0.yaml b/profiles/glm53-flash-nvfp4-spark-tp2/compose/compose.rank0.yaml index 387a90c2..706385c1 100644 --- a/profiles/glm53-flash-nvfp4-spark-tp2/compose/compose.rank0.yaml +++ b/profiles/glm53-flash-nvfp4-spark-tp2/compose/compose.rank0.yaml @@ -181,7 +181,7 @@ services: VLLM_WORKER_MULTIPROC_METHOD: spawn XDG_CACHE_HOME: /cache/glm53-flash-nvfp4-spark-f625053225d4-dec48abd33ef labels: - io.sparkring.deployment: dd06028efdf4cc20653a0ef7ddd932236f135e67bab4a400ef017fe604588333 + io.sparkring.deployment: 8b8ccdb3006f0780f1de86849c967136aa3d7cd1892a2e5ecfaee3ff11d867d4 io.sparkring.rank: '0' network_mode: host ipc: host diff --git a/profiles/glm53-flash-nvfp4-spark-tp2/compose/compose.rank1.yaml b/profiles/glm53-flash-nvfp4-spark-tp2/compose/compose.rank1.yaml index 8e56e909..f96e95ca 100644 --- a/profiles/glm53-flash-nvfp4-spark-tp2/compose/compose.rank1.yaml +++ b/profiles/glm53-flash-nvfp4-spark-tp2/compose/compose.rank1.yaml @@ -180,7 +180,7 @@ services: VLLM_WORKER_MULTIPROC_METHOD: spawn XDG_CACHE_HOME: /cache/glm53-flash-nvfp4-spark-f625053225d4-dec48abd33ef labels: - io.sparkring.deployment: dd06028efdf4cc20653a0ef7ddd932236f135e67bab4a400ef017fe604588333 + io.sparkring.deployment: 8b8ccdb3006f0780f1de86849c967136aa3d7cd1892a2e5ecfaee3ff11d867d4 io.sparkring.rank: '1' network_mode: host ipc: host diff --git a/profiles/glm53-flash-nvfp4-spark-tp2/compose/selection.json b/profiles/glm53-flash-nvfp4-spark-tp2/compose/selection.json index a40245ab..5b6edb42 100644 --- a/profiles/glm53-flash-nvfp4-spark-tp2/compose/selection.json +++ b/profiles/glm53-flash-nvfp4-spark-tp2/compose/selection.json @@ -3,5 +3,5 @@ "profile": "glm53-flash-nvfp4-spark-tp2", "checkpoint": "csf", "image_lock": "runtime/releases/dev-20261016-sparkcache-4a17f1f5198e-status038/installer-image.json", - "deployment": "dd06028efdf4cc20653a0ef7ddd932236f135e67bab4a400ef017fe604588333" + "deployment": "8b8ccdb3006f0780f1de86849c967136aa3d7cd1892a2e5ecfaee3ff11d867d4" } diff --git a/profiles/glm53-flash-nvfp4-spark-tp4/compose/compose.rank0.yaml b/profiles/glm53-flash-nvfp4-spark-tp4/compose/compose.rank0.yaml index 9ce6f29d..dec0c2c6 100644 --- a/profiles/glm53-flash-nvfp4-spark-tp4/compose/compose.rank0.yaml +++ b/profiles/glm53-flash-nvfp4-spark-tp4/compose/compose.rank0.yaml @@ -195,7 +195,7 @@ services: VLLM_WORKER_MULTIPROC_METHOD: spawn XDG_CACHE_HOME: /cache/glm53-flash-nvfp4-spark-f625053225d4-dec48abd33ef labels: - io.sparkring.deployment: 2483156c11e1e430ce46039c0bfc02f3bdf814b026565a5b22fbf30d2b7e0c7f + io.sparkring.deployment: 87d768b6f1e284c8045d7e082fb9434c891e2612857c290e247ba4ea5ad36aa0 io.sparkring.rank: '0' network_mode: host ipc: host diff --git a/profiles/glm53-flash-nvfp4-spark-tp4/compose/compose.rank1.yaml b/profiles/glm53-flash-nvfp4-spark-tp4/compose/compose.rank1.yaml index ea595c60..09985c4d 100644 --- a/profiles/glm53-flash-nvfp4-spark-tp4/compose/compose.rank1.yaml +++ b/profiles/glm53-flash-nvfp4-spark-tp4/compose/compose.rank1.yaml @@ -194,7 +194,7 @@ services: VLLM_WORKER_MULTIPROC_METHOD: spawn XDG_CACHE_HOME: /cache/glm53-flash-nvfp4-spark-f625053225d4-dec48abd33ef labels: - io.sparkring.deployment: 2483156c11e1e430ce46039c0bfc02f3bdf814b026565a5b22fbf30d2b7e0c7f + io.sparkring.deployment: 87d768b6f1e284c8045d7e082fb9434c891e2612857c290e247ba4ea5ad36aa0 io.sparkring.rank: '1' network_mode: host ipc: host diff --git a/profiles/glm53-flash-nvfp4-spark-tp4/compose/compose.rank2.yaml b/profiles/glm53-flash-nvfp4-spark-tp4/compose/compose.rank2.yaml index 90e15343..12a43d4b 100644 --- a/profiles/glm53-flash-nvfp4-spark-tp4/compose/compose.rank2.yaml +++ b/profiles/glm53-flash-nvfp4-spark-tp4/compose/compose.rank2.yaml @@ -194,7 +194,7 @@ services: VLLM_WORKER_MULTIPROC_METHOD: spawn XDG_CACHE_HOME: /cache/glm53-flash-nvfp4-spark-f625053225d4-dec48abd33ef labels: - io.sparkring.deployment: 2483156c11e1e430ce46039c0bfc02f3bdf814b026565a5b22fbf30d2b7e0c7f + io.sparkring.deployment: 87d768b6f1e284c8045d7e082fb9434c891e2612857c290e247ba4ea5ad36aa0 io.sparkring.rank: '2' network_mode: host ipc: host diff --git a/profiles/glm53-flash-nvfp4-spark-tp4/compose/compose.rank3.yaml b/profiles/glm53-flash-nvfp4-spark-tp4/compose/compose.rank3.yaml index 6e187fce..49ccfd0b 100644 --- a/profiles/glm53-flash-nvfp4-spark-tp4/compose/compose.rank3.yaml +++ b/profiles/glm53-flash-nvfp4-spark-tp4/compose/compose.rank3.yaml @@ -194,7 +194,7 @@ services: VLLM_WORKER_MULTIPROC_METHOD: spawn XDG_CACHE_HOME: /cache/glm53-flash-nvfp4-spark-f625053225d4-dec48abd33ef labels: - io.sparkring.deployment: 2483156c11e1e430ce46039c0bfc02f3bdf814b026565a5b22fbf30d2b7e0c7f + io.sparkring.deployment: 87d768b6f1e284c8045d7e082fb9434c891e2612857c290e247ba4ea5ad36aa0 io.sparkring.rank: '3' network_mode: host ipc: host diff --git a/profiles/glm53-flash-nvfp4-spark-tp4/compose/selection.json b/profiles/glm53-flash-nvfp4-spark-tp4/compose/selection.json index a8de182c..732bfeee 100644 --- a/profiles/glm53-flash-nvfp4-spark-tp4/compose/selection.json +++ b/profiles/glm53-flash-nvfp4-spark-tp4/compose/selection.json @@ -3,5 +3,5 @@ "profile": "glm53-flash-nvfp4-spark-tp4", "checkpoint": "csf", "image_lock": "runtime/releases/dev-20261016-sparkcache-4a17f1f5198e-status038/installer-image.json", - "deployment": "2483156c11e1e430ce46039c0bfc02f3bdf814b026565a5b22fbf30d2b7e0c7f" + "deployment": "87d768b6f1e284c8045d7e082fb9434c891e2612857c290e247ba4ea5ad36aa0" } diff --git a/profiles/mimo-v26-flash-mopd-tp2/compose/compose.rank0.yaml b/profiles/mimo-v26-flash-mopd-tp2/compose/compose.rank0.yaml index 3423befd..076169d8 100644 --- a/profiles/mimo-v26-flash-mopd-tp2/compose/compose.rank0.yaml +++ b/profiles/mimo-v26-flash-mopd-tp2/compose/compose.rank0.yaml @@ -149,7 +149,7 @@ services: VLLM_WORKER_MULTIPROC_METHOD: spawn XDG_CACHE_HOME: /cache/mimo-v26-flash-rl-f625053225d4-2479e2d0029e labels: - io.sparkring.deployment: 82f9d92a3a85d38a3b51512f3a591cc2bbfb474f93302696f1624aafd3d56de4 + io.sparkring.deployment: ad63a67b504d3ecfa00cdd0505a532cd58724d510c25c072847ea91427a2e072 io.sparkring.rank: '0' network_mode: host ipc: host diff --git a/profiles/mimo-v26-flash-mopd-tp2/compose/compose.rank1.yaml b/profiles/mimo-v26-flash-mopd-tp2/compose/compose.rank1.yaml index 503d741f..5c67c620 100644 --- a/profiles/mimo-v26-flash-mopd-tp2/compose/compose.rank1.yaml +++ b/profiles/mimo-v26-flash-mopd-tp2/compose/compose.rank1.yaml @@ -150,7 +150,7 @@ services: VLLM_WORKER_MULTIPROC_METHOD: spawn XDG_CACHE_HOME: /cache/mimo-v26-flash-rl-f625053225d4-2479e2d0029e labels: - io.sparkring.deployment: 82f9d92a3a85d38a3b51512f3a591cc2bbfb474f93302696f1624aafd3d56de4 + io.sparkring.deployment: ad63a67b504d3ecfa00cdd0505a532cd58724d510c25c072847ea91427a2e072 io.sparkring.rank: '1' network_mode: host ipc: host diff --git a/profiles/mimo-v26-flash-mopd-tp2/compose/selection.json b/profiles/mimo-v26-flash-mopd-tp2/compose/selection.json index b259fc57..bedb0f49 100644 --- a/profiles/mimo-v26-flash-mopd-tp2/compose/selection.json +++ b/profiles/mimo-v26-flash-mopd-tp2/compose/selection.json @@ -3,5 +3,5 @@ "profile": "mimo-v26-flash-mopd-tp2", "checkpoint": null, "image_lock": "runtime/releases/dev-20261016-sparkcache-4a17f1f5198e-status038/installer-image.json", - "deployment": "82f9d92a3a85d38a3b51512f3a591cc2bbfb474f93302696f1624aafd3d56de4" + "deployment": "ad63a67b504d3ecfa00cdd0505a532cd58724d510c25c072847ea91427a2e072" } diff --git a/profiles/mimo-v26-flash-mopd-tp4/compose/compose.rank0.yaml b/profiles/mimo-v26-flash-mopd-tp4/compose/compose.rank0.yaml index c8a15277..996a047c 100644 --- a/profiles/mimo-v26-flash-mopd-tp4/compose/compose.rank0.yaml +++ b/profiles/mimo-v26-flash-mopd-tp4/compose/compose.rank0.yaml @@ -163,7 +163,7 @@ services: VLLM_WORKER_MULTIPROC_METHOD: spawn XDG_CACHE_HOME: /cache/mimo-v26-flash-rl-f625053225d4-2479e2d0029e labels: - io.sparkring.deployment: dacb6a2559a9d3f9b3072fcc277ebb98870a16f5a0a717a7ce11d1218952c473 + io.sparkring.deployment: 937270f5d4f3734cad73bc63be20f45acafeae6a6af28dda8414514d0d6b8e09 io.sparkring.rank: '0' network_mode: host ipc: host diff --git a/profiles/mimo-v26-flash-mopd-tp4/compose/compose.rank1.yaml b/profiles/mimo-v26-flash-mopd-tp4/compose/compose.rank1.yaml index 9cb7ee03..ca8e5acf 100644 --- a/profiles/mimo-v26-flash-mopd-tp4/compose/compose.rank1.yaml +++ b/profiles/mimo-v26-flash-mopd-tp4/compose/compose.rank1.yaml @@ -164,7 +164,7 @@ services: VLLM_WORKER_MULTIPROC_METHOD: spawn XDG_CACHE_HOME: /cache/mimo-v26-flash-rl-f625053225d4-2479e2d0029e labels: - io.sparkring.deployment: dacb6a2559a9d3f9b3072fcc277ebb98870a16f5a0a717a7ce11d1218952c473 + io.sparkring.deployment: 937270f5d4f3734cad73bc63be20f45acafeae6a6af28dda8414514d0d6b8e09 io.sparkring.rank: '1' network_mode: host ipc: host diff --git a/profiles/mimo-v26-flash-mopd-tp4/compose/compose.rank2.yaml b/profiles/mimo-v26-flash-mopd-tp4/compose/compose.rank2.yaml index 39c13a2d..216f807c 100644 --- a/profiles/mimo-v26-flash-mopd-tp4/compose/compose.rank2.yaml +++ b/profiles/mimo-v26-flash-mopd-tp4/compose/compose.rank2.yaml @@ -164,7 +164,7 @@ services: VLLM_WORKER_MULTIPROC_METHOD: spawn XDG_CACHE_HOME: /cache/mimo-v26-flash-rl-f625053225d4-2479e2d0029e labels: - io.sparkring.deployment: dacb6a2559a9d3f9b3072fcc277ebb98870a16f5a0a717a7ce11d1218952c473 + io.sparkring.deployment: 937270f5d4f3734cad73bc63be20f45acafeae6a6af28dda8414514d0d6b8e09 io.sparkring.rank: '2' network_mode: host ipc: host diff --git a/profiles/mimo-v26-flash-mopd-tp4/compose/compose.rank3.yaml b/profiles/mimo-v26-flash-mopd-tp4/compose/compose.rank3.yaml index bc90dff6..d3189d81 100644 --- a/profiles/mimo-v26-flash-mopd-tp4/compose/compose.rank3.yaml +++ b/profiles/mimo-v26-flash-mopd-tp4/compose/compose.rank3.yaml @@ -164,7 +164,7 @@ services: VLLM_WORKER_MULTIPROC_METHOD: spawn XDG_CACHE_HOME: /cache/mimo-v26-flash-rl-f625053225d4-2479e2d0029e labels: - io.sparkring.deployment: dacb6a2559a9d3f9b3072fcc277ebb98870a16f5a0a717a7ce11d1218952c473 + io.sparkring.deployment: 937270f5d4f3734cad73bc63be20f45acafeae6a6af28dda8414514d0d6b8e09 io.sparkring.rank: '3' network_mode: host ipc: host diff --git a/profiles/mimo-v26-flash-mopd-tp4/compose/selection.json b/profiles/mimo-v26-flash-mopd-tp4/compose/selection.json index c0476964..16167f85 100644 --- a/profiles/mimo-v26-flash-mopd-tp4/compose/selection.json +++ b/profiles/mimo-v26-flash-mopd-tp4/compose/selection.json @@ -3,5 +3,5 @@ "profile": "mimo-v26-flash-mopd-tp4", "checkpoint": null, "image_lock": "runtime/releases/dev-20261016-sparkcache-4a17f1f5198e-status038/installer-image.json", - "deployment": "dacb6a2559a9d3f9b3072fcc277ebb98870a16f5a0a717a7ce11d1218952c473" + "deployment": "937270f5d4f3734cad73bc63be20f45acafeae6a6af28dda8414514d0d6b8e09" } diff --git a/profiles/qwen38-flash-next-qad-tp4-sparkcache/compose/compose.rank0.yaml b/profiles/qwen38-flash-next-qad-tp4-sparkcache/compose/compose.rank0.yaml index 94e5bb7c..b03bb9be 100644 --- a/profiles/qwen38-flash-next-qad-tp4-sparkcache/compose/compose.rank0.yaml +++ b/profiles/qwen38-flash-next-qad-tp4-sparkcache/compose/compose.rank0.yaml @@ -170,7 +170,7 @@ services: VLLM_WORKER_MULTIPROC_METHOD: spawn XDG_CACHE_HOME: /cache/qwen-flash-next-bc16a9819d85-629bc3218833 labels: - io.sparkring.deployment: 60caff55848ee1648e9e6611d002d2d2801f9d7d69faed18b9a1dcbf3b03ac73 + io.sparkring.deployment: ba3aff276915e2279c9c3c61ca1d0fc5d198fcd98c68ef5fa76c271747e8430d io.sparkring.rank: '0' network_mode: host ipc: host diff --git a/profiles/qwen38-flash-next-qad-tp4-sparkcache/compose/compose.rank1.yaml b/profiles/qwen38-flash-next-qad-tp4-sparkcache/compose/compose.rank1.yaml index a10797e2..991deeac 100644 --- a/profiles/qwen38-flash-next-qad-tp4-sparkcache/compose/compose.rank1.yaml +++ b/profiles/qwen38-flash-next-qad-tp4-sparkcache/compose/compose.rank1.yaml @@ -171,7 +171,7 @@ services: VLLM_WORKER_MULTIPROC_METHOD: spawn XDG_CACHE_HOME: /cache/qwen-flash-next-bc16a9819d85-629bc3218833 labels: - io.sparkring.deployment: 60caff55848ee1648e9e6611d002d2d2801f9d7d69faed18b9a1dcbf3b03ac73 + io.sparkring.deployment: ba3aff276915e2279c9c3c61ca1d0fc5d198fcd98c68ef5fa76c271747e8430d io.sparkring.rank: '1' network_mode: host ipc: host diff --git a/profiles/qwen38-flash-next-qad-tp4-sparkcache/compose/compose.rank2.yaml b/profiles/qwen38-flash-next-qad-tp4-sparkcache/compose/compose.rank2.yaml index cfadab9a..0f13f8c7 100644 --- a/profiles/qwen38-flash-next-qad-tp4-sparkcache/compose/compose.rank2.yaml +++ b/profiles/qwen38-flash-next-qad-tp4-sparkcache/compose/compose.rank2.yaml @@ -171,7 +171,7 @@ services: VLLM_WORKER_MULTIPROC_METHOD: spawn XDG_CACHE_HOME: /cache/qwen-flash-next-bc16a9819d85-629bc3218833 labels: - io.sparkring.deployment: 60caff55848ee1648e9e6611d002d2d2801f9d7d69faed18b9a1dcbf3b03ac73 + io.sparkring.deployment: ba3aff276915e2279c9c3c61ca1d0fc5d198fcd98c68ef5fa76c271747e8430d io.sparkring.rank: '2' network_mode: host ipc: host diff --git a/profiles/qwen38-flash-next-qad-tp4-sparkcache/compose/compose.rank3.yaml b/profiles/qwen38-flash-next-qad-tp4-sparkcache/compose/compose.rank3.yaml index ceabccd8..39c53a2f 100644 --- a/profiles/qwen38-flash-next-qad-tp4-sparkcache/compose/compose.rank3.yaml +++ b/profiles/qwen38-flash-next-qad-tp4-sparkcache/compose/compose.rank3.yaml @@ -171,7 +171,7 @@ services: VLLM_WORKER_MULTIPROC_METHOD: spawn XDG_CACHE_HOME: /cache/qwen-flash-next-bc16a9819d85-629bc3218833 labels: - io.sparkring.deployment: 60caff55848ee1648e9e6611d002d2d2801f9d7d69faed18b9a1dcbf3b03ac73 + io.sparkring.deployment: ba3aff276915e2279c9c3c61ca1d0fc5d198fcd98c68ef5fa76c271747e8430d io.sparkring.rank: '3' network_mode: host ipc: host diff --git a/profiles/qwen38-flash-next-qad-tp4/compose/compose.rank0.yaml b/profiles/qwen38-flash-next-qad-tp4/compose/compose.rank0.yaml index cd7421cc..cbf06e42 100644 --- a/profiles/qwen38-flash-next-qad-tp4/compose/compose.rank0.yaml +++ b/profiles/qwen38-flash-next-qad-tp4/compose/compose.rank0.yaml @@ -176,7 +176,7 @@ services: VLLM_WORKER_MULTIPROC_METHOD: spawn XDG_CACHE_HOME: /cache/qwen-flash-next-f625053225d4-60215d26cf5e labels: - io.sparkring.deployment: d9933be41fe5865980162aedbc5af1a51c9f648a2e26b2265e240cd7f1a17f0e + io.sparkring.deployment: 7c6a48072f6d3856e21a55c746922e84d1dbe1aeda101f65dc958ec63bebca68 io.sparkring.rank: '0' network_mode: host ipc: host diff --git a/profiles/qwen38-flash-next-qad-tp4/compose/compose.rank1.yaml b/profiles/qwen38-flash-next-qad-tp4/compose/compose.rank1.yaml index be13d426..238125fa 100644 --- a/profiles/qwen38-flash-next-qad-tp4/compose/compose.rank1.yaml +++ b/profiles/qwen38-flash-next-qad-tp4/compose/compose.rank1.yaml @@ -177,7 +177,7 @@ services: VLLM_WORKER_MULTIPROC_METHOD: spawn XDG_CACHE_HOME: /cache/qwen-flash-next-f625053225d4-60215d26cf5e labels: - io.sparkring.deployment: d9933be41fe5865980162aedbc5af1a51c9f648a2e26b2265e240cd7f1a17f0e + io.sparkring.deployment: 7c6a48072f6d3856e21a55c746922e84d1dbe1aeda101f65dc958ec63bebca68 io.sparkring.rank: '1' network_mode: host ipc: host diff --git a/profiles/qwen38-flash-next-qad-tp4/compose/compose.rank2.yaml b/profiles/qwen38-flash-next-qad-tp4/compose/compose.rank2.yaml index bfe33746..5e5ba850 100644 --- a/profiles/qwen38-flash-next-qad-tp4/compose/compose.rank2.yaml +++ b/profiles/qwen38-flash-next-qad-tp4/compose/compose.rank2.yaml @@ -177,7 +177,7 @@ services: VLLM_WORKER_MULTIPROC_METHOD: spawn XDG_CACHE_HOME: /cache/qwen-flash-next-f625053225d4-60215d26cf5e labels: - io.sparkring.deployment: d9933be41fe5865980162aedbc5af1a51c9f648a2e26b2265e240cd7f1a17f0e + io.sparkring.deployment: 7c6a48072f6d3856e21a55c746922e84d1dbe1aeda101f65dc958ec63bebca68 io.sparkring.rank: '2' network_mode: host ipc: host diff --git a/profiles/qwen38-flash-next-qad-tp4/compose/compose.rank3.yaml b/profiles/qwen38-flash-next-qad-tp4/compose/compose.rank3.yaml index d3057b4f..0292d389 100644 --- a/profiles/qwen38-flash-next-qad-tp4/compose/compose.rank3.yaml +++ b/profiles/qwen38-flash-next-qad-tp4/compose/compose.rank3.yaml @@ -177,7 +177,7 @@ services: VLLM_WORKER_MULTIPROC_METHOD: spawn XDG_CACHE_HOME: /cache/qwen-flash-next-f625053225d4-60215d26cf5e labels: - io.sparkring.deployment: d9933be41fe5865980162aedbc5af1a51c9f648a2e26b2265e240cd7f1a17f0e + io.sparkring.deployment: 7c6a48072f6d3856e21a55c746922e84d1dbe1aeda101f65dc958ec63bebca68 io.sparkring.rank: '3' network_mode: host ipc: host diff --git a/profiles/qwen38-flash-next-qad-tp4/compose/selection.json b/profiles/qwen38-flash-next-qad-tp4/compose/selection.json index 02bdf781..e172af2b 100644 --- a/profiles/qwen38-flash-next-qad-tp4/compose/selection.json +++ b/profiles/qwen38-flash-next-qad-tp4/compose/selection.json @@ -3,5 +3,5 @@ "profile": "qwen38-flash-next-qad-tp4", "checkpoint": "qad-step5500-ple1000", "image_lock": "runtime/releases/dev-20261016-sparkcache-4a17f1f5198e-status038/installer-image.json", - "deployment": "d9933be41fe5865980162aedbc5af1a51c9f648a2e26b2265e240cd7f1a17f0e" + "deployment": "7c6a48072f6d3856e21a55c746922e84d1dbe1aeda101f65dc958ec63bebca68" } diff --git a/profiles/qwen38-flash-next-tp2-sparkcache/compose/compose.rank0.yaml b/profiles/qwen38-flash-next-tp2-sparkcache/compose/compose.rank0.yaml index f0524433..37a3069b 100644 --- a/profiles/qwen38-flash-next-tp2-sparkcache/compose/compose.rank0.yaml +++ b/profiles/qwen38-flash-next-tp2-sparkcache/compose/compose.rank0.yaml @@ -147,7 +147,7 @@ services: VLLM_WORKER_MULTIPROC_METHOD: spawn XDG_CACHE_HOME: /cache/qwen-flash-next-bc16a9819d85-629bc3218833 labels: - io.sparkring.deployment: d200b01fbb52b1f1e7ca7c2c63ce50ae8f94c002080b0b9f33229688e586ebcd + io.sparkring.deployment: 42a0f8d70d4b03f7ca41ab5e9258ea280662fad53badac4b7600eb9697dec197 io.sparkring.rank: '0' network_mode: host ipc: host diff --git a/profiles/qwen38-flash-next-tp2-sparkcache/compose/compose.rank1.yaml b/profiles/qwen38-flash-next-tp2-sparkcache/compose/compose.rank1.yaml index d44d94da..73df4deb 100644 --- a/profiles/qwen38-flash-next-tp2-sparkcache/compose/compose.rank1.yaml +++ b/profiles/qwen38-flash-next-tp2-sparkcache/compose/compose.rank1.yaml @@ -148,7 +148,7 @@ services: VLLM_WORKER_MULTIPROC_METHOD: spawn XDG_CACHE_HOME: /cache/qwen-flash-next-bc16a9819d85-629bc3218833 labels: - io.sparkring.deployment: d200b01fbb52b1f1e7ca7c2c63ce50ae8f94c002080b0b9f33229688e586ebcd + io.sparkring.deployment: 42a0f8d70d4b03f7ca41ab5e9258ea280662fad53badac4b7600eb9697dec197 io.sparkring.rank: '1' network_mode: host ipc: host diff --git a/profiles/qwen38-flash-next-tp2/compose/compose.rank0.yaml b/profiles/qwen38-flash-next-tp2/compose/compose.rank0.yaml index 0e94a6a9..fa616579 100644 --- a/profiles/qwen38-flash-next-tp2/compose/compose.rank0.yaml +++ b/profiles/qwen38-flash-next-tp2/compose/compose.rank0.yaml @@ -160,7 +160,7 @@ services: VLLM_WORKER_MULTIPROC_METHOD: spawn XDG_CACHE_HOME: /cache/qwen-flash-next-f625053225d4-dc5b8ab2fa14 labels: - io.sparkring.deployment: 69d8190bd56a9d464a054d8c40ddb959c56bb3a0f2b0ad55df421f6e8f85e494 + io.sparkring.deployment: f46afc82bc9f734602d24926aae4a3dc5d40862172874504d284ad3fc6a2cd75 io.sparkring.rank: '0' network_mode: host ipc: host diff --git a/profiles/qwen38-flash-next-tp2/compose/compose.rank1.yaml b/profiles/qwen38-flash-next-tp2/compose/compose.rank1.yaml index 337e67a2..d7cdb54a 100644 --- a/profiles/qwen38-flash-next-tp2/compose/compose.rank1.yaml +++ b/profiles/qwen38-flash-next-tp2/compose/compose.rank1.yaml @@ -161,7 +161,7 @@ services: VLLM_WORKER_MULTIPROC_METHOD: spawn XDG_CACHE_HOME: /cache/qwen-flash-next-f625053225d4-dc5b8ab2fa14 labels: - io.sparkring.deployment: 69d8190bd56a9d464a054d8c40ddb959c56bb3a0f2b0ad55df421f6e8f85e494 + io.sparkring.deployment: f46afc82bc9f734602d24926aae4a3dc5d40862172874504d284ad3fc6a2cd75 io.sparkring.rank: '1' network_mode: host ipc: host diff --git a/profiles/qwen38-flash-next-tp2/compose/selection.json b/profiles/qwen38-flash-next-tp2/compose/selection.json index 435537fc..39af7859 100644 --- a/profiles/qwen38-flash-next-tp2/compose/selection.json +++ b/profiles/qwen38-flash-next-tp2/compose/selection.json @@ -3,5 +3,5 @@ "profile": "qwen38-flash-next-tp2", "checkpoint": "csf", "image_lock": "runtime/releases/dev-20261016-sparkcache-4a17f1f5198e-status038/installer-image.json", - "deployment": "69d8190bd56a9d464a054d8c40ddb959c56bb3a0f2b0ad55df421f6e8f85e494" + "deployment": "f46afc82bc9f734602d24926aae4a3dc5d40862172874504d284ad3fc6a2cd75" } diff --git a/profiles/swift15-qwen38-flash-next-tp2/compose/compose.rank0.yaml b/profiles/swift15-qwen38-flash-next-tp2/compose/compose.rank0.yaml index 6950b82f..012bba03 100644 --- a/profiles/swift15-qwen38-flash-next-tp2/compose/compose.rank0.yaml +++ b/profiles/swift15-qwen38-flash-next-tp2/compose/compose.rank0.yaml @@ -160,7 +160,7 @@ services: VLLM_WORKER_MULTIPROC_METHOD: spawn XDG_CACHE_HOME: /cache/swift15-qwen38-flash-next-f625053225d4-3ff0520224f2 labels: - io.sparkring.deployment: 6d2bf1706d5ac99e6a8ea3883934f1a71f80fa55e37b1d21c4beb2d643f8b680 + io.sparkring.deployment: 245469862d6818374d7ef489f8584ad46bddcb4d31a28ca13ff7624bfc0e7744 io.sparkring.rank: '0' network_mode: host ipc: host diff --git a/profiles/swift15-qwen38-flash-next-tp2/compose/compose.rank1.yaml b/profiles/swift15-qwen38-flash-next-tp2/compose/compose.rank1.yaml index 4375a215..31038d41 100644 --- a/profiles/swift15-qwen38-flash-next-tp2/compose/compose.rank1.yaml +++ b/profiles/swift15-qwen38-flash-next-tp2/compose/compose.rank1.yaml @@ -161,7 +161,7 @@ services: VLLM_WORKER_MULTIPROC_METHOD: spawn XDG_CACHE_HOME: /cache/swift15-qwen38-flash-next-f625053225d4-3ff0520224f2 labels: - io.sparkring.deployment: 6d2bf1706d5ac99e6a8ea3883934f1a71f80fa55e37b1d21c4beb2d643f8b680 + io.sparkring.deployment: 245469862d6818374d7ef489f8584ad46bddcb4d31a28ca13ff7624bfc0e7744 io.sparkring.rank: '1' network_mode: host ipc: host diff --git a/profiles/swift15-qwen38-flash-next-tp2/compose/selection.json b/profiles/swift15-qwen38-flash-next-tp2/compose/selection.json index 8fca993d..74cca8b3 100644 --- a/profiles/swift15-qwen38-flash-next-tp2/compose/selection.json +++ b/profiles/swift15-qwen38-flash-next-tp2/compose/selection.json @@ -3,5 +3,5 @@ "profile": "swift15-qwen38-flash-next-tp2", "checkpoint": null, "image_lock": "runtime/releases/dev-20261016-sparkcache-4a17f1f5198e-status038/installer-image.json", - "deployment": "6d2bf1706d5ac99e6a8ea3883934f1a71f80fa55e37b1d21c4beb2d643f8b680" + "deployment": "245469862d6818374d7ef489f8584ad46bddcb4d31a28ca13ff7624bfc0e7744" } diff --git a/profiles/swift15-qwen38-flash-next-tp4/compose/compose.rank0.yaml b/profiles/swift15-qwen38-flash-next-tp4/compose/compose.rank0.yaml index 31046773..415807c3 100644 --- a/profiles/swift15-qwen38-flash-next-tp4/compose/compose.rank0.yaml +++ b/profiles/swift15-qwen38-flash-next-tp4/compose/compose.rank0.yaml @@ -176,7 +176,7 @@ services: VLLM_WORKER_MULTIPROC_METHOD: spawn XDG_CACHE_HOME: /cache/swift15-qwen38-flash-next-f625053225d4-3ff0520224f2 labels: - io.sparkring.deployment: 2425f51e83084e7636ba2c630ca059b9ce0f2470536a3a419f92be5df396d015 + io.sparkring.deployment: 89e774356850d9c51d1aca722f5fa6ae5ac91593177d9002b4ac26c643058bf8 io.sparkring.rank: '0' network_mode: host ipc: host diff --git a/profiles/swift15-qwen38-flash-next-tp4/compose/compose.rank1.yaml b/profiles/swift15-qwen38-flash-next-tp4/compose/compose.rank1.yaml index 60b47ae6..93cfa9a8 100644 --- a/profiles/swift15-qwen38-flash-next-tp4/compose/compose.rank1.yaml +++ b/profiles/swift15-qwen38-flash-next-tp4/compose/compose.rank1.yaml @@ -177,7 +177,7 @@ services: VLLM_WORKER_MULTIPROC_METHOD: spawn XDG_CACHE_HOME: /cache/swift15-qwen38-flash-next-f625053225d4-3ff0520224f2 labels: - io.sparkring.deployment: 2425f51e83084e7636ba2c630ca059b9ce0f2470536a3a419f92be5df396d015 + io.sparkring.deployment: 89e774356850d9c51d1aca722f5fa6ae5ac91593177d9002b4ac26c643058bf8 io.sparkring.rank: '1' network_mode: host ipc: host diff --git a/profiles/swift15-qwen38-flash-next-tp4/compose/compose.rank2.yaml b/profiles/swift15-qwen38-flash-next-tp4/compose/compose.rank2.yaml index a5472c79..22345220 100644 --- a/profiles/swift15-qwen38-flash-next-tp4/compose/compose.rank2.yaml +++ b/profiles/swift15-qwen38-flash-next-tp4/compose/compose.rank2.yaml @@ -177,7 +177,7 @@ services: VLLM_WORKER_MULTIPROC_METHOD: spawn XDG_CACHE_HOME: /cache/swift15-qwen38-flash-next-f625053225d4-3ff0520224f2 labels: - io.sparkring.deployment: 2425f51e83084e7636ba2c630ca059b9ce0f2470536a3a419f92be5df396d015 + io.sparkring.deployment: 89e774356850d9c51d1aca722f5fa6ae5ac91593177d9002b4ac26c643058bf8 io.sparkring.rank: '2' network_mode: host ipc: host diff --git a/profiles/swift15-qwen38-flash-next-tp4/compose/compose.rank3.yaml b/profiles/swift15-qwen38-flash-next-tp4/compose/compose.rank3.yaml index 7c9ee907..baa00d3f 100644 --- a/profiles/swift15-qwen38-flash-next-tp4/compose/compose.rank3.yaml +++ b/profiles/swift15-qwen38-flash-next-tp4/compose/compose.rank3.yaml @@ -177,7 +177,7 @@ services: VLLM_WORKER_MULTIPROC_METHOD: spawn XDG_CACHE_HOME: /cache/swift15-qwen38-flash-next-f625053225d4-3ff0520224f2 labels: - io.sparkring.deployment: 2425f51e83084e7636ba2c630ca059b9ce0f2470536a3a419f92be5df396d015 + io.sparkring.deployment: 89e774356850d9c51d1aca722f5fa6ae5ac91593177d9002b4ac26c643058bf8 io.sparkring.rank: '3' network_mode: host ipc: host diff --git a/profiles/swift15-qwen38-flash-next-tp4/compose/selection.json b/profiles/swift15-qwen38-flash-next-tp4/compose/selection.json index e625a318..90ba301b 100644 --- a/profiles/swift15-qwen38-flash-next-tp4/compose/selection.json +++ b/profiles/swift15-qwen38-flash-next-tp4/compose/selection.json @@ -3,5 +3,5 @@ "profile": "swift15-qwen38-flash-next-tp4", "checkpoint": null, "image_lock": "runtime/releases/dev-20261016-sparkcache-4a17f1f5198e-status038/installer-image.json", - "deployment": "2425f51e83084e7636ba2c630ca059b9ce0f2470536a3a419f92be5df396d015" + "deployment": "89e774356850d9c51d1aca722f5fa6ae5ac91593177d9002b4ac26c643058bf8" } diff --git a/runtime/common/atomic_io.py b/runtime/common/atomic_io.py new file mode 100644 index 00000000..95bc4a9b --- /dev/null +++ b/runtime/common/atomic_io.py @@ -0,0 +1,113 @@ +"""Atomic file writes with restrictive permissions set before any bytes are written. + +Writes stage into a unique sibling temporary file created with +``os.O_WRONLY | os.O_CREAT | os.O_EXCL`` at the requested mode, tighten the open +descriptor with ``os.fchmod`` (where supported by the host OS) before writing +any payload, flush and ``fsync`` the descriptor, and atomically publish the +target with ``os.replace``. This eliminates write-then-``chmod`` TOCTOU windows +where sensitive site files or deployment manifests could briefly exist with +wider umask permissions or partial contents. +""" +from __future__ import annotations + +import os +from pathlib import Path +import secrets +from typing import BinaryIO, Callable + + +def _open_private_temp(target: Path, *, mode: int) -> tuple[Path, int]: + flags = ( + os.O_WRONLY + | os.O_CREAT + | os.O_EXCL + | getattr(os, "O_NOFOLLOW", 0) + | getattr(os, "O_BINARY", 0) + ) + for _ in range(16): + candidate = target.parent / f".{target.name}.{secrets.token_hex(8)}.tmp" + try: + fd = os.open(candidate, flags, mode) + except FileExistsError: + continue + return candidate, fd + raise FileExistsError(f"Could not allocate a unique temporary file beside {target}") + + +def atomic_write_stream( + path: str | os.PathLike[str], + writer: Callable[[BinaryIO], None], + *, + mode: int = 0o600, + exclusive: bool = False, + dir_mode: int = 0o700, +) -> Path: + """Create ``path`` atomically via ``writer(binary_stream)`` with ``mode`` set before writing. + + When ``exclusive=True``, raises ``FileExistsError`` if ``path`` already exists. + """ + target = Path(path) + target.parent.mkdir(parents=True, exist_ok=True, mode=dir_mode) + if exclusive and target.exists(): + raise FileExistsError(f"File already exists: {target}") + tmp, fd = _open_private_temp(target, mode=mode) + owned_by_stream = False + try: + if hasattr(os, "fchmod"): + os.fchmod(fd, mode) + with os.fdopen(fd, "wb") as stream: + owned_by_stream = True + writer(stream) + stream.flush() + os.fsync(stream.fileno()) + if exclusive and target.exists(): + raise FileExistsError(f"File already exists: {target}") + os.replace(tmp, target) + except BaseException: + if not owned_by_stream: + try: + os.close(fd) + except OSError: + pass + try: + tmp.unlink(missing_ok=True) + except OSError: + pass + raise + return target + + +def atomic_write_bytes( + path: str | os.PathLike[str], + data: bytes, + *, + mode: int = 0o600, + exclusive: bool = False, + dir_mode: int = 0o700, +) -> Path: + """Atomically write ``data`` to ``path`` with ``mode`` enforced before writing.""" + return atomic_write_stream( + path, + lambda stream: stream.write(data), + mode=mode, + exclusive=exclusive, + dir_mode=dir_mode, + ) + + +def atomic_write_text( + path: str | os.PathLike[str], + text: str, + *, + mode: int = 0o600, + exclusive: bool = False, + dir_mode: int = 0o700, +) -> Path: + """Atomically write UTF-8 LF ``text`` to ``path`` with ``mode`` enforced before writing.""" + return atomic_write_bytes( + path, + text.encode("utf-8"), + mode=mode, + exclusive=exclusive, + dir_mode=dir_mode, + ) diff --git a/runtime/common/compose.py b/runtime/common/compose.py index cac874d3..cf370da0 100644 --- a/runtime/common/compose.py +++ b/runtime/common/compose.py @@ -10,7 +10,7 @@ import yaml -from runtime.common import profiles, toolchain_profiles +from runtime.common import atomic_io, profiles, toolchain_profiles from runtime.common import serving as serving_settings ROOT = Path(__file__).resolve().parents[2] @@ -174,11 +174,60 @@ def installer_image_lock_path(): return image_lock.default_row()["path"].relative_to(ROOT).as_posix() -def source_inventory(profile_id, *, local_source_extension=None): - """Bind controller and host code plus release inputs using LF-normalized text.""" +def _profile_checkpoint_ids(profile): + """All ``repository@revision`` identifiers referenced by a profile and its checkpoints table.""" + ids = set() + model = profile.get("model") + if isinstance(model, dict) and model.get("repository") and model.get("revision"): + ids.add(f"{model['repository']}@{model['revision']}") + for entry in (profile.get("checkpoints") or {}).values(): + entry_model = entry.get("model") if isinstance(entry, dict) else None + if isinstance(entry_model, dict) and entry_model.get("repository") and entry_model.get("revision"): + ids.add(f"{entry_model['repository']}@{entry_model['revision']}") + return ids + + +def _is_sparkcache_profile(profile_id, profile): + return ( + "sparkcache" in profile_id + or (profile.get("environment") or {}).get("SPARKCACHE_ENABLED") == "1" + or "--kv-transfer-config" in (profile.get("vllm_args") or ()) + ) + + +def _profile_thinking_view(document, profile_id): + """Project ``profiles/thinking.json`` down to only the checkpoints and behaviours ``profile_id`` references.""" + if not isinstance(document, dict) or "checkpoints" not in document or "behaviours" not in document: + return document + metadata, _ = profiles.load(profile_id) + profile = toolchain_profiles.read(ROOT / metadata["configuration"]["path"]) + checkpoint_ids = _profile_checkpoint_ids(profile) + selected_checkpoints = { + key: value for key, value in document["checkpoints"].items() if key in checkpoint_ids + } + referenced_behaviours = set(selected_checkpoints.values()) + selected_behaviours = { + key: value for key, value in document["behaviours"].items() if key in referenced_behaviours + } + return { + "schema": document.get("schema"), + "behaviours": selected_behaviours, + "checkpoints": selected_checkpoints, + } + + +def source_inventory(profile_id, *, local_source_extension=None, image_runtime=None): + """Bind host-verified code and only the release/profile inputs actually referenced by ``profile_id``. + + Scoping the inventory to ``profile_id``'s own configuration, selected image + metadata, and referenced transport/composition files prevents edits to + unrelated profiles, catalogs, or other releases' ``installer-image.json`` + locks from churning this profile's deployment identity. + """ paths = { - "runtime/common/compose.py", "runtime/common/__init__.py", + "runtime/common/atomic_io.py", + "runtime/common/compose.py", "runtime/common/container_spec.py", "runtime/common/ports.py", "runtime/common/process_lock.py", @@ -189,56 +238,65 @@ def source_inventory(profile_id, *, local_source_extension=None): "runtime/common/cache_candidate.py", "runtime/common/serving.py", "runtime/common/sparkcache.py", - "runtime/common/sparkcache-debug-logging.json", "runtime/common/thinking.py", "scripts/sparkring_compose.py", "scripts/deploy_engine.py", - "profiles/catalog.json", - "profiles/thinking.json", f"profiles/{profile_id}/profile.json", - "profiles/qwen38-flash-next-tp2/config.json", - "profiles/qwen38-flash-next-tp2/sparkcache.json", } metadata, release = profiles.load(profile_id) + paths.add(metadata["release"]) paths.update(item["path"] for item in release["inputs"]) paths.add(metadata["configuration"]["path"]) profile = toolchain_profiles.read(ROOT / metadata["configuration"]["path"]) + if _is_sparkcache_profile(profile_id, profile): + paths.add("runtime/common/sparkcache-debug-logging.json") + thinking_path = ROOT / "profiles/thinking.json" + if thinking_path.is_file(): + thinking_doc = json.loads(source_bytes("profiles/thinking.json")) + if _profile_checkpoint_ids(profile) & set(thinking_doc.get("checkpoints") or ()): + paths.add("profiles/thinking.json") policy = toolchain_profiles.image_policy(profile, local_source_extension=local_source_extension) if policy["kind"] == "native": paths.add("runtime/common/native_candidate.py") paths.add(f"runtime/releases/{policy['native_release']}/publication.json") if policy["kind"] == "toolchain": - from runtime.common import loader_policy + from runtime.common import image_lock, installer_image, loader_policy # Compose reads the seccomp file named by security_opt on each host, # from that host's repository checkout; its hash is checked there. paths.update(("runtime/common/installer_image.py", "runtime/common/image_lock.py", "runtime/common/setup.py", - "runtime/releases/installer-releases.json", installer_image_lock_path(), + "runtime/releases/installer-releases.json", "runtime/common/loader_policy.py", loader_policy.RELATIVE)) - # Default selection examines the packaged image catalog; retain it in staged checkouts. - paths.update(path.relative_to(ROOT).as_posix() - for path in (ROOT / "runtime/releases").glob("*/installer-image.json")) + # Scope image-lock metadata to this profile's selected lock (plus the frozen fallback lock + # that installer_image.default_lock() reads), rather than hashing every release's lock. + selected_lock = None + if isinstance(image_runtime, dict) and image_runtime.get("name"): + lock_candidate = image_lock.lock_path(image_runtime["name"]) + if lock_candidate is not None and lock_candidate.is_relative_to(ROOT): + selected_lock = lock_candidate.relative_to(ROOT).as_posix() + paths.add(selected_lock or installer_image_lock_path()) + if installer_image.DEFAULT_LOCK.is_relative_to(ROOT): + paths.add(installer_image.DEFAULT_LOCK.relative_to(ROOT).as_posix()) if profile_id in TP4_PROFILES: from runtime.common import qwen_mesh - paths.add("runtime/common/feature_candidate.py") - paths.update(("profiles/qwen38-flash-next-qad-tp4/config.json", - "profiles/qwen38-flash-next-qad-tp4/sparkcache.json")) paths.update(qwen_mesh.SOURCE_FILES) - folders = ["lil-r37-glm-spark", "lil-r37-cache64"] - if profile_id in TP4_PROFILES: + folders = [] + if policy["kind"] in ("base", "cache", "feature", "source"): + folders.append("lil-r37-glm-spark") + if policy["kind"] in ("cache", "feature", "source"): + folders.append("lil-r37-cache64") + if policy["kind"] in ("feature", "source"): + paths.add("runtime/common/feature_candidate.py") folders.append("lil-r37-shared") if policy["source_extension"] is not None: from runtime.common import source_candidate source_candidate.descriptor(policy["source_extension"]) paths.update(("runtime/common/source_candidate.py", "runtime/common/feature_candidate.py")) - if "lil-r37-shared" not in folders: - folders.append("lil-r37-shared") folders.append(policy["source_extension"]) for folder in folders: paths.update( p.relative_to(ROOT).as_posix() for p in (ROOT / "runtime/images/compositions" / folder).glob("*.json") ) - paths.add(profiles.load(profile_id)[0]["release"]) return {name: digest(source_bytes(name)) for name in sorted(paths)} @@ -247,18 +305,24 @@ def source_bytes(name): return (ROOT / name).read_bytes().replace(b"\r\n", b"\n") -def identity_inventory(inventory): +def identity_inventory(inventory, *, profile_id=None): """The source inventory as the deployment identity covers it. ``inventory`` holds each file's byte digest, which hosts verify before they import the coordinator. For a profile document under ``profiles/`` - the identity instead covers the digest of profiles.identity_view, so text - in its descriptive fields (profiles.DESCRIPTIVE_FIELDS) does not change the - deployment identity or the generated Compose files. + the identity instead covers the digest of ``profiles.identity_view``, so + text in its descriptive fields (``profiles.DESCRIPTIVE_FIELDS``) does not + change the deployment identity or the generated Compose files. When + ``profile_id`` is provided, ``profiles/thinking.json`` is projected to only + the checkpoints and behaviours referenced by that profile so unrelated + models' thinking entries do not churn this profile's deployment identity. """ result = dict(inventory) for name in inventory: - if name.startswith("profiles/") and name.endswith(".json"): + if name == "profiles/thinking.json" and profile_id is not None: + document = json.loads(source_bytes(name)) + result[name] = digest(encoded(_profile_thinking_view(document, profile_id))) + elif name.startswith("profiles/") and name.endswith(".json"): document = json.loads(source_bytes(name)) view = profiles.identity_view(document) if view is not document: @@ -599,7 +663,8 @@ def build(profile_id, site, *, local_image_id=None, local_source_extension=None, specs, image = specifications(profile_id, site, **options) inputs = (source_inventory(profile_id) if local_source_extension is None else source_inventory(profile_id, local_source_extension=local_source_extension)) - identity_inputs = {"profile": profile_id, "site": site, "inputs": identity_inventory(inputs)} + identity_inputs = {"profile": profile_id, "site": site, + "inputs": identity_inventory(inputs, profile_id=profile_id)} identity_inputs.update(options) identity = digest(encoded(identity_inputs)) files = {} @@ -659,10 +724,7 @@ def render(profile_id, site, output, *, local_image_id=None, local_source_extens ) output.mkdir(parents=True, exist_ok=False, mode=0o700) for name, text in {**files, "deployment.json": encoded(manifest)}.items(): - path = output / name - path.parent.mkdir(parents=True, exist_ok=True, mode=0o700) - path.write_text(text, encoding="utf-8", newline="\n") - path.chmod(0o600) + atomic_io.atomic_write_text(output / name, text, mode=0o600, exclusive=True, dir_mode=0o700) return manifest diff --git a/runtime/common/engine_adapter.py b/runtime/common/engine_adapter.py new file mode 100644 index 00000000..9cfa5345 --- /dev/null +++ b/runtime/common/engine_adapter.py @@ -0,0 +1,725 @@ +"""Engine adapter abstraction for running vLLM, SGLang, and generic NCCL containers on SparkRing. + +SparkRing runs heterogeneous serving and compute runtimes (vLLM, SGLang, and +arbitrary PyTorch/ExLlamaV3/NCCL containers) over switchless rings and chains +of DGX Sparks via ``libsircl``. Each runtime differs in how it: + +- constructs per-rank commands and distributed launch arguments; +- binds ``libsircl`` into PyNccl and/or ``torch``'s ProcessGroupNCCL (using + ``LD_PRELOAD`` plus read-only ``libnccl.so.2`` shadow mounts from + ``stock_image.nccl_shadow_paths``); +- exposes liveness/readiness HTTP endpoints and signals fatal engine crashes + (such as vLLM's ``503`` ``EngineDeadError`` on ``/health``); +- lays out process groups (TP, PP, DP, EP, CP) on the physical Spark ring + (validated via ``runtime/common/parallel_groups.py``). + +``EngineAdapter`` encapsulates those per-engine rules behind one crisp interface +with three concrete implementations: ``VllmAdapter``, ``SglangAdapter``, and +``GenericContainerAdapter``. Use ``get_engine_adapter(name)`` or +``adapter_for_facts(facts)`` to obtain an adapter instance. +""" +from __future__ import annotations + +from abc import ABC, abstractmethod +from dataclasses import dataclass +from pathlib import PurePosixPath +from typing import Any + +from runtime.common import libsircl, parallel_groups, stock_image, transport +from runtime.common.container_spec import Bind, ContainerSpec + + +@dataclass(frozen=True) +class NcclInjectionPlan: + """Host-library mounts and environment needed to redirect NCCL calls to ``libsircl``.""" + + library_target: str + env: dict[str, str] + mounts: tuple[Bind, ...] + shadow_paths: tuple[str, ...] = () + + +@dataclass(frozen=True) +class HealthEndpoint: + """One HTTP health or readiness probe endpoint for a serving rank.""" + + path: str + url: str + method: str = "GET" + expected_status: tuple[int, ...] = (200,) + role: str = "liveness" + + +@dataclass(frozen=True) +class HealthVerdict: + """Structured classification of an HTTP health response.""" + + state: str + detail: str + fatal: bool = False + + +@dataclass(frozen=True) +class ParallelValidation: + """Result of validating a runtime's parallelism widths against ``parallel_groups``.""" + + runtime: str + world_size: int + tp: int + pp: int = 1 + dp: int = 1 + ep: int = 1 + groups: tuple[parallel_groups.Group, ...] = () + problems: tuple[str, ...] = () + ring_assignment: dict[int, int] | None = None + + @property + def ok(self) -> bool: + return not self.problems + + +class EngineAdapter(ABC): + """Protocol/ABC for engine-specific launch, NCCL injection, health, and parallelism checks.""" + + name: str + nccl_so_path_var: str | None = None + + @abstractmethod + def build_rank_command( + self, + image: dict[str, Any], + facts: dict[str, Any] | None, + arguments: list[str] | tuple[str, ...], + *, + rank: int, + size: int, + master: str, + model_target: str = stock_image.MODEL_TARGET, + api_port: int = stock_image.API_PORT, + master_port: int = stock_image.MASTER_PORT, + positions: list[int] | tuple[int, ...] | None = None, + ring_only: bool = False, + ) -> list[str]: + """Construct the rank command passed after the container's entrypoint.""" + + @abstractmethod + def build_env( + self, + image: dict[str, Any], + facts: dict[str, Any] | None, + *, + rank: int, + row: dict[str, Any], + routes: dict[str, str], + version: str, + size: int | None = None, + master: str | None = None, + master_port: int = stock_image.MASTER_PORT, + gid: int | None = None, + gid_index: int | None = None, + extra_env: dict[str, str] | None = None, + ) -> dict[str, str]: + """Construct the rank container's environment including ``libsircl`` and route variables.""" + + @abstractmethod + def health_endpoints( + self, + *, + host: str = "127.0.0.1", + port: int | None = stock_image.API_PORT, + rank: int = 0, + ) -> tuple[HealthEndpoint, ...]: + """Return HTTP health/readiness endpoints for ``rank`` (empty for headless workers).""" + + @abstractmethod + def classify_health_response(self, status_code: int, body: str = "") -> HealthVerdict: + """Classify an HTTP health check response into healthy/starting/unhealthy/dead.""" + + def nccl_injection_plan( + self, + image: dict[str, Any], + facts: dict[str, Any] | None, + *, + host_library: str, + version: str, + ) -> NcclInjectionPlan: + """Plan ``LD_PRELOAD``, optional PyNccl path variable, and ``libnccl.so.2`` shadow mounts.""" + target = stock_image.library_target(version) + shadows = stock_image.nccl_shadow_paths(facts, version) + env = { + "LD_PRELOAD": stock_image.preloads(image, version), + "LIBSIRCL_NCCL_API_VERSION": str(libsircl.NCCL_API_VERSION), + } + if self.nccl_so_path_var: + env[self.nccl_so_path_var] = target + mounts = ( + Bind(host_library, target, True), + *(Bind(host_library, path, True) for path in shadows), + ) + return NcclInjectionPlan( + library_target=target, + env=env, + mounts=mounts, + shadow_paths=shadows, + ) + + @abstractmethod + def validate_parallelism( + self, + arguments: list[str] | tuple[str, ...], + *, + size: int, + positions: list[int] | tuple[int, ...] | None = None, + ring_only: bool = False, + ) -> ParallelValidation: + """Validate process-group widths and ring closure via ``parallel_groups``.""" + + def _base_libsircl_env( + self, + image: dict[str, Any], + row: dict[str, Any], + routes: dict[str, str], + version: str, + *, + gid: int | None = None, + gid_index: int | None = None, + ) -> dict[str, str]: + resolved_gid = stock_image.resolve_gid_index(gid_index=gid_index, gid=gid, row=row) + library = { + libsircl.FAIL_STOP_VARIABLE: "1", + "LIBSIRCL_NCCL_API_VERSION": str(libsircl.NCCL_API_VERSION), + "LIBSIRCL_TRANSPORT": "verbs", + "LIBSIRCL_RECEIPT": libsircl.RECEIPT_PREFIX, + } + return { + **stock_image.image_environment(image), + **library, + **routes, + "LD_PRELOAD": stock_image.preloads(image, version), + "SIRCL_BOOTSTRAP_ADDR": row["fabric_ip"], + "SIRCL_GID_INDEX": str(resolved_gid), + "GLOO_SOCKET_IFNAME": row["interface"], + "NCCL_SOCKET_IFNAME": row["interface"], + "NCCL_DEBUG": "INFO", + "NCCL_DEBUG_SUBSYS": "INIT", + } + + def build_container_spec( + self, + image: dict[str, Any], + facts: dict[str, Any] | None, + arguments: list[str] | tuple[str, ...], + *, + name: str, + reference: str, + rank: int, + row: dict[str, Any], + master: str, + size: int, + routes: dict[str, str], + host_library: str, + version: str, + model_path: str | None, + directory: str, + gid: int | None = None, + gid_index: int | None = None, + positions: list[int] | tuple[int, ...] | None = None, + ring_only: bool = False, + extra_env: dict[str, str] | None = None, + ) -> ContainerSpec: + """Build a complete ``ContainerSpec`` for ``rank`` using this adapter's rules.""" + injection = self.nccl_injection_plan(image, facts, host_library=host_library, version=version) + environment = self.build_env( + image, + facts, + rank=rank, + row=row, + routes=routes, + version=version, + size=size, + master=master, + gid=gid, + gid_index=gid_index, + extra_env=extra_env, + ) + mounts: list[Bind] = list(injection.mounts) + if model_path is not None: + mounts.append(Bind(model_path, stock_image.MODEL_TARGET, True)) + mounts.append(Bind(str(PurePosixPath(directory) / stock_image.RECEIPTS), transport.RECEIPT_TARGET, False)) + security = () + if stock_image.loader_policy_needed(facts or {}, arguments): + security = ("seccomp=" + str(PurePosixPath(directory) / "loader-seccomp.json"),) + command = self.build_rank_command( + image, + facts, + arguments, + rank=rank, + size=size, + master=master, + positions=positions, + ring_only=ring_only, + ) + return ContainerSpec( + name=f"{name}-r{rank}", + image_id=reference, + entrypoint=tuple((image.get("Config") or {}).get("Entrypoint") or ()), + command=tuple(command), + environment=environment, + mounts=tuple(mounts), + cap_add=("IPC_LOCK",), + security_opt=security, + labels={ + "io.sparkring.stock-plan": name, + "io.sparkring.rank": str(rank), + "io.sparkring.status": libsircl.STATUS, + }, + ) + + +class VllmAdapter(EngineAdapter): + """Adapter for vLLM serving runtimes (``vllm serve``, ``VLLM_PLUGINS``, ``--headless``).""" + + name = "vllm" + nccl_so_path_var = "VLLM_NCCL_SO_PATH" + profile_args_key = "vllm_args" + managed_flags = ( + "--nnodes", + "--node-rank", + "--headless", + "--gpu-memory-utilization", + "--tensor-parallel-size", + "--disable-custom-all-reduce", + ) + plugin_env_var = "VLLM_PLUGINS" + + def build_rank_command( + self, + image: dict[str, Any], + facts: dict[str, Any] | None, + arguments: list[str] | tuple[str, ...], + *, + rank: int, + size: int, + master: str, + model_target: str = stock_image.MODEL_TARGET, + api_port: int = stock_image.API_PORT, + master_port: int = stock_image.MASTER_PORT, + positions: list[int] | tuple[int, ...] | None = None, + ring_only: bool = False, + ) -> list[str]: + entrypoint = (image.get("Config") or {}).get("Entrypoint") or [] + try: + pp = libsircl._count(arguments, "--pipeline-parallel-size", "-pp") + dp = libsircl._count(arguments, "--data-parallel-size", "-dp") + except libsircl.LibsirclError: + pp = dp = 1 + tp = size // (pp * dp) if pp > 0 and dp > 0 and size % (pp * dp) == 0 else size + distributed = [ + "--tensor-parallel-size", str(tp), + "--nnodes", str(size), + "--node-rank", str(rank), + "--master-addr", master, + "--master-port", str(master_port), + libsircl.CUSTOM_ALL_REDUCE_OFF, + ] + distributed += ["--headless"] if rank else ["--host", "0.0.0.0", "--port", str(api_port)] + return stock_image.serve_command( + entrypoint, + [model_target, *arguments, *distributed, *stock_image.compilation_arguments(arguments, facts or {})], + ) + + def build_env( + self, + image: dict[str, Any], + facts: dict[str, Any] | None, + *, + rank: int, + row: dict[str, Any], + routes: dict[str, str], + version: str, + size: int | None = None, + master: str | None = None, + master_port: int = stock_image.MASTER_PORT, + gid: int | None = None, + gid_index: int | None = None, + extra_env: dict[str, str] | None = None, + ) -> dict[str, str]: + switches = ((facts or {}).get("vllm") or {}).get("switches") or [] + off = {key: value for key, value in libsircl.INDEPENDENT_TRANSPORTS_OFF.items() if key in switches} + if "VLLM_ENABLE_ROCE_ALLREDUCE" in switches: + off["VLLM_ENABLE_ROCE_ALLREDUCE"] = "0" + base = self._base_libsircl_env(image, row, routes, version, gid=gid, gid_index=gid_index) + env = { + **base, + **off, + "VLLM_NCCL_SO_PATH": stock_image.library_target(version), + "VLLM_HOST_IP": row["fabric_ip"], + } + if extra_env: + env.update(extra_env) + return env + + def health_endpoints( + self, + *, + host: str = "127.0.0.1", + port: int | None = stock_image.API_PORT, + rank: int = 0, + ) -> tuple[HealthEndpoint, ...]: + if rank != 0 or port is None: + return () + return ( + HealthEndpoint(path="/health", url=f"http://{host}:{port}/health", role="liveness"), + HealthEndpoint(path="/v1/models", url=f"http://{host}:{port}/v1/models", role="api"), + ) + + def classify_health_response(self, status_code: int, body: str = "") -> HealthVerdict: + if status_code == 200: + return HealthVerdict(state="healthy", detail="vLLM /health returned 200 OK", fatal=False) + if status_code in (500, 503) and ("EngineDeadError" in body or "EngineCore encountered an issue" in body): + return HealthVerdict( + state="dead", + detail=f"vLLM reported fatal EngineDeadError (HTTP {status_code})", + fatal=True, + ) + if status_code == 503: + return HealthVerdict( + state="starting", + detail="vLLM /health returned 503 (starting or temporarily unavailable)", + fatal=False, + ) + return HealthVerdict(state="unhealthy", detail=f"vLLM health returned HTTP {status_code}", fatal=False) + + def validate_parallelism( + self, + arguments: list[str] | tuple[str, ...], + *, + size: int, + positions: list[int] | tuple[int, ...] | None = None, + ring_only: bool = False, + ) -> ParallelValidation: + problems: list[str] = [] + try: + pp = libsircl._count(arguments, "--pipeline-parallel-size", "-pp") + dp = libsircl._count(arguments, "--data-parallel-size", "-dp") + pcp = libsircl._count(arguments, "--prefill-context-parallel-size") + dcp = libsircl._count(arguments, "--decode-context-parallel-size", "-dcp") + except libsircl.LibsirclError as error: + return ParallelValidation(runtime=self.name, world_size=size, tp=size, problems=(str(error),)) + enable_ep = stock_image._has_flag(arguments, "--enable-expert-parallel", "-ep") + problems.extend(libsircl.capability_problems(list(arguments))) + divisor = pp * dp * pcp + if size < 1 or divisor < 1 or size % divisor != 0: + problems.append( + f"group of {size} Sparks is not divisible by pp={pp} x dp={dp} x pcp={pcp}" + ) + return ParallelValidation( + runtime=self.name, world_size=size, tp=max(1, size), pp=pp, dp=dp, + ep=size if enable_ep else 1, problems=tuple(problems), + ) + tp = size // divisor + world = parallel_groups.vllm_world_size(tp=tp, pp=pp, dp=dp, pcp=pcp) + if world != size: + problems.append(f"vLLM world size {world} differs from group size {size}") + try: + groups = tuple(parallel_groups.vllm_groups( + tp=tp, pp=pp, dp=dp, pcp=pcp, dcp=dcp, enable_expert_parallel=enable_ep, + )) + except ValueError as error: + problems.append(str(error)) + return ParallelValidation( + runtime=self.name, world_size=size, tp=tp, pp=pp, dp=dp, + ep=dp * pcp * tp if enable_ep else 1, problems=tuple(problems), + ) + pos = list(range(size)) if positions is None else list(positions) + try: + ring_issues = parallel_groups.arc_problems(groups, pos) + ring_assignment = parallel_groups.assignment(groups, size) + except ValueError as error: + problems.append(str(error)) + ring_issues, ring_assignment = [], None + if ring_only and ring_issues: + problems.extend(ring_issues) + return ParallelValidation( + runtime=self.name, + world_size=size, + tp=tp, + pp=pp, + dp=dp, + ep=dp * pcp * tp if enable_ep else 1, + groups=groups, + problems=tuple(problems), + ring_assignment=ring_assignment, + ) + + +class SglangAdapter(EngineAdapter): + """First-class adapter for SGLang (``python3 -m sglang.launch_server``, shadow mounts, ``parallel_groups``).""" + + name = "sglang" + nccl_so_path_var = "SGLANG_NCCL_SO_PATH" + + def build_rank_command( + self, + image: dict[str, Any], + facts: dict[str, Any] | None, + arguments: list[str] | tuple[str, ...], + *, + rank: int, + size: int, + master: str, + model_target: str = stock_image.MODEL_TARGET, + api_port: int = stock_image.API_PORT, + master_port: int = stock_image.MASTER_PORT, + positions: list[int] | tuple[int, ...] | None = None, + ring_only: bool = False, + ) -> list[str]: + entrypoint = (image.get("Config") or {}).get("Entrypoint") or [] + plan = stock_image.sglang_parallel_plan(arguments, size, positions=positions, ring_only=ring_only) + distributed = [ + "--model-path", model_target, + "--tp-size", str(plan.tp), + "--nnodes", str(size), + "--node-rank", str(rank), + "--dist-init-addr", f"{master}:{master_port}", + libsircl.CUSTOM_ALL_REDUCE_OFF, + ] + if plan.pp > 1 and not stock_image._has_flag(arguments, *stock_image.SGLANG_PP_FLAGS): + distributed += ["--pp-size", str(plan.pp)] + if plan.ep > 1 and not stock_image._has_flag(arguments, *stock_image.SGLANG_EP_FLAGS): + distributed += ["--ep-size", str(plan.ep)] + if rank == 0: + distributed += ["--host", "0.0.0.0", "--port", str(api_port)] + return stock_image.sglang_command(entrypoint, [*distributed, *arguments]) + + def build_env( + self, + image: dict[str, Any], + facts: dict[str, Any] | None, + *, + rank: int, + row: dict[str, Any], + routes: dict[str, str], + version: str, + size: int | None = None, + master: str | None = None, + master_port: int = stock_image.MASTER_PORT, + gid: int | None = None, + gid_index: int | None = None, + extra_env: dict[str, str] | None = None, + ) -> dict[str, str]: + base = self._base_libsircl_env(image, row, routes, version, gid=gid, gid_index=gid_index) + env = { + **base, + "SGLANG_NCCL_SO_PATH": stock_image.library_target(version), + # SGLang unconditionally imports deep_ep at server startup; deep_ep.check_nccl_so scans + # /proc/self/maps for the literal substring "libnccl" and crashes when only libsircl is mapped. + "EP_SUPPRESS_NCCL_CHECK": "1", + } + if extra_env: + env.update(extra_env) + return env + + def health_endpoints( + self, + *, + host: str = "127.0.0.1", + port: int | None = stock_image.API_PORT, + rank: int = 0, + ) -> tuple[HealthEndpoint, ...]: + if rank != 0 or port is None: + return () + return ( + HealthEndpoint(path="/health", url=f"http://{host}:{port}/health", role="liveness"), + HealthEndpoint(path="/health_generate", url=f"http://{host}:{port}/health_generate", role="readiness"), + HealthEndpoint(path="/v1/models", url=f"http://{host}:{port}/v1/models", role="api"), + ) + + def classify_health_response(self, status_code: int, body: str = "") -> HealthVerdict: + if status_code == 200: + return HealthVerdict(state="healthy", detail="SGLang server returned 200 OK", fatal=False) + if status_code in (500, 503) and any( + marker in body for marker in ("SchedulerDead", "EngineDead", "TokenizerManager is dead") + ): + return HealthVerdict( + state="dead", + detail=f"SGLang reported fatal runtime crash (HTTP {status_code})", + fatal=True, + ) + if status_code == 503: + return HealthVerdict( + state="starting", + detail="SGLang returned 503 (warming up or loading weights)", + fatal=False, + ) + return HealthVerdict(state="unhealthy", detail=f"SGLang health returned HTTP {status_code}", fatal=False) + + def validate_parallelism( + self, + arguments: list[str] | tuple[str, ...], + *, + size: int, + positions: list[int] | tuple[int, ...] | None = None, + ring_only: bool = False, + ) -> ParallelValidation: + problems = stock_image.sglang_parallel_problems( + arguments, size, positions=positions, ring_only=ring_only, + ) + try: + plan = stock_image.sglang_parallel_plan( + arguments, size, positions=positions, ring_only=ring_only, + ) + return ParallelValidation( + runtime=self.name, + world_size=plan.world_size, + tp=plan.tp, + pp=plan.pp, + dp=plan.dp, + ep=plan.ep, + groups=plan.groups, + problems=tuple(problems), + ring_assignment=plan.ring_assignment, + ) + except stock_image.StockImageError as error: + combined = list(problems) + if not combined: + combined.append(str(error)) + return ParallelValidation( + runtime=self.name, + world_size=size, + tp=size, + problems=tuple(combined), + ) + + +class GenericContainerAdapter(EngineAdapter): + """Adapter for ExLlamaV3, custom PyTorch DDP/FSDP, or arbitrary NCCL containers over ``libsircl``. + + Injects ``LD_PRELOAD``, ``libnccl.so.2`` shadow mounts, and ``SIRCL_*`` / + ``LIBSIRCL_*`` route variables without injecting any vLLM or SGLang CLI flags + or environment variables. + """ + + name = "generic" + nccl_so_path_var = None + + def build_rank_command( + self, + image: dict[str, Any], + facts: dict[str, Any] | None, + arguments: list[str] | tuple[str, ...], + *, + rank: int, + size: int, + master: str, + model_target: str = stock_image.MODEL_TARGET, + api_port: int = stock_image.API_PORT, + master_port: int = stock_image.MASTER_PORT, + positions: list[int] | tuple[int, ...] | None = None, + ring_only: bool = False, + ) -> list[str]: + # Pass the container's command/arguments through verbatim; never inject vLLM or SGLang flags. + return list(arguments) + + def build_env( + self, + image: dict[str, Any], + facts: dict[str, Any] | None, + *, + rank: int, + row: dict[str, Any], + routes: dict[str, str], + version: str, + size: int | None = None, + master: str | None = None, + master_port: int = stock_image.MASTER_PORT, + gid: int | None = None, + gid_index: int | None = None, + extra_env: dict[str, str] | None = None, + ) -> dict[str, str]: + env = self._base_libsircl_env(image, row, routes, version, gid=gid, gid_index=gid_index) + env["RANK"] = str(rank) + if size is not None: + env["WORLD_SIZE"] = str(size) + if master is not None: + env["MASTER_ADDR"] = str(master) + env["MASTER_PORT"] = str(master_port) + if extra_env: + env.update(extra_env) + return env + + def health_endpoints( + self, + *, + host: str = "127.0.0.1", + port: int | None = None, + rank: int = 0, + ) -> tuple[HealthEndpoint, ...]: + if rank != 0 or port is None: + return () + return (HealthEndpoint(path="/health", url=f"http://{host}:{port}/health", role="liveness"),) + + def classify_health_response(self, status_code: int, body: str = "") -> HealthVerdict: + if 200 <= status_code < 300: + return HealthVerdict(state="healthy", detail=f"endpoint returned HTTP {status_code}", fatal=False) + if status_code == 503: + return HealthVerdict(state="starting", detail="endpoint returned 503", fatal=False) + return HealthVerdict(state="unhealthy", detail=f"endpoint returned HTTP {status_code}", fatal=False) + + def validate_parallelism( + self, + arguments: list[str] | tuple[str, ...], + *, + size: int, + positions: list[int] | tuple[int, ...] | None = None, + ring_only: bool = False, + ) -> ParallelValidation: + if not isinstance(size, int) or isinstance(size, bool) or size < 1: + return ParallelValidation( + runtime=self.name, world_size=0, tp=1, + problems=(f"generic container parallelism requires a positive world size, got {size!r}",), + ) + groups = (parallel_groups.Group("world", tuple(range(size))),) + pos = list(range(size)) if positions is None else list(positions) + try: + ring_issues = parallel_groups.arc_problems(groups, pos) + ring_assignment = parallel_groups.assignment(groups, size) + except ValueError as error: + return ParallelValidation( + runtime=self.name, world_size=size, tp=size, groups=groups, problems=(str(error),), + ) + problems = tuple(ring_issues) if ring_only else () + return ParallelValidation( + runtime=self.name, + world_size=size, + tp=size, + groups=groups, + problems=problems, + ring_assignment=ring_assignment, + ) + + +ADAPTERS: dict[str, EngineAdapter] = { + "vllm": VllmAdapter(), + "sglang": SglangAdapter(), + "generic": GenericContainerAdapter(), +} + + +def get_engine_adapter(engine_name: str) -> EngineAdapter: + """Return the registered ``EngineAdapter`` for ``engine_name`` (``vllm``, ``sglang``, ``generic``).""" + if not isinstance(engine_name, str): + raise ValueError(f"Unknown engine adapter: {engine_name!r}; expected one of {', '.join(sorted(ADAPTERS))}") + key = engine_name.strip().lower() + adapter = ADAPTERS.get(key) + if adapter is None: + raise ValueError(f"Unknown engine adapter: {engine_name!r}; expected one of {', '.join(sorted(ADAPTERS))}") + return adapter + + +def adapter_for_facts(facts: dict[str, Any] | None) -> EngineAdapter: + """Select the ``EngineAdapter`` corresponding to ``stock_image.framework(facts)``.""" + detected = stock_image.framework(facts) + if detected == "both": + raise stock_image.StockImageError("the image has both vllm and sglang packages; select one serving runtime") + return get_engine_adapter(detected or "generic") diff --git a/runtime/common/experimental-overrides.json b/runtime/common/experimental-overrides.json new file mode 100644 index 00000000..0f5f3de8 --- /dev/null +++ b/runtime/common/experimental-overrides.json @@ -0,0 +1,69 @@ +{ + "schema": "sparkring-experimental-overrides/v1", + "overrides": { + "row_owned_prefill": { + "switch_env": [ + "DS41_ROW_SHARD_PREFILL", + "1" + ], + "help": "experimental DeepSeek V4.1-Flash-1017 prefill with token rows split across four Sparks", + "profile": "deepseek-v41-flash-tp4", + "checkpoint": "1017", + "image_name": "dev-20261013-dcp2prefill-status038-sircl-tp6", + "image_id": "sha256:3cc9a81fd344fe52fe9cc261b46dc051e3c3f494e51b8142846a5f854835c502", + "transport": { + "backend": "sircl", + "nccl": "never", + "group_name": "path-4", + "dcp": 1 + }, + "max_context_length": 262144, + "plugin": "ds41_row_shard", + "pythonpath_prefix": "/opt/ds41_row_shard", + "mounts": [ + { + "source": "integrations/vllm/ds41_row_shard", + "target": "/opt/ds41_row_shard", + "read_only": true + }, + { + "source": "spark_transport/sircl/sparkring_sircl/vllm/adapter.py", + "target": "/usr/local/lib/python3.12/dist-packages/sparkring_sircl/vllm/adapter.py", + "read_only": true + } + ], + "json_flag_overrides": { + "--compilation-config": { + "mode": 0, + "cudagraph_mode": "FULL_DECODE_ONLY" + }, + "--engram-config": { + "projection_tp": false + }, + "--speculative-config": { + "enable_adaptive_verification": true + } + }, + "extra_args": [ + "--disable-custom-all-reduce" + ], + "extra_env": { + "DS41_ROW_SHARD_INDEXER": "1", + "DS41_ROW_SHARD_COMPACT_ROUTES": "1", + "DS41_ROW_SHARD_LOCAL_QUERIES": "1", + "DS41_ROW_SHARD_KV_LATENTS": "1", + "DS41_ROW_SHARD_COMPRESSOR_LATENTS": "1" + }, + "companion_switches": { + "chain_all_gather": { + "switch_env": [ + "SIRCL_GATHER_SCHEDULE", + "chain" + ], + "help": "use direct-link SIRCL all-gather with --row-owned-prefill", + "forbid_tp_tuning_table": true + } + } + } + } +} diff --git a/runtime/common/installer.py b/runtime/common/installer.py index 590c2eb4..6fd5bdea 100644 --- a/runtime/common/installer.py +++ b/runtime/common/installer.py @@ -13,8 +13,8 @@ import uuid import zipfile -from runtime.common import (compose, derived_checkpoint, distribution, fabric_layout, installer_image, process_lock, - profiles, serving, setup, tp2) +from runtime.common import (atomic_io, compose, derived_checkpoint, distribution, fabric_layout, installer_image, + process_lock, profiles, serving, setup, tp2) from scripts import deploy_engine ROOT = profiles.ROOT @@ -38,11 +38,8 @@ def write(path, value): - path = Path(path) - path.parent.mkdir(parents=True, exist_ok=True, mode=0o700) - with path.open("x", encoding="utf-8", newline="\n") as stream: - stream.write(value if isinstance(value, str) else compose.encoded(value)) - path.chmod(0o600) + text = value if isinstance(value, str) else compose.encoded(value) + atomic_io.atomic_write_text(path, text, mode=0o600, exclusive=True, dir_mode=0o700) def read(path): @@ -846,11 +843,13 @@ def export(directory, output, *, share=False): files.update(rendered(lock)) else: files["README.txt"] += "Managed GLM exports Compose at staging; retain its managed lifecycle for start/stop.\n" - with zipfile.ZipFile(output, "x", compression=zipfile.ZIP_DEFLATED) as archive: - for name, text in files.items(): - archive.writestr(name, text) - if not share: - archive.write(Path(directory) / "source.bundle", "source.bundle") - files["source.bundle"] = "" - output.chmod(0o600) + def _write_archive(stream): + with zipfile.ZipFile(stream, "w", compression=zipfile.ZIP_DEFLATED) as archive: + for name, text in files.items(): + archive.writestr(name, text) + if not share: + archive.write(Path(directory) / "source.bundle", "source.bundle") + files["source.bundle"] = "" + + atomic_io.atomic_write_stream(output, _write_archive, mode=0o600, exclusive=True) return {"path": str(output), "shareable_template": share, "files": sorted(files)} diff --git a/runtime/common/serving.py b/runtime/common/serving.py index df44d3dd..c0e43c1d 100644 --- a/runtime/common/serving.py +++ b/runtime/common/serving.py @@ -26,14 +26,18 @@ (``model``). A request's own values take precedence over these defaults. """ import dataclasses +import functools import ipaddress import json -from pathlib import PurePosixPath +from pathlib import Path, PurePosixPath import re from runtime.common import sparkcache from runtime.common.container_spec import Bind +EXPERIMENTAL_OVERRIDES_PATH = Path(__file__).resolve().with_name("experimental-overrides.json") +EXPERIMENTAL_OVERRIDES_SCHEMA = "sparkring-experimental-overrides/v1" + # name: (vLLM flag, key in the flag's JSON value or None, value multiplier, minimum, help) SETTINGS = { "max_images": ("--limit-mm-per-prompt", "image", 1, 0, "images per request (0 accepts none)"), @@ -73,16 +77,72 @@ # value up to a tenth above the profile's, and at least one unit above it, is # accepted with a warning, and a larger one is refused. ABOVE_PROFILE = frozenset({"kv_cache_gib"}) -# The experiment uses the pinned installer image and the deployment's retained source. +# Declarative experimental profile overrides live in experimental-overrides.json +# rather than hardcoding checkpoint/image constants inline in serving logic. ROW_OWNED_PREFILL = "row_owned_prefill" CHAIN_ALL_GATHER = "chain_all_gather" -ROW_OWNED_PREFILL_IMAGE = "dev-20261013-dcp2prefill-status038-sircl-tp6" -ROW_OWNED_PREFILL_IMAGE_ID = "sha256:3cc9a81fd344fe52fe9cc261b46dc051e3c3f494e51b8142846a5f854835c502" -ROW_OWNED_PREFILL_CONTEXT = 262144 -ROW_OWNED_PREFILL_SOURCE = "integrations/vllm/ds41_row_shard" -ROW_OWNED_PREFILL_TARGET = "/opt/ds41_row_shard" -ROW_OWNED_SIRCL_SOURCE = "spark_transport/sircl/sparkring_sircl/vllm/adapter.py" -ROW_OWNED_SIRCL_TARGET = "/usr/local/lib/python3.12/dist-packages/sparkring_sircl/vllm/adapter.py" + + +@functools.lru_cache(maxsize=8) +def _load_experimental_overrides(path_str: str, mtime_ns: int, size: int): + document = json.loads(Path(path_str).read_text(encoding="utf-8")) + if document.get("schema") != EXPERIMENTAL_OVERRIDES_SCHEMA or not isinstance(document.get("overrides"), dict): + raise ValueError(f"Expected {EXPERIMENTAL_OVERRIDES_SCHEMA} in {path_str}") + return document["overrides"] + + +def experimental_overrides(): + """Return the declarative map of experimental profile overrides (cached by mtime/size).""" + if not EXPERIMENTAL_OVERRIDES_PATH.is_file(): + return {} + stat = EXPERIMENTAL_OVERRIDES_PATH.stat() + return _load_experimental_overrides(str(EXPERIMENTAL_OVERRIDES_PATH), stat.st_mtime_ns, stat.st_size) + + +def experimental_override(name): + """Return the declarative configuration for experimental override ``name``, or None.""" + return experimental_overrides().get(name) + + +def engine_adapter(engine_name="vllm"): + """Look up the registered ``EngineAdapter`` for ``engine_name``.""" + from runtime.common import engine_adapter as adapters + return adapters.get_engine_adapter(engine_name) + + +def _install_switches(): + switches = dict(SWITCHES) + for name, entry in experimental_overrides().items(): + var, value = entry["switch_env"] + switches[name] = (var, value, entry["help"]) + for companion_name, companion in (entry.get("companion_switches") or {}).items(): + c_var, c_value = companion["switch_env"] + switches[companion_name] = (c_var, c_value, companion["help"]) + return switches + + +def __getattr__(name): + # Backward-compatible attribute aliases backed by experimental-overrides.json. + override = experimental_override(ROW_OWNED_PREFILL) + if override is None: + raise AttributeError(f"module {__name__!r} has no attribute {name!r}") + mounts = override.get("mounts") or () + aliases = { + "ROW_OWNED_PREFILL_PROFILE": override["profile"], + "ROW_OWNED_PREFILL_CHECKPOINT": override["checkpoint"], + "ROW_OWNED_PREFILL_IMAGE": override["image_name"], + "ROW_OWNED_PREFILL_IMAGE_ID": override["image_id"], + "ROW_OWNED_PREFILL_CONTEXT": override["max_context_length"], + "ROW_OWNED_PREFILL_SOURCE": mounts[0]["source"] if len(mounts) > 0 else "", + "ROW_OWNED_PREFILL_TARGET": mounts[0]["target"] if len(mounts) > 0 else "", + "ROW_OWNED_SIRCL_SOURCE": mounts[1]["source"] if len(mounts) > 1 else "", + "ROW_OWNED_SIRCL_TARGET": mounts[1]["target"] if len(mounts) > 1 else "", + } + if name in aliases: + return aliases[name] + raise AttributeError(f"module {__name__!r} has no attribute {name!r}") + + # name: (container environment variable, value, help). save_cpu shortens the # time vLLM's shared-memory readers poll after a read from one second to 2 ms, # so between decode steps they sleep until notified instead of keeping CPU @@ -95,13 +155,7 @@ "save_cpu": ("SPARKRING_SHM_BUSY_LOOP_S", "0.002", "let vLLM's waiting processes sleep between decode steps: less CPU use, about 1 to 2 percent slower decode"), } -INSTALL_SWITCHES = { - **SWITCHES, - ROW_OWNED_PREFILL: ("DS41_ROW_SHARD_PREFILL", "1", - "experimental DeepSeek V4.1-Flash-1017 prefill with token rows split across four Sparks"), - CHAIN_ALL_GATHER: ("SIRCL_GATHER_SCHEDULE", "chain", - "use direct-link SIRCL all-gather with --row-owned-prefill"), -} +INSTALL_SWITCHES = _install_switches() # The installer image capability (installer_image.capabilities) that each # switch needs: on an image without it, the switch's variable would change nothing. NEEDS = {"save_cpu": "shm_reader_window"} @@ -254,25 +308,40 @@ def check_image(settings, image, capabilities): f"{image} does not. Leave out {option(name)} or choose another image.") +def check_experimental_overrides(settings, model, image, transport): + """Validate any active declarative experimental overrides against model, image, and transport.""" + for name, entry in experimental_overrides().items(): + companions = entry.get("companion_switches") or {} + if not settings.get(name): + for companion_name in companions: + if settings.get(companion_name): + raise ValueError(f"{option(companion_name)} requires {option(name)}") + continue + flag = option(name) + expected_model = (entry["profile"], entry["checkpoint"]) + if model != expected_model: + raise ValueError(f"{flag} requires --profile {entry['profile']} --checkpoint {entry['checkpoint']}") + if not image or image["image_id"] != entry["image_id"]: + raise ValueError(f"{flag} requires --image {entry['image_name']}") + req_transport = entry["transport"] + if (not transport or transport.get("backend") != req_transport["backend"] + or transport.get("nccl") != req_transport["nccl"] + or transport["group"]["name"] != req_transport["group_name"] + or transport["group"]["dcp"] != req_transport["dcp"]): + raise ValueError(f"{flag} requires --transport {req_transport['backend']} --nccl {req_transport['nccl']} " + "on a four-Spark path") + for companion_name, companion in companions.items(): + if settings.get(companion_name) and companion.get("forbid_tp_tuning_table"): + if any("tp" in row["sessions"] for row in transport["tuning"]["tables"]): + raise ValueError(f"{option(companion_name)} requires a SIRCL path without a TP tuning table") + max_ctx = entry["max_context_length"] + if settings.get("context_length", max_ctx) > max_ctx: + raise ValueError(f"{flag} supports --context-length up to {max_ctx} tokens") + + def check_row_owned_prefill(settings, model, image, transport): - """Admit the row-owned prefill experiment for the measured image, model and transport.""" - chain = settings.get(CHAIN_ALL_GATHER) - if not settings.get(ROW_OWNED_PREFILL): - if chain: - raise ValueError(f"{option(CHAIN_ALL_GATHER)} requires {option(ROW_OWNED_PREFILL)}") - return - flag = option(ROW_OWNED_PREFILL) - if model != ("deepseek-v41-flash-tp4", "1017"): - raise ValueError(f"{flag} requires --profile deepseek-v41-flash-tp4 --checkpoint 1017") - if not image or image["image_id"] != ROW_OWNED_PREFILL_IMAGE_ID: - raise ValueError(f"{flag} requires --image {ROW_OWNED_PREFILL_IMAGE}") - if (not transport or transport.get("backend") != "sircl" or transport.get("nccl") != "never" - or transport["group"]["name"] != "path-4" or transport["group"]["dcp"] != 1): - raise ValueError(f"{flag} requires --transport sircl --nccl never on a four-Spark path") - if chain and any("tp" in entry["sessions"] for entry in transport["tuning"]["tables"]): - raise ValueError(f"{option(CHAIN_ALL_GATHER)} requires a SIRCL path without a TP tuning table") - if settings.get("context_length", ROW_OWNED_PREFILL_CONTEXT) > ROW_OWNED_PREFILL_CONTEXT: - raise ValueError(f"{flag} supports --context-length up to {ROW_OWNED_PREFILL_CONTEXT} tokens") + """Admit declarative experimental overrides (backward-compatible alias for ``check_experimental_overrides``).""" + check_experimental_overrides(settings, model, image, transport) def choice(name, value): @@ -452,37 +521,44 @@ def container(spec, settings, *, rank, model=None, source_root=None): if source_root is None: raise ValueError("SparkCache debug logging requires the deployment source directory") mounts = (*mounts, Bind(str(PurePosixPath(source_root) / sparkcache.DEBUG_SOURCE), sparkcache.DEBUG_TARGET, True)) - if settings.get(ROW_OWNED_PREFILL): + for name, entry in experimental_overrides().items(): + if not settings.get(name): + continue if source_root is None: - raise ValueError(f"{option(ROW_OWNED_PREFILL)} requires the deployment source directory") - command = _row_owned_prefill_arguments(command) - plugins = env.get("VLLM_PLUGINS") - python_path = env.get("PYTHONPATH", "/opt/sparkring/toolchain/python:/opt/sparkring/addons/python") - env["VLLM_PLUGINS"] = ",".join(filter(None, (plugins, "ds41_row_shard"))) - env["PYTHONPATH"] = f"{ROW_OWNED_PREFILL_TARGET}:{python_path}" + raise ValueError(f"{option(name)} requires the deployment source directory") + command = _apply_experimental_arguments(command, entry) + plugin = entry.get("plugin") + if plugin: + plugins = env.get("VLLM_PLUGINS") + env["VLLM_PLUGINS"] = ",".join(filter(None, (plugins, plugin))) + pythonpath_prefix = entry.get("pythonpath_prefix") + if pythonpath_prefix: + python_path = env.get("PYTHONPATH", "/opt/sparkring/toolchain/python:/opt/sparkring/addons/python") + env["PYTHONPATH"] = f"{pythonpath_prefix}:{python_path}" source = PurePosixPath(source_root) - mounts = (*mounts, - Bind(str(source / ROW_OWNED_PREFILL_SOURCE), ROW_OWNED_PREFILL_TARGET, True), - Bind(str(source / ROW_OWNED_SIRCL_SOURCE), ROW_OWNED_SIRCL_TARGET, True)) + extra_mounts = tuple( + Bind(str(source / mount["source"]), mount["target"], bool(mount.get("read_only", True))) + for mount in (entry.get("mounts") or ()) + ) + mounts = (*mounts, *extra_mounts) return dataclasses.replace(spec, command=command, mounts=mounts, environment=env, health_command=health) -def _row_owned_prefill_arguments(command): - """Keep prefill eager and capture uniform decode on the pinned profile.""" +def _apply_experimental_arguments(command, entry): + """Apply declarative JSON flag overrides, context ceiling, and extra args from ``entry``.""" command = list(command) - for flag, overrides in ( - ("--compilation-config", {"mode": 0, "cudagraph_mode": "FULL_DECODE_ONLY"}), - ("--engram-config", {"projection_tp": False}), - ("--speculative-config", {"enable_adaptive_verification": True}), - ): + for flag, overrides in (entry.get("json_flag_overrides") or {}).items(): index = command.index(flag) + 1 config = json.loads(command[index]) config.update(overrides) command[index] = json.dumps(config, separators=(",", ":")) - context = command.index("--max-model-len") + 1 - command[context] = str(min(int(command[context]), ROW_OWNED_PREFILL_CONTEXT)) - command.append("--disable-custom-all-reduce") + max_ctx = entry.get("max_context_length") + if max_ctx is not None and "--max-model-len" in command: + context = command.index("--max-model-len") + 1 + command[context] = str(min(int(command[context]), max_ctx)) + for arg in (entry.get("extra_args") or ()): + command.append(arg) return tuple(command) @@ -492,14 +568,9 @@ def environment(settings): for name in sorted(set(settings) & set(INSTALL_SWITCHES))} if settings.get("sparkcache_debug"): result["VLLM_LOGGING_CONFIG_PATH"] = sparkcache.DEBUG_TARGET - if settings.get(ROW_OWNED_PREFILL): - result.update( - DS41_ROW_SHARD_INDEXER="1", - DS41_ROW_SHARD_COMPACT_ROUTES="1", - DS41_ROW_SHARD_LOCAL_QUERIES="1", - DS41_ROW_SHARD_KV_LATENTS="1", - DS41_ROW_SHARD_COMPRESSOR_LATENTS="1", - ) + for name, entry in experimental_overrides().items(): + if settings.get(name): + result.update(entry.get("extra_env") or {}) return result diff --git a/runtime/common/stock_image.py b/runtime/common/stock_image.py index dd187bce..c3851210 100644 --- a/runtime/common/stock_image.py +++ b/runtime/common/stock_image.py @@ -42,12 +42,13 @@ ``torch.cuda.nccl.version()``), and libsircl must be the only mapped file with the SONAME ``libnccl.so.2``. """ +from dataclasses import dataclass import json +import os from pathlib import Path, PurePosixPath import re -from runtime.common import libsircl, stock_image_probe, transport -from runtime.common.container_spec import Bind, ContainerSpec +from runtime.common import libsircl, parallel_groups, stock_image_probe ROOT = Path(__file__).resolve().parents[2] TREE = ROOT / "spark_transport" / "libsircl" @@ -79,6 +80,8 @@ # _MOE_EP = _TP"), so it adds no communicator, and the deployment's own ring carries it. A narrower width # forms groups of every moe_tp-th rank, which no ring order connects (parallel_groups.assignment finds none). SGLANG_EP_FLAGS = ("--ep-size", "--expert-parallel-size", "--ep") +SGLANG_PP_FLAGS = ("--pp-size", "--pipeline-parallel-size") +SGLANG_DP_FLAGS = ("--dp-size", "--data-parallel-size") # The MoE dispatch backend PyNccl alone carries: SGLang's own all-gatherv and reduce_scatterv, grouped # broadcasts and reductions. Every other backend dispatches through DeepEP's NVSHMEM, NIXL, Mooncake, MORI # or FlashInfer's symmetric memory, none of which an image without them can run. @@ -89,9 +92,28 @@ MODEL_TARGET = "/model" API_PORT = 8000 MASTER_PORT = 29511 +# Fallback RoCE GID index used only when neither explicit argument, site rank config, +# nor SIRCL_GID_INDEX environment override supplies a GID index. +DEFAULT_GID_INDEX = 3 RECEIPTS = "receipts" +@dataclass(frozen=True) +class SglangParallelPlan: + """Planned SGLang parallelism widths and ring/process-group verification from ``parallel_groups``.""" + world_size: int + tp: int + pp: int = 1 + dp: int = 1 + ep: int = 1 + moe_dp: int = 1 + attn_cp: int = 1 + enable_dp_attention: bool = False + groups: tuple[parallel_groups.Group, ...] = () + ring_problems: tuple[str, ...] = () + ring_assignment: dict[int, int] | None = None + + class StockImageError(libsircl.LibsirclError): """A stock image cannot run with libsircl, or an input of its plan is malformed.""" @@ -200,42 +222,202 @@ def owned_arguments(arguments, runtime="vllm"): return sorted({flag for flag in flags for item in arguments if item == flag or item.startswith(flag + "=")}) -def expert_parallel_problems(arguments, size): - """Why this expert width does not match the tensor-parallel width; empty when it does. +def _has_flag(arguments, *flags): + return any(item == flag or item.startswith(flag + "=") for flag in flags for item in arguments) + - SGLang makes the expert group the tensor-parallel group itself only when - ``--ep-size`` equals ``--tp-size`` (``parallel_state.py``: ``if moe_ep_size - == tensor_model_parallel_size: _MOE_EP = _TP``), adding no communicator. - Every narrower width forms strided or open-arc expert groups that fail under - ``LIBSIRCL_RING_ONLY=1`` (``parallel_groups.assignment`` finds no order). +def resolve_gid_index(*, gid_index=None, gid=None, row=None, env=None): + """Resolve ``SIRCL_GID_INDEX`` from explicit args, site rank config, env override, or documented fallback. - ``size`` is the group's Spark count; when pipeline parallelism is set, the - tensor width is ``size // pp`` (``size`` when ``pp == 1``). Without ``size`` - the width cannot be compared, and any ``--ep-size`` above one is refused. + Precedence: + 1. Explicit ``gid_index`` argument. + 2. Explicit ``gid`` argument (legacy alias; must agree if both are given). + 3. Site rank row ``row["gid_index"]`` or ``row["gid"]``. + 4. Process environment variable ``SIRCL_GID_INDEX``. + 5. Documented fallback ``DEFAULT_GID_INDEX`` (3). """ + if gid_index is not None and gid is not None and str(gid_index) != str(gid): + raise StockImageError(f"conflicting GID index values: gid_index={gid_index!r}, gid={gid!r}") + value = gid_index if gid_index is not None else gid + if value is None and isinstance(row, dict): + value = row.get("gid_index") if row.get("gid_index") is not None else row.get("gid") + if value is None: + source_env = os.environ if env is None else env + raw_env = source_env.get("SIRCL_GID_INDEX") + if raw_env is not None and str(raw_env).strip() != "": + value = str(raw_env).strip() + if value is None: + value = DEFAULT_GID_INDEX + if isinstance(value, bool): + raise StockImageError(f"SIRCL_GID_INDEX must be an integer from 0 to 255, got {value!r}") try: - ep = libsircl._count(arguments, *SGLANG_EP_FLAGS) - except libsircl.LibsirclError as error: - return [str(error)] + parsed = int(value) + except (TypeError, ValueError): + raise StockImageError(f"SIRCL_GID_INDEX must be an integer from 0 to 255, got {value!r}") from None + _require(0 <= parsed <= 255, f"SIRCL_GID_INDEX must be an integer from 0 to 255, got {parsed}") + return parsed + + +def _parse_sglang_widths(arguments): + """Parse SGLang parallelism widths from CLI arguments; returns ``(widths_dict, parse_problems)``.""" + problems = [] + values = {} + specs = ( + ("pp", SGLANG_PP_FLAGS), + ("dp", SGLANG_DP_FLAGS), + ("ep", SGLANG_EP_FLAGS), + ("moe_dp", ("--moe-dp-size",)), + ("attn_cp", ("--attn-cp-size",)), + ) + for key, flags in specs: + try: + count = libsircl._count(arguments, *flags) + except libsircl.LibsirclError as error: + problems.append(str(error)) + values[key] = 1 + continue + if count < 1: + problems.append(f"{flags[0]} must be a positive integer, got {count}") + values[key] = 1 + continue + values[key] = count + values["enable_dp_attention"] = _has_flag(arguments, "--enable-dp-attention") + return values, problems + + +def sglang_parallel_plan(arguments, size, *, positions=None, ring_only=False): + """Compute SGLang's process-group plan and ring closure checks via ``parallel_groups``. + + Derives ``tp = size // (pp * (1 if enable_dp_attention else dp))``, builds + every communicator SGLang's ``initialize_model_parallel`` creates, and runs + ``parallel_groups.arc_problems`` and ``parallel_groups.assignment`` on them. + """ + _require(isinstance(size, int) and not isinstance(size, bool) and size >= 1, + f"SGLang parallel planning requires a positive Spark count, got {size!r}") + widths, parse_problems = _parse_sglang_widths(arguments) + _require(not parse_problems, "; ".join(parse_problems)) + pp = widths["pp"] + dp = widths["dp"] + ep = widths["ep"] + moe_dp = widths["moe_dp"] + attn_cp = widths["attn_cp"] + enable_dp_attention = widths["enable_dp_attention"] + divisor = pp if enable_dp_attention else dp * pp + _require( + size % divisor == 0, + f"a group of {size} Sparks is not divisible by pipeline parallelism {pp}" + + ("" if enable_dp_attention else f" x data parallelism {dp}"), + ) + tp = size // divisor + world = parallel_groups.sglang_world_size(tp=tp, pp=pp, dp=dp, enable_dp_attention=enable_dp_attention) + _require(world == size, f"SGLang world size {world} differs from group size {size}") + try: + groups = tuple(parallel_groups.sglang_groups( + tp=tp, pp=pp, dp=dp, enable_dp_attention=enable_dp_attention, + attn_cp=attn_cp, moe_ep=ep, moe_dp=moe_dp, + )) + except ValueError as error: + raise StockImageError(str(error)) from None + pos = list(range(size)) if positions is None else list(positions) + try: + ring_problems = tuple(parallel_groups.arc_problems(groups, pos)) + ring_assignment = parallel_groups.assignment(groups, size) + except ValueError as error: + raise StockImageError(str(error)) from None + return SglangParallelPlan( + world_size=size, + tp=tp, + pp=pp, + dp=dp, + ep=ep, + moe_dp=moe_dp, + attn_cp=attn_cp, + enable_dp_attention=enable_dp_attention, + groups=groups, + ring_problems=ring_problems, + ring_assignment=ring_assignment, + ) + + +def expert_parallel_problems(arguments, size, *, positions=None): + """Why this expert width cannot run on the deployment's ring; empty when it can. + + Backed by ``parallel_groups.sglang_groups`` and ``parallel_groups.arc_problems``: + SGLang aliases ``_MOE_EP = _TP`` only when ``--ep-size`` equals the derived + tensor-parallel width ``tp = size // (pp * (1 if enable_dp_attention else dp))``. + Every narrower width forms strided or open-arc expert groups whose + communicators fail ring closure under ``LIBSIRCL_RING_ONLY=1``. + """ + widths, parse_problems = _parse_sglang_widths(arguments) + ep = widths["ep"] + if parse_problems and any(flag in problem for problem in parse_problems for flag in SGLANG_EP_FLAGS): + return [problem for problem in parse_problems if any(flag in problem for flag in SGLANG_EP_FLAGS)] if ep <= 1: return [] if size is None: return [f"expert parallelism {ep} runs at the deployment's tensor width, which the plan sets from the " "group's Spark count; this check has no group to compare it with"] - try: - pp = libsircl._count(arguments, "--pp-size", "--pipeline-parallel-size") - except libsircl.LibsirclError: - pp = 1 - if pp > 1 and size % pp == 0: - tp = size // pp - if ep == tp: + pp = widths["pp"] + dp = widths["dp"] + divisor = pp if widths["enable_dp_attention"] else dp * pp + if size % divisor != 0: + return [f"expert parallelism {ep} against a group of {size} Sparks: group size is not divisible by " + f"pipeline parallelism {pp}" + ("" if widths["enable_dp_attention"] else f" x data parallelism {dp}")] + tp = size // divisor + if ep == tp: + try: + plan = sglang_parallel_plan(arguments, size, positions=positions) + except StockImageError as error: + return [f"expert parallelism {ep} against tensor width {tp}: {error}"] + tp_sets = {group.ranks for group in plan.groups if group.name == "tp"} + ep_sets = {group.ranks for group in plan.groups if group.name == "moe_ep"} + if ep_sets <= tp_sets: return [] + return [f"expert parallelism {ep} does not alias the tensor-parallel groups {sorted(tp_sets)}"] + if pp > 1: return [f"expert parallelism {ep} against tensor width {tp} (group of {size} Sparks with pipeline " f"parallelism {pp}): the expert group aliases the tensor-parallel group only at --ep-size {tp}"] - if ep == size: - return [] return [f"expert parallelism {ep} against a group of {size} Sparks: the plan sets the tensor width to the " - f"group's Spark count, so the expert group is the deployment's ring only at --ep-size {size}"] + f"group's Spark count, so the expert group is the deployment's ring only at --ep-size {tp}"] + + +def sglang_parallel_problems(arguments, size, *, positions=None, ring_only=False): + """Single authoritative parallelism refusal check for SGLang stock-image plans. + + Refuses unsupported pipeline/data parallelism in one place without emitting + contradictory EP diagnostics, and validates all supported TP/EP/MoE/CP + process-group shapes through ``parallel_groups``. + """ + widths, problems = _parse_sglang_widths(arguments) + pp, dp, ep = widths["pp"], widths["dp"], widths["ep"] + moe_dp, attn_cp = widths["moe_dp"], widths["attn_cp"] + if pp > 1: + problems.append(f"pipeline parallelism {pp} is not covered by libsircl stock-image SGLang plans") + if dp > 1: + problems.append(f"data parallelism {dp} is not covered by libsircl stock-image SGLang plans") + if pp > 1 or dp > 1: + # Unsupported PP/DP is already refused above; avoid contradictory EP checks against an unsupported shape. + return problems + if size is None: + if ep > 1: + problems += expert_parallel_problems(arguments, None) + if moe_dp > 1: + problems.append(f"MoE data parallelism {moe_dp} requires a group size to validate against the ring") + if attn_cp > 1: + problems.append(f"attention context parallelism {attn_cp} requires a group size to validate against the ring") + return problems + ep_issues = expert_parallel_problems(arguments, size, positions=positions) + if ep_issues: + problems += ep_issues + return problems + try: + plan = sglang_parallel_plan(arguments, size, positions=positions, ring_only=ring_only) + except StockImageError as error: + problems.append(str(error)) + return problems + if (ring_only or moe_dp > 1 or attn_cp > 1) and plan.ring_problems: + problems.extend(plan.ring_problems) + return problems def moe_a2a_problems(arguments): @@ -252,7 +434,7 @@ def moe_a2a_problems(arguments): return problems -def sglang_refusals(environment, arguments, *, size=None): +def sglang_refusals(environment, arguments, *, size=None, positions=None, ring_only=False): """Why an SGLang stock image or its arguments cannot run with libsircl; empty when it can.""" problems = [] owned = libsircl.owned_settings(environment) @@ -260,16 +442,7 @@ def sglang_refusals(environment, arguments, *, size=None): problems.append(f"the image sets {owned}, which the libsircl transport owns") if environment.get("SGLANG_DISABLE_PYNCCL", "").lower() in ("1", "true", "yes"): problems.append("the image sets SGLANG_DISABLE_PYNCCL, which bypasses PyNccl") - for label, flags in (("pipeline parallelism", ("--pp-size", "--pipeline-parallel-size")), - ("data parallelism", ("--dp-size", "--data-parallel-size"))): - try: - count = libsircl._count(arguments, *flags) - except libsircl.LibsirclError as error: - problems.append(str(error)) - continue - if count > 1: - problems.append(f"{label} {count} is not covered by libsircl stock-image SGLang plans") - problems += expert_parallel_problems(arguments, size) + problems += sglang_parallel_problems(arguments, size, positions=positions, ring_only=ring_only) problems += moe_a2a_problems(arguments) for flag in SGLANG_REFUSED_FLAGS: if any(item == flag or item.startswith(flag + "=") for item in arguments): @@ -279,7 +452,7 @@ def sglang_refusals(environment, arguments, *, size=None): return problems -def _check_vllm(image, facts, arguments, library, manifest): +def _check_vllm(image, facts, arguments, library, manifest, *, size=None, positions=None, ring_only=False): problems = [] vllm = facts["vllm"] if not (vllm.get("nccl_so_path") and vllm.get("find_reads_nccl_so_path")): @@ -305,10 +478,30 @@ def _check_vllm(image, facts, arguments, library, manifest): if owned: problems.append(f"the vLLM arguments set {', '.join(owned)}, which the plan sets on every rank") problems += libsircl.refusals(image_environment(image), arguments) + if size is not None and ring_only: + try: + pp = libsircl._count(arguments, "--pipeline-parallel-size", "-pp") + dp = libsircl._count(arguments, "--data-parallel-size", "-dp") + pcp = libsircl._count(arguments, "--prefill-context-parallel-size") + dcp = libsircl._count(arguments, "--decode-context-parallel-size", "-dcp") + except libsircl.LibsirclError: + pp = dp = pcp = dcp = 1 + divisor = pp * dp * pcp + if divisor > 0 and size % divisor == 0: + tp = size // divisor + enable_ep = _has_flag(arguments, "--enable-expert-parallel", "-ep") + try: + groups = parallel_groups.vllm_groups( + tp=tp, pp=pp, dp=dp, pcp=pcp, dcp=dcp, enable_expert_parallel=enable_ep, + ) + pos = list(range(size)) if positions is None else list(positions) + problems += parallel_groups.arc_problems(groups, pos) + except ValueError as error: + problems.append(str(error)) return problems -def _check_sglang(image, facts, arguments, library, manifest, *, size=None): +def _check_sglang(image, facts, arguments, library, manifest, *, size=None, positions=None, ring_only=False): problems = [] sglang = facts["sglang"] if not (sglang.get("nccl_so_path") and sglang.get("find_reads_nccl_so_path")): @@ -334,11 +527,12 @@ def _check_sglang(image, facts, arguments, library, manifest, *, size=None): owned = owned_arguments(arguments, "sglang") if owned: problems.append(f"the SGLang arguments set {', '.join(owned)}, which the plan sets on every rank") - problems += sglang_refusals(image_environment(image), arguments, size=size) + problems += sglang_refusals(image_environment(image), arguments, size=size, positions=positions, + ring_only=ring_only) return problems -def preflight(image, facts, arguments, *, packs=None, manifest=None, size=None): +def preflight(image, facts, arguments, *, packs=None, manifest=None, size=None, positions=None, ring_only=False): """What stops ``image`` with ``facts`` (``stock_image_probe.probe``) from running ``arguments`` on libsircl; empty when nothing does.""" packs = architectures() if packs is None else packs @@ -386,9 +580,11 @@ def preflight(image, facts, arguments, *, packs=None, manifest=None, size=None): elif runtime == "both": problems.append("the image has both vllm and sglang packages; stock-image plans require one serving runtime") elif runtime == "sglang": - problems += _check_sglang(image, facts, arguments, library, manifest, size=size) + problems += _check_sglang(image, facts, arguments, library, manifest, size=size, positions=positions, + ring_only=ring_only) else: - problems += _check_vllm(image, facts, arguments, library, manifest) + problems += _check_vllm(image, facts, arguments, library, manifest, size=size, positions=positions, + ring_only=ring_only) return problems @@ -455,20 +651,13 @@ def compilation_arguments(arguments, facts): separators=(",", ":"))] -def rank_command(image, facts, arguments, *, rank, size, master): - entrypoint = (image.get("Config") or {}).get("Entrypoint") or [] - if framework(facts) == "sglang": - distributed = ["--model-path", MODEL_TARGET, "--tp-size", str(size), "--nnodes", str(size), - "--node-rank", str(rank), "--dist-init-addr", f"{master}:{MASTER_PORT}", - libsircl.CUSTOM_ALL_REDUCE_OFF] - if rank == 0: - distributed += ["--host", "0.0.0.0", "--port", str(API_PORT)] - return sglang_command(entrypoint, [*distributed, *arguments]) - distributed = ["--tensor-parallel-size", str(size), "--nnodes", str(size), "--node-rank", str(rank), - "--master-addr", master, "--master-port", str(MASTER_PORT), libsircl.CUSTOM_ALL_REDUCE_OFF] - distributed += ["--headless"] if rank else ["--host", "0.0.0.0", "--port", str(API_PORT)] - return serve_command(entrypoint, [MODEL_TARGET, *arguments, *distributed, - *compilation_arguments(arguments, facts)]) +def rank_command(image, facts, arguments, *, rank, size, master, positions=None, ring_only=False): + from runtime.common import engine_adapter + runtime = framework(facts) or "vllm" + return engine_adapter.get_engine_adapter(runtime).build_rank_command( + image, facts, arguments, rank=rank, size=size, master=master, + positions=positions, ring_only=ring_only, + ) def loader_policy_needed(facts, arguments): @@ -479,46 +668,22 @@ def loader_policy_needed(facts, arguments): def rank_spec(image, facts, arguments, *, name, reference, rank, row, master, size, routes, host_library, version, - model_path, directory, gid=3): + model_path, directory, gid=None, gid_index=None, positions=None, ring_only=False): """Rank ``rank``'s container: the image's own entrypoint with libsircl as its NCCL. - ``row`` is the rank's site row (``host``, ``fabric_ip``, ``interface``); - ``directory`` the plan's directory on every Spark, which holds the - receipts and, when the loader needs it, the seccomp policy. + ``row`` is the rank's site row (``host``, ``fabric_ip``, ``interface``, + and optional ``gid`` / ``gid_index``); ``directory`` is the plan's + directory on every Spark, which holds the receipts and, when the loader + needs it, the seccomp policy. """ - runtime = framework(facts) - if runtime == "sglang": - off = {} - # SGLang unconditionally imports deep_ep at server startup; deep_ep.check_nccl_so scans - # /proc/self/maps for the literal substring "libnccl" and crashes when only libsircl is mapped. - runtime_env = {"SGLANG_NCCL_SO_PATH": library_target(version), "EP_SUPPRESS_NCCL_CHECK": "1"} - else: - switches = (facts.get("vllm") or {}).get("switches") or [] - off = {key: value for key, value in libsircl.INDEPENDENT_TRANSPORTS_OFF.items() if key in switches} - if "VLLM_ENABLE_ROCE_ALLREDUCE" in switches: - off["VLLM_ENABLE_ROCE_ALLREDUCE"] = "0" - runtime_env = {"VLLM_NCCL_SO_PATH": library_target(version), "VLLM_HOST_IP": row["fabric_ip"]} - library = {libsircl.FAIL_STOP_VARIABLE: "1", "LIBSIRCL_NCCL_API_VERSION": str(libsircl.NCCL_API_VERSION), - "LIBSIRCL_TRANSPORT": "verbs", "LIBSIRCL_RECEIPT": libsircl.RECEIPT_PREFIX} - environment = { - **image_environment(image), **library, **off, **routes, **runtime_env, - "LD_PRELOAD": preloads(image, version), - "SIRCL_BOOTSTRAP_ADDR": row["fabric_ip"], "SIRCL_GID_INDEX": str(gid), - "GLOO_SOCKET_IFNAME": row["interface"], "NCCL_SOCKET_IFNAME": row["interface"], - "NCCL_DEBUG": "INFO", "NCCL_DEBUG_SUBSYS": "INIT", - } - shadows = tuple(Bind(host_library, path, True) for path in nccl_shadow_paths(facts, version)) - mounts = (Bind(host_library, library_target(version), True), *shadows, Bind(model_path, MODEL_TARGET, True), - Bind(str(PurePosixPath(directory) / RECEIPTS), transport.RECEIPT_TARGET, False)) - security = () - if loader_policy_needed(facts, arguments): - security = ("seccomp=" + str(PurePosixPath(directory) / "loader-seccomp.json"),) - return ContainerSpec(name=f"{name}-r{rank}", image_id=reference, - entrypoint=tuple((image.get("Config") or {}).get("Entrypoint") or ()), - command=tuple(rank_command(image, facts, arguments, rank=rank, size=size, master=master)), - environment=environment, mounts=mounts, cap_add=("IPC_LOCK",), security_opt=security, - labels={"io.sparkring.stock-plan": name, "io.sparkring.rank": str(rank), - "io.sparkring.status": libsircl.STATUS}) + from runtime.common import engine_adapter + runtime = framework(facts) or "vllm" + return engine_adapter.get_engine_adapter(runtime).build_container_spec( + image, facts, arguments, name=name, reference=reference, rank=rank, row=row, + master=master, size=size, routes=routes, host_library=host_library, version=version, + model_path=model_path, directory=directory, gid=gid, gid_index=gid_index, + positions=positions, ring_only=ring_only, + ) def compose_text(spec, reference): diff --git a/runtime/common/test_compose.py b/runtime/common/test_compose.py index b53ad349..ffa50415 100644 --- a/runtime/common/test_compose.py +++ b/runtime/common/test_compose.py @@ -528,10 +528,87 @@ def test_adding_a_research_profile_changes_no_export(tmp_path, monkeypatch): assert "example-research-tp8" in profiles.catalog() and "example-research-tp8" in profiles.relayed_research() assert thinking.catalog()["checkpoints"]["example-owner/Example-Model@" + "0" * 40] == "example-template" assert rendered_examples() == before - # A row in the main catalog, which the labels hash, changes every Compose label. + # Editing profiles/catalog.json no longer churns unrelated Compose exports. original = compose.source_bytes monkeypatch.setattr(compose, "source_bytes", lambda name: original(name) + ( b" " if name == profiles.CATALOG else b"")) - changed = rendered_examples() - ranks = [path for path in before if "/compose/compose.rank" in path.as_posix()] - assert ranks and all(changed[path] != before[path] for path in ranks) + assert rendered_examples() == before + + +def test_source_inventory_is_scoped_so_single_profile_edits_never_churn_unrelated_profiles(monkeypatch): + before = rendered_examples() + target_profile = "mimo-v26-flash-mopd-tp2" + target_config = f"profiles/{target_profile}/config.json" + # Verify non-Qwen toolchain profiles do not hash unrelated Qwen configs, catalog, or every installer-image.json. + mimo_inputs = compose.source_inventory(target_profile) + assert target_config in mimo_inputs + assert "profiles/catalog.json" not in mimo_inputs + assert "profiles/qwen38-flash-next-tp2/config.json" not in mimo_inputs + assert "profiles/qwen38-flash-next-tp2/sparkcache.json" not in mimo_inputs + assert "profiles/qwen38-flash-next-qad-tp4/config.json" not in mimo_inputs + assert "runtime/common/sparkcache-debug-logging.json" not in mimo_inputs + lock_entries = [name for name in mimo_inputs if name.endswith("/installer-image.json")] + assert len(lock_entries) <= 2, f"expected only active/fallback locks, got {lock_entries}" + + # Mutating one profile's config changes ONLY that profile's Compose outputs and leaves every other profile intact. + edit_sources(monkeypatch, { + target_config: lambda doc: doc["vllm_args"].__setitem__(doc["vllm_args"].index("--max-num-seqs") + 1, "8"), + }) + after_config_edit = rendered_examples() + changed_paths = {path.relative_to(compose.ROOT).as_posix() for path in before if after_config_edit[path] != before[path]} + assert changed_paths == { + f"profiles/{target_profile}/compose/compose.rank0.yaml", + f"profiles/{target_profile}/compose/compose.rank1.yaml", + f"profiles/{target_profile}/compose/selection.json", + } + + # Mutating one model's entry in profiles/thinking.json changes ONLY that model's profile and leaves others intact. + monkeypatch.undo() + edit_sources(monkeypatch, { + "profiles/thinking.json": lambda doc: doc["behaviours"]["deepseek-v41-encoder"].update(default="off"), + }) + after_thinking_edit = rendered_examples() + changed_thinking = { + path.relative_to(compose.ROOT).as_posix() for path in before if after_thinking_edit[path] != before[path] + } + assert changed_thinking and all(path.startswith("profiles/deepseek-v41-flash-") for path in changed_thinking) + + +def test_compose_render_uses_atomic_write_without_write_then_chmod_toctou(site, tmp_path, monkeypatch): + from runtime.common import atomic_io + events = [] + real_open = os.open + real_replace = os.replace + real_fchmod = getattr(os, "fchmod", None) + + def tracked_open(path, flags, mode=0o777): + if str(path).endswith(".tmp"): + assert flags & os.O_CREAT and flags & os.O_EXCL and flags & os.O_WRONLY + assert mode == 0o600 + events.append(("open", mode)) + return real_open(path, flags, mode) + + def tracked_replace(src, dst): + events.append(("replace", str(src), str(dst))) + return real_replace(src, dst) + + monkeypatch.setattr(atomic_io.os, "open", tracked_open) + monkeypatch.setattr(atomic_io.os, "replace", tracked_replace) + if real_fchmod is not None: + def tracked_fchmod(fd, mode): + events.append(("fchmod", mode)) + return real_fchmod(fd, mode) + monkeypatch.setattr(atomic_io.os, "fchmod", tracked_fchmod) + + target = tmp_path / "atomic-export" + compose.render(compose.SUPPORTED[0], site, target) + assert any(event[0] == "open" for event in events) + assert any(event[0] == "replace" and event[2].endswith("deployment.json") for event in events) + if real_fchmod is not None: + first_open = next(i for i, e in enumerate(events) if e[0] == "open") + first_fchmod = next(i for i, e in enumerate(events) if e[0] == "fchmod") + first_replace = next(i for i, e in enumerate(events) if e[0] == "replace") + assert first_open < first_fchmod < first_replace + # No stray temp files remain on disk. + assert not list(target.rglob("*.tmp")) + diff --git a/runtime/common/test_engine_adapter.py b/runtime/common/test_engine_adapter.py new file mode 100644 index 00000000..f97cbadc --- /dev/null +++ b/runtime/common/test_engine_adapter.py @@ -0,0 +1,169 @@ +"""Unit tests for EngineAdapter (VllmAdapter, SglangAdapter, GenericContainerAdapter) and registry; offline.""" +import pytest + +from runtime.common import engine_adapter, libsircl +from runtime.common.test_stock_image import LIBRARY, REFERENCE, SGLANG_REFERENCE, TARGET, facts, image, sglang_facts +from runtime.common.test_transport import document + + +def _rows_and_routes(shape="pair", size=2, positions=(0, 1)): + _, _, routes, _ = libsircl.group(document(shape, size), list(positions)) + rows = [ + {"host": f"spark{pos}", "fabric_ip": f"192.0.2.{20 + pos}", "interface": "enP7s7"} + for pos in positions + ] + return rows, routes + + +def test_registry_resolves_all_three_adapters_and_rejects_unknown(): + assert isinstance(engine_adapter.get_engine_adapter("vllm"), engine_adapter.VllmAdapter) + assert isinstance(engine_adapter.get_engine_adapter("SGLang"), engine_adapter.SglangAdapter) + assert isinstance(engine_adapter.get_engine_adapter("generic"), engine_adapter.GenericContainerAdapter) + assert engine_adapter.get_engine_adapter("vllm").name == "vllm" + assert engine_adapter.get_engine_adapter("sglang").name == "sglang" + assert engine_adapter.get_engine_adapter("generic").name == "generic" + with pytest.raises(ValueError, match="Unknown engine adapter"): + engine_adapter.get_engine_adapter("unknown-engine") + assert engine_adapter.adapter_for_facts(facts()).name == "vllm" + assert engine_adapter.adapter_for_facts(sglang_facts()).name == "sglang" + neither = facts() + neither["vllm"] = None + assert engine_adapter.adapter_for_facts(neither).name == "generic" + both = facts() + both["sglang"] = sglang_facts()["sglang"] + with pytest.raises(engine_adapter.stock_image.StockImageError, match="both vllm and sglang"): + engine_adapter.adapter_for_facts(both) + + +def test_vllm_adapter_command_env_injection_health_and_parallelism(): + adapter = engine_adapter.get_engine_adapter("vllm") + rows, routes = _rows_and_routes("cycle", 4, [0, 1, 2, 3]) + wheel = "/opt/vllm/nvidia/nccl/lib/libnccl.so.2" + found = facts(**{"torch.nccl_libraries": [wheel]}) + + # Command & headless worker handling + cmd0 = adapter.build_rank_command(image(), found, ["--gpu-memory-utilization", "0.85"], rank=0, size=4, + master=rows[0]["fabric_ip"]) + cmd1 = adapter.build_rank_command(image(), found, ["--gpu-memory-utilization", "0.85"], rank=1, size=4, + master=rows[0]["fabric_ip"]) + assert "--tensor-parallel-size" in cmd0 and cmd0[cmd0.index("--tensor-parallel-size") + 1] == "4" + assert "--nnodes" in cmd0 and cmd0[cmd0.index("--nnodes") + 1] == "4" + assert "--gpu-memory-utilization" in cmd0 + assert "--headless" not in cmd0 and "--host" in cmd0 + assert "--headless" in cmd1 and "--host" not in cmd1 + + # Env & NCCL injection plan (with configurable GID index) + plan = adapter.nccl_injection_plan(image(), found, host_library=LIBRARY, version="0.6.0") + assert plan.env["VLLM_NCCL_SO_PATH"] == TARGET + assert plan.env["LD_PRELOAD"] == TARGET + assert plan.shadow_paths == (wheel,) + assert any(m.target == wheel and m.source == LIBRARY and m.read_only for m in plan.mounts) + + env = adapter.build_env(image(), found, rank=0, row=rows[0], routes=routes[0], version="0.6.0", gid_index=5) + assert env["VLLM_NCCL_SO_PATH"] == TARGET + assert env["VLLM_HOST_IP"] == rows[0]["fabric_ip"] + assert env["SIRCL_GID_INDEX"] == "5" + assert env["VLLM_USE_NCCL_SYMM_MEM"] == "0" + + # Health endpoints and EngineDeadError classification + eps = adapter.health_endpoints(host="127.0.0.1", port=8000, rank=0) + assert [ep.path for ep in eps] == ["/health", "/v1/models"] + assert adapter.health_endpoints(host="127.0.0.1", port=8000, rank=1) == () + assert adapter.classify_health_response(200).state == "healthy" + dead = adapter.classify_health_response(503, '{"detail":"EngineDeadError: worker died"}') + assert dead.state == "dead" and dead.fatal is True + starting = adapter.classify_health_response(503, "warming up") + assert starting.state == "starting" and starting.fatal is False + + # Parallelism validation via parallel_groups + ok = adapter.validate_parallelism([], size=4, ring_only=True) + assert ok.ok and ok.tp == 4 and ok.world_size == 4 + # DP2 x TP2 fails on identity ring positions [0,1,2,3], succeeds on cable order [0,1,3,2] + bad_ring = adapter.validate_parallelism(["--data-parallel-size", "2"], size=4, positions=[0, 1, 2, 3], + ring_only=True) + assert not bad_ring.ok and bad_ring.ring_assignment is not None + assert any("dp" in problem for problem in bad_ring.problems) + + +def test_sglang_adapter_command_env_injection_health_and_parallelism(): + adapter = engine_adapter.get_engine_adapter("sglang") + rows, routes = _rows_and_routes("cycle", 4, [0, 1, 2, 3]) + wheel = "/opt/sglang/lib/python3.12/site-packages/nvidia/nccl/lib/libnccl.so.2" + found = sglang_facts(**{"torch.nccl_libraries": [wheel]}) + + spec = adapter.build_container_spec( + image(), found, ["--enable-ep-moe", "--ep-size", "4", "--moe-a2a-backend", "none"], + name="sr-stock-sglang", reference=SGLANG_REFERENCE, rank=0, row=rows[0], + master=rows[0]["fabric_ip"], size=4, routes=routes[0], host_library=LIBRARY, + version="0.6.0", model_path="/srv/models/m", directory="/var/lib/sparkring/stock/sr-stock-sglang", + gid_index=4, + ) + cmd = list(spec.command) + assert cmd[:5] == ["python3", "-m", "sglang.launch_server", "--model-path", "/model"] + assert cmd[cmd.index("--tp-size") + 1] == "4" + assert cmd[cmd.index("--ep-size") + 1] == "4" + assert "--headless" not in cmd + assert spec.environment["SGLANG_NCCL_SO_PATH"] == TARGET + assert spec.environment["EP_SUPPRESS_NCCL_CHECK"] == "1" + assert spec.environment["SIRCL_GID_INDEX"] == "4" + assert "VLLM_NCCL_SO_PATH" not in spec.environment + assert any(m.target == wheel and m.read_only for m in spec.mounts) + + # Health endpoints & classification + eps = adapter.health_endpoints(host="127.0.0.1", port=30000, rank=0) + assert [ep.path for ep in eps] == ["/health", "/health_generate", "/v1/models"] + assert adapter.health_endpoints(host="127.0.0.1", port=30000, rank=1) == () + assert adapter.classify_health_response(200).state == "healthy" + assert adapter.classify_health_response(503, "loading").state == "starting" + dead = adapter.classify_health_response(503, "SchedulerDead") + assert dead.state == "dead" and dead.fatal is True + + # Parallelism validation via parallel_groups + valid_ep = adapter.validate_parallelism(["--ep-size", "4"], size=4, ring_only=True) + assert valid_ep.ok and valid_ep.tp == 4 and valid_ep.ep == 4 + invalid_ep = adapter.validate_parallelism(["--ep-size", "2"], size=4, ring_only=True) + assert not invalid_ep.ok and any("expert parallelism 2" in p for p in invalid_ep.problems) + invalid_pp = adapter.validate_parallelism(["--pp-size", "2"], size=4) + assert not invalid_pp.ok and any("pipeline parallelism 2" in p for p in invalid_pp.problems) + + +def test_generic_container_adapter_runs_arbitrary_nccl_workloads_without_vllm_or_sglang_flags(): + adapter = engine_adapter.get_engine_adapter("generic") + rows, routes = _rows_and_routes("pair", 2, [0, 1]) + wheel = "/usr/local/lib/python3.12/dist-packages/nvidia/nccl/lib/libnccl.so.2" + found = {"torch": {"nccl": "dynamic", "nccl_libraries": [wheel]}} + user_cmd = ["python3", "-m", "exllamav3.server", "--model", "/model", "--tp", "2"] + + injection = adapter.nccl_injection_plan(image(), found, host_library=LIBRARY, version="0.6.0") + assert injection.env == {"LD_PRELOAD": TARGET, "LIBSIRCL_NCCL_API_VERSION": str(libsircl.NCCL_API_VERSION)} + assert "VLLM_NCCL_SO_PATH" not in injection.env and "SGLANG_NCCL_SO_PATH" not in injection.env + assert injection.shadow_paths == (wheel,) + + spec = adapter.build_container_spec( + image(entrypoint=()), found, user_cmd, + name="sr-generic-exl3", reference=REFERENCE, rank=1, row={**rows[1], "gid_index": 2}, + master=rows[0]["fabric_ip"], size=2, routes=routes[1], host_library=LIBRARY, + version="0.6.0", model_path="/srv/models/exl3", directory="/var/lib/sparkring/stock/sr-generic-exl3", + ) + # Verbatim command: no vLLM or SGLang flags injected + assert list(spec.command) == user_cmd + for forbidden in ("--headless", "--tensor-parallel-size", "--tp-size", "--disable-custom-all-reduce", "--nnodes"): + assert forbidden not in spec.command + # Clean libsircl + PyTorch DDP/NCCL env with zero VLLM_*/SGLANG_* leakage + assert spec.environment["LD_PRELOAD"] == TARGET + assert spec.environment["SIRCL_GID_INDEX"] == "2" + assert spec.environment["SIRCL_BOOTSTRAP_ADDR"] == rows[1]["fabric_ip"] + assert spec.environment["SIRCL_PEER_ROUTES"] == routes[1]["SIRCL_PEER_ROUTES"] + assert spec.environment["RANK"] == "1" and spec.environment["WORLD_SIZE"] == "2" + assert spec.environment["MASTER_ADDR"] == rows[0]["fabric_ip"] + assert not any(k.startswith(("VLLM_", "SGLANG_")) for k in spec.environment) + assert any(m.target == wheel and m.read_only for m in spec.mounts) + + # Generic health & parallelism + assert adapter.health_endpoints(rank=0, port=None) == () + assert [ep.path for ep in adapter.health_endpoints(rank=0, port=8080)] == ["/health"] + assert adapter.classify_health_response(204).state == "healthy" + assert adapter.classify_health_response(503).state == "starting" + assert adapter.classify_health_response(500).state == "unhealthy" + valid = adapter.validate_parallelism(user_cmd, size=2, ring_only=True) + assert valid.ok and valid.world_size == 2 and len(valid.groups) == 1 diff --git a/runtime/common/test_installer.py b/runtime/common/test_installer.py index 2cf4533f..4b684747 100644 --- a/runtime/common/test_installer.py +++ b/runtime/common/test_installer.py @@ -640,3 +640,51 @@ def test_checkpoint_directory_is_per_cluster_and_revision_and_disjoint(): ("model_repository", "owner--name/model"), ("model_repository", "owner/na..me")): with pytest.raises(ValueError): installer.checkpoint_directory("tp2", {**cards[QWEN], field: value}) + + +def test_installer_write_is_atomic_exclusive_and_cleans_up_on_error(tmp_path, monkeypatch): + import os + from runtime.common import atomic_io + events = [] + real_open = os.open + real_replace = os.replace + real_fchmod = getattr(os, "fchmod", None) + + def tracked_open(path, flags, mode=0o777): + if str(path).endswith(".tmp"): + assert flags & os.O_CREAT and flags & os.O_EXCL and flags & os.O_WRONLY + assert mode == 0o600 + events.append("open") + return real_open(path, flags, mode) + + def tracked_replace(src, dst): + events.append("replace") + return real_replace(src, dst) + + monkeypatch.setattr(atomic_io.os, "open", tracked_open) + monkeypatch.setattr(atomic_io.os, "replace", tracked_replace) + if real_fchmod is not None: + def tracked_fchmod(fd, mode): + assert mode == 0o600 + events.append("fchmod") + return real_fchmod(fd, mode) + monkeypatch.setattr(atomic_io.os, "fchmod", tracked_fchmod) + + target = tmp_path / "nested" / "secret.json" + installer.write(target, {"secret": "value"}) + assert json.loads(target.read_text(encoding="utf-8")) == {"secret": "value"} + if real_fchmod is not None: + assert events == ["open", "fchmod", "replace"] + else: + assert events == ["open", "replace"] + # Refuses overwriting an existing file (exclusive=True) and leaves no temp file. + with pytest.raises(FileExistsError): + installer.write(target, {"secret": "overwrite"}) + assert json.loads(target.read_text(encoding="utf-8")) == {"secret": "value"} + # A failing writer leaves neither partial target nor stray temp files. + failing = tmp_path / "nested" / "failed.json" + with pytest.raises(RuntimeError, match="boom"): + atomic_io.atomic_write_stream(failing, lambda _stream: (_ for _ in ()).throw(RuntimeError("boom"))) + assert not failing.exists() + assert not list(tmp_path.rglob("*.tmp")) + diff --git a/runtime/common/test_qwen_tp4.py b/runtime/common/test_qwen_tp4.py index f4764ebe..707fdb3c 100644 --- a/runtime/common/test_qwen_tp4.py +++ b/runtime/common/test_qwen_tp4.py @@ -238,10 +238,12 @@ def test_tp4_cache_compose_has_four_hosts_and_source_bound_feature_admission(sit compose.check_equivalence(spec, image, compose.compose_text(spec, image)) inputs = compose.source_inventory(profile) assert "runtime/common/qwen_mesh.py" in inputs - assert "runtime/common/feature_candidate.py" in inputs - assert "runtime/images/compositions/lil-r37-shared/descriptor.json" in inputs - assert "profiles/qwen38-flash-next-qad-tp4/config.json" in inputs + assert "runtime/common/native_candidate.py" in inputs + assert "runtime/releases/shared-2026.09.3/publication.json" in inputs assert "profiles/qwen38-flash-next-qad-tp4/sparkcache.json" in inputs + # Scoped inventory omits unrelated configs and legacy R37 composition descriptors. + assert "profiles/qwen38-flash-next-qad-tp4/config.json" not in inputs + assert "runtime/images/compositions/lil-r37-shared/descriptor.json" not in inputs manifest, files = compose.build(profile, site) phases = {phase["id"]: phase for phase in coordinator.plan(manifest, files, "start")["phases"]} assert len(phases["preflight"]["actions"]) == 4 diff --git a/runtime/common/test_serving.py b/runtime/common/test_serving.py index 31c40c22..e288fa5a 100644 --- a/runtime/common/test_serving.py +++ b/runtime/common/test_serving.py @@ -351,3 +351,23 @@ def test_without_thinking_settings_commands_compose_files_and_locks_are_unchange # The other serving settings render as before. tuned = installer.make_lock(QWEN, site(), "1" * 40, "2" * 64, settings={"max_images": 8}) assert all(KWARGS not in spec.command for spec in installer.specifications(tuned)) + + +def test_experimental_overrides_are_loaded_declaratively_with_backward_compatible_aliases(): + overrides = serving.experimental_overrides() + assert serving.ROW_OWNED_PREFILL in overrides + entry = serving.experimental_override(serving.ROW_OWNED_PREFILL) + assert entry["profile"] == "deepseek-v41-flash-tp4" and entry["checkpoint"] == "1017" + assert serving.ROW_OWNED_PREFILL_PROFILE == entry["profile"] + assert serving.ROW_OWNED_PREFILL_CHECKPOINT == entry["checkpoint"] + assert serving.ROW_OWNED_PREFILL_IMAGE == entry["image_name"] + assert serving.ROW_OWNED_PREFILL_IMAGE_ID == entry["image_id"] + assert serving.ROW_OWNED_PREFILL_CONTEXT == entry["max_context_length"] + assert serving.ROW_OWNED_PREFILL in serving.INSTALL_SWITCHES + assert serving.CHAIN_ALL_GATHER in serving.INSTALL_SWITCHES + with pytest.raises(ValueError, match="requires --row-owned-prefill"): + serving.check_experimental_overrides({serving.CHAIN_ALL_GATHER: True}, None, None, None) + assert serving.engine_adapter("vllm").name == "vllm" + assert serving.engine_adapter("sglang").name == "sglang" + assert serving.engine_adapter("generic").name == "generic" + diff --git a/runtime/common/test_stock_image.py b/runtime/common/test_stock_image.py index 199c4867..60206a45 100644 --- a/runtime/common/test_stock_image.py +++ b/runtime/common/test_stock_image.py @@ -516,3 +516,69 @@ def test_shadow_mounts_cover_discovered_image_nccl_libraries_in_probe_and_rank_s for item in rendered["services"]["model"]["volumes"]} assert targets[wheel] == (LIBRARY, True) and targets[system] == (LIBRARY, True) + +def test_parallel_groups_is_exercised_end_to_end_through_stock_image(): + # TP-only and TP+EP at group width compute real parallel_groups plans and pass ring closure. + tp_plan = stock_image.sglang_parallel_plan([], 4) + assert tp_plan.tp == 4 and tp_plan.pp == 1 and tp_plan.ep == 1 + assert tp_plan.ring_problems == () and tp_plan.ring_assignment is not None + ep_plan = stock_image.sglang_parallel_plan(["--enable-ep-moe", "--ep-size", "4"], 4) + assert ep_plan.tp == 4 and ep_plan.ep == 4 and ep_plan.ring_problems == () + assert any(g.name == "moe_ep" and g.ranks == (0, 1, 2, 3) for g in ep_plan.groups) + # TP+PP planning derives tp = size // pp consistently (no hardcoded --tp-size str(size)). + pp_plan = stock_image.sglang_parallel_plan(["--pp-size", "2", "--ep-size", "2"], 4, positions=[0, 1, 3, 2]) + assert pp_plan.tp == 2 and pp_plan.pp == 2 and pp_plan.ep == 2 and pp_plan.ring_problems == () + pp_cmd = stock_image.rank_command(image(), sglang_facts(), ["--pp-size", "2", "--ep-size", "2"], + rank=0, size=4, master="192.0.2.20") + assert pp_cmd[pp_cmd.index("--tp-size") + 1] == "2" + assert pp_cmd[pp_cmd.index("--pp-size") + 1] == "2" + assert pp_cmd[pp_cmd.index("--ep-size") + 1] == "2" + # Unordered [0, 1, 2, 3] exposes PP ring problems through parallel_groups.arc_problems. + pp_bad = stock_image.sglang_parallel_plan(["--pp-size", "2"], 4, positions=[0, 1, 2, 3]) + assert len(pp_bad.ring_problems) == 2 and all("pp" in p for p in pp_bad.ring_problems) + # Single authoritative refusal when --pp-size > 1 is passed to preflight (no contradictory EP error). + pp_refusals = stock_image.preflight(image(), sglang_facts(), ["--pp-size", "2", "--ep-size", "4"], size=4) + assert len(pp_refusals) == 1 and "pipeline parallelism 2" in pp_refusals[0] + # Non-aliased MoE DP / attention CP groups are caught by parallel_groups.arc_problems. + moe_dp_refusals = stock_image.preflight(image(), sglang_facts(), ["--moe-dp-size", "2"], size=4, ring_only=True) + assert any("moe_dp" in p for p in moe_dp_refusals), moe_dp_refusals + attn_cp_refusals = stock_image.preflight(image(), sglang_facts(), ["--attn-cp-size", "2"], size=4, ring_only=True) + assert any("attn_cp" in p for p in attn_cp_refusals), attn_cp_refusals + + +def test_sircl_gid_index_is_configurable_with_documented_fallback(monkeypatch): + monkeypatch.delenv("SIRCL_GID_INDEX", raising=False) + assert stock_image.resolve_gid_index() == stock_image.DEFAULT_GID_INDEX == 3 + # Site row config overrides default + assert stock_image.resolve_gid_index(row={"gid": 5}) == 5 + assert stock_image.resolve_gid_index(row={"gid_index": 7, "gid": 5}) == 7 + # Env override applies when neither explicit arg nor row supplies a GID + monkeypatch.setenv("SIRCL_GID_INDEX", "6") + assert stock_image.resolve_gid_index() == 6 + assert stock_image.resolve_gid_index(row={"gid": 4}) == 4 + # Explicit gid_index overrides both row and env + assert stock_image.resolve_gid_index(gid_index=2, row={"gid": 4}) == 2 + assert stock_image.resolve_gid_index(gid=1, row={"gid": 4}) == 1 + with pytest.raises(stock_image.StockImageError, match="conflicting"): + stock_image.resolve_gid_index(gid_index=2, gid=3) + for bad in (-1, 256, True, "not-a-number"): + with pytest.raises(stock_image.StockImageError, match="integer from 0 to 255"): + stock_image.resolve_gid_index(gid_index=bad) + # Propagates into rank_spec for both vLLM and SGLang + _, _, routes, _ = libsircl.group(document("pair", 2), [0, 1]) + row = {"host": "spark0", "fabric_ip": "192.0.2.20", "interface": "enP7s7", "gid_index": 4} + spec_from_row = stock_image.rank_spec( + image(), sglang_facts(), [], name="sr-stock-gid", reference=SGLANG_REFERENCE, + rank=0, row=row, master="192.0.2.20", size=2, routes=routes[0], host_library=LIBRARY, + version="0.6.0", model_path="/srv/models/m", directory="/var/lib/sparkring/stock/sr-stock-gid", + ) + assert spec_from_row.environment["SIRCL_GID_INDEX"] == "4" + spec_explicit = stock_image.rank_spec( + image(), sglang_facts(), [], name="sr-stock-gid", reference=SGLANG_REFERENCE, + rank=0, row=row, master="192.0.2.20", size=2, routes=routes[0], host_library=LIBRARY, + version="0.6.0", model_path="/srv/models/m", directory="/var/lib/sparkring/stock/sr-stock-gid", + gid_index=1, + ) + assert spec_explicit.environment["SIRCL_GID_INDEX"] == "1" + + diff --git a/runtime/common/test_toolchain_profiles.py b/runtime/common/test_toolchain_profiles.py index dd7b5c99..561fc085 100644 --- a/runtime/common/test_toolchain_profiles.py +++ b/runtime/common/test_toolchain_profiles.py @@ -819,3 +819,39 @@ def test_swift_follows_the_qwen_profile_except_its_checkpoint_format(swift_id, q # Compile caches and container names stay separate from the Qwen checkpoint's. assert spec.name == f"swift15-qwen38-flash-next-tp{nodes}-r0" assert spec.environment["B12X_COMPILE_CACHE_DIR"].startswith("/cache/swift15-qwen38-flash-next-cuda") + + +def test_canonical_caches_json_reads_by_mtime_and_invalidates_on_change(tmp_path, monkeypatch): + profile = adapter.read(PROFILE) + adapter.clear_canonical_cache() + reads = [] + real_read = adapter.read + + def counting_read(path): + reads.append(str(path)) + return real_read(path) + + monkeypatch.setattr(adapter, "read", counting_read) + assert adapter.canonical(profile) is profile + first_call_reads = len(reads) + assert first_call_reads > 0 + # Subsequent calls hit the mtime-keyed cache and perform zero disk JSON reads. + for _ in range(5): + assert adapter.canonical(profile) is profile + assert len(reads) == first_call_reads + + # Modifying a watched canonical file's content/mtime invalidates the cache automatically. + custom_dir = tmp_path / "profiles" / "qwen38-flash-next-tp2" + custom_dir.mkdir(parents=True) + custom_config = custom_dir / "config.json" + edited = copy.deepcopy(profile) + edited["served_model_name"] = "Cached-Custom-TP2" + custom_config.write_text(json.dumps(edited), encoding="utf-8") + monkeypatch.setattr(adapter, "CONFIG_ROOT", custom_dir) + assert adapter.canonical(edited) is edited + after_swap = len(reads) + assert after_swap > first_call_reads + assert adapter.canonical(edited) is edited + assert len(reads) == after_swap + adapter.clear_canonical_cache() + diff --git a/runtime/common/toolchain_profiles.py b/runtime/common/toolchain_profiles.py index 2313ce8c..720f08cb 100644 --- a/runtime/common/toolchain_profiles.py +++ b/runtime/common/toolchain_profiles.py @@ -15,6 +15,7 @@ from __future__ import annotations import argparse import copy +import functools import hashlib import ipaddress import json @@ -68,20 +69,71 @@ def publication(): return read(ROOT / "runtime/images/compositions/lil-r37-glm-spark/publication.json") +@functools.lru_cache(maxsize=256) +def _read_cached(path_str: str, mtime_ns: int, size: int) -> str: + """Read and canonically serialize a profile JSON file, cached by ``(path, mtime_ns, size)``.""" + return json.dumps(read(path_str), sort_keys=True, separators=(",", ":")) + + +@functools.lru_cache(maxsize=64) +def _canonical_fingerprints(path_stats: tuple[tuple[str, int, int], ...]) -> frozenset[str]: + return frozenset(_read_cached(path_str, mtime_ns, size) for path_str, mtime_ns, size in path_stats) + + +@functools.lru_cache(maxsize=32) +def _fabric_configs_cached(root_str: str, research_catalog: str, mtime_ns: int | None, size: int | None): + from runtime.common import profiles + return tuple(profiles.relayed_research(Path(root_str)).values()) + + +def _path_stats(paths): + seen, stats = set(), [] + for raw in paths: + path = Path(raw) + key = str(path) + if key in seen or not path.is_file(): + continue + seen.add(key) + st = path.stat() + stats.append((key, st.st_mtime_ns, st.st_size)) + return tuple(stats) + + +def clear_canonical_cache(): + """Clear mtime-keyed caches used by ``canonical()`` and ``fabric_configs()``.""" + _read_cached.cache_clear() + _canonical_fingerprints.cache_clear() + _fabric_configs_cached.cache_clear() + + def fabric_configs(): """Serving configurations of the research profiles that only SIRCL ring sessions run, on the shared toolchain image (profiles.relayed_research; installer_image.SIRCL_ONLY); they keep the envelope above. A source tree without profiles.RESEARCH_CATALOG renders the other profiles.""" from runtime.common import profiles - return tuple(profiles.relayed_research().values()) + catalog_path = Path(profiles.ROOT) / profiles.RESEARCH_CATALOG + if catalog_path.is_file(): + st = catalog_path.stat() + return _fabric_configs_cached(str(profiles.ROOT), str(profiles.RESEARCH_CATALOG), st.st_mtime_ns, st.st_size) + return _fabric_configs_cached(str(profiles.ROOT), str(profiles.RESEARCH_CATALOG), None, None) def canonical(profile): - fabric = profile in [read(path) for path in fabric_configs()] - if (profile not in [read(CONFIG_ROOT / name) for name in CONFIG_NAMES] - and profile not in [read(TP4_CONFIG), read(TP4_CACHE_CONFIG)] - and profile not in [read(path) for path in TOOLCHAIN_CONFIGS] and not fabric): - raise ValueError("Select an unchanged canonical serving configuration") + try: + needle = json.dumps(profile, sort_keys=True, separators=(",", ":")) + except TypeError: + raise ValueError("Select an unchanged canonical serving configuration") from None + fabric_set = _canonical_fingerprints(_path_stats(fabric_configs())) + fabric = needle in fabric_set + if not fabric: + standard_paths = ( + *(CONFIG_ROOT / name for name in CONFIG_NAMES), + TP4_CONFIG, + TP4_CACHE_CONFIG, + *TOOLCHAIN_CONFIGS, + ) + if needle not in _canonical_fingerprints(_path_stats(standard_paths)): + raise ValueError("Select an unchanged canonical serving configuration") topologies = ("direct-path-6", "direct-cycle-8") if fabric else ("direct-pair-2", "direct-cycle-4") if profile.get("schema") != "sparkring-serving-profile/v1" or profile.get("topology") not in topologies: raise ValueError("Invalid serving profile schema/topology") diff --git a/scripts/compose_builder/export.py b/scripts/compose_builder/export.py index f73cfb9b..05fb9379 100644 --- a/scripts/compose_builder/export.py +++ b/scripts/compose_builder/export.py @@ -456,7 +456,7 @@ def profile_data(profile_id, image_runtime=None, image_option=None, image_lock_v "checkpoints": checkpoints, "example_site": example, "inputs": inputs, - "identity_inventory": compose.identity_inventory(inputs), + "identity_inventory": compose.identity_inventory(inputs, profile_id=profile_id), "options": options, }