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.

24.2 KB
Raw Blame
"""Wan VAE invocations: working-memory estimation and cpu_only device handling."""

from unittest.mock import MagicMock, patch

import PIL.Image
import pytest
import torch
from diffusers.models.autoencoders import AutoencoderKLWan

from invokeai.app.invocations.vae.wan_image_to_latents import WanImageToLatentsInvocation
from invokeai.app.invocations.vae.wan_latents_to_image import WanLatentsToImageInvocation
from invokeai.app.invocations.vae.wan_latents_to_video import WanLatentsToVideoInvocation
from invokeai.app.invocations.wan.wan_ref_image_encoder import WanRefImageEncoderInvocation
from invokeai.backend.util.devices import TorchDevice
from invokeai.backend.util.vae_working_memory import VAE_PRETILE_VRAM_FRACTION, estimate_vae_working_memory_wan


def _mock_wan_vae(
    z_dim: int = 16, spatial_scale: int = 8, temporal_scale: int = 4, dtype: torch.dtype = torch.float16
) -> MagicMock:
    vae = MagicMock(spec=AutoencoderKLWan)
    param = torch.zeros(1, dtype=dtype)
    # parameters() is consumed several times (estimator, dtype probe, effective device).
    vae.parameters.side_effect = lambda: iter([param])
    vae.config = MagicMock()
    vae.config.z_dim = z_dim
    vae.config.scale_factor_spatial = spatial_scale
    vae.config.scale_factor_temporal = temporal_scale
    vae.config.latents_mean = [0.0] * z_dim
    vae.config.latents_std = [1.0] * z_dim
    # `patch_qwen_image_vae_tiling` snapshots and restores all five, and `enable_tiling` writes
    # all four geometry values rather than inheriting any.
    vae.use_tiling = False
    vae.tile_sample_min_height = 256
    vae.tile_sample_min_width = 256
    vae.tile_sample_stride_height = 192
    vae.tile_sample_stride_width = 192
    return vae


def _mock_vae_info(vae: MagicMock, cpu_only: bool | None = None) -> MagicMock:
    vae_info = MagicMock()
    vae_info.model = vae
    vae_info.config = MagicMock()
    vae_info.config.cpu_only = cpu_only
    cm = MagicMock()
    cm.__enter__ = MagicMock(return_value=(None, vae))
    cm.__exit__ = MagicMock(return_value=None)
    vae_info.model_on_device = MagicMock(return_value=cm)
    return vae_info


