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: wrap torch.cuda.empty_cache itself with the peer-aware guard
Lincoln Stein6a5f993629f4
diff --git a/invokeai/app/util/startup_utils.py b/invokeai/app/util/startup_utils.pyindex 08368021cf..aaa0097b83 100644--- a/invokeai/app/util/startup_utils.py+++ b/invokeai/app/util/startup_utils.py@@ -65,6 +65,14 @@ def apply_monkeypatches() -> None:import invokeai.backend.util.hotfixes # noqa: F401 (monkeypatching on import)+ # Third-party libraries (diffusers calls empty_device_cache inside every from_pretrained /+ # from_single_file) invoke torch.cuda.empty_cache directly, convoying a busy peer GPU on+ # multi-GPU installs. Wrap the torch entry point so every Python caller inherits the+ # skip-while-a-peer-generates policy.+ from invokeai.backend.util.devices import install_peer_aware_empty_cache++ install_peer_aware_empty_cache()+def register_mime_types() -> None:"""Register additional mime types for windows."""diff --git a/invokeai/backend/util/devices.py b/invokeai/backend/util/devices.pyindex 9df2d1c7aa..23e1c33675 100644--- a/invokeai/backend/util/devices.py+++ b/invokeai/backend/util/devices.py@@ -1,5 +1,6 @@import threadingfrom collections import Counter, defaultdict+from functools import wrapsfrom typing import Dict, Literal, Optional, Unionimport torch@@ -345,8 +346,6 @@ class TorchDevice: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.")@@ -464,3 +463,38 @@ class TorchDevice:if config.precision == "auto":return cls.choose_bfloat16_safe_dtype(device)return NAME_TO_PRECISION[config.precision]+++_PEER_AWARE_SENTINEL = "_invokeai_peer_aware"+++def install_peer_aware_empty_cache() -> None:+ """Rebind ``torch.cuda.empty_cache`` itself with the peer-aware guard (idempotent).++ ``TorchDevice.empty_cache`` already skips while another generation device is mid-session,+ but third-party libraries call ``torch.cuda.empty_cache`` directly and convoy the peer all+ the same — py-spy caught diffusers doing it from inside every model materialization+ (``from_pretrained`` -> ``_load_pretrained_model`` -> ``empty_device_cache``,+ ``modeling_utils.py``; likewise ``from_single_file``), freezing the other GPU's in-flight+ denoise for the remainder of its step. Wrapping the torch entry point makes every Python+ caller inherit the policy. (Torch-internal C++ callers — e.g. MIOpen's chooseAlgorithm+ workspace-OOM fallback — bypass Python entirely and remain out of reach.)++ Installed once at startup via ``apply_monkeypatches``. Single-GPU installs never have an+ "other" busy device, so the wrapper is a pass-through there.+ """+ if getattr(torch.cuda.empty_cache, _PEER_AWARE_SENTINEL, False):+ return+ original_empty_cache = torch.cuda.empty_cache++ @wraps(original_empty_cache)+ def peer_aware_empty_cache() -> None:+ if TorchDevice._another_generation_device_busy():+ InvokeAILogger.get_logger("TorchDevice").debug(+ "Skipping torch.cuda.empty_cache: another generation device is mid-session."+ )+ return+ original_empty_cache()++ setattr(peer_aware_empty_cache, _PEER_AWARE_SENTINEL, True)+ torch.cuda.empty_cache = peer_aware_empty_cachediff --git a/tests/backend/util/test_devices.py b/tests/backend/util/test_devices.pyindex e00ba01371..57ac821f39 100644--- a/tests/backend/util/test_devices.py+++ b/tests/backend/util/test_devices.py@@ -673,3 +673,44 @@ def test_empty_cache_skips_while_peer_device_busy(monkeypatch):TorchDevice.clear_session_device()finally:GENERATION_DEVICE_POOL.reset()+++def test_install_peer_aware_empty_cache_wraps_torch_entry_point(monkeypatch):+ """Third-party callers (diffusers' internal empty_device_cache) invoke+ torch.cuda.empty_cache directly; the installed wrapper must apply the same+ skip-while-a-peer-generates policy, idempotently, and pass through when quiet."""+ import torch as torch_mod++ from invokeai.backend.util.device_pool import GENERATION_DEVICE_POOL+ from invokeai.backend.util.devices import TorchDevice, install_peer_aware_empty_cache++ calls: list[str] = []+ original = torch_mod.cuda.empty_cache+ monkeypatch.setattr(torch_mod.cuda, "empty_cache", lambda: calls.append("cuda"))+ try:+ install_peer_aware_empty_cache()+ wrapped = torch_mod.cuda.empty_cache+ assert wrapped is not original+ install_peer_aware_empty_cache()+ assert torch_mod.cuda.empty_cache is wrapped, "install must be idempotent"++ 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:+ torch_mod.cuda.empty_cache() # what diffusers calls+ assert calls == [], "wrapper ran empty_cache while a peer was mid-session"+ finally:+ GENERATION_DEVICE_POOL.release_session(torch.device("cuda:0"))+ torch_mod.cuda.empty_cache()+ assert calls == ["cuda"], "wrapper did not pass through once quiet"+ finally:+ TorchDevice.clear_session_device()+ finally:+ GENERATION_DEVICE_POOL.reset()+ finally:+ # monkeypatch restores the attribute we set; make sure the true original is back for+ # other tests regardless of ordering.+ torch_mod.cuda.empty_cache = original