Skip to content

armgit / sie

Public Imported from GitHub
0

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

fix(server): fetch model weights outside the registry load lock (#272)

Krisztian Gajdar394df634824e
diff --git a/packages/sie_server/src/sie_server/core/model_loader.py b/packages/sie_server/src/sie_server/core/model_loader.py
index 4dcba5c28..f9c8c9bdf 100644
--- a/packages/sie_server/src/sie_server/core/model_loader.py
+++ b/packages/sie_server/src/sie_server/core/model_loader.py
@@ -3,6 +3,7 @@ from __future__ import annotations
import asyncio
import logging
import os
+import threading
import time
from collections import OrderedDict
from concurrent.futures import ThreadPoolExecutor
@@ -178,6 +179,12 @@ class ModelLoader:
self._oom_recovery = oom_recovery or OomRecoveryConfig()
self._registry_callbacks = registry_callbacks
self._load_executor = ThreadPoolExecutor(max_workers=1, thread_name_prefix="model-load")
+ # Weight downloads run apart from instantiation so a slow fetch of one
+ # model never queues another model's instantiate behind it. The disk
+ # cache manager is not thread-safe, so its accounting calls are
+ # serialized here while the downloads themselves proceed concurrently.
+ self._download_executor = ThreadPoolExecutor(max_workers=4, thread_name_prefix="model-download")
+ self._disk_cache_lock = threading.Lock()
# Loader-owned admission results. Catalog data can identify a derived
# artifact but can never inject a filesystem root into an adapter.
self._verified_serving_artifacts: dict[str, VerifiedServingArtifact] = {}
@@ -271,7 +278,7 @@ class ModelLoader:
raise ValueError("derived serving artifacts require an immutable HF source identity")
derived_id = serving_artifact.repo_id
if self._disk_cache is not None:
- evicted = self._disk_cache.ensure_space_before_download(derived_id)
+ evicted = self._ensure_disk_space_locked(derived_id)
if evicted:
logger.info(
"Pre-download disk eviction: freed %d model(s): %s",
@@ -292,7 +299,7 @@ class ModelLoader:
)
self._verified_serving_artifacts[config.sie_id] = verified
if self._disk_cache is not None:
- self._disk_cache.touch(derived_id)
+ self._touch_disk_locked(derived_id)
logger.debug(
"Derived serving artifact %s@%s materialized at %s",
derived_id,
@@ -301,7 +308,7 @@ class ModelLoader:
)
elif model_id is not None:
if self._disk_cache is not None:
- evicted = self._disk_cache.ensure_space_before_download(model_id)
+ evicted = self._ensure_disk_space_locked(model_id)
if evicted:
logger.info(
"Pre-download disk eviction: freed %d model(s): %s",
@@ -311,7 +318,7 @@ class ModelLoader:
cached_path = ensure_model_cached(model_id, cache_config, revision=config.hf_revision)
if self._disk_cache is not None:
- self._disk_cache.touch(model_id)
+ self._touch_disk_locked(model_id)
logger.debug("Model %s available at %s", model_id, cached_path)
# External speculative assistants are separate checkpoints. Stage each
@@ -319,7 +326,7 @@ class ModelLoader:
# engine-owned, moving-branch download during launch.
for draft_model, revision in config.speculative_draft_revisions().items():
if self._disk_cache is not None:
- evicted = self._disk_cache.ensure_space_before_download(draft_model)
+ evicted = self._ensure_disk_space_locked(draft_model)
if evicted:
logger.info(
"Pre-download disk eviction for speculative draft: freed %d model(s): %s",
@@ -328,7 +335,7 @@ class ModelLoader:
)
draft_path = ensure_model_cached(draft_model, cache_config, revision=revision)
if self._disk_cache is not None:
- self._disk_cache.touch(draft_model)
+ self._touch_disk_locked(draft_model)
logger.debug(
"Speculative draft %s@%s available at %s",
draft_model,
@@ -336,11 +343,22 @@ class ModelLoader:
draft_path,
)
+ def _ensure_disk_space_locked(self, model_id: str) -> list[str]:
+ assert self._disk_cache is not None
+ with self._disk_cache_lock:
+ return self._disk_cache.ensure_space_before_download(model_id)
+
+ def _touch_disk_locked(self, model_id: str) -> None:
+ assert self._disk_cache is not None
+ with self._disk_cache_lock:
+ self._disk_cache.touch(model_id)
+
async def ensure_weights_cached_async(self, name: str, config: ModelConfig) -> None:
"""Async version of :meth:`ensure_weights_cached`.
- Runs the (potentially long) download on the load executor so it
- doesn't block the event loop. Intentionally NOT wrapped in
+ Runs the (potentially long) download on the download executor, apart
+ from the single-threaded load executor, so it blocks neither the event
+ loop nor another model's instantiation. Intentionally NOT wrapped in
``asyncio.wait_for`` — slow networks are allowed; stalls are
detected by ``HF_HUB_DOWNLOAD_TIMEOUT`` inside ``huggingface_hub``.
@@ -350,7 +368,7 @@ class ModelLoader:
"""
logger.debug("Ensuring weights cached for '%s'", name)
loop = asyncio.get_running_loop()
- await loop.run_in_executor(self._load_executor, self.ensure_weights_cached, config)
+ await loop.run_in_executor(self._download_executor, self.ensure_weights_cached, config)
async def instantiate_adapter_async(
self,
@@ -855,6 +873,7 @@ class ModelLoader:
def shutdown(self) -> None:
"""Shutdown the loader's thread pool."""
self._load_executor.shutdown(wait=False)
+ self._download_executor.shutdown(wait=False)
def _run_load_with_markers(name: str, device: str, adapter: ModelAdapter) -> None:
diff --git a/packages/sie_server/src/sie_server/core/registry.py b/packages/sie_server/src/sie_server/core/registry.py
index 6dc46cb37..9b70f71b2 100644
--- a/packages/sie_server/src/sie_server/core/registry.py
+++ b/packages/sie_server/src/sie_server/core/registry.py
@@ -262,6 +262,7 @@ class ModelRegistry:
# Concurrency-safe loading
self._load_lock: asyncio.Lock | None = None # Created lazily on first use
+ self._model_load_locks: dict[str, asyncio.Lock] = {}
self._config_update_lock: asyncio.Lock | None = None
# Async lifecycle state is owned by one long-lived server event loop.
# Legacy synchronous callers are serialized independently until that
@@ -799,6 +800,14 @@ class ModelRegistry:
self._load_lock = asyncio.Lock()
return self._load_lock
+ def _get_model_load_lock(self, name: str) -> asyncio.Lock:
+ """Per-model load serialization, created on the registry lifecycle loop."""
+ self._bind_lifecycle_loop()
+ lock = self._model_load_locks.get(name)
+ if lock is None:
+ lock = self._model_load_locks[name] = asyncio.Lock()
+ return lock
+
def _get_config_update_lock(self) -> asyncio.Lock:
"""Serialize async config mutations across IPC/hot-reload entrypoints."""
self._bind_lifecycle_loop()
@@ -1056,122 +1065,146 @@ class ModelRegistry:
self._check_model_loadable(name)
lock = self._get_load_lock()
- async with lock:
- # Double-check after acquiring lock (another request may have loaded it)
- if name in self._loaded:
- self._memory_manager_for_model(name).touch(name)
- return self._loaded[name].adapter
+ async with self._get_model_load_lock(name):
+ async with lock:
+ # Double-check after acquiring lock (another request may have loaded it)
+ if name in self._loaded:
+ self._memory_manager_for_model(name).touch(name)
+ return self._loaded[name].adapter
- load_device = self._resolve_load_device(device)
- memory_manager = self._memory_manager_for_device(load_device)
+ # Check if model is being unloaded - caller should retry
+ if name in self._unloading:
+ msg = f"Model '{name}' is currently being unloaded"
+ raise RuntimeError(msg)
- # Check if model is being unloaded - caller should retry
- if name in self._unloading:
- msg = f"Model '{name}' is currently being unloaded"
- raise RuntimeError(msg)
+ config = self._configs[name]
- config = self._configs[name]
+ # Mark as loading before starting (visible to WebSocket status)
+ self._loading.add(name)
- # Mark as loading before starting (visible to WebSocket status)
- self._loading.add(name)
load_start = time.monotonic()
load_outcome = "error"
load_stage = "total"
try:
- model_dir = self._model_dirs.get(name, Path())
-
- # Ensure weights are cached BEFORE instantiation. This
- # phase is intentionally unbounded by the post-download
- # timeout in ``ModelLoader`` — slow user networks are
- # supported via ``HF_HUB_DOWNLOAD_TIMEOUT`` stall
- # detection inside ``huggingface_hub`` only.
+ # The download holds neither lock. It is intentionally unbounded
+ # by the post-download timeout in ``ModelLoader`` — slow user
+ # networks are supported via ``HF_HUB_DOWNLOAD_TIMEOUT`` stall
+ # detection inside ``huggingface_hub`` only — and the registry
+ # 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.
await self._loader.ensure_weights_cached_async(name, config)
- # Instantiate adapter (in thread pool, post-download timeout applies)
- adapter = await self._loader.instantiate_adapter_async(name, config, model_dir, load_device)
+ async with lock:
+ if name in self._loaded:
+ self._memory_manager_for_model(name).touch(name)
+ load_outcome = "success"
+ return self._loaded[name].adapter
+ if name in self._unloading:
+ msg = f"Model '{name}' is currently being unloaded"
+ raise RuntimeError(msg)
+ # Config mutation only takes the registry lock, so the
+ # config this load started from may have been removed or
+ # replaced while the weights were fetched. Never register
+ # an adapter built from a config the registry no longer
+ # serves; a changed one is retried by the caller.
+ current_config = self._configs.get(name)
+ if current_config is None:
+ msg = f"Model '{name}' config was removed while its weights were being fetched"
+ raise RuntimeError(msg)
+ if current_config != config:
+ msg = f"Model '{name}' config changed while its weights were being fetched; retry"
+ raise RuntimeError(msg)
+ model_dir = self._model_dirs.get(name, Path())
+
+ load_device = self._resolve_load_device(device)
+ memory_manager = self._memory_manager_for_device(load_device)
+
+ # Instantiate adapter (in thread pool, post-download timeout applies)
+ adapter = await self._loader.instantiate_adapter_async(name, config, model_dir, load_device)
+
+ required_load_bytes = _adapter_load_required_bytes(adapter, memory_manager)
+
+ # Pre-load eviction: evict LRU non-pinned models until current pressure
+ # and any adapter-provided load headroom requirement are satisfied.
+ while memory_manager.should_evict_for_load(required_load_bytes):
+ lru_model = memory_manager.get_lru_model(exclude=self._pinned_models)
+ if lru_model is None:
+ break # No non-pinned models to evict, proceed with load attempt
+
+ if lru_model not in self._loaded:
+ # Belt-and-braces: a MemoryManager entry with no matching
+ # ``_loaded`` model is a ghost (see #1600). ``_do_unload``
+ # would no-op on it, so drop the stale accounting entry and
+ # re-evaluate rather than spin. The ``_do_unload`` finally
+ # normally prevents ghosts; this guards any other source.
+ logger.warning(
+ "Evictor found ghost '%s' (in memory manager, not loaded); dropping stale entry",
+ lru_model,
+ )
+ memory_manager.unregister_model(lru_model)
+ continue
- required_load_bytes = _adapter_load_required_bytes(adapter, memory_manager)
+ stats = memory_manager.get_stats()
+ logger.info(
+ "Pre-load eviction: %s %.2f GB free, %.2f GB required, %.1f%% used "
+ "(threshold %.1f%%); evicting '%s' before loading '%s'",
+ load_device,
+ stats.available_gb,
+ (required_load_bytes or 0) / (1024**3),
+ stats.usage_ratio * 100,
+ memory_manager.pressure_threshold_pct,
+ lru_model,
+ name,
+ )
+ await self._do_unload(lru_model, reason="preload_pressure")
- # Pre-load eviction: evict LRU non-pinned models until current pressure
- # and any adapter-provided load headroom requirement are satisfied.
- while memory_manager.should_evict_for_load(required_load_bytes):
- lru_model = memory_manager.get_lru_model(exclude=self._pinned_models)
- if lru_model is None:
- break # No non-pinned models to evict, proceed with load attempt
+ try:
+ # Load onto device (loader handles main thread vs executor)
+ loaded = await self._loader.load_and_register_async(name, load_device, adapter, config)
+ except RuntimeError as e:
+ if not self._is_oom_error(e):
+ raise
+
+ # OOM despite pre-load eviction: evict LRU non-pinned model and retry once
+ lru_model = memory_manager.get_lru_model(exclude=self._pinned_models)
+ if lru_model is None:
+ logger.error("OOM loading '%s' but no non-pinned models to evict", name)
+ raise
- if lru_model not in self._loaded:
- # Belt-and-braces: a MemoryManager entry with no matching
- # ``_loaded`` model is a ghost (see #1600). ``_do_unload``
- # would no-op on it, so drop the stale accounting entry and
- # re-evaluate rather than spin. The ``_do_unload`` finally
- # normally prevents ghosts; this guards any other source.
logger.warning(
- "Evictor found ghost '%s' (in memory manager, not loaded); dropping stale entry",
+ "OOM loading '%s' despite pre-eviction, evicting '%s' and retrying",
+ name,
lru_model,
)
- memory_manager.unregister_model(lru_model)
- continue
+ await self._do_unload(lru_model, reason="load_oom")
- stats = memory_manager.get_stats()
- logger.info(
- "Pre-load eviction: %s %.2f GB free, %.2f GB required, %.1f%% used "
- "(threshold %.1f%%); evicting '%s' before loading '%s'",
- load_device,
- stats.available_gb,
- (required_load_bytes or 0) / (1024**3),
- stats.usage_ratio * 100,
- memory_manager.pressure_threshold_pct,
- lru_model,
- name,
- )
- await self._do_unload(lru_model, reason="preload_pressure")
+ # Retry once after eviction. Weights are still cached
+ # on disk so we skip ``ensure_weights_cached_async``.
+ adapter = await self._loader.instantiate_adapter_async(name, config, model_dir, load_device)
+ loaded = await self._loader.load_and_register_async(name, load_device, adapter, config)
- try:
- # Load onto device (loader handles main thread vs executor)
- loaded = await self._loader.load_and_register_async(name, load_device, adapter, config)
- except RuntimeError as e:
- if not self._is_oom_error(e):
- raise
-
- # OOM despite pre-load eviction: evict LRU non-pinned model and retry once
- lru_model = memory_manager.get_lru_model(exclude=self._pinned_models)
- if lru_model is None:
- logger.error("OOM loading '%s' but no non-pinned models to evict", name)
- raise
+ # Track loaded state
+ self._loaded[name] = loaded
- logger.warning(
- "OOM loading '%s' despite pre-eviction, evicting '%s' and retrying",
+ # Register with memory manager for LRU tracking
+ self._memory_manager_for_device(loaded.device).register_model(
name,
- lru_model,
+ estimated_bytes=loaded.memory_bytes,
)
- await self._do_unload(lru_model, reason="load_oom")
-
- # Retry once after eviction. Weights are still cached
- # on disk so we skip ``ensure_weights_cached_async``.
- adapter = await self._loader.instantiate_adapter_async(name, config, model_dir, load_device)
- loaded = await self._loader.load_and_register_async(name, load_device, adapter, config)
-
- # Track loaded state
- 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,
- )
-
- load_duration = time.monotonic() - load_start
- if load_duration > 300:
- logger.warning(
- "Model '%s' took %.0fs to load (>300s) — may indicate a gated model "
- "missing HF_TOKEN or network issues",
- name,
- load_duration,
- )
+ load_duration = time.monotonic() - load_start
+ if load_duration > 300:
+ logger.warning(
+ "Model '%s' took %.0fs to load (>300s) — may indicate a gated model "
+ "missing HF_TOKEN or network issues",
+ name,
+ load_duration,
+ )
- load_outcome = "success"
- return loaded.adapter
+ load_outcome = "success"
+ return loaded.adapter
except ModelLoadTimeoutError as exc:
load_outcome = "timeout"
load_stage = exc.stage
diff --git a/packages/sie_server/tests/core/test_registry_async.py b/packages/sie_server/tests/core/test_registry_async.py
index 56b069941..997c6b439 100644
--- a/packages/sie_server/tests/core/test_registry_async.py
+++ b/packages/sie_server/tests/core/test_registry_async.py
@@ -938,3 +938,122 @@ class TestSetPinnedModels:
return mock
return make_mock
+
+
+# ---- weight downloads run outside the registry load lock ---------------------
+
+
+class _BlockingDownload:
+ """``ensure_model_cached`` stand-in that parks one repo until released."""
+
+ def __init__(self, slow_repo: str) -> None:
+ import threading
+
+ self.slow_repo = slow_repo
+ self.entered = threading.Event()
+ self.release = threading.Event()
+
+ def __call__(self, model_id: str, *_args: object, **_kwargs: object) -> Path:
+ if model_id == self.slow_repo:
+ self.entered.set()
+ assert self.release.wait(timeout=10), "download was never released"
+ return Path(f"/fake/cache/models--{model_id.replace('/', '--')}")
+
+
+def _two_model_registry() -> ModelRegistry:
+ registry = ModelRegistry()
+ registry.add_config(_make_config(name="slow", hf_id="org/slow"))
+ registry.add_config(_make_config(name="fast", hf_id="org/fast"))
+ return registry
+
+
+def _adapter_factory() -> Callable[..., MagicMock]:
+ def make(*_args: object, **_kwargs: object) -> MagicMock:
+ adapter = MagicMock()
+ adapter.memory_footprint.return_value = 1000
+ return adapter
+
+ return make
+
+
+async def test_download_of_one_model_does_not_block_another_load(patch_ensure_model_cached: MagicMock) -> None:
+ """A cold model's fetch must not serialize a model whose weights are on disk."""
+ download = _BlockingDownload("org/slow")
+ patch_ensure_model_cached.side_effect = download
+ registry = _two_model_registry()
+ with patch("sie_server.core.model_loader.load_adapter", side_effect=_adapter_factory()):
+ slow = asyncio.create_task(registry.load_async("slow", "cpu"))
+ await asyncio.to_thread(download.entered.wait, 5)
+ assert registry.is_loading("slow")
+
+ # With the fetch holding the registry lock this would wait on ``slow``.
+ await asyncio.wait_for(registry.load_async("fast", "cpu"), timeout=5)
+ assert registry.is_loaded("fast")
+ assert not registry.is_loaded("slow")
+
+ download.release.set()
+ await asyncio.wait_for(slow, timeout=5)
+ assert registry.is_loaded("slow")
+
+
+async def test_download_does_not_block_unload_or_eviction(patch_ensure_model_cached: MagicMock) -> None:
+ download = _BlockingDownload("org/slow")
+ patch_ensure_model_cached.side_effect = download
+ registry = _two_model_registry()
+ with patch("sie_server.core.model_loader.load_adapter", side_effect=_adapter_factory()):
+ await registry.load_async("fast", "cpu")
+ slow = asyncio.create_task(registry.load_async("slow", "cpu"))
+ await asyncio.to_thread(download.entered.wait, 5)
+
+ await asyncio.wait_for(registry.unload_async("fast"), timeout=5)
+ assert not registry.is_loaded("fast")
+
+ download.release.set()
+ await asyncio.wait_for(slow, timeout=5)
+
+
+async def test_concurrent_loads_of_one_model_fetch_once(patch_ensure_model_cached: MagicMock) -> None:
+ download = _BlockingDownload("org/slow")
+ patch_ensure_model_cached.side_effect = download
+ registry = _two_model_registry()
+ with patch("sie_server.core.model_loader.load_adapter", side_effect=_adapter_factory()):
+ first = asyncio.create_task(registry.load_async("slow", "cpu"))
+ second = asyncio.create_task(registry.load_async("slow", "cpu"))
+ await asyncio.to_thread(download.entered.wait, 5)
+ download.release.set()
+ adapters = await asyncio.wait_for(asyncio.gather(first, second), timeout=5)
+ assert adapters[0] is adapters[1]
+ slow_fetches = [c for c in patch_ensure_model_cached.call_args_list if c.args and c.args[0] == "org/slow"]
+ assert len(slow_fetches) == 1
+
+
+async def test_config_replaced_during_download_is_not_registered(
+ patch_ensure_model_cached: MagicMock, tmp_path: Path
+) -> None:
+ """A config swapped out under a parked download never gets an adapter registered from the old one."""
+ download = _BlockingDownload("org/slow")
+ patch_ensure_model_cached.side_effect = download
+ registry = _two_model_registry()
+ with patch("sie_server.core.model_loader.load_adapter", side_effect=_adapter_factory()):
+ slow = asyncio.create_task(registry.load_async("slow", "cpu"))
+ await asyncio.to_thread(download.entered.wait, 5)
+
+ # Same name, different config: what hot reload does under the load lock.
+ await registry.replace_configs_async(
+ [_make_config(name="slow", hf_id="org/slow", max_sequence_length=4096)],
+ model_dir=tmp_path,
+ )
+ download.release.set()
+ with pytest.raises(RuntimeError, match="changed"):
+ await asyncio.wait_for(slow, timeout=5)
+ assert not registry.is_loaded("slow")
+ assert not registry.is_loading("slow")
+
+
+def test_loader_shutdown_closes_the_download_executor() -> None:
+ from sie_server.core.model_loader import ModelLoader
+
+ loader = ModelLoader(preprocessor_registry=MagicMock(), postprocessor_registry=MagicMock(), all_configs={})
+ loader.shutdown()
+ with pytest.raises(RuntimeError):
+ loader._download_executor.submit(lambda: None)