class TestEstimateVaeWorkingMemoryWan:
    """Lock in the generalized Wan estimator: per-frame conv working set plus the full
    RGB clip that stays resident on the execution device."""

    def test_decode_single_frame(self):
        vae = _mock_wan_vae()
        est = estimate_vae_working_memory_wan(
            operation="decode", vae=vae, pixel_height=256, pixel_width=256, pixel_frames=1
        )
        area_bytes = 256 * 256 * 2
        # Decode counts the clip twice: torch.cat frame accumulation transiently holds
        # the clip and its copy at peak.
        assert est == area_bytes * 2900 + 2 * 3 * 1 * area_bytes

    def test_encode_uses_half_the_decode_constant(self):
        vae = _mock_wan_vae()
        est = estimate_vae_working_memory_wan(
            operation="encode", vae=vae, pixel_height=256, pixel_width=256, pixel_frames=1
        )
        area_bytes = 256 * 256 * 2
        # Encode consumes the input clip without duplicating it — one copy only.
        assert est == area_bytes * 1450 + 3 * 1 * area_bytes

    def test_additional_frames_add_only_clip_bytes(self):
        """The Wan VAE is causal (frame-at-a-time with cached features), so extra frames
        grow the resident clip (2 copies at decode peak), not the conv working set."""
        vae = _mock_wan_vae()
        one = estimate_vae_working_memory_wan(
            operation="decode", vae=vae, pixel_height=128, pixel_width=128, pixel_frames=2
        )
        many = estimate_vae_working_memory_wan(
            operation="decode", vae=vae, pixel_height=128, pixel_width=128, pixel_frames=81
        )
        assert many - one == 2 * 3 * 79 * 128 * 128 * 2

    def test_streaming_decode_bounds_resident_clip_to_one_temporal_chunk(self):
        vae = _mock_wan_vae(temporal_scale=4)
        one = estimate_vae_working_memory_wan(
            operation="decode",
            vae=vae,
            pixel_height=128,
            pixel_width=128,
            pixel_frames=2,
            streaming=True,
        )
        many = estimate_vae_working_memory_wan(
            operation="decode",
            vae=vae,
            pixel_height=128,
            pixel_width=128,
            pixel_frames=81,
            streaming=True,
        )

        assert many - one == 2 * 3 * 128 * 128 * 2

    def test_tile_size_bounds_the_per_frame_term(self):
        vae = _mock_wan_vae()
        tiled = estimate_vae_working_memory_wan(
            operation="decode", vae=vae, pixel_height=1920, pixel_width=1080, pixel_frames=17, tile_size=256
        )
        # The tile's working set, plus the six clip copies the tiled assembly holds at once.
        expected = int(256 * 256 * 2 * 10000 * 1.25 + 6 * 3 * 17 * 1920 * 1080 * 2)
        assert tiled == expected
        full = estimate_vae_working_memory_wan(
            operation="decode", vae=vae, pixel_height=1920, pixel_width=1080, pixel_frames=17
        )
        assert tiled < full

    @pytest.mark.parametrize(
        ("z_dim", "spatial_scale", "width", "height", "frames", "mode", "reserved_mib"),
        [
            (16, 8, 832, 480, 49, "full", 6666),
            (16, 8, 1280, 704, 121, "full", 15124),
            (16, 8, 1280, 704, 81, "streaming", 14804),
            (16, 8, 1280, 704, 121, "tiled", 3530),
            (48, 16, 640, 352, 49, "full", 3952),
            (48, 16, 832, 480, 49, "full", 7464),  # in a server: the highest relative to its size
            (48, 16, 1280, 704, 49, "full", 15878),  # in a server
            (48, 16, 832, 480, 49, "streaming", 6926),  # in a server
            (48, 16, 1280, 704, 49, "streaming", 15894),  # in a server
            (48, 16, 1280, 704, 121, "tiled", 3620),
        ],
        ids=[
            "a14b-480p",
            "a14b-720p-121f",
            "a14b-720p-streaming",
            "a14b-720p-121f-tiled",
            "ti2v-352p",
            "ti2v-480p-server",
            "ti2v-720p-server",
            "ti2v-480p-streaming-server",
            "ti2v-720p-streaming-server",
            "ti2v-720p-121f-tiled",
        ],
    )
    def test_video_decode_estimate_covers_the_measured_reserved_peak(
        self, z_dim, spatial_scale, width, height, frames, mode, reserved_mib
    ):
        """Peak reserved growth of bf16 decodes on an RTX 4090. The cache keeps only the estimate free, so an
        estimate below what the allocator reserves leaves a full card short (sysmem fallback: a stalled decode)."""
        vae = _mock_wan_vae(z_dim=z_dim, spatial_scale=spatial_scale, dtype=torch.bfloat16)
        estimate = estimate_vae_working_memory_wan(
            operation="decode",
            vae=vae,
            pixel_height=height,
            pixel_width=width,
            pixel_frames=frames,
            tile_size=256 if mode == "tiled" else None,
            streaming=mode == "streaming",
        )
        assert estimate >= reserved_mib * 2**20

    @pytest.mark.parametrize(("z_dim", "spatial_scale", "width", "height"), [(16, 8, 1280, 720), (48, 16, 1280, 704)])
    def test_720p_video_decodes_stay_untiled_on_24gb_cards(self, z_dim, spatial_scale, width, height):
        """Tiled output is not pixel-identical. A 24 GB card's untiled 720p decode fits (15.9 GiB reserved), so its
        estimate must stay below the auto-tiling line, which on Windows is 0.9 of a ~22.4 GiB budget."""
        vae = _mock_wan_vae(z_dim=z_dim, spatial_scale=spatial_scale, dtype=torch.bfloat16)
        estimate = estimate_vae_working_memory_wan(
            operation="decode", vae=vae, pixel_height=height, pixel_width=width, pixel_frames=121
        )
        assert estimate < VAE_PRETILE_VRAM_FRACTION * 22.4 * 2**30

    @pytest.mark.parametrize(("z_dim", "spatial_scale", "width", "height"), [(16, 8, 1280, 720), (48, 16, 1280, 704)])
    def test_tiling_fits_a_121_frame_720p_decode_on_8gb_cards(self, z_dim, spatial_scale, width, height):
        """Tiling is what lets a small card run a clip whose untiled decode it cannot hold: tiled, 720p at 121 frames
        reserved about 3.5 GiB. An estimate past an 8 GB card's tiling line would push the VAE itself off the card
        for a decode that fits there."""
        vae = _mock_wan_vae(z_dim=z_dim, spatial_scale=spatial_scale, dtype=torch.bfloat16)
        estimate = estimate_vae_working_memory_wan(
            operation="decode", vae=vae, pixel_height=height, pixel_width=width, pixel_frames=121, tile_size=256
        )
        assert estimate < VAE_PRETILE_VRAM_FRACTION * 8 * 2**30

    def test_multi_frame_decode_estimate_triggers_tiling_on_12gb_cards(self):
        """Conservative video estimates must engage the tiling fallback for both Wan VAEs."""
        for z_dim, spatial_scale in ((16, 8), (48, 16)):
            vae = _mock_wan_vae(z_dim=z_dim, spatial_scale=spatial_scale)
            estimate = estimate_vae_working_memory_wan(
                operation="decode",
                vae=vae,
                pixel_height=704,
                pixel_width=1280,
                pixel_frames=81,
                streaming=True,
            )
            assert estimate > 0.9 * 12 * 2**30


