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(queue): release a failed generation's VRAM and keep Empty Cache working (#10267)
Alexander Eichhorn4d2a3de75a58
diff --git a/docs/src/content/docs/troubleshooting/faq.mdx b/docs/src/content/docs/troubleshooting/faq.mdxindex 5cd685aed3..404c8cbc1d 100644--- a/docs/src/content/docs/troubleshooting/faq.mdx+++ b/docs/src/content/docs/troubleshooting/faq.mdx@@ -87,6 +87,8 @@ Check the [configuration docs] for more detail about the settings and how to speThe models are large, VRAM is expensive, and you may find yourself faced with Out of Memory errors when generating images. Follow our [Low VRAM mode guide] to configure Invoke to prevent these.+If generations keep failing with GPU errors after an out-of-memory error, clear the model cache: open **Cache** in the **Queue** panel header and click **Clear** in the **Models** row. On a server shared by several people, only administrators see **Cache**. If Invoke then reports that the GPU memory was not released, restart Invoke.+## Memory Leak (Linux)If you notice a memory leak, it could be caused by memory fragmentation as models are loaded and/or moved from CPU to GPU.diff --git a/invokeai/app/api/routers/model_manager.py b/invokeai/app/api/routers/model_manager.pyindex 84271c3694..d18dc45685 100644--- a/invokeai/app/api/routers/model_manager.py+++ b/invokeai/app/api/routers/model_manager.py@@ -174,6 +174,11 @@ class ModelsList(BaseModel):class EmptyModelCacheResponse(BaseModel):models_cleared: intbytes_freed: int+ vram_release_refused: bool = Field(+ description="The device refused to return its cached memory to the driver after the models were dropped (for "+ "example an earlier error left it in a bad state). The models were still dropped; the memory stays reserved "+ "by this process."+ )class CacheType(str, Enum):@@ -1610,11 +1615,15 @@ def empty_model_cache(current_admin: AdminUserOrDefault) -> EmptyModelCacheRespoApiDependencies.invoker.services.logger.info("Emptying model cache.")models_cleared = 0bytes_freed = 0+ vram_release_refused = Falsefor cache in distinct_caches(ApiDependencies.invoker.services.model_manager.load.ram_caches.values()):result = cache.make_room(1000 * 2**30)models_cleared += result.models_clearedbytes_freed += result.bytes_freed- return EmptyModelCacheResponse(models_cleared=models_cleared, bytes_freed=bytes_freed)+ vram_release_refused = vram_release_refused or result.vram_release_refused+ return EmptyModelCacheResponse(+ models_cleared=models_cleared, bytes_freed=bytes_freed, vram_release_refused=vram_release_refused+ )class HFTokenStatus(str, Enum):diff --git a/invokeai/app/invocations/text_encoder/qwen_image_text_encoder.py b/invokeai/app/invocations/text_encoder/qwen_image_text_encoder.pyindex 06015324e8..9c20a8b2a5 100644--- a/invokeai/app/invocations/text_encoder/qwen_image_text_encoder.py+++ b/invokeai/app/invocations/text_encoder/qwen_image_text_encoder.py@@ -584,11 +584,7 @@ class QwenImageTextEncoderInvocation(BaseInvocation):state_dict = Nonetext_encoder = Nonegc.collect()- try:- TorchDevice.empty_cache()- except Exception as cache_exc:- # A sick device context fails here too; the original error is the one worth reporting.- context.logger.warning(f"Could not empty the device cache after the failed load: {cache_exc}")+ TorchDevice.empty_cache()# Only a failed load is reported as the encoder not fitting; an OOM while patching is not that.if load_failed and isinstance(exc, torch.OutOfMemoryError):raise torch.OutOfMemoryError(self._oom_message(device, quantized_bytes, vram_available)) from excdiff --git a/invokeai/app/services/session_processor/session_processor_default.py b/invokeai/app/services/session_processor/session_processor_default.pyindex 1164bbfd4b..ee56ff56cc 100644--- a/invokeai/app/services/session_processor/session_processor_default.py+++ b/invokeai/app/services/session_processor/session_processor_default.py@@ -397,6 +397,10 @@ class DefaultSessionRunner(SessionRunnerBase):self._services.logger.warning(f"Could not record the outcome of calibration item {queue_item.item_id}", exc_info=True)+ # `raised` and the exception's traceback (through this frame) would otherwise reference each other, so the+ # failed node's frames and tensors would wait for the cyclic GC instead of being freed when the worker+ # drops the exception, before its VRAM release.+ raised = Nonedef _run_calibration_node(self, invocation: BaseInvocation, queue_item: SessionQueueItem, run_id: str) -> bool:"""Run one node of a calibration item inside a probe scope and persist its windows, whether the node completed,@@ -1220,31 +1224,33 @@ class DefaultSessionProcessor(SessionProcessorBase):self._poll_now()return- def _release_vram_after_session(self, worker: _SessionWorker) -> None:+ def _release_vram_after_session(self, worker: _SessionWorker, *, run_returned: bool) -> None:"""Return this worker's unoccupied cached VRAM to the driver now that its session is over.- A canceled session aborts mid-node, orphaning the whole denoise working set in the- caching allocator; nothing downstream (a VAE decode, say) runs to release it, so the- GPU keeps reporting the memory as used. Ask for the release explicitly. On a multi-GPU- box with a peer mid-render the call is deferred (see `TorchDevice.empty_cache`) and the- peer performs it at its next step boundary. A session that ran to completion has- released its own working memory along the way, so it only flushes a release a peer- deferred onto it — a flag test when nothing is pending.+ A session that ended early -- canceled, failed in a node, or aborted by an error escaping the runner+ (`run_returned` False) -- never ran the nodes that would release its working memory (a VAE decode, say). A+ canceled or failed node also leaves its own working set orphaned in the caching allocator, so the GPU keeps+ reporting the memory as used. Ask for the release explicitly. After an out-of-memory failure this matters+ most: those blocks were the card's only headroom, and the next session can fail on its first device operation+ that needs memory from the driver rather than from torch's allocator. On a multi-GPU box with a peer+ mid-render the call is deferred (see `TorchDevice.empty_cache`) and runs at the first flush that finds no+ other device mid-session. A session that ran to completion has released its own working memory along the way,+ so it only flushes a release a peer deferred onto it -- a flag test when nothing is pending.With `clear_vram_after_session`, every unlocked model on this worker's device also moves toRAM first (it stays cached there), and the release is forced past a busy peer: deferred, itwould leave the freed memory with the allocator while this worker's next session budgets itsfirst load, which then loads at minimum residency. Once per session, and the user opted in.- Both are best effort: the session's outcome is already recorded, and a free on a sick- device context must not fail the worker.+ Best effort: the session's outcome is already recorded, and neither the offload nor the forced release (which+ raises when the device refuses it) on a sick device context may fail the worker."""try:services = self._invoker.servicesif services.configuration.clear_vram_after_session and services.model_manager.load is not None:services.model_manager.load.ram_cache.offload_models_from_vram_except(())TorchDevice.empty_cache(force=True)- elif worker.cancel_event.is_set():+ elif self._session_ended_early(worker, run_returned):TorchDevice.empty_cache()else:TorchDevice.flush_deferred_empty_cache()@@ -1253,6 +1259,19 @@ class DefaultSessionProcessor(SessionProcessorBase):f"Could not release cached VRAM after the session on {worker.label}", exc_info=True)+ @staticmethod+ def _session_ended_early(worker: _SessionWorker, run_returned: bool) -> bool:+ """True when the session was stopped by the cancel event, recorded a node error, or the runner raised.++ The runner records node errors on the in-memory session it was handed, which is `queue_item.session`. An+ ending between nodes (the owner revoked before the status handler set the cancel event, a calibration whose+ measurements were not saved) counts as finished: no node was interrupted.+ """+ if not run_returned or worker.cancel_event.is_set():+ return True+ queue_item = worker.queue_item+ return queue_item is not None and queue_item.session.has_error()+def _log_attention_backends(self, worker: _SessionWorker) -> None:"""Log which SDPA kernels this worker's device has and the order they are tried in, once per device.@@ -1419,6 +1438,8 @@ class DefaultSessionProcessor(SessionProcessorBase):# goes on reporting that item as running for as long as it stays parked.# `get_status` and `get_running_queue_item_owners` both read it.worker.queue_item = None+ session_started = False+ processor_error = Falsetry:# Any unhandled exception in this block is a nonfatal processor error and will be handled.@@ -1536,11 +1557,12 @@ class DefaultSessionProcessor(SessionProcessorBase):# workflow completion resumes the parent via the runner that owns this# worker's cancel event.GENERATION_DEVICE_POOL.acquire_session(worker.device)+ session_started = Truetry:worker.runner.workflow_call_queue_lifecycle.run_queue_item(worker.queue_item)finally:GENERATION_DEVICE_POOL.release_session(worker.device)- self._release_vram_after_session(worker)+ self._release_vram_after_session(worker, run_returned=True)self._warn_if_vram_paged(worker)except Exception as e:@@ -1553,9 +1575,15 @@ class DefaultSessionProcessor(SessionProcessorBase):error_message=error_message,error_traceback=error_traceback,)+ processor_error = True++ if processor_error:+ # Outside the `except`: while the exception is in flight its traceback keeps the failed node's+ # frames, and the tensors in them, alive, so the release would not free what that node held.+ if session_started:+ self._release_vram_after_session(worker, run_returned=False)# Wait for next polling interval or event to try againworker.poll_now_event.wait(self._polling_interval)- continueexcept Exception as e:# Fatal error in this worker, log and pass - we're done hereerror_type = e.__class__.__name__diff --git a/invokeai/backend/model_manager/load/model_cache/model_cache.py b/invokeai/backend/model_manager/load/model_cache/model_cache.pyindex ab4ae65364..b71337e45c 100644--- a/invokeai/backend/model_manager/load/model_cache/model_cache.py+++ b/invokeai/backend/model_manager/load/model_cache/model_cache.py@@ -34,7 +34,7 @@ from invokeai.backend.model_manager.load.model_cache.torch_module_autocast.torch)from invokeai.backend.model_manager.load.model_util import calc_model_size_by_datafrom invokeai.backend.model_manager.taxonomy import AnyModel, SubModelType-from invokeai.backend.util.devices import TorchDevice, device_has_dedicated_vram+from invokeai.backend.util.devices import EmptyCacheOutcome, TorchDevice, device_has_dedicated_vramfrom invokeai.backend.util.level_zero import xpu_device_is_integratedfrom invokeai.backend.util.logging import InvokeAILoggerfrom invokeai.backend.util.prefix_logger_adapter import PrefixedLoggerAdapter@@ -423,13 +423,13 @@ def synchronized(method: Callable[..., Any]) -> Callable[..., Any]:self._reconcile_budget_if_pending()except Exception:# The reconcile is deferrable housekeeping and must not fail the operation- # that triggered it. It can raise from a sick CUDA context (empty_cache after- # an eviction) - and this hook runs inside the caller's frame AFTER the- # method body, so a raise out of lock_in_ram()/lock() here would propagate- # before LoadedModel's unlock-pairing try block is entered, leaking a- # permanently locked record (the same shape as a keep-alive Timer.start()- # failure, handled in _record_activity). The pending flag is only cleared- # once the budget is satisfied, so the next lock release retries.+ # that triggered it. It can still raise (the clear callbacks, budget bookkeeping) -+ # and this hook runs inside the caller's frame AFTER the method body, so a raise+ # out of lock_in_ram()/lock() here would propagate before LoadedModel's+ # unlock-pairing try block is entered, leaking a permanently locked record (the+ # same shape as a keep-alive Timer.start() failure, handled in _record_activity).+ # The pending flag is only cleared once the budget is satisfied, so the next lock+ # release retries.self._logger.exception("Error reconciling the shared RAM budget after a lock release")return wrapper@@ -461,6 +461,7 @@ class CacheEntrySnapshot:class CacheClearResult:models_cleared: intbytes_freed: int+ vram_release_refused: bool # the device refused to return its cached blocks after the dropclass CacheMissCallback(Protocol):@@ -1646,18 +1647,8 @@ class ModelCache:bytes_requested=0,bytes_freed=bytes_freed,)- try:- gc.collect()- TorchDevice.empty_cache()- except Exception:- # Deferrable housekeeping: empty_cache() can raise from a sick CUDA context after- # an eviction, and this runs in a dying worker's last frame. The eviction itself- # is already done and must not be undone by a failure to hand memory back.- _log_best_effort(- self._logger,- "exception",- "Error releasing device memory after a stranded-record eviction",- )+ gc.collect()+ TorchDevice.empty_cache()@synchronizeddef _recover_from_dead_worker(self, worker: threading.Thread) -> None:@@ -2276,11 +2267,11 @@ class ModelCache:releasable = self._get_reclaimable_allocator_bytes()if releasable < _MIN_RELEASABLE_FOR_RESERVE:return- TorchDevice.empty_cache(force=sys.platform == "win32")- self._logger.debug(- f"Returned {releasable / MB:.0f}MB of the allocator's unused blocks to the driver: {driver_free / MB:.0f}MB "- f"driver-free was short of the {reserve / MB:.0f}MB working-memory reserve."- )+ if TorchDevice.empty_cache(force=sys.platform == "win32") is EmptyCacheOutcome.RAN:+ self._logger.debug(+ f"Returned {releasable / MB:.0f}MB of the allocator's unused blocks to the driver: "+ f"{driver_free / MB:.0f}MB driver-free was short of the {reserve / MB:.0f}MB working-memory reserve."+ )def _move_model_to_vram(self, cache_entry: CacheRecord, vram_available: int, max_move_bytes: Optional[int] = None@@ -2677,7 +2668,7 @@ class ModelCache:f"Unloaded {cache_entry.key} from VRAM to free {(cache_entry_bytes_freed / MB):.0f} MB.")if empty_cache_per_offload:- if TorchDevice.empty_cache():+ if TorchDevice.empty_cache() is EmptyCacheOutcome.RAN:vram_bytes_freed_uncounted = 0else:vram_bytes_freed_uncounted += cache_entry_bytes_freed@@ -2716,19 +2707,24 @@ class ModelCache:)if self._execution_device.type != "cpu":- vram_in_use_bytes = self._get_vram_in_use()- vram_available_bytes = self._get_vram_available(None)- vram_size_bytes = vram_in_use_bytes + vram_available_bytes- vram_in_use_bytes_percent = vram_in_use_bytes / vram_size_bytes if vram_size_bytes > 0 else 0- vram_available_bytes_percent = vram_available_bytes / vram_size_bytes if vram_size_bytes > 0 else 0- log += log_format.format(- f"Compute Device ({self._execution_device.type})",- vram_size_bytes / MB,- vram_in_use_bytes / MB,- vram_in_use_bytes_percent,- vram_available_bytes / MB,- vram_available_bytes_percent,- )+ # Diagnostic only: a broken device context must not fail the eviction that logs its state.+ try:+ vram_in_use_bytes = self._get_vram_in_use()+ vram_available_bytes = self._get_vram_available(None)+ except RuntimeError as e:+ log += f" Compute Device ({self._execution_device.type}): unavailable ({e})\n"+ else:+ vram_size_bytes = vram_in_use_bytes + vram_available_bytes+ vram_in_use_bytes_percent = vram_in_use_bytes / vram_size_bytes if vram_size_bytes > 0 else 0+ vram_available_bytes_percent = vram_available_bytes / vram_size_bytes if vram_size_bytes > 0 else 0+ log += log_format.format(+ f"Compute Device ({self._execution_device.type})",+ vram_size_bytes / MB,+ vram_in_use_bytes / MB,+ vram_in_use_bytes_percent,+ vram_available_bytes / MB,+ vram_available_bytes_percent,+ )# Dispatch on this cache's execution device, not on availability order: a box with both# an NVIDIA card and an Arc would otherwise take the CUDA branch while running on XPU and@@ -2872,11 +2868,12 @@ class ModelCache:# box: a no-op make_room during one worker's model load froze the other worker's denoise# step for its full duration). make_room runs on every put(), and most of those evict# nothing, so the unconditional call turned every submodel load into a cross-GPU stall.- if models_cleared > 0:- TorchDevice.empty_cache()+ vram_release_refused = models_cleared > 0 and TorchDevice.empty_cache() is EmptyCacheOutcome.REFUSEDself._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)+ return CacheClearResult(+ models_cleared=models_cleared, bytes_freed=ram_bytes_freed, vram_release_refused=vram_release_refused+ )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).diff --git a/invokeai/backend/util/devices.py b/invokeai/backend/util/devices.pyindex 44812a63e4..f307675549 100644--- a/invokeai/backend/util/devices.py+++ b/invokeai/backend/util/devices.py@@ -1,6 +1,7 @@import sysimport threadingfrom collections import Counter, defaultdict+from enum import Enumfrom functools import wrapsfrom typing import Dict, Literal, Optional, Protocol, Union@@ -26,17 +27,26 @@ MPS_DEVICE = torch.device("mps")_XPU_MEM_FALLBACK_WARNED: set[str] = set()+class EmptyCacheOutcome(Enum):+ """What `TorchDevice.empty_cache` did. Callers compare members explicitly; only RAN returned memory to the driver."""++ RAN = "ran"+ DEFERRED = "deferred" # another generation device is mid-session; flush_deferred_empty_cache() runs it later+ REFUSED = "refused" # the backend raised; logged as a warning, the blocks stay reserved++class EmptyCacheObserver(Protocol):def before_empty_cache(self) -> None: ...- def after_empty_cache(self) -> None: ...+ def after_empty_cache(self, released: bool) -> None: ...EMPTY_CACHE_OBSERVERS: list[EmptyCacheObserver] = []-"""Told about every `TorchDevice.empty_cache` that releases memory, just before and just after the release, in-registration order. The working-memory probe registers here while a calibration scope is open, so that a release inside-a measured window ends a segment there (`invokeai.backend.working_memory.probe`); otherwise the list is empty and a-release pays one truth test for it. Observers must not raise."""+"""Told about every `TorchDevice.empty_cache` that attempts a release, just before and just after it, in+registration order; `released` is False when the backend refused (raised). The working-memory probe registers here+while a calibration scope is open, so that a release inside a measured window ends a segment there+(`invokeai.backend.working_memory.probe`); otherwise the list is empty and a release pays one truth test for it.+Observers must not raise."""def _xpu_is_available() -> bool:@@ -147,8 +157,8 @@ class TorchDevice:# Set when a peer-aware empty_cache (this class's or the installed torch.cuda wrapper) skipped# the real call because another generation device was mid-session. The skipped release is- # not lost: `flush_deferred_empty_cache()` performs it at the next quiet moment — a busy- # worker's step boundary or a session's end (see `flush_deferred_empty_cache`).+ # not lost: `flush_deferred_empty_cache()` performs it at the first step boundary or session+ # end that finds no other generation device mid-session._empty_cache_deferred = threading.Event()@classmethod@@ -441,8 +451,9 @@ class TorchDevice:torch.mps.synchronize()@classmethod- def empty_cache(cls, force: bool = False) -> bool:- """Clear the GPU device cache — unless another generation device is mid-session. Says whether it ran.+ def empty_cache(cls, force: bool = False) -> EmptyCacheOutcome:+ """Clear the GPU device cache — unless another generation device is mid-session.+ Returns RAN, DEFERRED (skipped for a busy peer) or REFUSED (the backend raised).`force` runs it regardless, for callers whose alternative is worse than stalling a busy peer for the rest ofits current step: a model about to run without the driver-free working memory it needs, which on Windows@@ -465,8 +476,8 @@ class TorchDevice:VRAM accounting turns conservative until a quiet-moment call runs. On single-GPUinstalls a worker never sees another busy device, so its own calls run as before; onlya thread with no session device (the cache keep-alive timer, the cache's background- worker) defers while the worker is mid-session, and that release now lands at the- worker's next step boundary instead of being dropped.+ worker) defers while the worker is mid-session, and that release runs at the next flush+ that finds no other device mid-session instead of being dropped.A skipped call is recorded as deferred rather than dropped: the memory it would havereturned (a canceled session's working set, a timed-out cache's weights) stays cached in@@ -474,19 +485,29 @@ class TorchDevice:driver and every other process — until `flush_deferred_empty_cache()` runs it from aquiet moment. Without that, VRAM freed on one GPU stayed resident until the peer'swhole render finished and something else happened to call empty_cache.++ A release the backend refuses (a `RuntimeError` such as `torch.AcceleratorError` or `OutOfMemoryError` from a+ broken or exhausted device context) is, for an ordinary call, logged as a warning and reported as REFUSED,+ never raised: the release is advisory, torch keeps reusing the blocks it could not return, and the operation+ that asked for it (an eviction, an offload, the Empty Cache request, the release after a session) must still+ complete. A context that stays broken fails the next real operation on its own. A `force` call raises the+ error instead, because its caller cannot proceed as if the release ran: a short working-memory reserve on+ Windows hangs instead of failing (`ModelCache._release_allocator_blocks_for_reserve`), and the working-memory+ probe would record a measurement window whose baseline still counts the blocks."""if not force and cls._another_generation_device_busy():cls._empty_cache_deferred.set()InvokeAILogger.get_logger(cls.__name__).debug("Deferring empty_cache: another generation device is mid-session.")- return False+ return EmptyCacheOutcome.DEFERRED# Clear before running: a skip that races in after this point re-sets the flag, so a# request is never lost, only (harmlessly) repeated.cls._empty_cache_deferred.clear()observers = tuple(EMPTY_CACHE_OBSERVERS) if EMPTY_CACHE_OBSERVERS else ()for observer in observers:observer.before_empty_cache()+ released = Falsetry:if torch.backends.mps.is_available():torch.mps.empty_cache()@@ -496,10 +517,21 @@ class TorchDevice:(getattr(cuda_empty_cache, "__wrapped__", cuda_empty_cache) if force else cuda_empty_cache)()if _xpu_is_available():torch.xpu.empty_cache()+ released = True+ except RuntimeError as e:+ if force:+ raise+ reason = str(e)+ InvokeAILogger.get_logger(cls.__name__).warning(+ f"Could not release cached device memory: {reason.splitlines()[0] if reason else type(e).__name__}. "+ "The memory stays reserved by this process; restart Invoke if generations keep failing with GPU "+ "errors."+ )+ return EmptyCacheOutcome.REFUSEDfinally:for observer in observers:- observer.after_empty_cache()- return True+ observer.after_empty_cache(released)+ return EmptyCacheOutcome.RAN@classmethoddef flush_deferred_empty_cache(cls) -> None:@@ -509,10 +541,10 @@ class TorchDevice:and a driver-level free is cheap — a denoise step boundary (the progress path calls it)or the end of a session. It is a flag test when nothing is pending, so it is safe to calloften. When a device other than the caller's is still mid-session the flush is skipped- again (and stays pending): on a two-GPU box the requester's session has ended, so the- busy worker's own step boundary is the first quiet moment and the release lands there —- within one of its steps instead of at the end of its render. The cost to the busy worker- is re-allocating its own cached working blocks on the next step, once per request.+ again (and stays pending): the release runs at the first flush that finds no OTHER device+ mid-session, which on a box whose GPUs stay busy is when one of them goes idle. The cost to+ a busy worker that runs it is re-allocating its own cached working blocks on the next step,+ once per request."""if not cls._empty_cache_deferred.is_set():returndiff --git a/invokeai/backend/working_memory/probe.py b/invokeai/backend/working_memory/probe.pyindex 5f75062d8d..ae53a215da 100644--- a/invokeai/backend/working_memory/probe.py+++ b/invokeai/backend/working_memory/probe.py@@ -624,17 +624,21 @@ class _EmptyCacheObserver:# moved or freed before it have voided the window (`offloading`, `dropped`).window.fold(window.counters.read(), ends_segment=False)elif not own_boundary:- window.fold(window.counters.read())+ window.fold(window.counters.read(), ends_segment=False)window.pending_reset = Trueexcept Exception:_all_failed("follow a release")- def after_empty_cache(self) -> None:+ def after_empty_cache(self, released: bool) -> None:+ # The boundary is only real once the backend released: a refused release (see `TorchDevice.empty_cache`) left+ # the segment, and its peaks, running.try:with _state_lock:for window in _open_windows:if window.pending_reset and window.counters is not None:- window.counters.reset_peaks()+ if released:+ window.segments += 1+ window.counters.reset_peaks()window.pending_reset = Falseexcept Exception:_all_failed("follow a release")diff --git a/invokeai/frontend/api/openapi.json b/invokeai/frontend/api/openapi.jsonindex 6f10c26853..c18657ee70 100644--- a/invokeai/frontend/api/openapi.json+++ b/invokeai/frontend/api/openapi.json@@ -35462,10 +35462,15 @@"bytes_freed": {"type": "integer","title": "Bytes Freed"+ },+ "vram_release_refused": {+ "type": "boolean",+ "title": "Vram Release Refused",+ "description": "The device refused to return its cached memory to the driver after the models were dropped (for example an earlier error left it in a bad state). The models were still dropped; the memory stays reserved by this process."}},"type": "object",- "required": ["models_cleared", "bytes_freed"],+ "required": ["models_cleared", "bytes_freed", "vram_release_refused"],"title": "EmptyModelCacheResponse"},"EnqueueBatchReceipt": {diff --git a/invokeai/frontend/api/schema.ts b/invokeai/frontend/api/schema.tsindex ede9a69d17..22ce87fdf6 100644--- a/invokeai/frontend/api/schema.ts+++ b/invokeai/frontend/api/schema.ts@@ -12991,6 +12991,11 @@ export type components = {models_cleared: number;/** Bytes Freed */bytes_freed: number;+ /**+ * Vram Release Refused+ * @description The device refused to return its cached memory to the driver after the models were dropped (for example an earlier error left it in a bad state). The models were still dropped; the memory stays reserved by this process.+ */+ vram_release_refused: boolean;};/** EnqueueBatchReceipt */EnqueueBatchReceipt: {diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.jsonindex 4434fef6e1..8e4493f08c 100644--- a/invokeai/frontend/webv2/public/locales/en.json+++ b/invokeai/frontend/webv2/public/locales/en.json@@ -1884,6 +1884,8 @@"variantHelp": "Architecture variant, e.g. inpaint or dev.","viewModel": "View model","viewQueue": "View queue",+ "vramNotReleased": "GPU memory not released",+ "vramNotReleasedDescription": "The model cache was emptied, but the GPU could not release its memory. Restart Invoke if generations keep failing.","workingMemory": {"title": "Working memory","description": "Measures this model's VAE decode on this GPU, so Invoke reserves what it really needs.",@@ -4192,7 +4194,10 @@"clearedDescription_other": "Cleared {{count}} cached models and freed {{bytes}}.","couldNotClear": "Could not clear the model cache.","noModelsCleared": "No cached models cleared",- "noModelsClearedDescription": "No unlocked cached models were available to clear. Active models stay loaded until they are no longer in use."+ "noModelsClearedDescription": "No unlocked cached models were available to clear. Active models stay loaded until they are no longer in use.",+ "vramNotReleased": "GPU memory not released",+ "vramNotReleasedDescription_one": "Cleared {{count}} cached model, but the GPU could not release its memory. Restart Invoke if generations keep failing.",+ "vramNotReleasedDescription_other": "Cleared {{count}} cached models, but the GPU could not release its memory. Restart Invoke if generations keep failing."},"noCurrentItem": "Nothing to cancel","nothingRecalled": "Nothing recalled",diff --git a/invokeai/frontend/webv2/src/features/models/core/types.ts b/invokeai/frontend/webv2/src/features/models/core/types.tsindex 5cd9a2d066..d1b4dc157e 100644--- a/invokeai/frontend/webv2/src/features/models/core/types.ts+++ b/invokeai/frontend/webv2/src/features/models/core/types.ts@@ -1,3 +1,5 @@+import type { components } from '@api/schema';+/*** Mirror snake_case backend model contracts with open unions so unknown architectures display generic labels* without a frontend release.@@ -340,6 +342,8 @@ export interface BulkReidentifyModelsResponse {failed: { key: string; error: string }[];}+export type EmptyModelCacheResponse = components['schemas']['EmptyModelCacheResponse'];+export interface DeleteOrphanedModelsResponse {deleted: string[];errors: Record<string, string>;diff --git a/invokeai/frontend/webv2/src/features/models/data/api.ts b/invokeai/frontend/webv2/src/features/models/data/api.tsindex 5e3cca337d..6b1e265e8d 100644--- a/invokeai/frontend/webv2/src/features/models/data/api.ts+++ b/invokeai/frontend/webv2/src/features/models/data/api.ts@@ -2,6 +2,7 @@ import type {BulkDeleteModelsResponse,BulkReidentifyModelsResponse,DeleteOrphanedModelsResponse,+ EmptyModelCacheResponse,FoundModel,HFTokenStatus,HuggingFaceModels,@@ -214,9 +215,8 @@ export const deleteOrphanedModels = (paths: string[], signal?: AbortSignal): Prosignal,});-export const emptyModelCache = async (signal?: AbortSignal): Promise<void> => {- await request(`${MODELS_BASE}/empty_model_cache`, { method: 'POST', signal });-};+export const emptyModelCache = (signal?: AbortSignal): Promise<EmptyModelCacheResponse> =>+ requestJson<EmptyModelCacheResponse>(`${MODELS_BASE}/empty_model_cache`, { method: 'POST', signal });/** External image-provider credentials (OpenAI, Gemini, ...). */diff --git a/invokeai/frontend/webv2/src/features/models/ui/library/MaintenanceMenu.browser.test.tsx b/invokeai/frontend/webv2/src/features/models/ui/library/MaintenanceMenu.browser.test.tsxindex 21a0b858e8..1337e2f0bd 100644--- a/invokeai/frontend/webv2/src/features/models/ui/library/MaintenanceMenu.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/models/ui/library/MaintenanceMenu.browser.test.tsx@@ -9,10 +9,17 @@ import { userEvent } from 'vitest/browser';import { MaintenanceMenu } from './MaintenanceMenu';+const dependencies = vi.hoisted(() => ({+ emptyModelCache: vi.fn(),+ notify: { error: vi.fn(), info: vi.fn(), success: vi.fn() },+}));+vi.mock('@features/models/data/api', async (importOriginal) => ({...(await importOriginal<object>()),+ emptyModelCache: dependencies.emptyModelCache,getOrphanedModels: vi.fn(() => Promise.resolve([])),}));+vi.mock('@features/models/ui/useModelsNotify', () => ({ useNotify: () => dependencies.notify }));vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;@@ -35,6 +42,12 @@ describe('MaintenanceMenu', () => {);});+ beforeEach(() => {+ dependencies.emptyModelCache.mockReset();+ dependencies.notify.error.mockReset();+ dependencies.notify.success.mockReset();+ });+afterEach(async () => {await act(() => root.unmount());host.remove();@@ -57,4 +70,35 @@ describe('MaintenanceMenu', () => {expect(frame.text).toContain('models.noOrphaned');}});++ it.each([+ { refused: true, error: ['models.vramNotReleased', 'models.vramNotReleasedDescription'], success: null },+ { refused: false, error: null, success: ['models.cacheEmptied'] },+ ])('reports an emptied cache with refused VRAM release = $refused', async ({ refused, error, success }) => {+ dependencies.emptyModelCache.mockResolvedValue({+ bytes_freed: 1,+ models_cleared: 1,+ vram_release_refused: refused,+ });++ await act(() => userEvent.click(document.querySelector<HTMLElement>('[aria-label="models.libraryMaintenance"]')!));+ await expect.poll(() => document.querySelector('[role="menuitem"][data-value="empty-cache"]')).not.toBeNull();+ await act(() =>+ userEvent.click(document.querySelector<HTMLElement>('[role="menuitem"][data-value="empty-cache"]')!)+ );+ const findConfirm = () =>+ [...document.querySelectorAll<HTMLElement>('button')].find(+ (button) => button.textContent?.trim() === 'models.emptyCache'+ );+ await expect.poll(findConfirm).toBeDefined();+ const confirm = findConfirm()!;+ await act(() => userEvent.click(confirm));++ await expect.poll(() => dependencies.emptyModelCache.mock.calls.length).toBe(1);+ await expect+ .poll(() => dependencies.notify.error.mock.calls.length + dependencies.notify.success.mock.calls.length)+ .toBe(1);+ expect(dependencies.notify.error.mock.calls[0] ?? null).toEqual(error);+ expect(dependencies.notify.success.mock.calls[0] ?? null).toEqual(success);+ });});diff --git a/invokeai/frontend/webv2/src/features/models/ui/library/MaintenanceMenu.tsx b/invokeai/frontend/webv2/src/features/models/ui/library/MaintenanceMenu.tsxindex 58f1141ebf..bd71badf1e 100644--- a/invokeai/frontend/webv2/src/features/models/ui/library/MaintenanceMenu.tsx+++ b/invokeai/frontend/webv2/src/features/models/ui/library/MaintenanceMenu.tsx@@ -26,10 +26,15 @@ export const MaintenanceMenu = () => {const handleEmptyCache = () =>runEmptyCache(async (owner) => {- await emptyModelCache(owner.signal);+ const { vram_release_refused } = await emptyModelCache(owner.signal);assertAccountScopeCurrent(owner);- notify.success(t('models.cacheEmptied'));++ if (vram_release_refused) {+ notify.error(t('models.vramNotReleased'), t('models.vramNotReleasedDescription'));+ } else {+ notify.success(t('models.cacheEmptied'));+ }},(message) => notify.error(t('models.failedToEmptyCache'), message));diff --git a/invokeai/frontend/webv2/src/features/queue/ui/QueueHeaderActions.browser.test.tsx b/invokeai/frontend/webv2/src/features/queue/ui/QueueHeaderActions.browser.test.tsxindex af13cf921b..5f7db81e1b 100644--- a/invokeai/frontend/webv2/src/features/queue/ui/QueueHeaderActions.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/queue/ui/QueueHeaderActions.browser.test.tsx@@ -95,7 +95,7 @@ beforeEach(() => {server.invocationStatus.mockResolvedValue(invocationStatus());server.modelStats.mockResolvedValue(modelStats());server.clearInvocations.mockResolvedValue(null);- server.clearModels.mockResolvedValue({ bytes_freed: 2 * GIB, models_cleared: 2 });+ server.clearModels.mockResolvedValue({ bytes_freed: 2 * GIB, models_cleared: 2, vram_release_refused: false });server.setInvocationsEnabled.mockResolvedValue(null);host = document.createElement('div');document.body.append(host);diff --git a/invokeai/frontend/webv2/src/features/queue/ui/modelCacheStore.test.ts b/invokeai/frontend/webv2/src/features/queue/ui/modelCacheStore.test.tsindex 765943b1b4..11652a8a6b 100644--- a/invokeai/frontend/webv2/src/features/queue/ui/modelCacheStore.test.ts+++ b/invokeai/frontend/webv2/src/features/queue/ui/modelCacheStore.test.ts@@ -33,6 +33,8 @@ const t = ((key: string, values?: Record<string, unknown>) => {'widgets.queue.modelCache.cleared': 'Model cache cleared','widgets.queue.modelCache.clearedDescription': `Cleared ${values?.count} cached models and freed ${values?.bytes}.`,'widgets.queue.modelCache.noModelsCleared': 'No cached models cleared',+ 'widgets.queue.modelCache.vramNotReleased': 'GPU memory not released',+ 'widgets.queue.modelCache.vramNotReleasedDescription': `Cleared ${values?.count}, GPU kept memory.`,'widgets.queue.modelCache.noModelsClearedDescription':'No unlocked cached models were available to clear. Active models stay loaded until they are no longer in use.',};@@ -61,13 +63,13 @@ describe('model cache stats helpers', () => {});it('reports whether clear cache actually cleared models', () => {- expect(getModelCacheClearToast({ bytes_freed: 1024, models_cleared: 2 }, t)).toEqual({+ expect(getModelCacheClearToast({ bytes_freed: 1024, models_cleared: 2, vram_release_refused: false }, t)).toEqual({description: 'Cleared 2 cached models and freed 1.0\u00a0KiB.',status: 'success',title: 'Model cache cleared',});- expect(getModelCacheClearToast({ bytes_freed: 0, models_cleared: 0 }, t)).toEqual({+ expect(getModelCacheClearToast({ bytes_freed: 0, models_cleared: 0, vram_release_refused: false }, t)).toEqual({description:'No unlocked cached models were available to clear. Active models stay loaded until they are no longer in use.',status: 'info',@@ -75,6 +77,14 @@ describe('model cache stats helpers', () => {});});+ it('reports a refused VRAM release as an error even though models were cleared', () => {+ expect(getModelCacheClearToast({ bytes_freed: 4096, models_cleared: 2, vram_release_refused: true }, t)).toEqual({+ description: 'Cleared 2, GPU kept memory.',+ status: 'error',+ title: 'GPU memory not released',+ });+ });+it('names a shared unit once in the usage range, and both units when they differ', () => {const gib = 1024 ** 3;@@ -84,7 +94,11 @@ describe('model cache stats helpers', () => {});it('normalizes legacy null clear-cache responses', () => {- expect(normalizeModelCacheClearResult(null)).toEqual({ bytes_freed: 0, models_cleared: 0 });+ expect(normalizeModelCacheClearResult(null)).toEqual({+ bytes_freed: 0,+ models_cleared: 0,+ vram_release_refused: false,+ });});it('drops a stale stats response without releasing the replacement account refresh', async () => {diff --git a/invokeai/frontend/webv2/src/features/queue/ui/modelCacheStore.ts b/invokeai/frontend/webv2/src/features/queue/ui/modelCacheStore.tsindex 8f9e3764ac..4e4c60df08 100644--- a/invokeai/frontend/webv2/src/features/queue/ui/modelCacheStore.ts+++ b/invokeai/frontend/webv2/src/features/queue/ui/modelCacheStore.ts@@ -1,3 +1,4 @@+import type { components } from '@api/schema';import type { TFunction } from 'i18next';import { formatBytes } from '@platform/i18n/languages';@@ -41,12 +42,13 @@ export interface ModelCacheStats {loaded_model_sizes?: Record<string, number>;}-export interface ModelCacheClearResult {- models_cleared: number;- bytes_freed: number;-}+export type ModelCacheClearResult = components['schemas']['EmptyModelCacheResponse'];-const EMPTY_MODEL_CACHE_CLEAR_RESULT: ModelCacheClearResult = { bytes_freed: 0, models_cleared: 0 };+const EMPTY_MODEL_CACHE_CLEAR_RESULT: ModelCacheClearResult = {+ bytes_freed: 0,+ models_cleared: 0,+ vram_release_refused: false,+};export const normalizeModelCacheClearResult = (result: ModelCacheClearResult | null): ModelCacheClearResult =>result ?? EMPTY_MODEL_CACHE_CLEAR_RESULT;@@ -57,9 +59,17 @@ export const getModelCacheUsage = (stats: ModelCacheStats | null): { used: numbe});export const getModelCacheClearToast = (- { bytes_freed, models_cleared }: ModelCacheClearResult,+ { bytes_freed, models_cleared, vram_release_refused }: ModelCacheClearResult,t: TFunction-): { title: string; description: string; status: 'info' | 'success' } => {+): { title: string; description: string; status: 'error' | 'info' | 'success' } => {+ if (vram_release_refused) {+ return {+ description: t('widgets.queue.modelCache.vramNotReleasedDescription', { count: models_cleared }),+ status: 'error',+ title: t('widgets.queue.modelCache.vramNotReleased'),+ };+ }+if (models_cleared === 0) {return {description: t('widgets.queue.modelCache.noModelsClearedDescription'),diff --git a/tests/app/routers/test_model_manager.py b/tests/app/routers/test_model_manager.pyindex 2a1dfdc9c3..53c7115921 100644--- a/tests/app/routers/test_model_manager.py+++ b/tests/app/routers/test_model_manager.py@@ -282,15 +282,17 @@ def test_empty_model_cache_aggregates_per_device_results(monkeypatch: Any, clienfrom invokeai.backend.model_manager.load.model_cache.model_cache import CacheClearResultclass _Cache:- def __init__(self, models_cleared: int, bytes_freed: int) -> None:- self._result = CacheClearResult(models_cleared=models_cleared, bytes_freed=bytes_freed)+ def __init__(self, models_cleared: int, bytes_freed: int, vram_release_refused: bool = False) -> None:+ self._result = CacheClearResult(+ models_cleared=models_cleared, bytes_freed=bytes_freed, vram_release_refused=vram_release_refused+ )self.requested: list[int] = []def make_room(self, bytes_needed: int) -> CacheClearResult:self.requested.append(bytes_needed)return self._result- cache_0 = _Cache(models_cleared=2, bytes_freed=100)+ cache_0 = _Cache(models_cleared=2, bytes_freed=100, vram_release_refused=True)cache_1 = _Cache(models_cleared=3, bytes_freed=250)services = _make_stats_services({"cuda:0": cache_0, "cuda:1": cache_1})invoker = DummyInvoker(services)@@ -300,7 +302,7 @@ def test_empty_model_cache_aggregates_per_device_results(monkeypatch: Any, clienresponse = client.post("/api/v2/models/empty_model_cache")assert response.status_code == 200- assert response.json() == {"models_cleared": 5, "bytes_freed": 350}+ assert response.json() == {"models_cleared": 5, "bytes_freed": 350, "vram_release_refused": True}# Both devices were actually asked to clear, not just the API thread's default cache.assert len(cache_0.requested) == 1assert len(cache_1.requested) == 1@@ -317,7 +319,7 @@ def test_empty_model_cache_clears_duplicate_cache_objects_once(monkeypatch: Any,def make_room(self, bytes_needed: int) -> CacheClearResult:self.calls += 1- return CacheClearResult(models_cleared=2, bytes_freed=100)+ return CacheClearResult(models_cleared=2, bytes_freed=100, vram_release_refused=False)shared = _Cache()services = _make_stats_services({"cuda:0": shared, "cpu": shared})@@ -328,10 +330,95 @@ def test_empty_model_cache_clears_duplicate_cache_objects_once(monkeypatch: Any,response = client.post("/api/v2/models/empty_model_cache")assert response.status_code == 200- assert response.json() == {"models_cleared": 2, "bytes_freed": 100}+ assert response.json() == {"models_cleared": 2, "bytes_freed": 100, "vram_release_refused": False}assert shared.calls == 1+def test_empty_model_cache_succeeds_when_the_device_refuses_to_release_its_cached_memory(+ monkeypatch: Any, client: TestClient+) -> None:+ """The models are dropped before the allocator is asked to hand its blocks back; a device context that refuses+ (here a CUDA error) must not turn the finished eviction into a server error."""+ import torch++ from invokeai.backend.model_manager.load.model_cache.model_cache import ModelCache+ from invokeai.backend.util import devices+ from tests.backend.model_manager.load.model_cache.cached_model.utils import DummyModule++ releases = []++ def refuse() -> None:+ releases.append("refused")+ # The type the report hit; older torch builds only have RuntimeError.+ raise getattr(torch, "AcceleratorError", RuntimeError)("CUDA error: out of memory")++ monkeypatch.setattr(torch.cuda, "is_available", lambda: True)+ monkeypatch.setattr(torch.cuda, "empty_cache", refuse)+ monkeypatch.setattr(torch.backends.mps, "is_available", lambda: False)+ monkeypatch.setattr(devices, "_xpu_is_available", lambda: False)++ cache = 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=logging.getLogger("test.model_manager_router"),+ )+ cache.put("model", DummyModule())+ size = cache.get("model").cached_model.total_bytes()+ invoker = DummyInvoker(_make_stats_services({"cpu": cache}))+ monkeypatch.setattr("invokeai.app.api.routers.model_manager.ApiDependencies", MockApiDependencies(invoker))+ monkeypatch.setattr("invokeai.app.api.auth_dependencies.ApiDependencies", MockApiDependencies(invoker))++ response = client.post("/api/v2/models/empty_model_cache")++ assert response.status_code == 200+ assert response.json() == {"models_cleared": 1, "bytes_freed": size, "vram_release_refused": True}+ assert "model" not in cache._cached_models+ assert releases == ["refused"]+++def test_empty_model_cache_does_not_report_a_deferred_release_as_refused(monkeypatch: Any, client: TestClient) -> None:+ """A release skipped because another generation device is mid-session runs later; it is not a refusal, so the+ client must not warn about unreleased GPU memory."""+ import torch++ from invokeai.backend.model_manager.load.model_cache.model_cache import ModelCache+ from invokeai.backend.util import devices+ from invokeai.backend.util.devices import TorchDevice+ from tests.backend.model_manager.load.model_cache.cached_model.utils import DummyModule++ releases = []++ monkeypatch.setattr(torch.cuda, "is_available", lambda: True)+ monkeypatch.setattr(torch.cuda, "empty_cache", lambda: releases.append("released"))+ monkeypatch.setattr(torch.backends.mps, "is_available", lambda: False)+ monkeypatch.setattr(devices, "_xpu_is_available", lambda: False)+ monkeypatch.setattr(TorchDevice, "_another_generation_device_busy", classmethod(lambda cls: True))++ cache = 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=logging.getLogger("test.model_manager_router"),+ )+ cache.put("model", DummyModule())+ size = cache.get("model").cached_model.total_bytes()+ invoker = DummyInvoker(_make_stats_services({"cpu": cache}))+ monkeypatch.setattr("invokeai.app.api.routers.model_manager.ApiDependencies", MockApiDependencies(invoker))+ monkeypatch.setattr("invokeai.app.api.auth_dependencies.ApiDependencies", MockApiDependencies(invoker))++ response = client.post("/api/v2/models/empty_model_cache")++ assert response.status_code == 200+ assert response.json() == {"models_cleared": 1, "bytes_freed": size, "vram_release_refused": False}+ assert "model" not in cache._cached_models+ assert releases == []++def test_get_stats_returns_null_when_no_stats(monkeypatch: Any, client: TestClient) -> None:class _Cache:def __init__(self) -> None:diff --git a/tests/app/services/session_processor/test_release_vram_after_session.py b/tests/app/services/session_processor/test_release_vram_after_session.pyindex a95792acd6..fe80016ec7 100644--- a/tests/app/services/session_processor/test_release_vram_after_session.py+++ b/tests/app/services/session_processor/test_release_vram_after_session.py@@ -1,16 +1,36 @@-"""The worker's end-of-session VRAM release: a canceled session asks for an empty_cache (its-denoise working set is orphaned mid-node with nothing downstream to release it); a completed-one only flushes a release a peer deferred onto it; neither may fail the worker."""+"""The worker's end-of-session VRAM release: a session that ended early (canceled, failed in a node, or aborted by an+error out of the runner) asks for an empty_cache, its working set being orphaned mid-node with nothing downstream to+release it; a completed one only flushes a release a peer deferred onto it; neither may fail the worker."""+import asyncio+import gcimport threading+import weakref+from contextlib import contextmanagerfrom types import SimpleNamespace+from typing import Callable, Iterator+import pytestimport torch+from invokeai.app.invocations.baseinvocation import BaseInvocation, BaseInvocationOutput, invocation, invocation_output+from invokeai.app.invocations.fields import InputField, OutputFieldfrom invokeai.app.services.config.config_default import InvokeAIAppConfig+from invokeai.app.services.invoker import Invokerfrom invokeai.app.services.model_load.model_load_default import ModelLoadService-from invokeai.app.services.session_processor.session_processor_default import DefaultSessionProcessor-from invokeai.backend.util.devices import TorchDevice+from invokeai.app.services.session_processor.session_processor_default import (+ DefaultSessionProcessor,+ DefaultSessionRunner,+)+from invokeai.app.services.session_queue.session_queue_common import Batch+from invokeai.app.services.session_queue.session_queue_default import SessionQueue+from invokeai.app.services.shared.database.database import Database+from invokeai.app.services.shared.graph import Graph, GraphExecutionState+from invokeai.app.services.shared.invocation_context import InvocationContext+from invokeai.backend.util.devices import EmptyCacheOutcome, TorchDevice++# Bounds a hang, not worker latency.+_TIMEOUT = 30class _Logger:@@ -21,6 +41,51 @@ class _Logger:self.warnings.append(message)+class _DeviceRequests:+ """The calls the worker makes to `TorchDevice` for a release, as (name, force), and an event set by each one.++ The worker releases on its own thread after the queue status is final, so a test waits on `wait()`. `sample`, when+ set, is called as each release is requested and its results are collected in `samples`."""++ def __init__(self, monkeypatch: pytest.MonkeyPatch) -> None:+ self.calls: list[tuple[str, bool]] = []+ self.sample: Callable[[], object] | None = None+ self.samples: list[object] = []+ self._released = threading.Event()+ monkeypatch.setattr(TorchDevice, "empty_cache", self._record("empty_cache"))+ monkeypatch.setattr(TorchDevice, "flush_deferred_empty_cache", self._record("flush"))++ def _record(self, name: str):+ def stub(cls, force: bool = False) -> None:+ self.calls.append((name, force))+ if self.sample is not None:+ self.samples.append(self.sample())+ self._released.set()++ return classmethod(stub)++ def wait(self) -> list[tuple[str, bool]]:+ assert self._released.wait(_TIMEOUT)+ return self.calls+++def device_requests(monkeypatch: pytest.MonkeyPatch) -> _DeviceRequests:+ return _DeviceRequests(monkeypatch)+++class _Stats:+ @contextmanager+ def collect_stats(self, invocation, graph_execution_state_id) -> Iterator[None]:+ yield++ def log_stats(self, graph_execution_state_id) -> None:+ pass++ def reset_stats(self, graph_execution_state_id) -> None:+ pass++class _Cache:def __init__(self) -> None:self.offloaded: list[tuple[str, ...]] = []@@ -44,74 +109,57 @@ def _processor(return processor, logger-def _worker(canceled: bool) -> SimpleNamespace:+def _worker(outcome: str = "completed") -> SimpleNamespace:+ """A worker whose session ended as `outcome`: completed, canceled, or failed in a node."""event = threading.Event()- if canceled:+ if outcome == "canceled":event.set()- return SimpleNamespace(cancel_event=event, label="worker (cuda:0)")+ session = GraphExecutionState(graph=Graph())+ if outcome == "failed":+ session.errors["node"] = "RuntimeError: out of memory"+ return SimpleNamespace(cancel_event=event, label="worker (cuda:0)", queue_item=SimpleNamespace(session=session))-def test_canceled_session_requests_an_empty_cache(monkeypatch) -> None:- calls: list[str] = []- monkeypatch.setattr(TorchDevice, "empty_cache", classmethod(lambda cls: calls.append("empty")))- monkeypatch.setattr(TorchDevice, "flush_deferred_empty_cache", classmethod(lambda cls: calls.append("flush")))+def test_canceled_session_requests_an_unforced_empty_cache(device_requests) -> None:processor, logger = _processor()- processor._release_vram_after_session(_worker(canceled=True)) # type: ignore[arg-type]+ processor._release_vram_after_session(_worker("canceled"), run_returned=True) # type: ignore[arg-type]- assert calls == ["empty"]+ assert device_requests.calls == [("empty_cache", False)]assert logger.warnings == []-def test_completed_session_only_flushes_a_deferred_release(monkeypatch) -> None:- calls: list[str] = []- monkeypatch.setattr(TorchDevice, "empty_cache", classmethod(lambda cls: calls.append("empty")))- monkeypatch.setattr(TorchDevice, "flush_deferred_empty_cache", classmethod(lambda cls: calls.append("flush")))- processor, logger = _processor()[email protected]("outcome", ["completed", "canceled", "failed"])+def test_clear_vram_after_session_moves_every_model_to_ram_and_forces_the_release(device_requests, outcome) -> None:+ """The setting for a session that runs fine once and runs out of memory the second time: every unlocked model+ leaves VRAM (staying cached in RAM) and the allocator hands its blocks back, whatever the session's outcome."""+ cache = _Cache()+ processor, logger = _processor(clear_vram_after_session=True, cache=cache)- processor._release_vram_after_session(_worker(canceled=False)) # type: ignore[arg-type]+ processor._release_vram_after_session(_worker(outcome), run_returned=True) # type: ignore[arg-type]- assert calls == ["flush"]+ assert cache.offloaded == [()]+ # Forced: deferred behind a busy peer, the next session would budget against memory the allocator still holds.+ assert device_requests.calls == [("empty_cache", True)]assert logger.warnings == []-def test_release_failure_is_logged_not_raised(monkeypatch) -> None:- def boom(cls) -> None:+def test_clear_vram_after_session_logs_a_refused_forced_release_instead_of_failing_the_worker(monkeypatch) -> None:+ def refuse(cls, force: bool = False) -> EmptyCacheOutcome:raise RuntimeError("HIP error: invalid device context")- monkeypatch.setattr(TorchDevice, "empty_cache", classmethod(boom))- processor, logger = _processor()+ monkeypatch.setattr(TorchDevice, "empty_cache", classmethod(refuse))+ processor, logger = _processor(clear_vram_after_session=True)- processor._release_vram_after_session(_worker(canceled=True)) # type: ignore[arg-type]+ processor._release_vram_after_session(_worker(), run_returned=True) # type: ignore[arg-type]assert len(logger.warnings) == 1assert "cuda:0" in logger.warnings[0]-def test_clear_vram_after_session_moves_every_model_to_ram_and_releases_the_memory(monkeypatch) -> None:- """The setting for a session that runs fine once and runs out of memory the second time: every unlocked model- leaves VRAM (staying cached in RAM) and the allocator hands its blocks back, even after a completed session."""- calls: list[tuple[str, bool]] = []- monkeypatch.setattr(- TorchDevice, "empty_cache", classmethod(lambda cls, force=False: calls.append(("empty", force)))- )- monkeypatch.setattr(- TorchDevice, "flush_deferred_empty_cache", classmethod(lambda cls: calls.append(("flush", False)))- )- cache = _Cache()- processor, logger = _processor(clear_vram_after_session=True, cache=cache)-- processor._release_vram_after_session(_worker(canceled=False)) # type: ignore[arg-type]-- assert cache.offloaded == [()]- # Forced: deferred behind a busy peer, the next session would budget against memory the allocator still holds.- assert calls == [("empty", True)]- assert logger.warnings == []--def test_clear_vram_after_session_leaves_other_gpus_caches_alone(monkeypatch) -> None:"""Multi-GPU: a worker clears its own device's cache only -- a peer may be mid-session on its own."""- monkeypatch.setattr(TorchDevice, "empty_cache", classmethod(lambda cls, force=False: True))+ monkeypatch.setattr(TorchDevice, "empty_cache", classmethod(lambda cls, force=False: EmptyCacheOutcome.RAN))caches = {"cuda:0": _Cache(), "cuda:1": _Cache()}for device, cache in caches.items():cache.execution_device = torch.device(device) # type: ignore[attr-defined]@@ -122,7 +170,7 @@ def test_clear_vram_after_session_leaves_other_gpus_caches_alone(monkeypatch) ->def worker() -> None:TorchDevice.set_session_device("cuda:1")try:- processor._release_vram_after_session(_worker(canceled=False)) # type: ignore[arg-type]+ processor._release_vram_after_session(_worker(), run_returned=True) # type: ignore[arg-type]finally:TorchDevice.clear_session_device()@@ -133,3 +181,140 @@ def test_clear_vram_after_session_leaves_other_gpus_caches_alone(monkeypatch) ->assert caches["cuda:1"].offloaded == [()]assert caches["cuda:0"].offloaded == []assert logger.warnings == []+++@invocation_output("test_release_vram_output")+class _ReleaseVramOutput(BaseInvocationOutput):+ value: int = OutputField(description="The node's value")+++@invocation("test_release_vram_node", version="1.0.0")+class _ReleaseVramInvocation(BaseInvocation):+ fail: bool = InputField(default=False, description="Raise instead of returning")++ def invoke(self, context: InvocationContext) -> _ReleaseVramOutput:+ if self.fail:+ raise RuntimeError("out of memory")+ return _ReleaseVramOutput(value=1)+++class _NodeMemory:+ """Stands in for the tensors a node holds."""+++class _RaisingRunner(DefaultSessionRunner):+ def __init__(self) -> None:+ super().__init__()+ self.node_memory: weakref.ref[_NodeMemory] | None = None++ def run(self, queue_item) -> None:+ node_memory = _NodeMemory()+ self.node_memory = weakref.ref(node_memory)+ raise RuntimeError("runner broke")+++def _run_one_session(+ invoker: Invoker,+ database: Database,+ device_requests: _DeviceRequests,+ *,+ fail: bool = False,+ runner: DefaultSessionRunner | None = None,+) -> tuple[SessionQueue, list[tuple[str, bool]]]:+ """Run one session on a real processor and return the queue and what the worker then asked of the device.++ The worker releases after the item's status is final, so the item is read back once the release was requested.+ Stopping the processor sets the worker's cancel event, so it waits for the release first or the session would+ look canceled."""+ # One worker on the CPU, whatever GPUs the host has: `auto` would start a worker per GPU (rejecting `_RaisingRunner`,+ # which cannot be cloned) and create CUDA contexts. The release under test does not depend on the worker's device.+ invoker.services.configuration.generation_devices = ["cpu"]+ queue = SessionQueue(database)+ invoker.services.session_queue = queue+ invoker.services.performance_statistics = _Stats()+ queue.start(invoker)+ graph = Graph()+ graph.add_node(_ReleaseVramInvocation(id="node", fail=fail))+ asyncio.run(queue.enqueue_batch("default", Batch(graph=graph, origin="canvas"), prepend=False))+ processor = DefaultSessionProcessor(session_runner=runner or DefaultSessionRunner(), polling_interval=0)+ try:+ processor.start(invoker)+ calls = device_requests.wait()+ finally:+ processor.stop()+ for worker in processor._workers:+ assert worker.thread is not None+ worker.thread.join(timeout=_TIMEOUT)+ assert not worker.thread.is_alive()+ return queue, calls+++def test_session_failed_in_a_node_requests_an_unforced_empty_cache(+ mock_invoker: Invoker, mock_sqlite_database: Database, device_requests: _DeviceRequests+) -> None:+ queue, calls = _run_one_session(mock_invoker, mock_sqlite_database, device_requests, fail=True)++ assert calls == [("empty_cache", False)]+ item = queue.get_queue_item(1)+ assert (item.status, item.error_message) == ("failed", "out of memory")+++def test_completed_session_only_flushes_a_deferred_release(+ mock_invoker: Invoker, mock_sqlite_database: Database, device_requests: _DeviceRequests+) -> None:+ queue, calls = _run_one_session(mock_invoker, mock_sqlite_database, device_requests)++ assert calls == [("flush", False)]+ assert queue.get_queue_item(1).status == "completed"+++def test_error_out_of_the_runner_fails_the_item_and_requests_an_unforced_empty_cache(+ mock_invoker: Invoker, mock_sqlite_database: Database, device_requests: _DeviceRequests+) -> None:+ queue, calls = _run_one_session(mock_invoker, mock_sqlite_database, device_requests, runner=_RaisingRunner())++ assert calls == [("empty_cache", False)]+ item = queue.get_queue_item(1)+ assert (item.status, item.error_message) == ("failed", "runner broke")+++def test_release_after_an_error_out_of_the_runner_runs_once_the_failed_frames_are_gone(+ mock_invoker: Invoker, mock_sqlite_database: Database, device_requests: _DeviceRequests+) -> None:+ """While the exception is in flight its traceback keeps what the failed frames hold alive, so a release made then+ would free none of it."""+ runner = _RaisingRunner()+ device_requests.sample = lambda: runner.node_memory is not None and runner.node_memory() is not None++ _run_one_session(mock_invoker, mock_sqlite_database, device_requests, runner=runner)++ assert runner.node_memory is not None+ assert device_requests.samples == [False]+++def test_a_failed_calibration_item_leaves_no_reference_cycle_through_the_exception() -> None:+ """The worker releases VRAM once it dropped the exception; a cycle (the runner's frame holding the exception it+ re-raises) would keep the failed node's tensors alive until the garbage collector ran."""+ node_memory: list[weakref.ref[_NodeMemory]] = []++ def run_session_loop(queue_item) -> None:+ memory = _NodeMemory()+ node_memory.append(weakref.ref(memory))+ raise RuntimeError("out of memory")++ runner = DefaultSessionRunner()+ runner._services = SimpleNamespace( # type: ignore[assignment]+ working_memory_calibration=SimpleNamespace(admit=lambda item, run_id: None, observe=lambda *args: None),+ logger=_Logger(),+ )+ runner._on_before_run_session = lambda queue_item: None # type: ignore[method-assign]+ runner._run_session_loop = run_session_loop # type: ignore[method-assign]+ item = SimpleNamespace(item_id=1)++ gc.disable()+ try:+ with pytest.raises(RuntimeError, match="out of memory"):+ runner._run_calibration_item(item, "run") # type: ignore[arg-type]+ assert node_memory[0]() is None+ finally:+ gc.enable()diff --git a/tests/backend/model_manager/load/model_cache/test_model_cache_make_room_in_vram.py b/tests/backend/model_manager/load/model_cache/test_model_cache_make_room_in_vram.pyindex d0d6b2d8a5..93f75d72e0 100644--- a/tests/backend/model_manager/load/model_cache/test_model_cache_make_room_in_vram.py+++ b/tests/backend/model_manager/load/model_cache/test_model_cache_make_room_in_vram.py@@ -14,7 +14,7 @@ import pytestimport torchfrom invokeai.backend.model_manager.load.model_cache.model_cache import ModelCache-from invokeai.backend.util.devices import TorchDevice+from invokeai.backend.util.devices import EmptyCacheOutcome, TorchDevicefrom tests.backend.model_manager.load.model_cache.cached_model.utils import DummyModuleMB = 2**20@@ -194,6 +194,7 @@ def test_reports_the_availability_re_measured_after_the_offloads_empty_cache(gpudef empty_cache():vram.available += 30 * MB # now the driver sees (some of) it+ return EmptyCacheOutcome.RANwith (patch.object(cache, "_get_physical_vram_available", side_effect=vram.get_physical_vram_available),diff --git a/tests/backend/model_manager/load/model_cache/test_model_cache_offload_from_vram.py b/tests/backend/model_manager/load/model_cache/test_model_cache_offload_from_vram.pyindex 46b492ce96..cc6a8c8750 100644--- a/tests/backend/model_manager/load/model_cache/test_model_cache_offload_from_vram.py+++ b/tests/backend/model_manager/load/model_cache/test_model_cache_offload_from_vram.py@@ -10,6 +10,7 @@ import pytestimport torchfrom invokeai.backend.model_manager.load.model_cache.model_cache import ModelCache+from invokeai.backend.util.devices import EmptyCacheOutcomeMB = 2**20MODULE = "invokeai.backend.model_manager.load.model_cache.model_cache"@@ -44,7 +45,7 @@ def moved(cache: ModelCache):with (patch.object(cache, "_move_model_to_ram", side_effect=move),patch(f"{MODULE}.device_has_dedicated_vram", return_value=True),- patch(f"{MODULE}.TorchDevice.empty_cache") as empty_cache,+ patch(f"{MODULE}.TorchDevice.empty_cache", return_value=EmptyCacheOutcome.RAN) as empty_cache,):yield keys, empty_cache@@ -120,7 +121,7 @@ def test_a_device_whose_vram_is_system_ram_moves_nothing(cache: ModelCache, devipatch.object(cache, "_execution_device", torch.device(device)),patch("invokeai.backend.util.devices.xpu_device_is_integrated", return_value=True),patch.object(cache, "_move_model_to_ram", return_value=MB) as move,- patch(f"{MODULE}.TorchDevice.empty_cache"),+ patch(f"{MODULE}.TorchDevice.empty_cache", return_value=EmptyCacheOutcome.RAN),):assert cache.offload_models_from_vram_except(set()) == 0move.assert_not_called()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 646445fb2f..b18338c52a 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@@ -2353,7 +2353,7 @@ def test_keep_alive_timer_start_failure_does_not_leak_a_pin(mock_logger, monkeypdef test_reconcile_hook_failure_does_not_leak_a_pin(mock_logger, monkeypatch):"""The synchronized-decorator's post-release reconcile runs inside the caller's frame after the- method body - a raise there (e.g. TorchDevice.empty_cache on a sick CUDA context) escapes+ method body - a raise there (e.g. from a clear callback) escapeslock_in_ram() after the lock count was incremented, before model_in_ram()'s unlock-pairing tryblock. It must be swallowed and logged; the pending flag persists so the next release retries."""store = SharedCpuWeightsStore()diff --git a/tests/backend/model_manager/load/model_cache/test_model_cache_vram_accounting.py b/tests/backend/model_manager/load/model_cache/test_model_cache_vram_accounting.pyindex 5dc2164b36..1dab6c304e 100644--- a/tests/backend/model_manager/load/model_cache/test_model_cache_vram_accounting.py+++ b/tests/backend/model_manager/load/model_cache/test_model_cache_vram_accounting.py@@ -17,7 +17,7 @@ import torchfrom invokeai.backend.model_manager.load.model_cache import model_cache as model_cache_modulefrom invokeai.backend.model_manager.load.model_cache.model_cache import ModelCache-from invokeai.backend.util.devices import TorchDevice+from invokeai.backend.util.devices import EmptyCacheOutcome, TorchDeviceGB = 1024**3MB = 1024**2@@ -294,12 +294,12 @@ def test_offloading_under_expandable_segments_stops_once_enough_is_free(monkeypadevice["unmappable"] += 4 * GBreturn 4 * GB- def empty_cache() -> bool:+ def empty_cache() -> EmptyCacheOutcome:if peer_busy: # deferred: nothing is released, and the driver keeps reporting the old figure- return False+ return EmptyCacheOutcome.DEFERREDdevice["free"] += device["unmappable"]device["unmappable"] = 0- return True+ return EmptyCacheOutcome.RANmonkeypatch.setenv("PYTORCH_CUDA_ALLOC_CONF", "expandable_segments:True")monkeypatch.setattr(torch.cuda, "mem_get_info", lambda d: (device["free"], 16 * GB))diff --git a/tests/backend/util/test_devices.py b/tests/backend/util/test_devices.pyindex e95c0c56fc..4a35878d2d 100644--- a/tests/backend/util/test_devices.py+++ b/tests/backend/util/test_devices.py@@ -12,6 +12,7 @@ import torchfrom invokeai.app.services.config import get_configfrom invokeai.backend.util.devices import (+ EmptyCacheOutcome,TorchDevice,choose_precision,choose_torch_device,@@ -1107,9 +1108,9 @@ def test_a_forced_empty_cache_runs_past_a_busy_peer_and_its_wrapper(monkeypatch)monkeypatch.setattr(torch.backends.mps, "is_available", lambda: False)monkeypatch.setattr(TorchDevice, "_another_generation_device_busy", classmethod(lambda cls: True))- assert TorchDevice.empty_cache() is False+ assert TorchDevice.empty_cache() is EmptyCacheOutcome.DEFERREDassert calls == []- assert TorchDevice.empty_cache(force=True) is True+ assert TorchDevice.empty_cache(force=True) is EmptyCacheOutcome.RANassert calls == ["torch"]@@ -1162,3 +1163,61 @@ def test_choose_krea2_transformer_dtype_otherwise_ignores_precision(monkeypatch,with patch.object(TorchDevice, "choose_bfloat16_safe_dtype", return_value=torch.bfloat16) as mock_safe:assert TorchDevice.choose_krea2_transformer_dtype(is_gguf=is_gguf, device=device) is torch.bfloat16mock_safe.assert_called_once_with(device)+++class _CountingObserver:+ def __init__(self) -> None:+ self.calls: list[str] = []++ def before_empty_cache(self) -> None:+ self.calls.append("before")++ def after_empty_cache(self, released: bool) -> None:+ self.calls.append(f"after:{released}")+++def refusing_backend(monkeypatch):+ """A CUDA backend whose release raises, and the observer that sees every release attempt."""+ from invokeai.backend.util import devices as devices_module++ class Backend:+ calls = 0++ def refuse(self) -> None:+ self.calls += 1+ raise torch.OutOfMemoryError("CUDA out of memory while releasing\nsecond line of detail")++ backend = Backend()+ backend.observer = _CountingObserver()+ monkeypatch.setattr(torch.cuda, "is_available", lambda: True)+ monkeypatch.setattr(torch.cuda, "empty_cache", backend.refuse)+ monkeypatch.setattr(torch.backends.mps, "is_available", lambda: False)+ monkeypatch.setattr(devices_module, "_xpu_is_available", lambda: False)+ monkeypatch.setattr(devices_module, "EMPTY_CACHE_OBSERVERS", [backend.observer])+ TorchDevice._empty_cache_deferred.clear()+ return backend+++def test_empty_cache_the_backend_refuses_is_reported_as_refused(refusing_backend, caplog):+ """An ordinary release is advisory: a device context that cannot return its cached blocks (or runs out of+ memory doing so) must not fail the eviction, offload or Empty Cache request that asked for it."""+ with caplog.at_level("WARNING"):+ outcome = TorchDevice.empty_cache()++ assert outcome is EmptyCacheOutcome.REFUSED+ assert refusing_backend.calls == 1+ assert refusing_backend.observer.calls == ["before", "after:False"]+ assert not TorchDevice._empty_cache_deferred.is_set()+ assert "CUDA out of memory while releasing" in caplog.text+ assert "second line of detail" not in caplog.text+++def test_forced_empty_cache_the_backend_refuses_raises(refusing_backend):+ """A forced caller cannot proceed as if the release ran (a short reserve hangs on Windows, a probe window would+ record a baseline that still counts the blocks), so the refusal reaches it."""+ with pytest.raises(torch.OutOfMemoryError, match="while releasing"):+ TorchDevice.empty_cache(force=True)++ assert refusing_backend.calls == 1+ assert refusing_backend.observer.calls == ["before", "after:False"]diff --git a/tests/backend/working_memory/test_probe.py b/tests/backend/working_memory/test_probe.pyindex e6c29440c2..e3ca2a0ef9 100644--- a/tests/backend/working_memory/test_probe.py+++ b/tests/backend/working_memory/test_probe.py@@ -120,7 +120,7 @@ class FakeDevice:def before_empty_cache(self) -> None:pass- def after_empty_cache(self) -> None:+ def after_empty_cache(self, released: bool) -> None:self.releases += 1if self.releases == self.fail_on_release:raise RuntimeError("the device context is sick")@@ -909,6 +909,36 @@ def test_an_empty_cache_inside_a_window_ends_a_segment_so_the_driver_peak_is_kepassert window.segments == 2+def test_a_release_the_backend_refuses_inside_a_window_is_not_a_segment_boundary(+ device: FakeDevice, monkeypatch: pytest.MonkeyPatch+):+ """An advisory release that fails (`TorchDevice.empty_cache` reports REFUSED) returned nothing, so the segment and+ its peaks run on; the next release that works ends the window's first segment."""+ refusing = False++ def empty_cache() -> None:+ if refusing:+ raise torch.OutOfMemoryError("CUDA out of memory while releasing")++ monkeypatch.setattr(torch.cuda, "is_available", lambda: True)+ monkeypatch.setattr(torch.cuda, "empty_cache", empty_cache)+ monkeypatch.setattr(torch.backends.mps, "is_available", lambda: False)+ monkeypatch.setattr(devices, "_xpu_is_available", lambda: False)+ cache = FakeCache(device)++ with _scope() as scope:+ with _model(cache, "vae").model_on_device(working_memory=_estimate()):+ device.alloc(3 * GIB)+ device.free(3 * GIB)+ refusing = True # the window opened its own baseline release already+ assert TorchDevice.empty_cache() is devices.EmptyCacheOutcome.REFUSED+ refusing = False+ assert TorchDevice.empty_cache() is devices.EmptyCacheOutcome.RAN++ (window,) = scope.windows+ assert window.segments == 2, "the release that worked and the end of the window; not the refused one"++def test_an_allocated_peak_above_the_reserved_peak_decides_the_demand(device: FakeDevice):"""cudaMallocAsync: `max_memory_reserved` measured 128 MiB under an allocated peak of 136 MiB."""cache = FakeCache(device)