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.

feat(model-cache): report clear results and current usage

joshistoasta10384504d59
diff --git a/invokeai/app/api/routers/model_manager.py b/invokeai/app/api/routers/model_manager.py
index 09dada7f8c..a1c47b4e72 100644
--- a/invokeai/app/api/routers/model_manager.py
+++ b/invokeai/app/api/routers/model_manager.py
@@ -68,6 +68,11 @@ class ModelsList(BaseModel):
model_config = ConfigDict(use_enum_values=True)
+class EmptyModelCacheResponse(BaseModel):
+ models_cleared: int
+ bytes_freed: int
+
+
class CacheType(str, Enum):
"""Cache type - one of vram or ram."""
@@ -1320,12 +1325,14 @@ async def get_stats() -> Optional[CacheStats]:
"/empty_model_cache",
operation_id="empty_model_cache",
status_code=200,
+ response_model=EmptyModelCacheResponse,
)
-async def empty_model_cache(current_admin: AdminUserOrDefault) -> None:
+async def empty_model_cache(current_admin: AdminUserOrDefault) -> EmptyModelCacheResponse:
"""Drop all models from the model cache to free RAM/VRAM. 'Locked' models that are in active use will not be dropped."""
# Request 1000GB of room in order to force the cache to drop all models.
ApiDependencies.invoker.services.logger.info("Emptying model cache.")
- ApiDependencies.invoker.services.model_manager.load.ram_cache.make_room(1000 * 2**30)
+ result = ApiDependencies.invoker.services.model_manager.load.ram_cache.make_room(1000 * 2**30)
+ return EmptyModelCacheResponse(models_cleared=result.models_cleared, bytes_freed=result.bytes_freed)
class HFTokenStatus(str, Enum):
diff --git a/invokeai/backend/model_manager/load/model_cache/cache_stats.py b/invokeai/backend/model_manager/load/model_cache/cache_stats.py
index 4998ac6c77..c339d3b7ad 100644
--- a/invokeai/backend/model_manager/load/model_cache/cache_stats.py
+++ b/invokeai/backend/model_manager/load/model_cache/cache_stats.py
@@ -9,6 +9,7 @@ class CacheStats(object):
hits: int = 0 # cache hits
misses: int = 0 # cache misses
high_watermark: int = 0 # amount of cache used
+ cache_used: int = 0 # current amount of cache used
in_cache: int = 0 # number of models in cache
cleared: int = 0 # number of models cleared to make space
cache_size: int = 0 # total size of cache
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 e3a0928e52..6b5da65984 100644
--- a/invokeai/backend/model_manager/load/model_cache/model_cache.py
+++ b/invokeai/backend/model_manager/load/model_cache/model_cache.py
@@ -77,6 +77,12 @@ class CacheEntrySnapshot:
current_vram_bytes: int
+@dataclass(frozen=True)
+class CacheClearResult:
+ models_cleared: int
+ bytes_freed: int
+
+
class CacheMissCallback(Protocol):
def __call__(
self,
@@ -360,6 +366,7 @@ class ModelCache:
cache_record = CacheRecord(key=key, cached_model=wrapped_model)
self._cached_models[key] = cache_record
self._cache_stack.append(key)
+ 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)"
)
@@ -378,6 +385,11 @@ class ModelCache:
return overview
+ def _sync_current_stats(self) -> None:
+ if self.stats:
+ self.stats.cache_used = self._get_ram_in_use()
+ self.stats.in_cache = len(self._cached_models)
+
@synchronized
@record_activity
def get(self, key: str, stats_name: Optional[str] = None) -> CacheRecord:
@@ -405,6 +417,7 @@ class ModelCache:
if self.stats:
stats_name = stats_name or key
self.stats.high_watermark = max(self.stats.high_watermark, self._get_ram_in_use())
+ self.stats.cache_used = self._get_ram_in_use()
self.stats.in_cache = len(self._cached_models)
self.stats.loaded_model_sizes[stats_name] = max(
self.stats.loaded_model_sizes.get(stats_name, 0), cache_entry.cached_model.total_bytes()
@@ -485,6 +498,7 @@ class ModelCache:
self._delete_cache_entry(cache_entry)
if self.stats:
self.stats.cleared = (self.stats.cleared or 0) + 1
+ self._sync_current_stats()
snapshot = self._get_cache_snapshot()
for cb in self._on_cache_models_cleared_callbacks:
cb(
@@ -820,16 +834,16 @@ class ModelCache:
self._logger.debug(log)
@synchronized
- def make_room(self, bytes_needed: int) -> None:
+ def make_room(self, bytes_needed: int) -> 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 are
external references to the model, there's nothing that the cache can do about it, and those models will not be
garbage-collected.
"""
- self._make_room_internal(bytes_needed)
+ return self._make_room_internal(bytes_needed)
- def _make_room_internal(self, bytes_needed: int) -> None:
+ def _make_room_internal(self, bytes_needed: int) -> CacheClearResult:
"""Internal implementation of make_room(). Assumes the lock is already held."""
self._logger.debug(f"Making room for {bytes_needed / MB:.2f}MB of RAM.")
self._log_cache_state(title="Before dropping models:")
@@ -878,9 +892,12 @@ class ModelCache:
)
gc.collect()
+ self._sync_current_stats()
+
TorchDevice.empty_cache()
self._logger.debug(f"Dropped {models_cleared} models to free {ram_bytes_freed / MB:.2f}MB of RAM.")
self._log_cache_state(title="After dropping models:")
+ return CacheClearResult(models_cleared=models_cleared, bytes_freed=ram_bytes_freed)
def _delete_cache_entry(self, cache_entry: CacheRecord) -> None:
"""Delete cache_entry from the cache if it exists. No exception is thrown if it doesn't exist."""
@@ -918,6 +935,7 @@ class ModelCache:
if dropped:
if self.stats:
self.stats.cleared = len(dropped)
+ self._sync_current_stats()
snapshot = self._get_cache_snapshot()
for cb in self._on_cache_models_cleared_callbacks:
cb(
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 1a2ba34c01..17c674c235 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
@@ -169,6 +169,34 @@ def test_drop_model_updates_stats_and_fires_callbacks(cache: ModelCache):
assert kwargs["bytes_freed"] > 0
+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))
+ cache.stats = CacheStats()
+ before_bytes = cache._get_ram_in_use()
+
+ result = cache.make_room(1000 * 2**30)
+
+ assert result.models_cleared == 2
+ assert result.bytes_freed == before_bytes
+ assert cache.stats.in_cache == 0
+ assert cache.stats.cache_used == 0
+
+
+def test_make_room_reports_noop_when_all_models_are_locked(cache: ModelCache):
+ cache.put("model-a", torch.nn.Linear(4, 4))
+ entry = cache._cached_models["model-a"]
+ entry.lock()
+ cache.stats = CacheStats()
+
+ result = cache.make_room(1000 * 2**30)
+
+ assert result.models_cleared == 0
+ assert result.bytes_freed == 0
+ assert cache.stats.in_cache == 1
+ assert cache.stats.cache_used > 0
+
+
def test_unlock_stale_eviction_updates_stats_and_fires_callbacks(cache: ModelCache):
"""Stale-entry eviction is also a cache change observers care about."""
model_key = "abc123"