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.

feat(anima) - Anima Performance Improvements (#9220)

kappacommitbe8ebeb34a50
diff --git a/invokeai/app/invocations/anima_denoise.py b/invokeai/app/invocations/anima_denoise.py
index 9fa4b3fb07..1e490dd581 100644
--- a/invokeai/app/invocations/anima_denoise.py
+++ b/invokeai/app/invocations/anima_denoise.py
@@ -17,11 +17,13 @@ Key differences from Z-Image denoise:
"""
import math
+import sys
from contextlib import ExitStack
from typing import Callable, Iterator, Optional, Tuple
import torch
import torchvision.transforms as tv_transforms
+from torch.nn.attention import SDPBackend, sdpa_kernel
from torchvision.transforms.functional import resize as tv_resize
from tqdm import tqdm
@@ -528,6 +530,29 @@ class AnimaDenoiseInvocation(BaseInvocation):
)
with ExitStack() as exit_stack:
+ # On Windows + CUDA, opt into cuDNN's flash-attention kernel. torch on
+ # Windows does not ship the native flash-attention backend, so SDPA falls
+ # back to the slower memory-efficient kernel; cuDNN's kernel is ~1.7x faster
+ # for Anima's attention shapes (~6% per denoising step at 1024x1024). The
+ # cuDNN SDP backend sits low in torch's default priority and is never
+ # selected, so we opt in explicitly.
+ #
+ # This is a priority *list*, not a forced kernel: torch picks the first
+ # eligible backend per call, and MATH is always eligible, so it degrades
+ # safely on any GPU/dtype where cuDNN is unavailable. Scoped to Windows +
+ # CUDA — elsewhere torch's default backend is already fast.
+ if device.type == "cuda" and sys.platform == "win32":
+ exit_stack.enter_context(
+ sdpa_kernel(
+ [
+ SDPBackend.CUDNN_ATTENTION,
+ SDPBackend.FLASH_ATTENTION,
+ SDPBackend.EFFICIENT_ATTENTION,
+ SDPBackend.MATH,
+ ],
+ set_priority=True,
+ )
+ )
(cached_weights, transformer) = exit_stack.enter_context(transformer_info.model_on_device())
# Apply LoRA models to the transformer.
diff --git a/invokeai/app/invocations/anima_image_to_latents.py b/invokeai/app/invocations/anima_image_to_latents.py
index 83073ab4a8..95afea885c 100644
--- a/invokeai/app/invocations/anima_image_to_latents.py
+++ b/invokeai/app/invocations/anima_image_to_latents.py
@@ -33,7 +33,10 @@ from invokeai.backend.flux.modules.autoencoder import AutoEncoder as FluxAutoEnc
from invokeai.backend.model_manager.load.load_base import LoadedModel
from invokeai.backend.stable_diffusion.diffusers_pipeline import image_resized_to_grid_as_tensor
from invokeai.backend.util.devices import TorchDevice
-from invokeai.backend.util.vae_working_memory import estimate_vae_working_memory_flux
+from invokeai.backend.util.vae_working_memory import (
+ estimate_vae_working_memory_anima,
+ estimate_vae_working_memory_flux,
+)
AnimaVAE = Union[AutoencoderKLWan, FluxAutoEncoder]
@@ -43,7 +46,7 @@ AnimaVAE = Union[AutoencoderKLWan, FluxAutoEncoder]
title="Image to Latents - Anima",
tags=["image", "latents", "vae", "i2l", "anima"],
category="image",
- version="1.0.0",
+ version="1.0.1",
classification=Classification.Prototype,
)
class AnimaImageToLatentsInvocation(BaseInvocation, WithMetadata, WithBoard):
@@ -59,11 +62,19 @@ class AnimaImageToLatentsInvocation(BaseInvocation, WithMetadata, WithBoard):
f"Expected AutoencoderKLWan or FluxAutoEncoder for Anima VAE, got {type(vae_info.model).__name__}."
)
- estimated_working_memory = estimate_vae_working_memory_flux(
- operation="encode",
- image_tensor=image_tensor,
- vae=vae_info.model,
- )
+ if isinstance(vae_info.model, AutoencoderKLWan):
+ estimated_working_memory = estimate_vae_working_memory_anima(
+ operation="encode",
+ image_tensor=image_tensor,
+ vae=vae_info.model,
+ tile_size=None,
+ )
+ else:
+ estimated_working_memory = estimate_vae_working_memory_flux(
+ operation="encode",
+ image_tensor=image_tensor,
+ vae=vae_info.model,
+ )
with vae_info.model_on_device(working_mem_bytes=estimated_working_memory) as (_, vae):
if not isinstance(vae, (AutoencoderKLWan, FluxAutoEncoder)):
@@ -78,6 +89,9 @@ class AnimaImageToLatentsInvocation(BaseInvocation, WithMetadata, WithBoard):
generator = torch.Generator(device=TorchDevice.choose_torch_device()).manual_seed(0)
latents = vae.encode(image_tensor, sample=True, generator=generator)
else:
+ # The cached VAE instance is shared with the decode invocation, which
+ # may have enabled tiling — encode untiled for exactness.
+ vae.disable_tiling()
# AutoencoderKLWan expects 5D input [B, C, T, H, W]
if image_tensor.ndim == 4:
image_tensor = image_tensor.unsqueeze(2) # [B, C, H, W] -> [B, C, 1, H, W]
diff --git a/invokeai/app/invocations/anima_latents_to_image.py b/invokeai/app/invocations/anima_latents_to_image.py
index 080c101fa4..26e3998ae7 100644
--- a/invokeai/app/invocations/anima_latents_to_image.py
+++ b/invokeai/app/invocations/anima_latents_to_image.py
@@ -29,7 +29,29 @@ from invokeai.app.invocations.primitives import ImageOutput
from invokeai.app.services.shared.invocation_context import InvocationContext
from invokeai.backend.flux.modules.autoencoder import AutoEncoder as FluxAutoEncoder
from invokeai.backend.util.devices import TorchDevice
-from invokeai.backend.util.vae_working_memory import estimate_vae_working_memory_flux
+from invokeai.backend.util.vae_working_memory import (
+ estimate_vae_working_memory_anima,
+ estimate_vae_working_memory_flux,
+)
+
+# Tile geometry for tiled Wan VAE decode. 512px tiles with a 384px stride (128px blended
+# overlap) cap peak decode working memory at ~1.7GB regardless of image size, while images
+# <=512px still decode in a single pass.
+ANIMA_VAE_TILE_SIZE = 512
+ANIMA_VAE_TILE_STRIDE = 384
+
+
+def _is_oom_error(e: RuntimeError) -> bool:
+ """Return True if the error indicates a CUDA out-of-memory condition.
+
+ The caching allocator raises torch.cuda.OutOfMemoryError, but an OOM surfaced from inside a
+ cuDNN/cuBLAS kernel (e.g. workspace allocation in the Wan VAE's convolutions) arrives as a
+ plain RuntimeError, which must be matched by message.
+ """
+ if isinstance(e, torch.cuda.OutOfMemoryError):
+ return True
+ msg = str(e)
+ return "out of memory" in msg.lower() or "CUDNN_STATUS_ALLOC_FAILED" in msg or "CUBLAS_STATUS_ALLOC_FAILED" in msg
@invocation(
@@ -37,7 +59,7 @@ from invokeai.backend.util.vae_working_memory import estimate_vae_working_memory
title="Latents to Image - Anima",
tags=["latents", "image", "vae", "l2i", "anima"],
category="latents",
- version="1.0.2",
+ version="1.0.3",
classification=Classification.Prototype,
)
class AnimaLatentsToImageInvocation(BaseInvocation, WithMetadata, WithBoard):
@@ -50,6 +72,22 @@ class AnimaLatentsToImageInvocation(BaseInvocation, WithMetadata, WithBoard):
latents: LatentsField = InputField(description=FieldDescriptions.latents, input=Input.Connection)
vae: VAEField = InputField(description=FieldDescriptions.vae, input=Input.Connection)
+ @staticmethod
+ def _use_tiled_decode(device: torch.device, full_decode_working_memory: int) -> bool:
+ """Decide whether to decode in tiles.
+
+ A full 1024x1024 Wan VAE decode reserves ~6GB of working memory. On small-VRAM
+ GPUs this evicts the (~4GB) Anima transformer from the model cache and thrashes
+ the allocator near the VRAM ceiling (decode times of 7s+ observed on 8GB, vs
+ ~1s tiled with the transformer left resident). Tile when the full-decode working
+ memory would consume most of the device, otherwise a single-pass decode is
+ faster (~0.65s vs ~1.05s at 1024x1024) and exact.
+ """
+ if device.type != "cuda":
+ return False
+ total_vram = torch.cuda.get_device_properties(device).total_memory
+ return full_decode_working_memory > 0.7 * total_vram
+
@torch.no_grad()
def invoke(self, context: InvocationContext) -> ImageOutput:
latents = context.tensors.load(self.latents.latents_name)
@@ -60,11 +98,27 @@ class AnimaLatentsToImageInvocation(BaseInvocation, WithMetadata, WithBoard):
f"Expected AutoencoderKLWan or FluxAutoEncoder for Anima VAE, got {type(vae_info.model).__name__}."
)
- estimated_working_memory = estimate_vae_working_memory_flux(
- operation="decode",
- image_tensor=latents,
- vae=vae_info.model,
- )
+ use_tiling = False
+ if isinstance(vae_info.model, AutoencoderKLWan):
+ full_decode_working_memory = estimate_vae_working_memory_anima(
+ operation="decode",
+ image_tensor=latents,
+ vae=vae_info.model,
+ tile_size=None,
+ )
+ use_tiling = self._use_tiled_decode(TorchDevice.choose_torch_device(), full_decode_working_memory)
+ estimated_working_memory = estimate_vae_working_memory_anima(
+ operation="decode",
+ image_tensor=latents,
+ vae=vae_info.model,
+ tile_size=ANIMA_VAE_TILE_SIZE if use_tiling else None,
+ )
+ else:
+ estimated_working_memory = estimate_vae_working_memory_flux(
+ operation="decode",
+ image_tensor=latents,
+ vae=vae_info.model,
+ )
with vae_info.model_on_device(working_mem_bytes=estimated_working_memory) as (_, vae):
context.util.signal_progress("Running Anima VAE decode")
@@ -81,6 +135,18 @@ class AnimaLatentsToImageInvocation(BaseInvocation, WithMetadata, WithBoard):
# FLUX VAE handles scaling internally, expects 4D [B, C, H, W]
img = vae.decode(latents)
else:
+ # The cached VAE instance is shared across invocations, so always set
+ # the tiling state explicitly rather than leaving it as-is.
+ if use_tiling:
+ vae.enable_tiling(
+ tile_sample_min_height=ANIMA_VAE_TILE_SIZE,
+ tile_sample_min_width=ANIMA_VAE_TILE_SIZE,
+ tile_sample_stride_height=ANIMA_VAE_TILE_STRIDE,
+ tile_sample_stride_width=ANIMA_VAE_TILE_STRIDE,
+ )
+ else:
+ vae.disable_tiling()
+
# Expects 5D latents [B, C, T, H, W]
if latents.ndim == 4:
latents = latents.unsqueeze(2) # [B, C, H, W] -> [B, C, 1, H, W]
@@ -91,7 +157,21 @@ class AnimaLatentsToImageInvocation(BaseInvocation, WithMetadata, WithBoard):
latents_std = torch.tensor(vae.config.latents_std).view(1, -1, 1, 1, 1).to(latents)
latents = latents * latents_std + latents_mean
- decoded = vae.decode(latents, return_dict=False)[0]
+ try:
+ decoded = vae.decode(latents, return_dict=False)[0]
+ except RuntimeError as e:
+ if use_tiling or not _is_oom_error(e):
+ raise
+ # The working-memory estimate was insufficient on this system;
+ # retry once with tiling, which caps the peak allocation.
+ TorchDevice.empty_cache()
+ vae.enable_tiling(
+ tile_sample_min_height=ANIMA_VAE_TILE_SIZE,
+ tile_sample_min_width=ANIMA_VAE_TILE_SIZE,
+ tile_sample_stride_height=ANIMA_VAE_TILE_STRIDE,
+ tile_sample_stride_width=ANIMA_VAE_TILE_STRIDE,
+ )
+ decoded = vae.decode(latents, return_dict=False)[0]
# Output is 5D [B, C, T, H, W] — squeeze temporal dim
if decoded.ndim == 5:
diff --git a/invokeai/backend/util/vae_working_memory.py b/invokeai/backend/util/vae_working_memory.py
index 57d558c03b..7a2fa1f381 100644
--- a/invokeai/backend/util/vae_working_memory.py
+++ b/invokeai/backend/util/vae_working_memory.py
@@ -3,6 +3,7 @@ from typing import Literal
import torch
from diffusers.models.autoencoders.autoencoder_kl import AutoencoderKL
from diffusers.models.autoencoders.autoencoder_kl_qwenimage import AutoencoderKLQwenImage
+from diffusers.models.autoencoders.autoencoder_kl_wan import AutoencoderKLWan
from diffusers.models.autoencoders.autoencoder_tiny import AutoencoderTiny
from invokeai.app.invocations.constants import LATENT_SCALE_FACTOR
@@ -93,6 +94,37 @@ def estimate_vae_working_memory_flux(
return int(working_memory)
+def estimate_vae_working_memory_anima(
+ operation: Literal["encode", "decode"],
+ image_tensor: torch.Tensor,
+ vae: AutoencoderKLWan,
+ tile_size: int | None,
+) -> int:
+ """Estimate the working memory required to encode or decode with the Wan 2.1 VAE (Anima).
+
+ The Wan VAE uses 3D convolutions and needs noticeably more working memory per output
+ pixel than the 2D VAEs estimated above. Calibrated empirically on a 1024x1024 fp16
+ decode: peak reserved memory was ~5.95GB for a full decode and ~1.73GB with 512px
+ tiles (384px stride), i.e. ~2900 bytes per output pixel per element byte. Encoding
+ follows the house ratio of ~50% of decode.
+ """
+ element_size = next(vae.parameters()).element_size()
+ scaling_constant = 2900 if operation == "decode" else 1450
+
+ if tile_size is not None:
+ h = tile_size
+ w = tile_size
+ # Add 25% to account for tile overlap.
+ working_memory = h * w * element_size * scaling_constant * 1.25
+ else:
+ latent_scale_factor_for_operation = LATENT_SCALE_FACTOR if operation == "decode" else 1
+ h = latent_scale_factor_for_operation * image_tensor.shape[-2]
+ w = latent_scale_factor_for_operation * image_tensor.shape[-1]
+ working_memory = h * w * element_size * scaling_constant
+
+ return int(working_memory)
+
+
def estimate_vae_working_memory_qwen_image(
operation: Literal["encode", "decode"], image_tensor: torch.Tensor, vae: AutoencoderKLQwenImage
) -> int:
diff --git a/invokeai/frontend/web/openapi.json b/invokeai/frontend/web/openapi.json
index be3ff4059e..13a3185b23 100644
--- a/invokeai/frontend/web/openapi.json
+++ b/invokeai/frontend/web/openapi.json
@@ -10852,7 +10852,7 @@
"tags": ["image", "latents", "vae", "i2l", "anima"],
"title": "Image to Latents - Anima",
"type": "object",
- "version": "1.0.0",
+ "version": "1.0.1",
"output": {
"$ref": "#/components/schemas/LatentsOutput"
}
@@ -10962,7 +10962,7 @@
"tags": ["latents", "image", "vae", "l2i", "anima"],
"title": "Latents to Image - Anima",
"type": "object",
- "version": "1.0.2",
+ "version": "1.0.3",
"output": {
"$ref": "#/components/schemas/ImageOutput"
}
diff --git a/tests/app/invocations/test_anima_vae.py b/tests/app/invocations/test_anima_vae.py
new file mode 100644
index 0000000000..7f139dd91c
--- /dev/null
+++ b/tests/app/invocations/test_anima_vae.py
@@ -0,0 +1,214 @@
+"""Tests for the Anima VAE invocations: working-memory estimation, the tiled-decode
+decision, and the tiled retry on out-of-memory."""
+
+import math
+from unittest.mock import MagicMock, patch
+
+import pytest
+import torch
+from diffusers.models.autoencoders import AutoencoderKLWan
+
+from invokeai.app.invocations.anima_image_to_latents import AnimaImageToLatentsInvocation
+from invokeai.app.invocations.anima_latents_to_image import (
+ ANIMA_VAE_TILE_SIZE,
+ ANIMA_VAE_TILE_STRIDE,
+ AnimaLatentsToImageInvocation,
+)
+from invokeai.app.invocations.constants import LATENT_SCALE_FACTOR
+from invokeai.backend.util.devices import TorchDevice
+from invokeai.backend.util.vae_working_memory import estimate_vae_working_memory_anima
+
+
+def _mock_wan_vae(dtype: torch.dtype = torch.float16) -> MagicMock:
+ vae = MagicMock(spec=AutoencoderKLWan)
+ param = torch.zeros(1, dtype=dtype)
+ # Return a fresh iterator on every call so the estimator can be called repeatedly.
+ vae.parameters.side_effect = lambda: iter([param])
+ return vae
+
+
+class TestEstimateVaeWorkingMemoryAnima:
+ def test_untiled_decode_uses_decode_constant_and_scales_latent_dims(self):
+ latents = torch.zeros(1, 16, 1, 128, 128)
+ result = estimate_vae_working_memory_anima(
+ operation="decode", image_tensor=latents, vae=_mock_wan_vae(torch.float16), tile_size=None
+ )
+ out_h = out_w = 128 * LATENT_SCALE_FACTOR
+ assert result == int(out_h * out_w * 2 * 2900)
+
+ def test_untiled_encode_uses_encode_constant_and_pixel_dims(self):
+ image = torch.zeros(1, 3, 1, 1024, 1024)
+ result = estimate_vae_working_memory_anima(
+ operation="encode", image_tensor=image, vae=_mock_wan_vae(torch.float16), tile_size=None
+ )
+ assert result == int(1024 * 1024 * 2 * 1450)
+
+ @pytest.mark.parametrize("latent_hw", [(64, 64), (160, 160)])
+ def test_tiled_decode_estimate_is_independent_of_image_size(self, latent_hw):
+ latents = torch.zeros(1, 16, 1, *latent_hw)
+ result = estimate_vae_working_memory_anima(
+ operation="decode", image_tensor=latents, vae=_mock_wan_vae(torch.float16), tile_size=512
+ )
+ assert result == int(512 * 512 * 2 * 2900 * 1.25)
+
+ def test_estimate_scales_with_element_size(self):
+ latents = torch.zeros(1, 16, 1, 128, 128)
+ fp16 = estimate_vae_working_memory_anima(
+ operation="decode", image_tensor=latents, vae=_mock_wan_vae(torch.float16), tile_size=None
+ )
+ fp32 = estimate_vae_working_memory_anima(
+ operation="decode", image_tensor=latents, vae=_mock_wan_vae(torch.float32), tile_size=None
+ )
+ assert fp32 == 2 * fp16
+
+
+class TestUseTiledDecode:
+ @pytest.mark.parametrize("device_type", ["cpu", "mps"])
+ def test_non_cuda_never_tiles(self, device_type):
+ assert AnimaLatentsToImageInvocation._use_tiled_decode(torch.device(device_type), 10**12) is False
+
+ def test_cuda_flips_at_70_percent_of_total_vram(self):
+ total_vram = 8 * 2**30
+ boundary = 0.7 * total_vram
+ device = torch.device("cuda")
+ with patch("torch.cuda.get_device_properties", return_value=MagicMock(total_memory=total_vram)) as mock_props:
+ assert AnimaLatentsToImageInvocation._use_tiled_decode(device, math.floor(boundary)) is False
+ assert AnimaLatentsToImageInvocation._use_tiled_decode(device, math.ceil(boundary) + 1) is True
+ mock_props.assert_called_with(device)
+
+
+def _build_decode_mocks(latents: torch.Tensor, decoded: torch.Tensor):
+ """Mock the Wan VAE decode path: a spec'd AutoencoderKLWan, its LoadedModel wrapper, and the
+ invocation context, wired so `AnimaLatentsToImageInvocation.invoke` runs end-to-end on CPU."""
+ vae = _mock_wan_vae(torch.float32)
+ vae.config.latents_mean = [0.0] * 16
+ vae.config.latents_std = [1.0] * 16
+ vae.decode.return_value = (decoded,)
+
+ vae_info = MagicMock()
+ vae_info.model = vae
+ cm = MagicMock()
+ cm.__enter__ = MagicMock(return_value=(None, vae))
+ cm.__exit__ = MagicMock(return_value=None)
+ vae_info.model_on_device.return_value = cm
+
+ context = MagicMock()
+ context.models.load.return_value = vae_info
+ context.tensors.load.return_value = latents
+ image_dto = MagicMock()
+ image_dto.image_name = "test.png"
+ image_dto.width = decoded.shape[-1]
+ image_dto.height = decoded.shape[-2]
+ context.images.save.return_value = image_dto
+
+ return vae, vae_info, context
+
+
+def _build_l2i_invocation() -> AnimaLatentsToImageInvocation:
+ return AnimaLatentsToImageInvocation.model_construct(
+ latents=MagicMock(latents_name="test_latents"),
+ vae=MagicMock(vae=MagicMock()),
+ )
+
+
+class TestAnimaLatentsToImageOomFallback:
+ @pytest.mark.parametrize(
+ "oom_error",
+ [
+ torch.cuda.OutOfMemoryError("CUDA out of memory. Tried to allocate 5.9 GiB"),
+ RuntimeError("CUDA error: out of memory"),
+ RuntimeError("cuDNN error: CUDNN_STATUS_ALLOC_FAILED"),
+ ],
+ )
+ def test_untiled_decode_oom_retries_with_tiling(self, oom_error):
+ decoded = torch.zeros(1, 3, 1, 64, 64)
+ vae, _, context = _build_decode_mocks(latents=torch.zeros(1, 16, 32, 32), decoded=decoded)
+ vae.decode.side_effect = [oom_error, (decoded,)]
+
+ with patch.object(TorchDevice, "choose_torch_device", return_value=torch.device("cpu")):
+ result = _build_l2i_invocation().invoke(context)
+
+ assert vae.decode.call_count == 2
+ vae.enable_tiling.assert_called_once_with(
+ tile_sample_min_height=ANIMA_VAE_TILE_SIZE,
+ tile_sample_min_width=ANIMA_VAE_TILE_SIZE,
+ tile_sample_stride_height=ANIMA_VAE_TILE_STRIDE,
+ tile_sample_stride_width=ANIMA_VAE_TILE_STRIDE,
+ )
+ assert result.width == 64
+
+ def test_non_oom_runtime_error_propagates_without_retry(self):
+ vae, _, context = _build_decode_mocks(latents=torch.zeros(1, 16, 32, 32), decoded=torch.zeros(1, 3, 1, 64, 64))
+ vae.decode.side_effect = RuntimeError("Input type (float) and weight type (half) should be the same")
+
+ with patch.object(TorchDevice, "choose_torch_device", return_value=torch.device("cpu")):
+ with pytest.raises(RuntimeError, match="weight type"):
+ _build_l2i_invocation().invoke(context)
+
+ assert vae.decode.call_count == 1
+ vae.enable_tiling.assert_not_called()
+
+ def test_oom_while_already_tiled_reraises(self):
+ vae, _, context = _build_decode_mocks(latents=torch.zeros(1, 16, 32, 32), decoded=torch.zeros(1, 3, 1, 64, 64))
+ vae.decode.side_effect = torch.cuda.OutOfMemoryError("CUDA out of memory")
+
+ with (
+ patch.object(TorchDevice, "choose_torch_device", return_value=torch.device("cpu")),
+ patch.object(AnimaLatentsToImageInvocation, "_use_tiled_decode", return_value=True),
+ ):
+ with pytest.raises(torch.cuda.OutOfMemoryError):
+ _build_l2i_invocation().invoke(context)
+
+ # No second attempt: the initial enable_tiling is the only one, and decode is not retried.
+ assert vae.decode.call_count == 1
+ vae.enable_tiling.assert_called_once()
+
+ def test_decode_requests_estimated_working_memory(self):
+ decoded = torch.zeros(1, 3, 1, 64, 64)
+ vae, vae_info, context = _build_decode_mocks(latents=torch.zeros(1, 16, 32, 32), decoded=decoded)
+
+ estimation_path = "invokeai.app.invocations.anima_latents_to_image.estimate_vae_working_memory_anima"
+ expected_memory = 1024 * 1024 * 500
+ with (
+ patch.object(TorchDevice, "choose_torch_device", return_value=torch.device("cpu")),
+ patch(estimation_path, return_value=expected_memory) as mock_estimate,
+ ):
+ _build_l2i_invocation().invoke(context)
+
+ # Called once for the full-decode estimate (tiling decision) and once for the actual request.
+ assert mock_estimate.call_count == 2
+ vae_info.model_on_device.assert_called_once_with(working_mem_bytes=expected_memory)
+
+
+class TestAnimaImageToLatentsEncode:
+ def test_encode_disables_tiling_and_requests_working_memory(self):
+ vae = _mock_wan_vae(torch.float32)
+ vae.config.latents_mean = [0.0] * 16
+ vae.config.latents_std = [1.0] * 16
+ mock_dist = MagicMock()
+ mock_dist.sample.return_value = torch.zeros(1, 16, 1, 4, 4)
+ vae.encode.return_value = (mock_dist,)
+
+ vae_info = MagicMock()
+ vae_info.model = vae
+ cm = MagicMock()
+ cm.__enter__ = MagicMock(return_value=(None, vae))
+ cm.__exit__ = MagicMock(return_value=None)
+ vae_info.model_on_device.return_value = cm
+
+ estimation_path = "invokeai.app.invocations.anima_image_to_latents.estimate_vae_working_memory_anima"
+ expected_memory = 1024 * 1024 * 250
+ with (
+ patch.object(TorchDevice, "choose_torch_device", return_value=torch.device("cpu")),
+ patch(estimation_path, return_value=expected_memory) as mock_estimate,
+ ):
+ latents = AnimaImageToLatentsInvocation.vae_encode(
+ vae_info=vae_info, image_tensor=torch.zeros(1, 3, 32, 32)
+ )
+
+ # The shared cached VAE may have tiling enabled from a previous decode; encode must reset it.
+ vae.disable_tiling.assert_called_once()
+ vae.enable_tiling.assert_not_called()
+ mock_estimate.assert_called_once()
+ vae_info.model_on_device.assert_called_once_with(working_mem_bytes=expected_memory)
+ assert latents.shape == (1, 16, 4, 4)