Skip to content

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.

fix(wan): keep the ROCm conv3d decomposition on HIP 7.2 and hand MIOpen contiguous tensors

Lincoln Stein84ddc64035c7
diff --git a/invokeai/backend/minimax_h3/rocm_causal_conv3d.py b/invokeai/backend/minimax_h3/rocm_causal_conv3d.py
index 9fd45180a4..0fe512f443 100644
--- a/invokeai/backend/minimax_h3/rocm_causal_conv3d.py
+++ b/invokeai/backend/minimax_h3/rocm_causal_conv3d.py
@@ -17,16 +17,12 @@ 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.
-Unlike the Wan twin, this decomposition stays on for EVERY HIP version. The Wan
-one was retired on HIP >= 7.2 because new MIOpen ran Wan's conv3ds at full speed
-and the decomposition showed allocator-state-dependent corruption in Wan *decodes*
-there. Neither finding transfers to this encoder: measured on a W7900 with torch
-2.13.0+rocm7.2 (HIP 7.2.53211), one 17-frame 768x448 reference chunk encodes in
-208 s fp32 / 222 s under fp16 autocast on native MIOpen conv3d (peak 9.2 GiB —
-the Im3d2Col column buffer), against 3.6 s / 2.7 s decomposed (peak 6.7 GiB).
-That is the same ~50x Im3d2Col penalty as on older HIP, so the retirement was
-wrong for these shapes (3x3x3 taps over 17-frame chunks with reflect padding);
-the H3 encoder was never re-timed when it happened.
+Like the Wan twin, the decomposition stays on for every HIP version: measured on
+a W7900 with torch 2.13.0+rocm7.2 (HIP 7.2.53211), one 17-frame 768x448 reference
+chunk encodes in 208 s fp32 / 222 s under fp16 autocast on native MIOpen conv3d
+(peak 9.2 GiB — the Im3d2Col column buffer), against 3.6 s / 2.7 s decomposed
+(peak 6.7 GiB). Native conv3d is only fast when a conv emits a single output
+frame, which never happens for these 17-frame chunks.
``INVOKEAI_ROCM_CONV3D=native`` (the Wan module's diagnostic override, shared)
leaves the stock forward in place on any HIP version, for A/B or if a future
diff --git a/invokeai/backend/util/vae_decode_diagnostics.py b/invokeai/backend/util/vae_decode_diagnostics.py
index d1468422bd..ed1ad3de18 100644
--- a/invokeai/backend/util/vae_decode_diagnostics.py
+++ b/invokeai/backend/util/vae_decode_diagnostics.py
@@ -11,9 +11,9 @@ The failure has at least three candidate mechanisms that ordinary logs cannot te
denoise or the tensor transfer) — the VAE is innocent.
2. The VAE's cached weights are corrupt (a bad RAM->VRAM move, or a corrupted canonical CPU
copy) — every decode fails until the model cache entry is dropped and reloaded.
-3. The weights and latents are clean but the decode *compute* produces NaN — the
- allocator-state-dependent MIOpen conv3d failure class already seen on gfx1100 (the
- HIP 7.2 decomposition heisenbug), plausibly surfaced by the multi-GPU policy of skipping
+3. The weights and latents are clean but the decode *compute* produces NaN — an
+ allocator-state-dependent kernel failure of the kind already seen on gfx1100 (the ROCm
+ fused-SDPA head-dim defect), plausibly surfaced by the multi-GPU policy of skipping
every ``empty_cache`` while a peer device is mid-session: during an hours-long video
generation the image GPU's allocator runs in a never-emptied, maximally-grown state.
diff --git a/invokeai/backend/wan/rocm_causal_conv3d.py b/invokeai/backend/wan/rocm_causal_conv3d.py
index 6fc8befa3a..7d9499431f 100644
--- a/invokeai/backend/wan/rocm_causal_conv3d.py
+++ b/invokeai/backend/wan/rocm_causal_conv3d.py
@@ -2,18 +2,25 @@
MIOpen (ROCm's cuDNN equivalent) has no implicit-GEMM 3D-convolution kernels for
the shapes used by the Wan VAE on RDNA3 — it falls back to ``Im3d2Col``, which
-materializes every 3x3x3 patch into a matrix before a GEMM. Profiling a Wan 2.1
-VAE decode on a W7900 showed Im3d2Col consuming 61% of GPU time, and neither
-dtype changes nor ``cudnn.benchmark`` kernel search helped (all configs within
-±7%). 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 ``WanCausalConv3d.forward`` to that decomposition.
-
-Measured on a W7900 (832x480, 3 latent frames, bf16): 81.6s -> 1.71s (~48x),
-matching NVIDIA wall-clock for the same decode. Numerics: identical math up to
-floating-point summation order — max abs error vs ``F.conv3d`` is ~1e-6 in fp32;
-a full bf16 VAE decode differs by at most ~3/255 in pixel space with 0.1% of
-pixels off by more than 1/255 (bf16 accumulation noise, visually imperceptible).
+materializes every 3x3x3 patch into a matrix before a GEMM. 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
+``WanCausalConv3d.forward`` to that decomposition.
+
+The fallback is a size cliff, not a slope: a conv that emits a single output
+frame (an image encode or decode) degenerates to a 2D conv and is fast natively,
+and so are small canvases, but every multi-frame chunk at video size still takes
+Im3d2Col on current MIOpen. Measured on a W7900 with torch 2.13.0+rocm7.2
+(A14B VAE, bf16, 832x480), native vs decomposed: encode 17 frames 103 s vs 2.4 s,
+decode 5 latent frames 162 s vs 3.6 s, peak VRAM 1-3 GiB lower decomposed. So
+the decomposition applies on every HIP version; a single-frame or small-shape
+timing cannot justify a gate (one shipped that way once and regressed every
+I2V encode and video decode). ``tests/backend/wan/test_rocm_causal_conv3d.py``
+has a ``slow`` ROCm test that fails when native conv3d stops taking the fallback.
+
+Numerics: identical math up to floating-point summation order — max abs error vs
+``F.conv3d`` is ~1e-6 in fp32; a full bf16 VAE decode differs from native by at
+most ~3/255 in pixel space (bf16 accumulation noise, visually imperceptible).
The patch is class-level and idempotent, applied only when torch is a ROCm/HIP
build. It covers every ``AutoencoderKLWan`` consumer (Wan decode/encode nodes,
@@ -36,16 +43,24 @@ def _decomposed_conv3d(module: torch.nn.Conv3d, x: torch.Tensor) -> torch.Tensor
b, c, t, h, w = x.shape
k_t = module.weight.shape[2]
t_out = t - k_t + 1
+ # Every tensor handed to MIOpen, and the activation handed back, is made standard-contiguous.
+ # The natural expressions are legal strided views (a tap input whose channel stride exceeds
+ # its batch stride at B=1, a temporal slice of the weight, a transposed result), and MIOpen in
+ # torch 2.13.0+rocm7.2 faults on them: an A14B encode of 161 frames at 720x1024 aborts with a
+ # GPU memory-access fault (or segfaults the process) every time with the views, never with the
+ # copies. The fault is asynchronous -- HIP_LAUNCH_BLOCKING=1 hides it -- and needs a long clip,
+ # so short repros pass. The copies cost a small fraction of the conv itself.
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
+ 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)
+ del xs # keep at most one tap input live alongside the accumulator
+ out = o if out is None else out.add_(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)
+ return out.reshape(b, t_out, -1, oh, ow).transpose(1, 2).contiguous()
def _decomposed_forward(self, x: torch.Tensor, cache_x: torch.Tensor | None = None) -> torch.Tensor:
@@ -66,7 +81,7 @@ def _decomposed_forward(self, x: torch.Tensor, cache_x: torch.Tensor | None = No
return _decomposed_conv3d(self, x)
-# Diagnostic switch for the torch-2.13/rocm7.2 corruption investigation. Values:
+# Diagnostic override for A/B checks against native MIOpen conv3d. Values:
# decomposed (default) — the normal patched path.
# native — leave the stock conv3d forward in place (patch becomes a no-op).
# verify — run BOTH the stock forward and the decomposition for every call,
@@ -118,43 +133,22 @@ 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 older than HIP 7.2; no-op elsewhere.
+ """Apply the conv2d decomposition on ROCm builds; 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.
-
- 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).
+ implicit-GEMM conv3d kernels, so CUDA builds keep the stock path. There is
+ deliberately no HIP-version gate (see the module docstring). The row tearing once
+ blamed on this decomposition on HIP 7.2 has two known causes, both since fixed: the
+ ROCm fused-SDPA head-dim defect (``install_rocm_sdpa_head_dim_guard`` in
+ ``invokeai.backend.util.attention``; the Wan VAE mid-block attention is wider than its
+ threshold) and MIOpen faulting on the strided views the decomposition used to hand it
+ (see ``_decomposed_conv3d``). With both in place the decomposition matches native
+ conv3d at non-square sizes under allocator churn. ``INVOKEAI_ROCM_CONV3D=native|verify``
+ (``_MODE`` above) remain for A/B checks.
"""
if torch.version.hip is None:
return
if _MODE == "native":
return
- if _MODE != "verify" and hip_version_at_least(7, 2):
- return
_patch_wan_causal_conv3d()
diff --git a/scripts/benchmark_minimax_h3_vae_encode.py b/scripts/benchmark_minimax_h3_vae_encode.py
index f14b95c860..bb78aedf05 100644
--- a/scripts/benchmark_minimax_h3_vae_encode.py
+++ b/scripts/benchmark_minimax_h3_vae_encode.py
@@ -9,8 +9,8 @@ the numeric drift between the two encodes, and projects the cost of a full-lengt
python scripts/benchmark_minimax_h3_vae_encode.py --vae /path/to/MiniMax-H3-components/vae
python scripts/benchmark_minimax_h3_vae_encode.py --root ~/invokeai # finds the VAE in the models dir
-The same ROCm conv3d handling the model loader applies (the conv2d decomposition on HIP < 7.2,
-native conv3d otherwise) is applied here, and the active path is printed; ``--conv3d decomposed``
+The same ROCm conv3d handling the model loader applies (the conv2d decomposition on every HIP
+version) is applied here, and the active path is printed; ``--conv3d decomposed``
or ``--conv3d native`` forces one path so the two can be A/B'd on the same HIP version. The decoder is not
loaded onto the device — it is a ~4.5 GiB ViT that the encode never touches.
diff --git a/tests/backend/minimax_h3/test_rocm_causal_conv3d.py b/tests/backend/minimax_h3/test_rocm_causal_conv3d.py
index 2595536062..782bf7462a 100644
--- a/tests/backend/minimax_h3/test_rocm_causal_conv3d.py
+++ b/tests/backend/minimax_h3/test_rocm_causal_conv3d.py
@@ -83,7 +83,7 @@ def test_class_patch_is_idempotent_and_preserves_behavior() -> None:
def test_patch_applies_on_every_hip_version(monkeypatch) -> None:
- """Unlike the Wan twin there is no HIP-version gate: MIOpen in rocm7.2 still takes the
+ """There is no HIP-version gate: MIOpen in rocm7.2 still takes the
~50x Im3d2Col fallback for this encoder's shapes (W7900: 208 s vs 3.6 s per chunk).
Non-HIP builds are never patched; INVOKEAI_ROCM_CONV3D=native opts out."""
import invokeai.backend.minimax_h3.rocm_causal_conv3d as mod
diff --git a/tests/backend/wan/test_rocm_causal_conv3d.py b/tests/backend/wan/test_rocm_causal_conv3d.py
index 3dd12ce787..300322b20e 100644
--- a/tests/backend/wan/test_rocm_causal_conv3d.py
+++ b/tests/backend/wan/test_rocm_causal_conv3d.py
@@ -7,9 +7,13 @@ forward on CPU — including the causal feature-cache path — so the ROCm-gated
class patch can never change results, only speed.
"""
+import random
+import time
+
import pytest
import torch
+import invokeai.backend.wan.rocm_causal_conv3d as mod
from invokeai.backend.wan.rocm_causal_conv3d import (
_decomposed_conv3d,
_decomposed_forward,
@@ -20,6 +24,12 @@ diffusers = pytest.importorskip("diffusers")
from diffusers.models.autoencoders.autoencoder_kl_wan import WanCausalConv3d # noqa: E402
[email protected](autouse=True)
+def _decomposed_mode(monkeypatch: pytest.MonkeyPatch) -> None:
+ """A developer's INVOKEAI_ROCM_CONV3D=verify shell must not reroute the parity tests."""
+ monkeypatch.setattr(mod, "_MODE", "decomposed")
+
+
@pytest.mark.parametrize(
"kernel_size",
[(3, 3, 3), (1, 1, 1), (3, 1, 1), (1, 3, 3)],
@@ -89,46 +99,133 @@ def test_class_patch_is_idempotent_and_preserves_behavior() -> None:
delattr(WanCausalConv3d, "_invokeai_rocm_conv2d_decomposition")
-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
-
+def test_patch_applies_on_every_hip_version(monkeypatch: pytest.MonkeyPatch) -> None:
+ """Every ROCm build decomposes, HIP 7.2+ included: native conv3d there is only fast when a
+ conv emits a single output frame, and multi-frame encodes/decodes still take the Im3d2Col
+ fallback (a HIP >= 7.2 gate shipped once on a single-frame timing and regressed video
+ encode/decode). CUDA/CPU builds are never patched; the diagnostic modes still work."""
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"
+ # No version parser exists any more: any HIP build string patches.
+ for hip in ("7.1.25424", "7.2.10101", "10.0.999"):
+ calls.clear()
+ monkeypatch.setattr(torch.version, "hip", hip)
+ mod.patch_wan_causal_conv3d_for_rocm()
+ assert calls == [True], f"must decompose on HIP {hip}"
+ calls.clear()
monkeypatch.setattr(torch.version, "hip", None)
mod.patch_wan_causal_conv3d_for_rocm()
- assert calls == [True, True], "CUDA/CPU builds are never patched"
+ assert calls == [], "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")
+ monkeypatch.setattr(mod, "_MODE", "verify")
mod.patch_wan_causal_conv3d_for_rocm()
- assert calls == [True, True, True]
+ assert calls == [True], "verify mode patches (diagnostics must be able to run)"
- # native mode never patches.
+ calls.clear()
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]
+ assert calls == [], "native mode never patches"
+
+
+needs_rocm = pytest.mark.skipif(torch.version.hip is None or not torch.cuda.is_available(), reason="needs a ROCm GPU")
+
+
+@needs_rocm
+class TestOnRocmHardware:
+ """The reason the decomposition exists, on the real device. `slow`: a dev-machine lane, not CI."""
+
+ # One 4-frame encoder chunk (plus its first frame) at 832x480, base_dim channels: the smallest
+ # production shape past MIOpen's Im3d2Col cliff. Sub-production shapes run ~2x either way and
+ # would rationalize a gate, which is exactly how the HIP >= 7.2 regression shipped.
+ SHAPE = (1, 96, 5, 480, 832)
+ NEEDS_FREE_BYTES = 14 * 2**30 # native peaks ~10-12 GiB on the column buffer
+
+ @staticmethod
+ def _timed(fn) -> float:
+ torch.cuda.synchronize()
+ start = time.perf_counter()
+ fn()
+ torch.cuda.synchronize()
+ return time.perf_counter() - start
+
+ def _conv_and_input(self) -> tuple[WanCausalConv3d, torch.Tensor]:
+ torch.cuda.empty_cache() # a previous test's cached column buffer must not force a skip
+ if torch.cuda.mem_get_info()[0] < self.NEEDS_FREE_BYTES:
+ pytest.skip("native conv3d's Im3d2Col column buffer needs ~14 GiB free")
+ torch.manual_seed(0)
+ conv = WanCausalConv3d(96, 96, kernel_size=3, padding=1).to("cuda", torch.bfloat16)
+ return conv, torch.randn(self.SHAPE, device="cuda", dtype=torch.bfloat16)
+
+ def test_native_conv3d_still_takes_the_multiframe_fallback(self) -> None:
+ """Pins why the patch has no HIP-version gate. When this passes on a new torch, the
+ decomposition may be unnecessary."""
+ conv, x = self._conv_and_input()
+ stock = mod._STOCK_FORWARD or WanCausalConv3d.forward
+ with torch.inference_mode():
+ for fn in (stock, _decomposed_forward):
+ fn(conv, x) # warm-up: MIOpen find + kernel compile
+ native = self._timed(lambda: stock(conv, x))
+ decomposed = self._timed(lambda: _decomposed_forward(conv, x))
+ # Measured 128x on a W7900 with torch 2.13.0+rocm7.2; 10x leaves room for clock/contention noise.
+ assert native / decomposed >= 10, (
+ f"native conv3d is now within {native / decomposed:.1f}x of the decomposition for multi-frame "
+ "chunks: the Wan decomposition may be unnecessary"
+ )
+
+ def test_long_clip_encode_completes(self) -> None:
+ """Pins the contiguous copies in `_decomposed_conv3d`. With the natural strided views,
+ MIOpen faults asynchronously part-way through a long clip (161 frames at 720x1024 aborted
+ or segfaulted the process every time on torch 2.13.0+rocm7.2; 81 frames passed) -- so a
+ fault here kills the pytest process rather than failing an assertion. Weights are random:
+ the fault does not depend on them."""
+ from diffusers.models.autoencoders import AutoencoderKLWan
+
+ torch.cuda.empty_cache()
+ if torch.cuda.mem_get_info()[0] < 12 * 2**30:
+ pytest.skip("the 161-frame encode peaks ~9 GiB")
+ stock_forward = WanCausalConv3d.forward
+ already_patched = getattr(WanCausalConv3d, mod._SENTINEL, False)
+ _patch_wan_causal_conv3d()
+ try:
+ torch.manual_seed(0)
+ vae = AutoencoderKLWan(z_dim=16).to("cuda", torch.bfloat16).eval()
+ clip = torch.zeros((1, 3, 161, 1024, 720), device="cuda", dtype=torch.bfloat16)
+ clip[:, :, 0] = torch.rand((1, 3, 1024, 720), device="cuda", dtype=torch.bfloat16) * 2 - 1
+ with torch.inference_mode():
+ latents = vae.encode(clip, return_dict=False)[0].mode()
+ torch.cuda.synchronize()
+ finally:
+ if not already_patched:
+ WanCausalConv3d.forward = stock_forward
+ delattr(WanCausalConv3d, mod._SENTINEL)
+ assert latents.shape == (1, 16, 41, 128, 90)
+ assert torch.isfinite(latents).all()
+
+ def test_decomposition_matches_native_under_allocation_churn(self) -> None:
+ """The decomposition's outputs must not depend on allocator state (the failure class once
+ blamed on it): both device paths stay within bf16 noise of a CPU fp32 reference while
+ junk allocations come and go between calls."""
+ conv, x = self._conv_and_input()
+ x = x[:, :, :, :240, :416] # non-square, past the cache path, cheap enough for many calls
+ cache = torch.randn((1, 96, 2, 240, 416), device="cuda", dtype=torch.bfloat16)
+ stock = mod._STOCK_FORWARD or WanCausalConv3d.forward
+ with torch.inference_mode():
+ reference = WanCausalConv3d.forward(conv.float().cpu(), x.float().cpu(), cache_x=cache.float().cpu())
+ conv = conv.to("cuda", torch.bfloat16)
+ rnd = random.Random(0)
+ for _ in range(20):
+ junk = [
+ torch.empty(rnd.randint(1, 400) * 2**20, device="cuda", dtype=torch.uint8)
+ for _ in range(rnd.randint(1, 4))
+ ]
+ for fn in (stock, _decomposed_forward):
+ out = fn(conv, x, cache_x=cache).float().cpu()
+ err = (out - reference).abs().max().item()
+ assert err < mod._VERIFY_TOL, f"{fn.__name__}: max abs error {err:.4f} vs CPU fp32"
+ del junk
+ if rnd.random() < 0.5:
+ torch.cuda.empty_cache()