Skip to content

armgit / sie

Public Imported from GitHub
0

Open-source inference server and production cluster for all the models your agent needs.

feat(server)!: serve one model across several GPUs with tensor parallelism (#282)

Krisztian Gajdara03f5dbf878d
diff --git a/deploy/helm/sie-cluster/README.md b/deploy/helm/sie-cluster/README.md
index 29b4e3b27..aaf711971 100644
--- a/deploy/helm/sie-cluster/README.md
+++ b/deploy/helm/sie-cluster/README.md
@@ -580,8 +580,8 @@ routing and metrics only; GPU pools must use `gpu.count` for real capacity.
This is the Req6 one-child-at-a-time model placement topology. It distributes
different models from one runtime bundle across the pod's GPU slots. A child can
-own multiple models, but one model is not spread across children, replicated for
-throughput, or tensor/model-parallelized for an oversized model.
+own multiple models, but one model is not spread across children or replicated
+for throughput. A model too large for one GPU needs a device group instead.
Each worker pod serves exactly one runtime bundle. Different bundles render as
different worker StatefulSets and therefore different worker identities.
@@ -604,6 +604,51 @@ workers:
maxReplicas: 3
```
+### Tensor-Parallel Device Groups
+
+To serve one model across several GPUs, set `gpu.deviceGroup: true` alongside
+`gpu.count`. The pod then runs a single worker child that owns every GPU in the
+pod (`SIE_DEVICES=cuda:0,...,cuda:N-1`) instead of one child per GPU, and the
+model profile declares how many of them it uses:
+
+```yaml
+profiles:
+ default:
+ adapter_path: sie_server.adapters.sglang.generation:SGLangGenerationAdapter
+ adapter_options:
+ loadtime:
+ tensor_parallel_size: 4
+ request_read_timeout_s: 600
+```
+
+```yaml
+workers:
+ pools:
+ l4-4x-group:
+ enabled: true
+ machineProfile: l4-4x
+ gpu:
+ count: 4
+ deviceGroup: true
+```
+
+- The worker claims a contiguous block of `tensor_parallel_size` devices for
+ the model exclusively, evicting unpinned models to free a block when it has
+ to, and releases the block when the model unloads. Loading a single-GPU model
+ while every device is held evicts the least recently used unpinned group.
+- The SGLang generation and embedding adapters accept a width. The generation
+ adapter also requires `request_read_timeout_s` above width one, because a
+ stalled collective produces no bytes and no error.
+- Width and placement are declared only through `tensor_parallel_size`. Engine
+ placement flags in `extra_launch_args` (including abbreviations such as
+ `--tp`) and device-visibility variables in `extra_env` are refused.
+- `gpu.deviceGroup` requires `gpu.count >= 2`. `SIE_GPU_COUNT` and the cluster
+ health `gpu_count` count serving slots, so a device-group pod reports one
+ slot however many GPUs it holds.
+- Splitting a model across GPUs on a node without a fast GPU interconnect adds
+ communication overhead. For a model that fits one GPU, fan-out children
+ serving replicas usually deliver more throughput for the same GPUs.
+
### Queue Pool Patterns
Use one of these patterns deliberately:
diff --git a/deploy/helm/sie-cluster/templates/_helpers.tpl b/deploy/helm/sie-cluster/templates/_helpers.tpl
index aa436059c..324133d1b 100644
--- a/deploy/helm/sie-cluster/templates/_helpers.tpl
+++ b/deploy/helm/sie-cluster/templates/_helpers.tpl
@@ -1345,10 +1345,11 @@ port; pods without a named child port are simply not endpoints for that port.
{{- range $poolName, $pool := $root.Values.workers.pools -}}
{{- if $pool.enabled -}}
{{- $gpuCount := int $pool.gpu.count -}}
+{{- $deviceGroup := dig "deviceGroup" false (default dict $pool.gpu) -}}
{{- $poolSidecar := default dict $pool.sidecar -}}
{{- $emulatedChildCount := int (dig "emulatedChildCount" 0 $poolSidecar) -}}
{{- $count := 1 -}}
-{{- if gt $gpuCount 1 -}}
+{{- if and (gt $gpuCount 1) (not $deviceGroup) -}}
{{- $count = $gpuCount -}}
{{- else if gt $emulatedChildCount 1 -}}
{{- $count = $emulatedChildCount -}}
diff --git a/deploy/helm/sie-cluster/templates/worker-statefulset.yaml b/deploy/helm/sie-cluster/templates/worker-statefulset.yaml
index 14720d032..c48b1d8d9 100644
--- a/deploy/helm/sie-cluster/templates/worker-statefulset.yaml
+++ b/deploy/helm/sie-cluster/templates/worker-statefulset.yaml
@@ -134,8 +134,12 @@ fast at render time.
{{- if and (gt $emulatedChildCount 0) (gt $gpuCount 0) }}
{{- fail (printf "workers.pools.%s.sidecar.emulatedChildCount is CPU-only; GPU pools use gpu.count for child fanout." $poolName) }}
{{- end }}
+{{- $deviceGroup := dig "deviceGroup" false $pool.gpu }}
+{{- if and $deviceGroup (lt $gpuCount 2) }}
+{{- fail (printf "workers.pools.%s.gpu.deviceGroup requires gpu.count >= 2; a single accelerator is the ordinary pool shape." $poolName) }}
+{{- end }}
{{- $workerChildCount := 1 }}
-{{- if gt $gpuCount 1 }}
+{{- if and (gt $gpuCount 1) (not $deviceGroup) }}
{{- $workerChildCount = $gpuCount }}
{{- else if gt $emulatedChildCount 1 }}
{{- $workerChildCount = $emulatedChildCount }}
@@ -634,8 +638,11 @@ spec:
value: {{ $machineProfile | quote }}
{{- if $pool.gpu }}
{{- if $pool.gpu.count }}
+ # Serving slots, not cards: a device-group pod runs one engine that
+ # owns every accelerator, so the sidecar must not advertise the
+ # card count as capacity.
- name: SIE_GPU_COUNT
- value: {{ $pool.gpu.count | quote }}
+ value: {{ $workerChildCount | quote }}
{{- end }}
{{- end }}
{{- if $payloadStoreUrl }}
diff --git a/deploy/helm/sie-cluster/values.yaml b/deploy/helm/sie-cluster/values.yaml
index 7ad0ef91c..11f7dc631 100644
--- a/deploy/helm/sie-cluster/values.yaml
+++ b/deploy/helm/sie-cluster/values.yaml
@@ -803,7 +803,19 @@ workers:
# worker process env var.
# gpu.count: int. 0 disables nvidia.com/gpu request on the pod.
# Values >1 render one adapter child container per GPU
- # plus one sidecar routing across child IPC sockets.
+ # plus one sidecar routing across child IPC sockets,
+ # unless gpu.deviceGroup is set.
+ # gpu.deviceGroup: bool, default false. Inverts what gpu.count means. One
+ # adapter child owns every GPU in the pod instead of one
+ # child per GPU, which is what a model too large for a
+ # single accelerator needs. The child sees the full
+ # device list in SIE_DEVICES and requests every GPU, and
+ # the model profile declares the matching
+ # adapter_options.loadtime.tensor_parallel_size. Requires
+ # gpu.count >= 2. The pod, the lane tuple and the
+ # autoscaling unit are otherwise unchanged. SIE_GPU_COUNT
+ # advertises serving slots rather than cards, so a device
+ # group publishes one however many accelerators it holds.
# sidecar.emulatedChildCount:
# int. CPU-only local/dev fanout for exercising the same
# sidecar child routing without GPU resources. GPU pools
diff --git a/packages/sie_config/src/sie_config/model_registry.py b/packages/sie_config/src/sie_config/model_registry.py
index 2de145af7..b48876717 100644
--- a/packages/sie_config/src/sie_config/model_registry.py
+++ b/packages/sie_config/src/sie_config/model_registry.py
@@ -147,6 +147,73 @@ def _validate_profile_name(profile_name: str) -> None:
_IMMUTABLE_REVISION_RE = re.compile(r"^[0-9a-f]{40}$")
+# Mirror of sie_server's placement rules (config/model.py). A worker refuses a
+# snapshot containing a profile that breaks them, so the config service refuses
+# the write that would put one there.
+_MAX_TENSOR_PARALLEL_SIZE = 8
+_PLACEMENT_LAUNCH_FLAGS = frozenset(
+ {
+ "--tp",
+ "--tp-size",
+ "--tensor-parallel-size",
+ "--dp",
+ "--dp-size",
+ "--data-parallel-size",
+ "--ep-size",
+ "--expert-parallel-size",
+ "--pp-size",
+ "--pipeline-parallel-size",
+ "--nnodes",
+ "--node-rank",
+ "--dist-init-addr",
+ "--base-gpu-id",
+ "--gpu-id-step",
+ }
+)
+_PLACEMENT_ENV_VARS = frozenset({"CUDA_VISIBLE_DEVICES", "NVIDIA_VISIBLE_DEVICES", "ROCR_VISIBLE_DEVICES"})
+
+
+def _validate_profile_placement(profiles: dict) -> None:
+ """Mirror sie_server's tensor-parallel width and placement rules on raw dicts."""
+ for profile_name, profile in profiles.items():
+ if not isinstance(profile, dict):
+ continue
+ options = profile.get("adapter_options")
+ loadtime = options.get("loadtime") if isinstance(options, dict) else None
+ if not isinstance(loadtime, dict):
+ continue
+ if "tensor_parallel_size" in loadtime:
+ width = loadtime["tensor_parallel_size"]
+ if isinstance(width, bool) or not isinstance(width, int) or not 1 <= width <= _MAX_TENSOR_PARALLEL_SIZE:
+ msg = (
+ f"Profile '{profile_name}': tensor_parallel_size must be an integer between 1 and "
+ f"{_MAX_TENSOR_PARALLEL_SIZE}, got {width!r}"
+ )
+ raise ValueError(msg)
+ raw_args = loadtime.get("extra_launch_args") or []
+ if isinstance(raw_args, list):
+ for entry in raw_args:
+ flag = str(entry).split("=", 1)[0].strip()
+ if not flag.startswith("--") or len(flag) <= len("--"):
+ continue
+ refused = next((f for f in sorted(_PLACEMENT_LAUNCH_FLAGS) if f.startswith(flag)), None)
+ if refused is not None:
+ msg = (
+ f"Profile '{profile_name}': extra_launch_args carries {flag!r}, which sets the "
+ f"placement flag {refused!r}. Declare loadtime.tensor_parallel_size instead."
+ )
+ raise ValueError(msg)
+ raw_env = loadtime.get("extra_env") or {}
+ if isinstance(raw_env, dict):
+ for key in raw_env:
+ if str(key).strip().upper() in _PLACEMENT_ENV_VARS:
+ msg = (
+ f"Profile '{profile_name}': extra_env sets {key!r}, which the worker overwrites "
+ "with its device mask. Declare loadtime.tensor_parallel_size instead."
+ )
+ raise ValueError(msg)
+
+
def _validate_profile_lora_pins(profiles: dict) -> None:
"""Mirror sie_server's pinned-LoRA spelling rules (#2113) on raw dicts.
@@ -1036,6 +1103,7 @@ class ModelRegistry:
raise ValueError(msg)
_validate_profile_lora_pins(profiles)
+ _validate_profile_placement(profiles)
for profile_name, profile in profiles.items():
_validate_profile_name(str(profile_name))
@@ -1335,6 +1403,7 @@ class ModelRegistry:
raise ValueError(msg)
_validate_profile_lora_pins(profiles)
+ _validate_profile_placement(profiles)
for profile_name, profile in profiles.items():
_validate_profile_name(str(profile_name))
diff --git a/packages/sie_config/tests/test_model_registry.py b/packages/sie_config/tests/test_model_registry.py
index 4fe993a75..bccb95b50 100644
--- a/packages/sie_config/tests/test_model_registry.py
+++ b/packages/sie_config/tests/test_model_registry.py
@@ -990,3 +990,49 @@ class TestProfileLoraPins:
"b": {"adapter_options": {"runtime": {"lora_id": "acme/l"}}},
}
model_registry._validate_profile_lora_pins(profiles)
+
+
+class TestProfilePlacement:
+ """Dict-level mirror of sie_server's tensor-parallel placement rules.
+
+ A worker refuses a whole config snapshot containing a profile that breaks
+ them, so accepting such a write would take down every model in the bundle.
+ """
+
+ @staticmethod
+ def _profiles(**loadtime: object) -> dict:
+ return {"p": {"adapter_options": {"loadtime": dict(loadtime)}}}
+
+ @pytest.mark.parametrize("width", [1, 2, 8])
+ def test_a_usable_width_passes(self, width: int) -> None:
+ model_registry._validate_profile_placement(self._profiles(tensor_parallel_size=width))
+
+ @pytest.mark.parametrize("width", [0, 9, True, "2", None, 2.5])
+ def test_an_unusable_width_is_refused(self, width: object) -> None:
+ with pytest.raises(ValueError, match="tensor_parallel_size"):
+ model_registry._validate_profile_placement(self._profiles(tensor_parallel_size=width))
+
+ @pytest.mark.parametrize(
+ "args",
+ [["--tp", "2"], ["--tensor-parallel-size=4"], ["--tensor-parallel", "4"], ["--base-gpu-id", "1"]],
+ )
+ def test_a_placement_flag_is_refused_however_it_is_spelled(self, args: list[str]) -> None:
+ with pytest.raises(ValueError, match="placement flag"):
+ model_registry._validate_profile_placement(self._profiles(extra_launch_args=args))
+
+ def test_a_device_visibility_variable_is_refused(self) -> None:
+ with pytest.raises(ValueError, match="CUDA_VISIBLE_DEVICES"):
+ model_registry._validate_profile_placement(self._profiles(extra_env={"CUDA_VISIBLE_DEVICES": "0"}))
+
+ def test_ordinary_passthroughs_still_pass(self) -> None:
+ model_registry._validate_profile_placement(
+ self._profiles(extra_launch_args=["--dtype", "bfloat16"], extra_env={"SGLANG_ENABLE_SPEC_V2": "1"})
+ )
+
+ def test_the_mirror_matches_the_server_rules(self) -> None:
+ server = pytest.importorskip("sie_server.config.model")
+ groups = pytest.importorskip("sie_server.config.device_groups")
+
+ assert model_registry._PLACEMENT_LAUNCH_FLAGS == server._PLACEMENT_LAUNCH_FLAGS
+ assert model_registry._PLACEMENT_ENV_VARS == server._PLACEMENT_ENV_VARS
+ assert model_registry._MAX_TENSOR_PARALLEL_SIZE == groups.MAX_TENSOR_PARALLEL_SIZE
diff --git a/packages/sie_server/src/sie_server/adapters/sglang/_server.py b/packages/sie_server/src/sie_server/adapters/sglang/_server.py
index 1c74db9b3..098591c68 100644
--- a/packages/sie_server/src/sie_server/adapters/sglang/_server.py
+++ b/packages/sie_server/src/sie_server/adapters/sglang/_server.py
@@ -14,6 +14,7 @@ from __future__ import annotations
import hashlib
import importlib.metadata
+import json
import logging
import math
import os
@@ -25,12 +26,27 @@ import sys
import tempfile
import threading
import time
+from collections.abc import Sequence
from pathlib import Path
+from typing import Any
import requests
+from sie_server.config.device_groups import (
+ MAX_TENSOR_PARALLEL_SIZE,
+ format_device_mask,
+ resolve_device_group,
+ validate_tensor_parallel_size,
+)
from sie_server.core.oom import is_oom_error
+__all__ = [
+ "MAX_TENSOR_PARALLEL_SIZE",
+ "format_device_mask",
+ "resolve_device_group",
+ "validate_tensor_parallel_size",
+]
+
logger = logging.getLogger(__name__)
# In-process record of ports already handed out by ``find_free_port`` but
@@ -61,6 +77,12 @@ KERNEL_CACHE_ROOT_ENV_VAR = "SIE_SGLANG_KERNEL_CACHE_ROOT"
STARTUP_TIMEOUT_S = DEFAULT_STARTUP_TIMEOUT_S
HEALTH_CHECK_INTERVAL_S = 2.0
BASE_PORT = 30000 # Starting port for SGLang servers
+# Collective rendezvous ports for multi-rank groups. The engine otherwise picks
+# a random port, so two groups starting together on one host can pick the same
+# one and one of them hangs in rendezvous rather than failing. Kept clear of the
+# SGLang HTTP span above and of 30200-30299, which the MLX and TensorRT-LLM
+# adapters hand out from reservation sets of their own.
+NCCL_BASE_PORT = 30400
ERR_SERVER_STARTUP = "SGLang server failed to start within timeout"
ERR_SERVER_CRASH = "SGLang server process exited during startup"
@@ -107,7 +129,13 @@ def _installed_jit_abi_key() -> str:
return hashlib.sha256("\n".join(components).encode()).hexdigest()[:20]
-def _gpu_cache_key(device_index: int) -> str | None:
+def _gpu_cache_key(device_indices: Sequence[int]) -> str | None:
+ """Return one cache key for the whole device group, or None to disable the cache.
+
+ Every member of a tensor-parallel group must be the same product. A mixed
+ group is refused rather than cached under one member's name, because the
+ artifacts compiled for it are not valid for the others.
+ """
try:
result = subprocess.run(
["nvidia-smi", "--query-gpu=name", "--format=csv,noheader"], # noqa: S607
@@ -117,18 +145,27 @@ def _gpu_cache_key(device_index: int) -> str | None:
timeout=5,
)
device_names = [line.strip() for line in result.stdout.splitlines() if line.strip()]
- device_name = device_names[device_index]
+ group_names = [device_names[index] for index in device_indices]
except (FileNotFoundError, IndexError, OSError, subprocess.SubprocessError) as exc:
logger.warning(
- "SGLang kernel cache disabled: could not identify cuda:%d without CUDA init: %s", device_index, exc
+ "SGLang kernel cache disabled: could not identify %s without CUDA init: %s",
+ ", ".join(f"cuda:{index}" for index in device_indices),
+ exc,
+ )
+ return None
+
+ if len(set(group_names)) > 1:
+ logger.warning(
+ "SGLang kernel cache disabled: device group spans more than one product: %s",
+ ", ".join(sorted(set(group_names))),
)
return None
- device_digest = hashlib.sha256(device_name.encode()).hexdigest()[:12]
+ device_digest = hashlib.sha256(group_names[0].encode()).hexdigest()[:12]
return f"gpu-{device_digest}"
-def _kernel_cache_env(env: dict[str, str], *, device_index: int) -> dict[str, str]:
+def _kernel_cache_env(env: dict[str, str], *, device_indices: Sequence[int]) -> dict[str, str]:
"""Return missing upstream cache variables for one persistent cache root.
Cache namespaces include the installed JIT ABI and exact GPU product name. This
@@ -146,11 +183,14 @@ def _kernel_cache_env(env: dict[str, str], *, device_index: int) -> dict[str, st
logger.warning("SGLang kernel cache disabled: %s must be an absolute path", KERNEL_CACHE_ROOT_ENV_VAR)
return {}
- gpu_key = _gpu_cache_key(device_index)
+ gpu_key = _gpu_cache_key(device_indices)
if gpu_key is None:
return {}
- namespace = root / _KERNEL_CACHE_LAYOUT_VERSION / _installed_jit_abi_key() / gpu_key / f"device-{device_index}"
+ # The group, not the anchor, names the namespace. Artifacts compiled for a
+ # four-rank launch are not interchangeable with single-device artifacts.
+ group_key = "device-" + "_".join(str(index) for index in device_indices)
+ namespace = root / _KERNEL_CACHE_LAYOUT_VERSION / _installed_jit_abi_key() / gpu_key / group_key
defaults = {name: str(namespace / suffix) for name, suffix in _KERNEL_CACHE_DIRS.items() if not env.get(name)}
if not defaults:
return {}
@@ -260,6 +300,28 @@ def find_free_port(start_port: int = BASE_PORT) -> int:
raise RuntimeError(msg)
+def reserve_port(port: int) -> None:
+ """Reserve one specific port, as :func:`find_free_port` reserves the one it picks.
+
+ For a port a profile declares. Release it with :func:`release_port`.
+
+ Raises:
+ RuntimeError: If another model in this process has it reserved, or
+ something already has it bound.
+ """
+ with _RESERVED_PORTS_LOCK:
+ if port in _RESERVED_PORTS:
+ msg = f"port {port} is already reserved by another model in this process"
+ raise RuntimeError(msg)
+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
+ try:
+ s.bind(("localhost", port))
+ except OSError as error:
+ msg = f"port {port} is already in use: {error}"
+ raise RuntimeError(msg) from error
+ _RESERVED_PORTS.add(port)
+
+
def release_port(port: int | None) -> None:
"""Return a port handed out by :func:`find_free_port` to the pool.
@@ -283,6 +345,130 @@ def parse_device_index(device: str) -> int:
return 0
+def _read_cached_model_config(model_name_or_path: str, revision: str | None) -> dict[str, Any] | None:
+ """Return a model's ``config.json`` if it can be read without a download.
+
+ Best effort by design. A model served from a local directory, a cached
+ repository or neither are all ordinary, so an unreadable config disables
+ the checks that depend on it rather than failing a load that would
+ otherwise work.
+ """
+ local = Path(model_name_or_path)
+ candidate: Path | None = None
+ if local.is_dir():
+ candidate = local / "config.json"
+ else:
+ try:
+ from huggingface_hub import try_to_load_from_cache
+
+ # HFValidationError subclasses ValueError, so a malformed repo id
+ # is covered without importing the hub's error module here.
+ cached = try_to_load_from_cache(model_name_or_path, "config.json", revision=revision)
+ except (ImportError, OSError, ValueError):
+ return None
+ if isinstance(cached, str):
+ candidate = Path(cached)
+ if candidate is None or not candidate.is_file():
+ return None
+ try:
+ parsed = json.loads(candidate.read_text(encoding="utf-8"))
+ except (OSError, ValueError):
+ return None
+ return parsed if isinstance(parsed, dict) else None
+
+
+def validate_width_against_model_config(
+ width: int,
+ *,
+ model_name_or_path: str,
+ revision: str | None = None,
+) -> None:
+ """Refuse a width the model's own shape cannot be divided by.
+
+ The engine asserts these itself, but only after loading weights, which on a
+ multi-accelerator load means several cards are held for minutes before the
+ launch fails, and a supervisor that restarts the worker repeats that on every restart.
+
+ Only heads the config actually reports are checked, and an unreadable
+ config checks nothing, so this can only turn a later crash into an earlier
+ and clearer error, never reject a shape that would have worked.
+
+ Raises:
+ ValueError: Naming the attribute, its value and the width.
+ """
+ if width < 2:
+ return
+ config = _read_cached_model_config(model_name_or_path, revision)
+ if config is None:
+ return
+ # A multimodal config's top-level head counts can describe the vision
+ # tower, which is not the stack the engine shards.
+ text_config = config.get("text_config")
+ if isinstance(text_config, dict):
+ config = text_config
+
+ attention_heads = _positive_int(config.get("num_attention_heads"))
+ if attention_heads is not None and attention_heads % width:
+ msg = (
+ f"tensor_parallel_size={width} does not divide num_attention_heads={attention_heads} "
+ f"for {model_name_or_path!r}. The engine shards query heads across ranks and "
+ "requires an exact division."
+ )
+ raise ValueError(msg)
+
+ # Key/value heads are replicated rather than split when a model publishes
+ # fewer of them than the width, so the engine requires divisibility in
+ # whichever direction applies and a grouped-query shape narrower than the
+ # group is legal.
+ kv_heads = _positive_int(config.get("num_key_value_heads"))
+ if kv_heads is not None and kv_heads % width and width % kv_heads:
+ msg = (
+ f"tensor_parallel_size={width} is neither a multiple nor a divisor of "
+ f"num_key_value_heads={kv_heads} for {model_name_or_path!r}. The engine splits "
+ "key/value heads across ranks when there are at least as many as the width and "
+ "replicates them otherwise, and neither is possible at this width."
+ )
+ raise ValueError(msg)
+
+
+def _positive_int(value: object) -> int | None:
+ """A config attribute usable as a head count, or None when it is not one."""
+ if isinstance(value, bool) or not isinstance(value, int) or value <= 0:
+ return None
+ return value
+
+
+def validate_optional_positive(value: float | None, *, field: str) -> float | None:
+ """Return a positive finite float, or None.
+
+ Raises:
+ ValueError: If the value is present but not a positive finite number.
+ """
+ if value is None:
+ return None
+ if isinstance(value, bool) or not isinstance(value, (int, float)):
+ msg = f"{field} must be a number, got {value!r}"
+ raise ValueError(msg)
+ if not math.isfinite(value) or value <= 0:
+ msg = f"{field} must be a finite number greater than zero, got {value!r}"
+ raise ValueError(msg)
+ return float(value)
+
+
+def validate_optional_port(value: int | None) -> int | None:
+ """Return a usable TCP port, or None to let SIE reserve one.
+
+ Raises:
+ ValueError: If the value is present but not a port number.
+ """
+ if value is None:
+ return None
+ if isinstance(value, bool) or not isinstance(value, int) or not 1024 <= value <= 65535:
+ msg = f"nccl_port must be an integer between 1024 and 65535, got {value!r}"
+ raise ValueError(msg)
+ return value
+
+
def open_output_log(prefix: str = "sglang_") -> tempfile._TemporaryFileWrapper:
"""Open a named temp file for capturing subprocess stdout/stderr."""
return tempfile.NamedTemporaryFile(
@@ -296,16 +482,18 @@ def open_output_log(prefix: str = "sglang_") -> tempfile._TemporaryFileWrapper:
def launch_sglang_server(
cmd: list[str],
*,
- device_index: int,
+ device_indices: Sequence[int],
output_file: tempfile._TemporaryFileWrapper,
extra_env: dict[str, str] | None = None,
) -> subprocess.Popen[bytes]:
- """Launch an SGLang HTTP server subprocess.
+ """Launch an SGLang HTTP server subprocess over an ordered device group.
Args:
cmd: Full argv (must already include ``python -m sglang.launch_server``
plus all flags).
- device_index: CUDA device index for ``CUDA_VISIBLE_DEVICES``.
+ device_indices: Ordered CUDA device indices the child may see. A
+ single-element sequence is the ordinary one-GPU case. The order is
+ preserved, because rank N binds the Nth entry of the mask.
output_file: Temp file open for write — subprocess stdout/stderr is
redirected here for debugging.
extra_env: Additional environment variables to set on the subprocess.
@@ -317,12 +505,22 @@ def launch_sglang_server(
The ``Popen`` handle. Subprocess is started in a new process group
(``start_new_session=True``) so the entire group can be signalled on
shutdown without affecting the parent.
+
+ Raises:
+ ValueError: If no device is supplied, or a device repeats. A repeated
+ index would give two ranks the same card and deadlock the group.
"""
+ mask = format_device_mask(device_indices)
+
env = os.environ.copy()
- env["CUDA_VISIBLE_DEVICES"] = str(device_index)
if extra_env:
env.update(extra_env)
- for name, value in _kernel_cache_env(env, device_index=device_index).items():
+ # The device mask is written after the profile environment, never before.
+ # It is the registry's placement decision, and a profile that also set
+ # CUDA_VISIBLE_DEVICES would otherwise silently move or widen the claim
+ # the registry is accounting for.
+ env["CUDA_VISIBLE_DEVICES"] = mask
+ for name, value in _kernel_cache_env(env, device_indices=device_indices).items():
env.setdefault(name, value)
logger.info("SGLang subprocess output will be logged to: %s", output_file.name)
return subprocess.Popen( # noqa: S603 — intentional subprocess call
diff --git a/packages/sie_server/src/sie_server/adapters/sglang/embedding.py b/packages/sie_server/src/sie_server/adapters/sglang/embedding.py
index 45dff3feb..0b0120dc6 100644
--- a/packages/sie_server/src/sie_server/adapters/sglang/embedding.py
+++ b/packages/sie_server/src/sie_server/adapters/sglang/embedding.py
@@ -57,6 +57,14 @@ _EMBED_CONCURRENCY_ENV = "SIE_SGLANG_EMBED_CONCURRENCY"
_DEFAULT_EMBED_CONCURRENCY = 8
+_EMBED_READ_TIMEOUT_S = 60.0
+"""Read cap for one embedding POST.
+
+A stalled collective produces no bytes and no error, so an unbounded read
+would hold the request, and every accelerator in the group, open forever.
+"""
+
+
def _resolve_embed_concurrency(configured: int | None) -> int:
"""Resolve the embedding POST concurrency (env override wins, then config)."""
raw = os.environ.get(_EMBED_CONCURRENCY_ENV)
@@ -109,6 +117,21 @@ class SGLangEmbeddingAdapter(BaseAdapter):
def _check_loaded(self) -> None:
if self._server_url is None:
raise RuntimeError(ERR_NOT_LOADED)
+ process = self._process
+ if process is None:
+ return
+ exit_code = process.poll()
+ if exit_code is None:
+ return
+ # Without this the adapter never notices its engine exiting, and every
+ # later request opens a connection to a port nobody is listening on,
+ # waits out the connect timeout and returns a transport error, with no
+ # reload and no readiness change.
+ msg = (
+ f"SGLang engine for {self._model_name_or_path!r} is not running "
+ f"(process exited with code {exit_code}). The model must be reloaded."
+ )
+ raise RuntimeError(msg)
def __init__(
self,
@@ -124,12 +147,19 @@ class SGLangEmbeddingAdapter(BaseAdapter):
doc_template: str | None = None,
default_instruction: str | None = None,
append_eos: bool = False,
- pooling_method: str | None = None,
lora_paths: dict[str, str] | None = None,
max_loras_per_batch: int = 8,
dense_dim: int | None = None,
startup_timeout_s: float | None = None,
embed_concurrency: int | None = None,
+ # Accepted for the same reason the generation adapter accepts it: the
+ # width is a property of a load, not of a task. No embedding profile
+ # needs it today, and one is the byte-identical single-device case.
+ tensor_parallel_size: int = 1,
+ disable_piecewise_cuda_graph: bool | None = None,
+ request_read_timeout_s: float | None = None,
+ watchdog_timeout_s: float | None = None,
+ nccl_port: int | None = None,
**kwargs: Any, # Accept extra args from loader (e.g., pooling)
) -> None:
r"""Initialize the adapter.
@@ -160,9 +190,6 @@ class SGLangEmbeddingAdapter(BaseAdapter):
from the model's own tokenizer at load time (see ``load``), so it
is never hardcoded. Leave False for models SGLang already handles
(e.g. Qwen3-Embedding).
- pooling_method: Pooling method for embeddings. Options: "cls", "lasttoken",
- "max", "mean", "mean_sqrt_len_tokens", "weightedmean". If None, uses
- SGLang's default (usually lasttoken for LLM models).
lora_paths: LoRA adapters to load. Dict mapping adapter name to path.
Example: {"legal": "org/legal-lora", "medical": "/path/to/medical"}.
At request time, select via lora parameter in encode().
@@ -184,11 +211,27 @@ class SGLangEmbeddingAdapter(BaseAdapter):
self._default_instruction = default_instruction
self._append_eos = append_eos
self._eos_token = "" # Resolved from the model tokenizer in load() when append_eos
- self._pooling_method = pooling_method
self._lora_paths = lora_paths or {}
self._max_loras_per_batch = max_loras_per_batch
self._startup_timeout_s = _server.resolve_startup_timeout(startup_timeout_s)
self._embed_concurrency = _resolve_embed_concurrency(embed_concurrency)
+ self._tensor_parallel_size = _server.validate_tensor_parallel_size(tensor_parallel_size)
+ self._disable_piecewise_cuda_graph = (
+ self._tensor_parallel_size > 1 if disable_piecewise_cuda_graph is None else disable_piecewise_cuda_graph
+ )
+ self._request_read_timeout_s = (
+ _server.validate_optional_positive(request_read_timeout_s, field="request_read_timeout_s")
+ or _EMBED_READ_TIMEOUT_S
+ )
+ self._watchdog_timeout_s = _server.validate_optional_positive(watchdog_timeout_s, field="watchdog_timeout_s")
+ self._declared_nccl_port = _server.validate_optional_port(nccl_port)
+ if self._declared_nccl_port is not None and self._tensor_parallel_size == 1:
+ msg = "nccl_port applies only above tensor_parallel_size=1; a single rank has no rendezvous"
+ raise ValueError(msg)
+ self._nccl_port: int | None = None
+ # Declared or chosen, the rendezvous port is reserved in the shared set,
+ # so teardown hands back exactly what this adapter holds.
+ self._reserved_nccl_port: int | None = None
self._process: subprocess.Popen[bytes] | None = None
self._server_url: str | None = None
@@ -239,16 +282,26 @@ class SGLangEmbeddingAdapter(BaseAdapter):
if self._append_eos:
self._eos_token = self._resolve_eos_token()
+ # Before any accelerator is claimed: a width the model's own head counts
+ # cannot be divided by fails here rather than minutes into the engine's
+ # own assertion, with the whole group held in the meantime.
+ _server.validate_width_against_model_config(
+ self._tensor_parallel_size,
+ model_name_or_path=str(self._model_name_or_path),
+ revision=self._revision,
+ )
device_index = _server.parse_device_index(device)
+ device_indices = _server.resolve_device_group(device_index, self._tensor_parallel_size)
port = _server.find_free_port()
self._port = port
self._server_url = f"http://localhost:{port}"
logger.info(
- "Starting SGLang server for %s on device=%s (gpu_id=%d) at port %d",
+ "Starting SGLang server for %s on device=%s (gpu_ids=%s, tp=%d) at port %d",
self._model_name_or_path,
device,
- device_index,
+ ",".join(str(index) for index in device_indices),
+ self._tensor_parallel_size,
port,
)
@@ -269,8 +322,10 @@ class SGLangEmbeddingAdapter(BaseAdapter):
str(self._max_seq_length),
"--mem-fraction-static",
str(self._mem_fraction_static),
- "--tp",
- "1", # Tensor parallel = 1 (single GPU)
+ # Full flag name rather than the "--tp" abbreviation, which a
+ # future upstream flag sharing that prefix would make ambiguous.
+ "--tensor-parallel-size",
+ str(self._tensor_parallel_size),
"--log-level",
"warning",
]
@@ -278,12 +333,19 @@ class SGLangEmbeddingAdapter(BaseAdapter):
if self._trust_remote_code:
cmd.append("--trust-remote-code")
+ # Overrides the engine's default watchdog, which decides how long a
+ # forward batch may run before the engine crashes itself.
+ if self._watchdog_timeout_s is not None:
+ cmd.extend(["--watchdog-timeout", str(self._watchdog_timeout_s)])
+
+ # SGLang's default piecewise capture path is measured to hang at width
+ # two and to exhaust memory at width four. Disabled above width one.
+ if self._disable_piecewise_cuda_graph:
+ cmd.append("--disable-piecewise-cuda-graph")
+
if self._revision is not None:
cmd.extend(["--revision", self._revision])
- if self._pooling_method:
- cmd.extend(["--pooling-method", self._pooling_method])
-
# LoRA configuration for the SGLang server.
if self._lora_paths:
cmd.append("--enable-lora")
@@ -301,8 +363,21 @@ class SGLangEmbeddingAdapter(BaseAdapter):
# rather than leaking one slot of the 100-port span per attempt: a full
# /tmp in open_output_log, a failed exec, or a cancelled load included.
try:
+ # Only a group rendezvouses, so width one reserves nothing and its
+ # launch argv is unchanged. Left to the engine it picks a random
+ # port, which is the collision NCCL_BASE_PORT exists to prevent.
+ if self._tensor_parallel_size > 1:
+ if self._declared_nccl_port is not None:
+ _server.reserve_port(self._declared_nccl_port)
+ self._reserved_nccl_port = self._declared_nccl_port
+ else:
+ self._reserved_nccl_port = _server.find_free_port(_server.NCCL_BASE_PORT)
+ self._nccl_port = self._reserved_nccl_port
+ cmd.extend(["--nccl-port", str(self._nccl_port)])
self._output_file = _server.open_output_log()
- self._process = _server.launch_sglang_server(cmd, device_index=device_index, output_file=self._output_file)
+ self._process = _server.launch_sglang_server(
+ cmd, device_indices=device_indices, output_file=self._output_file
+ )
if not _server.wait_for_server(
self._server_url,
@@ -354,6 +429,12 @@ class SGLangEmbeddingAdapter(BaseAdapter):
_server.terminate_process(self._process)
self._process = None
_server.release_port(self._port)
+ # Guarded rather than unconditional: width one never reserves a
+ # collective port, and its teardown must stay exactly as it was.
+ if self._reserved_nccl_port is not None:
+ _server.release_port(self._reserved_nccl_port)
+ self._reserved_nccl_port = None
+ self._nccl_port = None
self._port = None
self._server_url = None
self._device = None
@@ -375,6 +456,12 @@ class SGLangEmbeddingAdapter(BaseAdapter):
# Release only after the child is down so a concurrent load can't be
# handed a port the dying child still holds bound.
_server.release_port(self._port)
+ # Guarded rather than unconditional: width one never reserves a
+ # collective port, and its teardown must stay exactly as it was.
+ if self._reserved_nccl_port is not None:
+ _server.release_port(self._reserved_nccl_port)
+ self._reserved_nccl_port = None
+ self._nccl_port = None
self._port = None
self._server_url = None
self._device = None
@@ -451,7 +538,8 @@ class SGLangEmbeddingAdapter(BaseAdapter):
self._validate_output_types(output_types)
# Resolve runtime options (config defaults -> profile -> request overrides)
- # Note: pooling is NOT overridable for SGLang (set at subprocess startup via --pooling-method)
+ # Note: pooling is not overridable. The engine decides it from the
+ # checkpoint, and neither pinned version accepts a flag for it.
opts = options or {}
query_template = opts.get("query_template", self._query_template)
doc_template = opts.get("doc_template", self._doc_template)
@@ -642,7 +730,7 @@ class SGLangEmbeddingAdapter(BaseAdapter):
"input": texts,
"encoding_format": "float",
},
- timeout=60,
+ timeout=self._request_read_timeout_s,
)
if response.status_code != 200:
logger.error(
diff --git a/packages/sie_server/src/sie_server/adapters/sglang/generation.py b/packages/sie_server/src/sie_server/adapters/sglang/generation.py
index 04ca11165..0e52ee796 100644
--- a/packages/sie_server/src/sie_server/adapters/sglang/generation.py
+++ b/packages/sie_server/src/sie_server/adapters/sglang/generation.py
@@ -93,12 +93,47 @@ def _resolve_read_timeout() -> float | None:
value = float(raw)
except ValueError:
return None
- return value if value > 0 else None
+ return value if math.isfinite(value) and value > 0 else None
_GENERATE_READ_TIMEOUT_S: float | None = _resolve_read_timeout()
+def _resolve_profile_read_timeout(declared: float | None, *, tensor_parallel_size: int) -> float | None:
+ """Return the streaming read cap for one adapter instance.
+
+ Args:
+ declared: The profile's own value, or None to inherit the module
+ default.
+ tensor_parallel_size: Declared width. Above one a finite cap is
+ required rather than optional.
+
+ Raises:
+ ValueError: If the declared value is not a positive finite number, or
+ if a width above one is left without a cap. A stalled collective
+ emits no bytes and raises nothing, so an unbounded read on a
+ multi-accelerator load is a request that never ends and a group of
+ accelerators that is never freed.
+ """
+ if declared is not None:
+ if isinstance(declared, bool) or not isinstance(declared, (int, float)):
+ msg = f"request_read_timeout_s must be a number, got {declared!r}"
+ raise ValueError(msg)
+ if not math.isfinite(declared) or declared <= 0:
+ msg = f"request_read_timeout_s must be a finite number greater than zero, got {declared!r}"
+ raise ValueError(msg)
+ return float(declared)
+ effective = _GENERATE_READ_TIMEOUT_S
+ if tensor_parallel_size > 1 and effective is None:
+ msg = (
+ f"a profile declaring tensor_parallel_size={tensor_parallel_size} must also declare a finite "
+ "request_read_timeout_s. A stalled collective produces no bytes and no error, so an "
+ "unbounded read would hold the request and its accelerators open indefinitely."
+ )
+ raise ValueError(msg)
+ return effective
+
+
def _mamba_scheduler_strategy_value(extra_launch_args: list[str]) -> str | None:
"""Return the value passed to ``--mamba-scheduler-strategy``, or ``None``.
@@ -348,12 +383,55 @@ class SGLangGenerationAdapter(GenerationAdapter):
# adapters in one batch (SGLang ``--max-loras-per-batch``).
lora_paths: dict[str, str] | None = None,
max_loras_per_batch: int = 4,
+ # Tensor-parallel width. One is every existing profile and keeps the
+ # launch argv byte-identical. Above one, this adapter owns that many
+ # whole accelerators for the life of the load, which is an exclusive
+ # claim the registry accounts for rather than a placement hint.
+ tensor_parallel_size: int = 1,
+ # Wall-clock cap on the gap between streamed bytes. None keeps the
+ # module default, which is unbounded so the worker's own admission and
+ # cancel layer owns request lifetime. A width above one must set it:
+ # a stalled collective produces no bytes and no error, so an unbounded
+ # read would hold the request open indefinitely. The cap fails the
+ # request; it does not unload or restart the engine.
+ request_read_timeout_s: float | None = None,
+ # Seconds a single forward batch may take before the engine crashes
+ # itself. None keeps the engine's own default. A crashed engine fails
+ # every later request; the adapter does not unload or restart it.
+ watchdog_timeout_s: float | None = None,
+ # Collective rendezvous port. None lets SIE reserve one beside the HTTP
+ # port, which is the point: the engine's own default is a random port,
+ # and two groups starting together can collide on it.
+ nccl_port: int | None = None,
+ # SGLang enables a piecewise CUDA-graph capture path by default. It is
+ # measured to hang indefinitely at width two and to exhaust memory at
+ # width four, on a card and memory fraction where width one serves
+ # normally, so any width above one disables it unless a profile opts
+ # back in explicitly. None means "decide from the width".
+ disable_piecewise_cuda_graph: bool | None = None,
**kwargs: Any, # accept extra args from loader for compatibility
) -> None:
_ = kwargs
self._model_name_or_path = str(model_name_or_path)
self._max_seq_length = max_seq_length
self._mem_fraction_static = mem_fraction_static
+ self._tensor_parallel_size = _server.validate_tensor_parallel_size(tensor_parallel_size)
+ self._watchdog_timeout_s = _server.validate_optional_positive(watchdog_timeout_s, field="watchdog_timeout_s")
+ self._declared_nccl_port = _server.validate_optional_port(nccl_port)
+ if self._declared_nccl_port is not None and self._tensor_parallel_size == 1:
+ msg = "nccl_port applies only above tensor_parallel_size=1; a single rank has no rendezvous"
+ raise ValueError(msg)
+ self._nccl_port: int | None = None
+ # Declared or chosen, the rendezvous port is reserved in the shared set,
+ # so teardown hands back exactly what this adapter holds.
+ self._reserved_nccl_port: int | None = None
+ self._request_read_timeout_s = _resolve_profile_read_timeout(
+ request_read_timeout_s,
+ tensor_parallel_size=self._tensor_parallel_size,
+ )
+ self._disable_piecewise_cuda_graph = (
+ self._tensor_parallel_size > 1 if disable_piecewise_cuda_graph is None else disable_piecewise_cuda_graph
+ )
self._compute_precision = compute_precision
self._trust_remote_code = trust_remote_code
self._revision = revision
@@ -515,6 +593,17 @@ class SGLangGenerationAdapter(GenerationAdapter):
def load(self, device: str) -> None:
self._device = device
device_index = _server.parse_device_index(device)
+ # Derived from the anchor and the declared width by the one shared
+ # rule, so this adapter claims exactly the cards the registry reserved.
+ device_indices = _server.resolve_device_group(device_index, self._tensor_parallel_size)
+ # Before any accelerator is claimed: a width the model's own head counts
+ # cannot be divided by fails here rather than minutes into the engine's
+ # own assertion, with the whole group held in the meantime.
+ _server.validate_width_against_model_config(
+ self._tensor_parallel_size,
+ model_name_or_path=self._model_name_or_path,
+ revision=self._revision,
+ )
port = _server.find_free_port()
self._port = port
self._server_url = f"http://localhost:{port}"
@@ -523,24 +612,35 @@ class SGLangGenerationAdapter(GenerationAdapter):
# the reservation above onward, so every raise below hands them back
# rather than leaking one slot of the 100-port span per attempt: a full
# /tmp in open_output_log, a failed exec, the pre-launch speculative
- # validation, or a cancelled load included.
+ # validation, an exhausted rendezvous span, or a cancelled load
+ # included.
try:
- self._start_server(port=port, device_index=device_index, server_url=self._server_url)
+ # Only a group rendezvouses, so width one reserves nothing and its
+ # launch argv is unchanged.
+ if self._tensor_parallel_size > 1:
+ if self._declared_nccl_port is not None:
+ _server.reserve_port(self._declared_nccl_port)
+ self._reserved_nccl_port = self._declared_nccl_port
+ else:
+ self._reserved_nccl_port = _server.find_free_port(_server.NCCL_BASE_PORT)
+ self._nccl_port = self._reserved_nccl_port
+ self._start_server(port=port, device_indices=device_indices, server_url=self._server_url)
except BaseException:
self._abort_failed_load()
raise
- def _start_server(self, *, port: int, device_index: int, server_url: str) -> None:
+ def _start_server(self, *, port: int, device_indices: list[int], server_url: str) -> None:
"""Launch the SGLang child and block until it serves the model.
Always called under ``load``'s abort-on-failure guard, so it raises
without cleaning up the port or log itself.
"""
logger.info(
- "Starting SGLang generation server for %s on device=%s (gpu_id=%d) at port %d",
+ "Starting SGLang generation server for %s on device=%s (gpu_ids=%s, tp=%d) at port %d",
self._model_name_or_path,
self._device,
- device_index,
+ ",".join(str(index) for index in device_indices),
+ self._tensor_parallel_size,
port,
)
@@ -559,8 +659,12 @@ class SGLangGenerationAdapter(GenerationAdapter):
str(self._max_seq_length),
"--mem-fraction-static",
str(self._mem_fraction_static),
- "--tp",
- "1",
+ # Full flag name, not the "--tp" abbreviation. Nothing upstream
+ # disables abbreviation matching, so a future upstream flag sharing
+ # that prefix would break every SIE launch with an ambiguous-option
+ # error rather than a clear one.
+ "--tensor-parallel-size",
+ str(self._tensor_parallel_size),
"--log-level",
"warning",
"--served-model-name",
@@ -572,6 +676,18 @@ class SGLangGenerationAdapter(GenerationAdapter):
cmd.extend(["--revision", self._revision])
if self._disable_cuda_graph:
cmd.append("--disable-cuda-graph")
+ # Distinct from --disable-cuda-graph, which turns off graph replay
+ # entirely. This disables only the piecewise capture path, so width
+ # above one keeps ordinary graph replay and its throughput.
+ if self._disable_piecewise_cuda_graph and not self._disable_cuda_graph:
+ cmd.append("--disable-piecewise-cuda-graph")
+ # A forward batch that exceeds this crashes the engine rather than
+ # hanging, so requests fail instead of waiting on a rank that will not
+ # answer.
+ if self._watchdog_timeout_s is not None:
+ cmd.extend(["--watchdog-timeout", str(self._watchdog_timeout_s)])
+ if self._nccl_port is not None:
+ cmd.extend(["--nccl-port", str(self._nccl_port)])
if self._attention_backend:
cmd.extend(["--attention-backend", self._attention_backend])
if self._grammar_backend:
@@ -640,7 +756,7 @@ class SGLangGenerationAdapter(GenerationAdapter):
)
self._process = _server.launch_sglang_server(
cmd,
- device_index=device_index,
+ device_indices=device_indices,
output_file=self._output_file,
extra_env=extra_env or None,
)
@@ -691,6 +807,12 @@ class SGLangGenerationAdapter(GenerationAdapter):
_server.terminate_process(self._process)
self._process = None
_server.release_port(self._port)
+ # Guarded rather than unconditional: width one never reserves a
+ # collective port, and its teardown must stay exactly as it was.
+ if self._reserved_nccl_port is not None:
+ _server.release_port(self._reserved_nccl_port)
+ self._reserved_nccl_port = None
+ self._nccl_port = None
self._port = None
self._server_url = None
self._device = None
@@ -1014,6 +1136,12 @@ class SGLangGenerationAdapter(GenerationAdapter):
# Release only after the child is down so a concurrent load can't be
# handed a port the dying child still holds bound.
_server.release_port(self._port)
+ # Guarded rather than unconditional: width one never reserves a
+ # collective port, and its teardown must stay exactly as it was.
+ if self._reserved_nccl_port is not None:
+ _server.release_port(self._reserved_nccl_port)
+ self._reserved_nccl_port = None
+ self._nccl_port = None
self._port = None
self._server_url = None
self._device = None
@@ -1050,6 +1178,39 @@ class SGLangGenerationAdapter(GenerationAdapter):
def _check_loaded(self) -> None:
if self._server_url is None:
raise RuntimeError(ERR_NOT_LOADED)
+ self._check_engine_alive()
+
+ def _check_engine_alive(self) -> None:
+ """Fail a request whose engine child has already exited.
+
+ Without this the adapter never notices. Every request goes on to open a
+ connection to a port nobody is listening on, waits out the connect
+ timeout and returns a transport error, forever, with no reload and no
+ readiness change. On one accelerator that is a wasteful way to say
+ "dead". On four it strands four accelerators behind a queue of requests
+ that cannot succeed.
+
+ Measured on a four-rank group: a killed rank makes the engine
+ refuse health in about 5 seconds, but its process tree takes about 67
+ seconds to exit. This check is what turns the rest of that window, and
+ everything after it, into one terminal answer rather than a timeout per
+ request.
+
+ Raises:
+ RuntimeError: Naming the exit code, so a crash is distinguishable
+ from an orderly unload in a log.
+ """
+ process = self._process
+ if process is None:
+ return
+ exit_code = process.poll()
+ if exit_code is None:
+ return
+ msg = (
+ f"SGLang engine for {self._served_model_name!r} is not running "
+ f"(process exited with code {exit_code}). The model must be reloaded."
+ )
+ raise RuntimeError(msg)
async def _get_or_create_http_client(self) -> httpx.AsyncClient:
"""Return the shared client, opening it if this is the first call.
@@ -1092,7 +1253,7 @@ class SGLangGenerationAdapter(GenerationAdapter):
self._http_client = httpx.AsyncClient(
timeout=httpx.Timeout(
connect=_GENERATE_CONNECT_TIMEOUT_S,
- read=_GENERATE_READ_TIMEOUT_S,
+ read=self._request_read_timeout_s,
write=_GENERATE_WRITE_TIMEOUT_S,
pool=_GENERATE_POOL_TIMEOUT_S,
),
diff --git a/packages/sie_server/src/sie_server/config/device_groups.py b/packages/sie_server/src/sie_server/config/device_groups.py
new file mode 100644
index 000000000..ecc1c13f8
--- /dev/null
+++ b/packages/sie_server/src/sie_server/config/device_groups.py
@@ -0,0 +1,83 @@
+"""Ordered accelerator groups claimed by one model.
+
+A model whose profile declares a tensor-parallel width above one does not sit
+on a device, it owns several of them for the life of the load. That is an
+exception to the registry's ordinary placement, where devices are shared and a
+model can be evicted to make room. The rules live here, engine-neutral, so the
+adapter that launches the engine and the registry that reserves the hardware
+derive the same group from the same anchor and cannot disagree about which
+cards are taken.
+"""
+
+from __future__ import annotations
+
+from collections.abc import Sequence
+
+MAX_TENSOR_PARALLEL_SIZE = 8
+"""Largest declarable width.
+
+A surface limit rather than a hardware one. A declared width is an exclusive
+claim on that many whole cards, so an unbounded field would let a typo claim
+every card a worker has.
+"""
+
+
+def validate_tensor_parallel_size(value: object) -> int:
+ """Return ``value`` as a usable tensor-parallel width, or raise.
+
+ Rejects ``bool`` explicitly. ``True`` is an ``int`` in Python and would
+ otherwise pass as width one, turning a mistyped flag into a silent
+ single-device load on a deployment sized for the whole group.
+
+ Raises:
+ ValueError: If the value is not an integer in range.
+ """
+ if isinstance(value, bool) or not isinstance(value, int):
+ msg = f"tensor_parallel_size must be an integer, got {value!r}"
+ raise ValueError(msg)
+ if not 1 <= value <= MAX_TENSOR_PARALLEL_SIZE:
+ msg = f"tensor_parallel_size must be between 1 and {MAX_TENSOR_PARALLEL_SIZE}, got {value}"
+ raise ValueError(msg)
+ return value
+
+
+def resolve_device_group(anchor_index: int, width: int) -> list[int]:
+ """Return the ordered CUDA indices a width-``width`` load claims from ``anchor_index``.
+
+ The group is the contiguous block starting at the anchor. Contiguity is not
+ a performance claim, it is what makes the mapping single-valued: two
+ callers given the same anchor and width name the same cards. Whether those
+ cards exist is the registry's check, made against its own device list.
+
+ Args:
+ anchor_index: The device the placement decision selected.
+ width: Declared width. One yields ``[anchor_index]``.
+
+ Raises:
+ ValueError: If ``width`` is below one or the anchor is negative.
+ """
+ if width < 1:
+ msg = f"tensor-parallel width must be at least 1, got {width}"
+ raise ValueError(msg)
+ if anchor_index < 0:
+ msg = f"anchor device index must not be negative, got {anchor_index}"
+ raise ValueError(msg)
+ return list(range(anchor_index, anchor_index + width))
+
+
+def format_device_mask(device_indices: Sequence[int]) -> str:
+ """Return the ``CUDA_VISIBLE_DEVICES`` value for an ordered group.
+
+ Order is preserved because rank N binds the Nth entry of the mask.
+
+ Raises:
+ ValueError: If the group is empty, or a device repeats. A repeat would
+ give two ranks the same card, which deadlocks rather than fails.
+ """
+ if not device_indices:
+ msg = "a device group must contain at least one device index"
+ raise ValueError(msg)
+ if len(set(device_indices)) != len(device_indices):
+ msg = f"device indices must be distinct, got {list(device_indices)!r}"
+ raise ValueError(msg)
+ return ",".join(str(index) for index in device_indices)
diff --git a/packages/sie_server/src/sie_server/config/model.py b/packages/sie_server/src/sie_server/config/model.py
index 2798e7fbb..d5553fa78 100644
--- a/packages/sie_server/src/sie_server/config/model.py
+++ b/packages/sie_server/src/sie_server/config/model.py
@@ -9,6 +9,7 @@ from typing import Any, Literal
from pydantic import BaseModel, ConfigDict, Field, PrivateAttr, field_validator, model_validator
+from sie_server.config.device_groups import validate_tensor_parallel_size
from sie_server.config.engine import ComputePrecision
from sie_server.config.package_artifacts import (
PackageArtifactDeclaration,
@@ -291,6 +292,52 @@ class Tasks(BaseModel):
generate: GenerateTask | None = None
+_PLACEMENT_LAUNCH_FLAGS = frozenset(
+ {
+ "--tp",
+ "--tp-size",
+ "--tensor-parallel-size",
+ "--dp",
+ "--dp-size",
+ "--data-parallel-size",
+ "--ep-size",
+ "--expert-parallel-size",
+ "--pp-size",
+ "--pipeline-parallel-size",
+ "--nnodes",
+ "--node-rank",
+ "--dist-init-addr",
+ "--base-gpu-id",
+ "--gpu-id-step",
+ }
+)
+"""Launch flags that decide how many accelerators a model takes, or which.
+
+Each one is refused inside ``extra_launch_args`` because the registry reserves
+devices from the declared width, and a width passed straight to the engine
+would serve on devices nothing reserved.
+"""
+
+
+def _refused_placement_flag(token: object) -> str | None:
+ """The placement flag a launch-argument token spells, abbreviations included.
+
+ SGLang's parser accepts any unambiguous prefix of a long option, so
+ ``--tensor-parallel 4`` reaches ``--tensor-parallel-size`` exactly as the
+ full spelling does.
+ """
+ flag = str(token).split("=", 1)[0].strip()
+ if not flag.startswith("--") or len(flag) <= len("--"):
+ return None
+ for refused in sorted(_PLACEMENT_LAUNCH_FLAGS):
+ if refused.startswith(flag):
+ return refused
+ return None
+
+
+_PLACEMENT_ENV_VARS = frozenset({"CUDA_VISIBLE_DEVICES", "NVIDIA_VISIBLE_DEVICES", "ROCR_VISIBLE_DEVICES"})
+
+
class AdapterOptions(BaseModel):
model_config = ConfigDict(extra="forbid")
@@ -372,6 +419,50 @@ class AdapterOptions(BaseModel):
parse_serving_artifact_declaration(self.loadtime)
return self
+ @model_validator(mode="after")
+ def validate_placement_is_not_smuggled(self) -> "AdapterOptions":
+ """Refuse placement facts hidden in the raw passthroughs.
+
+ How many accelerators a model takes has to be visible to the registry
+ that reserves them. A width reaching the engine through
+ ``extra_launch_args`` is not, so the model would serve on a group
+ nothing reserved. ``extra_env`` is refused for the same reason, and
+ because the launcher writes the device mask last, so a mask set there
+ would be silently discarded rather than honoured.
+
+ Requirements that belong to one engine, such as a read cap for a
+ group, are enforced by that engine's adapter, since a width is valid
+ for any adapter that accepts one.
+ """
+ # Key presence, not value: an explicit null is a mistake rather than a
+ # request for the default, and the adapter rejects it either way.
+ # Catching it here keeps the two layers from disagreeing.
+ if "tensor_parallel_size" in self.loadtime:
+ validate_tensor_parallel_size(self.loadtime.get("tensor_parallel_size"))
+
+ raw_args = self.loadtime.get("extra_launch_args") or []
+ if isinstance(raw_args, list):
+ for entry in raw_args:
+ refused = _refused_placement_flag(entry)
+ if refused is not None:
+ msg = (
+ f"extra_launch_args carries {str(entry).split('=', 1)[0].strip()!r}, which sets the "
+ f"placement flag {refused!r}. Declare the width as "
+ "loadtime.tensor_parallel_size instead, so the registry can reserve the devices."
+ )
+ raise ValueError(msg)
+
+ raw_env = self.loadtime.get("extra_env") or {}
+ if isinstance(raw_env, dict):
+ for key in raw_env:
+ if str(key).strip().upper() in _PLACEMENT_ENV_VARS:
+ msg = (
+ f"extra_env sets {key!r}, which the launcher overwrites with the "
+ "registry's device mask. Declare loadtime.tensor_parallel_size instead."
+ )
+ raise ValueError(msg)
+ return self
+
class ProfileAdaptiveBatching(BaseModel):
"""Per-model adaptive batching overrides.
diff --git a/packages/sie_server/src/sie_server/core/load_errors.py b/packages/sie_server/src/sie_server/core/load_errors.py
index 002d42ddc..089985b9b 100644
--- a/packages/sie_server/src/sie_server/core/load_errors.py
+++ b/packages/sie_server/src/sie_server/core/load_errors.py
@@ -16,9 +16,9 @@ class LoadErrorClass(StrEnum):
Permanent classes (``GATED``, ``NOT_FOUND``, ``DEPENDENCY``) should not
be retried automatically because re-attempting them produces the same
- error every time and burns request budget. ``OOM`` and ``NETWORK`` are
- transient — the registry holds a cooldown to avoid hot retry loops
- but eventually allows another attempt. ``UNKNOWN`` is treated as
+ error every time and burns request budget. ``OOM``, ``NETWORK`` and
+ ``PLACEMENT`` are transient — the registry holds a cooldown to avoid hot
+ retry loops but eventually allows another attempt. ``UNKNOWN`` is treated as
permanent for safety; operators should inspect the underlying error
and either fix it or restart the server to clear the failure.
"""
@@ -29,6 +29,7 @@ class LoadErrorClass(StrEnum):
NETWORK = "NETWORK"
DEPENDENCY = "DEPENDENCY"
TIMEOUT = "TIMEOUT"
+ PLACEMENT = "PLACEMENT"
UNKNOWN = "UNKNOWN"
@@ -45,9 +46,19 @@ _COOLDOWN_BY_CLASS: dict[LoadErrorClass, float | None] = {
LoadErrorClass.OOM: 60.0,
LoadErrorClass.NETWORK: 30.0,
LoadErrorClass.TIMEOUT: 30.0,
+ LoadErrorClass.PLACEMENT: 30.0,
}
+class DevicePlacementError(RuntimeError):
+ """No device, or no block of devices, can take this load right now.
+
+ Another model loading or unloading changes the answer, so the failure is
+ retried after a cooldown and cleared on unload rather than staying sticky
+ the way an unclassified error does.
+ """
+
+
class ModelLoadTimeoutError(TimeoutError):
"""Raised when a post-download load stage exceeds ``SIE_MODEL_LOAD_TIMEOUT_S``.
@@ -109,6 +120,13 @@ def classify_load_error(exc: BaseException) -> LoadFailureClassification:
cooldown_s=_COOLDOWN_BY_CLASS[LoadErrorClass.TIMEOUT],
)
+ # Checked before OOM because both are RuntimeErrors.
+ if isinstance(exc, DevicePlacementError):
+ return LoadFailureClassification(
+ error_class=LoadErrorClass.PLACEMENT,
+ cooldown_s=_COOLDOWN_BY_CLASS[LoadErrorClass.PLACEMENT],
+ )
+
# Gated repo (HF auth) — permanent until operator fixes HF_TOKEN.
if isinstance(exc, GatedModelError):
return LoadFailureClassification(
diff --git a/packages/sie_server/src/sie_server/core/loader.py b/packages/sie_server/src/sie_server/core/loader.py
index f540eebe0..9c2ee061c 100644
--- a/packages/sie_server/src/sie_server/core/loader.py
+++ b/packages/sie_server/src/sie_server/core/loader.py
@@ -1,3 +1,4 @@
+import difflib
import importlib
import importlib.util
import inspect
@@ -373,6 +374,99 @@ def load_model_config(config_path: Path) -> ModelConfig:
return ModelConfig(**raw_config)
+_LOADTIME_PASSTHROUGH_ALLOWLIST = frozenset(
+ {
+ # Forwarded verbatim into the HuggingFace config/loader by the flash
+ # encoder adapters, which take them through **kwargs by design.
+ "config_kwargs",
+ "trust_remote_code",
+ # Read by the Apple-silicon generation path, which selects a sibling
+ # repo rather than a constructor parameter.
+ "mlx_repo",
+ }
+)
+"""Load-time keys that reach an adapter through ``**kwargs`` on purpose.
+
+These are genuinely absorbed rather than named, so the rule below can be
+strict without breaking an existing profile.
+"""
+
+
+_LOADER_OWNED_LOADTIME_KEYS = frozenset(
+ {
+ SERVING_ARTIFACT_KEY,
+ PACKAGE_ARTIFACT_MODE_KEY,
+ PACKAGE_ARTIFACT_MANIFEST_PATH_KEY,
+ PACKAGE_ARTIFACT_MANIFEST_SHA256_KEY,
+ }
+)
+"""Load-time keys the loader consumes instead of forwarding.
+
+``_build_adapter_kwargs`` pops each of these and instantiates the adapter with
+the parameters it derives from them, so no adapter names the declared spelling
+and measuring one against a constructor signature rejects a valid profile.
+``test_catalog_loadtime_options.py`` holds this set and the allowlist above to
+the shipped catalog.
+"""
+
+
+def _accepted_adapter_parameters(adapter_class: type) -> set[str]:
+ """Return every keyword any ``__init__`` in the class's MRO names.
+
+ The chain matters: a thin subclass that forwards ``**kwargs`` to its parent
+ accepts the parent's keywords, and treating only its own signature as the
+ contract would reject options that work today.
+ """
+ names: set[str] = set()
+ for klass in adapter_class.__mro__:
+ initializer = klass.__dict__.get("__init__")
+ if initializer is None:
+ continue
+ try:
+ names |= set(inspect.signature(initializer).parameters)
+ except (TypeError, ValueError):
+ continue
+ return names
+
+
+def reject_unknown_loadtime_options(
+ adapter_class: type,
+ loadtime: Mapping[str, Any],
+ *,
+ model_name: str,
+) -> None:
+ """Fail a load whose profile sets an option the adapter cannot receive.
+
+ Every adapter accepts ``**kwargs`` for forward compatibility, so an option
+ the constructor does not name is not rejected by Python. It is silently
+ dropped. That is how a mistyped ``tensor_parallel_size`` serves one
+ accelerator while the deployment reserves several, and the same silence
+ hides a mistyped precision, cache budget or grammar backend.
+
+ Raises:
+ ValueError: Naming the unknown keys, the adapter, and the closest
+ accepted spelling where one is obvious.
+ """
+ accepted = _accepted_adapter_parameters(adapter_class)
+ unknown = sorted(
+ key
+ for key in loadtime
+ if key not in accepted and key not in _LOADTIME_PASSTHROUGH_ALLOWLIST and key not in _LOADER_OWNED_LOADTIME_KEYS
+ )
+ if not unknown:
+ return
+ hints: list[str] = []
+ for key in unknown:
+ close = difflib.get_close_matches(key, sorted(accepted), n=1, cutoff=0.8)
+ hints.append(f"{key!r}" + (f" (did you mean {close[0]!r}?)" if close else ""))
+ msg = (
+ f"Model '{model_name}': adapter {adapter_class.__name__} does not accept load-time "
+ f"option(s) {', '.join(hints)}. An unrecognised option is dropped rather than applied, "
+ "so the model would serve with a different configuration than the profile declares."
+ )
+ raise ValueError(msg)
+
+
def resolve_adapter_path(
config: ModelConfig,
model_dir: Path,
@@ -409,6 +503,42 @@ def resolve_adapter_path(
return f"{full_path}:{class_part}"
+def resolve_adapter_class(config: ModelConfig, model_dir: Path) -> type[ModelAdapter]:
+ """Import the adapter class a config names, without instantiating it.
+
+ Raises:
+ ValueError: If the adapter path is malformed.
+ ImportError: If the adapter module or class cannot be found.
+ """
+ adapter_path = resolve_adapter_path(config, model_dir)
+
+ # Parse module:class
+ if ":" not in adapter_path:
+ msg = f"Invalid adapter path '{adapter_path}': expected 'module:ClassName'"
+ raise ValueError(msg)
+
+ module_path, class_name = adapter_path.rsplit(":", 1)
+
+ if module_path.startswith("sie_server."):
+ # Built-in adapter: import normally
+ return _import_builtin_adapter(module_path, class_name)
+ # Custom adapter: load from file path
+ return _import_custom_adapter(Path(module_path), class_name)
+
+
+def validate_loadtime_options(config: ModelConfig, model_dir: Path) -> None:
+ """Refuse a profile whose load-time options its adapter cannot receive.
+
+ The same check ``load_adapter`` makes, available before a caller commits
+ resources to the load.
+ """
+ reject_unknown_loadtime_options(
+ resolve_adapter_class(config, model_dir),
+ config.resolve_profile("default").loadtime,
+ model_name=config.sie_id,
+ )
+
+
def load_adapter(
config: ModelConfig,
model_dir: Path,
@@ -435,22 +565,7 @@ def load_adapter(
doesn't support the config's output types.
ImportError: If adapter module/class not found.
"""
- adapter_path = resolve_adapter_path(config, model_dir)
-
- # Parse module:class
- if ":" not in adapter_path:
- msg = f"Invalid adapter path '{adapter_path}': expected 'module:ClassName'"
- raise ValueError(msg)
-
- module_path, class_name = adapter_path.rsplit(":", 1)
-
- # Load the adapter class
- if module_path.startswith("sie_server."):
- # Built-in adapter: import normally
- adapter_class = _import_builtin_adapter(module_path, class_name)
- else:
- # Custom adapter: load from file path
- adapter_class = _import_custom_adapter(Path(module_path), class_name)
+ adapter_class = resolve_adapter_class(config, model_dir)
# Instantiate with config values. The engine-level default compute precision
# is fp32 off-CUDA (numerically safe on CPU/MPS for models we have not verified
@@ -461,6 +576,12 @@ def load_adapter(
effective_default_precision: ComputePrecision = (
default_compute_precision if device.startswith("cuda") else "float32"
)
+ reject_unknown_loadtime_options(
+ adapter_class,
+ config.resolve_profile("default").loadtime,
+ model_name=config.sie_id,
+ )
+
adapter_kwargs = _build_adapter_kwargs(
config,
effective_default_precision,
diff --git a/packages/sie_server/src/sie_server/core/registry.py b/packages/sie_server/src/sie_server/core/registry.py
index 9b70f71b2..aa3d8b668 100644
--- a/packages/sie_server/src/sie_server/core/registry.py
+++ b/packages/sie_server/src/sie_server/core/registry.py
@@ -27,17 +27,19 @@ from sie_sdk.storage import is_cloud_path
from sie_server.adapters._generation_base import GenerationAdapter
from sie_server.adapters.base import ModelAdapter
+from sie_server.config.device_groups import resolve_device_group, validate_tensor_parallel_size
from sie_server.config.engine import EngineConfig
from sie_server.config.model import ModelConfig
from sie_server.core.disk_cache import DiskCacheConfig, ModelDiskCacheManager
from sie_server.core.hot_reload import HotReloader
from sie_server.core.load_errors import (
+ DevicePlacementError,
LoadErrorClass,
LoadFailure,
ModelLoadTimeoutError,
classify_load_error,
)
-from sie_server.core.loader import expand_profile_variants, load_model_configs
+from sie_server.core.loader import expand_profile_variants, load_model_configs, validate_loadtime_options
from sie_server.core.memory import MemoryConfig, MemoryManager
from sie_server.core.model_loader import DEFAULT_MAX_LORAS, LoadedModel, ModelLoader
from sie_server.core.oom import is_oom_error
@@ -155,6 +157,26 @@ def _device_family(device: str) -> str:
return device.split(":", 1)[0].lower()
+def declared_tensor_parallel_size(config: ModelConfig) -> int:
+ """Return the width a config declares, defaulting to one.
+
+ Read from the same resolved profile the loader builds adapter kwargs from,
+ so the registry reserves exactly the devices the adapter will claim. A
+ malformed value is reported as a load failure rather than silently treated
+ as one, because a width that reads as one would serve on a single card
+ while the operator believes several are in use.
+
+ A config with no resolvable default profile raises here rather than
+ defaulting, for the same reason: the loader would fail on it moments later
+ anyway, and a width guessed from an unreadable profile is the one answer
+ that fails quietly.
+ """
+ declared = config.resolve_profile("default").loadtime.get("tensor_parallel_size")
+ if declared is None:
+ return 1
+ return validate_tensor_parallel_size(declared)
+
+
class ModelRegistry:
"""Registry for managing model configs and loaded models.
@@ -226,6 +248,11 @@ class ModelRegistry:
self._configs: dict[str, ModelConfig] = {}
self._model_dirs: dict[str, Path] = {}
self._loaded: dict[str, LoadedModel] = {}
+ # Devices held exclusively by a multi-device load: device name -> model.
+ # Only a width above one populates this, so a deployment of ordinary
+ # single-device models never consults a non-empty map and behaves
+ # exactly as it did before widths existed.
+ self._device_claims: dict[str, str] = {}
preprocessor_workers = engine_config.preprocessor_workers if engine_config else None
self._preprocessor_registry = PreprocessorRegistry(max_workers=preprocessor_workers)
# Share CPU pool between preprocessor and postprocessor registries
@@ -643,8 +670,22 @@ class ModelRegistry:
def _select_device_for_model(self, requested_family: str | None = None) -> str:
candidates = [
- device for device in self._devices if requested_family is None or _device_family(device) == requested_family
+ device
+ for device in self._devices
+ if (requested_family is None or _device_family(device) == requested_family)
+ and device not in self._device_claims
]
+ if not candidates:
+ # Every eligible device is exclusively held by a multi-device model.
+ # Falling back to the unfiltered list would place this model onto a
+ # group member, which is the corruption the claim exists to prevent:
+ # the group sized its cache against the whole card.
+ held = sorted(self._device_claims)
+ msg = (
+ f"No device is available for placement. Every eligible device is exclusively "
+ f"held by a multi-device model ({held}). Unload one of those models first."
+ )
+ raise DevicePlacementError(msg)
def score(device: str) -> tuple[bool, int, int]:
manager = self._memory_manager_for_device(device)
@@ -681,6 +722,316 @@ class ModelRegistry:
return self._select_device_for_model(requested_family)
return requested_device
+ def _device_index(self, device: str) -> int | None:
+ """Return the concrete CUDA index of ``device``, or None if it has none."""
+ _, _, suffix = device.partition(":")
+ if not suffix.isdigit():
+ return None
+ return int(suffix)
+
+ def _group_members(self, anchor_device: str, width: int) -> list[str] | None:
+ """Return the device names a width-``width`` load anchored here would claim.
+
+ None when the block runs off the end of this worker's device list, or
+ when the anchor carries no concrete index (``cuda`` rather than
+ ``cuda:0``), which is a single-device shape by construction.
+ """
+ anchor_index = self._device_index(anchor_device)
+ if anchor_index is None:
+ return [anchor_device] if width == 1 else None
+ family = _device_family(anchor_device)
+ try:
+ indices = resolve_device_group(anchor_index, width)
+ except ValueError:
+ return None
+ members = [f"{family}:{index}" for index in indices]
+ if any(member not in self._devices for member in members):
+ return None
+ return members
+
+ def _is_group_free(self, members: Iterable[str], *, for_model: str) -> bool:
+ """True when every member is unclaimed and hosts no other model.
+
+ A group member cannot be shared. The engine reserves the large majority
+ of each card it is given, so a co-resident model would have almost no
+ room, and the headroom it would compete for is what graph capture needs
+ for the group to start at all.
+ """
+ for member in members:
+ holder = self._device_claims.get(member)
+ if holder is not None and holder != for_model:
+ return False
+ manager = self._memory_managers.get(member)
+ if manager is None:
+ return False
+ residents = {
+ loaded_name
+ for loaded_name, loaded in self._loaded.items()
+ if loaded.device == member and loaded_name != for_model
+ }
+ if residents:
+ return False
+ return True
+
+ def _group_candidates(self, width: int, requested_device: str) -> list[tuple[str, list[str]]]:
+ """Every block of ``width`` devices on this worker, a named anchor first.
+
+ Built from the device list rather than the single-device resolver,
+ which refuses outright once every device is claimed: a resident group
+ would then be impossible to displace.
+ """
+ anchors = list(self._devices)
+ if requested_device in anchors:
+ anchors.remove(requested_device)
+ anchors.insert(0, requested_device)
+ candidates: list[tuple[str, list[str]]] = []
+ for anchor in anchors:
+ members = self._group_members(anchor, width)
+ if members is not None:
+ candidates.append((anchor, members))
+ return candidates
+
+ def _group_blockers(self, members: Iterable[str], *, for_model: str) -> set[str] | None:
+ """Models occupying ``members``, or None when no eviction can free the block.
+
+ A member this worker does not account for is not a device the group can
+ ever use, which is a different answer from a member something is merely
+ sitting on.
+ """
+ blockers: set[str] = set()
+ for member in members:
+ if self._memory_managers.get(member) is None:
+ return None
+ holder = self._device_claims.get(member)
+ if holder is not None and holder != for_model:
+ blockers.add(holder)
+ blockers.update(
+ loaded_name
+ for loaded_name, loaded in self._loaded.items()
+ if loaded.device == member and loaded_name != for_model
+ )
+ return blockers
+
+ def _resolve_group_placement(self, name: str, width: int, requested_device: str) -> tuple[str, list[str]]:
+ """Return the anchor device and the full group for a width-``width`` load.
+
+ Prefers the placement the ordinary resolver chose, then walks the
+ worker's device list for the first block that is entirely free.
+
+ Raises:
+ DevicePlacementError: When no block of that width is free. A
+ multi-device load must say so rather than silently serve on
+ fewer cards than it declared.
+ """
+ for anchor, members in self._group_candidates(width, requested_device):
+ if self._is_group_free(members, for_model=name):
+ return anchor, members
+ msg = (
+ f"Model '{name}' declares tensor_parallel_size={width} but no block of {width} "
+ f"free device(s) is available on this worker (devices={self._devices}, "
+ f"claims={sorted(self._device_claims)})"
+ )
+ raise DevicePlacementError(msg)
+
+ async def _resolve_group_placement_evicting(
+ self, name: str, width: int, requested_device: str
+ ) -> tuple[str, list[str]]:
+ """Return a group for ``name``, evicting unpinned residents when needed.
+
+ This registry is lazy-load with LRU eviction, so an occupied block is
+ not an unavailable one. Refusing to evict would let a single idle
+ neighbour keep a declared width from ever loading again, and nothing
+ would unload that neighbour afterwards: the failure would persist until
+ an operator intervened.
+
+ A block holding a pinned model is skipped rather than emptied, and the
+ block needing the fewest evictions wins.
+
+ Raises:
+ DevicePlacementError: When no block of that width can be freed.
+ """
+ candidates = self._group_candidates(width, requested_device)
+ fewest: tuple[str, list[str], set[str]] | None = None
+ for anchor, members in candidates:
+ blockers = self._group_blockers(members, for_model=name)
+ if blockers is None:
+ continue
+ if not blockers:
+ return anchor, members
+ if any(self._is_pinned(blocker) for blocker in blockers):
+ continue
+ if fewest is None or len(blockers) < len(fewest[2]):
+ fewest = (anchor, members, blockers)
+
+ if fewest is None:
+ msg = (
+ f"Model '{name}' declares tensor_parallel_size={width} but no block of {width} "
+ f"device(s) on this worker can be freed for it (devices={self._devices}, "
+ f"claims={sorted(self._device_claims)}, pinned={sorted(self._pinned_models)})"
+ )
+ raise DevicePlacementError(msg)
+
+ anchor, members, blockers = fewest
+ for blocker in sorted(blockers):
+ if blocker not in self._loaded:
+ continue
+ logger.info(
+ "Group placement: evicting '%s' to free %s for '%s' (tensor_parallel_size=%d)",
+ blocker,
+ members,
+ name,
+ width,
+ )
+ await self._do_unload(blocker, reason="group_placement")
+
+ if not self._is_group_free(members, for_model=name):
+ msg = (
+ f"Model '{name}' declares tensor_parallel_size={width} but {members} did not come "
+ f"free after evicting {sorted(blockers)}"
+ )
+ raise DevicePlacementError(msg)
+ return anchor, members
+
+ def _group_holder_to_evict(self, requested_device: str) -> str | None:
+ """The unpinned multi-device model a single-device load should displace.
+
+ A concrete request displaces the group holding that device. A family
+ request displaces the least recently used group holding a device of
+ that family. None when every candidate is pinned or already unloading.
+ """
+ family = _device_family(requested_device)
+ holders: set[str] = set()
+ for device, holder in self._device_claims.items():
+ if requested_device in self._devices:
+ if device != requested_device:
+ continue
+ elif _device_family(device) != family:
+ continue
+ if holder in self._loaded and holder not in self._unloading and not self._is_pinned(holder):
+ holders.add(holder)
+ if not holders:
+ return None
+
+ def last_used(holder: str) -> float:
+ info = self._memory_manager_for_model(holder).get_model_info(holder)
+ return info.last_used_at if info is not None else 0.0
+
+ return min(sorted(holders), key=last_used)
+
+ async def _resolve_single_device_evicting(self, name: str, requested_device: str) -> str:
+ """Resolve one device for a single-device load, displacing a group if it must.
+
+ Groups hold every card they claim, so once they hold every eligible
+ device a single-device load has nowhere to go. Nothing else would ever
+ unload such a group, so without this one wide model would keep every
+ other model on the worker from loading.
+
+ Raises:
+ DevicePlacementError: When no device is free and no group can be displaced.
+ """
+ for _ in range(len(self._devices) + 1):
+ try:
+ load_device = self._resolve_load_device(requested_device)
+ self._reject_claimed_device(name, load_device)
+ except DevicePlacementError:
+ holder = self._group_holder_to_evict(requested_device)
+ if holder is None:
+ raise
+ logger.info("Placement: evicting multi-device model '%s' to place '%s'", holder, name)
+ await self._do_unload(holder, reason="group_placement")
+ continue
+ return load_device
+ msg = f"Model '{name}' found no device after displacing every eligible multi-device model"
+ raise DevicePlacementError(msg)
+
+ def _reject_claimed_device(self, name: str, device: str) -> None:
+ """Refuse to place ``name`` on a device another model holds exclusively.
+
+ Placement by family already skips claimed devices. A request that names
+ a device outright bypasses that, and would otherwise put a second model
+ onto a card a tensor-parallel group has already sized its cache
+ against.
+
+ Raises:
+ DevicePlacementError: Naming the holder, so the conflict is actionable.
+ """
+ holder = self._device_claims.get(device)
+ if holder is None or holder == name:
+ return
+ msg = (
+ f"Cannot load '{name}' onto {device}: it is held exclusively by multi-device "
+ f"model '{holder}'. Unload '{holder}' first, or let the registry choose a device."
+ )
+ raise DevicePlacementError(msg)
+
+ def _claim_device_group(self, name: str, members: Iterable[str]) -> None:
+ claimed = list(members)
+ for member in claimed:
+ self._device_claims[member] = name
+ logger.info("Model '%s' claimed devices %s exclusively", name, claimed)
+
+ def _reject_unservable_width(self, name: str, width: int) -> None:
+ """Refuse a width this worker could never satisfy, whatever is free.
+
+ Distinct from "no free block right now", which is a transient placement
+ failure worth retrying. A worker with two devices can never serve a
+ width of four, so saying so plainly beats waiting for a block that
+ cannot exist.
+
+ Raises:
+ RuntimeError: Naming the declared width and the visible devices.
+ """
+ if width <= len(self._devices):
+ return
+ msg = (
+ f"Model '{name}' declares tensor_parallel_size={width} but this worker sees "
+ f"{len(self._devices)} device(s) ({self._devices}). The declared width and the "
+ "visible devices must agree."
+ )
+ raise RuntimeError(msg)
+
+ def _claimed_members(self, name: str) -> list[str]:
+ """Devices this model holds exclusively, anchor first, or empty."""
+ members = [device for device, holder in self._device_claims.items() if holder == name]
+ return sorted(members, key=lambda device: self._device_order.get(device, 0))
+
+ def _register_across_group(self, name: str, loaded: LoadedModel) -> None:
+ """Account for a load on every device it actually occupies.
+
+ A width-N load reserves memory on N cards. Registering only the anchor
+ leaves the other members looking free, so a later placement sizes itself
+ against memory this model already holds, and the eviction that would
+ have prevented the collision never fires.
+
+ The estimate is divided across members because sharding divides the
+ weights, so the total across the group is the figure a single-device
+ load of the same model would have registered, to within the truncation
+ of an integer division.
+
+ For the engine this work exists for that figure is zero by design: the
+ SGLang adapter reports no footprint because its child allocates in a
+ subprocess, and the registry reads the device instead. So the division
+ matters only for adapters that do report one. What matters on every
+ adapter is the registration itself, which is what placement scoring,
+ the eviction order and the group-free check all read.
+ """
+ members = self._claimed_members(name) or [loaded.device]
+ share = loaded.memory_bytes // len(members) if loaded.memory_bytes else 0
+ for device in members:
+ self._memory_manager_for_device(device).register_model(name, estimated_bytes=share)
+
+ def _unregister_across_group(self, name: str, anchor_device: str) -> None:
+ """Drop this model from every device manager that was accounting for it."""
+ for device in self._claimed_members(name) or [anchor_device]:
+ self._memory_manager_for_device(device).unregister_model(name)
+
+ def _release_device_claims(self, name: str) -> None:
+ released = [device for device, holder in self._device_claims.items() if holder == name]
+ for device in released:
+ del self._device_claims[device]
+ if released:
+ logger.info("Model '%s' released devices %s", name, released)
+
def has_model(self, name: str) -> bool:
"""Check if a model config exists in the registry."""
return name in self._configs
@@ -954,7 +1305,14 @@ class ModelRegistry:
msg = _ERR_MODEL_ALREADY_LOADED.format(name=name)
raise ValueError(msg)
- load_device = self._resolve_load_device(device)
+ width = declared_tensor_parallel_size(config)
+ self._reject_unservable_width(name, width)
+ if width > 1:
+ load_device, group_members = self._resolve_group_placement(name, width, device)
+ self._claim_device_group(name, group_members)
+ else:
+ load_device = self._resolve_load_device(device)
+ self._reject_claimed_device(name, load_device)
memory_manager = self._memory_manager_for_device(load_device)
load_start = time.monotonic()
load_outcome = "error"
@@ -1017,10 +1375,7 @@ class ModelRegistry:
# Track loaded state and register it for LRU accounting.
self._loaded[name] = loaded
- self._memory_manager_for_device(loaded.device).register_model(
- name,
- estimated_bytes=loaded.memory_bytes,
- )
+ self._register_across_group(name, loaded)
# Clear any stale failure record from a prior attempt.
self._failed.pop(name, None)
@@ -1031,6 +1386,11 @@ class ModelRegistry:
load_stage = exc.stage
raise
finally:
+ # A claim outlives only a load that succeeded. Anything else hands
+ # the devices back, or a failed multi-device attempt would strand
+ # every card it reserved for the life of the process.
+ if load_outcome != "success":
+ self._release_device_claims(name)
worker_telemetry().model_load_completed(
model=name,
duration_s=time.monotonic() - load_start,
@@ -1094,6 +1454,8 @@ class ModelRegistry:
# lock must stay free for every other model's load, unload and
# eviction meanwhile. The per-model lock keeps two loads of the
# same model from fetching twice.
+ width = declared_tensor_parallel_size(config)
+ self._reject_unservable_width(name, width)
await self._loader.ensure_weights_cached_async(name, config)
async with lock:
@@ -1118,7 +1480,14 @@ class ModelRegistry:
raise RuntimeError(msg)
model_dir = self._model_dirs.get(name, Path())
- load_device = self._resolve_load_device(device)
+ if width > 1:
+ # Refuse a profile the adapter would reject before evicting
+ # or claiming anything for it.
+ await asyncio.to_thread(validate_loadtime_options, config, model_dir)
+ load_device, group_members = await self._resolve_group_placement_evicting(name, width, device)
+ self._claim_device_group(name, group_members)
+ else:
+ load_device = await self._resolve_single_device_evicting(name, device)
memory_manager = self._memory_manager_for_device(load_device)
# Instantiate adapter (in thread pool, post-download timeout applies)
@@ -1189,10 +1558,7 @@ class ModelRegistry:
self._loaded[name] = loaded
# Register with memory manager for LRU tracking
- self._memory_manager_for_device(loaded.device).register_model(
- name,
- estimated_bytes=loaded.memory_bytes,
- )
+ self._register_across_group(name, loaded)
load_duration = time.monotonic() - load_start
if load_duration > 300:
@@ -1210,6 +1576,11 @@ class ModelRegistry:
load_stage = exc.stage
raise
finally:
+ # A claim outlives only a load that succeeded. Anything else
+ # hands the devices back, or a failed multi-device attempt
+ # would strand every card it reserved.
+ if load_outcome != "success":
+ self._release_device_claims(name)
worker_telemetry().model_load_completed(
model=name,
duration_s=time.monotonic() - load_start,
@@ -1382,7 +1753,7 @@ class ModelRegistry:
an owning lifecycle loop. A sync-only registry fails closed instead of
inventing a temporary event loop for that teardown.
"""
- if name not in self._configs:
+ if name not in self._configs and name not in self._loaded:
msg = _ERR_MODEL_NOT_FOUND.format(name=name)
raise KeyError(msg)
@@ -1400,14 +1771,19 @@ class ModelRegistry:
device = loaded.device
worker_telemetry().model_evicted(model=name, reason=reason)
- # Adapter.unload() handles gc.collect + empty_cache
- loaded.adapter.unload()
-
- # Unregister tokenizer, preprocessor, and clear metrics
- self._loader.unregister(name, device)
+ try:
+ # Adapter.unload() handles gc.collect + empty_cache
+ loaded.adapter.unload()
- # Unregister from memory manager
- self._memory_manager_for_device(device).unregister_model(name)
+ # Unregister tokenizer, preprocessor, and clear metrics
+ self._loader.unregister(name, device)
+ finally:
+ # The model has already left ``_loaded``, so no later unload can
+ # reach it: accounting and device claims must be handed back even
+ # when teardown raises, or the group stays held for the life of
+ # the process.
+ self._unregister_across_group(name, device)
+ self._release_device_claims(name)
logger.info("Model '%s' unloaded", name)
@@ -1595,13 +1971,18 @@ class ModelRegistry:
self._loader.unregister(name, device)
except Exception: # noqa: BLE001 - best-effort; must not skip below
logger.warning("loader.unregister failed during unload of '%s'", name, exc_info=True)
- # Unregister from memory manager (a plain dict-pop; never raises)
- self._memory_manager_for_device(device).unregister_model(name)
+ # Unregister from every manager that accounted for it (plain
+ # dict-pops; never raise). Ordered before the claim release,
+ # because the claim is what names the group's members.
+ self._unregister_across_group(name, device)
+ # Hand back any exclusively held devices. A no-op for the
+ # single-device models that are every profile today.
+ self._release_device_claims(name)
# Freeing memory makes any prior OOM-class load failure on a
# *sibling* model retryable; clear those records so the next
# request can re-attempt without waiting out the cooldown.
- cleared = self._clear_transient_failures()
+ cleared = self._clear_transient_failures((LoadErrorClass.OOM, LoadErrorClass.PLACEMENT))
if cleared:
logger.debug(
"Cleared %d transient failure record(s) after unloading '%s'",
@@ -1626,7 +2007,11 @@ class ModelRegistry:
Raises:
KeyError: If model not found or not loaded.
"""
- if name not in self._configs:
+ # A config update can drop an entry whose model is still resident, and
+ # that model still holds its memory and its whole device group. Gating
+ # on the config alone would make it unloadable for the life of the
+ # process.
+ if name not in self._configs and name not in self._loaded:
msg = _ERR_MODEL_NOT_FOUND.format(name=name)
raise KeyError(msg)
diff --git a/packages/sie_server/tests/adapters/test_sglang.py b/packages/sie_server/tests/adapters/test_sglang.py
index 9fac1cef9..cd8c91e2e 100644
--- a/packages/sie_server/tests/adapters/test_sglang.py
+++ b/packages/sie_server/tests/adapters/test_sglang.py
@@ -1,5 +1,6 @@
"""Tests for SGLang embedding adapter (HTTP server mode)."""
+import json
import socket
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
@@ -807,14 +808,14 @@ class TestPortReservation:
class TestKernelCacheEnvironment:
def test_disabled_without_root(self) -> None:
- assert _server._kernel_cache_env({}, device_index=0) == {}
+ assert _server._kernel_cache_env({}, device_indices=[0]) == {}
@patch("sie_server.adapters.sglang._server.subprocess.run")
def test_gpu_key_uses_driver_inventory_without_initializing_cuda(self, mock_run: MagicMock) -> None:
mock_run.return_value = MagicMock(stdout="NVIDIA H100 80GB HBM3\nNVIDIA H200\n")
- first_key = _server._gpu_cache_key(0)
- second_key = _server._gpu_cache_key(1)
+ first_key = _server._gpu_cache_key([0])
+ second_key = _server._gpu_cache_key([1])
assert first_key is not None
assert first_key.startswith("gpu-")
@@ -827,12 +828,29 @@ class TestKernelCacheEnvironment:
"--format=csv,noheader",
]
+ @patch("sie_server.adapters.sglang._server.subprocess.run")
+ def test_gpu_key_is_shared_by_a_uniform_group(self, mock_run: MagicMock) -> None:
+ mock_run.return_value = MagicMock(stdout="NVIDIA L4\nNVIDIA L4\nNVIDIA L4\nNVIDIA L4\n")
+
+ assert _server._gpu_cache_key([0, 1, 2, 3]) == _server._gpu_cache_key([0])
+
+ @patch("sie_server.adapters.sglang._server.subprocess.run")
+ def test_gpu_key_refuses_a_mixed_group(self, mock_run: MagicMock) -> None:
+ """A mixed group must not reuse either member's artifacts.
+
+ Kernels compiled for one product are not valid for the other, and a
+ cache hit would serve them silently.
+ """
+ mock_run.return_value = MagicMock(stdout="NVIDIA L4\nNVIDIA H100 80GB HBM3\n")
+
+ assert _server._gpu_cache_key([0, 1]) is None
+
def test_scopes_upstream_caches_by_abi_and_gpu(self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(_server, "_installed_jit_abi_key", lambda: "abi123")
- monkeypatch.setattr(_server, "_gpu_cache_key", lambda _device_index: "sm120-gpu123")
+ monkeypatch.setattr(_server, "_gpu_cache_key", lambda _device_indices: "sm120-gpu123")
env = {_server.KERNEL_CACHE_ROOT_ENV_VAR: str(tmp_path)}
- cache_env = _server._kernel_cache_env(env, device_index=0)
+ cache_env = _server._kernel_cache_env(env, device_indices=[0])
namespace = tmp_path / "v1" / "abi123" / "sm120-gpu123" / "device-0"
assert cache_env["SGLANG_DG_CACHE_DIR"] == str(namespace / "deep-gemm")
@@ -841,16 +859,35 @@ class TestKernelCacheEnvironment:
assert cache_env["TRITON_CACHE_DIR"] == str(namespace / "triton")
assert all(Path(path).is_dir() for path in cache_env.values())
+ def test_group_namespace_is_distinct_from_single_device(
+ self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ """Width-four artifacts must not be served to a width-one load.
+
+ The namespace carries the whole group, so the same card at a different
+ width reads a different directory.
+ """
+ monkeypatch.setattr(_server, "_installed_jit_abi_key", lambda: "abi123")
+ monkeypatch.setattr(_server, "_gpu_cache_key", lambda _device_indices: "sm120-gpu123")
+ env = {_server.KERNEL_CACHE_ROOT_ENV_VAR: str(tmp_path)}
+
+ single = _server._kernel_cache_env(dict(env), device_indices=[0])
+ group = _server._kernel_cache_env(dict(env), device_indices=[0, 1, 2, 3])
+
+ assert single["TRITON_CACHE_DIR"].endswith("/device-0/triton")
+ assert group["TRITON_CACHE_DIR"].endswith("/device-0_1_2_3/triton")
+ assert single["TRITON_CACHE_DIR"] != group["TRITON_CACHE_DIR"]
+
def test_explicit_upstream_path_wins(self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(_server, "_installed_jit_abi_key", lambda: "abi123")
- monkeypatch.setattr(_server, "_gpu_cache_key", lambda _device_index: "sm90-gpu123")
+ monkeypatch.setattr(_server, "_gpu_cache_key", lambda _device_indices: "sm90-gpu123")
explicit = tmp_path / "operator-deep-gemm"
env = {
_server.KERNEL_CACHE_ROOT_ENV_VAR: str(tmp_path / "managed"),
"SGLANG_DG_CACHE_DIR": str(explicit),
}
- cache_env = _server._kernel_cache_env(env, device_index=0)
+ cache_env = _server._kernel_cache_env(env, device_indices=[0])
assert "SGLANG_DG_CACHE_DIR" not in cache_env
assert not explicit.exists()
@@ -858,12 +895,12 @@ class TestKernelCacheEnvironment:
def test_invalid_or_unwritable_root_falls_back(self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(_server, "_installed_jit_abi_key", lambda: "abi123")
- monkeypatch.setattr(_server, "_gpu_cache_key", lambda _device_index: "sm90-gpu123")
+ monkeypatch.setattr(_server, "_gpu_cache_key", lambda _device_indices: "sm90-gpu123")
blocker = tmp_path / "not-a-directory"
blocker.write_text("x")
- assert _server._kernel_cache_env({_server.KERNEL_CACHE_ROOT_ENV_VAR: "relative"}, device_index=0) == {}
- assert _server._kernel_cache_env({_server.KERNEL_CACHE_ROOT_ENV_VAR: str(blocker)}, device_index=0) == {}
+ assert _server._kernel_cache_env({_server.KERNEL_CACHE_ROOT_ENV_VAR: "relative"}, device_indices=[0]) == {}
+ assert _server._kernel_cache_env({_server.KERNEL_CACHE_ROOT_ENV_VAR: str(blocker)}, device_indices=[0]) == {}
with patch(
"sie_server.adapters.sglang._server.tempfile.NamedTemporaryFile",
@@ -872,7 +909,7 @@ class TestKernelCacheEnvironment:
assert (
_server._kernel_cache_env(
{_server.KERNEL_CACHE_ROOT_ENV_VAR: str(tmp_path / "read-only")},
- device_index=0,
+ device_indices=[0],
)
== {}
)
@@ -889,3 +926,184 @@ def test_startup_failure_error_distinguishes_crash_from_timeout() -> None:
crash_error = _server.startup_failure_error(None, crash_exit_code=-9)
assert "process exited during startup (exit code -9)" in str(crash_error)
assert "failed to start within timeout" not in str(crash_error)
+
+
+class TestWidthAgainstModelShape:
+ """A width must divide the dimensions the engine shards across ranks.
+
+ The engine asserts this itself, but only after loading weights, which on a
+ multi-accelerator load holds every card in the group for minutes before the
+ launch fails, and a supervisor that restarts the worker repeats that.
+ """
+
+ @staticmethod
+ def _model_dir(tmp_path: Path, **config: object) -> str:
+ (tmp_path / "config.json").write_text(json.dumps(config), encoding="utf-8")
+ return str(tmp_path)
+
+ @pytest.mark.parametrize("width", [1, 2, 4])
+ def test_a_dividing_width_is_accepted(self, tmp_path: Path, width: int) -> None:
+ path = self._model_dir(tmp_path, num_attention_heads=28, num_key_value_heads=4)
+
+ _server.validate_width_against_model_config(width, model_name_or_path=path)
+
+ def test_a_width_that_splits_attention_heads_unevenly_is_refused(self, tmp_path: Path) -> None:
+ path = self._model_dir(tmp_path, num_attention_heads=28, num_key_value_heads=28)
+
+ with pytest.raises(ValueError, match="num_attention_heads=28"):
+ _server.validate_width_against_model_config(8, model_name_or_path=path)
+
+ def test_a_width_that_splits_key_value_heads_unevenly_is_refused(self, tmp_path: Path) -> None:
+ """Neither a multiple nor a divisor: the heads can be neither split nor replicated."""
+ path = self._model_dir(tmp_path, num_attention_heads=24, num_key_value_heads=6)
+
+ with pytest.raises(ValueError, match="num_key_value_heads=6"):
+ _server.validate_width_against_model_config(4, model_name_or_path=path)
+
+ def test_fewer_key_value_heads_than_the_width_are_replicated(self, tmp_path: Path) -> None:
+ """A width above the group count is legal: the engine replicates the heads.
+
+ Refusing it would reject a shape that serves, which this check exists
+ never to do.
+ """
+ path = self._model_dir(tmp_path, num_attention_heads=32, num_key_value_heads=4)
+
+ _server.validate_width_against_model_config(8, model_name_or_path=path)
+
+ def test_a_multimodal_config_is_checked_against_its_text_stack(self, tmp_path: Path) -> None:
+ """Top-level head counts can describe the vision tower, which is not sharded."""
+ path = self._model_dir(
+ tmp_path,
+ num_attention_heads=12,
+ text_config={"num_attention_heads": 32, "num_key_value_heads": 8},
+ )
+
+ _server.validate_width_against_model_config(8, model_name_or_path=path)
+
+ def test_width_one_is_never_checked(self, tmp_path: Path) -> None:
+ """Single-device serving shards nothing, so no division has to hold."""
+ path = self._model_dir(tmp_path, num_attention_heads=7, num_key_value_heads=7)
+
+ _server.validate_width_against_model_config(1, model_name_or_path=path)
+
+ def test_an_unreadable_config_checks_nothing(self, tmp_path: Path) -> None:
+ """Best effort: this may only turn a later crash into an earlier error.
+
+ It must never reject a shape that would have worked, so a model whose
+ config cannot be read without a download is left to the engine.
+ """
+ _server.validate_width_against_model_config(4, model_name_or_path=str(tmp_path / "absent"))
+ _server.validate_width_against_model_config(4, model_name_or_path="org/not-in-any-cache")
+
+ def test_a_malformed_config_checks_nothing(self, tmp_path: Path) -> None:
+ (tmp_path / "config.json").write_text("{not json", encoding="utf-8")
+
+ _server.validate_width_against_model_config(4, model_name_or_path=str(tmp_path))
+
+ def test_missing_or_nonsense_head_counts_are_skipped(self, tmp_path: Path) -> None:
+ path = self._model_dir(tmp_path, num_attention_heads=0, num_key_value_heads="many")
+
+ _server.validate_width_against_model_config(4, model_name_or_path=path)
+
+
+class TestEmbeddingEngineLiveness:
+ """The embedding adapter must notice its engine dying, like generation does."""
+
+ @staticmethod
+ def _adapter() -> object:
+ from sie_server.adapters.sglang.embedding import SGLangEmbeddingAdapter
+
+ return SGLangEmbeddingAdapter(model_name_or_path="org/embed", dense_dim=768)
+
+ def test_an_unloaded_adapter_reports_not_loaded(self) -> None:
+ adapter = self._adapter()
+
+ with pytest.raises(RuntimeError, match="not loaded"):
+ adapter._check_loaded()
+
+ def test_a_live_engine_passes(self) -> None:
+ adapter = self._adapter()
+ adapter._server_url = "http://localhost:30005"
+ adapter._process = MagicMock(poll=MagicMock(return_value=None))
+
+ adapter._check_loaded()
+
+ def test_a_dead_engine_is_a_terminal_error_not_a_timeout(self) -> None:
+ adapter = self._adapter()
+ adapter._server_url = "http://localhost:30005"
+ adapter._process = MagicMock(poll=MagicMock(return_value=-9))
+
+ with pytest.raises(RuntimeError, match="exited with code -9"):
+ adapter._check_loaded()
+
+ def test_the_removed_pooling_option_is_no_longer_accepted(self) -> None:
+ """Neither pinned engine declares a pooling flag, so the option was dead.
+
+ It is better refused by the loader's unknown-option check than emitted
+ and rejected by the engine at startup.
+ """
+ from sie_server.adapters.sglang.embedding import SGLangEmbeddingAdapter
+ from sie_server.core.loader import reject_unknown_loadtime_options
+
+ with pytest.raises(ValueError, match="pooling_method"):
+ reject_unknown_loadtime_options(SGLangEmbeddingAdapter, {"pooling_method": "mean"}, model_name="demo")
+
+
+class TestEmbeddingGroupLaunch:
+ """An embedding profile that declares a width, through the real ``load``."""
+
+ @staticmethod
+ def _reserving(port: int) -> object:
+ def reserve(start_port: int = _server.BASE_PORT) -> int:
+ _server._RESERVED_PORTS.add(port)
+ return port
+
+ return reserve
+
+ @patch("sie_server.adapters.sglang._server.os.getpgid", return_value=12345)
+ @patch("sie_server.adapters.sglang._server.os.killpg")
+ @patch("sie_server.adapters.sglang._server.subprocess.Popen")
+ @patch("sie_server.adapters.sglang._server.requests.get")
+ def test_a_width_launches_the_whole_group_and_hands_every_port_back(
+ self,
+ mock_requests_get: MagicMock,
+ mock_popen: MagicMock,
+ mock_killpg: MagicMock,
+ mock_getpgid: MagicMock,
+ ) -> None:
+ mock_popen.return_value = MagicMock(
+ pid=12345, poll=MagicMock(return_value=None), wait=MagicMock(return_value=None)
+ )
+ mock_requests_get.return_value = MagicMock(status_code=200)
+ ports = iter([30011, 30411])
+ adapter = SGLangEmbeddingAdapter(
+ model_name_or_path="Qwen/Qwen3-Embedding-8B",
+ tensor_parallel_size=2,
+ watchdog_timeout_s=90.0,
+ )
+
+ try:
+ with patch(
+ "sie_server.adapters.sglang._server.find_free_port",
+ side_effect=lambda start_port=_server.BASE_PORT: self._reserving(next(ports))(start_port),
+ ):
+ adapter.load("cuda:2")
+
+ cmd = mock_popen.call_args[0][0]
+ env = mock_popen.call_args.kwargs["env"]
+ assert cmd[cmd.index("--tensor-parallel-size") + 1] == "2"
+ assert cmd[cmd.index("--nccl-port") + 1] == "30411"
+ assert cmd[cmd.index("--watchdog-timeout") + 1] == "90.0"
+ assert "--disable-piecewise-cuda-graph" in cmd
+ assert env["CUDA_VISIBLE_DEVICES"] == "2,3"
+
+ adapter.unload()
+
+ assert {30011, 30411}.isdisjoint(_server._RESERVED_PORTS)
+ finally:
+ _server.release_port(30011)
+ _server.release_port(30411)
+
+ def test_a_declared_collective_port_at_width_one_is_refused(self) -> None:
+ with pytest.raises(ValueError, match="nccl_port applies only above"):
+ SGLangEmbeddingAdapter(model_name_or_path="Qwen/Qwen3-Embedding-8B", nccl_port=30499)
diff --git a/packages/sie_server/tests/adapters/test_sglang_generation.py b/packages/sie_server/tests/adapters/test_sglang_generation.py
index 8e4475400..6bef62a7c 100644
--- a/packages/sie_server/tests/adapters/test_sglang_generation.py
+++ b/packages/sie_server/tests/adapters/test_sglang_generation.py
@@ -15,6 +15,7 @@ import asyncio
import base64
import json
import os
+import re
import subprocess
import sys
from pathlib import Path
@@ -30,7 +31,9 @@ from sie_server.adapters._generation_base import (
collect_generation,
suppress_thinking_blocks,
)
+from sie_server.adapters._types import ERR_NOT_LOADED
from sie_server.adapters.sglang import _server
+from sie_server.adapters.sglang import generation as generation_module
from sie_server.adapters.sglang.cuda13 import SGLangStrictThinkingAdapter
from sie_server.adapters.sglang.generation import (
SGLangGenerationAdapter,
@@ -2873,3 +2876,424 @@ async def test_duplicate_event_keys_raise_typed_error_before_output(adapter, n,
raise AssertionError("duplicate keys must not yield text or usage")
assert error.value.code == "inference_error"
assert "secret" not in str(error.value)
+
+
+def _tp_adapter(**overrides: Any) -> SGLangGenerationAdapter:
+ kwargs: dict[str, Any] = {
+ "model_name_or_path": "Qwen/Qwen3-4B-Instruct",
+ "max_seq_length": 32768,
+ "mem_fraction_static": 0.85,
+ "served_model_name": "Qwen/Qwen3-4B-Instruct",
+ }
+ # A width above one requires a finite streaming read cap, so supply one by
+ # default here and let the tests that are about that rule set it explicitly.
+ declared = overrides.get("tensor_parallel_size", 1)
+ if isinstance(declared, int) and not isinstance(declared, bool) and declared > 1:
+ kwargs["request_read_timeout_s"] = 120.0
+ kwargs.update(overrides)
+ return SGLangGenerationAdapter(**kwargs)
+
+
+def _launch(adapter: SGLangGenerationAdapter, mock_popen: MagicMock, device: str = "cuda:0") -> tuple[list[str], dict]:
+ adapter.load(device)
+ return mock_popen.call_args[0][0], mock_popen.call_args.kwargs["env"]
+
+
+@patch("sie_server.adapters.sglang._server.subprocess.Popen")
+@patch("sie_server.adapters.sglang._server.requests.get")
+@patch("sie_server.adapters.sglang._server.find_free_port")
+def test_default_width_is_one_and_leaves_the_launch_unchanged(
+ mock_find_port: MagicMock,
+ mock_requests_get: MagicMock,
+ mock_popen: MagicMock,
+) -> None:
+ """Every profile that does not ask for a width must launch exactly as before."""
+ mock_find_port.return_value = 30005
+ mock_popen.return_value = MagicMock(poll=MagicMock(return_value=None))
+ mock_requests_get.return_value = MagicMock(status_code=200)
+
+ cmd, env = _launch(_tp_adapter(), mock_popen)
+
+ assert cmd[cmd.index("--tensor-parallel-size") + 1] == "1"
+ assert "--disable-piecewise-cuda-graph" not in cmd
+ assert env["CUDA_VISIBLE_DEVICES"] == "0"
+
+
+@patch("sie_server.adapters.sglang._server.subprocess.Popen")
+@patch("sie_server.adapters.sglang._server.requests.get")
+@patch("sie_server.adapters.sglang._server.find_free_port")
+def test_declared_width_masks_the_whole_group_and_disables_piecewise_capture(
+ mock_find_port: MagicMock,
+ mock_requests_get: MagicMock,
+ mock_popen: MagicMock,
+) -> None:
+ """Width four claims four ordered devices and turns off the capture path.
+
+ SGLang's default piecewise capture is measured to hang at width two and to
+ exhaust memory at width four on a memory fraction that serves at width one.
+ """
+ mock_find_port.return_value = 30005
+ mock_popen.return_value = MagicMock(poll=MagicMock(return_value=None))
+ mock_requests_get.return_value = MagicMock(status_code=200)
+
+ cmd, env = _launch(_tp_adapter(tensor_parallel_size=4), mock_popen)
+
+ assert cmd[cmd.index("--tensor-parallel-size") + 1] == "4"
+ assert "--disable-piecewise-cuda-graph" in cmd
+ assert env["CUDA_VISIBLE_DEVICES"] == "0,1,2,3"
+
+
+@patch("sie_server.adapters.sglang._server.subprocess.Popen")
+@patch("sie_server.adapters.sglang._server.requests.get")
+@patch("sie_server.adapters.sglang._server.find_free_port")
+def test_group_is_anchored_on_the_placement_device(
+ mock_find_port: MagicMock,
+ mock_requests_get: MagicMock,
+ mock_popen: MagicMock,
+) -> None:
+ mock_find_port.return_value = 30005
+ mock_popen.return_value = MagicMock(poll=MagicMock(return_value=None))
+ mock_requests_get.return_value = MagicMock(status_code=200)
+
+ _cmd, env = _launch(_tp_adapter(tensor_parallel_size=2), mock_popen, device="cuda:2")
+
+ assert env["CUDA_VISIBLE_DEVICES"] == "2,3"
+
+
+@patch("sie_server.adapters.sglang._server.subprocess.Popen")
+@patch("sie_server.adapters.sglang._server.requests.get")
+@patch("sie_server.adapters.sglang._server.find_free_port")
+def test_profile_environment_cannot_move_or_widen_the_device_claim(
+ mock_find_port: MagicMock,
+ mock_requests_get: MagicMock,
+ mock_popen: MagicMock,
+) -> None:
+ """The mask is the registry's decision, not the profile's.
+
+ Before the width was typed, a profile could set CUDA_VISIBLE_DEVICES in
+ ``extra_env`` and silently serve on devices the registry had not reserved
+ and was not accounting for. The mask is now written last.
+ """
+ mock_find_port.return_value = 30005
+ mock_popen.return_value = MagicMock(poll=MagicMock(return_value=None))
+ mock_requests_get.return_value = MagicMock(status_code=200)
+
+ adapter = _tp_adapter(
+ tensor_parallel_size=2,
+ extra_env={"CUDA_VISIBLE_DEVICES": "4,5,6,7", "SIE_UNRELATED": "kept"},
+ )
+ _cmd, env = _launch(adapter, mock_popen)
+
+ assert env["CUDA_VISIBLE_DEVICES"] == "0,1"
+ assert env["SIE_UNRELATED"] == "kept"
+
+
+@patch("sie_server.adapters.sglang._server.subprocess.Popen")
+@patch("sie_server.adapters.sglang._server.requests.get")
+@patch("sie_server.adapters.sglang._server.find_free_port")
+def test_capture_path_can_be_re_enabled_explicitly(
+ mock_find_port: MagicMock,
+ mock_requests_get: MagicMock,
+ mock_popen: MagicMock,
+) -> None:
+ """A profile that has measured its own engine build may opt back in."""
+ mock_find_port.return_value = 30005
+ mock_popen.return_value = MagicMock(poll=MagicMock(return_value=None))
+ mock_requests_get.return_value = MagicMock(status_code=200)
+
+ cmd, _env = _launch(
+ _tp_adapter(tensor_parallel_size=4, disable_piecewise_cuda_graph=False),
+ mock_popen,
+ )
+
+ assert "--disable-piecewise-cuda-graph" not in cmd
+
+
[email protected]("bad", [0, -1, 9, 2.0, "4", True, None])
+def test_invalid_width_is_refused_at_construction(bad: Any) -> None:
+ """A bad width fails where it is declared, not as an engine crash later."""
+ with pytest.raises(ValueError, match="tensor_parallel_size"):
+ _tp_adapter(tensor_parallel_size=bad)
+
+
+def test_width_one_is_the_only_width_that_needs_no_extra_devices() -> None:
+ assert _server.resolve_device_group(0, 1) == [0]
+ assert _server.resolve_device_group(3, 1) == [3]
+
+
+def test_launcher_refuses_a_repeated_device() -> None:
+ """Two ranks on one card deadlock rather than fail, so refuse it early."""
+ with pytest.raises(ValueError, match="distinct"):
+ _server.launch_sglang_server(["true"], device_indices=[0, 0], output_file=MagicMock())
+
+
+def test_launcher_refuses_an_empty_group() -> None:
+ with pytest.raises(ValueError, match="at least one device"):
+ _server.launch_sglang_server(["true"], device_indices=[], output_file=MagicMock())
+
+
+def test_width_above_one_requires_a_finite_streaming_read_cap() -> None:
+ """A stalled collective emits no bytes and raises nothing.
+
+ An unbounded read would hold the request open forever, and with it every
+ accelerator in the group.
+ """
+ with pytest.raises(ValueError, match="request_read_timeout_s"):
+ SGLangGenerationAdapter(
+ model_name_or_path="Qwen/Qwen3-4B-Instruct",
+ served_model_name="Qwen/Qwen3-4B-Instruct",
+ tensor_parallel_size=4,
+ )
+
+
+def test_width_one_keeps_the_unbounded_default() -> None:
+ """Single-device serving is unchanged: the worker owns request lifetime."""
+ adapter = _tp_adapter()
+
+ assert adapter._request_read_timeout_s is None
+
+
[email protected]("bad", [0, -1, float("inf"), float("nan"), True, "30"])
+def test_invalid_read_cap_is_refused(bad: Any) -> None:
+ with pytest.raises(ValueError, match="request_read_timeout_s"):
+ _tp_adapter(request_read_timeout_s=bad)
+
+
[email protected]("raw", ["inf", "+inf", "Infinity", "nan"])
+def test_a_non_finite_inherited_read_cap_leaves_a_wide_profile_without_one(
+ monkeypatch: pytest.MonkeyPatch, raw: str
+) -> None:
+ """An infinite cap from the environment is no cap, so width two must still refuse it."""
+ monkeypatch.setenv("SIE_SGLANG_GENERATE_READ_TIMEOUT_S", raw)
+ monkeypatch.setattr(generation_module, "_GENERATE_READ_TIMEOUT_S", generation_module._resolve_read_timeout())
+
+ assert generation_module._GENERATE_READ_TIMEOUT_S is None
+ with pytest.raises(ValueError, match="must also declare a finite"):
+ _tp_adapter(tensor_parallel_size=2, request_read_timeout_s=None)
+
+
+def test_declared_read_cap_reaches_the_http_client() -> None:
+ adapter = _tp_adapter(tensor_parallel_size=2, request_read_timeout_s=45.5)
+
+ assert adapter._request_read_timeout_s == 45.5
+
+
+@patch("sie_server.adapters.sglang._server.subprocess.Popen")
+@patch("sie_server.adapters.sglang._server.requests.get")
+@patch("sie_server.adapters.sglang._server.find_free_port")
+def test_a_dead_engine_fails_immediately_instead_of_timing_out_per_request(
+ mock_find_port: MagicMock,
+ mock_requests_get: MagicMock,
+ mock_popen: MagicMock,
+) -> None:
+ """A crashed engine is a terminal answer, not a connection error forever.
+
+ Measured on a four-rank group: a killed rank refused health in about 5 seconds while its
+ process tree took about 67 seconds to exit. Before this check the adapter
+ never noticed either, and kept accepting requests it could not serve.
+ """
+ mock_find_port.return_value = 30005
+ process = MagicMock()
+ process.poll.return_value = None
+ mock_popen.return_value = process
+ mock_requests_get.return_value = MagicMock(status_code=200)
+
+ adapter = _tp_adapter(tensor_parallel_size=2)
+ adapter.load("cuda:0")
+ adapter._check_loaded() # alive: no raise
+
+ process.poll.return_value = -9
+
+ with pytest.raises(RuntimeError, match="exited with code -9"):
+ adapter._check_loaded()
+
+
+def test_an_unloaded_adapter_still_reports_not_loaded_first() -> None:
+ """The dead-engine check must not mask the ordinary not-loaded error."""
+ adapter = _tp_adapter()
+
+ with pytest.raises(RuntimeError, match=re.escape(ERR_NOT_LOADED)):
+ adapter._check_loaded()
+
+
+@patch("sie_server.adapters.sglang._server.subprocess.Popen")
+@patch("sie_server.adapters.sglang._server.requests.get")
+@patch("sie_server.adapters.sglang._server.find_free_port")
+def test_width_one_reserves_no_collective_port(
+ mock_find_port: MagicMock,
+ mock_requests_get: MagicMock,
+ mock_popen: MagicMock,
+) -> None:
+ """Single-device serving does not rendezvous, so nothing extra is taken."""
+ mock_find_port.return_value = 30005
+ mock_popen.return_value = MagicMock(poll=MagicMock(return_value=None))
+ mock_requests_get.return_value = MagicMock(status_code=200)
+
+ adapter = _tp_adapter()
+ cmd, _env = _launch(adapter, mock_popen)
+
+ assert adapter._nccl_port is None
+ assert "--nccl-port" not in cmd
+ assert "--watchdog-timeout" not in cmd
+
+
+@patch("sie_server.adapters.sglang._server.subprocess.Popen")
+@patch("sie_server.adapters.sglang._server.requests.get")
+@patch("sie_server.adapters.sglang._server.find_free_port")
+def test_a_group_reserves_its_own_collective_port(
+ mock_find_port: MagicMock,
+ mock_requests_get: MagicMock,
+ mock_popen: MagicMock,
+) -> None:
+ """The engine otherwise picks a random port and two groups can collide.
+
+ A collision does not fail, it hangs in rendezvous, which is the failure
+ shape hardest to attribute.
+ """
+ mock_find_port.side_effect = [30005, 30207]
+ mock_popen.return_value = MagicMock(poll=MagicMock(return_value=None))
+ mock_requests_get.return_value = MagicMock(status_code=200)
+
+ adapter = _tp_adapter(tensor_parallel_size=2)
+ cmd, _env = _launch(adapter, mock_popen)
+
+ assert adapter._nccl_port == 30207
+ assert cmd[cmd.index("--nccl-port") + 1] == "30207"
+ # Reserved from a span kept clear of the HTTP ports.
+ assert mock_find_port.call_args_list[-1].args[0] == _server.NCCL_BASE_PORT
+
+
+@patch("sie_server.adapters.sglang._server.os.getpgid")
+@patch("sie_server.adapters.sglang._server.os.killpg")
+def test_unload_returns_the_collective_port(
+ mock_killpg: MagicMock,
+ mock_getpgid: MagicMock,
+) -> None:
+ """Both spans exhaust under reload churn if either is leaked."""
+ mock_process = MagicMock()
+ mock_process.pid = 12345
+ mock_process.wait.return_value = None
+ mock_getpgid.return_value = 12345
+
+ adapter = _tp_adapter(tensor_parallel_size=2)
+ adapter._process = mock_process
+ adapter._server_url = "http://localhost:30005"
+ adapter._device = "cuda:0"
+ adapter._port = 30005
+ # What ``load`` sets when it takes the rendezvous port from the span.
+ adapter._nccl_port = 30207
+ adapter._reserved_nccl_port = 30207
+ adapter._output_file = _server.open_output_log(prefix="sie_test_sglang_")
+
+ with patch("sie_server.adapters.sglang._server.release_port") as mock_release:
+ adapter.unload()
+
+ released = [call.args[0] for call in mock_release.call_args_list]
+ assert released == [30005, 30207]
+ assert adapter._nccl_port is None
+ assert adapter._reserved_nccl_port is None
+
+
+_DECLARED_NCCL_PORT = 30499
+
+
+def _reserving_http_port(port: int = 30005) -> Any:
+ """A ``find_free_port`` that reserves what it hands out, as the real one does."""
+
+ def reserve(start_port: int = _server.BASE_PORT) -> int:
+ _server._RESERVED_PORTS.add(port)
+ return port
+
+ return reserve
+
+
+@patch("sie_server.adapters.sglang._server.os.getpgid", return_value=12345)
+@patch("sie_server.adapters.sglang._server.os.killpg")
+@patch("sie_server.adapters.sglang._server.subprocess.Popen")
+@patch("sie_server.adapters.sglang._server.requests.get")
+def test_a_declared_collective_port_is_reserved_while_loaded_and_returned_on_unload(
+ mock_requests_get: MagicMock,
+ mock_popen: MagicMock,
+ mock_killpg: MagicMock,
+ mock_getpgid: MagicMock,
+) -> None:
+ mock_popen.return_value = MagicMock(pid=12345, poll=MagicMock(return_value=None), wait=MagicMock(return_value=None))
+ mock_requests_get.return_value = MagicMock(status_code=200)
+ adapter = _tp_adapter(tensor_parallel_size=2, nccl_port=_DECLARED_NCCL_PORT)
+
+ try:
+ with patch("sie_server.adapters.sglang._server.find_free_port", side_effect=_reserving_http_port()):
+ cmd, _env = _launch(adapter, mock_popen)
+
+ assert cmd[cmd.index("--nccl-port") + 1] == str(_DECLARED_NCCL_PORT)
+ assert _DECLARED_NCCL_PORT in _server._RESERVED_PORTS
+
+ adapter.unload()
+
+ assert _DECLARED_NCCL_PORT not in _server._RESERVED_PORTS
+ assert 30005 not in _server._RESERVED_PORTS
+ finally:
+ _server.release_port(_DECLARED_NCCL_PORT)
+ _server.release_port(30005)
+
+
+@patch("sie_server.adapters.sglang._server.subprocess.Popen")
+@patch("sie_server.adapters.sglang._server.requests.get")
+def test_a_declared_port_another_model_holds_is_refused_without_leaking(
+ mock_requests_get: MagicMock,
+ mock_popen: MagicMock,
+) -> None:
+ """Two groups sharing a rendezvous port hang rather than fail."""
+ mock_requests_get.return_value = MagicMock(status_code=200)
+ adapter = _tp_adapter(tensor_parallel_size=2, nccl_port=_DECLARED_NCCL_PORT)
+ _server._RESERVED_PORTS.add(_DECLARED_NCCL_PORT)
+
+ try:
+ with (
+ patch("sie_server.adapters.sglang._server.find_free_port", side_effect=_reserving_http_port()),
+ pytest.raises(RuntimeError, match="already reserved by another model"),
+ ):
+ adapter.load("cuda:0")
+
+ mock_popen.assert_not_called()
+ assert 30005 not in _server._RESERVED_PORTS
+ assert _DECLARED_NCCL_PORT in _server._RESERVED_PORTS, "the other model's reservation must survive"
+ finally:
+ _server.release_port(_DECLARED_NCCL_PORT)
+ _server.release_port(30005)
+
+
+def test_a_declared_collective_port_at_width_one_is_refused() -> None:
+ """A single rank never rendezvouses, so the port would be silently ignored."""
+ with pytest.raises(ValueError, match="nccl_port applies only above"):
+ _tp_adapter(nccl_port=_DECLARED_NCCL_PORT)
+
+
+@patch("sie_server.adapters.sglang._server.subprocess.Popen")
+@patch("sie_server.adapters.sglang._server.requests.get")
+@patch("sie_server.adapters.sglang._server.find_free_port")
+def test_a_declared_watchdog_bound_reaches_the_engine(
+ mock_find_port: MagicMock,
+ mock_requests_get: MagicMock,
+ mock_popen: MagicMock,
+) -> None:
+ """A wedged forward batch must crash the engine inside a budget SIE owns."""
+ mock_find_port.side_effect = [30005, 30207]
+ mock_popen.return_value = MagicMock(poll=MagicMock(return_value=None))
+ mock_requests_get.return_value = MagicMock(status_code=200)
+
+ cmd, _env = _launch(_tp_adapter(tensor_parallel_size=2, watchdog_timeout_s=90.0), mock_popen)
+
+ assert cmd[cmd.index("--watchdog-timeout") + 1] == "90.0"
+
+
[email protected]("bad", [0, -1, float("inf"), True, "90"])
+def test_an_invalid_watchdog_bound_is_refused(bad: Any) -> None:
+ with pytest.raises(ValueError, match="watchdog_timeout_s"):
+ _tp_adapter(watchdog_timeout_s=bad)
+
+
[email protected]("bad", [0, 80, 70000, True, "30207"])
+def test_an_invalid_collective_port_is_refused(bad: Any) -> None:
+ with pytest.raises(ValueError, match="nccl_port must be"):
+ _tp_adapter(tensor_parallel_size=2, nccl_port=bad)
diff --git a/packages/sie_server/tests/adapters/test_sglang_launch_flags.py b/packages/sie_server/tests/adapters/test_sglang_launch_flags.py
new file mode 100644
index 000000000..5607ca607
--- /dev/null
+++ b/packages/sie_server/tests/adapters/test_sglang_launch_flags.py
@@ -0,0 +1,138 @@
+"""Every engine flag the SGLang adapters emit must be one the engine declares.
+
+Two failures motivated this. ``--tp`` was emitted for years and is not a
+declared option at all: it worked only through argparse prefix matching, so any
+future upstream flag sharing that prefix would have turned every SIE launch
+into an ambiguous-option error. And a sweep of the pinned engine found a flag
+emitted that the engine does not declare in any form.
+
+The list below is the contract. It is deliberately explicit rather than derived
+at run time, because the engine is only importable inside a GPU bundle and this
+check has to run in an ordinary unit suite. Adding a flag means adding it here,
+which is the moment to confirm the engine declares it in **every** pinned
+version that loads the adapter emitting it.
+
+Verified against both pinned engines by reading ``sglang/srt/server_args.py``:
+``0.5.10.post1`` (the ``sglang`` and ``sglang-embedding`` bundles) from the
+published sdist, 364 declared flags, and ``0.5.13`` (the ``sglang-cu130``
+bundle) from the installed package inside a GPU container, 417 declared flags.
+Neither declares ``--tp``. No flag recorded below is a strict prefix of another
+declared flag in either version.
+"""
+
+from __future__ import annotations
+
+import re
+from pathlib import Path
+
+import pytest
+
+_ADAPTER_DIR = Path(__file__).resolve().parents[2] / "src/sie_server/adapters/sglang"
+
+# Flags confirmed present in sglang 0.5.10.post1's declared argument set.
+_DECLARED_IN_PINNED_ENGINE = frozenset(
+ {
+ "--attention-backend",
+ "--context-length",
+ "--disable-cuda-graph",
+ "--disable-piecewise-cuda-graph",
+ "--dtype",
+ "--enable-lora",
+ "--grammar-backend",
+ "--is-embedding",
+ "--log-level",
+ "--lora-paths",
+ "--mamba-scheduler-strategy",
+ "--max-loras-per-batch",
+ "--mem-fraction-static",
+ "--model-path",
+ "--nccl-port",
+ "--port",
+ "--reasoning-parser",
+ "--revision",
+ "--served-model-name",
+ "--speculative-algorithm",
+ "--speculative-draft-model-path",
+ "--speculative-draft-model-revision",
+ "--speculative-eagle-topk",
+ "--speculative-num-draft-tokens",
+ "--speculative-num-steps",
+ "--tensor-parallel-size",
+ "--tool-call-parser",
+ "--trust-remote-code",
+ "--watchdog-timeout",
+ }
+)
+
+# Emitted only by adapters whose bundle pins the newer engine. Absent from
+# 0.5.10.post1 and present in 0.5.13, which is the bundle that loads them.
+_NEWER_ENGINE_ONLY = frozenset(
+ {
+ "--enable-strict-thinking", # cuda13.py, sglang-cu130 bundle
+ }
+)
+
+# Nothing currently. A flag belongs here only while it is emitted and known not
+# to be declared, which should be never: the previous occupant,
+# ``--pooling-method``, was removed once the sweep showed neither pinned engine
+# declares it in any form.
+_KNOWN_UNDECLARED: frozenset[str] = frozenset()
+
+_FLAG_LITERAL = re.compile(r'"(--[a-z0-9][a-z0-9-]*)"')
+
+
+def _emitted_flags() -> dict[str, set[Path]]:
+ """Return every ``--flag`` literal in the adapter sources, by source path."""
+ found: dict[str, set[Path]] = {}
+ for source in sorted(_ADAPTER_DIR.rglob("*.py")):
+ for match in _FLAG_LITERAL.finditer(source.read_text(encoding="utf-8")):
+ found.setdefault(match.group(1), set()).add(source)
+ return found
+
+
+def test_no_emitted_flag_is_outside_the_verified_contract() -> None:
+ """A new flag must be added to this module, which is where it gets checked."""
+ known = _DECLARED_IN_PINNED_ENGINE | _NEWER_ENGINE_ONLY | _KNOWN_UNDECLARED
+ emitted = _emitted_flags()
+ # "--tp" survives as comment text explaining why it is not emitted.
+ unexpected = {
+ flag: sorted(str(path.relative_to(_ADAPTER_DIR)) for path in paths)
+ for flag, paths in emitted.items()
+ if flag not in known and flag != "--tp"
+ }
+
+ assert not unexpected, (
+ f"adapter sources carry engine flag literal(s) not recorded in this module: {unexpected}. "
+ "Confirm the engine declares each one in every pinned version that loads the emitting "
+ "adapter, then add it to the matching set here."
+ )
+
+
+def test_the_width_flag_is_spelled_in_full() -> None:
+ """``--tp`` is not a declared option, only an argparse prefix match."""
+ emitted = _emitted_flags()
+
+ assert "--tensor-parallel-size" in emitted
+ for flag in ("--tp", "--tp-size"):
+ for path in sorted(emitted.get(flag, set())):
+ for line in path.read_text(encoding="utf-8").splitlines():
+ if f'"{flag}"' in line:
+ assert line.lstrip().startswith("#"), (
+ f"{path.relative_to(_ADAPTER_DIR)} emits the abbreviated {flag!r}. Emit "
+ "--tensor-parallel-size: the short form is not a declared option and survives only by "
+ "prefix matching."
+ )
+
+
[email protected]("abbreviation", ["--tp", "--dp", "--pp", "--ep"])
+def test_no_parallelism_abbreviation_is_emitted(abbreviation: str) -> None:
+ """The whole class, not just the one instance that was found."""
+ for path in sorted(_emitted_flags().get(abbreviation, set())):
+ emitting = [
+ line
+ for line in path.read_text(encoding="utf-8").splitlines()
+ if f'"{abbreviation}"' in line and not line.lstrip().startswith("#")
+ ]
+ assert not emitting, (
+ f"{path.relative_to(_ADAPTER_DIR)} emits the abbreviated parallelism flag {abbreviation!r}: {emitting}"
+ )
diff --git a/packages/sie_server/tests/config/test_catalog_loadtime_options.py b/packages/sie_server/tests/config/test_catalog_loadtime_options.py
new file mode 100644
index 000000000..1eb24949b
--- /dev/null
+++ b/packages/sie_server/tests/config/test_catalog_loadtime_options.py
@@ -0,0 +1,95 @@
+"""Every shipped profile's load-time options must reach its adapter.
+
+An adapter absorbs unrecognised keyword arguments, so a load-time option its
+constructor does not name is dropped rather than applied. ``load_adapter``
+refuses that silence, which turns the refusal into a release gate: a key the
+loader consumes on the profile's behalf, or one an adapter takes through
+``**kwargs`` by design, has to be declared as such or the model stops loading
+entirely.
+
+The catalog is read the way a worker reads it, so every non-default profile is
+checked as the variant model the loader serves it as.
+"""
+
+from pathlib import Path
+
+import pytest
+from sie_server.config.model import ModelConfig
+from sie_server.core.loader import (
+ load_model_configs,
+ reject_unknown_loadtime_options,
+ resolve_adapter_class,
+)
+
+_MODELS_DIR = Path(__file__).resolve().parents[2] / "models"
+
+# A catalog this much smaller than today's means collection silently stopped
+# finding profiles, which would make every assertion below vacuous.
+_MIN_PROFILES_CHECKED = 200
+
+
+def _servable_catalog() -> list[tuple[str, ModelConfig]]:
+ """Every config the Python loader can serve, variants included, by id.
+
+ A config with no ``default`` profile is served by the Rust gateway rather
+ than through ``load_adapter``, so it is outside this gate.
+ """
+ servable: list[tuple[str, ModelConfig]] = []
+ for sie_id, config in sorted(load_model_configs(_MODELS_DIR).items()):
+ try:
+ config.resolve_profile("default")
+ except ValueError:
+ continue
+ servable.append((sie_id, config))
+ return servable
+
+
+_CATALOG = _servable_catalog()
+
+
[email protected](("sie_id", "config"), _CATALOG, ids=[sie_id for sie_id, _ in _CATALOG])
+def test_shipped_profile_loadtime_options_are_accepted(sie_id: str, config: ModelConfig) -> None:
+ try:
+ adapter_class = resolve_adapter_class(config, _MODELS_DIR)
+ except ImportError as exc: # optional serving dependency absent in this environment
+ pytest.skip(f"adapter for {sie_id} not importable here: {exc}")
+
+ reject_unknown_loadtime_options(
+ adapter_class,
+ config.resolve_profile("default").loadtime,
+ model_name=config.sie_id,
+ )
+
+
+def test_catalog_coverage_is_not_vacuous() -> None:
+ variants = [sie_id for sie_id, _ in _CATALOG if ":" in sie_id]
+
+ assert len(_CATALOG) >= _MIN_PROFILES_CHECKED, (
+ f"only {len(_CATALOG)} servable configs were collected from {_MODELS_DIR}; "
+ "the per-profile assertions above are no longer covering the catalog"
+ )
+ assert variants, "no non-default profile variants were collected"
+
+
+def test_derived_serving_artifact_profile_still_loads() -> None:
+ """A derived serving artifact is declared in the profile and consumed by the loader.
+
+ ``_build_adapter_kwargs`` replaces it with ``artifact_path`` and
+ ``ct2_compute_type``, so the adapter never names the declared spelling.
+ """
+ declaring = [
+ (sie_id, config)
+ for sie_id, config in _CATALOG
+ if "serving_artifact" in config.resolve_profile("default").loadtime
+ ]
+ assert declaring, "no shipped profile declares a derived serving artifact any more"
+ for sie_id, config in declaring:
+ try:
+ adapter_class = resolve_adapter_class(config, _MODELS_DIR)
+ except ImportError as exc:
+ pytest.skip(f"adapter for {sie_id} not importable here: {exc}")
+ reject_unknown_loadtime_options(
+ adapter_class,
+ config.resolve_profile("default").loadtime,
+ model_name=config.sie_id,
+ )
diff --git a/packages/sie_server/tests/config/test_tensor_parallel_options.py b/packages/sie_server/tests/config/test_tensor_parallel_options.py
new file mode 100644
index 000000000..90a604449
--- /dev/null
+++ b/packages/sie_server/tests/config/test_tensor_parallel_options.py
@@ -0,0 +1,90 @@
+"""Config-time rules for a profile that declares a tensor-parallel width.
+
+Each rule exists because the failure it prevents is silent. A placement flag
+passed straight to the engine serves on devices the registry never reserved,
+and a mistyped width is dropped rather than rejected, so the model serves on
+one card while the profile declares several.
+"""
+
+from __future__ import annotations
+
+from typing import Any
+
+import pytest
+from sie_server.config.model import AdapterOptions
+
+
+def _options(**loadtime: Any) -> AdapterOptions:
+ return AdapterOptions(loadtime=dict(loadtime))
+
+
+class TestDeclaredWidth:
+ def test_absent_width_needs_nothing_else(self) -> None:
+ """Every existing profile must keep loading unchanged."""
+ assert _options(mem_fraction_static=0.85).loadtime["mem_fraction_static"] == 0.85
+
+ def test_width_one_needs_nothing_else(self) -> None:
+ assert _options(tensor_parallel_size=1).loadtime["tensor_parallel_size"] == 1
+
+ @pytest.mark.parametrize("bad", [0, 9, -1, 2.5, "4", True, None])
+ def test_an_unusable_width_is_refused(self, bad: Any) -> None:
+ with pytest.raises(ValueError, match="tensor_parallel_size"):
+ _options(tensor_parallel_size=bad)
+
+
+class TestEngineSpecificRules:
+ def test_a_width_needs_no_engine_specific_option_at_the_config_layer(self) -> None:
+ """Any adapter that accepts a width may be given one.
+
+ A read cap is an SGLang requirement, enforced by the SGLang adapters
+ when they are constructed. Requiring it here refused every other
+ adapter's width, since those adapters do not accept the option.
+ """
+ assert _options(tensor_parallel_size=2).loadtime["tensor_parallel_size"] == 2
+
+
+class TestPlacementIsNotSmuggled:
+ @pytest.mark.parametrize(
+ "flag",
+ ["--tp", "--tp-size", "--tensor-parallel-size", "--dp-size", "--nnodes", "--base-gpu-id"],
+ )
+ def test_a_placement_flag_in_the_raw_passthrough_is_refused(self, flag: str) -> None:
+ """The registry reserves devices from the declared width. A width reaching
+ the engine another way serves on devices nothing reserved.
+ """
+ with pytest.raises(ValueError, match="placement flag"):
+ _options(extra_launch_args=[flag, "8"])
+
+ @pytest.mark.parametrize(
+ ("abbreviation", "flag"),
+ [
+ ("--tensor-parallel", "--tensor-parallel-size"),
+ ("--tp-s", "--tp-size"),
+ ("--base-gpu", "--base-gpu-id"),
+ ("--dist-init=10.0.0.1:5000", "--dist-init-addr"),
+ ],
+ )
+ def test_an_abbreviated_placement_flag_is_refused(self, abbreviation: str, flag: str) -> None:
+ """SGLang accepts any unambiguous prefix of a long option."""
+ with pytest.raises(ValueError, match=flag):
+ _options(extra_launch_args=[abbreviation, "4"])
+
+ def test_the_flag_equals_value_spelling_is_refused_too(self) -> None:
+ with pytest.raises(ValueError, match="placement flag"):
+ _options(extra_launch_args=["--tensor-parallel-size=8"])
+
+ @pytest.mark.parametrize("variable", ["CUDA_VISIBLE_DEVICES", "NVIDIA_VISIBLE_DEVICES", "ROCR_VISIBLE_DEVICES"])
+ def test_a_device_visibility_variable_is_refused(self, variable: str) -> None:
+ """The launcher overwrites it with the registry's mask, so setting it
+ here is silently discarded rather than honoured.
+ """
+ with pytest.raises(ValueError, match=variable):
+ _options(extra_env={variable: "0,1"})
+
+ def test_an_ordinary_passthrough_still_works(self) -> None:
+ options = _options(
+ extra_launch_args=["--mamba-scheduler-strategy", "extra_buffer"],
+ extra_env={"SGLANG_ENABLE_SPEC_V2": "1"},
+ )
+
+ assert options.loadtime["extra_launch_args"] == ["--mamba-scheduler-strategy", "extra_buffer"]
diff --git a/packages/sie_server/tests/core/test_registry_device_groups.py b/packages/sie_server/tests/core/test_registry_device_groups.py
new file mode 100644
index 000000000..2cd979638
--- /dev/null
+++ b/packages/sie_server/tests/core/test_registry_device_groups.py
@@ -0,0 +1,610 @@
+"""A declared tensor-parallel width is an exclusive claim on whole devices.
+
+The registry has always placed one model on one device and kept the right to
+evict it. A width above one changes that for the models that declare it: the
+load owns every card in its group until it unloads, because the engine reserves
+the large majority of each card it is given and the headroom left over is what
+graph capture needs for the group to start at all.
+
+These tests pin the parts a single-device deployment must never notice, and the
+parts a multi-device one depends on.
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+from unittest.mock import AsyncMock, MagicMock, patch
+
+import pytest
+from sie_server.config.model import AdapterOptions, EmbeddingDim, EncodeTask, ModelConfig, ProfileConfig, Tasks
+from sie_server.core.load_errors import DevicePlacementError, LoadErrorClass
+from sie_server.core.registry import ModelRegistry, declared_tensor_parallel_size
+
+
+def _make_config(
+ name: str = "test", *, width: int | None = None, extra_loadtime: dict[str, object] | None = None
+) -> ModelConfig:
+ loadtime: dict[str, object] = dict(extra_loadtime or {})
+ if width is not None:
+ loadtime["tensor_parallel_size"] = width
+ if width > 1:
+ # A width above one requires a finite streaming read cap.
+ loadtime["request_read_timeout_s"] = 120.0
+ return ModelConfig(
+ sie_id=name,
+ hf_id=f"org/{name}",
+ tasks=Tasks(encode=EncodeTask(dense=EmbeddingDim(dim=768))),
+ profiles={
+ "default": ProfileConfig(
+ # An adapter that accepts a width: the registry validates the
+ # profile's load-time options against it before placing a group.
+ adapter_path="sie_server.adapters.sglang.embedding:SGLangEmbeddingAdapter",
+ max_batch_tokens=8192,
+ adapter_options=AdapterOptions(loadtime=loadtime),
+ )
+ },
+ )
+
+
[email protected](autouse=True)
+def patch_ensure_model_cached():
+ with patch("sie_sdk.cache.ensure_model_cached") as mock:
+ mock.return_value = Path("/fake/cache/models--org--test")
+ yield mock
+
+
+def _registry(devices: list[str]) -> ModelRegistry:
+ registry = ModelRegistry(device="cuda", devices=devices)
+ for manager in registry.memory_managers.values():
+ manager.check_pressure = MagicMock(return_value=False) # type: ignore[method-assign]
+ return registry
+
+
+def _pinned_registry(devices: list[str], *, pinned: list[str]) -> ModelRegistry:
+ registry = ModelRegistry(device="cuda", devices=devices, pinned_models=pinned)
+ for manager in registry.memory_managers.values():
+ manager.check_pressure = MagicMock(return_value=False) # type: ignore[method-assign]
+ return registry
+
+
+def _adapter() -> MagicMock:
+ adapter = MagicMock()
+ adapter.capabilities.outputs = ["dense"]
+ adapter.memory_footprint.return_value = 1000
+ return adapter
+
+
+class TestDeclaredWidth:
+ def test_absent_declaration_is_width_one(self) -> None:
+ assert declared_tensor_parallel_size(_make_config()) == 1
+
+ def test_declared_width_is_read_from_the_default_profile(self) -> None:
+ assert declared_tensor_parallel_size(_make_config(width=4)) == 4
+
+ def test_malformed_width_is_refused_rather_than_read_as_one(self) -> None:
+ """A width that silently read as one would serve on a single card.
+
+ The operator would believe several were in use while the model ran on
+ one of the cards reserved for it.
+ """
+ with pytest.raises(ValueError, match="tensor_parallel_size"):
+ declared_tensor_parallel_size(_make_config(width=0))
+
+
+class TestExclusiveClaim:
+ @patch("sie_server.core.model_loader.load_adapter")
+ async def test_width_four_claims_every_member_of_its_group(self, mock_load_adapter: MagicMock) -> None:
+ registry = _registry(["cuda:0", "cuda:1", "cuda:2", "cuda:3"])
+ registry.add_config(_make_config("wide", width=4))
+ mock_load_adapter.return_value = _adapter()
+
+ await registry.load_async("wide", "cuda")
+
+ assert registry._device_claims == {
+ "cuda:0": "wide",
+ "cuda:1": "wide",
+ "cuda:2": "wide",
+ "cuda:3": "wide",
+ }
+ assert registry._loaded["wide"].device == "cuda:0"
+
+ @patch("sie_server.core.model_loader.load_adapter")
+ async def test_the_claim_log_names_only_the_loading_models_devices(
+ self, mock_load_adapter: MagicMock, caplog: pytest.LogCaptureFixture
+ ) -> None:
+ """With two groups resident, the second claim must not report the first group's cards."""
+ registry = _registry(["cuda:0", "cuda:1", "cuda:2", "cuda:3"])
+ registry.add_config(_make_config("first", width=2))
+ registry.add_config(_make_config("second", width=2))
+ mock_load_adapter.return_value = _adapter()
+ await registry.load_async("first", "cuda:0")
+ caplog.clear()
+
+ with caplog.at_level("INFO", logger="sie_server.core.registry"):
+ await registry.load_async("second", "cuda:2")
+
+ claims = [record.getMessage() for record in caplog.records if "claimed devices" in record.getMessage()]
+ assert claims == ["Model 'second' claimed devices ['cuda:2', 'cuda:3'] exclusively"]
+
+ @patch("sie_server.core.model_loader.load_adapter")
+ async def test_a_single_device_model_never_claims_anything(self, mock_load_adapter: MagicMock) -> None:
+ """The path every existing profile takes must be untouched."""
+ registry = _registry(["cuda:0", "cuda:1"])
+ registry.add_config(_make_config("ordinary"))
+ mock_load_adapter.return_value = _adapter()
+
+ await registry.load_async("ordinary", "cuda")
+
+ assert registry._device_claims == {}
+
+ @patch("sie_server.core.model_loader.load_adapter")
+ async def test_claimed_devices_are_released_on_unload(self, mock_load_adapter: MagicMock) -> None:
+ registry = _registry(["cuda:0", "cuda:1"])
+ registry.add_config(_make_config("wide", width=2))
+ mock_load_adapter.return_value = _adapter()
+
+ await registry.load_async("wide", "cuda")
+ assert registry._device_claims
+ await registry.unload_async("wide")
+
+ assert registry._device_claims == {}
+
+ @patch("sie_server.core.model_loader.load_adapter")
+ async def test_a_width_that_does_not_fit_fails_with_a_named_reason(self, mock_load_adapter: MagicMock) -> None:
+ """Serving on fewer cards than declared is the failure to avoid.
+
+ A width-four model quietly serving on one card holds four accelerators
+ and uses one.
+ """
+ registry = _registry(["cuda:0", "cuda:1"])
+ registry.add_config(_make_config("too-wide", width=4))
+ mock_load_adapter.return_value = _adapter()
+
+ with pytest.raises(RuntimeError, match="tensor_parallel_size=4"):
+ await registry.load_async("too-wide", "cuda")
+
+ assert registry._device_claims == {}
+
+ @patch("sie_server.core.model_loader.load_adapter")
+ async def test_a_failed_load_strands_no_claim(self, mock_load_adapter: MagicMock) -> None:
+ registry = _registry(["cuda:0", "cuda:1"])
+ registry.add_config(_make_config("wide", width=2))
+ mock_load_adapter.side_effect = RuntimeError("engine refused to start")
+
+ with pytest.raises(RuntimeError, match="engine refused"):
+ await registry.load_async("wide", "cuda")
+
+ assert registry._device_claims == {}
+
+ @patch("sie_server.core.model_loader.load_adapter")
+ async def test_a_group_does_not_land_on_a_device_another_model_occupies(self, mock_load_adapter: MagicMock) -> None:
+ registry = _registry(["cuda:0", "cuda:1", "cuda:2", "cuda:3"])
+ registry.add_config(_make_config("resident"))
+ registry.add_config(_make_config("wide", width=2))
+ mock_load_adapter.side_effect = [_adapter(), _adapter()]
+
+ await registry.load_async("resident", "cuda:0")
+ await registry.load_async("wide", "cuda")
+
+ assert registry._loaded["resident"].device == "cuda:0"
+ # Which free block it picks is not the contract. Not overlapping the
+ # resident is.
+ claimed = set(registry._device_claims)
+ assert len(claimed) == 2
+ assert "cuda:0" not in claimed
+
+ @patch("sie_server.core.model_loader.load_adapter")
+ async def test_naming_a_device_an_idle_group_holds_displaces_the_group(self, mock_load_adapter: MagicMock) -> None:
+ """Naming a group member must never put a second model onto it while held.
+
+ The group has sized its cache against the whole card, so the model is
+ placed only after the group has gone, never beside it.
+ """
+ registry = _registry(["cuda:0", "cuda:1", "cuda:2"])
+ registry.add_config(_make_config("wide", width=2))
+ registry.add_config(_make_config("intruder"))
+ mock_load_adapter.side_effect = [_adapter(), _adapter()]
+
+ await registry.load_async("wide", "cuda")
+ assert set(registry._device_claims) == {"cuda:0", "cuda:1"}
+
+ await registry.load_async("intruder", "cuda:1")
+
+ assert "wide" not in registry._loaded
+ assert registry._device_claims == {}
+ assert registry._loaded["intruder"].device == "cuda:1"
+
+ @patch("sie_server.core.model_loader.load_adapter")
+ async def test_naming_a_device_a_pinned_group_holds_is_refused(self, mock_load_adapter: MagicMock) -> None:
+ registry = _pinned_registry(["cuda:0", "cuda:1", "cuda:2"], pinned=["Org/Wide"])
+ registry.add_config(_make_config("Org/Wide", width=2))
+ registry.add_config(_make_config("intruder"))
+ mock_load_adapter.side_effect = [_adapter(), _adapter()]
+
+ await registry.load_async("Org/Wide", "cuda")
+
+ with pytest.raises(DevicePlacementError, match="held exclusively by multi-device model 'Org/Wide'"):
+ await registry.load_async("intruder", "cuda:1")
+
+ assert "Org/Wide" in registry._loaded
+ assert "intruder" not in registry._loaded
+
+ @patch("sie_server.core.model_loader.load_adapter")
+ async def test_an_unclaimed_device_can_still_be_named(self, mock_load_adapter: MagicMock) -> None:
+ registry = _registry(["cuda:0", "cuda:1", "cuda:2"])
+ registry.add_config(_make_config("wide", width=2))
+ registry.add_config(_make_config("ordinary"))
+ mock_load_adapter.side_effect = [_adapter(), _adapter()]
+
+ await registry.load_async("wide", "cuda")
+ await registry.load_async("ordinary", "cuda:2")
+
+ assert registry._loaded["ordinary"].device == "cuda:2"
+
+ @patch("sie_server.core.model_loader.load_adapter")
+ async def test_a_fully_claimed_worker_displaces_an_idle_group_rather_than_overlapping(
+ self, mock_load_adapter: MagicMock
+ ) -> None:
+ """With every card held, the group goes before anything else is placed.
+
+ Refusing instead would leave every other model on the worker unloadable
+ for as long as the group stayed resident, and nothing else unloads it.
+ """
+ registry = _registry(["cuda:0", "cuda:1"])
+ registry.add_config(_make_config("wide", width=2))
+ registry.add_config(_make_config("ordinary"))
+ mock_load_adapter.side_effect = [_adapter(), _adapter()]
+
+ await registry.load_async("wide", "cuda")
+ await registry.load_async("ordinary", "cuda")
+
+ assert "wide" not in registry._loaded
+ assert registry._device_claims == {}
+ assert "ordinary" in registry._loaded
+
+ @patch("sie_server.core.model_loader.load_adapter")
+ async def test_a_fully_claimed_worker_refuses_when_the_group_is_pinned(self, mock_load_adapter: MagicMock) -> None:
+ registry = _pinned_registry(["cuda:0", "cuda:1"], pinned=["Org/Wide"])
+ registry.add_config(_make_config("Org/Wide", width=2))
+ registry.add_config(_make_config("ordinary"))
+ mock_load_adapter.side_effect = [_adapter(), _adapter()]
+
+ await registry.load_async("Org/Wide", "cuda")
+
+ with pytest.raises(DevicePlacementError, match="exclusively"):
+ await registry.load_async("ordinary", "cuda")
+
+ assert "ordinary" not in registry._loaded
+
+ @patch("sie_server.core.model_loader.load_adapter")
+ async def test_a_single_device_model_avoids_a_claimed_device(self, mock_load_adapter: MagicMock) -> None:
+ registry = _registry(["cuda:0", "cuda:1", "cuda:2"])
+ registry.add_config(_make_config("wide", width=2))
+ registry.add_config(_make_config("ordinary"))
+ mock_load_adapter.side_effect = [_adapter(), _adapter()]
+
+ await registry.load_async("wide", "cuda")
+ await registry.load_async("ordinary", "cuda")
+
+ assert set(registry._device_claims) == {"cuda:0", "cuda:1"}
+ assert registry._loaded["ordinary"].device == "cuda:2"
+
+
+class TestGroupMemoryAccounting:
+ """A width-N load reserves memory on N cards, so N managers must know.
+
+ Registering only the anchor leaves the other members looking free, so a
+ later placement sizes itself against memory this model already holds and
+ the eviction that would have prevented the collision never fires.
+ """
+
+ @patch("sie_server.core.model_loader.load_adapter")
+ async def test_every_member_accounts_for_the_load(self, mock_load_adapter: MagicMock) -> None:
+ registry = _registry(["cuda:0", "cuda:1", "cuda:2", "cuda:3"])
+ registry.add_config(_make_config("wide", width=4))
+ mock_load_adapter.return_value = _adapter()
+
+ await registry.load_async("wide", "cuda")
+
+ for device in ("cuda:0", "cuda:1", "cuda:2", "cuda:3"):
+ assert "wide" in registry.memory_managers[device].loaded_models, device
+
+ @patch("sie_server.core.model_loader.load_adapter")
+ async def test_the_group_total_matches_a_single_device_load(self, mock_load_adapter: MagicMock) -> None:
+ """Sharding divides the weights, so the shares must divide too."""
+ registry = _registry(["cuda:0", "cuda:1"])
+ registry.add_config(_make_config("wide", width=2))
+ adapter = _adapter()
+ adapter.memory_footprint.return_value = 1000
+ mock_load_adapter.return_value = adapter
+
+ await registry.load_async("wide", "cuda")
+
+ shares = [registry.memory_managers[device]._models["wide"].estimated_bytes for device in ("cuda:0", "cuda:1")]
+ total = registry._loaded["wide"].memory_bytes
+
+ assert all(share == total // 2 for share in shares)
+ # Integer division may drop a remainder; the group must never claim
+ # more than a single-device load of the same model would have.
+ assert sum(shares) <= total
+
+ @patch("sie_server.core.model_loader.load_adapter")
+ async def test_unload_clears_every_member(self, mock_load_adapter: MagicMock) -> None:
+ registry = _registry(["cuda:0", "cuda:1", "cuda:2"])
+ registry.add_config(_make_config("wide", width=2))
+ mock_load_adapter.return_value = _adapter()
+
+ await registry.load_async("wide", "cuda")
+ await registry.unload_async("wide")
+
+ for device in ("cuda:0", "cuda:1", "cuda:2"):
+ assert "wide" not in registry.memory_managers[device].loaded_models, device
+ assert registry._device_claims == {}
+
+ @patch("sie_server.core.model_loader.load_adapter")
+ async def test_a_single_device_load_registers_exactly_where_it_did_before(
+ self, mock_load_adapter: MagicMock
+ ) -> None:
+ """The path every existing profile takes must be untouched."""
+ registry = _registry(["cuda:0", "cuda:1"])
+ registry.add_config(_make_config("ordinary"))
+ mock_load_adapter.return_value = _adapter()
+
+ await registry.load_async("ordinary", "cuda")
+
+ anchor = registry._loaded["ordinary"].device
+ assert "ordinary" in registry.memory_managers[anchor].loaded_models
+ other = "cuda:1" if anchor == "cuda:0" else "cuda:0"
+ assert "ordinary" not in registry.memory_managers[other].loaded_models
+
+
+class TestWidthAgainstVisibleDevices:
+ @patch("sie_server.core.model_loader.load_adapter")
+ async def test_a_width_this_worker_can_never_serve_says_so(self, mock_load_adapter: MagicMock) -> None:
+ """Distinct from 'no free block right now', which is worth retrying."""
+ registry = _registry(["cuda:0", "cuda:1"])
+ registry.add_config(_make_config("too-wide", width=4))
+ mock_load_adapter.return_value = _adapter()
+
+ with pytest.raises(RuntimeError, match="sees 2 device"):
+ await registry.load_async("too-wide", "cuda")
+
+ assert registry._device_claims == {}
+
+ @patch("sie_server.core.model_loader.load_adapter")
+ async def test_a_width_equal_to_the_device_count_is_servable(self, mock_load_adapter: MagicMock) -> None:
+ registry = _registry(["cuda:0", "cuda:1"])
+ registry.add_config(_make_config("exact", width=2))
+ mock_load_adapter.return_value = _adapter()
+
+ await registry.load_async("exact", "cuda")
+
+ assert set(registry._device_claims) == {"cuda:0", "cuda:1"}
+
+
+class TestTheRegistryAndTheAdapterAgree:
+ """The registry reserves cards and the adapter masks cards, separately.
+
+ They are kept in step by both deriving the group from the same anchor and
+ width through one shared function rather than by passing a list. This pins
+ that, because a silent disagreement would have the registry accounting for
+ one set of cards while the engine ran on another.
+ """
+
+ @pytest.mark.parametrize("width", [1, 2, 4, 8])
+ def test_the_claimed_devices_are_the_masked_devices(self, width: int) -> None:
+ from sie_server.adapters.sglang._server import format_device_mask, parse_device_index
+ from sie_server.config.device_groups import resolve_device_group
+
+ registry = _registry([f"cuda:{index}" for index in range(width)])
+
+ claimed = registry._group_members("cuda:0", width)
+ assert claimed is not None
+
+ masked = format_device_mask(resolve_device_group(parse_device_index("cuda:0"), width))
+
+ assert masked == ",".join(str(index) for index in range(width))
+ assert claimed == [f"cuda:{index}" for index in range(width)]
+
+ def test_a_group_that_runs_past_the_device_list_is_not_claimable(self) -> None:
+ registry = _registry(["cuda:0", "cuda:1"])
+
+ assert registry._group_members("cuda:1", 2) is None
+
+ def test_an_anchor_without_a_concrete_index_is_single_device_only(self) -> None:
+ """A bare 'cuda' names no card, so it cannot anchor a group."""
+ registry = _registry(["cuda"])
+
+ assert registry._group_members("cuda", 1) == ["cuda"]
+ assert registry._group_members("cuda", 2) is None
+
+
+class TestGroupPlacementEvicts:
+ """An occupied block is not an unavailable one.
+
+ The registry is lazy-load with LRU eviction. If a group load refused to
+ evict, one request for any sibling model would keep the wide model from
+ ever loading again, and nothing would unload that sibling afterwards.
+ """
+
+ @patch("sie_server.core.model_loader.load_adapter")
+ async def test_an_idle_neighbour_is_evicted_to_free_the_group(self, mock_load_adapter: MagicMock) -> None:
+ registry = _registry(["cuda:0", "cuda:1"])
+ registry.add_config(_make_config("small"))
+ registry.add_config(_make_config("wide", width=2))
+ mock_load_adapter.return_value = _adapter()
+
+ await registry.load_async("small", "cuda:0")
+ assert "small" in registry._loaded
+
+ await registry.load_async("wide", "cuda")
+
+ assert "small" not in registry._loaded
+ assert registry._device_claims == {"cuda:0": "wide", "cuda:1": "wide"}
+
+ @patch("sie_server.core.model_loader.load_adapter")
+ async def test_a_free_block_is_preferred_over_evicting_one(self, mock_load_adapter: MagicMock) -> None:
+ registry = _registry(["cuda:0", "cuda:1", "cuda:2", "cuda:3"])
+ registry.add_config(_make_config("small"))
+ registry.add_config(_make_config("wide", width=2))
+ mock_load_adapter.return_value = _adapter()
+
+ await registry.load_async("small", "cuda:0")
+ await registry.load_async("wide", "cuda")
+
+ assert "small" in registry._loaded
+ claimed = sorted(registry._device_claims)
+ assert len(claimed) == 2
+ assert "cuda:0" not in claimed
+
+ @patch("sie_server.core.model_loader.load_adapter")
+ async def test_a_pinned_neighbour_is_never_evicted(self, mock_load_adapter: MagicMock) -> None:
+ registry = ModelRegistry(device="cuda", devices=["cuda:0", "cuda:1"], pinned_models=["small"])
+ for manager in registry.memory_managers.values():
+ manager.check_pressure = MagicMock(return_value=False) # type: ignore[method-assign]
+ registry.add_config(_make_config("small"))
+ registry.add_config(_make_config("wide", width=2))
+ mock_load_adapter.return_value = _adapter()
+
+ await registry.load_async("small", "cuda:0")
+
+ with pytest.raises(RuntimeError, match="can be freed"):
+ await registry.load_async("wide", "cuda")
+
+ assert "small" in registry._loaded
+ assert registry._device_claims == {}
+
+
+def _rescanning_registry(devices: list[str], configs: list[dict[str, ModelConfig]]) -> ModelRegistry:
+ """A registry whose on-disk catalog changes between scans, as a config update drops an entry."""
+ with patch("sie_server.core.registry.load_model_configs", side_effect=configs):
+ registry = ModelRegistry(models_dir=Path("/fake/models"), device="cuda", devices=devices)
+ for manager in registry.memory_managers.values():
+ manager.check_pressure = MagicMock(return_value=False) # type: ignore[method-assign]
+ return registry
+
+
+class TestConfigDropDoesNotStrandAGroup:
+ @patch("sie_server.core.model_loader.load_adapter")
+ async def test_a_resident_whose_config_was_rescanned_away_can_still_be_unloaded(
+ self, mock_load_adapter: MagicMock
+ ) -> None:
+ """A rescan replaces the whole catalog while the model stays loaded and claimed."""
+ wide = _make_config("wide", width=2)
+ registry = _rescanning_registry(["cuda:0", "cuda:1"], [{"wide": wide}])
+ mock_load_adapter.return_value = _adapter()
+
+ await registry.load_async("wide", "cuda")
+ assert sorted(registry._device_claims) == ["cuda:0", "cuda:1"]
+
+ with patch("sie_server.core.registry.load_model_configs", return_value={}):
+ registry.rescan_configs()
+ assert not registry.has_model("wide")
+
+ await registry.unload_async("wide")
+
+ assert registry._device_claims == {}
+ assert "wide" not in registry._loaded
+
+ async def test_an_unknown_name_is_still_a_key_error(self) -> None:
+ registry = _registry(["cuda:0"])
+
+ with pytest.raises(KeyError):
+ await registry.unload_async("never-existed")
+
+
+@patch("sie_server.core.model_loader.load_adapter")
+def test_the_synchronous_unload_also_reaches_a_rescanned_away_resident(mock_load_adapter: MagicMock) -> None:
+ wide = _make_config("wide", width=2)
+ registry = _rescanning_registry(["cuda:0", "cuda:1"], [{"wide": wide}])
+ mock_load_adapter.return_value = _adapter()
+
+ registry.load("wide", "cuda")
+ with patch("sie_server.core.registry.load_model_configs", return_value={}):
+ registry.rescan_configs()
+
+ registry.unload("wide")
+
+ assert registry._device_claims == {}
+ assert "wide" not in registry._loaded
+
+
+class TestPlacementUnderContention:
+ """The shapes the first review of eviction missed, through the load paths workers use."""
+
+ @patch("sie_server.core.model_loader.load_adapter")
+ async def test_a_second_wide_model_displaces_the_first(self, mock_load_adapter: MagicMock) -> None:
+ """With every card claimed, the only way a group can move is if another group can displace it."""
+ registry = _registry(["cuda:0", "cuda:1"])
+ registry.add_config(_make_config("wide-a", width=2))
+ registry.add_config(_make_config("wide-b", width=2))
+ mock_load_adapter.side_effect = [_adapter(), _adapter()]
+
+ await registry._load_model_background("wide-a", "cuda")
+ await registry._load_model_background("wide-b", "cuda")
+
+ assert "wide-a" not in registry._loaded
+ assert registry._device_claims == {"cuda:0": "wide-b", "cuda:1": "wide-b"}
+ assert not registry.is_failed("wide-b")
+
+ @patch("sie_server.core.model_loader.load_adapter")
+ async def test_a_placement_conflict_is_retryable_and_clears_on_unload(self, mock_load_adapter: MagicMock) -> None:
+ """Recorded as an unclassified failure it stayed sticky after the cards came free."""
+ registry = _pinned_registry(["cuda:0", "cuda:1"], pinned=["Org/Wide"])
+ registry.add_config(_make_config("Org/Wide", width=2))
+ registry.add_config(_make_config("small"))
+ mock_load_adapter.side_effect = [_adapter(), _adapter()]
+
+ await registry._load_model_background("Org/Wide", "cuda")
+ await registry._load_model_background("small", "cuda")
+
+ failure = registry.get_failure("small")
+ assert failure is not None
+ assert failure.error_class is LoadErrorClass.PLACEMENT
+ assert not failure.is_permanent
+
+ await registry.unload_async("Org/Wide")
+
+ assert not registry.is_failed("small")
+
+ @patch("sie_server.core.model_loader.load_adapter")
+ async def test_a_pinned_neighbour_with_a_hub_style_id_is_never_evicted(self, mock_load_adapter: MagicMock) -> None:
+ """The pinned set is lowercased; loaded names keep their case."""
+ registry = _pinned_registry(["cuda:0", "cuda:1"], pinned=["BAAI/bge-m3"])
+ registry.add_config(_make_config("BAAI/bge-m3"))
+ registry.add_config(_make_config("Org/Wide", width=2))
+ mock_load_adapter.side_effect = [_adapter(), _adapter()]
+
+ await registry.load_async("BAAI/bge-m3", "cuda:0")
+
+ with pytest.raises(DevicePlacementError, match="can be freed"):
+ await registry.load_async("Org/Wide", "cuda")
+
+ assert "BAAI/bge-m3" in registry._loaded
+ assert registry._device_claims == {}
+
+ @patch("sie_server.core.model_loader.load_adapter")
+ async def test_a_profile_its_adapter_rejects_evicts_nothing(self, mock_load_adapter: MagicMock) -> None:
+ """A typo must fail before a group evicts working models to make room for it."""
+ registry = _registry(["cuda:0", "cuda:1"])
+ registry.add_config(_make_config("small"))
+ registry.add_config(_make_config("wide", width=2, extra_loadtime={"watchdog_timeout": 90}))
+ mock_load_adapter.side_effect = [_adapter(), _adapter()]
+
+ await registry.load_async("small", "cuda:0")
+
+ with pytest.raises(ValueError, match="does not accept load-time option"):
+ await registry.load_async("wide", "cuda")
+
+ assert "small" in registry._loaded
+ assert registry._device_claims == {}
+
+ async def test_an_unservable_width_is_refused_before_any_download(self) -> None:
+ registry = _registry(["cuda:0", "cuda:1"])
+ registry.add_config(_make_config("too-wide", width=4))
+ registry._loader.ensure_weights_cached_async = AsyncMock() # type: ignore[method-assign]
+
+ with pytest.raises(RuntimeError, match="sees 2 device"):
+ await registry.load_async("too-wide", "cuda")
+
+ registry._loader.ensure_weights_cached_async.assert_not_awaited()