Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
fix(model cache): tie the admission grace to its LoadedModel handle
Lincoln Stein0dc9a51913d4
diff --git a/invokeai/app/api/routers/model_manager.py b/invokeai/app/api/routers/model_manager.pyindex 713a26cc92..3e2abab220 100644--- a/invokeai/app/api/routers/model_manager.py+++ b/invokeai/app/api/routers/model_manager.py@@ -1524,7 +1524,9 @@ def empty_model_cache(current_admin: AdminUserOrDefault) -> EmptyModelCacheRespoif id(cache) in seen_cache_ids:continueseen_cache_ids.add(id(cache))- result = cache.make_room(1000 * 2**30)+ # spare_awaiting_first_use=False: the user asked for a full clear, which outranks the+ # admission grace (an in-flight loader survives via the tolerated issue-7513 path).+ result = cache.make_room(1000 * 2**30, spare_awaiting_first_use=False)models_cleared += result.models_clearedbytes_freed += result.bytes_freedreturn EmptyModelCacheResponse(models_cleared=models_cleared, bytes_freed=bytes_freed)diff --git a/invokeai/backend/model_manager/load/load_base.py b/invokeai/backend/model_manager/load/load_base.pyindex 98d7681f8c..c073dcf70c 100644--- a/invokeai/backend/model_manager/load/load_base.py+++ b/invokeai/backend/model_manager/load/load_base.py@@ -4,6 +4,7 @@ Base class for model loading in InvokeAI."""import time+import weakreffrom abc import ABC, abstractmethodfrom contextlib import contextmanagerfrom logging import Logger@@ -69,6 +70,9 @@ class LoadedModelWithoutConfig:)if self._first_use_finalizer is not None:self._first_use_finalizer.atexit = False+ # This handle owns the grace: put()'s sweep keeps a grace whose holder is alive+ # (an in-flight multi-model load) and clears one whose holder is gone.+ cache_record.grace_holder = weakref.ref(self)def _lock_paced(self, working_mem_bytes: Optional[int]) -> None:"""Move the model into VRAM in bounded passes, yielding the global load lock between them.diff --git a/invokeai/backend/model_manager/load/model_cache/cache_record.py b/invokeai/backend/model_manager/load/model_cache/cache_record.pyindex a266cdb79e..5f2340931e 100644--- a/invokeai/backend/model_manager/load/model_cache/cache_record.py+++ b/invokeai/backend/model_manager/load/model_cache/cache_record.py@@ -1,3 +1,4 @@+import weakreffrom dataclasses import dataclassfrom invokeai.backend.model_manager.load.model_cache.cached_model.cached_model_only_full_load import (@@ -24,20 +25,32 @@ class CacheRecord:is_stale: bool = False# Post-admission grace: set by ModelCache.put() (unless the admission is a prefetch of a# model nothing will come back for) and cleared on the entry's first lock(). A freshly- # admitted model is about to be used — its loader calls get() as soon as put() returns, then- # locks it for inference — so the asynchronous eviction paths (shared-budget reconcile,- # peer-requested eviction) must not treat it as idle: they would evict the record out from- # under the in-flight load, breaking the loader's get() or detaching a live model from the- # cache's RAM accounting. The grace deliberately survives get(): get() is synchronized, and- # its own lock-release hook may run a pending reconcile before the caller can lock the record- # it was just handed. The flag cannot shield a record forever: the cache's local make_room- # path ignores it (cold loads are serialized under MODEL_LOAD_LOCK, so make_room can never- # see another loader's entry inside the put()->lock() window), and the next admission on the- # same cache clears any flag still standing (see the sweep in ModelCache.put()), so a load- # that errors out — or a LoadedModel dropped without ever locking — cannot dodge budget- # reconciles indefinitely.+ # admitted model is about to be used — its loader calls get() as soon as put() returns,+ # constructs a LoadedModel handle, and locks it for inference — so no eviction path+ # (make_room, shared-budget reconcile, peer-requested eviction) may treat it as idle:+ # evicting it frees nothing (the handle keeps the model alive) while detaching the record+ # from the cache's RAM accounting. The window is NOT confined to a single load: multi-model+ # invocations load their whole set (e.g. text encoder, then tokenizer, then processor)+ # before locking any of it, so a sibling's cold load legitimately runs make_room — and+ # put() — while earlier entries sit graced with live handles. The grace deliberately+ # survives get(): get() is synchronized, and its own lock-release hook may run a pending+ # reconcile before the caller can lock the record it was just handed.+ #+ # The flag cannot shield a record forever. Its owner is the LoadedModel handle+ # (`grace_holder` below): a dropped handle releases the grace through its finalizer, and+ # ModelCache.put()'s sweep clears any grace that is provably orphaned — no handle was ever+ # registered (the load raised between put() and LoadedModel construction), or the handle+ # died without its finalizer running (deferred worker lost) — so an orphaned record cannot+ # dodge budget reconciles indefinitely. The keep-alive timeout clear also ignores the grace:+ # after an idle period it is abandoned by definition.awaiting_first_use: bool = False+ # Weak reference to the LoadedModel handle that owns `awaiting_first_use`, registered at+ # handle construction (see LoadedModelWithoutConfig.__init__). None until then — which is+ # exactly what put()'s sweep uses to tell an in-flight sibling (live holder: keep the grace)+ # from an orphaned admission (no holder, or a dead one: clear it).+ grace_holder: "weakref.ref[object] | None" = None+def lock(self) -> None:"""Lock this record."""self._locks += 1diff --git a/invokeai/backend/model_manager/load/model_cache/model_cache.py b/invokeai/backend/model_manager/load/model_cache/model_cache.pyindex b9119e61b4..79d0436144 100644--- a/invokeai/backend/model_manager/load/model_cache/model_cache.py+++ b/invokeai/backend/model_manager/load/model_cache/model_cache.py@@ -637,16 +637,23 @@ class ModelCache:# unused cache.self._ensure_deferred_worker()- # Any entry still carrying the post-admission grace belongs to an earlier load: cold loads- # are serialized under MODEL_LOAD_LOCK's write lock and each load's only graced put() is- # its final one, so a flag that survives to the next admission is stale — its loader- # either errored out before retrieving the model or dropped the LoadedModel without ever- # locking it. Clear such flags so an orphaned record cannot dodge budget reconciles- # indefinitely. (An entry retrieved but not yet locked loses its shield here; if a- # reconcile then evicts it, lock() falls back to the tolerated issue-7513 path and- # proceeds on the detached record.)+ # A grace that survives to the next admission is NOT necessarily stale: multi-model+ # invocations load their whole set (text encoder, then tokenizer, then processor) before+ # locking any of it, so earlier siblings' graces legitimately outlive later puts — and+ # sweeping them let a sibling's make_room evict a just-admitted multi-GB model to fit a+ # tiny one, freeing nothing (the loader's handle keeps it alive) while detaching the+ # record from all accounting. The grace's owner is the LoadedModel handle: clear only+ # provably orphaned graces — no handle was ever registered (the load raised between+ # put() and LoadedModel construction), or the handle died without its finalizer running+ # (deferred worker lost). A live holder means lock() or the finalizer will release the+ # grace. (Residual race, tolerated via the issue-7513 path: a sibling's put() landing in+ # the instructions between a load's MODEL_LOAD_LOCK release and its LoadedModel+ # construction sees a grace with no holder yet and sweeps it.)for stale_entry in self._cached_models.values():- stale_entry.awaiting_first_use = False+ if not stale_entry.awaiting_first_use:+ continue+ if stale_entry.grace_holder is None or stale_entry.grace_holder() is None:+ stale_entry.awaiting_first_use = Falsesize = calc_model_size_by_data(self._logger, model)self._make_room_internal(size)@@ -1656,14 +1663,18 @@ class ModelCache:self._logger.debug(log)@synchronized- def make_room(self, bytes_needed: int) -> CacheClearResult:+ def make_room(self, bytes_needed: int, spare_awaiting_first_use: bool = True) -> CacheClearResult:"""Make enough room in the cache to accommodate a new model of indicated size.Note: This function deletes all of the cache's internal references to a model in order to free it. If there areexternal references to the model, there's nothing that the cache can do about it, and those models will not begarbage-collected.++ `spare_awaiting_first_use=False` (the explicit clear-cache paths) also evicts entries+ still inside their admission grace — a user asking for a full clear outranks the grace,+ and the tolerated issue-7513 path covers an in-flight loader."""- return self._make_room_internal(bytes_needed)+ return self._make_room_internal(bytes_needed, spare_awaiting_first_use=spare_awaiting_first_use)def _make_room_internal(self, bytes_needed: int, spare_awaiting_first_use: bool = True) -> CacheClearResult:"""Internal implementation of make_room(). Assumes the lock is already held.diff --git a/tests/app/routers/test_model_manager.py b/tests/app/routers/test_model_manager.pyindex c8ffee2801..8165d78d5e 100644--- a/tests/app/routers/test_model_manager.py+++ b/tests/app/routers/test_model_manager.py@@ -284,7 +284,7 @@ def test_empty_model_cache_aggregates_per_device_results(monkeypatch: Any, clienself._result = CacheClearResult(models_cleared=models_cleared, bytes_freed=bytes_freed)self.requested: list[int] = []- def make_room(self, bytes_needed: int) -> CacheClearResult:+ def make_room(self, bytes_needed: int, spare_awaiting_first_use: bool = True) -> CacheClearResult:self.requested.append(bytes_needed)return self._result@@ -313,7 +313,7 @@ def test_empty_model_cache_clears_duplicate_cache_objects_once(monkeypatch: Any,def __init__(self) -> None:self.calls = 0- def make_room(self, bytes_needed: int) -> CacheClearResult:+ def make_room(self, bytes_needed: int, spare_awaiting_first_use: bool = True) -> CacheClearResult:self.calls += 1return CacheClearResult(models_cleared=2, bytes_freed=100)diff --git a/tests/backend/model_manager/load/model_cache/test_model_cache_make_room.py b/tests/backend/model_manager/load/model_cache/test_model_cache_make_room.pyindex c8547d0780..abb298f5f5 100644--- a/tests/backend/model_manager/load/model_cache/test_model_cache_make_room.py+++ b/tests/backend/model_manager/load/model_cache/test_model_cache_make_room.py@@ -1,10 +1,11 @@"""Tests for make_room()'s eviction guards."""+import gcimport logging+import timefrom unittest.mock import MagicMock-import torch-+from invokeai.backend.model_manager.load.load_base import LoadedModelWithoutConfigfrom invokeai.backend.model_manager.load.model_cache.model_cache import ModelCachefrom tests.backend.model_manager.load.model_cache.cached_model.utils import DummyModule@@ -70,7 +71,82 @@ def test_make_room_never_evicts_locked_entries():cache.unlock(record)-def test_dummy_module_is_cpu():- # Guard against the fixture silently needing CUDA: everything above must run CPU-only.- assert not any(p.is_cuda for p in DummyModule().parameters())- assert torch.cuda.is_available() or True+def test_grace_survives_sibling_admissions_while_the_handle_lives():+ """Multi-model invocations load their whole set before locking any of it: an earlier+ sibling's grace must survive later puts (whose sweep previously cleared every grace) and the+ make_rooms they trigger, for as long as its LoadedModel handle is alive."""+ cache = _make_cache()+ cache.put("first", DummyModule())+ record = cache.get("first")+ handle = LoadedModelWithoutConfig(cache_record=record, cache=cache)++ # Two more siblings admitted — each put() runs the stale-grace sweep and a make_room.+ cache.put("second", DummyModule())+ cache.put("third", DummyModule())+ assert record.awaiting_first_use, "a sibling's put() swept a grace whose handle is alive"++ cache.make_room(10**15)+ assert "first" in cache._cached_models++ # The handle finally locks: grace released, ordinary cache content again.+ with handle:+ pass+ assert not record.awaiting_first_use+ cache.make_room(10**15)+ assert "first" not in cache._cached_models+++def test_sweep_clears_orphaned_graces():+ """A grace with no registered handle (the load raised between put() and LoadedModel+ construction) — or whose handle died without its finalizer running (lost deferred worker) —+ is orphaned, and the next admission's sweep must clear it so the record cannot dodge budget+ reconciles indefinitely."""+ cache = _make_cache()++ # No handle ever registered.+ cache.put("orphan", DummyModule())+ orphan = cache.get("orphan")+ assert orphan.grace_holder is None+ cache.put("sibling", DummyModule())+ assert not orphan.awaiting_first_use++ # Handle registered, then dies with its finalizer disarmed (simulated lost worker).+ cache.put("undead", DummyModule())+ undead = cache.get("undead")+ handle = LoadedModelWithoutConfig(cache_record=undead, cache=cache)+ assert handle._first_use_finalizer is not None+ handle._first_use_finalizer.detach()+ del handle+ gc.collect()+ assert undead.grace_holder is not None and undead.grace_holder() is None+ cache.put("sibling-2", DummyModule())+ assert not undead.awaiting_first_use+++def test_dropped_handle_releases_the_grace_through_its_finalizer():+ cache = _make_cache()+ cache.put("dropped", DummyModule())+ record = cache.get("dropped")+ handle = LoadedModelWithoutConfig(cache_record=record, cache=cache)++ del handle+ gc.collect()+ # The finalizer dispatches the release through the deferred worker; give it a moment.+ for _ in range(100):+ if not record.awaiting_first_use:+ break+ time.sleep(0.02)+ assert not record.awaiting_first_use+++def test_explicit_clear_ignores_the_grace():+ """The clear-model-cache button path (spare_awaiting_first_use=False) evicts graced+ entries too — a user-requested full clear outranks the grace."""+ cache = _make_cache()+ cache.put("fresh", DummyModule())+ record = cache.get("fresh")+ assert record.awaiting_first_use++ result = cache.make_room(10**15, spare_awaiting_first_use=False)+ assert "fresh" not in cache._cached_models+ assert result.models_cleared == 1