Skip to content

Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.

fix: skip empty_cache while another generation device is mid-session

Lincoln Stein624a1574ff35
diff --git a/invokeai/backend/util/device_pool.py b/invokeai/backend/util/device_pool.py
index 650cec2b0c..6e7e57aa55 100644
--- a/invokeai/backend/util/device_pool.py
+++ b/invokeai/backend/util/device_pool.py
@@ -131,6 +131,23 @@ class _GenerationDevicePool:
if lock is not None:
lock.release()
+ def any_other_device_busy(self, device: Optional[torch.device]) -> bool:
+ """True when any registered generation device OTHER than ``device`` is in use.
+
+ "In use" means its exclusive-use lock is held — a native session is running on it, or
+ a borrower is running an encoder there. Used to decide whether a process-global,
+ peer-convoying operation (``TorchDevice.empty_cache``) is safe to run right now.
+ ``device=None`` (a caller with no pinned session device, e.g. a maintenance thread)
+ treats EVERY busy device as "other". Single-device and legacy installs have at most
+ one registered lock, so a device's own worker always gets False — pre-multi-GPU
+ behavior is unchanged there.
+ """
+ exclude_key = None
+ if device is not None and device.type in _OFFLOAD_DEVICE_TYPES:
+ exclude_key = str(TorchDevice.normalize(device))
+ with self._registry_lock:
+ return any(lock.locked() for key, lock in self._device_locks.items() if key != exclude_key)
+
def reset(self) -> None:
"""Clear all registered devices (used by tests)."""
with self._registry_lock:
diff --git a/invokeai/backend/util/devices.py b/invokeai/backend/util/devices.py
index 1b53fd521b..9df2d1c7aa 100644
--- a/invokeai/backend/util/devices.py
+++ b/invokeai/backend/util/devices.py
@@ -327,7 +327,30 @@ class TorchDevice:
@classmethod
def empty_cache(cls) -> None:
- """Clear the GPU device cache."""
+ """Clear the GPU device cache — unless another generation device is mid-session.
+
+ ``torch.cuda.empty_cache()`` is process-global: it takes EVERY device's
+ caching-allocator mutex and cudaFree/hipFrees their cached blocks, and a free on a
+ device with a long kernel in flight blocks until that kernel completes with the mutex
+ held. On a multi-GPU box this freezes the busy worker — it cannot allocate or even
+ deallocate a tensor — for the remainder of its current step (observed via py-spy on a
+ dual-GPU ROCm rig: one worker spinning in HIP ``release_block`` inside ``emptyCache``,
+ the other parked on the allocator mutex; a video step is 40-100 s).
+
+ empty_cache is advisory — torch reuses its own cached blocks whether or not they are
+ returned to the driver — so when any OTHER registered generation device is running a
+ session, skip it rather than convoy. Cost of skipping: driver-level free-memory
+ queries (``mem_get_info``) count the still-cached blocks as used, so the model cache's
+ VRAM accounting turns conservative until a quiet-moment call runs. On single-GPU
+ installs there is never another busy device, so behavior is unchanged.
+ """
+ if cls._another_generation_device_busy():
+ from invokeai.backend.util.logging import InvokeAILogger
+
+ InvokeAILogger.get_logger(cls.__name__).debug(
+ "Skipping empty_cache: another generation device is mid-session."
+ )
+ return
if torch.backends.mps.is_available():
torch.mps.empty_cache()
if torch.cuda.is_available():
@@ -335,6 +358,16 @@ class TorchDevice:
if _xpu_is_available():
torch.xpu.empty_cache()
+ @classmethod
+ def _another_generation_device_busy(cls) -> bool:
+ """True when a generation device OTHER than this thread's session device is running.
+
+ Imported lazily: the device pool module imports this one at top level.
+ """
+ from invokeai.backend.util.device_pool import GENERATION_DEVICE_POOL
+
+ return GENERATION_DEVICE_POOL.any_other_device_busy(cls.get_session_device())
+
@classmethod
def xpu_mem_get_info(cls, device: torch.device) -> tuple[int, int]:
"""Return ``(free, total)`` VRAM in bytes for an XPU (Intel GPU) device.
diff --git a/tests/backend/util/test_device_pool.py b/tests/backend/util/test_device_pool.py
index ffe4a731aa..85f6c0de4b 100644
--- a/tests/backend/util/test_device_pool.py
+++ b/tests/backend/util/test_device_pool.py
@@ -191,3 +191,61 @@ def test_concurrent_sessions_and_borrows_never_overlap_on_a_device():
t.join()
assert not violations, f"device(s) used concurrently by a session and a borrow: {set(violations)}"
+
+
+class TestAnyOtherDeviceBusy:
+ """any_other_device_busy() gates process-global empty_cache against peer convoys."""
+
+ def test_idle_pool_reports_not_busy(self):
+ GENERATION_DEVICE_POOL.set_generation_devices([torch.device("cuda:0"), torch.device("cuda:1")])
+ try:
+ assert not GENERATION_DEVICE_POOL.any_other_device_busy(torch.device("cuda:0"))
+ assert not GENERATION_DEVICE_POOL.any_other_device_busy(None)
+ finally:
+ GENERATION_DEVICE_POOL.reset()
+
+ def test_own_session_does_not_count(self):
+ GENERATION_DEVICE_POOL.set_generation_devices([torch.device("cuda:0"), torch.device("cuda:1")])
+ try:
+ GENERATION_DEVICE_POOL.acquire_session(torch.device("cuda:0"))
+ try:
+ # cuda:0's own worker sees no OTHER busy device...
+ assert not GENERATION_DEVICE_POOL.any_other_device_busy(torch.device("cuda:0"))
+ # ...but cuda:1's worker (and an unpinned maintenance thread) must defer to it.
+ assert GENERATION_DEVICE_POOL.any_other_device_busy(torch.device("cuda:1"))
+ assert GENERATION_DEVICE_POOL.any_other_device_busy(None)
+ finally:
+ GENERATION_DEVICE_POOL.release_session(torch.device("cuda:0"))
+ assert not GENERATION_DEVICE_POOL.any_other_device_busy(torch.device("cuda:1"))
+ finally:
+ GENERATION_DEVICE_POOL.reset()
+
+ def test_borrow_counts_as_busy(self):
+ GENERATION_DEVICE_POOL.set_generation_devices([torch.device("cuda:0"), torch.device("cuda:1")])
+ try:
+ borrowed = GENERATION_DEVICE_POOL.try_borrow(exclude=torch.device("cuda:0"))
+ assert borrowed is not None
+ try:
+ assert GENERATION_DEVICE_POOL.any_other_device_busy(torch.device("cuda:0"))
+ finally:
+ GENERATION_DEVICE_POOL.release_borrow(borrowed)
+ finally:
+ GENERATION_DEVICE_POOL.reset()
+
+ def test_single_device_never_busy_for_own_worker(self):
+ """Single-GPU installs must keep pre-multi-GPU empty_cache behavior."""
+ GENERATION_DEVICE_POOL.set_generation_devices([torch.device("cuda:0")])
+ try:
+ GENERATION_DEVICE_POOL.acquire_session(torch.device("cuda:0"))
+ try:
+ assert not GENERATION_DEVICE_POOL.any_other_device_busy(torch.device("cuda:0"))
+ finally:
+ GENERATION_DEVICE_POOL.release_session(torch.device("cuda:0"))
+ finally:
+ GENERATION_DEVICE_POOL.reset()
+
+ def test_empty_registry_never_busy(self):
+ """Legacy mode registers no devices; empty_cache must run as before."""
+ GENERATION_DEVICE_POOL.reset()
+ assert not GENERATION_DEVICE_POOL.any_other_device_busy(None)
+ assert not GENERATION_DEVICE_POOL.any_other_device_busy(torch.device("cuda:0"))
diff --git a/tests/backend/util/test_devices.py b/tests/backend/util/test_devices.py
index 5a85cb2a30..e00ba01371 100644
--- a/tests/backend/util/test_devices.py
+++ b/tests/backend/util/test_devices.py
@@ -642,3 +642,34 @@ def test_session_device_index_on_xpu():
assert TorchDevice.get_session_device_label() == " (#1)"
finally:
TorchDevice.clear_session_device()
+
+
+def test_empty_cache_skips_while_peer_device_busy(monkeypatch):
+ """TorchDevice.empty_cache() must not run the process-global (peer-convoying) empty_cache
+ while another generation device is mid-session, and must run it when the pool is quiet."""
+ import torch as torch_mod
+
+ from invokeai.backend.util.device_pool import GENERATION_DEVICE_POOL
+ from invokeai.backend.util.devices import TorchDevice
+
+ calls: list[str] = []
+ monkeypatch.setattr(torch_mod.cuda, "is_available", lambda: True)
+ monkeypatch.setattr(torch_mod.cuda, "empty_cache", lambda: calls.append("cuda"))
+ monkeypatch.setattr(torch_mod.backends.mps, "is_available", lambda: False)
+
+ GENERATION_DEVICE_POOL.set_generation_devices([torch.device("cuda:0"), torch.device("cuda:1")])
+ try:
+ TorchDevice.set_session_device(torch.device("cuda:1"))
+ try:
+ GENERATION_DEVICE_POOL.acquire_session(torch.device("cuda:0"))
+ try:
+ TorchDevice.empty_cache()
+ assert calls == [], "empty_cache ran while a peer device was mid-session"
+ finally:
+ GENERATION_DEVICE_POOL.release_session(torch.device("cuda:0"))
+ TorchDevice.empty_cache()
+ assert calls == ["cuda"], "empty_cache did not run once the pool was quiet"
+ finally:
+ TorchDevice.clear_session_device()
+ finally:
+ GENERATION_DEVICE_POOL.reset()