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
diag(anima): triage and recover non-finite VAE decodes (black images)
Lincoln Steina9293e139bb5
diff --git a/invokeai/app/invocations/anima_latents_to_image.py b/invokeai/app/invocations/anima_latents_to_image.pyindex 18b5db028d..2b6973b3db 100644--- a/invokeai/app/invocations/anima_latents_to_image.py+++ b/invokeai/app/invocations/anima_latents_to_image.py@@ -29,6 +29,12 @@ from invokeai.app.invocations.primitives import ImageOutputfrom invokeai.app.services.shared.invocation_context import InvocationContextfrom invokeai.backend.flux.modules.autoencoder import AutoEncoder as FluxAutoEncoderfrom invokeai.backend.util.devices import TorchDevice+from invokeai.backend.util.vae_decode_diagnostics import (+ allocator_state_summary,+ force_real_empty_cache,+ nonfinite_fraction,+ scan_module_for_nonfinite_weights,+)from invokeai.backend.util.vae_working_memory import (estimate_vae_working_memory_anima,estimate_vae_working_memory_flux,@@ -177,6 +183,9 @@ class AnimaLatentsToImageInvocation(BaseInvocation, WithMetadata, WithBoard):latents_mean = torch.tensor(vae.config.latents_mean).view(1, -1, 1, 1, 1).to(latents)latents_std = torch.tensor(vae.config.latents_std).view(1, -1, 1, 1, 1).to(latents)latents = latents * latents_std + latents_mean+ # Cheap (latents are small); the black-image triage below needs it to tell+ # upstream corruption from decode-side corruption.+ latents_finite = bool(torch.isfinite(latents).all())try:decoded = vae.decode(latents, return_dict=False)[0]@@ -194,6 +203,11 @@ class AnimaLatentsToImageInvocation(BaseInvocation, WithMetadata, WithBoard):)decoded = vae.decode(latents, return_dict=False)[0]+ if not bool(torch.isfinite(decoded).all()):+ # NaN survives clamp(-1, 1) and quantizes to 0: without this, the+ # failure renders as a silent black image. Diagnose and try to recover.+ decoded = self._recover_nonfinite_decode(context, vae, latents, decoded, latents_finite)+# Output is 5D [B, C, T, H, W] — squeeze temporal dimif decoded.ndim == 5:decoded = decoded.squeeze(2)@@ -207,3 +221,84 @@ class AnimaLatentsToImageInvocation(BaseInvocation, WithMetadata, WithBoard):image_dto = context.images.save(image=img_pil)return ImageOutput.build(image_dto)++ def _recover_nonfinite_decode(+ self,+ context: InvocationContext,+ vae: AutoencoderKLWan,+ latents: torch.Tensor,+ decoded: torch.Tensor,+ latents_finite: bool,+ ) -> torch.Tensor:+ """Diagnose and, when possible, recover a decode that produced NaN/Inf (a black image).++ Seen intermittently on a dual-GPU ROCm rig while a long video generation runs on the+ other GPU. Logs a fingerprint that discriminates the candidate mechanisms — non-finite+ latents from upstream, corrupt cached VAE weights, or clean-inputs/clean-weights decode+ compute failure (the allocator-state-dependent kernel class) — then makes two bounded+ recovery attempts whose outcomes sharpen the diagnosis. Returns the best decode+ achieved; never raises, since a black image plus a diagnostic log beats a failed+ generation.+ """+ device = latents.device+ scan = scan_module_for_nonfinite_weights(vae, device.type)++ if not latents_finite:+ assessment = (+ "the latents entering the decode already contain NaN/Inf — corruption happened "+ "UPSTREAM of the VAE (denoise output or tensor transfer); retrying the decode cannot help"+ )+ 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)"+ )+ else:+ assessment = (+ "latents and weights are finite but the decode COMPUTED NaN/Inf — consistent with an "+ "allocator-state-dependent kernel failure on this device"+ )+ context.logger.error(+ "VAE decode produced non-finite output (this renders as a black image).\n"+ f" non-finite fraction of decode output: {nonfinite_fraction(decoded):.4f}\n"+ f" latents finite: {latents_finite}\n"+ f" weights: {scan.describe()}\n"+ f" allocator: {allocator_state_summary(device)}\n"+ f" assessment: {assessment}"+ )++ if not latents_finite or not scan.clean:+ return decoded++ try:+ # Attempt 1: plain retry, to rule out a transient.+ retry = vae.decode(latents, return_dict=False)[0]+ if bool(torch.isfinite(retry).all()):+ context.logger.warning("VAE decode recovered on a plain retry (transient non-finite decode).")+ 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.+ 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."+ )+ force_real_empty_cache()+ retry = vae.decode(latents, return_dict=False)[0]+ if bool(torch.isfinite(retry).all()):+ context.logger.warning(+ "VAE decode recovered after a forced global empty_cache — allocator-state-dependent "+ "decode corruption on this device is CONFIRMED."+ )+ return retry+ except RuntimeError as e:+ context.logger.error(f"VAE decode recovery attempt raised {type(e).__name__}: {e}")+ return decoded++ context.logger.error(+ "VAE decode remained non-finite after both recovery attempts; returning the corrupt "+ "decode (the image will be black)."+ )+ return retrydiff --git a/invokeai/backend/util/vae_decode_diagnostics.py b/invokeai/backend/util/vae_decode_diagnostics.pynew file mode 100644index 0000000000..fb40c95dd6--- /dev/null+++ b/invokeai/backend/util/vae_decode_diagnostics.py@@ -0,0 +1,144 @@+"""Triage for non-finite VAE decode output ("black image" generations).++On a dual-GPU ROCm rig, Wan-VAE (Anima) image decodes intermittently start returning+all-NaN output while a long video generation runs on the other GPU, and stay broken until+the video finishes. NaN survives the final ``clamp(-1, 1)`` and quantizes to 0, so every+affected generation is a solid black image with no error anywhere in the log.++The failure has at least three candidate mechanisms that ordinary logs cannot tell apart:++1. The latents entering the decode are already non-finite (corruption upstream, in the+ 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+ 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.++These helpers gather the discriminating evidence at the moment of failure — latent+finiteness is checked by the caller, weight state and allocator state here — and support a+bounded recovery attempt whose outcome is itself the fingerprint: a decode healed by a+*forced real* ``empty_cache`` (mechanism 3) versus one only healed by a weight reload+(mechanism 2).+"""++from dataclasses import dataclass, field++import torch++from invokeai.backend.util.devices import TorchDevice+++@dataclass+class NonFiniteWeightScan:+ """Result of scanning a module's parameters/buffers for NaN/Inf."""++ tensors_scanned: int = 0+ # Fully-qualified names of tensors containing at least one non-finite value, capped by the+ # scanner to keep log lines bounded.+ nonfinite_names: list[str] = field(default_factory=list)+ nonfinite_on_compute: int = 0+ nonfinite_on_cpu: int = 0++ @property+ def clean(self) -> bool:+ return self.nonfinite_on_compute == 0 and self.nonfinite_on_cpu == 0++ def describe(self) -> str:+ if self.clean:+ return f"all {self.tensors_scanned} weight tensors finite"+ names = ", ".join(self.nonfinite_names[:8])+ suffix = ", ..." if len(self.nonfinite_names) > 8 else ""+ return (+ f"{self.nonfinite_on_compute} weight tensor(s) with NaN/Inf on the compute device and "+ f"{self.nonfinite_on_cpu} on the CPU, of {self.tensors_scanned} scanned ({names}{suffix})"+ )++[email protected]_grad()+def scan_module_for_nonfinite_weights(module: torch.nn.Module, compute_device_type: str) -> NonFiniteWeightScan:+ """Scan every parameter and buffer of ``module`` for NaN/Inf values.++ Cheap relative to a decode (one reduction per tensor; a Wan VAE is a few hundred MB), and+ only ever run after a decode has already produced non-finite output.++ Floating tensors only: integer tensors cannot hold NaN/Inf and ``isfinite`` on them is+ wasted work (quantized models keep int8 weights).+ """+ scan = NonFiniteWeightScan()+ seen: set[int] = set()+ 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).+ try:+ key = tensor.data_ptr()+ except RuntimeError:+ key = id(tensor)+ if key in seen:+ continue+ seen.add(key)+ if not tensor.is_floating_point():+ continue+ scan.tensors_scanned += 1+ try:+ if bool(torch.isfinite(tensor).all()):+ continue+ except RuntimeError:+ # A tensor that cannot even be read (sick context, meta device) is itself a+ # finding; report it rather than aborting the whole scan.+ pass+ scan.nonfinite_names.append(f"{name}@{tensor.device}")+ if tensor.device.type == compute_device_type:+ scan.nonfinite_on_compute += 1+ else:+ scan.nonfinite_on_cpu += 1+ return scan+++def allocator_state_summary(device: torch.device) -> str:+ """One-line caching-allocator + peer-activity summary for ``device``.++ Includes whether another generation device is mid-session — i.e. whether every+ ``empty_cache`` on this device has been getting skipped by the peer-aware policy.+ """+ peer_busy = TorchDevice._another_generation_device_busy()+ if device.type != "cuda" or not torch.cuda.is_available():+ return f"device={device}, peer_generation_device_busy={peer_busy}"+ try:+ reserved = torch.cuda.memory_reserved(device)+ allocated = torch.cuda.memory_allocated(device)+ stats = torch.cuda.memory_stats(device)+ inactive_split = int(stats.get("inactive_split_bytes.all.current", 0))+ segments = int(stats.get("segment.all.current", 0))+ mb = 2**20+ return (+ f"device={device}, reserved={reserved / mb:.0f}MB, allocated={allocated / mb:.0f}MB, "+ f"inactive_split={inactive_split / mb:.0f}MB, segments={segments}, "+ f"peer_generation_device_busy={peer_busy}"+ )+ except Exception as e:+ return f"device={device}, allocator stats unavailable ({type(e).__name__}), peer_generation_device_busy={peer_busy}"+++def force_real_empty_cache() -> None:+ """Run the REAL ``torch.cuda.empty_cache``, bypassing the peer-aware skip.++ ``install_peer_aware_empty_cache`` rebinds ``torch.cuda.empty_cache`` with a wrapper that+ skips while any other generation device is mid-session. This helper reaches through the+ wrapper (``functools.wraps`` preserves the original as ``__wrapped__``) for the one case+ where the skip is the wrong trade: recovering a decode that is producing garbage, where a+ single peer-convoying cache flush is strictly better than a black image. Callers must log+ that they did this — a peer device's in-flight step will stall until this returns.+ """+ real = getattr(torch.cuda.empty_cache, "__wrapped__", torch.cuda.empty_cache)+ real()+++def nonfinite_fraction(tensor: torch.Tensor) -> float:+ """Fraction of ``tensor``'s elements that are NaN/Inf."""+ if tensor.numel() == 0:+ return 0.0+ return float((~torch.isfinite(tensor)).sum().item()) / tensor.numel()diff --git a/tests/backend/util/test_vae_decode_diagnostics.py b/tests/backend/util/test_vae_decode_diagnostics.pynew file mode 100644index 0000000000..3dc3fd4198--- /dev/null+++ b/tests/backend/util/test_vae_decode_diagnostics.py@@ -0,0 +1,97 @@+import math++import torch++from invokeai.backend.util.vae_decode_diagnostics import (+ allocator_state_summary,+ force_real_empty_cache,+ nonfinite_fraction,+ scan_module_for_nonfinite_weights,+)+++class _TinyModule(torch.nn.Module):+ def __init__(self):+ super().__init__()+ self.linear = torch.nn.Linear(4, 4)+ self.register_buffer("scale", torch.ones(4))+ self.register_buffer("counts", torch.zeros(4, dtype=torch.int64))+++def test_scan_clean_module_reports_no_nonfinite():+ scan = scan_module_for_nonfinite_weights(_TinyModule(), "cuda")+ assert scan.clean+ assert scan.nonfinite_names == []+ # linear.weight, linear.bias, scale — the int64 buffer is skipped.+ assert scan.tensors_scanned == 3+ assert "finite" in scan.describe()+++def test_scan_finds_and_names_nonfinite_tensor():+ module = _TinyModule()+ module.linear.weight.data[0, 0] = math.nan+ module.scale[1] = math.inf+ scan = scan_module_for_nonfinite_weights(module, "cuda")+ assert not scan.clean+ # Both corrupt tensors live on CPU, and the scan ran with a cuda compute-device type.+ assert scan.nonfinite_on_cpu == 2+ assert scan.nonfinite_on_compute == 0+ assert any(n.startswith("linear.weight@") for n in scan.nonfinite_names)+ assert any(n.startswith("scale@") for n in scan.nonfinite_names)+ assert "linear.weight" in scan.describe()+++def test_scan_classifies_compute_device_by_type():+ module = _TinyModule()+ module.linear.weight.data[0, 0] = math.nan+ # Treat CPU as the compute device: the corrupt tensor must be counted on-compute.+ scan = scan_module_for_nonfinite_weights(module, "cpu")+ assert scan.nonfinite_on_compute == 1+ assert scan.nonfinite_on_cpu == 0+++def test_scan_counts_tied_tensors_once():+ module = _TinyModule()+ module.tied = torch.nn.Parameter(module.linear.weight) # same tensor under a second name+ scan = scan_module_for_nonfinite_weights(module, "cuda")+ assert scan.tensors_scanned == 3+++def test_nonfinite_fraction():+ t = torch.zeros(10)+ assert nonfinite_fraction(t) == 0.0+ t[0] = math.nan+ t[1] = math.inf+ assert abs(nonfinite_fraction(t) - 0.2) < 1e-9+ assert nonfinite_fraction(torch.zeros(0)) == 0.0+++def test_force_real_empty_cache_bypasses_wrapper(monkeypatch):+ calls = {"real": 0, "wrapper": 0}++ def real():+ calls["real"] += 1++ def wrapper():+ calls["wrapper"] += 1++ wrapper.__wrapped__ = real+ monkeypatch.setattr(torch.cuda, "empty_cache", wrapper)+ force_real_empty_cache()+ assert calls == {"real": 1, "wrapper": 0}+++def test_force_real_empty_cache_without_wrapper(monkeypatch):+ calls = {"n": 0}++ def plain():+ calls["n"] += 1++ monkeypatch.setattr(torch.cuda, "empty_cache", plain)+ force_real_empty_cache()+ assert calls["n"] == 1+++def test_allocator_state_summary_cpu_device_mentions_peer_state():+ summary = allocator_state_summary(torch.device("cpu"))+ assert "peer_generation_device_busy=" in summary