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(models): show preview decoders under every family they serve (#10125)
Lincoln Steinb33c2dec5f8b
diff --git a/docs/src/content/docs/Users Guide/03.Models/03.model-format-support.mdx b/docs/src/content/docs/Users Guide/03.Models/03.model-format-support.mdxindex 01d5d9af07..1ec9ea3e36 100644--- a/docs/src/content/docs/Users Guide/03.Models/03.model-format-support.mdx+++ b/docs/src/content/docs/Users Guide/03.Models/03.model-format-support.mdx@@ -174,7 +174,7 @@ and nothing else. Each one is a single file, a `.safetensors`, `.pth` or `.pt`.| TAESDXL | `taesdxl_decoder.safetensors` | SDXL | SDXL, SDXL Refiner || TAESD3 | `diffusion_pytorch_model.safetensors` from `madebyollin/taesd3` | SD 3 | SD 3 || TAEF1 | `diffusion_pytorch_model.safetensors` from `madebyollin/taef1` | FLUX.1 | FLUX.1, Z-Image |-| TAEF2 | `taef2.safetensors` | FLUX.2 | FLUX.2, FLUX.3, ERNIE-Image |+| TAEF2 | `taef2.safetensors` | FLUX.2 | FLUX.2, FLUX.3, ERNIE-Image, Ideogram 4, MOSS-Image || TAEQI2.1 | `taeqi2_1.safetensors` | Qwen-Image-2.1 | Qwen-Image-2.1 || TAEW2.1 | `taew2_1.safetensors` | Wan 2.2 | Wan 2.2 A14B, Qwen-Image, Krea-2, Anima || TAEW2.2 | `taew2_2.safetensors` | Wan 2.2 | Wan 2.2 TI2V-5B |diff --git a/docs/src/content/docs/Users Guide/04.Image Generation/Advanced Topics/tiny-autoencoder-previews.mdx b/docs/src/content/docs/Users Guide/04.Image Generation/Advanced Topics/tiny-autoencoder-previews.mdxindex 8f42c7d005..04040b5464 100644--- a/docs/src/content/docs/Users Guide/04.Image Generation/Advanced Topics/tiny-autoencoder-previews.mdx+++ b/docs/src/content/docs/Users Guide/04.Image Generation/Advanced Topics/tiny-autoencoder-previews.mdx@@ -28,21 +28,18 @@ always and is identical with the setting on or off.It is a server setting and is off by default. See [All Settings](/configuration/invokeai-yaml/#all-settings).2. In **Model Manager → Starter Models**, install the Tiny AutoEncoder for the families you generate with- (search for *preview decoder*). Each one is 5 to 31 MB.+ (search for *preview decoder*). Each one is 5 to 31 MB. Filtering by your model's family also shows its+ decoder, even when the decoder is filed under another family, and a selected bundle names its missing decoder+ in its summary line.</Steps>-<Aside type="tip">-TAEW2.1 is filed under Wan. Filtering the starter models by Qwen-Image, Krea-2 or Anima hides it; searching for-*TAEW2.1* or *preview decoder* finds it.-</Aside>-| Starter model | Previews for ||---|---|| TAESD (SD 1.x/2.x preview decoder) | SD 1.x, SD 2.x || TAESDXL (SDXL preview decoder) | SDXL, SDXL Refiner || TAESD3 (SD3 preview decoder) | SD 3 || TAEF1 (FLUX.1 preview decoder) | FLUX.1, Z-Image |-| TAEF2 (FLUX.2 preview decoder) | FLUX.2, FLUX.3, ERNIE-Image |+| TAEF2 (FLUX.2 preview decoder) | FLUX.2, FLUX.3, ERNIE-Image, Ideogram 4, MOSS-Image || TAEQI2.1 (Qwen-Image-2.1 preview decoder) | Qwen-Image-2.1 || TAEW2.1 (Wan 2.1 VAE preview decoder) | Wan 2.2 T2V and I2V A14B, Qwen-Image, Qwen-Image Edit, Krea-2, Anima || TAEW2.2 (Wan 2.2 TI2V-5B preview decoder) | Wan 2.2 TI2V-5B |@@ -52,16 +49,17 @@ A TAE serves every family that denoises in its latent space, so you need only onyou already have, see [Preview decoders](/users-guide/models/model-format-support/#preview-decoders-tiny-autoencoders)for the files InvokeAI accepts.-FLUX.1, FLUX.2, FLUX.3, ERNIE-Image, Anima and LTX-2.5 preview the image the model predicts, so the preview is clean from-the first step. Z-Image, SD 3, Qwen-Image-2.1, Qwen-Image, Krea-2 and Wan 2.2 preview the current noisy latent:-early previews show sharp noise, which clears as denoising proceeds. SD 1.x/2.x and SDXL depend on the scheduler:-DDIM, DDPM, Euler, Euler a, Heun, LMS, KDPM2, KDPM2 a and DPM++ SDE report their prediction and preview cleanly;-DPM++ 2M, 2M SDE, 3M and 2S, UniPC, DEIS, PNDM, LCM, TCD and ER-SDE preview the noisy latent.+FLUX.1, FLUX.2, FLUX.3, ERNIE-Image, MOSS-Image, Anima and LTX-2.5 preview the image the model predicts, so the+preview is clean from the first step. Z-Image, SD 3, Qwen-Image-2.1, Qwen-Image, Krea-2, Wan 2.2 and Ideogram 4+preview the current noisy latent: early previews show sharp noise, which clears as denoising proceeds. SD 1.x/2.x and+SDXL depend on the scheduler: DDIM, DDPM, Euler, Euler a, Heun, LMS, KDPM2, KDPM2 a and DPM++ SDE report their+prediction and preview cleanly; DPM++ 2M, 2M SDE, 3M and 2S, UniPC, DEIS, PNDM, LCM, TCD and ER-SDE preview the noisy+latent.A video preview shows the middle frame of the clip. For Wan 2.2 the TAE decodes it together with the frame beforeit, which it needs as context for a sharp result; LTX-2.5 decodes the middle frame alone.-CogView4 and Ideogram 4 keep the linear preview. MiniMax H3 always previews with its own built-in decoder, whatever+CogView4 keeps the linear preview. MiniMax H3 always previews with its own built-in decoder, whateverthis setting says.## Cost and fallbackdiff --git a/invokeai/app/invocations/ideogram4/ideogram4_denoise.py b/invokeai/app/invocations/ideogram4/ideogram4_denoise.pyindex 5d80406fa9..7573274a15 100644--- a/invokeai/app/invocations/ideogram4/ideogram4_denoise.py+++ b/invokeai/app/invocations/ideogram4/ideogram4_denoise.py@@ -14,12 +14,10 @@ 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.backend.architectures import resolve_latent_spacefrom invokeai.backend.ideogram4 import run_ideogram4_denoise-from invokeai.backend.ideogram4.latent_norm import get_latent_normfrom invokeai.backend.ideogram4.modeling_ideogram4 import Ideogram4Transformer, compute_dtype_offrom invokeai.backend.ideogram4.sampler_configs import PRESETS-from invokeai.backend.ideogram4.sampling_utils import PIXELS_PER_IMAGE_TOKEN, unpatchify_and_denormalize+from invokeai.backend.ideogram4.sampling_utils import PIXELS_PER_IMAGE_TOKEN, unpatchifyfrom invokeai.backend.ideogram4.transformer_pair import Ideogram4TransformerPairfrom invokeai.backend.model_manager.load.load_base import LoadedModelfrom invokeai.backend.model_manager.taxonomy import BaseModelType, ModelFormat@@ -29,6 +27,7 @@ from invokeai.backend.patches.model_patch_raw import ModelPatchRawfrom invokeai.backend.patches.sidecar_working_memory import lora_sidecar_bytesfrom invokeai.backend.quantization.dequantizing_linear import peak_dequant_transient_bytes, requires_sidecar_patchingfrom invokeai.backend.quantization.fp8_rowwise import Fp8Linear+from invokeai.backend.stable_diffusion.diffusers_pipeline import PipelineIntermediateStatefrom invokeai.backend.stable_diffusion.diffusion.conditioning_data import Ideogram4ConditioningInfofrom invokeai.backend.util.devices import TorchDevicefrom invokeai.backend.util.fp8 import FP8_STORAGE_DTYPES, get_model_compute_dtype@@ -173,41 +172,11 @@ class Ideogram4DenoiseInvocation(BaseInvocation):assert isinstance(info, Ideogram4ConditioningInfo)llm_features = info.prompt_embeds.to(device=device, dtype=torch.float32)- # Denormalization params come from get_latent_norm (no VAE).- latent_shift, latent_scale = get_latent_norm()-- 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 = None- try:- # packed_latents: (1, LATENT_DIM, grid_h, grid_w) -> VAE latent (1, 32, H/8, W/8).- vae_latent = unpatchify_and_denormalize(- packed_latents.float(),- latent_shift.to(packed_latents.device),- latent_scale.to(packed_latents.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.- preview = None- if preview is not None:- context.util.signal_progress(- "Running Ideogram 4 denoising",- step / total,- preview,- preview_size,- )- else:- context.util.signal_progress("Running Ideogram 4 denoising", step / total)+ def step_callback(state: PipelineIntermediateState) -> None:+ # No denormalize: the FLUX.2 preview space is normalized, and Ideogram's stats are close enough to the+ # FLUX.2 VAE's for previews (TAEF2 measured 21.0 dB against 22.7 with FLUX.2's own; raw scores 16.9).+ state.latents = unpatchify(state.latents.float())+ context.util.sd_step_callback(state, BaseModelType.Ideogram4)with ExitStack() as stack:conditional, unconditional = self._load_branches(diff --git a/invokeai/app/util/tiny_autoencoder_previews.py b/invokeai/app/util/tiny_autoencoder_previews.pyindex a030d44ced..85ac0e3e76 100644--- a/invokeai/app/util/tiny_autoencoder_previews.py+++ b/invokeai/app/util/tiny_autoencoder_previews.py@@ -10,9 +10,9 @@ import torchfrom PIL import Imagefrom invokeai.app.util.step_callback import preview_frame, render_linear_preview-from invokeai.backend.architectures import LatentSpace, latent_space_with_channels, resolve_latent_space+from invokeai.backend.architectures import LatentSpace, resolve_latent_spacefrom invokeai.backend.model_manager.configs.factory import AnyModelConfig-from invokeai.backend.model_manager.configs.tiny_autoencoder import named_tiny_autoencoder+from invokeai.backend.model_manager.configs.tiny_autoencoder import named_tiny_autoencoder_spacefrom invokeai.backend.model_manager.load.load_base import LoadedModelfrom invokeai.backend.model_manager.load.model_cache.model_cache import MODEL_LOAD_LOCKfrom invokeai.backend.model_manager.starter_models import STARTER_MODELS, StarterModel@@ -56,8 +56,7 @@ def tiny_autoencoder_starters(space: LatentSpace) -> list[StarterModel]:for starter in STARTER_MODELS:if starter.type is not ModelType.TinyAutoencoder:continue- named = named_tiny_autoencoder((starter.source,))- if named is not None and latent_space_with_channels(starter.base, named[2]) is space:+ if named_tiny_autoencoder_space(starter.base, starter.source) is space:starters.append(starter)return startersdiff --git a/invokeai/backend/ideogram4/denoise.py b/invokeai/backend/ideogram4/denoise.pyindex ef73f913b9..4408e11b61 100644--- a/invokeai/backend/ideogram4/denoise.py+++ b/invokeai/backend/ideogram4/denoise.py@@ -19,11 +19,11 @@ from invokeai.backend.ideogram4.sampling_utils import (pack_latents_to_grid,)from invokeai.backend.ideogram4.scheduler import get_schedule_for_resolution, make_step_intervals+from invokeai.backend.stable_diffusion.diffusers_pipeline import PipelineIntermediateState-# Called after each completed step with (step_index, total_steps, packed_latents), where-# packed_latents is the current estimate in packed grid form ``(1, LATENT_DIM, grid_h, grid_w)`` —-# ready for a preview (unpatchify + VAE decode / RGB approximation) without re-deriving the grid.-StepCallback = Callable[[int, int, torch.Tensor], None]+# Called after each completed step. `latents` is the current noisy latent in packed grid form+# ``(1, LATENT_DIM, grid_h, grid_w)``, still normalized.+StepCallback = Callable[[PipelineIntermediateState], None]def _compute_dtype(transformer: Ideogram4Transformer) -> torch.dtype:@@ -134,7 +134,14 @@ def run_ideogram4_denoise(z = z + v * (s_val - t_val)if step_callback is not None:- # Hand the callback the current estimate in packed grid form so it can render a preview.- step_callback(num_steps - i, num_steps, pack_latents_to_grid(z, grid_h, grid_w))+ step_callback(+ PipelineIntermediateState(+ step=num_steps - i,+ order=1,+ total_steps=num_steps,+ timestep=int(t_val * 1000),+ latents=pack_latents_to_grid(z, grid_h, grid_w),+ )+ )return pack_latents_to_grid(z, grid_h, grid_w)diff --git a/invokeai/backend/ideogram4/sampling_utils.py b/invokeai/backend/ideogram4/sampling_utils.pyindex 54dede15bb..67c561bdcc 100644--- a/invokeai/backend/ideogram4/sampling_utils.py+++ b/invokeai/backend/ideogram4/sampling_utils.py@@ -105,6 +105,18 @@ def pack_latents_to_grid(z: torch.Tensor, grid_h: int, grid_w: int) -> torch.Tenreturn z.permute(0, 3, 1, 2).contiguous()+def unpatchify(packed: torch.Tensor) -> torch.Tensor:+ """Convert a packed latent ``(1, LATENT_DIM, grid_h, grid_w)`` to ``(1, 32, H/8, W/8)``, leaving its values as they are."""+ batch_size, channels, grid_h, grid_w = packed.shape+ if channels != LATENT_DIM:+ raise ValueError(f"expected {LATENT_DIM} packed channels, got {channels}")++ ae_channels = LATENT_DIM // (PATCH_SIZE * PATCH_SIZE) # 32+ z = packed.permute(0, 2, 3, 1).reshape(batch_size, grid_h, grid_w, PATCH_SIZE, PATCH_SIZE, ae_channels)+ z = z.permute(0, 5, 1, 3, 2, 4).contiguous()+ return z.reshape(batch_size, ae_channels, grid_h * PATCH_SIZE, grid_w * PATCH_SIZE)++def unpatchify_and_denormalize(packed: torch.Tensor,latent_shift: torch.Tensor,@@ -115,16 +127,6 @@ def unpatchify_and_denormalize(Applies the per-channel latent denormalization (``z * scale + shift``) in thepacked space, then unpatchifies, exactly as ``Ideogram4Pipeline._decode`` does."""- batch_size, channels, grid_h, grid_w = packed.shape- if channels != LATENT_DIM:- raise ValueError(f"expected {LATENT_DIM} packed channels, got {channels}")-- # (B, grid_h, grid_w, LATENT_DIM)- z = packed.permute(0, 2, 3, 1)- z = z * latent_scale.to(z.device, z.dtype) + latent_shift.to(z.device, z.dtype)-- ae_channels = LATENT_DIM // (PATCH_SIZE * PATCH_SIZE) # 32- z = z.reshape(batch_size, grid_h, grid_w, PATCH_SIZE, PATCH_SIZE, ae_channels)- z = z.permute(0, 5, 1, 3, 2, 4).contiguous()- z = z.reshape(batch_size, ae_channels, grid_h * PATCH_SIZE, grid_w * PATCH_SIZE)- return z+ scale = latent_scale.to(packed.device, packed.dtype).view(1, -1, 1, 1)+ shift = latent_shift.to(packed.device, packed.dtype).view(1, -1, 1, 1)+ return unpatchify(packed * scale + shift)diff --git a/invokeai/backend/model_manager/configs/tiny_autoencoder.py b/invokeai/backend/model_manager/configs/tiny_autoencoder.pyindex fea4b4b1a6..b8a727da9e 100644--- a/invokeai/backend/model_manager/configs/tiny_autoencoder.py+++ b/invokeai/backend/model_manager/configs/tiny_autoencoder.py@@ -25,7 +25,7 @@ from typing import ClassVar, Literal, Selffrom pydantic import Fieldfrom typing_extensions import Any-from invokeai.backend.architectures import latent_space_with_channels+from invokeai.backend.architectures import LatentSpace, latent_space_with_channelsfrom invokeai.backend.model_manager.configs.backbone_names import name_componentsfrom invokeai.backend.model_manager.configs.base import Checkpoint_Config_Base, Config_Basefrom invokeai.backend.model_manager.configs.identification_utils import (@@ -135,6 +135,12 @@ def named_tiny_autoencoder(components: tuple[str, ...]) -> tuple[str, BaseModelTreturn None+def named_tiny_autoencoder_space(base: BaseModelType, source: str) -> LatentSpace | None:+ """The latent space the published TAE `source` names decodes for, when filed under `base`."""+ named = named_tiny_autoencoder((source,))+ return latent_space_with_channels(base, named[2]) if named is not None else None++def _name_verdict(layout: TinyAutoencoderLayout, components: tuple[str, ...]) -> BaseModelType | _Twin | None:"""What the most specific segment naming a supported TAE or one of `layout`'s twins says the file is."""twins = _TWINS.get(layout, ())diff --git a/invokeai/backend/model_manager/starter_models/types.py b/invokeai/backend/model_manager/starter_models/types.pyindex cb788ca0e8..b01d4c7f14 100644--- a/invokeai/backend/model_manager/starter_models/types.py+++ b/invokeai/backend/model_manager/starter_models/types.py@@ -3,15 +3,17 @@Split out so the per-architecture modules can import it without importing each other."""-from typing import Optional+from typing import Optional, Self-from pydantic import BaseModel+from pydantic import BaseModel, Field, model_validator+from invokeai.backend.architectures import generative_bases, latent_space_with_channelsfrom invokeai.backend.model_manager.configs.external_api import (ExternalApiModelDefaultSettings,ExternalModelCapabilities,ExternalModelPanelSchema,)+from invokeai.backend.model_manager.configs.tiny_autoencoder import named_tiny_autoencoder_spacefrom invokeai.backend.model_manager.taxonomy import (AnyVariant,BaseModelType,@@ -38,6 +40,28 @@ class StarterModelWithoutDependencies(BaseModel):# same for sources: installs made from a superseded URL stay recognized even if the user renamed the modelprevious_sources: list[str] = []+ compatible_bases: list[BaseModelType] = Field(+ default=[], description="Other bases this model also serves, besides `base`."+ )++ @model_validator(mode="after")+ def _derive_compatible_bases(self) -> Self:+ # A TAE serves every base whose latents resolve to the same space object as its own base's, the+ # same pairing `latent_space_with_channels` makes for an installed TAE record. The published TAE the+ # source names gives the channel count, which tells Wan's two spaces apart.+ if self.type is ModelType.TinyAutoencoder:+ space = named_tiny_autoencoder_space(self.base, self.source)+ if space is not None:+ self.compatible_bases = sorted(+ (+ b+ for b in generative_bases()+ if b is not self.base and latent_space_with_channels(b, space.channels) is space+ ),+ key=lambda b: b.value,+ )+ return self+class StarterModel(StarterModelWithoutDependencies):# Optional list of model source dependencies that need to be installed before this model can be useddiff --git a/invokeai/frontend/api/openapi.json b/invokeai/frontend/api/openapi.jsonindex 7da88765b0..958762bb19 100644--- a/invokeai/frontend/api/openapi.json+++ b/invokeai/frontend/api/openapi.json@@ -113208,6 +113208,15 @@"title": "Previous Sources","default": []},+ "compatible_bases": {+ "items": {+ "$ref": "#/components/schemas/BaseModelType"+ },+ "type": "array",+ "title": "Compatible Bases",+ "description": "Other bases this model also serves, besides `base`.",+ "default": []+ },"dependencies": {"anyOf": [{@@ -113414,6 +113423,15 @@"type": "array","title": "Previous Sources","default": []+ },+ "compatible_bases": {+ "items": {+ "$ref": "#/components/schemas/BaseModelType"+ },+ "type": "array",+ "title": "Compatible Bases",+ "description": "Other bases this model also serves, besides `base`.",+ "default": []}},"type": "object",diff --git a/invokeai/frontend/api/schema.ts b/invokeai/frontend/api/schema.tsindex f1c31aed71..eef9c8b42d 100644--- a/invokeai/frontend/api/schema.ts+++ b/invokeai/frontend/api/schema.ts@@ -49616,6 +49616,12 @@ export type components = {* @default []*/previous_sources?: string[];+ /**+ * Compatible Bases+ * @description Other bases this model also serves, besides `base`.+ * @default []+ */+ compatible_bases?: components["schemas"]["BaseModelType"][];/** Dependencies */dependencies?: components["schemas"]["StarterModelWithoutDependencies"][] | null;};@@ -49666,6 +49672,12 @@ export type components = {* @default []*/previous_sources?: string[];+ /**+ * Compatible Bases+ * @description Other bases this model also serves, besides `base`.+ * @default []+ */+ compatible_bases?: components["schemas"]["BaseModelType"][];};/*** Empty Loop Statediff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.jsonindex 2a76cb7ced..3b996da554 100644--- a/invokeai/frontend/webv2/public/locales/en.json+++ b/invokeai/frontend/webv2/public/locales/en.json@@ -1797,6 +1797,8 @@"statusUnauthorized": "Unauthorized","stopScan": "Stop","scanFolderTooltip": "Scan this folder for model files",+ "showStarterModel": "Show {{name}}",+ "previewDecoderHint": "Optional live-preview decoder (needs tiny_autoencoder_previews):","scanModelsFolder": "Scan models folder","modelsFolderUnavailable": "Couldn't get the models folder location from the server. Check that the server is reachable, then retry.","scanSummary_one": "{{count}} file in {{path}} · {{notInstalled}} not installed",diff --git a/invokeai/frontend/webv2/src/features/models/core/starters.test.ts b/invokeai/frontend/webv2/src/features/models/core/starters.test.tsindex ad1811956e..1317ae7ab3 100644--- a/invokeai/frontend/webv2/src/features/models/core/starters.test.ts+++ b/invokeai/frontend/webv2/src/features/models/core/starters.test.ts@@ -2,7 +2,7 @@ import { describe, expect, it } from 'vitest';import type { StarterModel } from './types';-import { DEFAULT_STARTER_MODEL_FILTERS, filterStarterModels } from './starters';+import { DEFAULT_STARTER_MODEL_FILTERS, filterStarterModels, findBundlePreviewDecoder } from './starters';const createStarter = (overrides: Partial<StarterModel>): StarterModel => ({base: 'sdxl',@@ -61,6 +61,19 @@ describe('filterStarterModels', () => {).toEqual(['Alpha FLUX']);});+ it('shows a model under the other bases it serves, as well as its own', () => {+ const withDecoder = [+ ...catalog,+ createStarter({ base: 'flux', compatible_bases: ['z-image'], name: 'TAEF1', type: 'tiny_autoencoder' }),+ createStarter({ base: 'z-image', name: 'Z-Image Turbo', type: 'main' }),+ ];+ const byBase = (baseFilter: string) =>+ filterStarterModels(withDecoder, { ...DEFAULT_STARTER_MODEL_FILTERS, baseFilter }, '').map((m) => m.name);++ expect(byBase('z-image')).toEqual(['TAEF1', 'Z-Image Turbo']);+ expect(byBase('flux')).toEqual(['Alpha FLUX', 'TAEF1']);+ });+it('sorts by name in either direction', () => {const byName = { ...DEFAULT_STARTER_MODEL_FILTERS, sortField: 'name' as const };@@ -97,3 +110,49 @@ describe('filterStarterModels', () => {).toEqual(['flux', 'sd-1', 'sdxl', 'zeta-arch']);});});++describe('findBundlePreviewDecoder', () => {+ const taef1 = createStarter({+ base: 'flux',+ compatible_bases: ['z-image'],+ name: 'TAEF1',+ source: 'taef1',+ type: 'tiny_autoencoder',+ });+ const taesdxl = createStarter({ base: 'sdxl', name: 'TAESDXL', source: 'taesdxl', type: 'tiny_autoencoder' });+ const starters = [taesdxl, taef1];+ const bundle = (...models: StarterModel[]) => ({ models, name: 'Bundle' });+ const encoder = createStarter({ base: 'any', name: 'Encoder', type: 'qwen3_encoder' });++ it('finds the decoder a family shares through its compatible bases', () => {+ expect(findBundlePreviewDecoder(bundle(createStarter({ base: 'z-image' }), encoder), starters)).toEqual({+ decoder: taef1,+ family: 'z-image',+ });+ });++ it('finds the decoder filed under the family itself', () => {+ expect(findBundlePreviewDecoder(bundle(createStarter({ base: 'flux' })), starters)?.decoder).toBe(taef1);+ });++ it('gives nothing once the decoder is installed', () => {+ const installed = [taesdxl, { ...taef1, is_installed: true }];+ expect(findBundlePreviewDecoder(bundle(createStarter({ base: 'flux' })), installed)).toBeNull();+ });++ it('names the next missing decoder when a family has two', () => {+ const taew2_1 = createStarter({ base: 'wan', is_installed: true, name: 'TAEW2.1', type: 'tiny_autoencoder' });+ const taew2_2 = createStarter({ base: 'wan', name: 'TAEW2.2', type: 'tiny_autoencoder' });+ expect(findBundlePreviewDecoder(bundle(createStarter({ base: 'wan' })), [taew2_1, taew2_2])?.decoder).toBe(taew2_2);+ });++ it('gives nothing for a family without a decoder', () => {+ expect(findBundlePreviewDecoder(bundle(createStarter({ base: 'cogview4' })), starters)).toBeNull();+ });++ it('gives nothing when the main models name no single family', () => {+ const mixed = bundle(createStarter({ base: 'flux' }), createStarter({ base: 'sdxl' }));+ expect(findBundlePreviewDecoder(mixed, starters)).toBeNull();+ expect(findBundlePreviewDecoder(bundle(encoder), starters)).toBeNull();+ });+});diff --git a/invokeai/frontend/webv2/src/features/models/core/starters.ts b/invokeai/frontend/webv2/src/features/models/core/starters.tsindex ff866b328c..5d005c4e1f 100644--- a/invokeai/frontend/webv2/src/features/models/core/starters.ts+++ b/invokeai/frontend/webv2/src/features/models/core/starters.ts@@ -1,5 +1,5 @@import type { ModelSortField } from './library';-import type { ModelTaxonomyType, StarterModel } from './types';+import type { ModelBase, ModelTaxonomyType, StarterModel, StarterModelBundle } from './types';import { getModelBaseLabel } from './baseIdentity';@@ -61,10 +61,43 @@ export const filterStarterModels = (return ((filters.typeFilter === null || model.type === filters.typeFilter) &&- (filters.baseFilter === null || model.base === filters.baseFilter) &&+ // A preview decoder also lists the other bases sharing its latent space.+ (filters.baseFilter === null ||+ model.base === filters.baseFilter ||+ model.compatible_bases?.includes(filters.baseFilter)) &&terms.every((term) => haystack.includes(term)));}).sort((a, b) => compareStarterModels(a, b, filters.sortField) * directionFactor).map(({ model }) => model);};++export interface BundlePreviewDecoder {+ decoder: StarterModel;+ /** The bundle's base, which the decoder serves: filtering the starters by it shows the decoder. */+ family: ModelBase;+}++/**+ * The missing preview decoder (Tiny AutoEncoder) for a bundle's family, or null. Bundles leave decoders out, so this+ * is how a bundle points at one. The family is its main models' shared base; mixed or absent mains name no family.+ */+export const findBundlePreviewDecoder = (+ bundle: StarterModelBundle,+ starterModels: readonly StarterModel[]+): BundlePreviewDecoder | null => {+ const bases = new Set(bundle.models.filter((model) => model.type === 'main').map((model) => model.base));+ if (bases.size !== 1) {+ return null;+ }+ const [family] = bases;+ // Wan serves two latent spaces, so its bundle can match two decoders: name the first one still missing.+ const decoder = starterModels.find(+ (model) =>+ model.type === 'tiny_autoencoder' &&+ !model.is_installed &&+ (model.base === family || model.compatible_bases?.includes(family) === true)+ );++ return decoder ? { decoder, family } : null;+};diff --git a/invokeai/frontend/webv2/src/features/models/core/types.ts b/invokeai/frontend/webv2/src/features/models/core/types.tsindex e17745fddf..5cd9a2d066 100644--- a/invokeai/frontend/webv2/src/features/models/core/types.ts+++ b/invokeai/frontend/webv2/src/features/models/core/types.ts@@ -305,6 +305,8 @@ export interface StarterModel {is_installed: boolean;dependencies?: Omit<StarterModel, 'dependencies'>[] | null;previous_names?: string[];+ /** Other bases this model also serves, e.g. a preview decoder's bases sharing its latent space. */+ compatible_bases?: ModelBase[];previous_sources?: string[];}diff --git a/invokeai/frontend/webv2/src/features/models/ui/add-models/AddModelsView.browser.test.tsx b/invokeai/frontend/webv2/src/features/models/ui/add-models/AddModelsView.browser.test.tsxindex 444f54037a..264d5c554e 100644--- a/invokeai/frontend/webv2/src/features/models/ui/add-models/AddModelsView.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/models/ui/add-models/AddModelsView.browser.test.tsx@@ -2,6 +2,7 @@ import type { FoundModel, ModelConfig } from '@features/models/core/types';import type { ReactNode } from 'react';import { ChakraProvider } from '@chakra-ui/react';+import { getModelTypeLabel } from '@features/models/core/taxonomy';import { getModelsDir, listMissingModels, listModels, scanFolderForModels } from '@features/models/data/api';import { setModelsSnapshotForTests } from '@features/models/data/modelsStore';import { type ModelsUiAdapter, ModelsUiProvider, NO_SCHEDULER_POLICY } from '@features/models/ui/ModelsUiContext';@@ -50,11 +51,14 @@ const INSTALLED_STARTERS = [},];+const DEFAULT_STARTER_RESPONSE = { starter_bundles: {}, starter_models: INSTALLED_STARTERS };+let starterResponse: object = DEFAULT_STARTER_RESPONSE;+vi.mock('@features/models/data/startersStore', async (importOriginal) => ({...(await importOriginal<Record<string, unknown>>()),ensureStartersLoaded: vi.fn(),useStartersSelector: (selector: (snapshot: unknown) => unknown) =>- selector({ error: null, response: { starter_bundles: {}, starter_models: INSTALLED_STARTERS }, status: 'loaded' }),+ selector({ error: null, response: starterResponse, status: 'loaded' }),}));vi.mock('@features/models/data/externalProvidersStore', async (importOriginal) => ({@@ -605,3 +609,186 @@ describe('AddModelsView models folder scan', () => {expect(document.querySelector('[role="alert"]')).toBeNull();});});++describe('AddModelsView bundle preview decoder', () => {+ let host: HTMLDivElement;+ let root: Root;++ const TAEF1 = {+ base: 'flux',+ compatible_bases: ['z-image'],+ description: 'Preview decoder.',+ is_installed: false,+ name: 'TAEF1 (FLUX.1 preview decoder)',+ source: 'https://example/taef1.safetensors',+ type: 'tiny_autoencoder',+ };+ // Decoders the reveal must leave out: another family's, and one filed under TAEF1's base that Z-Image cannot use.+ const TAESDXL = { ...TAEF1, base: 'sdxl', compatible_bases: [], name: 'TAESDXL', source: 'https://example/taesdxl' };+ const FLUX_ONLY_DECODER = { ...TAEF1, compatible_bases: [], name: 'FLUX-only decoder', source: 'https://example/fo' };+ const Z_IMAGE = {+ base: 'z-image',+ description: 'Z-Image main model.',+ is_installed: false,+ name: 'Z-Image Turbo',+ source: 'https://example/z-image-turbo',+ type: 'main',+ };+ const Z_IMAGE_ENCODER = {+ ...Z_IMAGE,+ name: 'Z-Image encoder',+ source: 'https://example/qwen3',+ type: 'qwen3_encoder',+ };++ const useCatalog = (decoderInstalled: boolean) => {+ const decoder = { ...TAEF1, is_installed: decoderInstalled };+ starterResponse = {+ starter_bundles: { 'z-image': { models: [Z_IMAGE, Z_IMAGE_ENCODER], name: 'Z-Image' } },+ starter_models: [...INSTALLED_STARTERS, Z_IMAGE, Z_IMAGE_ENCODER, decoder, TAESDXL, FLUX_ONLY_DECODER],+ };+ };++ const mount = async () => {+ root = createRoot(host);+ await act(async () => {+ root.render(+ <ChakraProvider value={system}>+ <WithAccountPreferences>+ <AddModelsView />+ </WithAccountPreferences>+ </ChakraProvider>+ );+ await new Promise<void>((resolve) => {+ setTimeout(resolve, 0);+ });+ });+ };+ const selectBundle = () =>+ act(() =>+ userEvent.click(+ [...document.querySelectorAll('button')].find((button) => button.textContent?.startsWith('Z-Image'))!+ )+ );+ const hint = () => document.querySelector<HTMLButtonElement>('button[aria-label="models.showStarterModel"]');+ const listedNames = () => [...document.querySelectorAll('[title]')].map((element) => element.getAttribute('title'));+ const pickFilter = async (submenu: string, item: string) => {+ const menuItem = (startsWith: string) =>+ vi.waitFor(() => {+ const item = [...document.querySelectorAll<HTMLElement>('[role^="menuitem"]')].find((element) =>+ element.textContent?.startsWith(startsWith)+ );+ expect(item).toBeDefined();+ return item!;+ });+ await act(() =>+ userEvent.click(document.querySelector<HTMLElement>('[aria-label="models.filterAndSortStarterModels"]')!)+ );+ await act(async () => userEvent.click(await menuItem(submenu)));+ await act(async () => userEvent.click(await menuItem(item)));+ await act(() => userEvent.keyboard('{Escape}'));+ };++ beforeEach(() => {+ host = document.createElement('div');+ document.body.append(host);+ });++ afterEach(async () => {+ await act(() => root.unmount());+ host.remove();+ starterResponse = DEFAULT_STARTER_RESPONSE;+ updateModelsUi({ selectedBundleName: null });+ resetSessionAndPreferences();+ });++ it('points a bundle at its missing decoder, and reveals it in the starters filtered to the family', async () => {+ useCatalog(false);+ // A type filter and search text that would each hide the decoder; revealing it replaces both.+ updateModelsUi({ addModelsTypeSeed: 'main' });+ setAddModelsQuery('turbo');+ await mount();+ await selectBundle();++ // The decoder is a hint in the bundle's summary, not one of its rows.+ expect(getModelsUiSnapshotForTests().selectedBundleName).toBe('Z-Image');+ expect(listedNames()).not.toContain(TAEF1.name);+ expect(hint()?.textContent).toBe(TAEF1.name);++ hint()!.focus();+ await act(() => userEvent.keyboard('{Enter}'));++ expect(getModelsUiSnapshotForTests().selectedBundleName).toBeNull();+ expect(hint()).toBeNull();+ await expect.poll(listedNames).toContain(TAEF1.name);+ // Only the decoder: the family's other starters and the rest of the catalog stay out.+ expect(listedNames()).not.toContain(Z_IMAGE.name);+ expect(listedNames()).not.toContain(Z_IMAGE_ENCODER.name);+ expect(listedNames()).not.toContain(INSTALLED_STARTERS[0]!.name);+ expect(listedNames()).not.toContain(TAESDXL.name);+ expect(listedNames()).not.toContain(FLUX_ONLY_DECODER.name);+ expect(getModelsUiSnapshotForTests().addModelsQuery).toBe('');+ // The hint left with the bar; focus moves on to the revealed decoder's own install button.+ await expect+ .poll(() => document.activeElement?.closest('[data-list-row]')?.getAttribute('data-list-row'))+ .toBe(TAEF1.source);+ expect(document.activeElement?.tagName).toBe('BUTTON');+ expect(installActions.installMany).not.toHaveBeenCalled();+ });++ it('drops the revealed decoder filter when a bundle is picked again', async () => {+ useCatalog(false);+ await mount();+ await selectBundle();+ await act(() => userEvent.click(hint()!));+ await expect.poll(listedNames).toContain(TAEF1.name);++ // The Launchpad selects a bundle through the store, not the chip.+ act(() => updateModelsUi({ selectedBundleName: 'Z-Image' }));++ // No bundle holds a decoder, so keeping the reveal's type filter would empty every bundle.+ await expect.poll(listedNames).toContain(Z_IMAGE.name);+ expect(listedNames()).toContain(Z_IMAGE_ENCODER.name);+ });++ it('drops the revealed type even when the user changed only the base', async () => {+ useCatalog(false);+ await mount();+ await selectBundle();+ await act(() => userEvent.click(hint()!));+ await expect.poll(listedNames).toContain(TAEF1.name);+ act(() => updateModelsUi({ selectedBundleName: null }));+ await pickFilter('models.baseArchitecture', 'models.allBases');++ await selectBundle();++ // The reveal's type filter alone would still hide every member of the bundle.+ await expect.poll(listedNames).toContain(Z_IMAGE.name);+ expect(listedNames()).toContain(Z_IMAGE_ENCODER.name);+ });++ it('keeps a filter the user picked after the reveal', async () => {+ useCatalog(false);+ await mount();+ await selectBundle();+ await act(() => userEvent.click(hint()!));+ await expect.poll(listedNames).toContain(TAEF1.name);+ // The user's own choice replaces the reveal's type, then they come back to the bundle.+ act(() => updateModelsUi({ selectedBundleName: null }));+ await pickFilter('models.modelType', getModelTypeLabel('qwen3_encoder'));++ await selectBundle();++ await expect.poll(listedNames).toContain(Z_IMAGE_ENCODER.name);+ expect(listedNames()).not.toContain(Z_IMAGE.name);+ });++ it('gives no hint when the decoder is already installed', async () => {+ useCatalog(true);+ await mount();+ await selectBundle();++ expect(getModelsUiSnapshotForTests().selectedBundleName).toBe('Z-Image');+ expect(hint()).toBeNull();+ });+});diff --git a/invokeai/frontend/webv2/src/features/models/ui/add-models/AddModelsView.tsx b/invokeai/frontend/webv2/src/features/models/ui/add-models/AddModelsView.tsxindex 8a414bd380..9874f29367 100644--- a/invokeai/frontend/webv2/src/features/models/ui/add-models/AddModelsView.tsx+++ b/invokeai/frontend/webv2/src/features/models/ui/add-models/AddModelsView.tsx@@ -8,6 +8,8 @@ import { isInModelsDir } from '@features/models/core/schemas';import {DEFAULT_STARTER_MODEL_FILTERS,filterStarterModels,+ findBundlePreviewDecoder,+ type BundlePreviewDecoder,type StarterModelFilters,} from '@features/models/core/starters';import { getHuggingFaceModels, scanFolderForModels, type InstallModelRequest } from '@features/models/data/api';@@ -28,6 +30,7 @@ import {useModelsUiSelector,} from '@features/models/ui/uiStore';import { useNotify } from '@features/models/ui/useModelsNotify';+import { focusIfUnclaimed } from '@platform/react/focusIfUnclaimed';import { useMountEffect } from '@platform/react/useMountEffect';import { useScopedAction } from '@platform/react/useScopedAction';import {@@ -69,6 +72,9 @@ const SOURCE_KIND_ICONS: Record<string, ElementType> = {*/const FP8_STORAGE_INSTALL_CONFIG: ModelRecordChanges = { default_settings: { fp8_storage: true } };+/** How long to wait for a revealed starter's row; the deferred search re-renders within a few frames. */+const REVEAL_WAIT_MS = 1500;+export const AddModelsView = () => {const { t } = useTranslation();const notify = useNotify();@@ -159,6 +165,10 @@ export const AddModelsView = () => {() => selectedBundle?.models ?? response?.starter_models ?? [],[response, selectedBundle]);+ const bundleDecoder = useMemo(+ () => (selectedBundle ? findBundlePreviewDecoder(selectedBundle, response?.starter_models ?? []) : null),+ [response, selectedBundle]+ );const selectedBundleSources = useMemo(() => (selectedBundle ? new Set(selectedBundle.models.map((model) => model.source)) : undefined),[selectedBundle]@@ -171,6 +181,46 @@ export const AddModelsView = () => {[deferredTrimmed, sourceModels, starterFilters]);+ const starterListRef = useRef<HTMLDivElement | null>(null);+ const starterFilterMenuRef = useRef<HTMLDivElement | null>(null);+ // The base and type a decoder reveal set. No bundle holds a decoder, so selecting a bundle by any path (a chip, the+ // Launchpad) drops each one still holding the reveal's value; a base or type the user picked since stays.+ const [revealedFilters, setRevealedFilters] = useState<Pick<StarterModelFilters, 'baseFilter' | 'typeFilter'> | null>(+ null+ );+ const [previousBundleName, setPreviousBundleName] = useState(selectedBundleName);+ if (selectedBundleName !== previousBundleName) {+ setPreviousBundleName(selectedBundleName);+ if (selectedBundleName !== null && revealedFilters) {+ setRevealedFilters(null);+ setStarterFilters({+ ...starterFilters,+ baseFilter: starterFilters.baseFilter === revealedFilters.baseFilter ? null : starterFilters.baseFilter,+ typeFilter: starterFilters.typeFilter === revealedFilters.typeFilter ? null : starterFilters.typeFilter,+ });+ }+ }++ /** Reveal, not install: the starters filtered to the decoder's type and the family show it with its install button. */+ const showBundleDecoder = async ({ decoder, family }: BundlePreviewDecoder) => {+ // Search text and other filters reset so they cannot hide it.+ updateModelsUi({ addModelsQuery: '', selectedBundleName: null });+ setRevealedFilters({ baseFilter: family, typeFilter: decoder.type });+ setStarterFilters({ ...DEFAULT_STARTER_MODEL_FILTERS, baseFilter: family, typeFilter: decoder.type });+ // The hint left with the bundle bar, dropping focus. The row appears once the deferred search catches up: wait a+ // bounded time, then hand focus to its install button, else to the filter menu that now shows it.+ const findRow = () =>+ starterListRef.current?.querySelector<HTMLElement>(`[data-list-row="${CSS.escape(decoder.source)}"]`) ?? null;+ const deadline = performance.now() + REVEAL_WAIT_MS;+ while (!findRow() && performance.now() < deadline) {+ await new Promise<void>((resolve) => {+ requestAnimationFrame(() => resolve());+ });+ }+ focusIfUnclaimed(findRow());+ focusIfUnclaimed(starterFilterMenuRef.current);+ };+const installStarter = async (model: StarterModel) => {const owner = captureAccountScope();const queued = await installMany(@@ -431,12 +481,14 @@ export const AddModelsView = () => {starterCount={response?.starter_models.length ?? 0}trailing={response ? (- <StarterFilterMenu- availableBases={availableStarterBases}- availableTypes={availableStarterTypes}- filters={starterFilters}- onChange={setStarterFilters}- />+ <Box ref={starterFilterMenuRef} display="contents">+ <StarterFilterMenu+ availableBases={availableStarterBases}+ availableTypes={availableStarterTypes}+ filters={starterFilters}+ onChange={setStarterFilters}+ />+ </Box>) : undefined}onSelect={(name) => updateModelsUi({ selectedBundleName: name })}@@ -445,8 +497,14 @@ export const AddModelsView = () => {{selectedBundle ? (<SelectedBundleBarbundle={selectedBundle}+ decoder={bundleDecoder}isInstalling={installingBundle === selectedBundle.name}onInstall={() => void installBundle()}+ onShowDecoder={() => {+ if (bundleDecoder) {+ void showBundleDecoder(bundleDecoder);+ }+ }}/>) : null}</>@@ -455,7 +513,7 @@ export const AddModelsView = () => {<Box flex="1" minH="0"><Scrollable h="full" label={t('models.addModelsResults')} minH="0" px="3" pb="3">- <Stack gap="3">+ <Stack ref={starterListRef} gap="3">{hfLookup ? (<HuggingFaceFilesfp8Storage={fp8Storage}diff --git a/invokeai/frontend/webv2/src/features/models/ui/add-models/SelectedBundleBar.tsx b/invokeai/frontend/webv2/src/features/models/ui/add-models/SelectedBundleBar.tsxindex 1a6c906337..b5b89197da 100644--- a/invokeai/frontend/webv2/src/features/models/ui/add-models/SelectedBundleBar.tsx+++ b/invokeai/frontend/webv2/src/features/models/ui/add-models/SelectedBundleBar.tsx@@ -1,19 +1,25 @@+import type { BundlePreviewDecoder } from '@features/models/core/starters';import type { StarterModelBundle } from '@features/models/core/types';import { HStack, Icon, Text } from '@chakra-ui/react';import { Button } from '@platform/ui/Button';-import { DownloadIcon } from 'lucide-react';+import { ChevronRightIcon, DownloadIcon } from 'lucide-react';import { useTranslation } from 'react-i18next';/** Summary + install action for the currently selected bundle. */export const SelectedBundleBar = ({bundle,+ decoder,isInstalling,onInstall,+ onShowDecoder,}: {bundle: StarterModelBundle;+ /** The family's preview decoder when it is missing; bundles never include one. */+ decoder: BundlePreviewDecoder | null;isInstalling: boolean;onInstall: () => void;+ onShowDecoder: () => void;}) => {const { t } = useTranslation();const missingCount = bundle.models.filter((model) => !model.is_installed).length;@@ -23,6 +29,28 @@ export const SelectedBundleBar = ({<Text color="fg.muted" fontSize="xs" minW="0">{t('models.modelCount', { count: bundle.models.length })} ·{' '}{missingCount === 0 ? t('models.allInstalled') : t('models.countToInstall', { count: missingCount })}+ {decoder ? (+ <>+ {' · '}+ {t('models.previewDecoderHint')}{' '}+ <Button+ aria-label={t('models.showStarterModel', { name: decoder.decoder.name })}+ color="fg.muted"+ fontSize="xs"+ gap="0.5"+ h="auto"+ minW="0"+ p="0"+ size="sm"+ textDecoration="underline"+ variant="plain"+ onClick={onShowDecoder}+ >+ {decoder.decoder.name}+ <Icon as={ChevronRightIcon} boxSize="3" />+ </Button>+ </>+ ) : null}</Text>{missingCount > 0 ? (<Button flexShrink={0} loading={isInstalling} size="sm" variant="solid" onClick={onInstall}>diff --git a/invokeai/frontend/webv2/src/features/models/ui/shared/InstallSourceRow.tsx b/invokeai/frontend/webv2/src/features/models/ui/shared/InstallSourceRow.tsxindex 93faee4ba5..a95e46d40b 100644--- a/invokeai/frontend/webv2/src/features/models/ui/shared/InstallSourceRow.tsx+++ b/invokeai/frontend/webv2/src/features/models/ui/shared/InstallSourceRow.tsx@@ -46,6 +46,7 @@ export const InstallSourceRow = ({badges={badges}description={description}isMenuOpen={isMenuOpen}+ itemKey={source}tabIndex={-1}title={title}onContextMenu={(anchor) => onOpenMenu(source, anchor)}diff --git a/tests/app/invocations/test_ideogram4_denoise_previews.py b/tests/app/invocations/test_ideogram4_denoise_previews.pynew file mode 100644index 0000000000..295655fb40--- /dev/null+++ b/tests/app/invocations/test_ideogram4_denoise_previews.py@@ -0,0 +1,83 @@+"""Ideogram 4's denoise previews go through the shared step callback.++That is what gives them the throttle, the cancel check and the FLUX.2 Tiny AutoEncoder: Ideogram 4 denoises in+the FLUX.2 VAE's latent space, so the shared path needs the unpacked 32-channel latent, filed under Ideogram 4 --+still in the normalized denoise space, which is what TAEF2 and the FLUX.2 linear factors read.+"""++from types import SimpleNamespace++import pytest+import torch++from invokeai.app.invocations.fields import Ideogram4ConditioningField+from invokeai.app.invocations.ideogram4 import ideogram4_denoise+from invokeai.app.invocations.ideogram4.ideogram4_denoise import Ideogram4DenoiseInvocation+from invokeai.backend.ideogram4.modeling_ideogram4 import Ideogram4Config, Ideogram4Transformer+from invokeai.backend.ideogram4.sampling_utils import LATENT_DIM+from invokeai.backend.model_manager.taxonomy import BaseModelType+from invokeai.backend.stable_diffusion.diffusion.conditioning_data import (+ ConditioningFieldData,+ Ideogram4ConditioningInfo,+)++TINY = Ideogram4Config(+ emb_dim=64,+ num_layers=1,+ num_heads=2,+ intermediate_size=128,+ adanln_dim=16,+ in_channels=LATENT_DIM,+ llm_features_dim=32,+ mrope_section=(4, 2, 2),+)+++def test_each_step_previews_the_flux2_space_latent_through_the_shared_callback(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.setattr(ideogram4_denoise.TorchDevice, "choose_torch_device", lambda: torch.device("cpu"))+ # float64: CPU bf16 matmul can raise an illegal instruction on Windows runners.+ branches = (Ideogram4Transformer(TINY).double().eval(), Ideogram4Transformer(TINY).double().eval())+ monkeypatch.setattr(Ideogram4DenoiseInvocation, "_load_branches", lambda self, context, stack, mem, **_: branches)++ # Keep a copy of each packed latent the loop hands over, before the node's callback replaces it.+ packed: list[torch.Tensor] = []+ run = ideogram4_denoise.run_ideogram4_denoise++ def recording_run(*, step_callback, **kwargs):+ def record(state):+ packed.append(state.latents.clone())+ step_callback(state)++ return run(step_callback=record, **kwargs)++ monkeypatch.setattr(ideogram4_denoise, "run_ideogram4_denoise", recording_run)++ seen: list[tuple[BaseModelType, int, int, torch.Tensor]] = []+ conditioning = ConditioningFieldData(+ conditionings=[Ideogram4ConditioningInfo(prompt_embeds=torch.zeros(4, TINY.llm_features_dim))]+ )+ context = SimpleNamespace(+ conditioning=SimpleNamespace(load=lambda name: conditioning),+ tensors=SimpleNamespace(save=lambda tensor: "latents"),+ util=SimpleNamespace(+ sd_step_callback=lambda state, base: seen.append((base, state.step, state.total_steps, state.latents))+ ),+ )+ invocation = Ideogram4DenoiseInvocation.model_construct(+ positive_conditioning=Ideogram4ConditioningField(conditioning_name="c"), width=64, height=32, steps=2+ )++ invocation.invoke(context) # type: ignore[arg-type]++ # The percentage is step / total, as it was before.+ assert [(base, step, total) for base, step, total, _ in seen] == [+ (BaseModelType.Ideogram4, 1, 2),+ (BaseModelType.Ideogram4, 2, 2),+ ]+ for (*_, latent), grid in zip(seen, packed, strict=True):+ # Packed channel (py * 2 + px) * 32 + c holds VAE channel c at pixel (2 * gy + py, 2 * gx + px). A 64x32 image+ # is a 4x2 grid and an 8x4 latent. Values unchanged: no denormalize.+ expected = grid.float().view(1, 2, 2, 32, 2, 4).permute(0, 3, 4, 1, 5, 2).reshape(1, 32, 4, 8)+ assert torch.equal(latent, expected)diff --git a/tests/backend/ideogram4/test_unpatchify.py b/tests/backend/ideogram4/test_unpatchify.pynew file mode 100644index 0000000000..4fae0f5bca--- /dev/null+++ b/tests/backend/ideogram4/test_unpatchify.py@@ -0,0 +1,23 @@+"""The final decode's latent: Ideogram 4 denormalizes per packed channel, then unpatchifies 2x2 patches."""++import torch++from invokeai.backend.ideogram4.sampling_utils import LATENT_DIM, PATCH_SIZE, unpatchify_and_denormalize+++def test_unpatchify_and_denormalize_scales_each_packed_channel_then_places_its_patch_pixel() -> None:+ ae_channels = LATENT_DIM // (PATCH_SIZE * PATCH_SIZE)+ packed = torch.randn(1, LATENT_DIM, 3, 2, dtype=torch.float64)+ scale = torch.rand(LATENT_DIM, dtype=torch.float64) + 0.5+ shift = torch.randn(LATENT_DIM, dtype=torch.float64)++ z = unpatchify_and_denormalize(packed, shift, scale)++ assert z.shape == (1, ae_channels, 3 * PATCH_SIZE, 2 * PATCH_SIZE)+ # Packed channel (i * PATCH_SIZE + j) * ae_channels + c holds pixel (i, j) of channel c's patch.+ for c in range(ae_channels):+ for i in range(PATCH_SIZE):+ for j in range(PATCH_SIZE):+ k = (i * PATCH_SIZE + j) * ae_channels + c+ expected = packed[0, k] * scale[k] + shift[k]+ assert torch.equal(z[0, c, i::PATCH_SIZE, j::PATCH_SIZE], expected), (c, i, j)diff --git a/tests/backend/model_manager/test_starter_models.py b/tests/backend/model_manager/test_starter_models.pyindex 489036a2cb..0dde3591db 100644--- a/tests/backend/model_manager/test_starter_models.py+++ b/tests/backend/model_manager/test_starter_models.py@@ -7,6 +7,7 @@ two standalone dependencies so installing it also pulls the pieces needed to runone click on the Launchpad, so it must stay free of gated or non-commercial weights and still run on its own."""+from invokeai.backend.model_manager.configs.tiny_autoencoder import named_tiny_autoencoder_spacefrom invokeai.backend.model_manager.starter_models import (STARTER_BUNDLES,STARTER_MODELS,@@ -192,6 +193,47 @@ def test_the_ltx2_gguf_transformers_pull_the_components_and_the_encoder() -> Nonassert all(dep.source in starter_sources for dep in dependencies), model.name+def test_preview_decoders_list_the_bases_sharing_their_latent_space() -> None:+ """A TAE is filed under one base but decodes for every base denoising in the same latents, so the starter-model+ base filter can show it there too. A base with a different latent space must not be listed."""+ taes = [m for m in STARTER_MODELS if m.type is ModelType.TinyAutoencoder]+ taesd = next(m for m in taes if m.base is BaseModelType.StableDiffusion1)+ taef1 = next(m for m in taes if m.base is BaseModelType.Flux)+ taef2 = next(m for m in taes if m.base is BaseModelType.Flux2)++ assert BaseModelType.StableDiffusion2 in taesd.compatible_bases+ assert BaseModelType.StableDiffusionXL not in taesd.compatible_bases+ assert BaseModelType.ZImage in taef1.compatible_bases+ assert BaseModelType.Flux2 not in taef1.compatible_bases+ assert {BaseModelType.Flux3, BaseModelType.ErnieImage, BaseModelType.Ideogram4} <= set(taef2.compatible_bases)+ assert BaseModelType.Flux not in taef2.compatible_bases+ for model in taes:+ assert model.base not in model.compatible_bases, model.name+++def test_wan_preview_decoders_list_only_their_own_latent_space() -> None:+ """Both Wan TAEs are filed under Wan, but only the 16-channel one shares latents with other families."""+ taes = {m.name: m for m in STARTER_MODELS if m.type is ModelType.TinyAutoencoder and m.base is BaseModelType.Wan}+ taew2_1 = next(m for n, m in taes.items() if n.startswith("TAEW2.1"))+ taew2_2 = next(m for n, m in taes.items() if n.startswith("TAEW2.2"))++ assert {BaseModelType.QwenImage, BaseModelType.Krea2, BaseModelType.Anima} <= set(taew2_1.compatible_bases)+ assert taew2_2.compatible_bases == []+++def test_every_preview_decoder_starter_resolves_to_a_latent_space() -> None:+ """`compatible_bases` and the missing-TAE log both read the space from the TAE the source names: a starter whose+ URL names no published TAE would silently drop out of the base filter, the bundle hint and the log."""+ for model in STARTER_MODELS:+ if model.type is ModelType.TinyAutoencoder:+ assert named_tiny_autoencoder_space(model.base, model.source) is not None, model.name+++def test_only_preview_decoders_list_compatible_bases() -> None:+ others = [m for m in STARTER_MODELS if m.type is not ModelType.TinyAutoencoder]+ assert others and all(m.compatible_bases == [] for m in others)++def test_every_flux3_transformer_only_starter_pulls_the_vae_and_the_encoder() -> None:"""The single files, quantized or not, and the GGUFs hold only the transformer: installing one has to pull theFLUX.2 VAE and the Qwen3-VL encoder, both installable starters themselves. Klein and Klein Base both ship that way."""