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): wait for queued kernels before each per-block cancel poll
Lincoln Stein906db256abd6
diff --git a/invokeai/backend/minimax_h3/denoise.py b/invokeai/backend/minimax_h3/denoise.pyindex 1b8fcc5834..1b76fcb96e 100644--- a/invokeai/backend/minimax_h3/denoise.py+++ b/invokeai/backend/minimax_h3/denoise.py@@ -125,15 +125,20 @@ def _profile_one_step(trace_target: str, device: torch.device, run_step: Callabl@contextmanagerdef _cancel_between_blocks(- transformer: MiniMaxH3Transformer3DModel, is_canceled: Callable[[], bool] | None+ 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 referencedual-GPU rig — and the step loop only polls between steps, so a cancel used to keep the GPUbusy 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.+ 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@@ -141,6 +146,8 @@ def _cancel_between_blocks(from invokeai.app.services.session_processor.session_processor_common import CanceledExceptiondef raise_if_canceled(module: torch.nn.Module, args: tuple[object, ...]) -> None:+ if device.type != "cpu":+ torch.accelerator.synchronize(device)if is_canceled():raise CanceledException@@ -169,9 +176,10 @@ 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 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.+ is_canceled: Polled before every step and before every transformer block within a step,+ after the previous block's kernels have finished; a True return raises+ ``CanceledException`` from inside the forward, so a cancel idles the GPU 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).@@ -233,7 +241,7 @@ 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):+ with _cancel_between_blocks(transformer, is_canceled, latents.device):for i, t in enumerate(state.timesteps):if is_canceled is not None and is_canceled():raise CanceledExceptiondiff --git a/tests/backend/minimax_h3/test_denoise.py b/tests/backend/minimax_h3/test_denoise.pyindex ab70898aa7..d304502d94 100644--- a/tests/backend/minimax_h3/test_denoise.py+++ b/tests/backend/minimax_h3/test_denoise.py@@ -1,10 +1,13 @@-"""Tests for the MiniMax H3 denoising loop, on a micro-config CPU transformer."""+"""Tests for the MiniMax H3 denoising loop: a micro-config CPU transformer, plus one slow GPU test."""++import threading+import timeimport pytestimport torchfrom invokeai.app.services.session_processor.session_processor_common import CanceledException-from invokeai.backend.minimax_h3.denoise import denoise+from invokeai.backend.minimax_h3.denoise import _cancel_between_blocks, denoisefrom invokeai.backend.minimax_h3.sampling import build_denoise_statefrom invokeai.backend.minimax_h3.transformer_minimax_h3 import MiniMaxH3Transformer3DModel@@ -145,6 +148,85 @@ 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] = []