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(multi-gpu): cancel mid-step and release VRAM while a peer renders
Lincoln Stein4ab9d565cf4a
diff --git a/invokeai/app/services/session_processor/session_processor_default.py b/invokeai/app/services/session_processor/session_processor_default.pyindex 721d35092c..affefc84d6 100644--- a/invokeai/app/services/session_processor/session_processor_default.py+++ b/invokeai/app/services/session_processor/session_processor_default.py@@ -817,6 +817,30 @@ class DefaultSessionProcessor(SessionProcessorBase):self._poll_now()return+ def _release_vram_after_session(self, worker: _SessionWorker) -> 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.++ Both are best effort: the session's outcome is already recorded, and a free on a sick+ device context must not fail the worker.+ """+ try:+ if worker.cancel_event.is_set():+ TorchDevice.empty_cache()+ else:+ TorchDevice.flush_deferred_empty_cache()+ except Exception:+ self._invoker.services.logger.warning(+ f"Could not release cached VRAM after the session on {worker.label}", exc_info=True+ )+def resume(self) -> SessionProcessorStatus:if not self._resume_event.is_set():self._resume_event.set()@@ -1029,6 +1053,7 @@ class DefaultSessionProcessor(SessionProcessorBase):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)except Exception as e:error_type = e.__class__.__name__diff --git a/invokeai/app/services/shared/invocation_context.py b/invokeai/app/services/shared/invocation_context.pyindex fca191924c..edf876b452 100644--- a/invokeai/app/services/shared/invocation_context.py+++ b/invokeai/app/services/shared/invocation_context.py@@ -28,6 +28,7 @@ from invokeai.backend.model_manager.load.load_base import LoadedModel, LoadedModfrom invokeai.backend.model_manager.taxonomy import AnyModel, BaseModelType, ModelFormat, ModelType, SubModelTypefrom invokeai.backend.stable_diffusion.diffusers_pipeline import PipelineIntermediateStatefrom invokeai.backend.stable_diffusion.diffusion.conditioning_data import ConditioningFieldData+from invokeai.backend.util.devices import TorchDeviceif TYPE_CHECKING:from invokeai.app.invocations.baseinvocation import BaseInvocation@@ -886,6 +887,13 @@ class UtilInterface(InvocationContextInterface):original size."""+ # Every denoise loop reports here once per step, so this is where a busy worker reaches a+ # natural boundary in its own GPU work. If a peer deferred a process-global empty_cache+ # (skipped so as not to stall THIS worker mid-step), run it now, from this thread, where+ # the driver-level free costs this device at most a re-allocation of its cached working+ # blocks. A flag test when nothing is pending.+ TorchDevice.flush_deferred_empty_cache()+queue_item = self._data.queue_itemif image is None:diff --git a/invokeai/backend/minimax_h3/denoise.py b/invokeai/backend/minimax_h3/denoise.pyindex 6e299ddb1d..1b8fcc5834 100644--- a/invokeai/backend/minimax_h3/denoise.py+++ b/invokeai/backend/minimax_h3/denoise.py@@ -16,8 +16,9 @@ Unset, the loop behaves exactly as before.import osimport time+from contextlib import contextmanagerfrom pathlib import Path-from typing import Callable+from typing import Callable, Iteratorimport torch@@ -122,6 +123,35 @@ def _profile_one_step(trace_target: str, device: torch.device, run_step: Callabllogger.warning(f"MiniMax H3 denoise: failed to write profile files to {trace_dir}", exc_info=True)+@contextmanager+def _cancel_between_blocks(+ transformer: MiniMaxH3Transformer3DModel, is_canceled: Callable[[], bool] | None+) -> Iterator[None]:+ """Poll ``is_canceled`` before every transformer block for the duration of the context.++ A step is one forward through the full block stack — 40-100 s for a video on the reference+ dual-GPU rig — and the step loop only polls between steps, so a cancel used to keep the GPU+ busy for the rest of the step. Polling from a forward pre-hook on each block bounds the+ latency to one block plus the drain of the kernels already queued. The hooks are removed on+ exit: the transformer is a shared cache resident, and the callback belongs to this session.+ """+ if is_canceled is None:+ yield+ return+ from invokeai.app.services.session_processor.session_processor_common import CanceledException++ def raise_if_canceled(module: torch.nn.Module, args: tuple[object, ...]) -> None:+ if is_canceled():+ raise CanceledException++ handles = [block.register_forward_pre_hook(raise_if_canceled) for block in transformer.transformer_blocks]+ try:+ yield+ finally:+ for handle in handles:+ handle.remove()++def denoise(transformer: MiniMaxH3Transformer3DModel,state: MiniMaxH3DenoiseState,@@ -139,8 +169,9 @@ def denoise(— the step's *predicted-clean* (x-hat-0) estimate of the GENERATED video rows(conditioning rows excluded), float32, for previews. Unlike the noisy runninglatents, the prediction is decodable at every step.- is_canceled: Polled once per step; a True return raises ``KeyboardInterrupt``-free- cancellation by letting the caller's exception type propagate from the callback.+ is_canceled: Polled before every step and before every transformer block within a step;+ a True return raises ``CanceledException`` from inside the forward, so a cancel takes+ effect within one block rather than at the end of a 40-100 s step.Returns:The denoised ``(video_rows, audio_rows)`` (conditioning/reference rows still included).@@ -202,14 +233,15 @@ def denoise(assert pred_x0_video_rows is not Nonestep_callback(i + 1, total_steps, pred_x0_video_rows)- for i, t in enumerate(state.timesteps):- if is_canceled is not None and is_canceled():- raise CanceledException+ with _cancel_between_blocks(transformer, is_canceled):+ for i, t in enumerate(state.timesteps):+ if is_canceled is not None and is_canceled():+ raise CanceledException- if i == profile_step_index:- assert profile_target is not None- _profile_one_step(profile_target, latents.device, lambda i=i, t=t: run_step(i, t))- else:- run_step(i, t)+ if i == profile_step_index:+ assert profile_target is not None+ _profile_one_step(profile_target, latents.device, lambda i=i, t=t: run_step(i, t))+ else:+ run_step(i, t)return latents, audio_latentsdiff --git a/invokeai/backend/util/devices.py b/invokeai/backend/util/devices.pyindex 3d55c3fe95..7a28973344 100644--- a/invokeai/backend/util/devices.py+++ b/invokeai/backend/util/devices.py@@ -68,6 +68,12 @@ class TorchDevice:# patcher, etc.) resolve to the calling worker's GPU without per-call-site changes._session_device = threading.local()+ # 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`).+ _empty_cache_deferred = threading.Event()+@classmethoddef set_session_device(cls, device: Union[str, torch.device]) -> None:"""Pin the calling thread's execution device. Used by multi-GPU session workers."""@@ -343,13 +349,27 @@ class TorchDevice:session, skip it rather than convoy. Cost of skipping: driver-level free-memoryqueries (``mem_get_info``) count the still-cached blocks as used, so the model cache'sVRAM accounting turns conservative until a quiet-moment call runs. On single-GPU- installs there is never another busy device, so behavior is unchanged.+ installs a worker never sees another busy device, so its own calls run as before; only+ a 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.++ A skipped call is recorded as deferred rather than dropped: the memory it would have+ returned (a canceled session's working set, a timed-out cache's weights) stays cached in+ the allocator — invisible to the caller's own accounting, but counted as used by the+ driver and every other process — until `flush_deferred_empty_cache()` runs it from a+ quiet moment. Without that, VRAM freed on one GPU stayed resident until the peer's+ whole render finished and something else happened to call empty_cache."""if cls._another_generation_device_busy():+ cls._empty_cache_deferred.set()InvokeAILogger.get_logger(cls.__name__).debug(- "Skipping empty_cache: another generation device is mid-session."+ "Deferring empty_cache: another generation device is mid-session.")return+ # 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()if torch.backends.mps.is_available():torch.mps.empty_cache()if torch.cuda.is_available():@@ -357,6 +377,23 @@ class TorchDevice:if _xpu_is_available():torch.xpu.empty_cache()+ @classmethod+ def flush_deferred_empty_cache(cls) -> None:+ """Run an empty_cache that a peer-aware skip deferred, if the pool is quiet now.++ Call this from points where the calling worker's own device is at a natural sync point+ 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 call+ often. 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.+ """+ if not cls._empty_cache_deferred.is_set():+ return+ cls.empty_cache()+@classmethoddef _another_generation_device_busy(cls) -> bool:"""True when a generation device OTHER than this thread's session device is running.@@ -490,10 +527,13 @@ def install_peer_aware_empty_cache() -> None:@wraps(original_empty_cache)def peer_aware_empty_cache() -> None:if TorchDevice._another_generation_device_busy():+ # Deferred, not dropped — see TorchDevice.empty_cache / flush_deferred_empty_cache.+ TorchDevice._empty_cache_deferred.set()InvokeAILogger.get_logger("TorchDevice").debug(- "Skipping torch.cuda.empty_cache: another generation device is mid-session."+ "Deferring torch.cuda.empty_cache: another generation device is mid-session.")return+ TorchDevice._empty_cache_deferred.clear()original_empty_cache()setattr(peer_aware_empty_cache, _PEER_AWARE_SENTINEL, True)diff --git a/invokeai/backend/util/vae_decode_diagnostics.py b/invokeai/backend/util/vae_decode_diagnostics.pyindex 735faca89c..d1468422bd 100644--- a/invokeai/backend/util/vae_decode_diagnostics.py+++ b/invokeai/backend/util/vae_decode_diagnostics.py@@ -136,6 +136,8 @@ def force_real_empty_cache() -> None:that they did this — a peer device's in-flight step will stall until this returns."""real = getattr(torch.cuda.empty_cache, "__wrapped__", torch.cuda.empty_cache)+ # A real, process-global release satisfies any release a peer-aware skip deferred.+ TorchDevice._empty_cache_deferred.clear()real()diff --git a/tests/app/services/progress_previews/test_signal_progress.py b/tests/app/services/progress_previews/test_signal_progress.pyindex 1754f7f933..20dbf51402 100644--- a/tests/app/services/progress_previews/test_signal_progress.py+++ b/tests/app/services/progress_previews/test_signal_progress.py@@ -70,3 +70,20 @@ def test_imageless_progress_is_neither_throttled_nor_revisioned() -> None:assert len(events.emitted) == 2assert all("revision" not in call and call.get("image") is None for call in events.emitted)assert previews.get(7) is None+++def test_signal_progress_flushes_a_deferred_empty_cache(monkeypatch) -> None:+ """Every denoise loop reports progress once per step, which is the busy worker's natural+ boundary for performing a process-global empty_cache that a peer deferred. Both the+ imageless and the image-bearing paths must reach the flush."""+ from invokeai.backend.util.devices import TorchDevice++ flushes: list[int] = []+ monkeypatch.setattr(TorchDevice, "flush_deferred_empty_cache", classmethod(lambda cls: flushes.append(1)))+ clock = _Clock()+ util, _events, _previews = _util(clock)++ util.signal_progress("Denoising", 0.1)+ assert len(flushes) == 1+ util.signal_progress("Denoising", 0.2, Image.new("RGB", (8, 8)), (64, 64))+ assert len(flushes) == 2diff --git a/tests/app/services/session_processor/test_release_vram_after_session.py b/tests/app/services/session_processor/test_release_vram_after_session.pynew file mode 100644index 0000000000..796a0f24d8--- /dev/null+++ b/tests/app/services/session_processor/test_release_vram_after_session.py@@ -0,0 +1,68 @@+"""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."""++import threading+from types import SimpleNamespace++from invokeai.app.services.session_processor.session_processor_default import DefaultSessionProcessor+from invokeai.backend.util.devices import TorchDevice+++class _Logger:+ def __init__(self) -> None:+ self.warnings: list[str] = []++ def warning(self, message: str, **kwargs) -> None:+ self.warnings.append(message)+++def _processor() -> tuple[DefaultSessionProcessor, _Logger]:+ logger = _Logger()+ processor = DefaultSessionProcessor()+ processor._invoker = SimpleNamespace(services=SimpleNamespace(logger=logger)) # type: ignore[attr-defined]+ return processor, logger+++def _worker(canceled: bool) -> SimpleNamespace:+ event = threading.Event()+ if canceled:+ event.set()+ return SimpleNamespace(cancel_event=event, label="worker (cuda:0)")+++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")))+ processor, logger = _processor()++ processor._release_vram_after_session(_worker(canceled=True)) # type: ignore[arg-type]++ assert calls == ["empty"]+ 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()++ processor._release_vram_after_session(_worker(canceled=False)) # type: ignore[arg-type]++ assert calls == ["flush"]+ assert logger.warnings == []+++def test_release_failure_is_logged_not_raised(monkeypatch) -> None:+ def boom(cls) -> None:+ raise RuntimeError("HIP error: invalid device context")++ monkeypatch.setattr(TorchDevice, "empty_cache", classmethod(boom))+ processor, logger = _processor()++ processor._release_vram_after_session(_worker(canceled=True)) # type: ignore[arg-type]++ assert len(logger.warnings) == 1+ assert "cuda:0" in logger.warnings[0]diff --git a/tests/backend/minimax_h3/test_denoise.py b/tests/backend/minimax_h3/test_denoise.pyindex 96b7b92540..ab70898aa7 100644--- a/tests/backend/minimax_h3/test_denoise.py+++ b/tests/backend/minimax_h3/test_denoise.py@@ -119,6 +119,47 @@ def test_cancellation_raises(tiny_transformer):denoise(tiny_transformer, state, prompt_embeds, is_canceled=lambda: next(polls))+def test_cancellation_is_polled_between_transformer_blocks():+ """A cancel that lands mid-step must stop the forward at the next block boundary, not at+ the end of the step: with two blocks, a poll that turns True after the first block's+ pre-hook leaves the second block unrun. The hooks must not outlive the call — the+ transformer is a shared cache resident."""+ torch.manual_seed(0)+ transformer = MiniMaxH3Transformer3DModel(**{**TINY_CONFIG, "num_layers": 2})+ transformer.eval()+ block_forwards: list[int] = []+ for index, block in enumerate(transformer.transformer_blocks):+ block.register_forward_hook(lambda module, args, output, index=index: block_forwards.append(index))+ hooks_before = [dict(block._forward_pre_hooks) for block in transformer.transformer_blocks]++ state = _state()+ prompt_embeds = torch.randn(1, 3, TINY_CONFIG["text_dim"])+ # Polls: step-loop check (False), block 0 pre-hook (False), block 1 pre-hook (True).+ polls = iter([False, False, True])+ with pytest.raises(CanceledException):+ denoise(transformer, state, prompt_embeds, is_canceled=lambda: next(polls))++ assert block_forwards == [0], "the forward did not stop at the first block boundary after the cancel"+ assert [dict(block._forward_pre_hooks) for block in transformer.transformer_blocks] == hooks_before, (+ "cancel pre-hooks leaked onto the shared transformer"+ )+++def test_uncanceled_run_leaves_no_hooks_and_polls_every_block(tiny_transformer):+ polls: list[bool] = []++ def is_canceled() -> bool:+ polls.append(False)+ return False++ state = _state()+ prompt_embeds = torch.randn(1, 3, TINY_CONFIG["text_dim"])+ denoise(tiny_transformer, state, prompt_embeds, is_canceled=is_canceled)+ # One poll per step plus one per block per step.+ assert len(polls) == NUM_EVALS * (1 + TINY_CONFIG["num_layers"])+ assert all(not block._forward_pre_hooks for block in tiny_transformer.transformer_blocks)++def test_denoise_is_deterministic(tiny_transformer):prompt_embeds = torch.randn(1, 3, TINY_CONFIG["text_dim"], generator=torch.Generator().manual_seed(2))v1, a1 = denoise(tiny_transformer, _state(), prompt_embeds.clone())diff --git a/tests/backend/util/test_devices.py b/tests/backend/util/test_devices.pyindex ac6a764246..b4716084ae 100644--- a/tests/backend/util/test_devices.py+++ b/tests/backend/util/test_devices.py@@ -716,6 +716,96 @@ def test_install_peer_aware_empty_cache_wraps_torch_entry_point(monkeypatch):torch_mod.cuda.empty_cache = original+def test_skipped_empty_cache_is_deferred_and_flushed_at_a_quiet_moment(monkeypatch):+ """A peer-aware skip must not lose the release: it is recorded as deferred, stays pending+ while any other device is still busy, and is performed exactly once by the first flush that+ finds the pool 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")])+ TorchDevice._empty_cache_deferred.clear()+ try:+ # Nothing pending: a flush is a no-op even when quiet.+ TorchDevice.flush_deferred_empty_cache()+ assert calls == []++ # Worker on cuda:0 finishes (cancels) while cuda:1 is mid-render: its release is deferred.+ GENERATION_DEVICE_POOL.acquire_session(torch.device("cuda:1"))+ TorchDevice.set_session_device(torch.device("cuda:0"))+ try:+ TorchDevice.empty_cache()+ assert calls == []+ assert TorchDevice._empty_cache_deferred.is_set(), "skip did not record a deferred release"+ # The requester itself cannot flush while the peer is busy; the request stays pending.+ TorchDevice.flush_deferred_empty_cache()+ assert calls == []+ assert TorchDevice._empty_cache_deferred.is_set()+ finally:+ TorchDevice.clear_session_device()++ # The busy worker on cuda:1 reaches a step boundary: no OTHER device is busy from its+ # point of view, so it performs the deferred release itself, once.+ TorchDevice.set_session_device(torch.device("cuda:1"))+ try:+ TorchDevice.flush_deferred_empty_cache()+ assert calls == ["cuda"], "busy worker did not flush the deferred release at its step boundary"+ assert not TorchDevice._empty_cache_deferred.is_set()+ TorchDevice.flush_deferred_empty_cache()+ assert calls == ["cuda"], "a flushed request was repeated"+ finally:+ TorchDevice.clear_session_device()+ GENERATION_DEVICE_POOL.release_session(torch.device("cuda:1"))+ finally:+ TorchDevice._empty_cache_deferred.clear()+ GENERATION_DEVICE_POOL.reset()+++def test_peer_aware_wrapper_defers_and_a_direct_run_clears_the_request(monkeypatch):+ """Third-party calls through the installed torch.cuda.empty_cache wrapper defer the same+ way, and any real run (from either entry point) satisfies the pending request."""+ 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"))+ TorchDevice._empty_cache_deferred.clear()+ try:+ install_peer_aware_empty_cache()+ GENERATION_DEVICE_POOL.set_generation_devices([torch.device("cuda:0"), torch.device("cuda:1")])+ try:+ TorchDevice.set_session_device(torch.device("cuda:0"))+ GENERATION_DEVICE_POOL.acquire_session(torch.device("cuda:1"))+ try:+ torch_mod.cuda.empty_cache() # what diffusers calls+ assert calls == []+ assert TorchDevice._empty_cache_deferred.is_set(), "wrapper skip did not defer the release"+ finally:+ GENERATION_DEVICE_POOL.release_session(torch.device("cuda:1"))+ # Quiet again: a direct call runs and clears the request, so a later flush is a no-op.+ torch_mod.cuda.empty_cache()+ assert calls == ["cuda"]+ assert not TorchDevice._empty_cache_deferred.is_set(), "a real run left the request pending"+ TorchDevice.flush_deferred_empty_cache()+ assert calls == ["cuda"]+ finally:+ TorchDevice.clear_session_device()+ GENERATION_DEVICE_POOL.reset()+ finally:+ TorchDevice._empty_cache_deferred.clear()+ torch_mod.cuda.empty_cache = original++def test_disable_conv_benchmark_empty_cache_flips_torch_flag():"""The multi-GPU startup path must clear torch's post-conv-find emptyCache flag (and no-opgracefully on builds that lack it)."""diff --git a/tests/conftest.py b/tests/conftest.pyindex dc7de96b48..f0ab3cf4aa 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -41,6 +41,17 @@ from tests.fixtures.sqlite_database import create_mock_sqlite_database # noqa:from tests.test_nodes import TestEventService[email protected](autouse=True)+def _clear_deferred_empty_cache():+ """`TorchDevice._empty_cache_deferred` is process-global: a test that exercises a peer-aware+ skip must not make a later test perform a real (GPU-initializing) empty_cache."""+ from invokeai.backend.util.devices import TorchDevice++ TorchDevice._empty_cache_deferred.clear()+ yield+ TorchDevice._empty_cache_deferred.clear()++@pytest.fixturedef mock_services() -> InvocationServices:# Image indexing is on by default, but `model_manager` below is None: starting