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
debug: env-gated torch.profiler hook for one MiniMax H3 denoise step
Lincoln Stein46d64ecd87f8
diff --git a/invokeai/backend/minimax_h3/denoise.py b/invokeai/backend/minimax_h3/denoise.pyindex 13d83f86fd..c7b330de16 100644--- a/invokeai/backend/minimax_h3/denoise.py+++ b/invokeai/backend/minimax_h3/denoise.py@@ -5,14 +5,71 @@ First-party port of ``modular_pipelines/minimax_h3/denoise.py`` (commit recordednoise level — followed by one scheduler step per modality on the *generated* rows only. Theconditioning rows are never written, so the anchors survive the loop by construction. Thecheckpoint is guidance-distilled: no unconditional pass, no CFG.++Diagnostics: set ``INVOKEAI_PROFILE_H3_DENOISE`` to profile exactly one denoise step with+``torch.profiler`` — the second step when there is one (the first step pays allocator warm-up+and, under partial loading, first-touch weight streaming). The kernel-level summary table is+logged at INFO and a chrome trace (viewable at ``chrome://tracing`` or https://ui.perfetto.dev)+is written to the directory the variable names (or the working directory when set to ``1``).+Unset, the loop behaves exactly as before."""+import os+import time+from pathlib import Pathfrom typing import Callableimport torchfrom invokeai.backend.minimax_h3.sampling import MiniMaxH3DenoiseStatefrom invokeai.backend.minimax_h3.transformer_minimax_h3 import MiniMaxH3Transformer3DModel+from invokeai.backend.util.logging import InvokeAILogger++PROFILE_ENV_VAR = "INVOKEAI_PROFILE_H3_DENOISE"+++def _profile_one_step(trace_target: str, device: torch.device, run_step: Callable[[], None]) -> None:+ """Run one denoise step under torch.profiler; log the kernel table and write a chrome trace.++ The device is synchronized before and after the profiled region so the window contains this+ step's kernels only (not the tail of the previous step's asynchronous queue).+ """+ from torch.profiler import ProfilerActivity, profile++ logger = InvokeAILogger.get_logger(__name__)+ is_gpu = device.type == "cuda"+ activities = [ProfilerActivity.CPU] + ([ProfilerActivity.CUDA] if is_gpu else [])++ if is_gpu:+ torch.cuda.synchronize(device)+ wall_start = time.time()+ with profile(activities=activities) as prof:+ run_step()+ if is_gpu:+ torch.cuda.synchronize(device)+ wall_elapsed = time.time() - wall_start++ # The sort key was renamed cuda -> device across torch releases; try newest first. The CPU+ # key always exists, so the loop cannot fall through with `table` still empty.+ table = ""+ for sort_key in ("self_device_time_total", "self_cuda_time_total", "self_cpu_time_total"):+ try:+ table = prof.key_averages().table(sort_by=sort_key, row_limit=40)+ break+ except Exception:+ continue+ logger.info(f"MiniMax H3 denoise: profiled one step in {wall_elapsed:.2f}s wall time. Kernel summary:\n{table}")++ trace_dir = Path(trace_target) if trace_target.lower() not in ("1", "true", "yes") else Path.cwd()+ trace_path = trace_dir / "h3_denoise_step_trace.json"+ try:+ trace_dir.mkdir(parents=True, exist_ok=True)+ prof.export_chrome_trace(str(trace_path))+ logger.info(f"MiniMax H3 denoise: wrote chrome trace to {trace_path}")+ except Exception:+ # The table above is the primary deliverable; a failed trace export must not kill the+ # generation mid-denoise.+ logger.warning(f"MiniMax H3 denoise: failed to write chrome trace to {trace_path}", exc_info=True)def denoise(@@ -48,10 +105,11 @@ def denoise(prompt_embeds = prompt_embeds.to(latents.device)total_steps = len(state.timesteps)- for i, t in enumerate(state.timesteps):- if is_canceled is not None and is_canceled():- raise CanceledException+ profile_target = os.environ.get(PROFILE_ENV_VAR)+ profile_step_index = (1 if total_steps > 1 else 0) if profile_target else None++ def run_step(i: int, t: torch.Tensor) -> None:unique_timesteps, timestep_indices = state.row_timestep_plan[i]noise_pred, audio_noise_pred = transformer(hidden_states=latents[None],@@ -94,4 +152,14 @@ 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++ 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/tests/backend/minimax_h3/test_denoise.py b/tests/backend/minimax_h3/test_denoise.pyindex 62a2778dd2..41c7630677 100644--- a/tests/backend/minimax_h3/test_denoise.py+++ b/tests/backend/minimax_h3/test_denoise.py@@ -170,3 +170,17 @@ def test_denoise_working_memory_estimate():padded = estimate(_layout(38_000, 4))assert padded == large + 5 * 38_000**2+++def test_profiling_env_var_preserves_results_and_writes_trace(tiny_transformer, tmp_path, monkeypatch):+ """INVOKEAI_PROFILE_H3_DENOISE must not change the denoise output, and must leave a trace."""+ prompt_embeds = torch.randn(1, 3, TINY_CONFIG["text_dim"], generator=torch.Generator().manual_seed(1))++ reference_video, reference_audio = denoise(tiny_transformer, _state(), prompt_embeds.clone())++ monkeypatch.setenv("INVOKEAI_PROFILE_H3_DENOISE", str(tmp_path))+ profiled_video, profiled_audio = denoise(tiny_transformer, _state(), prompt_embeds.clone())++ assert torch.equal(reference_video, profiled_video)+ assert torch.equal(reference_audio, profiled_audio)+ assert (tmp_path / "h3_denoise_step_trace.json").exists()