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): sync stats on the peer-eviction paths
joshistoastd127f27a9acd
diff --git a/invokeai/backend/model_manager/load/model_cache/model_cache.py b/invokeai/backend/model_manager/load/model_cache/model_cache.pyindex b78a41f953..40bba44e88 100644--- a/invokeai/backend/model_manager/load/model_cache/model_cache.py+++ b/invokeai/backend/model_manager/load/model_cache/model_cache.py@@ -647,7 +647,6 @@ class ModelCache:# total (a non-shared model resident on N devices correctly counts N times).if self._ram_budget is not None and not wrapped_model.uses_shared_weights:self._ram_budget.add_non_shared(wrapped_model.total_bytes(), cache=self)- self._sync_current_stats()self._logger.debug(f"Added model {key} (Type: {model.__class__.__name__}, Wrap mode: {wrapped_model.__class__.__name__}, Model size: {size / MB:.2f}MB)")@@ -670,6 +669,11 @@ class ModelCache:# everything unlocked, so the only entry a self-reconcile could ever claim is the# model just admitted — evicting it out from under its own loader.)+ # Synced last, not right after the model is counted: request_budget_reconcile() above can+ # evict inline on a peer, and cache_used reads the shared budget's global usage, so syncing+ # before that loop would report a pre-reconcile (too high) figure.+ self._sync_current_stats()+def cached_model_keys(self) -> set[str]:"""Return the base model keys of every model currently resident in this cache.@@ -1498,6 +1502,15 @@ class ModelCache:)self._delete_cache_entry(cache_entry)models_cleared += 1+ if models_cleared > 0:+ # Peer eviction mutates residency just like make_room/unlock/drop_model, so it owes+ # the same stat sync. Without it this cache reports a stale cache_used/in_cache+ # until its device next runs a session — and because the /models/stats aggregate+ # takes max(cache_used) across per-device caches, one stale idle cache pins the+ # reported usage high for the whole system.+ self._sync_current_stats()+ if self.stats:+ self.stats.cleared = (self.stats.cleared or 0) + models_clearedreturn models_clearedfinally:self._lock.release()@@ -1571,6 +1584,13 @@ class ModelCache:)self._delete_cache_entry(cache_entry)models_cleared += 1+ if models_cleared > 0:+ # Same reasoning as evict_unlocked_for_peer: this path drops entries outside+ # the synchronized methods that normally re-sync, so it must do so itself+ # while the lock is still held.+ self._sync_current_stats()+ if self.stats:+ self.stats.cleared = (self.stats.cleared or 0) + models_clearedfinally:self._lock.release()if models_cleared > 0:diff --git a/tests/backend/model_manager/load/model_cache/test_model_cache_ram_budget.py b/tests/backend/model_manager/load/model_cache/test_model_cache_ram_budget.pyindex 656a10be53..16f424a3ae 100644--- a/tests/backend/model_manager/load/model_cache/test_model_cache_ram_budget.py+++ b/tests/backend/model_manager/load/model_cache/test_model_cache_ram_budget.py@@ -332,6 +332,84 @@ def test_cache_stats_reflect_shared_global_budget(mock_logger):# system high watermark is their max — not their sum.assert cache_a.stats.high_watermark == Sassert cache_b.stats.high_watermark == S+ # cache_used is system-wide for the same reason, and is the field the aggregate reports as+ # *current* usage. Asserted here because it is the one the aggregate takes a max() over:+ # a cache that stops syncing it silently pins the reported usage for the whole system.+ assert cache_a.stats.cache_used == S+ assert cache_b.stats.cache_used == S+ finally:+ cache_a.shutdown()+ cache_b.shutdown()+++def test_peer_eviction_syncs_the_evicted_caches_stats(mock_logger):+ """A cache evicted on behalf of a peer must re-sync its own stats.++ evict_unlocked_for_peer() is reached from another device's make_room, not from one of this+ cache's synchronized methods, so nothing else re-syncs it. If it does not sync, the evicted+ cache keeps advertising its pre-eviction cache_used/in_cache until its device next runs a+ session — and because /models/stats aggregates cache_used with max() across per-device caches,+ a single stale idle cache reports peak usage for the entire system, which reads as a cache+ that never releases memory."""+ store = SharedCpuWeightsStore()+ budget = RamBudget(max_bytes=int(S * 10), shared_store=store)+ cache_a = _make_cache(store, budget, mock_logger)+ cache_b = _make_cache(store, budget, mock_logger)+ try:+ cache_a.stats = CacheStats()+ cache_b.stats = CacheStats()+ cache_a.put("a1", DummyModule())+ cache_b.put("b1", DummyModule())+ _use_and_release(cache_a, "a1")+ _use_and_release(cache_b, "b1")+ # Two distinct models resident across the two devices: global usage is 2S, and b holds one.+ assert budget.total_in_use() == 2 * S+ assert cache_b.stats.in_cache == 1+ assert cache_b.stats.cache_used == 2 * S++ # The multi-GPU path: a's own evictable entries are exhausted, so it asks b to shed.+ # `is_satisfied` never returns True, so b drops every unlocked entry it has.+ assert cache_b.evict_unlocked_for_peer(is_satisfied=lambda: False) == 1+ assert "b1" not in cache_b._cached_models+ assert budget.total_in_use() == S++ assert cache_b.stats.in_cache == 0+ assert cache_b.stats.cache_used == S+ # Peer evictions are real evictions and must be counted; otherwise `cleared` only ever+ # reflects the requesting cache and under-reports system-wide.+ assert cache_b.stats.cleared == 1+ finally:+ cache_a.shutdown()+ cache_b.shutdown()+++def test_budget_reconcile_syncs_the_reconciling_caches_stats(mock_logger):+ """The deferred-reconcile path drops entries outside any synchronized method too, so it owes+ the same stat sync as evict_unlocked_for_peer (same defect, second door)."""+ store = SharedCpuWeightsStore()+ budget = RamBudget(max_bytes=int(S * 10), shared_store=store)+ cache_a = _make_cache(store, budget, mock_logger)+ cache_b = _make_cache(store, budget, mock_logger)+ try:+ cache_b.stats = CacheStats()+ cache_a.put("a1", DummyModule())+ cache_b.put("b1", DummyModule())+ _use_and_release(cache_a, "a1")+ _use_and_release(cache_b, "b1")+ assert cache_b.stats.in_cache == 1+ assert cache_b.stats.cache_used == 2 * S++ # Drive the budget negative so a pending reconcile actually evicts, then ask b to honor it+ # exactly as a peer's post-admission request would. The cap is lowered directly because+ # RamBudget exposes max_bytes read-only; reaching this state through admissions would only+ # add setup without exercising anything more.+ budget._max_bytes = int(S * 0.5)+ cache_b.request_budget_reconcile()++ assert _wait_until(lambda: "b1" not in cache_b._cached_models)+ assert cache_b.stats.in_cache == 0+ assert cache_b.stats.cache_used == budget.total_in_use()+ assert cache_b.stats.cleared == 1finally:cache_a.shutdown()cache_b.shutdown()