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.

harden non-finite decode triage per adversarial review

Lincoln Steindbd1a193e0a8
diff --git a/invokeai/app/invocations/anima_latents_to_image.py b/invokeai/app/invocations/anima_latents_to_image.py
index 2b6973b3db..3dad78d244 100644
--- a/invokeai/app/invocations/anima_latents_to_image.py
+++ b/invokeai/app/invocations/anima_latents_to_image.py
@@ -240,6 +240,21 @@ class AnimaLatentsToImageInvocation(BaseInvocation, WithMetadata, WithBoard):
achieved; never raises, since a black image plus a diagnostic log beats a failed
generation.
"""
+ try:
+ return self._recover_nonfinite_decode_impl(context, vae, latents, decoded, latents_finite)
+ except Exception:
+ # The triage itself must never convert a black image into a failed generation.
+ context.logger.exception("VAE decode non-finite triage failed; returning the corrupt decode.")
+ return decoded
+
+ def _recover_nonfinite_decode_impl(
+ self,
+ context: InvocationContext,
+ vae: AutoencoderKLWan,
+ latents: torch.Tensor,
+ decoded: torch.Tensor,
+ latents_finite: bool,
+ ) -> torch.Tensor:
device = latents.device
scan = scan_module_for_nonfinite_weights(vae, device.type)
@@ -250,8 +265,9 @@ class AnimaLatentsToImageInvocation(BaseInvocation, WithMetadata, WithBoard):
)
elif not scan.clean:
assessment = (
- "the cached VAE WEIGHTS are corrupt — every decode will fail until the model is "
- "reloaded (clearing the model cache should recover it)"
+ "NaN/Inf (or unreadable tensors) found among the cached VAE WEIGHTS — if genuinely "
+ "corrupt, every decode will fail until the model is reloaded (clearing the model "
+ "cache should recover it)"
)
else:
assessment = (
@@ -278,9 +294,10 @@ class AnimaLatentsToImageInvocation(BaseInvocation, WithMetadata, WithBoard):
return retry
# Attempt 2: force a REAL global empty_cache — bypassing the peer-aware skip — and
- # retry. This can stall a peer GPU's in-flight step once, which is a better trade
- # than a black image; if it heals the decode, the allocator-state mechanism is
- # confirmed.
+ # retry. This stalls BOTH workers once: the peer's in-flight step, and this thread,
+ # which waits inside hipFree until that step's kernel completes (up to ~a minute on
+ # a long video step). Still a better trade than a black image; if it heals the
+ # decode, the allocator-state mechanism is confirmed.
context.logger.warning(
"VAE decode still non-finite after a plain retry; forcing a global empty_cache "
"(a peer GPU's in-flight step may stall once) and retrying."
diff --git a/invokeai/backend/util/vae_decode_diagnostics.py b/invokeai/backend/util/vae_decode_diagnostics.py
index fb40c95dd6..735faca89c 100644
--- a/invokeai/backend/util/vae_decode_diagnostics.py
+++ b/invokeai/backend/util/vae_decode_diagnostics.py
@@ -72,9 +72,10 @@ def scan_module_for_nonfinite_weights(module: torch.nn.Module, compute_device_ty
for name, tensor in list(module.named_parameters()) + list(module.named_buffers()):
# Shared/tied tensors appear under multiple names; count each storage once. data_ptr
# catches ties that wrap the same storage in distinct tensor objects; fall back to
- # object identity for tensors without an addressable storage (e.g. meta).
+ # object identity for tensors without an addressable storage (data_ptr() is 0 on meta
+ # and zero-element tensors — one shared key there would hide all but the first).
try:
- key = tensor.data_ptr()
+ key = tensor.data_ptr() or id(tensor)
except RuntimeError:
key = id(tensor)
if key in seen:
@@ -86,8 +87,9 @@ def scan_module_for_nonfinite_weights(module: torch.nn.Module, compute_device_ty
try:
if bool(torch.isfinite(tensor).all()):
continue
- except RuntimeError:
- # A tensor that cannot even be read (sick context, meta device) is itself a
+ except Exception:
+ # A tensor that cannot even be read (sick context, meta device, a dtype or wrapper
+ # subclass without isfinite — those raise TypeError, not RuntimeError) is itself a
# finding; report it rather than aborting the whole scan.
pass
scan.nonfinite_names.append(f"{name}@{tensor.device}")
diff --git a/tests/app/invocations/test_anima_nonfinite_decode_recovery.py b/tests/app/invocations/test_anima_nonfinite_decode_recovery.py
new file mode 100644
index 0000000000..bea6d469e8
--- /dev/null
+++ b/tests/app/invocations/test_anima_nonfinite_decode_recovery.py
@@ -0,0 +1,126 @@
+"""Tests for AnimaLatentsToImageInvocation._recover_nonfinite_decode's gating and retry logic.
+
+The method is exercised directly (it reads nothing from ``self``), with a scripted stub VAE
+and a plain-logger context, so the tests cover exactly the shipped decision tree: the
+short-circuits for upstream/weight corruption, the retry ordering, which tensor is returned,
+and the never-raise backstop.
+"""
+
+import logging
+import math
+from types import SimpleNamespace
+
+import torch
+
+import invokeai.app.invocations.anima_latents_to_image as anima_l2i
+from invokeai.app.invocations.anima_latents_to_image import AnimaLatentsToImageInvocation
+
+
+class _StubWanVae(torch.nn.Module):
+ """A minimal module whose decode() returns scripted outputs in order."""
+
+ def __init__(self, outputs: list[torch.Tensor]):
+ super().__init__()
+ self.linear = torch.nn.Linear(2, 2) # gives the weight scanner something finite to scan
+ self._outputs = list(outputs)
+ self.decode_calls = 0
+
+ def decode(self, latents: torch.Tensor, return_dict: bool = True):
+ self.decode_calls += 1
+ return (self._outputs.pop(0),)
+
+
+def _ctx():
+ return SimpleNamespace(logger=logging.getLogger("test_anima_nonfinite_decode_recovery"))
+
+
+def _nan_image() -> torch.Tensor:
+ t = torch.zeros(1, 3, 1, 4, 4)
+ t[0, 0, 0, 0, 0] = math.nan
+ return t
+
+
+_LATENTS = torch.zeros(1, 16, 1, 2, 2)
+
+
+def _recover(vae, decoded, latents_finite):
+ # model_construct() skips pydantic validation; the method reads none of the input fields.
+ invocation = AnimaLatentsToImageInvocation.model_construct()
+ return invocation._recover_nonfinite_decode(_ctx(), vae, _LATENTS, decoded, latents_finite)
+
+
+def test_nonfinite_latents_short_circuit_no_retry():
+ vae = _StubWanVae([])
+ decoded = _nan_image()
+ out = _recover(vae, decoded, latents_finite=False)
+ assert out is decoded
+ assert vae.decode_calls == 0
+
+
+def test_corrupt_weights_short_circuit_no_retry():
+ vae = _StubWanVae([])
+ vae.linear.weight.data[0, 0] = math.nan
+ decoded = _nan_image()
+ out = _recover(vae, decoded, latents_finite=True)
+ assert out is decoded
+ assert vae.decode_calls == 0
+
+
+def test_plain_retry_heals(monkeypatch):
+ flush_calls = {"n": 0}
+ monkeypatch.setattr(anima_l2i, "force_real_empty_cache", lambda: flush_calls.__setitem__("n", flush_calls["n"] + 1))
+ good = torch.zeros(1, 3, 1, 4, 4)
+ vae = _StubWanVae([good])
+ out = _recover(vae, _nan_image(), latents_finite=True)
+ assert out is good
+ assert vae.decode_calls == 1
+ assert flush_calls["n"] == 0 # the forced flush must not run when a plain retry suffices
+
+
+def test_forced_empty_cache_retry_heals(monkeypatch):
+ flush_calls = {"n": 0}
+ monkeypatch.setattr(anima_l2i, "force_real_empty_cache", lambda: flush_calls.__setitem__("n", flush_calls["n"] + 1))
+ good = torch.zeros(1, 3, 1, 4, 4)
+ vae = _StubWanVae([_nan_image(), good])
+ out = _recover(vae, _nan_image(), latents_finite=True)
+ assert out is good
+ assert vae.decode_calls == 2
+ assert flush_calls["n"] == 1
+
+
+def test_unrecoverable_returns_last_retry(monkeypatch):
+ monkeypatch.setattr(anima_l2i, "force_real_empty_cache", lambda: None)
+ still_bad = _nan_image()
+ vae = _StubWanVae([_nan_image(), still_bad])
+ out = _recover(vae, _nan_image(), latents_finite=True)
+ assert out is still_bad
+ assert vae.decode_calls == 2
+
+
+def test_retry_runtime_error_returns_original_decode(monkeypatch):
+ monkeypatch.setattr(anima_l2i, "force_real_empty_cache", lambda: None)
+
+ class _RaisingVae(_StubWanVae):
+ def decode(self, latents, return_dict=True):
+ self.decode_calls += 1
+ raise RuntimeError("HIP error: out of memory")
+
+ vae = _RaisingVae([])
+ decoded = _nan_image()
+ out = _recover(vae, decoded, latents_finite=True)
+ assert out is decoded
+
+
+def test_triage_failure_backstop_returns_original_decode(monkeypatch):
+ """The never-raise contract: even the triage machinery blowing up (any exception type)
+ must fall back to returning the corrupt decode, not fail the generation."""
+
+ def boom(*args, **kwargs):
+ raise TypeError("wrapper subclass without isfinite")
+
+ monkeypatch.setattr(anima_l2i, "scan_module_for_nonfinite_weights", boom)
+ vae = _StubWanVae([])
+ decoded = _nan_image()
+ out = _recover(vae, decoded, latents_finite=True)
+ assert out is decoded
+ assert vae.decode_calls == 0
diff --git a/tests/backend/util/test_vae_decode_diagnostics.py b/tests/backend/util/test_vae_decode_diagnostics.py
index 3dc3fd4198..35754108b7 100644
--- a/tests/backend/util/test_vae_decode_diagnostics.py
+++ b/tests/backend/util/test_vae_decode_diagnostics.py
@@ -95,3 +95,38 @@ def test_force_real_empty_cache_without_wrapper(monkeypatch):
def test_allocator_state_summary_cpu_device_mentions_peer_state():
summary = allocator_state_summary(torch.device("cpu"))
assert "peer_generation_device_busy=" in summary
+
+
+def test_force_real_empty_cache_bypasses_installed_peer_aware_wrapper(monkeypatch):
+ """Integration: the bypass must reach the real entry point through the wrapper that
+ install_peer_aware_empty_cache actually builds, in the exact scenario the recovery targets
+ (a peer generation device mid-session, where the wrapper itself skips)."""
+ from invokeai.backend.util.device_pool import GENERATION_DEVICE_POOL
+ from invokeai.backend.util.devices import install_peer_aware_empty_cache
+
+ calls = {"real": 0}
+
+ def stub():
+ calls["real"] += 1
+
+ original = torch.cuda.empty_cache
+ monkeypatch.setattr(torch.cuda, "empty_cache", stub)
+ try:
+ install_peer_aware_empty_cache()
+ assert torch.cuda.empty_cache is not stub # the wrapper is installed over the stub
+
+ GENERATION_DEVICE_POOL.reset()
+ GENERATION_DEVICE_POOL.set_generation_devices([torch.device("cuda:0"), torch.device("cuda:1")])
+ GENERATION_DEVICE_POOL.acquire_session(torch.device("cuda:1"))
+ try:
+ torch.cuda.empty_cache()
+ assert calls["real"] == 0 # the peer-aware wrapper skipped (peer busy)
+ force_real_empty_cache()
+ assert calls["real"] == 1 # the bypass reached the real entry point anyway
+ finally:
+ GENERATION_DEVICE_POOL.release_session(torch.device("cuda:1"))
+ GENERATION_DEVICE_POOL.reset()
+ finally:
+ # monkeypatch restores the attribute it replaced; make certain the pristine original is
+ # back regardless of ordering with the wrapper installation.
+ torch.cuda.empty_cache = original