Skip to content

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

fix(architectures): backend owns VAE and scheduler policy; clear capability outage states

Alexander Eichhorn2ae9fdd9967a
diff --git a/.github/workflows/python-tests.yml b/.github/workflows/python-tests.yml
index 8e58e36e00..d26a66c175 100644
--- a/.github/workflows/python-tests.yml
+++ b/.github/workflows/python-tests.yml
@@ -111,6 +111,8 @@ jobs:
# that adds the directory does not also have to remember to add this line.
- 'invokeai/frontend/webv2/src/features/generation/core/__snapshots__/**'
- 'invokeai/frontend/webv2/src/features/generation/core/__fixtures__/**'
+ # test_ideogram4_frontend_bounds.py reads the Ideogram 4 control bounds from here.
+ - 'invokeai/frontend/webv2/src/features/generation/core/settings.ts'
- 'tests/**'
# tests/ covers a few of these (e.g. test_check_pins.py, test_docs_json_export.py)
- 'scripts/**'
diff --git a/invokeai/app/invocations/anima/anima_model_loader.py b/invokeai/app/invocations/anima/anima_model_loader.py
index 29cd7e532a..11ac96e789 100644
--- a/invokeai/app/invocations/anima/anima_model_loader.py
+++ b/invokeai/app/invocations/anima/anima_model_loader.py
@@ -13,6 +13,7 @@ from invokeai.app.invocations.model import (
VAEField,
)
from invokeai.app.services.shared.invocation_context import InvocationContext
+from invokeai.backend.architectures import accepted_vae_bases
from invokeai.backend.model_manager.taxonomy import BaseModelType, ModelType, SubModelType
@@ -56,15 +57,7 @@ class AnimaModelLoaderInvocation(BaseInvocation):
vae_model: ModelIdentifierField = InputField(
description="Standalone VAE model. Anima uses a Wan 2.1 / QwenImage VAE (16-channel).",
input=Input.Direct,
- # The same Wan-family checkpoint whichever of the three bases it was installed under.
- # Declaring nothing here offered every VAE ever installed. A FLUX VAE is *not* among
- # them: it shares the channel count but not the basis, so `anima_l2i` decodes it
- # without error into noise -- 6.10 dB PSNR against the Wan decode, measured.
- ui_model_base=[
- BaseModelType.Anima,
- BaseModelType.QwenImage,
- BaseModelType.Wan,
- ],
+ ui_model_base=accepted_vae_bases(BaseModelType.Anima),
ui_model_type=ModelType.VAE,
title="VAE",
)
diff --git a/invokeai/app/invocations/flux/flux_model_loader.py b/invokeai/app/invocations/flux/flux_model_loader.py
index df4be38173..5133c972a7 100644
--- a/invokeai/app/invocations/flux/flux_model_loader.py
+++ b/invokeai/app/invocations/flux/flux_model_loader.py
@@ -20,6 +20,7 @@ from invokeai.app.util.t5_model_identifier import (
preprocess_t5_encoder_model_identifier,
preprocess_t5_tokenizer_model_identifier,
)
+from invokeai.backend.architectures import accepted_vae_bases
from invokeai.backend.flux.util import get_flux_max_seq_length
from invokeai.backend.model_manager.configs.base import Checkpoint_Config_Base
from invokeai.backend.model_manager.configs.main import Main_SDNQ_Diffusers_FLUX_Config
@@ -78,7 +79,7 @@ class FluxModelLoaderInvocation(BaseInvocation):
default=None,
description=FieldDescriptions.vae_model,
title="VAE",
- ui_model_base=BaseModelType.Flux,
+ ui_model_base=accepted_vae_bases(BaseModelType.Flux),
ui_model_type=ModelType.VAE,
)
diff --git a/invokeai/app/invocations/flux2/flux2_dev_model_loader.py b/invokeai/app/invocations/flux2/flux2_dev_model_loader.py
index 0b013bbcf5..c772a18b41 100644
--- a/invokeai/app/invocations/flux2/flux2_dev_model_loader.py
+++ b/invokeai/app/invocations/flux2/flux2_dev_model_loader.py
@@ -21,6 +21,7 @@ from invokeai.app.invocations.model import (
VAEField,
)
from invokeai.app.services.shared.invocation_context import InvocationContext
+from invokeai.backend.architectures import accepted_vae_bases
from invokeai.backend.model_manager.configs.factory import AnyModelConfig
from invokeai.backend.model_manager.taxonomy import (
BaseModelType,
@@ -81,7 +82,7 @@ class Flux2DevModelLoaderInvocation(BaseInvocation):
description="Standalone FLUX.2 VAE (AutoencoderKLFlux2). "
"If not provided, the VAE is extracted from the Diffusers source model.",
input=Input.Direct,
- ui_model_base=BaseModelType.Flux2,
+ ui_model_base=accepted_vae_bases(BaseModelType.Flux2),
ui_model_type=ModelType.VAE,
title="VAE",
)
diff --git a/invokeai/app/invocations/flux2/flux2_klein_model_loader.py b/invokeai/app/invocations/flux2/flux2_klein_model_loader.py
index dffd55430a..94d338138d 100644
--- a/invokeai/app/invocations/flux2/flux2_klein_model_loader.py
+++ b/invokeai/app/invocations/flux2/flux2_klein_model_loader.py
@@ -22,6 +22,7 @@ from invokeai.app.invocations.model import (
is_self_contained_sdnq_pipeline,
)
from invokeai.app.services.shared.invocation_context import InvocationContext
+from invokeai.backend.architectures import accepted_vae_bases
from invokeai.backend.model_manager.configs.factory import AnyModelConfig
from invokeai.backend.model_manager.taxonomy import (
BaseModelType,
@@ -99,7 +100,7 @@ class Flux2KleinModelLoaderInvocation(BaseInvocation):
# A FLUX VAE was offered here and does not work: it is the legacy `AutoEncoder` class with
# a 16-channel latent space, and decoding a FLUX.2 latent with it raises
# `AutoEncoder.decode() got an unexpected keyword argument 'return_dict'`.
- ui_model_base=BaseModelType.Flux2,
+ ui_model_base=accepted_vae_bases(BaseModelType.Flux2),
ui_model_type=ModelType.VAE,
title="VAE",
)
diff --git a/invokeai/app/invocations/krea2/krea2_model_loader.py b/invokeai/app/invocations/krea2/krea2_model_loader.py
index 5a010f726c..38130eed1d 100644
--- a/invokeai/app/invocations/krea2/krea2_model_loader.py
+++ b/invokeai/app/invocations/krea2/krea2_model_loader.py
@@ -15,6 +15,7 @@ from invokeai.app.invocations.model import (
VAEField,
)
from invokeai.app.services.shared.invocation_context import InvocationContext
+from invokeai.backend.architectures import accepted_vae_bases, accepts_vae
from invokeai.backend.model_manager.taxonomy import BaseModelType, ModelFormat, ModelType, SubModelType
@@ -58,7 +59,7 @@ class Krea2ModelLoaderInvocation(BaseInvocation):
description="Standalone VAE model. Krea-2 uses the Qwen-Image VAE (16-channel). "
"If not provided, the VAE is loaded from the Krea-2 (diffusers) model.",
input=Input.Direct,
- ui_model_base=[BaseModelType.QwenImage, BaseModelType.Anima],
+ ui_model_base=accepted_vae_bases(BaseModelType.Krea2),
ui_model_type=ModelType.VAE,
title="VAE",
)
@@ -85,12 +86,12 @@ class Krea2ModelLoaderInvocation(BaseInvocation):
# Determine VAE source.
if self.vae_model is not None:
vae_config = context.models.get_config(self.vae_model)
- if vae_config.type is not ModelType.VAE or vae_config.base not in (
- BaseModelType.QwenImage,
- BaseModelType.Anima,
+ if vae_config.type is not ModelType.VAE or not accepts_vae(
+ BaseModelType.Krea2, vae_config.base, getattr(vae_config, "latent_channels", None)
):
+ accepted = " or ".join(base.value for base in accepted_vae_bases(BaseModelType.Krea2))
raise ValueError(
- f"VAE '{vae_config.name}' is not compatible with Krea-2. Select a Qwen Image or Anima VAE."
+ f"VAE '{vae_config.name}' is not compatible with Krea-2. Select a VAE of base {accepted}."
)
vae = self.vae_model.model_copy(update={"submodel_type": SubModelType.VAE})
else:
diff --git a/invokeai/app/invocations/qwen_image/qwen_image_model_loader.py b/invokeai/app/invocations/qwen_image/qwen_image_model_loader.py
index 86a18747c9..d6e94b123a 100644
--- a/invokeai/app/invocations/qwen_image/qwen_image_model_loader.py
+++ b/invokeai/app/invocations/qwen_image/qwen_image_model_loader.py
@@ -15,6 +15,7 @@ from invokeai.app.invocations.model import (
VAEField,
)
from invokeai.app.services.shared.invocation_context import InvocationContext
+from invokeai.backend.architectures import accepted_vae_bases
from invokeai.backend.model_manager.taxonomy import BaseModelType, ModelFormat, ModelType, SubModelType
@@ -65,9 +66,7 @@ class QwenImageModelLoaderInvocation(BaseInvocation):
description="Standalone Qwen Image VAE model. "
"If not provided, VAE will be loaded from the Component Source (or from the main model if it is Diffusers).",
input=Input.Direct,
- # The same 16-channel checkpoint is registered under either base depending on which
- # family it was installed for; krea2_model_loader already offers both.
- ui_model_base=[BaseModelType.QwenImage, BaseModelType.Anima],
+ ui_model_base=accepted_vae_bases(BaseModelType.QwenImage),
ui_model_type=ModelType.VAE,
title="VAE",
)
diff --git a/invokeai/app/invocations/sd3/sd3_model_loader.py b/invokeai/app/invocations/sd3/sd3_model_loader.py
index 7d095d96c6..cb5bc1c18c 100644
--- a/invokeai/app/invocations/sd3/sd3_model_loader.py
+++ b/invokeai/app/invocations/sd3/sd3_model_loader.py
@@ -13,6 +13,7 @@ from invokeai.app.util.t5_model_identifier import (
preprocess_t5_encoder_model_identifier,
preprocess_t5_tokenizer_model_identifier,
)
+from invokeai.backend.architectures import accepted_vae_bases
from invokeai.backend.model_manager.taxonomy import BaseModelType, ClipVariantType, ModelType, SubModelType
@@ -74,7 +75,7 @@ class Sd3ModelLoaderInvocation(BaseInvocation):
description=FieldDescriptions.vae_model,
title="VAE",
default=None,
- ui_model_base=BaseModelType.StableDiffusion3,
+ ui_model_base=accepted_vae_bases(BaseModelType.StableDiffusion3),
ui_model_type=ModelType.VAE,
)
diff --git a/invokeai/app/invocations/vae/anima_image_to_latents.py b/invokeai/app/invocations/vae/anima_image_to_latents.py
index 949514ca64..8fe3cc30c5 100644
--- a/invokeai/app/invocations/vae/anima_image_to_latents.py
+++ b/invokeai/app/invocations/vae/anima_image_to_latents.py
@@ -1,19 +1,17 @@
"""Anima image-to-latents invocation.
-Encodes an image to latent space using the Anima VAE (AutoencoderKLWan or FLUX VAE).
+Encodes an image to latent space with the Wan 2.1 VAE, in either layout: the original-layout file loads as
+AutoencoderKLWan, the diffusers-layout Qwen-Image export as AutoencoderKLQwenImage (same weights, same
+latent statistics). Any other encoder is refused, and so is a Wan VAE of another geometry (Wan 2.2's
+48-channel VAE).
-For Wan VAE (AutoencoderKLWan):
- Input image is converted to 5D tensor [B, C, T, H, W] with T=1
- After encoding, latents are normalized: (latents - mean) / std
(inverse of the denormalization in anima_latents_to_image.py)
-
-For FLUX VAE (AutoEncoder):
-- Encoding is handled internally by the FLUX VAE
"""
import einops
import torch
-from diffusers.models.autoencoders import AutoencoderKLWan
from invokeai.app.invocations.baseinvocation import BaseInvocation, Classification, invocation
from invokeai.app.invocations.fields import (
@@ -27,6 +25,7 @@ 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.krea2.vae_compat import as_qwen_image_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
@@ -40,18 +39,21 @@ from invokeai.backend.util.vae_working_memory import (
title="Image to Latents - Anima",
tags=["image", "latents", "vae", "i2l", "anima"],
category="image",
- version="1.0.1",
+ version="1.0.2",
classification=Classification.Prototype,
)
class AnimaImageToLatentsInvocation(BaseInvocation, WithMetadata, WithBoard):
- """Generates latents from an image using the Anima VAE (supports Wan 2.1 and FLUX VAE)."""
+ """Generates latents from an image using the Anima VAE (the Wan 2.1 VAE, in either layout)."""
image: ImageField = InputField(description="The image to encode.")
vae: VAEField = InputField(description=FieldDescriptions.vae, input=Input.Connection)
@staticmethod
def vae_encode(vae_info: LoadedModel, image_tensor: torch.Tensor) -> torch.Tensor:
- if not isinstance(vae_info.model, AutoencoderKLWan):
+ 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)
+ except TypeError as e:
# The encode side of the same mismatch the decode refuses: a FLUX VAE has Anima's
# channel count and compression but a different basis, so it would hand the denoiser
# a latent that means something else. See `anima_latents_to_image` for the measurement.
@@ -59,7 +61,7 @@ class AnimaImageToLatentsInvocation(BaseInvocation, WithMetadata, WithBoard):
"Anima encodes into the 16-channel Wan 2.1 latent space, and "
f"{type(vae_info.model).__name__} is not that encoder. Choose a VAE registered "
"under 'anima', 'qwen-image', or a 16-channel 'wan' VAE."
- )
+ ) from e
estimated_working_memory = estimate_vae_working_memory_anima(
operation="encode",
@@ -68,8 +70,7 @@ class AnimaImageToLatentsInvocation(BaseInvocation, WithMetadata, WithBoard):
tile_size=None,
)
with vae_info.model_on_device(working_mem_bytes=estimated_working_memory) as (_, vae):
- if not isinstance(vae, AutoencoderKLWan):
- raise TypeError(f"Expected AutoencoderKLWan, got {type(vae).__name__}.")
+ vae = as_qwen_image_vae(vae)
vae_dtype = next(iter(vae.parameters())).dtype
image_tensor = image_tensor.to(device=TorchDevice.choose_torch_device(), dtype=vae_dtype)
@@ -78,7 +79,7 @@ class AnimaImageToLatentsInvocation(BaseInvocation, WithMetadata, WithBoard):
# The cached VAE instance is shared with the decode invocation, which
# may have enabled tiling — encode untiled for exactness.
vae.disable_tiling()
- # AutoencoderKLWan expects 5D input [B, C, T, H, W]
+ # 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]
@@ -105,10 +106,8 @@ class AnimaImageToLatentsInvocation(BaseInvocation, WithMetadata, WithBoard):
if image_tensor.dim() == 3:
image_tensor = einops.rearrange(image_tensor, "c h w -> 1 c h w")
+ # `vae_encode` refuses a foreign encoder with a message that says which VAE to pick instead.
vae_info = context.models.load(self.vae.vae)
- if not isinstance(vae_info.model, AutoencoderKLWan):
- raise TypeError(f"Expected AutoencoderKLWan for Anima VAE, got {type(vae_info.model).__name__}.")
-
context.util.signal_progress("Running Anima VAE encode")
latents = self.vae_encode(vae_info=vae_info, image_tensor=image_tensor)
diff --git a/invokeai/app/invocations/vae/anima_latents_to_image.py b/invokeai/app/invocations/vae/anima_latents_to_image.py
index 90c19bff32..68af196577 100644
--- a/invokeai/app/invocations/vae/anima_latents_to_image.py
+++ b/invokeai/app/invocations/vae/anima_latents_to_image.py
@@ -1,7 +1,10 @@
"""Anima latents-to-image invocation.
-Decodes Anima latents using the QwenImage VAE (AutoencoderKLWan) or
-compatible FLUX VAE as fallback.
+Decodes Anima latents with the Wan 2.1 VAE, whichever of the anima, qwen-image or 16-channel wan
+registrations it was installed under and in either layout: the original-layout file loads as
+AutoencoderKLWan, the diffusers-layout Qwen-Image export as AutoencoderKLQwenImage (same weights, same
+latent statistics). Any other decoder is refused, and so is a Wan VAE of another geometry (Wan 2.2's
+48-channel VAE).
Latents from the denoiser are in normalized space (zero-centered). Before
VAE decode, they must be denormalized using the Wan 2.1 per-channel
@@ -11,7 +14,6 @@ The VAE expects 5D latents [B, C, T, H, W] — for single images, T=1.
"""
import torch
-from diffusers.models.autoencoders import AutoencoderKLWan
from einops import rearrange
from PIL import Image
@@ -27,7 +29,11 @@ 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.krea2.vae_compat import patch_qwen_image_vae_tiling
+from invokeai.backend.krea2.vae_compat import (
+ QwenImageCompatibleVAE,
+ as_qwen_image_vae,
+ patch_qwen_image_vae_tiling,
+)
from invokeai.backend.util.devices import TorchDevice
from invokeai.backend.util.oom import is_oom_error
from invokeai.backend.util.vae_decode_diagnostics import (
@@ -54,15 +60,11 @@ ANIMA_VAE_TILE_STRIDE = 384
title="Latents to Image - Anima",
tags=["latents", "image", "vae", "l2i", "anima"],
category="latents",
- version="1.0.3",
+ version="1.0.4",
classification=Classification.Prototype,
)
class AnimaLatentsToImageInvocation(BaseInvocation, WithMetadata, WithBoard):
- """Generates an image from latents using the Anima VAE.
-
- Supports the Wan 2.1 QwenImage VAE (AutoencoderKLWan) with explicit
- latent denormalization, and FLUX VAE as fallback.
- """
+ """Generates an image from latents using the Anima VAE (the Wan 2.1 VAE, in either layout)."""
latents: LatentsField = InputField(description=FieldDescriptions.latents, input=Input.Connection)
vae: VAEField = InputField(description=FieldDescriptions.vae, input=Input.Connection)
@@ -91,7 +93,10 @@ class AnimaLatentsToImageInvocation(BaseInvocation, WithMetadata, WithBoard):
latents = context.tensors.load(self.latents.latents_name)
vae_info = context.models.load(self.vae.vae)
- if not isinstance(vae_info.model, AutoencoderKLWan):
+ 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)
+ except TypeError as e:
# A FLUX VAE reaches here with the right shape -- 16 channels at 8x, same as Anima --
# and decodes without raising, which is why it was offered for a while. It is a
# different basis: measured against the correct decode of the same latent, 8.67 dB
@@ -104,7 +109,7 @@ class AnimaLatentsToImageInvocation(BaseInvocation, WithMetadata, WithBoard):
"'anima', 'qwen-image', or a 16-channel 'wan' VAE -- all three are the same "
"194-tensor checkpoint. A FLUX VAE has the same channel count but a different "
"basis, and converting between them is not implemented."
- )
+ ) from e
full_decode_working_memory = estimate_vae_working_memory_anima(
operation="decode",
@@ -122,8 +127,7 @@ class AnimaLatentsToImageInvocation(BaseInvocation, WithMetadata, WithBoard):
with vae_info.model_on_device(working_mem_bytes=estimated_working_memory) as (_, vae):
context.util.signal_progress("Running Anima VAE decode")
- if not isinstance(vae, AutoencoderKLWan):
- raise TypeError(f"Expected AutoencoderKLWan, got {type(vae).__name__}.")
+ vae = as_qwen_image_vae(vae)
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
@@ -201,7 +205,7 @@ class AnimaLatentsToImageInvocation(BaseInvocation, WithMetadata, WithBoard):
def _recover_nonfinite_decode(
self,
context: InvocationContext,
- vae: AutoencoderKLWan,
+ vae: QwenImageCompatibleVAE,
latents: torch.Tensor,
decoded: torch.Tensor,
latents_finite: bool,
@@ -226,7 +230,7 @@ class AnimaLatentsToImageInvocation(BaseInvocation, WithMetadata, WithBoard):
def _recover_nonfinite_decode_impl(
self,
context: InvocationContext,
- vae: AutoencoderKLWan,
+ vae: QwenImageCompatibleVAE,
latents: torch.Tensor,
decoded: torch.Tensor,
latents_finite: bool,
diff --git a/invokeai/app/invocations/wan/wan_model_loader.py b/invokeai/app/invocations/wan/wan_model_loader.py
index 4a3857e966..1abbe525e8 100644
--- a/invokeai/app/invocations/wan/wan_model_loader.py
+++ b/invokeai/app/invocations/wan/wan_model_loader.py
@@ -15,6 +15,7 @@ from invokeai.app.invocations.model import (
WanTransformerField,
)
from invokeai.app.services.shared.invocation_context import InvocationContext
+from invokeai.backend.architectures import accepted_vae_bases, accepts_vae
from invokeai.backend.model_manager.taxonomy import BaseModelType, ModelFormat, ModelType, SubModelType, WanVariantType
# Transformer-only Wan formats: one file holds exactly one expert, so the A14B MoE
@@ -95,7 +96,7 @@ class WanModelLoaderInvocation(BaseInvocation):
description="Standalone Wan VAE model. If not set, the VAE is loaded from the main model "
"(when in Diffusers format) or from the Component Source.",
input=Input.Direct,
- ui_model_base=BaseModelType.Wan,
+ ui_model_base=accepted_vae_bases(BaseModelType.Wan),
ui_model_type=ModelType.VAE,
title="VAE",
)
@@ -336,11 +337,12 @@ class WanModelLoaderInvocation(BaseInvocation):
context: InvocationContext, model: ModelIdentifierField, main_variant: WanVariantType
) -> None:
vae_config = context.models.get_config(model)
- if vae_config.base != BaseModelType.Wan or vae_config.type != ModelType.VAE:
+ if vae_config.type != ModelType.VAE:
raise ValueError("The VAE must resolve to a standalone Wan VAE model.")
- expected_channels = 48 if main_variant == WanVariantType.TI2V_5B else 16
- if vae_config.latent_channels != expected_channels:
+ if not accepts_vae(
+ BaseModelType.Wan, vae_config.base, getattr(vae_config, "latent_channels", None), main_variant
+ ):
raise ValueError(
- "The standalone VAE is incompatible with the selected transformer. "
+ f"The standalone VAE '{vae_config.name}' is incompatible with the selected transformer. "
"TI2V-5B requires the 48-channel Wan 2.2 VAE; A14B models require the 16-channel Wan 2.1 VAE."
)
diff --git a/invokeai/app/invocations/z_image/z_image_model_loader.py b/invokeai/app/invocations/z_image/z_image_model_loader.py
index 2901a2e2ac..feb04b825b 100644
--- a/invokeai/app/invocations/z_image/z_image_model_loader.py
+++ b/invokeai/app/invocations/z_image/z_image_model_loader.py
@@ -16,6 +16,7 @@ from invokeai.app.invocations.model import (
is_self_contained_sdnq_pipeline,
)
from invokeai.app.services.shared.invocation_context import InvocationContext
+from invokeai.backend.architectures import accepted_vae_bases
from invokeai.backend.model_manager.taxonomy import BaseModelType, ModelFormat, ModelType, SubModelType
@@ -61,7 +62,7 @@ class ZImageModelLoaderInvocation(BaseInvocation):
description="Standalone VAE model. Z-Image uses the same VAE as FLUX (16-channel). "
"If not provided, VAE will be loaded from the Qwen3 Source model.",
input=Input.Direct,
- ui_model_base=BaseModelType.Flux,
+ ui_model_base=accepted_vae_bases(BaseModelType.ZImage),
ui_model_type=ModelType.VAE,
title="VAE",
)
diff --git a/invokeai/backend/architectures/__init__.py b/invokeai/backend/architectures/__init__.py
index 97ad2985f4..52fa95a238 100644
--- a/invokeai/backend/architectures/__init__.py
+++ b/invokeai/backend/architectures/__init__.py
@@ -41,6 +41,11 @@ from invokeai.backend.architectures.facets.unet import (
UNetDownscaleFacet,
get_max_unet_downscale,
)
+from invokeai.backend.architectures.facets.vae import (
+ VaeFacet,
+ accepted_vae_bases,
+ accepts_vae,
+)
from invokeai.backend.architectures.facets.variant import (
VariantFacet,
declared_variant_enums,
@@ -72,9 +77,12 @@ __all__ = [
"GenerationModeKind",
"ModalityFacet",
"UNetDownscaleFacet",
+ "VaeFacet",
"VariantFacet",
"LatentSpace",
"LatentSpaceFacet",
+ "accepted_vae_bases",
+ "accepts_vae",
"conditioning_infos",
"conditioning_safe_globals",
"declared_variant_enums",
diff --git a/invokeai/backend/architectures/capabilities.py b/invokeai/backend/architectures/capabilities.py
index 8ff60dc67f..070e2f4e5a 100644
--- a/invokeai/backend/architectures/capabilities.py
+++ b/invokeai/backend/architectures/capabilities.py
@@ -129,7 +129,7 @@ def _features_of(facet: FeaturesFacet, variant: AnyVariant | None = None) -> Arc
guidance_label=facet.guidance_label,
guidance_min=facet.guidance_min,
guidance_max=facet.guidance_max,
- scheduler_set=facet.scheduler_set,
+ scheduler_set=facet.resolve_scheduler_set(variant),
scheduler_applies_to_graph=facet.scheduler_applies_to_graph,
control_kinds=sorted(facet.control_kinds),
max_reference_images=facet.max_reference_images,
@@ -162,7 +162,8 @@ def architecture_capabilities() -> list[ArchitectureCapabilities]:
A variant gets its own row only where something served actually differs: its recommended
parameters (`DefaultSettingsFacet.by_variant`), its dimension grid
- (`FeaturesFacet.dimension_grid_by_variant`) or the VAEs it decodes with (`VaeFacet.by_variant`).
+ (`FeaturesFacet.dimension_grid_by_variant`), its schedulers (`FeaturesFacet.scheduler_set_by_variant`)
+ or the VAEs it decodes with (`VaeFacet.by_variant`).
Those mappings are the whole rule — a row is emitted for the union of their keys, and every row
is rendered in full, so a client never has to know which fields a variant row is allowed to omit.
@@ -192,6 +193,7 @@ def architecture_capabilities() -> list[ArchitectureCapabilities]:
differing = (
set(defaults.by_variant)
| set(features.dimension_grid_by_variant)
+ | set(features.scheduler_set_by_variant)
| set(vae_facet.by_variant if vae_facet is not None else ())
) - {None}
for variant in sorted(differing):
diff --git a/invokeai/backend/architectures/defs/anima.py b/invokeai/backend/architectures/defs/anima.py
index c871a1bb58..fec89d0d6e 100644
--- a/invokeai/backend/architectures/defs/anima.py
+++ b/invokeai/backend/architectures/defs/anima.py
@@ -39,9 +39,9 @@ register(
#
# Not FLUX. `anima_l2i` takes a FluxAutoEncoder without raising, but that branch
# skips the Wan denormalisation and decodes a WAN21_16 latent in FLUX's basis:
- # measured against the Anima VAE on real weights, 6.10 dB PSNR, 0.93 MAE, a
- # magenta moire in place of the subject. Accepting it is a silent corruption, not
- # a fallback. See `tests/backend/architectures/test_vae.py`.
+ # measured on a real denoised latent against the Anima VAE's decode of it, 8.67 dB
+ # PSNR, a magenta moire in place of the subject. Accepting it is a silent corruption,
+ # not a fallback. See `tests/app/invocations/test_anima_vae.py`.
VaeCompatibility(BaseModelType.Anima),
VaeCompatibility(BaseModelType.QwenImage),
VaeCompatibility(BaseModelType.Wan, latent_channels=16),
diff --git a/invokeai/backend/architectures/defs/qwen_image.py b/invokeai/backend/architectures/defs/qwen_image.py
index 23cb5d837c..6f1f375883 100644
--- a/invokeai/backend/architectures/defs/qwen_image.py
+++ b/invokeai/backend/architectures/defs/qwen_image.py
@@ -37,6 +37,8 @@ register(
VaeFacet(
frozenset(
{
+ # The same 16-channel checkpoint is registered under either base depending on which
+ # family it was installed for.
VaeCompatibility(BaseModelType.QwenImage),
VaeCompatibility(BaseModelType.Anima),
}
diff --git a/invokeai/backend/architectures/defs/z_image.py b/invokeai/backend/architectures/defs/z_image.py
index b438c64297..5a18e04261 100644
--- a/invokeai/backend/architectures/defs/z_image.py
+++ b/invokeai/backend/architectures/defs/z_image.py
@@ -35,6 +35,8 @@ register(
# z_image_denoise.guidance_scale is ge=1.0; 1.0 is CFG off, which is what Turbo runs at.
guidance_min=1.0,
scheduler_set="flow",
+ # `z_image_denoise.scheduler` documents LCM as working with Turbo only, not Base.
+ scheduler_set_by_variant={ZImageVariantType.ZBase: "flow-no-lcm"},
scheduler_applies_to_graph=True,
control_kinds=frozenset({"z_image_control"}),
# The text encoder masks positive conditioning; the denoiser takes a negative list but
diff --git a/invokeai/backend/architectures/facets/features.py b/invokeai/backend/architectures/facets/features.py
index a46870f399..548af9baa4 100644
--- a/invokeai/backend/architectures/facets/features.py
+++ b/invokeai/backend/architectures/facets/features.py
@@ -4,12 +4,10 @@ The UI has to know whether to show a negative prompt box, whether a ControlNet l
how many reference images to accept, whether clip-skip means anything. None of it is derivable from
a model file — it follows from what the architecture is — and all of it was living in the frontend.
-webv2 holds the working version of this table for thirteen bases at
-`features/generation/core/baseGenerationPolicies.ts`, plus three more predicates scattered across
-`controlValidation.ts` and `addRegionalGuidance.ts`. Those values are the source for what is
-declared here; the point is not to change them but to move them somewhere a new architecture cannot
-be added without them, and where the three bases webv2 has never heard of — ERNIE-Image, MiniMax H3
-and the SDXL refiner — get an answer too.
+This is where those answers live now. `capabilities.py` serves them, and webv2 reads the served table
+instead of keeping its own copy; a new architecture cannot be registered without declaring them.
+Where a number is enforced by a node -- a `multiple_of`, a `ge`/`le` -- a test pins the declaration to
+that node, so the table cannot offer what the graph will reject.
"""
from collections.abc import Mapping
@@ -24,9 +22,10 @@ NegativePromptUsage = Literal["always", "cfg-gated", "never"]
ControlKind = Literal["controlnet", "t2i_adapter", "control_lora", "z_image_control"]
-SchedulerSet = Literal["standard", "flow", "anima"]
+SchedulerSet = Literal["standard", "flow", "flow-no-lcm", "anima"]
"""Which family of schedulers to offer. `None` means the architecture drives its own and offers no
-choice — MiniMax H3 steps video and audio down two hardcoded flow schedules."""
+choice — MiniMax H3 steps video and audio down two hardcoded flow schedules. `flow-no-lcm` is the flow
+set without LCM, for a variant whose schedule LCM does not fit."""
@dataclass(frozen=True)
@@ -101,6 +100,9 @@ class FeaturesFacet(Facet):
only says the graph will not reject a large value."""
scheduler_set: SchedulerSet | None = None
+ scheduler_set_by_variant: Mapping[AnyVariant, SchedulerSet] = field(default_factory=dict)
+ """A variant whose scheduler choice differs from `scheduler_set`; the declaring architecture says why."""
+
scheduler_applies_to_graph: bool = False
"""Whether the chosen scheduler reaches the graph, or is only a UI affordance."""
@@ -129,6 +131,12 @@ class FeaturesFacet(Facet):
"answer for every variant not named here, and a None key would be dead weight."
)
+ if None in self.scheduler_set_by_variant:
+ raise ValueError(
+ "FeaturesFacet.scheduler_set_by_variant has a None key; `scheduler_set` is already the "
+ "answer for every variant not named here."
+ )
+
if self.guidance_max is not None and self.guidance_max < self.guidance_min:
raise ValueError(
f"FeaturesFacet declares a guidance range that holds no values: guidance_min="
@@ -141,6 +149,12 @@ class FeaturesFacet(Facet):
return self.dimension_grid
return self.dimension_grid_by_variant.get(variant, self.dimension_grid)
+ def resolve_scheduler_set(self, variant: AnyVariant | None = None) -> SchedulerSet | None:
+ """The scheduler family one concrete model is offered."""
+ if variant is None:
+ return self.scheduler_set
+ return self.scheduler_set_by_variant.get(variant, self.scheduler_set)
+
@property
def supports_reference_images(self) -> bool:
return self.max_reference_images > 0
diff --git a/invokeai/backend/architectures/facets/vae.py b/invokeai/backend/architectures/facets/vae.py
index fea5b0b896..742b34d890 100644
--- a/invokeai/backend/architectures/facets/vae.py
+++ b/invokeai/backend/architectures/facets/vae.py
@@ -114,3 +114,15 @@ def accepts_vae(
return vae_base == base
return facet.accepts(vae_base, vae_latent_channels, variant)
+
+
+def accepted_vae_bases(base: BaseModelType) -> list[BaseModelType]:
+ """The VAE bases a loader for `base` offers, as its `vae_model` field's `ui_model_base`.
+
+ Bases only, across every variant: one loader serves all variants and the field cannot express a
+ channel constraint, so the loader's own validation narrows further with `accepts_vae`. Sorted by
+ value because frozenset iteration order follows the hash seed, and this lands in the schema.
+ """
+ facet = get(base, VaeFacet)
+ bases = facet.accepted_bases if facet is not None else frozenset({base})
+ return sorted(bases, key=lambda b: b.value)
diff --git a/invokeai/backend/util/vae_working_memory.py b/invokeai/backend/util/vae_working_memory.py
index 176f7ab669..e2e2dd4442 100644
--- a/invokeai/backend/util/vae_working_memory.py
+++ b/invokeai/backend/util/vae_working_memory.py
@@ -338,11 +338,14 @@ def estimate_vae_working_memory_flux2(
def estimate_vae_working_memory_anima(
operation: Literal["encode", "decode"],
image_tensor: torch.Tensor,
- vae: AutoencoderKLWan,
+ vae: AutoencoderKLWan | AutoencoderKLQwenImage,
tile_size: int | None,
) -> int:
"""Estimate the working memory required to encode or decode with the Wan 2.1 VAE (Anima).
+ Anima reaches that VAE as either class: AutoencoderKLWan (original layout) or AutoencoderKLQwenImage
+ (the diffusers-layout Qwen-Image export), which run the same network on the same weights.
+
The Wan VAE uses 3D convolutions and needs noticeably more working memory per output
pixel than the 2D VAEs estimated above. Calibrated empirically on a 1024x1024 fp16
decode: peak reserved memory was ~5.95GB for a full decode and ~1.73GB with 512px
diff --git a/invokeai/frontend/web/openapi.json b/invokeai/frontend/web/openapi.json
index 6482ab2e0d..7d60d4ed94 100644
--- a/invokeai/frontend/web/openapi.json
+++ b/invokeai/frontend/web/openapi.json
@@ -16242,7 +16242,7 @@
"category": "image",
"class": "invocation",
"classification": "prototype",
- "description": "Generates latents from an image using the Anima VAE (supports Wan 2.1 and FLUX VAE).",
+ "description": "Generates latents from an image using the Anima VAE (the Wan 2.1 VAE, in either layout).",
"node_pack": "invokeai",
"properties": {
"board": {
@@ -16343,7 +16343,7 @@
"tags": ["image", "latents", "vae", "i2l", "anima"],
"title": "Image to Latents - Anima",
"type": "object",
- "version": "1.0.1",
+ "version": "1.0.2",
"output": {
"$ref": "#/components/schemas/LatentsOutput"
}
@@ -16561,7 +16561,7 @@
"category": "latents",
"class": "invocation",
"classification": "prototype",
- "description": "Generates an image from latents using the Anima VAE.\n\nSupports the Wan 2.1 QwenImage VAE (AutoencoderKLWan) with explicit\nlatent denormalization, and FLUX VAE as fallback.",
+ "description": "Generates an image from latents using the Anima VAE (the Wan 2.1 VAE, in either layout).",
"node_pack": "invokeai",
"properties": {
"board": {
@@ -16662,7 +16662,7 @@
"tags": ["latents", "image", "vae", "l2i", "anima"],
"title": "Latents to Image - Anima",
"type": "object",
- "version": "1.0.3",
+ "version": "1.0.4",
"output": {
"$ref": "#/components/schemas/ImageOutput"
}
@@ -17866,7 +17866,7 @@
"anyOf": [
{
"type": "string",
- "enum": ["standard", "flow", "anima"]
+ "enum": ["standard", "flow", "flow-no-lcm", "anima"]
},
{
"type": "null"
@@ -56892,7 +56892,7 @@
"orig_default": null,
"orig_required": false,
"title": "VAE",
- "ui_model_base": ["qwen-image", "anima"],
+ "ui_model_base": ["anima", "qwen-image"],
"ui_model_type": ["vae"]
},
"qwen3_vl_encoder_model": {
@@ -84122,7 +84122,7 @@
"orig_default": null,
"orig_required": false,
"title": "VAE",
- "ui_model_base": ["qwen-image", "anima"],
+ "ui_model_base": ["anima", "qwen-image"],
"ui_model_type": ["vae"]
},
"qwen_vl_encoder_model": {
diff --git a/invokeai/frontend/web/src/services/api/schema.ts b/invokeai/frontend/web/src/services/api/schema.ts
index 9fbe6e7e16..d78f592c02 100644
--- a/invokeai/frontend/web/src/services/api/schema.ts
+++ b/invokeai/frontend/web/src/services/api/schema.ts
@@ -4565,7 +4565,7 @@ export type components = {
};
/**
* Image to Latents - Anima
- * @description Generates latents from an image using the Anima VAE (supports Wan 2.1 and FLUX VAE).
+ * @description Generates latents from an image using the Anima VAE (the Wan 2.1 VAE, in either layout).
*/
AnimaImageToLatentsInvocation: {
/**
@@ -4732,10 +4732,7 @@ export type components = {
};
/**
* Latents to Image - Anima
- * @description Generates an image from latents using the Anima VAE.
- *
- * Supports the Wan 2.1 QwenImage VAE (AutoencoderKLWan) with explicit
- * latent denormalization, and FLUX VAE as fallback.
+ * @description Generates an image from latents using the Anima VAE (the Wan 2.1 VAE, in either layout).
*/
AnimaLatentsToImageInvocation: {
/**
@@ -5207,7 +5204,7 @@ export type components = {
* Scheduler Set
* @description Which scheduler family to offer; null means no choice.
*/
- scheduler_set?: ("standard" | "flow" | "anima") | null;
+ scheduler_set?: ("standard" | "flow" | "flow-no-lcm" | "anima") | null;
/**
* Scheduler Applies To Graph
* @default false
diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.json
index 0d2398c777..8f3e3f457c 100644
--- a/invokeai/frontend/webv2/public/locales/en.json
+++ b/invokeai/frontend/webv2/public/locales/en.json
@@ -3064,6 +3064,9 @@
"applyFilter": "Apply filter",
"beginStep": "Begin step",
"cancel": "Cancel",
+ "capabilitiesLoadFailed": "Model capabilities could not be loaded, so this layer cannot be checked yet.",
+ "capabilitiesLoading": "This layer is checked once model capabilities have loaded.",
+ "capabilitiesRetryHint": "Open the layer's settings to retry.",
"endStep": "End step",
"filter": "Filter",
"filterParams": {
@@ -3171,6 +3174,7 @@
"stepRange": "Step range",
"transparencyEffect": "Transparent preview",
"validation": {
+ "capabilities_unavailable": "waiting for model capabilities to load.",
"control_lora_limit": "Only one Control LoRA can be used at a time.",
"flux_fill_control_lora": "Control LoRA is not compatible with FLUX Fill.",
"incompatible_adapter": "The selected model does not match this adapter type.",
diff --git a/invokeai/frontend/webv2/src/features/generation/core/__fixtures__/architectureCapabilities.json b/invokeai/frontend/webv2/src/features/generation/core/__fixtures__/architectureCapabilities.json
index 0f85d1e155..a9be598108 100644
--- a/invokeai/frontend/webv2/src/features/generation/core/__fixtures__/architectureCapabilities.json
+++ b/invokeai/frontend/webv2/src/features/generation/core/__fixtures__/architectureCapabilities.json
@@ -1040,7 +1040,7 @@
"guidance_label": "CFG",
"guidance_min": 1.0,
"guidance_max": null,
- "scheduler_set": "flow",
+ "scheduler_set": "flow-no-lcm",
"scheduler_applies_to_graph": true,
"control_kinds": [
"z_image_control"
diff --git a/invokeai/frontend/webv2/src/features/generation/core/architectureCapabilities.ts b/invokeai/frontend/webv2/src/features/generation/core/architectureCapabilities.ts
index c746b6ca45..35ce9af5c7 100644
--- a/invokeai/frontend/webv2/src/features/generation/core/architectureCapabilities.ts
+++ b/invokeai/frontend/webv2/src/features/generation/core/architectureCapabilities.ts
@@ -32,7 +32,7 @@ export interface ArchitectureCapabilitiesRow {
guidance_min: number;
/** The ceiling the denoise node enforces, or `null` where it enforces none. */
guidance_max: number | null;
- /** No `flow-no-lcm` here: that set is reached by a frontend-only variant rule, see below. */
+ /** A variant row may carry its own. */
scheduler_set: SchedulerSetId | null;
scheduler_applies_to_graph: boolean;
control_kinds: string[];
diff --git a/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.ts b/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.ts
index d61f50a46d..444e8b1419 100644
--- a/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.ts
+++ b/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.ts
@@ -357,10 +357,6 @@ export const getSchedulerOptions = (
): readonly SchedulerOption[] => {
const config = getBaseGenerationConfig(model);
const options = (() => {
- if (model?.base === 'z-image' && model.variant === 'zbase') {
- return FLOW_SCHEDULER_OPTIONS_WITHOUT_LCM;
- }
-
switch (config.schedulerSet) {
case 'flow':
return FLOW_SCHEDULER_OPTIONS;
@@ -392,10 +388,6 @@ export const coerceSchedulerForGraph = (
return config.defaults.scheduler;
}
- if (model?.base === 'z-image' && model.variant === 'zbase') {
- return FLOW_SCHEDULERS_WITHOUT_LCM.has(scheduler) ? scheduler : 'euler';
- }
-
switch (config.schedulerSet) {
case 'flow':
return FLOW_SCHEDULERS.has(scheduler) ? scheduler : 'euler';
diff --git a/invokeai/frontend/webv2/src/features/generation/core/canvas/addControlLayers.ts b/invokeai/frontend/webv2/src/features/generation/core/canvas/addControlLayers.ts
index 63aacc4470..00491a6e75 100644
--- a/invokeai/frontend/webv2/src/features/generation/core/canvas/addControlLayers.ts
+++ b/invokeai/frontend/webv2/src/features/generation/core/canvas/addControlLayers.ts
@@ -236,6 +236,9 @@ export const getControlValidationReasonMessage = (reason: ControlValidationReaso
if (reason === 'missing_model') {
return `Control layer "${layerName}" has no control model selected.`;
}
+ if (reason === 'capabilities_unavailable') {
+ return `Control layer "${layerName}" cannot be checked until model capabilities have loaded.`;
+ }
if (reason === 'unsupported_adapter') {
return `Control layer "${layerName}" is not supported for the selected base model.`;
}
diff --git a/invokeai/frontend/webv2/src/features/generation/core/canvas/controlValidation.ts b/invokeai/frontend/webv2/src/features/generation/core/canvas/controlValidation.ts
index cdad06de76..a7988a0345 100644
--- a/invokeai/frontend/webv2/src/features/generation/core/canvas/controlValidation.ts
+++ b/invokeai/frontend/webv2/src/features/generation/core/canvas/controlValidation.ts
@@ -1,8 +1,12 @@
-import { getArchitectureFeatures } from '@features/generation/core/architectureCapabilities';
+import {
+ getArchitectureFeatures,
+ hasArchitectureCapabilities,
+} from '@features/generation/core/architectureCapabilities';
export type ControlAdapterKind = 'controlnet' | 't2i_adapter' | 'control_lora' | 'z_image_control';
export type ControlValidationReason =
+ | 'capabilities_unavailable'
| 'missing_model'
| 'unsupported_adapter'
| 'incompatible_base'
@@ -48,6 +52,11 @@ export const getControlValidationReason = (params: {
if (!adapterModel) {
return 'missing_model';
}
+ // Without the table every kind reads as unsupported. Report that the answer is not in yet rather
+ // than calling a valid adapter unsupported.
+ if (!hasArchitectureCapabilities()) {
+ return 'capabilities_unavailable';
+ }
if (!isControlKindSupportedForBase(mainBase, kind)) {
return 'unsupported_adapter';
}
diff --git a/invokeai/frontend/webv2/src/features/generation/ui/GenerateWidgetView.browser.test.tsx b/invokeai/frontend/webv2/src/features/generation/ui/GenerateWidgetView.browser.test.tsx
index 200b62582c..074b44da20 100644
--- a/invokeai/frontend/webv2/src/features/generation/ui/GenerateWidgetView.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/features/generation/ui/GenerateWidgetView.browser.test.tsx
@@ -35,7 +35,10 @@ vi.mock('./GenerateSettingsForm', () => ({
selectedModel?: { key: string };
settings: { positivePrompt: string };
}) => (
- <div data-testid="generate-form">{`model:${selectedModel?.key ?? 'none'} prompt:${settings.positivePrompt}`}</div>
+ // A button, so the form has something operable to receive focus, as the real one does.
+ <button data-testid="generate-form" type="button">
+ {`model:${selectedModel?.key ?? 'none'} prompt:${settings.positivePrompt}`}
+ </button>
),
}));
@@ -171,15 +174,51 @@ describe('GenerateWidgetView capability gate', () => {
const alert = document.querySelector('[role="alert"]');
+ // A localized headline, with what the request said as the detail beneath it.
+ expect(alert?.textContent).toContain('Could not load model capabilities from the backend.');
expect(alert?.textContent).toContain('Fixture capability outage.');
expect(formStub()).toBeNull();
getArchitectureCapabilities.mockResolvedValueOnce(architectureCapabilitiesFixture);
- await settle(() => retryButton().click());
+ await settle(() => {
+ retryButton().focus();
+ retryButton().click();
+ });
// The stored selection, not the catalog's first entry, and the project's own prompt.
expect(formStub()?.textContent).toBe('model:stored-sdxl prompt:a saved prompt');
+ // The button that held focus is gone; focus moved into the form it revealed, not to <body>.
+ expect(document.activeElement).toBe(formStub());
+ });
+
+ it('leaves focus where the user moved it while the retry was in flight', async () => {
+ getArchitectureCapabilities.mockRejectedValueOnce(new Error('Fixture capability outage.'));
+
+ await renderView();
+ await settle(ensureArchitectureCapabilitiesLoaded);
+
+ let finishLoad: (rows: ArchitectureCapabilitiesRow[]) => void = () => undefined;
+ getArchitectureCapabilities.mockReturnValueOnce(
+ new Promise((resolve) => {
+ finishLoad = resolve;
+ })
+ );
+
+ await settle(() => {
+ retryButton().focus();
+ retryButton().click();
+ });
+
+ const elsewhere = document.createElement('input');
+ document.body.append(elsewhere);
+ elsewhere.focus();
+
+ await settle(() => finishLoad(architectureCapabilitiesFixture));
+
+ expect(formStub()).not.toBeNull();
+ expect(document.activeElement).toBe(elsewhere);
+ elsewhere.remove();
});
it('keeps focus on the retry button while its own retry is in flight', async () => {
diff --git a/invokeai/frontend/webv2/src/features/generation/ui/GenerateWidgetView.tsx b/invokeai/frontend/webv2/src/features/generation/ui/GenerateWidgetView.tsx
index b3d64b0e2c..8a5667e064 100644
--- a/invokeai/frontend/webv2/src/features/generation/ui/GenerateWidgetView.tsx
+++ b/invokeai/frontend/webv2/src/features/generation/ui/GenerateWidgetView.tsx
@@ -1,16 +1,19 @@
import type { GenerationModelCatalogItem as ModelConfig } from '@features/generation/contracts';
import type { GenerateModelConfig, GenerateSettings, LoraModelConfig } from '@features/generation/core/types';
-import { HStack, Spinner, Stack, Text } from '@chakra-ui/react';
+import { Box, HStack, Spinner, Stack, Text } from '@chakra-ui/react';
import { getDefaultGenerateSettings, isSupportedGenerateModel } from '@features/generation/core/baseGenerationPolicies';
import { isLoraModelConfig, normalizeGenerateSettings } from '@features/generation/core/settings';
import {
ensureArchitectureCapabilitiesLoaded,
+ getArchitectureCapabilitiesSnapshot,
+ subscribeArchitectureCapabilities,
useArchitectureCapabilitiesSelector,
} from '@features/generation/data/architectureCapabilitiesStore';
import { resolveGenerateWidgetValues } from '@features/generation/settings';
+import { focusIfUnclaimed } from '@platform/react/focusIfUnclaimed';
import { Button } from '@platform/ui/Button';
-import { useCallback, useMemo, useState } from 'react';
+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { getGenerateFormCommitPatch } from './generateFormViewModel';
@@ -49,15 +52,44 @@ export const GenerateWidgetView = () => {
// the retry it started is what keeps the button -- and the user's focus -- in place.
const isRetrying = hasRequestedRetry && capabilitiesStatus === 'loading';
+ // Set by the click, consumed when the form the retry revealed mounts.
+ const focusHandoffPending = useRef(false);
+
const retryCapabilities = useCallback(() => {
if (isRetrying) {
return;
}
+ focusHandoffPending.current = true;
setHasRequestedRetry(true);
ensureArchitectureCapabilitiesLoaded();
}, [isRetrying]);
+ // The request belongs to one retry. Once that load settles, a later reload -- an account switch,
+ // a retry started from another panel -- is not this widget's retry: no failure surface while it
+ // loads, and no focus taken when it lands.
+ useEffect(() => {
+ if (!hasRequestedRetry) {
+ return undefined;
+ }
+
+ return subscribeArchitectureCapabilities(() => {
+ const next = getArchitectureCapabilitiesSnapshot().status;
+
+ if (next !== 'loading') {
+ focusHandoffPending.current = next === 'loaded';
+ setHasRequestedRetry(false);
+ }
+ });
+ }, [hasRequestedRetry]);
+
+ const handOverFocus = useCallback((element: HTMLDivElement | null) => {
+ if (element && focusHandoffPending.current) {
+ focusHandoffPending.current = false;
+ focusIfUnclaimed(element);
+ }
+ }, []);
+
const commitSettings = useCallback(
(nextSettings: GenerateSettings) => {
const model = supportedModels.find((candidate) => candidate.key === nextSettings.modelKey);
@@ -94,8 +126,13 @@ export const GenerateWidgetView = () => {
return (
<Stack aria-busy={isRetrying} aria-live="polite" gap="2" justify="center" minH="8rem" p="1" role="alert">
<Text color="fg.error" fontSize="2xs" textWrap="pretty">
- {capabilitiesError ?? t('widgets.generate.capabilitiesLoadFailed')}
+ {t('widgets.generate.capabilitiesLoadFailed')}
</Text>
+ {capabilitiesError ? (
+ <Text color="fg.muted" fontSize="2xs" textWrap="pretty">
+ {capabilitiesError}
+ </Text>
+ ) : null}
{/* `aria-disabled` rather than `disabled`: a disabled button drops the focus it holds. */}
<Button
alignSelf="flex-start"
@@ -132,17 +169,20 @@ export const GenerateWidgetView = () => {
}
return (
- <GenerateSettingsForm
- isLoadingModels={status === 'idle' || status === 'loading'}
- loadError={error}
- loraModels={loraModels}
- models={models}
- projectId={projectId}
- selectedModel={selectedModel}
- settings={settings}
- supportedModels={supportedModels}
- onCommitSettings={commitSettings}
- onPatchSettings={patchSettings}
- />
+ // A successful retry unmounts the button that held focus; hand it to the form the retry revealed.
+ <Box ref={handOverFocus}>
+ <GenerateSettingsForm
+ isLoadingModels={status === 'idle' || status === 'loading'}
+ loadError={error}
+ loraModels={loraModels}
+ models={models}
+ projectId={projectId}
+ selectedModel={selectedModel}
+ settings={settings}
+ supportedModels={supportedModels}
+ onCommitSettings={commitSettings}
+ onPatchSettings={patchSettings}
+ />
+ </Box>
);
};
diff --git a/invokeai/frontend/webv2/src/platform/react/focusIfUnclaimed.ts b/invokeai/frontend/webv2/src/platform/react/focusIfUnclaimed.ts
new file mode 100644
index 0000000000..878f0008fe
--- /dev/null
+++ b/invokeai/frontend/webv2/src/platform/react/focusIfUnclaimed.ts
@@ -0,0 +1,18 @@
+/** Operable elements, minus the ones kept out of the tab order -- a select's hidden native control, for one. */
+const FOCUSABLE = ['button', '[href]', 'input', 'select', 'textarea', '[tabindex]']
+ .map((selector) => `${selector}:not([disabled]):not([tabindex="-1"]):not([aria-hidden="true"])`)
+ .join(', ');
+
+/**
+ * For content revealed after the control that held focus unmounted -- a retry button replaced by the
+ * thing it loaded. Moves focus to the first operable element inside `element`, but only while nothing
+ * holds focus: it rescues a keyboard user whose focus fell to `<body>` without pulling focus from
+ * wherever someone has since moved it.
+ */
+export const focusIfUnclaimed = (element: HTMLElement | null): void => {
+ if (!element || (document.activeElement !== null && document.activeElement !== document.body)) {
+ return;
+ }
+
+ element.querySelector<HTMLElement>(FOCUSABLE)?.focus();
+};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/ControlLayerSettings.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/ControlLayerSettings.browser.test.tsx
index 80a5b792f9..264162b7c1 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/ControlLayerSettings.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/ControlLayerSettings.browser.test.tsx
@@ -1,11 +1,10 @@
+import type { ArchitectureCapabilitiesRow } from '@features/generation/core/architectureCapabilities';
import type { CanvasControlLayerContract } from '@workbench/canvas-engine/api';
import { ChakraProvider } from '@chakra-ui/react';
-import {
- resetArchitectureCapabilities,
- setArchitectureCapabilities,
-} from '@features/generation/core/architectureCapabilities';
import { architectureCapabilitiesFixture } from '@features/generation/core/architectureCapabilities.testing';
+import { ensureArchitectureCapabilitiesLoaded } from '@features/generation/data/architectureCapabilitiesStore';
+import { accountLifecycle } from '@platform/state/accountLifecycle';
import { applyThemeToRoot } from '@theme/applyTheme';
import { system } from '@theme/system';
import { createInstance } from 'i18next';
@@ -29,6 +28,11 @@ vi.mock('@features/models', async (importOriginal) => ({
}));
vi.mock('./useSelectedMainModel', () => ({ useSelectedMainModel: () => catalog.mainModel }));
+const getArchitectureCapabilities = vi.fn<() => Promise<ArchitectureCapabilitiesRow[]>>();
+vi.mock('@features/generation/data/architectureCapabilitiesApi', () => ({
+ getArchitectureCapabilities: () => getArchitectureCapabilities(),
+}));
+
const i18n = createInstance();
void i18n.use(initReactI18next).init({ fallbackLng: 'en', initAsync: false, lng: 'en', resources: {} });
@@ -57,45 +61,89 @@ const layer = {
const ignoreOperationStarted = (): void => undefined;
+const settle = async (run: () => void = () => undefined) => {
+ await act(async () => {
+ run();
+ await new Promise<void>((resolve) => {
+ globalThis.setTimeout(resolve, 0);
+ });
+ });
+};
+
const render = async () => {
applyThemeToRoot('classic');
host = document.createElement('div');
host.style.width = '260px';
document.body.append(host);
root = createRoot(host);
- await act(() => {
+ await settle(() =>
root?.render(
<I18nextProvider i18n={i18n}>
<ChakraProvider value={system}>
<ControlLayerSettings engine={null} layer={layer} onOperationStarted={ignoreOperationStarted} />
</ChakraProvider>
</I18nextProvider>
- );
- });
+ )
+ );
};
/** The kind Select renders a hidden native select, so its offered kinds are readable without opening it. */
const offersKind = (kind: string) => host!.querySelector(`option[value="${kind}"]`) !== null;
+const textOf = (role: 'alert' | 'status') =>
+ [...host!.querySelectorAll(`[role="${role}"]`)].map((element) => element.textContent).join(' ');
+const retryButton = () => [...host!.querySelectorAll('button')].find((button) => button.textContent === 'common.retry');
afterEach(async () => {
await act(() => root?.unmount());
host?.remove();
host = null;
root = null;
- resetArchitectureCapabilities();
+ getArchitectureCapabilities.mockReset();
+ // Returns the capability store and the core registry to their unloaded state between tests.
+ accountLifecycle.invalidate();
});
describe('ControlLayerSettings and the capability table', () => {
- it('offers the adapter kinds once a retried load succeeds, without remounting', async () => {
- // Without the table every kind reads as unsupported. The list used to be memoised on the base
- // alone, so it stayed empty after the table arrived until the model changed or the panel remounted.
+ it('says the adapter is waiting for model capabilities rather than that it is unsupported', async () => {
await render();
+
+ expect(textOf('status')).toContain('widgets.layers.control.capabilitiesLoading');
+ });
+
+ it('keeps the retry and its focus through a retry that fails again, then offers the adapter kinds', async () => {
+ // The kind list used to be memoised on the base alone, so it stayed empty after the table
+ // arrived until the model changed or the panel remounted.
+ getArchitectureCapabilities.mockRejectedValueOnce(new Error('Fixture capability outage.'));
+ await settle(ensureArchitectureCapabilitiesLoaded);
+ await render();
+
+ expect(textOf('alert')).toContain('widgets.layers.control.capabilitiesLoadFailed');
expect(offersKind('controlnet')).toBe(false);
- await act(() => {
- setArchitectureCapabilities(architectureCapabilitiesFixture);
+ // A retry that fails again: the button never unmounts, so a keyboard user's focus stays on it.
+ let failLoad: (error: Error) => void = () => undefined;
+ getArchitectureCapabilities.mockReturnValueOnce(
+ new Promise((_, reject) => {
+ failLoad = reject;
+ })
+ );
+ await settle(() => {
+ retryButton()?.focus();
+ retryButton()?.click();
});
+ expect(document.activeElement).toBe(retryButton());
+ expect(retryButton()?.getAttribute('aria-busy')).toBe('true');
+
+ await settle(() => failLoad(new Error('Still out.')));
+ expect(document.activeElement).toBe(retryButton());
+
+ getArchitectureCapabilities.mockResolvedValueOnce(architectureCapabilitiesFixture);
+ await settle(() => retryButton()?.click());
expect(offersKind('controlnet')).toBe(true);
+ expect(retryButton()).toBeUndefined();
+ // The button that held focus is gone; focus moved into the panel instead of falling to <body>.
+ expect(document.activeElement).not.toBe(document.body);
+ expect(host!.contains(document.activeElement)).toBe(true);
});
});
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/ControlLayerSettings.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/ControlLayerSettings.tsx
index 53ceb65c7d..d512570739 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/ControlLayerSettings.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/ControlLayerSettings.tsx
@@ -3,6 +3,7 @@ import type {
SelectValueChangeDetails,
SliderValueChangeDetails,
} from '@chakra-ui/react';
+import type { ArchitectureCapabilitiesSnapshot } from '@features/generation/runtime';
import type {
CanvasControlAdapterContract,
CanvasControlLayerContract,
@@ -18,14 +19,19 @@ import {
isControlKindSupportedForBase,
type ControlAdapterKind,
} from '@features/generation/graph';
-import { getArchitectureCapabilitiesSnapshot, subscribeArchitectureCapabilities } from '@features/generation/runtime';
+import {
+ ensureArchitectureCapabilitiesLoaded,
+ getArchitectureCapabilitiesSnapshot,
+ subscribeArchitectureCapabilities,
+} from '@features/generation/runtime';
import { useModelsSelector } from '@features/models';
+import { focusIfUnclaimed } from '@platform/react/focusIfUnclaimed';
import { useExternalStoreSelector } from '@platform/state/selectors';
-import { Field, Select, Slider } from '@platform/ui';
+import { Button, Field, Select, Slider } from '@platform/ui';
import { lookupDocumentLeaf } from '@workbench/canvas-engine/api';
import { getCanvasOperations, resolveDefaultFilterForModel } from '@workbench/canvas-operations/api';
import { usePreparedCommit } from '@workbench/widgets/canvas/useStructuralCommit';
-import { useCallback, useMemo, useRef } from 'react';
+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { getCompatibleControlModels } from './controlModelOptions';
@@ -36,6 +42,8 @@ import { useSelectedMainModel } from './useSelectedMainModel';
const SELECT_POSITIONING = { placement: 'bottom-end', sameWidth: true } as const;
+const selectCapabilitiesStatus = (snapshot: ArchitectureCapabilitiesSnapshot) => snapshot.status;
+
const CONTROL_ADAPTER_KINDS: readonly ControlAdapterKind[] = [
'controlnet',
't2i_adapter',
@@ -109,6 +117,36 @@ export const ControlLayerSettings = ({ engine, layer, onOperationStarted }: Cont
[commitPrepared, layer.id]
);
+ const capabilitiesStatus = useExternalStoreSelector(
+ subscribeArchitectureCapabilities,
+ getArchitectureCapabilitiesSnapshot,
+ selectCapabilitiesStatus
+ );
+ const [hasRequestedCapabilitiesRetry, setHasRequestedCapabilitiesRetry] = useState(false);
+ const rootRef = useRef<HTMLDivElement | null>(null);
+ // Set by the click, consumed once the retry has filled the panel in.
+ const focusHandoffPending = useRef(false);
+ const retryCapabilities = useCallback(() => {
+ if (hasRequestedCapabilitiesRetry && capabilitiesStatus === 'loading') {
+ return;
+ }
+ focusHandoffPending.current = true;
+ setHasRequestedCapabilitiesRetry(true);
+ ensureArchitectureCapabilitiesLoaded();
+ }, [capabilitiesStatus, hasRequestedCapabilitiesRetry]);
+ // The request belongs to one retry; a later reload started elsewhere is not this panel's retry.
+ useEffect(() => {
+ if (!hasRequestedCapabilitiesRetry) {
+ return undefined;
+ }
+ return subscribeArchitectureCapabilities(() => {
+ const next = getArchitectureCapabilitiesSnapshot().status;
+ if (next !== 'loading') {
+ focusHandoffPending.current = next === 'loaded';
+ setHasRequestedCapabilitiesRetry(false);
+ }
+ });
+ }, [hasRequestedCapabilitiesRetry]);
// Adapter kinds supported by the selected base. Z-Image Control is only shown
// when a compatible Z-Image main model is selected. Read inside the store's
// selector: the answer comes from the capability table, and a call memoised on
@@ -352,11 +390,28 @@ export const ControlLayerSettings = ({ engine, layer, onOperationStarted }: Cont
)
);
// Content-dependent problems only matter once the layer has pixels, but a
- // missing model deserves the warning even on a fresh empty layer.
+ // missing model deserves the warning even on a fresh empty layer. A missing
+ // capability table is not a problem with this layer and is shown on its own.
+ const capabilitiesUnavailable = validationReason === 'capabilities_unavailable';
+ // The click flips the status to `loading` synchronously; keeping the failure surface mounted for the
+ // retry it started keeps the button, and the user's focus, in place.
+ const isRetryingCapabilities = hasRequestedCapabilitiesRetry && capabilitiesStatus === 'loading';
+ const showCapabilitiesFailure = capabilitiesUnavailable && (capabilitiesStatus === 'error' || isRetryingCapabilities);
const visibleValidationReason =
- validationReason && (hasContent || validationReason === 'missing_model') ? validationReason : null;
+ validationReason && !capabilitiesUnavailable && (hasContent || validationReason === 'missing_model')
+ ? validationReason
+ : null;
+
+ // A successful retry unmounts the button that held focus; hand it to the panel the retry filled in.
+ useEffect(() => {
+ if (!capabilitiesUnavailable && focusHandoffPending.current) {
+ focusHandoffPending.current = false;
+ focusIfUnclaimed(rootRef.current);
+ }
+ }, [capabilitiesUnavailable]);
+
return (
- <Stack gap="2">
+ <Stack ref={rootRef} gap="2">
<HStack gap="2">
<Field flex="1" label={t('widgets.layers.control.kind')} minW="0">
<Select
@@ -463,6 +518,28 @@ export const ControlLayerSettings = ({ engine, layer, onOperationStarted }: Cont
{t(`widgets.layers.control.validation.${visibleValidationReason}`)}
</Text>
) : null}
+ {showCapabilitiesFailure ? (
+ <HStack aria-busy={isRetryingCapabilities} gap="2" role="alert">
+ <Text color="fg.warning" flex="1" fontSize="2xs">
+ {t('widgets.layers.control.capabilitiesLoadFailed')}
+ </Text>
+ {/* `aria-disabled` rather than `disabled`: a disabled button drops the focus it holds. */}
+ <Button
+ aria-busy={isRetryingCapabilities}
+ aria-disabled={isRetryingCapabilities}
+ size="xs"
+ variant="outline"
+ onClick={retryCapabilities}
+ >
+ {t('common.retry')}
+ </Button>
+ </HStack>
+ ) : null}
+ {capabilitiesUnavailable && !showCapabilitiesFailure ? (
+ <Text color="fg.muted" fontSize="2xs" role="status">
+ {t('widgets.layers.control.capabilitiesLoading')}
+ </Text>
+ ) : null}
</Stack>
);
};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/ControlLayerWarningIcon.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/ControlLayerWarningIcon.browser.test.tsx
index 8291888e2f..05fbf8fce2 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/ControlLayerWarningIcon.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/ControlLayerWarningIcon.browser.test.tsx
@@ -1,11 +1,10 @@
+import type { ArchitectureCapabilitiesRow } from '@features/generation/core/architectureCapabilities';
import type { CanvasLayerContract } from '@workbench/canvas-engine/api';
import { ChakraProvider } from '@chakra-ui/react';
-import {
- resetArchitectureCapabilities,
- setArchitectureCapabilities,
-} from '@features/generation/core/architectureCapabilities';
import { architectureCapabilitiesFixture } from '@features/generation/core/architectureCapabilities.testing';
+import { ensureArchitectureCapabilitiesLoaded } from '@features/generation/data/architectureCapabilitiesStore';
+import { accountLifecycle } from '@platform/state/accountLifecycle';
import { applyThemeToRoot } from '@theme/applyTheme';
import { system } from '@theme/system';
import { createInstance } from 'i18next';
@@ -30,6 +29,11 @@ vi.mock('@features/models', async (importOriginal) => ({
}));
vi.mock('./useSelectedMainModel', () => ({ useSelectedMainModel: () => catalog.mainModel }));
+const getArchitectureCapabilities = vi.fn<() => Promise<ArchitectureCapabilitiesRow[]>>();
+vi.mock('@features/generation/data/architectureCapabilitiesApi', () => ({
+ getArchitectureCapabilities: () => getArchitectureCapabilities(),
+}));
+
const i18n = createInstance();
void i18n.use(initReactI18next).init({ fallbackLng: 'en', initAsync: false, lng: 'en', resources: {} });
@@ -54,42 +58,63 @@ const layer = {
type: 'control',
} as unknown as CanvasLayerContract;
+const settle = async (run: () => void = () => undefined) => {
+ await act(async () => {
+ run();
+ await new Promise<void>((resolve) => {
+ globalThis.setTimeout(resolve, 0);
+ });
+ });
+};
+
const render = async () => {
applyThemeToRoot('classic');
host = document.createElement('div');
document.body.append(host);
root = createRoot(host);
- await act(() => {
+ await settle(() =>
root?.render(
<I18nextProvider i18n={i18n}>
<ChakraProvider value={system}>
<ControlLayerWarningIcon layer={layer} />
</ChakraProvider>
</I18nextProvider>
- );
- });
+ )
+ );
};
-const warning = () => host!.querySelector('[aria-label="widgets.layers.control.needsAttention"]');
+const warning = () => host!.querySelector('[aria-label^="widgets.layers.control.needsAttention"]');
afterEach(async () => {
await act(() => root?.unmount());
host?.remove();
host = null;
root = null;
- resetArchitectureCapabilities();
+ getArchitectureCapabilities.mockReset();
+ // Returns the capability store and the core registry to their unloaded state between tests.
+ accountLifecycle.invalidate();
});
describe('ControlLayerWarningIcon and the capability table', () => {
- it('drops the "unsupported adapter" warning once a retried load succeeds, without remounting', async () => {
- // Without the table every adapter kind reads as unsupported. The row used to keep that answer
- // until the layer or model changed, so a healthy SD-1 ControlNet layer stayed flagged.
+ it('flags nothing about a valid adapter while the table is still loading', async () => {
+ // Without the table every adapter kind reads as unsupported, which used to be shown as exactly
+ // that -- a warning on a healthy SD-1 ControlNet layer.
await render();
- expect(warning()).not.toBeNull();
- await act(() => {
- setArchitectureCapabilities(architectureCapabilitiesFixture);
- });
+ expect(warning()).toBeNull();
+ });
+
+ it('points at the failed capability load, and clears once a retry succeeds, without remounting', async () => {
+ getArchitectureCapabilities.mockRejectedValueOnce(new Error('Fixture capability outage.'));
+ await settle(ensureArchitectureCapabilitiesLoaded);
+ await render();
+
+ const label = warning()?.getAttribute('aria-label') ?? '';
+ expect(label).toContain('widgets.layers.control.capabilitiesLoadFailed');
+ expect(label).not.toContain('unsupported_adapter');
+
+ getArchitectureCapabilities.mockResolvedValueOnce(architectureCapabilitiesFixture);
+ await settle(ensureArchitectureCapabilitiesLoaded);
expect(warning()).toBeNull();
});
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/ControlLayerWarningIcon.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/ControlLayerWarningIcon.tsx
index 3fbd3e0c68..d0ba5d5695 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/ControlLayerWarningIcon.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/ControlLayerWarningIcon.tsx
@@ -1,3 +1,4 @@
+import type { ArchitectureCapabilitiesSnapshot } from '@features/generation/runtime';
import type { CanvasLayerContract } from '@workbench/canvas-engine/api';
import { Icon } from '@chakra-ui/react';
@@ -12,6 +13,8 @@ import { useTranslation } from 'react-i18next';
import { useSelectedMainModel } from './useSelectedMainModel';
+const selectCapabilitiesStatus = (snapshot: ArchitectureCapabilitiesSnapshot) => snapshot.status;
+
/**
* Quiet per-row indicator for a control layer that would be rejected at
* generation time (no model, incompatible adapter, …). Renders nothing for
@@ -28,9 +31,13 @@ export const ControlLayerWarningIcon = ({
const { t } = useTranslation();
const models = useModelsSelector((snapshot) => snapshot.models);
const mainModel = useSelectedMainModel();
+ const capabilitiesStatus = useExternalStoreSelector(
+ subscribeArchitectureCapabilities,
+ getArchitectureCapabilitiesSnapshot,
+ selectCapabilitiesStatus
+ );
// Read inside the store's selector: whether the adapter kind is supported comes from the capability
- // table, and a call memoised on the layer and model would keep flagging "unsupported adapter" after a
- // retried load succeeded, until something unrelated re-rendered the row.
+ // table, and a call memoised on the layer and model would keep its first answer after the table loads.
const reason = useExternalStoreSelector(
subscribeArchitectureCapabilities,
getArchitectureCapabilitiesSnapshot,
@@ -43,14 +50,21 @@ export const ControlLayerWarningIcon = ({
)
);
- if (!reason) {
+ // Without the table nothing can be said about the adapter. While it loads there is nothing to flag;
+ // once the load has failed, say that and where to retry, instead of calling a valid adapter unsupported.
+ if (!reason || (reason === 'capabilities_unavailable' && capabilitiesStatus !== 'error')) {
return null;
}
+ const message =
+ reason === 'capabilities_unavailable'
+ ? `${t('widgets.layers.control.capabilitiesLoadFailed')} ${t('widgets.layers.control.capabilitiesRetryHint')}`
+ : t(`widgets.layers.control.validation.${reason}`);
+
return (
- <Tooltip content={t(`widgets.layers.control.validation.${reason}`)}>
+ <Tooltip content={message}>
<Icon
- aria-label={t('widgets.layers.control.needsAttention')}
+ aria-label={`${t('widgets.layers.control.needsAttention')}: ${message}`}
as={TriangleAlertIcon}
boxSize="3"
color="fg.warning"
diff --git a/tests/app/invocations/test_anima_vae.py b/tests/app/invocations/test_anima_vae.py
index 59234e57d1..855f0638ba 100644
--- a/tests/app/invocations/test_anima_vae.py
+++ b/tests/app/invocations/test_anima_vae.py
@@ -1,12 +1,14 @@
-"""Tests for the Anima VAE invocations: working-memory estimation, the tiled-decode
-decision, and the tiled retry on out-of-memory."""
+"""Tests for the Anima VAE invocations: which VAEs they accept, working-memory estimation, the
+tiled-decode decision, and the tiled retry on out-of-memory."""
import math
from unittest.mock import MagicMock, patch
+import accelerate
import pytest
import torch
from diffusers.models.autoencoders import AutoencoderKLWan
+from diffusers.models.autoencoders.autoencoder_kl_qwenimage import AutoencoderKLQwenImage
from invokeai.app.invocations.constants import LATENT_SCALE_FACTOR
from invokeai.app.invocations.vae.anima_image_to_latents import AnimaImageToLatentsInvocation
@@ -15,31 +17,56 @@ from invokeai.app.invocations.vae.anima_latents_to_image import (
ANIMA_VAE_TILE_STRIDE,
AnimaLatentsToImageInvocation,
)
+from invokeai.backend.model_manager.load.model_loaders.vae import _WAN_TI2V_5B_VAE_CONFIG
from invokeai.backend.util.devices import TorchDevice
from invokeai.backend.util.vae_working_memory import estimate_vae_working_memory_anima
+# The two classes the Wan 2.1 VAE loads as: the original-layout file as AutoencoderKLWan, the
+# diffusers-layout Qwen-Image export as AutoencoderKLQwenImage.
+WAN21_VAE_LAYOUTS = [AutoencoderKLWan, AutoencoderKLQwenImage]
-def _mock_wan_vae(dtype: torch.dtype = torch.float16) -> MagicMock:
- vae = MagicMock(spec=AutoencoderKLWan)
+
+def _mock_vae(vae_class: type = AutoencoderKLWan, dtype: torch.dtype = torch.float16) -> MagicMock:
+ vae = MagicMock(spec=vae_class)
param = torch.zeros(1, dtype=dtype)
# Return a fresh iterator on every call so the estimator can be called repeatedly.
vae.parameters.side_effect = lambda: iter([param])
- # `patch_qwen_image_vae_tiling` records and restores these; they are set in
- # `AutoencoderKLWan.__init__` rather than on the class, so a spec'd mock does not have them.
- # The stock values keep any assertion against them reading as real numbers.
+ # `patch_qwen_image_vae_tiling` records and restores these; they are set in `__init__` rather
+ # than on the class, so a spec'd mock does not have them. The stock values keep any assertion
+ # against them reading as real numbers.
vae.use_tiling = False
vae.tile_sample_min_height = 256
vae.tile_sample_min_width = 256
vae.tile_sample_stride_height = 192
vae.tile_sample_stride_width = 192
+ # The Wan 2.1 geometry, which the nodes check before using a Wan VAE.
+ vae.config.z_dim = 16
+ vae.config.patch_size = None
+ vae.config.scale_factor_spatial = 8
+ vae.config.latents_mean = [0.0] * 16
+ vae.config.latents_std = [1.0] * 16
return vae
+def _mock_vae_info(vae) -> MagicMock:
+ vae_info = MagicMock()
+ vae_info.model = vae
+ # The invocation places latents on the VAE's intended compute device (see #9373), so this
+ # must be a real torch.device rather than a MagicMock for `latents.to(device=...)` to work.
+ vae_info.compute_device = torch.device("cpu")
+ cm = MagicMock()
+ cm.__enter__ = MagicMock(return_value=(None, vae))
+ cm.__exit__ = MagicMock(return_value=None)
+ vae_info.model_on_device.return_value = cm
+ return vae_info
+
+
class TestEstimateVaeWorkingMemoryAnima:
- def test_untiled_decode_uses_decode_constant_and_scales_latent_dims(self):
+ @pytest.mark.parametrize("vae_class", WAN21_VAE_LAYOUTS)
+ def test_untiled_decode_uses_decode_constant_and_scales_latent_dims(self, vae_class):
latents = torch.zeros(1, 16, 1, 128, 128)
result = estimate_vae_working_memory_anima(
- operation="decode", image_tensor=latents, vae=_mock_wan_vae(torch.float16), tile_size=None
+ operation="decode", image_tensor=latents, vae=_mock_vae(vae_class, torch.float16), tile_size=None
)
out_h = out_w = 128 * LATENT_SCALE_FACTOR
assert result == int(out_h * out_w * 2 * 2900)
@@ -47,7 +74,7 @@ class TestEstimateVaeWorkingMemoryAnima:
def test_untiled_encode_uses_encode_constant_and_pixel_dims(self):
image = torch.zeros(1, 3, 1, 1024, 1024)
result = estimate_vae_working_memory_anima(
- operation="encode", image_tensor=image, vae=_mock_wan_vae(torch.float16), tile_size=None
+ operation="encode", image_tensor=image, vae=_mock_vae(dtype=torch.float16), tile_size=None
)
assert result == int(1024 * 1024 * 2 * 1450)
@@ -55,17 +82,17 @@ class TestEstimateVaeWorkingMemoryAnima:
def test_tiled_decode_estimate_is_independent_of_image_size(self, latent_hw):
latents = torch.zeros(1, 16, 1, *latent_hw)
result = estimate_vae_working_memory_anima(
- operation="decode", image_tensor=latents, vae=_mock_wan_vae(torch.float16), tile_size=512
+ operation="decode", image_tensor=latents, vae=_mock_vae(dtype=torch.float16), tile_size=512
)
assert result == int(512 * 512 * 2 * 2900 * 1.25)
def test_estimate_scales_with_element_size(self):
latents = torch.zeros(1, 16, 1, 128, 128)
fp16 = estimate_vae_working_memory_anima(
- operation="decode", image_tensor=latents, vae=_mock_wan_vae(torch.float16), tile_size=None
+ operation="decode", image_tensor=latents, vae=_mock_vae(dtype=torch.float16), tile_size=None
)
fp32 = estimate_vae_working_memory_anima(
- operation="decode", image_tensor=latents, vae=_mock_wan_vae(torch.float32), tile_size=None
+ operation="decode", image_tensor=latents, vae=_mock_vae(dtype=torch.float32), tile_size=None
)
assert fp32 == 2 * fp16
@@ -85,23 +112,12 @@ class TestUseTiledDecode:
mock_props.assert_called_with(device)
-def _build_decode_mocks(latents: torch.Tensor, decoded: torch.Tensor):
- """Mock the Wan VAE decode path: a spec'd AutoencoderKLWan, its LoadedModel wrapper, and the
- invocation context, wired so `AnimaLatentsToImageInvocation.invoke` runs end-to-end on CPU."""
- vae = _mock_wan_vae(torch.float32)
- vae.config.latents_mean = [0.0] * 16
- vae.config.latents_std = [1.0] * 16
+def _build_decode_mocks(latents: torch.Tensor, decoded: torch.Tensor, vae_class: type = AutoencoderKLWan):
+ """Mock the Anima VAE decode path: a spec'd VAE, its LoadedModel wrapper, and the invocation
+ context, wired so `AnimaLatentsToImageInvocation.invoke` runs end-to-end on CPU."""
+ vae = _mock_vae(vae_class, torch.float32)
vae.decode.return_value = (decoded,)
-
- vae_info = MagicMock()
- vae_info.model = vae
- # The invocation places latents on the VAE's intended compute device (see #9373), so this
- # must be a real torch.device rather than a MagicMock for `latents.to(device=...)` to work.
- vae_info.compute_device = torch.device("cpu")
- cm = MagicMock()
- cm.__enter__ = MagicMock(return_value=(None, vae))
- cm.__exit__ = MagicMock(return_value=None)
- vae_info.model_on_device.return_value = cm
+ vae_info = _mock_vae_info(vae)
context = MagicMock()
context.models.load.return_value = vae_info
@@ -122,6 +138,66 @@ def _build_l2i_invocation() -> AnimaLatentsToImageInvocation:
)
+class TestAnimaAcceptsBothWan21VaeLayouts:
+ """The picker offers a `qwen-image` VAE for Anima. Its diffusers-layout file loads as
+ AutoencoderKLQwenImage, which the nodes used to refuse with a TypeError; it is the same network
+ on the same weights with the same latent statistics, so it must encode and decode like the
+ original-layout AutoencoderKLWan."""
+
+ @pytest.mark.parametrize("vae_class", WAN21_VAE_LAYOUTS)
+ def test_decode_denormalises_with_the_vae_statistics(self, vae_class):
+ decoded = torch.zeros(1, 3, 1, 32, 32)
+ vae, _, context = _build_decode_mocks(
+ latents=torch.full((1, 16, 4, 4), 0.5), decoded=decoded, vae_class=vae_class
+ )
+ vae.config.latents_mean = [1.0] * 16
+ vae.config.latents_std = [2.0] * 16
+
+ with patch.object(TorchDevice, "choose_torch_device", return_value=torch.device("cpu")):
+ result = _build_l2i_invocation().invoke(context)
+
+ vae.decode.assert_called_once()
+ vae_input = vae.decode.call_args.args[0]
+ assert vae_input.shape == (1, 16, 1, 4, 4)
+ # latents * std + mean = 0.5 * 2 + 1
+ assert torch.all(vae_input == 2.0)
+ assert result.width == 32
+
+ @pytest.mark.parametrize("vae_class", WAN21_VAE_LAYOUTS)
+ def test_encode_normalises_with_the_vae_statistics(self, vae_class):
+ vae = _mock_vae(vae_class, torch.float32)
+ vae.config.latents_mean = [1.0] * 16
+ vae.config.latents_std = [2.0] * 16
+ posterior = MagicMock()
+ posterior.sample.return_value = torch.full((1, 16, 1, 4, 4), 3.0)
+ vae.encode.return_value = (posterior,)
+
+ with patch.object(TorchDevice, "choose_torch_device", return_value=torch.device("cpu")):
+ latents = AnimaImageToLatentsInvocation.vae_encode(
+ vae_info=_mock_vae_info(vae), image_tensor=torch.zeros(1, 3, 32, 32)
+ )
+
+ assert vae.encode.call_args.args[0].shape == (1, 3, 1, 32, 32)
+ # (latents - mean) / std = (3 - 1) / 2
+ assert latents.shape == (1, 16, 4, 4)
+ assert torch.all(latents == 1.0)
+
+
+def _flux_vae_info() -> MagicMock:
+ from invokeai.backend.flux.modules.autoencoder import AutoEncoder as FluxAutoEncoder
+
+ vae_info = MagicMock()
+ vae_info.model = MagicMock(spec=FluxAutoEncoder)
+ return vae_info
+
+
+def _flux_decode_context(vae_info: MagicMock) -> MagicMock:
+ context = MagicMock()
+ context.models.load.return_value = vae_info
+ context.tensors.load.return_value = torch.zeros(1, 16, 64, 64)
+ return context
+
+
class TestAnimaRefusesAForeignDecoder:
"""A FLUX VAE has Anima's channel count and compression but a different basis.
@@ -132,36 +208,62 @@ class TestAnimaRefusesAForeignDecoder:
refuses instead of guessing."""
def test_a_flux_vae_is_refused_before_any_decode(self):
- from invokeai.backend.flux.modules.autoencoder import AutoEncoder as FluxAutoEncoder
-
- vae_info = MagicMock()
- vae_info.model = MagicMock(spec=FluxAutoEncoder)
- context = MagicMock()
- context.models.load.return_value = vae_info
- context.tensors.load.return_value = torch.zeros(1, 16, 64, 64)
+ vae_info = _flux_vae_info()
with pytest.raises(TypeError, match="16-channel Wan 2.1 latent space"):
- _build_l2i_invocation().invoke(context)
+ _build_l2i_invocation().invoke(_flux_decode_context(vae_info))
# Refused before the model is placed on a device: a wrong decode costs VRAM and time
# before it produces the wrong image.
vae_info.model_on_device.assert_not_called()
def test_the_message_names_what_to_choose_instead(self):
- from invokeai.backend.flux.modules.autoencoder import AutoEncoder as FluxAutoEncoder
+ with pytest.raises(TypeError) as excinfo:
+ _build_l2i_invocation().invoke(_flux_decode_context(_flux_vae_info()))
- vae_info = MagicMock()
- vae_info.model = MagicMock(spec=FluxAutoEncoder)
- context = MagicMock()
- context.models.load.return_value = vae_info
- context.tensors.load.return_value = torch.zeros(1, 16, 64, 64)
+ message = str(excinfo.value)
+ for base in ("'anima'", "'qwen-image'", "'wan'"):
+ assert base in message, message
- with pytest.raises(TypeError) as excinfo:
- _build_l2i_invocation().invoke(context)
+ def test_a_flux_vae_is_refused_before_any_encode_with_the_same_advice(self):
+ vae_info = _flux_vae_info()
+
+ with pytest.raises(TypeError, match="16-channel Wan 2.1 latent space") as excinfo:
+ AnimaImageToLatentsInvocation.vae_encode(vae_info=vae_info, image_tensor=torch.zeros(1, 3, 32, 32))
message = str(excinfo.value)
for base in ("'anima'", "'qwen-image'", "'wan'"):
assert base in message, message
+ vae_info.model_on_device.assert_not_called()
+
+
+class TestAnimaRefusesTheWan22Vae:
+ """Wan 2.2's TI2V VAE is also an AutoencoderKLWan, but a 48-channel, patchified latent space.
+ The class check alone let it through to a device, where the 16-entry normalisation broke on it."""
+
+ @pytest.fixture
+ def wan22_vae_info(self) -> MagicMock:
+ with accelerate.init_empty_weights():
+ vae = AutoencoderKLWan(**_WAN_TI2V_5B_VAE_CONFIG)
+ vae_info = MagicMock()
+ vae_info.model = vae
+ return vae_info
+
+ def test_decode_refuses_it_before_any_decode(self, wan22_vae_info):
+ context = MagicMock()
+ context.models.load.return_value = wan22_vae_info
+ context.tensors.load.return_value = torch.zeros(1, 48, 16, 16)
+
+ with pytest.raises(ValueError, match="z_dim=48"):
+ _build_l2i_invocation().invoke(context)
+
+ wan22_vae_info.model_on_device.assert_not_called()
+
+ def test_encode_refuses_it_before_any_encode(self, wan22_vae_info):
+ with pytest.raises(ValueError, match="z_dim=48"):
+ AnimaImageToLatentsInvocation.vae_encode(vae_info=wan22_vae_info, image_tensor=torch.zeros(1, 3, 32, 32))
+
+ wan22_vae_info.model_on_device.assert_not_called()
class TestAnimaLatentsToImageOomFallback:
@@ -242,19 +344,11 @@ class TestAnimaLatentsToImageOomFallback:
class TestAnimaImageToLatentsEncode:
def test_encode_disables_tiling_and_requests_working_memory(self):
- vae = _mock_wan_vae(torch.float32)
- vae.config.latents_mean = [0.0] * 16
- vae.config.latents_std = [1.0] * 16
+ vae = _mock_vae(dtype=torch.float32)
mock_dist = MagicMock()
mock_dist.sample.return_value = torch.zeros(1, 16, 1, 4, 4)
vae.encode.return_value = (mock_dist,)
-
- 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
+ vae_info = _mock_vae_info(vae)
estimation_path = "invokeai.app.invocations.vae.anima_image_to_latents.estimate_vae_working_memory_anima"
expected_memory = 1024 * 1024 * 250
diff --git a/tests/app/invocations/test_ideogram4_frontend_bounds.py b/tests/app/invocations/test_ideogram4_frontend_bounds.py
new file mode 100644
index 0000000000..efbee480b3
--- /dev/null
+++ b/tests/app/invocations/test_ideogram4_frontend_bounds.py
@@ -0,0 +1,41 @@
+"""webv2's Ideogram 4 controls are bounded by the same numbers the denoise node validates.
+
+These three bounds are not served: they belong to controls only Ideogram 4 has, and the shared
+guidance slider never reaches the field (see `NO_GUIDANCE_SLIDER` in
+`tests/backend/architectures/test_guidance_range.py`). So the frontend keeps them as constants, and
+this reads both sides -- the constants from `settings.ts`, the bounds from the node's own schema --
+so a change to either fails here instead of at enqueue. All three were wrong once: `mu` offered 0..10
+against a node that accepts -4..4.
+"""
+
+import re
+from pathlib import Path
+
+import pytest
+
+from invokeai.app.invocations.ideogram4.ideogram4_denoise import Ideogram4DenoiseInvocation
+
+REPO_ROOT = Path(__file__).resolve().parents[3]
+SETTINGS_TS = REPO_ROOT / "invokeai/frontend/webv2/src/features/generation/core/settings.ts"
+
+
+def _frontend_constant(name: str) -> float:
+ match = re.search(rf"export const {name} = (-?\d+(?:\.\d+)?);", SETTINGS_TS.read_text(encoding="utf-8"))
+ assert match is not None, f"{name} is not a numeric constant in {SETTINGS_TS.name}"
+ return float(match.group(1))
+
+
+def _node_bounds(field: str) -> tuple[float, float]:
+ """`ge`/`le` of an optional numeric field, which sit on the numeric branch of its `anyOf`."""
+ schema = Ideogram4DenoiseInvocation.model_json_schema()["properties"][field]
+ branches = schema.get("anyOf", [schema])
+ numeric = next(branch for branch in branches if "minimum" in branch or "maximum" in branch)
+ return float(numeric["minimum"]), float(numeric["maximum"])
+
+
+ ("field", "prefix"),
+ [("steps", "IDEOGRAM4_STEPS"), ("guidance_scale", "IDEOGRAM4_GUIDANCE"), ("mu", "IDEOGRAM4_MU")],
+)
+def test_the_control_bounds_match_the_node(field: str, prefix: str) -> None:
+ assert (_frontend_constant(f"{prefix}_MIN"), _frontend_constant(f"{prefix}_MAX")) == _node_bounds(field)
diff --git a/tests/app/invocations/test_wan_model_loader.py b/tests/app/invocations/test_wan_model_loader.py
index e908e58eef..01d28b8bed 100644
--- a/tests/app/invocations/test_wan_model_loader.py
+++ b/tests/app/invocations/test_wan_model_loader.py
@@ -390,6 +390,16 @@ def test_loader_rejects_forged_non_wan_vae_identifier() -> None:
)
[email protected]("vae_base", [BaseModelType.Flux, BaseModelType.StableDiffusion3])
+def test_loader_rejects_a_standalone_vae_of_another_family(vae_base: BaseModelType) -> None:
+ """A 16-channel VAE record that is not Wan's must not pass on its channel count alone."""
+ with pytest.raises(ValueError, match="16-channel Wan 2.1 VAE"):
+ _invoke(
+ _config("main", WanVariantType.T2V_A14B, "high"),
+ vae_config=SimpleNamespace(name="other", latent_channels=16, base=vae_base, type=ModelType.VAE),
+ )
+
+
def test_loader_rejects_forged_non_wan_component_source_identifier() -> None:
with pytest.raises(ValueError, match="Wan.*Component Source|Component Source.*Wan"):
_invoke(
diff --git a/tests/backend/architectures/test_scheduler_set.py b/tests/backend/architectures/test_scheduler_set.py
new file mode 100644
index 0000000000..0002fd7e10
--- /dev/null
+++ b/tests/backend/architectures/test_scheduler_set.py
@@ -0,0 +1,31 @@
+"""The scheduler family a variant is offered, where it differs from its architecture's.
+
+webv2 used to special-case Z-Image Base in two places to drop LCM, against a `flow-no-lcm` set id the
+backend never served. The rule is the node's -- `z_image_denoise` documents LCM as Turbo-only -- so
+it is declared here, served on the variant row, and the frontend has no case of its own.
+"""
+
+from invokeai.app.invocations.z_image.z_image_denoise import ZImageDenoiseInvocation
+from invokeai.backend.architectures import architecture_capabilities
+from invokeai.backend.architectures.facets.features import FeaturesFacet
+from invokeai.backend.architectures.registry import require
+from invokeai.backend.model_manager.taxonomy import BaseModelType, ZImageVariantType
+
+
+def test_z_image_base_is_offered_the_flow_set_without_lcm() -> None:
+ # Read from the node rather than restated: if the node ever supports LCM on Base, this fails
+ # and the declaration should go.
+ description = ZImageDenoiseInvocation.model_fields["scheduler"].description or ""
+ assert "LCM works with Turbo only (not Base)" in description
+
+ facet = require(BaseModelType.ZImage, FeaturesFacet)
+ assert facet.resolve_scheduler_set(ZImageVariantType.ZBase) == "flow-no-lcm"
+ assert facet.resolve_scheduler_set(ZImageVariantType.Turbo) == "flow"
+ assert facet.resolve_scheduler_set() == "flow"
+
+
+def test_the_variant_set_is_what_the_table_serves() -> None:
+ rows = {(row.base, row.variant): row for row in architecture_capabilities()}
+
+ assert rows[(BaseModelType.ZImage, "zbase")].features.scheduler_set == "flow-no-lcm"
+ assert rows[(BaseModelType.ZImage, None)].features.scheduler_set == "flow"
diff --git a/tests/backend/architectures/test_vae.py b/tests/backend/architectures/test_vae.py
index ebfaa37e97..24775dbc29 100644
--- a/tests/backend/architectures/test_vae.py
+++ b/tests/backend/architectures/test_vae.py
@@ -1,9 +1,10 @@
-"""Which VAEs each architecture accepts, and that the loaders agree.
+"""Which VAEs each architecture accepts.
The facts here were duplicated three times before -- once per loader as `ui_model_base`, once in
webv2's VAE picker, once more in its related-models linker -- and all three disagreed. Anima's
loader declared nothing at all while its description named three families; FLUX.2 Klein's offered
-FLUX VAEs that crash in `decode()`.
+FLUX VAEs that crash in `decode()`. The loaders now derive `ui_model_base` from the facet through
+`accepted_vae_bases`.
"""
import pytest
@@ -12,58 +13,10 @@ from invokeai.app.invocations.baseinvocation import InvocationRegistry
from invokeai.app.services.shared.graph import Graph # noqa: F401 -- imports every invocation
from invokeai.backend.architectures import architecture_capabilities, generative_bases, get
from invokeai.backend.architectures.facets.latent_space import LatentSpace, LatentSpaceFacet
-from invokeai.backend.architectures.facets.vae import VaeCompatibility, VaeFacet, accepts_vae
+from invokeai.backend.architectures.facets.vae import VaeCompatibility, VaeFacet, accepted_vae_bases, accepts_vae
from invokeai.backend.architectures.registry import require
from invokeai.backend.model_manager.taxonomy import BaseModelType, WanVariantType
-# The loader that owns each architecture's VAE input. Architectures absent from this map take no
-# standalone VAE: the SD family overrides it through model settings instead.
-VAE_LOADER = {
- BaseModelType.Anima: "anima_model_loader",
- BaseModelType.Flux: "flux_model_loader",
- BaseModelType.Flux2: "flux2_klein_model_loader",
- BaseModelType.Krea2: "krea2_model_loader",
- BaseModelType.QwenImage: "qwen_image_model_loader",
- BaseModelType.StableDiffusion3: "sd3_model_loader",
- BaseModelType.Wan: "wan_model_loader",
- BaseModelType.ZImage: "z_image_model_loader",
-}
-
-
-def _ui_model_bases() -> dict[str, list[str] | None]:
- out: dict[str, list[str] | None] = {}
- for cls in InvocationRegistry.get_invocation_classes():
- vae = cls.model_json_schema().get("properties", {}).get("vae_model")
- if vae is not None:
- out[cls.get_type()] = vae.get("ui_model_base")
- return out
-
-
-def test_the_declaration_and_the_loader_agree() -> None:
- """`ui_model_base` is what the UI filters on today; the facet is what it will filter on.
-
- While both exist they must say the same thing, or a model the graph accepts is hidden -- or
- worse, one it rejects is offered. `ui_model_base` cannot express a channel constraint, so the
- comparison is over bases; the channel rules are checked separately below.
- """
- ui_bases = _ui_model_bases()
-
- disagreements = []
- for base, node_type in sorted(VAE_LOADER.items(), key=lambda item: item[0].value):
- declared = ui_bases.get(node_type)
- if declared is None:
- continue # covered by test_every_loader_with_a_vae_input_declares_its_bases
-
- facet = get(base, VaeFacet)
- accepted = facet.accepted_bases if facet else frozenset({base})
- if {b.value for b in accepted} != set(declared):
- disagreements.append(
- f"{base.value}: facet accepts {sorted(b.value for b in accepted)}, "
- f"{node_type} offers {sorted(declared)}"
- )
-
- assert disagreements == []
-
def test_flux2_no_longer_offers_a_vae_that_crashes() -> None:
"""Klein advertised FLUX VAEs. Decoding a FLUX.2 latent with one raises
@@ -86,18 +39,11 @@ def test_anima_accepts_the_wan_family_under_each_base_it_registers_as() -> None:
def test_anima_no_longer_offers_a_flux_vae_that_decodes_to_noise() -> None:
"""Anima denoises in WAN21_16; a FLUX VAE reads the same 16 channels in a different basis.
- `anima_l2i` takes the `FluxAutoEncoder` branch without raising and without the Wan per-channel
- denormalisation the `AutoencoderKLWan` branch applies, so nothing fails and nothing is logged.
- Measured on real weights (`qwenImage_qwenImageVAE.safetensors` vs FLUX `ae.safetensors`,
- 512x512, float32) by encoding an image with the Anima VAE and decoding that one latent down
- both production branches:
-
- Anima VAE vs original 46.18 dB PSNR, 0.0041 MAE, 0.327 max abs
- FLUX VAE vs original 6.10 dB PSNR, 0.9325 MAE, 2.000 max abs
-
- Per-channel means move from R +0.858 / G +0.804 / B +0.666 to R +0.156 / G -0.212 / B +0.111 --
- a magenta, moire-patterned image in which the subject is barely discernible. It is not a
- fallback, so it is not offered.
+ `anima_l2i` used to take a `FluxAutoEncoder` without raising and without the Wan per-channel
+ denormalisation, so nothing failed and nothing was logged. Measured on real weights: one Anima
+ denoise decoded by both VAEs in the same graph, 8.67 dB PSNR between the two images -- a magenta,
+ moire-patterned image in which the subject is barely discernible. It is not a fallback, so it is
+ not offered; `tests/app/invocations/test_anima_vae.py` pins the node's refusal.
"""
assert accepts_vae(BaseModelType.Anima, BaseModelType.Flux) is False
@@ -107,12 +53,25 @@ def test_an_architecture_without_the_facet_accepts_only_its_own_base() -> None:
assert accepts_vae(BaseModelType.StableDiffusionXL, BaseModelType.Flux) is False
[email protected]("base", sorted(VAE_LOADER, key=lambda b: b.value))
-def test_every_loader_with_a_vae_input_declares_its_bases(base: BaseModelType) -> None:
- """Anima's did not, so nothing constrained its picker and the two frontend copies drifted."""
- assert _ui_model_bases().get(VAE_LOADER[base]) is not None, (
- f"{VAE_LOADER[base]} takes a VAE but declares no `ui_model_base`, so the UI offers every "
- f"VAE ever installed. Declare it, and keep it in step with {base.value}'s VaeFacet."
+# The generic loader serves the families that declare no facet at all; it names them itself.
+GENERIC_VAE_NODES = {"vae_loader"}
+
+
+def test_every_node_with_a_vae_input_takes_its_bases_from_a_facet() -> None:
+ """Anima's loader declared no bases, so its picker offered every VAE installed; a loader with its
+ own literal list drifts from what the graph accepts. Each list must be one the facet answers."""
+ facet_lists = {tuple(b.value for b in accepted_vae_bases(base)) for base in generative_bases()}
+ mismatched = sorted(
+ f"{cls.get_type()}: {vae.get('ui_model_base')}"
+ for cls in InvocationRegistry.get_invocation_classes()
+ if cls.get_type() not in GENERIC_VAE_NODES
+ and (vae := cls.model_json_schema().get("properties", {}).get("vae_model")) is not None
+ and tuple(vae.get("ui_model_base") or ()) not in facet_lists
+ )
+
+ assert mismatched == [], (
+ "These nodes take a VAE but their `ui_model_base` is not a facet's list. "
+ "Use `ui_model_base=accepted_vae_bases(<base>)`."
)
@@ -134,8 +93,8 @@ def test_every_accepted_vae_shares_the_architectures_latent_space() -> None:
Eight architectures denoise in 16 channels at 8x and their VAEs are still not interchangeable:
WAN21_16 and FLUX_16 have different `rgb_factors` and only WAN21_16 carries an `rgb_bias`.
- Anima declared `VaeCompatibility(Flux)` and `anima_l2i` decoded it without raising -- 6.10 dB
- PSNR against the correct decode, measured on real weights; see
+ Anima declared `VaeCompatibility(Flux)` and `anima_l2i` decoded it without raising -- 8.67 dB
+ PSNR against the correct decode of the same latent, measured on real weights; see
`test_anima_no_longer_offers_a_flux_vae_that_decodes_to_noise`.
There is no exception list. A new entry that fails this is a silently wrong decode, so the fix
diff --git a/tests/backend/model_manager/load/test_wan_vae_loader.py b/tests/backend/model_manager/load/test_wan_vae_loader.py
index c06022ead1..762e28e810 100644
--- a/tests/backend/model_manager/load/test_wan_vae_loader.py
+++ b/tests/backend/model_manager/load/test_wan_vae_loader.py
@@ -62,9 +62,9 @@ def test_a14b_kwargs_instantiate_with_expected_shapes() -> None:
def test_wan_vae_checkpoint_loads_bfloat16_even_when_loader_dtype_is_fp16() -> None:
- """fp16 is unstable on the Wan VAE (NaN/garbled frames), so the checkpoint path must
- force bfloat16 like ``_load_wan_vae_diffusers`` and ``WanDiffusersModel`` do — even
- though ``precision: auto`` resolves the loader's default dtype to float16 on CUDA."""
+ """fp16 is unstable on the Wan VAE (NaN/garbled frames), so the checkpoint path raises a
+ float16 request to bfloat16 like ``_load_wan_vae_diffusers`` does — ``precision: auto``
+ resolves the loader's default dtype to float16 on CUDA."""
loader = VAELoader.__new__(VAELoader)
loader._ram_cache = MagicMock()
loader._torch_dtype = torch.float16 # what `precision: auto` yields on CUDA
@@ -74,6 +74,8 @@ def test_wan_vae_checkpoint_loads_bfloat16_even_when_loader_dtype_is_fp16() -> N
"step_counter": torch.zeros(1, dtype=torch.int64),
}
config = MagicMock()
+ # The loader picks its reader from the suffix, so the (mocked) safetensors reader is the one used.
+ config.path = "wan-vae.safetensors"
config.latent_channels = 16
fake_model = MagicMock()