Open-source inference server and production cluster for all the models your agent needs.
Python bgecolbertdata-pipelinedeep-learningembeddingsinferenceinference-serverinformation-retrievalllmmlmlopsnatural-language-processingnlppythonrerankingretrievalretrieval-augmented-generationsemantic-searchspladevector-search
fix(server): count an eviction that finishes during an OOM retry (#987)
Krisztian Gajdar26adb39377e9
diff --git a/packages/sie_server/src/sie_server/core/registry.py b/packages/sie_server/src/sie_server/core/registry.pyindex ac3ef9549..ae312a67a 100644--- a/packages/sie_server/src/sie_server/core/registry.py+++ b/packages/sie_server/src/sie_server/core/registry.py@@ -1628,7 +1628,8 @@ class ModelRegistry:- Runs the blocking load in a thread pool to avoid blocking the event loop- After an OOM, releases the failed attempt and evicts LRU models untiltwice the memory that attempt had is free, retrying while any unpinned- model is left to evict+ model is left to evict; a model another eviction removed during the+ attempt counts as evicted- On-demand config discovery: rescans models_dir if model not found- Dependency checking: verifies model deps match installed packages@@ -1787,6 +1788,7 @@ class ModelRegistry:while True:await self._wait_for_unloads()attempt_free_bytes = memory_manager.get_stats().available_bytes+ attempt_residents = frozenset(memory_manager.loaded_models)try:loaded = await self._loader.load_and_register_async(name, load_device, adapter, config)break@@ -1795,7 +1797,8 @@ class ModelRegistry:raiseasync with lock:lru_model = memory_manager.get_lru_model(exclude=self._pinned_models)- if lru_model is None:+ resident_left = bool(attempt_residents.difference(memory_manager.loaded_models))+ if lru_model is None and not resident_left:logger.error("OOM loading '%s' but no non-pinned models to evict", name)await self._release_failed_load(adapter, name)raise@@ -1805,7 +1808,9 @@ class ModelRegistry:if not await self._release_failed_load(adapter, name):msg = _ERR_OOM_RELEASE_FAILED.format(oom=oom_message)raise RuntimeError(msg)- if not await self._evict_for_load_retry(name, memory_manager, 2 * attempt_free_bytes):+ if not await self._evict_for_load_retry(+ name, memory_manager, 2 * attempt_free_bytes, attempt_residents+ ):msg = _ERR_OOM_ONLY_RELEASING.format(oom=oom_message)raise RuntimeError(msg)adapter = await self._loader.instantiate_adapter_async(name, config, model_dir, load_device)@@ -1867,8 +1872,20 @@ class ModelRegistry:return Falsereturn True- async def _evict_for_load_retry(self, name: str, memory_manager: MemoryManager, target_free_bytes: int) -> bool:- """Evict LRU non-pinned models until ``target_free_bytes`` are free; False if none could be evicted.+ async def _evict_for_load_retry(+ self,+ name: str,+ memory_manager: MemoryManager,+ target_free_bytes: int,+ attempt_residents: frozenset[str],+ ) -> bool:+ """Evict LRU non-pinned models until ``target_free_bytes`` are free; False if none left the device.++ A model of ``attempt_residents``, the residents when the failed attempt+ began, that is no longer resident counts as evicted, whoever evicted+ it. Memory an eviction already in flight freed is then used instead of+ evicting another model, and the retry is not refused when that+ eviction took the last unpinned model.A model whose optional-memory release is still running is skipped, asthe memory monitor skips it: its unload would join the inference@@ -1876,12 +1893,12 @@ class ModelRegistry:releases are awaited once, up to the release bound."""lock = self._get_load_lock()- evicted = Falseawaited_releases = Falsewhile True:await self._wait_for_unloads()async with lock:stats = memory_manager.get_stats()+ evicted = bool(attempt_residents.difference(memory_manager.loaded_models))if evicted and stats.available_bytes >= target_free_bytes:return Truelru_model = memory_manager.get_lru_model(@@ -1916,7 +1933,6 @@ class ModelRegistry:await asyncio.wait(releasing, timeout=_OPTIONAL_MEMORY_RELEASE_TIMEOUT_S)continueawait self._do_unload(lru_model, reason="load_oom")- evicted = Trueasync def start_load_async(self, name: str, device: str) -> bool:"""Start loading a model in the background (non-blocking).diff --git a/packages/sie_server/tests/core/test_registry_load_oom.py b/packages/sie_server/tests/core/test_registry_load_oom.pyindex 244658ef4..5d1881e46 100644--- a/packages/sie_server/tests/core/test_registry_load_oom.py+++ b/packages/sie_server/tests/core/test_registry_load_oom.py@@ -46,6 +46,9 @@ class _Device:self._footprints: dict[str, int] = {}self._failing_unloads: set[str] = set()self._after_unload: dict[str, Callable[[], None]] = {}+ self._before_load: dict[str, Callable[[], None]] = {}+ self._on_oom: dict[str, Callable[[], None]] = {}+ self._held_unloads: dict[str, tuple[threading.Event, threading.Event]] = {}self.adapters: dict[str, list[MagicMock]] = {}self.stranded_bytes: list[int] = []self.failed_loads: list[str] = []@@ -65,6 +68,20 @@ class _Device:def after_unload(self, name: str, callback: Callable[[], None]) -> None:self._after_unload[name] = callback+ def before_load(self, name: str, callback: Callable[[], None]) -> None:+ """Run ``callback`` at the start of the next load of ``name``, before it allocates."""+ self._before_load[name] = callback++ def on_oom(self, name: str, callback: Callable[[], None]) -> None:+ """Run ``callback`` when the next load of ``name`` runs out of memory, after it records the OOM."""+ self._on_oom[name] = callback++ def hold_unload(self, name: str) -> tuple[threading.Event, threading.Event]:+ """Hold the next unload of ``name`` with its memory still allocated; return (started, release)."""+ started, release = threading.Event(), threading.Event()+ self._held_unloads[name] = (started, release)+ return started, release+def make_adapter(self, name: str) -> MagicMock:footprint = self._footprints[name]adapter = MagicMock()@@ -77,11 +94,17 @@ class _Device:def load(_device: str) -> None:self.stranded_bytes.append(sum(self._partial.values()))+ before = self._before_load.pop(name, None)+ if before is not None:+ before()free = self.total_bytes - self.used_bytes()if footprint > free:partial = _Allocation(self._partial, free)msg = f"CUDA out of memory. Tried to allocate {footprint - partial.nbytes} bytes"self.failed_loads.append(name)+ on_oom = self._on_oom.pop(name, None)+ if on_oom is not None:+ on_oom()raise RuntimeError(msg)held[key] = footprint@@ -91,6 +114,11 @@ class _Device:if name in self._failing_unloads:msg = f"unload of {name} failed"raise RuntimeError(msg)+ hold = self._held_unloads.pop(name, None)+ if hold is not None:+ started, release = hold+ started.set()+ release.wait(5)held.pop(key, None)if name in self._after_unload:self._after_unload[name]()@@ -384,3 +412,88 @@ async def test_cancelling_the_load_while_the_attempt_is_released_still_unloads_iassert cancelled.is_set()device.adapters["new"][0].unload.assert_called_once()assert registry.loaded_model_names == ["pinned", "cold"]+++async def test_load_that_starts_during_an_eviction_waits_for_its_memory() -> None:+ device = _Device(total_bytes=10 * GIB)+ registry = await _registry(+ device,+ {"pinned": 2 * GIB, "cold": 4 * GIB, "new": 5 * GIB},+ pinned=["pinned"],+ resident=["pinned", "cold"],+ )+ started, release = device.hold_unload("cold")+ eviction = asyncio.create_task(registry.unload_async("cold", reason="memory_pressure"))+ assert await asyncio.to_thread(started.wait, 5)++ load = asyncio.create_task(registry.load_now("new", "cpu"))+ await asyncio.sleep(0.1)+ assert not load.done()++ release.set()+ assert await load+ await eviction++ assert registry.loaded_model_names == ["pinned", "new"]+ assert device.failed_loads == []+ assert registry.get_failure("new") is None+++def _evict_during_the_first_attempt(+ registry: ModelRegistry, device: _Device, *, evicted: str, loading: str+) -> list[asyncio.Task[None]]:+ """Evict ``evicted`` while the first load of ``loading`` allocates, as the memory monitor can.++ The attempt runs while the eviction still holds its memory, and the+ eviction's teardown finishes once the attempt has recorded its OOM.+ """+ loop = asyncio.get_running_loop()+ started, release = device.hold_unload(evicted)+ evictions: list[asyncio.Task[None]] = []++ def start_eviction() -> None:+ evictions.append(asyncio.create_task(registry.unload_async(evicted, reason="memory_pressure")))++ def evict_during_the_attempt() -> None:+ loop.call_soon_threadsafe(start_eviction)+ assert started.wait(5)++ device.before_load(loading, evict_during_the_attempt)+ device.on_oom(loading, release.set)+ return evictions+++async def test_retry_uses_the_memory_an_eviction_freed_while_the_attempt_failed() -> None:+ device = _Device(total_bytes=10 * GIB)+ registry = await _registry(+ device,+ {"pinned": 2 * GIB, "cold": 4 * GIB, "new": 5 * GIB},+ pinned=["pinned"],+ resident=["pinned", "cold"],+ )+ evictions = _evict_during_the_first_attempt(registry, device, evicted="cold", loading="new")++ assert await registry.load_now("new", "cpu")+ await asyncio.gather(*evictions)++ assert device.failed_loads == ["new"]+ assert registry.loaded_model_names == ["pinned", "new"]+ assert registry.get_failure("new") is None+++async def test_retry_evicts_nothing_more_when_a_finished_eviction_freed_enough() -> None:+ device = _Device(total_bytes=11 * GIB)+ registry = await _registry(+ device,+ {"pinned": 2 * GIB, "cold": 4 * GIB, "warm": 1 * GIB, "new": 5 * GIB},+ pinned=["pinned"],+ resident=["pinned", "cold", "warm"],+ )+ evictions = _evict_during_the_first_attempt(registry, device, evicted="cold", loading="new")++ assert await registry.load_now("new", "cpu")+ await asyncio.gather(*evictions)++ assert device.failed_loads == ["new"]+ assert registry.loaded_model_names == ["pinned", "warm", "new"]+ assert registry.get_failure("new") is None