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.

26.1 KB
Raw Blame
"""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 collections.abc import Mapping
from dataclasses import dataclass, field
from typing import ClassVar, Final

import torch
from PIL import Image

from invokeai.backend.architectures.facet import Facet
from invokeai.backend.architectures.registry import ArchitectureError, get, require
from invokeai.backend.model_manager.taxonomy import AnyVariant, BaseModelType

_DEFS_PACKAGE: Final = "invokeai/backend/architectures/defs/"
"""Where a declaration lives. `registry.defs_module_path` names the exact file given a base; a
`LatentSpace` is constructed before anything associates it with one, so the messages below point at
the package and leave the filename to the traceback."""

# 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]
# LTX-2.5's video VAE: 128 latent channels, 32x spatial downscale. Least-squares fit of
# NORMALIZED posterior-mean latents against 32x-downscaled RGB in [-1, 1], over 48 real images
# plus synthetic gradients/flat patches, using the released 2.5 video VAE encoder (fit rms
# 0.075). Single-frame encodes: the preview projects one latent frame at a time.
LTX2_LATENT_RGB_FACTORS = [
    [0.0039, -0.0080, 0.0047],
    [0.0001, 0.0003, 0.0001],
    [-0.0004, 0.0030, 0.0042],
    [0.0078, 0.0048, 0.0028],
    [-0.0063, -0.0020, 0.0035],
    [0.0057, -0.0029, -0.0011],
    [-0.0084, -0.0153, -0.0193],
    [-0.0207, 0.0017, 0.0124],
    [-0.0074, 0.0010, 0.0009],
    [0.0070, 0.0079, -0.0019],
    [-0.0048, -0.0039, -0.0029],
    [-0.0003, 0.0089, 0.0130],
    [0.0130, 0.0113, -0.0010],
    [0.0066, -0.0019, -0.0128],
    [0.0011, 0.0006, 0.0005],
    [-0.0002, -0.0040, -0.0053],
    [-0.0005, 0.0029, 0.0075],
    [-0.0052, -0.0028, 0.0006],
    [-0.0028, -0.0028, 0.0005],
    [0.0060, 0.0001, 0.0038],
    [0.0148, 0.0025, -0.0057],
    [-0.0022, -0.0006, -0.0009],
    [0.0017, -0.0039, 0.0035],
    [-0.0023, -0.0088, 0.0064],
    [0.0061, 0.0092, 0.0237],
    [-0.0085, -0.0079, 0.0002],
    [-0.0102, -0.0088, -0.0142],
    [-0.0070, 0.0007, 0.0013],
    [0.0057, -0.0000, -0.0030],
    [0.0003, -0.0007, 0.0017],
    [-0.0029, 0.0035, 0.0062],
    [-0.0012, 0.0002, 0.0012],
    [0.0020, 0.0006, 0.0038],
    [-0.0010, -0.0030, -0.0055],
    [0.0014, 0.0011, 0.0059],
    [0.0004, 0.0008, 0.0041],
    [-0.0004, -0.0038, -0.0005],
    [0.0020, 0.0015, 0.0010],
    [0.0033, -0.0006, -0.0012],
    [0.0020, -0.0022, -0.0022],
    [0.0003, 0.0014, 0.0010],
    [-0.0107, -0.0068, -0.0016],
    [-0.0027, -0.0020, -0.0001],
    [-0.0038, 0.0005, -0.0010],
    [-0.0027, -0.0041, -0.0051],
    [0.0132, 0.0168, 0.0239],
    [0.0038, 0.0038, 0.0008],
    [-0.0021, 0.0001, 0.0020],
    [-0.0018, 0.0008, 0.0024],
    [0.0008, -0.0012, 0.0002],
    [0.0050, 0.0011, 0.0034],
    [0.0039, 0.0070, 0.0054],
    [0.0006, -0.0011, 0.0009],
    [-0.0038, -0.0018, -0.0018],
    [-0.0046, -0.0027, -0.0065],
    [-0.0149, -0.0102, 0.0042],
    [-0.0011, 0.0002, -0.0029],
    [0.0798, 0.0779, 0.1003],
    [-0.0023, -0.0031, -0.0003],
    [-0.0019, -0.0011, -0.0008],
    [0.0032, 0.0020, -0.0017],
    [-0.0012, -0.0012, -0.0008],
    [-0.0043, 0.0007, 0.0015],
    [0.0076, -0.0021, 0.0025],
    [-0.0175, 0.0000, 0.0057],
    [-0.0116, -0.0041, -0.0172],
    [-0.0040, 0.0006, 0.0024],
    [-0.0077, -0.0037, -0.0020],
    [0.0010, 0.0008, 0.0002],
    [0.0025, -0.0001, 0.0023],
    [0.0007, -0.0001, -0.0023],
    [0.0002, -0.0000, -0.0003],
    [-0.0170, -0.0027, -0.0163],
    [0.0005, 0.0014, 0.0006],
    [-0.0038, 0.0015, 0.0017],
    [-0.1267, -0.1276, -0.0992],
    [0.0007, -0.0031, -0.0012],
    [-0.0033, -0.0007, -0.0014],
    [0.0042, -0.0011, -0.0059],
    [-0.0004, -0.0036, 0.0009],
    [0.0052, -0.0041, -0.0047],
    [0.0097, 0.0091, 0.0030],
    [0.0138, 0.0001, 0.0029],
    [-0.0024, -0.0054, -0.0062],
    [-0.0036, -0.0016, -0.0004],
    [-0.0004, -0.0014, -0.0007],
    [0.0150, 0.0080, 0.0099],
    [0.0131, 0.0003, -0.0017],
    [0.0033, 0.0012, 0.0036],
    [-0.0068, -0.0021, -0.0039],
    [-0.0005, -0.0014, 0.0001],
    [-0.0046, -0.0022, -0.0066],
    [-0.0021, 0.0001, 0.0134],
    [-0.0035, -0.0074, -0.0034],
    [0.0026, 0.0031, -0.0013],
    [-0.0022, 0.0003, -0.0042],
    [-0.0048, 0.0105, 0.0005],
    [0.0011, -0.0383, -0.0655],
    [-0.0012, 0.0094, -0.0055],
    [-0.0020, -0.0028, -0.0005],
    [-0.0123, -0.0039, -0.0032],
    [0.0075, -0.0086, -0.0034],
    [0.0011, -0.0017, 0.0027],
    [0.1109, 0.1516, 0.1298],
    [0.0022, 0.0000, -0.0019],
    [0.0053, 0.0008, 0.0040],
    [-0.0010, -0.0009, 0.0001],
    [-0.0057, 0.0024, 0.0035],
    [-0.0191, -0.0196, -0.0024],
    [0.0128, 0.0144, 0.0186],
    [0.0083, 0.0006, -0.0436],
    [0.0004, 0.0064, 0.0063],
    [-0.0097, -0.0054, -0.0047],
    [-0.0066, 0.0029, -0.0050],
    [-0.0032, -0.0073, 0.0057],
    [0.0115, 0.0084, 0.0083],
    [-0.0821, -0.0599, -0.0339],
    [0.0017, 0.0029, 0.0008],
    [0.0024, 0.0047, -0.0013],
    [0.0071, 0.0051, -0.0008],
    [0.0056, -0.0006, -0.0022],
    [0.0046, 0.0029, 0.0050],
    [-0.0026, -0.0020, 0.0005],
    [-0.0010, 0.0016, 0.0001],
    [-0.0021, -0.0017, 0.0008],
    [-0.0055, 0.0010, -0.0006],
    [-0.0055, -0.0106, -0.0146],
    [-0.0008, -0.0017, -0.0007],
]
LTX2_LATENT_RGB_BIAS = [-0.2223, -0.2864, -0.2917]
# Qwen-Image-2.1's RGBA VAE: 64 latent channels, 16x spatial downscale. Least-squares fit of
# NORMALIZED posterior-mean latents against 16x-downscaled RGB in [-1, 1], over 9 real images
# plus synthetic gradients/flat patches, encoded opaque (alpha 1) with the released VAE in fp32
# (fit rms 0.100, 0.118 on a held-out image). The preview shows colour only; alpha is not projected.
QWEN_IMAGE21_LATENT_RGB_FACTORS = [
    [-0.0241, -0.0126, -0.0179],
    [-0.0123, 0.0152, 0.0080],
    [0.0557, 0.0438, -0.0390],
    [0.0253, 0.0674, 0.0062],
    [0.0064, 0.0214, 0.0078],
    [0.0038, 0.0165, 0.0104],
    [-0.0076, 0.0111, 0.0185],
    [-0.0375, -0.0645, -0.0483],
    [0.0310, -0.0063, -0.0011],
    [-0.1367, -0.0179, 0.0090],
    [0.0050, -0.0204, 0.0005],
    [-0.0251, 0.0056, -0.0330],
    [0.0069, -0.0437, -0.0007],
    [-0.0120, -0.0040, -0.0377],
    [0.0185, 0.0287, 0.0288],
    [0.0238, -0.0015, 0.0163],
    [0.0269, 0.0072, 0.0102],
    [-0.0137, -0.0161, -0.0297],
    [-0.0280, -0.0076, -0.0115],
    [-0.0299, -0.0507, -0.0481],
    [0.0118, 0.0032, 0.0104],
    [0.0090, 0.0326, 0.0253],
    [0.0303, 0.0019, 0.0622],
    [-0.0035, 0.0042, 0.0099],
    [-0.0918, 0.0112, 0.0169],
    [-0.0234, -0.0013, 0.0812],
    [-0.0021, -0.0039, -0.0248],
    [-0.0166, 0.0120, -0.0527],
    [-0.0108, -0.0054, -0.0087],
    [0.0072, 0.0181, 0.0215],
    [0.0162, 0.0083, 0.0289],
    [-0.0305, -0.0442, 0.0057],
    [0.0127, -0.0008, 0.0086],
    [-0.0360, 0.0189, -0.0351],
    [0.0870, 0.1157, 0.1429],
    [0.0005, -0.0050, 0.0068],
    [0.0004, 0.0060, -0.0103],
    [0.0165, 0.0159, 0.0122],
    [-0.0102, -0.0156, 0.0057],
    [0.0401, -0.0026, 0.0058],
    [0.0074, 0.0291, 0.0076],
    [0.1393, 0.0479, 0.0658],
    [-0.0061, 0.0031, -0.0132],
    [0.0463, 0.0128, 0.0126],
    [0.0104, 0.0033, -0.0008],
    [0.0088, -0.0214, -0.0111],
    [0.0170, -0.0225, -0.1466],
    [-0.1310, -0.0702, -0.0858],
    [0.0044, 0.0173, 0.0229],
    [0.0364, 0.1623, 0.0673],
    [-0.0194, -0.0099, -0.0460],
    [0.0039, -0.0078, 0.0006],
    [-0.0129, -0.0207, 0.0017],
    [0.0542, -0.0377, -0.1196],
    [0.0195, -0.0066, 0.0132],
    [-0.0364, 0.0424, -0.0571],
    [0.0010, 0.0207, 0.0023],
    [-0.0370, -0.0271, -0.0288],
    [0.0076, -0.0014, -0.0002],
    [-0.0016, -0.0063, 0.0191],
    [0.0111, 0.0053, 0.0142],
    [-0.0280, -0.0277, -0.0318],
    [-0.0034, -0.0083, -0.0081],
    [0.0078, -0.0005, -0.0037],
]
QWEN_IMAGE21_LATENT_RGB_BIAS = [-0.1543, -0.1408, -0.2869]
# 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 __post_init__(self) -> None:
        """Reject a declaration `preview()` could not use.

        Every shape here is read for the first time on the *first preview step* — after the model
        has loaded and generation has begun — where a mismatch is a `RuntimeError` from a matmul or
        a reshape. Checking at construction moves that to the import of the `defs/` module that
        declared it, which happens at boot: the traceback names the file to fix, and a placeholder
        never reaches a user's generation.
        """
        if len(self.rgb_factors) != self.channels or any(len(row) != 3 for row in self.rgb_factors):
            widths = sorted({len(row) for row in self.rgb_factors})
            raise ArchitectureError(
                f"LatentSpace declares {self.channels} channels but its rgb_factors are "
                f"{len(self.rgb_factors)} rows of width {widths}; the projection must be exactly "
                f"{self.channels} rows of 3. The traceback names the module under {_DEFS_PACKAGE} "
                f"that declared it."
            )
        if not any(factor for row in self.rgb_factors for factor in row):
            raise ArchitectureError(
                "LatentSpace.rgb_factors is all zeros, which projects every latent to the same "
                "colour — it is the scaffolder's placeholder, not a VAE. Replace it with this "
                f"VAE's real latent -> RGB matrix in the module under {_DEFS_PACKAGE} the traceback "
                "names."
            )
        if self.rgb_bias is not None and len(self.rgb_bias) != 3:
            raise ArchitectureError(
                f"LatentSpace.rgb_bias has {len(self.rgb_bias)} entries; it is added to an RGB "
                "triple and must have exactly 3."
            )
        if self.smooth_matrix is not None and (
            len(self.smooth_matrix) != 3 or any(len(row) != 3 for row in self.smooth_matrix)
        ):
            raise ArchitectureError("LatentSpace.smooth_matrix is convolved as a 3x3 kernel and must be 3x3.")

    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, FLUX.3, ERNIE-Image, Ideogram 4 and MOSS-Image."""

