Skip to content

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.

fix(model cache): make_room honors the admission grace

Lincoln Steinaa0f35ad48d2
diff --git a/invokeai/backend/model_manager/load/model_cache/model_cache.py b/invokeai/backend/model_manager/load/model_cache/model_cache.py
index e737c8b7af..b9119e61b4 100644
--- a/invokeai/backend/model_manager/load/model_cache/model_cache.py
+++ b/invokeai/backend/model_manager/load/model_cache/model_cache.py
@@ -578,8 +578,10 @@ class ModelCache:
)
# Clear the cache by requesting a very large amount of space.
# This is the same logic used by the "Clear Model Cache" button.
- # Using 1000 GB ensures all unlocked models are removed.
- self._make_room_internal(1000 * GB)
+ # Using 1000 GB ensures all unlocked models are removed. A surviving admission grace
+ # is abandoned by definition here — a healthy loader locks within seconds and every
+ # lock resets the keep-alive timer — so the timeout clear ignores it.
+ self._make_room_internal(1000 * GB, spare_awaiting_first_use=False)
elif len(self._cached_models) > 0:
# All models are locked, don't log at info level
self._logger.debug(
@@ -1085,9 +1087,10 @@ class ModelCache:
the last pass's.
"""
if cache_entry.key not in self._cached_models:
- # Same diagnostic as lock()/unlock() (issue 7513): a detached record's continuation
- # passes should not run silently.
- self._logger.info(
+ # Same diagnostic as lock()/unlock() (issue 7513) — but at DEBUG: lock() already said
+ # it once at INFO, and a paced stream repeats this method dozens of times, which turned
+ # one detached record into a page of identical log lines.
+ self._logger.debug(
f"Continuing paced lock of model cache entry {cache_entry.key} "
f"(Type: {cache_entry.cached_model.model.__class__.__name__}), but it has already been dropped from "
"the RAM cache. This is a sign that the model loading order is non-optimal in the invocation code "
@@ -1662,8 +1665,12 @@ class ModelCache:
"""
return self._make_room_internal(bytes_needed)
- def _make_room_internal(self, bytes_needed: int) -> CacheClearResult:
- """Internal implementation of make_room(). Assumes the lock is already held."""
+ 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.
+
+ `spare_awaiting_first_use=False` (the keep-alive timeout clear) also evicts entries whose
+ admission grace was never released — abandoned by definition after an idle period.
+ """
self._logger.debug(f"Making room for {bytes_needed / MB:.2f}MB of RAM.")
self._log_cache_state(title="Before dropping models:")
@@ -1688,7 +1695,16 @@ class ModelCache:
model_key = self._cache_stack[pos]
cache_entry = self._cached_models[model_key]
- if not cache_entry.is_locked:
+ # awaiting_first_use marks the window between put() and the loader's first lock() —
+ # a window a SINGLE worker thread can re-enter this method inside, because multi-model
+ # invocations load their whole set before locking any of it (e.g. the H3 text encoder
+ # loads text_encoder, then tokenizer, then processor; the tokenizer's cold-load
+ # make_room runs with the 27GB text encoder admitted but not yet locked). Evicting
+ # such an entry frees NOTHING — the loader's handle keeps the model alive — while
+ # detaching the record from all cache accounting and turning every subsequent lock
+ # pass into an issue-7513 diagnostic. The asynchronous eviction paths (budget
+ # reconcile, peer eviction) already honor the grace; the synchronous path must too.
+ if not cache_entry.is_locked and not (spare_awaiting_first_use and cache_entry.awaiting_first_use):
ram_bytes_freed += cache_entry.cached_model.total_bytes()
self._logger.debug(
f"Dropping {model_key} from RAM cache to free {(cache_entry.cached_model.total_bytes() / MB):.2f}MB."
diff --git a/tests/backend/model_manager/load/model_cache/test_model_cache_drop_model.py b/tests/backend/model_manager/load/model_cache/test_model_cache_drop_model.py
index 17c674c235..047a3c7be9 100644
--- a/tests/backend/model_manager/load/model_cache/test_model_cache_drop_model.py
+++ b/tests/backend/model_manager/load/model_cache/test_model_cache_drop_model.py
@@ -172,6 +172,12 @@ def test_drop_model_updates_stats_and_fires_callbacks(cache: ModelCache):
def test_make_room_returns_clear_result_and_updates_current_cache_usage(cache: ModelCache):
cache.put("model-a", torch.nn.Linear(4, 4))
cache.put("model-b", torch.nn.Linear(4, 4))
+ # Release the admission grace the way a real loader does — make_room spares entries still
+ # awaiting their first lock (the loader's handle keeps them alive; evicting frees nothing).
+ for key in ("model-a", "model-b"):
+ record = cache.get(key)
+ cache.lock(record, None)
+ cache.unlock(record)
cache.stats = CacheStats()
before_bytes = cache._get_ram_in_use()
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.py
new file mode 100644
index 0000000000..c8547d0780
--- /dev/null
+++ b/tests/backend/model_manager/load/model_cache/test_model_cache_make_room.py
@@ -0,0 +1,76 @@
+"""Tests for make_room()'s eviction guards."""
+
+import logging
+from unittest.mock import MagicMock
+
+import torch
+
+from invokeai.backend.model_manager.load.model_cache.model_cache import ModelCache
+from tests.backend.model_manager.load.model_cache.cached_model.utils import DummyModule
+
+
+def _make_cache() -> ModelCache:
+ logger = MagicMock()
+ logger.getEffectiveLevel.return_value = logging.INFO
+ return ModelCache(
+ execution_device_working_mem_gb=1.0,
+ enable_partial_loading=False,
+ keep_ram_copy_of_weights=True,
+ execution_device="cpu",
+ storage_device="cpu",
+ logger=logger,
+ )
+
+
+def test_make_room_spares_entries_awaiting_first_use():
+ """A just-admitted entry (put() done, first lock() pending) must survive make_room: the
+ loader's handle keeps the model alive anyway — multi-model invocations load their whole set
+ before locking any of it, so a sibling's cold-load make_room runs inside this window — and
+ evicting it frees nothing while detaching the record from all cache accounting."""
+ cache = _make_cache()
+ cache.put("fresh", DummyModule())
+ record = cache.get("fresh")
+
+ # Precondition: the admission grace is armed (the deferred worker is running in-process).
+ assert record.awaiting_first_use
+
+ cache.make_room(10**15)
+ assert "fresh" in cache._cached_models, "make_room evicted an entry still awaiting its first lock"
+
+ # After the first lock/unlock cycle the grace is released and the entry is ordinary cache
+ # content again.
+ cache.lock(record, None)
+ cache.unlock(record)
+ assert not record.awaiting_first_use
+
+ cache.make_room(10**15)
+ assert "fresh" not in cache._cached_models
+
+
+def test_make_room_still_evicts_ordinary_unlocked_entries():
+ cache = _make_cache()
+ cache.put("used", DummyModule())
+ record = cache.get("used")
+ cache.lock(record, None)
+ cache.unlock(record)
+
+ cache.make_room(10**15)
+ assert "used" not in cache._cached_models
+
+
+def test_make_room_never_evicts_locked_entries():
+ cache = _make_cache()
+ cache.put("held", DummyModule())
+ record = cache.get("held")
+ cache.lock(record, None)
+ try:
+ cache.make_room(10**15)
+ assert "held" in cache._cached_models
+ finally:
+ 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
diff --git a/tests/backend/model_manager/load/model_cache/test_model_cache_shared_weights.py b/tests/backend/model_manager/load/model_cache/test_model_cache_shared_weights.py
index 2c75a68b98..69824536ce 100644
--- a/tests/backend/model_manager/load/model_cache/test_model_cache_shared_weights.py
+++ b/tests/backend/model_manager/load/model_cache/test_model_cache_shared_weights.py
@@ -53,12 +53,19 @@ def test_two_device_caches_share_one_cpu_copy(mock_logger: MagicMock):
assert sd_a is sd_b
# Evicting from one device drops only its reference; the weights stay for the other.
+ # (Release the admission grace first: make_room spares entries awaiting their first lock.)
+ record_a = cache_a.get("m")
+ cache_a.lock(record_a, None)
+ cache_a.unlock(record_a)
cache_a.make_room(10**12)
assert "m" not in cache_a._cached_models
assert store.refcount("m") == 1
assert "m" in store
# Evicting from the last device frees the shared RAM.
+ record_b = cache_b.get("m")
+ cache_b.lock(record_b, None)
+ cache_b.unlock(record_b)
cache_b.make_room(10**12)
assert store.refcount("m") == 0
assert "m" not in store