class TestWanInvocationsRequestWorkingMemory:
    """Every Wan VAE path must reserve its estimated working memory with the model cache."""

    def test_latents_to_image_requests_decode_memory(self):
        vae = _mock_wan_vae()
        vae_info = _mock_vae_info(vae)
        mock_context = MagicMock()
        mock_context.models.load.return_value = vae_info
        mock_context.tensors.load.return_value = torch.zeros(1, 16, 64, 64)

        with patch(
            "invokeai.app.invocations.vae.wan_latents_to_image.estimate_vae_working_memory_wan"
        ) as mock_estimate:
            mock_estimate.return_value = 1234
            invocation = WanLatentsToImageInvocation.model_construct(
                latents=MagicMock(latents_name="l"), vae=MagicMock(vae=MagicMock())
            )
            try:
                invocation.invoke(mock_context)
            except Exception:
                pass  # Downstream image math fails under mocking; the reservation is what matters.

        assert mock_estimate.call_args.kwargs["operation"] == "decode"
        # Latent 64x64 at the standard 8x spatial scale -> 512x512 pixels.
        assert mock_estimate.call_args.kwargs["pixel_height"] == 512
        assert mock_estimate.call_args.kwargs["pixel_width"] == 512
        vae_info.model_on_device.assert_called_once_with(working_mem_bytes=1234)

    def test_latents_to_image_uses_config_spatial_scale_for_ti2v(self):
        vae = _mock_wan_vae(z_dim=48, spatial_scale=16)
        vae_info = _mock_vae_info(vae)
        mock_context = MagicMock()
        mock_context.models.load.return_value = vae_info
        mock_context.tensors.load.return_value = torch.zeros(1, 48, 32, 32)

        with patch(
            "invokeai.app.invocations.vae.wan_latents_to_image.estimate_vae_working_memory_wan"
        ) as mock_estimate:
            mock_estimate.return_value = 1
            invocation = WanLatentsToImageInvocation.model_construct(
                latents=MagicMock(latents_name="l"), vae=MagicMock(vae=MagicMock())
            )
            try:
                invocation.invoke(mock_context)
            except Exception:
                pass

        # TI2V-5B VAE compresses 16x spatially -> 32 latent px = 512 pixel px.
        assert mock_estimate.call_args.kwargs["pixel_height"] == 512

    def test_image_to_latents_requests_encode_memory(self):
        vae = _mock_wan_vae()
        vae_info = _mock_vae_info(vae)

        with patch(
            "invokeai.app.invocations.vae.wan_image_to_latents.estimate_vae_working_memory_wan"
        ) as mock_estimate:
            mock_estimate.return_value = 4321
            try:
                WanImageToLatentsInvocation.vae_encode(vae_info, torch.zeros(1, 3, 512, 512))
            except Exception:
                pass

        assert mock_estimate.call_args.kwargs["operation"] == "encode"
        assert mock_estimate.call_args.kwargs["pixel_frames"] == 1
        vae_info.model_on_device.assert_called_once_with(working_mem_bytes=4321)

    def test_ref_image_encoder_requests_encode_memory(self):
        vae = _mock_wan_vae()
        vae_info = _mock_vae_info(vae)
        mock_context = MagicMock()
        mock_context.models.load.return_value = vae_info
        mock_context.images.get_pil.return_value = PIL.Image.new("RGB", (32, 32))
        mock_context.tensors.save.return_value = "t"

        with (
            patch(
                "invokeai.app.invocations.wan.wan_ref_image_encoder.estimate_vae_working_memory_wan"
            ) as mock_estimate,
            patch(
                "invokeai.app.invocations.wan.wan_ref_image_encoder.encode_reference_image_to_condition",
                return_value=torch.zeros(1, 20, 1, 4, 4),
            ),
        ):
            mock_estimate.return_value = 999
            invocation = WanRefImageEncoderInvocation.model_construct(
                image=MagicMock(image_name="i"),
                vae=MagicMock(vae=MagicMock()),
                width=32,
                height=32,
                num_frames=1,
                end_image=None,
            )
            invocation.invoke(mock_context)

        assert mock_estimate.call_args.kwargs["operation"] == "encode"
        assert mock_estimate.call_args.kwargs["pixel_frames"] == 1
        vae_info.model_on_device.assert_called_once_with(working_mem_bytes=999)

    def _video_context(self, vae_info: MagicMock, t_lat: int = 5) -> MagicMock:
        mock_context = MagicMock()
        mock_context.models.load.return_value = vae_info
        mock_context.tensors.load.return_value = torch.zeros(1, 16, t_lat, 32, 32)
        mock_context.util.is_canceled.return_value = False
        mock_context.config.get.return_value.wan_memory_optimization = False
        return mock_context

    def test_latents_to_video_requests_decode_memory_for_all_frames(self):
        vae = _mock_wan_vae()
        vae_info = _mock_vae_info(vae)
        mock_context = self._video_context(vae_info)

        with patch(
            "invokeai.app.invocations.vae.wan_latents_to_video.estimate_vae_working_memory_wan"
        ) as mock_estimate:
            mock_estimate.return_value = 5678
            invocation = WanLatentsToVideoInvocation.model_construct(
                latents=MagicMock(latents_name="l"), vae=MagicMock(vae=MagicMock()), fps=16
            )
            try:
                invocation.invoke(mock_context)
            except Exception:
                pass

        assert mock_estimate.call_args.kwargs["operation"] == "decode"
        # 5 latent frames -> (5-1)*4+1 = 17 pixel frames at 32*8 = 256px.
        assert mock_estimate.call_args.kwargs["pixel_frames"] == 17
        assert mock_estimate.call_args.kwargs["pixel_height"] == 256
        vae_info.model_on_device.assert_called_once_with(working_mem_bytes=5678)

    def test_latents_to_video_streams_decode_chunks_directly_to_mp4(self):
        vae = _mock_wan_vae()
        vae.use_tiling = True  # Simulate a prior Anima tiled decode on the shared VAE.
        vae_info = _mock_vae_info(vae)
        mock_context = self._video_context(vae_info, t_lat=2)
        mock_context.config.get.return_value.wan_memory_optimization = True
        writer = MagicMock()
        chunks = [
            torch.zeros(1, 3, 1, 256, 256),
            torch.zeros(1, 3, 4, 256, 256),
        ]
        expected_output = MagicMock()

        with (
            patch(
                "invokeai.app.invocations.vae.wan_latents_to_video.estimate_vae_working_memory_wan",
                return_value=5678,
            ) as mock_estimate,
            patch(
                "invokeai.app.invocations.vae.wan_latents_to_video.iter_wan_vae_decode_chunks",
                return_value=iter(chunks),
            ) as mock_decode_chunks,
            patch("invokeai.app.invocations.vae.wan_latents_to_video.make_mp4_writer", return_value=writer),
            patch("invokeai.app.invocations.vae.wan_latents_to_video.VideoOutput.build", return_value=expected_output),
            patch.object(TorchDevice, "choose_torch_device", return_value=torch.device("cpu")),
            patch.object(TorchDevice, "empty_cache"),
        ):
            invocation = WanLatentsToVideoInvocation.model_construct(
                latents=MagicMock(latents_name="l"), vae=MagicMock(vae=MagicMock()), fps=16
            )
            actual_output = invocation.invoke(mock_context)

        assert actual_output is expected_output
        assert mock_estimate.call_args.kwargs["streaming"] is True
        mock_decode_chunks.assert_called_once()
        assert writer.append_data.call_count == 5
        writer.close.assert_called_once()
        vae.disable_tiling.assert_called_once()
        vae.decode.assert_not_called()

    @pytest.mark.parametrize("auto", [True, False], ids=["auto-tiled-decode-on", "auto-tiled-decode-off"])
    def test_latents_to_video_falls_back_to_tiling_when_estimate_exceeds_vram(self, auto):
        vae = _mock_wan_vae()
        # Not 256: the point of the change is that the tile comes from a module constant rather than
        # from the shared cache instance, and with 256 on the instance both implementations agree.
        vae.tile_sample_min_height = 999
        vae_info = _mock_vae_info(vae)
        vae_info.compute_device = torch.device("cuda")
        mock_context = self._video_context(vae_info)
        mock_context.config.get.return_value.auto_tiled_decode = auto

        with (
            patch(
                "invokeai.app.invocations.vae.wan_latents_to_video.estimate_vae_working_memory_wan",
                side_effect=[100 * 2**30, 4 * 2**30],
            ) as mock_estimate,
            patch.object(TorchDevice, "choose_torch_device", return_value=torch.device("cuda")),
            patch.object(TorchDevice, "empty_cache"),
            patch("torch.cuda.get_device_properties", return_value=MagicMock(total_memory=8 * 2**30)),
        ):
            invocation = WanLatentsToVideoInvocation.model_construct(
                latents=MagicMock(latents_name="l"), vae=MagicMock(vae=MagicMock()), fps=16
            )
            try:
                invocation.invoke(mock_context)
            except Exception:
                pass

        if auto:
            assert mock_estimate.call_count == 2
            assert mock_estimate.call_args_list[1].kwargs["tile_size"] == 256
            # All four geometry values are set explicitly rather than inherited from the shared module:
            # `enable_tiling` falls back to whatever the instance carries for any argument left out, and
            # a min below the inherited stride drops whole bands of the frame.
            vae.enable_tiling.assert_called_once_with(
                tile_sample_min_height=256,
                tile_sample_min_width=256,
                tile_sample_stride_height=192,
                tile_sample_stride_width=192,
            )
            vae_info.model_on_device.assert_called_once_with(working_mem_bytes=4 * 2**30)
        else:
            assert mock_estimate.call_count == 1
            vae.enable_tiling.assert_not_called()
            vae_info.model_on_device.assert_called_once_with(working_mem_bytes=100 * 2**30)

    def test_latents_to_video_keeps_streaming_when_tiling_would_need_more(self):
        """Tiling holds six copies of the clip; streaming holds one 4-frame chunk. At 832x480x481 on an 8 GB card the
        streaming decode is past the tiling line, but the tiled one would need even more (7.97 vs 7.45 GiB)."""
        vae = _mock_wan_vae()
        vae_info = _mock_vae_info(vae)
        vae_info.compute_device = torch.device("cuda")
        mock_context = self._video_context(vae_info)
        mock_context.tensors.load.return_value = torch.zeros(1, 16, 121, 60, 104)
        mock_context.config.get.return_value.wan_memory_optimization = True
        mock_context.config.get.return_value.auto_tiled_decode = True

        with (
            patch(
                "invokeai.app.invocations.vae.wan_latents_to_video.iter_wan_vae_decode_chunks",
                side_effect=RuntimeError("decoded past the reservation"),
            ),
            patch("invokeai.app.invocations.vae.wan_latents_to_video.make_mp4_writer"),
            patch.object(TorchDevice, "empty_cache"),
            patch("torch.cuda.get_device_properties", return_value=MagicMock(total_memory=8 * 2**30)),
            patch("invokeai.backend.util.wddm.local_video_memory", return_value=None),
        ):
            invocation = WanLatentsToVideoInvocation.model_construct(
                latents=MagicMock(latents_name="l"), vae=MagicMock(vae=MagicMock()), fps=16
            )
            with pytest.raises(RuntimeError, match="decoded past the reservation"):
                invocation.invoke(mock_context)

        streaming = estimate_vae_working_memory_wan(
            operation="decode", vae=vae, pixel_height=480, pixel_width=832, pixel_frames=481, streaming=True
        )
        assert streaming > VAE_PRETILE_VRAM_FRACTION * 8 * 2**30
        vae.enable_tiling.assert_not_called()
        vae_info.model_on_device.assert_called_once_with(working_mem_bytes=streaming)

    def test_latents_to_video_skips_tiling_for_cpu_only_vae(self):
        """A cpu_only VAE runs in system RAM; VRAM-based tiling must not kick in, even with a small GPU present."""
        vae = _mock_wan_vae()
        vae_info = _mock_vae_info(vae, cpu_only=True)
        vae_info.compute_device = torch.device("cpu")
        mock_context = self._video_context(vae_info)

        with (
            patch(
                "invokeai.app.invocations.vae.wan_latents_to_video.estimate_vae_working_memory_wan",
                return_value=100 * 2**30,
            ) as mock_estimate,
            patch.object(TorchDevice, "choose_torch_device", return_value=torch.device("cuda")),
            patch.object(TorchDevice, "empty_cache"),
            patch("torch.cuda.get_device_properties", return_value=MagicMock(total_memory=8 * 2**30)),
        ):
            invocation = WanLatentsToVideoInvocation.model_construct(
                latents=MagicMock(latents_name="l"), vae=MagicMock(vae=MagicMock()), fps=16
            )
            try:
                invocation.invoke(mock_context)
            except Exception:
                pass

        assert mock_estimate.call_count == 1
        vae.enable_tiling.assert_not_called()


