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
perf(qwen-image): add a tiling option to the Qwen-Image VAE nodes (#9427)
Alexander Eichhorn8e71a8a51939
diff --git a/invokeai/app/invocations/qwen_image_image_to_latents.py b/invokeai/app/invocations/qwen_image_image_to_latents.pyindex f56b0695dc..ca0b42aaea 100644--- a/invokeai/app/invocations/qwen_image_image_to_latents.py+++ b/invokeai/app/invocations/qwen_image_image_to_latents.py@@ -14,7 +14,12 @@ from invokeai.app.invocations.fields import (from invokeai.app.invocations.model import VAEFieldfrom invokeai.app.invocations.primitives import LatentsOutputfrom invokeai.app.services.shared.invocation_context import InvocationContext-from invokeai.backend.krea2.vae_compat import as_qwen_image_vae+from invokeai.backend.krea2.vae_compat import (+ QWEN_IMAGE_VAE_MIN_TILE_SIZE,+ as_qwen_image_vae,+ patch_qwen_image_vae_tiling,+ resolve_qwen_image_vae_tile_size,+)from invokeai.backend.model_manager.load.load_base import LoadedModelfrom invokeai.backend.stable_diffusion.diffusers_pipeline import image_resized_to_grid_as_tensorfrom invokeai.backend.util.devices import TorchDevice@@ -26,7 +31,7 @@ from invokeai.backend.util.vae_working_memory import estimate_vae_working_memorytitle="Image to Latents - Qwen Image",tags=["image", "latents", "vae", "i2l", "qwen_image"],category="image",- version="1.0.0",+ version="1.1.0",classification=Classification.Prototype,)class QwenImageImageToLatentsInvocation(BaseInvocation, WithMetadata, WithBoard):@@ -34,6 +39,15 @@ class QwenImageImageToLatentsInvocation(BaseInvocation, WithMetadata, WithBoard)image: ImageField = InputField(description="The image to encode.")vae: VAEField = InputField(description=FieldDescriptions.vae, input=Input.Connection)+ tiled: bool = InputField(default=False, description=FieldDescriptions.tiled)+ # NOTE: tile_size = 0 is a special value meaning "use the model's default", matching the+ # SD/SDXL i2l node. `int | None` is avoided because the workflow UI does not handle it well.+ tile_size: int = InputField(+ default=0,+ multiple_of=8,+ description=f"{FieldDescriptions.vae_tile_size} Values between 1 and "+ f"{QWEN_IMAGE_VAE_MIN_TILE_SIZE} are raised to {QWEN_IMAGE_VAE_MIN_TILE_SIZE}.",+ )width: int | None = InputField(default=None,description="Resize the image to this width before encoding. If not set, encodes at the image's original size.",@@ -44,24 +58,36 @@ class QwenImageImageToLatentsInvocation(BaseInvocation, WithMetadata, WithBoard))@staticmethod- def vae_encode(vae_info: LoadedModel, image_tensor: torch.Tensor) -> torch.Tensor:+ def vae_encode(+ vae_info: LoadedModel, image_tensor: torch.Tensor, tiled: bool = False, tile_size: int = 0+ ) -> torch.Tensor:# NOTE: vae_info.model may be an AutoencoderKLWan (a native-layout qwen_image_vae single file is# classified with the Anima base); it is reinterpreted as AutoencoderKLQwenImage inside the# model_on_device context below. The working-memory estimate only reads tensor shape + element# size, so it is safe to run on either class here.+ # Resolve tile_size=0 ("model default") before estimating, so the reserved working memory+ # matches the tiles the VAE will actually use. Resolved against a constant rather than the+ # module's current tile_sample_min_height, which a previous invocation may have overwritten.+ effective_tile_size = resolve_qwen_image_vae_tile_size(tile_size) if tiled else None+estimated_working_memory = estimate_vae_working_memory_qwen_image(operation="encode",image_tensor=image_tensor,vae=vae_info.model,+ tile_size=effective_tile_size,)with vae_info.model_on_device(working_mem_bytes=estimated_working_memory) as (_, vae):# Reinterpret an Anima-classified Wan VAE as AutoencoderKLQwenImage (identical weights).vae = as_qwen_image_vae(vae)- vae.disable_tiling()-image_tensor = image_tensor.to(device=TorchDevice.choose_torch_device(), dtype=vae.dtype)- with torch.inference_mode():++ # Tiling bounds the encode's peak memory to a single tile, which is what makes large+ # inputs (e.g. a 2560x1440 upscale round-trip) encodable while a multi-GB transformer+ # is still resident. Off by default: full-frame is faster and avoids tile blending.+ # The tiling state is scoped to this block: the VAE module belongs to the model cache+ # and is shared with later invocations (and with the Anima decode node).+ with torch.inference_mode(), patch_qwen_image_vae_tiling(vae, effective_tile_size):# The Qwen Image VAE expects 5D input: (B, C, num_frames, H, W)if image_tensor.dim() == 4:image_tensor = image_tensor.unsqueeze(2)@@ -91,7 +117,13 @@ class QwenImageImageToLatentsInvocation(BaseInvocation, WithMetadata, WithBoard)# If target dimensions are specified, resize the image BEFORE encoding# (matching the diffusers pipeline which resizes in pixel space, not latent space).- if self.width is not None and self.height is not None:+ #+ # `width`/`height` are `int | None`, but the workflow UI cannot represent None in a number+ # input and sends 0 for "unset" — which `is not None`, so a naive check reached+ # `resize((0, 0))` and raised "height and width must be > 0". Treat any non-positive value+ # as unset, which is also how `tile_size` uses 0. Note this means a half-filled pair (e.g.+ # width=1024, height=0) encodes at the original size rather than raising.+ if (self.width or 0) > 0 and (self.height or 0) > 0:image = image.convert("RGB").resize((self.width, self.height), resample=PILImage.LANCZOS)# multiple_of=16 ensures the post-VAE latents (vae_scale_factor=8) have even@@ -102,7 +134,12 @@ class QwenImageImageToLatentsInvocation(BaseInvocation, WithMetadata, WithBoard)vae_info = context.models.load(self.vae.vae)- latents = self.vae_encode(vae_info=vae_info, image_tensor=image_tensor)+ latents = self.vae_encode(+ vae_info=vae_info,+ image_tensor=image_tensor,+ tiled=self.tiled or context.config.get().force_tiled_decode,+ tile_size=self.tile_size,+ )latents = latents.to("cpu")name = context.tensors.save(tensor=latents)diff --git a/invokeai/app/invocations/qwen_image_latents_to_image.py b/invokeai/app/invocations/qwen_image_latents_to_image.pyindex 38ecd1e594..cb12ba6daa 100644--- a/invokeai/app/invocations/qwen_image_latents_to_image.py+++ b/invokeai/app/invocations/qwen_image_latents_to_image.py@@ -1,5 +1,3 @@-from contextlib import nullcontext-import torchfrom einops import rearrangefrom PIL import Image@@ -16,7 +14,12 @@ from invokeai.app.invocations.fields import (from invokeai.app.invocations.model import VAEFieldfrom invokeai.app.invocations.primitives import ImageOutputfrom invokeai.app.services.shared.invocation_context import InvocationContext-from invokeai.backend.krea2.vae_compat import as_qwen_image_vae+from invokeai.backend.krea2.vae_compat import (+ QWEN_IMAGE_VAE_MIN_TILE_SIZE,+ as_qwen_image_vae,+ patch_qwen_image_vae_tiling,+ resolve_qwen_image_vae_tile_size,+)from invokeai.backend.stable_diffusion.extensions.seamless import SeamlessExtfrom invokeai.backend.util.devices import TorchDevicefrom invokeai.backend.util.vae_working_memory import estimate_vae_working_memory_qwen_image@@ -27,7 +30,7 @@ from invokeai.backend.util.vae_working_memory import estimate_vae_working_memorytitle="Latents to Image - Qwen Image",tags=["latents", "image", "vae", "l2i", "qwen_image"],category="latents",- version="1.0.0",+ version="1.1.0",classification=Classification.Prototype,)class QwenImageLatentsToImageInvocation(BaseInvocation, WithMetadata, WithBoard):@@ -35,12 +38,30 @@ class QwenImageLatentsToImageInvocation(BaseInvocation, WithMetadata, WithBoard)latents: LatentsField = InputField(description=FieldDescriptions.latents, input=Input.Connection)vae: VAEField = InputField(description=FieldDescriptions.vae, input=Input.Connection)+ tiled: bool = InputField(default=False, description=FieldDescriptions.tiled)+ # NOTE: tile_size = 0 is a special value meaning "use the model's default", matching the+ # SD/SDXL l2i node. `int | None` is avoided because the workflow UI does not handle it well.+ tile_size: int = InputField(+ default=0,+ multiple_of=8,+ description=f"{FieldDescriptions.vae_tile_size} Values between 1 and "+ f"{QWEN_IMAGE_VAE_MIN_TILE_SIZE} are raised to {QWEN_IMAGE_VAE_MIN_TILE_SIZE}.",+ )@torch.no_grad()def invoke(self, context: InvocationContext) -> ImageOutput:latents = context.tensors.load(self.latents.latents_name)vae_info = context.models.load(self.vae.vae)+ tiled = self.tiled or context.config.get().force_tiled_decode+ # Resolve tile_size=0 ("model default") before estimating, so the memory the cache reserves+ # matches the tiles the VAE will actually use. Without this the estimate stays at the+ # full-frame figure (~21 GB at 2560x1440 on CUDA) and tiling frees nothing: the VAE is+ # bounded, but the cache still evicts other models to honour the reservation.+ # Resolved against a constant rather than the module's current tile_sample_min_height, which a+ # previous invocation (including the Anima decode node, which shares this VAE instance) may+ # have overwritten.+ effective_tile_size = resolve_qwen_image_vae_tile_size(self.tile_size) if tiled else None# NOTE: vae_info.model may be an AutoencoderKLWan (a native-layout qwen_image_vae single file is# classified with the Anima base); it is reinterpreted as AutoencoderKLQwenImage inside the# model_on_device context below. The working-memory estimate only reads tensor shape + element@@ -49,6 +70,7 @@ class QwenImageLatentsToImageInvocation(BaseInvocation, WithMetadata, WithBoard)operation="decode",image_tensor=latents,vae=vae_info.model,+ tile_size=effective_tile_size,)with vae_info.model_on_device(working_mem_bytes=estimated_working_memory) as (_, vae):context.util.signal_progress("Running VAE")@@ -62,17 +84,13 @@ class QwenImageLatentsToImageInvocation(BaseInvocation, WithMetadata, WithBoard)# which would wrongly place the latents (and thus the whole decode) on the CPU (see #9373).latents = latents.to(device=vae_info.compute_device, dtype=vae.dtype)- # Honor the global force_tiled_decode setting, like the SD/SDXL l2i node. Tiling bounds the- # VAE's per-tile memory, which is the scalable way to decode very large outputs that would- # exceed VRAM even after offloading the transformer/text encoder. For normal sizes, leave- # it off (faster, no tile blending) — the reserved working memory offloads other models so- # the full-frame decode fits.- if context.config.get().force_tiled_decode:- vae.enable_tiling()- else:- vae.disable_tiling()-- tiling_context = nullcontext()+ # Tiling bounds the VAE's per-tile memory, which is the scalable way to decode very+ # large outputs that would exceed VRAM even after offloading the transformer/text+ # encoder. For normal sizes, leave it off (faster, no tile blending) — the reserved+ # working memory offloads other models so the full-frame decode fits.+ # The tiling state is scoped to this block: the VAE module belongs to the model cache+ # and is shared with later invocations (and with the Anima decode node).+ tiling_context = patch_qwen_image_vae_tiling(vae, effective_tile_size)TorchDevice.empty_cache()diff --git a/invokeai/backend/krea2/vae_compat.py b/invokeai/backend/krea2/vae_compat.pyindex 00d5a81ef2..181cb7a6e9 100644--- a/invokeai/backend/krea2/vae_compat.py+++ b/invokeai/backend/krea2/vae_compat.py@@ -6,8 +6,13 @@ and therefore classified with the Anima base, which loads it as ``AutoencoderKLWshare the exact same diffusers state-dict (identical keys and shapes), so a Wan-loaded VAE can beused through the same encode/decode path without rebuilding it. Both default configs carry the sameQwen-Image ``latents_mean`` / ``latents_std`` / ``z_dim`` values read by the Qwen encode/decode nodes.++Also holds the tiling helpers those nodes share, since the tile geometry has to be applied identically+on both classes and restored afterwards — see ``patch_qwen_image_vae_tiling``."""+from collections.abc import Iterator+from contextlib import contextmanagerfrom typing import Anyfrom diffusers.models.autoencoders import AutoencoderKLWan@@ -55,3 +60,92 @@ def as_qwen_image_vae(model: Any) -> QwenImageCompatibleVAE:)return model+++# The stock AutoencoderKLQwenImage tile geometry: 256px tiles advancing in 192px steps, i.e. a 3/4+# stride ratio with a 64px blend band. Both nodes resolve tile_size=0 to QWEN_IMAGE_VAE_DEFAULT_TILE_SIZE+# rather than reading the module's current value, which another invocation may have overwritten.+QWEN_IMAGE_VAE_DEFAULT_TILE_SIZE = 256+_QWEN_IMAGE_VAE_TILE_STRIDE_NUMERATOR = 3+_QWEN_IMAGE_VAE_TILE_STRIDE_DENOMINATOR = 4++# A cost floor, not a correctness one: `_tile_stride_for` keeps the geometry valid all the way down+# (smaller tiles decode and encode to the right size), but the tile *count* grows with the inverse+# square of the stride. At 2560x1440 a 64px tile already emits 1620 tiles; an 8px tile would emit+# 57,600, and the per-tile Python/kernel-launch overhead dominates long before that. Tiles this small+# also blend badly, so the field's low end is clamped rather than honoured literally.+QWEN_IMAGE_VAE_MIN_TILE_SIZE = 64+++def resolve_qwen_image_vae_tile_size(tile_size: int) -> int:+ """Resolve a node's ``tile_size`` field to the tile size the VAE will actually use.++ ``tile_size <= 0`` is the nodes' "use the default" sentinel (the workflow UI cannot represent+ ``None`` in a number input and sends 0). Values below ``QWEN_IMAGE_VAE_MIN_TILE_SIZE`` are clamped+ rather than rejected, because the field also has to accept the 0 sentinel and so cannot carry a+ pydantic lower bound. The clamp is about cost, not validity -- see the constant.+ """+ if tile_size <= 0:+ return QWEN_IMAGE_VAE_DEFAULT_TILE_SIZE+ return max(tile_size, QWEN_IMAGE_VAE_MIN_TILE_SIZE)+++def _tile_stride_for(tile_size: int) -> int:+ """Return the tile stride to pair with ``tile_size``, keeping the stock 3/4 ratio.++ Rounded down to a multiple of the VAE's 8x spatial compression: ``tiled_encode``/``tiled_decode``+ step the tile loop in one space (pixels for encode, latents for decode) while slicing the+ accumulated tile in the other, so the pixel stride must be exactly 8x the latent stride or the+ two disagree and the output is misaligned.+ """+ stride = tile_size * _QWEN_IMAGE_VAE_TILE_STRIDE_NUMERATOR // _QWEN_IMAGE_VAE_TILE_STRIDE_DENOMINATOR+ return max(_QWEN_IMAGE_VAE_SPATIAL_SCALE, stride // _QWEN_IMAGE_VAE_SPATIAL_SCALE * _QWEN_IMAGE_VAE_SPATIAL_SCALE)+++@contextmanager+def patch_qwen_image_vae_tiling(vae: QwenImageCompatibleVAE, tile_size: int | None) -> Iterator[None]:+ """Set the VAE's tiling state for the duration of the block, then restore it.++ Two things make this a context manager rather than a bare ``enable_tiling()`` call:++ - ``enable_tiling`` writes the tile geometry straight onto the module, and ``disable_tiling`` only+ clears ``use_tiling`` — it does not restore the sizes. The module here is the model cache's own+ instance (``as_qwen_image_vae`` deliberately returns it unchanged to keep partial-loading hooks+ intact), so without a restore a tile size set once would persist for the lifetime of the cache+ entry and leak into later invocations — including ``anima_latents_to_image``, which shares the+ same VAE instance when a native-layout ``qwen_image_vae`` single file is loaded.+ - All four parameters are always passed explicitly. ``enable_tiling`` falls back to the module's+ current value for any argument left out, and its ``min``/``stride`` pair must stay consistent:+ the tile loops advance by *stride* but slice each accumulated tile to *min*. A ``min`` below the+ inherited 192px stride silently drops whole bands of the image, and a ``min`` above it grows+ every tile without removing any, making compute scale with ``tile_size**2``.++ ``tile_size=None`` disables tiling for the block.+ """+ original = (+ vae.use_tiling,+ vae.tile_sample_min_height,+ vae.tile_sample_min_width,+ vae.tile_sample_stride_height,+ vae.tile_sample_stride_width,+ )+ try:+ if tile_size is None:+ vae.disable_tiling()+ else:+ stride = _tile_stride_for(tile_size)+ vae.enable_tiling(+ tile_sample_min_height=tile_size,+ tile_sample_min_width=tile_size,+ tile_sample_stride_height=stride,+ tile_sample_stride_width=stride,+ )+ yield+ finally:+ (+ vae.use_tiling,+ vae.tile_sample_min_height,+ vae.tile_sample_min_width,+ vae.tile_sample_stride_height,+ vae.tile_sample_stride_width,+ ) = originaldiff --git a/invokeai/backend/util/vae_working_memory.py b/invokeai/backend/util/vae_working_memory.pyindex bc224e5076..bd780d4c0b 100644--- a/invokeai/backend/util/vae_working_memory.py+++ b/invokeai/backend/util/vae_working_memory.py@@ -189,14 +189,25 @@ def estimate_vae_working_memory_wan(def estimate_vae_working_memory_qwen_image(- operation: Literal["encode", "decode"], image_tensor: torch.Tensor, vae: AutoencoderKLQwenImage+ operation: Literal["encode", "decode"],+ image_tensor: torch.Tensor,+ vae: AutoencoderKLQwenImage,+ tile_size: int | None = None,) -> int:"""Estimate the working memory required by the invocation in bytes.The Qwen Image VAE is a video-style autoencoder that operates on 5D tensors of shape- (B, C, num_frames, H, W). Tiling is not used, so peak working memory scales with the full- spatial output. The two trailing dimensions are the spatial H/W in latent space (decode) or- pixel space (encode), matching the convention used by the other estimators here.+ (B, C, num_frames, H, W). The two trailing dimensions are the spatial H/W in latent space+ (decode) or pixel space (encode), matching the convention used by the other estimators here.++ Without tiling, peak working memory scales with the full spatial extent. With tiling it is+ bounded by a single tile instead, so the estimate must follow suit — otherwise the cache keeps+ reserving the full-frame figure (~11.8 GB for a 2560x1440 encode on CUDA) and tiling buys+ nothing. Mirrors ``estimate_vae_working_memory_wan``: one tile plus 25% for the tile overlap,+ plus the pixel-space buffers, which stay resident on the execution device either way.++ ``tile_size`` is the resolved tile size (the nodes' 0 sentinel already substituted), and assumes+ the 4:3 tile-to-stride ratio applied by ``patch_qwen_image_vae_tiling``."""latent_scale_factor_for_operation = LATENT_SCALE_FACTOR if operation == "decode" else 1@@ -240,7 +251,22 @@ def estimate_vae_working_memory_qwen_image(else: # encodescaling_constant = 6300 if is_rocm else 1600- working_memory = h * w * element_size * scaling_constant+ if tile_size is not None and tile_size > 0:+ # Bounded by one tile (plus overlap) rather than the full frame.+ working_memory = tile_size * tile_size * element_size * scaling_constant * 1.25+ # The full RGB image is the encode input / decode output and stays resident regardless. Unlike+ # the per-tile term this scales with the output area, so it is the term that decides whether the+ # estimate still holds at the resolutions tiling exists for.+ #+ # `tiled_decode` holds several pixel-space copies at once: every decoded tile in `rows`+ # ((tile_min / tile_stride)^2 ~ 1.8 frames at the 4:3 ratio the nodes set), the blended and+ # cropped `result_rows` (~1 frame) and the final `torch.cat` output (~1 frame). Measured at+ # ~5 frames on a 2560x1440 fp16 decode. Encode consumes its input image without duplicating it,+ # and accumulates only latents (16 channels at 1/64 the area — negligible).+ image_copies = 5 if operation == "decode" else 1+ working_memory += image_copies * 3 * h * w * element_size+ else:+ working_memory = h * w * element_size * scaling_constantreturn int(working_memory)diff --git a/invokeai/frontend/web/openapi.json b/invokeai/frontend/web/openapi.jsonindex 233fef6bee..6de4b71d54 100644--- a/invokeai/frontend/web/openapi.json+++ b/invokeai/frontend/web/openapi.json@@ -74950,6 +74950,27 @@"input": "connection","orig_required": true},+ "tiled": {+ "default": false,+ "description": "Processing using overlapping tiles (reduce memory consumption)",+ "field_kind": "input",+ "input": "any",+ "orig_default": false,+ "orig_required": false,+ "title": "Tiled",+ "type": "boolean"+ },+ "tile_size": {+ "default": 0,+ "description": "The tile size for VAE tiling in pixels (image space). If set to 0, the default tile size for the model will be used. Larger tile sizes generally produce better results at the cost of higher memory usage. Values between 1 and 64 are raised to 64.",+ "field_kind": "input",+ "input": "any",+ "multipleOf": 8,+ "orig_default": 0,+ "orig_required": false,+ "title": "Tile Size",+ "type": "integer"+ },"width": {"anyOf": [{@@ -74996,7 +75017,7 @@"tags": ["image", "latents", "vae", "i2l", "qwen_image"],"title": "Image to Latents - Qwen Image","type": "object",- "version": "1.0.0",+ "version": "1.1.0","output": {"$ref": "#/components/schemas/LatentsOutput"}@@ -75094,6 +75115,27 @@"input": "connection","orig_required": true},+ "tiled": {+ "default": false,+ "description": "Processing using overlapping tiles (reduce memory consumption)",+ "field_kind": "input",+ "input": "any",+ "orig_default": false,+ "orig_required": false,+ "title": "Tiled",+ "type": "boolean"+ },+ "tile_size": {+ "default": 0,+ "description": "The tile size for VAE tiling in pixels (image space). If set to 0, the default tile size for the model will be used. Larger tile sizes generally produce better results at the cost of higher memory usage. Values between 1 and 64 are raised to 64.",+ "field_kind": "input",+ "input": "any",+ "multipleOf": 8,+ "orig_default": 0,+ "orig_required": false,+ "title": "Tile Size",+ "type": "integer"+ },"type": {"const": "qwen_image_l2i","default": "qwen_image_l2i",@@ -75106,7 +75148,7 @@"tags": ["latents", "image", "vae", "l2i", "qwen_image"],"title": "Latents to Image - Qwen Image","type": "object",- "version": "1.0.0",+ "version": "1.1.0","output": {"$ref": "#/components/schemas/ImageOutput"}diff --git a/invokeai/frontend/web/src/services/api/schema.ts b/invokeai/frontend/web/src/services/api/schema.tsindex 0fb19d1c67..f1779d9814 100644--- a/invokeai/frontend/web/src/services/api/schema.ts+++ b/invokeai/frontend/web/src/services/api/schema.ts@@ -31861,6 +31861,18 @@ export type components = {* @default null*/vae?: components["schemas"]["VAEField"] | null;+ /**+ * Tiled+ * @description Processing using overlapping tiles (reduce memory consumption)+ * @default false+ */+ tiled?: boolean;+ /**+ * Tile Size+ * @description The tile size for VAE tiling in pixels (image space). If set to 0, the default tile size for the model will be used. Larger tile sizes generally produce better results at the cost of higher memory usage. Values between 1 and 64 are raised to 64.+ * @default 0+ */+ tile_size?: number;/*** Width* @description Resize the image to this width before encoding. If not set, encodes at the image's original size.@@ -31922,6 +31934,18 @@ export type components = {* @default null*/vae?: components["schemas"]["VAEField"] | null;+ /**+ * Tiled+ * @description Processing using overlapping tiles (reduce memory consumption)+ * @default false+ */+ tiled?: boolean;+ /**+ * Tile Size+ * @description The tile size for VAE tiling in pixels (image space). If set to 0, the default tile size for the model will be used. Larger tile sizes generally produce better results at the cost of higher memory usage. Values between 1 and 64 are raised to 64.+ * @default 0+ */+ tile_size?: number;/*** type* @default qwen_image_l2idiff --git a/tests/app/invocations/test_qwen_image_working_memory.py b/tests/app/invocations/test_qwen_image_working_memory.pyindex 02a6faedf1..82af54c9e4 100644--- a/tests/app/invocations/test_qwen_image_working_memory.py+++ b/tests/app/invocations/test_qwen_image_working_memory.py@@ -1,5 +1,6 @@"""Test that Qwen Image VAE invocations properly estimate and request working memory."""+import mathfrom contextlib import nullcontextfrom unittest.mock import MagicMock, patch@@ -9,6 +10,10 @@ from diffusers.models.autoencoders.autoencoder_kl_qwenimage import AutoencoderKLfrom invokeai.app.invocations.qwen_image_image_to_latents import QwenImageImageToLatentsInvocationfrom invokeai.app.invocations.qwen_image_latents_to_image import QwenImageLatentsToImageInvocation+from invokeai.backend.krea2.vae_compat import (+ QWEN_IMAGE_VAE_DEFAULT_TILE_SIZE,+ patch_qwen_image_vae_tiling,+)from invokeai.backend.util.vae_working_memory import estimate_vae_working_memory_qwen_image@@ -51,6 +56,71 @@ class TestQwenImageWorkingMemoryEstimate:assert result == h * w * 2 * expected_constant+ def _mock_fp16_vae(self):+ mock_vae = MagicMock(spec=AutoencoderKLQwenImage)+ mock_vae.parameters.return_value = iter([torch.zeros(1, dtype=torch.float16)]) # element_size == 2+ return mock_vae++ @pytest.mark.parametrize("operation, image_copies", [("decode", 5), ("encode", 1)])+ def test_tiled_estimate_is_one_tile_plus_the_pixel_buffers(self, operation, image_copies):+ """The tiled branch must budget the per-tile conv working set *and* the pixel-space buffers.++ The tile term is constant in the output size, so the pixel term is the one that decides whether+ the estimate still holds at the resolutions tiling exists for. `tiled_decode` keeps several full+ frames alive at once (every decoded tile in `rows`, the cropped `result_rows`, and the final+ `torch.cat`), so a single-frame budget under-counts by ~5x and does so linearly with area.+ """+ # 2560x1440, the resolution the PR was measured at.+ if operation == "decode":+ image_tensor = torch.zeros(1, 16, 1, 180, 320)+ else:+ image_tensor = torch.zeros(1, 3, 1, 1440, 2560)+ h, w = 1440, 2560+ tile_size = 256++ with patch("torch.version.hip", None):+ tiled = estimate_vae_working_memory_qwen_image(+ operation=operation, image_tensor=image_tensor, vae=self._mock_fp16_vae(), tile_size=tile_size+ )+ untiled = estimate_vae_working_memory_qwen_image(+ operation=operation, image_tensor=image_tensor, vae=self._mock_fp16_vae(), tile_size=None+ )++ scaling_constant = 2900 if operation == "decode" else 1600+ assert tiled == int(tile_size * tile_size * 2 * scaling_constant * 1.25 + image_copies * 3 * h * w * 2)+ # The whole point: tiling has to shrink the reservation, not just bound the VAE.+ assert tiled < untiled / 4++ def test_tiled_estimate_grows_with_the_tile_not_the_image(self):+ """Reserved memory scales with tile_size^2 and is otherwise flat in resolution.++ Only the pixel-buffer term varies with the image, so doubling the output area must not come+ close to doubling the reservation -- that is what lets a 24 GB card survive a 2560x1440 decode.+ """+ with patch("torch.version.hip", None):+ small = estimate_vae_working_memory_qwen_image(+ operation="decode",+ image_tensor=torch.zeros(1, 16, 1, 128, 128),+ vae=self._mock_fp16_vae(),+ tile_size=256,+ )+ large = estimate_vae_working_memory_qwen_image(+ operation="decode",+ image_tensor=torch.zeros(1, 16, 1, 180, 320),+ vae=self._mock_fp16_vae(),+ tile_size=256,+ )+ big_tile = estimate_vae_working_memory_qwen_image(+ operation="decode",+ image_tensor=torch.zeros(1, 16, 1, 128, 128),+ vae=self._mock_fp16_vae(),+ tile_size=512,+ )++ assert large < small * 2+ # 512px tiles cover 4x the area of 256px tiles; the tile term must follow.+ assert big_tile - small == pytest.approx((512**2 - 256**2) * 2 * 2900 * 1.25, rel=1e-6)+class TestQwenImageWorkingMemory:"""Test that Qwen Image VAE invocations request working memory before decode/encode."""@@ -62,6 +132,14 @@ class TestQwenImageWorkingMemory:# Create mock parameter for dtype detectionmock_param = torch.zeros(1)mock_vae.parameters.return_value = iter([mock_param])+ mock_vae.dtype = torch.float32+ # patch_qwen_image_vae_tiling records and restores these; give them the stock values so+ # assertions read against real numbers rather than auto-created MagicMocks.+ mock_vae.use_tiling = False+ mock_vae.tile_sample_min_height = 256+ mock_vae.tile_sample_min_width = 256+ mock_vae.tile_sample_stride_height = 192+ mock_vae.tile_sample_stride_width = 192# Create mock vae_info with a model_on_device context manager yielding (None, vae)mock_vae_info = MagicMock()@@ -120,6 +198,12 @@ class TestQwenImageWorkingMemory:converted_vae = MagicMock(spec=AutoencoderKLQwenImage)converted_vae.parameters.return_value = iter([torch.zeros(1)])converted_vae.dtype = torch.float32+ # Tiling state lives on the instance, so `spec=` does not provide it.+ converted_vae.use_tiling = False+ converted_vae.tile_sample_min_height = 256+ converted_vae.tile_sample_min_width = 256+ converted_vae.tile_sample_stride_height = 192+ converted_vae.tile_sample_stride_width = 192converted_vae.config.z_dim = 16converted_vae.config.latents_mean = [0.0] * 16converted_vae.config.latents_std = [1.0] * 16@@ -164,17 +248,340 @@ class TestQwenImageWorkingMemory:estimation_path = "invokeai.app.invocations.qwen_image_image_to_latents.estimate_vae_working_memory_qwen_image"+ # Stop at the encode itself: everything before it is what this test is about, and a bare+ # `except Exception` here would also swallow a failure in the code under test.+ mock_vae.encode.side_effect = RuntimeError("stop at encode")+with patch(estimation_path) as mock_estimate:expected_memory = 1024 * 1024 * 5000 # 5GBmock_estimate.return_value = expected_memory- try:+ with pytest.raises(RuntimeError, match="stop at encode"):QwenImageImageToLatentsInvocation.vae_encode(mock_vae_info, mock_image_tensor)- except Exception:- # Downstream encode math fails under mocking; we only care that the cache was- # asked to reserve the estimated working memory before entering the device context.- passmock_estimate.assert_called_once()assert mock_estimate.call_args.kwargs["operation"] == "encode"mock_vae_info.model_on_device.assert_called_once_with(working_mem_bytes=expected_memory)++ def test_qwen_image_to_latents_passes_resolved_tile_size_to_the_estimate(self):+ """Tiling only helps if the *estimate* shrinks with it.++ The cache reserves whatever the estimator returns, so enabling tiling on the VAE without+ telling the estimator would leave it reserving the full-frame figure (~11 GB at 2560x1440)+ and evicting models to honour it: the encode would be bounded, but nothing else would fit.+ tile_size=0 means "use the model default", which must be resolved before estimating.+ """+ mock_vae, mock_vae_info = self._mock_vae_info()+ mock_vae.encode.side_effect = RuntimeError("stop at encode")+ # A previous invocation left a different tile size on the shared module. The resolved default+ # must come from the constant, not from whatever is currently on the model.+ mock_vae_info.model.tile_sample_min_height = 512+ mock_image_tensor = torch.zeros(1, 3, 512, 512)++ estimation_path = "invokeai.app.invocations.qwen_image_image_to_latents.estimate_vae_working_memory_qwen_image"++ cases = (+ (False, 0, None),+ (True, 0, QWEN_IMAGE_VAE_DEFAULT_TILE_SIZE),+ (True, 512, 512),+ # Below the minimum the tile size is clamped, and the estimate must follow the clamp.+ (True, 8, 64),+ )+ for tiled, tile_size, expected in cases:+ with patch(estimation_path) as mock_estimate:+ mock_estimate.return_value = 1024+ with pytest.raises(RuntimeError, match="stop at encode"):+ QwenImageImageToLatentsInvocation.vae_encode(+ mock_vae_info, mock_image_tensor, tiled=tiled, tile_size=tile_size+ )+ assert mock_estimate.call_args.kwargs["tile_size"] == expected, f"tiled={tiled}, tile_size={tile_size}"++ @pytest.mark.parametrize(+ "tile_size, expected_min, expected_stride",+ [+ (0, 256, 192),+ (512, 512, 384),+ (128, 128, 96),+ (8, 64, 48),+ # 3/4 of these is 54 and 60, neither a multiple of the VAE's 8x spatial compression:+ # the stride must be rounded down to 48 / 56 or the pixel and latent tile loops disagree.+ (72, 72, 48),+ (80, 80, 56),+ ],+ )+ def test_image_to_latents_sets_a_matched_tile_stride(self, tile_size, expected_min, expected_stride):+ """`enable_tiling` must always receive all four parameters.++ Left out, the stride keeps whatever value the module already carries (192 by default): a+ smaller `min` then makes the tile loops skip whole bands of the image, and a larger one grows+ every tile without removing any. See TestQwenImageVaeTiling for the end-to-end consequence.+ """+ mock_vae, mock_vae_info = self._mock_vae_info()+ mock_vae.encode.side_effect = RuntimeError("stop at encode")++ with patch(+ "invokeai.app.invocations.qwen_image_image_to_latents.estimate_vae_working_memory_qwen_image",+ return_value=1024,+ ):+ with pytest.raises(RuntimeError, match="stop at encode"):+ QwenImageImageToLatentsInvocation.vae_encode(+ mock_vae_info, torch.zeros(1, 3, 512, 512), tiled=True, tile_size=tile_size+ )++ mock_vae.enable_tiling.assert_called_once_with(+ tile_sample_min_height=expected_min,+ tile_sample_min_width=expected_min,+ tile_sample_stride_height=expected_stride,+ tile_sample_stride_width=expected_stride,+ )++ def test_latents_to_image_sets_a_matched_tile_stride(self):+ """Same contract on the decode node, which is where the inert-tiling bug actually was."""+ mock_vae, mock_vae_info = self._mock_vae_info()+ mock_vae.decode.side_effect = RuntimeError("stop at decode")+ mock_vae.config.z_dim = 16+ mock_vae.config.latents_mean = [0.0] * 16+ mock_vae.config.latents_std = [1.0] * 16++ mock_context = MagicMock()+ mock_context.models.load.return_value = mock_vae_info+ mock_context.tensors.load.return_value = torch.zeros(1, 16, 1, 64, 64)+ mock_context.config.get.return_value.force_tiled_decode = False++ with (+ patch(+ "invokeai.app.invocations.qwen_image_latents_to_image.estimate_vae_working_memory_qwen_image",+ return_value=1024,+ ) as mock_estimate,+ patch(+ "invokeai.app.invocations.qwen_image_latents_to_image.SeamlessExt.static_patch_model",+ return_value=nullcontext(),+ ),+ ):+ invocation = QwenImageLatentsToImageInvocation.model_construct(+ latents=MagicMock(latents_name="test_latents"),+ vae=MagicMock(vae=MagicMock(), seamless_axes=[]),+ tiled=True,+ tile_size=512,+ )+ with pytest.raises(RuntimeError, match="stop at decode"):+ invocation.invoke(mock_context)++ assert mock_estimate.call_args.kwargs["tile_size"] == 512+ mock_vae.enable_tiling.assert_called_once_with(+ tile_sample_min_height=512,+ tile_sample_min_width=512,+ tile_sample_stride_height=384,+ tile_sample_stride_width=384,+ )++ def test_latents_to_image_honours_the_global_force_tiled_decode(self):+ """`force_tiled_decode` must reach both the VAE and the estimate, or tiling stays inert."""+ mock_vae, mock_vae_info = self._mock_vae_info()+ mock_vae.decode.side_effect = RuntimeError("stop at decode")+ mock_vae.config.z_dim = 16+ mock_vae.config.latents_mean = [0.0] * 16+ mock_vae.config.latents_std = [1.0] * 16++ mock_context = MagicMock()+ mock_context.models.load.return_value = mock_vae_info+ mock_context.tensors.load.return_value = torch.zeros(1, 16, 1, 64, 64)+ mock_context.config.get.return_value.force_tiled_decode = True++ with (+ patch(+ "invokeai.app.invocations.qwen_image_latents_to_image.estimate_vae_working_memory_qwen_image",+ return_value=1024,+ ) as mock_estimate,+ patch(+ "invokeai.app.invocations.qwen_image_latents_to_image.SeamlessExt.static_patch_model",+ return_value=nullcontext(),+ ),+ ):+ invocation = QwenImageLatentsToImageInvocation.model_construct(+ latents=MagicMock(latents_name="test_latents"),+ vae=MagicMock(vae=MagicMock(), seamless_axes=[]),+ tiled=False,+ tile_size=0,+ )+ with pytest.raises(RuntimeError, match="stop at decode"):+ invocation.invoke(mock_context)++ assert mock_estimate.call_args.kwargs["tile_size"] == QWEN_IMAGE_VAE_DEFAULT_TILE_SIZE+ mock_vae.enable_tiling.assert_called_once()+++class TestQwenImageVaeTiling:+ """Exercise the tiling parameters against a real (tiny, randomly initialised) Qwen-Image VAE.++ The mocked tests above can only assert which arguments are passed. These assert what those+ arguments actually do, which is where both tiling bugs lived: `AutoencoderKLQwenImage` steps its+ tile loops by *stride* while slicing each accumulated tile to *min*, so an inherited stride+ silently truncates the output instead of raising.+ """++ @pytest.fixture(scope="class")+ @classmethod+ def vae(cls):+ # Smallest configuration that keeps the real 8x spatial compression and 16 latent channels.+ return AutoencoderKLQwenImage(+ base_dim=4,+ z_dim=16,+ dim_mult=[1, 1, 1, 1],+ num_res_blocks=1,+ attn_scales=[],+ temperal_downsample=[False, True, True],+ ).eval()++ # 72 and 80 are the interesting ones: their raw 3/4 stride (54, 60) is not a multiple of 8.+ @pytest.mark.parametrize("tile_size", [64, 72, 80, 128, 192, 256, 512])+ def test_tiled_decode_keeps_the_full_output_size(self, vae, tile_size):+ latents = torch.zeros(1, 16, 1, 32, 32) # -> 256x256+ with torch.inference_mode(), patch_qwen_image_vae_tiling(vae, tile_size):+ decoded = vae.decode(latents, return_dict=False)[0]+ assert decoded.shape == (1, 3, 1, 256, 256)++ @pytest.mark.parametrize("tile_size", [64, 72, 80, 128, 192, 256, 512])+ def test_tiled_encode_keeps_the_full_latent_size(self, vae, tile_size):+ image = torch.zeros(1, 3, 1, 256, 256)+ with torch.inference_mode(), patch_qwen_image_vae_tiling(vae, tile_size):+ latents = vae.encode(image).latent_dist.mode()+ assert latents.shape == (1, 16, 1, 32, 32)++ def test_inherited_stride_would_truncate(self, vae):+ """Pin the failure mode the four-parameter call exists to prevent.++ This is the pre-fix call: `min` only, stride left at the module's 192. If diffusers ever+ starts deriving the stride from `min`, this test fails and the explicit stride can be dropped.+ """+ latents = torch.zeros(1, 16, 1, 32, 32)+ with patch_qwen_image_vae_tiling(vae, 256):+ vae.enable_tiling(tile_sample_min_height=128, tile_sample_min_width=128)+ with torch.inference_mode():+ decoded = vae.decode(latents, return_dict=False)[0]+ assert decoded.shape == (1, 3, 1, 192, 192) # not 256x256 -- silently truncated++ def test_unrounded_stride_would_misalign(self, vae):+ """Pin the failure mode the multiple-of-8 rounding exists to prevent.++ `tiled_encode` steps the tile loop by `tile_sample_stride_height` (pixels) but slices each+ accumulated tile to `tile_sample_stride_height // spatial_compression_ratio` (latents). Unless+ the pixel stride is exactly 8x the latent stride the two disagree, and the encode silently+ returns a latent smaller than the image -- the same class of bug as the inherited stride, but+ reachable from a `multiple_of=8` field value whose 3/4 stride is not itself a multiple of 8.+ """+ image = torch.zeros(1, 3, 1, 512, 512)+ with patch_qwen_image_vae_tiling(vae, 72):+ # The rounded stride the helper actually applies.+ assert vae.tile_sample_stride_height == 48+ with torch.inference_mode():+ assert vae.encode(image).latent_dist.mode().shape == (1, 16, 1, 64, 64)++ # ...and the un-rounded 3/4 value it deliberately avoids.+ vae.enable_tiling(tile_sample_stride_height=54, tile_sample_stride_width=54)+ with torch.inference_mode():+ misaligned = vae.encode(image).latent_dist.mode()+ assert misaligned.shape == (1, 16, 1, 57, 57) # not 64x64 -- silently truncated++ def test_tiling_state_is_restored(self, vae):+ """The VAE module belongs to the model cache and outlives the invocation.++ `enable_tiling` writes the geometry onto the module and `disable_tiling` only clears+ `use_tiling`, so without the restore a tile size set once would persist for the lifetime of+ the cache entry -- and leak into other nodes sharing the instance.+ """+ before = (+ vae.use_tiling,+ vae.tile_sample_min_height,+ vae.tile_sample_min_width,+ vae.tile_sample_stride_height,+ vae.tile_sample_stride_width,+ )+ with patch_qwen_image_vae_tiling(vae, 512):+ assert vae.use_tiling is True+ assert vae.tile_sample_min_height == 512+ assert vae.tile_sample_stride_height == 384+ assert (+ vae.use_tiling,+ vae.tile_sample_min_height,+ vae.tile_sample_min_width,+ vae.tile_sample_stride_height,+ vae.tile_sample_stride_width,+ ) == before++ with patch_qwen_image_vae_tiling(vae, None):+ assert vae.use_tiling is False+ assert (+ vae.use_tiling,+ vae.tile_sample_min_height,+ vae.tile_sample_min_width,+ vae.tile_sample_stride_height,+ vae.tile_sample_stride_width,+ ) == before++ def test_geometry_left_by_another_node_does_not_affect_the_decode(self, vae):+ """`anima_latents_to_image` sets 512/384 on the same instance and never restores it.++ A native-layout `qwen_image_vae` single file is classified with the Anima base, so one loaded+ VAE can feed both nodes in a single workflow. Because all four parameters are passed+ explicitly and the 0 sentinel resolves against a constant, the leaked geometry cannot change+ this decode -- and is still intact afterwards for whoever set it.+ """+ vae.enable_tiling(+ tile_sample_min_height=512,+ tile_sample_min_width=512,+ tile_sample_stride_height=384,+ tile_sample_stride_width=384,+ )+ try:+ latents = torch.zeros(1, 16, 1, 32, 32)+ with torch.inference_mode(), patch_qwen_image_vae_tiling(vae, QWEN_IMAGE_VAE_DEFAULT_TILE_SIZE):+ decoded = vae.decode(latents, return_dict=False)[0]+ assert decoded.shape == (1, 3, 1, 256, 256)+ assert vae.tile_sample_min_height == 512+ assert vae.tile_sample_stride_height == 384+ finally:+ vae.disable_tiling()+ vae.tile_sample_min_height = vae.tile_sample_min_width = 256+ vae.tile_sample_stride_height = vae.tile_sample_stride_width = 192++ def test_tile_count_is_bounded_by_the_stride_ratio(self, vae):+ """Raising `tile_size` must remove tiles, not just enlarge them.++ With a fixed stride the loops emit the same number of tiles at every `tile_size`, so compute+ grows with `tile_size**2` -- 8x a full frame at 512px on a 2560x1440 decode. The proportional+ stride keeps the processed area flat at ~2x regardless of tile size.+ """+ latent_h, latent_w = 180, 320 # 2560x1440+ for tile_size in (256, 512, 768):+ with patch_qwen_image_vae_tiling(vae, tile_size):+ latent_stride = vae.tile_sample_stride_height // 8+ tiles = math.ceil(latent_h / latent_stride) * math.ceil(latent_w / latent_stride)+ processed = tiles * tile_size * tile_size+ assert processed / (1440 * 2560) < 2.5, f"tile_size={tile_size} processes {processed} px"++ @pytest.mark.parametrize("tile_size", [0, 64, 128, 512])+ def test_image_to_latents_node_produces_the_untiled_latent_shape(self, vae, tile_size):+ """The whole node path, tiled, against a real VAE -- the shape must not depend on tile_size.++ An undersized latent raises nothing here: it flows onward as a perfectly valid-looking tensor,+ which is why this is asserted end-to-end rather than only on the arguments.+ """+ 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 = MagicMock(return_value=cm)++ with patch(+ "invokeai.app.invocations.qwen_image_image_to_latents.TorchDevice.choose_torch_device",+ return_value=torch.device("cpu"),+ ):+ latents = QwenImageImageToLatentsInvocation.vae_encode(+ vae_info, torch.zeros(1, 3, 256, 256), tiled=True, tile_size=tile_size+ )++ assert latents.shape == (1, 16, 1, 32, 32)+ # And the shared module is left exactly as it was found.+ assert (vae.use_tiling, vae.tile_sample_min_height, vae.tile_sample_stride_height) == (False, 256, 192)