MINIMAX_H3_24 = LatentSpace(
    channels=24,
    spatial_compression=16,
    rgb_factors=MINIMAX_H3_LATENT_RGB_FACTORS,
    rgb_bias=MINIMAX_H3_LATENT_RGB_BIAS,
)

LTX2_128 = LatentSpace(
    channels=128,
    spatial_compression=32,
    rgb_factors=LTX2_LATENT_RGB_FACTORS,
    rgb_bias=LTX2_LATENT_RGB_BIAS,
)
"""LTX-2.5's video VAE."""

QWEN_IMAGE21_64 = LatentSpace(
    channels=64,
    spatial_compression=16,
    rgb_factors=QWEN_IMAGE21_LATENT_RGB_FACTORS,
    rgb_bias=QWEN_IMAGE21_LATENT_RGB_BIAS,
)
"""Qwen-Image-2.1's AutoencoderKLQwenImage21 (RGBA)."""

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.
    """

    by_variant: Mapping[AnyVariant, LatentSpace] = field(default_factory=dict)
    """Which of these spaces a variant denoises in, where the variant alone settles it.

    `resolve` answers the same question from a tensor, which is what generation has; this answers
    it from a model record, which is what the served capability table has. Wan TI2V-5B compresses
    16x per side where A14B compresses 8x, and a client joining on `(base, variant)` would
    otherwise be told its base's number.

    Every value must be `primary` or one of `alternates`: this names an existing space for a
    variant, it does not introduce one."""

    def __post_init__(self) -> None:
        known = (self.primary, *self.alternates)
        unknown = sorted(str(v.channels) for v in self.by_variant.values() if v not in known)
        if unknown:
            raise ArchitectureError(
                f"by_variant names {len(unknown)} latent space(s) this facet does not declare "
                f"({', '.join(unknown)} channels). Add them to `alternates`, or `resolve` will "
                "never return them for a real sample. See " + _DEFS_PACKAGE + "."
            )

    def resolve_variant(self, variant: AnyVariant | None = None) -> LatentSpace:
        """The space one concrete model denoises in, from its variant alone."""
        if variant is None:
            return self.primary
        return self.by_variant.get(variant, self.primary)

    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 with_channels(self, channels: int) -> LatentSpace | None:
        """The declared space with this many latent channels, or None.

        Unlike `resolve`, an unknown count is no match rather than the primary: a caller asking by
        channel count is pairing a model with a space, and a fallback would pair it with the wrong one.
        `by_variant` names no space of its own, so `primary` and `alternates` cover it.
        """
        return next((space for space in (self.primary, *self.alternates) if space.channels == channels), None)


def latent_space_with_channels(base: BaseModelType, channels: int) -> LatentSpace | None:
    """The space `base` denoises in that has `channels` latent channels; None if it declares none.

    Tiny AutoEncoders consume diffusion-space latents, which is exactly what a `LatentSpace` describes,
    so a TAE recorded as `(base, channels)` serves every architecture whose sample resolves to the same
    space *object*. Spaces are shared by identity -- SD15_4 by SD 1 and SD 2, FLUX_16 by FLUX.1 and
    Z-Image, FLUX2_32 by FLUX.2, ERNIE-Image and Ideogram 4, WAN21_16 by Wan, Qwen-Image, Krea-2 and
    Anima -- so one TAE record serves them all. Compare results with `is`: `LatentSpace` holds lists
    and is unhashable.
    """
    facet = get(base, LatentSpaceFacet)
    return None if facet is None else facet.with_channels(channels)


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)