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.

chore: merge upstream/main through 01a8315ab6

joshistoasta5ef7ae32aad
diff --cc invokeai/app/api/routers/model_manager.py
index 2e3b2d54dd,09c9a8bca0..c0b7d518ef
--- a/invokeai/app/api/routers/model_manager.py
+++ b/invokeai/app/api/routers/model_manager.py
@@@ -1344,14 -1363,13 +1387,26 @@@ async def get_stats(current_admin: Admi
"/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.
+ # Request 1000GB of room in order to force each per-device cache to drop all models.
ApiDependencies.invoker.services.logger.info("Emptying model cache.")
- 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)
++ models_cleared = 0
++ bytes_freed = 0
++ seen_cache_ids: set[int] = set()
++ # ram_caches can map several device keys to the same cache object; clearing one twice would
++ # report the second (empty) pass and double-count nothing, but the id() guard keeps the totals
++ # honest and matches get_stats above.
+ for cache in ApiDependencies.invoker.services.model_manager.load.ram_caches.values():
- cache.make_room(1000 * 2**30)
++ if id(cache) in seen_cache_ids:
++ continue
++ seen_cache_ids.add(id(cache))
++ result = cache.make_room(1000 * 2**30)
++ models_cleared += result.models_cleared
++ bytes_freed += result.bytes_freed
++ return EmptyModelCacheResponse(models_cleared=models_cleared, bytes_freed=bytes_freed)
class HFTokenStatus(str, Enum):
diff --cc invokeai/app/services/session_queue/session_queue_sqlite.py
index f21c2845af,00e82b3406..149e9c33a3
--- a/invokeai/app/services/session_queue/session_queue_sqlite.py
+++ b/invokeai/app/services/session_queue/session_queue_sqlite.py
@@@ -302,20 -320,105 +320,104 @@@ class SqliteSessionQueue(SessionQueueBa
query = ROUND_ROBIN_DEQUEUE_QUERY if use_round_robin else FIFO_DEQUEUE_QUERY
- with self._db.transaction() as cursor:
- cursor.execute(query)
- result = cast(Union[sqlite3.Row, None], cursor.fetchone())
- if result is None:
- return None
- queue_item = SessionQueueItem.queue_item_from_dict(dict(result))
- queue_item = self._set_queue_item_status(
- item_id=queue_item.item_id, status="in_progress", queue_item=queue_item
- )
+ # Snapshot the claiming device's warm models BEFORE taking the dequeue lock: the lookup
+ # touches the ModelCache lock, which other threads may hold across long operations (VRAM
+ # transfers, cache clears). A slightly stale snapshot is fine for a heuristic; stalling
+ # every worker's dequeue is not. An explicitly configured session_queue_mode=FIFO is a
+ # request for strict insertion order, so it opts out of affinity reordering entirely
+ # (the setting defaults to round_robin, which keeps affinity active for single-user
+ # installs even though they use the FIFO query).
+ if config.session_queue_mode == "round_robin":
+ resident_model_keys = self._get_device_resident_model_keys(device)
+ else:
+ resident_model_keys = set()
+
+ # Hold the dequeue lock across the select-then-claim so concurrent workers (multi-GPU)
+ # cannot select and claim the same pending item. `_set_queue_item_status` already no-ops
+ # if the item was concurrently moved to a terminal state (e.g. canceled), so we only need
+ # to guard against two dequeues racing for the same pending row.
+ with self._dequeue_lock:
+ with self._db.transaction() as cursor:
+ cursor.execute(query)
+ result = cast(Union[sqlite3.Row, None], cursor.fetchone())
+ if result is None:
+ return None
+ queue_item = SessionQueueItem.queue_item_from_dict(dict(result))
+ queue_item = self._apply_device_affinity(queue_item, resident_model_keys)
+ # Record the claiming worker's device so the UI can label the item by GPU. Passing the
+ # item we already materialized lets _set_queue_item_status patch it in place instead of
+ # re-reading (and re-parsing the session graph of) the row we just read.
+ queue_item = self._set_queue_item_status(
+ item_id=queue_item.item_id, status="in_progress", device=device, queue_item=queue_item
+ )
return queue_item
+ def _apply_device_affinity(self, candidate: SessionQueueItem, resident_keys: set[str]) -> SessionQueueItem:
+ """Swap the fairness-chosen candidate for a nearby same-user, same-priority pending item
+ whose models are already cached on the claiming device, if one exists.
+
+ Cross-device model reloads are expensive (tens of seconds for large models), so when a user
+ has queued a mix of models, preferring an item whose models are warm on the freeing GPU cuts
+ thrash. Fairness is preserved by construction: round-robin decides *which user* is served and
+ priority ordering decides *which tier* of their items is eligible; this heuristic only
+ reorders within that user's equal-priority pending items, and only within
+ AFFINITY_MAX_LOOKAHEAD of the candidate's item_id, so a cold item's deferral is bounded.
+ The caller passes an empty key set to disable affinity (legacy single-device mode, explicit
+ FIFO mode, or cache introspection unavailable).
+ """
+ if not resident_keys:
+ return candidate
+ # Model keys are UUID strings that appear verbatim in the session JSON, so residency can be
+ # scored with substring matches — no need to parse each candidate's session. Sort for
+ # deterministic parameter binding; cap to bound the query if a cache is unexpectedly large.
+ keys = sorted(resident_keys)[:MAX_AFFINITY_MODEL_KEYS]
+ score = " + ".join(["(instr(sq.session, ?) > 0)"] * len(keys))
+ with self._db.transaction() as cursor:
+ cursor.execute(
+ f"""--sql
+ SELECT
+ sq.*,
+ u.display_name AS user_display_name,
+ u.email AS user_email,
+ ({score}) AS affinity
+ FROM session_queue sq
+ LEFT JOIN users u ON sq.user_id = u.user_id
+ WHERE sq.status = 'pending'
+ AND sq.user_id IS ?
+ AND sq.priority = ?
+ AND sq.item_id <= ?
+ ORDER BY affinity DESC, sq.item_id ASC
+ LIMIT 1
+ """,
+ (*keys, candidate.user_id, candidate.priority, candidate.item_id + AFFINITY_MAX_LOOKAHEAD),
+ )
+ row = cast(Union[sqlite3.Row, None], cursor.fetchone())
+ if row is None:
+ return candidate
+ row_dict = dict(row)
+ if not row_dict.pop("affinity", 0) or row_dict["item_id"] == candidate.item_id:
+ # No warm-model item for this user (or the candidate already is one) — keep the
+ # fairness-chosen candidate.
+ return candidate
+ return SessionQueueItem.queue_item_from_dict(row_dict)
+
+ def _get_device_resident_model_keys(self, device: Optional[str]) -> set[str]:
+ """Best-effort lookup of the model keys currently cached for the given generation device."""
+ if device is None:
+ return set()
+ try:
+ cache = self.__invoker.services.model_manager.load.ram_caches.get(device)
+ if cache is None:
+ return set()
+ return set(cache.cached_model_keys())
+ except Exception:
+ # Affinity is purely an optimization — dequeue must never fail because cache
+ # introspection did (e.g. model manager not fully started, or mocked in tests).
+ return set()
+
- def get_next(self, queue_id: str) -> Optional[SessionQueueItem]:
+ def get_next(self, queue_id: str, origin_prefix: Optional[str] = None) -> Optional[SessionQueueItem]:
with self._db.transaction() as cursor:
- cursor.execute(
- """--sql
+ query = """--sql
SELECT
sq.*,
u.display_name as user_display_name,
@@@ -1260,18 -1404,12 +1433,17 @@@
SELECT item_id, session_id, batch_id, user_id
FROM session_queue
WHERE queue_id = ? AND status = 'in_progress'
- LIMIT 1
- """,
- (queue_id,),
- )
+ """
+ current_item_params: list[str] = [queue_id]
+
+ if origin_prefix is not None:
+ current_item_query += " AND origin LIKE ?"
+ current_item_params.append(f"{origin_prefix}%")
+
+ current_item_query += " LIMIT 1"
+ cursor.execute(current_item_query, current_item_params)
current_item = cast(Union[sqlite3.Row, None], cursor.fetchone())
-
total = sum(row[1] or 0 for row in counts_result)
counts: dict[str, int] = {row[0]: row[1] for row in counts_result}
diff --cc invokeai/backend/model_manager/load/model_cache/model_cache.py
index 86d59c7b06,47dd4d45a8..b78a41f953
--- a/invokeai/backend/model_manager/load/model_cache/model_cache.py
+++ b/invokeai/backend/model_manager/load/model_cache/model_cache.py
@@@ -360,13 -609,38 +615,39 @@@ class ModelCache
)
else:
wrapped_model = CachedModelOnlyFullLoad(
- model, effective_execution_device, size, keep_ram_copy=self._keep_ram_copy_of_weights
+ model,
+ effective_execution_device,
+ size,
+ keep_ram_copy=self._keep_ram_copy_of_weights,
+ shared_store=self._shared_cpu_weights,
+ cache_key=key,
)
- cache_record = CacheRecord(key=key, cached_model=wrapped_model)
+ # awaiting_first_use protects the new entry from the asynchronous eviction paths (budget
+ # reconcile, peer-requested eviction) until the loader locks it — see CacheRecord. A
+ # prefetch admission gets no grace: nothing will come back for it, so it must stay
+ # ordinarily evictable.
+ #
+ # Neither does an admission made while no deferred worker is running to release the grace
+ # if the loader abandons the model. Both states are reachable — put() after shutdown()
+ # (Invoker.stop() stops model_manager before session_processor, so an in-flight generation
+ # can land here), and a worker that could not be started under thread exhaustion — and in
+ # both the flag would never be cleared, leaving the record permanently invisible to every
+ # asynchronous eviction path while its bytes stay charged to the shared budget. Without the
+ # grace the record is merely ordinarily evictable; lock() still clears the flag on the
+ # normal path, so nothing changes when the worker is healthy.
+ worker_running = self._deferred_work_thread is not None and self._deferred_work_thread.is_alive()
+ cache_record = CacheRecord(
+ key=key, cached_model=wrapped_model, awaiting_first_use=not prefetch and worker_running
+ )
self._cached_models[key] = cache_record
self._cache_stack.append(key)
+ # Account this model's RAM in the global budget. Shared weights are tracked once by the
+ # SharedCpuWeightsStore; only non-deduplicated models are added to the budget's non-shared
+ # 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)"
)
@@@ -910,12 -1446,143 +1462,144 @@@
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 evict_unlocked_for_peer(self, is_satisfied: Callable[[], bool]) -> Optional[int]:
+ """Evict this cache's unlocked entries on behalf of another device's cache (best effort).
+
+ Called by a peer whose own eviction stack is exhausted while the shared RamBudget is still
+ over-committed — typically because this cache holds the last reference to shared weights the
+ peer already dropped. `is_satisfied` is re-checked after every eviction so no more entries
+ are dropped than the peer actually needs.
+
+ The peer calls this while holding its own cache lock, so this cache's lock is taken
+ NON-blocking: if it is contended, this device is actively working and the peer simply skips
+ it — blocking here could deadlock two caches making room for each other simultaneously.
+
+ Returns the number of entries evicted, or None if the lock was contended and nothing could
+ be attempted. Either way, if the shared budget is still exceeded once the caller admits its
+ model, the caller records a deferred reconcile request on every peer (see
+ request_budget_reconcile) — and every unlock that leaves the budget exceeded records one on
+ its own cache — so a skip never leaves the budget exceeded indefinitely.
+ """
+ if not self._lock.acquire(blocking=False):
+ return None
+ try:
+ models_cleared = 0
+ pos = 0
+ while pos < len(self._cache_stack) and not is_satisfied():
+ cache_entry = self._cached_models[self._cache_stack[pos]]
+ if cache_entry.is_locked or cache_entry.awaiting_first_use:
+ pos += 1
+ continue
+ self._logger.debug(
+ f"Dropping {cache_entry.key} from RAM cache on behalf of a peer device cache "
+ f"({(cache_entry.cached_model.total_bytes() / MB):.2f}MB)."
+ )
+ self._delete_cache_entry(cache_entry)
+ models_cleared += 1
+ return models_cleared
+ finally:
+ self._lock.release()
+ # This manual release must honor a pending budget reconcile just like the
+ # synchronized-decorator hook — a requester whose inline attempt found the lock
+ # held by this method depends on it (see request_budget_reconcile). Non-blocking:
+ # the peer calling this method holds its own cache lock, and blocking on this
+ # cache's lock while holding another cache's lock is the one shape that could
+ # deadlock; on contention the new holder's release hook processes the flag.
+ if not self._lock._is_owned():
+ self._reconcile_budget_if_pending(blocking=False)
+
+ def request_budget_reconcile(self) -> None:
+ """Ask this cache to shed unlocked entries until the shared budget is satisfied.
+
+ Called by a peer that admitted a model while the global RamBudget was exceeded and could
+ not free enough by evicting from this cache directly (evict_unlocked_for_peer found the
+ lock contended, or everything evictable was already gone). Setting the pending flag alone
+ is not enough: this cache's busy operation may have released its lock — running its
+ reconcile hook while the flag was still unset — just before the flag was set here, and if
+ the cache then stays idle no future lock release would ever honor the request (lost
+ wakeup). The inline attempt below closes that window: either the lock is free now and the
+ reconcile runs immediately, or it is still held and the eventual release hook — which runs
+ strictly after the flag set below — performs it.
+ """
+ self._budget_reconcile_pending.set()
+ # Non-blocking: the caller holds its own cache lock, and blocking here could deadlock two
+ # caches requesting reconciles from each other.
+ self._reconcile_budget_if_pending(blocking=False)
+
+ def _reconcile_budget_if_pending(self, blocking: bool = True) -> None:
+ """Evict this cache's unlocked entries while a requested reconcile is pending and the
+ shared budget is exceeded.
+
+ Called (blocking) from the synchronized-decorator hook after each lock release,
+ (non-blocking) inline from request_budget_reconcile and from the manual lock release in
+ evict_unlocked_for_peer, and (blocking, on a dedicated background thread) from
+ cached_model_keys' release, which must not stall. The pending flag stays set until the
+ budget is actually satisfied: if the remaining overshoot is held by locked (in-use)
+ entries, the unlock that eventually frees them is itself a synchronized method, whose hook
+ re-runs this reconcile.
+ """
+ if self._ram_budget is None or not self._budget_reconcile_pending.is_set():
+ return
+ while True:
+ if self._ram_budget.available() >= 0:
+ # Budget satisfied: retire the request. Clearing races a concurrent admission —
+ # a peer counts its new model (driving the budget negative) BEFORE setting the
+ # flag, so if the budget is negative again after the clear, the clear may have
+ # wiped a request whose own inline attempt already saw the flag unset and
+ # returned. Restore the flag and keep reconciling in that case.
+ self._budget_reconcile_pending.clear()
+ if self._ram_budget.available() >= 0:
+ return
+ self._budget_reconcile_pending.set()
+ if not self._lock.acquire(blocking=blocking):
+ # Contended (non-blocking caller only): the holder releases through a reconcile
+ # hook, which re-runs this reconcile with the flag still set.
+ return
+ models_cleared = 0
+ try:
+ pos = 0
+ while pos < len(self._cache_stack) and self._ram_budget.available() < 0:
+ cache_entry = self._cached_models[self._cache_stack[pos]]
+ if cache_entry.is_locked or cache_entry.awaiting_first_use:
+ pos += 1
+ continue
+ self._logger.debug(
+ f"Dropping {cache_entry.key} from RAM cache to reconcile the shared RAM budget "
+ f"({(cache_entry.cached_model.total_bytes() / MB):.2f}MB)."
+ )
+ self._delete_cache_entry(cache_entry)
+ models_cleared += 1
+ finally:
+ self._lock.release()
+ if models_cleared > 0:
+ gc.collect()
+ TorchDevice.empty_cache()
+ if self._ram_budget.available() < 0:
+ # Everything evictable here is gone; the remainder is held by locked (in-use)
+ # or just-admitted entries. Leave the flag set — the eventual unlock()'s hook
+ # (or the loader's next cache operation) retries.
+ return
+ # Satisfied: loop back to retire the flag via the guarded clear above.
+
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."""
+ was_present = cache_entry.key in self._cached_models
self._cache_stack = [key for key in self._cache_stack if key != cache_entry.key]
self._cached_models.pop(cache_entry.key, None)
+ # Drop this device's reference to the shared canonical CPU weights so they can be freed once
+ # the last device releases them. Guard on was_present so a double-delete doesn't
+ # double-release (release_shared_weights is itself idempotent, but a re-added entry under the
+ # same key must not be released by a stale delete).
+ if was_present:
+ uses_shared = cache_entry.cached_model.uses_shared_weights
+ total_bytes = cache_entry.cached_model.total_bytes()
+ cache_entry.cached_model.release_shared_weights()
+ # Drop the matching non-shared contribution from the global budget (shared weights are
+ # released via the store above). Captured before release_shared_weights() flips the flag.
+ if self._ram_budget is not None and not uses_shared:
+ self._ram_budget.remove_non_shared(total_bytes, cache=self)
@synchronized
def drop_model(self, model_key: str) -> int: