Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
feat(architectures): declare latent spaces, and resolve previews through them
Alexander Eichhorn74207b855793
diff --git a/invokeai/app/invocations/ideogram4/ideogram4_denoise.py b/invokeai/app/invocations/ideogram4/ideogram4_denoise.pyindex f9bc9ea855..c501b41a9f 100644--- a/invokeai/app/invocations/ideogram4/ideogram4_denoise.py+++ b/invokeai/app/invocations/ideogram4/ideogram4_denoise.py@@ -12,16 +12,13 @@ from invokeai.app.invocations.fields import (from invokeai.app.invocations.model import TransformerFieldfrom invokeai.app.invocations.primitives import LatentsOutputfrom invokeai.app.services.shared.invocation_context import InvocationContext-from invokeai.app.util.step_callback import (- FLUX2_LATENT_RGB_BIAS,- FLUX2_LATENT_RGB_FACTORS,- sample_to_lowres_estimated_image,-)+from invokeai.backend.architectures import resolve_latent_spacefrom invokeai.backend.ideogram4 import run_ideogram4_denoisefrom invokeai.backend.ideogram4.latent_norm import get_latent_normfrom invokeai.backend.ideogram4.sampler_configs import PRESETSfrom invokeai.backend.ideogram4.sampling_utils import unpatchify_and_denormalizefrom invokeai.backend.ideogram4.transformer_pair import Ideogram4TransformerPair+from invokeai.backend.model_manager.taxonomy import BaseModelTypefrom invokeai.backend.stable_diffusion.diffusion.conditioning_data import Ideogram4ConditioningInfofrom invokeai.backend.util.devices import TorchDevice@@ -122,15 +119,16 @@ class Ideogram4DenoiseInvocation(BaseInvocation):assert isinstance(info, Ideogram4ConditioningInfo)llm_features = info.prompt_embeds.to(device=device, dtype=torch.float32)- # Progress-preview setup: Ideogram uses a FLUX.2-style 32-channel VAE, so the FLUX.2- # latent->RGB factors give a usable (approximate) low-res preview of the forming image at each- # step, without a full VAE decode. Denormalization params come from get_latent_norm (no VAE).+ # Denormalization params come from get_latent_norm (no VAE).latent_shift, latent_scale = get_latent_norm()- rgb_factors = torch.tensor(FLUX2_LATENT_RGB_FACTORS, dtype=torch.float32)- rgb_bias = torch.tensor(FLUX2_LATENT_RGB_BIAS, dtype=torch.float32)def step_callback(step: int, total: int, packed_latents: torch.Tensor) -> None:+ # The projection and the downscale come from what this architecture declares, which is+ # the same source the shared denoise callback reads. This was a second copy of the+ # FLUX.2 constants with the 8x downscale hardcoded — and Ideogram 4 was missing from+ # that shared dispatch entirely, so reading either one could not have revealed the other.preview = None+ preview_size = Nonetry:# packed_latents: (1, LATENT_DIM, grid_h, grid_w) -> VAE latent (1, 32, H/8, W/8).vae_latent = unpatchify_and_denormalize(@@ -138,10 +136,11 @@ class Ideogram4DenoiseInvocation(BaseInvocation):latent_shift.to(packed_latents.device),latent_scale.to(packed_latents.device),)- preview = sample_to_lowres_estimated_image(- samples=vae_latent,- latent_rgb_factors=rgb_factors.to(vae_latent.device),- latent_rgb_bias=rgb_bias.to(vae_latent.device),+ latent_space = resolve_latent_space(BaseModelType.Ideogram4, vae_latent)+ preview = latent_space.preview(vae_latent)+ preview_size = (+ preview.width * latent_space.spatial_compression,+ preview.height * latent_space.spatial_compression,)except Exception:# A preview must never break generation — fall back to a plain progress signal.@@ -151,7 +150,7 @@ class Ideogram4DenoiseInvocation(BaseInvocation):"Running Ideogram 4 denoising",step / total,preview,- (preview.width * 8, preview.height * 8),+ preview_size,)else:context.util.signal_progress("Running Ideogram 4 denoising", step / total)diff --git a/invokeai/app/util/step_callback.py b/invokeai/app/util/step_callback.pyindex f70dfda9cb..4f6b7d22c4 100644--- a/invokeai/app/util/step_callback.py+++ b/invokeai/app/util/step_callback.py@@ -1,321 +1,13 @@from math import floor-from typing import Callable, Optional, TypeAlias+from typing import Callable, TypeAlias-import torchfrom PIL import Imagefrom invokeai.app.services.session_processor.session_processor_common import CanceledException+from invokeai.backend.architectures import resolve_latent_spacefrom invokeai.backend.model_manager.taxonomy import BaseModelTypefrom invokeai.backend.stable_diffusion.diffusers_pipeline import PipelineIntermediateState-# See scripts/generate_vae_linear_approximation.py for generating these factors.--# fast latents preview matrix for sdxl-# generated by @StAlKeR7779-SDXL_LATENT_RGB_FACTORS = [- # R G B- [0.3816, 0.4930, 0.5320],- [-0.3753, 0.1631, 0.1739],- [0.1770, 0.3588, -0.2048],- [-0.4350, -0.2644, -0.4289],-]-SDXL_SMOOTH_MATRIX = [- [0.0358, 0.0964, 0.0358],- [0.0964, 0.4711, 0.0964],- [0.0358, 0.0964, 0.0358],-]--# origingally adapted from code by @erucipe and @keturn here:-# https://discuss.huggingface.co/t/decoding-latents-to-rgb-without-upscaling/23204/7-# these updated numbers for v1.5 are from @torridgristle-SD1_5_LATENT_RGB_FACTORS = [- # R G B- [0.3444, 0.1385, 0.0670], # L1- [0.1247, 0.4027, 0.1494], # L2- [-0.3192, 0.2513, 0.2103], # L3- [-0.1307, -0.1874, -0.7445], # L4-]--SD3_5_LATENT_RGB_FACTORS = [- [-0.05240681, 0.03251581, 0.0749016],- [-0.0580572, 0.00759826, 0.05729818],- [0.16144888, 0.01270368, -0.03768577],- [0.14418615, 0.08460266, 0.15941818],- [0.04894035, 0.0056485, -0.06686988],- [0.05187166, 0.19222395, 0.06261094],- [0.1539433, 0.04818359, 0.07103094],- [-0.08601796, 0.09013458, 0.10893912],- [-0.12398469, -0.06766567, 0.0033688],- [-0.0439737, 0.07825329, 0.02258823],- [0.03101129, 0.06382551, 0.07753657],- [-0.01315361, 0.08554491, -0.08772475],- [0.06464487, 0.05914605, 0.13262741],- [-0.07863674, -0.02261737, -0.12761454],- [-0.09923835, -0.08010759, -0.06264447],- [-0.03392309, -0.0804029, -0.06078822],-]--FLUX_LATENT_RGB_FACTORS = [- [-0.0412, 0.0149, 0.0521],- [0.0056, 0.0291, 0.0768],- [0.0342, -0.0681, -0.0427],- [-0.0258, 0.0092, 0.0463],- [0.0863, 0.0784, 0.0547],- [-0.0017, 0.0402, 0.0158],- [0.0501, 0.1058, 0.1152],- [-0.0209, -0.0218, -0.0329],- [-0.0314, 0.0083, 0.0896],- [0.0851, 0.0665, -0.0472],- [-0.0534, 0.0238, -0.0024],- [0.0452, -0.0026, 0.0048],- [0.0892, 0.0831, 0.0881],- [-0.1117, -0.0304, -0.0789],- [0.0027, -0.0479, -0.0043],- [-0.1146, -0.0827, -0.0598],-]--COGVIEW4_LATENT_RGB_FACTORS = [- [0.00408832, -0.00082485, -0.00214816],- [0.00084172, 0.00132241, 0.00842067],- [-0.00466737, -0.00983181, -0.00699561],- [0.03698397, -0.04797235, 0.03585809],- [0.00234701, -0.00124326, 0.00080869],- [-0.00723903, -0.00388422, -0.00656606],- [-0.00970917, -0.00467356, -0.00971113],- [0.17292486, -0.03452463, -0.1457515],- [0.02330308, 0.02942557, 0.02704329],- [-0.00903131, -0.01499841, -0.01432564],- [0.01250298, 0.0019407, -0.02168986],- [0.01371188, 0.00498283, -0.01302135],- [0.42396525, 0.4280575, 0.42148206],- [0.00983825, 0.00613302, 0.00610316],- [0.00473307, -0.00889551, -0.00915924],- [-0.00955853, -0.00980067, -0.00977842],-]--# Qwen Image uses the same VAE as Wan 2.1 (16-channel).-# Factors from ComfyUI: https://github.com/comfyanonymous/ComfyUI/blob/master/comfy/latent_formats.py-QWEN_IMAGE_LATENT_RGB_FACTORS = [- [-0.1299, -0.1692, 0.2932],- [0.0671, 0.0406, 0.0442],- [0.3568, 0.2548, 0.1747],- [0.0372, 0.2344, 0.1420],- [0.0313, 0.0189, -0.0328],- [0.0296, -0.0956, -0.0665],- [-0.3477, -0.4059, -0.2925],- [0.0166, 0.1902, 0.1975],- [-0.0412, 0.0267, -0.1364],- [-0.1293, 0.0740, 0.1636],- [0.0680, 0.3019, 0.1128],- [0.0032, 0.0581, 0.0639],- [-0.1251, 0.0927, 0.1699],- [0.0060, -0.0633, 0.0005],- [0.3477, 0.2275, 0.2950],- [0.1984, 0.0913, 0.1861],-]--QWEN_IMAGE_LATENT_RGB_BIAS = [-0.1835, -0.0868, -0.3360]--# FLUX.2 uses 32 latent channels.-# Factors from ComfyUI: https://github.com/Comfy-Org/ComfyUI/blob/main/comfy/latent_formats.py-FLUX2_LATENT_RGB_FACTORS = [- # R G B- [0.0058, 0.0113, 0.0073],- [0.0495, 0.0443, 0.0836],- [-0.0099, 0.0096, 0.0644],- [0.2144, 0.3009, 0.3652],- [0.0166, -0.0039, -0.0054],- [0.0157, 0.0103, -0.0160],- [-0.0398, 0.0902, -0.0235],- [-0.0052, 0.0095, 0.0109],- [-0.3527, -0.2712, -0.1666],- [-0.0301, -0.0356, -0.0180],- [-0.0107, 0.0078, 0.0013],- [0.0746, 0.0090, -0.0941],- [0.0156, 0.0169, 0.0070],- [-0.0034, -0.0040, -0.0114],- [0.0032, 0.0181, 0.0080],- [-0.0939, -0.0008, 0.0186],- [0.0018, 0.0043, 0.0104],- [0.0284, 0.0056, -0.0127],- [-0.0024, -0.0022, -0.0030],- [0.1207, -0.0026, 0.0065],- [0.0128, 0.0101, 0.0142],- [0.0137, -0.0072, -0.0007],- [0.0095, 0.0092, -0.0059],- [0.0000, -0.0077, -0.0049],- [-0.0465, -0.0204, -0.0312],- [0.0095, 0.0012, -0.0066],- [0.0290, -0.0034, 0.0025],- [0.0220, 0.0169, -0.0048],- [-0.0332, -0.0457, -0.0468],- [-0.0085, 0.0389, 0.0609],- [-0.0076, 0.0003, -0.0043],- [-0.0111, -0.0460, -0.0614],-]--FLUX2_LATENT_RGB_BIAS = [-0.0329, -0.0718, -0.0851]--# Anima uses Wan 2.1 VAE with 16 latent channels.-# Factors from ComfyUI: https://github.com/Comfy-Org/ComfyUI/blob/main/comfy/latent_formats.py-ANIMA_LATENT_RGB_FACTORS = [- [-0.1299, -0.1692, 0.2932],- [0.0671, 0.0406, 0.0442],- [0.3568, 0.2548, 0.1747],- [0.0372, 0.2344, 0.1420],- [0.0313, 0.0189, -0.0328],- [0.0296, -0.0956, -0.0665],- [-0.3477, -0.4059, -0.2925],- [0.0166, 0.1902, 0.1975],- [-0.0412, 0.0267, -0.1364],- [-0.1293, 0.0740, 0.1636],- [0.0680, 0.3019, 0.1128],- [0.0032, 0.0581, 0.0639],- [-0.1251, 0.0927, 0.1699],- [0.0060, -0.0633, 0.0005],- [0.3477, 0.2275, 0.2950],- [0.1984, 0.0913, 0.1861],-]--ANIMA_LATENT_RGB_BIAS = [-0.1835, -0.0868, -0.3360]--# Wan 2.2 A14B uses the standard 16-channel Wan VAE.-# Factors come from ComfyUI's Wan21 latent_format (same VAE as A14B).-WAN_LATENT_RGB_FACTORS = [- [-0.1299, -0.1692, 0.2932],- [0.0671, 0.0406, 0.0442],- [0.3568, 0.2548, 0.1747],- [0.0372, 0.2344, 0.1420],- [0.0313, 0.0189, -0.0328],- [0.0296, -0.0956, -0.0665],- [-0.3477, -0.4059, -0.2925],- [0.0166, 0.1902, 0.1975],- [-0.0412, 0.0267, -0.1364],- [-0.1293, 0.0740, 0.1636],- [0.0680, 0.3019, 0.1128],- [0.0032, 0.0581, 0.0639],- [-0.1251, 0.0927, 0.1699],- [0.0060, -0.0633, 0.0005],- [0.3477, 0.2275, 0.2950],- [0.1984, 0.0913, 0.1861],-]--WAN_LATENT_RGB_BIAS = [-0.1835, -0.0868, -0.3360]--# Wan 2.2 TI2V-5B uses Wan2.2-VAE with 48 latent channels and 16x spatial downscale.-# Factors come from ComfyUI's Wan22 latent_format.-WAN22_LATENT_RGB_FACTORS = [- [0.0119, 0.0103, 0.0046],- [-0.1062, -0.0504, 0.0165],- [0.0140, 0.0409, 0.0491],- [-0.0813, -0.0677, 0.0607],- [0.0656, 0.0851, 0.0808],- [0.0264, 0.0463, 0.0912],- [0.0295, 0.0326, 0.0590],- [-0.0244, -0.0270, 0.0025],- [0.0443, -0.0102, 0.0288],- [-0.0465, -0.0090, -0.0205],- [0.0359, 0.0236, 0.0082],- [-0.0776, 0.0854, 0.1048],- [0.0564, 0.0264, 0.0561],- [0.0006, 0.0594, 0.0418],- [-0.0319, -0.0542, -0.0637],- [-0.0268, 0.0024, 0.0260],- [0.0539, 0.0265, 0.0358],- [-0.0359, -0.0312, -0.0287],- [-0.0285, -0.1032, -0.1237],- [0.1041, 0.0537, 0.0622],- [-0.0086, -0.0374, -0.0051],- [0.0390, 0.0670, 0.2863],- [0.0069, 0.0144, 0.0082],- [0.0006, -0.0167, 0.0079],- [0.0313, -0.0574, -0.0232],- [-0.1454, -0.0902, -0.0481],- [0.0714, 0.0827, 0.0447],- [-0.0304, -0.0574, -0.0196],- [0.0401, 0.0384, 0.0204],- [-0.0758, -0.0297, -0.0014],- [0.0568, 0.1307, 0.1372],- [-0.0055, -0.0310, -0.0380],- [0.0239, -0.0305, 0.0325],- [-0.0663, -0.0673, -0.0140],- [-0.0416, -0.0047, -0.0023],- [0.0166, 0.0112, -0.0093],- [-0.0211, 0.0011, 0.0331],- [0.1833, 0.1466, 0.2250],- [-0.0368, 0.0370, 0.0295],- [-0.3441, -0.3543, -0.2008],- [-0.0479, -0.0489, -0.0420],- [-0.0660, -0.0153, 0.0800],- [-0.0101, 0.0068, 0.0156],- [-0.0690, -0.0452, -0.0927],- [-0.0145, 0.0041, 0.0015],- [0.0421, 0.0451, 0.0373],- [0.0504, -0.0483, -0.0356],- [-0.0837, 0.0168, 0.0055],-]--WAN22_LATENT_RGB_BIAS = [0.0317, -0.0878, -0.1388]--# MiniMax H3's video VAE: 24 latent channels, 16x spatial downscale. Least-squares fit of-# NORMALIZED posterior-mean latents against 16x-downscaled RGB in [-1, 1], over real photos-# plus synthetic gradients/patches, using the released H3 video VAE encoder (fit rms ~0.09).-# This is the fallback path only — when the taeh3 preview decoder is available, the denoise-# node decodes previews with it instead.-MINIMAX_H3_LATENT_RGB_FACTORS = [- [-0.0127, -0.0944, -0.1146],- [-0.0083, 0.0638, -0.0942],- [0.3635, 0.4082, 0.1479],- [0.2079, 0.1357, -0.5101],- [0.0178, 0.3250, -0.3183],- [0.0567, 0.2060, -0.2453],- [0.0343, -0.0136, -0.0482],- [0.0079, 0.0299, -0.0814],- [0.0220, 0.0043, 0.0158],- [0.2984, 0.0988, 0.1576],- [-0.0066, 0.0184, 0.1134],- [-0.0794, -0.0416, 0.0628],- [0.0419, -0.0184, 0.0618],- [-0.0274, 0.0420, -0.0235],- [-0.0231, -0.0312, 0.0310],- [0.0089, 0.0368, -0.0387],- [0.0126, 0.0085, -0.0299],- [-0.0187, 0.0028, 0.0194],- [0.0264, -0.0304, 0.0089],- [0.0512, 0.0168, 0.0110],- [0.0168, -0.0357, -0.0001],- [0.0063, -0.0116, -0.0509],- [-0.0237, -0.0347, 0.0324],- [-0.0099, 0.0042, -0.0358],-]--MINIMAX_H3_LATENT_RGB_BIAS = [0.1189, 0.1415, -0.0034]---def sample_to_lowres_estimated_image(- samples: torch.Tensor,- latent_rgb_factors: torch.Tensor,- smooth_matrix: Optional[torch.Tensor] = None,- latent_rgb_bias: Optional[torch.Tensor] = None,-):- if samples.dim() == 4:- samples = samples[0]- latent_image = samples.permute(1, 2, 0) @ latent_rgb_factors-- if latent_rgb_bias is not None:- latent_image = latent_image + latent_rgb_bias-- if smooth_matrix is not None:- latent_image = latent_image.unsqueeze(0).permute(3, 0, 1, 2)- latent_image = torch.nn.functional.conv2d(latent_image, smooth_matrix.reshape((1, 1, 3, 3)), padding=1)- latent_image = latent_image.permute(1, 2, 3, 0).squeeze(0)-- latents_ubyte = (- ((latent_image + 1) / 2).clamp(0, 1).mul(0xFF).byte() # change scale from -1..1 to 0..1 # to 0..255- ).cpu()-- return Image.fromarray(latents_ubyte.numpy())-def calc_percentage(intermediate_state: PipelineIntermediateState) -> float:"""Calculate the percentage of completion of denoising."""@@ -356,80 +48,17 @@ def diffusion_step_callback(else:sample = intermediate_state.latents- smooth_matrix: list[list[float]] | None = None- latent_rgb_bias: list[float] | None = None- if base_model in [BaseModelType.StableDiffusion1, BaseModelType.StableDiffusion2]:- latent_rgb_factors = SD1_5_LATENT_RGB_FACTORS- elif base_model in [BaseModelType.StableDiffusionXL, BaseModelType.StableDiffusionXLRefiner]:- latent_rgb_factors = SDXL_LATENT_RGB_FACTORS- smooth_matrix = SDXL_SMOOTH_MATRIX- elif base_model == BaseModelType.StableDiffusion3:- latent_rgb_factors = SD3_5_LATENT_RGB_FACTORS- elif base_model == BaseModelType.CogView4:- latent_rgb_factors = COGVIEW4_LATENT_RGB_FACTORS- elif base_model in [BaseModelType.QwenImage, BaseModelType.Krea2]:- # Krea-2 decodes with the Qwen-Image VAE (16 latent channels), so it shares the preview factors.- latent_rgb_factors = QWEN_IMAGE_LATENT_RGB_FACTORS- latent_rgb_bias = QWEN_IMAGE_LATENT_RGB_BIAS- elif base_model == BaseModelType.Flux:- latent_rgb_factors = FLUX_LATENT_RGB_FACTORS- elif base_model == BaseModelType.Flux2:- latent_rgb_factors = FLUX2_LATENT_RGB_FACTORS- latent_rgb_bias = FLUX2_LATENT_RGB_BIAS- elif base_model == BaseModelType.ZImage:- # Z-Image uses FLUX-compatible VAE with 16 latent channels- latent_rgb_factors = FLUX_LATENT_RGB_FACTORS- elif base_model == BaseModelType.Anima:- # Anima uses Wan 2.1 VAE with 16 latent channels- latent_rgb_factors = ANIMA_LATENT_RGB_FACTORS- latent_rgb_bias = ANIMA_LATENT_RGB_BIAS- elif base_model == BaseModelType.ErnieImage:- # ERNIE-Image uses AutoencoderKLFlux2 (same as FLUX.2) with 32 latent channels, and the- # denoise loop unpatches before previewing, so the shapes line up. The values do not:- # ERNIE denoises in BN-normalized latent space (denormalized only at VAE decode) and the- # BN stats live on the VAE, which isn't loaded here. Previews are therefore approximate- # in color/contrast.- latent_rgb_factors = FLUX2_LATENT_RGB_FACTORS- latent_rgb_bias = FLUX2_LATENT_RGB_BIAS- elif base_model == BaseModelType.Wan:- # A14B (16-ch standard Wan VAE, 8x spatial) vs TI2V-5B (48-ch Wan2.2-VAE,- # 16x spatial). The latent channel count uniquely identifies the variant.- if sample.shape[-3] == 48:- latent_rgb_factors = WAN22_LATENT_RGB_FACTORS- latent_rgb_bias = WAN22_LATENT_RGB_BIAS- else:- latent_rgb_factors = WAN_LATENT_RGB_FACTORS- latent_rgb_bias = WAN_LATENT_RGB_BIAS- elif base_model == BaseModelType.MiniMaxH3:- # 24-ch H3 video VAE; factors fitted against the released encoder (see constants above).- latent_rgb_factors = MINIMAX_H3_LATENT_RGB_FACTORS- latent_rgb_bias = MINIMAX_H3_LATENT_RGB_BIAS- else:- raise ValueError(f"Unsupported base model: {base_model}")-- latent_rgb_factors_torch = torch.tensor(latent_rgb_factors, dtype=sample.dtype, device=sample.device)- smooth_matrix_torch = (- torch.tensor(smooth_matrix, dtype=sample.dtype, device=sample.device) if smooth_matrix else None- )- latent_rgb_bias_torch = (- torch.tensor(latent_rgb_bias, dtype=sample.dtype, device=sample.device) if latent_rgb_bias else None+ # Which projection, which bias, whether to smooth, and how much the VAE downscales are all facts+ # about the architecture, and they live in invokeai/backend/architectures/defs/. This used to be+ # a fifteen-branch if/elif ending in `raise ValueError(f"Unsupported base model: {base_model}")`,+ # which fired on the first preview step — after the model had loaded and generation had started.+ # An architecture that declares no latent space now fails at boot instead.+ latent_space = resolve_latent_space(base_model, sample)+ image = latent_space.preview(sample)++ signal_progress(+ "Denoising",+ calc_percentage(intermediate_state),+ image,+ (image.width * latent_space.spatial_compression, image.height * latent_space.spatial_compression),)- image = sample_to_lowres_estimated_image(- samples=sample,- latent_rgb_factors=latent_rgb_factors_torch,- smooth_matrix=smooth_matrix_torch,- latent_rgb_bias=latent_rgb_bias_torch,- )-- # Spatial downscale ratio: 8x is the SD/SDXL/FLUX/Wan-A14B default;- # Wan TI2V-5B's Wan2.2-VAE uses 16x.- spatial_scale = 8- if base_model == BaseModelType.Wan and sample.shape[-3] == 48:- spatial_scale = 16- elif base_model == BaseModelType.MiniMaxH3:- spatial_scale = 16- width = image.width * spatial_scale- height = image.height * spatial_scale- percentage = calc_percentage(intermediate_state)-- signal_progress("Denoising", percentage, image, (width, height))diff --git a/invokeai/backend/architectures/__init__.py b/invokeai/backend/architectures/__init__.pyindex 173996707d..11548d5147 100644--- a/invokeai/backend/architectures/__init__.py+++ b/invokeai/backend/architectures/__init__.py@@ -7,6 +7,11 @@ Import this package to use the registry; importing it fills the registry as a sifrom invokeai.backend.architectures import defs as defs # noqa: F401 (imported for side effects)from invokeai.backend.architectures import facets as facets # noqa: F401 (imported for side effects)from invokeai.backend.architectures.facet import Facet+from invokeai.backend.architectures.facets.latent_space import (+ LatentSpace,+ LatentSpaceFacet,+ resolve_latent_space,+)from invokeai.backend.architectures.registry import (ArchitectureError,defs_module_path,@@ -21,6 +26,9 @@ from invokeai.backend.architectures.registry import (__all__ = ["ArchitectureError","Facet",+ "LatentSpace",+ "LatentSpaceFacet",+ "resolve_latent_space","defs_module_path","facets_of","generative_bases",diff --git a/invokeai/backend/architectures/defs/anima.py b/invokeai/backend/architectures/defs/anima.pyindex 73d4ead201..c336232cda 100644--- a/invokeai/backend/architectures/defs/anima.py+++ b/invokeai/backend/architectures/defs/anima.py@@ -1,6 +1,11 @@"""What the anima architecture declares."""+from invokeai.backend.architectures.facets.latent_space import WAN21_16, LatentSpaceFacetfrom invokeai.backend.architectures.registry import registerfrom invokeai.backend.model_manager.taxonomy import BaseModelType-register(BaseModelType.Anima)+# Anima uses the Wan 2.1 VAE.+register(+ BaseModelType.Anima,+ LatentSpaceFacet(WAN21_16),+)diff --git a/invokeai/backend/architectures/defs/cogview4.py b/invokeai/backend/architectures/defs/cogview4.pyindex fd4cc68d19..cb4cb7d4cc 100644--- a/invokeai/backend/architectures/defs/cogview4.py+++ b/invokeai/backend/architectures/defs/cogview4.py@@ -1,6 +1,10 @@"""What the cogview4 architecture declares."""+from invokeai.backend.architectures.facets.latent_space import COGVIEW4_16, LatentSpaceFacetfrom invokeai.backend.architectures.registry import registerfrom invokeai.backend.model_manager.taxonomy import BaseModelType-register(BaseModelType.CogView4)+register(+ BaseModelType.CogView4,+ LatentSpaceFacet(COGVIEW4_16),+)diff --git a/invokeai/backend/architectures/defs/ernie_image.py b/invokeai/backend/architectures/defs/ernie_image.pyindex 76a023dffa..00e660a95c 100644--- a/invokeai/backend/architectures/defs/ernie_image.py+++ b/invokeai/backend/architectures/defs/ernie_image.py@@ -1,6 +1,13 @@"""What the ernie-image architecture declares."""+from invokeai.backend.architectures.facets.latent_space import FLUX2_32, LatentSpaceFacetfrom invokeai.backend.architectures.registry import registerfrom invokeai.backend.model_manager.taxonomy import BaseModelType-register(BaseModelType.ErnieImage)+# ERNIE-Image uses AutoencoderKLFlux2. The shapes line up because the denoise loop unpatches+# before previewing; the values are approximate, because ERNIE denoises in BN-normalized+# latent space and the BN stats live on the VAE, which is not loaded to draw a preview.+register(+ BaseModelType.ErnieImage,+ LatentSpaceFacet(FLUX2_32),+)diff --git a/invokeai/backend/architectures/defs/flux.py b/invokeai/backend/architectures/defs/flux.pyindex 048aeb0f84..4e63964736 100644--- a/invokeai/backend/architectures/defs/flux.py+++ b/invokeai/backend/architectures/defs/flux.py@@ -1,6 +1,10 @@"""What the flux architecture declares."""+from invokeai.backend.architectures.facets.latent_space import FLUX_16, LatentSpaceFacetfrom invokeai.backend.architectures.registry import registerfrom invokeai.backend.model_manager.taxonomy import BaseModelType-register(BaseModelType.Flux)+register(+ BaseModelType.Flux,+ LatentSpaceFacet(FLUX_16),+)diff --git a/invokeai/backend/architectures/defs/flux2.py b/invokeai/backend/architectures/defs/flux2.pyindex bbc1daa2af..341bda4c06 100644--- a/invokeai/backend/architectures/defs/flux2.py+++ b/invokeai/backend/architectures/defs/flux2.py@@ -1,6 +1,10 @@"""What the flux2 architecture declares."""+from invokeai.backend.architectures.facets.latent_space import FLUX2_32, LatentSpaceFacetfrom invokeai.backend.architectures.registry import registerfrom invokeai.backend.model_manager.taxonomy import BaseModelType-register(BaseModelType.Flux2)+register(+ BaseModelType.Flux2,+ LatentSpaceFacet(FLUX2_32),+)diff --git a/invokeai/backend/architectures/defs/ideogram_4.py b/invokeai/backend/architectures/defs/ideogram_4.pyindex 8d48d9fb5b..9f16e45216 100644--- a/invokeai/backend/architectures/defs/ideogram_4.py+++ b/invokeai/backend/architectures/defs/ideogram_4.py@@ -1,6 +1,12 @@"""What the ideogram-4 architecture declares."""+from invokeai.backend.architectures.facets.latent_space import FLUX2_32, LatentSpaceFacetfrom invokeai.backend.architectures.registry import registerfrom invokeai.backend.model_manager.taxonomy import BaseModelType-register(BaseModelType.Ideogram4)+# Ideogram 4 also uses a FLUX.2-style 32-channel VAE. It was the one architecture missing+# from the old preview dispatch entirely — its node carried a second copy of the logic.+register(+ BaseModelType.Ideogram4,+ LatentSpaceFacet(FLUX2_32),+)diff --git a/invokeai/backend/architectures/defs/krea_2.py b/invokeai/backend/architectures/defs/krea_2.pyindex 7eeaca2c04..603ee26012 100644--- a/invokeai/backend/architectures/defs/krea_2.py+++ b/invokeai/backend/architectures/defs/krea_2.py@@ -1,6 +1,11 @@"""What the krea-2 architecture declares."""+from invokeai.backend.architectures.facets.latent_space import WAN21_16, LatentSpaceFacetfrom invokeai.backend.architectures.registry import registerfrom invokeai.backend.model_manager.taxonomy import BaseModelType-register(BaseModelType.Krea2)+# Krea-2 decodes with the Qwen-Image VAE, which is the Wan 2.1 VAE.+register(+ BaseModelType.Krea2,+ LatentSpaceFacet(WAN21_16),+)diff --git a/invokeai/backend/architectures/defs/minimax_h3.py b/invokeai/backend/architectures/defs/minimax_h3.pyindex 3c3cb0fd19..2c5659a15c 100644--- a/invokeai/backend/architectures/defs/minimax_h3.py+++ b/invokeai/backend/architectures/defs/minimax_h3.py@@ -1,6 +1,10 @@"""What the minimax-h3 architecture declares."""+from invokeai.backend.architectures.facets.latent_space import MINIMAX_H3_24, LatentSpaceFacetfrom invokeai.backend.architectures.registry import registerfrom invokeai.backend.model_manager.taxonomy import BaseModelType-register(BaseModelType.MiniMaxH3)+register(+ BaseModelType.MiniMaxH3,+ LatentSpaceFacet(MINIMAX_H3_24),+)diff --git a/invokeai/backend/architectures/defs/qwen_image.py b/invokeai/backend/architectures/defs/qwen_image.pyindex cf4714df77..f95dd3eca7 100644--- a/invokeai/backend/architectures/defs/qwen_image.py+++ b/invokeai/backend/architectures/defs/qwen_image.py@@ -1,6 +1,11 @@"""What the qwen-image architecture declares."""+from invokeai.backend.architectures.facets.latent_space import WAN21_16, LatentSpaceFacetfrom invokeai.backend.architectures.registry import registerfrom invokeai.backend.model_manager.taxonomy import BaseModelType-register(BaseModelType.QwenImage)+# Qwen-Image uses the Wan 2.1 VAE.+register(+ BaseModelType.QwenImage,+ LatentSpaceFacet(WAN21_16),+)diff --git a/invokeai/backend/architectures/defs/sd_1.py b/invokeai/backend/architectures/defs/sd_1.pyindex 022d0385f7..0ee2029e00 100644--- a/invokeai/backend/architectures/defs/sd_1.py+++ b/invokeai/backend/architectures/defs/sd_1.py@@ -1,6 +1,10 @@"""What the sd-1 architecture declares."""+from invokeai.backend.architectures.facets.latent_space import SD15_4, LatentSpaceFacetfrom invokeai.backend.architectures.registry import registerfrom invokeai.backend.model_manager.taxonomy import BaseModelType-register(BaseModelType.StableDiffusion1)+register(+ BaseModelType.StableDiffusion1,+ LatentSpaceFacet(SD15_4),+)diff --git a/invokeai/backend/architectures/defs/sd_2.py b/invokeai/backend/architectures/defs/sd_2.pyindex 8e5f1a1cb2..7dcd457e46 100644--- a/invokeai/backend/architectures/defs/sd_2.py+++ b/invokeai/backend/architectures/defs/sd_2.py@@ -1,6 +1,11 @@"""What the sd-2 architecture declares."""+from invokeai.backend.architectures.facets.latent_space import SD15_4, LatentSpaceFacetfrom invokeai.backend.architectures.registry import registerfrom invokeai.backend.model_manager.taxonomy import BaseModelType-register(BaseModelType.StableDiffusion2)+# SD 2.x previews with the SD 1.x factors; same four-channel VAE.+register(+ BaseModelType.StableDiffusion2,+ LatentSpaceFacet(SD15_4),+)diff --git a/invokeai/backend/architectures/defs/sd_3.py b/invokeai/backend/architectures/defs/sd_3.pyindex 2104688303..87b29dcfac 100644--- a/invokeai/backend/architectures/defs/sd_3.py+++ b/invokeai/backend/architectures/defs/sd_3.py@@ -1,6 +1,10 @@"""What the sd-3 architecture declares."""+from invokeai.backend.architectures.facets.latent_space import SD3_16, LatentSpaceFacetfrom invokeai.backend.architectures.registry import registerfrom invokeai.backend.model_manager.taxonomy import BaseModelType-register(BaseModelType.StableDiffusion3)+register(+ BaseModelType.StableDiffusion3,+ LatentSpaceFacet(SD3_16),+)diff --git a/invokeai/backend/architectures/defs/sdxl.py b/invokeai/backend/architectures/defs/sdxl.pyindex f6ad623422..5abf759ab0 100644--- a/invokeai/backend/architectures/defs/sdxl.py+++ b/invokeai/backend/architectures/defs/sdxl.py@@ -1,6 +1,10 @@"""What the sdxl architecture declares."""+from invokeai.backend.architectures.facets.latent_space import SDXL_4, LatentSpaceFacetfrom invokeai.backend.architectures.registry import registerfrom invokeai.backend.model_manager.taxonomy import BaseModelType-register(BaseModelType.StableDiffusionXL)+register(+ BaseModelType.StableDiffusionXL,+ LatentSpaceFacet(SDXL_4),+)diff --git a/invokeai/backend/architectures/defs/sdxl_refiner.py b/invokeai/backend/architectures/defs/sdxl_refiner.pyindex 0b37e5eda4..c0b42b0f43 100644--- a/invokeai/backend/architectures/defs/sdxl_refiner.py+++ b/invokeai/backend/architectures/defs/sdxl_refiner.py@@ -1,6 +1,11 @@"""What the sdxl-refiner architecture declares."""+from invokeai.backend.architectures.facets.latent_space import SDXL_4, LatentSpaceFacetfrom invokeai.backend.architectures.registry import registerfrom invokeai.backend.model_manager.taxonomy import BaseModelType-register(BaseModelType.StableDiffusionXLRefiner)+# The refiner shares SDXL's VAE.+register(+ BaseModelType.StableDiffusionXLRefiner,+ LatentSpaceFacet(SDXL_4),+)diff --git a/invokeai/backend/architectures/defs/wan.py b/invokeai/backend/architectures/defs/wan.pyindex 5b90c87db9..ce9bba287e 100644--- a/invokeai/backend/architectures/defs/wan.py+++ b/invokeai/backend/architectures/defs/wan.py@@ -1,6 +1,13 @@"""What the wan architecture declares."""+from invokeai.backend.architectures.facets.latent_space import WAN21_16, WAN22_48, LatentSpaceFacetfrom invokeai.backend.architectures.registry import registerfrom invokeai.backend.model_manager.taxonomy import BaseModelType-register(BaseModelType.Wan)+# Two variants that model identity cannot tell apart: A14B denoises in the 16-channel Wan 2.1+# space at 8x, TI2V-5B in the 48-channel Wan2.2-VAE space at 16x. The loaded checkpoint+# decides, so the sample's channel count is what resolves it.+register(+ BaseModelType.Wan,+ LatentSpaceFacet(WAN21_16, alternates=(WAN22_48,)),+)diff --git a/invokeai/backend/architectures/defs/z_image.py b/invokeai/backend/architectures/defs/z_image.pyindex 8bd63d0814..6309e76f53 100644--- a/invokeai/backend/architectures/defs/z_image.py+++ b/invokeai/backend/architectures/defs/z_image.py@@ -1,6 +1,11 @@"""What the z-image architecture declares."""+from invokeai.backend.architectures.facets.latent_space import FLUX_16, LatentSpaceFacetfrom invokeai.backend.architectures.registry import registerfrom invokeai.backend.model_manager.taxonomy import BaseModelType-register(BaseModelType.ZImage)+# Z-Image decodes with a FLUX-compatible 16-channel VAE.+register(+ BaseModelType.ZImage,+ LatentSpaceFacet(FLUX_16),+)diff --git a/invokeai/backend/architectures/facets/latent_space.py b/invokeai/backend/architectures/facets/latent_space.pynew file mode 100644index 0000000000..76fe3aa81a--- /dev/null+++ b/invokeai/backend/architectures/facets/latent_space.py@@ -0,0 +1,380 @@+"""What an architecture's latent space looks like, and how to preview a sample of it.++Denoising previews are produced by projecting latents onto RGB with a per-VAE matrix. Which matrix,+whether a bias or a smoothing kernel applies, and how much the VAE downscales are all facts about+the *VAE*, not about the sampler — but they were spread across a fifteen-branch `if/elif` chain in+`step_callback.py` plus a second, divergent copy in the Ideogram 4 node. Adding an architecture and+forgetting the branch produced "Unsupported base model" on the first preview step, i.e. after the+model had loaded and generation had begun.++Nine latent spaces serve sixteen architectures, which is the point: the sharing is real and was+previously expressed by duplicating matrices under different names.+"""++from dataclasses import dataclass+from typing import ClassVar++import torch+from PIL import Image++from invokeai.backend.architectures.facet import Facet+from invokeai.backend.architectures.registry import require+from invokeai.backend.model_manager.taxonomy import BaseModelType++# origingally adapted from code by @erucipe and @keturn here:+# https://discuss.huggingface.co/t/decoding-latents-to-rgb-without-upscaling/23204/7+# these updated numbers for v1.5 are from @torridgristle+SD1_5_LATENT_RGB_FACTORS = [+ # R G B+ [0.3444, 0.1385, 0.0670], # L1+ [0.1247, 0.4027, 0.1494], # L2+ [-0.3192, 0.2513, 0.2103], # L3+ [-0.1307, -0.1874, -0.7445], # L4+]+# fast latents preview matrix for sdxl+# generated by @StAlKeR7779+SDXL_LATENT_RGB_FACTORS = [+ # R G B+ [0.3816, 0.4930, 0.5320],+ [-0.3753, 0.1631, 0.1739],+ [0.1770, 0.3588, -0.2048],+ [-0.4350, -0.2644, -0.4289],+]+SDXL_SMOOTH_MATRIX = [+ [0.0358, 0.0964, 0.0358],+ [0.0964, 0.4711, 0.0964],+ [0.0358, 0.0964, 0.0358],+]+SD3_5_LATENT_RGB_FACTORS = [+ [-0.05240681, 0.03251581, 0.0749016],+ [-0.0580572, 0.00759826, 0.05729818],+ [0.16144888, 0.01270368, -0.03768577],+ [0.14418615, 0.08460266, 0.15941818],+ [0.04894035, 0.0056485, -0.06686988],+ [0.05187166, 0.19222395, 0.06261094],+ [0.1539433, 0.04818359, 0.07103094],+ [-0.08601796, 0.09013458, 0.10893912],+ [-0.12398469, -0.06766567, 0.0033688],+ [-0.0439737, 0.07825329, 0.02258823],+ [0.03101129, 0.06382551, 0.07753657],+ [-0.01315361, 0.08554491, -0.08772475],+ [0.06464487, 0.05914605, 0.13262741],+ [-0.07863674, -0.02261737, -0.12761454],+ [-0.09923835, -0.08010759, -0.06264447],+ [-0.03392309, -0.0804029, -0.06078822],+]+COGVIEW4_LATENT_RGB_FACTORS = [+ [0.00408832, -0.00082485, -0.00214816],+ [0.00084172, 0.00132241, 0.00842067],+ [-0.00466737, -0.00983181, -0.00699561],+ [0.03698397, -0.04797235, 0.03585809],+ [0.00234701, -0.00124326, 0.00080869],+ [-0.00723903, -0.00388422, -0.00656606],+ [-0.00970917, -0.00467356, -0.00971113],+ [0.17292486, -0.03452463, -0.1457515],+ [0.02330308, 0.02942557, 0.02704329],+ [-0.00903131, -0.01499841, -0.01432564],+ [0.01250298, 0.0019407, -0.02168986],+ [0.01371188, 0.00498283, -0.01302135],+ [0.42396525, 0.4280575, 0.42148206],+ [0.00983825, 0.00613302, 0.00610316],+ [0.00473307, -0.00889551, -0.00915924],+ [-0.00955853, -0.00980067, -0.00977842],+]+FLUX_LATENT_RGB_FACTORS = [+ [-0.0412, 0.0149, 0.0521],+ [0.0056, 0.0291, 0.0768],+ [0.0342, -0.0681, -0.0427],+ [-0.0258, 0.0092, 0.0463],+ [0.0863, 0.0784, 0.0547],+ [-0.0017, 0.0402, 0.0158],+ [0.0501, 0.1058, 0.1152],+ [-0.0209, -0.0218, -0.0329],+ [-0.0314, 0.0083, 0.0896],+ [0.0851, 0.0665, -0.0472],+ [-0.0534, 0.0238, -0.0024],+ [0.0452, -0.0026, 0.0048],+ [0.0892, 0.0831, 0.0881],+ [-0.1117, -0.0304, -0.0789],+ [0.0027, -0.0479, -0.0043],+ [-0.1146, -0.0827, -0.0598],+]+# The 16-channel Wan 2.1 VAE. Shared by Wan 2.2 A14B, Qwen-Image, Krea-2 and Anima — this was+# three byte-identical copies under three names before the registry gave them one home.+# Factors from ComfyUI's Wan21 latent_format:+# https://github.com/comfyanonymous/ComfyUI/blob/master/comfy/latent_formats.py+WAN21_LATENT_RGB_FACTORS = [+ [-0.1299, -0.1692, 0.2932],+ [0.0671, 0.0406, 0.0442],+ [0.3568, 0.2548, 0.1747],+ [0.0372, 0.2344, 0.1420],+ [0.0313, 0.0189, -0.0328],+ [0.0296, -0.0956, -0.0665],+ [-0.3477, -0.4059, -0.2925],+ [0.0166, 0.1902, 0.1975],+ [-0.0412, 0.0267, -0.1364],+ [-0.1293, 0.0740, 0.1636],+ [0.0680, 0.3019, 0.1128],+ [0.0032, 0.0581, 0.0639],+ [-0.1251, 0.0927, 0.1699],+ [0.0060, -0.0633, 0.0005],+ [0.3477, 0.2275, 0.2950],+ [0.1984, 0.0913, 0.1861],+]+WAN21_LATENT_RGB_BIAS = [-0.1835, -0.0868, -0.3360]+# FLUX.2 uses 32 latent channels.+# Factors from ComfyUI: https://github.com/Comfy-Org/ComfyUI/blob/main/comfy/latent_formats.py+FLUX2_LATENT_RGB_FACTORS = [+ # R G B+ [0.0058, 0.0113, 0.0073],+ [0.0495, 0.0443, 0.0836],+ [-0.0099, 0.0096, 0.0644],+ [0.2144, 0.3009, 0.3652],+ [0.0166, -0.0039, -0.0054],+ [0.0157, 0.0103, -0.0160],+ [-0.0398, 0.0902, -0.0235],+ [-0.0052, 0.0095, 0.0109],+ [-0.3527, -0.2712, -0.1666],+ [-0.0301, -0.0356, -0.0180],+ [-0.0107, 0.0078, 0.0013],+ [0.0746, 0.0090, -0.0941],+ [0.0156, 0.0169, 0.0070],+ [-0.0034, -0.0040, -0.0114],+ [0.0032, 0.0181, 0.0080],+ [-0.0939, -0.0008, 0.0186],+ [0.0018, 0.0043, 0.0104],+ [0.0284, 0.0056, -0.0127],+ [-0.0024, -0.0022, -0.0030],+ [0.1207, -0.0026, 0.0065],+ [0.0128, 0.0101, 0.0142],+ [0.0137, -0.0072, -0.0007],+ [0.0095, 0.0092, -0.0059],+ [0.0000, -0.0077, -0.0049],+ [-0.0465, -0.0204, -0.0312],+ [0.0095, 0.0012, -0.0066],+ [0.0290, -0.0034, 0.0025],+ [0.0220, 0.0169, -0.0048],+ [-0.0332, -0.0457, -0.0468],+ [-0.0085, 0.0389, 0.0609],+ [-0.0076, 0.0003, -0.0043],+ [-0.0111, -0.0460, -0.0614],+]+FLUX2_LATENT_RGB_BIAS = [-0.0329, -0.0718, -0.0851]+# MiniMax H3's video VAE: 24 latent channels, 16x spatial downscale. Least-squares fit of+# NORMALIZED posterior-mean latents against 16x-downscaled RGB in [-1, 1], over real photos+# plus synthetic gradients/patches, using the released H3 video VAE encoder (fit rms ~0.09).+# This is the fallback path only — when the taeh3 preview decoder is available, the denoise+# node decodes previews with it instead.+MINIMAX_H3_LATENT_RGB_FACTORS = [+ [-0.0127, -0.0944, -0.1146],+ [-0.0083, 0.0638, -0.0942],+ [0.3635, 0.4082, 0.1479],+ [0.2079, 0.1357, -0.5101],+ [0.0178, 0.3250, -0.3183],+ [0.0567, 0.2060, -0.2453],+ [0.0343, -0.0136, -0.0482],+ [0.0079, 0.0299, -0.0814],+ [0.0220, 0.0043, 0.0158],+ [0.2984, 0.0988, 0.1576],+ [-0.0066, 0.0184, 0.1134],+ [-0.0794, -0.0416, 0.0628],+ [0.0419, -0.0184, 0.0618],+ [-0.0274, 0.0420, -0.0235],+ [-0.0231, -0.0312, 0.0310],+ [0.0089, 0.0368, -0.0387],+ [0.0126, 0.0085, -0.0299],+ [-0.0187, 0.0028, 0.0194],+ [0.0264, -0.0304, 0.0089],+ [0.0512, 0.0168, 0.0110],+ [0.0168, -0.0357, -0.0001],+ [0.0063, -0.0116, -0.0509],+ [-0.0237, -0.0347, 0.0324],+ [-0.0099, 0.0042, -0.0358],+]+MINIMAX_H3_LATENT_RGB_BIAS = [0.1189, 0.1415, -0.0034]+# Wan 2.2 TI2V-5B uses Wan2.2-VAE with 48 latent channels and 16x spatial downscale.+# Factors come from ComfyUI's Wan22 latent_format.+WAN22_LATENT_RGB_FACTORS = [+ [0.0119, 0.0103, 0.0046],+ [-0.1062, -0.0504, 0.0165],+ [0.0140, 0.0409, 0.0491],+ [-0.0813, -0.0677, 0.0607],+ [0.0656, 0.0851, 0.0808],+ [0.0264, 0.0463, 0.0912],+ [0.0295, 0.0326, 0.0590],+ [-0.0244, -0.0270, 0.0025],+ [0.0443, -0.0102, 0.0288],+ [-0.0465, -0.0090, -0.0205],+ [0.0359, 0.0236, 0.0082],+ [-0.0776, 0.0854, 0.1048],+ [0.0564, 0.0264, 0.0561],+ [0.0006, 0.0594, 0.0418],+ [-0.0319, -0.0542, -0.0637],+ [-0.0268, 0.0024, 0.0260],+ [0.0539, 0.0265, 0.0358],+ [-0.0359, -0.0312, -0.0287],+ [-0.0285, -0.1032, -0.1237],+ [0.1041, 0.0537, 0.0622],+ [-0.0086, -0.0374, -0.0051],+ [0.0390, 0.0670, 0.2863],+ [0.0069, 0.0144, 0.0082],+ [0.0006, -0.0167, 0.0079],+ [0.0313, -0.0574, -0.0232],+ [-0.1454, -0.0902, -0.0481],+ [0.0714, 0.0827, 0.0447],+ [-0.0304, -0.0574, -0.0196],+ [0.0401, 0.0384, 0.0204],+ [-0.0758, -0.0297, -0.0014],+ [0.0568, 0.1307, 0.1372],+ [-0.0055, -0.0310, -0.0380],+ [0.0239, -0.0305, 0.0325],+ [-0.0663, -0.0673, -0.0140],+ [-0.0416, -0.0047, -0.0023],+ [0.0166, 0.0112, -0.0093],+ [-0.0211, 0.0011, 0.0331],+ [0.1833, 0.1466, 0.2250],+ [-0.0368, 0.0370, 0.0295],+ [-0.3441, -0.3543, -0.2008],+ [-0.0479, -0.0489, -0.0420],+ [-0.0660, -0.0153, 0.0800],+ [-0.0101, 0.0068, 0.0156],+ [-0.0690, -0.0452, -0.0927],+ [-0.0145, 0.0041, 0.0015],+ [0.0421, 0.0451, 0.0373],+ [0.0504, -0.0483, -0.0356],+ [-0.0837, 0.0168, 0.0055],+]+WAN22_LATENT_RGB_BIAS = [0.0317, -0.0878, -0.1388]+++@dataclass(frozen=True)+class LatentSpace:+ """One VAE's latent space, and how to render a preview from it."""++ channels: int+ """Latent channels. Also what identifies the space when an architecture has more than one."""++ spatial_compression: int+ """How much smaller a latent is than the image. The preview is reported at this multiple."""++ rgb_factors: list[list[float]]+ """`channels x 3` projection onto RGB."""++ rgb_bias: list[float] | None = None+ smooth_matrix: list[list[float]] | None = None+ """A 3x3 kernel convolved over the projection. Only SDXL's four-channel space uses one."""++ def preview(self, sample: torch.Tensor) -> Image.Image:+ """Project a latent sample to a low-resolution RGB image.++ The output is one `spatial_compression`-th of the generated image in each dimension; the+ caller reports the full size alongside it so the UI can scale the preview.+ """+ if sample.dim() == 4:+ sample = sample[0]++ factors = torch.tensor(self.rgb_factors, dtype=sample.dtype, device=sample.device)+ latent_image = sample.permute(1, 2, 0) @ factors++ if self.rgb_bias is not None:+ latent_image = latent_image + torch.tensor(self.rgb_bias, dtype=sample.dtype, device=sample.device)++ if self.smooth_matrix is not None:+ kernel = torch.tensor(self.smooth_matrix, dtype=sample.dtype, device=sample.device)+ latent_image = latent_image.unsqueeze(0).permute(3, 0, 1, 2)+ latent_image = torch.nn.functional.conv2d(latent_image, kernel.reshape((1, 1, 3, 3)), padding=1)+ latent_image = latent_image.permute(1, 2, 3, 0).squeeze(0)++ # -1..1 -> 0..1 -> 0..255+ latents_ubyte = (((latent_image + 1) / 2).clamp(0, 1).mul(0xFF).byte()).cpu()+ return Image.fromarray(latents_ubyte.numpy())+++SD15_4 = LatentSpace(channels=4, spatial_compression=8, rgb_factors=SD1_5_LATENT_RGB_FACTORS)+"""Stable Diffusion 1.x and 2.x."""++SDXL_4 = LatentSpace(+ channels=4,+ spatial_compression=8,+ rgb_factors=SDXL_LATENT_RGB_FACTORS,+ smooth_matrix=SDXL_SMOOTH_MATRIX,+)+"""SDXL and its refiner. The only space with a smoothing kernel."""++SD3_16 = LatentSpace(channels=16, spatial_compression=8, rgb_factors=SD3_5_LATENT_RGB_FACTORS)++COGVIEW4_16 = LatentSpace(channels=16, spatial_compression=8, rgb_factors=COGVIEW4_LATENT_RGB_FACTORS)++FLUX_16 = LatentSpace(channels=16, spatial_compression=8, rgb_factors=FLUX_LATENT_RGB_FACTORS)+"""FLUX.1, and Z-Image, which decodes with a FLUX-compatible VAE."""++WAN21_16 = LatentSpace(+ channels=16,+ spatial_compression=8,+ rgb_factors=WAN21_LATENT_RGB_FACTORS,+ rgb_bias=WAN21_LATENT_RGB_BIAS,+)+"""The Wan 2.1 VAE: Wan 2.2 A14B, Qwen-Image, Krea-2 and Anima."""++FLUX2_32 = LatentSpace(+ channels=32,+ spatial_compression=8,+ rgb_factors=FLUX2_LATENT_RGB_FACTORS,+ rgb_bias=FLUX2_LATENT_RGB_BIAS,+)+"""AutoencoderKLFlux2: FLUX.2, ERNIE-Image and Ideogram 4."""++MINIMAX_H3_24 = LatentSpace(+ channels=24,+ spatial_compression=16,+ rgb_factors=MINIMAX_H3_LATENT_RGB_FACTORS,+ rgb_bias=MINIMAX_H3_LATENT_RGB_BIAS,+)++WAN22_48 = LatentSpace(+ channels=48,+ spatial_compression=16,+ rgb_factors=WAN22_LATENT_RGB_FACTORS,+ rgb_bias=WAN22_LATENT_RGB_BIAS,+)+"""Wan 2.2 TI2V-5B's Wan2.2-VAE. Reached through `alternates`, never registered on its own."""+++@dataclass(frozen=True)+class LatentSpaceFacet(Facet):+ """The latent space or spaces an architecture denoises in."""++ REQUIRED: ClassVar[bool] = True++ primary: LatentSpace+ alternates: tuple[LatentSpace, ...] = ()+ """Spaces the same architecture may also use, told apart at runtime by latent channel count.++ Only Wan has any: A14B denoises in 16 channels at 8x, TI2V-5B in 48 at 16x, and nothing in the+ model identity distinguishes them — the loaded checkpoint does. Empty for every other+ architecture, which is what keeps them from depending on the shape of a tensor.+ """++ def resolve(self, sample: torch.Tensor) -> LatentSpace:+ """Which space this sample is in.++ Returns `primary` without looking at `sample` when there are no alternates. That short+ circuit is deliberate: an architecture with one latent space must not acquire a dependency+ on tensor shape, or a change in how latents are packed becomes a preview bug.+ """+ if not self.alternates:+ return self.primary+ channels = sample.shape[-3]+ for space in self.alternates:+ if space.channels == channels:+ return space+ return self.primary+++def resolve_latent_space(base: BaseModelType, sample: torch.Tensor) -> LatentSpace:+ """The latent space `base` is denoising `sample` in.++ Raises `ArchitectureError` naming the file to edit if the architecture declares none — at the+ same moment the old `if/elif` chain raised "Unsupported base model", but saying what to do.+ """+ return require(base, LatentSpaceFacet).resolve(sample)diff --git a/tests/app/util/test_step_callback.py b/tests/app/util/test_step_callback.pydeleted file mode 100644index 3235d4d469..0000000000--- a/tests/app/util/test_step_callback.py+++ /dev/null@@ -1,119 +0,0 @@-"""Tests for diffusion step callback preview image generation."""--import torch-from PIL import Image--from invokeai.app.util.step_callback import (- QWEN_IMAGE_LATENT_RGB_BIAS,- QWEN_IMAGE_LATENT_RGB_FACTORS,- sample_to_lowres_estimated_image,-)---class TestSampleToLowresEstimatedImage:- """Test the latent-to-preview-image conversion used during denoising."""-- def test_qwen_image_preview_produces_valid_image(self):- """A synthetic Qwen latent tensor produces a valid RGB preview image."""- # Create a small 1x16x4x4 latent tensor (batch=1, channels=16, 4x4 spatial)- torch.manual_seed(42)- sample = torch.randn(1, 16, 4, 4)-- factors = torch.tensor(QWEN_IMAGE_LATENT_RGB_FACTORS, dtype=sample.dtype)- bias = torch.tensor(QWEN_IMAGE_LATENT_RGB_BIAS, dtype=sample.dtype)-- image = sample_to_lowres_estimated_image(- samples=sample,- latent_rgb_factors=factors,- latent_rgb_bias=bias,- )-- assert isinstance(image, Image.Image)- assert image.size == (4, 4)- assert image.mode == "RGB"-- def test_qwen_image_preview_deterministic(self):- """The same input tensor always produces the same preview image."""- sample = torch.ones(1, 16, 2, 2)-- factors = torch.tensor(QWEN_IMAGE_LATENT_RGB_FACTORS, dtype=sample.dtype)- bias = torch.tensor(QWEN_IMAGE_LATENT_RGB_BIAS, dtype=sample.dtype)-- image1 = sample_to_lowres_estimated_image(samples=sample, latent_rgb_factors=factors, latent_rgb_bias=bias)- image2 = sample_to_lowres_estimated_image(samples=sample, latent_rgb_factors=factors, latent_rgb_bias=bias)-- assert list(image1.getdata()) == list(image2.getdata())-- def test_qwen_image_preview_known_value(self):- """Verify the preview computation against a hand-calculated expected value.-- With a 1x16x1x1 tensor of all ones:- - latent_image = [1,1,...,1] @ factors = sum of each column of factors- - R = sum(col 0) = 0.3677, G = sum(col 1) = 0.4577, B = sum(col 2) = 0.9101- - After bias: R = 0.1842, G = 0.3709, B = 0.5741- - After scale ((x+1)/2): R = 0.5921, G = 0.6855, B = 0.7871- - After quantize (*255): R = 151, G = 175, B = 201- """- sample = torch.ones(1, 16, 1, 1)-- factors = torch.tensor(QWEN_IMAGE_LATENT_RGB_FACTORS, dtype=sample.dtype)- bias = torch.tensor(QWEN_IMAGE_LATENT_RGB_BIAS, dtype=sample.dtype)-- image = sample_to_lowres_estimated_image(samples=sample, latent_rgb_factors=factors, latent_rgb_bias=bias)-- assert image.size == (1, 1)- pixel = image.getpixel((0, 0))-- # Compute expected values- col_sums = [sum(row[c] for row in QWEN_IMAGE_LATENT_RGB_FACTORS) for c in range(3)]- expected = []- for c in range(3):- val = col_sums[c] + QWEN_IMAGE_LATENT_RGB_BIAS[c]- val = (val + 1) / 2 # scale from [-1,1] to [0,1]- val = max(0.0, min(1.0, val)) # clamp- expected.append(int(val * 255))-- assert pixel == tuple(expected), f"Expected {tuple(expected)}, got {pixel}"-- def test_qwen_image_preview_zeros_tensor(self):- """A zero tensor with bias produces a valid image reflecting just the bias."""- sample = torch.zeros(1, 16, 2, 2)-- factors = torch.tensor(QWEN_IMAGE_LATENT_RGB_FACTORS, dtype=sample.dtype)- bias = torch.tensor(QWEN_IMAGE_LATENT_RGB_BIAS, dtype=sample.dtype)-- image = sample_to_lowres_estimated_image(samples=sample, latent_rgb_factors=factors, latent_rgb_bias=bias)-- assert isinstance(image, Image.Image)- assert image.size == (2, 2)-- # All pixels should be identical (uniform zero input)- pixels = [image.getpixel((x, y)) for y in range(image.height) for x in range(image.width)]- assert all(p == pixels[0] for p in pixels)-- # With zero input, result = bias, scaled: ((bias + 1) / 2) * 255- expected = []- for c in range(3):- val = (QWEN_IMAGE_LATENT_RGB_BIAS[c] + 1) / 2- val = max(0.0, min(1.0, val))- expected.append(int(val * 255))- assert pixels[0] == tuple(expected)-- def test_qwen_image_factors_have_correct_shape(self):- """Qwen Image uses 16 latent channels, so factors should be 16x3."""- assert len(QWEN_IMAGE_LATENT_RGB_FACTORS) == 16- for row in QWEN_IMAGE_LATENT_RGB_FACTORS:- assert len(row) == 3- assert len(QWEN_IMAGE_LATENT_RGB_BIAS) == 3-- def test_3d_input_accepted(self):- """sample_to_lowres_estimated_image accepts 3D input (no batch dim)."""- sample = torch.randn(16, 4, 4) # no batch dimension-- factors = torch.tensor(QWEN_IMAGE_LATENT_RGB_FACTORS, dtype=sample.dtype)- bias = torch.tensor(QWEN_IMAGE_LATENT_RGB_BIAS, dtype=sample.dtype)-- image = sample_to_lowres_estimated_image(samples=sample, latent_rgb_factors=factors, latent_rgb_bias=bias)-- assert isinstance(image, Image.Image)- assert image.size == (4, 4)diff --git a/tests/backend/architectures/test_latent_space.py b/tests/backend/architectures/test_latent_space.pynew file mode 100644index 0000000000..afbeac75e4--- /dev/null+++ b/tests/backend/architectures/test_latent_space.py@@ -0,0 +1,116 @@+"""The latent-space facet: the projection maths, and what each architecture declares."""++import torch++from invokeai.backend.architectures import generative_bases, resolve_latent_space+from invokeai.backend.architectures.facets.latent_space import (+ SDXL_4,+ WAN21_16,+ WAN22_48,+ LatentSpace,+ LatentSpaceFacet,+)+from invokeai.backend.architectures.registry import get+from invokeai.backend.model_manager.taxonomy import BaseModelType+++class TestProjection:+ def test_a_known_pixel(self) -> None:+ """One reference value, written down rather than recomputed.++ The previous version of this test derived its expectation by summing the columns of the very+ matrix under test, which made it a tautology: any change to the matrix changed both sides+ and the test stayed green. Its docstring claimed 0.3677/0.4577/0.9101 for these column sums;+ the real values are 0.3887/0.8771/1.3152, and nothing noticed for as long as it existed.++ A 1x16x1x1 tensor of ones projects to the column sums of WAN21, plus the bias, mapped from+ -1..1 to 0..255.+ """+ assert WAN21_16.preview(torch.ones(1, 16, 1, 1)).getpixel((0, 0)) == (153, 228, 252)++ def test_a_zero_sample_shows_the_bias(self) -> None:+ assert WAN21_16.preview(torch.zeros(1, 16, 1, 1)).getpixel((0, 0)) == (104, 116, 84)++ def test_the_preview_is_one_pixel_per_latent(self) -> None:+ assert WAN21_16.preview(torch.zeros(1, 16, 5, 7)).size == (7, 5)++ def test_a_sample_without_a_batch_dimension_is_accepted(self) -> None:+ assert WAN21_16.preview(torch.randn(16, 4, 4)).size == (4, 4)++ def test_a_uniform_sample_gives_a_uniform_preview(self) -> None:+ image = WAN21_16.preview(torch.zeros(1, 16, 3, 3))+ pixels = [image.getpixel((x, y)) for y in range(3) for x in range(3)]+ assert all(p == pixels[0] for p in pixels)++ def test_the_smoothing_kernel_changes_the_result(self) -> None:+ """SDXL is the only space with one; without this, dropping it would go unnoticed."""+ unsmoothed = LatentSpace(channels=4, spatial_compression=8, rgb_factors=SDXL_4.rgb_factors)+ sample = torch.randn(1, 4, 8, 8)+ torch.manual_seed(0)+ assert SDXL_4.preview(sample).tobytes() != unsmoothed.preview(sample).tobytes()+++class TestResolution:+ def test_wan_picks_its_space_by_channel_count(self) -> None:+ """A14B and TI2V-5B are one `BaseModelType`; only the loaded checkpoint tells them apart."""+ assert resolve_latent_space(BaseModelType.Wan, torch.zeros(1, 16, 4, 4)) is WAN21_16+ assert resolve_latent_space(BaseModelType.Wan, torch.zeros(1, 48, 4, 4)) is WAN22_48++ def test_an_unknown_channel_count_falls_back_to_the_primary(self) -> None:+ assert resolve_latent_space(BaseModelType.Wan, torch.zeros(1, 7, 4, 4)) is WAN21_16++ def test_a_single_space_never_looks_at_the_sample(self) -> None:+ """The short circuit, pinned: an architecture with one space must not depend on tensor shape.++ A zero-dimensional tensor has no `shape[-3]`, so reading it would raise here.+ """+ facet = LatentSpaceFacet(WAN21_16)+ assert facet.resolve(torch.empty(0)) is WAN21_16+++class TestWhatArchitecturesDeclare:+ def test_every_architecture_declares_a_latent_space(self) -> None:+ """`REQUIRED = True` makes `validate()` enforce this at boot; this says what it means."""+ undeclared = sorted(b.value for b in generative_bases() if get(b, LatentSpaceFacet) is None)+ assert undeclared == []++ def test_each_matrix_has_one_row_per_channel(self) -> None:+ """A projection that disagrees with its own channel count fails only at generation time."""+ wrong = [+ (b.value, space.channels, len(space.rgb_factors))+ for b in generative_bases()+ for facet in [get(b, LatentSpaceFacet)]+ if facet is not None+ for space in (facet.primary, *facet.alternates)+ if len(space.rgb_factors) != space.channels or any(len(row) != 3 for row in space.rgb_factors)+ ]+ assert wrong == []++ def test_no_two_declared_spaces_hold_the_same_matrix(self) -> None:+ """Three byte-identical Wan 2.1 matrices lived under three names before the merge.++ Duplicates are how a projection gets fixed in one place and stays wrong in two others, so+ this fails the next time one is pasted rather than shared.+ """+ spaces: list[LatentSpace] = []+ for base in generative_bases():+ facet = get(base, LatentSpaceFacet)+ assert facet is not None+ for space in (facet.primary, *facet.alternates):+ if space not in spaces:+ spaces.append(space)+ matrices = [tuple(tuple(row) for row in s.rgb_factors) for s in spaces]+ assert len(set(matrices)) == len(matrices)++ def test_the_shared_spaces_are_actually_shared(self) -> None:+ """Sharing is by identity, not by an equal copy — the point of naming the spaces."""+ for base in (BaseModelType.QwenImage, BaseModelType.Krea2, BaseModelType.Anima, BaseModelType.Wan):+ facet = get(base, LatentSpaceFacet)+ assert facet is not None and facet.primary is WAN21_16, base.value++ def test_only_wan_has_alternates(self) -> None:+ """Every other architecture stays independent of what shape its latents happen to be."""+ with_alternates = sorted(+ b.value for b in generative_bases() if (f := get(b, LatentSpaceFacet)) is not None and f.alternates+ )+ assert with_alternates == ["wan"]