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
Merge remote-tracking branch 'origin/main' into feat/rocm-windows-memory
Alexander Eichhorn87d4692f6f05
diff --cc invokeai/app/invocations/vae/flux_vae_decode.pyindex 5118429b8c,d365f88180..170162e807--- a/invokeai/app/invocations/vae/flux_vae_decode.py+++ b/invokeai/app/invocations/vae/flux_vae_decode.py@@@ -18,12 -18,8 +18,11 @@@ from invokeai.app.services.shared.invocfrom invokeai.backend.model_manager.load.load_base import LoadedModelfrom invokeai.backend.util.devices import TorchDevicefrom invokeai.backend.util.oom import is_oom_error- from invokeai.backend.util.vae_tiling_scope import scoped_vae_tiling+ from invokeai.backend.util.vae_tiling_scope import MIN_TILE_SAMPLE_SIZE, scoped_vae_tiling-from invokeai.backend.util.vae_working_memory import estimate_vae_working_memory_flux+from invokeai.backend.util.vae_working_memory import (+ estimate_vae_working_memory_flux,+ should_pretile_vae_decode,+)@invocation(@@@ -44,43 -40,36 +43,57 @@@ class FluxVaeDecodeInvocation(BaseInvocdescription=FieldDescriptions.vae,input=Input.Connection,)+ tiled: bool = InputField(default=False, description=FieldDescriptions.tiled)+ # 0 is the "use the model's default" sentinel shared with the SD and Qwen-Image nodes: the+ # workflow UI cannot represent None in a number field.+ tile_size: int = InputField(+ default=0,+ multiple_of=8,+ description=f"{FieldDescriptions.vae_tile_size} Values between 1 and "+ f"{MIN_TILE_SAMPLE_SIZE} are raised to {MIN_TILE_SAMPLE_SIZE}.",+ )def _vae_decode(self, context: InvocationContext, vae_info: LoadedModel, latents: torch.Tensor) -> Image.Image:- assert isinstance(vae_info.model, (AutoEncoder, AutoencoderKL))-- # This node has no tiling fields, so the config switch is the only way a user can ask for a- # tiled decode here -- the same one the Z-Image, SD and Qwen-Image decode nodes honour. 0 is- # the "use the VAE's default tile" sentinel shared by the estimator and `scoped_vae_tiling`.+ # Deliberately still a class check, and deliberately not `is_flux_family_vae`.+ #+ # This node has accepted any `AutoencoderKL` since before the FLUX.1 VAE became one, so the+ # hazard that a foreign 16-channel VAE (SD 3.5's is the same 244 tensors with the same+ # shapes, differing only in `scaling_factor`/`shift_factor`) decodes here and is normalised+ # by the wrong constant is pre-existing, not introduced by that swap. Narrowing it would also+ # refuse a VAE whose config carries no `shift_factor`, which `test_flux_vae_decode.py`+ # exercises on purpose. The encode node *is* guarded, because it used to reject every+ # `AutoencoderKL` and the swap is what widened it.+ assert isinstance(vae_info.model, AutoencoderKL)- use_tiling = self.tiled or context.config.get().force_tiled_decode+ config = context.config.get()- use_tiling = config.force_tiled_decode- tile_size = 0 if use_tiling else None++ use_tiling = self.tiled or config.force_tiled_decode+ tile_size = self.tile_size if use_tiling else None- # Priced for either class, as in the Z-Image decode: a diffusers-layout FLUX VAE runs the same network, and a- # decode with nothing reserved is one Windows pages into system memory rather than failing.estimated_working_memory = estimate_vae_working_memory_flux(- operation="decode", image_tensor=latents, vae=vae_info.model, tile_size=tile_size+ operation="decode",+ image_tensor=latents,+ vae=vae_info.model,+ tile_size=tile_size,+ device=vae_info.compute_device,)++ # Where the untiled decode would claim most of what the device keeps resident, tile before it runs: on Windows++ # an allocation that does not fit is paged rather than refused, so the retry below never fires.+ if (+ not use_tiling+ and config.auto_tiled_decode+ and should_pretile_vae_decode(vae_info.compute_device, estimated_working_memory)+ ):+ use_tiling = True- tile_size = 0++ tile_size = self.tile_size+ estimated_working_memory = estimate_vae_working_memory_flux(+ operation="decode",+ image_tensor=latents,+ vae=vae_info.model,+ tile_size=tile_size,+ device=vae_info.compute_device,+ )with vae_info.model_on_device(working_mem_bytes=estimated_working_memory) as (_, vae):- assert isinstance(vae, (AutoEncoder, AutoencoderKL))+ assert isinstance(vae, AutoencoderKL)vae_dtype = next(iter(vae.parameters())).dtype# Use the VAE's intended compute device (CUDA/MPS, or CPU if configured cpu_only). Do NOT infer it from# current param residency: partial loading may have temporarily offloaded all weights to RAM, which woulddiff --cc invokeai/app/invocations/vae/flux_vae_encode.pyindex 3fc1adc307,7b77f3fc9d..5984fa737e--- a/invokeai/app/invocations/vae/flux_vae_encode.py+++ b/invokeai/app/invocations/vae/flux_vae_encode.py@@@ -41,19 -69,35 +69,41 @@@ class FluxVaeEncodeInvocation(BaseInvoc# TODO(ryand): Write a util function for generating random tensors that is consistent across devices / dtypes.# There's a starting point in get_noise(...), but it needs to be extracted and generalized. This function# should be used for VAE encode sampling.- assert isinstance(vae_info.model, AutoEncoder)+ # Not `isinstance(..., AutoencoderKL)`: that used to mean "the FLUX autoencoder" and now+ # admits SD, SD 3.5 and CogView 4 as well, which would hand the denoiser a latent in the+ # wrong space. The normalisation is what separates them.+ if not is_flux_family_vae(vae_info.model):+ raise ValueError(+ "This node encodes into the FLUX.1 latent space (Z-Image uses the same autoencoder). "+ f"The VAE given is a {type(vae_info.model).__name__} with a different latent "+ "normalisation."+ )+ effective_tile_size = tile_size if tiled else Noneestimated_working_memory = estimate_vae_working_memory_flux(- operation="encode", image_tensor=image_tensor, vae=vae_info.model, device=vae_info.compute_device- operation="encode", image_tensor=image_tensor, vae=vae_info.model, tile_size=effective_tile_size++ operation="encode",++ image_tensor=image_tensor,++ vae=vae_info.model,++ tile_size=effective_tile_size,++ device=vae_info.compute_device,)+ # Seeded here rather than by the caller on purpose: an OOM retry calls this again, and a+ # generator held outside would already have been drawn from by the attempt that failed, so+ # the retry would produce a different latent than a directly tiled run.- generator = torch.Generator(device=TorchDevice.choose_torch_device()).manual_seed(0)+ generator = torch.Generator(device=vae_info.compute_device).manual_seed(0)with vae_info.model_on_device(working_mem_bytes=estimated_working_memory) as (_, vae):- assert isinstance(vae, AutoEncoder)+ assert isinstance(vae, AutoencoderKL)vae_dtype = next(iter(vae.parameters())).dtype- image_tensor = image_tensor.to(device=TorchDevice.choose_torch_device(), dtype=vae_dtype)+ # The VAE's own device, as in the decode nodes: a cpu_only VAE (or another worker's GPU)+ # is not the session device, and encoding there would fail or run on the wrong card (#9373).+ image_tensor = image_tensor.to(device=vae_info.compute_device, dtype=vae_dtype)- latents = vae.encode(image_tensor, sample=True, generator=generator)- return latents+ with scoped_vae_tiling(vae, effective_tile_size):+ latents = vae.encode(image_tensor).latent_dist.sample(generator)+ # `AutoencoderKL` leaves the scaling to the caller; `shift_factor` is None on a+ # plain SD-style config, where absent means no shift.+ shift_factor = getattr(vae.config, "shift_factor", None)+ if shift_factor is not None:+ latents = latents - shift_factor+ return latents * vae.config.scaling_factor@torch.no_grad()def invoke(self, context: InvocationContext) -> LatentsOutput:diff --cc invokeai/app/invocations/vae/wan_latents_to_video.pyindex 2658a33ff6,ae1b0754a2..b63ad36694--- a/invokeai/app/invocations/vae/wan_latents_to_video.py+++ b/invokeai/app/invocations/vae/wan_latents_to_video.py@@@ -35,10 -35,11 +35,14 @@@ from invokeai.app.services.shared.invocfrom invokeai.app.util.video_encoding import make_mp4_writerfrom invokeai.backend.model_manager.load.model_cache.utils import get_effective_devicefrom invokeai.backend.util.devices import TorchDevice+ from invokeai.backend.util.qwen_image_vae import (+ patch_qwen_image_vae_tiling,+ resolve_qwen_image_vae_tile_size,+ )-from invokeai.backend.util.vae_working_memory import estimate_vae_working_memory_wan+from invokeai.backend.util.vae_working_memory import (+ estimate_vae_working_memory_wan,+ should_pretile_vae_decode,+)from invokeai.backend.wan.vae_decode import iter_wan_vae_decode_chunks@@@ -132,23 -133,34 +136,28 @@@ class WanLatentsToVideoInvocation(BaseIstreaming=optimize_memory,)# Long/high-res clips can need a working set no card fits. When the full-frame- # estimate would claim most of the VAE's device, fall back to spatial tiling and- # budget for the tiled working set instead. (A cpu_only VAE runs in system RAM,- # estimate exceeds the execution device's total VRAM, fall back to spatial tiling- # and budget for the tiled working set instead. (A cpu_only VAE runs in system- # RAM, where the working set is not the constraint.)- use_tiling = False++ # estimate would claim most of what the VAE's device keeps resident, fall back to spatial++ # tiling and budget for the tiled working set instead. (A cpu_only VAE runs in system RAM,+ # where the working set is not the constraint; the helper never tiles off-GPU.)+ use_tiling = context.config.get().auto_tiled_decode and should_pretile_vae_decode(+ vae_info.compute_device, estimated_working_memory+ )+ tile_size: int | None = None- if not getattr(vae_info.config, "cpu_only", None):- exec_device = TorchDevice.choose_torch_device()- total_vram: int | None = None- if exec_device.type == "cuda":- total_vram = torch.cuda.get_device_properties(exec_device).total_memory- elif exec_device.type == "xpu":- total_vram = torch.xpu.get_device_properties(exec_device).total_memory- if total_vram is not None and estimated_working_memory > 0.9 * total_vram:- use_tiling = True- # Resolved against the module constant, not read off `vae_info.model`: that is the- # cache's shared instance, so its current geometry is whatever the last invocation- # 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(- operation="decode",- vae=vae_info.model,- pixel_height=h_pixel,- pixel_width=w_pixel,- pixel_frames=t_pixel,- tile_size=tile_size,- streaming=False,- )+ if use_tiling:- tile_size = int(getattr(vae_info.model, "tile_sample_min_height", 256))++ # Resolved against the module constant, not read off `vae_info.model`: that is the++ # cache's shared instance, so its current geometry is whatever the last invocation++ # 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(+ operation="decode",+ vae=vae_info.model,+ pixel_height=h_pixel,+ pixel_width=w_pixel,+ pixel_frames=t_pixel,+ tile_size=tile_size,+ streaming=False,+ )tmp = tempfile.NamedTemporaryFile(prefix="invokeai_wan_video_", suffix=".mp4", delete=False)tmp.close()diff --cc invokeai/app/invocations/vae/z_image_image_to_latents.pyindex 6a85f62f1a,21e7d91e73..d3aaa13513--- a/invokeai/app/invocations/vae/z_image_image_to_latents.py+++ b/invokeai/app/invocations/vae/z_image_image_to_latents.py@@@ -16,14 -14,12 +14,11 @@@ from invokeai.app.invocations.fields imfrom invokeai.app.invocations.model import VAEFieldfrom invokeai.app.invocations.primitives import LatentsOutputfrom invokeai.app.services.shared.invocation_context import InvocationContext- from invokeai.backend.flux.modules.autoencoder import AutoEncoder as FluxAutoEncoderfrom invokeai.backend.model_manager.load.load_base import LoadedModelfrom invokeai.backend.stable_diffusion.diffusers_pipeline import image_resized_to_grid_as_tensor-from invokeai.backend.util.devices import TorchDevice+ from invokeai.backend.util.vae_tiling_scope import MIN_TILE_SAMPLE_SIZE, scoped_vae_tilingfrom invokeai.backend.util.vae_working_memory import estimate_vae_working_memory_flux- # Z-Image can use either the Diffusers AutoencoderKL or the FLUX AutoEncoder- ZImageVAE = Union[AutoencoderKL, FluxAutoEncoder]-@invocation("z_image_i2l",@@@ -52,7 -69,7 +68,8 @@@ class ZImageImageToLatentsInvocation(Baoperation="encode",image_tensor=image_tensor,vae=vae_info.model,+ tile_size=effective_tile_size,+ device=vae_info.compute_device,)with vae_info.model_on_device(working_mem_bytes=estimated_working_memory) as (_, vae):@@@ -63,29 -79,22 +79,24 @@@)vae_dtype = next(iter(vae.parameters())).dtype- image_tensor = image_tensor.to(device=TorchDevice.choose_torch_device(), dtype=vae_dtype)+ # The VAE's own device, as in the decode nodes: a cpu_only VAE (or another worker's GPU)+ # is not the session device, and encoding there would fail or run on the wrong card (#9373).+ image_tensor = image_tensor.to(device=vae_info.compute_device, dtype=vae_dtype)- with torch.inference_mode():- if isinstance(vae, FluxAutoEncoder):- # FLUX VAE handles scaling internally- generator = torch.Generator(device=vae_info.compute_device).manual_seed(0)- latents = vae.encode(image_tensor, sample=True, generator=generator)- else:- # AutoencoderKL - needs manual scaling- vae.disable_tiling()- image_tensor_dist = vae.encode(image_tensor).latent_dist- latents: torch.Tensor = image_tensor_dist.sample().to(dtype=vae.dtype)-- # Apply scaling_factor and shift_factor from VAE config- # Z-Image uses: latents = (latents - shift_factor) * scaling_factor- scaling_factor = vae.config.scaling_factor- shift_factor = getattr(vae.config, "shift_factor", None)-- if shift_factor is not None:- latents = latents - shift_factor- latents = latents * scaling_factor+ # The VAE belongs to the model cache and is shared with the decode node and with every+ # other node that reaches this class. Tiling is a property of this one encode, so the+ # state is scoped and restored rather than switched off by hand and left behind.+ with torch.inference_mode(), scoped_vae_tiling(vae, effective_tile_size):+ latents: torch.Tensor = vae.encode(image_tensor).latent_dist.sample().to(dtype=vae.dtype)++ # Apply scaling_factor and shift_factor from VAE config.+ # Z-Image uses: latents = (latents - shift_factor) * scaling_factor+ scaling_factor = vae.config.scaling_factor+ shift_factor = getattr(vae.config, "shift_factor", None)++ if shift_factor is not None:+ latents = latents - shift_factor+ latents = latents * scaling_factorreturn latentsdiff --cc invokeai/app/invocations/vae/z_image_latents_to_image.pyindex dadf047a40,eae50c5795..2c5055402f--- a/invokeai/app/invocations/vae/z_image_latents_to_image.py+++ b/invokeai/app/invocations/vae/z_image_latents_to_image.py@@@ -21,16 -18,9 +18,12 @@@ from invokeai.app.services.shared.invocfrom invokeai.backend.stable_diffusion.extensions.seamless import SeamlessExtfrom invokeai.backend.util.devices import TorchDevicefrom invokeai.backend.util.oom import is_oom_error- from invokeai.backend.util.vae_tiling_scope import scoped_vae_tiling+ from invokeai.backend.util.vae_tiling_scope import MIN_TILE_SAMPLE_SIZE, scoped_vae_tiling-from invokeai.backend.util.vae_working_memory import estimate_vae_working_memory_flux+from invokeai.backend.util.vae_working_memory import (+ estimate_vae_working_memory_flux,+ should_pretile_vae_decode,+)- # Z-Image can use either the Diffusers AutoencoderKL or the FLUX AutoEncoder- ZImageVAE = Union[AutoencoderKL, FluxAutoEncoder]-@invocation("z_image_l2i",@@@ -62,9 -57,7 +60,8 @@@ class ZImageLatentsToImageInvocation(Ba"Ensure you are using a compatible VAE model.")- is_flux_vae = isinstance(vae_info.model, FluxAutoEncoder)- use_tiling = self.tiled or context.config.get().force_tiled_decode+ config = context.config.get()+ use_tiling = self.tiled or config.force_tiled_decode# Estimate working memory needed for VAE decodeestimated_working_memory = estimate_vae_working_memory_flux(@@@ -72,26 -65,12 +69,26 @@@image_tensor=latents,vae=vae_info.model,tile_size=self.tile_size if use_tiling else None,+ device=vae_info.compute_device,)+ if (+ not use_tiling+ and config.auto_tiled_decode+ and should_pretile_vae_decode(vae_info.compute_device, estimated_working_memory)+ ):+ use_tiling = True+ estimated_working_memory = estimate_vae_working_memory_flux(+ operation="decode",+ image_tensor=latents,+ vae=vae_info.model,+ tile_size=self.tile_size,+ device=vae_info.compute_device,+ )- # FLUX VAE doesn't support seamless, so only apply for AutoencoderKL- seamless_context = (- nullcontext() if is_flux_vae else SeamlessExt.static_patch_model(vae_info.model, self.vae.seamless_axes)- )+ # Seamless applies to every VAE this node accepts. It used to be skipped for the FLUX+ # autoencoder, which had no circular-padding path -- that class is gone, and a standalone+ # FLUX VAE now honours the axes the UI has always offered for it.+ seamless_context = SeamlessExt.static_patch_model(vae_info.model, self.vae.seamless_axes)with seamless_context, vae_info.model_on_device(working_mem_bytes=estimated_working_memory) as (_, vae):context.util.signal_progress("Running VAE")diff --cc invokeai/backend/util/vae_working_memory.pyindex f1b321a20a,4aff57b3b7..c4c16bd876--- a/invokeai/backend/util/vae_working_memory.py+++ b/invokeai/backend/util/vae_working_memory.py@@@ -8,71 -8,10 +8,71 @@@ from diffusers.models.autoencoders.autofrom diffusers.models.autoencoders.autoencoder_tiny import AutoencoderTinyfrom invokeai.app.invocations.constants import LATENT_SCALE_FACTOR- from invokeai.backend.flux.modules.autoencoder import AutoEncoder, resolve_tile_size+from invokeai.backend.util import wddmfrom invokeai.backend.util.attention import sdpa_score_matrix_bytesfrom invokeai.backend.util.devices import TorchDevice+from invokeai.backend.util.logging import InvokeAILogger+ from invokeai.backend.util.vae_tiling_scope import resolve_tile_size+# Share of the device's memory an untiled decode may claim before the decode nodes tile it up front (see+# `should_pretile_vae_decode`). High enough that common resolutions on common cards stay untiled -- tiled output is+# not pixel-identical -- and low enough that a decode no card of that size can hold is tiled before it starts.+VAE_PRETILE_VRAM_FRACTION = 0.9+++def should_pretile_vae_decode(+ device: torch.device, full_decode_bytes: int, vram_fraction: float = VAE_PRETILE_VRAM_FRACTION+) -> bool:+ """Whether a decode should be tiled up front because its untiled working memory would claim more than+ ``vram_fraction`` of the memory ``device`` will keep resident.++ Waiting for an out-of-memory error does not work everywhere: on Windows, drivers page an allocation that does not+ fit into system memory instead of failing it (always for ROCm, by default for NVIDIA's sysmem fallback), and the+ decode just runs very slowly. ``device`` is where the VAE runs: a ``cpu_only`` VAE (and MPS, sharing system+ memory) is never tiled on these grounds.++ On Windows the ceiling is the video-memory budget rather than the card's nameplate total -- the budget is the point+ past which Windows pages this process out. With one correction: a budget *below* what this process keeps resident is+ Windows asking it to trim itself, and the cache does exactly that to honour the reservation, so the ceiling is then+ that residency. Measured on an RX 9060 XT (16 GB): with Invoke holding 12 GiB and nothing else on the card the+ budget read 7.62 GiB, and comparing against that tiled a 7.0 GiB decode that fits, changing output that had been+ pixel-identical.++ Residency, not ``CurrentUsage``: that also counts what Windows has already paged out, which a foreign process forces+ exactly when the budget carries its pressure (next to an 8 GiB holder the budget stepped down to 7.58 GiB while our+ ``CurrentUsage`` kept growing past our 7.70 GiB in VRAM). So the override is ``CurrentUsage`` minus this process's+ paged bytes, and where either is unknown -- ``CurrentUsage`` beyond the card, or no counter reading -- the budget+ alone decides (so a transient counter failure can tile a decode that the next run leaves untiled).++ Known limit: the budget reacts to a foreign process only once this process grows into the memory it holds -- it+ stays at 15.09 GiB next to an 8 GiB holder while Invoke holds little -- torch's free figure ignores other processes,+ and the adapter-wide performance counter contradicts itself between processes (15.66 GiB read from the holding+ process against 0.18 GiB from another, same instance, same instant). A decode sized before that point can still+ page, and the end-of-session paging warning is what surfaces it.+ """+ if device.type == "cuda":+ total_bytes = torch.cuda.get_device_properties(device).total_memory+ local = wddm.local_video_memory(device)+ if local is not None:+ budget_bytes, usage_bytes = local+ ceiling_bytes = budget_bytes+ paged = wddm.paged_bytes(device) if usage_bytes is not None else None+ if paged is not None:+ ceiling_bytes = max(budget_bytes, usage_bytes - paged)+ total_bytes = min(total_bytes, ceiling_bytes)+ elif device.type == "xpu":+ total_bytes = torch.xpu.get_device_properties(device).total_memory+ else:+ return False+ if full_decode_bytes <= vram_fraction * total_bytes:+ return False+ InvokeAILogger.get_logger(__name__).debug(+ f"Decoding in tiles: an untiled decode would need ~{full_decode_bytes / 2**30:.1f} GiB of working memory, more "+ f"than {vram_fraction:.0%} of the {total_bytes / 2**30:.1f} GiB the GPU keeps resident."+ )+ return True++# The diffusers AutoencoderKL (SD1/SDXL, SD3, CogView4) and the FLUX.1 AutoEncoder run the same# mid-block self-attention as the FLUX.2 VAE: one head over the 512-channel width, on the# 8x-downsampled grid. Where that attention runs on the math kernel (see `sdpa_score_matrix_bytes`)@@@ -214,9 -151,8 +220,9 @@@ _VAE_MOMENT_CHANNELS_PER_LATENT =def estimate_vae_working_memory_flux(operation: Literal["encode", "decode"],image_tensor: torch.Tensor,- vae: AutoEncoder,+ vae: AutoencoderKL,tile_size: int | None = None,+ device: torch.device | None = None,) -> int:"""Estimate the working memory required by the invocation in bytes.@@@ -226,11 -162,9 +232,12 @@@tiling does *not* bound are added on top. `tile_size <= 0` is the nodes' "use the default"sentinel; see `resolve_tile_size`.- Only `decode` tiles: `AutoEncoder.encode` never consults `use_tiling`. So a `tile_size` with- `operation="encode"` would price a tiled encode that cannot happen, and no call site passes one.+ Both operations tile. The tile-bounded term is the same for either; what tiling does *not*+ bound differs, so the residual is chosen by `operation` -- see `_FLUX_VAE_TILED_IMAGE_COPIES`+ for the decode side.++ `device` is where the VAE will run (a `cpu_only` VAE runs on the CPU); it picks the convolution+ backend's constant. Defaults to the session device."""latent_scale_factor_for_operation = LATENT_SCALE_FACTOR if operation == "decode" else 1diff --cc tests/app/invocations/test_anima_vae.pyindex 766fa4319e,a44d37b496..76c946b764--- a/tests/app/invocations/test_anima_vae.py+++ b/tests/app/invocations/test_anima_vae.py@@@ -99,6 -97,50 +99,35 @@@ class TestEstimateVaeWorkingMemoryAnimaassert fp32 == 2 * fp16+ class TestTheTiledEncodeResidual:+ """A tiled encode does not bound the frame it slices from, nor the moments it assembles.++ Without those terms the estimate is flat in the image size while the measurement grows about+ 4 bytes per pixel: measured on a 4090 it fell from 1.07x headroom at 1024px to 0.69x at 4096px,+ i.e. the cache promised less than the encode used -- and this node has no tiled retry, so that+ is a failed generation rather than a slower one.+ """++ def test_the_tiled_encode_estimate_grows_with_the_frame(self):+ vae = _mock_vae()+ estimates = [+ estimate_vae_working_memory_anima("encode", torch.zeros(1, 3, edge, edge), vae, tile_size=256)+ for edge in (1024, 4096)+ ]+ assert estimates[1] > estimates[0], "the un-bounded part of a tiled encode is not priced"++ def test_the_tiled_decode_estimate_is_left_flat(self):+ """Stated rather than assumed: the decode has the same kind of un-bounded assembly and does+ not price it either. That is pre-existing -- this node has tiled since it was written -- and+ is deliberately not changed in a diff about the encode."""+ vae = _mock_vae()+ estimates = [+ estimate_vae_working_memory_anima("decode", torch.zeros(1, 16, edge // 8, edge // 8), vae, tile_size=256)+ for edge in (1024, 4096)+ ]+ assert estimates[0] == estimates[1]++-class TestUseTiledDecode:- @pytest.mark.parametrize("device_type", ["cpu", "mps"])- def test_non_cuda_never_tiles(self, device_type):- assert AnimaLatentsToImageInvocation._use_tiled_decode(torch.device(device_type), 10**12) is False-- def test_cuda_flips_at_70_percent_of_total_vram(self):- total_vram = 8 * 2**30- boundary = 0.7 * total_vram- device = torch.device("cuda")- with patch("torch.cuda.get_device_properties", return_value=MagicMock(total_memory=total_vram)) as mock_props:- assert AnimaLatentsToImageInvocation._use_tiled_decode(device, math.floor(boundary)) is False- assert AnimaLatentsToImageInvocation._use_tiled_decode(device, math.ceil(boundary) + 1) is True- mock_props.assert_called_with(device)--def _build_decode_mocks(latents: torch.Tensor, decoded: torch.Tensor, vae_class: type = AutoencoderKLWan):"""Mock the Anima VAE decode path: a spec'd VAE, its LoadedModel wrapper, and the invocationcontext, wired so `AnimaLatentsToImageInvocation.invoke` runs end-to-end on CPU."""diff --cc tests/app/invocations/test_flux_vae_decode_tiling.pyindex c80e1c3a5f,1f28fbe1bf..2b6f998067--- a/tests/app/invocations/test_flux_vae_decode_tiling.py+++ b/tests/app/invocations/test_flux_vae_decode_tiling.py@@@ -74,54 -112,31 +112,56 @@@ class TestAskingForTiling"""A tiled decode reserved for a single pass is the OOM the retry exists to avoid, and anuntiled decode reserved for a tile evicts models it did not need to."""path = "invokeai.app.invocations.vae.flux_vae_decode.estimate_vae_working_memory_flux"- _, _, context = _build_decode_mocks(- torch.zeros(1, 16, 64, 64), torch.zeros(1, 3, 512, 512), force_tiled_decode=force_tiled_decode+ vae = flux_shaped_vae()+ _, context, _ = _build_decode_mocks(+ vae, torch.zeros(1, 16, 64, 64), torch.zeros(1, 3, 512, 512), force_tiled_decode=force_tiled_decode)with patch(path, return_value=1024) as estimate:- _build_invocation().invoke(context)+ _build_invocation(tiled=tiled, tile_size=256 if tiled else 0).invoke(context)assert estimate.call_args.kwargs["tile_size"] == expected_tile_size+ @pytest.mark.parametrize("auto", [True, False], ids=["auto-tiled-decode-on", "auto-tiled-decode-off"])- def test_a_decode_too_large_for_its_gpu_is_tiled_up_front_unless_switched_off(self, auto):++ def test_a_decode_too_large_for_its_gpu_is_tiled_up_front_unless_switched_off(self, auto, flux_shaped_vae):++ """On Windows an allocation that does not fit is paged rather than refused, so the OOM retry never fires and++ the decision has to be made from the estimate alone."""+ module = "invokeai.app.invocations.vae.flux_vae_decode"- vae, vae_info, context = _build_decode_mocks(torch.zeros(1, 16, 64, 64), torch.zeros(1, 3, 512, 512))++ vae_info, context, tiling_state = _build_decode_mocks(++ flux_shaped_vae(), torch.zeros(1, 16, 64, 64), torch.zeros(1, 3, 512, 512)++ )+ context.config.get.return_value.auto_tiled_decode = auto+ with (+ patch(f"{module}.estimate_vae_working_memory_flux", side_effect=[20 * 2**30, 2 * 2**30]) as estimate,+ patch(f"{module}.should_pretile_vae_decode", return_value=True) as pretile,+ ):+ _build_invocation().invoke(context)++ if auto:+ pretile.assert_called_once_with(vae_info.compute_device, 20 * 2**30)+ assert estimate.call_args.kwargs["tile_size"] == 0+ vae_info.model_on_device.assert_called_once_with(working_mem_bytes=2 * 2**30)- vae.enable_tiling.assert_called_once_with(tile_sample_min_size=DEFAULT_TILE_SAMPLE_MIN_SIZE)++ assert tiling_state[0]["use_tiling"] is True++ assert tiling_state[0]["tile_sample_min_size"] == DEFAULT_TILE_SAMPLE_MIN_SIZE+ else:+ pretile.assert_not_called()- vae.disable_tiling.assert_called_once()--- class TestDiffusersLayoutVae:- def test_a_diffusers_layout_flux_vae_reserves_its_working_memory(self):- """It runs the same network; a decode with nothing reserved is the one Windows pages instead of failing."""- vae, vae_info, context = _build_decode_mocks(- torch.zeros(1, 16, 64, 64), torch.zeros(1, 3, 512, 512), vae_class=AutoencoderKL- )- vae.config = MagicMock(scaling_factor=0.3611, shift_factor=0.1159)- vae.decode.return_value = (torch.zeros(1, 3, 512, 512),)-- _build_invocation().invoke(context)-- (reservation,) = vae_info.model_on_device.call_args.kwargs.values()- assert reservation > 0++ assert tiling_state[0]["use_tiling"] is False+class TestOomFallback:- def test_an_untiled_oom_retries_once_tiled_and_says_so(self):+ def test_an_untiled_oom_retries_once_tiled_and_says_so(self, flux_shaped_vae):+ vae = flux_shaped_vae()decoded = torch.zeros(1, 3, 512, 512)- vae, _, context = _build_decode_mocks(torch.zeros(1, 16, 64, 64), decoded)- vae.decode.side_effect = [torch.cuda.OutOfMemoryError("CUDA out of memory"), decoded]+ _, context, state = _build_decode_mocks(vae, torch.zeros(1, 16, 64, 64), decoded)+ calls = {"n": 0}+ real = vae.decode.side_effect++ def fail_then_succeed(latents_arg, return_dict=True):+ calls["n"] += 1+ result = real(latents_arg, return_dict=return_dict)+ if calls["n"] == 1:+ raise torch.cuda.OutOfMemoryError("CUDA out of memory")+ return result++ vae.decode = MagicMock(side_effect=fail_then_succeed)result = _build_invocation().invoke(context)diff --cc tests/app/invocations/test_flux_vae_encode_tiling.pyindex 0000000000,81cdc37579..19413922d9mode 000000,100644..100644--- a/tests/app/invocations/test_flux_vae_encode_tiling.py+++ b/tests/app/invocations/test_flux_vae_encode_tiling.py@@@ -1,0 -1,202 +1,204 @@@+ """Tiling on the FLUX.1 image-to-latents node, and the OOM fallback that makes it worth having.++ An untiled encode of the frame an upscale graph produces is not merely large, it is quadratic: the+ FLUX autoencoder's mid-block attention is a single head over the whole latent grid, so at 3072px it+ reserves 18.8 GiB on a 4090 where a tiled encode reserves 0.81 GiB and finishes faster. On a 16 GiB+ card the untiled pass does not complete at all.++ The node had no tiling of any kind before the FLUX.1 VAE became a diffusers `AutoencoderKL` -- the+ hand-rolled class implemented a tiled decode and never a tiled encode, and `encode()` did not so+ much as consult the flag.++ The VAE is a real, tiny `AutoencoderKL` (`conftest.flux_shaped_vae`), so the tiling state asserted+ here is state that actually existed rather than a recorded call.++ **The images are 768px on purpose.** `AutoencoderKL._encode` tiles only when a side is strictly+ greater than `tile_sample_min_size`, so a 512px image against the default 512px tile takes the+ single-pass path -- and a cell named for the tiled path would assert a flag while testing the+ untiled one.+ """++ from unittest.mock import MagicMock, patch++ import pytest+ import torch++ from invokeai.app.invocations.vae.flux_vae_encode import FluxVaeEncodeInvocation+ from invokeai.backend.util.vae_tiling_scope import DEFAULT_TILE_SAMPLE_MIN_SIZE+++ @pytest.fixture(autouse=True)+ def _pin_to_cpu(monkeypatch):+ """The node moves its input to `choose_torch_device()`, which is CUDA on a machine that has one,+ while the VAE under test stays on the CPU."""+ monkeypatch.setattr(+ "invokeai.backend.util.devices.TorchDevice.choose_torch_device", staticmethod(lambda: torch.device("cpu"))+ )+++ def _build_encode_mocks(vae, image: torch.Tensor, force_tiled_decode: bool = False):+ tiling_state: list[dict] = []+ real_encode = vae.encode++ def record_and_encode(x, return_dict=True):+ tiling_state.append({"use_tiling": vae.use_tiling, "tile_sample_min_size": vae.tile_sample_min_size})+ return real_encode(x, return_dict=return_dict)++ vae.encode = MagicMock(side_effect=record_and_encode)++ vae_info = MagicMock()+ vae_info.model = vae++ # A real device: the node places the image and the generator on the VAE's own device.++ vae_info.compute_device = torch.device("cpu")+ cm = MagicMock()+ cm.__enter__ = MagicMock(return_value=(None, vae))+ cm.__exit__ = MagicMock(return_value=None)+ vae_info.model_on_device.return_value = cm++ context = MagicMock()+ context.models.load.return_value = vae_info+ context.images.get_pil.return_value = MagicMock()+ # A bare MagicMock config would read as truthy and silently tile everything.+ context.config.get.return_value.force_tiled_decode = force_tiled_decode+ # `LatentsOutput.build` validates this as a string.+ context.tensors.save.return_value = "test_latents"+ return vae_info, context, tiling_state+++ def _invoke(context, image: torch.Tensor, tiled: bool = False, tile_size: int = 0):+ invocation = FluxVaeEncodeInvocation.model_construct(+ image=MagicMock(image_name="test.png"),+ vae=MagicMock(vae=MagicMock()),+ tiled=tiled,+ tile_size=tile_size,+ )+ with patch("invokeai.app.invocations.vae.flux_vae_encode.image_resized_to_grid_as_tensor", return_value=image[0]):+ return invocation.invoke(context)+++ class TestAskingForTiling:+ def test_the_default_encodes_untiled(self, flux_shaped_vae):+ vae = flux_shaped_vae()+ _, context, state = _build_encode_mocks(vae, torch.zeros(1, 3, 768, 768))+ _invoke(context, torch.zeros(1, 3, 768, 768))+ assert state[0]["use_tiling"] is False++ def test_the_node_field_reaches_the_tiled_path(self, flux_shaped_vae):+ vae = flux_shaped_vae()+ _, context, state = _build_encode_mocks(vae, torch.zeros(1, 3, 768, 768))+ _invoke(context, torch.zeros(1, 3, 768, 768), tiled=True, tile_size=256)+ assert state[0]["use_tiling"] is True+ assert state[0]["tile_sample_min_size"] == 256++ def test_the_config_flag_reaches_the_tiled_path(self, flux_shaped_vae):+ """`force_tiled_decode` is named for the decode but every encode node already reads it --+ `image_to_latents` and `qwen_image_i2l` both do, and a second setting would say nothing new."""+ vae = flux_shaped_vae()+ _, context, state = _build_encode_mocks(vae, torch.zeros(1, 3, 768, 768), force_tiled_decode=True)+ _invoke(context, torch.zeros(1, 3, 768, 768))+ assert state[0]["use_tiling"] is True+ assert state[0]["tile_sample_min_size"] == DEFAULT_TILE_SAMPLE_MIN_SIZE++ def test_the_tiling_state_is_restored_afterwards(self, flux_shaped_vae):+ """The VAE is the cache's, shared with the decode node, Z-Image, PiD and the ControlNet+ extension -- most of which never touch the flag and would silently inherit it."""+ vae = flux_shaped_vae()+ _, context, _ = _build_encode_mocks(vae, torch.zeros(1, 3, 768, 768))+ before = (vae.use_tiling, vae.tile_sample_min_size, vae.tile_latent_min_size)+ _invoke(context, torch.zeros(1, 3, 768, 768), tiled=True, tile_size=256)+ assert (vae.use_tiling, vae.tile_sample_min_size, vae.tile_latent_min_size) == before++ @pytest.mark.parametrize("tiled,tile_size,expected", [(False, 0, None), (True, 256, 256), (True, 0, 0)])+ def test_the_reservation_matches_the_encode_that_will_run(self, flux_shaped_vae, tiled, tile_size, expected):+ vae = flux_shaped_vae()+ _, context, _ = _build_encode_mocks(vae, torch.zeros(1, 3, 768, 768))+ path = "invokeai.app.invocations.vae.flux_vae_encode.estimate_vae_working_memory_flux"+ with patch(path, return_value=1024) as estimate:+ _invoke(context, torch.zeros(1, 3, 768, 768), tiled=tiled, tile_size=tile_size)+ assert estimate.call_args.kwargs["tile_size"] == expected+++ class TestTheCallersOutsideThisNode:+ def test_the_shared_helper_defaults_to_untiled(self, flux_shaped_vae):+ """`flux_denoise`, the InstantX ControlNet extension and PiD Upscale all call `vae_encode`+ positionally with no tiling arguments. They pass conditioning images at generation size, so+ the default has to stay what it was."""+ vae = flux_shaped_vae()+ vae_info, _, state = _build_encode_mocks(vae, torch.zeros(1, 3, 256, 256))++ FluxVaeEncodeInvocation.vae_encode(vae_info=vae_info, image_tensor=torch.zeros(1, 3, 256, 256))++ assert state[0]["use_tiling"] is False+++ class TestOomFallback:+ def test_an_untiled_oom_retries_once_tiled_and_says_so(self, flux_shaped_vae):+ vae = flux_shaped_vae()+ _, context, state = _build_encode_mocks(vae, torch.zeros(1, 3, 768, 768))+ calls = {"n": 0}+ record = vae.encode.side_effect++ def fail_then_succeed(x, return_dict=True):+ calls["n"] += 1+ result = record(x, return_dict=return_dict)+ if calls["n"] == 1:+ raise torch.cuda.OutOfMemoryError("CUDA out of memory")+ return result++ vae.encode = MagicMock(side_effect=fail_then_succeed)++ _invoke(context, torch.zeros(1, 3, 768, 768))++ assert vae.encode.call_count == 2+ assert [call["use_tiling"] for call in state] == [False, True]+ context.util.signal_progress.assert_any_call("VAE encode ran out of memory, retrying tiled")+ assert "not identical to an untiled encode" in context.logger.warning.call_args[0][0]++ def test_the_retry_draws_the_same_noise_as_a_directly_tiled_encode(self, flux_shaped_vae):+ """The encode samples from the latent distribution with a fixed seed. If the generator were+ created by the caller rather than inside `vae_encode`, the attempt that failed would already+ have drawn from it, and the retry would return a different latent than asking for tiling up+ front -- a difference nothing downstream could attribute to an OOM that was handled."""+ image = torch.rand(1, 3, 768, 768) * 2 - 1++ vae = flux_shaped_vae()+ _, retry_context, _ = _build_encode_mocks(vae, image)+ record = vae.encode.side_effect+ calls = {"n": 0}++ def fail_then_succeed(x, return_dict=True):+ calls["n"] += 1+ result = record(x, return_dict=return_dict)+ if calls["n"] == 1:+ raise torch.cuda.OutOfMemoryError("CUDA out of memory")+ return result++ vae.encode = MagicMock(side_effect=fail_then_succeed)+ _invoke(retry_context, image)++ # The same weights, so any difference in the result is the noise draw and nothing else.+ direct_vae = flux_shaped_vae()+ direct_vae.load_state_dict(vae.state_dict())+ _, direct_context, _ = _build_encode_mocks(direct_vae, image)+ _invoke(direct_context, image, tiled=True, tile_size=0)++ after_retry = retry_context.tensors.save.call_args.kwargs["tensor"]+ directly_tiled = direct_context.tensors.save.call_args.kwargs["tensor"]+ assert torch.equal(after_retry, directly_tiled)++ def test_an_oom_while_already_tiled_reraises(self, flux_shaped_vae):+ vae = flux_shaped_vae()+ _, context, state = _build_encode_mocks(vae, torch.zeros(1, 3, 768, 768), force_tiled_decode=True)+ record = vae.encode.side_effect++ def record_then_fail(x, return_dict=True):+ record(x, return_dict=return_dict)+ raise torch.cuda.OutOfMemoryError("CUDA out of memory")++ vae.encode = MagicMock(side_effect=record_then_fail)++ with pytest.raises(torch.cuda.OutOfMemoryError):+ _invoke(context, torch.zeros(1, 3, 768, 768))++ assert vae.encode.call_count == 1+ assert [call["use_tiling"] for call in state] == [True]diff --cc tests/app/invocations/test_wan_working_memory.pyindex 82ed50cbb7,8732f2aada..108e2263f3--- a/tests/app/invocations/test_wan_working_memory.py+++ b/tests/app/invocations/test_wan_working_memory.py@@@ -297,13 -302,13 +303,16 @@@ class TestWanInvocationsRequestWorkingMvae.disable_tiling.assert_called_once()vae.decode.assert_not_called()- def test_latents_to_video_falls_back_to_tiling_when_estimate_exceeds_vram(self):+ @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 = 999vae_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 = autowith (patch(@@@ -322,22 -327,23 +331,29 @@@except Exception:pass- 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)+ if auto:+ assert mock_estimate.call_count == 2+ assert mock_estimate.call_args_list[1].kwargs["tile_size"] == 256- vae.enable_tiling.assert_called_once()++ # 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)- vae.disable_tiling.assert_called_once()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."""+ """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 (diff --cc tests/app/invocations/test_z_image_tiled_decode.pyindex 8e29b7795f,37f73fb8db..eb1bd744a0--- a/tests/app/invocations/test_z_image_tiled_decode.py+++ b/tests/app/invocations/test_z_image_tiled_decode.py@@@ -233,68 -302,48 +326,85 @@@ def _build_invocation(tiled: bool = Falclass TestTilingIsWired:- def test_the_default_decodes_untiled(self):- vae, _, context = _build_decode_mocks(torch.zeros(1, 16, 64, 64), torch.zeros(1, 3, 512, 512))+ def test_the_default_decodes_untiled(self, flux_shaped_vae):+ vae = flux_shaped_vae()+ _, context, state = _build_decode_mocks(vae, torch.zeros(1, 16, 64, 64), torch.zeros(1, 3, 512, 512))_build_invocation().invoke(context)- vae.disable_tiling.assert_called_once()- vae.enable_tiling.assert_not_called()+ assert state[0]["use_tiling"] is False- def test_the_node_field_reaches_the_tiled_path(self):- vae, _, context = _build_decode_mocks(torch.zeros(1, 16, 64, 64), torch.zeros(1, 3, 512, 512))+ def test_the_node_field_reaches_the_tiled_path(self, flux_shaped_vae):+ vae = flux_shaped_vae()+ _, context, state = _build_decode_mocks(vae, torch.zeros(1, 16, 64, 64), torch.zeros(1, 3, 512, 512))_build_invocation(tiled=True).invoke(context)- vae.enable_tiling.assert_called_once_with(tile_sample_min_size=DEFAULT_TILE_SAMPLE_MIN_SIZE)- vae.disable_tiling.assert_not_called()+ assert state[0]["use_tiling"] is True+ assert state[0]["tile_sample_min_size"] == DEFAULT_TILE_SAMPLE_MIN_SIZE- def test_force_tiled_decode_reaches_the_tiled_path(self):+ def test_force_tiled_decode_reaches_the_tiled_path(self, flux_shaped_vae):"""The config switch a small-VRAM user actually has; the node field is not the only way in."""- vae, _, context = _build_decode_mocks(- torch.zeros(1, 16, 64, 64), torch.zeros(1, 3, 512, 512), force_tiled_decode=True+ vae = flux_shaped_vae()+ _, context, state = _build_decode_mocks(+ vae, torch.zeros(1, 16, 64, 64), torch.zeros(1, 3, 512, 512), force_tiled_decode=True)_build_invocation().invoke(context)- vae.enable_tiling.assert_called_once_with(tile_sample_min_size=DEFAULT_TILE_SAMPLE_MIN_SIZE)+ assert state[0]["use_tiling"] is True+ assert state[0]["tile_sample_min_size"] == DEFAULT_TILE_SAMPLE_MIN_SIZE- def test_a_requested_tile_size_is_passed_through(self):- vae, _, context = _build_decode_mocks(torch.zeros(1, 16, 64, 64), torch.zeros(1, 3, 512, 512))+ def test_a_requested_tile_size_is_passed_through(self, flux_shaped_vae):+ vae = flux_shaped_vae()+ _, context, state = _build_decode_mocks(vae, torch.zeros(1, 16, 64, 64), torch.zeros(1, 3, 512, 512))_build_invocation(tiled=True, tile_size=384).invoke(context)- vae.enable_tiling.assert_called_once_with(tile_sample_min_size=384)+ assert state[0]["tile_sample_min_size"] == 384++ def test_the_tiling_state_is_restored_afterwards(self, flux_shaped_vae):+ """The VAE is shared with the encode node and with FLUX.1; a tiled decode must not leak."""+ vae = flux_shaped_vae()+ _, context, _ = _build_decode_mocks(vae, torch.zeros(1, 16, 64, 64), torch.zeros(1, 3, 512, 512))+ before = (vae.use_tiling, vae.tile_sample_min_size, vae.tile_latent_min_size)+ _build_invocation(tiled=True, tile_size=384).invoke(context)+ assert (vae.use_tiling, vae.tile_sample_min_size, vae.tile_latent_min_size) == before+ @pytest.mark.parametrize("auto", [True, False], ids=["auto-tiled-decode-on", "auto-tiled-decode-off"])- def test_a_decode_too_large_for_its_gpu_is_tiled_up_front_unless_switched_off(self, auto):++ def test_a_decode_too_large_for_its_gpu_is_tiled_up_front_unless_switched_off(self, auto, flux_shaped_vae):+ """Where the driver pages instead of raising an OOM, the retry below never fires: the estimate decides."""+ module = "invokeai.app.invocations.vae.z_image_latents_to_image"- vae, vae_info, context = _build_decode_mocks(torch.zeros(1, 16, 64, 64), torch.zeros(1, 3, 512, 512))++ vae_info, context, state = _build_decode_mocks(++ flux_shaped_vae(), torch.zeros(1, 16, 64, 64), torch.zeros(1, 3, 512, 512)++ )+ context.config.get.return_value.auto_tiled_decode = auto+ with (+ patch(f"{module}.estimate_vae_working_memory_flux", side_effect=[20 * 2**30, 2 * 2**30]) as estimate,+ patch(f"{module}.should_pretile_vae_decode", return_value=True) as pretile,+ ):+ _build_invocation().invoke(context)++ if auto:+ pretile.assert_called_once_with(vae_info.compute_device, 20 * 2**30)+ assert estimate.call_args.kwargs["tile_size"] == 0+ vae_info.model_on_device.assert_called_once_with(working_mem_bytes=2 * 2**30)- vae.enable_tiling.assert_called_once_with(tile_sample_min_size=DEFAULT_TILE_SAMPLE_MIN_SIZE)++ assert state[0]["use_tiling"] is True+ else:+ pretile.assert_not_called()+ assert estimate.call_count == 1- vae.disable_tiling.assert_called_once()++ assert state[0]["use_tiling"] is False+- def test_requested_tiling_skips_the_untiled_estimate(self):++ def test_requested_tiling_skips_the_untiled_estimate(self, flux_shaped_vae):+ module = "invokeai.app.invocations.vae.z_image_latents_to_image"- _, _, context = _build_decode_mocks(torch.zeros(1, 16, 64, 64), torch.zeros(1, 3, 512, 512))++ _, context, _ = _build_decode_mocks(++ flux_shaped_vae(), torch.zeros(1, 16, 64, 64), torch.zeros(1, 3, 512, 512)++ )+ with (+ patch(f"{module}.estimate_vae_working_memory_flux", return_value=2 * 2**30) as estimate,+ patch(f"{module}.should_pretile_vae_decode") as pretile,+ ):+ _build_invocation(tiled=True).invoke(context)+ assert estimate.call_count == 1+ pretile.assert_not_called()+@pytest.mark.parametrize("tiled,expected_tile_size", [(False, None), (True, 0)])- def test_the_estimate_is_tile_bounded_only_when_tiling(self, tiled, expected_tile_size):+ def test_the_estimate_is_tile_bounded_only_when_tiling(self, flux_shaped_vae, tiled, expected_tile_size):path = "invokeai.app.invocations.vae.z_image_latents_to_image.estimate_vae_working_memory_flux"- _, _, context = _build_decode_mocks(torch.zeros(1, 16, 64, 64), torch.zeros(1, 3, 512, 512))+ vae = flux_shaped_vae()+ _, context, _ = _build_decode_mocks(vae, torch.zeros(1, 16, 64, 64), torch.zeros(1, 3, 512, 512))with patch(path, return_value=1024) as estimate:_build_invocation(tiled=tiled).invoke(context)assert estimate.call_args.kwargs["tile_size"] == expected_tile_size@@@ -342,5 -410,54 +471,56 @@@ class TestOomFallbackwith pytest.raises(torch.cuda.OutOfMemoryError):_build_invocation(tiled=True).invoke(context)+ # One attempt, and it was already the tiled one -- retrying it tiled again would only burn+ # the time a second full decode costs before failing the same way.assert vae.decode.call_count == 1- vae.enable_tiling.assert_called_once()+ assert [call["use_tiling"] for call in state] == [True]+++ class TestTheEncodeNodeTiling:+ """The encode node called a bare `vae.disable_tiling()` and offered no way to ask for tiling.++ That line predates the node having any tiling fields; it was there to give the shared cached VAE+ a deterministic state, which the scope now does in both directions.+ """++ @staticmethod+ def _encode(vae, tiled: bool = False, tile_size: int = 0):+ seen: list[dict] = []+ real_encode = vae.encode++ def record(x, return_dict=True):+ seen.append({"use_tiling": vae.use_tiling, "tile_sample_min_size": vae.tile_sample_min_size})+ return real_encode(x, return_dict=return_dict)++ vae.encode = record++ vae_info = MagicMock()+ vae_info.model = vae++ # A real device: the node places the image on the VAE's own device rather than the session's.++ vae_info.compute_device = torch.device("cpu")+ cm = MagicMock()+ cm.__enter__ = MagicMock(return_value=(None, vae))+ cm.__exit__ = MagicMock(return_value=None)+ vae_info.model_on_device.return_value = cm++ with patch.object(TorchDevice, "choose_torch_device", return_value=torch.device("cpu")):+ ZImageImageToLatentsInvocation.vae_encode(+ vae_info=vae_info, image_tensor=torch.zeros(1, 3, 512, 512), tiled=tiled, tile_size=tile_size+ )+ return seen++ def test_the_default_encodes_untiled(self, flux_shaped_vae):+ vae = flux_shaped_vae()+ assert self._encode(vae)[0]["use_tiling"] is False++ def test_the_field_reaches_the_tiled_path_and_the_state_is_restored(self, flux_shaped_vae):+ vae = flux_shaped_vae()+ before = (vae.use_tiling, vae.tile_sample_min_size, vae.tile_latent_min_size)++ seen = self._encode(vae, tiled=True, tile_size=384)++ assert seen[0]["use_tiling"] is True+ assert seen[0]["tile_sample_min_size"] == 384+ # Shared with the decode node and with every FLUX.1 node, most of which never touch the flag.+ assert (vae.use_tiling, vae.tile_sample_min_size, vae.tile_latent_min_size) == before