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(minimax-h3): cancel the video VAE decode within one tile
Lincoln Stein9ee33316b332
diff --git a/invokeai/app/invocations/minimax_h3_latents_to_video.py b/invokeai/app/invocations/minimax_h3_latents_to_video.pyindex b8b766fe92..9cf4e85065 100644--- a/invokeai/app/invocations/minimax_h3_latents_to_video.py+++ b/invokeai/app/invocations/minimax_h3_latents_to_video.py@@ -36,6 +36,7 @@ from invokeai.backend.minimax_h3.packing import (MINIMAX_H3_PIXEL_STD,)from invokeai.backend.model_manager.load.model_cache.utils import get_effective_device+from invokeai.backend.util.cancel_hooks import cancel_before_forwardfrom invokeai.backend.util.devices import TorchDevicefrom invokeai.backend.util.vae_working_memory import estimate_vae_working_memory_minimax_h3@@ -99,7 +100,9 @@ def decode_video_latents(# The H3 VAE tiles spatially by default (256px tiles / 64px overlap) and the released# frames are the blended-tile ones — never toggle tiling on the shared cached instance:# it would silently change every later encode/decode using the same cached model.- with torch.inference_mode():+ # The decoder runs once per spatial tile of every temporal chunk, so a cancel lands within+ # one tile rather than at the end of the whole decode.+ with torch.inference_mode(), cancel_before_forward([vae.decoder], context.util.is_canceled, device):latents_mean = torch.tensor(vae.config.latents_mean).view(1, -1, 1, 1, 1).to(latents)latents_std = torch.tensor(vae.config.latents_std).view(1, -1, 1, 1, 1).to(latents)latents = latents * latents_std + latents_meandiff --git a/invokeai/backend/minimax_h3/denoise.py b/invokeai/backend/minimax_h3/denoise.pyindex 1b76fcb96e..3e77b441db 100644--- a/invokeai/backend/minimax_h3/denoise.py+++ b/invokeai/backend/minimax_h3/denoise.py@@ -16,14 +16,15 @@ Unset, the loop behaves exactly as before.import osimport time-from contextlib import contextmanagerfrom pathlib import Path-from typing import Callable, Iterator+from typing import Callableimport torch+from invokeai.app.services.session_processor.session_processor_common import CanceledExceptionfrom invokeai.backend.minimax_h3.sampling import MiniMaxH3DenoiseStatefrom invokeai.backend.minimax_h3.transformer_minimax_h3 import MiniMaxH3Transformer3DModel+from invokeai.backend.util.cancel_hooks import cancel_before_forwardfrom invokeai.backend.util.logging import InvokeAILoggerPROFILE_ENV_VAR = "INVOKEAI_PROFILE_H3_DENOISE"@@ -123,42 +124,6 @@ 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, device: torch.device-) -> 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 — provided the poll waits for the queued kernels first. Kernel launches- are asynchronous: left alone, the CPU enqueues the whole step's blocks in tens of- milliseconds and parks at the step's end, so every poll would already have run by the time a- mid-step cancel arrived and the GPU would grind through the step regardless. Waiting for the- previous block's kernels to finish before each poll costs one launch gap, under a millisecond- (below 0.5% of a step at production sizes). 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 device.type != "cpu":- torch.accelerator.synchronize(device)- 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,@@ -184,8 +149,6 @@ def denoise(Returns:The denoised ``(video_rows, audio_rows)`` (conditioning/reference rows still included)."""- from invokeai.app.services.session_processor.session_processor_common import CanceledException-num_condition_video_rows = state.layout.num_condition_video_rowsnum_condition_audio_rows = state.layout.num_condition_audio_rows@@ -241,7 +204,9 @@ def denoise(assert pred_x0_video_rows is not Nonestep_callback(i + 1, total_steps, pred_x0_video_rows)- with _cancel_between_blocks(transformer, is_canceled, latents.device):+ # One step is a forward through the full block stack (40-100 s for a video on the reference+ # dual-GPU rig), so the step loop's own poll is not enough: poll before every block too.+ with cancel_before_forward(transformer.transformer_blocks, is_canceled, latents.device):for i, t in enumerate(state.timesteps):if is_canceled is not None and is_canceled():raise CanceledExceptiondiff --git a/invokeai/backend/util/cancel_hooks.py b/invokeai/backend/util/cancel_hooks.pynew file mode 100644index 0000000000..5ed763e421--- /dev/null+++ b/invokeai/backend/util/cancel_hooks.py@@ -0,0 +1,45 @@+"""Cancel a session from inside a long model call, at the boundaries of its units of work."""++from collections.abc import Callable, Iterable, Iterator+from contextlib import contextmanager++import torch++from invokeai.app.services.session_processor.session_processor_common import CanceledException+++@contextmanager+def cancel_before_forward(+ modules: Iterable[torch.nn.Module], is_canceled: Callable[[], bool] | None, device: torch.device+) -> Iterator[None]:+ """Poll ``is_canceled`` before every forward of ``modules`` for the duration of the context.++ A long inference call — a denoise step through 50 transformer blocks, a VAE decode over a few+ hundred tiles — returns to the caller only once, so a cancel polled between calls leaves the+ GPU busy for the rest of the call. Polling from a forward pre-hook on each unit of work bounds+ the latency to one unit — provided the poll waits for the queued kernels first. Kernel launches+ are asynchronous: left alone, the CPU enqueues the whole call's kernels in tens of milliseconds+ and parks at the first host sync, so every poll would already have run by the time a mid-call+ cancel arrived and the GPU would grind through regardless. Waiting for the previous unit's+ kernels before each poll costs one launch gap, under a millisecond (below 0.5% of a ~1 s+ transformer block at production sizes).++ A cancel raises ``CanceledException`` from inside the forward. The hooks are removed on exit:+ the modules belong to a shared cache resident, and the callback belongs to this session.+ """+ if is_canceled is None:+ yield+ return++ def raise_if_canceled(module: torch.nn.Module, args: tuple[object, ...]) -> None:+ if device.type != "cpu":+ torch.accelerator.synchronize(device)+ if is_canceled():+ raise CanceledException++ handles = [module.register_forward_pre_hook(raise_if_canceled) for module in modules]+ try:+ yield+ finally:+ for handle in handles:+ handle.remove()diff --git a/tests/app/invocations/test_minimax_h3_latents_to_video.py b/tests/app/invocations/test_minimax_h3_latents_to_video.pynew file mode 100644index 0000000000..d5649fe8de--- /dev/null+++ b/tests/app/invocations/test_minimax_h3_latents_to_video.py@@ -0,0 +1,75 @@+"""Cancellation inside the MiniMax H3 video VAE decode, on a micro-config CPU autoencoder.++A decode is one `vae.decode` call that runs the decoder once per spatial tile of every temporal+chunk. A cancel must land at the next tile rather than after the whole decode, and must leave no+hooks on the shared model.+"""++from contextlib import nullcontext+from unittest.mock import MagicMock++import pytest+import torch++from invokeai.app.invocations.minimax_h3_latents_to_video import decode_video_latents+from invokeai.app.services.session_processor.session_processor_common import CanceledException+from invokeai.backend.minimax_h3.autoencoder_kl_minimax_h3 import AutoencoderKLMiniMaxH3++LATENT_CHANNELS = 4+# 7 latent frames (5n+2, one chunk) at 20x20 latents = 320x320 px = four 256-px tiles.+LATENTS_SHAPE = (1, LATENT_CHANNELS, 7, 20, 20)+NUM_TILES = 4+++def vae() -> AutoencoderKLMiniMaxH3:+ torch.manual_seed(0)+ return AutoencoderKLMiniMaxH3(+ latent_channels=LATENT_CHANNELS,+ block_out_channels=(8, 8, 8, 8, 8, 8),+ norm_num_groups=8,+ layers_per_block=1,+ decoder_num_layers=1,+ decoder_num_attention_heads=1,+ decoder_attention_head_dim=8,+ latents_mean=(0.0,) * LATENT_CHANNELS,+ latents_std=(1.0,) * LATENT_CHANNELS,+ ).eval()+++def _context(vae: AutoencoderKLMiniMaxH3, polls: list[bool]) -> MagicMock:+ """A context whose model loader hands back `vae` on the CPU and whose cancel poll answers+ from `polls` in order."""+ context = MagicMock()+ context.models.load.return_value.model = vae+ context.models.load.return_value.model_on_device.return_value = nullcontext((None, vae))+ answers = iter(polls)+ context.util.is_canceled.side_effect = lambda: next(answers)+ return context+++def _count_decoder_forwards(vae: AutoencoderKLMiniMaxH3) -> list[int]:+ count = [0]+ vae.decoder.register_forward_hook(lambda module, args, output: count.__setitem__(0, count[0] + 1))+ return count+++def test_cancel_lands_within_a_tile(vae):+ decoder_forwards = _count_decoder_forwards(vae)+ # Polls: tile 0 (False), tile 1 (True); the remaining tiles never run.+ context = _context(vae, [False, True])+ with pytest.raises(CanceledException):+ decode_video_latents(context, MagicMock(), torch.randn(*LATENTS_SHAPE))+ assert decoder_forwards[0] == 1, "the decode did not stop at the first tile boundary after the cancel"+ assert not vae.decoder._forward_pre_hooks, "cancel hooks leaked onto the shared video VAE"+++def test_uncanceled_decode_polls_per_tile_and_leaves_no_hooks(vae):+ decoder_forwards = _count_decoder_forwards(vae)+ context = _context(vae, [False] * NUM_TILES)+ decoded = decode_video_latents(context, MagicMock(), torch.randn(*LATENTS_SHAPE))+ assert decoder_forwards[0] == NUM_TILES+ assert context.util.is_canceled.call_count == NUM_TILES+ assert decoded.shape == (3, 22, 320, 320)+ assert decoded.device.type == "cpu"+ assert not vae.decoder._forward_pre_hooksdiff --git a/tests/backend/minimax_h3/test_denoise.py b/tests/backend/minimax_h3/test_denoise.pyindex d304502d94..ab70898aa7 100644--- a/tests/backend/minimax_h3/test_denoise.py+++ b/tests/backend/minimax_h3/test_denoise.py@@ -1,13 +1,10 @@-"""Tests for the MiniMax H3 denoising loop: a micro-config CPU transformer, plus one slow GPU test."""--import threading-import time+"""Tests for the MiniMax H3 denoising loop, on a micro-config CPU transformer."""import pytestimport torchfrom invokeai.app.services.session_processor.session_processor_common import CanceledException-from invokeai.backend.minimax_h3.denoise import _cancel_between_blocks, denoise+from invokeai.backend.minimax_h3.denoise import denoisefrom invokeai.backend.minimax_h3.sampling import build_denoise_statefrom invokeai.backend.minimax_h3.transformer_minimax_h3 import MiniMaxH3Transformer3DModel@@ -148,85 +145,6 @@ def test_cancellation_is_polled_between_transformer_blocks():)-class _HeavyBlock(torch.nn.Module):- """Tens of milliseconds of GPU work per call: a step of them outlasts the CPU's enqueue time- by orders of magnitude, as the real stack does."""-- DIM = 8192-- def __init__(self, device: torch.device):- super().__init__()- self.weight = torch.nn.Parameter(torch.randn(self.DIM, self.DIM, dtype=torch.bfloat16, device=device) * 0.01)-- def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:- for _ in range(8):- hidden_states = torch.nn.functional.layer_norm(hidden_states @ self.weight, (self.DIM,)).to(torch.bfloat16)- return hidden_states---class _HeavyStack(torch.nn.Module):- """Stands in for the transformer: `_cancel_between_blocks` only needs `transformer_blocks`."""-- def __init__(self, device: torch.device, num_blocks: int):- super().__init__()- self.transformer_blocks = torch.nn.ModuleList([_HeavyBlock(device) for _ in range(num_blocks)])-- def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:- for block in self.transformer_blocks:- hidden_states = block(hidden_states)- return hidden_states--[email protected](not torch.cuda.is_available(), reason="measures cancel latency against queued GPU kernels")-def test_mid_step_cancel_idles_the_gpu_within_a_block():- """Kernel launches are asynchronous: without a wait in the poll, the CPU enqueues every block- of a step in tens of milliseconds and parks at the step's end, so a cancel landing mid-step- is not seen until the next step and the GPU grinds through the whole step (observed on the- dual-GPU rig: a cancel during H3 step 2 kept the GPU busy until the step ended). The poll- must wait for the queued work, so that the GPU goes idle within about a block of the cancel."""- device = torch.device("cuda")- num_blocks = 16- torch.manual_seed(0)- stack = _HeavyStack(device, num_blocks).eval()- hidden_states = torch.randn(4096, _HeavyBlock.DIM, dtype=torch.bfloat16, device=device)- cancel = threading.Event()-- def timed_forward(stack: _HeavyStack, hidden_states: torch.Tensor) -> tuple[float, bool]:- torch.cuda.synchronize(device)- start = time.perf_counter()- canceled = False- try:- with torch.no_grad(), _cancel_between_blocks(stack, cancel.is_set, device): # type: ignore[arg-type]- stack(hidden_states)- except CanceledException:- canceled = True- torch.cuda.synchronize(device)- return time.perf_counter() - start, canceled-- full_step, canceled = timed_forward(stack, hidden_states)- assert not canceled- block_time = full_step / num_blocks-- cancel_at = full_step * 0.4- timer = threading.Timer(cancel_at, cancel.set)- timer.start()- try:- elapsed, canceled = timed_forward(stack, hidden_states)- finally:- timer.cancel()- # 2 GiB of synthetic weights: hand them back rather than leaving them cached for the session.- del stack, hidden_states- torch.cuda.empty_cache()- assert canceled, f"cancel at {cancel_at:.2f}s was never seen inside the {full_step:.2f}s step"- idle_after_cancel = elapsed - cancel_at- # The bound is one block plus the poll's own latency; without the wait it is the rest of the- # step (~0.6 * full_step). Allow generous scheduling jitter on the dev machine.- assert idle_after_cancel < 3 * block_time, (- f"GPU stayed busy {idle_after_cancel:.2f}s after the cancel (block ~{block_time:.2f}s, step {full_step:.2f}s)"- )--def test_uncanceled_run_leaves_no_hooks_and_polls_every_block(tiny_transformer):polls: list[bool] = []diff --git a/tests/backend/util/test_cancel_hooks.py b/tests/backend/util/test_cancel_hooks.pynew file mode 100644index 0000000000..fc995f4a6a--- /dev/null+++ b/tests/backend/util/test_cancel_hooks.py@@ -0,0 +1,152 @@+"""Tests for `cancel_before_forward`: CPU behavior on a small module chain, plus one slow GPU test."""++import threading+import time++import pytest+import torch++from invokeai.app.services.session_processor.session_processor_common import CanceledException+from invokeai.backend.util.cancel_hooks import cancel_before_forward++CPU = torch.device("cpu")+++class _Chain(torch.nn.Module):+ """Three units of work run in sequence, each recording that it ran."""++ def __init__(self) -> None:+ super().__init__()+ self.units = torch.nn.ModuleList([torch.nn.Linear(4, 4) for _ in range(3)])+ self.ran: list[int] = []+ for index, unit in enumerate(self.units):+ unit.register_forward_hook(lambda module, args, output, index=index: self.ran.append(index))++ def forward(self, x: torch.Tensor) -> torch.Tensor:+ for unit in self.units:+ x = unit(x)+ return x+++def _no_cancel_hooks(chain: _Chain) -> bool:+ return all(not unit._forward_pre_hooks for unit in chain.units)+++def test_cancel_stops_at_the_next_unit_and_removes_the_hooks():+ chain = _Chain()+ polls = iter([False, True])+ with pytest.raises(CanceledException):+ with cancel_before_forward(chain.units, lambda: next(polls), CPU):+ chain(torch.zeros(1, 4))+ assert chain.ran == [0], "the forward did not stop at the first unit boundary after the cancel"+ assert _no_cancel_hooks(chain)+++def test_uncanceled_forward_polls_once_per_unit_and_removes_the_hooks():+ chain = _Chain()+ polls = 0++ def is_canceled() -> bool:+ nonlocal polls+ polls += 1+ return False++ with cancel_before_forward(chain.units, is_canceled, CPU):+ chain(torch.zeros(1, 4))+ assert not _no_cancel_hooks(chain), "hooks must stay installed for the whole context"+ assert chain.ran == [0, 1, 2]+ assert polls == 3+ assert _no_cancel_hooks(chain)+++def test_hooks_are_removed_when_the_forward_raises_something_else():+ chain = _Chain()+ with pytest.raises(RuntimeError):+ with cancel_before_forward(chain.units, lambda: False, CPU):+ chain(torch.zeros(1, 5)) # wrong width: the first unit raises+ assert _no_cancel_hooks(chain)+++def test_no_callback_installs_nothing():+ chain = _Chain()+ with cancel_before_forward(chain.units, None, CPU):+ assert _no_cancel_hooks(chain)+ chain(torch.zeros(1, 4))+ assert chain.ran == [0, 1, 2]+++class _HeavyBlock(torch.nn.Module):+ """Tens of milliseconds of GPU work per call: a chain of them outlasts the CPU's enqueue time+ by orders of magnitude, as a real transformer step or VAE decode does."""++ DIM = 8192++ def __init__(self, device: torch.device):+ super().__init__()+ self.weight = torch.nn.Parameter(torch.randn(self.DIM, self.DIM, dtype=torch.bfloat16, device=device) * 0.01)++ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:+ for _ in range(8):+ hidden_states = torch.nn.functional.layer_norm(hidden_states @ self.weight, (self.DIM,))+ return hidden_states+++class _HeavyStack(torch.nn.Module):+ def __init__(self, device: torch.device, num_blocks: int):+ super().__init__()+ self.blocks = torch.nn.ModuleList([_HeavyBlock(device) for _ in range(num_blocks)])++ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:+ for block in self.blocks:+ hidden_states = block(hidden_states)+ return hidden_states++[email protected](not torch.cuda.is_available(), reason="measures cancel latency against queued GPU kernels")+def test_mid_call_cancel_idles_the_gpu_within_a_unit():+ """Kernel launches are asynchronous: without a wait in the poll, the CPU enqueues every unit of+ a call in tens of milliseconds and parks at the first host sync, so a cancel landing mid-call+ is not seen until the call returns and the GPU grinds through all of it (observed on the+ dual-GPU rig: a cancel during H3 denoise step 2 kept the GPU busy until the step ended). The+ poll must wait for the queued work, so that the GPU goes idle within about a unit of the cancel."""+ device = torch.device("cuda")+ num_blocks = 16+ torch.manual_seed(0)+ stack = _HeavyStack(device, num_blocks).eval()+ hidden_states = torch.randn(4096, _HeavyBlock.DIM, dtype=torch.bfloat16, device=device)+ cancel = threading.Event()++ def timed_forward(stack: _HeavyStack, hidden_states: torch.Tensor) -> tuple[float, bool]:+ torch.cuda.synchronize(device)+ start = time.perf_counter()+ canceled = False+ try:+ with torch.no_grad(), cancel_before_forward(stack.blocks, cancel.is_set, device):+ stack(hidden_states)+ except CanceledException:+ canceled = True+ torch.cuda.synchronize(device)+ return time.perf_counter() - start, canceled++ full_call, canceled = timed_forward(stack, hidden_states)+ assert not canceled+ block_time = full_call / num_blocks++ cancel_at = full_call * 0.4+ timer = threading.Timer(cancel_at, cancel.set)+ timer.start()+ try:+ elapsed, canceled = timed_forward(stack, hidden_states)+ finally:+ timer.cancel()+ # 2 GiB of synthetic weights: hand them back rather than leaving them cached for the session.+ del stack, hidden_states+ torch.cuda.empty_cache()+ assert canceled, f"cancel at {cancel_at:.2f}s was never seen inside the {full_call:.2f}s call"+ idle_after_cancel = elapsed - cancel_at+ # The bound is one block plus the poll's own latency; without the wait it is the rest of the+ # call (~0.6 * full_call). Allow generous scheduling jitter on the dev machine.+ assert idle_after_cancel < 3 * block_time, (+ f"GPU stayed busy {idle_after_cancel:.2f}s after the cancel (block ~{block_time:.2f}s, call {full_call:.2f}s)"+ )