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): tile a video decode only when tiling needs less memory (#9668)

Alexander Eichhorn18f97208bc0c
diff --git a/invokeai/app/invocations/vae/wan_latents_to_video.py b/invokeai/app/invocations/vae/wan_latents_to_video.py
index b63ad36694..b7753dadf3 100644
--- a/invokeai/app/invocations/vae/wan_latents_to_video.py
+++ b/invokeai/app/invocations/vae/wan_latents_to_video.py
@@ -149,7 +149,7 @@ class WanLatentsToVideoInvocation(BaseInvocation, WithMetadata, WithBoard):
# left rather than what this decode is about to ask for. The sentinel resolves to
# 256/192, which is also this VAE class's own default.
tile_size = resolve_qwen_image_vae_tile_size(0)
- estimated_working_memory = estimate_vae_working_memory_wan(
+ tiled_working_memory = estimate_vae_working_memory_wan(
operation="decode",
vae=vae_info.model,
pixel_height=h_pixel,
@@ -158,6 +158,18 @@ class WanLatentsToVideoInvocation(BaseInvocation, WithMetadata, WithBoard):
tile_size=tile_size,
streaming=False,
)
+ # Tiling holds six copies of the clip, so a long enough clip (480p from ~440 frames, against
+ # streaming) needs more tiled than untiled. Neither fits then, and the lighter decode is the better bet.
+ if tiled_working_memory < estimated_working_memory:
+ estimated_working_memory = tiled_working_memory
+ else:
+ context.logger.info(
+ f"Not tiling the Wan VAE decode: tiled it would need ~{tiled_working_memory / 2**30:.1f} GiB, "
+ f"more than the ~{estimated_working_memory / 2**30:.1f} GiB untiled, which is already more than "
+ "the GPU keeps resident."
+ )
+ use_tiling = False
+ tile_size = None
tmp = tempfile.NamedTemporaryFile(prefix="invokeai_wan_video_", suffix=".mp4", delete=False)
tmp.close()
diff --git a/scripts/calibrate_wan_vae_working_memory.py b/scripts/calibrate_wan_vae_working_memory.py
index 6e7993a18f..2b826cc07a 100644
--- a/scripts/calibrate_wan_vae_working_memory.py
+++ b/scripts/calibrate_wan_vae_working_memory.py
@@ -15,6 +15,10 @@ reserves, about 1.5x its peak of live tensors. The table behind the shipped cons
(in ``estimate_vae_working_memory_wan``) was measured with ``--dtype bfloat16``, both
with and without ``--no-streaming``; its highest point came from a running server, so
the constant sits above what this script reports.
+
+The allocator is configured from the environment only: the script does not read
+``pytorch_cuda_alloc_conf`` from ``invokeai.yaml``. To measure the allocator a server
+configures there, export the same value as ``PYTORCH_CUDA_ALLOC_CONF`` first.
"""
from __future__ import annotations
@@ -31,15 +35,21 @@ sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from invokeai.app.util.torch_cuda_allocator import apply_rocm_windows_allocator_default # noqa: E402
# The server's ROCm runtime, so a ROCm measurement is what Invoke would see: both must be set before torch is
-# imported (see `invokeai.app.run_app` and `apply_rocm_windows_allocator_default`). Inert on CUDA.
-os.environ.setdefault("MIOPEN_FIND_MODE", "FAST")
-apply_rocm_windows_allocator_default(logging.getLogger(__name__))
+# imported (see `invokeai.app.run_app` and `apply_rocm_windows_allocator_default`). Inert on CUDA. Only when run as a
+# script, so importing the module, as its tests do, leaves the process environment alone.
+if __name__ == "__main__":
+ os.environ.setdefault("MIOPEN_FIND_MODE", "FAST")
+ apply_rocm_windows_allocator_default(logging.getLogger(__name__))
import torch # noqa: E402
from diffusers.models.autoencoders import AutoencoderKLWan # noqa: E402
from invokeai.backend.model_manager.load.model_loaders.vae import _wan_vae_init_kwargs_for # noqa: E402
from invokeai.backend.util.attention import install_rocm_sdpa_guard # noqa: E402
+from invokeai.backend.util.qwen_image_vae import ( # noqa: E402
+ patch_qwen_image_vae_tiling,
+ resolve_qwen_image_vae_tile_size,
+)
from invokeai.backend.util.vae_working_memory import ( # noqa: E402
estimate_vae_working_memory_wan,
wan_vae_clip_bytes,
@@ -99,13 +109,14 @@ def _measure(
if tiling:
streaming = False
if tile_size is None:
- tile_size = int(getattr(vae, "tile_sample_min_height", 256))
- if tile_size < spatial_scale or tile_size % spatial_scale:
- raise ValueError(f"tile_size must be a positive multiple of {spatial_scale}")
- vae.enable_tiling(tile_sample_min_height=tile_size, tile_sample_min_width=tile_size)
+ tile_size = resolve_qwen_image_vae_tile_size(0) # the video node's tile
+ # The node pairs a tile with a stride of 3/4 of it, rounded down to 8 px. A tile on this grid keeps that stride
+ # on the latent grid (16 px for TI2V), so the decode steps through tiles the way it crops them.
+ tile_grid = 4 * spatial_scale
+ if tile_size < tile_grid or tile_size % tile_grid:
+ raise ValueError(f"tile_size must be a positive multiple of {tile_grid}")
else:
tile_size = None
- vae.disable_tiling()
element_size = next(vae.parameters()).element_size()
latent_frames = (pixel_frames - 1) // temporal_scale + 1
latent_height = pixel_height // spatial_scale
@@ -149,15 +160,14 @@ def _measure(
scaling_basis_bytes = tile_size**2 * element_size * 1.25
else:
scaling_basis_bytes = pixel_height * pixel_width * element_size
- try:
+ # The node's tiling geometry: a stride that follows the tile size, which `enable_tiling` would otherwise leave at
+ # the default 192 px, dropping bands of the frame under a smaller tile.
+ with patch_qwen_image_vae_tiling(vae, tile_size):
if streaming:
for chunk in iter_wan_vae_decode_chunks(vae, latents):
chunk = chunk[0].cpu()
else:
vae.decode(latents, return_dict=False)[0].cpu()
- finally:
- if tiling:
- vae.disable_tiling()
torch.cuda.synchronize()
peak_allocated = torch.cuda.max_memory_allocated(device)
peak_reserved = torch.cuda.max_memory_reserved(device)
@@ -205,7 +215,7 @@ def main() -> None:
"--tile-size",
type=int,
default=None,
- help="Spatial tile size in pixels. Requires --tiling; defaults to the VAE tile size.",
+ help="Spatial tile size in pixels. Requires --tiling; defaults to the video node's 256.",
)
args = parser.parse_args()
diff --git a/tests/app/invocations/test_wan_working_memory.py b/tests/app/invocations/test_wan_working_memory.py
index ba051d4e7c..d6f1b0c6e3 100644
--- a/tests/app/invocations/test_wan_working_memory.py
+++ b/tests/app/invocations/test_wan_working_memory.py
@@ -173,6 +173,17 @@ class TestEstimateVaeWorkingMemoryWan:
)
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)):
@@ -404,6 +415,40 @@ class TestWanInvocationsRequestWorkingMemory:
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()
diff --git a/tests/test_calibrate_wan_vae_working_memory.py b/tests/test_calibrate_wan_vae_working_memory.py
index 6b3c8651c8..8a9017a8dc 100644
--- a/tests/test_calibrate_wan_vae_working_memory.py
+++ b/tests/test_calibrate_wan_vae_working_memory.py
@@ -7,6 +7,8 @@ from unittest.mock import MagicMock
import pytest
import torch
+from invokeai.backend.util.vae_working_memory import wan_vae_clip_bytes
+
def _load_calibration_script():
path = Path(__file__).parents[1] / "scripts" / "calibrate_wan_vae_working_memory.py"
@@ -82,8 +84,13 @@ def test_measure_tiling_uses_full_decode_and_tile_estimate(monkeypatch):
assert result["streaming"] is False
assert result["tiling"] is True
assert result["tile_size"] == 128
- fake_vae.enable_tiling.assert_called_once_with(tile_sample_min_height=128, tile_sample_min_width=128)
- fake_vae.disable_tiling.assert_called_once_with()
+ # The stride follows the tile, as in the video node; left at its 192 px default, a 128 px tile drops bands.
+ fake_vae.enable_tiling.assert_called_once_with(
+ tile_sample_min_height=128,
+ tile_sample_min_width=128,
+ tile_sample_stride_height=96,
+ tile_sample_stride_width=96,
+ )
fake_vae.decode.assert_called_once()
estimate.assert_called_once_with(
operation="decode",
@@ -96,7 +103,11 @@ def test_measure_tiling_uses_full_decode_and_tile_estimate(monkeypatch):
)
-def test_measure_tiling_implied_constant_uses_tiled_area(monkeypatch):
[email protected](("streaming", "tiling"), [(False, False), (True, False), (True, True)])
+def test_measure_implied_constant_subtracts_the_clip_the_estimate_budgets(monkeypatch, streaming, tiling):
+ """The implied constant is the per-frame term the estimate would need to match the measurement, so it subtracts
+ exactly the clip bytes the estimate budgets for the decode that ran: one chunk streaming, two clips full, and six
+ tiled, where tiling overrides streaming."""
script = _load_calibration_script()
parameter = torch.nn.Parameter(torch.zeros(1, dtype=torch.bfloat16))
fake_vae = MagicMock()
@@ -104,14 +115,22 @@ def test_measure_tiling_implied_constant_uses_tiled_area(monkeypatch):
fake_vae.parameters.side_effect = lambda: iter([parameter])
fake_vae.decode.return_value = (torch.zeros(1, 3, 81, 64, 64),)
- tile_size = 128
+ tile_size = 128 if tiling else None
constant = 4321.0
element_size = parameter.element_size()
pixel_height = pixel_width = 512
pixel_frames = 81
- # The tiled decode's six clip copies, as the estimator budgets them.
- clip_bytes = 6 * 3 * pixel_frames * pixel_height * pixel_width * element_size
- measured_delta = int(tile_size**2 * element_size * constant * 1.25 + clip_bytes)
+ clip_bytes = wan_vae_clip_bytes(
+ "decode",
+ fake_vae,
+ pixel_height,
+ pixel_width,
+ pixel_frames,
+ tile_size=tile_size,
+ streaming=streaming and not tiling,
+ )
+ per_frame_basis = tile_size**2 * element_size * 1.25 if tile_size else pixel_height * pixel_width * element_size
+ measured_delta = int(per_frame_basis * constant + clip_bytes)
monkeypatch.setattr(script.torch, "randn", lambda *args, **kwargs: torch.zeros(*args, dtype=kwargs["dtype"]))
monkeypatch.setattr(script.torch.cuda, "synchronize", lambda *args, **kwargs: None)
@@ -123,14 +142,15 @@ def test_measure_tiling_implied_constant_uses_tiled_area(monkeypatch):
monkeypatch.setattr(script.torch.cuda, "max_memory_allocated", lambda device: measured_delta - 12345)
monkeypatch.setattr(script.torch.cuda, "get_device_name", lambda device: "test-device")
monkeypatch.setattr(script, "estimate_vae_working_memory_wan", lambda **kwargs: measured_delta)
+ monkeypatch.setattr(script, "iter_wan_vae_decode_chunks", lambda vae, latents: iter([torch.zeros(1, 3, 4, 8, 8)]))
result = script._measure(
fake_vae,
pixel_height,
pixel_width,
pixel_frames,
- streaming=True,
- tiling=True,
+ streaming=streaming,
+ tiling=tiling,
tile_size=tile_size,
)