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
perf(minimax-h3): decompose video-VAE encoder conv3d for ROCm
Lincoln Stein378f666560bb
diff --git a/invokeai/backend/minimax_h3/rocm_causal_conv3d.py b/invokeai/backend/minimax_h3/rocm_causal_conv3d.pynew file mode 100644index 0000000000..7caac3eabf--- /dev/null+++ b/invokeai/backend/minimax_h3/rocm_causal_conv3d.py@@ -0,0 +1,83 @@+"""ROCm workaround: decompose MiniMaxH3VideoCausalConv3d into per-temporal-tap conv2d calls.++MIOpen (ROCm's cuDNN equivalent) has no implicit-GEMM 3D-convolution kernels for+VAE-shaped workloads on RDNA3 — it falls back to ``Im3d2Col``, which materializes+every kT x kH x kW patch into a matrix before a GEMM. On a W7900 this measured+~48x slower than the equivalent conv2d work in the Wan VAE (see+``invokeai/backend/wan/rocm_causal_conv3d.py``, which this module mirrors).++In the MiniMax H3 video VAE only the ENCODER is convolutional+(``MiniMaxH3VideoCausalConv3d`` throughout); the decoder is a ViT and is not+affected. The encoder runs on every keyframe-conditioning encode (i2v first/last+frame), so the penalty is paid per generation, on a single-frame workload.+MIOpen's *2D* convolutions are well optimized, and a stride-1 kT x kH x kW conv3d+is exactly the sum of kT conv2d taps over shifted temporal slices, so this module+rebinds ``MiniMaxH3VideoCausalConv3d.forward`` to that decomposition.++Numerics: identical math up to floating-point summation order — max abs error vs+``F.conv3d`` is ~1e-6 in fp32.++The patch is class-level and idempotent, applied only when torch is a ROCm/HIP+build. It covers every ``AutoencoderKLMiniMaxH3`` consumer (keyframe+conditioning, latents-to-image/video encode paths) regardless of which loader+constructed it.+"""++import torch+import torch.nn.functional as F++_SENTINEL = "_invokeai_rocm_conv2d_decomposition"+++def _decomposed_conv3d(module: torch.nn.Conv3d, x: torch.Tensor) -> torch.Tensor:+ """``F.conv3d(x, module.weight, module.bias)`` for stride-1/dilation-1/groups-1+ convs, computed as kT batched conv2d taps. ``x`` must already be padded."""+ b, c, t, h, w = x.shape+ k_t = module.weight.shape[2]+ t_out = t - k_t + 1+ out = None+ for k in range(k_t):+ xs = x[:, :, k : k + t_out].transpose(1, 2).reshape(b * t_out, c, h, w)+ o = F.conv2d(xs, module.weight[:, :, k], None)+ out = o if out is None else out + o+ assert out is not None+ if module.bias is not None:+ out = out + module.bias.view(1, -1, 1, 1)+ oh, ow = out.shape[-2:]+ return out.reshape(b, t_out, -1, oh, ow).transpose(1, 2)+++def _decomposed_forward(self, hidden_states: torch.Tensor) -> torch.Tensor:+ # Padding handling copied verbatim from MiniMaxH3VideoCausalConv3d.forward+ # (spatial reflect pad, then causal constant temporal pad).+ if self.spatial_padding > 0:+ padding = self.spatial_padding+ hidden_states = F.pad(hidden_states, (padding, padding, padding, padding, 0, 0), mode=self.spatial_padding_mode)+ if self.temporal_padding > 0:+ hidden_states = F.pad(hidden_states, (0, 0, 0, 0, self.temporal_padding, 0), mode="constant")+ if self.stride != (1, 1, 1) or self.dilation != (1, 1, 1) or self.groups != 1:+ # Not worth decomposing (and stride couples the temporal taps) — these+ # only occur on encoder downsample convs, which are a minority of calls.+ return F.conv3d(hidden_states, self.weight, self.bias, self.stride, (0, 0, 0), self.dilation, self.groups)+ return _decomposed_conv3d(self, hidden_states)+++def _patch_minimax_h3_causal_conv3d() -> None:+ """Rebind MiniMaxH3VideoCausalConv3d.forward to the conv2d decomposition (idempotent)."""+ from invokeai.backend.minimax_h3.autoencoder_kl_minimax_h3 import MiniMaxH3VideoCausalConv3d++ if getattr(MiniMaxH3VideoCausalConv3d, _SENTINEL, False):+ return+ MiniMaxH3VideoCausalConv3d.forward = _decomposed_forward+ setattr(MiniMaxH3VideoCausalConv3d, _SENTINEL, True)+++def patch_minimax_h3_causal_conv3d_for_rocm() -> None:+ """Apply the conv2d decomposition on ROCm builds; no-op elsewhere.++ Call from any loader that constructs an ``AutoencoderKLMiniMaxH3``. cuDNN has+ real implicit-GEMM conv3d kernels, so CUDA builds keep the stock path.+ """+ if torch.version.hip is None:+ return+ _patch_minimax_h3_causal_conv3d()diff --git a/invokeai/backend/model_manager/load/model_loaders/minimax_h3.py b/invokeai/backend/model_manager/load/model_loaders/minimax_h3.pyindex 14a1a148fa..bdf2de19d4 100644--- a/invokeai/backend/model_manager/load/model_loaders/minimax_h3.py+++ b/invokeai/backend/model_manager/load/model_loaders/minimax_h3.py@@ -92,7 +92,12 @@ class MiniMaxH3DiffusersModel(ModelLoader):return AutoProcessor.from_pretrained(submodel_path, local_files_only=True)case SubModelType.VAE:from invokeai.backend.minimax_h3 import AutoencoderKLMiniMaxH3+ from invokeai.backend.minimax_h3.rocm_causal_conv3d import patch_minimax_h3_causal_conv3d_for_rocm+ # The convolutional encoder hits MIOpen's Im3d2Col conv3d fallback on ROCm+ # (~48x, same failure as the Wan VAE); decompose to per-temporal-tap conv2d.+ # The ViT decoder is unaffected either way.+ patch_minimax_h3_causal_conv3d_for_rocm()return AutoencoderKLMiniMaxH3.from_pretrained(submodel_path, torch_dtype=dtype, local_files_only=True)case SubModelType.AudioVAE:from invokeai.backend.minimax_h3 import AutoencoderKLMiniMaxH3Audiodiff --git a/tests/backend/minimax_h3/__init__.py b/tests/backend/minimax_h3/__init__.pynew file mode 100644index 0000000000..e69de29bb2diff --git a/tests/backend/minimax_h3/test_rocm_causal_conv3d.py b/tests/backend/minimax_h3/test_rocm_causal_conv3d.pynew file mode 100644index 0000000000..bb2fdbb115--- /dev/null+++ b/tests/backend/minimax_h3/test_rocm_causal_conv3d.py@@ -0,0 +1,82 @@+"""Tests for the ROCm MiniMaxH3VideoCausalConv3d conv2d decomposition.++The decomposition replaces MIOpen's Im3d2Col conv3d fallback on RDNA3 (~48x+slower than the decomposed path, measured on the Wan VAE's identical failure+mode). These tests pin that the decomposed forward is numerically equivalent to+the stock vendored forward on CPU — including the reflect spatial padding and+causal temporal padding — so the ROCm-gated class patch can never change+results, only speed.+"""++import torch++from invokeai.backend.minimax_h3.autoencoder_kl_minimax_h3 import MiniMaxH3VideoCausalConv3d+from invokeai.backend.minimax_h3.rocm_causal_conv3d import (+ _decomposed_conv3d,+ _decomposed_forward,+ _patch_minimax_h3_causal_conv3d,+)+++def test_decomposed_conv3d_matches_f_conv3d() -> None:+ torch.manual_seed(0)+ for kernel_size in [(3, 3, 3), (1, 1, 1), (3, 1, 1), (1, 3, 3)]:+ conv = torch.nn.Conv3d(6, 10, kernel_size=kernel_size)+ x = torch.randn(2, 6, 5, 12, 16)+ ref = torch.nn.functional.conv3d(x, conv.weight, conv.bias)+ got = _decomposed_conv3d(conv, x)+ assert torch.allclose(ref, got, atol=1e-5), f"mismatch for kernel {kernel_size}"+++def test_decomposed_forward_matches_stock_causal_conv3d() -> None:+ """The workhorse encoder conv: 3x3x3, reflect spatial padding, causal temporal padding."""+ torch.manual_seed(1)+ conv = MiniMaxH3VideoCausalConv3d(4, 8, kernel_size=3, spatial_padding=1, temporal_padding=2)+ x = torch.randn(1, 4, 5, 10, 14)+ ref = MiniMaxH3VideoCausalConv3d.forward(conv, x)+ got = _decomposed_forward(conv, x)+ assert ref.shape == got.shape+ assert torch.allclose(ref, got, atol=1e-5)+++def test_decomposed_forward_matches_stock_pointwise_shortcut() -> None:+ """Resnet shortcut convs are 1x1x1 with no padding."""+ torch.manual_seed(2)+ conv = MiniMaxH3VideoCausalConv3d(4, 8, kernel_size=1)+ x = torch.randn(1, 4, 5, 10, 14)+ ref = MiniMaxH3VideoCausalConv3d.forward(conv, x)+ got = _decomposed_forward(conv, x)+ assert torch.allclose(ref, got, atol=1e-5)+++def test_decomposed_forward_falls_back_to_conv3d_for_strided_convs() -> None:+ """Encoder downsample convs are strided; the temporal taps couple under stride,+ so those must go through F.conv3d untouched."""+ torch.manual_seed(3)+ conv = MiniMaxH3VideoCausalConv3d(4, 8, kernel_size=3, stride=(2, 2, 2), spatial_padding=1, temporal_padding=2)+ x = torch.randn(1, 4, 6, 12, 16)+ ref = MiniMaxH3VideoCausalConv3d.forward(conv, x)+ got = _decomposed_forward(conv, x)+ assert ref.shape == got.shape+ assert torch.allclose(ref, got, atol=1e-5)+++def test_class_patch_is_idempotent_and_preserves_behavior() -> None:+ torch.manual_seed(4)+ stock_forward = MiniMaxH3VideoCausalConv3d.forward+ try:+ conv = MiniMaxH3VideoCausalConv3d(4, 8, kernel_size=3, spatial_padding=1, temporal_padding=2)+ x = torch.randn(1, 4, 5, 10, 14)+ ref = conv(x)++ _patch_minimax_h3_causal_conv3d()+ patched_forward = MiniMaxH3VideoCausalConv3d.forward+ _patch_minimax_h3_causal_conv3d() # second call must be a no-op+ assert MiniMaxH3VideoCausalConv3d.forward is patched_forward+ assert MiniMaxH3VideoCausalConv3d.forward is not stock_forward++ assert torch.allclose(conv(x), ref, atol=1e-5)+ finally:+ MiniMaxH3VideoCausalConv3d.forward = stock_forward+ if hasattr(MiniMaxH3VideoCausalConv3d, "_invokeai_rocm_conv2d_decomposition"):+ delattr(MiniMaxH3VideoCausalConv3d, "_invokeai_rocm_conv2d_decomposition")