class TestWanCpuOnlyDeviceHandling:
    """With a cpu_only VAE, inputs must go to the VAE's device — not the globally
    selected accelerator (which would crash every Wan VAE invocation on GPU hosts)."""

    def test_latents_to_image_moves_latents_to_vae_device(self):
        vae = _mock_wan_vae(dtype=torch.float32)
        seen_devices: list[torch.device] = []

        def _decode(latents, return_dict):
            seen_devices.append(latents.device)
            return (torch.zeros(1, 3, 1, 8, 8),)

        vae.decode.side_effect = _decode
        vae_info = _mock_vae_info(vae, cpu_only=True)
        mock_context = MagicMock()
        mock_context.models.load.return_value = vae_info
        mock_context.tensors.load.return_value = torch.zeros(1, 16, 1, 1)

        # Poison the global device: if the invocation still routed through
        # choose_torch_device, the .to() below would produce a meta tensor and fail
        # the device assertion.
        with (
            patch.object(TorchDevice, "choose_torch_device", return_value=torch.device("meta")),
            patch.object(TorchDevice, "empty_cache"),
        ):
            invocation = WanLatentsToImageInvocation.model_construct(
                latents=MagicMock(latents_name="l"), vae=MagicMock(vae=MagicMock())
            )
            try:
                invocation.invoke(mock_context)
            except Exception:
                pass

        assert seen_devices == [torch.device("cpu")]

    def test_image_to_latents_moves_image_to_vae_device(self):
        vae = _mock_wan_vae(dtype=torch.float32)
        seen_devices: list[torch.device] = []

        def _encode(pixel, return_dict):
            seen_devices.append(pixel.device)
            raise RuntimeError("stop here")

        vae.encode.side_effect = _encode
        vae_info = _mock_vae_info(vae, cpu_only=True)

        with patch.object(TorchDevice, "choose_torch_device", return_value=torch.device("meta")):
            try:
                WanImageToLatentsInvocation.vae_encode(vae_info, torch.zeros(1, 3, 64, 64))
            except Exception:
                pass

        assert seen_devices == [torch.device("cpu")]