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
fix(wan): budget the video VAE decode against reserved memory
Alexander Eichhornaf9bbaabeb0c
diff --git a/docs/src/content/docs/configuration/Optimization/low-vram-mode.mdx b/docs/src/content/docs/configuration/Optimization/low-vram-mode.mdxindex dd4345b297..e3d9204387 100644--- a/docs/src/content/docs/configuration/Optimization/low-vram-mode.mdx+++ b/docs/src/content/docs/configuration/Optimization/low-vram-mode.mdx@@ -57,7 +57,7 @@ This reserves VRAM so partial-load Wan transformer weights target about 2 GiB reThe optimized BF16 transformer path can produce small numerical differences because chunked matrix operations accumulate in a different order. Same-seed output is not guaranteed to be bit-identical; set `wan_memory_optimization: false` for the baseline path.-Developers with a CUDA or ROCm device can validate Wan VAE memory estimates with `python scripts/calibrate_wan_vae_working_memory.py --vae <directory-or-safetensors-file>`. The script reports allocated and reserved memory deltas; its implied scaling constant uses allocated memory to match the shipped estimator, while reserved memory shows allocator headroom. Use `--tiling` to measure the spatially tiled full-decode fallback; it overrides streaming mode. Use `--tile-size <pixels>` to override the VAE's default tile size.+Developers with a CUDA or ROCm device can validate Wan VAE memory estimates with `python scripts/calibrate_wan_vae_working_memory.py --vae <directory-or-safetensors-file>`. The script reports allocated and reserved memory deltas; its implied scaling constant uses reserved memory, which is what the shipped estimator covers, because reserved memory is what the decode takes from the GPU. Pass `--no-streaming` to measure the default full decode. The shipped constant sits above what the script reports for most sizes, because it has to cover the highest measurement, an 832x480 decode inside a running server; `estimate covers` in the output says whether the estimate holds. Use `--tiling` to measure the spatially tiled full-decode fallback; it overrides streaming mode. Use `--tile-size <pixels>` to override the VAE's default tile size.Direct MP4 streaming keeps the VAE cache lock while chunks are decoded and written. Wan's causal decoder state and weights must remain live for the sequence; releasing the lock would require a separate bounded decode and encode queue.@@ -172,7 +172,7 @@ keep_ram_copy_of_weights: falseWithout tiling, the memory a VAE needs grows with the square of the image size. For FLUX.1, an untiled 3072² encode peaks at about 18.8 GiB on an RTX 4090, and a tiled one at 0.8 GiB, while tiled memory stays roughly flat as the image grows. Tiling costs some speed on smaller images.-Invoke tiles large decodes by itself: when an untiled decode would claim most of the memory the GPU keeps resident, it decodes in tiles instead, for the FLUX.1, Z-Image, Qwen-Image, Krea-2, Anima and Wan decodes. Because a tiled decode is not pixel-identical to an untiled one, this only kicks in for images too large for the card: for Z-Image on a 16GB GPU, for example, from about 1850x1850 on Nvidia and from about 1500x1500 on AMD, whose convolution library needs more memory. On a ROCm build under Windows the comparison uses the video-memory budget Windows grants Invoke, which is lower than the card's total and lower again while another program uses the GPU. Anima tiles a little earlier, because its untiled decode pushes the Anima model itself out of VRAM on 8GB cards.+Invoke tiles large decodes by itself: when an untiled decode would claim most of the memory the GPU keeps resident, it decodes in tiles instead, for the FLUX.1, Z-Image, Qwen-Image, Krea-2, Anima and Wan decodes. Because a tiled decode is not pixel-identical to an untiled one, this only kicks in for images too large for the card: for Z-Image on a 16GB GPU, for example, from about 1850x1850 on Nvidia and from about 1500x1500 on AMD, whose convolution library needs more memory. On a ROCm build under Windows the comparison uses the video-memory budget Windows grants Invoke, which is lower than the card's total and lower again while another program uses the GPU. Anima tiles a little earlier, because its untiled decode pushes the Anima model itself out of VRAM on 8GB cards. Wan videos are tiled from 832x480 on 8GB cards and from 720p on 16GB cards, where their untiled decodes need about as much memory as the card holds, or more.To always decode untiled unless you ask for tiling, turn this off. A decode too large for the card then runs out of memory: the FLUX.1 and Z-Image decodes retry in tiles, the others fail, and on Windows the driver may move the decode into system memory and run it very slowly instead. Anima is not affected by this setting: there, tiling a large decode is what keeps the Anima model in VRAM, and turning it off would only make those decodes slower.diff --git a/invokeai/backend/util/vae_working_memory.py b/invokeai/backend/util/vae_working_memory.pyindex c4c16bd876..c43b13785f 100644--- a/invokeai/backend/util/vae_working_memory.py+++ b/invokeai/backend/util/vae_working_memory.py@@ -78,7 +78,8 @@ def should_pretile_vae_decode(# 8x-downsampled grid. Where that attention runs on the math kernel (see `sdpa_score_matrix_bytes`)# its score matrix is the dominant term for a large untiled image, exactly as it is for FLUX.2;# `_vae_mid_block_score_matrix_bytes` prices it for those estimators the same way. The video VAEs-# (Wan, Qwen-Image) need no such term: their ROCm constants below were measured with math attention.+# (Wan, Qwen-Image) need no such term: the Qwen-Image ROCm constants below were measured with math+# attention. The Wan video-decode constant was measured on CUDA only; ROCm is unmeasured there._CLASSIC_VAE_MID_BLOCK_HEADS = 1_CLASSIC_VAE_MID_BLOCK_HEAD_DIM = 512@@ -93,8 +94,7 @@ _LTX2_VAE_ENCODE_BYTES_PER_TILE_ELEMENT = 700_LTX2_VAE_TILED_ENCODE_BYTES_PER_TILE_ELEMENT = 360_WAN_VAE_SINGLE_FRAME_DECODE_SCALING_CONSTANT = 2900-_WAN_VAE_VIDEO_DECODE_SCALING_CONSTANT_A14B = 6500-_WAN_VAE_VIDEO_DECODE_SCALING_CONSTANT_TI2V = 7000+_WAN_VAE_VIDEO_DECODE_SCALING_CONSTANT = 10000def _vae_mid_block_score_matrix_bytes(@@ -694,8 +694,8 @@ def estimate_vae_working_memory_wan(Callers pass pixel-space dimensions, so the VAE's spatial scale factor is alreadyapplied. Single-frame decode and encode use the original Wan 2.1 calibration;- multi-frame decode uses conservative, VAE-variant-specific calibrations because- causal-convolution state makes the single-frame value unsafe at video resolutions.+ multi-frame decode uses a calibration of peak reserved memory because causal-convolution+ state makes the single-frame value unsafe at video resolutions.The Wan VAE processes the clip causally, one latent frame at a time with cachedfeatures. In streaming mode, only one temporal-upscale chunk of the RGB output iskept on the execution device; otherwise the full output clip and its transient copy@@ -705,18 +705,37 @@ def estimate_vae_working_memory_wan(# The original 2900-byte calibration covers a single Wan 2.1 frame. Multi-frame video# decodes retain causal-convolution state that makes that constant unsafe at video- # resolutions. These conservative constants are based on measured allocated-memory- # peaks with allocator headroom: 6500 for the z_dim=16 A14B VAE and 7000 for the- # larger z_dim=48 TI2V VAE. Keep the single-frame value for image decode and the- # existing encode calibration.+ # resolutions. The video constant is calibrated on peak *reserved* growth, which is what the+ # cache's `free >= estimate` check has to cover: the decode's live tensors peak at only about+ # two thirds of what the allocator reserves. The earlier constants (6500 A14B, 7000 TI2V)+ # covered the live tensors; in a server faking a 16 GB card the 832x480x49 decode then overran+ # the card by 1.3-1.9 GB, and with sysmem fallback such a decode stalled for minutes.+ #+ # Implied constant = (reserved - clip bytes) / (h * w * element_size), with the clip bytes this+ # function budgets for the mode (`wan_vae_clip_bytes`: two full clips, or one 4-frame chunk when+ # streaming); bf16,+ # RTX 4090, `scripts/calibrate_wan_vae_working_memory.py --dtype bfloat16 [--no-streaming]`, and+ # "server" = torch's peak stats around the decode inside a running server:+ # 640x352x49 832x480x49 832x480x81 1280x704x49 1280x704x81 1280x704x121+ # A14B full 7512 8457 7751 7557 8073+ # A14B streaming 7773 8601+ # TI2V full 8903 8457 8557 8943 8511+ # TI2V full, server 9505 8944+ # TI2V streaming 9004 9230+ # TI2V streaming, server 9081 9235+ # The reserved peak barely grows with the frame count (TI2V 1280x704 reserved 15876 MiB at 49+ # and at 121 frames), so the clip bytes are budget on top of it rather than part of it. Both+ # VAEs reserved exactly the same 6666 MiB at 832x480x49 standalone, so one constant covers+ # both: the highest measurement, the server's 480p full decode, plus ~5%.+ #+ # The same estimate decides auto-tiling (`should_pretile_vae_decode`): with it, 832x480 clips+ # tile on 8 GB cards and 720p clips on 16 GB cards, where their untiled decodes reserve about as+ # much as the card holds or more. A14B's 1280x720x81 sits right at the line on 20 GB cards: one+ # constant for both VAEs gives A14B 16-24% over its own standalone maxima at 720p, kept because+ # its in-server 480p peak was not measured.+ # Keep the single-frame value for image decode and the existing encode calibration.if operation == "decode" and pixel_frames > 1:- try:- z_dim = int(getattr(vae.config, "z_dim", 16))- except (TypeError, ValueError):- z_dim = 48- scaling_constant = (- _WAN_VAE_VIDEO_DECODE_SCALING_CONSTANT_TI2V if z_dim >= 32 else _WAN_VAE_VIDEO_DECODE_SCALING_CONSTANT_A14B- )+ scaling_constant = _WAN_VAE_VIDEO_DECODE_SCALING_CONSTANTelse:scaling_constant = _WAN_VAE_SINGLE_FRAME_DECODE_SCALING_CONSTANT if operation == "decode" else 1450if tile_size is not None:@@ -725,6 +744,26 @@ def estimate_vae_working_memory_wan(else:per_frame = pixel_height * pixel_width * element_size * scaling_constant+ return int(+ per_frame + wan_vae_clip_bytes(operation, vae, pixel_height, pixel_width, pixel_frames, tile_size, streaming)+ )+++def wan_vae_clip_bytes(+ operation: Literal["encode", "decode"],+ vae: AutoencoderKLWan,+ pixel_height: int,+ pixel_width: int,+ pixel_frames: int,+ tile_size: int | None = None,+ streaming: bool = False,+) -> int:+ """The RGB clip bytes `estimate_vae_working_memory_wan` budgets on top of the VAE's own working set.++ Shared with `scripts/calibrate_wan_vae_working_memory.py`, which subtracts exactly this from a measurement to+ report the implied constant.+ """+ element_size = next(vae.parameters()).element_size()# Streaming decode moves each causal decoder chunk to CPU immediately. Only one# temporal-upscale chunk remains on the execution device, instead of the full RGB# clip plus the transient copy created by torch.cat.@@ -732,12 +771,16 @@ def estimate_vae_working_memory_wan(temporal_scale = int(getattr(vae.config, "scale_factor_temporal", None) or 4)resident_frames = min(pixel_frames, temporal_scale)clip_copies = 1+ elif operation == "decode" and tile_size is not None:+ # diffusers' tiled_decode keeps every row of decoded tiles, the blended rows, their concatenation and the+ # clamped result alive together, and the tile's own working set is small next to them: reserved memory grew+ # by 5.2 (A14B) and 5.6 (TI2V) clip copies per frame (1280x704 at 81 vs 121 frames, bf16).+ resident_frames = pixel_frames+ clip_copies = 6else:resident_frames = pixel_framesclip_copies = 2 if operation == "decode" else 1- clip_bytes = clip_copies * 3 * resident_frames * pixel_height * pixel_width * element_size-- return int(per_frame + clip_bytes)+ return clip_copies * 3 * resident_frames * pixel_height * pixel_width * element_size# What a full-frame Qwen-Image VAE decode was actually measured to peak at, per output pixel-byte, against the outputdiff --git a/scripts/calibrate_wan_vae_working_memory.py b/scripts/calibrate_wan_vae_working_memory.pyindex 59cb83c992..0c2c18bde8 100644--- a/scripts/calibrate_wan_vae_working_memory.py+++ b/scripts/calibrate_wan_vae_working_memory.py@@ -8,8 +8,13 @@ single Wan ``.safetensors`` checkpoint:The default shape matches the 12 GiB-card calibration point. Use ``--no-streaming``to measure the full-frame decode path, or ``--tiling`` to measure the spatiallytiled path used as a low-VRAM fallback. Tiling overrides streaming. The script-reports allocated and reserved deltas; the implied scaling constant uses allocated-memory to match the shipped estimator, while reserved memory shows allocator headroom.+reports allocated and reserved deltas; the implied scaling constant uses reserved+memory, which the shipped estimator is calibrated on: the model cache keeps the estimate+free for the decode, and what the decode takes from the device is what the allocator+reserves, about 1.5x its peak of live tensors. The table behind the shipped constant+(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."""from __future__ import annotations@@ -25,7 +30,10 @@ from diffusers.models.autoencoders import AutoencoderKLWansys.path.insert(0, str(Path(__file__).resolve().parents[1]))from invokeai.backend.model_manager.load.model_loaders.vae import _wan_vae_init_kwargs_for # noqa: E402-from invokeai.backend.util.vae_working_memory import estimate_vae_working_memory_wan # noqa: E402+from invokeai.backend.util.vae_working_memory import ( # noqa: E402+ estimate_vae_working_memory_wan,+ wan_vae_clip_bytes,+)from invokeai.backend.wan.vae_decode import iter_wan_vae_decode_chunks # noqa: E402DTYPES = {"float16": torch.float16, "bfloat16": torch.bfloat16, "float32": torch.float32}@@ -110,13 +118,15 @@ def _measure(tile_size=tile_size,streaming=streaming,)- if streaming:- resident_frames = min(pixel_frames, temporal_scale)- clip_copies = 1- else:- resident_frames = pixel_frames- clip_copies = 2- clip_bytes = clip_copies * 3 * resident_frames * pixel_height * pixel_width * element_size+ clip_bytes = wan_vae_clip_bytes(+ operation="decode",+ vae=vae,+ pixel_height=pixel_height,+ pixel_width=pixel_width,+ pixel_frames=pixel_frames,+ tile_size=tile_size,+ streaming=streaming,+ )torch.cuda.synchronize()torch.cuda.empty_cache()@@ -142,7 +152,7 @@ def _measure(peak_reserved = torch.cuda.max_memory_reserved(device)measured_allocated_delta = peak_allocated - baseline_allocatedmeasured_reserved_delta = peak_reserved - baseline_reserved- implied_constant = (measured_allocated_delta - clip_bytes) / scaling_basis_bytes+ implied_constant = (measured_reserved_delta - clip_bytes) / scaling_basis_bytesreturn {"device": torch.cuda.get_device_name(device),"backend": "ROCm" if torch.version.hip is not None else "CUDA",@@ -218,7 +228,10 @@ def main() -> None:print(f"estimate: {result['estimate_bytes'] / gib:.3f} GiB")print(f"measured allocated delta: {result['measured_allocated_delta_bytes'] / gib:.3f} GiB")print(f"measured reserved delta: {result['measured_reserved_delta_bytes'] / gib:.3f} GiB")- print(f"implied scaling constant (allocated): {result['implied_scaling_constant']:.1f}")+ print(f"implied scaling constant (reserved): {result['implied_scaling_constant']:.1f}")+ # With --tiling the clip copies can exceed the whole measurement, leaving a negative constant: the coverage is the+ # figure that says whether the estimate holds.+ print(f"estimate covers: {result['estimate_bytes'] / result['measured_reserved_delta_bytes']:.2f}x of reserved")if __name__ == "__main__":diff --git a/tests/app/invocations/test_wan_working_memory.py b/tests/app/invocations/test_wan_working_memory.pyindex 108e2263f3..ba051d4e7c 100644--- a/tests/app/invocations/test_wan_working_memory.py+++ b/tests/app/invocations/test_wan_working_memory.py@@ -12,7 +12,7 @@ from invokeai.app.invocations.vae.wan_latents_to_image import WanLatentsToImageIfrom invokeai.app.invocations.vae.wan_latents_to_video import WanLatentsToVideoInvocationfrom invokeai.app.invocations.wan.wan_ref_image_encoder import WanRefImageEncoderInvocationfrom invokeai.backend.util.devices import TorchDevice-from invokeai.backend.util.vae_working_memory import estimate_vae_working_memory_wan+from invokeai.backend.util.vae_working_memory import VAE_PRETILE_VRAM_FRACTION, estimate_vae_working_memory_wandef _mock_wan_vae(@@ -111,13 +111,68 @@ class TestEstimateVaeWorkingMemoryWan:tiled = estimate_vae_working_memory_wan(operation="decode", vae=vae, pixel_height=1920, pixel_width=1080, pixel_frames=17, tile_size=256)- expected = int(256 * 256 * 2 * 6500 * 1.25 + 2 * 3 * 17 * 1920 * 1080 * 2)+ # 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 == expectedfull = 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+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)):diff --git a/tests/test_calibrate_wan_vae_working_memory.py b/tests/test_calibrate_wan_vae_working_memory.pyindex 4c0a59c6d7..6b3c8651c8 100644--- a/tests/test_calibrate_wan_vae_working_memory.py+++ b/tests/test_calibrate_wan_vae_working_memory.py@@ -109,7 +109,8 @@ def test_measure_tiling_implied_constant_uses_tiled_area(monkeypatch):element_size = parameter.element_size()pixel_height = pixel_width = 512pixel_frames = 81- clip_bytes = 2 * 3 * pixel_frames * pixel_height * pixel_width * element_size+ # The tiled decode's six clip copies, as the estimator budgets them.+ clip_bytes = 6 * 3 * pixel_frames * pixel_height * pixel_width * element_sizemeasured_delta = int(tile_size**2 * element_size * constant * 1.25 + clip_bytes)monkeypatch.setattr(script.torch, "randn", lambda *args, **kwargs: torch.zeros(*args, dtype=kwargs["dtype"]))@@ -117,9 +118,9 @@ def test_measure_tiling_implied_constant_uses_tiled_area(monkeypatch):monkeypatch.setattr(script.torch.cuda, "empty_cache", lambda: None)monkeypatch.setattr(script.torch.cuda, "reset_peak_memory_stats", lambda *args, **kwargs: None)monkeypatch.setattr(script.torch.cuda, "memory_reserved", lambda device: 100)- monkeypatch.setattr(script.torch.cuda, "max_memory_reserved", lambda device: measured_delta + 100 + 12345)+ monkeypatch.setattr(script.torch.cuda, "max_memory_reserved", lambda device: measured_delta + 100)monkeypatch.setattr(script.torch.cuda, "memory_allocated", lambda device: 0)- monkeypatch.setattr(script.torch.cuda, "max_memory_allocated", lambda device: measured_delta)+ 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)@@ -133,6 +134,7 @@ def test_measure_tiling_implied_constant_uses_tiled_area(monkeypatch):tile_size=tile_size,)- assert result["measured_allocated_delta_bytes"] == measured_delta- assert result["measured_reserved_delta_bytes"] == measured_delta + 12345+ assert result["measured_allocated_delta_bytes"] == measured_delta - 12345+ assert result["measured_reserved_delta_bytes"] == measured_delta+ # From reserved memory: the estimate has to cover what the decode takes from the device.assert result["implied_scaling_constant"] == pytest.approx(constant, abs=0.01)