Skip to content

Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.

feat(flux): load the FLUX.1 VAE as a diffusers AutoencoderKL, and tile its encode

Alexander Eichhorn326bdf1bd022
diff --git a/docs/src/content/docs/features/pid-decode.mdx b/docs/src/content/docs/features/pid-decode.mdx
index cc41cff505..1692ebdce5 100644
--- a/docs/src/content/docs/features/pid-decode.mdx
+++ b/docs/src/content/docs/features/pid-decode.mdx
@@ -78,7 +78,7 @@ Everything above describes PiD as a *decode* step: it needs the latent the model
It encodes your image with the FLUX VAE and hands the resulting latent to the PiD decoder, giving a 4× result in one pass — the PiD analogue of an ESRGAN / SUPIR upscale. Connect a FLUX VAE, a **FLUX** PiD decoder and the Gemma-2 encoder, and optionally give it a caption describing the image (the decoder is caption-conditioned; an empty caption is the cheapest option but usually the weaker result).
<Aside type="caution">
-This node is a **prototype** and FLUX-only in both directions: it requires InvokeAI's FLUX `AutoEncoder` VAE (a diffusers `AutoencoderKL`, e.g. Z-Image's, is rejected) and a FLUX PiD decoder. Since the input is a plain image rather than the generating model's own latent, results are less faithful than PiD used as a decode.
+This node is a **prototype** and FLUX-only in both directions: it requires the FLUX.1 VAE (which Z-Image also uses; a VAE of another family is rejected) and a FLUX PiD decoder. Since the input is a plain image rather than the generating model's own latent, results are less faithful than PiD used as a decode.
</Aside>
## Tips & limitations
diff --git a/invokeai/app/invocations/pid/pid_upscale.py b/invokeai/app/invocations/pid/pid_upscale.py
index 4ca46a8180..9db7864e72 100644
--- a/invokeai/app/invocations/pid/pid_upscale.py
+++ b/invokeai/app/invocations/pid/pid_upscale.py
@@ -37,8 +37,7 @@ from invokeai.app.invocations.model import Gemma2EncoderField, PiDDecoderField,
from invokeai.app.invocations.primitives import ImageOutput
from invokeai.app.invocations.vae.flux_vae_encode import FluxVaeEncodeInvocation
from invokeai.app.services.shared.invocation_context import InvocationContext
-from invokeai.backend.flux.modules.autoencoder import AutoEncoder
-from invokeai.backend.flux.util import get_flux_ae_params
+from invokeai.backend.flux.util import get_flux_ae_params, is_flux_family_vae
from invokeai.backend.model_manager.taxonomy import BaseModelType
from invokeai.backend.pid._src.networks.pid_net import PidNet
from invokeai.backend.pid.decode import (
@@ -72,9 +71,8 @@ class PiDUpscaleInvocation(BaseInvocation, WithMetadata, WithBoard):
image: ImageField = InputField(description="Image to upscale.")
vae: VAEField = InputField(
- description="FLUX AutoEncoder VAE. PiD upscale runs the FLUX backbone and applies FLUX VAE "
- "scaling, and the encode path only supports InvokeAI's FLUX AutoEncoder — a diffusers "
- "AutoencoderKL (e.g. Z-Image) is not supported here.",
+ description="The FLUX.1 VAE, which Z-Image also uses. PiD upscale runs the FLUX backbone "
+ "and undoes FLUX VAE scaling, so a VAE of another family is not accepted.",
input=Input.Connection,
)
gemma2_encoder: Gemma2EncoderField = InputField(
@@ -118,17 +116,19 @@ class PiDUpscaleInvocation(BaseInvocation, WithMetadata, WithBoard):
image_tensor = einops.rearrange(image_tensor, "c h w -> 1 c h w")
vae_info = context.models.load(self.vae.vae)
- # vae_encode + the FLUX scaling below only support InvokeAI's FLUX AutoEncoder. Reject any other
- # VAE (e.g. a Z-Image diffusers AutoencoderKL) up front with a clear error rather than failing on a
- # stripped assert inside vae_encode under `python -O`.
- if not isinstance(vae_info.model, AutoEncoder):
+ # Reject a foreign VAE up front with a clear error rather than failing on a stripped assert
+ # inside `vae_encode` under `python -O`. The check is on the latent normalisation rather than
+ # on the class: the FLUX.1 autoencoder is an `AutoencoderKL` now, and so are SD, SD 3.5 and
+ # CogView 4 -- and the scaling this node undoes below is precisely what differs between them.
+ if not is_flux_family_vae(vae_info.model):
raise ValueError(
- f"PiD Upscale requires a FLUX AutoEncoder VAE, but got {type(vae_info.model).__name__}. "
- "A diffusers AutoencoderKL (e.g. Z-Image) is not supported by this node."
+ "PiD Upscale requires the FLUX.1 autoencoder (Z-Image uses the same one). The VAE "
+ f"given is a {type(vae_info.model).__name__} with a different latent normalisation, "
+ "so its latents do not mean what the PiD decoder expects."
)
context.util.signal_progress("Running VAE encode")
normalised_latent = FluxVaeEncodeInvocation.vae_encode(vae_info=vae_info, image_tensor=image_tensor)
- # FluxAutoEncoder.encode emits `scale * (raw - shift)`. PiD expects raw, so undo it.
+ # The FLUX VAE encode emits `scale * (raw - shift)`. PiD expects raw, so undo it.
ae = get_flux_ae_params()
raw_latent = normalised_latent / ae.scale_factor + ae.shift_factor
raw_latent = raw_latent.to("cpu") # park while we swap to Gemma
diff --git a/invokeai/app/invocations/vae/anima_image_to_latents.py b/invokeai/app/invocations/vae/anima_image_to_latents.py
index b989178e81..64dd55eea8 100644
--- a/invokeai/app/invocations/vae/anima_image_to_latents.py
+++ b/invokeai/app/invocations/vae/anima_image_to_latents.py
@@ -28,7 +28,12 @@ from invokeai.app.services.shared.invocation_context import InvocationContext
from invokeai.backend.model_manager.load.load_base import LoadedModel
from invokeai.backend.stable_diffusion.diffusers_pipeline import image_resized_to_grid_as_tensor
from invokeai.backend.util.devices import TorchDevice
-from invokeai.backend.util.qwen_image_vae import as_qwen_image_vae
+from invokeai.backend.util.qwen_image_vae 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.util.vae_working_memory import (
estimate_vae_working_memory_anima,
)
@@ -39,7 +44,7 @@ from invokeai.backend.util.vae_working_memory import (
title="Image to Latents - Anima",
tags=["image", "latents", "vae", "i2l", "anima"],
category="image",
- version="1.0.2",
+ version="1.1.0",
classification=Classification.Prototype,
)
class AnimaImageToLatentsInvocation(BaseInvocation, WithMetadata, WithBoard):
@@ -47,9 +52,20 @@ class AnimaImageToLatentsInvocation(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
+ # Qwen-Image and SD i2l nodes. `int | None` is avoided because the workflow UI cannot send None.
+ 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}.",
+ )
@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:
try:
# Also raises ValueError for a Wan VAE of another geometry (Wan 2.2's 48-channel VAE).
as_qwen_image_vae(vae_info.model)
@@ -63,11 +79,14 @@ class AnimaImageToLatentsInvocation(BaseInvocation, WithMetadata, WithBoard):
"under 'anima', 'qwen-image', or a 16-channel 'wan' VAE."
) from e
+ # Resolved before estimating, so the reservation matches the tiles the VAE will use, and
+ # against a module constant rather than the cached module's current geometry.
+ effective_tile_size = resolve_qwen_image_vae_tile_size(tile_size) if tiled else None
estimated_working_memory = estimate_vae_working_memory_anima(
operation="encode",
image_tensor=image_tensor,
vae=vae_info.model,
- tile_size=None,
+ tile_size=effective_tile_size,
)
with vae_info.model_on_device(working_mem_bytes=estimated_working_memory) as (_, vae):
vae = as_qwen_image_vae(vae)
@@ -75,10 +94,12 @@ class AnimaImageToLatentsInvocation(BaseInvocation, WithMetadata, WithBoard):
vae_dtype = next(iter(vae.parameters())).dtype
image_tensor = image_tensor.to(device=TorchDevice.choose_torch_device(), dtype=vae_dtype)
- with torch.inference_mode():
- # The cached VAE instance is shared with the decode invocation, which
- # may have enabled tiling — encode untiled for exactness.
- vae.disable_tiling()
+ # The cached VAE instance is shared with the decode invocation, which may have enabled
+ # tiling. That used to be handled by switching tiling off here and leaving it off, which
+ # also meant this node could never tile; the scope sets exactly what this encode asked
+ # for and restores what was there, so "untiled for exactness" is still the default
+ # without being the only option.
+ with torch.inference_mode(), patch_qwen_image_vae_tiling(vae, effective_tile_size):
# Both VAE classes expect 5D input [B, C, T, H, W]
if image_tensor.ndim == 4:
image_tensor = image_tensor.unsqueeze(2) # [B, C, H, W] -> [B, C, 1, H, W]
@@ -109,7 +130,12 @@ class AnimaImageToLatentsInvocation(BaseInvocation, WithMetadata, WithBoard):
# `vae_encode` refuses a foreign encoder with a message that says which VAE to pick instead.
vae_info = context.models.load(self.vae.vae)
context.util.signal_progress("Running Anima VAE encode")
- 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/vae/flux_vae_decode.py b/invokeai/app/invocations/vae/flux_vae_decode.py
index 69a59564aa..d365f88180 100644
--- a/invokeai/app/invocations/vae/flux_vae_decode.py
+++ b/invokeai/app/invocations/vae/flux_vae_decode.py
@@ -15,11 +15,10 @@ from invokeai.app.invocations.fields import (
from invokeai.app.invocations.model import VAEField
from invokeai.app.invocations.primitives import ImageOutput
from invokeai.app.services.shared.invocation_context import InvocationContext
-from invokeai.backend.flux.modules.autoencoder import AutoEncoder
from invokeai.backend.model_manager.load.load_base import LoadedModel
from invokeai.backend.util.devices import TorchDevice
from 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
@@ -28,7 +27,7 @@ from invokeai.backend.util.vae_working_memory import estimate_vae_working_memory
title="Latents to Image - FLUX",
tags=["latents", "image", "vae", "l2i", "flux"],
category="latents",
- version="1.0.2",
+ version="1.1.0",
)
class FluxVaeDecodeInvocation(BaseInvocation, WithMetadata, WithBoard):
"""Generates an image from latents."""
@@ -41,49 +40,53 @@ class FluxVaeDecodeInvocation(BaseInvocation, WithMetadata, WithBoard):
description=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`.
- use_tiling = context.config.get().force_tiled_decode
- tile_size = 0 if use_tiling else None
+ # 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
+ tile_size = self.tile_size if use_tiling else None
- # Only estimate working memory for BFL AutoEncoder (diffusers VAE handles this internally)
- if isinstance(vae_info.model, AutoEncoder):
- estimated_working_memory = estimate_vae_working_memory_flux(
- operation="decode", image_tensor=latents, vae=vae_info.model, tile_size=tile_size
- )
- else:
- estimated_working_memory = 0
+ estimated_working_memory = estimate_vae_working_memory_flux(
+ operation="decode", image_tensor=latents, vae=vae_info.model, tile_size=tile_size
+ )
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 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)
- if not isinstance(vae, AutoEncoder):
- # Diffusers AutoencoderKL returns DecoderOutput with .sample attribute
- # Scale latents for diffusers VAE (FLUX uses shift_factor and scale_factor).
- # `shift_factor` is optional on AutoencoderKL: the FLUX VAE sets one, but a plain
- # SD-style config leaves it None, and `tensor + None` raises TypeError. Absent means
- # no shift — same handling as the Z-Image and PiD decode paths.
- scaling_factor = vae.config.scaling_factor
- shift_factor = getattr(vae.config, "shift_factor", None)
+ # `AutoencoderKL` leaves the scaling to the caller. `shift_factor` is optional on the
+ # class: the FLUX VAE sets one, but a plain SD-style config leaves it None, and
+ # `tensor + None` raises TypeError. Absent means no shift.
+ scaling_factor = vae.config.scaling_factor
+ shift_factor = getattr(vae.config, "shift_factor", None)
- latents = latents / scaling_factor
- if shift_factor is not None:
- latents = latents + shift_factor
+ latents = latents / scaling_factor
+ if shift_factor is not None:
+ latents = latents + shift_factor
def decode() -> torch.Tensor:
- if isinstance(vae, AutoEncoder):
- # BFL AutoEncoder returns tensor directly
- return vae.decode(latents)
return vae.decode(latents, return_dict=False)[0]
# The tiling state is set explicitly for this decode rather than inherited from whatever
diff --git a/invokeai/app/invocations/vae/flux_vae_encode.py b/invokeai/app/invocations/vae/flux_vae_encode.py
index 4ec0365c2c..7b77f3fc9d 100644
--- a/invokeai/app/invocations/vae/flux_vae_encode.py
+++ b/invokeai/app/invocations/vae/flux_vae_encode.py
@@ -1,5 +1,6 @@
import einops
import torch
+from diffusers.models.autoencoders.autoencoder_kl import AutoencoderKL
from invokeai.app.invocations.baseinvocation import BaseInvocation, invocation
from invokeai.app.invocations.fields import (
@@ -11,10 +12,12 @@ from invokeai.app.invocations.fields import (
from invokeai.app.invocations.model import VAEField
from invokeai.app.invocations.primitives import LatentsOutput
from invokeai.app.services.shared.invocation_context import InvocationContext
-from invokeai.backend.flux.modules.autoencoder import AutoEncoder
+from invokeai.backend.flux.util import is_flux_family_vae
from invokeai.backend.model_manager.load.load_base import LoadedModel
from invokeai.backend.stable_diffusion.diffusers_pipeline import image_resized_to_grid_as_tensor
from invokeai.backend.util.devices import TorchDevice
+from invokeai.backend.util.oom import is_oom_error
+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
@@ -23,7 +26,7 @@ from invokeai.backend.util.vae_working_memory import estimate_vae_working_memory
title="Image to Latents - FLUX",
tags=["latents", "image", "vae", "i2l", "flux"],
category="latents",
- version="1.0.1",
+ version="1.1.0",
)
class FluxVaeEncodeInvocation(BaseInvocation):
"""Encodes an image into latents."""
@@ -35,24 +38,66 @@ class FluxVaeEncodeInvocation(BaseInvocation):
description=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.
+ 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}.",
+ )
@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:
+ """Encode an image to a FLUX latent.
+
+ `tiled` defaults to off so the callers outside this node -- the Fill conditioning in
+ `flux_denoise`, the InstantX ControlNet extension, and PiD Upscale -- keep the behaviour they
+ have. Those three resize to the generation size before encoding.
+
+ Not all of them do, and the difference matters: the Kontext reference path encodes the
+ user's image at whatever resolution it has, with no resize anywhere. It does not come
+ through here -- it calls `vae.encode` directly in `flux/extensions/kontext_extension.py` --
+ and it carries its own OOM fallback for that reason.
+ """
# TODO(ryand): Expose seed parameter at the invocation level.
# 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 None
estimated_working_memory = estimate_vae_working_memory_flux(
- operation="encode", image_tensor=image_tensor, vae=vae_info.model
+ operation="encode", image_tensor=image_tensor, vae=vae_info.model, tile_size=effective_tile_size
)
+ # 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)
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)
- 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:
@@ -65,7 +110,27 @@ class FluxVaeEncodeInvocation(BaseInvocation):
image_tensor = einops.rearrange(image_tensor, "c h w -> 1 c h w")
context.util.signal_progress("Running VAE")
- latents = self.vae_encode(vae_info=vae_info, image_tensor=image_tensor)
+ use_tiling = self.tiled or context.config.get().force_tiled_decode
+ try:
+ latents = self.vae_encode(
+ vae_info=vae_info, image_tensor=image_tensor, tiled=use_tiling, tile_size=self.tile_size
+ )
+ except RuntimeError as e:
+ if use_tiling or not is_oom_error(e):
+ raise
+ # Same fallback the decode node has, and the same reason: an encode that does not fit
+ # should become a slower encode, not a failed generation. The FLUX autoencoder's
+ # mid-block attention is one head over the whole latent grid, so an untiled encode grows
+ # quadratically -- at 3072px it asks for 18.8 GiB where a tiled one asks for 0.8 GiB.
+ context.util.signal_progress("VAE encode ran out of memory, retrying tiled")
+ context.logger.warning(
+ "VAE encode ran out of memory; retrying with tiling. The tiled result is not identical to an "
+ "untiled encode -- the encoder's normalisation and attention are global, so the difference is "
+ "spread over the latent rather than confined to the seams."
+ )
+ e.__traceback__ = None
+ TorchDevice.empty_cache()
+ latents = self.vae_encode(vae_info=vae_info, image_tensor=image_tensor, tiled=True, tile_size=0)
latents = latents.to("cpu")
name = context.tensors.save(tensor=latents)
diff --git a/invokeai/app/invocations/vae/z_image_image_to_latents.py b/invokeai/app/invocations/vae/z_image_image_to_latents.py
index 263346e296..21e7d91e73 100644
--- a/invokeai/app/invocations/vae/z_image_image_to_latents.py
+++ b/invokeai/app/invocations/vae/z_image_image_to_latents.py
@@ -1,5 +1,3 @@
-from typing import Union
-
import einops
import torch
from diffusers.models.autoencoders.autoencoder_kl import AutoencoderKL
@@ -16,74 +14,87 @@ from invokeai.app.invocations.fields import (
from invokeai.app.invocations.model import VAEField
from invokeai.app.invocations.primitives import LatentsOutput
from invokeai.app.services.shared.invocation_context import InvocationContext
-from invokeai.backend.flux.modules.autoencoder import AutoEncoder as FluxAutoEncoder
from invokeai.backend.model_manager.load.load_base import LoadedModel
from 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_tiling
from 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",
title="Image to Latents - Z-Image",
tags=["image", "latents", "vae", "i2l", "z-image"],
category="latents",
- version="1.1.0",
+ version="1.2.0",
classification=Classification.Prototype,
)
class ZImageImageToLatentsInvocation(BaseInvocation, WithMetadata, WithBoard):
- """Generates latents from an image using Z-Image VAE (supports both Diffusers and FLUX VAE)."""
+ """Generates latents from an image using the Z-Image VAE."""
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. We use this rather than `int | None`, because the workflow UI does not
+ # offer a way to directly set None values. It is snapped down to a tile this VAE's own tiled encode can
+ # assemble -- see `scoped_vae_tiling`.
+ 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}.",
+ )
@staticmethod
- def vae_encode(vae_info: LoadedModel, image_tensor: torch.Tensor) -> torch.Tensor:
- if not isinstance(vae_info.model, (AutoencoderKL, FluxAutoEncoder)):
+ def vae_encode(
+ vae_info: LoadedModel,
+ image_tensor: torch.Tensor,
+ tiled: bool = False,
+ tile_size: int = 0,
+ ) -> torch.Tensor:
+ """Encode an image to a Z-Image latent.
+
+ `tiled` defaults to off so `z_image_denoise`'s control-latent call keeps the behaviour it
+ has: a control image is already at generation resolution, not the upscaled frame tiling
+ exists for.
+ """
+ if not isinstance(vae_info.model, AutoencoderKL):
raise TypeError(
- f"Expected AutoencoderKL or FluxAutoEncoder for Z-Image VAE, got {type(vae_info.model).__name__}. "
+ f"Expected AutoencoderKL for Z-Image VAE, got {type(vae_info.model).__name__}. "
"Ensure you are using a compatible VAE model."
)
- # Estimate working memory needed for VAE encode
+ effective_tile_size = tile_size if tiled else None
estimated_working_memory = estimate_vae_working_memory_flux(
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):
- if not isinstance(vae, (AutoencoderKL, FluxAutoEncoder)):
+ if not isinstance(vae, AutoencoderKL):
raise TypeError(
- f"Expected AutoencoderKL or FluxAutoEncoder, got {type(vae).__name__}. "
- "VAE model type changed unexpectedly after loading."
+ f"Expected AutoencoderKL, got {type(vae).__name__}. VAE model type changed unexpectedly after loading."
)
vae_dtype = next(iter(vae.parameters())).dtype
image_tensor = image_tensor.to(device=TorchDevice.choose_torch_device(), dtype=vae_dtype)
- with torch.inference_mode():
- if isinstance(vae, FluxAutoEncoder):
- # FLUX VAE handles scaling internally
- generator = torch.Generator(device=TorchDevice.choose_torch_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_factor
return latents
@@ -96,14 +107,14 @@ class ZImageImageToLatentsInvocation(BaseInvocation, WithMetadata, WithBoard):
image_tensor = einops.rearrange(image_tensor, "c h w -> 1 c h w")
vae_info = context.models.load(self.vae.vae)
- if not isinstance(vae_info.model, (AutoencoderKL, FluxAutoEncoder)):
- raise TypeError(
- f"Expected AutoencoderKL or FluxAutoEncoder for Z-Image VAE, got {type(vae_info.model).__name__}. "
- "Ensure you are using a compatible VAE model."
- )
context.util.signal_progress("Running 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/vae/z_image_latents_to_image.py b/invokeai/app/invocations/vae/z_image_latents_to_image.py
index 91805d0a1d..eae50c5795 100644
--- a/invokeai/app/invocations/vae/z_image_latents_to_image.py
+++ b/invokeai/app/invocations/vae/z_image_latents_to_image.py
@@ -1,6 +1,3 @@
-from contextlib import nullcontext
-from typing import Union
-
import torch
from diffusers.models.autoencoders.autoencoder_kl import AutoencoderKL
from einops import rearrange
@@ -18,16 +15,12 @@ from invokeai.app.invocations.fields import (
from invokeai.app.invocations.model import VAEField
from invokeai.app.invocations.primitives import ImageOutput
from invokeai.app.services.shared.invocation_context import InvocationContext
-from invokeai.backend.flux.modules.autoencoder import AutoEncoder as FluxAutoEncoder
from invokeai.backend.stable_diffusion.extensions.seamless import SeamlessExt
from invokeai.backend.util.devices import TorchDevice
from 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
-# Z-Image can use either the Diffusers AutoencoderKL or the FLUX AutoEncoder
-ZImageVAE = Union[AutoencoderKL, FluxAutoEncoder]
-
@invocation(
"z_image_l2i",
@@ -38,28 +31,32 @@ ZImageVAE = Union[AutoencoderKL, FluxAutoEncoder]
classification=Classification.Prototype,
)
class ZImageLatentsToImageInvocation(BaseInvocation, WithMetadata, WithBoard):
- """Generates an image from latents using Z-Image VAE (supports both Diffusers and FLUX VAE)."""
+ """Generates an image from latents using the Z-Image VAE."""
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. We use this rather than `int | None`, because the workflow UI does not
- # offer a way to directly set None values. InvokeAI's FLUX AutoEncoder takes the size as given; on a diffusers
- # AutoencoderKL it is snapped down to a tile that VAE's own tiled decode can assemble -- see `scoped_vae_tiling`.
- tile_size: int = InputField(default=0, multiple_of=8, description=FieldDescriptions.vae_tile_size)
+ # offer a way to directly set None values. It is snapped down to a tile this VAE's own tiled decode can
+ # assemble -- see `scoped_vae_tiling`.
+ 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}.",
+ )
@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)
- if not isinstance(vae_info.model, (AutoencoderKL, FluxAutoEncoder)):
+ if not isinstance(vae_info.model, AutoencoderKL):
raise TypeError(
- f"Expected AutoencoderKL or FluxAutoEncoder for Z-Image VAE, got {type(vae_info.model).__name__}. "
+ f"Expected AutoencoderKL for Z-Image VAE, got {type(vae_info.model).__name__}. "
"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
# Estimate working memory needed for VAE decode
@@ -70,16 +67,16 @@ class ZImageLatentsToImageInvocation(BaseInvocation, WithMetadata, WithBoard):
tile_size=self.tile_size if use_tiling else None,
)
- # 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")
- if not isinstance(vae, (AutoencoderKL, FluxAutoEncoder)):
+ if not isinstance(vae, AutoencoderKL):
raise TypeError(
- f"Expected AutoencoderKL or FluxAutoEncoder, got {type(vae).__name__}. "
+ f"Expected AutoencoderKL, got {type(vae).__name__}. "
"VAE model type changed unexpectedly after loading."
)
@@ -92,20 +89,15 @@ class ZImageLatentsToImageInvocation(BaseInvocation, WithMetadata, WithBoard):
# Clear memory as VAE decode can request a lot
TorchDevice.empty_cache()
- if not isinstance(vae, FluxAutoEncoder):
- # AutoencoderKL - Apply scaling_factor and shift_factor from VAE config
- # Z-Image uses: latents = latents / scaling_factor + shift_factor
- # (the FLUX VAE handles scaling internally)
- scaling_factor = vae.config.scaling_factor
- shift_factor = getattr(vae.config, "shift_factor", None)
+ # `AutoencoderKL` leaves the scaling to the caller: latents / scaling_factor + shift_factor.
+ scaling_factor = vae.config.scaling_factor
+ shift_factor = getattr(vae.config, "shift_factor", None)
- latents = latents / scaling_factor
- if shift_factor is not None:
- latents = latents + shift_factor
+ latents = latents / scaling_factor
+ if shift_factor is not None:
+ latents = latents + shift_factor
def decode() -> torch.Tensor:
- if isinstance(vae, FluxAutoEncoder):
- return vae.decode(latents)
return vae.decode(latents, return_dict=False)[0]
# The VAE belongs to the model cache and is shared with every other node that reaches
@@ -135,7 +127,10 @@ class ZImageLatentsToImageInvocation(BaseInvocation, WithMetadata, WithBoard):
# `ModelConfigFactory._detach_traceback`.
e.__traceback__ = None
TorchDevice.empty_cache()
- with scoped_vae_tiling(vae, self.tile_size):
+ # 0, not `self.tile_size`: the retry exists because the untiled pass did not
+ # fit, and the field may hold a size left over from a run where `tiled` was off.
+ # The FLUX sibling retries at 0 for the same reason.
+ with scoped_vae_tiling(vae, 0):
img = decode()
img = img.clamp(-1, 1)
diff --git a/invokeai/backend/flux/extensions/kontext_extension.py b/invokeai/backend/flux/extensions/kontext_extension.py
index b58c670115..7e801c54c0 100644
--- a/invokeai/backend/flux/extensions/kontext_extension.py
+++ b/invokeai/backend/flux/extensions/kontext_extension.py
@@ -1,14 +1,17 @@
import torch
import torch.nn.functional as F
import torchvision.transforms as T
+from diffusers.models.autoencoders.autoencoder_kl import AutoencoderKL
from einops import repeat
from invokeai.app.invocations.fields import FluxKontextConditioningField
from invokeai.app.invocations.model import VAEField
from invokeai.app.services.shared.invocation_context import InvocationContext
-from invokeai.backend.flux.modules.autoencoder import AutoEncoder
from invokeai.backend.flux.sampling_utils import pack
from invokeai.backend.util.devices import TorchDevice
+from invokeai.backend.util.oom import is_oom_error
+from invokeai.backend.util.vae_tiling_scope import scoped_vae_tiling
+from invokeai.backend.util.vae_working_memory import estimate_vae_working_memory_flux
def generate_img_ids_with_offset(
@@ -131,19 +134,43 @@ class KontextExtension:
# Continue with VAE encoding
# Don't sample from the distribution for reference images - use the mean (matching ComfyUI)
- # Estimate working memory for encode operation (50% of decode memory requirements)
- img_h = image_tensor.shape[-2]
- img_w = image_tensor.shape[-1]
- element_size = next(vae_info.model.parameters()).element_size()
- scaling_constant = 1100 # 50% of decode scaling constant (2200)
- estimated_working_memory = int(img_h * img_w * element_size * scaling_constant)
+ estimated_working_memory = estimate_vae_working_memory_flux(
+ operation="encode", image_tensor=image_tensor, vae=vae_info.model
+ )
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)
- # Use sample=False to get the distribution mean without noise
- kontext_latents_unpacked = vae.encode(image_tensor, sample=False)
+
+ def encode_reference(x: torch.Tensor = image_tensor) -> torch.Tensor:
+ # `.mode()` is the distribution mean without noise -- `sample=False` on the
+ # class this used to be written for. `x` is bound as a default rather than
+ # closed over: this runs inside a loop over the reference images.
+ return vae.encode(x).latent_dist.mode()
+
+ # Nothing on this path resizes: the reference is encoded at whatever resolution the
+ # user supplied, so a large one reserves in proportion -- 19.3 GiB at 3072px, which
+ # no consumer card has spare beside a resident transformer. Untiled first, because
+ # tiling changes the reference latents and with them the generation; tiled only when
+ # the untiled attempt has already failed, which turns a dead generation into a
+ # slower one. The FLUX.2 sibling forces a tile unconditionally
+ # (`flux2/ref_image_extension.py`); whether that trade is right here is a question
+ # about reference fidelity, not about memory, and is left open deliberately.
+ try:
+ moments = encode_reference()
+ except RuntimeError as e:
+ if not is_oom_error(e):
+ raise
+ e.__traceback__ = None
+ TorchDevice.empty_cache()
+ with scoped_vae_tiling(vae, 0):
+ moments = encode_reference()
+
+ shift_factor = getattr(vae.config, "shift_factor", None)
+ if shift_factor is not None:
+ moments = moments - shift_factor
+ kontext_latents_unpacked = moments * vae.config.scaling_factor
TorchDevice.empty_cache()
# Extract tensor dimensions
diff --git a/invokeai/backend/flux/modules/autoencoder.py b/invokeai/backend/flux/modules/autoencoder.py
deleted file mode 100644
index 135c362ed4..0000000000
--- a/invokeai/backend/flux/modules/autoencoder.py
+++ /dev/null
@@ -1,513 +0,0 @@
-# Initially pulled from https://github.com/black-forest-labs/flux
-
-from dataclasses import dataclass
-
-import numpy as np
-import torch
-from einops import rearrange
-from torch import Tensor, nn
-
-from invokeai.backend.tiles.tiles import calc_tiles_min_overlap, merge_tiles_with_linear_blending
-from invokeai.backend.tiles.utils import TBLR, Tile
-
-# Tile geometry for tiled decode, in output-pixel units. 512px tiles with a 128px minimum overlap is
-# the geometry the diffusers VAEs and the Anima node use. Both values must be divisible by the
-# autoencoder's spatial compression factor so that a pixel-space tile maps onto an exact latent slice.
-DEFAULT_TILE_SAMPLE_MIN_SIZE = 512
-DEFAULT_TILE_OVERLAP = 128
-
-# A cost floor, not a correctness one: the geometry stays valid all the way down, but the tile count
-# grows with the inverse square of the tile size. At 2048x2048 a 128px tile already emits 289 tiles;
-# a 16px tile would emit ~16k, and the per-tile kernel-launch overhead dominates long before that.
-# Small tiles are also measurably less accurate (see `enable_tiling`), so the low end of the node
-# field is clamped rather than honoured literally.
-MIN_TILE_SAMPLE_SIZE = 128
-
-
-def resolve_tile_size(tile_size: int) -> int:
- """Resolve a node's ``tile_size`` field to the size the autoencoder 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, and a negative value is not worth failing a generation
- over. It resolves to the module-level default rather than to whatever is currently set on the
- VAE: the instance belongs to the model cache, so reading it back would return whatever the
- previous invocation left there.
- """
- if tile_size <= 0:
- return DEFAULT_TILE_SAMPLE_MIN_SIZE
- return max(tile_size, MIN_TILE_SAMPLE_SIZE)
-
-
-@dataclass
-class AutoEncoderParams:
- resolution: int
- in_channels: int
- ch: int
- out_ch: int
- ch_mult: list[int]
- num_res_blocks: int
- z_channels: int
- scale_factor: float
- shift_factor: float
-
-
-class AttnBlock(nn.Module):
- def __init__(self, in_channels: int):
- super().__init__()
- self.in_channels = in_channels
-
- self.norm = nn.GroupNorm(num_groups=32, num_channels=in_channels, eps=1e-6, affine=True)
-
- self.q = nn.Conv2d(in_channels, in_channels, kernel_size=1)
- self.k = nn.Conv2d(in_channels, in_channels, kernel_size=1)
- self.v = nn.Conv2d(in_channels, in_channels, kernel_size=1)
- self.proj_out = nn.Conv2d(in_channels, in_channels, kernel_size=1)
-
- def attention(self, h_: Tensor) -> Tensor:
- h_ = self.norm(h_)
- q = self.q(h_)
- k = self.k(h_)
- v = self.v(h_)
-
- b, c, h, w = q.shape
- q = rearrange(q, "b c h w -> b 1 (h w) c").contiguous()
- k = rearrange(k, "b c h w -> b 1 (h w) c").contiguous()
- v = rearrange(v, "b c h w -> b 1 (h w) c").contiguous()
- h_ = nn.functional.scaled_dot_product_attention(q, k, v)
-
- return rearrange(h_, "b 1 (h w) c -> b c h w", h=h, w=w, c=c, b=b)
-
- def forward(self, x: Tensor) -> Tensor:
- return x + self.proj_out(self.attention(x))
-
-
-class ResnetBlock(nn.Module):
- def __init__(self, in_channels: int, out_channels: int):
- super().__init__()
- self.in_channels = in_channels
- out_channels = in_channels if out_channels is None else out_channels
- self.out_channels = out_channels
-
- self.norm1 = nn.GroupNorm(num_groups=32, num_channels=in_channels, eps=1e-6, affine=True)
- self.conv1 = nn.Conv2d(in_channels, out_channels, kernel_size=3, stride=1, padding=1)
- self.norm2 = nn.GroupNorm(num_groups=32, num_channels=out_channels, eps=1e-6, affine=True)
- self.conv2 = nn.Conv2d(out_channels, out_channels, kernel_size=3, stride=1, padding=1)
- if self.in_channels != self.out_channels:
- self.nin_shortcut = nn.Conv2d(in_channels, out_channels, kernel_size=1, stride=1, padding=0)
-
- def forward(self, x):
- h = x
- h = self.norm1(h)
- h = torch.nn.functional.silu(h)
- h = self.conv1(h)
-
- h = self.norm2(h)
- h = torch.nn.functional.silu(h)
- h = self.conv2(h)
-
- if self.in_channels != self.out_channels:
- x = self.nin_shortcut(x)
-
- return x + h
-
-
-class Downsample(nn.Module):
- def __init__(self, in_channels: int):
- super().__init__()
- # no asymmetric padding in torch conv, must do it ourselves
- self.conv = nn.Conv2d(in_channels, in_channels, kernel_size=3, stride=2, padding=0)
-
- def forward(self, x: Tensor):
- pad = (0, 1, 0, 1)
- x = nn.functional.pad(x, pad, mode="constant", value=0)
- x = self.conv(x)
- return x
-
-
-class Upsample(nn.Module):
- def __init__(self, in_channels: int):
- super().__init__()
- self.conv = nn.Conv2d(in_channels, in_channels, kernel_size=3, stride=1, padding=1)
-
- def forward(self, x: Tensor):
- x = nn.functional.interpolate(x, scale_factor=2.0, mode="nearest")
- x = self.conv(x)
- return x
-
-
-class Encoder(nn.Module):
- def __init__(
- self,
- resolution: int,
- in_channels: int,
- ch: int,
- ch_mult: list[int],
- num_res_blocks: int,
- z_channels: int,
- ):
- super().__init__()
- self.ch = ch
- self.num_resolutions = len(ch_mult)
- self.num_res_blocks = num_res_blocks
- self.resolution = resolution
- self.in_channels = in_channels
- # downsampling
- self.conv_in = nn.Conv2d(in_channels, self.ch, kernel_size=3, stride=1, padding=1)
-
- curr_res = resolution
- in_ch_mult = (1,) + tuple(ch_mult)
- self.in_ch_mult = in_ch_mult
- self.down = nn.ModuleList()
- block_in = self.ch
- for i_level in range(self.num_resolutions):
- block = nn.ModuleList()
- attn = nn.ModuleList()
- block_in = ch * in_ch_mult[i_level]
- block_out = ch * ch_mult[i_level]
- for _ in range(self.num_res_blocks):
- block.append(ResnetBlock(in_channels=block_in, out_channels=block_out))
- block_in = block_out
- down = nn.Module()
- down.block = block
- down.attn = attn
- if i_level != self.num_resolutions - 1:
- down.downsample = Downsample(block_in)
- curr_res = curr_res // 2
- self.down.append(down)
-
- # middle
- self.mid = nn.Module()
- self.mid.block_1 = ResnetBlock(in_channels=block_in, out_channels=block_in)
- self.mid.attn_1 = AttnBlock(block_in)
- self.mid.block_2 = ResnetBlock(in_channels=block_in, out_channels=block_in)
-
- # end
- self.norm_out = nn.GroupNorm(num_groups=32, num_channels=block_in, eps=1e-6, affine=True)
- self.conv_out = nn.Conv2d(block_in, 2 * z_channels, kernel_size=3, stride=1, padding=1)
-
- def forward(self, x: Tensor) -> Tensor:
- # downsampling
- hs = [self.conv_in(x)]
- for i_level in range(self.num_resolutions):
- for i_block in range(self.num_res_blocks):
- h = self.down[i_level].block[i_block](hs[-1])
- if len(self.down[i_level].attn) > 0:
- h = self.down[i_level].attn[i_block](h)
- hs.append(h)
- if i_level != self.num_resolutions - 1:
- hs.append(self.down[i_level].downsample(hs[-1]))
-
- # middle
- h = hs[-1]
- h = self.mid.block_1(h)
- h = self.mid.attn_1(h)
- h = self.mid.block_2(h)
- # end
- h = self.norm_out(h)
- h = torch.nn.functional.silu(h)
- h = self.conv_out(h)
- return h
-
-
-class Decoder(nn.Module):
- def __init__(
- self,
- ch: int,
- out_ch: int,
- ch_mult: list[int],
- num_res_blocks: int,
- in_channels: int,
- resolution: int,
- z_channels: int,
- ):
- super().__init__()
- self.ch = ch
- self.num_resolutions = len(ch_mult)
- self.num_res_blocks = num_res_blocks
- self.resolution = resolution
- self.in_channels = in_channels
- self.ffactor = 2 ** (self.num_resolutions - 1)
-
- # compute in_ch_mult, block_in and curr_res at lowest res
- block_in = ch * ch_mult[self.num_resolutions - 1]
- curr_res = resolution // 2 ** (self.num_resolutions - 1)
- self.z_shape = (1, z_channels, curr_res, curr_res)
-
- # z to block_in
- self.conv_in = nn.Conv2d(z_channels, block_in, kernel_size=3, stride=1, padding=1)
-
- # middle
- self.mid = nn.Module()
- self.mid.block_1 = ResnetBlock(in_channels=block_in, out_channels=block_in)
- self.mid.attn_1 = AttnBlock(block_in)
- self.mid.block_2 = ResnetBlock(in_channels=block_in, out_channels=block_in)
-
- # upsampling
- self.up = nn.ModuleList()
- for i_level in reversed(range(self.num_resolutions)):
- block = nn.ModuleList()
- attn = nn.ModuleList()
- block_out = ch * ch_mult[i_level]
- for _ in range(self.num_res_blocks + 1):
- block.append(ResnetBlock(in_channels=block_in, out_channels=block_out))
- block_in = block_out
- up = nn.Module()
- up.block = block
- up.attn = attn
- if i_level != 0:
- up.upsample = Upsample(block_in)
- curr_res = curr_res * 2
- self.up.insert(0, up) # prepend to get consistent order
-
- # end
- self.norm_out = nn.GroupNorm(num_groups=32, num_channels=block_in, eps=1e-6, affine=True)
- self.conv_out = nn.Conv2d(block_in, out_ch, kernel_size=3, stride=1, padding=1)
-
- def forward(self, z: Tensor) -> Tensor:
- # z to block_in
- h = self.conv_in(z)
-
- # middle
- h = self.mid.block_1(h)
- h = self.mid.attn_1(h)
- h = self.mid.block_2(h)
-
- # upsampling
- for i_level in reversed(range(self.num_resolutions)):
- for i_block in range(self.num_res_blocks + 1):
- h = self.up[i_level].block[i_block](h)
- if len(self.up[i_level].attn) > 0:
- h = self.up[i_level].attn[i_block](h)
- if i_level != 0:
- h = self.up[i_level].upsample(h)
-
- # end
- h = self.norm_out(h)
- h = torch.nn.functional.silu(h)
- h = self.conv_out(h)
- return h
-
-
-class DiagonalGaussian(nn.Module):
- def __init__(self, chunk_dim: int = 1):
- super().__init__()
- self.chunk_dim = chunk_dim
-
- def forward(self, z: Tensor, sample: bool = True, generator: torch.Generator | None = None) -> Tensor:
- mean, logvar = torch.chunk(z, 2, dim=self.chunk_dim)
- if sample:
- std = torch.exp(0.5 * logvar)
- # Unfortunately, torch.randn_like(...) does not accept a generator argument at the time of writing, so we
- # have to use torch.randn(...) instead.
- return mean + std * torch.randn(size=mean.size(), generator=generator, dtype=mean.dtype, device=mean.device)
- else:
- return mean
-
-
-class AutoEncoder(nn.Module):
- def __init__(self, params: AutoEncoderParams):
- super().__init__()
- self.encoder = Encoder(
- resolution=params.resolution,
- in_channels=params.in_channels,
- ch=params.ch,
- ch_mult=params.ch_mult,
- num_res_blocks=params.num_res_blocks,
- z_channels=params.z_channels,
- )
- self.decoder = Decoder(
- resolution=params.resolution,
- in_channels=params.in_channels,
- ch=params.ch,
- out_ch=params.out_ch,
- ch_mult=params.ch_mult,
- num_res_blocks=params.num_res_blocks,
- z_channels=params.z_channels,
- )
- self.reg = DiagonalGaussian()
-
- self.scale_factor = params.scale_factor
- self.shift_factor = params.shift_factor
-
- # Each level of `ch_mult` past the first halves the spatial resolution, so this is the ratio
- # between output pixels and latent elements along one axis (8 for the FLUX.1 autoencoder).
- self.spatial_compression = 2 ** (len(params.ch_mult) - 1)
-
- self.use_tiling = False
- self.tile_sample_min_size = DEFAULT_TILE_SAMPLE_MIN_SIZE
- self.tile_overlap = DEFAULT_TILE_OVERLAP
-
- def enable_tiling(
- self,
- tile_sample_min_size: int = DEFAULT_TILE_SAMPLE_MIN_SIZE,
- tile_overlap: int | None = None,
- ) -> None:
- """Decode in overlapping tiles, bounding peak memory at the cost of some decode time.
-
- Mirrors the `enable_tiling()` / `disable_tiling()` pair on the diffusers autoencoders so that
- callers can set the tiling state the same way regardless of which VAE class they hold. Sizes
- are in output pixels.
-
- `tile_overlap` defaults to DEFAULT_TILE_OVERLAP, shrunk to half the tile if the caller asked
- for a tile that small, rather than raising: that would turn a tile size the workflow UI lets
- a user type into a failed generation. The shrink bottoms out at one `spatial_compression`
- step, below which there is no overlap left to blend and the geometry is rejected.
-
- Note on accuracy: a tiled decode does not reproduce the single-pass one. The decoder's
- GroupNorms normalise over the whole spatial extent and `mid.attn_1` is global, so a tile
- sees different statistics than the full latent does -- and the difference is spread over the
- whole image rather than confined to the seams. Measured on the tiny test fixture at the
- default 512/128 geometry: max |tiled - untiled| of 0.12 at 768px and 0.19 at 1536px, against
- an output range of about +/-3. What *is* exact is the tile geometry. Accuracy degrades
- further as tiles get small relative to the image, because more tiles mean the blend bands
- sit closer to the tiles' own zero-padded borders. Prefer a large tile that fits over a small
- one that fits comfortably.
- """
- if tile_overlap is None:
- tile_overlap = min(DEFAULT_TILE_OVERLAP, tile_sample_min_size // 2)
- tile_overlap -= tile_overlap % self.spatial_compression
- if tile_sample_min_size % self.spatial_compression != 0:
- raise ValueError(
- f"tile_sample_min_size must be divisible by {self.spatial_compression}, got {tile_sample_min_size}."
- )
- if tile_overlap % self.spatial_compression != 0:
- raise ValueError(f"tile_overlap must be divisible by {self.spatial_compression}, got {tile_overlap}.")
- if tile_overlap <= 0:
- # Blending needs a band to blend over: `merge_tiles_with_linear_blending` builds its
- # gradient with `np.linspace(..., num=blend_amount)`, so a zero overlap yields no
- # gradient at all and the tiles butt together with a hard seam. Reachable only from a
- # direct call -- the nodes go through `resolve_tile_size`, which floors at 128 -- and
- # only for `tile_sample_min_size=8`, whose rounded-down automatic overlap is 0.
- raise ValueError(f"tile_overlap must be greater than 0, got {tile_overlap}.")
- if tile_overlap >= tile_sample_min_size:
- raise ValueError(
- f"tile_overlap ({tile_overlap}) must be smaller than tile_sample_min_size ({tile_sample_min_size})."
- )
- self.use_tiling = True
- self.tile_sample_min_size = tile_sample_min_size
- self.tile_overlap = tile_overlap
-
- def disable_tiling(self) -> None:
- """Decode in a single pass. The inverse of `enable_tiling()`."""
- self.use_tiling = False
-
- def encode(self, x: Tensor, sample: bool = True, generator: torch.Generator | None = None) -> Tensor:
- """Run VAE encoding on input tensor x.
-
- Args:
- x (Tensor): Input image tensor. Shape: (batch_size, in_channels, height, width).
- sample (bool, optional): If True, sample from the encoded distribution, else, return the distribution mean.
- Defaults to True.
- generator (torch.Generator | None, optional): Optional random number generator for reproducibility.
- Defaults to None.
-
- Returns:
- Tensor: Encoded latent tensor. Shape: (batch_size, z_channels, latent_height, latent_width).
- """
-
- z = self.reg(self.encoder(x), sample=sample, generator=generator)
- z = self.scale_factor * (z - self.shift_factor)
- return z
-
- def decode(self, z: Tensor) -> Tensor:
- z = z / self.scale_factor + self.shift_factor
- if self.use_tiling:
- return self._tiled_decode(z)
- return self.decoder(z)
-
- def _tiled_decode(self, z: Tensor) -> Tensor:
- """Decode `z` as overlapping tiles, blended back together linearly.
-
- `z` is expected to already be denormalised, i.e. this consumes what `decode()` hands to
- `self.decoder`. *Device* memory is what tiling bounds, to one tile: every finished tile is
- moved to the CPU as soon as it is decoded. Host memory is not bounded -- the tiles
- accumulate there until the merge runs after the loop, and the stack at the end copies the
- merged image again. At 4096x4096 with the default geometry the host peak is 121 tiles of
- 512x512x3 float32 (~380MB) plus the merged array and the stacked copy of it (~200MB each),
- so ~780MB, against ~200MB of device memory for the result.
-
- The tile layout is computed in *latent* space and scaled up afterwards. Computing it in pixel
- space would be wrong: `calc_tiles_min_overlap` distributes the leftover with integer
- division, so it hands back tile edges that are not multiples of `spatial_compression` and
- therefore cannot be sliced out of `z`. Overlaps scale with the coordinates because they are
- nothing but coordinate differences.
- """
- scale = self.spatial_compression
- latent_tile_size = self.tile_sample_min_size // scale
- latent_overlap = self.tile_overlap // scale
- latent_height, latent_width = z.shape[-2], z.shape[-1]
-
- # Nothing to gain from tiling something that already fits in a single tile.
- if latent_height <= latent_tile_size and latent_width <= latent_tile_size:
- return self.decoder(z)
-
- # `calc_tiles_min_overlap` clamps the tile down to the image on each axis and then divides
- # by `tile - min_overlap`, so an axis exactly as small as the overlap divides by zero -- a
- # 128x1024 image at the default 512/128 geometry, reachable from the node field, from
- # `force_tiled_decode`, and from the OOM retry, where it would replace the OOM with a
- # division-by-zero. Shrink the overlap to fit the smallest clamped tile; if nothing usable is
- # left the layout is degenerate, and at that size a single pass is both correct and cheap.
- latent_overlap = min(latent_overlap, min(latent_tile_size, latent_height, latent_width) - 1)
- if latent_overlap < 1:
- return self.decoder(z)
-
- latent_tiles = calc_tiles_min_overlap(
- image_height=latent_height,
- image_width=latent_width,
- tile_height=latent_tile_size,
- tile_width=latent_tile_size,
- min_overlap=latent_overlap,
- )
- pixel_tiles = [
- Tile(
- coords=TBLR(
- top=t.coords.top * scale,
- bottom=t.coords.bottom * scale,
- left=t.coords.left * scale,
- right=t.coords.right * scale,
- ),
- overlap=TBLR(
- top=t.overlap.top * scale,
- bottom=t.overlap.bottom * scale,
- left=t.overlap.left * scale,
- right=t.overlap.right * scale,
- ),
- )
- for t in latent_tiles
- ]
-
- out_channels = self.decoder.conv_out.out_channels
- batch_images: list[Tensor] = []
- for batch_idx in range(z.shape[0]):
- tile_images: list[np.ndarray] = []
- for latent_tile in latent_tiles:
- latent_slice = z[
- batch_idx : batch_idx + 1,
- :,
- latent_tile.coords.top : latent_tile.coords.bottom,
- latent_tile.coords.left : latent_tile.coords.right,
- ]
- decoded_tile = self.decoder(latent_slice)
- # Off the GPU immediately -- holding the finished tiles on the device is the thing
- # tiling exists to avoid.
- tile_images.append(decoded_tile[0].permute(1, 2, 0).float().cpu().numpy())
-
- merged = np.zeros(
- (latent_height * scale, latent_width * scale, out_channels),
- dtype=tile_images[0].dtype,
- )
- merge_tiles_with_linear_blending(
- dst_image=merged,
- tiles=pixel_tiles,
- tile_images=tile_images,
- # Derived from the overlap the layout was actually built with, not from
- # `self.tile_overlap`: the merge requires every non-edge tile overlap to be at least
- # `blend_amount`, and the shrink above can put the two below the configured value.
- blend_amount=latent_overlap * scale,
- )
- batch_images.append(torch.from_numpy(merged).permute(2, 0, 1))
-
- return torch.stack(batch_images).to(device=z.device, dtype=z.dtype)
-
- def forward(self, x: Tensor) -> Tensor:
- return self.decode(self.encode(x))
diff --git a/invokeai/backend/flux/util.py b/invokeai/backend/flux/util.py
index 81b10a913a..7e6d1a897a 100644
--- a/invokeai/backend/flux/util.py
+++ b/invokeai/backend/flux/util.py
@@ -1,13 +1,33 @@
# Initially pulled from https://github.com/black-forest-labs/flux
from dataclasses import dataclass
-from typing import Literal
+from typing import Any, Literal
from invokeai.backend.flux.model import FluxParams
-from invokeai.backend.flux.modules.autoencoder import AutoEncoderParams
from invokeai.backend.model_manager.taxonomy import AnyVariant, Flux2VariantType, FluxVariantType
+@dataclass
+class AutoEncoderParams:
+ """The BFL description of the FLUX.1 autoencoder.
+
+ Kept after the hand-written `AutoEncoder` module was replaced by diffusers' `AutoencoderKL`,
+ because it is still the single source of truth for this VAE: `get_flux_vae_diffusers_config`
+ derives the diffusers keyword arguments from these fields, and the PiD nodes read
+ `scale_factor`/`shift_factor` off it to undo the FLUX latent scaling.
+ """
+
+ resolution: int
+ in_channels: int
+ ch: int
+ out_ch: int
+ ch_mult: list[int]
+ num_res_blocks: int
+ z_channels: int
+ scale_factor: float
+ shift_factor: float
+
+
@dataclass
class ModelSpec:
params: FluxParams
@@ -75,6 +95,78 @@ def get_flux_ae_params() -> AutoEncoderParams:
return _flux_ae_params
+# The two values the BFL parameters do not carry, taken from the published diffusers config
+# (`black-forest-labs/FLUX.1-{dev,schnell}::vae/config.json`, 774 bytes, identical in both):
+#
+# sample_size seeds `AutoencoderKL.tile_sample_min_size`. `AutoEncoderParams.resolution` is
+# 256, the training crop, and is a different quantity -- using it would make the
+# default tile four times too small. Every call site that tiles sets the size
+# explicitly through `scoped_vae_tiling`, so this is the value used only when
+# nobody asks.
+# use_(post_)quant_conv
+# False. The FLUX autoencoder has no quant convolutions at all; diffusers
+# defaults to True, which would add two 1x1 convolutions the checkpoint cannot
+# fill.
+_FLUX_VAE_SAMPLE_SIZE = 1024
+
+
+def is_flux_family_vae(vae: Any) -> bool:
+ """Whether this VAE encodes into the FLUX.1 latent space.
+
+ `isinstance(vae, AutoencoderKL)` used to answer this, because InvokeAI's own port of the BFL
+ autoencoder was a distinct class. It no longer is: the FLUX.1 VAE *is* an `AutoencoderKL`, and so
+ are SD 1.5, SDXL, SD 3.5, CogView 4 and Z-Image's. Three of those even share the 16-channel
+ latent width, so the channel count alone does not separate them either.
+
+ What does separate them is the normalisation, and that is also exactly what a caller of this
+ depends on: `pid_upscale` undoes `scale * (raw - shift)` with the constants from
+ `get_flux_ae_params()`, and a VAE that used different ones hands it a latent that means something
+ else. So the test is on the constants themselves -- Z-Image passes, because it is the same
+ autoencoder (`_name_or_path: "flux-dev"` in its published config); SD 3.5 does not, because its
+ `scaling_factor` is 1.5305.
+ """
+ config = getattr(vae, "config", None)
+ if config is None:
+ return False
+ params = get_flux_ae_params()
+ return (
+ getattr(config, "latent_channels", None) == params.z_channels
+ and getattr(config, "scaling_factor", None) == params.scale_factor
+ and getattr(config, "shift_factor", None) == params.shift_factor
+ )
+
+
+def get_flux_vae_diffusers_config() -> dict[str, Any]:
+ """The FLUX.1 autoencoder as `AutoencoderKL.__init__` keyword arguments.
+
+ Derived from `_flux_ae_params` rather than transcribed from the published `vae/config.json`, so
+ the two descriptions of this autoencoder cannot drift apart -- `AutoEncoderParams` is still the
+ single source of truth, and is what the PiD nodes read for `scale_factor`/`shift_factor`.
+
+ Fields left to diffusers' own defaults (`act_fn`, `norm_num_groups`, `force_upcast`,
+ `mid_block_add_attention`, `latents_mean`, `latents_std`) match the published config today;
+ `tests/backend/model_manager/load/test_flux_vae_loader.py::TestTheConstructedConfig` pins the
+ fully constructed config against the published values, so a changed default in a future
+ diffusers breaks a test rather than the model.
+ """
+ params = get_flux_ae_params()
+ num_blocks = len(params.ch_mult)
+ return {
+ "in_channels": params.in_channels,
+ "out_channels": params.out_ch,
+ "down_block_types": ("DownEncoderBlock2D",) * num_blocks,
+ "up_block_types": ("UpDecoderBlock2D",) * num_blocks,
+ "block_out_channels": tuple(params.ch * mult for mult in params.ch_mult),
+ "layers_per_block": params.num_res_blocks,
+ "latent_channels": params.z_channels,
+ "sample_size": _FLUX_VAE_SAMPLE_SIZE,
+ "scaling_factor": params.scale_factor,
+ "shift_factor": params.shift_factor,
+ "use_quant_conv": False,
+ "use_post_quant_conv": False,
+ }
+
+
_flux_transformer_params: dict[AnyVariant, FluxParams] = {
FluxVariantType.Dev: FluxParams(
in_channels=64,
diff --git a/invokeai/backend/model_manager/load/model_loaders/flux.py b/invokeai/backend/model_manager/load/model_loaders/flux.py
index 88430e34bc..3983e8e598 100644
--- a/invokeai/backend/model_manager/load/model_loaders/flux.py
+++ b/invokeai/backend/model_manager/load/model_loaders/flux.py
@@ -32,9 +32,8 @@ from invokeai.backend.flux.ip_adapter.xlabs_ip_adapter_flux import (
XlabsIpAdapterFlux,
)
from invokeai.backend.flux.model import Flux
-from invokeai.backend.flux.modules.autoencoder import AutoEncoder
from invokeai.backend.flux.redux.flux_redux_model import FluxReduxModel
-from invokeai.backend.flux.util import get_flux_ae_params, get_flux_transformers_params
+from invokeai.backend.flux.util import get_flux_transformers_params, get_flux_vae_diffusers_config
from invokeai.backend.model_manager.checkpoint_prefix import CheckpointPrefix
from invokeai.backend.model_manager.configs.base import Checkpoint_Config_Base, Diffusers_Config_Base
from invokeai.backend.model_manager.configs.clip_embed import CLIPEmbed_Diffusers_Config_Base
@@ -136,23 +135,75 @@ except ImportError:
app_config = get_config()
+# A key that exists only in the BFL layout -- structural on purpose, because
+# `encoder.conv_in.weight` is present in every layout and in every 16-channel autoencoder.
+_FLUX_VAE_BFL_MARKER = "encoder.down.0.block.0.norm1.weight"
+
+# ...and the diffusers-layout key, which is recognised only in order to be *refused* with a reason.
+# See `FluxVAELoader` for why accepting it would be unsafe.
+_FLUX_VAE_DIFFUSERS_MARKER = "encoder.down_blocks.0.resnets.0.norm1.weight"
+
+
@ModelLoaderRegistry.register(base=BaseModelType.Flux, type=ModelType.VAE, format=ModelFormat.Checkpoint)
class FluxVAELoader(ModelLoader):
- """Class to load VAE models."""
+ """Load the FLUX.1 autoencoder as a diffusers `AutoencoderKL`.
+
+ This is the same network either way: loaded into InvokeAI's own port of the BFL reference and
+ into `AutoencoderKL`, the two agree in fp32 to `maxdiff 1.6e-06` on a latent and `1.5e-05` on an
+ image, which is float accumulation noise. The diffusers class is used because it brings a tiled
+ *encode*, which the port never had -- an untiled 3072px encode reserves 18.8 GiB on a 4090
+ against 0.81 GiB tiled, and does not complete at all on a 16 GiB card.
+
+ **Only the BFL `ae.safetensors` layout is accepted, and that is deliberate.**
+
+ `VAE_Checkpoint_FLUX_Config` recognises a FLUX VAE by `encoder.conv_in`/`decoder.conv_in` plus 16
+ latent channels, and `_get_base_or_raise` maps *every* 16-channel checkpoint to `flux` -- there
+ is no SD 3.5 or CogView 4 branch. Those two autoencoders are architecturally identical to this
+ one: same 244 keys, same shapes, differing only in `scaling_factor`/`shift_factor` (1.5305/0.0609
+ and 1.0/0.0 against 0.3611/0.1159).
+
+ A standalone diffusers-layout file carries no config, so loading one would mean stamping FLUX's
+ constants onto weights that may be SD 3.5's -- which loads cleanly, generates without error, and
+ produces a wrongly normalised image that nothing downstream can tell from an intended one.
+ `is_flux_family_vae` cannot catch it either, because it reads the config this loader synthesised.
+ The BFL layout has no such ambiguity: its key names belong to the BFL reference implementation
+ and neither of the others is published in it.
+
+ So a diffusers-layout single file is refused, as it was before this loader could read that layout
+ at all. The unambiguous route for one still works: install the `vae/` folder, which carries its
+ own `config.json` and loads through the generic `VAELoader`.
+ """
def _load_model(
self,
config: AnyModelConfig,
submodel_type: Optional[SubModelType] = None,
) -> AnyModel:
+ from diffusers.loaders.single_file_utils import convert_ldm_vae_checkpoint
+
if not isinstance(config, VAE_Checkpoint_Config_Base):
raise ValueError("Only VAECheckpointConfig models are currently supported here.")
model_path = Path(config.path)
- with accelerate.init_empty_weights():
- model = AutoEncoder(get_flux_ae_params())
sd = load_file(model_path)
- load_state_dict_ignoring_extras(model, sd, source="FLUX VAE checkpoint", assign=True)
+
+ with accelerate.init_empty_weights():
+ model = AutoencoderKL(**get_flux_vae_diffusers_config())
+
+ if _FLUX_VAE_BFL_MARKER in sd:
+ payload = convert_ldm_vae_checkpoint(sd, model.config)
+ elif _FLUX_VAE_DIFFUSERS_MARKER in sd:
+ raise ValueError(
+ f"{model_path.name} is a diffusers-layout autoencoder. A standalone file in that "
+ "layout carries no config, and the FLUX.1, SD 3.5 and CogView 4 autoencoders are "
+ "identical in shape -- so which latent space this one encodes into cannot be "
+ "determined from the file, and guessing wrong produces images that look plausible "
+ "and are not. Install the VAE's folder instead, which carries its own config.json."
+ )
+ else:
+ raise ValueError(f"{model_path.name} is not a FLUX.1 autoencoder: it has no '{_FLUX_VAE_BFL_MARKER}'.")
+
+ load_state_dict_ignoring_extras(model, payload, source="FLUX VAE checkpoint", assign=True)
# VAE is broken in float16, which mps defaults to
if self._torch_dtype == torch.float16:
try:
diff --git a/invokeai/backend/util/vae_tiling_scope.py b/invokeai/backend/util/vae_tiling_scope.py
index cb2725ca74..6c18a5d5d8 100644
--- a/invokeai/backend/util/vae_tiling_scope.py
+++ b/invokeai/backend/util/vae_tiling_scope.py
@@ -1,15 +1,15 @@
-"""Scoped VAE tiling state.
+"""Scoped VAE tiling state, and the tile size a node's field resolves to.
The VAE instances these helpers take belong to the model cache and are shared across invocations and
-across *nodes*: the FLUX.1 autoencoder is reached by nine call sites, and a diffusers AutoencoderKL
-loaded for Z-Image is reached by several more. Tiling is a property of one decode, not of the model,
-so it has to be restored rather than merely turned off -- `disable_tiling()` clears the flag but
-leaves the geometry, and most of the consumers never touch the flag at all.
+across *nodes*: the FLUX.1 autoencoder is reached by nine call sites, and the diffusers
+`AutoencoderKL` it is loaded as also serves Z-Image. Tiling is a property of one decode, not of the
+model, so it has to be restored rather than merely turned off -- `disable_tiling()` clears the flag
+but leaves the geometry, and most of the consumers never touch the flag at all.
Two siblings solve the same problem for their own classes: `patch_qwen_image_vae_tiling` for the
-Qwen-Image VAE, and `stable_diffusion.vae_tiling.patch_vae_tiling_params` for SD's. Neither fits
-here -- the SD one is typed to AutoencoderKL/AutoencoderTiny, patches three diffusers-specific
-attributes the FLUX autoencoder does not have, and leaves `use_tiling` to the caller.
+Qwen-Image and Wan VAEs, whose geometry is named `tile_sample_min_height`/`tile_sample_stride_*` and
+which have no `tile_overlap_factor` at all, and `stable_diffusion.vae_tiling.patch_vae_tiling_params`
+for SD's, which leaves `use_tiling` to the caller.
`diffusers_latent_tile` and `diffusers_vae_downsample` state constraints of the diffusers VAE
classes rather than of this module, which is why they are public: the SD sibling derived the tile
@@ -20,15 +20,22 @@ third copy of that arithmetic is the failure mode this module exists to stop.
from contextlib import contextmanager
from typing import Any, Iterator
-from invokeai.backend.flux.modules.autoencoder import AutoEncoder, resolve_tile_size
+# Tile geometry for tiled encode and decode, in output-pixel units. 512px is the geometry the
+# diffusers VAEs and the Anima node use.
+DEFAULT_TILE_SAMPLE_MIN_SIZE = 512
-# Attributes that carry tiling state, across the VAE classes that reach these nodes: InvokeAI's FLUX
-# AutoEncoder and diffusers' AutoencoderKL. Read defensively -- a class that has none of them simply
-# has nothing to restore.
+# A cost floor, not a correctness one: the geometry stays valid all the way down, but the tile count
+# grows with the inverse square of the tile size. At 2048x2048 a 128px tile already emits 289 tiles;
+# a 16px tile would emit ~16k, and the per-tile kernel-launch overhead dominates long before that.
+# Small tiles are also measurably less accurate, because more tiles mean the blend bands sit closer
+# to the tiles' own borders, so the low end of a node field is clamped rather than honoured.
+MIN_TILE_SAMPLE_SIZE = 128
+
+# Attributes that carry tiling state on the `AutoencoderKL` family. Read defensively -- a class that
+# has none of them simply has nothing to restore.
_TILING_ATTRS = (
"use_tiling",
"tile_sample_min_size",
- "tile_overlap",
"tile_latent_min_size",
"tile_overlap_factor",
)
@@ -41,28 +48,40 @@ _MISSING = object()
_MIN_DIFFUSERS_LATENT_TILE = 4
+def resolve_tile_size(tile_size: int) -> int:
+ """Resolve a node's ``tile_size`` field to the size the VAE will actually be given.
+
+ ``tile_size <= 0`` is the nodes' "use the default" sentinel -- the workflow UI cannot represent
+ ``None`` in a number input and sends 0, and a negative value is not worth failing a generation
+ over. It resolves to the module-level default rather than to whatever is currently set on the
+ VAE: the instance belongs to the model cache, so reading it back would return whatever the
+ previous invocation left there.
+ """
+ if tile_size <= 0:
+ return DEFAULT_TILE_SAMPLE_MIN_SIZE
+ return max(tile_size, MIN_TILE_SAMPLE_SIZE)
+
+
@contextmanager
def scoped_vae_tiling(vae: Any, tile_size: int | None) -> Iterator[None]:
"""Set the VAE's tiling state for the duration of the block, then restore exactly what was there.
- `tile_size=None` decodes in a single pass; `0` means "the VAE's own default"; any other value is
- the tile size in output pixels.
+ `tile_size=None` runs in a single pass; `0` is the node fields' sentinel and resolves to
+ `DEFAULT_TILE_SAMPLE_MIN_SIZE`, *not* to the VAE's own `sample_size` -- which is 1024 for the
+ FLUX.1 autoencoder and would not tile a 1024px image at all. Any other value is the tile size in
+ output pixels, floored at `MIN_TILE_SAMPLE_SIZE`.
"""
original = {name: getattr(vae, name, _MISSING) for name in _TILING_ATTRS}
try:
if tile_size is None:
vae.disable_tiling()
- elif _accepts_tile_size(vae):
- # resolve_tile_size owns the 0/negative sentinel and the cost floor, so every caller
- # gets the same answer for the same field value.
- vae.enable_tiling(tile_sample_min_size=resolve_tile_size(tile_size))
else:
# Diffusers' `AutoencoderKL.enable_tiling()` takes no arguments and leaves the geometry
- # at the VAE's own `sample_size` -- 1024 for Z-Image, which means a 1024px decode does
- # not tile at all while the caller's working-memory reservation assumes it did. Setting
- # the two attributes afterwards is how the rest of this codebase sizes a diffusers VAE's
- # tiles; see `flux2/ref_image_extension.py`, which forces 512 for the same reason. Both
- # are in `_TILING_ATTRS`, so the finally block puts them back.
+ # at the VAE's own `sample_size` -- 1024 for the FLUX.1 autoencoder, which means a
+ # 1024px decode does not tile at all while the caller's working-memory reservation
+ # assumes it did. Setting the two attributes afterwards is how the rest of this codebase
+ # sizes a diffusers VAE's tiles; see `flux2/ref_image_extension.py`, which forces 512
+ # for the same reason. Both are in `_TILING_ATTRS`, so the finally block puts them back.
downsample = diffusers_vae_downsample(vae)
latent_tile = diffusers_latent_tile(resolve_tile_size(tile_size), downsample, vae.tile_overlap_factor)
vae.enable_tiling()
@@ -75,11 +94,6 @@ def scoped_vae_tiling(vae: Any, tile_size: int | None) -> Iterator[None]:
setattr(vae, name, value)
-def _accepts_tile_size(vae: Any) -> bool:
- """True if `enable_tiling` takes a tile size. Diffusers' AutoencoderKL takes no arguments."""
- return isinstance(vae, AutoEncoder)
-
-
def diffusers_vae_downsample(vae: Any) -> int:
"""Output pixels per latent element along one axis, for the diffusers VAE classes.
diff --git a/invokeai/backend/util/vae_working_memory.py b/invokeai/backend/util/vae_working_memory.py
index ea1b9f1131..4aff57b3b7 100644
--- a/invokeai/backend/util/vae_working_memory.py
+++ b/invokeai/backend/util/vae_working_memory.py
@@ -8,9 +8,9 @@ from diffusers.models.autoencoders.autoencoder_kl_wan import AutoencoderKLWan
from diffusers.models.autoencoders.autoencoder_tiny import AutoencoderTiny
from invokeai.app.invocations.constants import LATENT_SCALE_FACTOR
-from invokeai.backend.flux.modules.autoencoder import AutoEncoder, resolve_tile_size
from invokeai.backend.util.attention import sdpa_score_matrix_bytes
from invokeai.backend.util.devices import TorchDevice
+from invokeai.backend.util.vae_tiling_scope import resolve_tile_size
# 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
@@ -119,12 +119,14 @@ def estimate_vae_working_memory_cogview4(
# What a tiled decode does *not* bound: the assembled image, several times over, per output pixel.
#
-# `AutoEncoder._tiled_decode` moves each tile to the host and merges there, so it lands one stacked
-# copy back on the device. Diffusers' `AutoencoderKL.tiled_decode` -- the other class this estimator
-# serves, through the Z-Image node -- assembles entirely on the device: every decoded tile stays
-# live in `rows` while the cropped rows and then the concatenated result are built. On top of
-# either, a decode node runs `clamp(-1, 1)`, `+ 1.0` and `* 127.5` over the result and then
-# `.byte()` it: more element-size RGB buffers plus the 8-bit one.
+# `AutoencoderKL.tiled_decode` assembles entirely on the device: every decoded tile stays live in
+# `rows` while the cropped rows and then the concatenated result are built. On top of that, a decode
+# node runs `clamp(-1, 1)`, `+ 1.0` and `* 127.5` over the result and then `.byte()` it: more
+# element-size RGB buffers plus the 8-bit one.
+#
+# The measurement below was taken when this estimator also served InvokeAI's own port of the BFL
+# autoencoder, which merged on the *host* and therefore had a far smaller slope. That class is gone;
+# the constant is kept at the value that covers the diffusers slope, which is the one that remains.
#
# Measured on this repo's fixtures (RTX 4090, fp32), device peak over baseline against one full
# image, at 1024px and 2048px:
@@ -141,11 +143,15 @@ def estimate_vae_working_memory_cogview4(
_FLUX_VAE_TILED_IMAGE_COPIES = 4
_IMAGE_CHANNELS = 3
+# An encoder emits mean and logvar before `DiagonalGaussianDistribution` splits them, so the tensor
+# a tiled encode assembles is twice the latent width.
+_VAE_MOMENT_CHANNELS_PER_LATENT = 2
+
def estimate_vae_working_memory_flux(
operation: Literal["encode", "decode"],
image_tensor: torch.Tensor,
- vae: AutoEncoder,
+ vae: AutoencoderKL,
tile_size: int | None = None,
) -> int:
"""Estimate the working memory required by the invocation in bytes.
@@ -156,8 +162,9 @@ def estimate_vae_working_memory_flux(
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.
"""
latent_scale_factor_for_operation = LATENT_SCALE_FACTOR if operation == "decode" else 1
@@ -187,7 +194,35 @@ def estimate_vae_working_memory_flux(
tile_w = min(tile, out_w)
# A 25% margin for tile overlap and the number of tiles, mirroring the SD1/SDXL estimator.
working_memory = tile_h * tile_w * element_size * scaling_constant * 1.25
- working_memory += out_h * out_w * _IMAGE_CHANNELS * (_FLUX_VAE_TILED_IMAGE_COPIES * element_size + 1)
+ if operation == "decode":
+ working_memory += out_h * out_w * _IMAGE_CHANNELS * (_FLUX_VAE_TILED_IMAGE_COPIES * element_size + 1)
+ else:
+ # A tiled encode leaves two things un-bounded: the full-resolution image it slices tiles
+ # from, and the moments it assembles.
+ #
+ # The moments are *not* one copy. `AutoencoderKL._tiled_encode` appends every encoded
+ # tile to `rows`, then builds `result_rows` from them -- blending against `rows[i-1][j]`,
+ # so `rows` stays live throughout -- and finally concatenates `enc` on top of both. The
+ # tiles overlap, so their total area is `1 / (1 - overlap_factor)**2` times the output;
+ # `result_rows` and `enc` are one output each. Hence the factor below, which is 3.78 at
+ # the 0.25 every `AutoencoderKL` ships.
+ #
+ # Read from the VAE rather than hard-coded: an overlap factor of 0.5 would make the
+ # tiles alone four times the output, and a fixed 3.78 would then under-reserve. An
+ # estimate consumed as `free >= estimate` has to err upwards.
+ config = getattr(vae, "config", None)
+ latent_channels = getattr(config, "latent_channels", 16)
+ overlap_factor = getattr(vae, "tile_overlap_factor", 0.25)
+ live_moment_copies = 1.0 / (1.0 - overlap_factor) ** 2 + 2.0
+ moments = (
+ (out_h // LATENT_SCALE_FACTOR)
+ * (out_w // LATENT_SCALE_FACTOR)
+ * _VAE_MOMENT_CHANNELS_PER_LATENT
+ * latent_channels
+ * element_size
+ )
+ working_memory += out_h * out_w * _IMAGE_CHANNELS * element_size
+ working_memory += moments * live_moment_copies
score_h, score_w = tile_h, tile_w
else:
working_memory = out_h * out_w * element_size * scaling_constant
@@ -370,6 +405,20 @@ def estimate_vae_working_memory_anima(
w = tile_size
# Add 25% to account for tile overlap.
working_memory = h * w * element_size * scaling_constant * 1.25
+ if operation == "encode":
+ # ...plus what tiling does not bound on the encode: the full-resolution frame the tiles
+ # are sliced from, and the moments assembled out of them. Without these the estimate is
+ # flat while the measurement grows about 4 bytes per pixel -- measured on a 4090 at 1.07x
+ # headroom at 1024px falling to 0.69x at 4096px, i.e. an under-reservation, and this node
+ # has no tiled retry to fall back on the way its decode sibling does.
+ #
+ # The decode has the same kind of un-bounded assembly and does not price it either. That
+ # is pre-existing -- `anima_l2i` has tiled since it was written -- and is left alone here
+ # rather than changed in a diff about the encode.
+ frame_h, frame_w = image_tensor.shape[-2], image_tensor.shape[-1]
+ latent_area = (frame_h // LATENT_SCALE_FACTOR) * (frame_w // LATENT_SCALE_FACTOR)
+ working_memory += frame_h * frame_w * _IMAGE_CHANNELS * element_size
+ working_memory += latent_area * _VAE_MOMENT_CHANNELS_PER_LATENT * vae.config.z_dim * element_size
else:
latent_scale_factor_for_operation = LATENT_SCALE_FACTOR if operation == "decode" else 1
h = latent_scale_factor_for_operation * image_tensor.shape[-2]
diff --git a/invokeai/frontend/web/openapi.json b/invokeai/frontend/web/openapi.json
index ecfe653d15..c9c2400752 100644
--- a/invokeai/frontend/web/openapi.json
+++ b/invokeai/frontend/web/openapi.json
@@ -17449,6 +17449,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": "anima_i2l",
"default": "anima_i2l",
@@ -17461,7 +17482,7 @@
"tags": ["image", "latents", "vae", "i2l", "anima"],
"title": "Image to Latents - Anima",
"type": "object",
- "version": "1.0.2",
+ "version": "1.1.0",
"output": {
"$ref": "#/components/schemas/LatentsOutput"
}
@@ -38441,6 +38462,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 128 are raised to 128.",
+ "field_kind": "input",
+ "input": "any",
+ "multipleOf": 8,
+ "orig_default": 0,
+ "orig_required": false,
+ "title": "Tile Size",
+ "type": "integer"
+ },
"type": {
"const": "flux_vae_decode",
"default": "flux_vae_decode",
@@ -38453,7 +38495,7 @@
"tags": ["latents", "image", "vae", "l2i", "flux"],
"title": "Latents to Image - FLUX",
"type": "object",
- "version": "1.0.2",
+ "version": "1.1.0",
"output": {
"$ref": "#/components/schemas/ImageOutput"
}
@@ -38519,6 +38561,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 128 are raised to 128.",
+ "field_kind": "input",
+ "input": "any",
+ "multipleOf": 8,
+ "orig_default": 0,
+ "orig_required": false,
+ "title": "Tile Size",
+ "type": "integer"
+ },
"type": {
"const": "flux_vae_encode",
"default": "flux_vae_encode",
@@ -38531,7 +38594,7 @@
"tags": ["latents", "image", "vae", "i2l", "flux"],
"title": "Image to Latents - FLUX",
"type": "object",
- "version": "1.0.1",
+ "version": "1.1.0",
"output": {
"$ref": "#/components/schemas/LatentsOutput"
}
@@ -87897,7 +87960,7 @@
}
],
"default": null,
- "description": "FLUX AutoEncoder VAE. PiD upscale runs the FLUX backbone and applies FLUX VAE scaling, and the encode path only supports InvokeAI's FLUX AutoEncoder \u2014 a diffusers AutoencoderKL (e.g. Z-Image) is not supported here.",
+ "description": "The FLUX.1 VAE, which Z-Image also uses. PiD upscale runs the FLUX backbone and undoes FLUX VAE scaling, so a VAE of another family is not accepted.",
"field_kind": "input",
"input": "connection",
"orig_required": true
@@ -110899,7 +110962,7 @@
"category": "latents",
"class": "invocation",
"classification": "prototype",
- "description": "Generates latents from an image using Z-Image VAE (supports both Diffusers and FLUX VAE).",
+ "description": "Generates latents from an image using the Z-Image VAE.",
"node_pack": "invokeai",
"properties": {
"board": {
@@ -110988,6 +111051,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 128 are raised to 128.",
+ "field_kind": "input",
+ "input": "any",
+ "multipleOf": 8,
+ "orig_default": 0,
+ "orig_required": false,
+ "title": "Tile Size",
+ "type": "integer"
+ },
"type": {
"const": "z_image_i2l",
"default": "z_image_i2l",
@@ -111000,7 +111084,7 @@
"tags": ["image", "latents", "vae", "i2l", "z-image"],
"title": "Image to Latents - Z-Image",
"type": "object",
- "version": "1.1.0",
+ "version": "1.2.0",
"output": {
"$ref": "#/components/schemas/LatentsOutput"
}
@@ -111009,7 +111093,7 @@
"category": "latents",
"class": "invocation",
"classification": "prototype",
- "description": "Generates an image from latents using Z-Image VAE (supports both Diffusers and FLUX VAE).",
+ "description": "Generates an image from latents using the Z-Image VAE.",
"node_pack": "invokeai",
"properties": {
"board": {
@@ -111110,7 +111194,7 @@
},
"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.",
+ "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 128 are raised to 128.",
"field_kind": "input",
"input": "any",
"multipleOf": 8,
diff --git a/invokeai/frontend/web/src/services/api/schema.ts b/invokeai/frontend/web/src/services/api/schema.ts
index 075d9976f5..c7e48c2894 100644
--- a/invokeai/frontend/web/src/services/api/schema.ts
+++ b/invokeai/frontend/web/src/services/api/schema.ts
@@ -4846,6 +4846,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 anima_i2l
@@ -15421,6 +15433,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 128 are raised to 128.
+ * @default 0
+ */
+ tile_size?: number;
/**
* type
* @default flux_vae_decode
@@ -15460,6 +15484,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 128 are raised to 128.
+ * @default 0
+ */
+ tile_size?: number;
/**
* type
* @default flux_vae_encode
@@ -37653,7 +37689,7 @@ export type components = {
*/
image?: components["schemas"]["ImageField"] | null;
/**
- * @description FLUX AutoEncoder VAE. PiD upscale runs the FLUX backbone and applies FLUX VAE scaling, and the encode path only supports InvokeAI's FLUX AutoEncoder — a diffusers AutoencoderKL (e.g. Z-Image) is not supported here.
+ * @description The FLUX.1 VAE, which Z-Image also uses. PiD upscale runs the FLUX backbone and undoes FLUX VAE scaling, so a VAE of another family is not accepted.
* @default null
*/
vae?: components["schemas"]["VAEField"] | null;
@@ -50325,7 +50361,7 @@ export type components = {
};
/**
* Image to Latents - Z-Image
- * @description Generates latents from an image using Z-Image VAE (supports both Diffusers and FLUX VAE).
+ * @description Generates latents from an image using the Z-Image VAE.
*/
ZImageImageToLatentsInvocation: {
/**
@@ -50365,6 +50401,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 128 are raised to 128.
+ * @default 0
+ */
+ tile_size?: number;
/**
* type
* @default z_image_i2l
@@ -50374,7 +50422,7 @@ export type components = {
};
/**
* Latents to Image - Z-Image
- * @description Generates an image from latents using Z-Image VAE (supports both Diffusers and FLUX VAE).
+ * @description Generates an image from latents using the Z-Image VAE.
*/
ZImageLatentsToImageInvocation: {
/**
@@ -50422,7 +50470,7 @@ export type components = {
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.
+ * @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 128 are raised to 128.
* @default 0
*/
tile_size?: number;
diff --git a/tests/app/invocations/conftest.py b/tests/app/invocations/conftest.py
new file mode 100644
index 0000000000..6aed50a419
--- /dev/null
+++ b/tests/app/invocations/conftest.py
@@ -0,0 +1,49 @@
+"""Shared fixtures for the VAE invocation tests."""
+
+from collections.abc import Callable
+
+import pytest
+from diffusers.models.autoencoders.autoencoder_kl import AutoencoderKL
+
+
+def _build_flux_shaped_vae() -> AutoencoderKL:
+ """A real `AutoencoderKL` with the FLUX.1 VAE's *shape* and almost none of its weight.
+
+ 8059 parameters against 84 million, built in ~6 ms, and it decodes an 8x8 latent in ~7 ms —
+ but it is the genuine class, so the properties these tests are about are the real ones rather
+ than a mock's:
+
+ * four blocks, hence the same 8x spatial compression, which is what `diffusers_latent_tile`
+ computes its geometry from;
+ * `tile_overlap_factor`, `tile_sample_min_size`, `tile_latent_min_size` and `use_tiling` as
+ instance attributes the tiling scope actually reads and restores;
+ * `latent_channels`, `scaling_factor` and `shift_factor`, which is what `is_flux_family_vae`
+ reads -- the class alone no longer says which latent space a VAE encodes into;
+ * a working `tiled_decode`/`tiled_encode`, so a cell can assert the assembled shape rather
+ than only that a flag was set.
+
+ A `MagicMock(spec=AutoencoderKL)` cannot stand in for it: `tile_overlap_factor` is set in
+ `__init__`, so it is not on the class and a spec'd mock does not have it at all — the tiling
+ scope would raise `AttributeError` on a double that looked correct.
+ """
+ return AutoencoderKL(
+ in_channels=3,
+ out_channels=3,
+ down_block_types=("DownEncoderBlock2D",) * 4,
+ up_block_types=("UpDecoderBlock2D",) * 4,
+ block_out_channels=(4, 4, 4, 4),
+ layers_per_block=1,
+ latent_channels=16,
+ norm_num_groups=2,
+ sample_size=64,
+ scaling_factor=0.3611,
+ shift_factor=0.1159,
+ use_quant_conv=False,
+ use_post_quant_conv=False,
+ )
+
+
+def flux_shaped_vae() -> Callable[[], AutoencoderKL]:
+ """Factory, not an instance: a test that needs two independent VAEs should not share one."""
+ return _build_flux_shaped_vae
diff --git a/tests/app/invocations/test_anima_vae.py b/tests/app/invocations/test_anima_vae.py
index 855f0638ba..a44d37b496 100644
--- a/tests/app/invocations/test_anima_vae.py
+++ b/tests/app/invocations/test_anima_vae.py
@@ -97,6 +97,35 @@ class TestEstimateVaeWorkingMemoryAnima:
assert 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):
@@ -184,10 +213,13 @@ class TestAnimaAcceptsBothWan21VaeLayouts:
def _flux_vae_info() -> MagicMock:
- from invokeai.backend.flux.modules.autoencoder import AutoEncoder as FluxAutoEncoder
+ from diffusers.models.autoencoders.autoencoder_kl import AutoencoderKL
vae_info = MagicMock()
- vae_info.model = MagicMock(spec=FluxAutoEncoder)
+ # The FLUX.1 autoencoder is loaded as a diffusers `AutoencoderKL`, which is *not* one of the two
+ # classes `as_qwen_image_vae` accepts (`AutoencoderKLQwenImage`, `AutoencoderKLWan`). So the
+ # refusal is still a class check here -- what changed is which class the FLUX VAE presents as.
+ vae_info.model = MagicMock(spec=AutoencoderKL)
return vae_info
@@ -201,7 +233,7 @@ def _flux_decode_context(vae_info: MagicMock) -> MagicMock:
class TestAnimaRefusesAForeignDecoder:
"""A FLUX VAE has Anima's channel count and compression but a different basis.
- It used to be accepted -- the node had a `FluxAutoEncoder` branch, the picker offered it, and
+ It used to be accepted -- the node had a branch for that class, the picker offered it, and
the decode returned a magenta moire with the subject barely visible while the run reported
success. Measured against the correct decode of the same latent: 8.67 dB PSNR, mean absolute
error 84 of 255. Nothing downstream can tell such an image from an intended one, so the node
diff --git a/tests/app/invocations/test_anima_vae_tiling.py b/tests/app/invocations/test_anima_vae_tiling.py
index 5ff52f3088..a893b3c2d5 100644
--- a/tests/app/invocations/test_anima_vae_tiling.py
+++ b/tests/app/invocations/test_anima_vae_tiling.py
@@ -1,4 +1,4 @@
-"""Tiling state on the Anima latents-to-image node's shared, cached Wan VAE.
+"""Tiling state on the Anima VAE nodes' shared, cached Wan VAE.
`enable_tiling` writes the tile geometry onto the module and `disable_tiling` restores only the
flag, never the sizes -- and the module is the model cache's own instance, shared with the
@@ -12,6 +12,7 @@ from unittest.mock import MagicMock, patch
import torch
from diffusers.models.autoencoders import AutoencoderKLWan
+from invokeai.app.invocations.vae.anima_image_to_latents import AnimaImageToLatentsInvocation
from invokeai.app.invocations.vae.anima_latents_to_image import (
ANIMA_VAE_TILE_SIZE,
ANIMA_VAE_TILE_STRIDE,
@@ -127,3 +128,105 @@ def test_a_tiled_decode_applies_the_calibrated_geometry_and_restores_it():
assert during == [(True, ANIMA_VAE_TILE_SIZE, ANIMA_VAE_TILE_SIZE, ANIMA_VAE_TILE_STRIDE, ANIMA_VAE_TILE_STRIDE)]
assert _tiling_state(vae) == before
+
+
+def _build_encode_context(vae: AutoencoderKLWan):
+ 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.return_value = cm
+
+ context = MagicMock()
+ context.models.load.return_value = vae_info
+ context.images.get_pil.return_value = MagicMock()
+ context.config.get.return_value.force_tiled_decode = False
+ context.tensors.save.return_value = "test_latents"
+ return vae_info, context
+
+
+def _encode(context, vae, image: torch.Tensor, tiled: bool = False, tile_size: int = 0):
+ """Run the encode node end to end, recording the tiling state the encode actually saw."""
+ seen: list[tuple] = []
+ real_encode = vae.encode
+
+ def record(x, return_dict=True):
+ seen.append(_tiling_state(vae))
+ return real_encode(x, return_dict=return_dict)
+
+ vae.encode = record
+ invocation = AnimaImageToLatentsInvocation.model_construct(
+ image=MagicMock(image_name="test.png"),
+ vae=MagicMock(vae=MagicMock()),
+ tiled=tiled,
+ tile_size=tile_size,
+ )
+ with (
+ patch(
+ "invokeai.app.invocations.vae.anima_image_to_latents.image_resized_to_grid_as_tensor",
+ return_value=image[0],
+ ),
+ patch.object(TorchDevice, "choose_torch_device", return_value=torch.device("cpu")),
+ ):
+ invocation.invoke(context)
+ return seen
+
+
+def test_the_encode_is_untiled_by_default_even_on_a_vae_left_tiled():
+ """The node used to call `disable_tiling()` unconditionally, with "encode untiled for exactness"
+ as the reason. That reason still holds for ordinary generation, so it is still the default --
+ what changed is that it is no longer the only option.
+
+ The VAE arrives with tiling *on*, which is the situation the production comment describes
+ ("shared with the decode invocation, which may have enabled tiling"). Starting from a fresh
+ instance would assert a value the fixture already handed over.
+ """
+ vae = _build_tiny_vae()
+ vae.enable_tiling(
+ tile_sample_min_height=256,
+ tile_sample_min_width=256,
+ tile_sample_stride_height=192,
+ tile_sample_stride_width=192,
+ )
+ before = _tiling_state(vae)
+ _, context = _build_encode_context(vae)
+
+ seen = _encode(context, vae, torch.zeros(1, 3, 768, 768))
+
+ assert seen[0][0] is False
+ assert _tiling_state(vae) == before
+
+
+def test_the_encode_field_applies_the_geometry_and_restores_it():
+ vae = _build_tiny_vae()
+ _, context = _build_encode_context(vae)
+ before = _tiling_state(vae)
+
+ seen = _encode(context, vae, torch.zeros(1, 3, 768, 768), tiled=True, tile_size=ANIMA_VAE_TILE_SIZE)
+
+ assert seen[0] == (
+ True,
+ ANIMA_VAE_TILE_SIZE,
+ ANIMA_VAE_TILE_SIZE,
+ ANIMA_VAE_TILE_STRIDE,
+ ANIMA_VAE_TILE_STRIDE,
+ )
+ # The instance is the cache's, shared with the decode node and with the Qwen-Image nodes.
+ assert _tiling_state(vae) == before
+
+
+def test_the_reservation_matches_the_encode_that_will_run():
+ vae = _build_tiny_vae()
+ _, context = _build_encode_context(vae)
+ path = "invokeai.app.invocations.vae.anima_image_to_latents.estimate_vae_working_memory_anima"
+
+ with patch(path, return_value=1024) as estimate:
+ _encode(context, vae, torch.zeros(1, 3, 768, 768), tiled=True, tile_size=ANIMA_VAE_TILE_SIZE)
+ assert estimate.call_args.kwargs["tile_size"] == ANIMA_VAE_TILE_SIZE
+
+ vae = _build_tiny_vae()
+ _, context = _build_encode_context(vae)
+ with patch(path, return_value=1024) as estimate:
+ _encode(context, vae, torch.zeros(1, 3, 768, 768))
+ assert estimate.call_args.kwargs["tile_size"] is None
diff --git a/tests/app/invocations/test_flux_vae_decode_tiling.py b/tests/app/invocations/test_flux_vae_decode_tiling.py
index 9dadc9682d..1f28fbe1bf 100644
--- a/tests/app/invocations/test_flux_vae_decode_tiling.py
+++ b/tests/app/invocations/test_flux_vae_decode_tiling.py
@@ -1,8 +1,13 @@
-"""`force_tiled_decode` on the FLUX.1 latents-to-image node, and its OOM fallback.
+"""Tiling on the FLUX.1 latents-to-image node: the two ways to ask for it, and the OOM fallback.
-The node exposes no tiling fields -- adding any would change the invocation schema -- so the app
-config switch is the only way a user can ask it for a tiled decode. It used to be ignored here
-while the Z-Image, SD and Qwen-Image decode nodes all honoured it.
+The node gained `tiled`/`tile_size` when the FLUX.1 VAE became a diffusers `AutoencoderKL`; before
+that the app config switch was the only way to reach a tiled decode here, because the node had no
+fields and adding them to the hand-rolled class would not have bought the encode side anything.
+Both routes are covered, because they are wired separately and either can rot on its own.
+
+The VAE is a real, tiny `AutoencoderKL` (see `conftest.flux_shaped_vae`) rather than a mock, so
+`scoped_vae_tiling` runs its genuine state machine and the assertions are about tiling state that
+actually existed rather than about calls that were recorded.
"""
from unittest.mock import MagicMock, patch
@@ -11,17 +16,29 @@ import pytest
import torch
from invokeai.app.invocations.vae.flux_vae_decode import FluxVaeDecodeInvocation
-from invokeai.backend.flux.modules.autoencoder import DEFAULT_TILE_SAMPLE_MIN_SIZE
-from invokeai.backend.flux.modules.autoencoder import AutoEncoder as FluxAutoEncoder
+from invokeai.backend.util.vae_tiling_scope import DEFAULT_TILE_SAMPLE_MIN_SIZE
+
+
+def _build_decode_mocks(vae, latents: torch.Tensor, decoded: torch.Tensor, force_tiled_decode: bool = False):
+ """Wire FluxVaeDecodeInvocation.invoke to run end-to-end on CPU against a real tiny VAE.
+ `decode` is replaced so the test controls the result and can raise, and so the tiling state at
+ the moment of the call can be recorded -- that is the thing under test, and it is restored by
+ the time `invoke` returns.
+ """
+ tiling_state: list[dict] = []
-def _build_decode_mocks(latents: torch.Tensor, decoded: torch.Tensor, force_tiled_decode: bool = False):
- """Wire FluxVaeDecodeInvocation.invoke to run end-to-end on CPU against a mocked FLUX VAE."""
- vae = MagicMock(spec=FluxAutoEncoder)
- # A fresh iterator per call: the decode path reads `parameters()` after the estimator already
- # has, and a single stored iterator would be exhausted by then.
- vae.parameters.side_effect = lambda: iter([torch.zeros(1, dtype=torch.float16)])
- vae.decode.return_value = decoded
+ def record_and_return(latents_arg, return_dict=True):
+ tiling_state.append(
+ {
+ "use_tiling": vae.use_tiling,
+ "tile_sample_min_size": vae.tile_sample_min_size,
+ "tile_latent_min_size": vae.tile_latent_min_size,
+ }
+ )
+ return (decoded,) if return_dict is False else MagicMock(sample=decoded)
+
+ vae.decode = MagicMock(side_effect=record_and_return)
vae_info = MagicMock()
vae_info.model = vae
@@ -41,66 +58,103 @@ def _build_decode_mocks(latents: torch.Tensor, decoded: torch.Tensor, force_tile
image_dto.width = decoded.shape[-1]
image_dto.height = decoded.shape[-2]
context.images.save.return_value = image_dto
- return vae, vae_info, context
+ return vae_info, context, tiling_state
-def _build_invocation() -> FluxVaeDecodeInvocation:
+def _build_invocation(tiled: bool = False, tile_size: int = 0) -> FluxVaeDecodeInvocation:
return FluxVaeDecodeInvocation.model_construct(
latents=MagicMock(latents_name="test_latents"),
vae=MagicMock(vae=MagicMock()),
+ tiled=tiled,
+ tile_size=tile_size,
)
-class TestForceTiledDecode:
- def test_the_default_decodes_untiled(self):
- vae, _, context = _build_decode_mocks(torch.zeros(1, 16, 64, 64), torch.zeros(1, 3, 512, 512))
+class TestAskingForTiling:
+ 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()
-
- def test_the_config_flag_reaches_the_tiled_path(self):
- vae, _, context = _build_decode_mocks(
- torch.zeros(1, 16, 64, 64), torch.zeros(1, 3, 512, 512), force_tiled_decode=True
+ assert state == [{"use_tiling": False, "tile_sample_min_size": 64, "tile_latent_min_size": 8}]
+
+ 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, tile_size=256).invoke(context)
+ 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):
+ 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)
- vae.disable_tiling.assert_not_called()
-
- @pytest.mark.parametrize("force_tiled_decode,expected_tile_size", [(False, None), (True, 0)])
- def test_the_reservation_matches_the_decode_that_will_run(self, force_tiled_decode, expected_tile_size):
+ assert state[0]["use_tiling"] is True
+ # 0 is the "model default" sentinel, which resolves to the shipped tile.
+ 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 belongs to the model cache; a tiled decode must not leave the next one tiled."""
+ 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=256).invoke(context)
+ assert (vae.use_tiling, vae.tile_sample_min_size, vae.tile_latent_min_size) == before
+
+ @pytest.mark.parametrize(
+ "tiled,force_tiled_decode,expected_tile_size",
+ [(False, False, None), (True, False, 256), (False, True, 0)],
+ )
+ def test_the_reservation_matches_the_decode_that_will_run(
+ self, flux_shaped_vae, tiled, force_tiled_decode, expected_tile_size
+ ):
"""A tiled decode reserved for a single pass is the OOM the retry exists to avoid, and an
untiled 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
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)
assert vae.decode.call_count == 2
- vae.enable_tiling.assert_called_once_with(tile_sample_min_size=DEFAULT_TILE_SAMPLE_MIN_SIZE)
+ assert state[0]["use_tiling"] is False
+ assert state[1]["use_tiling"] is True
# The retry takes noticeably longer than the failed attempt; the user is told why.
context.util.signal_progress.assert_any_call("VAE decode ran out of memory, retrying tiled")
assert result.width == 512
- def test_an_oom_while_already_tiled_reraises(self):
- vae, _, context = _build_decode_mocks(
- torch.zeros(1, 16, 64, 64), torch.zeros(1, 3, 512, 512), force_tiled_decode=True
+ def test_an_oom_while_already_tiled_reraises(self, flux_shaped_vae):
+ vae = flux_shaped_vae()
+ _, context, _ = _build_decode_mocks(
+ vae, torch.zeros(1, 16, 64, 64), torch.zeros(1, 3, 512, 512), force_tiled_decode=True
)
- vae.decode.side_effect = torch.cuda.OutOfMemoryError("CUDA out of memory")
+ vae.decode = MagicMock(side_effect=torch.cuda.OutOfMemoryError("CUDA out of memory"))
with pytest.raises(torch.cuda.OutOfMemoryError):
_build_invocation().invoke(context)
assert vae.decode.call_count == 1
- vae.enable_tiling.assert_called_once()
diff --git a/tests/app/invocations/test_flux_vae_encode_tiling.py b/tests/app/invocations/test_flux_vae_encode_tiling.py
new file mode 100644
index 0000000000..81cdc37579
--- /dev/null
+++ b/tests/app/invocations/test_flux_vae_encode_tiling.py
@@ -0,0 +1,202 @@
+"""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
+
+
[email protected](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
+ 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 --git a/tests/app/invocations/test_z_image_tiled_decode.py b/tests/app/invocations/test_z_image_tiled_decode.py
index e29c074ff1..37f73fb8db 100644
--- a/tests/app/invocations/test_z_image_tiled_decode.py
+++ b/tests/app/invocations/test_z_image_tiled_decode.py
@@ -6,18 +6,26 @@ import pytest
import torch
from diffusers.models.autoencoders.autoencoder_kl import AutoencoderKL
+from invokeai.app.invocations.vae.z_image_image_to_latents import ZImageImageToLatentsInvocation
from invokeai.app.invocations.vae.z_image_latents_to_image import ZImageLatentsToImageInvocation
-from invokeai.backend.flux.modules.autoencoder import DEFAULT_TILE_SAMPLE_MIN_SIZE, MIN_TILE_SAMPLE_SIZE
-from invokeai.backend.flux.modules.autoencoder import AutoEncoder as FluxAutoEncoder
+from invokeai.backend.util.devices import TorchDevice
+from invokeai.backend.util.vae_tiling_scope import DEFAULT_TILE_SAMPLE_MIN_SIZE, MIN_TILE_SAMPLE_SIZE
from invokeai.backend.util.vae_working_memory import estimate_vae_working_memory_flux
def _mock_flux_vae(element_size_bytes: int = 2) -> MagicMock:
- vae = MagicMock(spec=FluxAutoEncoder)
+ """A stand-in for the estimator cells only: they read nothing but the parameter element size.
+
+ The node-wiring cells below use a real `AutoencoderKL`, because they are about tiling state a
+ mock cannot have -- `tile_overlap_factor` is set in `__init__`, so a spec'd mock lacks it.
+ """
+ vae = MagicMock(spec=AutoencoderKL)
dtype = torch.float16 if element_size_bytes == 2 else torch.float32
# A fresh iterator per call: the decode path reads `parameters()` after the estimator already
# has, and a single stored iterator would be exhausted by then.
vae.parameters.side_effect = lambda: iter([torch.zeros(1, dtype=dtype)])
+ # The tiled *encode* residual prices the assembled moments, so it reads the latent width.
+ vae.config.latent_channels = 16
return vae
@@ -173,10 +181,93 @@ class TestFluxWorkingMemoryEstimate:
)
-def _build_decode_mocks(latents: torch.Tensor, decoded: torch.Tensor, force_tiled_decode: bool = False):
- """Wire ZImageLatentsToImageInvocation.invoke to run end-to-end on CPU against a mocked FLUX VAE."""
- vae = _mock_flux_vae()
- vae.decode.return_value = decoded
+class TestTheEncodeEstimate:
+ """Nothing exercised this estimator with `operation="encode"` before the FLUX.1 VAE could tile
+ an encode at all -- its docstring said as much: "a `tile_size` with `operation="encode"` would
+ price a tiled encode that cannot happen, and no call site passes one".
+
+ The tile-bounded term is shared with the decode. What tiling does *not* bound is not: a decode
+ assembles an image several times over and then converts it to bytes, while an encode consumes
+ its input once and accumulates latents at 1/64 the area. Inheriting the decode residual would
+ over-reserve by a wide margin on exactly the resolutions this feature exists for.
+ """
+
+ @pytest.fixture(autouse=True)
+ def _fused_non_rocm_build(self, monkeypatch):
+ monkeypatch.setattr("invokeai.backend.util.vae_working_memory.sdpa_score_matrix_bytes", lambda *a, **k: 0)
+ monkeypatch.setattr(torch.version, "hip", None, raising=False)
+
+ def test_the_untiled_estimate_is_unchanged(self):
+ """Four call sites pass no tile and depend on this number staying what it was."""
+ image = torch.zeros(1, 3, 1024, 1024)
+ assert estimate_vae_working_memory_flux("encode", image, _mock_flux_vae()) == 1024 * 1024 * 2 * 1100
+
+ def test_a_tiled_estimate_is_flat_in_the_image_size_where_the_untiled_one_is_not(self):
+ vae = _mock_flux_vae()
+ estimates = [
+ estimate_vae_working_memory_flux("encode", torch.zeros(1, 3, edge, edge), vae, tile_size=512)
+ for edge in (1024, 2048, 3072)
+ ]
+ # Not exactly equal: the input image and the assembled latent are not bounded by tiling.
+ # But they are a rounding error beside the tile term, which is what "flat" has to mean.
+ assert max(estimates) < min(estimates) * 1.2
+ untiled = [
+ estimate_vae_working_memory_flux("encode", torch.zeros(1, 3, edge, edge), vae) for edge in (1024, 3072)
+ ]
+ assert untiled[1] == untiled[0] * 9
+
+ def test_the_tiled_estimate_is_one_tile_plus_the_input_and_every_live_copy_of_the_moments(self):
+ """The moments are not one copy. `AutoencoderKL._tiled_encode` keeps every encoded tile in
+ `rows` while it builds `result_rows` from them, then concatenates `enc` on top of both; the
+ tiles overlap, so they alone are `1/(1-0.25)**2` of the output area."""
+ vae = _mock_flux_vae()
+ edge, tile = 2048, 512
+ live_moment_copies = 1.0 / (1.0 - 0.25) ** 2 + 2.0
+ expected = tile * tile * 2 * 1100 * 1.25
+ expected += edge * edge * 3 * 2
+ expected += (edge // 8) * (edge // 8) * 2 * 16 * 2 * live_moment_copies
+ assert estimate_vae_working_memory_flux("encode", torch.zeros(1, 3, edge, edge), vae, tile_size=tile) == int(
+ expected
+ )
+
+ def test_it_does_not_inherit_the_decode_residual(self):
+ """The decode adds four element-size copies of the assembled image plus a byte buffer, for
+ the node's `clamp/*127.5/.byte()` tail. An encode has no such tail, and the cost of assuming
+ it does is a reservation the cache has to evict models to honour."""
+ vae = _mock_flux_vae()
+ image = torch.zeros(1, 3, 2048, 2048)
+ latents = torch.zeros(1, 16, 2048 // 8, 2048 // 8)
+
+ encode = estimate_vae_working_memory_flux("encode", image, vae, tile_size=512)
+ decode = estimate_vae_working_memory_flux("decode", latents, vae, tile_size=512)
+
+ # Same tile, same output area, so the whole difference is the residual term.
+ assert decode - encode > 2048 * 2048 * 3 * 2, "the encode is paying for the decode's image copies"
+
+ def test_a_tile_larger_than_the_image_is_priced_as_the_untiled_encode(self):
+ """`scoped_vae_tiling` hands the VAE a tile it will not use below its own threshold, and an
+ oversized tile would otherwise reserve for a pass that never runs."""
+ vae = _mock_flux_vae()
+ image = torch.zeros(1, 3, 512, 512)
+ assert estimate_vae_working_memory_flux(
+ "encode", image, vae, tile_size=1024
+ ) == estimate_vae_working_memory_flux("encode", image, vae)
+
+
+def _build_decode_mocks(vae, latents: torch.Tensor, decoded: torch.Tensor, force_tiled_decode: bool = False):
+ """Wire ZImageLatentsToImageInvocation.invoke to run end-to-end on CPU against a real tiny VAE.
+
+ `decode` is replaced so the test controls the result and can raise, and so the tiling state at
+ the moment of the call is recorded -- that is the thing under test, and the scope has restored
+ it by the time `invoke` returns.
+ """
+ tiling_state: list[dict] = []
+
+ def record_and_return(latents_arg, return_dict=True):
+ tiling_state.append({"use_tiling": vae.use_tiling, "tile_sample_min_size": vae.tile_sample_min_size})
+ return (decoded,) if return_dict is False else MagicMock(sample=decoded)
+
+ vae.decode = MagicMock(side_effect=record_and_return)
vae_info = MagicMock()
vae_info.model = vae
@@ -196,48 +287,63 @@ def _build_decode_mocks(latents: torch.Tensor, decoded: torch.Tensor, force_tile
image_dto.width = decoded.shape[-1]
image_dto.height = decoded.shape[-2]
context.images.save.return_value = image_dto
- return vae, vae_info, context
+ return vae_info, context, tiling_state
def _build_invocation(tiled: bool = False, tile_size: int = 0) -> ZImageLatentsToImageInvocation:
+ # `seamless_axes=[]` rather than a MagicMock: the node patches seamless for every VAE it accepts
+ # now that there is only one class, and `SeamlessExt` would iterate a MagicMock.
return ZImageLatentsToImageInvocation.model_construct(
latents=MagicMock(latents_name="test_latents"),
- vae=MagicMock(vae=MagicMock()),
+ vae=MagicMock(vae=MagicMock(), seamless_axes=[]),
tiled=tiled,
tile_size=tile_size,
)
class 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, 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)
+ assert state[0]["tile_sample_min_size"] == 384
- 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_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)
- vae.enable_tiling.assert_called_once_with(tile_sample_min_size=384)
+ assert (vae.use_tiling, vae.tile_sample_min_size, vae.tile_latent_min_size) == before
@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
@@ -253,37 +359,105 @@ class TestOomFallback:
RuntimeError("Native API failed. Native API returns: UR_RESULT_ERROR_OUT_OF_DEVICE_MEMORY"),
],
)
- def test_an_untiled_oom_retries_once_tiled(self, oom_error):
+ def test_an_untiled_oom_retries_once_tiled(self, flux_shaped_vae, oom_error):
+ 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 = [oom_error, decoded]
+ _, context, state = _build_decode_mocks(vae, torch.zeros(1, 16, 64, 64), decoded)
+ calls = {"n": 0}
+ record = vae.decode.side_effect
+
+ def fail_then_succeed(latents_arg, return_dict=True):
+ calls["n"] += 1
+ result = record(latents_arg, return_dict=return_dict)
+ if calls["n"] == 1:
+ raise oom_error
+ return result
+
+ vae.decode = MagicMock(side_effect=fail_then_succeed)
result = _build_invocation().invoke(context)
assert vae.decode.call_count == 2
- vae.enable_tiling.assert_called_once_with(tile_sample_min_size=DEFAULT_TILE_SAMPLE_MIN_SIZE)
+ assert [call["use_tiling"] for call in state] == [False, True]
assert result.width == 512
# The user gets a different image than they asked for, so both channels have to carry it: the
# progress line while it happens, and a log line a bug report can still be read off afterwards.
context.util.signal_progress.assert_any_call("VAE decode ran out of memory, retrying tiled")
assert "not identical to an untiled decode" in context.logger.warning.call_args[0][0]
- def test_a_non_oom_error_propagates_without_a_retry(self):
- vae, _, context = _build_decode_mocks(torch.zeros(1, 16, 64, 64), torch.zeros(1, 3, 512, 512))
- vae.decode.side_effect = RuntimeError("Input type (float) and weight type (half) should be the same")
+ def test_a_non_oom_error_propagates_without_a_retry(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))
+ vae.decode = MagicMock(side_effect=RuntimeError("Input type (float) and weight type (half) should be the same"))
with pytest.raises(RuntimeError, match="weight type"):
_build_invocation().invoke(context)
assert vae.decode.call_count == 1
- vae.enable_tiling.assert_not_called()
+ assert state == []
- def test_an_oom_while_already_tiled_reraises(self):
- vae, _, context = _build_decode_mocks(torch.zeros(1, 16, 64, 64), torch.zeros(1, 3, 512, 512))
- vae.decode.side_effect = torch.cuda.OutOfMemoryError("CUDA out of memory")
+ def test_an_oom_while_already_tiled_reraises(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))
+ record = vae.decode.side_effect
+
+ def record_then_fail(latents_arg, return_dict=True):
+ record(latents_arg, return_dict=return_dict)
+ raise torch.cuda.OutOfMemoryError("CUDA out of memory")
+
+ vae.decode = MagicMock(side_effect=record_then_fail)
with 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
+ 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
diff --git a/tests/app/invocations/test_z_image_working_memory.py b/tests/app/invocations/test_z_image_working_memory.py
index 644da2ef5c..c04e44e2b0 100644
--- a/tests/app/invocations/test_z_image_working_memory.py
+++ b/tests/app/invocations/test_z_image_working_memory.py
@@ -1,142 +1,81 @@
-"""Test that Z-Image VAE invocations properly estimate and request working memory."""
+"""The Z-Image VAE nodes reserve what they estimated.
+
+Narrow on purpose: `test_z_image_tiled_decode.py` covers *what* is estimated (tile-bounded or not),
+and this covers that the number reaches the model cache at all. Both nodes, because the reservation
+is wired separately in each and either can be dropped without the other noticing.
+
+The earlier version of this file wrapped each invocation in `except Exception: pass`, which made it
+pass whether or not the node worked -- only the two mock assertions were load-bearing. The nodes run
+for real here instead, against the tiny `AutoencoderKL` from `conftest`.
+"""
from unittest.mock import MagicMock, patch
import pytest
import torch
-from diffusers.models.autoencoders.autoencoder_kl import AutoencoderKL
from invokeai.app.invocations.vae.z_image_image_to_latents import ZImageImageToLatentsInvocation
-from invokeai.backend.flux.modules.autoencoder import AutoEncoder as FluxAutoEncoder
-
-
-class TestZImageWorkingMemory:
- """Test that Z-Image VAE invocations request working memory."""
-
- @pytest.mark.parametrize("vae_type", [AutoencoderKL, FluxAutoEncoder])
- def test_z_image_latents_to_image_requests_working_memory(self, vae_type):
- """Test that ZImageLatentsToImageInvocation estimates and requests working memory."""
- # Create mock VAE
- mock_vae = MagicMock(spec=vae_type)
-
- # Only set config for AutoencoderKL (FluxAutoEncoder doesn't use config)
- if vae_type == AutoencoderKL:
- mock_vae.config.scaling_factor = 1.0
- mock_vae.config.shift_factor = None
-
- # Create mock parameter for dtype detection
- mock_param = torch.zeros(1)
- mock_vae.parameters.return_value = iter([mock_param])
-
- # Create mock vae_info
- mock_vae_info = MagicMock()
- mock_vae_info.model = mock_vae
- # Decode places latents on the VAE's intended compute device (see #9373); this must be a
- # real torch.device so `latents.to(device=...)` works instead of raising TypeError.
- mock_vae_info.compute_device = torch.device("cpu")
-
- # Create mock context manager return value
- mock_cm = MagicMock()
- mock_cm.__enter__ = MagicMock(return_value=(None, mock_vae))
- mock_cm.__exit__ = MagicMock(return_value=None)
- mock_vae_info.model_on_device = MagicMock(return_value=mock_cm)
-
- # Mock the context
- mock_context = MagicMock()
- mock_context.models.load.return_value = mock_vae_info
-
- # Mock latents
- mock_latents = torch.zeros(1, 16, 64, 64)
- mock_context.tensors.load.return_value = mock_latents
-
- estimation_path = "invokeai.app.invocations.vae.z_image_latents_to_image.estimate_vae_working_memory_flux"
-
- with patch(estimation_path) as mock_estimate:
- expected_memory = 1024 * 1024 * 500 # 500MB
- mock_estimate.return_value = expected_memory
-
- # Mock VAE decode to avoid actual computation
- if vae_type == FluxAutoEncoder:
- mock_vae.decode.return_value = torch.zeros(1, 3, 512, 512)
- else:
- mock_vae.decode.return_value = (torch.zeros(1, 3, 512, 512),)
-
- # Mock image save
- mock_image_dto = MagicMock()
- mock_context.images.save.return_value = mock_image_dto
-
- # Import and create invocation using model_construct to bypass validation
- from invokeai.app.invocations.vae.z_image_latents_to_image import ZImageLatentsToImageInvocation
-
- invocation = ZImageLatentsToImageInvocation.model_construct(
+from invokeai.app.invocations.vae.z_image_latents_to_image import ZImageLatentsToImageInvocation
+
+
[email protected](autouse=True)
+def _pin_to_cpu(monkeypatch):
+ """Both nodes move their input to `choose_torch_device()`, which is CUDA on a machine that has
+ one -- while the VAE here stays on the CPU, so the encode would die on a device mismatch. The
+ previous version of this file hid exactly that behind `except Exception: pass`."""
+ monkeypatch.setattr(
+ "invokeai.backend.util.devices.TorchDevice.choose_torch_device", staticmethod(lambda: torch.device("cpu"))
+ )
+
+
+def _vae_info(vae) -> MagicMock:
+ vae_info = MagicMock()
+ vae_info.model = vae
+ # Decode places latents on the VAE's intended compute device (see #9373); this must be a real
+ # torch.device so `latents.to(device=...)` works instead of raising TypeError.
+ 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 = MagicMock(return_value=cm)
+ return vae_info
+
+
+class TestTheEstimateReachesTheCache:
+ def test_the_decode_node_reserves_what_it_estimated(self, flux_shaped_vae):
+ vae = flux_shaped_vae()
+ vae_info = _vae_info(vae)
+
+ context = MagicMock()
+ context.models.load.return_value = vae_info
+ context.tensors.load.return_value = torch.zeros(1, 16, 64, 64)
+ context.config.get.return_value.force_tiled_decode = False
+ # `ImageOutput.build` validates these, so they cannot be bare MagicMocks.
+ context.images.save.return_value = MagicMock(image_name="test.png", width=512, height=512)
+
+ expected_memory = 500 * 1024 * 1024
+ path = "invokeai.app.invocations.vae.z_image_latents_to_image.estimate_vae_working_memory_flux"
+ with patch(path, return_value=expected_memory) as estimate:
+ ZImageLatentsToImageInvocation.model_construct(
latents=MagicMock(latents_name="test_latents"),
- vae=MagicMock(vae=MagicMock(), seamless_axes=["x", "y"]),
- )
-
- try:
- invocation.invoke(mock_context)
- except Exception:
- # We expect some errors due to mocking, but we just want to verify the working memory was requested
- pass
-
- # Verify that working memory estimation was called
- mock_estimate.assert_called_once()
- # Verify that model_on_device was called with the estimated working memory
- mock_vae_info.model_on_device.assert_called_once_with(working_mem_bytes=expected_memory)
-
- @pytest.mark.parametrize("vae_type", [AutoencoderKL, FluxAutoEncoder])
- def test_z_image_image_to_latents_requests_working_memory(self, vae_type):
- """Test that ZImageImageToLatentsInvocation estimates and requests working memory."""
- # Create mock VAE
- mock_vae = MagicMock(spec=vae_type)
-
- # Only set config for AutoencoderKL (FluxAutoEncoder doesn't use config)
- if vae_type == AutoencoderKL:
- mock_vae.config.scaling_factor = 1.0
- mock_vae.config.shift_factor = None
-
- # Create mock parameter for dtype detection
- mock_param = torch.zeros(1)
- mock_vae.parameters.return_value = iter([mock_param])
-
- # Create mock vae_info
- mock_vae_info = MagicMock()
- mock_vae_info.model = mock_vae
-
- # Create mock context manager return value
- mock_cm = MagicMock()
- mock_cm.__enter__ = MagicMock(return_value=(None, mock_vae))
- mock_cm.__exit__ = MagicMock(return_value=None)
- mock_vae_info.model_on_device = MagicMock(return_value=mock_cm)
-
- # Mock image tensor
- mock_image_tensor = torch.zeros(1, 3, 512, 512)
-
- # Mock the estimation function
- estimation_path = "invokeai.app.invocations.vae.z_image_image_to_latents.estimate_vae_working_memory_flux"
-
- with patch(estimation_path) as mock_estimate:
- expected_memory = 1024 * 1024 * 250 # 250MB
- mock_estimate.return_value = expected_memory
-
- # Mock VAE encode to avoid actual computation
- if vae_type == FluxAutoEncoder:
- mock_vae.encode.return_value = torch.zeros(1, 16, 64, 64)
- else:
- mock_latent_dist = MagicMock()
- mock_latent_dist.sample.return_value = torch.zeros(1, 16, 64, 64)
- mock_encode_result = MagicMock()
- mock_encode_result.latent_dist = mock_latent_dist
- mock_vae.encode.return_value = mock_encode_result
-
- # Call the static method directly
- try:
- ZImageImageToLatentsInvocation.vae_encode(mock_vae_info, mock_image_tensor)
- except Exception:
- # We expect some errors due to mocking, but we just want to verify the working memory was requested
- pass
-
- # Verify that working memory estimation was called
- mock_estimate.assert_called_once()
- # Verify that model_on_device was called with the estimated working memory
- mock_vae_info.model_on_device.assert_called_once_with(working_mem_bytes=expected_memory)
+ vae=MagicMock(vae=MagicMock(), seamless_axes=[]),
+ tiled=False,
+ tile_size=0,
+ ).invoke(context)
+
+ estimate.assert_called_once()
+ vae_info.model_on_device.assert_called_once_with(working_mem_bytes=expected_memory)
+
+ def test_the_encode_node_reserves_what_it_estimated(self, flux_shaped_vae):
+ vae = flux_shaped_vae()
+ vae_info = _vae_info(vae)
+
+ expected_memory = 250 * 1024 * 1024
+ path = "invokeai.app.invocations.vae.z_image_image_to_latents.estimate_vae_working_memory_flux"
+ with patch(path, return_value=expected_memory) as estimate:
+ latents = ZImageImageToLatentsInvocation.vae_encode(vae_info, torch.zeros(1, 3, 512, 512))
+
+ estimate.assert_called_once()
+ vae_info.model_on_device.assert_called_once_with(working_mem_bytes=expected_memory)
+ # The encode really ran: a 512px image through an 8x, 16-channel VAE is a 64px latent.
+ assert latents.shape == (1, 16, 64, 64)
diff --git a/tests/backend/flux/extensions/test_kontext_extension.py b/tests/backend/flux/extensions/test_kontext_extension.py
new file mode 100644
index 0000000000..d6d5cb0d9f
--- /dev/null
+++ b/tests/backend/flux/extensions/test_kontext_extension.py
@@ -0,0 +1,155 @@
+"""The Kontext reference encode: its normalisation, and the fallback that makes it survivable.
+
+Two things about this path are easy to get wrong and impossible to notice afterwards.
+
+**The normalisation is hand-written here.** The FLUX.1 VAE used to be InvokeAI's own class, whose
+`encode(sample=False)` applied `scale * (raw - shift)` internally. It is a diffusers `AutoencoderKL`
+now, which leaves that to the caller, so this extension re-derives it inline. A dropped shift or a
+swapped order offsets every reference latent by ~0.042 in latent space: reference adherence degrades
+and nothing raises.
+
+**Nothing on this path resizes.** `flux_kontext.py` only wraps the `ImageField`; the reference is
+encoded at whatever resolution the user supplied. At 3072px that reserves 19.3 GiB, which no
+consumer card has spare beside a resident transformer -- so the encode carries an OOM fallback, and
+the fallback has to produce a usable latent rather than merely not crash.
+"""
+
+from unittest.mock import MagicMock
+
+import pytest
+import torch
+from diffusers.models.autoencoders.autoencoder_kl import AutoencoderKL
+from PIL import Image
+
+from invokeai.backend.flux.extensions.kontext_extension import KontextExtension
+
+
+def _tiny_vae() -> AutoencoderKL:
+ """FLUX-shaped: four blocks for the real 8x compression, and the FLUX normalisation constants."""
+ return AutoencoderKL(
+ in_channels=3,
+ out_channels=3,
+ down_block_types=("DownEncoderBlock2D",) * 4,
+ up_block_types=("UpDecoderBlock2D",) * 4,
+ block_out_channels=(4, 4, 4, 4),
+ layers_per_block=1,
+ latent_channels=16,
+ norm_num_groups=2,
+ sample_size=64,
+ scaling_factor=0.3611,
+ shift_factor=0.1159,
+ use_quant_conv=False,
+ use_post_quant_conv=False,
+ ).eval()
+
+
+def _extension(vae: AutoencoderKL, image: Image.Image) -> KontextExtension:
+ """Build the extension without a model cache, and let `__init__` do the encode."""
+ 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.return_value = cm
+
+ context = MagicMock()
+ context.models.load.return_value = vae_info
+ context.images.get_pil.return_value = image
+
+ return KontextExtension(
+ kontext_conditioning=[MagicMock(image=MagicMock(image_name="reference.png"))],
+ context=context,
+ vae_field=MagicMock(),
+ device=torch.device("cpu"),
+ dtype=torch.float32,
+ )
+
+
[email protected](autouse=True)
+def _pin_to_cpu(monkeypatch):
+ monkeypatch.setattr(
+ "invokeai.backend.util.devices.TorchDevice.choose_torch_device", staticmethod(lambda: torch.device("cpu"))
+ )
+
+
+def _reference_image(edge: int = 64) -> Image.Image:
+ torch.manual_seed(0)
+ pixels = (torch.rand(edge, edge, 3) * 255).byte().numpy()
+ return Image.fromarray(pixels, mode="RGB")
+
+
+class TestTheNormalisation:
+ def test_it_matches_the_convention_the_deleted_class_applied_internally(self):
+ """`scale * (raw - shift)` on the distribution mode, which is what `sample=False` returned."""
+ vae = _tiny_vae()
+ image = _reference_image()
+
+ extension = _extension(vae, image)
+
+ # Recompute it from the VAE directly, the way the deleted class did in one step.
+ tensor = torch.from_numpy(torch.tensor(list(image.tobytes()), dtype=torch.uint8).numpy())
+ tensor = tensor.reshape(64, 64, 3).permute(2, 0, 1).float() / 255.0
+ tensor = (tensor * 2.0 - 1.0).unsqueeze(0)
+ with torch.no_grad():
+ raw = vae.encode(tensor).latent_dist.mode()
+ expected = (raw - vae.config.shift_factor) * vae.config.scaling_factor
+
+ # `kontext_latents` is packed 2x2; compare against the same packing of the expectation.
+ from invokeai.backend.flux.sampling_utils import pack
+
+ assert torch.allclose(extension.kontext_latents, pack(expected), atol=1e-5)
+
+ def test_dropping_the_shift_would_be_visible(self):
+ """A guard on the guard: the shift is small, so a cell that cannot see it is not testing it."""
+ vae = _tiny_vae()
+ image = _reference_image()
+ extension = _extension(vae, image)
+
+ tensor = torch.from_numpy(torch.tensor(list(image.tobytes()), dtype=torch.uint8).numpy())
+ tensor = tensor.reshape(64, 64, 3).permute(2, 0, 1).float() / 255.0
+ tensor = (tensor * 2.0 - 1.0).unsqueeze(0)
+ with torch.no_grad():
+ raw = vae.encode(tensor).latent_dist.mode()
+ without_shift = raw * vae.config.scaling_factor
+
+ from invokeai.backend.flux.sampling_utils import pack
+
+ assert not torch.allclose(extension.kontext_latents, pack(without_shift), atol=1e-5)
+
+
+class TestTheOomFallback:
+ def test_an_oom_retries_tiled_and_still_produces_the_reference(self):
+ vae = _tiny_vae()
+ image = _reference_image(edge=768)
+ real_encode = vae.encode
+ calls = {"n": 0}
+ tiling_seen: list[bool] = []
+
+ def fail_then_succeed(x, return_dict=True):
+ calls["n"] += 1
+ tiling_seen.append(vae.use_tiling)
+ if calls["n"] == 1:
+ raise torch.cuda.OutOfMemoryError("CUDA out of memory")
+ return real_encode(x, return_dict=return_dict)
+
+ vae.encode = fail_then_succeed
+ before = (vae.use_tiling, vae.tile_sample_min_size, vae.tile_latent_min_size)
+
+ extension = _extension(vae, image)
+
+ assert calls["n"] == 2
+ assert tiling_seen == [False, True], "the retry is the tiled one"
+ assert extension.kontext_latents.shape[-1] == 64, "a usable latent, not just a survived call"
+ # The VAE is the cache's; the fallback must not leave it tiled for the next node.
+ assert (vae.use_tiling, vae.tile_sample_min_size, vae.tile_latent_min_size) == before
+
+ def test_a_non_oom_error_propagates(self):
+ vae = _tiny_vae()
+
+ def boom(x, return_dict=True):
+ raise RuntimeError("Input type (float) and weight type (half) should be the same")
+
+ vae.encode = boom
+
+ with pytest.raises(RuntimeError, match="weight type"):
+ _extension(vae, _reference_image())
diff --git a/tests/backend/flux/modules/test_autoencoder_tiling.py b/tests/backend/flux/modules/test_autoencoder_tiling.py
deleted file mode 100644
index 79cc2c6218..0000000000
--- a/tests/backend/flux/modules/test_autoencoder_tiling.py
+++ /dev/null
@@ -1,288 +0,0 @@
-"""Tiled decode for InvokeAI's FLUX.1 autoencoder.
-
-The reference numbers for tiled-vs-untiled agreement come from measurement, not taste: diffusers'
-own tiling of this VAE gives max 0.082 / mean 0.0022 per pixel at 1536px on a +/-1 image. A tiled
-decode of this architecture can never be exact, because the decoder's GroupNorms normalise over the
-whole spatial extent and its mid-block attention is global -- both see a different input when the
-image arrives in tiles. `test_the_full_decoder_lands_in_the_measured_accuracy_band` pins that gap
-from both sides on the shipping decoder. What *is* exact is the tile geometry, and
-`test_geometry_is_exact_without_the_global_operators` pins it by removing those two operators and
-demanding equality.
-"""
-
-import numpy as np
-import pytest
-import torch
-from torch import nn
-
-from invokeai.backend.flux.modules.autoencoder import (
- DEFAULT_TILE_OVERLAP,
- DEFAULT_TILE_SAMPLE_MIN_SIZE,
- AutoEncoder,
- AutoEncoderParams,
-)
-
-
-def _build_autoencoder() -> AutoEncoder:
- """A structurally faithful but tiny FLUX.1 autoencoder: same block layout and the same
- 8x spatial compression, with the channel counts cut down so the test runs on CPU."""
- params = AutoEncoderParams(
- resolution=256,
- in_channels=3,
- ch=32, # GroupNorm(32) means this cannot go lower
- out_ch=3,
- ch_mult=[1, 2, 4, 4],
- num_res_blocks=1,
- z_channels=16,
- scale_factor=0.3611,
- shift_factor=0.1159,
- )
- torch.manual_seed(0)
- return AutoEncoder(params).eval()
-
-
-def _make_purely_convolutional(ae: AutoEncoder) -> None:
- """Strip the two operators with an unbounded receptive field from the decoder.
-
- Both make a tiled decode differ from an untiled one by construction, everywhere in the image
- rather than only near the seams, which is why they have to go before the geometry can be
- asserted at all.
- """
- ae.decoder.mid.attn_1 = nn.Identity()
- for name, module in list(ae.decoder.named_modules()):
- if not isinstance(module, nn.GroupNorm):
- continue
- parent: nn.Module = ae.decoder
- *path, attr = name.split(".")
- for step in path:
- parent = parent[int(step)] if step.isdigit() else getattr(parent, step)
- setattr(parent, attr, nn.Identity())
-
-
-class TestTilingState:
- def test_tiling_is_off_by_default(self):
- ae = _build_autoencoder()
- assert ae.use_tiling is False
- assert ae.tile_sample_min_size == DEFAULT_TILE_SAMPLE_MIN_SIZE
- assert ae.tile_overlap == DEFAULT_TILE_OVERLAP
-
- def test_spatial_compression_follows_ch_mult(self):
- assert _build_autoencoder().spatial_compression == 8
-
- def test_disable_tiling_restores_the_untiled_result(self):
- ae = _build_autoencoder()
- z = torch.randn(1, 16, 96, 96)
- with torch.no_grad():
- before = ae.decode(z)
- ae.enable_tiling()
- ae.decode(z)
- ae.disable_tiling()
- after = ae.decode(z)
- # The VAE instance is cached and shared across invocations, so a tiled run must not leave
- # the next one tiled.
- assert torch.equal(before, after)
-
- @pytest.mark.parametrize(
- "kwargs,message",
- [
- ({"tile_sample_min_size": 500}, "divisible by 8"),
- ({"tile_overlap": 100}, "divisible by 8"),
- ({"tile_sample_min_size": 128, "tile_overlap": 128}, "must be smaller than"),
- ({"tile_overlap": 0}, "greater than 0"),
- # The automatic overlap for an 8px tile is min(128, 4) rounded down to a multiple of
- # 8, i.e. 0. `merge_tiles_with_linear_blending` would take that as a blend band of
- # zero pixels and butt the tiles together with a hard seam instead of blending.
- ({"tile_sample_min_size": 8}, "greater than 0"),
- ],
- )
- def test_geometry_that_cannot_be_sliced_is_rejected(self, kwargs, message):
- # A tile edge that is not a multiple of the compression factor has no exact latent slice,
- # and an overlap at least as large as the tile -- or no overlap at all -- makes the layout
- # degenerate.
- with pytest.raises(ValueError, match=message):
- _build_autoencoder().enable_tiling(**kwargs)
-
-
-class TestTiledDecode:
- def test_the_full_decoder_lands_in_the_measured_accuracy_band(self):
- """The counterweight to the test below: exactness is a property of the *geometry* only.
-
- With the GroupNorms and the mid-block attention left in place -- i.e. the decoder that
- actually ships -- a tiled decode differs from a single-pass one everywhere, because both
- operators see the whole spatial extent and a tile is not the whole image. Measured on this
- fixture at 768px: 0.113 at the shipped 512/128 geometry, against an output range of about
- +/-2.7. The floor rules out the `enable_tiling` docstring's since-corrected claim of float32
- epsilon; the ceiling has ~2.7x headroom over the measurement and rules out a blend band,
- tile offset or slice that is merely plausible rather than right (a 128px tile, four times
- the seams, already drifts to 0.67).
- """
- ae = _build_autoencoder()
- z = torch.randn(1, 16, 96, 96)
- with torch.no_grad():
- untiled = ae.decode(z)
- ae.enable_tiling()
- tiled = ae.decode(z)
- assert 1e-3 < (untiled - tiled).abs().max() < 0.3
-
- def test_geometry_is_exact_without_the_global_operators(self):
- ae = _build_autoencoder()
- _make_purely_convolutional(ae)
- z = torch.randn(1, 16, 96, 96)
- with torch.no_grad():
- untiled = ae.decode(z)
- ae.enable_tiling()
- tiled = ae.decode(z)
- # Purely convolutional: the slicing, the coordinate scale-up and the linear blending must
- # reproduce the single-pass decode to float32 precision, seams included.
- assert torch.allclose(untiled, tiled, atol=1e-6)
-
- @pytest.mark.parametrize(
- "latent_hw",
- [
- (96, 96), # tiles do not divide the image evenly
- (128, 128), # 2x2 tiles, evenly divided
- (100, 77), # odd on both axes
- (64, 160), # tiling on one axis only
- # One axis exactly as small as the latent overlap (128px / 8 = 16). `calc_tiles_min_
- # overlap` clamps the tile down to the image there and then divides by
- # `tile - min_overlap`, which used to raise ZeroDivisionError -- including on the OOM
- # retry, where it replaced the out-of-memory error with a division by zero.
- (16, 96),
- (96, 16),
- # Same clamp, but the long axis now lands on a 15-latent (120px) tile overlap rather
- # than a comfortable 32-latent one. That is *below* the configured 128px overlap, so
- # the blend amount has to come from the clamped overlap; the configured one trips
- # `merge_tiles_with_linear_blending`'s `tile.overlap >= blend_amount` assertion.
- (16, 113),
- # A 1-latent axis leaves no overlap at all once clamped, so the layout is degenerate
- # and the decode falls back to a single pass.
- (1, 96),
- ],
- )
- def test_shape_and_dtype_survive_every_layout(self, latent_hw):
- ae = _build_autoencoder()
- h, w = latent_hw
- z = torch.randn(1, 16, h, w)
- with torch.no_grad():
- untiled = ae.decode(z)
- ae.enable_tiling()
- tiled = ae.decode(z)
- assert tiled.shape == untiled.shape == (1, 3, h * 8, w * 8)
- assert tiled.dtype == untiled.dtype == z.dtype
- assert tiled.device == z.device
-
- def test_an_image_smaller_than_one_tile_is_decoded_in_a_single_pass(self):
- ae = _build_autoencoder()
- z = torch.randn(1, 16, 32, 32) # 256px, well under the 512px tile
- with torch.no_grad():
- untiled = ae.decode(z)
- ae.enable_tiling()
- tiled = ae.decode(z)
- # Not merely close: there is nothing to tile, so it must be the same computation.
- assert torch.equal(untiled, tiled)
-
- def test_batches_are_decoded_independently(self):
- ae = _build_autoencoder()
- _make_purely_convolutional(ae)
- z = torch.randn(2, 16, 96, 96)
- with torch.no_grad():
- ae.enable_tiling()
- batched = ae.decode(z)
- singles = torch.cat([ae.decode(z[i : i + 1]) for i in range(2)])
- assert batched.shape == (2, 3, 768, 768)
- assert torch.allclose(batched, singles, atol=1e-6)
-
- def test_the_shipped_geometry_is_the_accurate_one(self):
- """Smaller tiles are less accurate, not more -- measured, and the reason for the default.
-
- Halving the tile at a fixed image size multiplies the seams, and the blend bands then sit
- closer to each tile's own zero-padded border. On this fixture, purely convolutional, at
- 96x96 latents: 512px tiles reproduce the single-pass decode to 1.0e-07, while 256px tiles
- with the same 128px overlap drift to 4.4e-03 -- four orders of magnitude worse.
- """
- ae = _build_autoencoder()
- _make_purely_convolutional(ae)
- z = torch.randn(1, 16, 96, 96)
- with torch.no_grad():
- untiled = ae.decode(z)
- ae.enable_tiling(tile_sample_min_size=DEFAULT_TILE_SAMPLE_MIN_SIZE)
- shipped = ae.decode(z)
- ae.enable_tiling(tile_sample_min_size=256)
- smaller = ae.decode(z)
-
- assert shipped.shape == smaller.shape == untiled.shape
- assert (untiled - shipped).abs().max() < 1e-6
- assert (untiled - shipped).abs().max() < (untiled - smaller).abs().max()
-
- def test_a_tile_too_small_for_the_default_overlap_shrinks_it_instead_of_raising(self):
- # The workflow UI lets a user type any multiple of 8 into `tile_size`; a value under the
- # default 128px overlap must not turn into a failed generation.
- ae = _build_autoencoder()
- ae.enable_tiling(tile_sample_min_size=128)
- assert ae.tile_overlap == 64
- assert ae.tile_overlap % ae.spatial_compression == 0
- with torch.no_grad():
- assert ae.decode(torch.randn(1, 16, 96, 96)).shape == (1, 3, 768, 768)
-
- def test_every_tile_reaches_the_merge_as_a_host_array(self):
- """What tiling bounds and what it does not.
-
- A tile leaves the decode device as soon as it is decoded, which is what bounds *device*
- memory to one tile. Host memory is a different story: the merge runs after the loop, so it
- receives all of them at once and the host holds the whole image in tiles. The decoder's
- docstring has to say both, and this is the observation behind it.
- """
- ae = _build_autoencoder()
- seen: list[tuple[list[type], int]] = []
-
- import invokeai.backend.flux.modules.autoencoder as autoencoder_module
-
- real_merge = autoencoder_module.merge_tiles_with_linear_blending
-
- def spy(dst_image, tiles, tile_images, blend_amount):
- seen.append(([type(t) for t in tile_images], blend_amount))
- return real_merge(dst_image, tiles, tile_images, blend_amount)
-
- autoencoder_module.merge_tiles_with_linear_blending = spy
- try:
- ae.enable_tiling()
- with torch.no_grad():
- ae.decode(torch.randn(1, 16, 96, 96))
- finally:
- autoencoder_module.merge_tiles_with_linear_blending = real_merge
-
- # 96 latents against a 64-latent tile with a 16-latent minimum overlap needs two tiles per
- # axis, so four in total -- and the merge is handed all four in one call. The blend band is
- # the configured overlap here, because nothing about this layout forces the clamp.
- assert seen == [([np.ndarray] * 4, DEFAULT_TILE_OVERLAP)]
-
- def test_a_clamped_overlap_shrinks_the_blend_band_with_it(self):
- """The blend band has to come from the overlap the layout was built with.
-
- On a 128x904 image the clamp drops the latent overlap from 16 to 15, and the tiler then
- lays the two columns out with exactly 15 latents (120px) of overlap. The configured 128px
- would exceed that, and `merge_tiles_with_linear_blending` asserts every non-edge overlap is
- at least the blend amount -- so passing `self.tile_overlap` here is an AssertionError deep
- in the tiling utility, not a seam.
- """
- ae = _build_autoencoder()
- seen: list[int] = []
-
- import invokeai.backend.flux.modules.autoencoder as autoencoder_module
-
- real_merge = autoencoder_module.merge_tiles_with_linear_blending
-
- def spy(dst_image, tiles, tile_images, blend_amount):
- seen.append(blend_amount)
- return real_merge(dst_image, tiles, tile_images, blend_amount)
-
- autoencoder_module.merge_tiles_with_linear_blending = spy
- try:
- ae.enable_tiling()
- with torch.no_grad():
- decoded = ae.decode(torch.randn(1, 16, 16, 113))
- finally:
- autoencoder_module.merge_tiles_with_linear_blending = real_merge
-
- assert seen == [120]
- assert decoded.shape == (1, 3, 128, 904)
diff --git a/tests/backend/model_manager/load/test_flux_vae_loader.py b/tests/backend/model_manager/load/test_flux_vae_loader.py
new file mode 100644
index 0000000000..fb21077008
--- /dev/null
+++ b/tests/backend/model_manager/load/test_flux_vae_loader.py
@@ -0,0 +1,275 @@
+"""The FLUX.1 VAE loader: the config it builds, and the two packagings it accepts.
+
+The FLUX.1 autoencoder is loaded as a diffusers `AutoencoderKL` rather than through InvokeAI's own
+port of the BFL reference. That is the same network -- measured in fp32 at `maxdiff 1.6e-06` on a
+latent and `1.5e-05` on an image -- and it is what gives the FLUX.1 nodes a tiled *encode*, which
+the port never had.
+
+Two things can break silently and are pinned here:
+
+* **the config.** It is derived from `AutoEncoderParams` and leaves six fields to diffusers'
+ defaults. A changed default in a future diffusers would build a different autoencoder out of the
+ same checkpoint, so the constructed config is compared against the values `black-forest-labs`
+ publishes rather than against the code that produced it.
+* **the refusal.** `VAE_Checkpoint_FLUX_Config` recognises a FLUX VAE by `encoder.conv_in` plus 16
+ latent channels, and `_get_base_or_raise` maps *every* 16-channel checkpoint to `flux`. The SD 3.5
+ and CogView 4 autoencoders are identical in shape to this one -- 244 keys, same shapes, differing
+ only in `scaling_factor`/`shift_factor` -- so a standalone diffusers-layout file, which carries no
+ config, cannot be attributed to a latent space. The loader refuses it rather than stamping FLUX's
+ constants on weights that may not be FLUX's.
+"""
+
+import os
+from pathlib import Path
+from unittest.mock import MagicMock
+
+import pytest
+import torch
+from diffusers.models.autoencoders.autoencoder_kl import AutoencoderKL
+
+from invokeai.backend.flux.util import get_flux_vae_diffusers_config
+from invokeai.backend.model_manager.load.model_loaders.flux import (
+ _FLUX_VAE_BFL_MARKER,
+ _FLUX_VAE_DIFFUSERS_MARKER,
+ FluxVAELoader,
+)
+from invokeai.backend.util.vae_tiling_scope import scoped_vae_tiling
+
+# `black-forest-labs/FLUX.1-dev::vae/config.json` and `…-schnell::vae/config.json`, which are
+# byte-identical to each other (774 bytes). Written out rather than fetched: the point is an
+# expectation that does not move when the code does.
+PUBLISHED_CONFIG = {
+ "act_fn": "silu",
+ "block_out_channels": [128, 256, 512, 512],
+ "down_block_types": ["DownEncoderBlock2D"] * 4,
+ "force_upcast": True,
+ "in_channels": 3,
+ "latent_channels": 16,
+ "latents_mean": None,
+ "latents_std": None,
+ "layers_per_block": 2,
+ "mid_block_add_attention": True,
+ "norm_num_groups": 32,
+ "out_channels": 3,
+ "sample_size": 1024,
+ "scaling_factor": 0.3611,
+ "shift_factor": 0.1159,
+ "up_block_types": ["UpDecoderBlock2D"] * 4,
+ "use_post_quant_conv": False,
+ "use_quant_conv": False,
+}
+
+
+def _loader(dtype: torch.dtype = torch.bfloat16) -> FluxVAELoader:
+ loader = FluxVAELoader.__new__(FluxVAELoader)
+ loader._torch_dtype = dtype
+ loader._torch_device = torch.device("cpu")
+ return loader
+
+
+def _config_for(path: Path) -> MagicMock:
+ from invokeai.backend.model_manager.configs.vae import VAE_Checkpoint_Config_Base
+
+ config = MagicMock(spec=VAE_Checkpoint_Config_Base)
+ config.path = str(path)
+ return config
+
+
+class TestTheConstructedConfig:
+ def test_it_matches_what_black_forest_labs_publishes(self):
+ built = dict(AutoencoderKL(**get_flux_vae_diffusers_config()).config)
+
+ def normalise(value):
+ return list(value) if isinstance(value, (list, tuple)) else value
+
+ differs = {
+ field: (normalise(built.get(field, "<absent>")), normalise(expected))
+ for field, expected in PUBLISHED_CONFIG.items()
+ if normalise(built.get(field, "<absent>")) != normalise(expected)
+ }
+ assert not differs
+
+ # Also the other direction: a *new* constructor argument in a future diffusers, with a
+ # default that changes the network, would pass the loop above by not being in it.
+ # Underscore-prefixed keys are diffusers' own bookkeeping (`_class_name`,
+ # `_diffusers_version`, `_use_default_values`), not network geometry.
+ unexpected = sorted(field for field in set(built) - set(PUBLISHED_CONFIG) if not field.startswith("_"))
+ assert not unexpected, f"diffusers grew config fields this test does not know about: {unexpected}"
+
+ def test_it_is_derived_from_the_bfl_parameters_rather_than_transcribed(self):
+ """`AutoEncoderParams` stays the single source of truth: the PiD nodes read
+ `scale_factor`/`shift_factor` off it, and a value edited there has to reach the loader."""
+ from invokeai.backend.flux.util import get_flux_ae_params
+
+ params = get_flux_ae_params()
+ config = get_flux_vae_diffusers_config()
+ assert config["latent_channels"] == params.z_channels
+ assert config["scaling_factor"] == params.scale_factor
+ assert config["shift_factor"] == params.shift_factor
+ assert config["block_out_channels"] == tuple(params.ch * mult for mult in params.ch_mult)
+ assert config["layers_per_block"] == params.num_res_blocks
+
+
+class TestWhatIsRefused:
+ def test_a_diffusers_layout_checkpoint_is_refused_because_it_cannot_be_attributed(self, tmp_path):
+ """The hazard this refusal exists for.
+
+ Identification sends any 16-channel autoencoder here as `flux`. SD 3.5's VAE has the same
+ 244 keys with the same shapes and differs only in `scaling_factor`/`shift_factor`, so
+ loading a standalone diffusers-layout file means stamping FLUX's constants on weights that
+ may be SD 3.5's -- which loads cleanly, generates without error, and produces an image
+ normalised by the wrong constant that nothing downstream can distinguish from an intended
+ one. `is_flux_family_vae` cannot catch it either: it reads the config the loader synthesised.
+ """
+ from safetensors.torch import save_file
+
+ reference = AutoencoderKL(**get_flux_vae_diffusers_config())
+ assert _FLUX_VAE_DIFFUSERS_MARKER in reference.state_dict(), "the marker must exist in this layout"
+
+ path = tmp_path / "diffusion_pytorch_model.safetensors"
+ save_file({k: v.contiguous() for k, v in list(reference.state_dict().items())[:8]}, path)
+
+ with pytest.raises(ValueError, match="carries no config"):
+ _loader()._load_model(_config_for(path))
+
+ def test_an_sd35_shaped_checkpoint_is_not_silently_loaded_as_flux(self, tmp_path):
+ """The same hazard stated as the thing a user would actually install.
+
+ SD 3.5's VAE is published in the diffusers layout, is 16-channel, and is what
+ `_get_base_or_raise` labels `flux`. If this ever starts loading, the cell above is the one
+ that explains why it must not.
+ """
+ from safetensors.torch import save_file
+
+ sd35 = AutoencoderKL(**dict(get_flux_vae_diffusers_config(), scaling_factor=1.5305, shift_factor=0.0609))
+ path = tmp_path / "diffusion_pytorch_model.safetensors"
+ save_file({k: v.contiguous() for k, v in list(sd35.state_dict().items())[:8]}, path)
+
+ with pytest.raises(ValueError):
+ _loader()._load_model(_config_for(path))
+
+ def test_a_checkpoint_in_no_known_layout_is_refused_by_name(self, tmp_path):
+ from safetensors.torch import save_file
+
+ path = tmp_path / "not_a_flux_vae.safetensors"
+ save_file({"encoder.conv_in.weight": torch.zeros(4, 3, 3, 3)}, path)
+
+ with pytest.raises(ValueError) as excinfo:
+ _loader()._load_model(_config_for(path))
+
+ # The marker is named: "not a FLUX VAE" about a file identification already accepted is not
+ # actionable on its own.
+ assert _FLUX_VAE_BFL_MARKER in str(excinfo.value)
+
+
+_REAL_VAE_ENV = "INVOKEAI_FLUX_VAE_CORPUS"
+
+
+def _real_bfl_vae() -> Path | None:
+ root = os.environ.get(_REAL_VAE_ENV)
+ if not root:
+ return None
+ path = Path(root) / "ae.safetensors"
+ return path if path.exists() else None
+
+
+class TestTheRealCheckpoint:
+ """The BFL `ae.safetensors`, when it is on disk -- the packaging every FLUX install uses.
+
+ Set `INVOKEAI_FLUX_VAE_CORPUS` to a directory holding it. Skipped otherwise: the file is 320 MiB
+ and CI has no business downloading it.
+ """
+
+ def test_it_loads_completely_through_the_conversion(self):
+ path = _real_bfl_vae()
+ if path is None:
+ pytest.skip(f"set {_REAL_VAE_ENV} to a directory holding ae.safetensors")
+
+ model = _loader(torch.float32)._load_model(_config_for(path))
+ unfilled = [k for k, v in model.state_dict().items() if v.is_meta]
+ assert not unfilled, f"{len(unfilled)} tensors were never filled by the conversion"
+
+ def test_a_tiled_decode_stays_inside_the_measured_accuracy_band(self):
+ """The property the deleted `test_autoencoder_tiling.py` asserted, on the class that now
+ does the work.
+
+ A tiled pass is not the untiled one: each tile is convolved against zero padding at its own
+ borders, and the GroupNorms and mid-block attention are global. The node warns the user about
+ exactly that, and this is the bound behind the warning.
+
+ **The bound is on the mean, not the max.** Measured here across three seeds, fp32 on CPU,
+ the max swings between 0.125 and 0.231 at 768px -- unstructured Gaussian latents put the VAE
+ far outside the range a denoiser produces, and one outlier pixel moves it. The mean is stable
+ to three digits over the same seeds (0.00305-0.00318 at 768px, 0.00383-0.00402 at 1536px),
+ so it is the quantity that answers "did the geometry change". The max is kept as a loose
+ sanity ceiling.
+ """
+ path = _real_bfl_vae()
+ if path is None:
+ pytest.skip(f"set {_REAL_VAE_ENV} to a directory holding ae.safetensors")
+
+ vae = _loader(torch.float32)._load_model(_config_for(path)).eval()
+ torch.manual_seed(0)
+ for edge, mean_band in ((768, 0.006), (1536, 0.008)):
+ latents = torch.randn(1, 16, edge // 8, edge // 8)
+ with torch.no_grad():
+ with scoped_vae_tiling(vae, None):
+ untiled = vae.decode(latents, return_dict=False)[0]
+ with scoped_vae_tiling(vae, 0):
+ tiled = vae.decode(latents, return_dict=False)[0]
+ assert tiled.shape == untiled.shape
+ difference = (tiled - untiled).abs()
+ assert difference.mean().item() <= mean_band, (
+ f"{edge}px: mean drift {difference.mean().item():.5f} exceeds {mean_band}"
+ )
+ assert difference.max().item() <= 0.5, f"{edge}px: max drift {difference.max().item():.4f}"
+
+
+class TestTheFamilyGuard:
+ """`isinstance(vae, AutoencoderKL)` used to mean "the FLUX autoencoder" and no longer does.
+
+ The FLUX.1 VAE is an `AutoencoderKL` now -- and so are SD 1.5, SDXL, SD 3.5, CogView 4 and
+ Z-Image's. Two of those even share the 16-channel latent width, so the nodes that used to be
+ protected by the class check need something that still separates the families.
+ """
+
+ @staticmethod
+ def _vae(**overrides) -> AutoencoderKL:
+ config = {
+ "in_channels": 3,
+ "out_channels": 3,
+ "down_block_types": ("DownEncoderBlock2D",) * 4,
+ "up_block_types": ("UpDecoderBlock2D",) * 4,
+ "block_out_channels": (4, 4, 4, 4),
+ "layers_per_block": 1,
+ "norm_num_groups": 2,
+ "sample_size": 64,
+ "latent_channels": 16,
+ "scaling_factor": 0.3611,
+ "shift_factor": 0.1159,
+ }
+ config.update(overrides)
+ return AutoencoderKL(**config)
+
+ def test_the_flux_autoencoder_passes(self):
+ from invokeai.backend.flux.util import is_flux_family_vae
+
+ assert is_flux_family_vae(self._vae()) is True
+
+ def test_an_sd_vae_is_rejected_on_its_latent_width(self):
+ from invokeai.backend.flux.util import is_flux_family_vae
+
+ assert is_flux_family_vae(self._vae(latent_channels=4, scaling_factor=0.18215, shift_factor=None)) is False
+
+ def test_an_sd35_vae_is_rejected_although_it_has_the_same_latent_width(self):
+ """The case the channel count alone does not catch, and the reason the test is on the
+ normalisation: SD 3.5 is 16-channel too, and its latents mean something else."""
+ from invokeai.backend.flux.util import is_flux_family_vae
+
+ assert is_flux_family_vae(self._vae(scaling_factor=1.5305, shift_factor=0.0609)) is False
+
+ def test_something_without_a_config_is_rejected_rather_than_raising(self):
+ from invokeai.backend.flux.util import is_flux_family_vae
+
+ assert is_flux_family_vae(object()) is False
diff --git a/tests/backend/util/test_rocm_sdpa_head_dim_guard.py b/tests/backend/util/test_rocm_sdpa_head_dim_guard.py
index 6dd8805879..8de8430dd3 100644
--- a/tests/backend/util/test_rocm_sdpa_head_dim_guard.py
+++ b/tests/backend/util/test_rocm_sdpa_head_dim_guard.py
@@ -314,13 +314,14 @@ class TestClassicVaeEstimators:
) == (2048 * 2048 * 2 * 2200)
def test_flux1_decode_prices_the_score_matrix_by_tile_when_tiled(self):
- from invokeai.backend.flux.modules.autoencoder import AutoEncoder
+ from diffusers.models.autoencoders.autoencoder_kl import AutoencoderKL
+
from invokeai.backend.util.vae_working_memory import estimate_vae_working_memory_flux
latents = torch.zeros(1, 16, 2048 // 8, 2048 // 8)
- untiled = estimate_vae_working_memory_flux("decode", latents, self._vae(AutoEncoder))
+ untiled = estimate_vae_working_memory_flux("decode", latents, self._vae(AutoencoderKL))
assert untiled == self._score_bytes(2048)
- tiled = estimate_vae_working_memory_flux("decode", latents, self._vae(AutoEncoder), tile_size=1024)
+ tiled = estimate_vae_working_memory_flux("decode", latents, self._vae(AutoencoderKL), tile_size=1024)
assert tiled < self._score_bytes(2048)
assert tiled >= self._score_bytes(1024), "a 1024px tile still materializes its own 16384-token score matrix"
diff --git a/tests/backend/util/test_vae_tiling_scope.py b/tests/backend/util/test_vae_tiling_scope.py
index ce9717e829..d944ec94a3 100644
--- a/tests/backend/util/test_vae_tiling_scope.py
+++ b/tests/backend/util/test_vae_tiling_scope.py
@@ -10,31 +10,12 @@ import pytest
import torch
from diffusers.models.autoencoders.autoencoder_kl import AutoencoderKL
-from invokeai.backend.flux.modules.autoencoder import (
- DEFAULT_TILE_OVERLAP,
+from invokeai.backend.util.vae_tiling_scope import (
DEFAULT_TILE_SAMPLE_MIN_SIZE,
MIN_TILE_SAMPLE_SIZE,
- AutoEncoder,
- AutoEncoderParams,
resolve_tile_size,
+ scoped_vae_tiling,
)
-from invokeai.backend.util.vae_tiling_scope import scoped_vae_tiling
-
-
-def _build_autoencoder() -> AutoEncoder:
- params = AutoEncoderParams(
- resolution=256,
- in_channels=3,
- ch=32,
- out_ch=3,
- ch_mult=[1, 2, 4, 4],
- num_res_blocks=1,
- z_channels=16,
- scale_factor=0.3611,
- shift_factor=0.1159,
- )
- torch.manual_seed(0)
- return AutoEncoder(params).eval()
class TestResolveTileSize:
@@ -55,80 +36,6 @@ class TestResolveTileSize:
assert resolve_tile_size(size) == size
-class TestEveryFieldValueProducesTheRightShape:
- """The sweep upstream #9427 used to catch silent truncation.
-
- That bug cannot occur here -- the destination is preallocated at the exact output size and tiles
- are merged into it, rather than a loop stepping by one quantity and slicing by another -- but the
- guarantee is worth asserting rather than reasoning about, across the shapes most likely to leave
- an awkward remainder.
- """
-
- @pytest.mark.parametrize("latent_hw", [(2, 2), (10, 10), (50, 50), (34, 18), (128, 72), (18, 34), (150, 10)])
- @pytest.mark.parametrize("tile_size", [0, 8, 128, 256, 384, 512, 1024])
- def test_output_shape_is_exact(self, latent_hw, tile_size):
- ae = _build_autoencoder()
- h, w = latent_hw
- z = torch.randn(1, 16, h, w)
- with torch.no_grad(), scoped_vae_tiling(ae, tile_size):
- out = ae.decode(z)
- assert out.shape == (1, 3, h * 8, w * 8)
-
-
-class TestStateIsRestored:
- def test_the_normal_path_restores_everything(self):
- ae = _build_autoencoder()
- before = (ae.use_tiling, ae.tile_sample_min_size, ae.tile_overlap)
- with scoped_vae_tiling(ae, 256):
- assert ae.use_tiling is True
- assert ae.tile_sample_min_size == 256
- assert (ae.use_tiling, ae.tile_sample_min_size, ae.tile_overlap) == before
-
- def test_the_untiled_path_restores_everything(self):
- # Entering with tiling already on: the block must decode untiled and hand the state back.
- ae = _build_autoencoder()
- ae.enable_tiling(tile_sample_min_size=256)
- before = (ae.use_tiling, ae.tile_sample_min_size, ae.tile_overlap)
- with scoped_vae_tiling(ae, None):
- assert ae.use_tiling is False
- assert (ae.use_tiling, ae.tile_sample_min_size, ae.tile_overlap) == before
-
- def test_an_exception_still_restores(self):
- # The OOM retry path raises through this context manager, so `finally` is load-bearing.
- ae = _build_autoencoder()
- before = (ae.use_tiling, ae.tile_sample_min_size, ae.tile_overlap)
- with pytest.raises(RuntimeError, match="boom"):
- with scoped_vae_tiling(ae, 256):
- raise RuntimeError("boom")
- assert (ae.use_tiling, ae.tile_sample_min_size, ae.tile_overlap) == before
-
- def test_geometry_does_not_leak_between_two_scopes(self):
- """The bug this exists for: `disable_tiling()` clears the flag but keeps the geometry, so a
- size set once would otherwise silently become the default for everyone afterwards."""
- ae = _build_autoencoder()
- with scoped_vae_tiling(ae, 256):
- pass
- assert ae.tile_sample_min_size == DEFAULT_TILE_SAMPLE_MIN_SIZE
- assert ae.tile_overlap == DEFAULT_TILE_OVERLAP
- with scoped_vae_tiling(ae, 0):
- assert ae.tile_sample_min_size == DEFAULT_TILE_SAMPLE_MIN_SIZE
-
- def test_a_tiled_decode_does_not_leave_the_shared_vae_tiled(self):
- """Nine nodes reach this class and most never touch the tiling flag -- FLUX.1 encode, PiD,
- and Anima's FLUX branch among them. A leaked flag would silently tile their work."""
- ae = _build_autoencoder()
- z = torch.randn(1, 16, 96, 96)
- with torch.no_grad():
- with scoped_vae_tiling(ae, 0):
- ae.decode(z)
- assert ae.use_tiling is False
- # What an unguarded consumer would get next, decoded with no tiling call of its own.
- after = ae.decode(z)
- ae.disable_tiling()
- expected = ae.decode(z)
- assert torch.equal(after, expected)
-
-
class TestDiffusersVaesAreHandledToo:
"""`AutoencoderKL.enable_tiling()` takes no arguments, so the size has to be set afterwards.
@@ -174,6 +81,57 @@ class TestDiffusersVaesAreHandledToo:
assert vae.tile_sample_min_size == expected_sample
assert vae.tile_latent_min_size == expected_sample // downsample
+ def test_an_exception_still_restores(self):
+ # The OOM retry path raises through this context manager, so `finally` is load-bearing.
+ vae = self._vae()
+ before = (vae.use_tiling, vae.tile_sample_min_size, vae.tile_latent_min_size)
+
+ with pytest.raises(RuntimeError, match="boom"):
+ with scoped_vae_tiling(vae, 256):
+ raise RuntimeError("boom")
+
+ assert (vae.use_tiling, vae.tile_sample_min_size, vae.tile_latent_min_size) == before
+
+ def test_entering_with_tiling_already_on_turns_it_off_and_puts_it_back(self):
+ """The branch `tile_size=None` exists for, and the only one no cell reached.
+
+ Every "default decodes untiled" cell elsewhere builds a fresh VAE, whose `use_tiling` is
+ already False -- so it asserts a value the fixture handed it. This one arrives with tiling on
+ and a non-stock geometry, which is what a shared cache instance looks like after
+ `latents_to_image.py` has called the bare `enable_tiling()` it still calls.
+ """
+ vae = self._vae()
+ vae.enable_tiling()
+ vae.tile_sample_min_size = 384
+ vae.tile_latent_min_size = 48
+ before = (vae.use_tiling, vae.tile_sample_min_size, vae.tile_latent_min_size)
+
+ with scoped_vae_tiling(vae, None):
+ assert vae.use_tiling is False
+
+ assert (vae.use_tiling, vae.tile_sample_min_size, vae.tile_latent_min_size) == before
+
+ def test_every_tile_size_the_field_accepts_assembles_the_full_latent(self):
+ """The decode sweep below, pointed at the encode.
+
+ `_tiled_encode` and `tiled_decode` are separate functions upstream, and `diffusers_latent_tile`
+ derives its snap from the decode expression alone -- justified by a docstring claim that the
+ two admit identical tiles. That claim is true today; this is what notices when a diffusers
+ bump makes it false, which would otherwise show up as a mis-shaped latent that still
+ generates.
+ """
+ vae = self._vae(block_out_channels=(4, 8, 16, 16), norm_num_groups=4).eval()
+ image = torch.zeros(1, 3, 512, 512)
+
+ wrong: list[tuple[int, tuple[int, ...]]] = []
+ for tile_size in range(128, 800, 8):
+ with torch.no_grad(), scoped_vae_tiling(vae, tile_size):
+ latent = vae.encode(image).latent_dist.mean
+ if latent.shape != (1, 4, 64, 64):
+ wrong.append((tile_size, tuple(latent.shape)))
+
+ assert not wrong
+
def test_the_vaes_own_geometry_is_restored(self):
vae = self._vae()
before = (vae.use_tiling, vae.tile_sample_min_size, vae.tile_latent_min_size)
@@ -184,7 +142,7 @@ class TestDiffusersVaesAreHandledToo:
assert (vae.use_tiling, vae.tile_sample_min_size, vae.tile_latent_min_size) == before
def test_every_tile_size_the_field_accepts_assembles_the_full_image(self):
- """The sweep the FLUX sibling above runs, pointed at the class that can actually fail it.
+ """A sweep over every value the node field accepts, on the class that can fail it.
`tiled_decode` steps the latent loop by one quantity and crops each decoded tile by another,
and the two agree only for some tile sizes. Setting `tile_sample_min_size` and