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: retire the ROCm conv3d decompositions on HIP >= 7.2
Lincoln Stein53da97586d59
diff --git a/invokeai/backend/minimax_h3/rocm_causal_conv3d.py b/invokeai/backend/minimax_h3/rocm_causal_conv3d.pyindex a22080b32d..9e3446d973 100644--- a/invokeai/backend/minimax_h3/rocm_causal_conv3d.py+++ b/invokeai/backend/minimax_h3/rocm_causal_conv3d.py@@ -35,29 +35,16 @@ def _decomposed_conv3d(module: torch.nn.Conv3d, x: torch.Tensor) -> torch.Tensorb, c, t, h, w = x.shapek_t = module.weight.shape[2]t_out = t - k_t + 1- # Every tensor this decomposition hands to a kernel (or returns to the caller) MUST be- # standard-contiguous. The naive expressions produce three legal-but-exotic strided views- # that old MIOpen tolerated (it copied internally) but the MIOpen in torch's rocm7.2 wheels- # consumes directly and mis-addresses, corrupting rows whenever H != W (observed as- # horizontal line/tearing artifacts via the Wan VAE's identical decomposition; this encoder- # shares the bug for non-square canvases):- # 1. the tap input — at B=1 (every real encode) the reshape is satisfiable as a zero-copy- # view whose channel stride (T*H*W) exceeds its batch stride (H*W);- # 2. the tap weight — weight[:, :, k] is a strided view over the temporal dim for every- # kT > 1 conv;- # 3. the returned activation — reshape+transpose yields a transposed view consumed by- # downstream norm/resample kernels.- # The explicit copies cost a small fraction of the conv itself.out = Nonefor k in range(k_t):- xs = x[:, :, k : k + t_out].transpose(1, 2).reshape(b * t_out, c, h, w).contiguous()- o = F.conv2d(xs, module.weight[:, :, k].contiguous(), None)+ 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 + oassert out is not Noneif 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).contiguous()+ return out.reshape(b, t_out, -1, oh, ow).transpose(1, 2)def _decomposed_forward(self, hidden_states: torch.Tensor) -> torch.Tensor:@@ -86,11 +73,21 @@ def _patch_minimax_h3_causal_conv3d() -> None:def patch_minimax_h3_causal_conv3d_for_rocm() -> None:- """Apply the conv2d decomposition on ROCm builds; no-op elsewhere.+ """Apply the conv2d decomposition on ROCm builds older than HIP 7.2; no-op elsewhere.Call from any loader that constructs an ``AutoencoderKLMiniMaxH3``. cuDNN hasreal implicit-GEMM conv3d kernels, so CUDA builds keep the stock path.++ HIP >= 7.2 also keeps the stock path, mirroring the Wan decomposition (see+ ``invokeai.backend.wan.rocm_causal_conv3d.patch_wan_causal_conv3d_for_rocm`` for the+ full story): new MIOpen runs these conv3ds at full speed, and the identical Wan+ decomposition exhibited allocator-state-dependent row corruption there — this encoder+ shares the code, so it shares the retirement."""+ from invokeai.backend.wan.rocm_causal_conv3d import hip_version_at_least+if torch.version.hip is None:return+ if hip_version_at_least(7, 2):+ return_patch_minimax_h3_causal_conv3d()diff --git a/invokeai/backend/wan/rocm_causal_conv3d.py b/invokeai/backend/wan/rocm_causal_conv3d.pyindex 25a7b25a2f..6fc8befa3a 100644--- a/invokeai/backend/wan/rocm_causal_conv3d.py+++ b/invokeai/backend/wan/rocm_causal_conv3d.py@@ -36,28 +36,16 @@ def _decomposed_conv3d(module: torch.nn.Conv3d, x: torch.Tensor) -> torch.Tensorb, c, t, h, w = x.shapek_t = module.weight.shape[2]t_out = t - k_t + 1- # Every tensor this decomposition hands to a kernel (or returns to the caller) MUST be- # standard-contiguous. The naive expressions produce three legal-but-exotic strided views- # that old MIOpen tolerated (it copied internally) but the MIOpen in torch's rocm7.2 wheels- # consumes directly and mis-addresses, corrupting rows whenever H != W (horizontal- # line/tearing artifacts in decoded images):- # 1. the tap input — at B=1 (every real decode) the reshape is satisfiable as a zero-copy- # view whose channel stride (T*H*W) exceeds its batch stride (H*W);- # 2. the tap weight — weight[:, :, k] is a strided view over the temporal dim for every- # kT > 1 conv;- # 3. the returned activation — reshape+transpose yields a transposed view consumed by- # downstream norm/upsample kernels.- # The explicit copies cost a small fraction of the conv itself.out = Nonefor k in range(k_t):- xs = x[:, :, k : k + t_out].transpose(1, 2).reshape(b * t_out, c, h, w).contiguous()- o = F.conv2d(xs, module.weight[:, :, k].contiguous(), None)+ 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 + oassert out is not Noneif 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).contiguous()+ return out.reshape(b, t_out, -1, oh, ow).transpose(1, 2)def _decomposed_forward(self, x: torch.Tensor, cache_x: torch.Tensor | None = None) -> torch.Tensor:@@ -130,15 +118,43 @@ def _patch_wan_causal_conv3d() -> None:setattr(WanCausalConv3d, _SENTINEL, True)+def hip_version_at_least(major: int, minor: int) -> bool:+ """True when this is a ROCm/HIP torch build at least as new as ``major.minor``.++ Parse failures return False (keep the proven old-stack behavior).+ """+ hip = torch.version.hip+ if hip is None:+ return False+ try:+ parts = hip.split(".")+ return (int(parts[0]), int(parts[1])) >= (major, minor)+ except (ValueError, IndexError):+ return False++def patch_wan_causal_conv3d_for_rocm() -> None:- """Apply the conv2d decomposition on ROCm builds; no-op elsewhere.+ """Apply the conv2d decomposition on ROCm builds older than HIP 7.2; no-op elsewhere.Call from any loader that constructs an ``AutoencoderKLWan``. cuDNN has real- implicit-GEMM conv3d kernels, so CUDA builds keep the stock path. See _MODE above for- the diagnostic overrides (INVOKEAI_ROCM_CONV3D=native|verify).+ implicit-GEMM conv3d kernels, so CUDA builds keep the stock path.++ HIP >= 7.2 also keeps the stock path: its MIOpen runs these conv3ds at full speed+ (making the decomposition unnecessary), and with the decomposition active it produces+ allocator-state-dependent row corruption in decoded images — horizontal line/tearing+ artifacts, observed on non-square Anima/Wan decodes on a W7900 with torch+ 2.13.0+rocm7.2. The corruption is a heisenbug: every isolated repro of the+ decomposition's kernels is numerically clean, and instrumenting the live decode to+ compare both implementations per call (INVOKEAI_ROCM_CONV3D=verify) finds no+ divergence AND yields a clean image — the signature of a kernel reading memory whose+ content depends on allocation history. Native conv3d is deterministic-clean and fast+ there, so it wins outright. See _MODE above for the diagnostic overrides+ (INVOKEAI_ROCM_CONV3D=native|verify; verify still patches on any HIP version)."""if torch.version.hip is None:returnif _MODE == "native":return+ if _MODE != "verify" and hip_version_at_least(7, 2):+ return_patch_wan_causal_conv3d()diff --git a/tests/backend/minimax_h3/test_rocm_causal_conv3d.py b/tests/backend/minimax_h3/test_rocm_causal_conv3d.pyindex fcec15166e..2805f05c7e 100644--- a/tests/backend/minimax_h3/test_rocm_causal_conv3d.py+++ b/tests/backend/minimax_h3/test_rocm_causal_conv3d.py@@ -82,24 +82,23 @@ def test_class_patch_is_idempotent_and_preserves_behavior() -> None:delattr(MiniMaxH3VideoCausalConv3d, "_invokeai_rocm_conv2d_decomposition")-def test_decomposed_conv3d_feeds_contiguous_conv2d_inputs(monkeypatch) -> None:- """At B=1 (every real encode) the tap reshape can be satisfied as a zero-copy view whose- channel stride exceeds its batch stride. The MIOpen shipped with torch's rocm7.2 wheels- mis-addresses rows of such inputs when H != W (observed as horizontal tearing via the Wan- VAE's identical decomposition), so conv2d must receive standard-contiguous tensors."""+def test_patch_gates_on_hip_version(monkeypatch) -> None:+ """Mirrors the Wan decomposition's HIP gate: >= 7.2 keeps the stock conv3d forward (fast+ native kernels; the shared decomposition code corrupted decodes there), older HIP keeps+ the decomposition, non-HIP builds are never patched."""import invokeai.backend.minimax_h3.rocm_causal_conv3d as mod- seen: list[bool] = []- original_conv2d = mod.F.conv2d+ calls: list[bool] = []+ monkeypatch.setattr(mod, "_patch_minimax_h3_causal_conv3d", lambda: calls.append(True))- def checked_conv2d(x: torch.Tensor, weight: torch.Tensor, *args, **kwargs) -> torch.Tensor:- seen.append(x.is_contiguous() and weight.is_contiguous())- return original_conv2d(x, weight, *args, **kwargs)+ monkeypatch.setattr(torch.version, "hip", "7.2.10101")+ mod.patch_minimax_h3_causal_conv3d_for_rocm()+ assert calls == [], "must not decompose on HIP 7.2+"- monkeypatch.setattr(mod.F, "conv2d", checked_conv2d)- conv = torch.nn.Conv3d(6, 10, kernel_size=(3, 3, 3))- x = torch.randn(1, 6, 5, 12, 16) # B=1 and H != W: the exotic-view case- result = _decomposed_conv3d(conv, x)- assert seen, "decomposition never called conv2d"- assert all(seen), "conv2d received a non-contiguous input or weight"- assert result.is_contiguous(), "decomposition returned a non-contiguous activation"+ monkeypatch.setattr(torch.version, "hip", "7.1.25424")+ mod.patch_minimax_h3_causal_conv3d_for_rocm()+ assert calls == [True], "must decompose on HIP < 7.2"++ monkeypatch.setattr(torch.version, "hip", None)+ mod.patch_minimax_h3_causal_conv3d_for_rocm()+ assert calls == [True], "CUDA/CPU builds are never patched"diff --git a/tests/backend/wan/test_rocm_causal_conv3d.py b/tests/backend/wan/test_rocm_causal_conv3d.pyindex 011ecdce57..3dd12ce787 100644--- a/tests/backend/wan/test_rocm_causal_conv3d.py+++ b/tests/backend/wan/test_rocm_causal_conv3d.py@@ -89,24 +89,46 @@ def test_class_patch_is_idempotent_and_preserves_behavior() -> None:delattr(WanCausalConv3d, "_invokeai_rocm_conv2d_decomposition")-def test_decomposed_conv3d_feeds_contiguous_conv2d_inputs(monkeypatch: pytest.MonkeyPatch) -> None:- """At B=1 (every real decode) the tap reshape can be satisfied as a zero-copy view whose- channel stride exceeds its batch stride. The MIOpen shipped with torch's rocm7.2 wheels- mis-addresses rows of such inputs when H != W (horizontal tearing in decoded images), so- the decomposition must hand conv2d standard-contiguous tensors."""+def test_patch_gates_on_hip_version(monkeypatch: pytest.MonkeyPatch) -> None:+ """HIP >= 7.2 keeps the stock conv3d forward: its MIOpen is fast for these convs, and the+ decomposition exhibited allocator-state-dependent row corruption there (heisenbug: clean in+ every isolated repro and under per-call verification, corrupt in the live decode). Older+ HIP keeps the decomposition (native conv3d is ~48x slower there); unparseable versions play+ it safe and keep the proven old-stack behavior."""import invokeai.backend.wan.rocm_causal_conv3d as mod- seen: list[bool] = []- original_conv2d = mod.F.conv2d-- def checked_conv2d(x: torch.Tensor, weight: torch.Tensor, *args, **kwargs) -> torch.Tensor:- seen.append(x.is_contiguous() and weight.is_contiguous())- return original_conv2d(x, weight, *args, **kwargs)-- monkeypatch.setattr(mod.F, "conv2d", checked_conv2d)- conv = torch.nn.Conv3d(6, 10, kernel_size=(3, 3, 3))- x = torch.randn(1, 6, 5, 12, 16) # B=1 and H != W: the exotic-view case- result = _decomposed_conv3d(conv, x)- assert seen, "decomposition never called conv2d"- assert all(seen), "conv2d received a non-contiguous input or weight"- assert result.is_contiguous(), "decomposition returned a non-contiguous activation"+ calls: list[bool] = []+ monkeypatch.setattr(mod, "_patch_wan_causal_conv3d", lambda: calls.append(True))+ monkeypatch.setattr(mod, "_MODE", "decomposed")++ monkeypatch.setattr(torch.version, "hip", "7.2.10101")+ mod.patch_wan_causal_conv3d_for_rocm()+ assert calls == [], "must not decompose on HIP 7.2+"++ monkeypatch.setattr(torch.version, "hip", "10.0.999")+ mod.patch_wan_causal_conv3d_for_rocm()+ assert calls == [], "must not decompose on later major versions either"++ monkeypatch.setattr(torch.version, "hip", "7.1.25424")+ mod.patch_wan_causal_conv3d_for_rocm()+ assert calls == [True], "must decompose on HIP < 7.2"++ monkeypatch.setattr(torch.version, "hip", "weird-version-string")+ mod.patch_wan_causal_conv3d_for_rocm()+ assert calls == [True, True], "unparseable version keeps the proven old-stack behavior"++ monkeypatch.setattr(torch.version, "hip", None)+ mod.patch_wan_causal_conv3d_for_rocm()+ assert calls == [True, True], "CUDA/CPU builds are never patched"++ # verify mode patches regardless of HIP version (diagnostics must be able to run anywhere).+ monkeypatch.setattr(mod, "_MODE", "verify")+ monkeypatch.setattr(torch.version, "hip", "7.2.10101")+ mod.patch_wan_causal_conv3d_for_rocm()+ assert calls == [True, True, True]++ # native mode never patches.+ monkeypatch.setattr(mod, "_MODE", "native")+ monkeypatch.setattr(torch.version, "hip", "7.1.25424")+ mod.patch_wan_causal_conv3d_for_rocm()+ assert calls == [True, True, True]